oledb32: GetConversionSize only returns a valid size of BSTR.
[wine.git] / dlls / wininet / http.c
bloba0e4973990e6d0a7c80f5e6f5b1aca8120c16544
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 #define HTTP_REFERER szReferer
145 #define HTTP_ACCEPT szAccept
146 #define HTTP_USERAGENT szUser_Agent
148 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
149 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
150 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
151 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
152 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
153 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
154 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
156 #define COLLECT_TIME 60000
158 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
160 struct HttpAuthInfo
162 LPWSTR scheme;
163 CredHandle cred;
164 CtxtHandle ctx;
165 TimeStamp exp;
166 ULONG attr;
167 ULONG max_token;
168 void *auth_data;
169 unsigned int auth_data_len;
170 BOOL finished; /* finished authenticating */
174 typedef struct _basicAuthorizationData
176 struct list entry;
178 LPWSTR host;
179 LPWSTR realm;
180 LPSTR authorization;
181 UINT authorizationLen;
182 } basicAuthorizationData;
184 typedef struct _authorizationData
186 struct list entry;
188 LPWSTR host;
189 LPWSTR scheme;
190 LPWSTR domain;
191 UINT domain_len;
192 LPWSTR user;
193 UINT user_len;
194 LPWSTR password;
195 UINT password_len;
196 } authorizationData;
198 static struct list basicAuthorizationCache = LIST_INIT(basicAuthorizationCache);
199 static struct list authorizationCache = LIST_INIT(authorizationCache);
201 static CRITICAL_SECTION authcache_cs;
202 static CRITICAL_SECTION_DEBUG critsect_debug =
204 0, 0, &authcache_cs,
205 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
206 0, 0, { (DWORD_PTR)(__FILE__ ": authcache_cs") }
208 static CRITICAL_SECTION authcache_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
210 static DWORD HTTP_GetResponseHeaders(http_request_t *req, INT *len);
211 static DWORD HTTP_ProcessHeader(http_request_t *req, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
212 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
213 static DWORD HTTP_InsertCustomHeader(http_request_t *req, LPHTTPHEADERW lpHdr);
214 static INT HTTP_GetCustomHeaderIndex(http_request_t *req, LPCWSTR lpszField, INT index, BOOL Request);
215 static BOOL HTTP_DeleteCustomHeader(http_request_t *req, DWORD index);
216 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
217 static DWORD HTTP_HttpQueryInfoW(http_request_t*, DWORD, LPVOID, LPDWORD, LPDWORD);
218 static LPWSTR HTTP_GetRedirectURL(http_request_t *req, LPCWSTR lpszUrl);
219 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
220 static BOOL HTTP_VerifyValidHeader(http_request_t *req, LPCWSTR field);
221 static BOOL drain_content(http_request_t*,BOOL);
223 static CRITICAL_SECTION connection_pool_cs;
224 static CRITICAL_SECTION_DEBUG connection_pool_debug =
226 0, 0, &connection_pool_cs,
227 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
228 0, 0, { (DWORD_PTR)(__FILE__ ": connection_pool_cs") }
230 static CRITICAL_SECTION connection_pool_cs = { &connection_pool_debug, -1, 0, 0, 0, 0 };
232 static struct list connection_pool = LIST_INIT(connection_pool);
233 static BOOL collector_running;
235 void server_addref(server_t *server)
237 InterlockedIncrement(&server->ref);
240 void server_release(server_t *server)
242 if(InterlockedDecrement(&server->ref))
243 return;
245 list_remove(&server->entry);
247 if(server->cert_chain)
248 CertFreeCertificateChain(server->cert_chain);
249 heap_free(server->name);
250 heap_free(server->scheme_host_port);
251 heap_free(server);
254 static BOOL process_host_port(server_t *server)
256 BOOL default_port;
257 size_t name_len;
258 WCHAR *buf;
260 static const WCHAR httpW[] = {'h','t','t','p',0};
261 static const WCHAR httpsW[] = {'h','t','t','p','s',0};
262 static const WCHAR formatW[] = {'%','s',':','/','/','%','s',':','%','u',0};
264 name_len = strlenW(server->name);
265 buf = heap_alloc((name_len + 10 /* strlen("://:<port>") */)*sizeof(WCHAR) + sizeof(httpsW));
266 if(!buf)
267 return FALSE;
269 sprintfW(buf, formatW, server->is_https ? httpsW : httpW, server->name, server->port);
270 server->scheme_host_port = buf;
272 server->host_port = server->scheme_host_port + 7 /* strlen("http://") */;
273 if(server->is_https)
274 server->host_port++;
276 default_port = server->port == (server->is_https ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT);
277 server->canon_host_port = default_port ? server->name : server->host_port;
278 return TRUE;
281 server_t *get_server(const WCHAR *name, INTERNET_PORT port, BOOL is_https, BOOL do_create)
283 server_t *iter, *server = NULL;
285 if(port == INTERNET_INVALID_PORT_NUMBER)
286 port = INTERNET_DEFAULT_HTTP_PORT;
288 EnterCriticalSection(&connection_pool_cs);
290 LIST_FOR_EACH_ENTRY(iter, &connection_pool, server_t, entry) {
291 if(iter->port == port && !strcmpW(iter->name, name) && iter->is_https == is_https) {
292 server = iter;
293 server_addref(server);
294 break;
298 if(!server && do_create) {
299 server = heap_alloc_zero(sizeof(*server));
300 if(server) {
301 server->ref = 2; /* list reference and return */
302 server->port = port;
303 server->is_https = is_https;
304 list_init(&server->conn_pool);
305 server->name = heap_strdupW(name);
306 if(server->name && process_host_port(server)) {
307 list_add_head(&connection_pool, &server->entry);
308 }else {
309 heap_free(server);
310 server = NULL;
315 LeaveCriticalSection(&connection_pool_cs);
317 return server;
320 BOOL collect_connections(collect_type_t collect_type)
322 netconn_t *netconn, *netconn_safe;
323 server_t *server, *server_safe;
324 BOOL remaining = FALSE;
325 DWORD64 now;
327 now = GetTickCount64();
329 LIST_FOR_EACH_ENTRY_SAFE(server, server_safe, &connection_pool, server_t, entry) {
330 LIST_FOR_EACH_ENTRY_SAFE(netconn, netconn_safe, &server->conn_pool, netconn_t, pool_entry) {
331 if(collect_type > COLLECT_TIMEOUT || netconn->keep_until < now) {
332 TRACE("freeing %p\n", netconn);
333 list_remove(&netconn->pool_entry);
334 free_netconn(netconn);
335 }else {
336 remaining = TRUE;
340 if(collect_type == COLLECT_CLEANUP) {
341 list_remove(&server->entry);
342 list_init(&server->entry);
343 server_release(server);
347 return remaining;
350 static DWORD WINAPI collect_connections_proc(void *arg)
352 BOOL remaining_conns;
354 do {
355 /* FIXME: Use more sophisticated method */
356 Sleep(5000);
358 EnterCriticalSection(&connection_pool_cs);
360 remaining_conns = collect_connections(COLLECT_TIMEOUT);
361 if(!remaining_conns)
362 collector_running = FALSE;
364 LeaveCriticalSection(&connection_pool_cs);
365 }while(remaining_conns);
367 FreeLibraryAndExitThread(WININET_hModule, 0);
370 static LPHTTPHEADERW HTTP_GetHeader(http_request_t *req, LPCWSTR head)
372 int HeaderIndex = 0;
373 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
374 if (HeaderIndex == -1)
375 return NULL;
376 else
377 return &req->custHeaders[HeaderIndex];
380 typedef enum {
381 READMODE_SYNC,
382 READMODE_ASYNC,
383 READMODE_NOBLOCK
384 } read_mode_t;
386 struct data_stream_vtbl_t {
387 DWORD (*get_avail_data)(data_stream_t*,http_request_t*);
388 BOOL (*end_of_data)(data_stream_t*,http_request_t*);
389 DWORD (*read)(data_stream_t*,http_request_t*,BYTE*,DWORD,DWORD*,read_mode_t);
390 BOOL (*drain_content)(data_stream_t*,http_request_t*);
391 void (*destroy)(data_stream_t*);
394 typedef struct {
395 data_stream_t data_stream;
397 BYTE buf[READ_BUFFER_SIZE];
398 DWORD buf_size;
399 DWORD buf_pos;
400 DWORD chunk_size;
401 } chunked_stream_t;
403 static inline void destroy_data_stream(data_stream_t *stream)
405 stream->vtbl->destroy(stream);
408 static void reset_data_stream(http_request_t *req)
410 destroy_data_stream(req->data_stream);
411 req->data_stream = &req->netconn_stream.data_stream;
412 req->read_pos = req->read_size = req->netconn_stream.content_read = 0;
413 req->read_chunked = req->read_gzip = FALSE;
416 #ifdef HAVE_ZLIB
418 typedef struct {
419 data_stream_t stream;
420 data_stream_t *parent_stream;
421 z_stream zstream;
422 BYTE buf[READ_BUFFER_SIZE];
423 DWORD buf_size;
424 DWORD buf_pos;
425 BOOL end_of_data;
426 } gzip_stream_t;
428 static DWORD gzip_get_avail_data(data_stream_t *stream, http_request_t *req)
430 /* Allow reading only from read buffer */
431 return 0;
434 static BOOL gzip_end_of_data(data_stream_t *stream, http_request_t *req)
436 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
437 return gzip_stream->end_of_data;
440 static DWORD gzip_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
441 DWORD *read, read_mode_t read_mode)
443 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
444 z_stream *zstream = &gzip_stream->zstream;
445 DWORD current_read, ret_read = 0;
446 BOOL end;
447 int zres;
448 DWORD res = ERROR_SUCCESS;
450 while(size && !gzip_stream->end_of_data) {
451 end = gzip_stream->parent_stream->vtbl->end_of_data(gzip_stream->parent_stream, req);
453 if(gzip_stream->buf_size <= 64 && !end) {
454 if(gzip_stream->buf_pos) {
455 if(gzip_stream->buf_size)
456 memmove(gzip_stream->buf, gzip_stream->buf+gzip_stream->buf_pos, gzip_stream->buf_size);
457 gzip_stream->buf_pos = 0;
459 res = gzip_stream->parent_stream->vtbl->read(gzip_stream->parent_stream, req, gzip_stream->buf+gzip_stream->buf_size,
460 sizeof(gzip_stream->buf)-gzip_stream->buf_size, &current_read, read_mode);
461 gzip_stream->buf_size += current_read;
462 if(res != ERROR_SUCCESS)
463 break;
464 end = gzip_stream->parent_stream->vtbl->end_of_data(gzip_stream->parent_stream, req);
465 if(!current_read && !end) {
466 if(read_mode != READMODE_NOBLOCK) {
467 WARN("unexpected end of data\n");
468 gzip_stream->end_of_data = TRUE;
470 break;
472 if(gzip_stream->buf_size <= 64 && !end)
473 continue;
476 zstream->next_in = gzip_stream->buf+gzip_stream->buf_pos;
477 zstream->avail_in = gzip_stream->buf_size-(end ? 0 : 64);
478 zstream->next_out = buf+ret_read;
479 zstream->avail_out = size;
480 zres = inflate(&gzip_stream->zstream, 0);
481 current_read = size - zstream->avail_out;
482 size -= current_read;
483 ret_read += current_read;
484 gzip_stream->buf_size -= zstream->next_in - (gzip_stream->buf+gzip_stream->buf_pos);
485 gzip_stream->buf_pos = zstream->next_in-gzip_stream->buf;
486 if(zres == Z_STREAM_END) {
487 TRACE("end of data\n");
488 gzip_stream->end_of_data = TRUE;
489 inflateEnd(zstream);
490 }else if(zres != Z_OK) {
491 WARN("inflate failed %d: %s\n", zres, debugstr_a(zstream->msg));
492 if(!ret_read)
493 res = ERROR_INTERNET_DECODING_FAILED;
494 break;
497 if(ret_read && read_mode == READMODE_ASYNC)
498 read_mode = READMODE_NOBLOCK;
501 TRACE("read %u bytes\n", ret_read);
502 *read = ret_read;
503 return res;
506 static BOOL gzip_drain_content(data_stream_t *stream, http_request_t *req)
508 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
509 return gzip_stream->parent_stream->vtbl->drain_content(gzip_stream->parent_stream, req);
512 static void gzip_destroy(data_stream_t *stream)
514 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
516 destroy_data_stream(gzip_stream->parent_stream);
518 if(!gzip_stream->end_of_data)
519 inflateEnd(&gzip_stream->zstream);
520 heap_free(gzip_stream);
523 static const data_stream_vtbl_t gzip_stream_vtbl = {
524 gzip_get_avail_data,
525 gzip_end_of_data,
526 gzip_read,
527 gzip_drain_content,
528 gzip_destroy
531 static voidpf wininet_zalloc(voidpf opaque, uInt items, uInt size)
533 return heap_alloc(items*size);
536 static void wininet_zfree(voidpf opaque, voidpf address)
538 heap_free(address);
541 static DWORD init_gzip_stream(http_request_t *req)
543 gzip_stream_t *gzip_stream;
544 int index, zres;
546 gzip_stream = heap_alloc_zero(sizeof(gzip_stream_t));
547 if(!gzip_stream)
548 return ERROR_OUTOFMEMORY;
550 gzip_stream->stream.vtbl = &gzip_stream_vtbl;
551 gzip_stream->zstream.zalloc = wininet_zalloc;
552 gzip_stream->zstream.zfree = wininet_zfree;
554 zres = inflateInit2(&gzip_stream->zstream, 0x1f);
555 if(zres != Z_OK) {
556 ERR("inflateInit failed: %d\n", zres);
557 heap_free(gzip_stream);
558 return ERROR_OUTOFMEMORY;
561 index = HTTP_GetCustomHeaderIndex(req, szContent_Length, 0, FALSE);
562 if(index != -1)
563 HTTP_DeleteCustomHeader(req, index);
565 if(req->read_size) {
566 memcpy(gzip_stream->buf, req->read_buf+req->read_pos, req->read_size);
567 gzip_stream->buf_size = req->read_size;
568 req->read_pos = req->read_size = 0;
571 req->read_gzip = TRUE;
572 gzip_stream->parent_stream = req->data_stream;
573 req->data_stream = &gzip_stream->stream;
574 return ERROR_SUCCESS;
577 #else
579 static DWORD init_gzip_stream(http_request_t *req)
581 ERR("gzip stream not supported, missing zlib.\n");
582 return ERROR_SUCCESS;
585 #endif
587 /***********************************************************************
588 * HTTP_FreeTokens (internal)
590 * Frees table of pointers.
592 static void HTTP_FreeTokens(LPWSTR * token_array)
594 int i;
595 for (i = 0; token_array[i]; i++) heap_free(token_array[i]);
596 heap_free(token_array);
599 static void HTTP_FixURL(http_request_t *request)
601 static const WCHAR szSlash[] = { '/',0 };
602 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
604 /* If we don't have a path we set it to root */
605 if (NULL == request->path)
606 request->path = heap_strdupW(szSlash);
607 else /* remove \r and \n*/
609 int nLen = strlenW(request->path);
610 while ((nLen >0 ) && ((request->path[nLen-1] == '\r')||(request->path[nLen-1] == '\n')))
612 nLen--;
613 request->path[nLen]='\0';
615 /* Replace '\' with '/' */
616 while (nLen>0) {
617 nLen--;
618 if (request->path[nLen] == '\\') request->path[nLen]='/';
622 if(CSTR_EQUAL != CompareStringW( LOCALE_INVARIANT, NORM_IGNORECASE,
623 request->path, strlenW(request->path), szHttp, strlenW(szHttp) )
624 && request->path[0] != '/') /* not an absolute path ?? --> fix it !! */
626 WCHAR *fixurl = heap_alloc((strlenW(request->path) + 2)*sizeof(WCHAR));
627 *fixurl = '/';
628 strcpyW(fixurl + 1, request->path);
629 heap_free( request->path );
630 request->path = fixurl;
634 static WCHAR* build_request_header(http_request_t *request, const WCHAR *verb,
635 const WCHAR *path, const WCHAR *version, BOOL use_cr)
637 LPWSTR requestString;
638 DWORD len, n;
639 LPCWSTR *req;
640 UINT i;
642 static const WCHAR szSpace[] = { ' ',0 };
643 static const WCHAR szColon[] = { ':',' ',0 };
644 static const WCHAR szCr[] = { '\r',0 };
645 static const WCHAR szLf[] = { '\n',0 };
647 /* allocate space for an array of all the string pointers to be added */
648 len = (request->nCustHeaders)*5 + 10;
649 req = heap_alloc(len*sizeof(LPCWSTR));
651 /* add the verb, path and HTTP version string */
652 n = 0;
653 req[n++] = verb;
654 req[n++] = szSpace;
655 req[n++] = path;
656 req[n++] = szSpace;
657 req[n++] = version;
658 if (use_cr)
659 req[n++] = szCr;
660 req[n++] = szLf;
662 /* Append custom request headers */
663 for (i = 0; i < request->nCustHeaders; i++)
665 if (request->custHeaders[i].wFlags & HDR_ISREQUEST)
667 req[n++] = request->custHeaders[i].lpszField;
668 req[n++] = szColon;
669 req[n++] = request->custHeaders[i].lpszValue;
670 if (use_cr)
671 req[n++] = szCr;
672 req[n++] = szLf;
674 TRACE("Adding custom header %s (%s)\n",
675 debugstr_w(request->custHeaders[i].lpszField),
676 debugstr_w(request->custHeaders[i].lpszValue));
679 if (use_cr)
680 req[n++] = szCr;
681 req[n++] = szLf;
682 req[n] = NULL;
684 requestString = HTTP_build_req( req, 4 );
685 heap_free( req );
686 return requestString;
689 static WCHAR* build_response_header(http_request_t *request, BOOL use_cr)
691 static const WCHAR colonW[] = { ':',' ',0 };
692 static const WCHAR crW[] = { '\r',0 };
693 static const WCHAR lfW[] = { '\n',0 };
694 static const WCHAR status_fmt[] = { ' ','%','u',' ',0 };
696 const WCHAR **req;
697 WCHAR *ret, buf[14];
698 DWORD i, n = 0;
700 req = heap_alloc((request->nCustHeaders*5+8)*sizeof(WCHAR*));
701 if(!req)
702 return NULL;
704 if (request->status_code)
706 req[n++] = request->version;
707 sprintfW(buf, status_fmt, request->status_code);
708 req[n++] = buf;
709 req[n++] = request->statusText;
710 if (use_cr)
711 req[n++] = crW;
712 req[n++] = lfW;
715 for(i = 0; i < request->nCustHeaders; i++)
717 if(!(request->custHeaders[i].wFlags & HDR_ISREQUEST)
718 && strcmpW(request->custHeaders[i].lpszField, szStatus))
720 req[n++] = request->custHeaders[i].lpszField;
721 req[n++] = colonW;
722 req[n++] = request->custHeaders[i].lpszValue;
723 if(use_cr)
724 req[n++] = crW;
725 req[n++] = lfW;
727 TRACE("Adding custom header %s (%s)\n",
728 debugstr_w(request->custHeaders[i].lpszField),
729 debugstr_w(request->custHeaders[i].lpszValue));
732 if(use_cr)
733 req[n++] = crW;
734 req[n++] = lfW;
735 req[n] = NULL;
737 ret = HTTP_build_req(req, 0);
738 heap_free(req);
739 return ret;
742 static void HTTP_ProcessCookies( http_request_t *request )
744 int HeaderIndex;
745 int numCookies = 0;
746 LPHTTPHEADERW setCookieHeader;
748 if(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES)
749 return;
751 while((HeaderIndex = HTTP_GetCustomHeaderIndex(request, szSet_Cookie, numCookies++, FALSE)) != -1)
753 HTTPHEADERW *host;
754 const WCHAR *data;
755 WCHAR *name;
757 setCookieHeader = &request->custHeaders[HeaderIndex];
759 if (!setCookieHeader->lpszValue)
760 continue;
762 host = HTTP_GetHeader(request, hostW);
763 if(!host)
764 continue;
766 data = strchrW(setCookieHeader->lpszValue, '=');
767 if(!data)
768 continue;
770 name = heap_strndupW(setCookieHeader->lpszValue, data-setCookieHeader->lpszValue);
771 if(!name)
772 continue;
774 data++;
775 set_cookie(host->lpszValue, request->path, name, data);
776 heap_free(name);
780 static void strip_spaces(LPWSTR start)
782 LPWSTR str = start;
783 LPWSTR end;
785 while (*str == ' ' && *str != '\0')
786 str++;
788 if (str != start)
789 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
791 end = start + strlenW(start) - 1;
792 while (end >= start && *end == ' ')
794 *end = '\0';
795 end--;
799 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue, LPWSTR *pszRealm )
801 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
802 static const WCHAR szRealm[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
803 BOOL is_basic;
804 is_basic = !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
805 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
806 if (is_basic && pszRealm)
808 LPCWSTR token;
809 LPCWSTR ptr = &pszAuthValue[ARRAYSIZE(szBasic)];
810 LPCWSTR realm;
811 ptr++;
812 *pszRealm=NULL;
813 token = strchrW(ptr,'=');
814 if (!token)
815 return TRUE;
816 realm = ptr;
817 while (*realm == ' ' && *realm != '\0')
818 realm++;
819 if(!strncmpiW(realm, szRealm, ARRAYSIZE(szRealm)) &&
820 (realm[ARRAYSIZE(szRealm)] == ' ' || realm[ARRAYSIZE(szRealm)] == '='))
822 token++;
823 while (*token == ' ' && *token != '\0')
824 token++;
825 if (*token == '\0')
826 return TRUE;
827 *pszRealm = heap_strdupW(token);
828 strip_spaces(*pszRealm);
832 return is_basic;
835 static void destroy_authinfo( struct HttpAuthInfo *authinfo )
837 if (!authinfo) return;
839 if (SecIsValidHandle(&authinfo->ctx))
840 DeleteSecurityContext(&authinfo->ctx);
841 if (SecIsValidHandle(&authinfo->cred))
842 FreeCredentialsHandle(&authinfo->cred);
844 heap_free(authinfo->auth_data);
845 heap_free(authinfo->scheme);
846 heap_free(authinfo);
849 static UINT retrieve_cached_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR *auth_data)
851 basicAuthorizationData *ad;
852 UINT rc = 0;
854 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host),debugstr_w(realm));
856 EnterCriticalSection(&authcache_cs);
857 LIST_FOR_EACH_ENTRY(ad, &basicAuthorizationCache, basicAuthorizationData, entry)
859 if (!strcmpiW(host,ad->host) && !strcmpW(realm,ad->realm))
861 TRACE("Authorization found in cache\n");
862 *auth_data = heap_alloc(ad->authorizationLen);
863 memcpy(*auth_data,ad->authorization,ad->authorizationLen);
864 rc = ad->authorizationLen;
865 break;
868 LeaveCriticalSection(&authcache_cs);
869 return rc;
872 static void cache_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR auth_data, UINT auth_data_len)
874 struct list *cursor;
875 basicAuthorizationData* ad = NULL;
877 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host),debugstr_w(realm),debugstr_an(auth_data,auth_data_len));
879 EnterCriticalSection(&authcache_cs);
880 LIST_FOR_EACH(cursor, &basicAuthorizationCache)
882 basicAuthorizationData *check = LIST_ENTRY(cursor,basicAuthorizationData,entry);
883 if (!strcmpiW(host,check->host) && !strcmpW(realm,check->realm))
885 ad = check;
886 break;
890 if (ad)
892 TRACE("Found match in cache, replacing\n");
893 heap_free(ad->authorization);
894 ad->authorization = heap_alloc(auth_data_len);
895 memcpy(ad->authorization, auth_data, auth_data_len);
896 ad->authorizationLen = auth_data_len;
898 else
900 ad = heap_alloc(sizeof(basicAuthorizationData));
901 ad->host = heap_strdupW(host);
902 ad->realm = heap_strdupW(realm);
903 ad->authorization = heap_alloc(auth_data_len);
904 memcpy(ad->authorization, auth_data, auth_data_len);
905 ad->authorizationLen = auth_data_len;
906 list_add_head(&basicAuthorizationCache,&ad->entry);
907 TRACE("authorization cached\n");
909 LeaveCriticalSection(&authcache_cs);
912 static BOOL retrieve_cached_authorization(LPWSTR host, LPWSTR scheme,
913 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
915 authorizationData *ad;
917 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
919 EnterCriticalSection(&authcache_cs);
920 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry) {
921 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
922 TRACE("Authorization found in cache\n");
924 nt_auth_identity->User = heap_strdupW(ad->user);
925 nt_auth_identity->Password = heap_strdupW(ad->password);
926 nt_auth_identity->Domain = heap_alloc(sizeof(WCHAR)*ad->domain_len);
927 if(!nt_auth_identity->User || !nt_auth_identity->Password ||
928 (!nt_auth_identity->Domain && ad->domain_len)) {
929 heap_free(nt_auth_identity->User);
930 heap_free(nt_auth_identity->Password);
931 heap_free(nt_auth_identity->Domain);
932 break;
935 nt_auth_identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
936 nt_auth_identity->UserLength = ad->user_len;
937 nt_auth_identity->PasswordLength = ad->password_len;
938 memcpy(nt_auth_identity->Domain, ad->domain, sizeof(WCHAR)*ad->domain_len);
939 nt_auth_identity->DomainLength = ad->domain_len;
940 LeaveCriticalSection(&authcache_cs);
941 return TRUE;
944 LeaveCriticalSection(&authcache_cs);
946 return FALSE;
949 static void cache_authorization(LPWSTR host, LPWSTR scheme,
950 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
952 authorizationData *ad;
953 BOOL found = FALSE;
955 TRACE("Caching authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
957 EnterCriticalSection(&authcache_cs);
958 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry)
959 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
960 found = TRUE;
961 break;
964 if(found) {
965 heap_free(ad->user);
966 heap_free(ad->password);
967 heap_free(ad->domain);
968 } else {
969 ad = heap_alloc(sizeof(authorizationData));
970 if(!ad) {
971 LeaveCriticalSection(&authcache_cs);
972 return;
975 ad->host = heap_strdupW(host);
976 ad->scheme = heap_strdupW(scheme);
977 list_add_head(&authorizationCache, &ad->entry);
980 ad->user = heap_strndupW(nt_auth_identity->User, nt_auth_identity->UserLength);
981 ad->password = heap_strndupW(nt_auth_identity->Password, nt_auth_identity->PasswordLength);
982 ad->domain = heap_strndupW(nt_auth_identity->Domain, nt_auth_identity->DomainLength);
983 ad->user_len = nt_auth_identity->UserLength;
984 ad->password_len = nt_auth_identity->PasswordLength;
985 ad->domain_len = nt_auth_identity->DomainLength;
987 if(!ad->host || !ad->scheme || !ad->user || !ad->password
988 || (nt_auth_identity->Domain && !ad->domain)) {
989 heap_free(ad->host);
990 heap_free(ad->scheme);
991 heap_free(ad->user);
992 heap_free(ad->password);
993 heap_free(ad->domain);
994 list_remove(&ad->entry);
995 heap_free(ad);
998 LeaveCriticalSection(&authcache_cs);
1001 static BOOL HTTP_DoAuthorization( http_request_t *request, LPCWSTR pszAuthValue,
1002 struct HttpAuthInfo **ppAuthInfo,
1003 LPWSTR domain_and_username, LPWSTR password,
1004 LPWSTR host )
1006 SECURITY_STATUS sec_status;
1007 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
1008 BOOL first = FALSE;
1009 LPWSTR szRealm = NULL;
1011 TRACE("%s\n", debugstr_w(pszAuthValue));
1013 if (!pAuthInfo)
1015 TimeStamp exp;
1017 first = TRUE;
1018 pAuthInfo = heap_alloc(sizeof(*pAuthInfo));
1019 if (!pAuthInfo)
1020 return FALSE;
1022 SecInvalidateHandle(&pAuthInfo->cred);
1023 SecInvalidateHandle(&pAuthInfo->ctx);
1024 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
1025 pAuthInfo->attr = 0;
1026 pAuthInfo->auth_data = NULL;
1027 pAuthInfo->auth_data_len = 0;
1028 pAuthInfo->finished = FALSE;
1030 if (is_basic_auth_value(pszAuthValue,NULL))
1032 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
1033 pAuthInfo->scheme = heap_strdupW(szBasic);
1034 if (!pAuthInfo->scheme)
1036 heap_free(pAuthInfo);
1037 return FALSE;
1040 else
1042 PVOID pAuthData;
1043 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
1045 pAuthInfo->scheme = heap_strdupW(pszAuthValue);
1046 if (!pAuthInfo->scheme)
1048 heap_free(pAuthInfo);
1049 return FALSE;
1052 if (domain_and_username)
1054 WCHAR *user = strchrW(domain_and_username, '\\');
1055 WCHAR *domain = domain_and_username;
1057 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1059 pAuthData = &nt_auth_identity;
1061 if (user) user++;
1062 else
1064 user = domain_and_username;
1065 domain = NULL;
1068 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1069 nt_auth_identity.User = user;
1070 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
1071 nt_auth_identity.Domain = domain;
1072 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
1073 nt_auth_identity.Password = password;
1074 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
1076 cache_authorization(host, pAuthInfo->scheme, &nt_auth_identity);
1078 else if(retrieve_cached_authorization(host, pAuthInfo->scheme, &nt_auth_identity))
1079 pAuthData = &nt_auth_identity;
1080 else
1081 /* use default credentials */
1082 pAuthData = NULL;
1084 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
1085 SECPKG_CRED_OUTBOUND, NULL,
1086 pAuthData, NULL,
1087 NULL, &pAuthInfo->cred,
1088 &exp);
1090 if(pAuthData && !domain_and_username) {
1091 heap_free(nt_auth_identity.User);
1092 heap_free(nt_auth_identity.Domain);
1093 heap_free(nt_auth_identity.Password);
1096 if (sec_status == SEC_E_OK)
1098 PSecPkgInfoW sec_pkg_info;
1099 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
1100 if (sec_status == SEC_E_OK)
1102 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
1103 FreeContextBuffer(sec_pkg_info);
1106 if (sec_status != SEC_E_OK)
1108 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1109 debugstr_w(pAuthInfo->scheme), sec_status);
1110 heap_free(pAuthInfo->scheme);
1111 heap_free(pAuthInfo);
1112 return FALSE;
1115 *ppAuthInfo = pAuthInfo;
1117 else if (pAuthInfo->finished)
1118 return FALSE;
1120 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
1121 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
1123 ERR("authentication scheme changed from %s to %s\n",
1124 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
1125 return FALSE;
1128 if (is_basic_auth_value(pszAuthValue,&szRealm))
1130 int userlen;
1131 int passlen;
1132 char *auth_data = NULL;
1133 UINT auth_data_len = 0;
1135 TRACE("basic authentication realm %s\n",debugstr_w(szRealm));
1137 if (!domain_and_username)
1139 if (host && szRealm)
1140 auth_data_len = retrieve_cached_basic_authorization(host, szRealm,&auth_data);
1141 if (auth_data_len == 0)
1143 heap_free(szRealm);
1144 return FALSE;
1147 else
1149 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
1150 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
1152 /* length includes a nul terminator, which will be re-used for the ':' */
1153 auth_data = heap_alloc(userlen + 1 + passlen);
1154 if (!auth_data)
1156 heap_free(szRealm);
1157 return FALSE;
1160 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
1161 auth_data[userlen] = ':';
1162 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
1163 auth_data_len = userlen + 1 + passlen;
1164 if (host && szRealm)
1165 cache_basic_authorization(host, szRealm, auth_data, auth_data_len);
1168 pAuthInfo->auth_data = auth_data;
1169 pAuthInfo->auth_data_len = auth_data_len;
1170 pAuthInfo->finished = TRUE;
1171 heap_free(szRealm);
1172 return TRUE;
1174 else
1176 LPCWSTR pszAuthData;
1177 SecBufferDesc out_desc, in_desc;
1178 SecBuffer out, in;
1179 unsigned char *buffer;
1180 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
1181 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
1183 in.BufferType = SECBUFFER_TOKEN;
1184 in.cbBuffer = 0;
1185 in.pvBuffer = NULL;
1187 in_desc.ulVersion = 0;
1188 in_desc.cBuffers = 1;
1189 in_desc.pBuffers = &in;
1191 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
1192 if (*pszAuthData == ' ')
1194 pszAuthData++;
1195 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
1196 in.pvBuffer = heap_alloc(in.cbBuffer);
1197 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
1200 buffer = heap_alloc(pAuthInfo->max_token);
1202 out.BufferType = SECBUFFER_TOKEN;
1203 out.cbBuffer = pAuthInfo->max_token;
1204 out.pvBuffer = buffer;
1206 out_desc.ulVersion = 0;
1207 out_desc.cBuffers = 1;
1208 out_desc.pBuffers = &out;
1210 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
1211 first ? NULL : &pAuthInfo->ctx,
1212 first ? request->server->name : NULL,
1213 context_req, 0, SECURITY_NETWORK_DREP,
1214 in.pvBuffer ? &in_desc : NULL,
1215 0, &pAuthInfo->ctx, &out_desc,
1216 &pAuthInfo->attr, &pAuthInfo->exp);
1217 if (sec_status == SEC_E_OK)
1219 pAuthInfo->finished = TRUE;
1220 pAuthInfo->auth_data = out.pvBuffer;
1221 pAuthInfo->auth_data_len = out.cbBuffer;
1222 TRACE("sending last auth packet\n");
1224 else if (sec_status == SEC_I_CONTINUE_NEEDED)
1226 pAuthInfo->auth_data = out.pvBuffer;
1227 pAuthInfo->auth_data_len = out.cbBuffer;
1228 TRACE("sending next auth packet\n");
1230 else
1232 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
1233 heap_free(out.pvBuffer);
1234 destroy_authinfo(pAuthInfo);
1235 *ppAuthInfo = NULL;
1236 return FALSE;
1240 return TRUE;
1243 /***********************************************************************
1244 * HTTP_HttpAddRequestHeadersW (internal)
1246 static DWORD HTTP_HttpAddRequestHeadersW(http_request_t *request,
1247 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1249 LPWSTR lpszStart;
1250 LPWSTR lpszEnd;
1251 LPWSTR buffer;
1252 DWORD len, res = ERROR_HTTP_INVALID_HEADER;
1254 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
1256 if( dwHeaderLength == ~0U )
1257 len = strlenW(lpszHeader);
1258 else
1259 len = dwHeaderLength;
1260 buffer = heap_alloc(sizeof(WCHAR)*(len+1));
1261 lstrcpynW( buffer, lpszHeader, len + 1);
1263 lpszStart = buffer;
1267 LPWSTR * pFieldAndValue;
1269 lpszEnd = lpszStart;
1271 while (*lpszEnd != '\0')
1273 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1274 break;
1275 lpszEnd++;
1278 if (*lpszStart == '\0')
1279 break;
1281 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1283 *lpszEnd = '\0';
1284 lpszEnd++; /* Jump over newline */
1286 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
1287 if (*lpszStart == '\0')
1289 /* Skip 0-length headers */
1290 lpszStart = lpszEnd;
1291 res = ERROR_SUCCESS;
1292 continue;
1294 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
1295 if (pFieldAndValue)
1297 res = HTTP_VerifyValidHeader(request, pFieldAndValue[0]);
1298 if (res == ERROR_SUCCESS)
1299 res = HTTP_ProcessHeader(request, pFieldAndValue[0],
1300 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
1301 HTTP_FreeTokens(pFieldAndValue);
1304 lpszStart = lpszEnd;
1305 } while (res == ERROR_SUCCESS);
1307 heap_free(buffer);
1308 return res;
1311 /***********************************************************************
1312 * HttpAddRequestHeadersW (WININET.@)
1314 * Adds one or more HTTP header to the request handler
1316 * NOTE
1317 * On Windows if dwHeaderLength includes the trailing '\0', then
1318 * HttpAddRequestHeadersW() adds it too. However this results in an
1319 * invalid HTTP header which is rejected by some servers so we probably
1320 * don't need to match Windows on that point.
1322 * RETURNS
1323 * TRUE on success
1324 * FALSE on failure
1327 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
1328 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1330 http_request_t *request;
1331 DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
1333 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1335 if (!lpszHeader)
1336 return TRUE;
1338 request = (http_request_t*) get_handle_object( hHttpRequest );
1339 if (request && request->hdr.htype == WH_HHTTPREQ)
1340 res = HTTP_HttpAddRequestHeadersW( request, lpszHeader, dwHeaderLength, dwModifier );
1341 if( request )
1342 WININET_Release( &request->hdr );
1344 if(res != ERROR_SUCCESS)
1345 SetLastError(res);
1346 return res == ERROR_SUCCESS;
1349 /***********************************************************************
1350 * HttpAddRequestHeadersA (WININET.@)
1352 * Adds one or more HTTP header to the request handler
1354 * RETURNS
1355 * TRUE on success
1356 * FALSE on failure
1359 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
1360 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1362 DWORD len;
1363 LPWSTR hdr;
1364 BOOL r;
1366 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1368 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
1369 hdr = heap_alloc(len*sizeof(WCHAR));
1370 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
1371 if( dwHeaderLength != ~0U )
1372 dwHeaderLength = len;
1374 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
1376 heap_free( hdr );
1377 return r;
1380 static void free_accept_types( WCHAR **accept_types )
1382 WCHAR *ptr, **types = accept_types;
1384 if (!types) return;
1385 while ((ptr = *types))
1387 heap_free( ptr );
1388 types++;
1390 heap_free( accept_types );
1393 static WCHAR **convert_accept_types( const char **accept_types )
1395 unsigned int count;
1396 const char **types = accept_types;
1397 WCHAR **typesW;
1398 BOOL invalid_pointer = FALSE;
1400 if (!types) return NULL;
1401 count = 0;
1402 while (*types)
1404 __TRY
1406 /* find out how many there are */
1407 if (*types && **types)
1409 TRACE("accept type: %s\n", debugstr_a(*types));
1410 count++;
1413 __EXCEPT_PAGE_FAULT
1415 WARN("invalid accept type pointer\n");
1416 invalid_pointer = TRUE;
1418 __ENDTRY;
1419 types++;
1421 if (invalid_pointer) return NULL;
1422 if (!(typesW = heap_alloc( sizeof(WCHAR *) * (count + 1) ))) return NULL;
1423 count = 0;
1424 types = accept_types;
1425 while (*types)
1427 if (*types && **types) typesW[count++] = heap_strdupAtoW( *types );
1428 types++;
1430 typesW[count] = NULL;
1431 return typesW;
1434 /***********************************************************************
1435 * HttpOpenRequestA (WININET.@)
1437 * Open a HTTP request handle
1439 * RETURNS
1440 * HINTERNET a HTTP request handle on success
1441 * NULL on failure
1444 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
1445 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
1446 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
1447 DWORD dwFlags, DWORD_PTR dwContext)
1449 LPWSTR szVerb = NULL, szObjectName = NULL;
1450 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
1451 HINTERNET rc = FALSE;
1453 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
1454 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
1455 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
1456 dwFlags, dwContext);
1458 if (lpszVerb)
1460 szVerb = heap_strdupAtoW(lpszVerb);
1461 if ( !szVerb )
1462 goto end;
1465 if (lpszObjectName)
1467 szObjectName = heap_strdupAtoW(lpszObjectName);
1468 if ( !szObjectName )
1469 goto end;
1472 if (lpszVersion)
1474 szVersion = heap_strdupAtoW(lpszVersion);
1475 if ( !szVersion )
1476 goto end;
1479 if (lpszReferrer)
1481 szReferrer = heap_strdupAtoW(lpszReferrer);
1482 if ( !szReferrer )
1483 goto end;
1486 szAcceptTypes = convert_accept_types( lpszAcceptTypes );
1487 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName, szVersion, szReferrer,
1488 (const WCHAR **)szAcceptTypes, dwFlags, dwContext);
1490 end:
1491 free_accept_types(szAcceptTypes);
1492 heap_free(szReferrer);
1493 heap_free(szVersion);
1494 heap_free(szObjectName);
1495 heap_free(szVerb);
1496 return rc;
1499 /***********************************************************************
1500 * HTTP_EncodeBase64
1502 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1504 UINT n = 0, x;
1505 static const CHAR HTTP_Base64Enc[] =
1506 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1508 while( len > 0 )
1510 /* first 6 bits, all from bin[0] */
1511 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1512 x = (bin[0] & 3) << 4;
1514 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1515 if( len == 1 )
1517 base64[n++] = HTTP_Base64Enc[x];
1518 base64[n++] = '=';
1519 base64[n++] = '=';
1520 break;
1522 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1523 x = ( bin[1] & 0x0f ) << 2;
1525 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1526 if( len == 2 )
1528 base64[n++] = HTTP_Base64Enc[x];
1529 base64[n++] = '=';
1530 break;
1532 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1534 /* last 6 bits, all from bin [2] */
1535 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1536 bin += 3;
1537 len -= 3;
1539 base64[n] = 0;
1540 return n;
1543 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1544 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1545 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1546 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1547 static const signed char HTTP_Base64Dec[256] =
1549 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1550 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1551 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1552 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1553 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1554 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1555 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1556 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1557 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1558 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1559 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1560 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1561 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1562 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1563 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1564 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1565 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1566 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1567 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1568 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1569 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1570 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1571 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1572 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1573 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1574 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1576 #undef CH
1578 /***********************************************************************
1579 * HTTP_DecodeBase64
1581 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1583 unsigned int n = 0;
1585 while(*base64)
1587 signed char in[4];
1589 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1590 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1591 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1592 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1594 WARN("invalid base64: %s\n", debugstr_w(base64));
1595 return 0;
1597 if (bin)
1598 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1599 n++;
1601 if ((base64[2] == '=') && (base64[3] == '='))
1602 break;
1603 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1604 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1606 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1607 return 0;
1609 if (bin)
1610 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1611 n++;
1613 if (base64[3] == '=')
1614 break;
1615 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1616 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1618 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1619 return 0;
1621 if (bin)
1622 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1623 n++;
1625 base64 += 4;
1628 return n;
1631 /***********************************************************************
1632 * HTTP_InsertAuthorization
1634 * Insert or delete the authorization field in the request header.
1636 static BOOL HTTP_InsertAuthorization( http_request_t *request, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1638 if (pAuthInfo)
1640 static const WCHAR wszSpace[] = {' ',0};
1641 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1642 unsigned int len;
1643 WCHAR *authorization = NULL;
1645 if (pAuthInfo->auth_data_len)
1647 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1648 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1649 authorization = heap_alloc((len+1)*sizeof(WCHAR));
1650 if (!authorization)
1651 return FALSE;
1653 strcpyW(authorization, pAuthInfo->scheme);
1654 strcatW(authorization, wszSpace);
1655 HTTP_EncodeBase64(pAuthInfo->auth_data,
1656 pAuthInfo->auth_data_len,
1657 authorization+strlenW(authorization));
1659 /* clear the data as it isn't valid now that it has been sent to the
1660 * server, unless it's Basic authentication which doesn't do
1661 * connection tracking */
1662 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1664 heap_free(pAuthInfo->auth_data);
1665 pAuthInfo->auth_data = NULL;
1666 pAuthInfo->auth_data_len = 0;
1670 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1672 HTTP_ProcessHeader(request, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1673 heap_free(authorization);
1675 return TRUE;
1678 static WCHAR *build_proxy_path_url(http_request_t *req)
1680 DWORD size, len;
1681 WCHAR *url;
1683 len = strlenW(req->server->scheme_host_port);
1684 size = len + strlenW(req->path) + 1;
1685 if(*req->path != '/')
1686 size++;
1687 url = heap_alloc(size * sizeof(WCHAR));
1688 if(!url)
1689 return NULL;
1691 memcpy(url, req->server->scheme_host_port, len*sizeof(WCHAR));
1692 if(*req->path != '/')
1693 url[len++] = '/';
1695 strcpyW(url+len, req->path);
1697 TRACE("url=%s\n", debugstr_w(url));
1698 return url;
1701 static BOOL HTTP_DomainMatches(LPCWSTR server, LPCWSTR domain)
1703 static const WCHAR localW[] = { '<','l','o','c','a','l','>',0 };
1704 BOOL ret = FALSE;
1706 if (!strcmpiW( domain, localW ) && !strchrW( server, '.' ))
1707 ret = TRUE;
1708 else if (*domain == '*')
1710 if (domain[1] == '.')
1712 LPCWSTR dot;
1714 /* For a hostname to match a wildcard, the last domain must match
1715 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1716 * hostname is www.foo.a.b, it matches, but a.b does not.
1718 dot = strchrW( server, '.' );
1719 if (dot)
1721 int len = strlenW( dot + 1 );
1723 if (len > strlenW( domain + 2 ))
1725 LPCWSTR ptr;
1727 /* The server's domain is longer than the wildcard, so it
1728 * could be a subdomain. Compare the last portion of the
1729 * server's domain.
1731 ptr = dot + len + 1 - strlenW( domain + 2 );
1732 if (!strcmpiW( ptr, domain + 2 ))
1734 /* This is only a match if the preceding character is
1735 * a '.', i.e. that it is a matching domain. E.g.
1736 * if domain is '*.b.c' and server is 'www.ab.c' they
1737 * do not match.
1739 ret = *(ptr - 1) == '.';
1742 else
1743 ret = !strcmpiW( dot + 1, domain + 2 );
1747 else
1748 ret = !strcmpiW( server, domain );
1749 return ret;
1752 static BOOL HTTP_ShouldBypassProxy(appinfo_t *lpwai, LPCWSTR server)
1754 LPCWSTR ptr;
1755 BOOL ret = FALSE;
1757 if (!lpwai->proxyBypass) return FALSE;
1758 ptr = lpwai->proxyBypass;
1759 do {
1760 LPCWSTR tmp = ptr;
1762 ptr = strchrW( ptr, ';' );
1763 if (!ptr)
1764 ptr = strchrW( tmp, ' ' );
1765 if (ptr)
1767 if (ptr - tmp < INTERNET_MAX_HOST_NAME_LENGTH)
1769 WCHAR domain[INTERNET_MAX_HOST_NAME_LENGTH];
1771 memcpy( domain, tmp, (ptr - tmp) * sizeof(WCHAR) );
1772 domain[ptr - tmp] = 0;
1773 ret = HTTP_DomainMatches( server, domain );
1775 ptr += 1;
1777 else if (*tmp)
1778 ret = HTTP_DomainMatches( server, tmp );
1779 } while (ptr && !ret);
1780 return ret;
1783 /***********************************************************************
1784 * HTTP_DealWithProxy
1786 static BOOL HTTP_DealWithProxy(appinfo_t *hIC, http_session_t *session, http_request_t *request)
1788 static const WCHAR protoHttp[] = { 'h','t','t','p',0 };
1789 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1790 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1791 WCHAR buf[INTERNET_MAX_HOST_NAME_LENGTH];
1792 WCHAR protoProxy[INTERNET_MAX_URL_LENGTH];
1793 DWORD protoProxyLen = INTERNET_MAX_URL_LENGTH;
1794 WCHAR proxy[INTERNET_MAX_URL_LENGTH];
1795 static WCHAR szNul[] = { 0 };
1796 URL_COMPONENTSW UrlComponents;
1797 server_t *new_server;
1798 BOOL is_https;
1800 memset( &UrlComponents, 0, sizeof UrlComponents );
1801 UrlComponents.dwStructSize = sizeof UrlComponents;
1802 UrlComponents.lpszHostName = buf;
1803 UrlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
1805 if (!INTERNET_FindProxyForProtocol(hIC->proxy, protoHttp, protoProxy, &protoProxyLen))
1806 return FALSE;
1807 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1808 protoProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1809 sprintfW(proxy, szFormat, protoProxy);
1810 else
1811 strcpyW(proxy, protoProxy);
1812 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1813 return FALSE;
1814 if( UrlComponents.dwHostNameLength == 0 )
1815 return FALSE;
1817 if( !request->path )
1818 request->path = szNul;
1820 is_https = (UrlComponents.nScheme == INTERNET_SCHEME_HTTPS);
1821 if (is_https && UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1822 UrlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
1824 new_server = get_server(UrlComponents.lpszHostName, UrlComponents.nPort, is_https, TRUE);
1825 if(!new_server)
1826 return FALSE;
1828 request->proxy = new_server;
1830 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server->name), new_server->port);
1831 return TRUE;
1834 static DWORD HTTP_ResolveName(http_request_t *request)
1836 server_t *server = request->proxy ? request->proxy : request->server;
1837 socklen_t addr_len;
1838 void *addr;
1840 if(server->addr_len)
1841 return ERROR_SUCCESS;
1843 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1844 INTERNET_STATUS_RESOLVING_NAME,
1845 server->name,
1846 (strlenW(server->name)+1) * sizeof(WCHAR));
1848 addr_len = sizeof(server->addr);
1849 if (!GetAddress(server->name, server->port, (struct sockaddr *)&server->addr, &addr_len))
1850 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1852 switch(server->addr.ss_family) {
1853 case AF_INET:
1854 addr = &((struct sockaddr_in *)&server->addr)->sin_addr;
1855 break;
1856 case AF_INET6:
1857 addr = &((struct sockaddr_in6 *)&server->addr)->sin6_addr;
1858 break;
1859 default:
1860 WARN("unsupported family %d\n", server->addr.ss_family);
1861 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1864 server->addr_len = addr_len;
1865 inet_ntop(server->addr.ss_family, addr, server->addr_str, sizeof(server->addr_str));
1866 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1867 INTERNET_STATUS_NAME_RESOLVED,
1868 server->addr_str, strlen(server->addr_str)+1);
1870 TRACE("resolved %s to %s\n", debugstr_w(server->name), server->addr_str);
1871 return ERROR_SUCCESS;
1874 static BOOL HTTP_GetRequestURL(http_request_t *req, LPWSTR buf)
1876 static const WCHAR http[] = { 'h','t','t','p',':','/','/',0 };
1877 static const WCHAR https[] = { 'h','t','t','p','s',':','/','/',0 };
1878 static const WCHAR slash[] = { '/',0 };
1879 LPHTTPHEADERW host_header;
1880 LPCWSTR scheme;
1882 host_header = HTTP_GetHeader(req, hostW);
1883 if(!host_header)
1884 return FALSE;
1886 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1887 scheme = https;
1888 else
1889 scheme = http;
1890 strcpyW(buf, scheme);
1891 strcatW(buf, host_header->lpszValue);
1892 if (req->path[0] != '/')
1893 strcatW(buf, slash);
1894 strcatW(buf, req->path);
1895 return TRUE;
1899 /***********************************************************************
1900 * HTTPREQ_Destroy (internal)
1902 * Deallocate request handle
1905 static void HTTPREQ_Destroy(object_header_t *hdr)
1907 http_request_t *request = (http_request_t*) hdr;
1908 DWORD i;
1910 TRACE("\n");
1912 if(request->hCacheFile) {
1913 CloseHandle(request->hCacheFile);
1914 DeleteFileW(request->cacheFile);
1916 heap_free(request->cacheFile);
1918 request->read_section.DebugInfo->Spare[0] = 0;
1919 DeleteCriticalSection( &request->read_section );
1920 WININET_Release(&request->session->hdr);
1922 destroy_authinfo(request->authInfo);
1923 destroy_authinfo(request->proxyAuthInfo);
1925 if(request->server)
1926 server_release(request->server);
1927 if(request->proxy)
1928 server_release(request->proxy);
1930 heap_free(request->path);
1931 heap_free(request->verb);
1932 heap_free(request->version);
1933 heap_free(request->statusText);
1935 for (i = 0; i < request->nCustHeaders; i++)
1937 heap_free(request->custHeaders[i].lpszField);
1938 heap_free(request->custHeaders[i].lpszValue);
1940 destroy_data_stream(request->data_stream);
1941 heap_free(request->custHeaders);
1944 static void http_release_netconn(http_request_t *req, BOOL reuse)
1946 TRACE("%p %p\n",req, req->netconn);
1948 if(!req->netconn)
1949 return;
1951 if(reuse && req->netconn->keep_alive) {
1952 BOOL run_collector;
1954 EnterCriticalSection(&connection_pool_cs);
1956 list_add_head(&req->netconn->server->conn_pool, &req->netconn->pool_entry);
1957 req->netconn->keep_until = GetTickCount64() + COLLECT_TIME;
1958 req->netconn = NULL;
1960 run_collector = !collector_running;
1961 collector_running = TRUE;
1963 LeaveCriticalSection(&connection_pool_cs);
1965 if(run_collector) {
1966 HANDLE thread = NULL;
1967 HMODULE module;
1969 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR*)WININET_hModule, &module);
1970 if(module)
1971 thread = CreateThread(NULL, 0, collect_connections_proc, NULL, 0, NULL);
1972 if(!thread) {
1973 EnterCriticalSection(&connection_pool_cs);
1974 collector_running = FALSE;
1975 LeaveCriticalSection(&connection_pool_cs);
1977 if(module)
1978 FreeLibrary(module);
1980 else
1981 CloseHandle(thread);
1983 return;
1986 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1987 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1989 free_netconn(req->netconn);
1990 req->netconn = NULL;
1992 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1993 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1996 static BOOL HTTP_KeepAlive(http_request_t *request)
1998 WCHAR szVersion[10];
1999 WCHAR szConnectionResponse[20];
2000 DWORD dwBufferSize = sizeof(szVersion);
2001 BOOL keepalive = FALSE;
2003 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
2004 * the connection is keep-alive by default */
2005 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_VERSION, szVersion, &dwBufferSize, NULL) == ERROR_SUCCESS
2006 && !strcmpiW(szVersion, g_szHttp1_1))
2008 keepalive = TRUE;
2011 dwBufferSize = sizeof(szConnectionResponse);
2012 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS
2013 || HTTP_HttpQueryInfoW(request, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS)
2015 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
2018 return keepalive;
2021 static void HTTPREQ_CloseConnection(object_header_t *hdr)
2023 http_request_t *req = (http_request_t*)hdr;
2025 http_release_netconn(req, drain_content(req, FALSE));
2028 static DWORD str_to_buffer(const WCHAR *str, void *buffer, DWORD *size, BOOL unicode)
2030 int len;
2031 if (unicode)
2033 len = strlenW(str);
2034 if (*size < (len + 1) * sizeof(WCHAR))
2036 *size = (len + 1) * sizeof(WCHAR);
2037 return ERROR_INSUFFICIENT_BUFFER;
2039 strcpyW(buffer, str);
2040 *size = len;
2041 return ERROR_SUCCESS;
2043 else
2045 len = WideCharToMultiByte(CP_ACP, 0, str, -1, buffer, *size, NULL, NULL);
2046 if (*size < len)
2048 *size = len;
2049 return ERROR_INSUFFICIENT_BUFFER;
2051 *size = len - 1;
2052 return ERROR_SUCCESS;
2056 static DWORD HTTPREQ_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2058 http_request_t *req = (http_request_t*)hdr;
2060 switch(option) {
2061 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO:
2063 INTERNET_DIAGNOSTIC_SOCKET_INFO *info = buffer;
2065 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2067 if (*size < sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO))
2068 return ERROR_INSUFFICIENT_BUFFER;
2069 *size = sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO);
2070 /* FIXME: can't get a SOCKET from our connection since we don't use
2071 * winsock
2073 info->Socket = 0;
2074 /* FIXME: get source port from req->netConnection */
2075 info->SourcePort = 0;
2076 info->DestPort = req->server->port;
2077 info->Flags = 0;
2078 if (HTTP_KeepAlive(req))
2079 info->Flags |= IDSI_FLAG_KEEP_ALIVE;
2080 if (req->proxy)
2081 info->Flags |= IDSI_FLAG_PROXY;
2082 if (req->netconn && req->netconn->secure)
2083 info->Flags |= IDSI_FLAG_SECURE;
2085 return ERROR_SUCCESS;
2088 case 98:
2089 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2090 /* fall through */
2091 case INTERNET_OPTION_SECURITY_FLAGS:
2093 DWORD flags;
2095 if (*size < sizeof(ULONG))
2096 return ERROR_INSUFFICIENT_BUFFER;
2098 *size = sizeof(DWORD);
2099 flags = req->netconn ? req->netconn->security_flags : req->security_flags | req->server->security_flags;
2100 *(DWORD *)buffer = flags;
2102 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags);
2103 return ERROR_SUCCESS;
2106 case INTERNET_OPTION_HANDLE_TYPE:
2107 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2109 if (*size < sizeof(ULONG))
2110 return ERROR_INSUFFICIENT_BUFFER;
2112 *size = sizeof(DWORD);
2113 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
2114 return ERROR_SUCCESS;
2116 case INTERNET_OPTION_URL: {
2117 WCHAR url[INTERNET_MAX_URL_LENGTH];
2118 HTTPHEADERW *host;
2120 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
2122 TRACE("INTERNET_OPTION_URL\n");
2124 host = HTTP_GetHeader(req, hostW);
2125 strcpyW(url, httpW);
2126 strcatW(url, host->lpszValue);
2127 strcatW(url, req->path);
2129 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
2130 return str_to_buffer(url, buffer, size, unicode);
2132 case INTERNET_OPTION_USER_AGENT:
2133 return str_to_buffer(req->session->appInfo->agent, buffer, size, unicode);
2134 case INTERNET_OPTION_USERNAME:
2135 return str_to_buffer(req->session->userName, buffer, size, unicode);
2136 case INTERNET_OPTION_PASSWORD:
2137 return str_to_buffer(req->session->password, buffer, size, unicode);
2138 case INTERNET_OPTION_PROXY_USERNAME:
2139 return str_to_buffer(req->session->appInfo->proxyUsername, buffer, size, unicode);
2140 case INTERNET_OPTION_PROXY_PASSWORD:
2141 return str_to_buffer(req->session->appInfo->proxyPassword, buffer, size, unicode);
2143 case INTERNET_OPTION_CACHE_TIMESTAMPS: {
2144 INTERNET_CACHE_ENTRY_INFOW *info;
2145 INTERNET_CACHE_TIMESTAMPS *ts = buffer;
2146 WCHAR url[INTERNET_MAX_URL_LENGTH];
2147 DWORD nbytes, error;
2148 BOOL ret;
2150 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2152 if (*size < sizeof(*ts))
2154 *size = sizeof(*ts);
2155 return ERROR_INSUFFICIENT_BUFFER;
2157 nbytes = 0;
2158 HTTP_GetRequestURL(req, url);
2159 ret = GetUrlCacheEntryInfoW(url, NULL, &nbytes);
2160 error = GetLastError();
2161 if (!ret && error == ERROR_INSUFFICIENT_BUFFER)
2163 if (!(info = heap_alloc(nbytes)))
2164 return ERROR_OUTOFMEMORY;
2166 GetUrlCacheEntryInfoW(url, info, &nbytes);
2168 ts->ftExpires = info->ExpireTime;
2169 ts->ftLastModified = info->LastModifiedTime;
2171 heap_free(info);
2172 *size = sizeof(*ts);
2173 return ERROR_SUCCESS;
2175 return error;
2178 case INTERNET_OPTION_DATAFILE_NAME: {
2179 DWORD req_size;
2181 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2183 if(!req->cacheFile) {
2184 *size = 0;
2185 return ERROR_INTERNET_ITEM_NOT_FOUND;
2188 if(unicode) {
2189 req_size = (lstrlenW(req->cacheFile)+1) * sizeof(WCHAR);
2190 if(*size < req_size)
2191 return ERROR_INSUFFICIENT_BUFFER;
2193 *size = req_size;
2194 memcpy(buffer, req->cacheFile, *size);
2195 return ERROR_SUCCESS;
2196 }else {
2197 req_size = WideCharToMultiByte(CP_ACP, 0, req->cacheFile, -1, NULL, 0, NULL, NULL);
2198 if (req_size > *size)
2199 return ERROR_INSUFFICIENT_BUFFER;
2201 *size = WideCharToMultiByte(CP_ACP, 0, req->cacheFile,
2202 -1, buffer, *size, NULL, NULL);
2203 return ERROR_SUCCESS;
2207 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
2208 PCCERT_CONTEXT context;
2210 if(!req->netconn)
2211 return ERROR_INTERNET_INVALID_OPERATION;
2213 if(*size < sizeof(INTERNET_CERTIFICATE_INFOA)) {
2214 *size = sizeof(INTERNET_CERTIFICATE_INFOA);
2215 return ERROR_INSUFFICIENT_BUFFER;
2218 context = (PCCERT_CONTEXT)NETCON_GetCert(req->netconn);
2219 if(context) {
2220 INTERNET_CERTIFICATE_INFOA *info = (INTERNET_CERTIFICATE_INFOA*)buffer;
2221 DWORD len;
2223 memset(info, 0, sizeof(*info));
2224 info->ftExpiry = context->pCertInfo->NotAfter;
2225 info->ftStart = context->pCertInfo->NotBefore;
2226 len = CertNameToStrA(context->dwCertEncodingType,
2227 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2228 info->lpszSubjectInfo = LocalAlloc(0, len);
2229 if(info->lpszSubjectInfo)
2230 CertNameToStrA(context->dwCertEncodingType,
2231 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2232 info->lpszSubjectInfo, len);
2233 len = CertNameToStrA(context->dwCertEncodingType,
2234 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2235 info->lpszIssuerInfo = LocalAlloc(0, len);
2236 if(info->lpszIssuerInfo)
2237 CertNameToStrA(context->dwCertEncodingType,
2238 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2239 info->lpszIssuerInfo, len);
2240 info->dwKeySize = NETCON_GetCipherStrength(req->netconn);
2241 CertFreeCertificateContext(context);
2242 return ERROR_SUCCESS;
2244 return ERROR_NOT_SUPPORTED;
2246 case INTERNET_OPTION_CONNECT_TIMEOUT:
2247 if (*size < sizeof(DWORD))
2248 return ERROR_INSUFFICIENT_BUFFER;
2250 *size = sizeof(DWORD);
2251 *(DWORD *)buffer = req->connect_timeout;
2252 return ERROR_SUCCESS;
2253 case INTERNET_OPTION_REQUEST_FLAGS: {
2254 DWORD flags = 0;
2256 if (*size < sizeof(DWORD))
2257 return ERROR_INSUFFICIENT_BUFFER;
2259 /* FIXME: Add support for:
2260 * INTERNET_REQFLAG_FROM_CACHE
2261 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2264 if(req->proxy)
2265 flags |= INTERNET_REQFLAG_VIA_PROXY;
2266 if(!req->status_code)
2267 flags |= INTERNET_REQFLAG_NO_HEADERS;
2269 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags);
2271 *size = sizeof(DWORD);
2272 *(DWORD*)buffer = flags;
2273 return ERROR_SUCCESS;
2277 return INET_QueryOption(hdr, option, buffer, size, unicode);
2280 static DWORD HTTPREQ_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
2282 http_request_t *req = (http_request_t*)hdr;
2284 switch(option) {
2285 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2286 TRACE("Undocumented option 99\n");
2288 if (!buffer || size != sizeof(DWORD))
2289 return ERROR_INVALID_PARAMETER;
2290 if(*(DWORD*)buffer & ~SECURITY_SET_MASK)
2291 return ERROR_INTERNET_OPTION_NOT_SETTABLE;
2293 /* fall through */
2294 case INTERNET_OPTION_SECURITY_FLAGS:
2296 DWORD flags;
2298 if (!buffer || size != sizeof(DWORD))
2299 return ERROR_INVALID_PARAMETER;
2300 flags = *(DWORD *)buffer;
2301 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags);
2302 flags &= SECURITY_SET_MASK;
2303 req->security_flags |= flags;
2304 if(req->netconn)
2305 req->netconn->security_flags |= flags;
2306 return ERROR_SUCCESS;
2308 case INTERNET_OPTION_CONNECT_TIMEOUT:
2309 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2310 req->connect_timeout = *(DWORD *)buffer;
2311 return ERROR_SUCCESS;
2313 case INTERNET_OPTION_SEND_TIMEOUT:
2314 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2315 req->send_timeout = *(DWORD *)buffer;
2316 return ERROR_SUCCESS;
2318 case INTERNET_OPTION_RECEIVE_TIMEOUT:
2319 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2320 req->receive_timeout = *(DWORD *)buffer;
2321 return ERROR_SUCCESS;
2323 case INTERNET_OPTION_USERNAME:
2324 heap_free(req->session->userName);
2325 if (!(req->session->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2326 return ERROR_SUCCESS;
2328 case INTERNET_OPTION_PASSWORD:
2329 heap_free(req->session->password);
2330 if (!(req->session->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2331 return ERROR_SUCCESS;
2333 case INTERNET_OPTION_PROXY_USERNAME:
2334 heap_free(req->session->appInfo->proxyUsername);
2335 if (!(req->session->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2336 return ERROR_SUCCESS;
2338 case INTERNET_OPTION_PROXY_PASSWORD:
2339 heap_free(req->session->appInfo->proxyPassword);
2340 if (!(req->session->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2341 return ERROR_SUCCESS;
2343 case INTERNET_OPTION_HTTP_DECODING:
2344 if(size != sizeof(BOOL))
2345 return ERROR_INVALID_PARAMETER;
2346 req->decoding = *(BOOL*)buffer;
2347 return ERROR_SUCCESS;
2350 return INET_SetOption(hdr, option, buffer, size);
2353 static void commit_cache_entry(http_request_t *req)
2355 WCHAR url[INTERNET_MAX_URL_LENGTH];
2357 TRACE("%p\n", req);
2359 CloseHandle(req->hCacheFile);
2360 req->hCacheFile = NULL;
2362 if(HTTP_GetRequestURL(req, url)) {
2363 WCHAR *header;
2364 DWORD header_len;
2366 header = build_response_header(req, TRUE);
2367 header_len = (header ? strlenW(header) : 0);
2368 CommitUrlCacheEntryW(url, req->cacheFile, req->expires,
2369 req->last_modified, NORMAL_CACHE_ENTRY,
2370 header, header_len, NULL, 0);
2371 heap_free(header);
2375 static void create_cache_entry(http_request_t *req)
2377 static const WCHAR no_cacheW[] = {'n','o','-','c','a','c','h','e',0};
2378 static const WCHAR no_storeW[] = {'n','o','-','s','t','o','r','e',0};
2380 WCHAR url[INTERNET_MAX_URL_LENGTH];
2381 WCHAR file_name[MAX_PATH+1];
2382 BOOL b = TRUE;
2384 /* FIXME: We should free previous cache file earlier */
2385 heap_free(req->cacheFile);
2386 CloseHandle(req->hCacheFile);
2387 req->hCacheFile = NULL;
2389 if(req->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE)
2390 b = FALSE;
2392 if(b) {
2393 int header_idx = HTTP_GetCustomHeaderIndex(req, szCache_Control, 0, FALSE);
2394 if(header_idx != -1) {
2395 WCHAR *ptr;
2397 for(ptr=req->custHeaders[header_idx].lpszValue; *ptr; ) {
2398 WCHAR *end;
2400 while(*ptr==' ' || *ptr=='\t')
2401 ptr++;
2403 end = strchrW(ptr, ',');
2404 if(!end)
2405 end = ptr + strlenW(ptr);
2407 if(!strncmpiW(ptr, no_cacheW, sizeof(no_cacheW)/sizeof(*no_cacheW)-1)
2408 || !strncmpiW(ptr, no_storeW, sizeof(no_storeW)/sizeof(*no_storeW)-1)) {
2409 b = FALSE;
2410 break;
2413 ptr = end;
2414 if(*ptr == ',')
2415 ptr++;
2420 if(!b) {
2421 if(!(req->hdr.dwFlags & INTERNET_FLAG_NEED_FILE))
2422 return;
2424 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2427 b = HTTP_GetRequestURL(req, url);
2428 if(!b) {
2429 WARN("Could not get URL\n");
2430 return;
2433 b = CreateUrlCacheEntryW(url, req->contentLength == ~0u ? 0 : req->contentLength, NULL, file_name, 0);
2434 if(!b) {
2435 WARN("Could not create cache entry: %08x\n", GetLastError());
2436 return;
2439 req->cacheFile = heap_strdupW(file_name);
2440 req->hCacheFile = CreateFileW(req->cacheFile, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
2441 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2442 if(req->hCacheFile == INVALID_HANDLE_VALUE) {
2443 WARN("Could not create file: %u\n", GetLastError());
2444 req->hCacheFile = NULL;
2445 return;
2448 if(req->read_size) {
2449 DWORD written;
2451 b = WriteFile(req->hCacheFile, req->read_buf+req->read_pos, req->read_size, &written, NULL);
2452 if(!b)
2453 FIXME("WriteFile failed: %u\n", GetLastError());
2455 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2456 commit_cache_entry(req);
2460 /* read some more data into the read buffer (the read section must be held) */
2461 static DWORD read_more_data( http_request_t *req, int maxlen )
2463 DWORD res;
2464 int len;
2466 if (req->read_pos)
2468 /* move existing data to the start of the buffer */
2469 if(req->read_size)
2470 memmove( req->read_buf, req->read_buf + req->read_pos, req->read_size );
2471 req->read_pos = 0;
2474 if (maxlen == -1) maxlen = sizeof(req->read_buf);
2476 res = NETCON_recv( req->netconn, req->read_buf + req->read_size,
2477 maxlen - req->read_size, 0, &len );
2478 if(res == ERROR_SUCCESS)
2479 req->read_size += len;
2481 return res;
2484 /* remove some amount of data from the read buffer (the read section must be held) */
2485 static void remove_data( http_request_t *req, int count )
2487 if (!(req->read_size -= count)) req->read_pos = 0;
2488 else req->read_pos += count;
2491 static DWORD read_line( http_request_t *req, LPSTR buffer, DWORD *len )
2493 int count, bytes_read, pos = 0;
2494 DWORD res;
2496 EnterCriticalSection( &req->read_section );
2497 for (;;)
2499 BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
2501 if (eol)
2503 count = eol - (req->read_buf + req->read_pos);
2504 bytes_read = count + 1;
2506 else count = bytes_read = req->read_size;
2508 count = min( count, *len - pos );
2509 memcpy( buffer + pos, req->read_buf + req->read_pos, count );
2510 pos += count;
2511 remove_data( req, bytes_read );
2512 if (eol) break;
2514 if ((res = read_more_data( req, -1 )))
2516 WARN( "read failed %u\n", res );
2517 LeaveCriticalSection( &req->read_section );
2518 return res;
2520 if (!req->read_size)
2522 *len = 0;
2523 TRACE( "returning empty string\n" );
2524 LeaveCriticalSection( &req->read_section );
2525 return ERROR_SUCCESS;
2528 LeaveCriticalSection( &req->read_section );
2530 if (pos < *len)
2532 if (pos && buffer[pos - 1] == '\r') pos--;
2533 *len = pos + 1;
2535 buffer[*len - 1] = 0;
2536 TRACE( "returning %s\n", debugstr_a(buffer));
2537 return ERROR_SUCCESS;
2540 /* check if we have reached the end of the data to read (the read section must be held) */
2541 static BOOL end_of_read_data( http_request_t *req )
2543 return !req->read_size && req->data_stream->vtbl->end_of_data(req->data_stream, req);
2546 static DWORD read_http_stream(http_request_t *req, BYTE *buf, DWORD size, DWORD *read, read_mode_t read_mode)
2548 DWORD res;
2550 res = req->data_stream->vtbl->read(req->data_stream, req, buf, size, read, read_mode);
2551 assert(*read <= size);
2553 if(req->hCacheFile) {
2554 if(*read) {
2555 BOOL bres;
2556 DWORD written;
2558 bres = WriteFile(req->hCacheFile, buf, *read, &written, NULL);
2559 if(!bres)
2560 FIXME("WriteFile failed: %u\n", GetLastError());
2563 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2564 commit_cache_entry(req);
2567 return res;
2570 /* fetch some more data into the read buffer (the read section must be held) */
2571 static DWORD refill_read_buffer(http_request_t *req, read_mode_t read_mode, DWORD *read_bytes)
2573 DWORD res, read=0;
2575 if(req->read_size == sizeof(req->read_buf))
2576 return ERROR_SUCCESS;
2578 if(req->read_pos) {
2579 if(req->read_size)
2580 memmove(req->read_buf, req->read_buf+req->read_pos, req->read_size);
2581 req->read_pos = 0;
2584 res = read_http_stream(req, req->read_buf+req->read_size, sizeof(req->read_buf) - req->read_size,
2585 &read, read_mode);
2586 req->read_size += read;
2588 TRACE("read %u bytes, read_size %u\n", read, req->read_size);
2589 if(read_bytes)
2590 *read_bytes = read;
2591 return res;
2594 /* return the size of data available to be read immediately (the read section must be held) */
2595 static DWORD get_avail_data( http_request_t *req )
2597 return req->read_size + req->data_stream->vtbl->get_avail_data(req->data_stream, req);
2600 static DWORD netconn_get_avail_data(data_stream_t *stream, http_request_t *req)
2602 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2603 DWORD avail = 0;
2605 if(req->netconn)
2606 NETCON_query_data_available(req->netconn, &avail);
2607 return netconn_stream->content_length == ~0u
2608 ? avail
2609 : min(avail, netconn_stream->content_length-netconn_stream->content_read);
2612 static BOOL netconn_end_of_data(data_stream_t *stream, http_request_t *req)
2614 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2615 return netconn_stream->content_read == netconn_stream->content_length || !req->netconn;
2618 static DWORD netconn_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2619 DWORD *read, read_mode_t read_mode)
2621 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2622 DWORD res = ERROR_SUCCESS;
2623 int len = 0;
2625 size = min(size, netconn_stream->content_length-netconn_stream->content_read);
2627 if(read_mode == READMODE_NOBLOCK) {
2628 DWORD avail = netconn_get_avail_data(stream, req);
2629 if (size > avail)
2630 size = avail;
2633 if(size && req->netconn) {
2634 if((res = NETCON_recv(req->netconn, buf, size, read_mode == READMODE_SYNC ? MSG_WAITALL : 0, &len)))
2635 len = 0;
2636 if(!len)
2637 netconn_stream->content_length = netconn_stream->content_read;
2640 netconn_stream->content_read += *read = len;
2641 TRACE("read %u bytes\n", len);
2642 return res;
2645 static BOOL netconn_drain_content(data_stream_t *stream, http_request_t *req)
2647 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2648 BYTE buf[1024];
2649 DWORD avail;
2650 int len;
2652 if(netconn_end_of_data(stream, req))
2653 return TRUE;
2655 do {
2656 avail = netconn_get_avail_data(stream, req);
2657 if(!avail)
2658 return FALSE;
2660 if(NETCON_recv(req->netconn, buf, min(avail, sizeof(buf)), 0, &len) != ERROR_SUCCESS)
2661 return FALSE;
2663 netconn_stream->content_read += len;
2664 }while(netconn_stream->content_read < netconn_stream->content_length);
2666 return TRUE;
2669 static void netconn_destroy(data_stream_t *stream)
2673 static const data_stream_vtbl_t netconn_stream_vtbl = {
2674 netconn_get_avail_data,
2675 netconn_end_of_data,
2676 netconn_read,
2677 netconn_drain_content,
2678 netconn_destroy
2681 /* read some more data into the read buffer (the read section must be held) */
2682 static DWORD read_more_chunked_data(chunked_stream_t *stream, http_request_t *req, int maxlen)
2684 DWORD res;
2685 int len;
2687 if (stream->buf_pos)
2689 /* move existing data to the start of the buffer */
2690 if(stream->buf_size)
2691 memmove(stream->buf, stream->buf + stream->buf_pos, stream->buf_size);
2692 stream->buf_pos = 0;
2695 if (maxlen == -1) maxlen = sizeof(stream->buf);
2697 res = NETCON_recv( req->netconn, stream->buf + stream->buf_size,
2698 maxlen - stream->buf_size, 0, &len );
2699 if(res == ERROR_SUCCESS)
2700 stream->buf_size += len;
2702 return res;
2705 /* remove some amount of data from the read buffer (the read section must be held) */
2706 static void remove_chunked_data(chunked_stream_t *stream, int count)
2708 if (!(stream->buf_size -= count)) stream->buf_pos = 0;
2709 else stream->buf_pos += count;
2712 /* discard data contents until we reach end of line (the read section must be held) */
2713 static DWORD discard_chunked_eol(chunked_stream_t *stream, http_request_t *req)
2715 DWORD res;
2719 BYTE *eol = memchr(stream->buf + stream->buf_pos, '\n', stream->buf_size);
2720 if (eol)
2722 remove_chunked_data(stream, (eol + 1) - (stream->buf + stream->buf_pos));
2723 break;
2725 stream->buf_pos = stream->buf_size = 0; /* discard everything */
2726 if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
2727 } while (stream->buf_size);
2728 return ERROR_SUCCESS;
2731 /* read the size of the next chunk (the read section must be held) */
2732 static DWORD start_next_chunk(chunked_stream_t *stream, http_request_t *req)
2734 /* TODOO */
2735 DWORD chunk_size = 0, res;
2737 if(stream->chunk_size != ~0u && (res = discard_chunked_eol(stream, req)) != ERROR_SUCCESS)
2738 return res;
2740 for (;;)
2742 while (stream->buf_size)
2744 char ch = stream->buf[stream->buf_pos];
2745 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
2746 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
2747 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
2748 else if (ch == ';' || ch == '\r' || ch == '\n')
2750 TRACE( "reading %u byte chunk\n", chunk_size );
2751 stream->chunk_size = chunk_size;
2752 req->contentLength += chunk_size;
2753 return discard_chunked_eol(stream, req);
2755 remove_chunked_data(stream, 1);
2757 if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
2758 if (!stream->buf_size)
2760 stream->chunk_size = 0;
2761 return ERROR_SUCCESS;
2766 static DWORD chunked_get_avail_data(data_stream_t *stream, http_request_t *req)
2768 /* Allow reading only from read buffer */
2769 return 0;
2772 static BOOL chunked_end_of_data(data_stream_t *stream, http_request_t *req)
2774 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2775 return !chunked_stream->chunk_size;
2778 static DWORD chunked_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2779 DWORD *read, read_mode_t read_mode)
2781 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2782 DWORD read_bytes = 0, ret_read = 0, res = ERROR_SUCCESS;
2784 if(chunked_stream->chunk_size == ~0u) {
2785 res = start_next_chunk(chunked_stream, req);
2786 if(res != ERROR_SUCCESS)
2787 return res;
2790 while(size && chunked_stream->chunk_size) {
2791 if(chunked_stream->buf_size) {
2792 read_bytes = min(size, min(chunked_stream->buf_size, chunked_stream->chunk_size));
2794 /* this could block */
2795 if(read_mode == READMODE_NOBLOCK && read_bytes == chunked_stream->chunk_size)
2796 break;
2798 memcpy(buf+ret_read, chunked_stream->buf+chunked_stream->buf_pos, read_bytes);
2799 remove_chunked_data(chunked_stream, read_bytes);
2800 }else {
2801 read_bytes = min(size, chunked_stream->chunk_size);
2803 if(read_mode == READMODE_NOBLOCK) {
2804 DWORD avail;
2806 if(!req->netconn || !NETCON_query_data_available(req->netconn, &avail) || !avail)
2807 break;
2808 if(read_bytes > avail)
2809 read_bytes = avail;
2811 /* this could block */
2812 if(read_bytes == chunked_stream->chunk_size)
2813 break;
2816 res = NETCON_recv(req->netconn, (char *)buf+ret_read, read_bytes, 0, (int*)&read_bytes);
2817 if(res != ERROR_SUCCESS)
2818 break;
2821 chunked_stream->chunk_size -= read_bytes;
2822 size -= read_bytes;
2823 ret_read += read_bytes;
2824 if(!chunked_stream->chunk_size) {
2825 assert(read_mode != READMODE_NOBLOCK);
2826 res = start_next_chunk(chunked_stream, req);
2827 if(res != ERROR_SUCCESS)
2828 break;
2831 if(read_mode == READMODE_ASYNC)
2832 read_mode = READMODE_NOBLOCK;
2835 TRACE("read %u bytes\n", ret_read);
2836 *read = ret_read;
2837 return res;
2840 static BOOL chunked_drain_content(data_stream_t *stream, http_request_t *req)
2842 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2844 /* FIXME: we can do better */
2845 return !chunked_stream->chunk_size;
2848 static void chunked_destroy(data_stream_t *stream)
2850 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2851 heap_free(chunked_stream);
2854 static const data_stream_vtbl_t chunked_stream_vtbl = {
2855 chunked_get_avail_data,
2856 chunked_end_of_data,
2857 chunked_read,
2858 chunked_drain_content,
2859 chunked_destroy
2862 /* set the request content length based on the headers */
2863 static DWORD set_content_length(http_request_t *request)
2865 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
2866 WCHAR encoding[20];
2867 DWORD size;
2869 if(request->status_code == HTTP_STATUS_NO_CONTENT) {
2870 request->contentLength = request->netconn_stream.content_length = 0;
2871 return ERROR_SUCCESS;
2874 size = sizeof(request->contentLength);
2875 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2876 &request->contentLength, &size, NULL) != ERROR_SUCCESS)
2877 request->contentLength = ~0u;
2878 request->netconn_stream.content_length = request->contentLength;
2879 request->netconn_stream.content_read = request->read_size;
2881 size = sizeof(encoding);
2882 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) == ERROR_SUCCESS &&
2883 !strcmpiW(encoding, szChunked))
2885 chunked_stream_t *chunked_stream;
2887 chunked_stream = heap_alloc(sizeof(*chunked_stream));
2888 if(!chunked_stream)
2889 return ERROR_OUTOFMEMORY;
2891 chunked_stream->data_stream.vtbl = &chunked_stream_vtbl;
2892 chunked_stream->buf_size = chunked_stream->buf_pos = 0;
2893 chunked_stream->chunk_size = ~0u;
2895 if(request->read_size) {
2896 memcpy(chunked_stream->buf, request->read_buf+request->read_pos, request->read_size);
2897 chunked_stream->buf_size = request->read_size;
2898 request->read_size = request->read_pos = 0;
2901 request->data_stream = &chunked_stream->data_stream;
2902 request->contentLength = ~0u;
2903 request->read_chunked = TRUE;
2906 if(request->decoding) {
2907 int encoding_idx;
2909 static const WCHAR gzipW[] = {'g','z','i','p',0};
2911 encoding_idx = HTTP_GetCustomHeaderIndex(request, szContent_Encoding, 0, FALSE);
2912 if(encoding_idx != -1 && !strcmpiW(request->custHeaders[encoding_idx].lpszValue, gzipW)) {
2913 HTTP_DeleteCustomHeader(request, encoding_idx);
2914 return init_gzip_stream(request);
2918 return ERROR_SUCCESS;
2921 static void send_request_complete(http_request_t *req, DWORD_PTR result, DWORD error)
2923 INTERNET_ASYNC_RESULT iar;
2925 iar.dwResult = result;
2926 iar.dwError = error;
2928 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2929 sizeof(INTERNET_ASYNC_RESULT));
2932 static void HTTP_ReceiveRequestData(http_request_t *req, BOOL first_notif, DWORD *ret_size)
2934 DWORD res, read = 0, avail = 0;
2935 read_mode_t mode;
2937 TRACE("%p\n", req);
2939 EnterCriticalSection( &req->read_section );
2941 mode = first_notif && req->read_size ? READMODE_NOBLOCK : READMODE_ASYNC;
2942 res = refill_read_buffer(req, mode, &read);
2943 if(res == ERROR_SUCCESS)
2944 avail = get_avail_data(req);
2946 LeaveCriticalSection( &req->read_section );
2948 if(res != ERROR_SUCCESS || (mode != READMODE_NOBLOCK && !read)) {
2949 WARN("res %u read %u, closing connection\n", res, read);
2950 http_release_netconn(req, FALSE);
2953 if(res != ERROR_SUCCESS) {
2954 send_request_complete(req, 0, res);
2955 return;
2958 if(ret_size)
2959 *ret_size = avail;
2960 if(first_notif)
2961 avail = 0;
2963 send_request_complete(req, req->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)req->hdr.hInternet : 1, avail);
2966 /* read data from the http connection (the read section must be held) */
2967 static DWORD HTTPREQ_Read(http_request_t *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
2969 DWORD current_read = 0, ret_read = 0;
2970 read_mode_t read_mode;
2971 DWORD res = ERROR_SUCCESS;
2973 read_mode = req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC ? READMODE_ASYNC : READMODE_SYNC;
2975 EnterCriticalSection( &req->read_section );
2977 if(req->read_size) {
2978 ret_read = min(size, req->read_size);
2979 memcpy(buffer, req->read_buf+req->read_pos, ret_read);
2980 req->read_size -= ret_read;
2981 req->read_pos += ret_read;
2982 if(read_mode == READMODE_ASYNC)
2983 read_mode = READMODE_NOBLOCK;
2986 if(ret_read < size) {
2987 res = read_http_stream(req, (BYTE*)buffer+ret_read, size-ret_read, &current_read, read_mode);
2988 ret_read += current_read;
2991 LeaveCriticalSection( &req->read_section );
2993 *read = ret_read;
2994 TRACE( "retrieved %u bytes (%u)\n", ret_read, req->contentLength );
2996 if(size && !ret_read)
2997 http_release_netconn(req, res == ERROR_SUCCESS);
2999 return res;
3002 static BOOL drain_content(http_request_t *req, BOOL blocking)
3004 BOOL ret;
3006 if(!req->netconn || req->contentLength == -1)
3007 return FALSE;
3009 if(!strcmpW(req->verb, szHEAD))
3010 return TRUE;
3012 if(!blocking)
3013 return req->data_stream->vtbl->drain_content(req->data_stream, req);
3015 EnterCriticalSection( &req->read_section );
3017 while(1) {
3018 DWORD bytes_read, res;
3019 BYTE buf[4096];
3021 res = HTTPREQ_Read(req, buf, sizeof(buf), &bytes_read, TRUE);
3022 if(res != ERROR_SUCCESS) {
3023 ret = FALSE;
3024 break;
3026 if(!bytes_read) {
3027 ret = TRUE;
3028 break;
3032 LeaveCriticalSection( &req->read_section );
3033 return ret;
3036 static DWORD HTTPREQ_ReadFile(object_header_t *hdr, void *buffer, DWORD size, DWORD *read)
3038 http_request_t *req = (http_request_t*)hdr;
3039 DWORD res;
3041 EnterCriticalSection( &req->read_section );
3042 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3043 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3045 res = HTTPREQ_Read(req, buffer, size, read, TRUE);
3046 if(res == ERROR_SUCCESS)
3047 res = hdr->dwError;
3048 LeaveCriticalSection( &req->read_section );
3050 return res;
3053 typedef struct {
3054 task_header_t hdr;
3055 void *buf;
3056 DWORD size;
3057 DWORD *ret_read;
3058 } read_file_ex_task_t;
3060 static void AsyncReadFileExProc(task_header_t *hdr)
3062 read_file_ex_task_t *task = (read_file_ex_task_t*)hdr;
3063 http_request_t *req = (http_request_t*)task->hdr.hdr;
3064 DWORD res;
3066 TRACE("INTERNETREADFILEEXW %p\n", task->hdr.hdr);
3068 res = HTTPREQ_Read(req, task->buf, task->size, task->ret_read, TRUE);
3069 send_request_complete(req, res == ERROR_SUCCESS, res);
3072 static DWORD HTTPREQ_ReadFileEx(object_header_t *hdr, void *buf, DWORD size, DWORD *ret_read,
3073 DWORD flags, DWORD_PTR context)
3076 http_request_t *req = (http_request_t*)hdr;
3077 DWORD res, read, cread, error = ERROR_SUCCESS;
3079 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3080 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3082 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3084 if (hdr->dwFlags & INTERNET_FLAG_ASYNC)
3086 read_file_ex_task_t *task;
3088 if (TryEnterCriticalSection( &req->read_section ))
3090 if (get_avail_data(req))
3092 res = HTTPREQ_Read(req, buf, size, &read, FALSE);
3093 LeaveCriticalSection( &req->read_section );
3094 goto done;
3096 LeaveCriticalSection( &req->read_section );
3099 task = alloc_async_task(&req->hdr, AsyncReadFileExProc, sizeof(*task));
3100 task->buf = buf;
3101 task->size = size;
3102 task->ret_read = ret_read;
3104 INTERNET_AsyncCall(&task->hdr);
3106 return ERROR_IO_PENDING;
3109 read = 0;
3111 EnterCriticalSection( &req->read_section );
3112 if(hdr->dwError == ERROR_SUCCESS)
3113 hdr->dwError = INTERNET_HANDLE_IN_USE;
3114 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3115 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3117 while(1) {
3118 res = HTTPREQ_Read(req, (char*)buf+read, size-read, &cread, !(flags & IRF_NO_WAIT));
3119 if(res != ERROR_SUCCESS)
3120 break;
3122 read += cread;
3123 if(read == size || end_of_read_data(req))
3124 break;
3126 LeaveCriticalSection( &req->read_section );
3128 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3129 &cread, sizeof(cread));
3130 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
3131 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3133 EnterCriticalSection( &req->read_section );
3136 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3137 hdr->dwError = ERROR_SUCCESS;
3138 else
3139 error = hdr->dwError;
3141 LeaveCriticalSection( &req->read_section );
3143 done:
3144 *ret_read = read;
3145 if (res == ERROR_SUCCESS) {
3146 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3147 &read, sizeof(read));
3150 return res==ERROR_SUCCESS ? error : res;
3153 static DWORD HTTPREQ_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
3155 DWORD res;
3156 http_request_t *request = (http_request_t*)hdr;
3158 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3160 *written = 0;
3161 res = NETCON_send(request->netconn, buffer, size, 0, (LPINT)written);
3162 if (res == ERROR_SUCCESS)
3163 request->bytesWritten += *written;
3165 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
3166 return res;
3169 typedef struct {
3170 task_header_t hdr;
3171 DWORD *ret_size;
3172 } http_data_available_task_t;
3174 static void AsyncQueryDataAvailableProc(task_header_t *hdr)
3176 http_data_available_task_t *task = (http_data_available_task_t*)hdr;
3178 HTTP_ReceiveRequestData((http_request_t*)task->hdr.hdr, FALSE, task->ret_size);
3181 static DWORD HTTPREQ_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
3183 http_request_t *req = (http_request_t*)hdr;
3185 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
3187 if (req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3189 http_data_available_task_t *task;
3191 /* never wait, if we can't enter the section we queue an async request right away */
3192 if (TryEnterCriticalSection( &req->read_section ))
3194 refill_read_buffer(req, READMODE_NOBLOCK, NULL);
3195 if ((*available = get_avail_data( req ))) goto done;
3196 if (end_of_read_data( req )) goto done;
3197 LeaveCriticalSection( &req->read_section );
3200 task = alloc_async_task(&req->hdr, AsyncQueryDataAvailableProc, sizeof(*task));
3201 task->ret_size = available;
3202 INTERNET_AsyncCall(&task->hdr);
3203 return ERROR_IO_PENDING;
3206 EnterCriticalSection( &req->read_section );
3208 if (!(*available = get_avail_data( req )) && !end_of_read_data( req ))
3210 refill_read_buffer( req, READMODE_ASYNC, NULL );
3211 *available = get_avail_data( req );
3214 done:
3215 LeaveCriticalSection( &req->read_section );
3217 TRACE( "returning %u\n", *available );
3218 return ERROR_SUCCESS;
3221 static const object_vtbl_t HTTPREQVtbl = {
3222 HTTPREQ_Destroy,
3223 HTTPREQ_CloseConnection,
3224 HTTPREQ_QueryOption,
3225 HTTPREQ_SetOption,
3226 HTTPREQ_ReadFile,
3227 HTTPREQ_ReadFileEx,
3228 HTTPREQ_WriteFile,
3229 HTTPREQ_QueryDataAvailable,
3230 NULL
3233 /***********************************************************************
3234 * HTTP_HttpOpenRequestW (internal)
3236 * Open a HTTP request handle
3238 * RETURNS
3239 * HINTERNET a HTTP request handle on success
3240 * NULL on failure
3243 static DWORD HTTP_HttpOpenRequestW(http_session_t *session,
3244 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3245 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3246 DWORD dwFlags, DWORD_PTR dwContext, HINTERNET *ret)
3248 appinfo_t *hIC = session->appInfo;
3249 http_request_t *request;
3250 DWORD len, res = ERROR_SUCCESS;
3252 TRACE("-->\n");
3254 request = alloc_object(&session->hdr, &HTTPREQVtbl, sizeof(http_request_t));
3255 if(!request)
3256 return ERROR_OUTOFMEMORY;
3258 request->hdr.htype = WH_HHTTPREQ;
3259 request->hdr.dwFlags = dwFlags;
3260 request->hdr.dwContext = dwContext;
3261 request->contentLength = ~0u;
3263 request->netconn_stream.data_stream.vtbl = &netconn_stream_vtbl;
3264 request->data_stream = &request->netconn_stream.data_stream;
3265 request->connect_timeout = session->connect_timeout;
3266 request->send_timeout = session->send_timeout;
3267 request->receive_timeout = session->receive_timeout;
3269 InitializeCriticalSection( &request->read_section );
3270 request->read_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.read_section");
3272 WININET_AddRef( &session->hdr );
3273 request->session = session;
3274 list_add_head( &session->hdr.children, &request->hdr.entry );
3276 request->server = get_server(session->hostName, session->hostPort, (dwFlags & INTERNET_FLAG_SECURE) != 0, TRUE);
3277 if(!request->server) {
3278 WININET_Release(&request->hdr);
3279 return ERROR_OUTOFMEMORY;
3282 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_CN_INVALID)
3283 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
3284 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_DATE_INVALID)
3285 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
3287 if (lpszObjectName && *lpszObjectName) {
3288 HRESULT rc;
3290 len = 0;
3291 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
3292 if (rc != E_POINTER)
3293 len = strlenW(lpszObjectName)+1;
3294 request->path = heap_alloc(len*sizeof(WCHAR));
3295 rc = UrlEscapeW(lpszObjectName, request->path, &len,
3296 URL_ESCAPE_SPACES_ONLY);
3297 if (rc != S_OK)
3299 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
3300 strcpyW(request->path,lpszObjectName);
3302 }else {
3303 static const WCHAR slashW[] = {'/',0};
3305 request->path = heap_strdupW(slashW);
3308 if (lpszReferrer && *lpszReferrer)
3309 HTTP_ProcessHeader(request, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3311 if (lpszAcceptTypes)
3313 int i;
3314 for (i = 0; lpszAcceptTypes[i]; i++)
3316 if (!*lpszAcceptTypes[i]) continue;
3317 HTTP_ProcessHeader(request, HTTP_ACCEPT, lpszAcceptTypes[i],
3318 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
3319 HTTP_ADDHDR_FLAG_REQ |
3320 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
3324 request->verb = heap_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
3325 request->version = heap_strdupW(lpszVersion && *lpszVersion ? lpszVersion : g_szHttp1_1);
3327 HTTP_ProcessHeader(request, hostW, request->server->canon_host_port, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3329 if (session->hostPort == INTERNET_INVALID_PORT_NUMBER)
3330 session->hostPort = INTERNET_DEFAULT_HTTP_PORT;
3332 if (hIC->proxy && hIC->proxy[0] && !HTTP_ShouldBypassProxy(hIC, session->hostName))
3333 HTTP_DealWithProxy( hIC, session, request );
3335 INTERNET_SendCallback(&session->hdr, dwContext,
3336 INTERNET_STATUS_HANDLE_CREATED, &request->hdr.hInternet,
3337 sizeof(HINTERNET));
3339 TRACE("<-- %u (%p)\n", res, request);
3341 if(res != ERROR_SUCCESS) {
3342 WININET_Release( &request->hdr );
3343 *ret = NULL;
3344 return res;
3347 *ret = request->hdr.hInternet;
3348 return ERROR_SUCCESS;
3351 /***********************************************************************
3352 * HttpOpenRequestW (WININET.@)
3354 * Open a HTTP request handle
3356 * RETURNS
3357 * HINTERNET a HTTP request handle on success
3358 * NULL on failure
3361 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
3362 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3363 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3364 DWORD dwFlags, DWORD_PTR dwContext)
3366 http_session_t *session;
3367 HINTERNET handle = NULL;
3368 DWORD res;
3370 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
3371 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
3372 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
3373 dwFlags, dwContext);
3374 if(lpszAcceptTypes!=NULL)
3376 int i;
3377 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
3378 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
3381 session = (http_session_t*) get_handle_object( hHttpSession );
3382 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
3384 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3385 goto lend;
3389 * My tests seem to show that the windows version does not
3390 * become asynchronous until after this point. And anyhow
3391 * if this call was asynchronous then how would you get the
3392 * necessary HINTERNET pointer returned by this function.
3395 res = HTTP_HttpOpenRequestW(session, lpszVerb, lpszObjectName,
3396 lpszVersion, lpszReferrer, lpszAcceptTypes,
3397 dwFlags, dwContext, &handle);
3398 lend:
3399 if( session )
3400 WININET_Release( &session->hdr );
3401 TRACE("returning %p\n", handle);
3402 if(res != ERROR_SUCCESS)
3403 SetLastError(res);
3404 return handle;
3407 static const LPCWSTR header_lookup[] = {
3408 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
3409 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3410 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3411 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
3412 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3413 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3414 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3415 szAllow, /* HTTP_QUERY_ALLOW = 7 */
3416 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
3417 szDate, /* HTTP_QUERY_DATE = 9 */
3418 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
3419 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3420 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
3421 szURI, /* HTTP_QUERY_URI = 13 */
3422 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
3423 NULL, /* HTTP_QUERY_COST = 15 */
3424 NULL, /* HTTP_QUERY_LINK = 16 */
3425 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
3426 NULL, /* HTTP_QUERY_VERSION = 18 */
3427 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
3428 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
3429 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
3430 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3431 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
3432 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
3433 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3434 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3435 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3436 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
3437 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3438 NULL, /* HTTP_QUERY_FORWARDED = 30 */
3439 NULL, /* HTTP_QUERY_FROM = 31 */
3440 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3441 szLocation, /* HTTP_QUERY_LOCATION = 33 */
3442 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
3443 szReferer, /* HTTP_QUERY_REFERER = 35 */
3444 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
3445 szServer, /* HTTP_QUERY_SERVER = 37 */
3446 NULL, /* HTTP_TITLE = 38 */
3447 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
3448 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3449 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3450 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3451 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
3452 szCookie, /* HTTP_QUERY_COOKIE = 44 */
3453 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3454 NULL, /* HTTP_QUERY_REFRESH = 46 */
3455 szContent_Disposition, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3456 szAge, /* HTTP_QUERY_AGE = 48 */
3457 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3458 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
3459 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3460 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3461 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3462 szETag, /* HTTP_QUERY_ETAG = 54 */
3463 hostW, /* HTTP_QUERY_HOST = 55 */
3464 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
3465 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3466 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
3467 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3468 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3469 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3470 szRange, /* HTTP_QUERY_RANGE = 62 */
3471 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3472 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
3473 szVary, /* HTTP_QUERY_VARY = 65 */
3474 szVia, /* HTTP_QUERY_VIA = 66 */
3475 szWarning, /* HTTP_QUERY_WARNING = 67 */
3476 szExpect, /* HTTP_QUERY_EXPECT = 68 */
3477 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3478 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3481 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3483 /***********************************************************************
3484 * HTTP_HttpQueryInfoW (internal)
3486 static DWORD HTTP_HttpQueryInfoW(http_request_t *request, DWORD dwInfoLevel,
3487 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3489 LPHTTPHEADERW lphttpHdr = NULL;
3490 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
3491 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
3492 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
3493 INT index = -1;
3495 /* Find requested header structure */
3496 switch (level)
3498 case HTTP_QUERY_CUSTOM:
3499 if (!lpBuffer) return ERROR_INVALID_PARAMETER;
3500 index = HTTP_GetCustomHeaderIndex(request, lpBuffer, requested_index, request_only);
3501 break;
3502 case HTTP_QUERY_RAW_HEADERS_CRLF:
3504 LPWSTR headers;
3505 DWORD len = 0;
3506 DWORD res = ERROR_INVALID_PARAMETER;
3508 if (request_only)
3509 headers = build_request_header(request, request->verb, request->path, request->version, TRUE);
3510 else
3511 headers = build_response_header(request, TRUE);
3512 if (!headers)
3513 return ERROR_OUTOFMEMORY;
3515 len = strlenW(headers) * sizeof(WCHAR);
3516 if (len + sizeof(WCHAR) > *lpdwBufferLength)
3518 len += sizeof(WCHAR);
3519 res = ERROR_INSUFFICIENT_BUFFER;
3521 else if (lpBuffer)
3523 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3524 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
3525 res = ERROR_SUCCESS;
3527 *lpdwBufferLength = len;
3529 heap_free(headers);
3530 return res;
3532 case HTTP_QUERY_RAW_HEADERS:
3534 LPWSTR headers;
3535 DWORD len;
3537 if (request_only)
3538 headers = build_request_header(request, request->verb, request->path, request->version, FALSE);
3539 else
3540 headers = build_response_header(request, FALSE);
3541 if (!headers)
3542 return ERROR_OUTOFMEMORY;
3544 len = strlenW(headers) * sizeof(WCHAR);
3545 if (len > *lpdwBufferLength)
3547 *lpdwBufferLength = len;
3548 heap_free(headers);
3549 return ERROR_INSUFFICIENT_BUFFER;
3552 if (lpBuffer)
3554 DWORD i;
3556 TRACE("returning data: %s\n", debugstr_wn(headers, len / sizeof(WCHAR)));
3558 for (i=0; i<len; i++)
3560 if (headers[i] == '\n')
3561 headers[i] = 0;
3563 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3565 *lpdwBufferLength = len - sizeof(WCHAR);
3567 heap_free(headers);
3568 return ERROR_SUCCESS;
3570 case HTTP_QUERY_STATUS_TEXT:
3571 if (request->statusText)
3573 DWORD len = strlenW(request->statusText);
3574 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3576 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3577 return ERROR_INSUFFICIENT_BUFFER;
3579 if (lpBuffer)
3581 memcpy(lpBuffer, request->statusText, (len + 1) * sizeof(WCHAR));
3582 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3584 *lpdwBufferLength = len * sizeof(WCHAR);
3585 return ERROR_SUCCESS;
3587 break;
3588 case HTTP_QUERY_VERSION:
3589 if (request->version)
3591 DWORD len = strlenW(request->version);
3592 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3594 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3595 return ERROR_INSUFFICIENT_BUFFER;
3597 if (lpBuffer)
3599 memcpy(lpBuffer, request->version, (len + 1) * sizeof(WCHAR));
3600 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3602 *lpdwBufferLength = len * sizeof(WCHAR);
3603 return ERROR_SUCCESS;
3605 break;
3606 case HTTP_QUERY_CONTENT_ENCODING:
3607 index = HTTP_GetCustomHeaderIndex(request, header_lookup[request->read_gzip ? HTTP_QUERY_CONTENT_TYPE : level],
3608 requested_index,request_only);
3609 break;
3610 case HTTP_QUERY_STATUS_CODE: {
3611 DWORD res = ERROR_SUCCESS;
3613 if(request_only)
3614 return ERROR_HTTP_INVALID_QUERY_REQUEST;
3616 if(requested_index)
3617 break;
3619 if(dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) {
3620 if(*lpdwBufferLength >= sizeof(DWORD))
3621 *(DWORD*)lpBuffer = request->status_code;
3622 else
3623 res = ERROR_INSUFFICIENT_BUFFER;
3624 *lpdwBufferLength = sizeof(DWORD);
3625 }else {
3626 WCHAR buf[12];
3627 DWORD size;
3628 static const WCHAR formatW[] = {'%','u',0};
3630 size = sprintfW(buf, formatW, request->status_code) * sizeof(WCHAR);
3632 if(size <= *lpdwBufferLength) {
3633 memcpy(lpBuffer, buf, size+sizeof(WCHAR));
3634 }else {
3635 size += sizeof(WCHAR);
3636 res = ERROR_INSUFFICIENT_BUFFER;
3639 *lpdwBufferLength = size;
3641 return res;
3643 default:
3644 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
3646 if (level < LAST_TABLE_HEADER && header_lookup[level])
3647 index = HTTP_GetCustomHeaderIndex(request, header_lookup[level],
3648 requested_index,request_only);
3651 if (index >= 0)
3652 lphttpHdr = &request->custHeaders[index];
3654 /* Ensure header satisfies requested attributes */
3655 if (!lphttpHdr ||
3656 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
3657 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
3659 return ERROR_HTTP_HEADER_NOT_FOUND;
3662 if (lpdwIndex) (*lpdwIndex)++;
3664 /* coalesce value to requested type */
3665 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
3667 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
3668 TRACE(" returning number: %d\n", *(int *)lpBuffer);
3670 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
3672 time_t tmpTime;
3673 struct tm tmpTM;
3674 SYSTEMTIME *STHook;
3676 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
3678 tmpTM = *gmtime(&tmpTime);
3679 STHook = (SYSTEMTIME *)lpBuffer;
3680 STHook->wDay = tmpTM.tm_mday;
3681 STHook->wHour = tmpTM.tm_hour;
3682 STHook->wMilliseconds = 0;
3683 STHook->wMinute = tmpTM.tm_min;
3684 STHook->wDayOfWeek = tmpTM.tm_wday;
3685 STHook->wMonth = tmpTM.tm_mon + 1;
3686 STHook->wSecond = tmpTM.tm_sec;
3687 STHook->wYear = 1900+tmpTM.tm_year;
3689 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3690 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
3691 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
3693 else if (lphttpHdr->lpszValue)
3695 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
3697 if (len > *lpdwBufferLength)
3699 *lpdwBufferLength = len;
3700 return ERROR_INSUFFICIENT_BUFFER;
3702 if (lpBuffer)
3704 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
3705 TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
3707 *lpdwBufferLength = len - sizeof(WCHAR);
3709 return ERROR_SUCCESS;
3712 /***********************************************************************
3713 * HttpQueryInfoW (WININET.@)
3715 * Queries for information about an HTTP request
3717 * RETURNS
3718 * TRUE on success
3719 * FALSE on failure
3722 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3723 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3725 http_request_t *request;
3726 DWORD res;
3728 if (TRACE_ON(wininet)) {
3729 #define FE(x) { x, #x }
3730 static const wininet_flag_info query_flags[] = {
3731 FE(HTTP_QUERY_MIME_VERSION),
3732 FE(HTTP_QUERY_CONTENT_TYPE),
3733 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
3734 FE(HTTP_QUERY_CONTENT_ID),
3735 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
3736 FE(HTTP_QUERY_CONTENT_LENGTH),
3737 FE(HTTP_QUERY_CONTENT_LANGUAGE),
3738 FE(HTTP_QUERY_ALLOW),
3739 FE(HTTP_QUERY_PUBLIC),
3740 FE(HTTP_QUERY_DATE),
3741 FE(HTTP_QUERY_EXPIRES),
3742 FE(HTTP_QUERY_LAST_MODIFIED),
3743 FE(HTTP_QUERY_MESSAGE_ID),
3744 FE(HTTP_QUERY_URI),
3745 FE(HTTP_QUERY_DERIVED_FROM),
3746 FE(HTTP_QUERY_COST),
3747 FE(HTTP_QUERY_LINK),
3748 FE(HTTP_QUERY_PRAGMA),
3749 FE(HTTP_QUERY_VERSION),
3750 FE(HTTP_QUERY_STATUS_CODE),
3751 FE(HTTP_QUERY_STATUS_TEXT),
3752 FE(HTTP_QUERY_RAW_HEADERS),
3753 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
3754 FE(HTTP_QUERY_CONNECTION),
3755 FE(HTTP_QUERY_ACCEPT),
3756 FE(HTTP_QUERY_ACCEPT_CHARSET),
3757 FE(HTTP_QUERY_ACCEPT_ENCODING),
3758 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
3759 FE(HTTP_QUERY_AUTHORIZATION),
3760 FE(HTTP_QUERY_CONTENT_ENCODING),
3761 FE(HTTP_QUERY_FORWARDED),
3762 FE(HTTP_QUERY_FROM),
3763 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
3764 FE(HTTP_QUERY_LOCATION),
3765 FE(HTTP_QUERY_ORIG_URI),
3766 FE(HTTP_QUERY_REFERER),
3767 FE(HTTP_QUERY_RETRY_AFTER),
3768 FE(HTTP_QUERY_SERVER),
3769 FE(HTTP_QUERY_TITLE),
3770 FE(HTTP_QUERY_USER_AGENT),
3771 FE(HTTP_QUERY_WWW_AUTHENTICATE),
3772 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
3773 FE(HTTP_QUERY_ACCEPT_RANGES),
3774 FE(HTTP_QUERY_SET_COOKIE),
3775 FE(HTTP_QUERY_COOKIE),
3776 FE(HTTP_QUERY_REQUEST_METHOD),
3777 FE(HTTP_QUERY_REFRESH),
3778 FE(HTTP_QUERY_CONTENT_DISPOSITION),
3779 FE(HTTP_QUERY_AGE),
3780 FE(HTTP_QUERY_CACHE_CONTROL),
3781 FE(HTTP_QUERY_CONTENT_BASE),
3782 FE(HTTP_QUERY_CONTENT_LOCATION),
3783 FE(HTTP_QUERY_CONTENT_MD5),
3784 FE(HTTP_QUERY_CONTENT_RANGE),
3785 FE(HTTP_QUERY_ETAG),
3786 FE(HTTP_QUERY_HOST),
3787 FE(HTTP_QUERY_IF_MATCH),
3788 FE(HTTP_QUERY_IF_NONE_MATCH),
3789 FE(HTTP_QUERY_IF_RANGE),
3790 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
3791 FE(HTTP_QUERY_MAX_FORWARDS),
3792 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
3793 FE(HTTP_QUERY_RANGE),
3794 FE(HTTP_QUERY_TRANSFER_ENCODING),
3795 FE(HTTP_QUERY_UPGRADE),
3796 FE(HTTP_QUERY_VARY),
3797 FE(HTTP_QUERY_VIA),
3798 FE(HTTP_QUERY_WARNING),
3799 FE(HTTP_QUERY_CUSTOM)
3801 static const wininet_flag_info modifier_flags[] = {
3802 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
3803 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
3804 FE(HTTP_QUERY_FLAG_NUMBER),
3805 FE(HTTP_QUERY_FLAG_COALESCE)
3807 #undef FE
3808 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
3809 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
3810 DWORD i;
3812 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, info);
3813 TRACE(" Attribute:");
3814 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
3815 if (query_flags[i].val == info) {
3816 TRACE(" %s", query_flags[i].name);
3817 break;
3820 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
3821 TRACE(" Unknown (%08x)", info);
3824 TRACE(" Modifier:");
3825 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
3826 if (modifier_flags[i].val & info_mod) {
3827 TRACE(" %s", modifier_flags[i].name);
3828 info_mod &= ~ modifier_flags[i].val;
3832 if (info_mod) {
3833 TRACE(" Unknown (%08x)", info_mod);
3835 TRACE("\n");
3838 request = (http_request_t*) get_handle_object( hHttpRequest );
3839 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
3841 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3842 goto lend;
3845 if (lpBuffer == NULL)
3846 *lpdwBufferLength = 0;
3847 res = HTTP_HttpQueryInfoW( request, dwInfoLevel,
3848 lpBuffer, lpdwBufferLength, lpdwIndex);
3850 lend:
3851 if( request )
3852 WININET_Release( &request->hdr );
3854 TRACE("%u <--\n", res);
3855 if(res != ERROR_SUCCESS)
3856 SetLastError(res);
3857 return res == ERROR_SUCCESS;
3860 /***********************************************************************
3861 * HttpQueryInfoA (WININET.@)
3863 * Queries for information about an HTTP request
3865 * RETURNS
3866 * TRUE on success
3867 * FALSE on failure
3870 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3871 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3873 BOOL result;
3874 DWORD len;
3875 WCHAR* bufferW;
3877 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
3878 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
3880 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
3881 lpdwBufferLength, lpdwIndex );
3884 if (lpBuffer)
3886 DWORD alloclen;
3887 len = (*lpdwBufferLength)*sizeof(WCHAR);
3888 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3890 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
3891 if (alloclen < len)
3892 alloclen = len;
3894 else
3895 alloclen = len;
3896 bufferW = heap_alloc(alloclen);
3897 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3898 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3899 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
3900 } else
3902 bufferW = NULL;
3903 len = 0;
3906 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
3907 &len, lpdwIndex );
3908 if( result )
3910 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
3911 lpBuffer, *lpdwBufferLength, NULL, NULL );
3912 *lpdwBufferLength = len - 1;
3914 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
3916 else
3917 /* since the strings being returned from HttpQueryInfoW should be
3918 * only ASCII characters, it is reasonable to assume that all of
3919 * the Unicode characters can be reduced to a single byte */
3920 *lpdwBufferLength = len / sizeof(WCHAR);
3922 heap_free( bufferW );
3923 return result;
3926 /***********************************************************************
3927 * HTTP_GetRedirectURL (internal)
3929 static LPWSTR HTTP_GetRedirectURL(http_request_t *request, LPCWSTR lpszUrl)
3931 static WCHAR szHttp[] = {'h','t','t','p',0};
3932 static WCHAR szHttps[] = {'h','t','t','p','s',0};
3933 http_session_t *session = request->session;
3934 URL_COMPONENTSW urlComponents;
3935 DWORD url_length = 0;
3936 LPWSTR orig_url;
3937 LPWSTR combined_url;
3939 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3940 urlComponents.lpszScheme = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
3941 urlComponents.dwSchemeLength = 0;
3942 urlComponents.lpszHostName = session->hostName;
3943 urlComponents.dwHostNameLength = 0;
3944 urlComponents.nPort = session->hostPort;
3945 urlComponents.lpszUserName = session->userName;
3946 urlComponents.dwUserNameLength = 0;
3947 urlComponents.lpszPassword = NULL;
3948 urlComponents.dwPasswordLength = 0;
3949 urlComponents.lpszUrlPath = request->path;
3950 urlComponents.dwUrlPathLength = 0;
3951 urlComponents.lpszExtraInfo = NULL;
3952 urlComponents.dwExtraInfoLength = 0;
3954 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
3955 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
3956 return NULL;
3958 orig_url = heap_alloc(url_length);
3960 /* convert from bytes to characters */
3961 url_length = url_length / sizeof(WCHAR) - 1;
3962 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
3964 heap_free(orig_url);
3965 return NULL;
3968 url_length = 0;
3969 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
3970 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
3972 heap_free(orig_url);
3973 return NULL;
3975 combined_url = heap_alloc(url_length * sizeof(WCHAR));
3977 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
3979 heap_free(orig_url);
3980 heap_free(combined_url);
3981 return NULL;
3983 heap_free(orig_url);
3984 return combined_url;
3988 /***********************************************************************
3989 * HTTP_HandleRedirect (internal)
3991 static DWORD HTTP_HandleRedirect(http_request_t *request, LPCWSTR lpszUrl)
3993 http_session_t *session = request->session;
3994 WCHAR path[INTERNET_MAX_PATH_LENGTH];
3995 int index;
3997 if(lpszUrl[0]=='/')
3999 /* if it's an absolute path, keep the same session info */
4000 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
4002 else
4004 URL_COMPONENTSW urlComponents;
4005 WCHAR protocol[INTERNET_MAX_SCHEME_LENGTH];
4006 WCHAR hostName[INTERNET_MAX_HOST_NAME_LENGTH];
4007 WCHAR userName[INTERNET_MAX_USER_NAME_LENGTH];
4008 BOOL custom_port = FALSE;
4010 static WCHAR httpW[] = {'h','t','t','p',0};
4011 static WCHAR httpsW[] = {'h','t','t','p','s',0};
4013 userName[0] = 0;
4014 hostName[0] = 0;
4015 protocol[0] = 0;
4017 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
4018 urlComponents.lpszScheme = protocol;
4019 urlComponents.dwSchemeLength = INTERNET_MAX_SCHEME_LENGTH;
4020 urlComponents.lpszHostName = hostName;
4021 urlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
4022 urlComponents.lpszUserName = userName;
4023 urlComponents.dwUserNameLength = INTERNET_MAX_USER_NAME_LENGTH;
4024 urlComponents.lpszPassword = NULL;
4025 urlComponents.dwPasswordLength = 0;
4026 urlComponents.lpszUrlPath = path;
4027 urlComponents.dwUrlPathLength = INTERNET_MAX_PATH_LENGTH;
4028 urlComponents.lpszExtraInfo = NULL;
4029 urlComponents.dwExtraInfoLength = 0;
4030 if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
4031 return INTERNET_GetLastError();
4033 if(!strcmpiW(protocol, httpW)) {
4034 if(request->hdr.dwFlags & INTERNET_FLAG_SECURE) {
4035 TRACE("redirect from secure page to non-secure page\n");
4036 /* FIXME: warn about from secure redirect to non-secure page */
4037 request->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
4040 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4041 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
4042 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT)
4043 custom_port = TRUE;
4044 }else if(!strcmpiW(protocol, httpsW)) {
4045 if(!(request->hdr.dwFlags & INTERNET_FLAG_SECURE)) {
4046 TRACE("redirect from non-secure page to secure page\n");
4047 /* FIXME: notify about redirect to secure page */
4048 request->hdr.dwFlags |= INTERNET_FLAG_SECURE;
4051 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4052 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
4053 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
4054 custom_port = TRUE;
4057 heap_free(session->hostName);
4059 if(custom_port) {
4060 int len;
4061 static const WCHAR fmt[] = {'%','s',':','%','u',0};
4062 len = lstrlenW(hostName);
4063 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
4064 session->hostName = heap_alloc(len*sizeof(WCHAR));
4065 sprintfW(session->hostName, fmt, hostName, urlComponents.nPort);
4067 else
4068 session->hostName = heap_strdupW(hostName);
4070 HTTP_ProcessHeader(request, hostW, session->hostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4072 heap_free(session->userName);
4073 session->userName = NULL;
4074 if (userName[0])
4075 session->userName = heap_strdupW(userName);
4077 reset_data_stream(request);
4079 if(strcmpiW(request->server->name, hostName) || request->server->port != urlComponents.nPort) {
4080 server_t *new_server;
4082 new_server = get_server(hostName, urlComponents.nPort, urlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
4083 server_release(request->server);
4084 request->server = new_server;
4087 heap_free(request->path);
4088 request->path=NULL;
4089 if (*path)
4091 DWORD needed = 0;
4092 HRESULT rc;
4094 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
4095 if (rc != E_POINTER)
4096 needed = strlenW(path)+1;
4097 request->path = heap_alloc(needed*sizeof(WCHAR));
4098 rc = UrlEscapeW(path, request->path, &needed,
4099 URL_ESCAPE_SPACES_ONLY);
4100 if (rc != S_OK)
4102 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4103 strcpyW(request->path,path);
4107 /* Remove custom content-type/length headers on redirects. */
4108 index = HTTP_GetCustomHeaderIndex(request, szContent_Type, 0, TRUE);
4109 if (0 <= index)
4110 HTTP_DeleteCustomHeader(request, index);
4111 index = HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE);
4112 if (0 <= index)
4113 HTTP_DeleteCustomHeader(request, index);
4115 return ERROR_SUCCESS;
4118 /***********************************************************************
4119 * HTTP_build_req (internal)
4121 * concatenate all the strings in the request together
4123 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
4125 LPCWSTR *t;
4126 LPWSTR str;
4128 for( t = list; *t ; t++ )
4129 len += strlenW( *t );
4130 len++;
4132 str = heap_alloc(len*sizeof(WCHAR));
4133 *str = 0;
4135 for( t = list; *t ; t++ )
4136 strcatW( str, *t );
4138 return str;
4141 static DWORD HTTP_SecureProxyConnect(http_request_t *request)
4143 server_t *server = request->server;
4144 LPWSTR requestString;
4145 INT len;
4146 INT cnt;
4147 INT responseLen;
4148 char *ascii_req;
4149 DWORD res;
4151 static const WCHAR connectW[] = {'C','O','N','N','E','C','T',0};
4153 TRACE("\n");
4155 requestString = build_request_header( request, connectW, server->host_port, g_szHttp1_1, TRUE );
4157 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
4158 NULL, 0, NULL, NULL );
4159 len--; /* the nul terminator isn't needed */
4160 ascii_req = heap_alloc(len);
4161 WideCharToMultiByte( CP_ACP, 0, requestString, -1, ascii_req, len, NULL, NULL );
4162 heap_free( requestString );
4164 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
4166 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
4167 res = NETCON_send( request->netconn, ascii_req, len, 0, &cnt );
4168 heap_free( ascii_req );
4169 if (res != ERROR_SUCCESS)
4170 return res;
4172 if (HTTP_GetResponseHeaders( request, &responseLen ) || !responseLen)
4173 return ERROR_HTTP_INVALID_HEADER;
4175 return ERROR_SUCCESS;
4178 static void HTTP_InsertCookies(http_request_t *request)
4180 DWORD cookie_size, size, cnt = 0;
4181 HTTPHEADERW *host;
4182 WCHAR *cookies;
4184 static const WCHAR cookieW[] = {'C','o','o','k','i','e',':',' ',0};
4186 host = HTTP_GetHeader(request, hostW);
4187 if(!host)
4188 return;
4190 if(get_cookie(host->lpszValue, request->path, NULL, &cookie_size) != ERROR_SUCCESS)
4191 return;
4193 size = sizeof(cookieW) + cookie_size * sizeof(WCHAR) + sizeof(szCrLf);
4194 if(!(cookies = heap_alloc(size)))
4195 return;
4197 cnt += sprintfW(cookies, cookieW);
4198 get_cookie(host->lpszValue, request->path, cookies+cnt, &cookie_size);
4199 strcatW(cookies, szCrLf);
4201 HTTP_HttpAddRequestHeadersW(request, cookies, strlenW(cookies), HTTP_ADDREQ_FLAG_REPLACE);
4203 heap_free(cookies);
4206 static WORD HTTP_ParseWkday(LPCWSTR day)
4208 static const WCHAR days[7][4] = {{ 's','u','n',0 },
4209 { 'm','o','n',0 },
4210 { 't','u','e',0 },
4211 { 'w','e','d',0 },
4212 { 't','h','u',0 },
4213 { 'f','r','i',0 },
4214 { 's','a','t',0 }};
4215 unsigned int i;
4216 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4217 if (!strcmpiW(day, days[i]))
4218 return i;
4220 /* Invalid */
4221 return 7;
4224 static WORD HTTP_ParseMonth(LPCWSTR month)
4226 static const WCHAR jan[] = { 'j','a','n',0 };
4227 static const WCHAR feb[] = { 'f','e','b',0 };
4228 static const WCHAR mar[] = { 'm','a','r',0 };
4229 static const WCHAR apr[] = { 'a','p','r',0 };
4230 static const WCHAR may[] = { 'm','a','y',0 };
4231 static const WCHAR jun[] = { 'j','u','n',0 };
4232 static const WCHAR jul[] = { 'j','u','l',0 };
4233 static const WCHAR aug[] = { 'a','u','g',0 };
4234 static const WCHAR sep[] = { 's','e','p',0 };
4235 static const WCHAR oct[] = { 'o','c','t',0 };
4236 static const WCHAR nov[] = { 'n','o','v',0 };
4237 static const WCHAR dec[] = { 'd','e','c',0 };
4239 if (!strcmpiW(month, jan)) return 1;
4240 if (!strcmpiW(month, feb)) return 2;
4241 if (!strcmpiW(month, mar)) return 3;
4242 if (!strcmpiW(month, apr)) return 4;
4243 if (!strcmpiW(month, may)) return 5;
4244 if (!strcmpiW(month, jun)) return 6;
4245 if (!strcmpiW(month, jul)) return 7;
4246 if (!strcmpiW(month, aug)) return 8;
4247 if (!strcmpiW(month, sep)) return 9;
4248 if (!strcmpiW(month, oct)) return 10;
4249 if (!strcmpiW(month, nov)) return 11;
4250 if (!strcmpiW(month, dec)) return 12;
4251 /* Invalid */
4252 return 0;
4255 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4256 * optionally preceded by whitespace.
4257 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4258 * st, and sets *str to the first character after the time format.
4260 static BOOL HTTP_ParseTime(SYSTEMTIME *st, LPCWSTR *str)
4262 LPCWSTR ptr = *str;
4263 WCHAR *nextPtr;
4264 unsigned long num;
4266 while (isspaceW(*ptr))
4267 ptr++;
4269 num = strtoulW(ptr, &nextPtr, 10);
4270 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4272 ERR("unexpected time format %s\n", debugstr_w(ptr));
4273 return FALSE;
4275 if (num > 23)
4277 ERR("unexpected hour in time format %s\n", debugstr_w(ptr));
4278 return FALSE;
4280 ptr = nextPtr + 1;
4281 st->wHour = (WORD)num;
4282 num = strtoulW(ptr, &nextPtr, 10);
4283 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4285 ERR("unexpected time format %s\n", debugstr_w(ptr));
4286 return FALSE;
4288 if (num > 59)
4290 ERR("unexpected minute in time format %s\n", debugstr_w(ptr));
4291 return FALSE;
4293 ptr = nextPtr + 1;
4294 st->wMinute = (WORD)num;
4295 num = strtoulW(ptr, &nextPtr, 10);
4296 if (!nextPtr || nextPtr <= ptr)
4298 ERR("unexpected time format %s\n", debugstr_w(ptr));
4299 return FALSE;
4301 if (num > 59)
4303 ERR("unexpected second in time format %s\n", debugstr_w(ptr));
4304 return FALSE;
4306 ptr = nextPtr + 1;
4307 *str = ptr;
4308 st->wSecond = (WORD)num;
4309 return TRUE;
4312 static BOOL HTTP_ParseDateAsAsctime(LPCWSTR value, FILETIME *ft)
4314 static const WCHAR gmt[]= { 'G','M','T',0 };
4315 WCHAR day[4], *dayPtr, month[4], *monthPtr, *nextPtr;
4316 LPCWSTR ptr;
4317 SYSTEMTIME st = { 0 };
4318 unsigned long num;
4320 for (ptr = value, dayPtr = day; *ptr && !isspaceW(*ptr) &&
4321 dayPtr - day < sizeof(day) / sizeof(day[0]) - 1; ptr++, dayPtr++)
4322 *dayPtr = *ptr;
4323 *dayPtr = 0;
4324 st.wDayOfWeek = HTTP_ParseWkday(day);
4325 if (st.wDayOfWeek >= 7)
4327 ERR("unexpected weekday %s\n", debugstr_w(day));
4328 return FALSE;
4331 while (isspaceW(*ptr))
4332 ptr++;
4334 for (monthPtr = month; !isspace(*ptr) &&
4335 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4336 monthPtr++, ptr++)
4337 *monthPtr = *ptr;
4338 *monthPtr = 0;
4339 st.wMonth = HTTP_ParseMonth(month);
4340 if (!st.wMonth || st.wMonth > 12)
4342 ERR("unexpected month %s\n", debugstr_w(month));
4343 return FALSE;
4346 while (isspaceW(*ptr))
4347 ptr++;
4349 num = strtoulW(ptr, &nextPtr, 10);
4350 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4352 ERR("unexpected day %s\n", debugstr_w(ptr));
4353 return FALSE;
4355 ptr = nextPtr;
4356 st.wDay = (WORD)num;
4358 while (isspaceW(*ptr))
4359 ptr++;
4361 if (!HTTP_ParseTime(&st, &ptr))
4362 return FALSE;
4364 while (isspaceW(*ptr))
4365 ptr++;
4367 num = strtoulW(ptr, &nextPtr, 10);
4368 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4370 ERR("unexpected year %s\n", debugstr_w(ptr));
4371 return FALSE;
4373 ptr = nextPtr;
4374 st.wYear = (WORD)num;
4376 while (isspaceW(*ptr))
4377 ptr++;
4379 /* asctime() doesn't report a timezone, but some web servers do, so accept
4380 * with or without GMT.
4382 if (*ptr && strcmpW(ptr, gmt))
4384 ERR("unexpected timezone %s\n", debugstr_w(ptr));
4385 return FALSE;
4387 return SystemTimeToFileTime(&st, ft);
4390 static BOOL HTTP_ParseRfc1123Date(LPCWSTR value, FILETIME *ft)
4392 static const WCHAR gmt[]= { 'G','M','T',0 };
4393 WCHAR *nextPtr, day[4], month[4], *monthPtr;
4394 LPCWSTR ptr;
4395 unsigned long num;
4396 SYSTEMTIME st = { 0 };
4398 ptr = strchrW(value, ',');
4399 if (!ptr)
4400 return FALSE;
4401 if (ptr - value != 3)
4403 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4404 return FALSE;
4406 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4407 day[3] = 0;
4408 st.wDayOfWeek = HTTP_ParseWkday(day);
4409 if (st.wDayOfWeek > 6)
4411 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4412 return FALSE;
4414 ptr++;
4416 while (isspaceW(*ptr))
4417 ptr++;
4419 num = strtoulW(ptr, &nextPtr, 10);
4420 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4422 WARN("unexpected day %s\n", debugstr_w(value));
4423 return FALSE;
4425 ptr = nextPtr;
4426 st.wDay = (WORD)num;
4428 while (isspaceW(*ptr))
4429 ptr++;
4431 for (monthPtr = month; !isspace(*ptr) &&
4432 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4433 monthPtr++, ptr++)
4434 *monthPtr = *ptr;
4435 *monthPtr = 0;
4436 st.wMonth = HTTP_ParseMonth(month);
4437 if (!st.wMonth || st.wMonth > 12)
4439 WARN("unexpected month %s\n", debugstr_w(month));
4440 return FALSE;
4443 while (isspaceW(*ptr))
4444 ptr++;
4446 num = strtoulW(ptr, &nextPtr, 10);
4447 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4449 ERR("unexpected year %s\n", debugstr_w(value));
4450 return FALSE;
4452 ptr = nextPtr;
4453 st.wYear = (WORD)num;
4455 if (!HTTP_ParseTime(&st, &ptr))
4456 return FALSE;
4458 while (isspaceW(*ptr))
4459 ptr++;
4461 if (strcmpW(ptr, gmt))
4463 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4464 return FALSE;
4466 return SystemTimeToFileTime(&st, ft);
4469 static WORD HTTP_ParseWeekday(LPCWSTR day)
4471 static const WCHAR days[7][10] = {{ 's','u','n','d','a','y',0 },
4472 { 'm','o','n','d','a','y',0 },
4473 { 't','u','e','s','d','a','y',0 },
4474 { 'w','e','d','n','e','s','d','a','y',0 },
4475 { 't','h','u','r','s','d','a','y',0 },
4476 { 'f','r','i','d','a','y',0 },
4477 { 's','a','t','u','r','d','a','y',0 }};
4478 unsigned int i;
4479 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4480 if (!strcmpiW(day, days[i]))
4481 return i;
4483 /* Invalid */
4484 return 7;
4487 static BOOL HTTP_ParseRfc850Date(LPCWSTR value, FILETIME *ft)
4489 static const WCHAR gmt[]= { 'G','M','T',0 };
4490 WCHAR *nextPtr, day[10], month[4], *monthPtr;
4491 LPCWSTR ptr;
4492 unsigned long num;
4493 SYSTEMTIME st = { 0 };
4495 ptr = strchrW(value, ',');
4496 if (!ptr)
4497 return FALSE;
4498 if (ptr - value == 3)
4500 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4501 day[3] = 0;
4502 st.wDayOfWeek = HTTP_ParseWkday(day);
4503 if (st.wDayOfWeek > 6)
4505 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4506 return FALSE;
4509 else if (ptr - value < sizeof(day) / sizeof(day[0]))
4511 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4512 day[ptr - value + 1] = 0;
4513 st.wDayOfWeek = HTTP_ParseWeekday(day);
4514 if (st.wDayOfWeek > 6)
4516 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4517 return FALSE;
4520 else
4522 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4523 return FALSE;
4525 ptr++;
4527 while (isspaceW(*ptr))
4528 ptr++;
4530 num = strtoulW(ptr, &nextPtr, 10);
4531 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4533 ERR("unexpected day %s\n", debugstr_w(value));
4534 return FALSE;
4536 ptr = nextPtr;
4537 st.wDay = (WORD)num;
4539 if (*ptr != '-')
4541 ERR("unexpected month format %s\n", debugstr_w(ptr));
4542 return FALSE;
4544 ptr++;
4546 for (monthPtr = month; *ptr != '-' &&
4547 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4548 monthPtr++, ptr++)
4549 *monthPtr = *ptr;
4550 *monthPtr = 0;
4551 st.wMonth = HTTP_ParseMonth(month);
4552 if (!st.wMonth || st.wMonth > 12)
4554 ERR("unexpected month %s\n", debugstr_w(month));
4555 return FALSE;
4558 if (*ptr != '-')
4560 ERR("unexpected year format %s\n", debugstr_w(ptr));
4561 return FALSE;
4563 ptr++;
4565 num = strtoulW(ptr, &nextPtr, 10);
4566 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4568 ERR("unexpected year %s\n", debugstr_w(value));
4569 return FALSE;
4571 ptr = nextPtr;
4572 st.wYear = (WORD)num;
4574 if (!HTTP_ParseTime(&st, &ptr))
4575 return FALSE;
4577 while (isspaceW(*ptr))
4578 ptr++;
4580 if (strcmpW(ptr, gmt))
4582 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4583 return FALSE;
4585 return SystemTimeToFileTime(&st, ft);
4588 static BOOL HTTP_ParseDate(LPCWSTR value, FILETIME *ft)
4590 static const WCHAR zero[] = { '0',0 };
4591 BOOL ret;
4593 if (!strcmpW(value, zero))
4595 ft->dwLowDateTime = ft->dwHighDateTime = 0;
4596 ret = TRUE;
4598 else if (strchrW(value, ','))
4600 ret = HTTP_ParseRfc1123Date(value, ft);
4601 if (!ret)
4603 ret = HTTP_ParseRfc850Date(value, ft);
4604 if (!ret)
4605 ERR("unexpected date format %s\n", debugstr_w(value));
4608 else
4610 ret = HTTP_ParseDateAsAsctime(value, ft);
4611 if (!ret)
4612 ERR("unexpected date format %s\n", debugstr_w(value));
4614 return ret;
4617 static void HTTP_ProcessExpires(http_request_t *request)
4619 BOOL expirationFound = FALSE;
4620 int headerIndex;
4622 /* Look for a Cache-Control header with a max-age directive, as it takes
4623 * precedence over the Expires header.
4625 headerIndex = HTTP_GetCustomHeaderIndex(request, szCache_Control, 0, FALSE);
4626 if (headerIndex != -1)
4628 LPHTTPHEADERW ccHeader = &request->custHeaders[headerIndex];
4629 LPWSTR ptr;
4631 for (ptr = ccHeader->lpszValue; ptr && *ptr; )
4633 LPWSTR comma = strchrW(ptr, ','), end, equal;
4635 if (comma)
4636 end = comma;
4637 else
4638 end = ptr + strlenW(ptr);
4639 for (equal = end - 1; equal > ptr && *equal != '='; equal--)
4641 if (*equal == '=')
4643 static const WCHAR max_age[] = {
4644 'm','a','x','-','a','g','e',0 };
4646 if (!strncmpiW(ptr, max_age, equal - ptr - 1))
4648 LPWSTR nextPtr;
4649 unsigned long age;
4651 age = strtoulW(equal + 1, &nextPtr, 10);
4652 if (nextPtr > equal + 1)
4654 LARGE_INTEGER ft;
4656 NtQuerySystemTime( &ft );
4657 /* Age is in seconds, FILETIME resolution is in
4658 * 100 nanosecond intervals.
4660 ft.QuadPart += age * (ULONGLONG)1000000;
4661 request->expires.dwLowDateTime = ft.u.LowPart;
4662 request->expires.dwHighDateTime = ft.u.HighPart;
4663 expirationFound = TRUE;
4667 if (comma)
4669 ptr = comma + 1;
4670 while (isspaceW(*ptr))
4671 ptr++;
4673 else
4674 ptr = NULL;
4677 if (!expirationFound)
4679 headerIndex = HTTP_GetCustomHeaderIndex(request, szExpires, 0, FALSE);
4680 if (headerIndex != -1)
4682 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4683 FILETIME ft;
4685 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4687 expirationFound = TRUE;
4688 request->expires = ft;
4692 if (!expirationFound)
4694 LARGE_INTEGER t;
4696 /* With no known age, default to 10 minutes until expiration. */
4697 NtQuerySystemTime( &t );
4698 t.QuadPart += 10 * 60 * (ULONGLONG)10000000;
4699 request->expires.dwLowDateTime = t.u.LowPart;
4700 request->expires.dwHighDateTime = t.u.HighPart;
4704 static void HTTP_ProcessLastModified(http_request_t *request)
4706 int headerIndex;
4708 headerIndex = HTTP_GetCustomHeaderIndex(request, szLast_Modified, 0, FALSE);
4709 if (headerIndex != -1)
4711 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4712 FILETIME ft;
4714 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4715 request->last_modified = ft;
4719 static void http_process_keep_alive(http_request_t *req)
4721 int index;
4723 if ((index = HTTP_GetCustomHeaderIndex(req, szConnection, 0, FALSE)) != -1)
4724 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4725 else if ((index = HTTP_GetCustomHeaderIndex(req, szProxy_Connection, 0, FALSE)) != -1)
4726 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4727 else
4728 req->netconn->keep_alive = !strcmpiW(req->version, g_szHttp1_1);
4731 static DWORD open_http_connection(http_request_t *request, BOOL *reusing)
4733 const BOOL is_https = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) != 0;
4734 netconn_t *netconn = NULL;
4735 DWORD res;
4737 assert(!request->netconn);
4738 reset_data_stream(request);
4740 res = HTTP_ResolveName(request);
4741 if(res != ERROR_SUCCESS)
4742 return res;
4744 EnterCriticalSection(&connection_pool_cs);
4746 while(!list_empty(&request->server->conn_pool)) {
4747 netconn = LIST_ENTRY(list_head(&request->server->conn_pool), netconn_t, pool_entry);
4748 list_remove(&netconn->pool_entry);
4750 if(NETCON_is_alive(netconn))
4751 break;
4753 TRACE("connection %p closed during idle\n", netconn);
4754 free_netconn(netconn);
4755 netconn = NULL;
4758 LeaveCriticalSection(&connection_pool_cs);
4760 if(netconn) {
4761 TRACE("<-- reusing %p netconn\n", netconn);
4762 request->netconn = netconn;
4763 *reusing = TRUE;
4764 return ERROR_SUCCESS;
4767 TRACE("connecting to %s, proxy %s\n", debugstr_w(request->server->name),
4768 request->proxy ? debugstr_w(request->proxy->name) : "(null)");
4770 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4771 INTERNET_STATUS_CONNECTING_TO_SERVER,
4772 request->server->addr_str,
4773 strlen(request->server->addr_str)+1);
4775 res = create_netconn(is_https, request->proxy ? request->proxy : request->server, request->security_flags,
4776 (request->hdr.ErrorMask & INTERNET_ERROR_MASK_COMBINED_SEC_CERT) != 0,
4777 request->connect_timeout, &netconn);
4778 if(res != ERROR_SUCCESS) {
4779 ERR("create_netconn failed: %u\n", res);
4780 return res;
4783 request->netconn = netconn;
4785 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4786 INTERNET_STATUS_CONNECTED_TO_SERVER,
4787 request->server->addr_str, strlen(request->server->addr_str)+1);
4789 if(is_https) {
4790 /* Note: we differ from Microsoft's WinINet here. they seem to have
4791 * a bug that causes no status callbacks to be sent when starting
4792 * a tunnel to a proxy server using the CONNECT verb. i believe our
4793 * behaviour to be more correct and to not cause any incompatibilities
4794 * because using a secure connection through a proxy server is a rare
4795 * case that would be hard for anyone to depend on */
4796 if(request->proxy)
4797 res = HTTP_SecureProxyConnect(request);
4798 if(res == ERROR_SUCCESS)
4799 res = NETCON_secure_connect(request->netconn, request->server);
4802 if(res != ERROR_SUCCESS) {
4803 http_release_netconn(request, FALSE);
4804 return res;
4807 *reusing = FALSE;
4808 TRACE("Created connection to %s: %p\n", debugstr_w(request->server->name), netconn);
4809 return ERROR_SUCCESS;
4812 /***********************************************************************
4813 * HTTP_HttpSendRequestW (internal)
4815 * Sends the specified request to the HTTP server
4817 * RETURNS
4818 * ERROR_SUCCESS on success
4819 * win32 error code on failure
4822 static DWORD HTTP_HttpSendRequestW(http_request_t *request, LPCWSTR lpszHeaders,
4823 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
4824 DWORD dwContentLength, BOOL bEndRequest)
4826 INT cnt;
4827 BOOL redirected = FALSE;
4828 LPWSTR requestString = NULL;
4829 INT responseLen;
4830 BOOL loop_next;
4831 static const WCHAR szPost[] = { 'P','O','S','T',0 };
4832 static const WCHAR szContentLength[] =
4833 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
4834 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
4835 DWORD res;
4837 TRACE("--> %p\n", request);
4839 assert(request->hdr.htype == WH_HHTTPREQ);
4841 /* if the verb is NULL default to GET */
4842 if (!request->verb)
4843 request->verb = heap_strdupW(szGET);
4845 if (dwContentLength || strcmpW(request->verb, szGET))
4847 sprintfW(contentLengthStr, szContentLength, dwContentLength);
4848 HTTP_HttpAddRequestHeadersW(request, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_REPLACE);
4849 request->bytesToWrite = dwContentLength;
4851 if (request->session->appInfo->agent)
4853 WCHAR *agent_header;
4854 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4855 int len;
4857 len = strlenW(request->session->appInfo->agent) + strlenW(user_agent);
4858 agent_header = heap_alloc(len * sizeof(WCHAR));
4859 sprintfW(agent_header, user_agent, request->session->appInfo->agent);
4861 HTTP_HttpAddRequestHeadersW(request, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4862 heap_free(agent_header);
4864 if (request->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
4866 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4867 HTTP_HttpAddRequestHeadersW(request, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4869 if ((request->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && !strcmpW(request->verb, szPost))
4871 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4872 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4873 HTTP_HttpAddRequestHeadersW(request, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4876 /* add the headers the caller supplied */
4877 if( lpszHeaders && dwHeaderLength )
4878 HTTP_HttpAddRequestHeadersW(request, lpszHeaders, dwHeaderLength, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
4882 DWORD len;
4883 BOOL reusing_connection;
4884 char *ascii_req;
4886 loop_next = FALSE;
4887 reusing_connection = request->netconn != NULL;
4889 if(redirected) {
4890 request->contentLength = ~0u;
4891 request->bytesToWrite = 0;
4894 if (TRACE_ON(wininet))
4896 LPHTTPHEADERW Host = HTTP_GetHeader(request, hostW);
4897 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(request->path));
4900 HTTP_FixURL(request);
4901 if (request->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
4903 HTTP_ProcessHeader(request, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
4905 HTTP_InsertAuthorization(request, request->authInfo, szAuthorization);
4906 HTTP_InsertAuthorization(request, request->proxyAuthInfo, szProxy_Authorization);
4908 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
4909 HTTP_InsertCookies(request);
4911 if (request->proxy)
4913 WCHAR *url = build_proxy_path_url(request);
4914 requestString = build_request_header(request, request->verb, url, request->version, TRUE);
4915 heap_free(url);
4917 else
4918 requestString = build_request_header(request, request->verb, request->path, request->version, TRUE);
4921 TRACE("Request header -> %s\n", debugstr_w(requestString) );
4923 if (!reusing_connection && (res = open_http_connection(request, &reusing_connection)) != ERROR_SUCCESS)
4924 break;
4926 /* send the request as ASCII, tack on the optional data */
4927 if (!lpOptional || redirected)
4928 dwOptionalLength = 0;
4929 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
4930 NULL, 0, NULL, NULL );
4931 ascii_req = heap_alloc(len + dwOptionalLength);
4932 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
4933 ascii_req, len, NULL, NULL );
4934 if( lpOptional )
4935 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
4936 len = (len + dwOptionalLength - 1);
4937 ascii_req[len] = 0;
4938 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
4940 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4941 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
4943 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
4944 res = NETCON_send(request->netconn, ascii_req, len, 0, &cnt);
4945 heap_free( ascii_req );
4946 if(res != ERROR_SUCCESS) {
4947 TRACE("send failed: %u\n", res);
4948 if(!reusing_connection)
4949 break;
4950 http_release_netconn(request, FALSE);
4951 loop_next = TRUE;
4952 continue;
4955 request->bytesWritten = dwOptionalLength;
4957 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4958 INTERNET_STATUS_REQUEST_SENT,
4959 &len, sizeof(DWORD));
4961 if (bEndRequest)
4963 DWORD dwBufferSize;
4965 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4966 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
4968 if (HTTP_GetResponseHeaders(request, &responseLen))
4970 http_release_netconn(request, FALSE);
4971 res = ERROR_INTERNET_CONNECTION_ABORTED;
4972 goto lend;
4974 /* FIXME: We should know that connection is closed before sending
4975 * headers. Otherwise wrong callbacks are executed */
4976 if(!responseLen && reusing_connection) {
4977 TRACE("Connection closed by server, reconnecting\n");
4978 http_release_netconn(request, FALSE);
4979 loop_next = TRUE;
4980 continue;
4983 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4984 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
4985 sizeof(DWORD));
4987 http_process_keep_alive(request);
4988 HTTP_ProcessCookies(request);
4989 HTTP_ProcessExpires(request);
4990 HTTP_ProcessLastModified(request);
4992 res = set_content_length(request);
4993 if(res != ERROR_SUCCESS)
4994 goto lend;
4995 if(!request->contentLength)
4996 http_release_netconn(request, TRUE);
4998 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
5000 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5001 dwBufferSize=sizeof(szNewLocation);
5002 switch(request->status_code) {
5003 case HTTP_STATUS_REDIRECT:
5004 case HTTP_STATUS_MOVED:
5005 case HTTP_STATUS_REDIRECT_KEEP_VERB:
5006 case HTTP_STATUS_REDIRECT_METHOD:
5007 if(HTTP_HttpQueryInfoW(request,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL) != ERROR_SUCCESS)
5008 break;
5010 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5011 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5013 heap_free(request->verb);
5014 request->verb = heap_strdupW(szGET);
5016 http_release_netconn(request, drain_content(request, FALSE));
5017 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5019 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5020 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5021 res = HTTP_HandleRedirect(request, new_url);
5022 if (res == ERROR_SUCCESS)
5024 heap_free(requestString);
5025 loop_next = TRUE;
5027 heap_free( new_url );
5029 redirected = TRUE;
5032 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
5034 WCHAR szAuthValue[2048];
5035 dwBufferSize=2048;
5036 if (request->status_code == HTTP_STATUS_DENIED)
5038 LPHTTPHEADERW Host = HTTP_GetHeader(request, hostW);
5039 DWORD dwIndex = 0;
5040 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5042 if (HTTP_DoAuthorization(request, szAuthValue,
5043 &request->authInfo,
5044 request->session->userName,
5045 request->session->password,
5046 Host->lpszValue))
5048 heap_free(requestString);
5049 if(!drain_content(request, TRUE)) {
5050 FIXME("Could not drain content\n");
5051 http_release_netconn(request, FALSE);
5053 loop_next = TRUE;
5054 break;
5058 if(!loop_next) {
5059 TRACE("Cleaning wrong authorization data\n");
5060 destroy_authinfo(request->authInfo);
5061 request->authInfo = NULL;
5064 if (request->status_code == HTTP_STATUS_PROXY_AUTH_REQ)
5066 DWORD dwIndex = 0;
5067 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5069 if (HTTP_DoAuthorization(request, szAuthValue,
5070 &request->proxyAuthInfo,
5071 request->session->appInfo->proxyUsername,
5072 request->session->appInfo->proxyPassword,
5073 NULL))
5075 heap_free(requestString);
5076 if(!drain_content(request, TRUE)) {
5077 FIXME("Could not drain content\n");
5078 http_release_netconn(request, FALSE);
5080 loop_next = TRUE;
5081 break;
5085 if(!loop_next) {
5086 TRACE("Cleaning wrong proxy authorization data\n");
5087 destroy_authinfo(request->proxyAuthInfo);
5088 request->proxyAuthInfo = NULL;
5093 else
5094 res = ERROR_SUCCESS;
5096 while (loop_next);
5098 lend:
5099 heap_free(requestString);
5101 /* TODO: send notification for P3P header */
5103 if(res == ERROR_SUCCESS)
5104 create_cache_entry(request);
5106 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5108 if (res == ERROR_SUCCESS) {
5109 if(bEndRequest && request->contentLength && request->bytesWritten == request->bytesToWrite)
5110 HTTP_ReceiveRequestData(request, TRUE, NULL);
5111 else
5112 send_request_complete(request,
5113 request->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)request->hdr.hInternet : 1, 0);
5114 }else {
5115 send_request_complete(request, 0, res);
5119 TRACE("<--\n");
5120 return res;
5123 typedef struct {
5124 task_header_t hdr;
5125 WCHAR *headers;
5126 DWORD headers_len;
5127 void *optional;
5128 DWORD optional_len;
5129 DWORD content_len;
5130 BOOL end_request;
5131 } send_request_task_t;
5133 /***********************************************************************
5135 * Helper functions for the HttpSendRequest(Ex) functions
5138 static void AsyncHttpSendRequestProc(task_header_t *hdr)
5140 send_request_task_t *task = (send_request_task_t*)hdr;
5141 http_request_t *request = (http_request_t*)task->hdr.hdr;
5143 TRACE("%p\n", request);
5145 HTTP_HttpSendRequestW(request, task->headers, task->headers_len, task->optional,
5146 task->optional_len, task->content_len, task->end_request);
5148 heap_free(task->headers);
5152 static DWORD HTTP_HttpEndRequestW(http_request_t *request, DWORD dwFlags, DWORD_PTR dwContext)
5154 DWORD dwBufferSize;
5155 INT responseLen;
5156 DWORD res = ERROR_SUCCESS;
5158 if(!request->netconn) {
5159 WARN("Not connected\n");
5160 send_request_complete(request, 0, ERROR_INTERNET_OPERATION_CANCELLED);
5161 return ERROR_INTERNET_OPERATION_CANCELLED;
5164 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5165 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5167 if (HTTP_GetResponseHeaders(request, &responseLen) || !responseLen)
5168 res = ERROR_HTTP_HEADER_NOT_FOUND;
5170 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5171 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
5173 /* process cookies here. Is this right? */
5174 http_process_keep_alive(request);
5175 HTTP_ProcessCookies(request);
5176 HTTP_ProcessExpires(request);
5177 HTTP_ProcessLastModified(request);
5179 if ((res = set_content_length(request)) == ERROR_SUCCESS) {
5180 if(!request->contentLength)
5181 http_release_netconn(request, TRUE);
5184 if (res == ERROR_SUCCESS && !(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
5186 switch(request->status_code) {
5187 case HTTP_STATUS_REDIRECT:
5188 case HTTP_STATUS_MOVED:
5189 case HTTP_STATUS_REDIRECT_METHOD:
5190 case HTTP_STATUS_REDIRECT_KEEP_VERB: {
5191 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5192 dwBufferSize=sizeof(szNewLocation);
5193 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, szNewLocation, &dwBufferSize, NULL) != ERROR_SUCCESS)
5194 break;
5196 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5197 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5199 heap_free(request->verb);
5200 request->verb = heap_strdupW(szGET);
5202 http_release_netconn(request, drain_content(request, FALSE));
5203 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5205 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5206 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5207 res = HTTP_HandleRedirect(request, new_url);
5208 if (res == ERROR_SUCCESS)
5209 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, TRUE);
5210 heap_free( new_url );
5216 if(res == ERROR_SUCCESS)
5217 create_cache_entry(request);
5219 if (res == ERROR_SUCCESS && request->contentLength)
5220 HTTP_ReceiveRequestData(request, TRUE, NULL);
5221 else
5222 send_request_complete(request, res == ERROR_SUCCESS, res);
5224 return res;
5227 /***********************************************************************
5228 * HttpEndRequestA (WININET.@)
5230 * Ends an HTTP request that was started by HttpSendRequestEx
5232 * RETURNS
5233 * TRUE if successful
5234 * FALSE on failure
5237 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
5238 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5240 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5242 if (lpBuffersOut)
5244 SetLastError(ERROR_INVALID_PARAMETER);
5245 return FALSE;
5248 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
5251 typedef struct {
5252 task_header_t hdr;
5253 DWORD flags;
5254 DWORD context;
5255 } end_request_task_t;
5257 static void AsyncHttpEndRequestProc(task_header_t *hdr)
5259 end_request_task_t *task = (end_request_task_t*)hdr;
5260 http_request_t *req = (http_request_t*)task->hdr.hdr;
5262 TRACE("%p\n", req);
5264 HTTP_HttpEndRequestW(req, task->flags, task->context);
5267 /***********************************************************************
5268 * HttpEndRequestW (WININET.@)
5270 * Ends an HTTP request that was started by HttpSendRequestEx
5272 * RETURNS
5273 * TRUE if successful
5274 * FALSE on failure
5277 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
5278 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5280 http_request_t *request;
5281 DWORD res;
5283 TRACE("%p %p %x %lx -->\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5285 if (lpBuffersOut)
5287 SetLastError(ERROR_INVALID_PARAMETER);
5288 return FALSE;
5291 request = (http_request_t*) get_handle_object( hRequest );
5293 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5295 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
5296 if (request)
5297 WININET_Release( &request->hdr );
5298 return FALSE;
5300 request->hdr.dwFlags |= dwFlags;
5302 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5304 end_request_task_t *task;
5306 task = alloc_async_task(&request->hdr, AsyncHttpEndRequestProc, sizeof(*task));
5307 task->flags = dwFlags;
5308 task->context = dwContext;
5310 INTERNET_AsyncCall(&task->hdr);
5311 res = ERROR_IO_PENDING;
5313 else
5314 res = HTTP_HttpEndRequestW(request, dwFlags, dwContext);
5316 WININET_Release( &request->hdr );
5317 TRACE("%u <--\n", res);
5318 if(res != ERROR_SUCCESS)
5319 SetLastError(res);
5320 return res == ERROR_SUCCESS;
5323 /***********************************************************************
5324 * HttpSendRequestExA (WININET.@)
5326 * Sends the specified request to the HTTP server and allows chunked
5327 * transfers.
5329 * RETURNS
5330 * Success: TRUE
5331 * Failure: FALSE, call GetLastError() for more information.
5333 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
5334 LPINTERNET_BUFFERSA lpBuffersIn,
5335 LPINTERNET_BUFFERSA lpBuffersOut,
5336 DWORD dwFlags, DWORD_PTR dwContext)
5338 INTERNET_BUFFERSW BuffersInW;
5339 BOOL rc = FALSE;
5340 DWORD headerlen;
5341 LPWSTR header = NULL;
5343 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5344 lpBuffersOut, dwFlags, dwContext);
5346 if (lpBuffersIn)
5348 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
5349 if (lpBuffersIn->lpcszHeader)
5351 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
5352 lpBuffersIn->dwHeadersLength,0,0);
5353 header = heap_alloc(headerlen*sizeof(WCHAR));
5354 if (!(BuffersInW.lpcszHeader = header))
5356 SetLastError(ERROR_OUTOFMEMORY);
5357 return FALSE;
5359 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
5360 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5361 header, headerlen);
5363 else
5364 BuffersInW.lpcszHeader = NULL;
5365 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
5366 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
5367 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
5368 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
5369 BuffersInW.Next = NULL;
5372 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
5374 heap_free(header);
5375 return rc;
5378 /***********************************************************************
5379 * HttpSendRequestExW (WININET.@)
5381 * Sends the specified request to the HTTP server and allows chunked
5382 * transfers
5384 * RETURNS
5385 * Success: TRUE
5386 * Failure: FALSE, call GetLastError() for more information.
5388 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
5389 LPINTERNET_BUFFERSW lpBuffersIn,
5390 LPINTERNET_BUFFERSW lpBuffersOut,
5391 DWORD dwFlags, DWORD_PTR dwContext)
5393 http_request_t *request;
5394 http_session_t *session;
5395 appinfo_t *hIC;
5396 DWORD res;
5398 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5399 lpBuffersOut, dwFlags, dwContext);
5401 request = (http_request_t*) get_handle_object( hRequest );
5403 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5405 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5406 goto lend;
5409 session = request->session;
5410 assert(session->hdr.htype == WH_HHTTPSESSION);
5411 hIC = session->appInfo;
5412 assert(hIC->hdr.htype == WH_HINIT);
5414 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5416 send_request_task_t *task;
5418 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5419 if (lpBuffersIn)
5421 DWORD size = 0;
5423 if (lpBuffersIn->lpcszHeader)
5425 if (lpBuffersIn->dwHeadersLength == ~0u)
5426 size = (strlenW( lpBuffersIn->lpcszHeader ) + 1) * sizeof(WCHAR);
5427 else
5428 size = lpBuffersIn->dwHeadersLength * sizeof(WCHAR);
5430 task->headers = heap_alloc(size);
5431 memcpy(task->headers, lpBuffersIn->lpcszHeader, size);
5433 else task->headers = NULL;
5435 task->headers_len = size / sizeof(WCHAR);
5436 task->optional = lpBuffersIn->lpvBuffer;
5437 task->optional_len = lpBuffersIn->dwBufferLength;
5438 task->content_len = lpBuffersIn->dwBufferTotal;
5440 else
5442 task->headers = NULL;
5443 task->headers_len = 0;
5444 task->optional = NULL;
5445 task->optional_len = 0;
5446 task->content_len = 0;
5449 task->end_request = FALSE;
5451 INTERNET_AsyncCall(&task->hdr);
5452 res = ERROR_IO_PENDING;
5454 else
5456 if (lpBuffersIn)
5457 res = HTTP_HttpSendRequestW(request, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5458 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
5459 lpBuffersIn->dwBufferTotal, FALSE);
5460 else
5461 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, FALSE);
5464 lend:
5465 if ( request )
5466 WININET_Release( &request->hdr );
5468 TRACE("<---\n");
5469 SetLastError(res);
5470 return res == ERROR_SUCCESS;
5473 /***********************************************************************
5474 * HttpSendRequestW (WININET.@)
5476 * Sends the specified request to the HTTP server
5478 * RETURNS
5479 * TRUE on success
5480 * FALSE on failure
5483 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
5484 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5486 http_request_t *request;
5487 http_session_t *session = NULL;
5488 appinfo_t *hIC = NULL;
5489 DWORD res = ERROR_SUCCESS;
5491 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
5492 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
5494 request = (http_request_t*) get_handle_object( hHttpRequest );
5495 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5497 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5498 goto lend;
5501 session = request->session;
5502 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
5504 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5505 goto lend;
5508 hIC = session->appInfo;
5509 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
5511 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5512 goto lend;
5515 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5517 send_request_task_t *task;
5519 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5520 if (lpszHeaders)
5522 DWORD size;
5524 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
5525 else size = dwHeaderLength * sizeof(WCHAR);
5527 task->headers = heap_alloc(size);
5528 memcpy(task->headers, lpszHeaders, size);
5530 else
5531 task->headers = NULL;
5532 task->headers_len = dwHeaderLength;
5533 task->optional = lpOptional;
5534 task->optional_len = dwOptionalLength;
5535 task->content_len = dwOptionalLength;
5536 task->end_request = TRUE;
5538 INTERNET_AsyncCall(&task->hdr);
5539 res = ERROR_IO_PENDING;
5541 else
5543 res = HTTP_HttpSendRequestW(request, lpszHeaders,
5544 dwHeaderLength, lpOptional, dwOptionalLength,
5545 dwOptionalLength, TRUE);
5547 lend:
5548 if( request )
5549 WININET_Release( &request->hdr );
5551 SetLastError(res);
5552 return res == ERROR_SUCCESS;
5555 /***********************************************************************
5556 * HttpSendRequestA (WININET.@)
5558 * Sends the specified request to the HTTP server
5560 * RETURNS
5561 * TRUE on success
5562 * FALSE on failure
5565 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
5566 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5568 BOOL result;
5569 LPWSTR szHeaders=NULL;
5570 DWORD nLen=dwHeaderLength;
5571 if(lpszHeaders!=NULL)
5573 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
5574 szHeaders = heap_alloc(nLen*sizeof(WCHAR));
5575 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
5577 result = HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
5578 heap_free(szHeaders);
5579 return result;
5582 /***********************************************************************
5583 * HTTPSESSION_Destroy (internal)
5585 * Deallocate session handle
5588 static void HTTPSESSION_Destroy(object_header_t *hdr)
5590 http_session_t *session = (http_session_t*) hdr;
5592 TRACE("%p\n", session);
5594 WININET_Release(&session->appInfo->hdr);
5596 heap_free(session->hostName);
5597 heap_free(session->password);
5598 heap_free(session->userName);
5601 static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
5603 http_session_t *ses = (http_session_t *)hdr;
5605 switch(option) {
5606 case INTERNET_OPTION_HANDLE_TYPE:
5607 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5609 if (*size < sizeof(ULONG))
5610 return ERROR_INSUFFICIENT_BUFFER;
5612 *size = sizeof(DWORD);
5613 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
5614 return ERROR_SUCCESS;
5615 case INTERNET_OPTION_CONNECT_TIMEOUT:
5616 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5618 if (*size < sizeof(DWORD))
5619 return ERROR_INSUFFICIENT_BUFFER;
5621 *size = sizeof(DWORD);
5622 *(DWORD *)buffer = ses->connect_timeout;
5623 return ERROR_SUCCESS;
5625 case INTERNET_OPTION_SEND_TIMEOUT:
5626 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5628 if (*size < sizeof(DWORD))
5629 return ERROR_INSUFFICIENT_BUFFER;
5631 *size = sizeof(DWORD);
5632 *(DWORD *)buffer = ses->send_timeout;
5633 return ERROR_SUCCESS;
5635 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5636 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5638 if (*size < sizeof(DWORD))
5639 return ERROR_INSUFFICIENT_BUFFER;
5641 *size = sizeof(DWORD);
5642 *(DWORD *)buffer = ses->receive_timeout;
5643 return ERROR_SUCCESS;
5646 return INET_QueryOption(hdr, option, buffer, size, unicode);
5649 static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
5651 http_session_t *ses = (http_session_t*)hdr;
5653 switch(option) {
5654 case INTERNET_OPTION_USERNAME:
5656 heap_free(ses->userName);
5657 if (!(ses->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5658 return ERROR_SUCCESS;
5660 case INTERNET_OPTION_PASSWORD:
5662 heap_free(ses->password);
5663 if (!(ses->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5664 return ERROR_SUCCESS;
5666 case INTERNET_OPTION_PROXY_USERNAME:
5668 heap_free(ses->appInfo->proxyUsername);
5669 if (!(ses->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5670 return ERROR_SUCCESS;
5672 case INTERNET_OPTION_PROXY_PASSWORD:
5674 heap_free(ses->appInfo->proxyPassword);
5675 if (!(ses->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5676 return ERROR_SUCCESS;
5678 case INTERNET_OPTION_CONNECT_TIMEOUT:
5680 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5681 ses->connect_timeout = *(DWORD *)buffer;
5682 return ERROR_SUCCESS;
5684 case INTERNET_OPTION_SEND_TIMEOUT:
5686 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5687 ses->send_timeout = *(DWORD *)buffer;
5688 return ERROR_SUCCESS;
5690 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5692 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5693 ses->receive_timeout = *(DWORD *)buffer;
5694 return ERROR_SUCCESS;
5696 default: break;
5699 return INET_SetOption(hdr, option, buffer, size);
5702 static const object_vtbl_t HTTPSESSIONVtbl = {
5703 HTTPSESSION_Destroy,
5704 NULL,
5705 HTTPSESSION_QueryOption,
5706 HTTPSESSION_SetOption,
5707 NULL,
5708 NULL,
5709 NULL,
5710 NULL,
5711 NULL
5715 /***********************************************************************
5716 * HTTP_Connect (internal)
5718 * Create http session handle
5720 * RETURNS
5721 * HINTERNET a session handle on success
5722 * NULL on failure
5725 DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
5726 INTERNET_PORT serverPort, LPCWSTR lpszUserName,
5727 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
5728 DWORD dwInternalFlags, HINTERNET *ret)
5730 http_session_t *session = NULL;
5732 TRACE("-->\n");
5734 if (!lpszServerName || !lpszServerName[0])
5735 return ERROR_INVALID_PARAMETER;
5737 assert( hIC->hdr.htype == WH_HINIT );
5739 session = alloc_object(&hIC->hdr, &HTTPSESSIONVtbl, sizeof(http_session_t));
5740 if (!session)
5741 return ERROR_OUTOFMEMORY;
5744 * According to my tests. The name is not resolved until a request is sent
5747 session->hdr.htype = WH_HHTTPSESSION;
5748 session->hdr.dwFlags = dwFlags;
5749 session->hdr.dwContext = dwContext;
5750 session->hdr.dwInternalFlags |= dwInternalFlags;
5752 WININET_AddRef( &hIC->hdr );
5753 session->appInfo = hIC;
5754 list_add_head( &hIC->hdr.children, &session->hdr.entry );
5756 session->hostName = heap_strdupW(lpszServerName);
5757 if (lpszUserName && lpszUserName[0])
5758 session->userName = heap_strdupW(lpszUserName);
5759 if (lpszPassword && lpszPassword[0])
5760 session->password = heap_strdupW(lpszPassword);
5761 session->hostPort = serverPort;
5762 session->connect_timeout = hIC->connect_timeout;
5763 session->send_timeout = INFINITE;
5764 session->receive_timeout = INFINITE;
5766 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5767 if (!(session->hdr.dwInternalFlags & INET_OPENURL))
5769 INTERNET_SendCallback(&hIC->hdr, dwContext,
5770 INTERNET_STATUS_HANDLE_CREATED, &session->hdr.hInternet,
5771 sizeof(HINTERNET));
5775 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5776 * windows
5779 TRACE("%p --> %p\n", hIC, session);
5781 *ret = session->hdr.hInternet;
5782 return ERROR_SUCCESS;
5785 /***********************************************************************
5786 * HTTP_clear_response_headers (internal)
5788 * clear out any old response headers
5790 static void HTTP_clear_response_headers( http_request_t *request )
5792 DWORD i;
5794 for( i=0; i<request->nCustHeaders; i++)
5796 if( !request->custHeaders[i].lpszField )
5797 continue;
5798 if( !request->custHeaders[i].lpszValue )
5799 continue;
5800 if ( request->custHeaders[i].wFlags & HDR_ISREQUEST )
5801 continue;
5802 HTTP_DeleteCustomHeader( request, i );
5803 i--;
5807 /***********************************************************************
5808 * HTTP_GetResponseHeaders (internal)
5810 * Read server response
5812 * RETURNS
5814 * TRUE on success
5815 * FALSE on error
5817 static DWORD HTTP_GetResponseHeaders(http_request_t *request, INT *len)
5819 INT cbreaks = 0;
5820 WCHAR buffer[MAX_REPLY_LEN];
5821 DWORD buflen = MAX_REPLY_LEN;
5822 INT rc = 0;
5823 char bufferA[MAX_REPLY_LEN];
5824 LPWSTR status_code = NULL, status_text = NULL;
5825 DWORD res = ERROR_HTTP_INVALID_SERVER_RESPONSE;
5826 BOOL codeHundred = FALSE;
5828 TRACE("-->\n");
5830 if(!request->netconn)
5831 goto lend;
5833 /* clear old response headers (eg. from a redirect response) */
5834 HTTP_clear_response_headers( request );
5836 NETCON_set_timeout( request->netconn, FALSE, request->receive_timeout );
5837 do {
5839 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5841 buflen = MAX_REPLY_LEN;
5842 if ((res = read_line(request, bufferA, &buflen)))
5843 goto lend;
5845 if (!buflen) goto lend;
5847 rc += buflen;
5848 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5849 /* check is this a status code line? */
5850 if (!strncmpW(buffer, g_szHttp1_0, 4))
5852 /* split the version from the status code */
5853 status_code = strchrW( buffer, ' ' );
5854 if( !status_code )
5855 goto lend;
5856 *status_code++=0;
5858 /* split the status code from the status text */
5859 status_text = strchrW( status_code, ' ' );
5860 if( !status_text )
5861 goto lend;
5862 *status_text++=0;
5864 request->status_code = atoiW(status_code);
5866 TRACE("version [%s] status code [%s] status text [%s]\n",
5867 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
5869 codeHundred = request->status_code == HTTP_STATUS_CONTINUE;
5871 else if (!codeHundred)
5873 WARN("No status line at head of response (%s)\n", debugstr_w(buffer));
5875 heap_free(request->version);
5876 heap_free(request->statusText);
5878 request->status_code = HTTP_STATUS_OK;
5879 request->version = heap_strdupW(g_szHttp1_0);
5880 request->statusText = heap_strdupW(szOK);
5882 goto lend;
5884 } while (codeHundred);
5886 /* Add status code */
5887 HTTP_ProcessHeader(request, szStatus, status_code,
5888 HTTP_ADDHDR_FLAG_REPLACE);
5890 heap_free(request->version);
5891 heap_free(request->statusText);
5893 request->version = heap_strdupW(buffer);
5894 request->statusText = heap_strdupW(status_text);
5896 /* Restore the spaces */
5897 *(status_code-1) = ' ';
5898 *(status_text-1) = ' ';
5900 /* Parse each response line */
5903 buflen = MAX_REPLY_LEN;
5904 if (!read_line(request, bufferA, &buflen) && buflen)
5906 LPWSTR * pFieldAndValue;
5908 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
5910 if (!bufferA[0]) break;
5911 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5913 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
5914 if (pFieldAndValue)
5916 HTTP_ProcessHeader(request, pFieldAndValue[0], pFieldAndValue[1],
5917 HTTP_ADDREQ_FLAG_ADD );
5918 HTTP_FreeTokens(pFieldAndValue);
5921 else
5923 cbreaks++;
5924 if (cbreaks >= 2)
5925 break;
5927 }while(1);
5929 res = ERROR_SUCCESS;
5931 lend:
5933 *len = rc;
5934 TRACE("<--\n");
5935 return res;
5938 /***********************************************************************
5939 * HTTP_InterpretHttpHeader (internal)
5941 * Parse server response
5943 * RETURNS
5945 * Pointer to array of field, value, NULL on success.
5946 * NULL on error.
5948 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
5950 LPWSTR * pTokenPair;
5951 LPWSTR pszColon;
5952 INT len;
5954 pTokenPair = heap_alloc_zero(sizeof(*pTokenPair)*3);
5956 pszColon = strchrW(buffer, ':');
5957 /* must have two tokens */
5958 if (!pszColon)
5960 HTTP_FreeTokens(pTokenPair);
5961 if (buffer[0])
5962 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
5963 return NULL;
5966 pTokenPair[0] = heap_alloc((pszColon - buffer + 1) * sizeof(WCHAR));
5967 if (!pTokenPair[0])
5969 HTTP_FreeTokens(pTokenPair);
5970 return NULL;
5972 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
5973 pTokenPair[0][pszColon - buffer] = '\0';
5975 /* skip colon */
5976 pszColon++;
5977 len = strlenW(pszColon);
5978 pTokenPair[1] = heap_alloc((len + 1) * sizeof(WCHAR));
5979 if (!pTokenPair[1])
5981 HTTP_FreeTokens(pTokenPair);
5982 return NULL;
5984 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
5986 strip_spaces(pTokenPair[0]);
5987 strip_spaces(pTokenPair[1]);
5989 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
5990 return pTokenPair;
5993 /***********************************************************************
5994 * HTTP_ProcessHeader (internal)
5996 * Stuff header into header tables according to <dwModifier>
6000 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6002 static DWORD HTTP_ProcessHeader(http_request_t *request, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
6004 LPHTTPHEADERW lphttpHdr = NULL;
6005 INT index = -1;
6006 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
6007 DWORD res = ERROR_HTTP_INVALID_HEADER;
6009 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
6011 /* REPLACE wins out over ADD */
6012 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6013 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
6015 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
6016 index = -1;
6017 else
6018 index = HTTP_GetCustomHeaderIndex(request, field, 0, request_only);
6020 if (index >= 0)
6022 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
6023 return ERROR_HTTP_INVALID_HEADER;
6024 lphttpHdr = &request->custHeaders[index];
6026 else if (value)
6028 HTTPHEADERW hdr;
6030 hdr.lpszField = (LPWSTR)field;
6031 hdr.lpszValue = (LPWSTR)value;
6032 hdr.wFlags = hdr.wCount = 0;
6034 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6035 hdr.wFlags |= HDR_ISREQUEST;
6037 return HTTP_InsertCustomHeader(request, &hdr);
6039 /* no value to delete */
6040 else return ERROR_SUCCESS;
6042 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6043 lphttpHdr->wFlags |= HDR_ISREQUEST;
6044 else
6045 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
6047 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6049 HTTP_DeleteCustomHeader( request, index );
6051 if (value)
6053 HTTPHEADERW hdr;
6055 hdr.lpszField = (LPWSTR)field;
6056 hdr.lpszValue = (LPWSTR)value;
6057 hdr.wFlags = hdr.wCount = 0;
6059 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6060 hdr.wFlags |= HDR_ISREQUEST;
6062 return HTTP_InsertCustomHeader(request, &hdr);
6065 return ERROR_SUCCESS;
6067 else if (dwModifier & COALESCEFLAGS)
6069 LPWSTR lpsztmp;
6070 WCHAR ch = 0;
6071 INT len = 0;
6072 INT origlen = strlenW(lphttpHdr->lpszValue);
6073 INT valuelen = strlenW(value);
6075 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
6077 ch = ',';
6078 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6080 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6082 ch = ';';
6083 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6086 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
6088 lpsztmp = heap_realloc(lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
6089 if (lpsztmp)
6091 lphttpHdr->lpszValue = lpsztmp;
6092 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6093 if (ch > 0)
6095 lphttpHdr->lpszValue[origlen] = ch;
6096 origlen++;
6097 lphttpHdr->lpszValue[origlen] = ' ';
6098 origlen++;
6101 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
6102 lphttpHdr->lpszValue[len] = '\0';
6103 res = ERROR_SUCCESS;
6105 else
6107 WARN("heap_realloc (%d bytes) failed\n",len+1);
6108 res = ERROR_OUTOFMEMORY;
6111 TRACE("<-- %d\n", res);
6112 return res;
6115 /***********************************************************************
6116 * HTTP_GetCustomHeaderIndex (internal)
6118 * Return index of custom header from header array
6121 static INT HTTP_GetCustomHeaderIndex(http_request_t *request, LPCWSTR lpszField,
6122 int requested_index, BOOL request_only)
6124 DWORD index;
6126 TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
6128 for (index = 0; index < request->nCustHeaders; index++)
6130 if (strcmpiW(request->custHeaders[index].lpszField, lpszField))
6131 continue;
6133 if (request_only && !(request->custHeaders[index].wFlags & HDR_ISREQUEST))
6134 continue;
6136 if (!request_only && (request->custHeaders[index].wFlags & HDR_ISREQUEST))
6137 continue;
6139 if (requested_index == 0)
6140 break;
6141 requested_index --;
6144 if (index >= request->nCustHeaders)
6145 index = -1;
6147 TRACE("Return: %d\n", index);
6148 return index;
6152 /***********************************************************************
6153 * HTTP_InsertCustomHeader (internal)
6155 * Insert header into array
6158 static DWORD HTTP_InsertCustomHeader(http_request_t *request, LPHTTPHEADERW lpHdr)
6160 INT count;
6161 LPHTTPHEADERW lph = NULL;
6163 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
6164 count = request->nCustHeaders + 1;
6165 if (count > 1)
6166 lph = heap_realloc_zero(request->custHeaders, sizeof(HTTPHEADERW) * count);
6167 else
6168 lph = heap_alloc_zero(sizeof(HTTPHEADERW) * count);
6170 if (!lph)
6171 return ERROR_OUTOFMEMORY;
6173 request->custHeaders = lph;
6174 request->custHeaders[count-1].lpszField = heap_strdupW(lpHdr->lpszField);
6175 request->custHeaders[count-1].lpszValue = heap_strdupW(lpHdr->lpszValue);
6176 request->custHeaders[count-1].wFlags = lpHdr->wFlags;
6177 request->custHeaders[count-1].wCount= lpHdr->wCount;
6178 request->nCustHeaders++;
6180 return ERROR_SUCCESS;
6184 /***********************************************************************
6185 * HTTP_DeleteCustomHeader (internal)
6187 * Delete header from array
6188 * If this function is called, the indexs may change.
6190 static BOOL HTTP_DeleteCustomHeader(http_request_t *request, DWORD index)
6192 if( request->nCustHeaders <= 0 )
6193 return FALSE;
6194 if( index >= request->nCustHeaders )
6195 return FALSE;
6196 request->nCustHeaders--;
6198 heap_free(request->custHeaders[index].lpszField);
6199 heap_free(request->custHeaders[index].lpszValue);
6201 memmove( &request->custHeaders[index], &request->custHeaders[index+1],
6202 (request->nCustHeaders - index)* sizeof(HTTPHEADERW) );
6203 memset( &request->custHeaders[request->nCustHeaders], 0, sizeof(HTTPHEADERW) );
6205 return TRUE;
6209 /***********************************************************************
6210 * HTTP_VerifyValidHeader (internal)
6212 * Verify the given header is not invalid for the given http request
6215 static BOOL HTTP_VerifyValidHeader(http_request_t *request, LPCWSTR field)
6217 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
6218 if (!strcmpW(request->version, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
6219 return ERROR_HTTP_INVALID_HEADER;
6221 return ERROR_SUCCESS;
6224 /***********************************************************************
6225 * IsHostInProxyBypassList (@)
6227 * Undocumented
6230 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
6232 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
6233 return FALSE;