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