comctl32/tests: Use BOOL type where appropriate.
[wine.git] / dlls / wininet / http.c
blob9c2d5d42d9fe7fb8da6b39e4ef06ee5fae579774
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 typedef enum {
383 READMODE_SYNC,
384 READMODE_ASYNC,
385 READMODE_NOBLOCK
386 } read_mode_t;
388 struct data_stream_vtbl_t {
389 DWORD (*get_avail_data)(data_stream_t*,http_request_t*);
390 BOOL (*end_of_data)(data_stream_t*,http_request_t*);
391 DWORD (*read)(data_stream_t*,http_request_t*,BYTE*,DWORD,DWORD*,read_mode_t);
392 BOOL (*drain_content)(data_stream_t*,http_request_t*);
393 void (*destroy)(data_stream_t*);
396 typedef struct {
397 data_stream_t data_stream;
399 BYTE buf[READ_BUFFER_SIZE];
400 DWORD buf_size;
401 DWORD buf_pos;
402 DWORD chunk_size;
403 BOOL end_of_data;
404 } chunked_stream_t;
406 static inline void destroy_data_stream(data_stream_t *stream)
408 stream->vtbl->destroy(stream);
411 static void reset_data_stream(http_request_t *req)
413 destroy_data_stream(req->data_stream);
414 req->data_stream = &req->netconn_stream.data_stream;
415 req->read_pos = req->read_size = req->netconn_stream.content_read = 0;
416 req->read_chunked = req->read_gzip = FALSE;
419 #ifdef HAVE_ZLIB
421 typedef struct {
422 data_stream_t stream;
423 data_stream_t *parent_stream;
424 z_stream zstream;
425 BYTE buf[READ_BUFFER_SIZE];
426 DWORD buf_size;
427 DWORD buf_pos;
428 BOOL end_of_data;
429 } gzip_stream_t;
431 static DWORD gzip_get_avail_data(data_stream_t *stream, http_request_t *req)
433 /* Allow reading only from read buffer */
434 return 0;
437 static BOOL gzip_end_of_data(data_stream_t *stream, http_request_t *req)
439 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
440 return gzip_stream->end_of_data;
443 static DWORD gzip_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
444 DWORD *read, read_mode_t read_mode)
446 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
447 z_stream *zstream = &gzip_stream->zstream;
448 DWORD current_read, ret_read = 0;
449 BOOL end;
450 int zres;
451 DWORD res = ERROR_SUCCESS;
453 while(size && !gzip_stream->end_of_data) {
454 end = gzip_stream->parent_stream->vtbl->end_of_data(gzip_stream->parent_stream, req);
456 if(gzip_stream->buf_size <= 64 && !end) {
457 if(gzip_stream->buf_pos) {
458 if(gzip_stream->buf_size)
459 memmove(gzip_stream->buf, gzip_stream->buf+gzip_stream->buf_pos, gzip_stream->buf_size);
460 gzip_stream->buf_pos = 0;
462 res = gzip_stream->parent_stream->vtbl->read(gzip_stream->parent_stream, req, gzip_stream->buf+gzip_stream->buf_size,
463 sizeof(gzip_stream->buf)-gzip_stream->buf_size, &current_read, read_mode);
464 gzip_stream->buf_size += current_read;
465 if(res != ERROR_SUCCESS)
466 break;
467 end = gzip_stream->parent_stream->vtbl->end_of_data(gzip_stream->parent_stream, req);
468 if(!current_read && !end) {
469 if(read_mode != READMODE_NOBLOCK) {
470 WARN("unexpected end of data\n");
471 gzip_stream->end_of_data = TRUE;
473 break;
475 if(gzip_stream->buf_size <= 64 && !end)
476 continue;
479 zstream->next_in = gzip_stream->buf+gzip_stream->buf_pos;
480 zstream->avail_in = gzip_stream->buf_size-(end ? 0 : 64);
481 zstream->next_out = buf+ret_read;
482 zstream->avail_out = size;
483 zres = inflate(&gzip_stream->zstream, 0);
484 current_read = size - zstream->avail_out;
485 size -= current_read;
486 ret_read += current_read;
487 gzip_stream->buf_size -= zstream->next_in - (gzip_stream->buf+gzip_stream->buf_pos);
488 gzip_stream->buf_pos = zstream->next_in-gzip_stream->buf;
489 if(zres == Z_STREAM_END) {
490 TRACE("end of data\n");
491 gzip_stream->end_of_data = TRUE;
492 inflateEnd(zstream);
493 }else if(zres != Z_OK) {
494 WARN("inflate failed %d: %s\n", zres, debugstr_a(zstream->msg));
495 if(!ret_read)
496 res = ERROR_INTERNET_DECODING_FAILED;
497 break;
500 if(ret_read && read_mode == READMODE_ASYNC)
501 read_mode = READMODE_NOBLOCK;
504 TRACE("read %u bytes\n", ret_read);
505 *read = ret_read;
506 return res;
509 static BOOL gzip_drain_content(data_stream_t *stream, http_request_t *req)
511 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
512 return gzip_stream->parent_stream->vtbl->drain_content(gzip_stream->parent_stream, req);
515 static void gzip_destroy(data_stream_t *stream)
517 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
519 destroy_data_stream(gzip_stream->parent_stream);
521 if(!gzip_stream->end_of_data)
522 inflateEnd(&gzip_stream->zstream);
523 heap_free(gzip_stream);
526 static const data_stream_vtbl_t gzip_stream_vtbl = {
527 gzip_get_avail_data,
528 gzip_end_of_data,
529 gzip_read,
530 gzip_drain_content,
531 gzip_destroy
534 static voidpf wininet_zalloc(voidpf opaque, uInt items, uInt size)
536 return heap_alloc(items*size);
539 static void wininet_zfree(voidpf opaque, voidpf address)
541 heap_free(address);
544 static DWORD init_gzip_stream(http_request_t *req)
546 gzip_stream_t *gzip_stream;
547 int index, zres;
549 gzip_stream = heap_alloc_zero(sizeof(gzip_stream_t));
550 if(!gzip_stream)
551 return ERROR_OUTOFMEMORY;
553 gzip_stream->stream.vtbl = &gzip_stream_vtbl;
554 gzip_stream->zstream.zalloc = wininet_zalloc;
555 gzip_stream->zstream.zfree = wininet_zfree;
557 zres = inflateInit2(&gzip_stream->zstream, 0x1f);
558 if(zres != Z_OK) {
559 ERR("inflateInit failed: %d\n", zres);
560 heap_free(gzip_stream);
561 return ERROR_OUTOFMEMORY;
564 index = HTTP_GetCustomHeaderIndex(req, szContent_Length, 0, FALSE);
565 if(index != -1)
566 HTTP_DeleteCustomHeader(req, index);
568 if(req->read_size) {
569 memcpy(gzip_stream->buf, req->read_buf+req->read_pos, req->read_size);
570 gzip_stream->buf_size = req->read_size;
571 req->read_pos = req->read_size = 0;
574 req->read_gzip = TRUE;
575 gzip_stream->parent_stream = req->data_stream;
576 req->data_stream = &gzip_stream->stream;
577 return ERROR_SUCCESS;
580 #else
582 static DWORD init_gzip_stream(http_request_t *req)
584 ERR("gzip stream not supported, missing zlib.\n");
585 return ERROR_SUCCESS;
588 #endif
590 /***********************************************************************
591 * HTTP_FreeTokens (internal)
593 * Frees table of pointers.
595 static void HTTP_FreeTokens(LPWSTR * token_array)
597 int i;
598 for (i = 0; token_array[i]; i++) heap_free(token_array[i]);
599 heap_free(token_array);
602 static void HTTP_FixURL(http_request_t *request)
604 static const WCHAR szSlash[] = { '/',0 };
605 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
607 /* If we don't have a path we set it to root */
608 if (NULL == request->path)
609 request->path = heap_strdupW(szSlash);
610 else /* remove \r and \n*/
612 int nLen = strlenW(request->path);
613 while ((nLen >0 ) && ((request->path[nLen-1] == '\r')||(request->path[nLen-1] == '\n')))
615 nLen--;
616 request->path[nLen]='\0';
618 /* Replace '\' with '/' */
619 while (nLen>0) {
620 nLen--;
621 if (request->path[nLen] == '\\') request->path[nLen]='/';
625 if(CSTR_EQUAL != CompareStringW( LOCALE_INVARIANT, NORM_IGNORECASE,
626 request->path, strlenW(request->path), szHttp, strlenW(szHttp) )
627 && request->path[0] != '/') /* not an absolute path ?? --> fix it !! */
629 WCHAR *fixurl = heap_alloc((strlenW(request->path) + 2)*sizeof(WCHAR));
630 *fixurl = '/';
631 strcpyW(fixurl + 1, request->path);
632 heap_free( request->path );
633 request->path = fixurl;
637 static WCHAR* build_request_header(http_request_t *request, const WCHAR *verb,
638 const WCHAR *path, const WCHAR *version, BOOL use_cr)
640 LPWSTR requestString;
641 DWORD len, n;
642 LPCWSTR *req;
643 UINT i;
645 static const WCHAR szSpace[] = { ' ',0 };
646 static const WCHAR szColon[] = { ':',' ',0 };
647 static const WCHAR szCr[] = { '\r',0 };
648 static const WCHAR szLf[] = { '\n',0 };
650 /* allocate space for an array of all the string pointers to be added */
651 len = (request->nCustHeaders)*5 + 10;
652 req = heap_alloc(len*sizeof(LPCWSTR));
654 /* add the verb, path and HTTP version string */
655 n = 0;
656 req[n++] = verb;
657 req[n++] = szSpace;
658 req[n++] = path;
659 req[n++] = szSpace;
660 req[n++] = version;
661 if (use_cr)
662 req[n++] = szCr;
663 req[n++] = szLf;
665 /* Append custom request headers */
666 for (i = 0; i < request->nCustHeaders; i++)
668 if (request->custHeaders[i].wFlags & HDR_ISREQUEST)
670 req[n++] = request->custHeaders[i].lpszField;
671 req[n++] = szColon;
672 req[n++] = request->custHeaders[i].lpszValue;
673 if (use_cr)
674 req[n++] = szCr;
675 req[n++] = szLf;
677 TRACE("Adding custom header %s (%s)\n",
678 debugstr_w(request->custHeaders[i].lpszField),
679 debugstr_w(request->custHeaders[i].lpszValue));
682 if (use_cr)
683 req[n++] = szCr;
684 req[n++] = szLf;
685 req[n] = NULL;
687 requestString = HTTP_build_req( req, 4 );
688 heap_free( req );
689 return requestString;
692 static WCHAR* build_response_header(http_request_t *request, BOOL use_cr)
694 static const WCHAR colonW[] = { ':',' ',0 };
695 static const WCHAR crW[] = { '\r',0 };
696 static const WCHAR lfW[] = { '\n',0 };
697 static const WCHAR status_fmt[] = { ' ','%','u',' ',0 };
699 const WCHAR **req;
700 WCHAR *ret, buf[14];
701 DWORD i, n = 0;
703 req = heap_alloc((request->nCustHeaders*5+8)*sizeof(WCHAR*));
704 if(!req)
705 return NULL;
707 if (request->status_code)
709 req[n++] = request->version;
710 sprintfW(buf, status_fmt, request->status_code);
711 req[n++] = buf;
712 req[n++] = request->statusText;
713 if (use_cr)
714 req[n++] = crW;
715 req[n++] = lfW;
718 for(i = 0; i < request->nCustHeaders; i++)
720 if(!(request->custHeaders[i].wFlags & HDR_ISREQUEST)
721 && strcmpW(request->custHeaders[i].lpszField, szStatus))
723 req[n++] = request->custHeaders[i].lpszField;
724 req[n++] = colonW;
725 req[n++] = request->custHeaders[i].lpszValue;
726 if(use_cr)
727 req[n++] = crW;
728 req[n++] = lfW;
730 TRACE("Adding custom header %s (%s)\n",
731 debugstr_w(request->custHeaders[i].lpszField),
732 debugstr_w(request->custHeaders[i].lpszValue));
735 if(use_cr)
736 req[n++] = crW;
737 req[n++] = lfW;
738 req[n] = NULL;
740 ret = HTTP_build_req(req, 0);
741 heap_free(req);
742 return ret;
745 static void HTTP_ProcessCookies( http_request_t *request )
747 int HeaderIndex;
748 int numCookies = 0;
749 LPHTTPHEADERW setCookieHeader;
751 if(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES)
752 return;
754 while((HeaderIndex = HTTP_GetCustomHeaderIndex(request, szSet_Cookie, numCookies++, FALSE)) != -1)
756 HTTPHEADERW *host;
757 const WCHAR *data;
758 WCHAR *name;
760 setCookieHeader = &request->custHeaders[HeaderIndex];
762 if (!setCookieHeader->lpszValue)
763 continue;
765 host = HTTP_GetHeader(request, hostW);
766 if(!host)
767 continue;
769 data = strchrW(setCookieHeader->lpszValue, '=');
770 if(!data)
771 continue;
773 name = heap_strndupW(setCookieHeader->lpszValue, data-setCookieHeader->lpszValue);
774 if(!name)
775 continue;
777 data++;
778 set_cookie(host->lpszValue, request->path, name, data);
779 heap_free(name);
783 static void strip_spaces(LPWSTR start)
785 LPWSTR str = start;
786 LPWSTR end;
788 while (*str == ' ' && *str != '\0')
789 str++;
791 if (str != start)
792 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
794 end = start + strlenW(start) - 1;
795 while (end >= start && *end == ' ')
797 *end = '\0';
798 end--;
802 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue, LPWSTR *pszRealm )
804 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
805 static const WCHAR szRealm[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
806 BOOL is_basic;
807 is_basic = !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
808 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
809 if (is_basic && pszRealm)
811 LPCWSTR token;
812 LPCWSTR ptr = &pszAuthValue[ARRAYSIZE(szBasic)];
813 LPCWSTR realm;
814 ptr++;
815 *pszRealm=NULL;
816 token = strchrW(ptr,'=');
817 if (!token)
818 return TRUE;
819 realm = ptr;
820 while (*realm == ' ' && *realm != '\0')
821 realm++;
822 if(!strncmpiW(realm, szRealm, ARRAYSIZE(szRealm)) &&
823 (realm[ARRAYSIZE(szRealm)] == ' ' || realm[ARRAYSIZE(szRealm)] == '='))
825 token++;
826 while (*token == ' ' && *token != '\0')
827 token++;
828 if (*token == '\0')
829 return TRUE;
830 *pszRealm = heap_strdupW(token);
831 strip_spaces(*pszRealm);
835 return is_basic;
838 static void destroy_authinfo( struct HttpAuthInfo *authinfo )
840 if (!authinfo) return;
842 if (SecIsValidHandle(&authinfo->ctx))
843 DeleteSecurityContext(&authinfo->ctx);
844 if (SecIsValidHandle(&authinfo->cred))
845 FreeCredentialsHandle(&authinfo->cred);
847 heap_free(authinfo->auth_data);
848 heap_free(authinfo->scheme);
849 heap_free(authinfo);
852 static UINT retrieve_cached_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR *auth_data)
854 basicAuthorizationData *ad;
855 UINT rc = 0;
857 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host),debugstr_w(realm));
859 EnterCriticalSection(&authcache_cs);
860 LIST_FOR_EACH_ENTRY(ad, &basicAuthorizationCache, basicAuthorizationData, entry)
862 if (!strcmpiW(host,ad->host) && !strcmpW(realm,ad->realm))
864 TRACE("Authorization found in cache\n");
865 *auth_data = heap_alloc(ad->authorizationLen);
866 memcpy(*auth_data,ad->authorization,ad->authorizationLen);
867 rc = ad->authorizationLen;
868 break;
871 LeaveCriticalSection(&authcache_cs);
872 return rc;
875 static void cache_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR auth_data, UINT auth_data_len)
877 struct list *cursor;
878 basicAuthorizationData* ad = NULL;
880 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host),debugstr_w(realm),debugstr_an(auth_data,auth_data_len));
882 EnterCriticalSection(&authcache_cs);
883 LIST_FOR_EACH(cursor, &basicAuthorizationCache)
885 basicAuthorizationData *check = LIST_ENTRY(cursor,basicAuthorizationData,entry);
886 if (!strcmpiW(host,check->host) && !strcmpW(realm,check->realm))
888 ad = check;
889 break;
893 if (ad)
895 TRACE("Found match in cache, replacing\n");
896 heap_free(ad->authorization);
897 ad->authorization = heap_alloc(auth_data_len);
898 memcpy(ad->authorization, auth_data, auth_data_len);
899 ad->authorizationLen = auth_data_len;
901 else
903 ad = heap_alloc(sizeof(basicAuthorizationData));
904 ad->host = heap_strdupW(host);
905 ad->realm = heap_strdupW(realm);
906 ad->authorization = heap_alloc(auth_data_len);
907 memcpy(ad->authorization, auth_data, auth_data_len);
908 ad->authorizationLen = auth_data_len;
909 list_add_head(&basicAuthorizationCache,&ad->entry);
910 TRACE("authorization cached\n");
912 LeaveCriticalSection(&authcache_cs);
915 static BOOL retrieve_cached_authorization(LPWSTR host, LPWSTR scheme,
916 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
918 authorizationData *ad;
920 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
922 EnterCriticalSection(&authcache_cs);
923 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry) {
924 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
925 TRACE("Authorization found in cache\n");
927 nt_auth_identity->User = heap_strdupW(ad->user);
928 nt_auth_identity->Password = heap_strdupW(ad->password);
929 nt_auth_identity->Domain = heap_alloc(sizeof(WCHAR)*ad->domain_len);
930 if(!nt_auth_identity->User || !nt_auth_identity->Password ||
931 (!nt_auth_identity->Domain && ad->domain_len)) {
932 heap_free(nt_auth_identity->User);
933 heap_free(nt_auth_identity->Password);
934 heap_free(nt_auth_identity->Domain);
935 break;
938 nt_auth_identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
939 nt_auth_identity->UserLength = ad->user_len;
940 nt_auth_identity->PasswordLength = ad->password_len;
941 memcpy(nt_auth_identity->Domain, ad->domain, sizeof(WCHAR)*ad->domain_len);
942 nt_auth_identity->DomainLength = ad->domain_len;
943 LeaveCriticalSection(&authcache_cs);
944 return TRUE;
947 LeaveCriticalSection(&authcache_cs);
949 return FALSE;
952 static void cache_authorization(LPWSTR host, LPWSTR scheme,
953 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
955 authorizationData *ad;
956 BOOL found = FALSE;
958 TRACE("Caching authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
960 EnterCriticalSection(&authcache_cs);
961 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry)
962 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
963 found = TRUE;
964 break;
967 if(found) {
968 heap_free(ad->user);
969 heap_free(ad->password);
970 heap_free(ad->domain);
971 } else {
972 ad = heap_alloc(sizeof(authorizationData));
973 if(!ad) {
974 LeaveCriticalSection(&authcache_cs);
975 return;
978 ad->host = heap_strdupW(host);
979 ad->scheme = heap_strdupW(scheme);
980 list_add_head(&authorizationCache, &ad->entry);
983 ad->user = heap_strndupW(nt_auth_identity->User, nt_auth_identity->UserLength);
984 ad->password = heap_strndupW(nt_auth_identity->Password, nt_auth_identity->PasswordLength);
985 ad->domain = heap_strndupW(nt_auth_identity->Domain, nt_auth_identity->DomainLength);
986 ad->user_len = nt_auth_identity->UserLength;
987 ad->password_len = nt_auth_identity->PasswordLength;
988 ad->domain_len = nt_auth_identity->DomainLength;
990 if(!ad->host || !ad->scheme || !ad->user || !ad->password
991 || (nt_auth_identity->Domain && !ad->domain)) {
992 heap_free(ad->host);
993 heap_free(ad->scheme);
994 heap_free(ad->user);
995 heap_free(ad->password);
996 heap_free(ad->domain);
997 list_remove(&ad->entry);
998 heap_free(ad);
1001 LeaveCriticalSection(&authcache_cs);
1004 static BOOL HTTP_DoAuthorization( http_request_t *request, LPCWSTR pszAuthValue,
1005 struct HttpAuthInfo **ppAuthInfo,
1006 LPWSTR domain_and_username, LPWSTR password,
1007 LPWSTR host )
1009 SECURITY_STATUS sec_status;
1010 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
1011 BOOL first = FALSE;
1012 LPWSTR szRealm = NULL;
1014 TRACE("%s\n", debugstr_w(pszAuthValue));
1016 if (!pAuthInfo)
1018 TimeStamp exp;
1020 first = TRUE;
1021 pAuthInfo = heap_alloc(sizeof(*pAuthInfo));
1022 if (!pAuthInfo)
1023 return FALSE;
1025 SecInvalidateHandle(&pAuthInfo->cred);
1026 SecInvalidateHandle(&pAuthInfo->ctx);
1027 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
1028 pAuthInfo->attr = 0;
1029 pAuthInfo->auth_data = NULL;
1030 pAuthInfo->auth_data_len = 0;
1031 pAuthInfo->finished = FALSE;
1033 if (is_basic_auth_value(pszAuthValue,NULL))
1035 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
1036 pAuthInfo->scheme = heap_strdupW(szBasic);
1037 if (!pAuthInfo->scheme)
1039 heap_free(pAuthInfo);
1040 return FALSE;
1043 else
1045 PVOID pAuthData;
1046 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
1048 pAuthInfo->scheme = heap_strdupW(pszAuthValue);
1049 if (!pAuthInfo->scheme)
1051 heap_free(pAuthInfo);
1052 return FALSE;
1055 if (domain_and_username)
1057 WCHAR *user = strchrW(domain_and_username, '\\');
1058 WCHAR *domain = domain_and_username;
1060 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1062 pAuthData = &nt_auth_identity;
1064 if (user) user++;
1065 else
1067 user = domain_and_username;
1068 domain = NULL;
1071 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1072 nt_auth_identity.User = user;
1073 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
1074 nt_auth_identity.Domain = domain;
1075 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
1076 nt_auth_identity.Password = password;
1077 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
1079 cache_authorization(host, pAuthInfo->scheme, &nt_auth_identity);
1081 else if(retrieve_cached_authorization(host, pAuthInfo->scheme, &nt_auth_identity))
1082 pAuthData = &nt_auth_identity;
1083 else
1084 /* use default credentials */
1085 pAuthData = NULL;
1087 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
1088 SECPKG_CRED_OUTBOUND, NULL,
1089 pAuthData, NULL,
1090 NULL, &pAuthInfo->cred,
1091 &exp);
1093 if(pAuthData && !domain_and_username) {
1094 heap_free(nt_auth_identity.User);
1095 heap_free(nt_auth_identity.Domain);
1096 heap_free(nt_auth_identity.Password);
1099 if (sec_status == SEC_E_OK)
1101 PSecPkgInfoW sec_pkg_info;
1102 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
1103 if (sec_status == SEC_E_OK)
1105 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
1106 FreeContextBuffer(sec_pkg_info);
1109 if (sec_status != SEC_E_OK)
1111 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1112 debugstr_w(pAuthInfo->scheme), sec_status);
1113 heap_free(pAuthInfo->scheme);
1114 heap_free(pAuthInfo);
1115 return FALSE;
1118 *ppAuthInfo = pAuthInfo;
1120 else if (pAuthInfo->finished)
1121 return FALSE;
1123 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
1124 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
1126 ERR("authentication scheme changed from %s to %s\n",
1127 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
1128 return FALSE;
1131 if (is_basic_auth_value(pszAuthValue,&szRealm))
1133 int userlen;
1134 int passlen;
1135 char *auth_data = NULL;
1136 UINT auth_data_len = 0;
1138 TRACE("basic authentication realm %s\n",debugstr_w(szRealm));
1140 if (!domain_and_username)
1142 if (host && szRealm)
1143 auth_data_len = retrieve_cached_basic_authorization(host, szRealm,&auth_data);
1144 if (auth_data_len == 0)
1146 heap_free(szRealm);
1147 return FALSE;
1150 else
1152 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
1153 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
1155 /* length includes a nul terminator, which will be re-used for the ':' */
1156 auth_data = heap_alloc(userlen + 1 + passlen);
1157 if (!auth_data)
1159 heap_free(szRealm);
1160 return FALSE;
1163 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
1164 auth_data[userlen] = ':';
1165 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
1166 auth_data_len = userlen + 1 + passlen;
1167 if (host && szRealm)
1168 cache_basic_authorization(host, szRealm, auth_data, auth_data_len);
1171 pAuthInfo->auth_data = auth_data;
1172 pAuthInfo->auth_data_len = auth_data_len;
1173 pAuthInfo->finished = TRUE;
1174 heap_free(szRealm);
1175 return TRUE;
1177 else
1179 LPCWSTR pszAuthData;
1180 SecBufferDesc out_desc, in_desc;
1181 SecBuffer out, in;
1182 unsigned char *buffer;
1183 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
1184 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
1186 in.BufferType = SECBUFFER_TOKEN;
1187 in.cbBuffer = 0;
1188 in.pvBuffer = NULL;
1190 in_desc.ulVersion = 0;
1191 in_desc.cBuffers = 1;
1192 in_desc.pBuffers = &in;
1194 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
1195 if (*pszAuthData == ' ')
1197 pszAuthData++;
1198 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
1199 in.pvBuffer = heap_alloc(in.cbBuffer);
1200 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
1203 buffer = heap_alloc(pAuthInfo->max_token);
1205 out.BufferType = SECBUFFER_TOKEN;
1206 out.cbBuffer = pAuthInfo->max_token;
1207 out.pvBuffer = buffer;
1209 out_desc.ulVersion = 0;
1210 out_desc.cBuffers = 1;
1211 out_desc.pBuffers = &out;
1213 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
1214 first ? NULL : &pAuthInfo->ctx,
1215 first ? request->server->name : NULL,
1216 context_req, 0, SECURITY_NETWORK_DREP,
1217 in.pvBuffer ? &in_desc : NULL,
1218 0, &pAuthInfo->ctx, &out_desc,
1219 &pAuthInfo->attr, &pAuthInfo->exp);
1220 if (sec_status == SEC_E_OK)
1222 pAuthInfo->finished = TRUE;
1223 pAuthInfo->auth_data = out.pvBuffer;
1224 pAuthInfo->auth_data_len = out.cbBuffer;
1225 TRACE("sending last auth packet\n");
1227 else if (sec_status == SEC_I_CONTINUE_NEEDED)
1229 pAuthInfo->auth_data = out.pvBuffer;
1230 pAuthInfo->auth_data_len = out.cbBuffer;
1231 TRACE("sending next auth packet\n");
1233 else
1235 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
1236 heap_free(out.pvBuffer);
1237 destroy_authinfo(pAuthInfo);
1238 *ppAuthInfo = NULL;
1239 return FALSE;
1243 return TRUE;
1246 /***********************************************************************
1247 * HTTP_HttpAddRequestHeadersW (internal)
1249 static DWORD HTTP_HttpAddRequestHeadersW(http_request_t *request,
1250 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1252 LPWSTR lpszStart;
1253 LPWSTR lpszEnd;
1254 LPWSTR buffer;
1255 DWORD len, res = ERROR_HTTP_INVALID_HEADER;
1257 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
1259 if( dwHeaderLength == ~0U )
1260 len = strlenW(lpszHeader);
1261 else
1262 len = dwHeaderLength;
1263 buffer = heap_alloc(sizeof(WCHAR)*(len+1));
1264 lstrcpynW( buffer, lpszHeader, len + 1);
1266 lpszStart = buffer;
1270 LPWSTR * pFieldAndValue;
1272 lpszEnd = lpszStart;
1274 while (*lpszEnd != '\0')
1276 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1277 break;
1278 lpszEnd++;
1281 if (*lpszStart == '\0')
1282 break;
1284 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1286 *lpszEnd = '\0';
1287 lpszEnd++; /* Jump over newline */
1289 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
1290 if (*lpszStart == '\0')
1292 /* Skip 0-length headers */
1293 lpszStart = lpszEnd;
1294 res = ERROR_SUCCESS;
1295 continue;
1297 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
1298 if (pFieldAndValue)
1300 res = HTTP_VerifyValidHeader(request, pFieldAndValue[0]);
1301 if (res == ERROR_SUCCESS)
1302 res = HTTP_ProcessHeader(request, pFieldAndValue[0],
1303 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
1304 HTTP_FreeTokens(pFieldAndValue);
1307 lpszStart = lpszEnd;
1308 } while (res == ERROR_SUCCESS);
1310 heap_free(buffer);
1311 return res;
1314 /***********************************************************************
1315 * HttpAddRequestHeadersW (WININET.@)
1317 * Adds one or more HTTP header to the request handler
1319 * NOTE
1320 * On Windows if dwHeaderLength includes the trailing '\0', then
1321 * HttpAddRequestHeadersW() adds it too. However this results in an
1322 * invalid HTTP header which is rejected by some servers so we probably
1323 * don't need to match Windows on that point.
1325 * RETURNS
1326 * TRUE on success
1327 * FALSE on failure
1330 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
1331 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1333 http_request_t *request;
1334 DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
1336 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1338 if (!lpszHeader)
1339 return TRUE;
1341 request = (http_request_t*) get_handle_object( hHttpRequest );
1342 if (request && request->hdr.htype == WH_HHTTPREQ)
1343 res = HTTP_HttpAddRequestHeadersW( request, lpszHeader, dwHeaderLength, dwModifier );
1344 if( request )
1345 WININET_Release( &request->hdr );
1347 if(res != ERROR_SUCCESS)
1348 SetLastError(res);
1349 return res == ERROR_SUCCESS;
1352 /***********************************************************************
1353 * HttpAddRequestHeadersA (WININET.@)
1355 * Adds one or more HTTP header to the request handler
1357 * RETURNS
1358 * TRUE on success
1359 * FALSE on failure
1362 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
1363 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1365 DWORD len;
1366 LPWSTR hdr;
1367 BOOL r;
1369 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1371 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
1372 hdr = heap_alloc(len*sizeof(WCHAR));
1373 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
1374 if( dwHeaderLength != ~0U )
1375 dwHeaderLength = len;
1377 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
1379 heap_free( hdr );
1380 return r;
1383 static void free_accept_types( WCHAR **accept_types )
1385 WCHAR *ptr, **types = accept_types;
1387 if (!types) return;
1388 while ((ptr = *types))
1390 heap_free( ptr );
1391 types++;
1393 heap_free( accept_types );
1396 static WCHAR **convert_accept_types( const char **accept_types )
1398 unsigned int count;
1399 const char **types = accept_types;
1400 WCHAR **typesW;
1401 BOOL invalid_pointer = FALSE;
1403 if (!types) return NULL;
1404 count = 0;
1405 while (*types)
1407 __TRY
1409 /* find out how many there are */
1410 if (*types && **types)
1412 TRACE("accept type: %s\n", debugstr_a(*types));
1413 count++;
1416 __EXCEPT_PAGE_FAULT
1418 WARN("invalid accept type pointer\n");
1419 invalid_pointer = TRUE;
1421 __ENDTRY;
1422 types++;
1424 if (invalid_pointer) return NULL;
1425 if (!(typesW = heap_alloc( sizeof(WCHAR *) * (count + 1) ))) return NULL;
1426 count = 0;
1427 types = accept_types;
1428 while (*types)
1430 if (*types && **types) typesW[count++] = heap_strdupAtoW( *types );
1431 types++;
1433 typesW[count] = NULL;
1434 return typesW;
1437 /***********************************************************************
1438 * HttpOpenRequestA (WININET.@)
1440 * Open a HTTP request handle
1442 * RETURNS
1443 * HINTERNET a HTTP request handle on success
1444 * NULL on failure
1447 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
1448 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
1449 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
1450 DWORD dwFlags, DWORD_PTR dwContext)
1452 LPWSTR szVerb = NULL, szObjectName = NULL;
1453 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
1454 HINTERNET rc = NULL;
1456 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
1457 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
1458 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
1459 dwFlags, dwContext);
1461 if (lpszVerb)
1463 szVerb = heap_strdupAtoW(lpszVerb);
1464 if ( !szVerb )
1465 goto end;
1468 if (lpszObjectName)
1470 szObjectName = heap_strdupAtoW(lpszObjectName);
1471 if ( !szObjectName )
1472 goto end;
1475 if (lpszVersion)
1477 szVersion = heap_strdupAtoW(lpszVersion);
1478 if ( !szVersion )
1479 goto end;
1482 if (lpszReferrer)
1484 szReferrer = heap_strdupAtoW(lpszReferrer);
1485 if ( !szReferrer )
1486 goto end;
1489 szAcceptTypes = convert_accept_types( lpszAcceptTypes );
1490 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName, szVersion, szReferrer,
1491 (const WCHAR **)szAcceptTypes, dwFlags, dwContext);
1493 end:
1494 free_accept_types(szAcceptTypes);
1495 heap_free(szReferrer);
1496 heap_free(szVersion);
1497 heap_free(szObjectName);
1498 heap_free(szVerb);
1499 return rc;
1502 /***********************************************************************
1503 * HTTP_EncodeBase64
1505 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1507 UINT n = 0, x;
1508 static const CHAR HTTP_Base64Enc[] =
1509 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1511 while( len > 0 )
1513 /* first 6 bits, all from bin[0] */
1514 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1515 x = (bin[0] & 3) << 4;
1517 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1518 if( len == 1 )
1520 base64[n++] = HTTP_Base64Enc[x];
1521 base64[n++] = '=';
1522 base64[n++] = '=';
1523 break;
1525 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1526 x = ( bin[1] & 0x0f ) << 2;
1528 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1529 if( len == 2 )
1531 base64[n++] = HTTP_Base64Enc[x];
1532 base64[n++] = '=';
1533 break;
1535 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1537 /* last 6 bits, all from bin [2] */
1538 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1539 bin += 3;
1540 len -= 3;
1542 base64[n] = 0;
1543 return n;
1546 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1547 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1548 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1549 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1550 static const signed char HTTP_Base64Dec[256] =
1552 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1553 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1554 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1555 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1556 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1557 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1558 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1559 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1560 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1561 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1562 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1563 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1564 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1565 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1566 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1567 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1568 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1569 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1570 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1571 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1572 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1573 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1574 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1575 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1576 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1577 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1579 #undef CH
1581 /***********************************************************************
1582 * HTTP_DecodeBase64
1584 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1586 unsigned int n = 0;
1588 while(*base64)
1590 signed char in[4];
1592 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1593 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1594 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1595 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1597 WARN("invalid base64: %s\n", debugstr_w(base64));
1598 return 0;
1600 if (bin)
1601 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1602 n++;
1604 if ((base64[2] == '=') && (base64[3] == '='))
1605 break;
1606 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1607 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1609 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1610 return 0;
1612 if (bin)
1613 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1614 n++;
1616 if (base64[3] == '=')
1617 break;
1618 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1619 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1621 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1622 return 0;
1624 if (bin)
1625 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1626 n++;
1628 base64 += 4;
1631 return n;
1634 /***********************************************************************
1635 * HTTP_InsertAuthorization
1637 * Insert or delete the authorization field in the request header.
1639 static BOOL HTTP_InsertAuthorization( http_request_t *request, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1641 if (pAuthInfo)
1643 static const WCHAR wszSpace[] = {' ',0};
1644 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1645 unsigned int len;
1646 WCHAR *authorization = NULL;
1648 if (pAuthInfo->auth_data_len)
1650 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1651 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1652 authorization = heap_alloc((len+1)*sizeof(WCHAR));
1653 if (!authorization)
1654 return FALSE;
1656 strcpyW(authorization, pAuthInfo->scheme);
1657 strcatW(authorization, wszSpace);
1658 HTTP_EncodeBase64(pAuthInfo->auth_data,
1659 pAuthInfo->auth_data_len,
1660 authorization+strlenW(authorization));
1662 /* clear the data as it isn't valid now that it has been sent to the
1663 * server, unless it's Basic authentication which doesn't do
1664 * connection tracking */
1665 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1667 heap_free(pAuthInfo->auth_data);
1668 pAuthInfo->auth_data = NULL;
1669 pAuthInfo->auth_data_len = 0;
1673 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1675 HTTP_ProcessHeader(request, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1676 heap_free(authorization);
1678 return TRUE;
1681 static WCHAR *build_proxy_path_url(http_request_t *req)
1683 DWORD size, len;
1684 WCHAR *url;
1686 len = strlenW(req->server->scheme_host_port);
1687 size = len + strlenW(req->path) + 1;
1688 if(*req->path != '/')
1689 size++;
1690 url = heap_alloc(size * sizeof(WCHAR));
1691 if(!url)
1692 return NULL;
1694 memcpy(url, req->server->scheme_host_port, len*sizeof(WCHAR));
1695 if(*req->path != '/')
1696 url[len++] = '/';
1698 strcpyW(url+len, req->path);
1700 TRACE("url=%s\n", debugstr_w(url));
1701 return url;
1704 static BOOL HTTP_DomainMatches(LPCWSTR server, LPCWSTR domain)
1706 static const WCHAR localW[] = { '<','l','o','c','a','l','>',0 };
1707 BOOL ret = FALSE;
1709 if (!strcmpiW( domain, localW ) && !strchrW( server, '.' ))
1710 ret = TRUE;
1711 else if (*domain == '*')
1713 if (domain[1] == '.')
1715 LPCWSTR dot;
1717 /* For a hostname to match a wildcard, the last domain must match
1718 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1719 * hostname is www.foo.a.b, it matches, but a.b does not.
1721 dot = strchrW( server, '.' );
1722 if (dot)
1724 int len = strlenW( dot + 1 );
1726 if (len > strlenW( domain + 2 ))
1728 LPCWSTR ptr;
1730 /* The server's domain is longer than the wildcard, so it
1731 * could be a subdomain. Compare the last portion of the
1732 * server's domain.
1734 ptr = dot + len + 1 - strlenW( domain + 2 );
1735 if (!strcmpiW( ptr, domain + 2 ))
1737 /* This is only a match if the preceding character is
1738 * a '.', i.e. that it is a matching domain. E.g.
1739 * if domain is '*.b.c' and server is 'www.ab.c' they
1740 * do not match.
1742 ret = *(ptr - 1) == '.';
1745 else
1746 ret = !strcmpiW( dot + 1, domain + 2 );
1750 else
1751 ret = !strcmpiW( server, domain );
1752 return ret;
1755 static BOOL HTTP_ShouldBypassProxy(appinfo_t *lpwai, LPCWSTR server)
1757 LPCWSTR ptr;
1758 BOOL ret = FALSE;
1760 if (!lpwai->proxyBypass) return FALSE;
1761 ptr = lpwai->proxyBypass;
1762 do {
1763 LPCWSTR tmp = ptr;
1765 ptr = strchrW( ptr, ';' );
1766 if (!ptr)
1767 ptr = strchrW( tmp, ' ' );
1768 if (ptr)
1770 if (ptr - tmp < INTERNET_MAX_HOST_NAME_LENGTH)
1772 WCHAR domain[INTERNET_MAX_HOST_NAME_LENGTH];
1774 memcpy( domain, tmp, (ptr - tmp) * sizeof(WCHAR) );
1775 domain[ptr - tmp] = 0;
1776 ret = HTTP_DomainMatches( server, domain );
1778 ptr += 1;
1780 else if (*tmp)
1781 ret = HTTP_DomainMatches( server, tmp );
1782 } while (ptr && !ret);
1783 return ret;
1786 /***********************************************************************
1787 * HTTP_DealWithProxy
1789 static BOOL HTTP_DealWithProxy(appinfo_t *hIC, http_session_t *session, http_request_t *request)
1791 static const WCHAR protoHttp[] = { 'h','t','t','p',0 };
1792 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1793 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1794 WCHAR buf[INTERNET_MAX_HOST_NAME_LENGTH];
1795 WCHAR protoProxy[INTERNET_MAX_URL_LENGTH];
1796 DWORD protoProxyLen = INTERNET_MAX_URL_LENGTH;
1797 WCHAR proxy[INTERNET_MAX_URL_LENGTH];
1798 static WCHAR szNul[] = { 0 };
1799 URL_COMPONENTSW UrlComponents;
1800 server_t *new_server;
1801 BOOL is_https;
1803 memset( &UrlComponents, 0, sizeof UrlComponents );
1804 UrlComponents.dwStructSize = sizeof UrlComponents;
1805 UrlComponents.lpszHostName = buf;
1806 UrlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
1808 if (!INTERNET_FindProxyForProtocol(hIC->proxy, protoHttp, protoProxy, &protoProxyLen))
1809 return FALSE;
1810 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1811 protoProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1812 sprintfW(proxy, szFormat, protoProxy);
1813 else
1814 strcpyW(proxy, protoProxy);
1815 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1816 return FALSE;
1817 if( UrlComponents.dwHostNameLength == 0 )
1818 return FALSE;
1820 if( !request->path )
1821 request->path = szNul;
1823 is_https = (UrlComponents.nScheme == INTERNET_SCHEME_HTTPS);
1824 if (is_https && UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1825 UrlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
1827 new_server = get_server(UrlComponents.lpszHostName, UrlComponents.nPort, is_https, TRUE);
1828 if(!new_server)
1829 return FALSE;
1831 request->proxy = new_server;
1833 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server->name), new_server->port);
1834 return TRUE;
1837 static DWORD HTTP_ResolveName(http_request_t *request)
1839 server_t *server = request->proxy ? request->proxy : request->server;
1840 socklen_t addr_len;
1841 void *addr;
1843 if(server->addr_len)
1844 return ERROR_SUCCESS;
1846 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1847 INTERNET_STATUS_RESOLVING_NAME,
1848 server->name,
1849 (strlenW(server->name)+1) * sizeof(WCHAR));
1851 addr_len = sizeof(server->addr);
1852 if (!GetAddress(server->name, server->port, (struct sockaddr *)&server->addr, &addr_len))
1853 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1855 switch(server->addr.ss_family) {
1856 case AF_INET:
1857 addr = &((struct sockaddr_in *)&server->addr)->sin_addr;
1858 break;
1859 case AF_INET6:
1860 addr = &((struct sockaddr_in6 *)&server->addr)->sin6_addr;
1861 break;
1862 default:
1863 WARN("unsupported family %d\n", server->addr.ss_family);
1864 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1867 server->addr_len = addr_len;
1868 inet_ntop(server->addr.ss_family, addr, server->addr_str, sizeof(server->addr_str));
1869 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1870 INTERNET_STATUS_NAME_RESOLVED,
1871 server->addr_str, strlen(server->addr_str)+1);
1873 TRACE("resolved %s to %s\n", debugstr_w(server->name), server->addr_str);
1874 return ERROR_SUCCESS;
1877 static BOOL HTTP_GetRequestURL(http_request_t *req, LPWSTR buf)
1879 static const WCHAR http[] = { 'h','t','t','p',':','/','/',0 };
1880 static const WCHAR https[] = { 'h','t','t','p','s',':','/','/',0 };
1881 static const WCHAR slash[] = { '/',0 };
1882 LPHTTPHEADERW host_header;
1883 LPCWSTR scheme;
1885 host_header = HTTP_GetHeader(req, hostW);
1886 if(!host_header)
1887 return FALSE;
1889 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1890 scheme = https;
1891 else
1892 scheme = http;
1893 strcpyW(buf, scheme);
1894 strcatW(buf, host_header->lpszValue);
1895 if (req->path[0] != '/')
1896 strcatW(buf, slash);
1897 strcatW(buf, req->path);
1898 return TRUE;
1902 /***********************************************************************
1903 * HTTPREQ_Destroy (internal)
1905 * Deallocate request handle
1908 static void HTTPREQ_Destroy(object_header_t *hdr)
1910 http_request_t *request = (http_request_t*) hdr;
1911 DWORD i;
1913 TRACE("\n");
1915 if(request->hCacheFile)
1916 CloseHandle(request->hCacheFile);
1917 if(request->req_file)
1918 req_file_release(request->req_file);
1920 request->read_section.DebugInfo->Spare[0] = 0;
1921 DeleteCriticalSection( &request->read_section );
1922 WININET_Release(&request->session->hdr);
1924 destroy_authinfo(request->authInfo);
1925 destroy_authinfo(request->proxyAuthInfo);
1927 if(request->server)
1928 server_release(request->server);
1929 if(request->proxy)
1930 server_release(request->proxy);
1932 heap_free(request->path);
1933 heap_free(request->verb);
1934 heap_free(request->version);
1935 heap_free(request->statusText);
1937 for (i = 0; i < request->nCustHeaders; i++)
1939 heap_free(request->custHeaders[i].lpszField);
1940 heap_free(request->custHeaders[i].lpszValue);
1942 destroy_data_stream(request->data_stream);
1943 heap_free(request->custHeaders);
1946 static void http_release_netconn(http_request_t *req, BOOL reuse)
1948 TRACE("%p %p\n",req, req->netconn);
1950 if(!req->netconn)
1951 return;
1953 if(reuse && req->netconn->keep_alive) {
1954 BOOL run_collector;
1956 EnterCriticalSection(&connection_pool_cs);
1958 list_add_head(&req->netconn->server->conn_pool, &req->netconn->pool_entry);
1959 req->netconn->keep_until = GetTickCount64() + COLLECT_TIME;
1960 req->netconn = NULL;
1962 run_collector = !collector_running;
1963 collector_running = TRUE;
1965 LeaveCriticalSection(&connection_pool_cs);
1967 if(run_collector) {
1968 HANDLE thread = NULL;
1969 HMODULE module;
1971 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR*)WININET_hModule, &module);
1972 if(module)
1973 thread = CreateThread(NULL, 0, collect_connections_proc, NULL, 0, NULL);
1974 if(!thread) {
1975 EnterCriticalSection(&connection_pool_cs);
1976 collector_running = FALSE;
1977 LeaveCriticalSection(&connection_pool_cs);
1979 if(module)
1980 FreeLibrary(module);
1982 else
1983 CloseHandle(thread);
1985 return;
1988 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1989 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1991 free_netconn(req->netconn);
1992 req->netconn = NULL;
1994 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1995 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1998 static BOOL HTTP_KeepAlive(http_request_t *request)
2000 WCHAR szVersion[10];
2001 WCHAR szConnectionResponse[20];
2002 DWORD dwBufferSize = sizeof(szVersion);
2003 BOOL keepalive = FALSE;
2005 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
2006 * the connection is keep-alive by default */
2007 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_VERSION, szVersion, &dwBufferSize, NULL) == ERROR_SUCCESS
2008 && !strcmpiW(szVersion, g_szHttp1_1))
2010 keepalive = TRUE;
2013 dwBufferSize = sizeof(szConnectionResponse);
2014 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS
2015 || HTTP_HttpQueryInfoW(request, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS)
2017 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
2020 return keepalive;
2023 static void HTTPREQ_CloseConnection(object_header_t *hdr)
2025 http_request_t *req = (http_request_t*)hdr;
2027 http_release_netconn(req, drain_content(req, FALSE));
2030 static DWORD str_to_buffer(const WCHAR *str, void *buffer, DWORD *size, BOOL unicode)
2032 int len;
2033 if (unicode)
2035 WCHAR *buf = buffer;
2037 if (str) len = strlenW(str);
2038 else len = 0;
2039 if (*size < (len + 1) * sizeof(WCHAR))
2041 *size = (len + 1) * sizeof(WCHAR);
2042 return ERROR_INSUFFICIENT_BUFFER;
2044 if (str) strcpyW(buf, str);
2045 else buf[0] = 0;
2047 *size = len;
2048 return ERROR_SUCCESS;
2050 else
2052 char *buf = buffer;
2054 if (str) len = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
2055 else len = 1;
2056 if (*size < len)
2058 *size = len;
2059 return ERROR_INSUFFICIENT_BUFFER;
2061 if (str) WideCharToMultiByte(CP_ACP, 0, str, -1, buf, *size, NULL, NULL);
2062 else buf[0] = 0;
2064 *size = len - 1;
2065 return ERROR_SUCCESS;
2069 static DWORD HTTPREQ_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2071 http_request_t *req = (http_request_t*)hdr;
2073 switch(option) {
2074 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO:
2076 INTERNET_DIAGNOSTIC_SOCKET_INFO *info = buffer;
2078 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2080 if (*size < sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO))
2081 return ERROR_INSUFFICIENT_BUFFER;
2082 *size = sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO);
2083 /* FIXME: can't get a SOCKET from our connection since we don't use
2084 * winsock
2086 info->Socket = 0;
2087 /* FIXME: get source port from req->netConnection */
2088 info->SourcePort = 0;
2089 info->DestPort = req->server->port;
2090 info->Flags = 0;
2091 if (HTTP_KeepAlive(req))
2092 info->Flags |= IDSI_FLAG_KEEP_ALIVE;
2093 if (req->proxy)
2094 info->Flags |= IDSI_FLAG_PROXY;
2095 if (req->netconn && req->netconn->secure)
2096 info->Flags |= IDSI_FLAG_SECURE;
2098 return ERROR_SUCCESS;
2101 case 98:
2102 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2103 /* fall through */
2104 case INTERNET_OPTION_SECURITY_FLAGS:
2106 DWORD flags;
2108 if (*size < sizeof(ULONG))
2109 return ERROR_INSUFFICIENT_BUFFER;
2111 *size = sizeof(DWORD);
2112 flags = req->netconn ? req->netconn->security_flags : req->security_flags | req->server->security_flags;
2113 *(DWORD *)buffer = flags;
2115 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags);
2116 return ERROR_SUCCESS;
2119 case INTERNET_OPTION_HANDLE_TYPE:
2120 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2122 if (*size < sizeof(ULONG))
2123 return ERROR_INSUFFICIENT_BUFFER;
2125 *size = sizeof(DWORD);
2126 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
2127 return ERROR_SUCCESS;
2129 case INTERNET_OPTION_URL: {
2130 WCHAR url[INTERNET_MAX_URL_LENGTH];
2131 HTTPHEADERW *host;
2133 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
2135 TRACE("INTERNET_OPTION_URL\n");
2137 host = HTTP_GetHeader(req, hostW);
2138 strcpyW(url, httpW);
2139 strcatW(url, host->lpszValue);
2140 strcatW(url, req->path);
2142 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
2143 return str_to_buffer(url, buffer, size, unicode);
2145 case INTERNET_OPTION_USER_AGENT:
2146 return str_to_buffer(req->session->appInfo->agent, buffer, size, unicode);
2147 case INTERNET_OPTION_USERNAME:
2148 return str_to_buffer(req->session->userName, buffer, size, unicode);
2149 case INTERNET_OPTION_PASSWORD:
2150 return str_to_buffer(req->session->password, buffer, size, unicode);
2151 case INTERNET_OPTION_PROXY_USERNAME:
2152 return str_to_buffer(req->session->appInfo->proxyUsername, buffer, size, unicode);
2153 case INTERNET_OPTION_PROXY_PASSWORD:
2154 return str_to_buffer(req->session->appInfo->proxyPassword, buffer, size, unicode);
2156 case INTERNET_OPTION_CACHE_TIMESTAMPS: {
2157 INTERNET_CACHE_ENTRY_INFOW *info;
2158 INTERNET_CACHE_TIMESTAMPS *ts = buffer;
2159 WCHAR url[INTERNET_MAX_URL_LENGTH];
2160 DWORD nbytes, error;
2161 BOOL ret;
2163 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2165 if (*size < sizeof(*ts))
2167 *size = sizeof(*ts);
2168 return ERROR_INSUFFICIENT_BUFFER;
2170 nbytes = 0;
2171 HTTP_GetRequestURL(req, url);
2172 ret = GetUrlCacheEntryInfoW(url, NULL, &nbytes);
2173 error = GetLastError();
2174 if (!ret && error == ERROR_INSUFFICIENT_BUFFER)
2176 if (!(info = heap_alloc(nbytes)))
2177 return ERROR_OUTOFMEMORY;
2179 GetUrlCacheEntryInfoW(url, info, &nbytes);
2181 ts->ftExpires = info->ExpireTime;
2182 ts->ftLastModified = info->LastModifiedTime;
2184 heap_free(info);
2185 *size = sizeof(*ts);
2186 return ERROR_SUCCESS;
2188 return error;
2191 case INTERNET_OPTION_DATAFILE_NAME: {
2192 DWORD req_size;
2194 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2196 if(!req->req_file) {
2197 *size = 0;
2198 return ERROR_INTERNET_ITEM_NOT_FOUND;
2201 if(unicode) {
2202 req_size = (lstrlenW(req->req_file->file_name)+1) * sizeof(WCHAR);
2203 if(*size < req_size)
2204 return ERROR_INSUFFICIENT_BUFFER;
2206 *size = req_size;
2207 memcpy(buffer, req->req_file->file_name, *size);
2208 return ERROR_SUCCESS;
2209 }else {
2210 req_size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name, -1, NULL, 0, NULL, NULL);
2211 if (req_size > *size)
2212 return ERROR_INSUFFICIENT_BUFFER;
2214 *size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name,
2215 -1, buffer, *size, NULL, NULL);
2216 return ERROR_SUCCESS;
2220 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
2221 PCCERT_CONTEXT context;
2223 if(!req->netconn)
2224 return ERROR_INTERNET_INVALID_OPERATION;
2226 if(*size < sizeof(INTERNET_CERTIFICATE_INFOA)) {
2227 *size = sizeof(INTERNET_CERTIFICATE_INFOA);
2228 return ERROR_INSUFFICIENT_BUFFER;
2231 context = (PCCERT_CONTEXT)NETCON_GetCert(req->netconn);
2232 if(context) {
2233 INTERNET_CERTIFICATE_INFOA *info = (INTERNET_CERTIFICATE_INFOA*)buffer;
2234 DWORD len;
2236 memset(info, 0, sizeof(*info));
2237 info->ftExpiry = context->pCertInfo->NotAfter;
2238 info->ftStart = context->pCertInfo->NotBefore;
2239 len = CertNameToStrA(context->dwCertEncodingType,
2240 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2241 info->lpszSubjectInfo = LocalAlloc(0, len);
2242 if(info->lpszSubjectInfo)
2243 CertNameToStrA(context->dwCertEncodingType,
2244 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2245 info->lpszSubjectInfo, len);
2246 len = CertNameToStrA(context->dwCertEncodingType,
2247 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2248 info->lpszIssuerInfo = LocalAlloc(0, len);
2249 if(info->lpszIssuerInfo)
2250 CertNameToStrA(context->dwCertEncodingType,
2251 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2252 info->lpszIssuerInfo, len);
2253 info->dwKeySize = NETCON_GetCipherStrength(req->netconn);
2254 CertFreeCertificateContext(context);
2255 return ERROR_SUCCESS;
2257 return ERROR_NOT_SUPPORTED;
2259 case INTERNET_OPTION_CONNECT_TIMEOUT:
2260 if (*size < sizeof(DWORD))
2261 return ERROR_INSUFFICIENT_BUFFER;
2263 *size = sizeof(DWORD);
2264 *(DWORD *)buffer = req->connect_timeout;
2265 return ERROR_SUCCESS;
2266 case INTERNET_OPTION_REQUEST_FLAGS: {
2267 DWORD flags = 0;
2269 if (*size < sizeof(DWORD))
2270 return ERROR_INSUFFICIENT_BUFFER;
2272 /* FIXME: Add support for:
2273 * INTERNET_REQFLAG_FROM_CACHE
2274 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2277 if(req->proxy)
2278 flags |= INTERNET_REQFLAG_VIA_PROXY;
2279 if(!req->status_code)
2280 flags |= INTERNET_REQFLAG_NO_HEADERS;
2282 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags);
2284 *size = sizeof(DWORD);
2285 *(DWORD*)buffer = flags;
2286 return ERROR_SUCCESS;
2290 return INET_QueryOption(hdr, option, buffer, size, unicode);
2293 static DWORD HTTPREQ_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
2295 http_request_t *req = (http_request_t*)hdr;
2297 switch(option) {
2298 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2299 TRACE("Undocumented option 99\n");
2301 if (!buffer || size != sizeof(DWORD))
2302 return ERROR_INVALID_PARAMETER;
2303 if(*(DWORD*)buffer & ~SECURITY_SET_MASK)
2304 return ERROR_INTERNET_OPTION_NOT_SETTABLE;
2306 /* fall through */
2307 case INTERNET_OPTION_SECURITY_FLAGS:
2309 DWORD flags;
2311 if (!buffer || size != sizeof(DWORD))
2312 return ERROR_INVALID_PARAMETER;
2313 flags = *(DWORD *)buffer;
2314 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags);
2315 flags &= SECURITY_SET_MASK;
2316 req->security_flags |= flags;
2317 if(req->netconn)
2318 req->netconn->security_flags |= flags;
2319 return ERROR_SUCCESS;
2321 case INTERNET_OPTION_CONNECT_TIMEOUT:
2322 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2323 req->connect_timeout = *(DWORD *)buffer;
2324 return ERROR_SUCCESS;
2326 case INTERNET_OPTION_SEND_TIMEOUT:
2327 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2328 req->send_timeout = *(DWORD *)buffer;
2329 return ERROR_SUCCESS;
2331 case INTERNET_OPTION_RECEIVE_TIMEOUT:
2332 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2333 req->receive_timeout = *(DWORD *)buffer;
2334 return ERROR_SUCCESS;
2336 case INTERNET_OPTION_USERNAME:
2337 heap_free(req->session->userName);
2338 if (!(req->session->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2339 return ERROR_SUCCESS;
2341 case INTERNET_OPTION_PASSWORD:
2342 heap_free(req->session->password);
2343 if (!(req->session->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2344 return ERROR_SUCCESS;
2346 case INTERNET_OPTION_PROXY_USERNAME:
2347 heap_free(req->session->appInfo->proxyUsername);
2348 if (!(req->session->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2349 return ERROR_SUCCESS;
2351 case INTERNET_OPTION_PROXY_PASSWORD:
2352 heap_free(req->session->appInfo->proxyPassword);
2353 if (!(req->session->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2354 return ERROR_SUCCESS;
2356 case INTERNET_OPTION_HTTP_DECODING:
2357 if(size != sizeof(BOOL))
2358 return ERROR_INVALID_PARAMETER;
2359 req->decoding = *(BOOL*)buffer;
2360 return ERROR_SUCCESS;
2363 return INET_SetOption(hdr, option, buffer, size);
2366 static void commit_cache_entry(http_request_t *req)
2368 WCHAR url[INTERNET_MAX_URL_LENGTH];
2370 TRACE("%p\n", req);
2372 CloseHandle(req->hCacheFile);
2373 req->hCacheFile = NULL;
2375 if(HTTP_GetRequestURL(req, url)) {
2376 WCHAR *header;
2377 DWORD header_len;
2378 BOOL res;
2380 header = build_response_header(req, TRUE);
2381 header_len = (header ? strlenW(header) : 0);
2382 res = CommitUrlCacheEntryW(url, req->req_file->file_name, req->expires,
2383 req->last_modified, NORMAL_CACHE_ENTRY,
2384 header, header_len, NULL, 0);
2385 if(res)
2386 req->req_file->is_committed = TRUE;
2387 else
2388 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2389 heap_free(header);
2393 static void create_cache_entry(http_request_t *req)
2395 static const WCHAR no_cacheW[] = {'n','o','-','c','a','c','h','e',0};
2396 static const WCHAR no_storeW[] = {'n','o','-','s','t','o','r','e',0};
2398 WCHAR url[INTERNET_MAX_URL_LENGTH];
2399 WCHAR file_name[MAX_PATH+1];
2400 BOOL b = TRUE;
2402 /* FIXME: We should free previous cache file earlier */
2403 if(req->req_file) {
2404 req_file_release(req->req_file);
2405 req->req_file = NULL;
2407 if(req->hCacheFile) {
2408 CloseHandle(req->hCacheFile);
2409 req->hCacheFile = NULL;
2412 if(req->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE)
2413 b = FALSE;
2415 if(b) {
2416 int header_idx = HTTP_GetCustomHeaderIndex(req, szCache_Control, 0, FALSE);
2417 if(header_idx != -1) {
2418 WCHAR *ptr;
2420 for(ptr=req->custHeaders[header_idx].lpszValue; *ptr; ) {
2421 WCHAR *end;
2423 while(*ptr==' ' || *ptr=='\t')
2424 ptr++;
2426 end = strchrW(ptr, ',');
2427 if(!end)
2428 end = ptr + strlenW(ptr);
2430 if(!strncmpiW(ptr, no_cacheW, sizeof(no_cacheW)/sizeof(*no_cacheW)-1)
2431 || !strncmpiW(ptr, no_storeW, sizeof(no_storeW)/sizeof(*no_storeW)-1)) {
2432 b = FALSE;
2433 break;
2436 ptr = end;
2437 if(*ptr == ',')
2438 ptr++;
2443 if(!b) {
2444 if(!(req->hdr.dwFlags & INTERNET_FLAG_NEED_FILE))
2445 return;
2447 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2450 b = HTTP_GetRequestURL(req, url);
2451 if(!b) {
2452 WARN("Could not get URL\n");
2453 return;
2456 b = CreateUrlCacheEntryW(url, req->contentLength == ~0u ? 0 : req->contentLength, NULL, file_name, 0);
2457 if(!b) {
2458 WARN("Could not create cache entry: %08x\n", GetLastError());
2459 return;
2462 create_req_file(file_name, &req->req_file);
2464 req->hCacheFile = CreateFileW(file_name, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
2465 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2466 if(req->hCacheFile == INVALID_HANDLE_VALUE) {
2467 WARN("Could not create file: %u\n", GetLastError());
2468 req->hCacheFile = NULL;
2469 return;
2472 if(req->read_size) {
2473 DWORD written;
2475 b = WriteFile(req->hCacheFile, req->read_buf+req->read_pos, req->read_size, &written, NULL);
2476 if(!b)
2477 FIXME("WriteFile failed: %u\n", GetLastError());
2479 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2480 commit_cache_entry(req);
2484 /* read some more data into the read buffer (the read section must be held) */
2485 static DWORD read_more_data( http_request_t *req, int maxlen )
2487 DWORD res;
2488 int len;
2490 if (req->read_pos)
2492 /* move existing data to the start of the buffer */
2493 if(req->read_size)
2494 memmove( req->read_buf, req->read_buf + req->read_pos, req->read_size );
2495 req->read_pos = 0;
2498 if (maxlen == -1) maxlen = sizeof(req->read_buf);
2500 res = NETCON_recv( req->netconn, req->read_buf + req->read_size,
2501 maxlen - req->read_size, 0, &len );
2502 if(res == ERROR_SUCCESS)
2503 req->read_size += len;
2505 return res;
2508 /* remove some amount of data from the read buffer (the read section must be held) */
2509 static void remove_data( http_request_t *req, int count )
2511 if (!(req->read_size -= count)) req->read_pos = 0;
2512 else req->read_pos += count;
2515 static DWORD read_line( http_request_t *req, LPSTR buffer, DWORD *len )
2517 int count, bytes_read, pos = 0;
2518 DWORD res;
2520 EnterCriticalSection( &req->read_section );
2521 for (;;)
2523 BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
2525 if (eol)
2527 count = eol - (req->read_buf + req->read_pos);
2528 bytes_read = count + 1;
2530 else count = bytes_read = req->read_size;
2532 count = min( count, *len - pos );
2533 memcpy( buffer + pos, req->read_buf + req->read_pos, count );
2534 pos += count;
2535 remove_data( req, bytes_read );
2536 if (eol) break;
2538 if ((res = read_more_data( req, -1 )))
2540 WARN( "read failed %u\n", res );
2541 LeaveCriticalSection( &req->read_section );
2542 return res;
2544 if (!req->read_size)
2546 *len = 0;
2547 TRACE( "returning empty string\n" );
2548 LeaveCriticalSection( &req->read_section );
2549 return ERROR_SUCCESS;
2552 LeaveCriticalSection( &req->read_section );
2554 if (pos < *len)
2556 if (pos && buffer[pos - 1] == '\r') pos--;
2557 *len = pos + 1;
2559 buffer[*len - 1] = 0;
2560 TRACE( "returning %s\n", debugstr_a(buffer));
2561 return ERROR_SUCCESS;
2564 /* check if we have reached the end of the data to read (the read section must be held) */
2565 static BOOL end_of_read_data( http_request_t *req )
2567 return !req->read_size && req->data_stream->vtbl->end_of_data(req->data_stream, req);
2570 static DWORD read_http_stream(http_request_t *req, BYTE *buf, DWORD size, DWORD *read, read_mode_t read_mode)
2572 DWORD res;
2574 res = req->data_stream->vtbl->read(req->data_stream, req, buf, size, read, read_mode);
2575 assert(*read <= size);
2577 if(req->hCacheFile) {
2578 if(*read) {
2579 BOOL bres;
2580 DWORD written;
2582 bres = WriteFile(req->hCacheFile, buf, *read, &written, NULL);
2583 if(!bres)
2584 FIXME("WriteFile failed: %u\n", GetLastError());
2587 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2588 commit_cache_entry(req);
2591 return res;
2594 /* fetch some more data into the read buffer (the read section must be held) */
2595 static DWORD refill_read_buffer(http_request_t *req, read_mode_t read_mode, DWORD *read_bytes)
2597 DWORD res, read=0;
2599 if(req->read_size == sizeof(req->read_buf))
2600 return ERROR_SUCCESS;
2602 if(req->read_pos) {
2603 if(req->read_size)
2604 memmove(req->read_buf, req->read_buf+req->read_pos, req->read_size);
2605 req->read_pos = 0;
2608 res = read_http_stream(req, req->read_buf+req->read_size, sizeof(req->read_buf) - req->read_size,
2609 &read, read_mode);
2610 req->read_size += read;
2612 TRACE("read %u bytes, read_size %u\n", read, req->read_size);
2613 if(read_bytes)
2614 *read_bytes = read;
2615 return res;
2618 /* return the size of data available to be read immediately (the read section must be held) */
2619 static DWORD get_avail_data( http_request_t *req )
2621 return req->read_size + req->data_stream->vtbl->get_avail_data(req->data_stream, req);
2624 static DWORD netconn_get_avail_data(data_stream_t *stream, http_request_t *req)
2626 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2627 DWORD avail = 0;
2629 if(req->netconn)
2630 NETCON_query_data_available(req->netconn, &avail);
2631 return netconn_stream->content_length == ~0u
2632 ? avail
2633 : min(avail, netconn_stream->content_length-netconn_stream->content_read);
2636 static BOOL netconn_end_of_data(data_stream_t *stream, http_request_t *req)
2638 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2639 return netconn_stream->content_read == netconn_stream->content_length || !req->netconn;
2642 static DWORD netconn_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2643 DWORD *read, read_mode_t read_mode)
2645 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2646 DWORD res = ERROR_SUCCESS;
2647 int len = 0;
2649 size = min(size, netconn_stream->content_length-netconn_stream->content_read);
2651 if(read_mode == READMODE_NOBLOCK) {
2652 DWORD avail = netconn_get_avail_data(stream, req);
2653 if (size > avail)
2654 size = avail;
2657 if(size && req->netconn) {
2658 if((res = NETCON_recv(req->netconn, buf, size, read_mode == READMODE_SYNC ? MSG_WAITALL : 0, &len)))
2659 len = 0;
2660 if(!len)
2661 netconn_stream->content_length = netconn_stream->content_read;
2664 netconn_stream->content_read += *read = len;
2665 TRACE("read %u bytes\n", len);
2666 return res;
2669 static BOOL netconn_drain_content(data_stream_t *stream, http_request_t *req)
2671 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2672 BYTE buf[1024];
2673 DWORD avail;
2674 int len;
2676 if(netconn_end_of_data(stream, req))
2677 return TRUE;
2679 do {
2680 avail = netconn_get_avail_data(stream, req);
2681 if(!avail)
2682 return FALSE;
2684 if(NETCON_recv(req->netconn, buf, min(avail, sizeof(buf)), 0, &len) != ERROR_SUCCESS)
2685 return FALSE;
2687 netconn_stream->content_read += len;
2688 }while(netconn_stream->content_read < netconn_stream->content_length);
2690 return TRUE;
2693 static void netconn_destroy(data_stream_t *stream)
2697 static const data_stream_vtbl_t netconn_stream_vtbl = {
2698 netconn_get_avail_data,
2699 netconn_end_of_data,
2700 netconn_read,
2701 netconn_drain_content,
2702 netconn_destroy
2705 /* read some more data into the read buffer (the read section must be held) */
2706 static DWORD read_more_chunked_data(chunked_stream_t *stream, http_request_t *req, int maxlen)
2708 DWORD res;
2709 int len;
2711 assert(!stream->end_of_data);
2713 if (stream->buf_pos)
2715 /* move existing data to the start of the buffer */
2716 if(stream->buf_size)
2717 memmove(stream->buf, stream->buf + stream->buf_pos, stream->buf_size);
2718 stream->buf_pos = 0;
2721 if (maxlen == -1) maxlen = sizeof(stream->buf);
2723 res = NETCON_recv( req->netconn, stream->buf + stream->buf_size,
2724 maxlen - stream->buf_size, 0, &len );
2725 if(res == ERROR_SUCCESS)
2726 stream->buf_size += len;
2728 return res;
2731 /* remove some amount of data from the read buffer (the read section must be held) */
2732 static void remove_chunked_data(chunked_stream_t *stream, int count)
2734 if (!(stream->buf_size -= count)) stream->buf_pos = 0;
2735 else stream->buf_pos += count;
2738 /* discard data contents until we reach end of line (the read section must be held) */
2739 static DWORD discard_chunked_eol(chunked_stream_t *stream, http_request_t *req)
2741 DWORD res;
2745 BYTE *eol = memchr(stream->buf + stream->buf_pos, '\n', stream->buf_size);
2746 if (eol)
2748 remove_chunked_data(stream, (eol + 1) - (stream->buf + stream->buf_pos));
2749 break;
2751 stream->buf_pos = stream->buf_size = 0; /* discard everything */
2752 if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
2753 } while (stream->buf_size);
2754 return ERROR_SUCCESS;
2757 /* read the size of the next chunk (the read section must be held) */
2758 static DWORD start_next_chunk(chunked_stream_t *stream, http_request_t *req)
2760 DWORD chunk_size = 0, res;
2762 assert(!stream->chunk_size || stream->chunk_size == ~0u);
2764 if (stream->end_of_data) return ERROR_NO_MORE_FILES;
2766 /* read terminator for the previous chunk */
2767 if(!stream->chunk_size && (res = discard_chunked_eol(stream, req)) != ERROR_SUCCESS)
2768 return res;
2770 for (;;)
2772 while (stream->buf_size)
2774 char ch = stream->buf[stream->buf_pos];
2775 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
2776 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
2777 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
2778 else if (ch == ';' || ch == '\r' || ch == '\n')
2780 TRACE( "reading %u byte chunk\n", chunk_size );
2781 stream->chunk_size = chunk_size;
2782 if (req->contentLength == ~0u) req->contentLength = chunk_size;
2783 else req->contentLength += chunk_size;
2785 if (!chunk_size) stream->end_of_data = TRUE;
2786 return discard_chunked_eol(stream, req);
2788 remove_chunked_data(stream, 1);
2790 if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
2791 if (!stream->buf_size)
2793 stream->chunk_size = 0;
2794 return ERROR_SUCCESS;
2799 static DWORD chunked_get_avail_data(data_stream_t *stream, http_request_t *req)
2801 /* Allow reading only from read buffer */
2802 return 0;
2805 static BOOL chunked_end_of_data(data_stream_t *stream, http_request_t *req)
2807 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2808 return chunked_stream->end_of_data;
2811 static DWORD chunked_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2812 DWORD *read, read_mode_t read_mode)
2814 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2815 DWORD read_bytes = 0, ret_read = 0, res = ERROR_SUCCESS;
2817 if(!chunked_stream->chunk_size || chunked_stream->chunk_size == ~0u) {
2818 res = start_next_chunk(chunked_stream, req);
2819 if(res != ERROR_SUCCESS)
2820 return res;
2823 while(size && chunked_stream->chunk_size && !chunked_stream->end_of_data) {
2824 if(chunked_stream->buf_size) {
2825 read_bytes = min(size, min(chunked_stream->buf_size, chunked_stream->chunk_size));
2827 /* this could block */
2828 if(read_mode == READMODE_NOBLOCK && read_bytes == chunked_stream->chunk_size)
2829 break;
2831 memcpy(buf+ret_read, chunked_stream->buf+chunked_stream->buf_pos, read_bytes);
2832 remove_chunked_data(chunked_stream, read_bytes);
2833 }else {
2834 read_bytes = min(size, chunked_stream->chunk_size);
2836 if(read_mode == READMODE_NOBLOCK) {
2837 DWORD avail;
2839 if(!req->netconn || !NETCON_query_data_available(req->netconn, &avail) || !avail)
2840 break;
2841 if(read_bytes > avail)
2842 read_bytes = avail;
2844 /* this could block */
2845 if(read_bytes == chunked_stream->chunk_size)
2846 break;
2849 res = NETCON_recv(req->netconn, (char *)buf+ret_read, read_bytes, 0, (int*)&read_bytes);
2850 if(res != ERROR_SUCCESS)
2851 break;
2854 chunked_stream->chunk_size -= read_bytes;
2855 size -= read_bytes;
2856 ret_read += read_bytes;
2857 if(size && !chunked_stream->chunk_size) {
2858 assert(read_mode != READMODE_NOBLOCK);
2859 res = start_next_chunk(chunked_stream, req);
2860 if(res != ERROR_SUCCESS)
2861 break;
2864 if(read_mode == READMODE_ASYNC)
2865 read_mode = READMODE_NOBLOCK;
2868 TRACE("read %u bytes\n", ret_read);
2869 *read = ret_read;
2870 return res;
2873 static BOOL chunked_drain_content(data_stream_t *stream, http_request_t *req)
2875 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2877 remove_chunked_data(chunked_stream, chunked_stream->buf_size);
2878 return chunked_stream->end_of_data;
2881 static void chunked_destroy(data_stream_t *stream)
2883 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2884 heap_free(chunked_stream);
2887 static const data_stream_vtbl_t chunked_stream_vtbl = {
2888 chunked_get_avail_data,
2889 chunked_end_of_data,
2890 chunked_read,
2891 chunked_drain_content,
2892 chunked_destroy
2895 /* set the request content length based on the headers */
2896 static DWORD set_content_length(http_request_t *request)
2898 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
2899 WCHAR encoding[20];
2900 DWORD size;
2902 if(request->status_code == HTTP_STATUS_NO_CONTENT) {
2903 request->contentLength = request->netconn_stream.content_length = 0;
2904 return ERROR_SUCCESS;
2907 size = sizeof(request->contentLength);
2908 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2909 &request->contentLength, &size, NULL) != ERROR_SUCCESS)
2910 request->contentLength = ~0u;
2911 request->netconn_stream.content_length = request->contentLength;
2912 request->netconn_stream.content_read = request->read_size;
2914 size = sizeof(encoding);
2915 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) == ERROR_SUCCESS &&
2916 !strcmpiW(encoding, szChunked))
2918 chunked_stream_t *chunked_stream;
2920 chunked_stream = heap_alloc(sizeof(*chunked_stream));
2921 if(!chunked_stream)
2922 return ERROR_OUTOFMEMORY;
2924 chunked_stream->data_stream.vtbl = &chunked_stream_vtbl;
2925 chunked_stream->buf_size = chunked_stream->buf_pos = 0;
2926 chunked_stream->chunk_size = ~0u;
2927 chunked_stream->end_of_data = FALSE;
2929 if(request->read_size) {
2930 memcpy(chunked_stream->buf, request->read_buf+request->read_pos, request->read_size);
2931 chunked_stream->buf_size = request->read_size;
2932 request->read_size = request->read_pos = 0;
2935 request->data_stream = &chunked_stream->data_stream;
2936 request->contentLength = ~0u;
2937 request->read_chunked = TRUE;
2940 if(request->decoding) {
2941 int encoding_idx;
2943 static const WCHAR gzipW[] = {'g','z','i','p',0};
2945 encoding_idx = HTTP_GetCustomHeaderIndex(request, szContent_Encoding, 0, FALSE);
2946 if(encoding_idx != -1 && !strcmpiW(request->custHeaders[encoding_idx].lpszValue, gzipW)) {
2947 HTTP_DeleteCustomHeader(request, encoding_idx);
2948 return init_gzip_stream(request);
2952 return ERROR_SUCCESS;
2955 static void send_request_complete(http_request_t *req, DWORD_PTR result, DWORD error)
2957 INTERNET_ASYNC_RESULT iar;
2959 iar.dwResult = result;
2960 iar.dwError = error;
2962 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2963 sizeof(INTERNET_ASYNC_RESULT));
2966 static void HTTP_ReceiveRequestData(http_request_t *req, BOOL first_notif, DWORD *ret_size)
2968 DWORD res, read = 0, avail = 0;
2969 read_mode_t mode;
2971 TRACE("%p\n", req);
2973 EnterCriticalSection( &req->read_section );
2975 mode = first_notif && req->read_size ? READMODE_NOBLOCK : READMODE_ASYNC;
2976 res = refill_read_buffer(req, mode, &read);
2977 if(res == ERROR_SUCCESS)
2978 avail = get_avail_data(req);
2980 LeaveCriticalSection( &req->read_section );
2982 if(res != ERROR_SUCCESS || (mode != READMODE_NOBLOCK && !read)) {
2983 WARN("res %u read %u, closing connection\n", res, read);
2984 http_release_netconn(req, FALSE);
2987 if(res != ERROR_SUCCESS) {
2988 send_request_complete(req, 0, res);
2989 return;
2992 if(ret_size)
2993 *ret_size = avail;
2994 if(first_notif)
2995 avail = 0;
2997 send_request_complete(req, req->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)req->hdr.hInternet : 1, avail);
3000 /* read data from the http connection (the read section must be held) */
3001 static DWORD HTTPREQ_Read(http_request_t *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
3003 DWORD current_read = 0, ret_read = 0;
3004 read_mode_t read_mode;
3005 DWORD res = ERROR_SUCCESS;
3007 read_mode = req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC ? READMODE_ASYNC : READMODE_SYNC;
3009 EnterCriticalSection( &req->read_section );
3011 if(req->read_size) {
3012 ret_read = min(size, req->read_size);
3013 memcpy(buffer, req->read_buf+req->read_pos, ret_read);
3014 req->read_size -= ret_read;
3015 req->read_pos += ret_read;
3016 if(read_mode == READMODE_ASYNC)
3017 read_mode = READMODE_NOBLOCK;
3020 if(ret_read < size) {
3021 res = read_http_stream(req, (BYTE*)buffer+ret_read, size-ret_read, &current_read, read_mode);
3022 ret_read += current_read;
3025 LeaveCriticalSection( &req->read_section );
3027 *read = ret_read;
3028 TRACE( "retrieved %u bytes (%u)\n", ret_read, req->contentLength );
3030 if(size && !ret_read)
3031 http_release_netconn(req, res == ERROR_SUCCESS);
3033 return res;
3036 static BOOL drain_content(http_request_t *req, BOOL blocking)
3038 BOOL ret;
3040 if(!req->netconn || req->contentLength == -1)
3041 return FALSE;
3043 if(!strcmpW(req->verb, szHEAD))
3044 return TRUE;
3046 if(!blocking)
3047 return req->data_stream->vtbl->drain_content(req->data_stream, req);
3049 EnterCriticalSection( &req->read_section );
3051 while(1) {
3052 DWORD bytes_read, res;
3053 BYTE buf[4096];
3055 res = HTTPREQ_Read(req, buf, sizeof(buf), &bytes_read, TRUE);
3056 if(res != ERROR_SUCCESS) {
3057 ret = FALSE;
3058 break;
3060 if(!bytes_read) {
3061 ret = TRUE;
3062 break;
3066 LeaveCriticalSection( &req->read_section );
3067 return ret;
3070 static DWORD HTTPREQ_ReadFile(object_header_t *hdr, void *buffer, DWORD size, DWORD *read)
3072 http_request_t *req = (http_request_t*)hdr;
3073 DWORD res;
3075 EnterCriticalSection( &req->read_section );
3076 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3077 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3079 res = HTTPREQ_Read(req, buffer, size, read, TRUE);
3080 if(res == ERROR_SUCCESS)
3081 res = hdr->dwError;
3082 LeaveCriticalSection( &req->read_section );
3084 return res;
3087 typedef struct {
3088 task_header_t hdr;
3089 void *buf;
3090 DWORD size;
3091 DWORD *ret_read;
3092 } read_file_ex_task_t;
3094 static void AsyncReadFileExProc(task_header_t *hdr)
3096 read_file_ex_task_t *task = (read_file_ex_task_t*)hdr;
3097 http_request_t *req = (http_request_t*)task->hdr.hdr;
3098 DWORD res;
3100 TRACE("INTERNETREADFILEEXW %p\n", task->hdr.hdr);
3102 res = HTTPREQ_Read(req, task->buf, task->size, task->ret_read, TRUE);
3103 send_request_complete(req, res == ERROR_SUCCESS, res);
3106 static DWORD HTTPREQ_ReadFileEx(object_header_t *hdr, void *buf, DWORD size, DWORD *ret_read,
3107 DWORD flags, DWORD_PTR context)
3110 http_request_t *req = (http_request_t*)hdr;
3111 DWORD res, read, cread, error = ERROR_SUCCESS;
3113 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3114 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3116 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3118 if (hdr->dwFlags & INTERNET_FLAG_ASYNC)
3120 read_file_ex_task_t *task;
3122 if (TryEnterCriticalSection( &req->read_section ))
3124 if (get_avail_data(req))
3126 res = HTTPREQ_Read(req, buf, size, &read, FALSE);
3127 LeaveCriticalSection( &req->read_section );
3128 goto done;
3130 LeaveCriticalSection( &req->read_section );
3133 task = alloc_async_task(&req->hdr, AsyncReadFileExProc, sizeof(*task));
3134 task->buf = buf;
3135 task->size = size;
3136 task->ret_read = ret_read;
3138 INTERNET_AsyncCall(&task->hdr);
3140 return ERROR_IO_PENDING;
3143 read = 0;
3145 EnterCriticalSection( &req->read_section );
3146 if(hdr->dwError == ERROR_SUCCESS)
3147 hdr->dwError = INTERNET_HANDLE_IN_USE;
3148 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3149 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3151 while(1) {
3152 res = HTTPREQ_Read(req, (char*)buf+read, size-read, &cread, !(flags & IRF_NO_WAIT));
3153 if(res != ERROR_SUCCESS)
3154 break;
3156 read += cread;
3157 if(read == size || end_of_read_data(req))
3158 break;
3160 LeaveCriticalSection( &req->read_section );
3162 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3163 &cread, sizeof(cread));
3164 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
3165 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3167 EnterCriticalSection( &req->read_section );
3170 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3171 hdr->dwError = ERROR_SUCCESS;
3172 else
3173 error = hdr->dwError;
3175 LeaveCriticalSection( &req->read_section );
3177 done:
3178 *ret_read = read;
3179 if (res == ERROR_SUCCESS) {
3180 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3181 &read, sizeof(read));
3184 return res==ERROR_SUCCESS ? error : res;
3187 static DWORD HTTPREQ_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
3189 DWORD res;
3190 http_request_t *request = (http_request_t*)hdr;
3192 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3194 *written = 0;
3195 res = NETCON_send(request->netconn, buffer, size, 0, (LPINT)written);
3196 if (res == ERROR_SUCCESS)
3197 request->bytesWritten += *written;
3199 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
3200 return res;
3203 typedef struct {
3204 task_header_t hdr;
3205 DWORD *ret_size;
3206 } http_data_available_task_t;
3208 static void AsyncQueryDataAvailableProc(task_header_t *hdr)
3210 http_data_available_task_t *task = (http_data_available_task_t*)hdr;
3212 HTTP_ReceiveRequestData((http_request_t*)task->hdr.hdr, FALSE, task->ret_size);
3215 static DWORD HTTPREQ_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
3217 http_request_t *req = (http_request_t*)hdr;
3219 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
3221 if (req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3223 http_data_available_task_t *task;
3225 /* never wait, if we can't enter the section we queue an async request right away */
3226 if (TryEnterCriticalSection( &req->read_section ))
3228 refill_read_buffer(req, READMODE_NOBLOCK, NULL);
3229 if ((*available = get_avail_data( req ))) goto done;
3230 if (end_of_read_data( req )) goto done;
3231 LeaveCriticalSection( &req->read_section );
3234 task = alloc_async_task(&req->hdr, AsyncQueryDataAvailableProc, sizeof(*task));
3235 task->ret_size = available;
3236 INTERNET_AsyncCall(&task->hdr);
3237 return ERROR_IO_PENDING;
3240 EnterCriticalSection( &req->read_section );
3242 if (!(*available = get_avail_data( req )) && !end_of_read_data( req ))
3244 refill_read_buffer( req, READMODE_ASYNC, NULL );
3245 *available = get_avail_data( req );
3248 done:
3249 LeaveCriticalSection( &req->read_section );
3251 TRACE( "returning %u\n", *available );
3252 return ERROR_SUCCESS;
3255 static DWORD HTTPREQ_LockRequestFile(object_header_t *hdr, req_file_t **ret)
3257 http_request_t *req = (http_request_t*)hdr;
3259 TRACE("(%p)\n", req);
3261 if(!req->req_file) {
3262 WARN("No cache file name available\n");
3263 return ERROR_FILE_NOT_FOUND;
3266 *ret = req_file_addref(req->req_file);
3267 return ERROR_SUCCESS;
3270 static const object_vtbl_t HTTPREQVtbl = {
3271 HTTPREQ_Destroy,
3272 HTTPREQ_CloseConnection,
3273 HTTPREQ_QueryOption,
3274 HTTPREQ_SetOption,
3275 HTTPREQ_ReadFile,
3276 HTTPREQ_ReadFileEx,
3277 HTTPREQ_WriteFile,
3278 HTTPREQ_QueryDataAvailable,
3279 NULL,
3280 HTTPREQ_LockRequestFile
3283 /***********************************************************************
3284 * HTTP_HttpOpenRequestW (internal)
3286 * Open a HTTP request handle
3288 * RETURNS
3289 * HINTERNET a HTTP request handle on success
3290 * NULL on failure
3293 static DWORD HTTP_HttpOpenRequestW(http_session_t *session,
3294 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3295 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3296 DWORD dwFlags, DWORD_PTR dwContext, HINTERNET *ret)
3298 appinfo_t *hIC = session->appInfo;
3299 http_request_t *request;
3300 DWORD len, res = ERROR_SUCCESS;
3302 TRACE("-->\n");
3304 request = alloc_object(&session->hdr, &HTTPREQVtbl, sizeof(http_request_t));
3305 if(!request)
3306 return ERROR_OUTOFMEMORY;
3308 request->hdr.htype = WH_HHTTPREQ;
3309 request->hdr.dwFlags = dwFlags;
3310 request->hdr.dwContext = dwContext;
3311 request->contentLength = ~0u;
3313 request->netconn_stream.data_stream.vtbl = &netconn_stream_vtbl;
3314 request->data_stream = &request->netconn_stream.data_stream;
3315 request->connect_timeout = session->connect_timeout;
3316 request->send_timeout = session->send_timeout;
3317 request->receive_timeout = session->receive_timeout;
3319 InitializeCriticalSection( &request->read_section );
3320 request->read_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.read_section");
3322 WININET_AddRef( &session->hdr );
3323 request->session = session;
3324 list_add_head( &session->hdr.children, &request->hdr.entry );
3326 request->server = get_server(session->hostName, session->hostPort, (dwFlags & INTERNET_FLAG_SECURE) != 0, TRUE);
3327 if(!request->server) {
3328 WININET_Release(&request->hdr);
3329 return ERROR_OUTOFMEMORY;
3332 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_CN_INVALID)
3333 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
3334 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_DATE_INVALID)
3335 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
3337 if (lpszObjectName && *lpszObjectName) {
3338 HRESULT rc;
3340 len = 0;
3341 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
3342 if (rc != E_POINTER)
3343 len = strlenW(lpszObjectName)+1;
3344 request->path = heap_alloc(len*sizeof(WCHAR));
3345 rc = UrlEscapeW(lpszObjectName, request->path, &len,
3346 URL_ESCAPE_SPACES_ONLY);
3347 if (rc != S_OK)
3349 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
3350 strcpyW(request->path,lpszObjectName);
3352 }else {
3353 static const WCHAR slashW[] = {'/',0};
3355 request->path = heap_strdupW(slashW);
3358 if (lpszReferrer && *lpszReferrer)
3359 HTTP_ProcessHeader(request, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3361 if (lpszAcceptTypes)
3363 int i;
3364 for (i = 0; lpszAcceptTypes[i]; i++)
3366 if (!*lpszAcceptTypes[i]) continue;
3367 HTTP_ProcessHeader(request, HTTP_ACCEPT, lpszAcceptTypes[i],
3368 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
3369 HTTP_ADDHDR_FLAG_REQ |
3370 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
3374 request->verb = heap_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
3375 request->version = heap_strdupW(lpszVersion && *lpszVersion ? lpszVersion : g_szHttp1_1);
3377 HTTP_ProcessHeader(request, hostW, request->server->canon_host_port, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3379 if (session->hostPort == INTERNET_INVALID_PORT_NUMBER)
3380 session->hostPort = INTERNET_DEFAULT_HTTP_PORT;
3382 if (hIC->proxy && hIC->proxy[0] && !HTTP_ShouldBypassProxy(hIC, session->hostName))
3383 HTTP_DealWithProxy( hIC, session, request );
3385 INTERNET_SendCallback(&session->hdr, dwContext,
3386 INTERNET_STATUS_HANDLE_CREATED, &request->hdr.hInternet,
3387 sizeof(HINTERNET));
3389 TRACE("<-- %u (%p)\n", res, request);
3391 if(res != ERROR_SUCCESS) {
3392 WININET_Release( &request->hdr );
3393 *ret = NULL;
3394 return res;
3397 *ret = request->hdr.hInternet;
3398 return ERROR_SUCCESS;
3401 /***********************************************************************
3402 * HttpOpenRequestW (WININET.@)
3404 * Open a HTTP request handle
3406 * RETURNS
3407 * HINTERNET a HTTP request handle on success
3408 * NULL on failure
3411 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
3412 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3413 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3414 DWORD dwFlags, DWORD_PTR dwContext)
3416 http_session_t *session;
3417 HINTERNET handle = NULL;
3418 DWORD res;
3420 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
3421 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
3422 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
3423 dwFlags, dwContext);
3424 if(lpszAcceptTypes!=NULL)
3426 int i;
3427 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
3428 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
3431 session = (http_session_t*) get_handle_object( hHttpSession );
3432 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
3434 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3435 goto lend;
3439 * My tests seem to show that the windows version does not
3440 * become asynchronous until after this point. And anyhow
3441 * if this call was asynchronous then how would you get the
3442 * necessary HINTERNET pointer returned by this function.
3445 res = HTTP_HttpOpenRequestW(session, lpszVerb, lpszObjectName,
3446 lpszVersion, lpszReferrer, lpszAcceptTypes,
3447 dwFlags, dwContext, &handle);
3448 lend:
3449 if( session )
3450 WININET_Release( &session->hdr );
3451 TRACE("returning %p\n", handle);
3452 if(res != ERROR_SUCCESS)
3453 SetLastError(res);
3454 return handle;
3457 static const LPCWSTR header_lookup[] = {
3458 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
3459 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3460 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3461 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
3462 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3463 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3464 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3465 szAllow, /* HTTP_QUERY_ALLOW = 7 */
3466 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
3467 szDate, /* HTTP_QUERY_DATE = 9 */
3468 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
3469 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3470 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
3471 szURI, /* HTTP_QUERY_URI = 13 */
3472 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
3473 NULL, /* HTTP_QUERY_COST = 15 */
3474 NULL, /* HTTP_QUERY_LINK = 16 */
3475 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
3476 NULL, /* HTTP_QUERY_VERSION = 18 */
3477 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
3478 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
3479 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
3480 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3481 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
3482 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
3483 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3484 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3485 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3486 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
3487 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3488 NULL, /* HTTP_QUERY_FORWARDED = 30 */
3489 NULL, /* HTTP_QUERY_FROM = 31 */
3490 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3491 szLocation, /* HTTP_QUERY_LOCATION = 33 */
3492 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
3493 szReferer, /* HTTP_QUERY_REFERER = 35 */
3494 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
3495 szServer, /* HTTP_QUERY_SERVER = 37 */
3496 NULL, /* HTTP_TITLE = 38 */
3497 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
3498 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3499 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3500 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3501 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
3502 szCookie, /* HTTP_QUERY_COOKIE = 44 */
3503 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3504 NULL, /* HTTP_QUERY_REFRESH = 46 */
3505 szContent_Disposition, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3506 szAge, /* HTTP_QUERY_AGE = 48 */
3507 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3508 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
3509 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3510 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3511 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3512 szETag, /* HTTP_QUERY_ETAG = 54 */
3513 hostW, /* HTTP_QUERY_HOST = 55 */
3514 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
3515 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3516 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
3517 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3518 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3519 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3520 szRange, /* HTTP_QUERY_RANGE = 62 */
3521 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3522 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
3523 szVary, /* HTTP_QUERY_VARY = 65 */
3524 szVia, /* HTTP_QUERY_VIA = 66 */
3525 szWarning, /* HTTP_QUERY_WARNING = 67 */
3526 szExpect, /* HTTP_QUERY_EXPECT = 68 */
3527 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3528 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3531 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3533 /***********************************************************************
3534 * HTTP_HttpQueryInfoW (internal)
3536 static DWORD HTTP_HttpQueryInfoW(http_request_t *request, DWORD dwInfoLevel,
3537 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3539 LPHTTPHEADERW lphttpHdr = NULL;
3540 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
3541 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
3542 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
3543 INT index = -1;
3545 /* Find requested header structure */
3546 switch (level)
3548 case HTTP_QUERY_CUSTOM:
3549 if (!lpBuffer) return ERROR_INVALID_PARAMETER;
3550 index = HTTP_GetCustomHeaderIndex(request, lpBuffer, requested_index, request_only);
3551 break;
3552 case HTTP_QUERY_RAW_HEADERS_CRLF:
3554 LPWSTR headers;
3555 DWORD len = 0;
3556 DWORD res = ERROR_INVALID_PARAMETER;
3558 if (request_only)
3559 headers = build_request_header(request, request->verb, request->path, request->version, TRUE);
3560 else
3561 headers = build_response_header(request, TRUE);
3562 if (!headers)
3563 return ERROR_OUTOFMEMORY;
3565 len = strlenW(headers) * sizeof(WCHAR);
3566 if (len + sizeof(WCHAR) > *lpdwBufferLength)
3568 len += sizeof(WCHAR);
3569 res = ERROR_INSUFFICIENT_BUFFER;
3571 else if (lpBuffer)
3573 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3574 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
3575 res = ERROR_SUCCESS;
3577 *lpdwBufferLength = len;
3579 heap_free(headers);
3580 return res;
3582 case HTTP_QUERY_RAW_HEADERS:
3584 LPWSTR headers;
3585 DWORD len;
3587 if (request_only)
3588 headers = build_request_header(request, request->verb, request->path, request->version, FALSE);
3589 else
3590 headers = build_response_header(request, FALSE);
3591 if (!headers)
3592 return ERROR_OUTOFMEMORY;
3594 len = strlenW(headers) * sizeof(WCHAR);
3595 if (len > *lpdwBufferLength)
3597 *lpdwBufferLength = len;
3598 heap_free(headers);
3599 return ERROR_INSUFFICIENT_BUFFER;
3602 if (lpBuffer)
3604 DWORD i;
3606 TRACE("returning data: %s\n", debugstr_wn(headers, len / sizeof(WCHAR)));
3608 for (i=0; i<len; i++)
3610 if (headers[i] == '\n')
3611 headers[i] = 0;
3613 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3615 *lpdwBufferLength = len - sizeof(WCHAR);
3617 heap_free(headers);
3618 return ERROR_SUCCESS;
3620 case HTTP_QUERY_STATUS_TEXT:
3621 if (request->statusText)
3623 DWORD len = strlenW(request->statusText);
3624 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3626 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3627 return ERROR_INSUFFICIENT_BUFFER;
3629 if (lpBuffer)
3631 memcpy(lpBuffer, request->statusText, (len + 1) * sizeof(WCHAR));
3632 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3634 *lpdwBufferLength = len * sizeof(WCHAR);
3635 return ERROR_SUCCESS;
3637 break;
3638 case HTTP_QUERY_VERSION:
3639 if (request->version)
3641 DWORD len = strlenW(request->version);
3642 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3644 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3645 return ERROR_INSUFFICIENT_BUFFER;
3647 if (lpBuffer)
3649 memcpy(lpBuffer, request->version, (len + 1) * sizeof(WCHAR));
3650 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3652 *lpdwBufferLength = len * sizeof(WCHAR);
3653 return ERROR_SUCCESS;
3655 break;
3656 case HTTP_QUERY_CONTENT_ENCODING:
3657 index = HTTP_GetCustomHeaderIndex(request, header_lookup[request->read_gzip ? HTTP_QUERY_CONTENT_TYPE : level],
3658 requested_index,request_only);
3659 break;
3660 case HTTP_QUERY_STATUS_CODE: {
3661 DWORD res = ERROR_SUCCESS;
3663 if(request_only)
3664 return ERROR_HTTP_INVALID_QUERY_REQUEST;
3666 if(requested_index)
3667 break;
3669 if(dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) {
3670 if(*lpdwBufferLength >= sizeof(DWORD))
3671 *(DWORD*)lpBuffer = request->status_code;
3672 else
3673 res = ERROR_INSUFFICIENT_BUFFER;
3674 *lpdwBufferLength = sizeof(DWORD);
3675 }else {
3676 WCHAR buf[12];
3677 DWORD size;
3678 static const WCHAR formatW[] = {'%','u',0};
3680 size = sprintfW(buf, formatW, request->status_code) * sizeof(WCHAR);
3682 if(size <= *lpdwBufferLength) {
3683 memcpy(lpBuffer, buf, size+sizeof(WCHAR));
3684 }else {
3685 size += sizeof(WCHAR);
3686 res = ERROR_INSUFFICIENT_BUFFER;
3689 *lpdwBufferLength = size;
3691 return res;
3693 default:
3694 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
3696 if (level < LAST_TABLE_HEADER && header_lookup[level])
3697 index = HTTP_GetCustomHeaderIndex(request, header_lookup[level],
3698 requested_index,request_only);
3701 if (index >= 0)
3702 lphttpHdr = &request->custHeaders[index];
3704 /* Ensure header satisfies requested attributes */
3705 if (!lphttpHdr ||
3706 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
3707 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
3709 return ERROR_HTTP_HEADER_NOT_FOUND;
3712 if (lpdwIndex) (*lpdwIndex)++;
3714 /* coalesce value to requested type */
3715 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
3717 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
3718 TRACE(" returning number: %d\n", *(int *)lpBuffer);
3720 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
3722 time_t tmpTime;
3723 struct tm tmpTM;
3724 SYSTEMTIME *STHook;
3726 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
3728 tmpTM = *gmtime(&tmpTime);
3729 STHook = (SYSTEMTIME *)lpBuffer;
3730 STHook->wDay = tmpTM.tm_mday;
3731 STHook->wHour = tmpTM.tm_hour;
3732 STHook->wMilliseconds = 0;
3733 STHook->wMinute = tmpTM.tm_min;
3734 STHook->wDayOfWeek = tmpTM.tm_wday;
3735 STHook->wMonth = tmpTM.tm_mon + 1;
3736 STHook->wSecond = tmpTM.tm_sec;
3737 STHook->wYear = 1900+tmpTM.tm_year;
3739 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3740 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
3741 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
3743 else if (lphttpHdr->lpszValue)
3745 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
3747 if (len > *lpdwBufferLength)
3749 *lpdwBufferLength = len;
3750 return ERROR_INSUFFICIENT_BUFFER;
3752 if (lpBuffer)
3754 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
3755 TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
3757 *lpdwBufferLength = len - sizeof(WCHAR);
3759 return ERROR_SUCCESS;
3762 /***********************************************************************
3763 * HttpQueryInfoW (WININET.@)
3765 * Queries for information about an HTTP request
3767 * RETURNS
3768 * TRUE on success
3769 * FALSE on failure
3772 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3773 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3775 http_request_t *request;
3776 DWORD res;
3778 if (TRACE_ON(wininet)) {
3779 #define FE(x) { x, #x }
3780 static const wininet_flag_info query_flags[] = {
3781 FE(HTTP_QUERY_MIME_VERSION),
3782 FE(HTTP_QUERY_CONTENT_TYPE),
3783 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
3784 FE(HTTP_QUERY_CONTENT_ID),
3785 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
3786 FE(HTTP_QUERY_CONTENT_LENGTH),
3787 FE(HTTP_QUERY_CONTENT_LANGUAGE),
3788 FE(HTTP_QUERY_ALLOW),
3789 FE(HTTP_QUERY_PUBLIC),
3790 FE(HTTP_QUERY_DATE),
3791 FE(HTTP_QUERY_EXPIRES),
3792 FE(HTTP_QUERY_LAST_MODIFIED),
3793 FE(HTTP_QUERY_MESSAGE_ID),
3794 FE(HTTP_QUERY_URI),
3795 FE(HTTP_QUERY_DERIVED_FROM),
3796 FE(HTTP_QUERY_COST),
3797 FE(HTTP_QUERY_LINK),
3798 FE(HTTP_QUERY_PRAGMA),
3799 FE(HTTP_QUERY_VERSION),
3800 FE(HTTP_QUERY_STATUS_CODE),
3801 FE(HTTP_QUERY_STATUS_TEXT),
3802 FE(HTTP_QUERY_RAW_HEADERS),
3803 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
3804 FE(HTTP_QUERY_CONNECTION),
3805 FE(HTTP_QUERY_ACCEPT),
3806 FE(HTTP_QUERY_ACCEPT_CHARSET),
3807 FE(HTTP_QUERY_ACCEPT_ENCODING),
3808 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
3809 FE(HTTP_QUERY_AUTHORIZATION),
3810 FE(HTTP_QUERY_CONTENT_ENCODING),
3811 FE(HTTP_QUERY_FORWARDED),
3812 FE(HTTP_QUERY_FROM),
3813 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
3814 FE(HTTP_QUERY_LOCATION),
3815 FE(HTTP_QUERY_ORIG_URI),
3816 FE(HTTP_QUERY_REFERER),
3817 FE(HTTP_QUERY_RETRY_AFTER),
3818 FE(HTTP_QUERY_SERVER),
3819 FE(HTTP_QUERY_TITLE),
3820 FE(HTTP_QUERY_USER_AGENT),
3821 FE(HTTP_QUERY_WWW_AUTHENTICATE),
3822 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
3823 FE(HTTP_QUERY_ACCEPT_RANGES),
3824 FE(HTTP_QUERY_SET_COOKIE),
3825 FE(HTTP_QUERY_COOKIE),
3826 FE(HTTP_QUERY_REQUEST_METHOD),
3827 FE(HTTP_QUERY_REFRESH),
3828 FE(HTTP_QUERY_CONTENT_DISPOSITION),
3829 FE(HTTP_QUERY_AGE),
3830 FE(HTTP_QUERY_CACHE_CONTROL),
3831 FE(HTTP_QUERY_CONTENT_BASE),
3832 FE(HTTP_QUERY_CONTENT_LOCATION),
3833 FE(HTTP_QUERY_CONTENT_MD5),
3834 FE(HTTP_QUERY_CONTENT_RANGE),
3835 FE(HTTP_QUERY_ETAG),
3836 FE(HTTP_QUERY_HOST),
3837 FE(HTTP_QUERY_IF_MATCH),
3838 FE(HTTP_QUERY_IF_NONE_MATCH),
3839 FE(HTTP_QUERY_IF_RANGE),
3840 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
3841 FE(HTTP_QUERY_MAX_FORWARDS),
3842 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
3843 FE(HTTP_QUERY_RANGE),
3844 FE(HTTP_QUERY_TRANSFER_ENCODING),
3845 FE(HTTP_QUERY_UPGRADE),
3846 FE(HTTP_QUERY_VARY),
3847 FE(HTTP_QUERY_VIA),
3848 FE(HTTP_QUERY_WARNING),
3849 FE(HTTP_QUERY_CUSTOM)
3851 static const wininet_flag_info modifier_flags[] = {
3852 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
3853 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
3854 FE(HTTP_QUERY_FLAG_NUMBER),
3855 FE(HTTP_QUERY_FLAG_COALESCE)
3857 #undef FE
3858 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
3859 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
3860 DWORD i;
3862 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, info);
3863 TRACE(" Attribute:");
3864 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
3865 if (query_flags[i].val == info) {
3866 TRACE(" %s", query_flags[i].name);
3867 break;
3870 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
3871 TRACE(" Unknown (%08x)", info);
3874 TRACE(" Modifier:");
3875 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
3876 if (modifier_flags[i].val & info_mod) {
3877 TRACE(" %s", modifier_flags[i].name);
3878 info_mod &= ~ modifier_flags[i].val;
3882 if (info_mod) {
3883 TRACE(" Unknown (%08x)", info_mod);
3885 TRACE("\n");
3888 request = (http_request_t*) get_handle_object( hHttpRequest );
3889 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
3891 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3892 goto lend;
3895 if (lpBuffer == NULL)
3896 *lpdwBufferLength = 0;
3897 res = HTTP_HttpQueryInfoW( request, dwInfoLevel,
3898 lpBuffer, lpdwBufferLength, lpdwIndex);
3900 lend:
3901 if( request )
3902 WININET_Release( &request->hdr );
3904 TRACE("%u <--\n", res);
3905 if(res != ERROR_SUCCESS)
3906 SetLastError(res);
3907 return res == ERROR_SUCCESS;
3910 /***********************************************************************
3911 * HttpQueryInfoA (WININET.@)
3913 * Queries for information about an HTTP request
3915 * RETURNS
3916 * TRUE on success
3917 * FALSE on failure
3920 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3921 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3923 BOOL result;
3924 DWORD len;
3925 WCHAR* bufferW;
3927 TRACE("%p %x\n", hHttpRequest, dwInfoLevel);
3929 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
3930 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
3932 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
3933 lpdwBufferLength, lpdwIndex );
3936 if (lpBuffer)
3938 DWORD alloclen;
3939 len = (*lpdwBufferLength)*sizeof(WCHAR);
3940 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3942 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
3943 if (alloclen < len)
3944 alloclen = len;
3946 else
3947 alloclen = len;
3948 bufferW = heap_alloc(alloclen);
3949 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3950 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3951 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
3952 } else
3954 bufferW = NULL;
3955 len = 0;
3958 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
3959 &len, lpdwIndex );
3960 if( result )
3962 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
3963 lpBuffer, *lpdwBufferLength, NULL, NULL );
3964 *lpdwBufferLength = len - 1;
3966 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
3968 else
3969 /* since the strings being returned from HttpQueryInfoW should be
3970 * only ASCII characters, it is reasonable to assume that all of
3971 * the Unicode characters can be reduced to a single byte */
3972 *lpdwBufferLength = len / sizeof(WCHAR);
3974 heap_free( bufferW );
3975 return result;
3978 /***********************************************************************
3979 * HTTP_GetRedirectURL (internal)
3981 static LPWSTR HTTP_GetRedirectURL(http_request_t *request, LPCWSTR lpszUrl)
3983 static WCHAR szHttp[] = {'h','t','t','p',0};
3984 static WCHAR szHttps[] = {'h','t','t','p','s',0};
3985 http_session_t *session = request->session;
3986 URL_COMPONENTSW urlComponents;
3987 DWORD url_length = 0;
3988 LPWSTR orig_url;
3989 LPWSTR combined_url;
3991 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3992 urlComponents.lpszScheme = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
3993 urlComponents.dwSchemeLength = 0;
3994 urlComponents.lpszHostName = session->hostName;
3995 urlComponents.dwHostNameLength = 0;
3996 urlComponents.nPort = session->hostPort;
3997 urlComponents.lpszUserName = session->userName;
3998 urlComponents.dwUserNameLength = 0;
3999 urlComponents.lpszPassword = NULL;
4000 urlComponents.dwPasswordLength = 0;
4001 urlComponents.lpszUrlPath = request->path;
4002 urlComponents.dwUrlPathLength = 0;
4003 urlComponents.lpszExtraInfo = NULL;
4004 urlComponents.dwExtraInfoLength = 0;
4006 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
4007 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
4008 return NULL;
4010 orig_url = heap_alloc(url_length);
4012 /* convert from bytes to characters */
4013 url_length = url_length / sizeof(WCHAR) - 1;
4014 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
4016 heap_free(orig_url);
4017 return NULL;
4020 url_length = 0;
4021 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
4022 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
4024 heap_free(orig_url);
4025 return NULL;
4027 combined_url = heap_alloc(url_length * sizeof(WCHAR));
4029 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
4031 heap_free(orig_url);
4032 heap_free(combined_url);
4033 return NULL;
4035 heap_free(orig_url);
4036 return combined_url;
4040 /***********************************************************************
4041 * HTTP_HandleRedirect (internal)
4043 static DWORD HTTP_HandleRedirect(http_request_t *request, LPCWSTR lpszUrl)
4045 http_session_t *session = request->session;
4046 WCHAR path[INTERNET_MAX_PATH_LENGTH];
4047 int index;
4049 if(lpszUrl[0]=='/')
4051 /* if it's an absolute path, keep the same session info */
4052 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
4054 else
4056 URL_COMPONENTSW urlComponents;
4057 WCHAR protocol[INTERNET_MAX_SCHEME_LENGTH];
4058 WCHAR hostName[INTERNET_MAX_HOST_NAME_LENGTH];
4059 WCHAR userName[INTERNET_MAX_USER_NAME_LENGTH];
4060 BOOL custom_port = FALSE;
4062 static WCHAR httpW[] = {'h','t','t','p',0};
4063 static WCHAR httpsW[] = {'h','t','t','p','s',0};
4065 userName[0] = 0;
4066 hostName[0] = 0;
4067 protocol[0] = 0;
4069 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
4070 urlComponents.lpszScheme = protocol;
4071 urlComponents.dwSchemeLength = INTERNET_MAX_SCHEME_LENGTH;
4072 urlComponents.lpszHostName = hostName;
4073 urlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
4074 urlComponents.lpszUserName = userName;
4075 urlComponents.dwUserNameLength = INTERNET_MAX_USER_NAME_LENGTH;
4076 urlComponents.lpszPassword = NULL;
4077 urlComponents.dwPasswordLength = 0;
4078 urlComponents.lpszUrlPath = path;
4079 urlComponents.dwUrlPathLength = INTERNET_MAX_PATH_LENGTH;
4080 urlComponents.lpszExtraInfo = NULL;
4081 urlComponents.dwExtraInfoLength = 0;
4082 if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
4083 return INTERNET_GetLastError();
4085 if(!strcmpiW(protocol, httpW)) {
4086 if(request->hdr.dwFlags & INTERNET_FLAG_SECURE) {
4087 TRACE("redirect from secure page to non-secure page\n");
4088 /* FIXME: warn about from secure redirect to non-secure page */
4089 request->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
4092 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4093 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
4094 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT)
4095 custom_port = TRUE;
4096 }else if(!strcmpiW(protocol, httpsW)) {
4097 if(!(request->hdr.dwFlags & INTERNET_FLAG_SECURE)) {
4098 TRACE("redirect from non-secure page to secure page\n");
4099 /* FIXME: notify about redirect to secure page */
4100 request->hdr.dwFlags |= INTERNET_FLAG_SECURE;
4103 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4104 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
4105 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
4106 custom_port = TRUE;
4109 heap_free(session->hostName);
4111 if(custom_port) {
4112 int len;
4113 static const WCHAR fmt[] = {'%','s',':','%','u',0};
4114 len = lstrlenW(hostName);
4115 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
4116 session->hostName = heap_alloc(len*sizeof(WCHAR));
4117 sprintfW(session->hostName, fmt, hostName, urlComponents.nPort);
4119 else
4120 session->hostName = heap_strdupW(hostName);
4122 HTTP_ProcessHeader(request, hostW, session->hostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4124 heap_free(session->userName);
4125 session->userName = NULL;
4126 if (userName[0])
4127 session->userName = heap_strdupW(userName);
4129 reset_data_stream(request);
4131 if(strcmpiW(request->server->name, hostName) || request->server->port != urlComponents.nPort) {
4132 server_t *new_server;
4134 new_server = get_server(hostName, urlComponents.nPort, urlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
4135 server_release(request->server);
4136 request->server = new_server;
4139 heap_free(request->path);
4140 request->path=NULL;
4141 if (*path)
4143 DWORD needed = 0;
4144 HRESULT rc;
4146 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
4147 if (rc != E_POINTER)
4148 needed = strlenW(path)+1;
4149 request->path = heap_alloc(needed*sizeof(WCHAR));
4150 rc = UrlEscapeW(path, request->path, &needed,
4151 URL_ESCAPE_SPACES_ONLY);
4152 if (rc != S_OK)
4154 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4155 strcpyW(request->path,path);
4159 /* Remove custom content-type/length headers on redirects. */
4160 index = HTTP_GetCustomHeaderIndex(request, szContent_Type, 0, TRUE);
4161 if (0 <= index)
4162 HTTP_DeleteCustomHeader(request, index);
4163 index = HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE);
4164 if (0 <= index)
4165 HTTP_DeleteCustomHeader(request, index);
4167 return ERROR_SUCCESS;
4170 /***********************************************************************
4171 * HTTP_build_req (internal)
4173 * concatenate all the strings in the request together
4175 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
4177 LPCWSTR *t;
4178 LPWSTR str;
4180 for( t = list; *t ; t++ )
4181 len += strlenW( *t );
4182 len++;
4184 str = heap_alloc(len*sizeof(WCHAR));
4185 *str = 0;
4187 for( t = list; *t ; t++ )
4188 strcatW( str, *t );
4190 return str;
4193 static DWORD HTTP_SecureProxyConnect(http_request_t *request)
4195 server_t *server = request->server;
4196 LPWSTR requestString;
4197 INT len;
4198 INT cnt;
4199 INT responseLen;
4200 char *ascii_req;
4201 DWORD res;
4203 static const WCHAR connectW[] = {'C','O','N','N','E','C','T',0};
4205 TRACE("\n");
4207 requestString = build_request_header( request, connectW, server->host_port, g_szHttp1_1, TRUE );
4209 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
4210 NULL, 0, NULL, NULL );
4211 len--; /* the nul terminator isn't needed */
4212 ascii_req = heap_alloc(len);
4213 WideCharToMultiByte( CP_ACP, 0, requestString, -1, ascii_req, len, NULL, NULL );
4214 heap_free( requestString );
4216 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
4218 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
4219 res = NETCON_send( request->netconn, ascii_req, len, 0, &cnt );
4220 heap_free( ascii_req );
4221 if (res != ERROR_SUCCESS)
4222 return res;
4224 if (HTTP_GetResponseHeaders( request, &responseLen ) || !responseLen)
4225 return ERROR_HTTP_INVALID_HEADER;
4227 return ERROR_SUCCESS;
4230 static void HTTP_InsertCookies(http_request_t *request)
4232 DWORD cookie_size, size, cnt = 0;
4233 HTTPHEADERW *host;
4234 WCHAR *cookies;
4236 static const WCHAR cookieW[] = {'C','o','o','k','i','e',':',' ',0};
4238 host = HTTP_GetHeader(request, hostW);
4239 if(!host)
4240 return;
4242 if(get_cookie(host->lpszValue, request->path, NULL, &cookie_size) != ERROR_SUCCESS)
4243 return;
4245 size = sizeof(cookieW) + cookie_size * sizeof(WCHAR) + sizeof(szCrLf);
4246 if(!(cookies = heap_alloc(size)))
4247 return;
4249 cnt += sprintfW(cookies, cookieW);
4250 get_cookie(host->lpszValue, request->path, cookies+cnt, &cookie_size);
4251 strcatW(cookies, szCrLf);
4253 HTTP_HttpAddRequestHeadersW(request, cookies, strlenW(cookies), HTTP_ADDREQ_FLAG_REPLACE);
4255 heap_free(cookies);
4258 static WORD HTTP_ParseWkday(LPCWSTR day)
4260 static const WCHAR days[7][4] = {{ 's','u','n',0 },
4261 { 'm','o','n',0 },
4262 { 't','u','e',0 },
4263 { 'w','e','d',0 },
4264 { 't','h','u',0 },
4265 { 'f','r','i',0 },
4266 { 's','a','t',0 }};
4267 unsigned int i;
4268 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4269 if (!strcmpiW(day, days[i]))
4270 return i;
4272 /* Invalid */
4273 return 7;
4276 static WORD HTTP_ParseMonth(LPCWSTR month)
4278 static const WCHAR jan[] = { 'j','a','n',0 };
4279 static const WCHAR feb[] = { 'f','e','b',0 };
4280 static const WCHAR mar[] = { 'm','a','r',0 };
4281 static const WCHAR apr[] = { 'a','p','r',0 };
4282 static const WCHAR may[] = { 'm','a','y',0 };
4283 static const WCHAR jun[] = { 'j','u','n',0 };
4284 static const WCHAR jul[] = { 'j','u','l',0 };
4285 static const WCHAR aug[] = { 'a','u','g',0 };
4286 static const WCHAR sep[] = { 's','e','p',0 };
4287 static const WCHAR oct[] = { 'o','c','t',0 };
4288 static const WCHAR nov[] = { 'n','o','v',0 };
4289 static const WCHAR dec[] = { 'd','e','c',0 };
4291 if (!strcmpiW(month, jan)) return 1;
4292 if (!strcmpiW(month, feb)) return 2;
4293 if (!strcmpiW(month, mar)) return 3;
4294 if (!strcmpiW(month, apr)) return 4;
4295 if (!strcmpiW(month, may)) return 5;
4296 if (!strcmpiW(month, jun)) return 6;
4297 if (!strcmpiW(month, jul)) return 7;
4298 if (!strcmpiW(month, aug)) return 8;
4299 if (!strcmpiW(month, sep)) return 9;
4300 if (!strcmpiW(month, oct)) return 10;
4301 if (!strcmpiW(month, nov)) return 11;
4302 if (!strcmpiW(month, dec)) return 12;
4303 /* Invalid */
4304 return 0;
4307 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4308 * optionally preceded by whitespace.
4309 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4310 * st, and sets *str to the first character after the time format.
4312 static BOOL HTTP_ParseTime(SYSTEMTIME *st, LPCWSTR *str)
4314 LPCWSTR ptr = *str;
4315 WCHAR *nextPtr;
4316 unsigned long num;
4318 while (isspaceW(*ptr))
4319 ptr++;
4321 num = strtoulW(ptr, &nextPtr, 10);
4322 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4324 ERR("unexpected time format %s\n", debugstr_w(ptr));
4325 return FALSE;
4327 if (num > 23)
4329 ERR("unexpected hour in time format %s\n", debugstr_w(ptr));
4330 return FALSE;
4332 ptr = nextPtr + 1;
4333 st->wHour = (WORD)num;
4334 num = strtoulW(ptr, &nextPtr, 10);
4335 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4337 ERR("unexpected time format %s\n", debugstr_w(ptr));
4338 return FALSE;
4340 if (num > 59)
4342 ERR("unexpected minute in time format %s\n", debugstr_w(ptr));
4343 return FALSE;
4345 ptr = nextPtr + 1;
4346 st->wMinute = (WORD)num;
4347 num = strtoulW(ptr, &nextPtr, 10);
4348 if (!nextPtr || nextPtr <= ptr)
4350 ERR("unexpected time format %s\n", debugstr_w(ptr));
4351 return FALSE;
4353 if (num > 59)
4355 ERR("unexpected second in time format %s\n", debugstr_w(ptr));
4356 return FALSE;
4358 ptr = nextPtr + 1;
4359 *str = ptr;
4360 st->wSecond = (WORD)num;
4361 return TRUE;
4364 static BOOL HTTP_ParseDateAsAsctime(LPCWSTR value, FILETIME *ft)
4366 static const WCHAR gmt[]= { 'G','M','T',0 };
4367 WCHAR day[4], *dayPtr, month[4], *monthPtr, *nextPtr;
4368 LPCWSTR ptr;
4369 SYSTEMTIME st = { 0 };
4370 unsigned long num;
4372 for (ptr = value, dayPtr = day; *ptr && !isspaceW(*ptr) &&
4373 dayPtr - day < sizeof(day) / sizeof(day[0]) - 1; ptr++, dayPtr++)
4374 *dayPtr = *ptr;
4375 *dayPtr = 0;
4376 st.wDayOfWeek = HTTP_ParseWkday(day);
4377 if (st.wDayOfWeek >= 7)
4379 ERR("unexpected weekday %s\n", debugstr_w(day));
4380 return FALSE;
4383 while (isspaceW(*ptr))
4384 ptr++;
4386 for (monthPtr = month; !isspace(*ptr) &&
4387 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4388 monthPtr++, ptr++)
4389 *monthPtr = *ptr;
4390 *monthPtr = 0;
4391 st.wMonth = HTTP_ParseMonth(month);
4392 if (!st.wMonth || st.wMonth > 12)
4394 ERR("unexpected month %s\n", debugstr_w(month));
4395 return FALSE;
4398 while (isspaceW(*ptr))
4399 ptr++;
4401 num = strtoulW(ptr, &nextPtr, 10);
4402 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4404 ERR("unexpected day %s\n", debugstr_w(ptr));
4405 return FALSE;
4407 ptr = nextPtr;
4408 st.wDay = (WORD)num;
4410 while (isspaceW(*ptr))
4411 ptr++;
4413 if (!HTTP_ParseTime(&st, &ptr))
4414 return FALSE;
4416 while (isspaceW(*ptr))
4417 ptr++;
4419 num = strtoulW(ptr, &nextPtr, 10);
4420 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4422 ERR("unexpected year %s\n", debugstr_w(ptr));
4423 return FALSE;
4425 ptr = nextPtr;
4426 st.wYear = (WORD)num;
4428 while (isspaceW(*ptr))
4429 ptr++;
4431 /* asctime() doesn't report a timezone, but some web servers do, so accept
4432 * with or without GMT.
4434 if (*ptr && strcmpW(ptr, gmt))
4436 ERR("unexpected timezone %s\n", debugstr_w(ptr));
4437 return FALSE;
4439 return SystemTimeToFileTime(&st, ft);
4442 static BOOL HTTP_ParseRfc1123Date(LPCWSTR value, FILETIME *ft)
4444 static const WCHAR gmt[]= { 'G','M','T',0 };
4445 WCHAR *nextPtr, day[4], month[4], *monthPtr;
4446 LPCWSTR ptr;
4447 unsigned long num;
4448 SYSTEMTIME st = { 0 };
4450 ptr = strchrW(value, ',');
4451 if (!ptr)
4452 return FALSE;
4453 if (ptr - value != 3)
4455 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4456 return FALSE;
4458 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4459 day[3] = 0;
4460 st.wDayOfWeek = HTTP_ParseWkday(day);
4461 if (st.wDayOfWeek > 6)
4463 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4464 return FALSE;
4466 ptr++;
4468 while (isspaceW(*ptr))
4469 ptr++;
4471 num = strtoulW(ptr, &nextPtr, 10);
4472 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4474 WARN("unexpected day %s\n", debugstr_w(value));
4475 return FALSE;
4477 ptr = nextPtr;
4478 st.wDay = (WORD)num;
4480 while (isspaceW(*ptr))
4481 ptr++;
4483 for (monthPtr = month; !isspace(*ptr) &&
4484 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4485 monthPtr++, ptr++)
4486 *monthPtr = *ptr;
4487 *monthPtr = 0;
4488 st.wMonth = HTTP_ParseMonth(month);
4489 if (!st.wMonth || st.wMonth > 12)
4491 WARN("unexpected month %s\n", debugstr_w(month));
4492 return FALSE;
4495 while (isspaceW(*ptr))
4496 ptr++;
4498 num = strtoulW(ptr, &nextPtr, 10);
4499 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4501 ERR("unexpected year %s\n", debugstr_w(value));
4502 return FALSE;
4504 ptr = nextPtr;
4505 st.wYear = (WORD)num;
4507 if (!HTTP_ParseTime(&st, &ptr))
4508 return FALSE;
4510 while (isspaceW(*ptr))
4511 ptr++;
4513 if (strcmpW(ptr, gmt))
4515 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4516 return FALSE;
4518 return SystemTimeToFileTime(&st, ft);
4521 static WORD HTTP_ParseWeekday(LPCWSTR day)
4523 static const WCHAR days[7][10] = {{ 's','u','n','d','a','y',0 },
4524 { 'm','o','n','d','a','y',0 },
4525 { 't','u','e','s','d','a','y',0 },
4526 { 'w','e','d','n','e','s','d','a','y',0 },
4527 { 't','h','u','r','s','d','a','y',0 },
4528 { 'f','r','i','d','a','y',0 },
4529 { 's','a','t','u','r','d','a','y',0 }};
4530 unsigned int i;
4531 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4532 if (!strcmpiW(day, days[i]))
4533 return i;
4535 /* Invalid */
4536 return 7;
4539 static BOOL HTTP_ParseRfc850Date(LPCWSTR value, FILETIME *ft)
4541 static const WCHAR gmt[]= { 'G','M','T',0 };
4542 WCHAR *nextPtr, day[10], month[4], *monthPtr;
4543 LPCWSTR ptr;
4544 unsigned long num;
4545 SYSTEMTIME st = { 0 };
4547 ptr = strchrW(value, ',');
4548 if (!ptr)
4549 return FALSE;
4550 if (ptr - value == 3)
4552 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4553 day[3] = 0;
4554 st.wDayOfWeek = HTTP_ParseWkday(day);
4555 if (st.wDayOfWeek > 6)
4557 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4558 return FALSE;
4561 else if (ptr - value < sizeof(day) / sizeof(day[0]))
4563 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4564 day[ptr - value + 1] = 0;
4565 st.wDayOfWeek = HTTP_ParseWeekday(day);
4566 if (st.wDayOfWeek > 6)
4568 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4569 return FALSE;
4572 else
4574 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4575 return FALSE;
4577 ptr++;
4579 while (isspaceW(*ptr))
4580 ptr++;
4582 num = strtoulW(ptr, &nextPtr, 10);
4583 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4585 ERR("unexpected day %s\n", debugstr_w(value));
4586 return FALSE;
4588 ptr = nextPtr;
4589 st.wDay = (WORD)num;
4591 if (*ptr != '-')
4593 ERR("unexpected month format %s\n", debugstr_w(ptr));
4594 return FALSE;
4596 ptr++;
4598 for (monthPtr = month; *ptr != '-' &&
4599 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4600 monthPtr++, ptr++)
4601 *monthPtr = *ptr;
4602 *monthPtr = 0;
4603 st.wMonth = HTTP_ParseMonth(month);
4604 if (!st.wMonth || st.wMonth > 12)
4606 ERR("unexpected month %s\n", debugstr_w(month));
4607 return FALSE;
4610 if (*ptr != '-')
4612 ERR("unexpected year format %s\n", debugstr_w(ptr));
4613 return FALSE;
4615 ptr++;
4617 num = strtoulW(ptr, &nextPtr, 10);
4618 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4620 ERR("unexpected year %s\n", debugstr_w(value));
4621 return FALSE;
4623 ptr = nextPtr;
4624 st.wYear = (WORD)num;
4626 if (!HTTP_ParseTime(&st, &ptr))
4627 return FALSE;
4629 while (isspaceW(*ptr))
4630 ptr++;
4632 if (strcmpW(ptr, gmt))
4634 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4635 return FALSE;
4637 return SystemTimeToFileTime(&st, ft);
4640 static BOOL HTTP_ParseDate(LPCWSTR value, FILETIME *ft)
4642 static const WCHAR zero[] = { '0',0 };
4643 BOOL ret;
4645 if (!strcmpW(value, zero))
4647 ft->dwLowDateTime = ft->dwHighDateTime = 0;
4648 ret = TRUE;
4650 else if (strchrW(value, ','))
4652 ret = HTTP_ParseRfc1123Date(value, ft);
4653 if (!ret)
4655 ret = HTTP_ParseRfc850Date(value, ft);
4656 if (!ret)
4657 ERR("unexpected date format %s\n", debugstr_w(value));
4660 else
4662 ret = HTTP_ParseDateAsAsctime(value, ft);
4663 if (!ret)
4664 ERR("unexpected date format %s\n", debugstr_w(value));
4666 return ret;
4669 static void HTTP_ProcessExpires(http_request_t *request)
4671 BOOL expirationFound = FALSE;
4672 int headerIndex;
4674 /* Look for a Cache-Control header with a max-age directive, as it takes
4675 * precedence over the Expires header.
4677 headerIndex = HTTP_GetCustomHeaderIndex(request, szCache_Control, 0, FALSE);
4678 if (headerIndex != -1)
4680 LPHTTPHEADERW ccHeader = &request->custHeaders[headerIndex];
4681 LPWSTR ptr;
4683 for (ptr = ccHeader->lpszValue; ptr && *ptr; )
4685 LPWSTR comma = strchrW(ptr, ','), end, equal;
4687 if (comma)
4688 end = comma;
4689 else
4690 end = ptr + strlenW(ptr);
4691 for (equal = end - 1; equal > ptr && *equal != '='; equal--)
4693 if (*equal == '=')
4695 static const WCHAR max_age[] = {
4696 'm','a','x','-','a','g','e',0 };
4698 if (!strncmpiW(ptr, max_age, equal - ptr - 1))
4700 LPWSTR nextPtr;
4701 unsigned long age;
4703 age = strtoulW(equal + 1, &nextPtr, 10);
4704 if (nextPtr > equal + 1)
4706 LARGE_INTEGER ft;
4708 NtQuerySystemTime( &ft );
4709 /* Age is in seconds, FILETIME resolution is in
4710 * 100 nanosecond intervals.
4712 ft.QuadPart += age * (ULONGLONG)1000000;
4713 request->expires.dwLowDateTime = ft.u.LowPart;
4714 request->expires.dwHighDateTime = ft.u.HighPart;
4715 expirationFound = TRUE;
4719 if (comma)
4721 ptr = comma + 1;
4722 while (isspaceW(*ptr))
4723 ptr++;
4725 else
4726 ptr = NULL;
4729 if (!expirationFound)
4731 headerIndex = HTTP_GetCustomHeaderIndex(request, szExpires, 0, FALSE);
4732 if (headerIndex != -1)
4734 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4735 FILETIME ft;
4737 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4739 expirationFound = TRUE;
4740 request->expires = ft;
4744 if (!expirationFound)
4746 LARGE_INTEGER t;
4748 /* With no known age, default to 10 minutes until expiration. */
4749 NtQuerySystemTime( &t );
4750 t.QuadPart += 10 * 60 * (ULONGLONG)10000000;
4751 request->expires.dwLowDateTime = t.u.LowPart;
4752 request->expires.dwHighDateTime = t.u.HighPart;
4756 static void HTTP_ProcessLastModified(http_request_t *request)
4758 int headerIndex;
4760 headerIndex = HTTP_GetCustomHeaderIndex(request, szLast_Modified, 0, FALSE);
4761 if (headerIndex != -1)
4763 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4764 FILETIME ft;
4766 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4767 request->last_modified = ft;
4771 static void http_process_keep_alive(http_request_t *req)
4773 int index;
4775 if ((index = HTTP_GetCustomHeaderIndex(req, szConnection, 0, FALSE)) != -1)
4776 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4777 else if ((index = HTTP_GetCustomHeaderIndex(req, szProxy_Connection, 0, FALSE)) != -1)
4778 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4779 else
4780 req->netconn->keep_alive = !strcmpiW(req->version, g_szHttp1_1);
4783 static DWORD open_http_connection(http_request_t *request, BOOL *reusing)
4785 const BOOL is_https = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) != 0;
4786 netconn_t *netconn = NULL;
4787 DWORD res;
4789 assert(!request->netconn);
4790 reset_data_stream(request);
4792 res = HTTP_ResolveName(request);
4793 if(res != ERROR_SUCCESS)
4794 return res;
4796 EnterCriticalSection(&connection_pool_cs);
4798 while(!list_empty(&request->server->conn_pool)) {
4799 netconn = LIST_ENTRY(list_head(&request->server->conn_pool), netconn_t, pool_entry);
4800 list_remove(&netconn->pool_entry);
4802 if(NETCON_is_alive(netconn))
4803 break;
4805 TRACE("connection %p closed during idle\n", netconn);
4806 free_netconn(netconn);
4807 netconn = NULL;
4810 LeaveCriticalSection(&connection_pool_cs);
4812 if(netconn) {
4813 TRACE("<-- reusing %p netconn\n", netconn);
4814 request->netconn = netconn;
4815 *reusing = TRUE;
4816 return ERROR_SUCCESS;
4819 TRACE("connecting to %s, proxy %s\n", debugstr_w(request->server->name),
4820 request->proxy ? debugstr_w(request->proxy->name) : "(null)");
4822 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4823 INTERNET_STATUS_CONNECTING_TO_SERVER,
4824 request->server->addr_str,
4825 strlen(request->server->addr_str)+1);
4827 res = create_netconn(is_https, request->proxy ? request->proxy : request->server, request->security_flags,
4828 (request->hdr.ErrorMask & INTERNET_ERROR_MASK_COMBINED_SEC_CERT) != 0,
4829 request->connect_timeout, &netconn);
4830 if(res != ERROR_SUCCESS) {
4831 ERR("create_netconn failed: %u\n", res);
4832 return res;
4835 request->netconn = netconn;
4837 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4838 INTERNET_STATUS_CONNECTED_TO_SERVER,
4839 request->server->addr_str, strlen(request->server->addr_str)+1);
4841 if(is_https) {
4842 /* Note: we differ from Microsoft's WinINet here. they seem to have
4843 * a bug that causes no status callbacks to be sent when starting
4844 * a tunnel to a proxy server using the CONNECT verb. i believe our
4845 * behaviour to be more correct and to not cause any incompatibilities
4846 * because using a secure connection through a proxy server is a rare
4847 * case that would be hard for anyone to depend on */
4848 if(request->proxy)
4849 res = HTTP_SecureProxyConnect(request);
4850 if(res == ERROR_SUCCESS)
4851 res = NETCON_secure_connect(request->netconn, request->server);
4854 if(res != ERROR_SUCCESS) {
4855 http_release_netconn(request, FALSE);
4856 return res;
4859 *reusing = FALSE;
4860 TRACE("Created connection to %s: %p\n", debugstr_w(request->server->name), netconn);
4861 return ERROR_SUCCESS;
4864 /***********************************************************************
4865 * HTTP_HttpSendRequestW (internal)
4867 * Sends the specified request to the HTTP server
4869 * RETURNS
4870 * ERROR_SUCCESS on success
4871 * win32 error code on failure
4874 static DWORD HTTP_HttpSendRequestW(http_request_t *request, LPCWSTR lpszHeaders,
4875 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
4876 DWORD dwContentLength, BOOL bEndRequest)
4878 INT cnt;
4879 BOOL redirected = FALSE;
4880 LPWSTR requestString = NULL;
4881 INT responseLen;
4882 BOOL loop_next;
4883 static const WCHAR szContentLength[] =
4884 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
4885 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
4886 DWORD res;
4888 TRACE("--> %p\n", request);
4890 assert(request->hdr.htype == WH_HHTTPREQ);
4892 /* if the verb is NULL default to GET */
4893 if (!request->verb)
4894 request->verb = heap_strdupW(szGET);
4896 if (dwContentLength || strcmpW(request->verb, szGET))
4898 sprintfW(contentLengthStr, szContentLength, dwContentLength);
4899 HTTP_HttpAddRequestHeadersW(request, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_REPLACE);
4900 request->bytesToWrite = dwContentLength;
4902 if (request->session->appInfo->agent)
4904 WCHAR *agent_header;
4905 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4906 int len;
4908 len = strlenW(request->session->appInfo->agent) + strlenW(user_agent);
4909 agent_header = heap_alloc(len * sizeof(WCHAR));
4910 sprintfW(agent_header, user_agent, request->session->appInfo->agent);
4912 HTTP_HttpAddRequestHeadersW(request, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4913 heap_free(agent_header);
4915 if (request->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
4917 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4918 HTTP_HttpAddRequestHeadersW(request, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4920 if ((request->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && strcmpW(request->verb, szGET))
4922 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4923 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4924 HTTP_HttpAddRequestHeadersW(request, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4927 /* add the headers the caller supplied */
4928 if( lpszHeaders && dwHeaderLength )
4929 HTTP_HttpAddRequestHeadersW(request, lpszHeaders, dwHeaderLength, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
4933 DWORD len;
4934 BOOL reusing_connection;
4935 char *ascii_req;
4937 loop_next = FALSE;
4939 if (request->netconn && !NETCON_is_alive(request->netconn))
4941 free_netconn(request->netconn);
4942 request->netconn = NULL;
4944 reusing_connection = request->netconn != NULL;
4946 if(redirected) {
4947 request->contentLength = ~0u;
4948 request->bytesToWrite = 0;
4951 if (TRACE_ON(wininet))
4953 LPHTTPHEADERW Host = HTTP_GetHeader(request, hostW);
4954 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(request->path));
4957 HTTP_FixURL(request);
4958 if (request->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
4960 HTTP_ProcessHeader(request, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
4962 HTTP_InsertAuthorization(request, request->authInfo, szAuthorization);
4963 HTTP_InsertAuthorization(request, request->proxyAuthInfo, szProxy_Authorization);
4965 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
4966 HTTP_InsertCookies(request);
4968 if (request->proxy)
4970 WCHAR *url = build_proxy_path_url(request);
4971 requestString = build_request_header(request, request->verb, url, request->version, TRUE);
4972 heap_free(url);
4974 else
4975 requestString = build_request_header(request, request->verb, request->path, request->version, TRUE);
4978 TRACE("Request header -> %s\n", debugstr_w(requestString) );
4980 if (!reusing_connection && (res = open_http_connection(request, &reusing_connection)) != ERROR_SUCCESS)
4981 break;
4983 /* send the request as ASCII, tack on the optional data */
4984 if (!lpOptional || redirected)
4985 dwOptionalLength = 0;
4986 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
4987 NULL, 0, NULL, NULL );
4988 ascii_req = heap_alloc(len + dwOptionalLength);
4989 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
4990 ascii_req, len, NULL, NULL );
4991 if( lpOptional )
4992 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
4993 len = (len + dwOptionalLength - 1);
4994 ascii_req[len] = 0;
4995 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
4997 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4998 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
5000 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
5001 res = NETCON_send(request->netconn, ascii_req, len, 0, &cnt);
5002 heap_free( ascii_req );
5003 if(res != ERROR_SUCCESS) {
5004 TRACE("send failed: %u\n", res);
5005 if(!reusing_connection)
5006 break;
5007 http_release_netconn(request, FALSE);
5008 loop_next = TRUE;
5009 continue;
5012 request->bytesWritten = dwOptionalLength;
5014 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5015 INTERNET_STATUS_REQUEST_SENT,
5016 &len, sizeof(DWORD));
5018 if (bEndRequest)
5020 DWORD dwBufferSize;
5022 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5023 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5025 if (HTTP_GetResponseHeaders(request, &responseLen))
5027 http_release_netconn(request, FALSE);
5028 res = ERROR_INTERNET_CONNECTION_ABORTED;
5029 goto lend;
5031 /* FIXME: We should know that connection is closed before sending
5032 * headers. Otherwise wrong callbacks are executed */
5033 if(!responseLen && reusing_connection) {
5034 TRACE("Connection closed by server, reconnecting\n");
5035 http_release_netconn(request, FALSE);
5036 loop_next = TRUE;
5037 continue;
5040 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5041 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
5042 sizeof(DWORD));
5044 http_process_keep_alive(request);
5045 HTTP_ProcessCookies(request);
5046 HTTP_ProcessExpires(request);
5047 HTTP_ProcessLastModified(request);
5049 res = set_content_length(request);
5050 if(res != ERROR_SUCCESS)
5051 goto lend;
5052 if(!request->contentLength)
5053 http_release_netconn(request, TRUE);
5055 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
5057 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5058 dwBufferSize=sizeof(szNewLocation);
5059 switch(request->status_code) {
5060 case HTTP_STATUS_REDIRECT:
5061 case HTTP_STATUS_MOVED:
5062 case HTTP_STATUS_REDIRECT_KEEP_VERB:
5063 case HTTP_STATUS_REDIRECT_METHOD:
5064 if(HTTP_HttpQueryInfoW(request,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL) != ERROR_SUCCESS)
5065 break;
5067 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5068 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5070 heap_free(request->verb);
5071 request->verb = heap_strdupW(szGET);
5073 http_release_netconn(request, drain_content(request, FALSE));
5074 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5076 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5077 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5078 res = HTTP_HandleRedirect(request, new_url);
5079 if (res == ERROR_SUCCESS)
5081 heap_free(requestString);
5082 loop_next = TRUE;
5084 heap_free( new_url );
5086 redirected = TRUE;
5089 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
5091 WCHAR szAuthValue[2048];
5092 dwBufferSize=2048;
5093 if (request->status_code == HTTP_STATUS_DENIED)
5095 LPHTTPHEADERW Host = HTTP_GetHeader(request, hostW);
5096 DWORD dwIndex = 0;
5097 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5099 if (HTTP_DoAuthorization(request, szAuthValue,
5100 &request->authInfo,
5101 request->session->userName,
5102 request->session->password,
5103 Host->lpszValue))
5105 heap_free(requestString);
5106 if(!drain_content(request, TRUE)) {
5107 FIXME("Could not drain content\n");
5108 http_release_netconn(request, FALSE);
5110 loop_next = TRUE;
5111 break;
5115 if(!loop_next) {
5116 TRACE("Cleaning wrong authorization data\n");
5117 destroy_authinfo(request->authInfo);
5118 request->authInfo = NULL;
5121 if (request->status_code == HTTP_STATUS_PROXY_AUTH_REQ)
5123 DWORD dwIndex = 0;
5124 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5126 if (HTTP_DoAuthorization(request, szAuthValue,
5127 &request->proxyAuthInfo,
5128 request->session->appInfo->proxyUsername,
5129 request->session->appInfo->proxyPassword,
5130 NULL))
5132 heap_free(requestString);
5133 if(!drain_content(request, TRUE)) {
5134 FIXME("Could not drain content\n");
5135 http_release_netconn(request, FALSE);
5137 loop_next = TRUE;
5138 break;
5142 if(!loop_next) {
5143 TRACE("Cleaning wrong proxy authorization data\n");
5144 destroy_authinfo(request->proxyAuthInfo);
5145 request->proxyAuthInfo = NULL;
5150 else
5151 res = ERROR_SUCCESS;
5153 while (loop_next);
5155 lend:
5156 heap_free(requestString);
5158 /* TODO: send notification for P3P header */
5160 if(res == ERROR_SUCCESS)
5161 create_cache_entry(request);
5163 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5165 if (res == ERROR_SUCCESS) {
5166 if(bEndRequest && request->contentLength && request->bytesWritten == request->bytesToWrite)
5167 HTTP_ReceiveRequestData(request, TRUE, NULL);
5168 else
5169 send_request_complete(request,
5170 request->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)request->hdr.hInternet : 1, 0);
5171 }else {
5172 send_request_complete(request, 0, res);
5176 TRACE("<--\n");
5177 return res;
5180 typedef struct {
5181 task_header_t hdr;
5182 WCHAR *headers;
5183 DWORD headers_len;
5184 void *optional;
5185 DWORD optional_len;
5186 DWORD content_len;
5187 BOOL end_request;
5188 } send_request_task_t;
5190 /***********************************************************************
5192 * Helper functions for the HttpSendRequest(Ex) functions
5195 static void AsyncHttpSendRequestProc(task_header_t *hdr)
5197 send_request_task_t *task = (send_request_task_t*)hdr;
5198 http_request_t *request = (http_request_t*)task->hdr.hdr;
5200 TRACE("%p\n", request);
5202 HTTP_HttpSendRequestW(request, task->headers, task->headers_len, task->optional,
5203 task->optional_len, task->content_len, task->end_request);
5205 heap_free(task->headers);
5209 static DWORD HTTP_HttpEndRequestW(http_request_t *request, DWORD dwFlags, DWORD_PTR dwContext)
5211 DWORD dwBufferSize;
5212 INT responseLen;
5213 DWORD res = ERROR_SUCCESS;
5215 if(!request->netconn) {
5216 WARN("Not connected\n");
5217 send_request_complete(request, 0, ERROR_INTERNET_OPERATION_CANCELLED);
5218 return ERROR_INTERNET_OPERATION_CANCELLED;
5221 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5222 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5224 if (HTTP_GetResponseHeaders(request, &responseLen) || !responseLen)
5225 res = ERROR_HTTP_HEADER_NOT_FOUND;
5227 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5228 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
5230 /* process cookies here. Is this right? */
5231 http_process_keep_alive(request);
5232 HTTP_ProcessCookies(request);
5233 HTTP_ProcessExpires(request);
5234 HTTP_ProcessLastModified(request);
5236 if ((res = set_content_length(request)) == ERROR_SUCCESS) {
5237 if(!request->contentLength)
5238 http_release_netconn(request, TRUE);
5241 if (res == ERROR_SUCCESS && !(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
5243 switch(request->status_code) {
5244 case HTTP_STATUS_REDIRECT:
5245 case HTTP_STATUS_MOVED:
5246 case HTTP_STATUS_REDIRECT_METHOD:
5247 case HTTP_STATUS_REDIRECT_KEEP_VERB: {
5248 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5249 dwBufferSize=sizeof(szNewLocation);
5250 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, szNewLocation, &dwBufferSize, NULL) != ERROR_SUCCESS)
5251 break;
5253 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5254 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5256 heap_free(request->verb);
5257 request->verb = heap_strdupW(szGET);
5259 http_release_netconn(request, drain_content(request, FALSE));
5260 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5262 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5263 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5264 res = HTTP_HandleRedirect(request, new_url);
5265 if (res == ERROR_SUCCESS)
5266 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, TRUE);
5267 heap_free( new_url );
5273 if(res == ERROR_SUCCESS)
5274 create_cache_entry(request);
5276 if (res == ERROR_SUCCESS && request->contentLength)
5277 HTTP_ReceiveRequestData(request, TRUE, NULL);
5278 else
5279 send_request_complete(request, res == ERROR_SUCCESS, res);
5281 return res;
5284 /***********************************************************************
5285 * HttpEndRequestA (WININET.@)
5287 * Ends an HTTP request that was started by HttpSendRequestEx
5289 * RETURNS
5290 * TRUE if successful
5291 * FALSE on failure
5294 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
5295 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5297 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5299 if (lpBuffersOut)
5301 SetLastError(ERROR_INVALID_PARAMETER);
5302 return FALSE;
5305 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
5308 typedef struct {
5309 task_header_t hdr;
5310 DWORD flags;
5311 DWORD context;
5312 } end_request_task_t;
5314 static void AsyncHttpEndRequestProc(task_header_t *hdr)
5316 end_request_task_t *task = (end_request_task_t*)hdr;
5317 http_request_t *req = (http_request_t*)task->hdr.hdr;
5319 TRACE("%p\n", req);
5321 HTTP_HttpEndRequestW(req, task->flags, task->context);
5324 /***********************************************************************
5325 * HttpEndRequestW (WININET.@)
5327 * Ends an HTTP request that was started by HttpSendRequestEx
5329 * RETURNS
5330 * TRUE if successful
5331 * FALSE on failure
5334 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
5335 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5337 http_request_t *request;
5338 DWORD res;
5340 TRACE("%p %p %x %lx -->\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5342 if (lpBuffersOut)
5344 SetLastError(ERROR_INVALID_PARAMETER);
5345 return FALSE;
5348 request = (http_request_t*) get_handle_object( hRequest );
5350 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5352 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
5353 if (request)
5354 WININET_Release( &request->hdr );
5355 return FALSE;
5357 request->hdr.dwFlags |= dwFlags;
5359 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5361 end_request_task_t *task;
5363 task = alloc_async_task(&request->hdr, AsyncHttpEndRequestProc, sizeof(*task));
5364 task->flags = dwFlags;
5365 task->context = dwContext;
5367 INTERNET_AsyncCall(&task->hdr);
5368 res = ERROR_IO_PENDING;
5370 else
5371 res = HTTP_HttpEndRequestW(request, dwFlags, dwContext);
5373 WININET_Release( &request->hdr );
5374 TRACE("%u <--\n", res);
5375 if(res != ERROR_SUCCESS)
5376 SetLastError(res);
5377 return res == ERROR_SUCCESS;
5380 /***********************************************************************
5381 * HttpSendRequestExA (WININET.@)
5383 * Sends the specified request to the HTTP server and allows chunked
5384 * transfers.
5386 * RETURNS
5387 * Success: TRUE
5388 * Failure: FALSE, call GetLastError() for more information.
5390 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
5391 LPINTERNET_BUFFERSA lpBuffersIn,
5392 LPINTERNET_BUFFERSA lpBuffersOut,
5393 DWORD dwFlags, DWORD_PTR dwContext)
5395 INTERNET_BUFFERSW BuffersInW;
5396 BOOL rc = FALSE;
5397 DWORD headerlen;
5398 LPWSTR header = NULL;
5400 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5401 lpBuffersOut, dwFlags, dwContext);
5403 if (lpBuffersIn)
5405 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
5406 if (lpBuffersIn->lpcszHeader)
5408 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
5409 lpBuffersIn->dwHeadersLength,0,0);
5410 header = heap_alloc(headerlen*sizeof(WCHAR));
5411 if (!(BuffersInW.lpcszHeader = header))
5413 SetLastError(ERROR_OUTOFMEMORY);
5414 return FALSE;
5416 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
5417 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5418 header, headerlen);
5420 else
5421 BuffersInW.lpcszHeader = NULL;
5422 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
5423 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
5424 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
5425 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
5426 BuffersInW.Next = NULL;
5429 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
5431 heap_free(header);
5432 return rc;
5435 /***********************************************************************
5436 * HttpSendRequestExW (WININET.@)
5438 * Sends the specified request to the HTTP server and allows chunked
5439 * transfers
5441 * RETURNS
5442 * Success: TRUE
5443 * Failure: FALSE, call GetLastError() for more information.
5445 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
5446 LPINTERNET_BUFFERSW lpBuffersIn,
5447 LPINTERNET_BUFFERSW lpBuffersOut,
5448 DWORD dwFlags, DWORD_PTR dwContext)
5450 http_request_t *request;
5451 http_session_t *session;
5452 appinfo_t *hIC;
5453 DWORD res;
5455 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5456 lpBuffersOut, dwFlags, dwContext);
5458 request = (http_request_t*) get_handle_object( hRequest );
5460 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5462 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5463 goto lend;
5466 session = request->session;
5467 assert(session->hdr.htype == WH_HHTTPSESSION);
5468 hIC = session->appInfo;
5469 assert(hIC->hdr.htype == WH_HINIT);
5471 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5473 send_request_task_t *task;
5475 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5476 if (lpBuffersIn)
5478 DWORD size = 0;
5480 if (lpBuffersIn->lpcszHeader)
5482 if (lpBuffersIn->dwHeadersLength == ~0u)
5483 size = (strlenW( lpBuffersIn->lpcszHeader ) + 1) * sizeof(WCHAR);
5484 else
5485 size = lpBuffersIn->dwHeadersLength * sizeof(WCHAR);
5487 task->headers = heap_alloc(size);
5488 memcpy(task->headers, lpBuffersIn->lpcszHeader, size);
5490 else task->headers = NULL;
5492 task->headers_len = size / sizeof(WCHAR);
5493 task->optional = lpBuffersIn->lpvBuffer;
5494 task->optional_len = lpBuffersIn->dwBufferLength;
5495 task->content_len = lpBuffersIn->dwBufferTotal;
5497 else
5499 task->headers = NULL;
5500 task->headers_len = 0;
5501 task->optional = NULL;
5502 task->optional_len = 0;
5503 task->content_len = 0;
5506 task->end_request = FALSE;
5508 INTERNET_AsyncCall(&task->hdr);
5509 res = ERROR_IO_PENDING;
5511 else
5513 if (lpBuffersIn)
5514 res = HTTP_HttpSendRequestW(request, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5515 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
5516 lpBuffersIn->dwBufferTotal, FALSE);
5517 else
5518 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, FALSE);
5521 lend:
5522 if ( request )
5523 WININET_Release( &request->hdr );
5525 TRACE("<---\n");
5526 SetLastError(res);
5527 return res == ERROR_SUCCESS;
5530 /***********************************************************************
5531 * HttpSendRequestW (WININET.@)
5533 * Sends the specified request to the HTTP server
5535 * RETURNS
5536 * TRUE on success
5537 * FALSE on failure
5540 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
5541 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5543 http_request_t *request;
5544 http_session_t *session = NULL;
5545 appinfo_t *hIC = NULL;
5546 DWORD res = ERROR_SUCCESS;
5548 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
5549 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
5551 request = (http_request_t*) get_handle_object( hHttpRequest );
5552 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5554 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5555 goto lend;
5558 session = request->session;
5559 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
5561 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5562 goto lend;
5565 hIC = session->appInfo;
5566 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
5568 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5569 goto lend;
5572 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5574 send_request_task_t *task;
5576 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5577 if (lpszHeaders)
5579 DWORD size;
5581 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
5582 else size = dwHeaderLength * sizeof(WCHAR);
5584 task->headers = heap_alloc(size);
5585 memcpy(task->headers, lpszHeaders, size);
5587 else
5588 task->headers = NULL;
5589 task->headers_len = dwHeaderLength;
5590 task->optional = lpOptional;
5591 task->optional_len = dwOptionalLength;
5592 task->content_len = dwOptionalLength;
5593 task->end_request = TRUE;
5595 INTERNET_AsyncCall(&task->hdr);
5596 res = ERROR_IO_PENDING;
5598 else
5600 res = HTTP_HttpSendRequestW(request, lpszHeaders,
5601 dwHeaderLength, lpOptional, dwOptionalLength,
5602 dwOptionalLength, TRUE);
5604 lend:
5605 if( request )
5606 WININET_Release( &request->hdr );
5608 SetLastError(res);
5609 return res == ERROR_SUCCESS;
5612 /***********************************************************************
5613 * HttpSendRequestA (WININET.@)
5615 * Sends the specified request to the HTTP server
5617 * RETURNS
5618 * TRUE on success
5619 * FALSE on failure
5622 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
5623 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5625 BOOL result;
5626 LPWSTR szHeaders=NULL;
5627 DWORD nLen=dwHeaderLength;
5628 if(lpszHeaders!=NULL)
5630 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
5631 szHeaders = heap_alloc(nLen*sizeof(WCHAR));
5632 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
5634 result = HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
5635 heap_free(szHeaders);
5636 return result;
5639 /***********************************************************************
5640 * HTTPSESSION_Destroy (internal)
5642 * Deallocate session handle
5645 static void HTTPSESSION_Destroy(object_header_t *hdr)
5647 http_session_t *session = (http_session_t*) hdr;
5649 TRACE("%p\n", session);
5651 WININET_Release(&session->appInfo->hdr);
5653 heap_free(session->hostName);
5654 heap_free(session->password);
5655 heap_free(session->userName);
5658 static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
5660 http_session_t *ses = (http_session_t *)hdr;
5662 switch(option) {
5663 case INTERNET_OPTION_HANDLE_TYPE:
5664 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5666 if (*size < sizeof(ULONG))
5667 return ERROR_INSUFFICIENT_BUFFER;
5669 *size = sizeof(DWORD);
5670 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
5671 return ERROR_SUCCESS;
5672 case INTERNET_OPTION_CONNECT_TIMEOUT:
5673 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5675 if (*size < sizeof(DWORD))
5676 return ERROR_INSUFFICIENT_BUFFER;
5678 *size = sizeof(DWORD);
5679 *(DWORD *)buffer = ses->connect_timeout;
5680 return ERROR_SUCCESS;
5682 case INTERNET_OPTION_SEND_TIMEOUT:
5683 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5685 if (*size < sizeof(DWORD))
5686 return ERROR_INSUFFICIENT_BUFFER;
5688 *size = sizeof(DWORD);
5689 *(DWORD *)buffer = ses->send_timeout;
5690 return ERROR_SUCCESS;
5692 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5693 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5695 if (*size < sizeof(DWORD))
5696 return ERROR_INSUFFICIENT_BUFFER;
5698 *size = sizeof(DWORD);
5699 *(DWORD *)buffer = ses->receive_timeout;
5700 return ERROR_SUCCESS;
5703 return INET_QueryOption(hdr, option, buffer, size, unicode);
5706 static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
5708 http_session_t *ses = (http_session_t*)hdr;
5710 switch(option) {
5711 case INTERNET_OPTION_USERNAME:
5713 heap_free(ses->userName);
5714 if (!(ses->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5715 return ERROR_SUCCESS;
5717 case INTERNET_OPTION_PASSWORD:
5719 heap_free(ses->password);
5720 if (!(ses->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5721 return ERROR_SUCCESS;
5723 case INTERNET_OPTION_PROXY_USERNAME:
5725 heap_free(ses->appInfo->proxyUsername);
5726 if (!(ses->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5727 return ERROR_SUCCESS;
5729 case INTERNET_OPTION_PROXY_PASSWORD:
5731 heap_free(ses->appInfo->proxyPassword);
5732 if (!(ses->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5733 return ERROR_SUCCESS;
5735 case INTERNET_OPTION_CONNECT_TIMEOUT:
5737 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5738 ses->connect_timeout = *(DWORD *)buffer;
5739 return ERROR_SUCCESS;
5741 case INTERNET_OPTION_SEND_TIMEOUT:
5743 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5744 ses->send_timeout = *(DWORD *)buffer;
5745 return ERROR_SUCCESS;
5747 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5749 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5750 ses->receive_timeout = *(DWORD *)buffer;
5751 return ERROR_SUCCESS;
5753 default: break;
5756 return INET_SetOption(hdr, option, buffer, size);
5759 static const object_vtbl_t HTTPSESSIONVtbl = {
5760 HTTPSESSION_Destroy,
5761 NULL,
5762 HTTPSESSION_QueryOption,
5763 HTTPSESSION_SetOption,
5764 NULL,
5765 NULL,
5766 NULL,
5767 NULL,
5768 NULL
5772 /***********************************************************************
5773 * HTTP_Connect (internal)
5775 * Create http session handle
5777 * RETURNS
5778 * HINTERNET a session handle on success
5779 * NULL on failure
5782 DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
5783 INTERNET_PORT serverPort, LPCWSTR lpszUserName,
5784 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
5785 DWORD dwInternalFlags, HINTERNET *ret)
5787 http_session_t *session = NULL;
5789 TRACE("-->\n");
5791 if (!lpszServerName || !lpszServerName[0])
5792 return ERROR_INVALID_PARAMETER;
5794 assert( hIC->hdr.htype == WH_HINIT );
5796 session = alloc_object(&hIC->hdr, &HTTPSESSIONVtbl, sizeof(http_session_t));
5797 if (!session)
5798 return ERROR_OUTOFMEMORY;
5801 * According to my tests. The name is not resolved until a request is sent
5804 session->hdr.htype = WH_HHTTPSESSION;
5805 session->hdr.dwFlags = dwFlags;
5806 session->hdr.dwContext = dwContext;
5807 session->hdr.dwInternalFlags |= dwInternalFlags;
5809 WININET_AddRef( &hIC->hdr );
5810 session->appInfo = hIC;
5811 list_add_head( &hIC->hdr.children, &session->hdr.entry );
5813 session->hostName = heap_strdupW(lpszServerName);
5814 if (lpszUserName && lpszUserName[0])
5815 session->userName = heap_strdupW(lpszUserName);
5816 if (lpszPassword && lpszPassword[0])
5817 session->password = heap_strdupW(lpszPassword);
5818 session->hostPort = serverPort;
5819 session->connect_timeout = hIC->connect_timeout;
5820 session->send_timeout = INFINITE;
5821 session->receive_timeout = INFINITE;
5823 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5824 if (!(session->hdr.dwInternalFlags & INET_OPENURL))
5826 INTERNET_SendCallback(&hIC->hdr, dwContext,
5827 INTERNET_STATUS_HANDLE_CREATED, &session->hdr.hInternet,
5828 sizeof(HINTERNET));
5832 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5833 * windows
5836 TRACE("%p --> %p\n", hIC, session);
5838 *ret = session->hdr.hInternet;
5839 return ERROR_SUCCESS;
5842 /***********************************************************************
5843 * HTTP_clear_response_headers (internal)
5845 * clear out any old response headers
5847 static void HTTP_clear_response_headers( http_request_t *request )
5849 DWORD i;
5851 for( i=0; i<request->nCustHeaders; i++)
5853 if( !request->custHeaders[i].lpszField )
5854 continue;
5855 if( !request->custHeaders[i].lpszValue )
5856 continue;
5857 if ( request->custHeaders[i].wFlags & HDR_ISREQUEST )
5858 continue;
5859 HTTP_DeleteCustomHeader( request, i );
5860 i--;
5864 /***********************************************************************
5865 * HTTP_GetResponseHeaders (internal)
5867 * Read server response
5869 * RETURNS
5871 * TRUE on success
5872 * FALSE on error
5874 static DWORD HTTP_GetResponseHeaders(http_request_t *request, INT *len)
5876 INT cbreaks = 0;
5877 WCHAR buffer[MAX_REPLY_LEN];
5878 DWORD buflen = MAX_REPLY_LEN;
5879 INT rc = 0;
5880 char bufferA[MAX_REPLY_LEN];
5881 LPWSTR status_code = NULL, status_text = NULL;
5882 DWORD res = ERROR_HTTP_INVALID_SERVER_RESPONSE;
5883 BOOL codeHundred = FALSE;
5885 TRACE("-->\n");
5887 if(!request->netconn)
5888 goto lend;
5890 /* clear old response headers (eg. from a redirect response) */
5891 HTTP_clear_response_headers( request );
5893 NETCON_set_timeout( request->netconn, FALSE, request->receive_timeout );
5894 do {
5896 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5898 buflen = MAX_REPLY_LEN;
5899 if ((res = read_line(request, bufferA, &buflen)))
5900 goto lend;
5902 if (!buflen) goto lend;
5904 rc += buflen;
5905 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5906 /* check is this a status code line? */
5907 if (!strncmpW(buffer, g_szHttp1_0, 4))
5909 /* split the version from the status code */
5910 status_code = strchrW( buffer, ' ' );
5911 if( !status_code )
5912 goto lend;
5913 *status_code++=0;
5915 /* split the status code from the status text */
5916 status_text = strchrW( status_code, ' ' );
5917 if( status_text )
5918 *status_text++=0;
5920 request->status_code = atoiW(status_code);
5922 TRACE("version [%s] status code [%s] status text [%s]\n",
5923 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
5925 codeHundred = request->status_code == HTTP_STATUS_CONTINUE;
5927 else if (!codeHundred)
5929 WARN("No status line at head of response (%s)\n", debugstr_w(buffer));
5931 heap_free(request->version);
5932 heap_free(request->statusText);
5934 request->status_code = HTTP_STATUS_OK;
5935 request->version = heap_strdupW(g_szHttp1_0);
5936 request->statusText = heap_strdupW(szOK);
5938 goto lend;
5940 } while (codeHundred);
5942 /* Add status code */
5943 HTTP_ProcessHeader(request, szStatus, status_code,
5944 HTTP_ADDHDR_FLAG_REPLACE);
5946 heap_free(request->version);
5947 heap_free(request->statusText);
5949 request->version = heap_strdupW(buffer);
5950 request->statusText = heap_strdupW(status_text ? status_text : emptyW);
5952 /* Restore the spaces */
5953 *(status_code-1) = ' ';
5954 if (status_text)
5955 *(status_text-1) = ' ';
5957 /* Parse each response line */
5960 buflen = MAX_REPLY_LEN;
5961 if (!read_line(request, bufferA, &buflen) && buflen)
5963 LPWSTR * pFieldAndValue;
5965 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
5967 if (!bufferA[0]) break;
5968 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5970 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
5971 if (pFieldAndValue)
5973 HTTP_ProcessHeader(request, pFieldAndValue[0], pFieldAndValue[1],
5974 HTTP_ADDREQ_FLAG_ADD );
5975 HTTP_FreeTokens(pFieldAndValue);
5978 else
5980 cbreaks++;
5981 if (cbreaks >= 2)
5982 break;
5984 }while(1);
5986 res = ERROR_SUCCESS;
5988 lend:
5990 *len = rc;
5991 TRACE("<--\n");
5992 return res;
5995 /***********************************************************************
5996 * HTTP_InterpretHttpHeader (internal)
5998 * Parse server response
6000 * RETURNS
6002 * Pointer to array of field, value, NULL on success.
6003 * NULL on error.
6005 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
6007 LPWSTR * pTokenPair;
6008 LPWSTR pszColon;
6009 INT len;
6011 pTokenPair = heap_alloc_zero(sizeof(*pTokenPair)*3);
6013 pszColon = strchrW(buffer, ':');
6014 /* must have two tokens */
6015 if (!pszColon)
6017 HTTP_FreeTokens(pTokenPair);
6018 if (buffer[0])
6019 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
6020 return NULL;
6023 pTokenPair[0] = heap_alloc((pszColon - buffer + 1) * sizeof(WCHAR));
6024 if (!pTokenPair[0])
6026 HTTP_FreeTokens(pTokenPair);
6027 return NULL;
6029 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
6030 pTokenPair[0][pszColon - buffer] = '\0';
6032 /* skip colon */
6033 pszColon++;
6034 len = strlenW(pszColon);
6035 pTokenPair[1] = heap_alloc((len + 1) * sizeof(WCHAR));
6036 if (!pTokenPair[1])
6038 HTTP_FreeTokens(pTokenPair);
6039 return NULL;
6041 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
6043 strip_spaces(pTokenPair[0]);
6044 strip_spaces(pTokenPair[1]);
6046 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
6047 return pTokenPair;
6050 /***********************************************************************
6051 * HTTP_ProcessHeader (internal)
6053 * Stuff header into header tables according to <dwModifier>
6057 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6059 static DWORD HTTP_ProcessHeader(http_request_t *request, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
6061 LPHTTPHEADERW lphttpHdr = NULL;
6062 INT index = -1;
6063 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
6064 DWORD res = ERROR_HTTP_INVALID_HEADER;
6066 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
6068 /* REPLACE wins out over ADD */
6069 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6070 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
6072 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
6073 index = -1;
6074 else
6075 index = HTTP_GetCustomHeaderIndex(request, field, 0, request_only);
6077 if (index >= 0)
6079 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
6080 return ERROR_HTTP_INVALID_HEADER;
6081 lphttpHdr = &request->custHeaders[index];
6083 else if (value)
6085 HTTPHEADERW hdr;
6087 hdr.lpszField = (LPWSTR)field;
6088 hdr.lpszValue = (LPWSTR)value;
6089 hdr.wFlags = hdr.wCount = 0;
6091 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6092 hdr.wFlags |= HDR_ISREQUEST;
6094 return HTTP_InsertCustomHeader(request, &hdr);
6096 /* no value to delete */
6097 else return ERROR_SUCCESS;
6099 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6100 lphttpHdr->wFlags |= HDR_ISREQUEST;
6101 else
6102 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
6104 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6106 HTTP_DeleteCustomHeader( request, index );
6108 if (value && value[0])
6110 HTTPHEADERW hdr;
6112 hdr.lpszField = (LPWSTR)field;
6113 hdr.lpszValue = (LPWSTR)value;
6114 hdr.wFlags = hdr.wCount = 0;
6116 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6117 hdr.wFlags |= HDR_ISREQUEST;
6119 return HTTP_InsertCustomHeader(request, &hdr);
6122 return ERROR_SUCCESS;
6124 else if (dwModifier & COALESCEFLAGS)
6126 LPWSTR lpsztmp;
6127 WCHAR ch = 0;
6128 INT len = 0;
6129 INT origlen = strlenW(lphttpHdr->lpszValue);
6130 INT valuelen = strlenW(value);
6132 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
6134 ch = ',';
6135 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6137 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6139 ch = ';';
6140 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6143 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
6145 lpsztmp = heap_realloc(lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
6146 if (lpsztmp)
6148 lphttpHdr->lpszValue = lpsztmp;
6149 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6150 if (ch > 0)
6152 lphttpHdr->lpszValue[origlen] = ch;
6153 origlen++;
6154 lphttpHdr->lpszValue[origlen] = ' ';
6155 origlen++;
6158 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
6159 lphttpHdr->lpszValue[len] = '\0';
6160 res = ERROR_SUCCESS;
6162 else
6164 WARN("heap_realloc (%d bytes) failed\n",len+1);
6165 res = ERROR_OUTOFMEMORY;
6168 TRACE("<-- %d\n", res);
6169 return res;
6172 /***********************************************************************
6173 * HTTP_GetCustomHeaderIndex (internal)
6175 * Return index of custom header from header array
6178 static INT HTTP_GetCustomHeaderIndex(http_request_t *request, LPCWSTR lpszField,
6179 int requested_index, BOOL request_only)
6181 DWORD index;
6183 TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
6185 for (index = 0; index < request->nCustHeaders; index++)
6187 if (strcmpiW(request->custHeaders[index].lpszField, lpszField))
6188 continue;
6190 if (request_only && !(request->custHeaders[index].wFlags & HDR_ISREQUEST))
6191 continue;
6193 if (!request_only && (request->custHeaders[index].wFlags & HDR_ISREQUEST))
6194 continue;
6196 if (requested_index == 0)
6197 break;
6198 requested_index --;
6201 if (index >= request->nCustHeaders)
6202 index = -1;
6204 TRACE("Return: %d\n", index);
6205 return index;
6209 /***********************************************************************
6210 * HTTP_InsertCustomHeader (internal)
6212 * Insert header into array
6215 static DWORD HTTP_InsertCustomHeader(http_request_t *request, LPHTTPHEADERW lpHdr)
6217 INT count;
6218 LPHTTPHEADERW lph = NULL;
6220 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
6221 count = request->nCustHeaders + 1;
6222 if (count > 1)
6223 lph = heap_realloc_zero(request->custHeaders, sizeof(HTTPHEADERW) * count);
6224 else
6225 lph = heap_alloc_zero(sizeof(HTTPHEADERW) * count);
6227 if (!lph)
6228 return ERROR_OUTOFMEMORY;
6230 request->custHeaders = lph;
6231 request->custHeaders[count-1].lpszField = heap_strdupW(lpHdr->lpszField);
6232 request->custHeaders[count-1].lpszValue = heap_strdupW(lpHdr->lpszValue);
6233 request->custHeaders[count-1].wFlags = lpHdr->wFlags;
6234 request->custHeaders[count-1].wCount= lpHdr->wCount;
6235 request->nCustHeaders++;
6237 return ERROR_SUCCESS;
6241 /***********************************************************************
6242 * HTTP_DeleteCustomHeader (internal)
6244 * Delete header from array
6245 * If this function is called, the indexs may change.
6247 static BOOL HTTP_DeleteCustomHeader(http_request_t *request, DWORD index)
6249 if( request->nCustHeaders <= 0 )
6250 return FALSE;
6251 if( index >= request->nCustHeaders )
6252 return FALSE;
6253 request->nCustHeaders--;
6255 heap_free(request->custHeaders[index].lpszField);
6256 heap_free(request->custHeaders[index].lpszValue);
6258 memmove( &request->custHeaders[index], &request->custHeaders[index+1],
6259 (request->nCustHeaders - index)* sizeof(HTTPHEADERW) );
6260 memset( &request->custHeaders[request->nCustHeaders], 0, sizeof(HTTPHEADERW) );
6262 return TRUE;
6266 /***********************************************************************
6267 * HTTP_VerifyValidHeader (internal)
6269 * Verify the given header is not invalid for the given http request
6272 static BOOL HTTP_VerifyValidHeader(http_request_t *request, LPCWSTR field)
6274 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
6275 if (!strcmpW(request->version, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
6276 return ERROR_HTTP_INVALID_HEADER;
6278 return ERROR_SUCCESS;
6281 /***********************************************************************
6282 * IsHostInProxyBypassList (@)
6284 * Undocumented
6287 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
6289 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
6290 return FALSE;