wininet: Handle secure proxy connections inside the main loop.
[wine/wine-gecko.git] / dlls / wininet / http.c
blob97becd4f6e45a9f043559a3e81fd369a9ac87e51
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);
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 WCHAR encoding[20];
2885 DWORD size;
2887 if(request->status_code == HTTP_STATUS_NO_CONTENT) {
2888 request->contentLength = request->netconn_stream.content_length = 0;
2889 return ERROR_SUCCESS;
2892 size = sizeof(request->contentLength);
2893 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2894 &request->contentLength, &size, NULL) != ERROR_SUCCESS)
2895 request->contentLength = ~0u;
2896 request->netconn_stream.content_length = request->contentLength;
2897 request->netconn_stream.content_read = request->read_size;
2899 size = sizeof(encoding);
2900 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) == ERROR_SUCCESS &&
2901 !strcmpiW(encoding, szChunked))
2903 chunked_stream_t *chunked_stream;
2905 chunked_stream = heap_alloc(sizeof(*chunked_stream));
2906 if(!chunked_stream)
2907 return ERROR_OUTOFMEMORY;
2909 chunked_stream->data_stream.vtbl = &chunked_stream_vtbl;
2910 chunked_stream->buf_size = chunked_stream->buf_pos = 0;
2911 chunked_stream->chunk_size = ~0u;
2912 chunked_stream->end_of_data = FALSE;
2914 if(request->read_size) {
2915 memcpy(chunked_stream->buf, request->read_buf+request->read_pos, request->read_size);
2916 chunked_stream->buf_size = request->read_size;
2917 request->read_size = request->read_pos = 0;
2920 request->data_stream = &chunked_stream->data_stream;
2921 request->contentLength = ~0u;
2922 request->read_chunked = TRUE;
2925 if(request->decoding) {
2926 int encoding_idx;
2928 static const WCHAR deflateW[] = {'d','e','f','l','a','t','e',0};
2929 static const WCHAR gzipW[] = {'g','z','i','p',0};
2931 encoding_idx = HTTP_GetCustomHeaderIndex(request, szContent_Encoding, 0, FALSE);
2932 if(encoding_idx != -1) {
2933 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, gzipW)) {
2934 HTTP_DeleteCustomHeader(request, encoding_idx);
2935 return init_gzip_stream(request, TRUE);
2937 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, deflateW)) {
2938 HTTP_DeleteCustomHeader(request, encoding_idx);
2939 return init_gzip_stream(request, FALSE);
2944 return ERROR_SUCCESS;
2947 static void send_request_complete(http_request_t *req, DWORD_PTR result, DWORD error)
2949 INTERNET_ASYNC_RESULT iar;
2951 iar.dwResult = result;
2952 iar.dwError = error;
2954 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2955 sizeof(INTERNET_ASYNC_RESULT));
2958 static void HTTP_ReceiveRequestData(http_request_t *req, BOOL first_notif, DWORD *ret_size)
2960 DWORD res, read = 0, avail = 0;
2961 blocking_mode_t mode;
2963 TRACE("%p\n", req);
2965 EnterCriticalSection( &req->read_section );
2967 mode = first_notif && req->read_size ? BLOCKING_DISALLOW : BLOCKING_ALLOW;
2968 res = refill_read_buffer(req, mode, &read);
2969 if(res == ERROR_SUCCESS)
2970 avail = get_avail_data(req);
2972 LeaveCriticalSection( &req->read_section );
2974 if(res != ERROR_SUCCESS || (mode != BLOCKING_DISALLOW && !read)) {
2975 WARN("res %u read %u, closing connection\n", res, read);
2976 http_release_netconn(req, FALSE);
2979 if(res != ERROR_SUCCESS) {
2980 send_request_complete(req, 0, res);
2981 return;
2984 if(ret_size)
2985 *ret_size = avail;
2986 if(first_notif)
2987 avail = 0;
2989 send_request_complete(req, req->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)req->hdr.hInternet : 1, avail);
2992 /* read data from the http connection (the read section must be held) */
2993 static DWORD HTTPREQ_Read(http_request_t *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
2995 DWORD current_read = 0, ret_read = 0;
2996 blocking_mode_t blocking_mode;
2997 DWORD res = ERROR_SUCCESS;
2999 blocking_mode = req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC ? BLOCKING_ALLOW : BLOCKING_WAITALL;
3001 EnterCriticalSection( &req->read_section );
3003 if(req->read_size) {
3004 ret_read = min(size, req->read_size);
3005 memcpy(buffer, req->read_buf+req->read_pos, ret_read);
3006 req->read_size -= ret_read;
3007 req->read_pos += ret_read;
3008 if(blocking_mode == BLOCKING_ALLOW)
3009 blocking_mode = BLOCKING_DISALLOW;
3012 if(ret_read < size) {
3013 res = read_http_stream(req, (BYTE*)buffer+ret_read, size-ret_read, &current_read, blocking_mode);
3014 ret_read += current_read;
3017 LeaveCriticalSection( &req->read_section );
3019 *read = ret_read;
3020 TRACE( "retrieved %u bytes (%u)\n", ret_read, req->contentLength );
3022 if(size && !ret_read)
3023 http_release_netconn(req, res == ERROR_SUCCESS);
3025 return res;
3028 static BOOL drain_content(http_request_t *req, BOOL blocking)
3030 BOOL ret;
3032 if(!is_valid_netconn(req->netconn) || req->contentLength == -1)
3033 return FALSE;
3035 if(!strcmpW(req->verb, szHEAD))
3036 return TRUE;
3038 if(!blocking)
3039 return req->data_stream->vtbl->drain_content(req->data_stream, req);
3041 EnterCriticalSection( &req->read_section );
3043 while(1) {
3044 DWORD bytes_read, res;
3045 BYTE buf[4096];
3047 res = HTTPREQ_Read(req, buf, sizeof(buf), &bytes_read, TRUE);
3048 if(res != ERROR_SUCCESS) {
3049 ret = FALSE;
3050 break;
3052 if(!bytes_read) {
3053 ret = TRUE;
3054 break;
3058 LeaveCriticalSection( &req->read_section );
3059 return ret;
3062 static DWORD HTTPREQ_ReadFile(object_header_t *hdr, void *buffer, DWORD size, DWORD *read)
3064 http_request_t *req = (http_request_t*)hdr;
3065 DWORD res;
3067 EnterCriticalSection( &req->read_section );
3068 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3069 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3071 res = HTTPREQ_Read(req, buffer, size, read, TRUE);
3072 if(res == ERROR_SUCCESS)
3073 res = hdr->dwError;
3074 LeaveCriticalSection( &req->read_section );
3076 return res;
3079 typedef struct {
3080 task_header_t hdr;
3081 void *buf;
3082 DWORD size;
3083 DWORD *ret_read;
3084 } read_file_ex_task_t;
3086 static void AsyncReadFileExProc(task_header_t *hdr)
3088 read_file_ex_task_t *task = (read_file_ex_task_t*)hdr;
3089 http_request_t *req = (http_request_t*)task->hdr.hdr;
3090 DWORD res;
3092 TRACE("INTERNETREADFILEEXW %p\n", task->hdr.hdr);
3094 res = HTTPREQ_Read(req, task->buf, task->size, task->ret_read, TRUE);
3095 send_request_complete(req, res == ERROR_SUCCESS, res);
3098 static DWORD HTTPREQ_ReadFileEx(object_header_t *hdr, void *buf, DWORD size, DWORD *ret_read,
3099 DWORD flags, DWORD_PTR context)
3102 http_request_t *req = (http_request_t*)hdr;
3103 DWORD res, read, cread, error = ERROR_SUCCESS;
3105 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3106 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3108 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3110 if (hdr->dwFlags & INTERNET_FLAG_ASYNC)
3112 read_file_ex_task_t *task;
3114 if (TryEnterCriticalSection( &req->read_section ))
3116 if (get_avail_data(req))
3118 res = HTTPREQ_Read(req, buf, size, &read, FALSE);
3119 LeaveCriticalSection( &req->read_section );
3120 goto done;
3122 LeaveCriticalSection( &req->read_section );
3125 task = alloc_async_task(&req->hdr, AsyncReadFileExProc, sizeof(*task));
3126 task->buf = buf;
3127 task->size = size;
3128 task->ret_read = ret_read;
3130 INTERNET_AsyncCall(&task->hdr);
3132 return ERROR_IO_PENDING;
3135 read = 0;
3137 EnterCriticalSection( &req->read_section );
3138 if(hdr->dwError == ERROR_SUCCESS)
3139 hdr->dwError = INTERNET_HANDLE_IN_USE;
3140 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3141 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3143 while(1) {
3144 res = HTTPREQ_Read(req, (char*)buf+read, size-read, &cread, !(flags & IRF_NO_WAIT));
3145 if(res != ERROR_SUCCESS)
3146 break;
3148 read += cread;
3149 if(read == size || end_of_read_data(req))
3150 break;
3152 LeaveCriticalSection( &req->read_section );
3154 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3155 &cread, sizeof(cread));
3156 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
3157 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3159 EnterCriticalSection( &req->read_section );
3162 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3163 hdr->dwError = ERROR_SUCCESS;
3164 else
3165 error = hdr->dwError;
3167 LeaveCriticalSection( &req->read_section );
3169 done:
3170 *ret_read = read;
3171 if (res == ERROR_SUCCESS) {
3172 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3173 &read, sizeof(read));
3176 return res==ERROR_SUCCESS ? error : res;
3179 static DWORD HTTPREQ_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
3181 DWORD res;
3182 http_request_t *request = (http_request_t*)hdr;
3184 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3186 *written = 0;
3187 res = NETCON_send(request->netconn, buffer, size, 0, (LPINT)written);
3188 if (res == ERROR_SUCCESS)
3189 request->bytesWritten += *written;
3191 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
3192 return res;
3195 typedef struct {
3196 task_header_t hdr;
3197 DWORD *ret_size;
3198 } http_data_available_task_t;
3200 static void AsyncQueryDataAvailableProc(task_header_t *hdr)
3202 http_data_available_task_t *task = (http_data_available_task_t*)hdr;
3204 HTTP_ReceiveRequestData((http_request_t*)task->hdr.hdr, FALSE, task->ret_size);
3207 static DWORD HTTPREQ_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
3209 http_request_t *req = (http_request_t*)hdr;
3211 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
3213 if (req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3215 http_data_available_task_t *task;
3217 /* never wait, if we can't enter the section we queue an async request right away */
3218 if (TryEnterCriticalSection( &req->read_section ))
3220 refill_read_buffer(req, BLOCKING_DISALLOW, NULL);
3221 if ((*available = get_avail_data( req ))) goto done;
3222 if (end_of_read_data( req )) goto done;
3223 LeaveCriticalSection( &req->read_section );
3226 task = alloc_async_task(&req->hdr, AsyncQueryDataAvailableProc, sizeof(*task));
3227 task->ret_size = available;
3228 INTERNET_AsyncCall(&task->hdr);
3229 return ERROR_IO_PENDING;
3232 EnterCriticalSection( &req->read_section );
3234 if (!(*available = get_avail_data( req )) && !end_of_read_data( req ))
3236 refill_read_buffer( req, BLOCKING_ALLOW, NULL );
3237 *available = get_avail_data( req );
3240 done:
3241 LeaveCriticalSection( &req->read_section );
3243 TRACE( "returning %u\n", *available );
3244 return ERROR_SUCCESS;
3247 static DWORD HTTPREQ_LockRequestFile(object_header_t *hdr, req_file_t **ret)
3249 http_request_t *req = (http_request_t*)hdr;
3251 TRACE("(%p)\n", req);
3253 if(!req->req_file) {
3254 WARN("No cache file name available\n");
3255 return ERROR_FILE_NOT_FOUND;
3258 *ret = req_file_addref(req->req_file);
3259 return ERROR_SUCCESS;
3262 static const object_vtbl_t HTTPREQVtbl = {
3263 HTTPREQ_Destroy,
3264 HTTPREQ_CloseConnection,
3265 HTTPREQ_QueryOption,
3266 HTTPREQ_SetOption,
3267 HTTPREQ_ReadFile,
3268 HTTPREQ_ReadFileEx,
3269 HTTPREQ_WriteFile,
3270 HTTPREQ_QueryDataAvailable,
3271 NULL,
3272 HTTPREQ_LockRequestFile
3275 /***********************************************************************
3276 * HTTP_HttpOpenRequestW (internal)
3278 * Open a HTTP request handle
3280 * RETURNS
3281 * HINTERNET a HTTP request handle on success
3282 * NULL on failure
3285 static DWORD HTTP_HttpOpenRequestW(http_session_t *session,
3286 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3287 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3288 DWORD dwFlags, DWORD_PTR dwContext, HINTERNET *ret)
3290 appinfo_t *hIC = session->appInfo;
3291 http_request_t *request;
3292 DWORD len;
3294 TRACE("-->\n");
3296 request = alloc_object(&session->hdr, &HTTPREQVtbl, sizeof(http_request_t));
3297 if(!request)
3298 return ERROR_OUTOFMEMORY;
3300 request->hdr.htype = WH_HHTTPREQ;
3301 request->hdr.dwFlags = dwFlags;
3302 request->hdr.dwContext = dwContext;
3303 request->contentLength = ~0u;
3305 request->netconn_stream.data_stream.vtbl = &netconn_stream_vtbl;
3306 request->data_stream = &request->netconn_stream.data_stream;
3307 request->connect_timeout = session->connect_timeout;
3308 request->send_timeout = session->send_timeout;
3309 request->receive_timeout = session->receive_timeout;
3311 InitializeCriticalSection( &request->read_section );
3312 request->read_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.read_section");
3314 WININET_AddRef( &session->hdr );
3315 request->session = session;
3316 list_add_head( &session->hdr.children, &request->hdr.entry );
3318 request->server = get_server(session->hostName, session->hostPort, (dwFlags & INTERNET_FLAG_SECURE) != 0, TRUE);
3319 if(!request->server) {
3320 WININET_Release(&request->hdr);
3321 return ERROR_OUTOFMEMORY;
3324 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_CN_INVALID)
3325 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
3326 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_DATE_INVALID)
3327 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
3329 if (lpszObjectName && *lpszObjectName) {
3330 HRESULT rc;
3332 len = 0;
3333 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
3334 if (rc != E_POINTER)
3335 len = strlenW(lpszObjectName)+1;
3336 request->path = heap_alloc(len*sizeof(WCHAR));
3337 rc = UrlEscapeW(lpszObjectName, request->path, &len,
3338 URL_ESCAPE_SPACES_ONLY);
3339 if (rc != S_OK)
3341 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
3342 strcpyW(request->path,lpszObjectName);
3344 }else {
3345 static const WCHAR slashW[] = {'/',0};
3347 request->path = heap_strdupW(slashW);
3350 if (lpszReferrer && *lpszReferrer)
3351 HTTP_ProcessHeader(request, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3353 if (lpszAcceptTypes)
3355 int i;
3356 for (i = 0; lpszAcceptTypes[i]; i++)
3358 if (!*lpszAcceptTypes[i]) continue;
3359 HTTP_ProcessHeader(request, HTTP_ACCEPT, lpszAcceptTypes[i],
3360 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
3361 HTTP_ADDHDR_FLAG_REQ |
3362 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
3366 request->verb = heap_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
3367 request->version = heap_strdupW(lpszVersion && *lpszVersion ? lpszVersion : g_szHttp1_1);
3369 HTTP_ProcessHeader(request, hostW, request->server->canon_host_port, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3371 if (session->hostPort == INTERNET_INVALID_PORT_NUMBER)
3372 session->hostPort = INTERNET_DEFAULT_HTTP_PORT;
3374 if (hIC->proxy && hIC->proxy[0] && !HTTP_ShouldBypassProxy(hIC, session->hostName))
3375 HTTP_DealWithProxy( hIC, session, request );
3377 INTERNET_SendCallback(&session->hdr, dwContext,
3378 INTERNET_STATUS_HANDLE_CREATED, &request->hdr.hInternet,
3379 sizeof(HINTERNET));
3381 TRACE("<-- (%p)\n", request);
3383 *ret = request->hdr.hInternet;
3384 return ERROR_SUCCESS;
3387 /***********************************************************************
3388 * HttpOpenRequestW (WININET.@)
3390 * Open a HTTP request handle
3392 * RETURNS
3393 * HINTERNET a HTTP request handle on success
3394 * NULL on failure
3397 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
3398 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3399 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3400 DWORD dwFlags, DWORD_PTR dwContext)
3402 http_session_t *session;
3403 HINTERNET handle = NULL;
3404 DWORD res;
3406 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
3407 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
3408 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
3409 dwFlags, dwContext);
3410 if(lpszAcceptTypes!=NULL)
3412 int i;
3413 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
3414 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
3417 session = (http_session_t*) get_handle_object( hHttpSession );
3418 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
3420 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3421 goto lend;
3425 * My tests seem to show that the windows version does not
3426 * become asynchronous until after this point. And anyhow
3427 * if this call was asynchronous then how would you get the
3428 * necessary HINTERNET pointer returned by this function.
3431 res = HTTP_HttpOpenRequestW(session, lpszVerb, lpszObjectName,
3432 lpszVersion, lpszReferrer, lpszAcceptTypes,
3433 dwFlags, dwContext, &handle);
3434 lend:
3435 if( session )
3436 WININET_Release( &session->hdr );
3437 TRACE("returning %p\n", handle);
3438 if(res != ERROR_SUCCESS)
3439 SetLastError(res);
3440 return handle;
3443 static const LPCWSTR header_lookup[] = {
3444 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
3445 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3446 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3447 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
3448 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3449 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3450 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3451 szAllow, /* HTTP_QUERY_ALLOW = 7 */
3452 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
3453 szDate, /* HTTP_QUERY_DATE = 9 */
3454 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
3455 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3456 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
3457 szURI, /* HTTP_QUERY_URI = 13 */
3458 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
3459 NULL, /* HTTP_QUERY_COST = 15 */
3460 NULL, /* HTTP_QUERY_LINK = 16 */
3461 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
3462 NULL, /* HTTP_QUERY_VERSION = 18 */
3463 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
3464 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
3465 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
3466 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3467 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
3468 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
3469 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3470 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3471 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3472 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
3473 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3474 NULL, /* HTTP_QUERY_FORWARDED = 30 */
3475 NULL, /* HTTP_QUERY_FROM = 31 */
3476 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3477 szLocation, /* HTTP_QUERY_LOCATION = 33 */
3478 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
3479 szReferer, /* HTTP_QUERY_REFERER = 35 */
3480 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
3481 szServer, /* HTTP_QUERY_SERVER = 37 */
3482 NULL, /* HTTP_TITLE = 38 */
3483 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
3484 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3485 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3486 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3487 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
3488 szCookie, /* HTTP_QUERY_COOKIE = 44 */
3489 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3490 NULL, /* HTTP_QUERY_REFRESH = 46 */
3491 szContent_Disposition, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3492 szAge, /* HTTP_QUERY_AGE = 48 */
3493 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3494 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
3495 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3496 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3497 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3498 szETag, /* HTTP_QUERY_ETAG = 54 */
3499 hostW, /* HTTP_QUERY_HOST = 55 */
3500 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
3501 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3502 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
3503 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3504 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3505 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3506 szRange, /* HTTP_QUERY_RANGE = 62 */
3507 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3508 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
3509 szVary, /* HTTP_QUERY_VARY = 65 */
3510 szVia, /* HTTP_QUERY_VIA = 66 */
3511 szWarning, /* HTTP_QUERY_WARNING = 67 */
3512 szExpect, /* HTTP_QUERY_EXPECT = 68 */
3513 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3514 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3517 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3519 /***********************************************************************
3520 * HTTP_HttpQueryInfoW (internal)
3522 static DWORD HTTP_HttpQueryInfoW(http_request_t *request, DWORD dwInfoLevel,
3523 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3525 LPHTTPHEADERW lphttpHdr = NULL;
3526 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
3527 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
3528 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
3529 INT index = -1;
3531 /* Find requested header structure */
3532 switch (level)
3534 case HTTP_QUERY_CUSTOM:
3535 if (!lpBuffer) return ERROR_INVALID_PARAMETER;
3536 index = HTTP_GetCustomHeaderIndex(request, lpBuffer, requested_index, request_only);
3537 break;
3538 case HTTP_QUERY_RAW_HEADERS_CRLF:
3540 LPWSTR headers;
3541 DWORD len = 0;
3542 DWORD res = ERROR_INVALID_PARAMETER;
3544 if (request_only)
3545 headers = build_request_header(request, request->verb, request->path, request->version, TRUE);
3546 else
3547 headers = build_response_header(request, TRUE);
3548 if (!headers)
3549 return ERROR_OUTOFMEMORY;
3551 len = strlenW(headers) * sizeof(WCHAR);
3552 if (len + sizeof(WCHAR) > *lpdwBufferLength)
3554 len += sizeof(WCHAR);
3555 res = ERROR_INSUFFICIENT_BUFFER;
3557 else if (lpBuffer)
3559 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3560 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
3561 res = ERROR_SUCCESS;
3563 *lpdwBufferLength = len;
3565 heap_free(headers);
3566 return res;
3568 case HTTP_QUERY_RAW_HEADERS:
3570 LPWSTR headers;
3571 DWORD len;
3573 if (request_only)
3574 headers = build_request_header(request, request->verb, request->path, request->version, FALSE);
3575 else
3576 headers = build_response_header(request, FALSE);
3577 if (!headers)
3578 return ERROR_OUTOFMEMORY;
3580 len = strlenW(headers) * sizeof(WCHAR);
3581 if (len > *lpdwBufferLength)
3583 *lpdwBufferLength = len;
3584 heap_free(headers);
3585 return ERROR_INSUFFICIENT_BUFFER;
3588 if (lpBuffer)
3590 DWORD i;
3592 TRACE("returning data: %s\n", debugstr_wn(headers, len / sizeof(WCHAR)));
3594 for (i=0; i<len; i++)
3596 if (headers[i] == '\n')
3597 headers[i] = 0;
3599 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3601 *lpdwBufferLength = len - sizeof(WCHAR);
3603 heap_free(headers);
3604 return ERROR_SUCCESS;
3606 case HTTP_QUERY_STATUS_TEXT:
3607 if (request->statusText)
3609 DWORD len = strlenW(request->statusText);
3610 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3612 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3613 return ERROR_INSUFFICIENT_BUFFER;
3615 if (lpBuffer)
3617 memcpy(lpBuffer, request->statusText, (len + 1) * sizeof(WCHAR));
3618 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3620 *lpdwBufferLength = len * sizeof(WCHAR);
3621 return ERROR_SUCCESS;
3623 break;
3624 case HTTP_QUERY_VERSION:
3625 if (request->version)
3627 DWORD len = strlenW(request->version);
3628 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3630 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3631 return ERROR_INSUFFICIENT_BUFFER;
3633 if (lpBuffer)
3635 memcpy(lpBuffer, request->version, (len + 1) * sizeof(WCHAR));
3636 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3638 *lpdwBufferLength = len * sizeof(WCHAR);
3639 return ERROR_SUCCESS;
3641 break;
3642 case HTTP_QUERY_CONTENT_ENCODING:
3643 index = HTTP_GetCustomHeaderIndex(request, header_lookup[request->read_gzip ? HTTP_QUERY_CONTENT_TYPE : level],
3644 requested_index,request_only);
3645 break;
3646 case HTTP_QUERY_STATUS_CODE: {
3647 DWORD res = ERROR_SUCCESS;
3649 if(request_only)
3650 return ERROR_HTTP_INVALID_QUERY_REQUEST;
3652 if(requested_index)
3653 break;
3655 if(dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) {
3656 if(*lpdwBufferLength >= sizeof(DWORD))
3657 *(DWORD*)lpBuffer = request->status_code;
3658 else
3659 res = ERROR_INSUFFICIENT_BUFFER;
3660 *lpdwBufferLength = sizeof(DWORD);
3661 }else {
3662 WCHAR buf[12];
3663 DWORD size;
3664 static const WCHAR formatW[] = {'%','u',0};
3666 size = sprintfW(buf, formatW, request->status_code) * sizeof(WCHAR);
3668 if(size <= *lpdwBufferLength) {
3669 memcpy(lpBuffer, buf, size+sizeof(WCHAR));
3670 }else {
3671 size += sizeof(WCHAR);
3672 res = ERROR_INSUFFICIENT_BUFFER;
3675 *lpdwBufferLength = size;
3677 return res;
3679 default:
3680 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
3682 if (level < LAST_TABLE_HEADER && header_lookup[level])
3683 index = HTTP_GetCustomHeaderIndex(request, header_lookup[level],
3684 requested_index,request_only);
3687 if (index >= 0)
3688 lphttpHdr = &request->custHeaders[index];
3690 /* Ensure header satisfies requested attributes */
3691 if (!lphttpHdr ||
3692 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
3693 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
3695 return ERROR_HTTP_HEADER_NOT_FOUND;
3698 if (lpdwIndex) (*lpdwIndex)++;
3700 /* coalesce value to requested type */
3701 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
3703 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
3704 TRACE(" returning number: %d\n", *(int *)lpBuffer);
3706 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
3708 time_t tmpTime;
3709 struct tm tmpTM;
3710 SYSTEMTIME *STHook;
3712 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
3714 tmpTM = *gmtime(&tmpTime);
3715 STHook = (SYSTEMTIME *)lpBuffer;
3716 STHook->wDay = tmpTM.tm_mday;
3717 STHook->wHour = tmpTM.tm_hour;
3718 STHook->wMilliseconds = 0;
3719 STHook->wMinute = tmpTM.tm_min;
3720 STHook->wDayOfWeek = tmpTM.tm_wday;
3721 STHook->wMonth = tmpTM.tm_mon + 1;
3722 STHook->wSecond = tmpTM.tm_sec;
3723 STHook->wYear = 1900+tmpTM.tm_year;
3725 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3726 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
3727 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
3729 else if (lphttpHdr->lpszValue)
3731 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
3733 if (len > *lpdwBufferLength)
3735 *lpdwBufferLength = len;
3736 return ERROR_INSUFFICIENT_BUFFER;
3738 if (lpBuffer)
3740 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
3741 TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
3743 *lpdwBufferLength = len - sizeof(WCHAR);
3745 return ERROR_SUCCESS;
3748 /***********************************************************************
3749 * HttpQueryInfoW (WININET.@)
3751 * Queries for information about an HTTP request
3753 * RETURNS
3754 * TRUE on success
3755 * FALSE on failure
3758 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3759 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3761 http_request_t *request;
3762 DWORD res;
3764 if (TRACE_ON(wininet)) {
3765 #define FE(x) { x, #x }
3766 static const wininet_flag_info query_flags[] = {
3767 FE(HTTP_QUERY_MIME_VERSION),
3768 FE(HTTP_QUERY_CONTENT_TYPE),
3769 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
3770 FE(HTTP_QUERY_CONTENT_ID),
3771 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
3772 FE(HTTP_QUERY_CONTENT_LENGTH),
3773 FE(HTTP_QUERY_CONTENT_LANGUAGE),
3774 FE(HTTP_QUERY_ALLOW),
3775 FE(HTTP_QUERY_PUBLIC),
3776 FE(HTTP_QUERY_DATE),
3777 FE(HTTP_QUERY_EXPIRES),
3778 FE(HTTP_QUERY_LAST_MODIFIED),
3779 FE(HTTP_QUERY_MESSAGE_ID),
3780 FE(HTTP_QUERY_URI),
3781 FE(HTTP_QUERY_DERIVED_FROM),
3782 FE(HTTP_QUERY_COST),
3783 FE(HTTP_QUERY_LINK),
3784 FE(HTTP_QUERY_PRAGMA),
3785 FE(HTTP_QUERY_VERSION),
3786 FE(HTTP_QUERY_STATUS_CODE),
3787 FE(HTTP_QUERY_STATUS_TEXT),
3788 FE(HTTP_QUERY_RAW_HEADERS),
3789 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
3790 FE(HTTP_QUERY_CONNECTION),
3791 FE(HTTP_QUERY_ACCEPT),
3792 FE(HTTP_QUERY_ACCEPT_CHARSET),
3793 FE(HTTP_QUERY_ACCEPT_ENCODING),
3794 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
3795 FE(HTTP_QUERY_AUTHORIZATION),
3796 FE(HTTP_QUERY_CONTENT_ENCODING),
3797 FE(HTTP_QUERY_FORWARDED),
3798 FE(HTTP_QUERY_FROM),
3799 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
3800 FE(HTTP_QUERY_LOCATION),
3801 FE(HTTP_QUERY_ORIG_URI),
3802 FE(HTTP_QUERY_REFERER),
3803 FE(HTTP_QUERY_RETRY_AFTER),
3804 FE(HTTP_QUERY_SERVER),
3805 FE(HTTP_QUERY_TITLE),
3806 FE(HTTP_QUERY_USER_AGENT),
3807 FE(HTTP_QUERY_WWW_AUTHENTICATE),
3808 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
3809 FE(HTTP_QUERY_ACCEPT_RANGES),
3810 FE(HTTP_QUERY_SET_COOKIE),
3811 FE(HTTP_QUERY_COOKIE),
3812 FE(HTTP_QUERY_REQUEST_METHOD),
3813 FE(HTTP_QUERY_REFRESH),
3814 FE(HTTP_QUERY_CONTENT_DISPOSITION),
3815 FE(HTTP_QUERY_AGE),
3816 FE(HTTP_QUERY_CACHE_CONTROL),
3817 FE(HTTP_QUERY_CONTENT_BASE),
3818 FE(HTTP_QUERY_CONTENT_LOCATION),
3819 FE(HTTP_QUERY_CONTENT_MD5),
3820 FE(HTTP_QUERY_CONTENT_RANGE),
3821 FE(HTTP_QUERY_ETAG),
3822 FE(HTTP_QUERY_HOST),
3823 FE(HTTP_QUERY_IF_MATCH),
3824 FE(HTTP_QUERY_IF_NONE_MATCH),
3825 FE(HTTP_QUERY_IF_RANGE),
3826 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
3827 FE(HTTP_QUERY_MAX_FORWARDS),
3828 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
3829 FE(HTTP_QUERY_RANGE),
3830 FE(HTTP_QUERY_TRANSFER_ENCODING),
3831 FE(HTTP_QUERY_UPGRADE),
3832 FE(HTTP_QUERY_VARY),
3833 FE(HTTP_QUERY_VIA),
3834 FE(HTTP_QUERY_WARNING),
3835 FE(HTTP_QUERY_CUSTOM)
3837 static const wininet_flag_info modifier_flags[] = {
3838 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
3839 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
3840 FE(HTTP_QUERY_FLAG_NUMBER),
3841 FE(HTTP_QUERY_FLAG_COALESCE)
3843 #undef FE
3844 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
3845 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
3846 DWORD i;
3848 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, info);
3849 TRACE(" Attribute:");
3850 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
3851 if (query_flags[i].val == info) {
3852 TRACE(" %s", query_flags[i].name);
3853 break;
3856 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
3857 TRACE(" Unknown (%08x)", info);
3860 TRACE(" Modifier:");
3861 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
3862 if (modifier_flags[i].val & info_mod) {
3863 TRACE(" %s", modifier_flags[i].name);
3864 info_mod &= ~ modifier_flags[i].val;
3868 if (info_mod) {
3869 TRACE(" Unknown (%08x)", info_mod);
3871 TRACE("\n");
3874 request = (http_request_t*) get_handle_object( hHttpRequest );
3875 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
3877 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3878 goto lend;
3881 if (lpBuffer == NULL)
3882 *lpdwBufferLength = 0;
3883 res = HTTP_HttpQueryInfoW( request, dwInfoLevel,
3884 lpBuffer, lpdwBufferLength, lpdwIndex);
3886 lend:
3887 if( request )
3888 WININET_Release( &request->hdr );
3890 TRACE("%u <--\n", res);
3891 if(res != ERROR_SUCCESS)
3892 SetLastError(res);
3893 return res == ERROR_SUCCESS;
3896 /***********************************************************************
3897 * HttpQueryInfoA (WININET.@)
3899 * Queries for information about an HTTP request
3901 * RETURNS
3902 * TRUE on success
3903 * FALSE on failure
3906 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3907 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3909 BOOL result;
3910 DWORD len;
3911 WCHAR* bufferW;
3913 TRACE("%p %x\n", hHttpRequest, dwInfoLevel);
3915 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
3916 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
3918 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
3919 lpdwBufferLength, lpdwIndex );
3922 if (lpBuffer)
3924 DWORD alloclen;
3925 len = (*lpdwBufferLength)*sizeof(WCHAR);
3926 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3928 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
3929 if (alloclen < len)
3930 alloclen = len;
3932 else
3933 alloclen = len;
3934 bufferW = heap_alloc(alloclen);
3935 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3936 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3937 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
3938 } else
3940 bufferW = NULL;
3941 len = 0;
3944 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
3945 &len, lpdwIndex );
3946 if( result )
3948 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
3949 lpBuffer, *lpdwBufferLength, NULL, NULL );
3950 *lpdwBufferLength = len - 1;
3952 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
3954 else
3955 /* since the strings being returned from HttpQueryInfoW should be
3956 * only ASCII characters, it is reasonable to assume that all of
3957 * the Unicode characters can be reduced to a single byte */
3958 *lpdwBufferLength = len / sizeof(WCHAR);
3960 heap_free( bufferW );
3961 return result;
3964 /***********************************************************************
3965 * HTTP_GetRedirectURL (internal)
3967 static LPWSTR HTTP_GetRedirectURL(http_request_t *request, LPCWSTR lpszUrl)
3969 static WCHAR szHttp[] = {'h','t','t','p',0};
3970 static WCHAR szHttps[] = {'h','t','t','p','s',0};
3971 http_session_t *session = request->session;
3972 URL_COMPONENTSW urlComponents;
3973 DWORD url_length = 0;
3974 LPWSTR orig_url;
3975 LPWSTR combined_url;
3977 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3978 urlComponents.lpszScheme = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
3979 urlComponents.dwSchemeLength = 0;
3980 urlComponents.lpszHostName = session->hostName;
3981 urlComponents.dwHostNameLength = 0;
3982 urlComponents.nPort = session->hostPort;
3983 urlComponents.lpszUserName = session->userName;
3984 urlComponents.dwUserNameLength = 0;
3985 urlComponents.lpszPassword = NULL;
3986 urlComponents.dwPasswordLength = 0;
3987 urlComponents.lpszUrlPath = request->path;
3988 urlComponents.dwUrlPathLength = 0;
3989 urlComponents.lpszExtraInfo = NULL;
3990 urlComponents.dwExtraInfoLength = 0;
3992 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
3993 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
3994 return NULL;
3996 orig_url = heap_alloc(url_length);
3998 /* convert from bytes to characters */
3999 url_length = url_length / sizeof(WCHAR) - 1;
4000 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
4002 heap_free(orig_url);
4003 return NULL;
4006 url_length = 0;
4007 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
4008 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
4010 heap_free(orig_url);
4011 return NULL;
4013 combined_url = heap_alloc(url_length * sizeof(WCHAR));
4015 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
4017 heap_free(orig_url);
4018 heap_free(combined_url);
4019 return NULL;
4021 heap_free(orig_url);
4022 return combined_url;
4026 /***********************************************************************
4027 * HTTP_HandleRedirect (internal)
4029 static DWORD HTTP_HandleRedirect(http_request_t *request, LPCWSTR lpszUrl)
4031 http_session_t *session = request->session;
4032 WCHAR path[INTERNET_MAX_PATH_LENGTH];
4033 int index;
4035 if(lpszUrl[0]=='/')
4037 /* if it's an absolute path, keep the same session info */
4038 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
4040 else
4042 URL_COMPONENTSW urlComponents;
4043 WCHAR protocol[INTERNET_MAX_SCHEME_LENGTH];
4044 WCHAR hostName[INTERNET_MAX_HOST_NAME_LENGTH];
4045 WCHAR userName[INTERNET_MAX_USER_NAME_LENGTH];
4046 BOOL custom_port = FALSE;
4048 static const WCHAR httpW[] = {'h','t','t','p',0};
4049 static const WCHAR httpsW[] = {'h','t','t','p','s',0};
4051 userName[0] = 0;
4052 hostName[0] = 0;
4053 protocol[0] = 0;
4055 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
4056 urlComponents.lpszScheme = protocol;
4057 urlComponents.dwSchemeLength = INTERNET_MAX_SCHEME_LENGTH;
4058 urlComponents.lpszHostName = hostName;
4059 urlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
4060 urlComponents.lpszUserName = userName;
4061 urlComponents.dwUserNameLength = INTERNET_MAX_USER_NAME_LENGTH;
4062 urlComponents.lpszPassword = NULL;
4063 urlComponents.dwPasswordLength = 0;
4064 urlComponents.lpszUrlPath = path;
4065 urlComponents.dwUrlPathLength = INTERNET_MAX_PATH_LENGTH;
4066 urlComponents.lpszExtraInfo = NULL;
4067 urlComponents.dwExtraInfoLength = 0;
4068 if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
4069 return INTERNET_GetLastError();
4071 if(!strcmpiW(protocol, httpW)) {
4072 if(request->hdr.dwFlags & INTERNET_FLAG_SECURE) {
4073 TRACE("redirect from secure page to non-secure page\n");
4074 /* FIXME: warn about from secure redirect to non-secure page */
4075 request->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
4078 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4079 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
4080 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT)
4081 custom_port = TRUE;
4082 }else if(!strcmpiW(protocol, httpsW)) {
4083 if(!(request->hdr.dwFlags & INTERNET_FLAG_SECURE)) {
4084 TRACE("redirect from non-secure page to secure page\n");
4085 /* FIXME: notify about redirect to secure page */
4086 request->hdr.dwFlags |= INTERNET_FLAG_SECURE;
4089 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4090 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
4091 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
4092 custom_port = TRUE;
4095 heap_free(session->hostName);
4097 if(custom_port) {
4098 int len;
4099 static const WCHAR fmt[] = {'%','s',':','%','u',0};
4100 len = lstrlenW(hostName);
4101 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
4102 session->hostName = heap_alloc(len*sizeof(WCHAR));
4103 sprintfW(session->hostName, fmt, hostName, urlComponents.nPort);
4105 else
4106 session->hostName = heap_strdupW(hostName);
4108 HTTP_ProcessHeader(request, hostW, session->hostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4110 heap_free(session->userName);
4111 session->userName = NULL;
4112 if (userName[0])
4113 session->userName = heap_strdupW(userName);
4115 reset_data_stream(request);
4117 if(strcmpiW(request->server->name, hostName) || request->server->port != urlComponents.nPort) {
4118 server_t *new_server;
4120 new_server = get_server(hostName, urlComponents.nPort, urlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
4121 server_release(request->server);
4122 request->server = new_server;
4125 heap_free(request->path);
4126 request->path=NULL;
4127 if (*path)
4129 DWORD needed = 0;
4130 HRESULT rc;
4132 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
4133 if (rc != E_POINTER)
4134 needed = strlenW(path)+1;
4135 request->path = heap_alloc(needed*sizeof(WCHAR));
4136 rc = UrlEscapeW(path, request->path, &needed,
4137 URL_ESCAPE_SPACES_ONLY);
4138 if (rc != S_OK)
4140 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4141 strcpyW(request->path,path);
4145 /* Remove custom content-type/length headers on redirects. */
4146 index = HTTP_GetCustomHeaderIndex(request, szContent_Type, 0, TRUE);
4147 if (0 <= index)
4148 HTTP_DeleteCustomHeader(request, index);
4149 index = HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE);
4150 if (0 <= index)
4151 HTTP_DeleteCustomHeader(request, index);
4153 return ERROR_SUCCESS;
4156 /***********************************************************************
4157 * HTTP_build_req (internal)
4159 * concatenate all the strings in the request together
4161 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
4163 LPCWSTR *t;
4164 LPWSTR str;
4166 for( t = list; *t ; t++ )
4167 len += strlenW( *t );
4168 len++;
4170 str = heap_alloc(len*sizeof(WCHAR));
4171 *str = 0;
4173 for( t = list; *t ; t++ )
4174 strcatW( str, *t );
4176 return str;
4179 static void HTTP_InsertCookies(http_request_t *request)
4181 DWORD cookie_size, size, cnt = 0;
4182 HTTPHEADERW *host;
4183 WCHAR *cookies;
4185 static const WCHAR cookieW[] = {'C','o','o','k','i','e',':',' ',0};
4187 host = HTTP_GetHeader(request, hostW);
4188 if(!host)
4189 return;
4191 if(get_cookie(host->lpszValue, request->path, NULL, &cookie_size) != ERROR_SUCCESS)
4192 return;
4194 size = sizeof(cookieW) + cookie_size * sizeof(WCHAR) + sizeof(szCrLf);
4195 if(!(cookies = heap_alloc(size)))
4196 return;
4198 cnt += sprintfW(cookies, cookieW);
4199 get_cookie(host->lpszValue, request->path, cookies+cnt, &cookie_size);
4200 strcatW(cookies, szCrLf);
4202 HTTP_HttpAddRequestHeadersW(request, cookies, strlenW(cookies), HTTP_ADDREQ_FLAG_REPLACE);
4204 heap_free(cookies);
4207 static WORD HTTP_ParseWkday(LPCWSTR day)
4209 static const WCHAR days[7][4] = {{ 's','u','n',0 },
4210 { 'm','o','n',0 },
4211 { 't','u','e',0 },
4212 { 'w','e','d',0 },
4213 { 't','h','u',0 },
4214 { 'f','r','i',0 },
4215 { 's','a','t',0 }};
4216 unsigned int i;
4217 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4218 if (!strcmpiW(day, days[i]))
4219 return i;
4221 /* Invalid */
4222 return 7;
4225 static WORD HTTP_ParseMonth(LPCWSTR month)
4227 static const WCHAR jan[] = { 'j','a','n',0 };
4228 static const WCHAR feb[] = { 'f','e','b',0 };
4229 static const WCHAR mar[] = { 'm','a','r',0 };
4230 static const WCHAR apr[] = { 'a','p','r',0 };
4231 static const WCHAR may[] = { 'm','a','y',0 };
4232 static const WCHAR jun[] = { 'j','u','n',0 };
4233 static const WCHAR jul[] = { 'j','u','l',0 };
4234 static const WCHAR aug[] = { 'a','u','g',0 };
4235 static const WCHAR sep[] = { 's','e','p',0 };
4236 static const WCHAR oct[] = { 'o','c','t',0 };
4237 static const WCHAR nov[] = { 'n','o','v',0 };
4238 static const WCHAR dec[] = { 'd','e','c',0 };
4240 if (!strcmpiW(month, jan)) return 1;
4241 if (!strcmpiW(month, feb)) return 2;
4242 if (!strcmpiW(month, mar)) return 3;
4243 if (!strcmpiW(month, apr)) return 4;
4244 if (!strcmpiW(month, may)) return 5;
4245 if (!strcmpiW(month, jun)) return 6;
4246 if (!strcmpiW(month, jul)) return 7;
4247 if (!strcmpiW(month, aug)) return 8;
4248 if (!strcmpiW(month, sep)) return 9;
4249 if (!strcmpiW(month, oct)) return 10;
4250 if (!strcmpiW(month, nov)) return 11;
4251 if (!strcmpiW(month, dec)) return 12;
4252 /* Invalid */
4253 return 0;
4256 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4257 * optionally preceded by whitespace.
4258 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4259 * st, and sets *str to the first character after the time format.
4261 static BOOL HTTP_ParseTime(SYSTEMTIME *st, LPCWSTR *str)
4263 LPCWSTR ptr = *str;
4264 WCHAR *nextPtr;
4265 unsigned long num;
4267 while (isspaceW(*ptr))
4268 ptr++;
4270 num = strtoulW(ptr, &nextPtr, 10);
4271 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4273 ERR("unexpected time format %s\n", debugstr_w(ptr));
4274 return FALSE;
4276 if (num > 23)
4278 ERR("unexpected hour in time format %s\n", debugstr_w(ptr));
4279 return FALSE;
4281 ptr = nextPtr + 1;
4282 st->wHour = (WORD)num;
4283 num = strtoulW(ptr, &nextPtr, 10);
4284 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4286 ERR("unexpected time format %s\n", debugstr_w(ptr));
4287 return FALSE;
4289 if (num > 59)
4291 ERR("unexpected minute in time format %s\n", debugstr_w(ptr));
4292 return FALSE;
4294 ptr = nextPtr + 1;
4295 st->wMinute = (WORD)num;
4296 num = strtoulW(ptr, &nextPtr, 10);
4297 if (!nextPtr || nextPtr <= ptr)
4299 ERR("unexpected time format %s\n", debugstr_w(ptr));
4300 return FALSE;
4302 if (num > 59)
4304 ERR("unexpected second in time format %s\n", debugstr_w(ptr));
4305 return FALSE;
4307 ptr = nextPtr + 1;
4308 *str = ptr;
4309 st->wSecond = (WORD)num;
4310 return TRUE;
4313 static BOOL HTTP_ParseDateAsAsctime(LPCWSTR value, FILETIME *ft)
4315 static const WCHAR gmt[]= { 'G','M','T',0 };
4316 WCHAR day[4], *dayPtr, month[4], *monthPtr, *nextPtr;
4317 LPCWSTR ptr;
4318 SYSTEMTIME st = { 0 };
4319 unsigned long num;
4321 for (ptr = value, dayPtr = day; *ptr && !isspaceW(*ptr) &&
4322 dayPtr - day < sizeof(day) / sizeof(day[0]) - 1; ptr++, dayPtr++)
4323 *dayPtr = *ptr;
4324 *dayPtr = 0;
4325 st.wDayOfWeek = HTTP_ParseWkday(day);
4326 if (st.wDayOfWeek >= 7)
4328 ERR("unexpected weekday %s\n", debugstr_w(day));
4329 return FALSE;
4332 while (isspaceW(*ptr))
4333 ptr++;
4335 for (monthPtr = month; !isspace(*ptr) &&
4336 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4337 monthPtr++, ptr++)
4338 *monthPtr = *ptr;
4339 *monthPtr = 0;
4340 st.wMonth = HTTP_ParseMonth(month);
4341 if (!st.wMonth || st.wMonth > 12)
4343 ERR("unexpected month %s\n", debugstr_w(month));
4344 return FALSE;
4347 while (isspaceW(*ptr))
4348 ptr++;
4350 num = strtoulW(ptr, &nextPtr, 10);
4351 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4353 ERR("unexpected day %s\n", debugstr_w(ptr));
4354 return FALSE;
4356 ptr = nextPtr;
4357 st.wDay = (WORD)num;
4359 while (isspaceW(*ptr))
4360 ptr++;
4362 if (!HTTP_ParseTime(&st, &ptr))
4363 return FALSE;
4365 while (isspaceW(*ptr))
4366 ptr++;
4368 num = strtoulW(ptr, &nextPtr, 10);
4369 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4371 ERR("unexpected year %s\n", debugstr_w(ptr));
4372 return FALSE;
4374 ptr = nextPtr;
4375 st.wYear = (WORD)num;
4377 while (isspaceW(*ptr))
4378 ptr++;
4380 /* asctime() doesn't report a timezone, but some web servers do, so accept
4381 * with or without GMT.
4383 if (*ptr && strcmpW(ptr, gmt))
4385 ERR("unexpected timezone %s\n", debugstr_w(ptr));
4386 return FALSE;
4388 return SystemTimeToFileTime(&st, ft);
4391 static BOOL HTTP_ParseRfc1123Date(LPCWSTR value, FILETIME *ft)
4393 static const WCHAR gmt[]= { 'G','M','T',0 };
4394 WCHAR *nextPtr, day[4], month[4], *monthPtr;
4395 LPCWSTR ptr;
4396 unsigned long num;
4397 SYSTEMTIME st = { 0 };
4399 ptr = strchrW(value, ',');
4400 if (!ptr)
4401 return FALSE;
4402 if (ptr - value != 3)
4404 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4405 return FALSE;
4407 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4408 day[3] = 0;
4409 st.wDayOfWeek = HTTP_ParseWkday(day);
4410 if (st.wDayOfWeek > 6)
4412 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4413 return FALSE;
4415 ptr++;
4417 while (isspaceW(*ptr))
4418 ptr++;
4420 num = strtoulW(ptr, &nextPtr, 10);
4421 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4423 WARN("unexpected day %s\n", debugstr_w(value));
4424 return FALSE;
4426 ptr = nextPtr;
4427 st.wDay = (WORD)num;
4429 while (isspaceW(*ptr))
4430 ptr++;
4432 for (monthPtr = month; !isspace(*ptr) &&
4433 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4434 monthPtr++, ptr++)
4435 *monthPtr = *ptr;
4436 *monthPtr = 0;
4437 st.wMonth = HTTP_ParseMonth(month);
4438 if (!st.wMonth || st.wMonth > 12)
4440 WARN("unexpected month %s\n", debugstr_w(month));
4441 return FALSE;
4444 while (isspaceW(*ptr))
4445 ptr++;
4447 num = strtoulW(ptr, &nextPtr, 10);
4448 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4450 ERR("unexpected year %s\n", debugstr_w(value));
4451 return FALSE;
4453 ptr = nextPtr;
4454 st.wYear = (WORD)num;
4456 if (!HTTP_ParseTime(&st, &ptr))
4457 return FALSE;
4459 while (isspaceW(*ptr))
4460 ptr++;
4462 if (strcmpW(ptr, gmt))
4464 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4465 return FALSE;
4467 return SystemTimeToFileTime(&st, ft);
4470 static WORD HTTP_ParseWeekday(LPCWSTR day)
4472 static const WCHAR days[7][10] = {{ 's','u','n','d','a','y',0 },
4473 { 'm','o','n','d','a','y',0 },
4474 { 't','u','e','s','d','a','y',0 },
4475 { 'w','e','d','n','e','s','d','a','y',0 },
4476 { 't','h','u','r','s','d','a','y',0 },
4477 { 'f','r','i','d','a','y',0 },
4478 { 's','a','t','u','r','d','a','y',0 }};
4479 unsigned int i;
4480 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4481 if (!strcmpiW(day, days[i]))
4482 return i;
4484 /* Invalid */
4485 return 7;
4488 static BOOL HTTP_ParseRfc850Date(LPCWSTR value, FILETIME *ft)
4490 static const WCHAR gmt[]= { 'G','M','T',0 };
4491 WCHAR *nextPtr, day[10], month[4], *monthPtr;
4492 LPCWSTR ptr;
4493 unsigned long num;
4494 SYSTEMTIME st = { 0 };
4496 ptr = strchrW(value, ',');
4497 if (!ptr)
4498 return FALSE;
4499 if (ptr - value == 3)
4501 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4502 day[3] = 0;
4503 st.wDayOfWeek = HTTP_ParseWkday(day);
4504 if (st.wDayOfWeek > 6)
4506 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4507 return FALSE;
4510 else if (ptr - value < sizeof(day) / sizeof(day[0]))
4512 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4513 day[ptr - value + 1] = 0;
4514 st.wDayOfWeek = HTTP_ParseWeekday(day);
4515 if (st.wDayOfWeek > 6)
4517 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4518 return FALSE;
4521 else
4523 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4524 return FALSE;
4526 ptr++;
4528 while (isspaceW(*ptr))
4529 ptr++;
4531 num = strtoulW(ptr, &nextPtr, 10);
4532 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4534 ERR("unexpected day %s\n", debugstr_w(value));
4535 return FALSE;
4537 ptr = nextPtr;
4538 st.wDay = (WORD)num;
4540 if (*ptr != '-')
4542 ERR("unexpected month format %s\n", debugstr_w(ptr));
4543 return FALSE;
4545 ptr++;
4547 for (monthPtr = month; *ptr != '-' &&
4548 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4549 monthPtr++, ptr++)
4550 *monthPtr = *ptr;
4551 *monthPtr = 0;
4552 st.wMonth = HTTP_ParseMonth(month);
4553 if (!st.wMonth || st.wMonth > 12)
4555 ERR("unexpected month %s\n", debugstr_w(month));
4556 return FALSE;
4559 if (*ptr != '-')
4561 ERR("unexpected year format %s\n", debugstr_w(ptr));
4562 return FALSE;
4564 ptr++;
4566 num = strtoulW(ptr, &nextPtr, 10);
4567 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4569 ERR("unexpected year %s\n", debugstr_w(value));
4570 return FALSE;
4572 ptr = nextPtr;
4573 st.wYear = (WORD)num;
4575 if (!HTTP_ParseTime(&st, &ptr))
4576 return FALSE;
4578 while (isspaceW(*ptr))
4579 ptr++;
4581 if (strcmpW(ptr, gmt))
4583 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4584 return FALSE;
4586 return SystemTimeToFileTime(&st, ft);
4589 static BOOL HTTP_ParseDate(LPCWSTR value, FILETIME *ft)
4591 static const WCHAR zero[] = { '0',0 };
4592 BOOL ret;
4594 if (!strcmpW(value, zero))
4596 ft->dwLowDateTime = ft->dwHighDateTime = 0;
4597 ret = TRUE;
4599 else if (strchrW(value, ','))
4601 ret = HTTP_ParseRfc1123Date(value, ft);
4602 if (!ret)
4604 ret = HTTP_ParseRfc850Date(value, ft);
4605 if (!ret)
4606 ERR("unexpected date format %s\n", debugstr_w(value));
4609 else
4611 ret = HTTP_ParseDateAsAsctime(value, ft);
4612 if (!ret)
4613 ERR("unexpected date format %s\n", debugstr_w(value));
4615 return ret;
4618 static void HTTP_ProcessExpires(http_request_t *request)
4620 BOOL expirationFound = FALSE;
4621 int headerIndex;
4623 /* Look for a Cache-Control header with a max-age directive, as it takes
4624 * precedence over the Expires header.
4626 headerIndex = HTTP_GetCustomHeaderIndex(request, szCache_Control, 0, FALSE);
4627 if (headerIndex != -1)
4629 LPHTTPHEADERW ccHeader = &request->custHeaders[headerIndex];
4630 LPWSTR ptr;
4632 for (ptr = ccHeader->lpszValue; ptr && *ptr; )
4634 LPWSTR comma = strchrW(ptr, ','), end, equal;
4636 if (comma)
4637 end = comma;
4638 else
4639 end = ptr + strlenW(ptr);
4640 for (equal = end - 1; equal > ptr && *equal != '='; equal--)
4642 if (*equal == '=')
4644 static const WCHAR max_age[] = {
4645 'm','a','x','-','a','g','e',0 };
4647 if (!strncmpiW(ptr, max_age, equal - ptr - 1))
4649 LPWSTR nextPtr;
4650 unsigned long age;
4652 age = strtoulW(equal + 1, &nextPtr, 10);
4653 if (nextPtr > equal + 1)
4655 LARGE_INTEGER ft;
4657 NtQuerySystemTime( &ft );
4658 /* Age is in seconds, FILETIME resolution is in
4659 * 100 nanosecond intervals.
4661 ft.QuadPart += age * (ULONGLONG)1000000;
4662 request->expires.dwLowDateTime = ft.u.LowPart;
4663 request->expires.dwHighDateTime = ft.u.HighPart;
4664 expirationFound = TRUE;
4668 if (comma)
4670 ptr = comma + 1;
4671 while (isspaceW(*ptr))
4672 ptr++;
4674 else
4675 ptr = NULL;
4678 if (!expirationFound)
4680 headerIndex = HTTP_GetCustomHeaderIndex(request, szExpires, 0, FALSE);
4681 if (headerIndex != -1)
4683 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4684 FILETIME ft;
4686 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4688 expirationFound = TRUE;
4689 request->expires = ft;
4693 if (!expirationFound)
4695 LARGE_INTEGER t;
4697 /* With no known age, default to 10 minutes until expiration. */
4698 NtQuerySystemTime( &t );
4699 t.QuadPart += 10 * 60 * (ULONGLONG)10000000;
4700 request->expires.dwLowDateTime = t.u.LowPart;
4701 request->expires.dwHighDateTime = t.u.HighPart;
4705 static void HTTP_ProcessLastModified(http_request_t *request)
4707 int headerIndex;
4709 headerIndex = HTTP_GetCustomHeaderIndex(request, szLast_Modified, 0, FALSE);
4710 if (headerIndex != -1)
4712 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4713 FILETIME ft;
4715 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4716 request->last_modified = ft;
4720 static void http_process_keep_alive(http_request_t *req)
4722 int index;
4724 if ((index = HTTP_GetCustomHeaderIndex(req, szConnection, 0, FALSE)) != -1)
4725 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4726 else if ((index = HTTP_GetCustomHeaderIndex(req, szProxy_Connection, 0, FALSE)) != -1)
4727 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4728 else
4729 req->netconn->keep_alive = !strcmpiW(req->version, g_szHttp1_1);
4732 static DWORD open_http_connection(http_request_t *request, BOOL *reusing)
4734 const BOOL is_https = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) != 0;
4735 netconn_t *netconn = NULL;
4736 DWORD res;
4738 reset_data_stream(request);
4740 if (request->netconn)
4742 if (is_valid_netconn(request->netconn) && NETCON_is_alive(request->netconn))
4744 *reusing = TRUE;
4745 return ERROR_SUCCESS;
4747 else
4749 free_netconn(request->netconn);
4750 request->netconn = NULL;
4754 res = HTTP_ResolveName(request);
4755 if(res != ERROR_SUCCESS)
4756 return res;
4758 EnterCriticalSection(&connection_pool_cs);
4760 while(!list_empty(&request->server->conn_pool)) {
4761 netconn = LIST_ENTRY(list_head(&request->server->conn_pool), netconn_t, pool_entry);
4762 list_remove(&netconn->pool_entry);
4764 if(is_valid_netconn(netconn) && NETCON_is_alive(netconn))
4765 break;
4767 TRACE("connection %p closed during idle\n", netconn);
4768 free_netconn(netconn);
4769 netconn = NULL;
4772 LeaveCriticalSection(&connection_pool_cs);
4774 if(netconn) {
4775 TRACE("<-- reusing %p netconn\n", netconn);
4776 request->netconn = netconn;
4777 *reusing = TRUE;
4778 return ERROR_SUCCESS;
4781 TRACE("connecting to %s, proxy %s\n", debugstr_w(request->server->name),
4782 request->proxy ? debugstr_w(request->proxy->name) : "(null)");
4784 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4785 INTERNET_STATUS_CONNECTING_TO_SERVER,
4786 request->server->addr_str,
4787 strlen(request->server->addr_str)+1);
4789 res = create_netconn(is_https, request->proxy ? request->proxy : request->server, request->security_flags,
4790 (request->hdr.ErrorMask & INTERNET_ERROR_MASK_COMBINED_SEC_CERT) != 0,
4791 request->connect_timeout, &netconn);
4792 if(res != ERROR_SUCCESS) {
4793 ERR("create_netconn failed: %u\n", res);
4794 return res;
4797 request->netconn = netconn;
4799 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4800 INTERNET_STATUS_CONNECTED_TO_SERVER,
4801 request->server->addr_str, strlen(request->server->addr_str)+1);
4803 *reusing = FALSE;
4804 TRACE("Created connection to %s: %p\n", debugstr_w(request->server->name), netconn);
4805 return ERROR_SUCCESS;
4808 static char *build_ascii_request( const WCHAR *str, void *data, DWORD data_len, DWORD *out_len )
4810 int len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
4811 char *ret;
4813 if (!(ret = heap_alloc( len + data_len ))) return NULL;
4814 WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
4815 if (data_len) memcpy( ret + len - 1, data, data_len );
4816 *out_len = len + data_len - 1;
4817 ret[*out_len] = 0;
4818 return ret;
4821 /***********************************************************************
4822 * HTTP_HttpSendRequestW (internal)
4824 * Sends the specified request to the HTTP server
4826 * RETURNS
4827 * ERROR_SUCCESS on success
4828 * win32 error code on failure
4831 static DWORD HTTP_HttpSendRequestW(http_request_t *request, LPCWSTR lpszHeaders,
4832 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
4833 DWORD dwContentLength, BOOL bEndRequest)
4835 static const WCHAR szContentLength[] =
4836 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
4837 BOOL redirected = FALSE, secure_proxy_connect = FALSE, loop_next;
4838 LPWSTR requestString = NULL;
4839 INT responseLen, cnt;
4840 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
4841 DWORD res;
4843 TRACE("--> %p\n", request);
4845 assert(request->hdr.htype == WH_HHTTPREQ);
4847 /* if the verb is NULL default to GET */
4848 if (!request->verb)
4849 request->verb = heap_strdupW(szGET);
4851 if (dwContentLength || strcmpW(request->verb, szGET))
4853 sprintfW(contentLengthStr, szContentLength, dwContentLength);
4854 HTTP_HttpAddRequestHeadersW(request, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_REPLACE);
4855 request->bytesToWrite = dwContentLength;
4857 if (request->session->appInfo->agent)
4859 WCHAR *agent_header;
4860 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4861 int len;
4863 len = strlenW(request->session->appInfo->agent) + strlenW(user_agent);
4864 agent_header = heap_alloc(len * sizeof(WCHAR));
4865 sprintfW(agent_header, user_agent, request->session->appInfo->agent);
4867 HTTP_HttpAddRequestHeadersW(request, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4868 heap_free(agent_header);
4870 if (request->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
4872 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4873 HTTP_HttpAddRequestHeadersW(request, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4875 if ((request->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && strcmpW(request->verb, szGET))
4877 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4878 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4879 HTTP_HttpAddRequestHeadersW(request, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4882 /* add the headers the caller supplied */
4883 if( lpszHeaders && dwHeaderLength )
4884 HTTP_HttpAddRequestHeadersW(request, lpszHeaders, dwHeaderLength, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
4888 DWORD len, data_len = dwOptionalLength;
4889 BOOL reusing_connection;
4890 char *ascii_req;
4892 loop_next = FALSE;
4894 if(redirected) {
4895 request->contentLength = ~0u;
4896 request->bytesToWrite = 0;
4899 if (TRACE_ON(wininet))
4901 LPHTTPHEADERW Host = HTTP_GetHeader(request, hostW);
4902 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(request->path));
4905 HTTP_FixURL(request);
4906 if (request->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
4908 HTTP_ProcessHeader(request, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
4910 HTTP_InsertAuthorization(request, request->authInfo, szAuthorization);
4911 HTTP_InsertAuthorization(request, request->proxyAuthInfo, szProxy_Authorization);
4913 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
4914 HTTP_InsertCookies(request);
4916 res = open_http_connection(request, &reusing_connection);
4917 if (res != ERROR_SUCCESS)
4918 break;
4920 if (!reusing_connection && (request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4922 if (request->proxy) secure_proxy_connect = TRUE;
4923 else
4925 res = NETCON_secure_connect(request->netconn, request->server);
4926 if (res != ERROR_SUCCESS)
4928 WARN("failed to upgrade to secure connection\n");
4929 http_release_netconn(request, FALSE);
4930 break;
4934 if (secure_proxy_connect)
4936 static const WCHAR connectW[] = {'C','O','N','N','E','C','T',0};
4937 const WCHAR *target = request->server->host_port;
4938 requestString = build_request_header(request, connectW, target, g_szHttp1_1, TRUE);
4940 else if (request->proxy && !(request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4942 WCHAR *url = build_proxy_path_url(request);
4943 requestString = build_request_header(request, request->verb, url, request->version, TRUE);
4944 heap_free(url);
4946 else
4947 requestString = build_request_header(request, request->verb, request->path, request->version, TRUE);
4949 TRACE("Request header -> %s\n", debugstr_w(requestString) );
4951 /* send the request as ASCII, tack on the optional data */
4952 if (!lpOptional || redirected || secure_proxy_connect)
4953 data_len = 0;
4955 ascii_req = build_ascii_request( requestString, lpOptional, data_len, &len );
4956 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
4958 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4959 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
4961 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
4962 res = NETCON_send(request->netconn, ascii_req, len, 0, &cnt);
4963 heap_free( ascii_req );
4964 if(res != ERROR_SUCCESS) {
4965 TRACE("send failed: %u\n", res);
4966 if(!reusing_connection)
4967 break;
4968 http_release_netconn(request, FALSE);
4969 loop_next = TRUE;
4970 continue;
4973 request->bytesWritten = data_len;
4975 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4976 INTERNET_STATUS_REQUEST_SENT,
4977 &len, sizeof(DWORD));
4979 if (bEndRequest)
4981 DWORD dwBufferSize;
4983 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4984 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
4986 if (HTTP_GetResponseHeaders(request, &responseLen))
4988 http_release_netconn(request, FALSE);
4989 res = ERROR_INTERNET_CONNECTION_ABORTED;
4990 goto lend;
4992 /* FIXME: We should know that connection is closed before sending
4993 * headers. Otherwise wrong callbacks are executed */
4994 if(!responseLen && reusing_connection) {
4995 TRACE("Connection closed by server, reconnecting\n");
4996 http_release_netconn(request, FALSE);
4997 loop_next = TRUE;
4998 continue;
5001 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5002 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
5003 sizeof(DWORD));
5005 http_process_keep_alive(request);
5006 HTTP_ProcessCookies(request);
5007 HTTP_ProcessExpires(request);
5008 HTTP_ProcessLastModified(request);
5010 res = set_content_length(request);
5011 if(res != ERROR_SUCCESS)
5012 goto lend;
5013 if(!request->contentLength)
5014 http_release_netconn(request, TRUE);
5016 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
5018 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5019 dwBufferSize=sizeof(szNewLocation);
5020 switch(request->status_code) {
5021 case HTTP_STATUS_REDIRECT:
5022 case HTTP_STATUS_MOVED:
5023 case HTTP_STATUS_REDIRECT_KEEP_VERB:
5024 case HTTP_STATUS_REDIRECT_METHOD:
5025 if(HTTP_HttpQueryInfoW(request,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL) != ERROR_SUCCESS)
5026 break;
5028 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5029 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5031 heap_free(request->verb);
5032 request->verb = heap_strdupW(szGET);
5034 http_release_netconn(request, drain_content(request, FALSE));
5035 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5037 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5038 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5039 res = HTTP_HandleRedirect(request, new_url);
5040 if (res == ERROR_SUCCESS)
5042 heap_free(requestString);
5043 loop_next = TRUE;
5045 heap_free( new_url );
5047 redirected = TRUE;
5050 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
5052 WCHAR szAuthValue[2048];
5053 dwBufferSize=2048;
5054 if (request->status_code == HTTP_STATUS_DENIED)
5056 LPHTTPHEADERW Host = HTTP_GetHeader(request, hostW);
5057 DWORD dwIndex = 0;
5058 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5060 if (HTTP_DoAuthorization(request, szAuthValue,
5061 &request->authInfo,
5062 request->session->userName,
5063 request->session->password,
5064 Host->lpszValue))
5066 heap_free(requestString);
5067 if(!drain_content(request, TRUE)) {
5068 FIXME("Could not drain content\n");
5069 http_release_netconn(request, FALSE);
5071 loop_next = TRUE;
5072 break;
5076 if(!loop_next) {
5077 TRACE("Cleaning wrong authorization data\n");
5078 destroy_authinfo(request->authInfo);
5079 request->authInfo = NULL;
5082 if (request->status_code == HTTP_STATUS_PROXY_AUTH_REQ)
5084 DWORD dwIndex = 0;
5085 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5087 if (HTTP_DoAuthorization(request, szAuthValue,
5088 &request->proxyAuthInfo,
5089 request->session->appInfo->proxyUsername,
5090 request->session->appInfo->proxyPassword,
5091 NULL))
5093 heap_free(requestString);
5094 if(!drain_content(request, TRUE)) {
5095 FIXME("Could not drain content\n");
5096 http_release_netconn(request, FALSE);
5098 loop_next = TRUE;
5099 break;
5103 if(!loop_next) {
5104 TRACE("Cleaning wrong proxy authorization data\n");
5105 destroy_authinfo(request->proxyAuthInfo);
5106 request->proxyAuthInfo = NULL;
5110 if (secure_proxy_connect && request->status_code == HTTP_STATUS_OK)
5112 int index;
5114 res = NETCON_secure_connect(request->netconn, request->server);
5115 if (res != ERROR_SUCCESS)
5117 WARN("failed to upgrade to secure proxy connection\n");
5118 http_release_netconn( request, FALSE );
5119 break;
5121 index = HTTP_GetCustomHeaderIndex(request, szProxy_Authorization, 0, TRUE);
5122 if (index != -1) HTTP_DeleteCustomHeader(request, index);
5123 destroy_authinfo(request->proxyAuthInfo);
5124 request->proxyAuthInfo = NULL;
5126 secure_proxy_connect = FALSE;
5127 loop_next = TRUE;
5130 else
5131 res = ERROR_SUCCESS;
5133 while (loop_next);
5135 lend:
5136 heap_free(requestString);
5138 /* TODO: send notification for P3P header */
5140 if(res == ERROR_SUCCESS)
5141 create_cache_entry(request);
5143 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5145 if (res == ERROR_SUCCESS) {
5146 if(bEndRequest && request->contentLength && request->bytesWritten == request->bytesToWrite)
5147 HTTP_ReceiveRequestData(request, TRUE, NULL);
5148 else
5149 send_request_complete(request,
5150 request->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)request->hdr.hInternet : 1, 0);
5151 }else {
5152 send_request_complete(request, 0, res);
5156 TRACE("<--\n");
5157 return res;
5160 typedef struct {
5161 task_header_t hdr;
5162 WCHAR *headers;
5163 DWORD headers_len;
5164 void *optional;
5165 DWORD optional_len;
5166 DWORD content_len;
5167 BOOL end_request;
5168 } send_request_task_t;
5170 /***********************************************************************
5172 * Helper functions for the HttpSendRequest(Ex) functions
5175 static void AsyncHttpSendRequestProc(task_header_t *hdr)
5177 send_request_task_t *task = (send_request_task_t*)hdr;
5178 http_request_t *request = (http_request_t*)task->hdr.hdr;
5180 TRACE("%p\n", request);
5182 HTTP_HttpSendRequestW(request, task->headers, task->headers_len, task->optional,
5183 task->optional_len, task->content_len, task->end_request);
5185 heap_free(task->headers);
5189 static DWORD HTTP_HttpEndRequestW(http_request_t *request, DWORD dwFlags, DWORD_PTR dwContext)
5191 DWORD dwBufferSize;
5192 INT responseLen;
5193 DWORD res = ERROR_SUCCESS;
5195 if(!is_valid_netconn(request->netconn)) {
5196 WARN("Not connected\n");
5197 send_request_complete(request, 0, ERROR_INTERNET_OPERATION_CANCELLED);
5198 return ERROR_INTERNET_OPERATION_CANCELLED;
5201 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5202 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5204 if (HTTP_GetResponseHeaders(request, &responseLen) || !responseLen)
5205 res = ERROR_HTTP_HEADER_NOT_FOUND;
5207 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5208 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
5210 /* process cookies here. Is this right? */
5211 http_process_keep_alive(request);
5212 HTTP_ProcessCookies(request);
5213 HTTP_ProcessExpires(request);
5214 HTTP_ProcessLastModified(request);
5216 if ((res = set_content_length(request)) == ERROR_SUCCESS) {
5217 if(!request->contentLength)
5218 http_release_netconn(request, TRUE);
5221 if (res == ERROR_SUCCESS && !(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
5223 switch(request->status_code) {
5224 case HTTP_STATUS_REDIRECT:
5225 case HTTP_STATUS_MOVED:
5226 case HTTP_STATUS_REDIRECT_METHOD:
5227 case HTTP_STATUS_REDIRECT_KEEP_VERB: {
5228 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5229 dwBufferSize=sizeof(szNewLocation);
5230 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, szNewLocation, &dwBufferSize, NULL) != ERROR_SUCCESS)
5231 break;
5233 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5234 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5236 heap_free(request->verb);
5237 request->verb = heap_strdupW(szGET);
5239 http_release_netconn(request, drain_content(request, FALSE));
5240 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5242 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5243 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5244 res = HTTP_HandleRedirect(request, new_url);
5245 if (res == ERROR_SUCCESS)
5246 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, TRUE);
5247 heap_free( new_url );
5253 if(res == ERROR_SUCCESS)
5254 create_cache_entry(request);
5256 if (res == ERROR_SUCCESS && request->contentLength)
5257 HTTP_ReceiveRequestData(request, TRUE, NULL);
5258 else
5259 send_request_complete(request, res == ERROR_SUCCESS, res);
5261 return res;
5264 /***********************************************************************
5265 * HttpEndRequestA (WININET.@)
5267 * Ends an HTTP request that was started by HttpSendRequestEx
5269 * RETURNS
5270 * TRUE if successful
5271 * FALSE on failure
5274 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
5275 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5277 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5279 if (lpBuffersOut)
5281 SetLastError(ERROR_INVALID_PARAMETER);
5282 return FALSE;
5285 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
5288 typedef struct {
5289 task_header_t hdr;
5290 DWORD flags;
5291 DWORD context;
5292 } end_request_task_t;
5294 static void AsyncHttpEndRequestProc(task_header_t *hdr)
5296 end_request_task_t *task = (end_request_task_t*)hdr;
5297 http_request_t *req = (http_request_t*)task->hdr.hdr;
5299 TRACE("%p\n", req);
5301 HTTP_HttpEndRequestW(req, task->flags, task->context);
5304 /***********************************************************************
5305 * HttpEndRequestW (WININET.@)
5307 * Ends an HTTP request that was started by HttpSendRequestEx
5309 * RETURNS
5310 * TRUE if successful
5311 * FALSE on failure
5314 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
5315 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5317 http_request_t *request;
5318 DWORD res;
5320 TRACE("%p %p %x %lx -->\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5322 if (lpBuffersOut)
5324 SetLastError(ERROR_INVALID_PARAMETER);
5325 return FALSE;
5328 request = (http_request_t*) get_handle_object( hRequest );
5330 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5332 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
5333 if (request)
5334 WININET_Release( &request->hdr );
5335 return FALSE;
5337 request->hdr.dwFlags |= dwFlags;
5339 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5341 end_request_task_t *task;
5343 task = alloc_async_task(&request->hdr, AsyncHttpEndRequestProc, sizeof(*task));
5344 task->flags = dwFlags;
5345 task->context = dwContext;
5347 INTERNET_AsyncCall(&task->hdr);
5348 res = ERROR_IO_PENDING;
5350 else
5351 res = HTTP_HttpEndRequestW(request, dwFlags, dwContext);
5353 WININET_Release( &request->hdr );
5354 TRACE("%u <--\n", res);
5355 if(res != ERROR_SUCCESS)
5356 SetLastError(res);
5357 return res == ERROR_SUCCESS;
5360 /***********************************************************************
5361 * HttpSendRequestExA (WININET.@)
5363 * Sends the specified request to the HTTP server and allows chunked
5364 * transfers.
5366 * RETURNS
5367 * Success: TRUE
5368 * Failure: FALSE, call GetLastError() for more information.
5370 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
5371 LPINTERNET_BUFFERSA lpBuffersIn,
5372 LPINTERNET_BUFFERSA lpBuffersOut,
5373 DWORD dwFlags, DWORD_PTR dwContext)
5375 INTERNET_BUFFERSW BuffersInW;
5376 BOOL rc = FALSE;
5377 DWORD headerlen;
5378 LPWSTR header = NULL;
5380 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5381 lpBuffersOut, dwFlags, dwContext);
5383 if (lpBuffersIn)
5385 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
5386 if (lpBuffersIn->lpcszHeader)
5388 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
5389 lpBuffersIn->dwHeadersLength,0,0);
5390 header = heap_alloc(headerlen*sizeof(WCHAR));
5391 if (!(BuffersInW.lpcszHeader = header))
5393 SetLastError(ERROR_OUTOFMEMORY);
5394 return FALSE;
5396 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
5397 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5398 header, headerlen);
5400 else
5401 BuffersInW.lpcszHeader = NULL;
5402 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
5403 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
5404 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
5405 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
5406 BuffersInW.Next = NULL;
5409 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
5411 heap_free(header);
5412 return rc;
5415 /***********************************************************************
5416 * HttpSendRequestExW (WININET.@)
5418 * Sends the specified request to the HTTP server and allows chunked
5419 * transfers
5421 * RETURNS
5422 * Success: TRUE
5423 * Failure: FALSE, call GetLastError() for more information.
5425 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
5426 LPINTERNET_BUFFERSW lpBuffersIn,
5427 LPINTERNET_BUFFERSW lpBuffersOut,
5428 DWORD dwFlags, DWORD_PTR dwContext)
5430 http_request_t *request;
5431 http_session_t *session;
5432 appinfo_t *hIC;
5433 DWORD res;
5435 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5436 lpBuffersOut, dwFlags, dwContext);
5438 request = (http_request_t*) get_handle_object( hRequest );
5440 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5442 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5443 goto lend;
5446 session = request->session;
5447 assert(session->hdr.htype == WH_HHTTPSESSION);
5448 hIC = session->appInfo;
5449 assert(hIC->hdr.htype == WH_HINIT);
5451 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5453 send_request_task_t *task;
5455 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5456 if (lpBuffersIn)
5458 DWORD size = 0;
5460 if (lpBuffersIn->lpcszHeader)
5462 if (lpBuffersIn->dwHeadersLength == ~0u)
5463 size = (strlenW( lpBuffersIn->lpcszHeader ) + 1) * sizeof(WCHAR);
5464 else
5465 size = lpBuffersIn->dwHeadersLength * sizeof(WCHAR);
5467 task->headers = heap_alloc(size);
5468 memcpy(task->headers, lpBuffersIn->lpcszHeader, size);
5470 else task->headers = NULL;
5472 task->headers_len = size / sizeof(WCHAR);
5473 task->optional = lpBuffersIn->lpvBuffer;
5474 task->optional_len = lpBuffersIn->dwBufferLength;
5475 task->content_len = lpBuffersIn->dwBufferTotal;
5477 else
5479 task->headers = NULL;
5480 task->headers_len = 0;
5481 task->optional = NULL;
5482 task->optional_len = 0;
5483 task->content_len = 0;
5486 task->end_request = FALSE;
5488 INTERNET_AsyncCall(&task->hdr);
5489 res = ERROR_IO_PENDING;
5491 else
5493 if (lpBuffersIn)
5494 res = HTTP_HttpSendRequestW(request, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5495 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
5496 lpBuffersIn->dwBufferTotal, FALSE);
5497 else
5498 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, FALSE);
5501 lend:
5502 if ( request )
5503 WININET_Release( &request->hdr );
5505 TRACE("<---\n");
5506 SetLastError(res);
5507 return res == ERROR_SUCCESS;
5510 /***********************************************************************
5511 * HttpSendRequestW (WININET.@)
5513 * Sends the specified request to the HTTP server
5515 * RETURNS
5516 * TRUE on success
5517 * FALSE on failure
5520 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
5521 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5523 http_request_t *request;
5524 http_session_t *session = NULL;
5525 appinfo_t *hIC = NULL;
5526 DWORD res = ERROR_SUCCESS;
5528 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
5529 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
5531 request = (http_request_t*) get_handle_object( hHttpRequest );
5532 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5534 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5535 goto lend;
5538 session = request->session;
5539 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
5541 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5542 goto lend;
5545 hIC = session->appInfo;
5546 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
5548 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5549 goto lend;
5552 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5554 send_request_task_t *task;
5556 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5557 if (lpszHeaders)
5559 DWORD size;
5561 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
5562 else size = dwHeaderLength * sizeof(WCHAR);
5564 task->headers = heap_alloc(size);
5565 memcpy(task->headers, lpszHeaders, size);
5567 else
5568 task->headers = NULL;
5569 task->headers_len = dwHeaderLength;
5570 task->optional = lpOptional;
5571 task->optional_len = dwOptionalLength;
5572 task->content_len = dwOptionalLength;
5573 task->end_request = TRUE;
5575 INTERNET_AsyncCall(&task->hdr);
5576 res = ERROR_IO_PENDING;
5578 else
5580 res = HTTP_HttpSendRequestW(request, lpszHeaders,
5581 dwHeaderLength, lpOptional, dwOptionalLength,
5582 dwOptionalLength, TRUE);
5584 lend:
5585 if( request )
5586 WININET_Release( &request->hdr );
5588 SetLastError(res);
5589 return res == ERROR_SUCCESS;
5592 /***********************************************************************
5593 * HttpSendRequestA (WININET.@)
5595 * Sends the specified request to the HTTP server
5597 * RETURNS
5598 * TRUE on success
5599 * FALSE on failure
5602 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
5603 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5605 BOOL result;
5606 LPWSTR szHeaders=NULL;
5607 DWORD nLen=dwHeaderLength;
5608 if(lpszHeaders!=NULL)
5610 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
5611 szHeaders = heap_alloc(nLen*sizeof(WCHAR));
5612 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
5614 result = HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
5615 heap_free(szHeaders);
5616 return result;
5619 /***********************************************************************
5620 * HTTPSESSION_Destroy (internal)
5622 * Deallocate session handle
5625 static void HTTPSESSION_Destroy(object_header_t *hdr)
5627 http_session_t *session = (http_session_t*) hdr;
5629 TRACE("%p\n", session);
5631 WININET_Release(&session->appInfo->hdr);
5633 heap_free(session->hostName);
5634 heap_free(session->password);
5635 heap_free(session->userName);
5638 static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
5640 http_session_t *ses = (http_session_t *)hdr;
5642 switch(option) {
5643 case INTERNET_OPTION_HANDLE_TYPE:
5644 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5646 if (*size < sizeof(ULONG))
5647 return ERROR_INSUFFICIENT_BUFFER;
5649 *size = sizeof(DWORD);
5650 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
5651 return ERROR_SUCCESS;
5652 case INTERNET_OPTION_CONNECT_TIMEOUT:
5653 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5655 if (*size < sizeof(DWORD))
5656 return ERROR_INSUFFICIENT_BUFFER;
5658 *size = sizeof(DWORD);
5659 *(DWORD *)buffer = ses->connect_timeout;
5660 return ERROR_SUCCESS;
5662 case INTERNET_OPTION_SEND_TIMEOUT:
5663 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5665 if (*size < sizeof(DWORD))
5666 return ERROR_INSUFFICIENT_BUFFER;
5668 *size = sizeof(DWORD);
5669 *(DWORD *)buffer = ses->send_timeout;
5670 return ERROR_SUCCESS;
5672 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5673 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5675 if (*size < sizeof(DWORD))
5676 return ERROR_INSUFFICIENT_BUFFER;
5678 *size = sizeof(DWORD);
5679 *(DWORD *)buffer = ses->receive_timeout;
5680 return ERROR_SUCCESS;
5683 return INET_QueryOption(hdr, option, buffer, size, unicode);
5686 static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
5688 http_session_t *ses = (http_session_t*)hdr;
5690 switch(option) {
5691 case INTERNET_OPTION_USERNAME:
5693 heap_free(ses->userName);
5694 if (!(ses->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5695 return ERROR_SUCCESS;
5697 case INTERNET_OPTION_PASSWORD:
5699 heap_free(ses->password);
5700 if (!(ses->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5701 return ERROR_SUCCESS;
5703 case INTERNET_OPTION_PROXY_USERNAME:
5705 heap_free(ses->appInfo->proxyUsername);
5706 if (!(ses->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5707 return ERROR_SUCCESS;
5709 case INTERNET_OPTION_PROXY_PASSWORD:
5711 heap_free(ses->appInfo->proxyPassword);
5712 if (!(ses->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5713 return ERROR_SUCCESS;
5715 case INTERNET_OPTION_CONNECT_TIMEOUT:
5717 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5718 ses->connect_timeout = *(DWORD *)buffer;
5719 return ERROR_SUCCESS;
5721 case INTERNET_OPTION_SEND_TIMEOUT:
5723 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5724 ses->send_timeout = *(DWORD *)buffer;
5725 return ERROR_SUCCESS;
5727 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5729 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5730 ses->receive_timeout = *(DWORD *)buffer;
5731 return ERROR_SUCCESS;
5733 default: break;
5736 return INET_SetOption(hdr, option, buffer, size);
5739 static const object_vtbl_t HTTPSESSIONVtbl = {
5740 HTTPSESSION_Destroy,
5741 NULL,
5742 HTTPSESSION_QueryOption,
5743 HTTPSESSION_SetOption,
5744 NULL,
5745 NULL,
5746 NULL,
5747 NULL,
5748 NULL
5752 /***********************************************************************
5753 * HTTP_Connect (internal)
5755 * Create http session handle
5757 * RETURNS
5758 * HINTERNET a session handle on success
5759 * NULL on failure
5762 DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
5763 INTERNET_PORT serverPort, LPCWSTR lpszUserName,
5764 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
5765 DWORD dwInternalFlags, HINTERNET *ret)
5767 http_session_t *session = NULL;
5769 TRACE("-->\n");
5771 if (!lpszServerName || !lpszServerName[0])
5772 return ERROR_INVALID_PARAMETER;
5774 assert( hIC->hdr.htype == WH_HINIT );
5776 session = alloc_object(&hIC->hdr, &HTTPSESSIONVtbl, sizeof(http_session_t));
5777 if (!session)
5778 return ERROR_OUTOFMEMORY;
5781 * According to my tests. The name is not resolved until a request is sent
5784 session->hdr.htype = WH_HHTTPSESSION;
5785 session->hdr.dwFlags = dwFlags;
5786 session->hdr.dwContext = dwContext;
5787 session->hdr.dwInternalFlags |= dwInternalFlags;
5789 WININET_AddRef( &hIC->hdr );
5790 session->appInfo = hIC;
5791 list_add_head( &hIC->hdr.children, &session->hdr.entry );
5793 session->hostName = heap_strdupW(lpszServerName);
5794 if (lpszUserName && lpszUserName[0])
5795 session->userName = heap_strdupW(lpszUserName);
5796 if (lpszPassword && lpszPassword[0])
5797 session->password = heap_strdupW(lpszPassword);
5798 session->hostPort = serverPort;
5799 session->connect_timeout = hIC->connect_timeout;
5800 session->send_timeout = INFINITE;
5801 session->receive_timeout = INFINITE;
5803 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5804 if (!(session->hdr.dwInternalFlags & INET_OPENURL))
5806 INTERNET_SendCallback(&hIC->hdr, dwContext,
5807 INTERNET_STATUS_HANDLE_CREATED, &session->hdr.hInternet,
5808 sizeof(HINTERNET));
5812 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5813 * windows
5816 TRACE("%p --> %p\n", hIC, session);
5818 *ret = session->hdr.hInternet;
5819 return ERROR_SUCCESS;
5822 /***********************************************************************
5823 * HTTP_clear_response_headers (internal)
5825 * clear out any old response headers
5827 static void HTTP_clear_response_headers( http_request_t *request )
5829 DWORD i;
5831 for( i=0; i<request->nCustHeaders; i++)
5833 if( !request->custHeaders[i].lpszField )
5834 continue;
5835 if( !request->custHeaders[i].lpszValue )
5836 continue;
5837 if ( request->custHeaders[i].wFlags & HDR_ISREQUEST )
5838 continue;
5839 HTTP_DeleteCustomHeader( request, i );
5840 i--;
5844 /***********************************************************************
5845 * HTTP_GetResponseHeaders (internal)
5847 * Read server response
5849 * RETURNS
5851 * TRUE on success
5852 * FALSE on error
5854 static DWORD HTTP_GetResponseHeaders(http_request_t *request, INT *len)
5856 INT cbreaks = 0;
5857 WCHAR buffer[MAX_REPLY_LEN];
5858 DWORD buflen = MAX_REPLY_LEN;
5859 INT rc = 0;
5860 char bufferA[MAX_REPLY_LEN];
5861 LPWSTR status_code = NULL, status_text = NULL;
5862 DWORD res = ERROR_HTTP_INVALID_SERVER_RESPONSE;
5863 BOOL codeHundred = FALSE;
5865 TRACE("-->\n");
5867 if(!is_valid_netconn(request->netconn))
5868 goto lend;
5870 /* clear old response headers (eg. from a redirect response) */
5871 HTTP_clear_response_headers( request );
5873 NETCON_set_timeout( request->netconn, FALSE, request->receive_timeout );
5874 do {
5876 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5878 buflen = MAX_REPLY_LEN;
5879 if ((res = read_line(request, bufferA, &buflen)))
5880 goto lend;
5882 if (!buflen) goto lend;
5884 rc += buflen;
5885 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5886 /* check is this a status code line? */
5887 if (!strncmpW(buffer, g_szHttp1_0, 4))
5889 /* split the version from the status code */
5890 status_code = strchrW( buffer, ' ' );
5891 if( !status_code )
5892 goto lend;
5893 *status_code++=0;
5895 /* split the status code from the status text */
5896 status_text = strchrW( status_code, ' ' );
5897 if( status_text )
5898 *status_text++=0;
5900 request->status_code = atoiW(status_code);
5902 TRACE("version [%s] status code [%s] status text [%s]\n",
5903 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
5905 codeHundred = request->status_code == HTTP_STATUS_CONTINUE;
5907 else if (!codeHundred)
5909 WARN("No status line at head of response (%s)\n", debugstr_w(buffer));
5911 heap_free(request->version);
5912 heap_free(request->statusText);
5914 request->status_code = HTTP_STATUS_OK;
5915 request->version = heap_strdupW(g_szHttp1_0);
5916 request->statusText = heap_strdupW(szOK);
5918 goto lend;
5920 } while (codeHundred);
5922 /* Add status code */
5923 HTTP_ProcessHeader(request, szStatus, status_code,
5924 HTTP_ADDHDR_FLAG_REPLACE);
5926 heap_free(request->version);
5927 heap_free(request->statusText);
5929 request->version = heap_strdupW(buffer);
5930 request->statusText = heap_strdupW(status_text ? status_text : emptyW);
5932 /* Restore the spaces */
5933 *(status_code-1) = ' ';
5934 if (status_text)
5935 *(status_text-1) = ' ';
5937 /* Parse each response line */
5940 buflen = MAX_REPLY_LEN;
5941 if (!read_line(request, bufferA, &buflen) && buflen)
5943 LPWSTR * pFieldAndValue;
5945 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
5947 if (!bufferA[0]) break;
5948 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5950 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
5951 if (pFieldAndValue)
5953 HTTP_ProcessHeader(request, pFieldAndValue[0], pFieldAndValue[1],
5954 HTTP_ADDREQ_FLAG_ADD );
5955 HTTP_FreeTokens(pFieldAndValue);
5958 else
5960 cbreaks++;
5961 if (cbreaks >= 2)
5962 break;
5964 }while(1);
5966 res = ERROR_SUCCESS;
5968 lend:
5970 *len = rc;
5971 TRACE("<--\n");
5972 return res;
5975 /***********************************************************************
5976 * HTTP_InterpretHttpHeader (internal)
5978 * Parse server response
5980 * RETURNS
5982 * Pointer to array of field, value, NULL on success.
5983 * NULL on error.
5985 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
5987 LPWSTR * pTokenPair;
5988 LPWSTR pszColon;
5989 INT len;
5991 pTokenPair = heap_alloc_zero(sizeof(*pTokenPair)*3);
5993 pszColon = strchrW(buffer, ':');
5994 /* must have two tokens */
5995 if (!pszColon)
5997 HTTP_FreeTokens(pTokenPair);
5998 if (buffer[0])
5999 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
6000 return NULL;
6003 pTokenPair[0] = heap_alloc((pszColon - buffer + 1) * sizeof(WCHAR));
6004 if (!pTokenPair[0])
6006 HTTP_FreeTokens(pTokenPair);
6007 return NULL;
6009 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
6010 pTokenPair[0][pszColon - buffer] = '\0';
6012 /* skip colon */
6013 pszColon++;
6014 len = strlenW(pszColon);
6015 pTokenPair[1] = heap_alloc((len + 1) * sizeof(WCHAR));
6016 if (!pTokenPair[1])
6018 HTTP_FreeTokens(pTokenPair);
6019 return NULL;
6021 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
6023 strip_spaces(pTokenPair[0]);
6024 strip_spaces(pTokenPair[1]);
6026 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
6027 return pTokenPair;
6030 /***********************************************************************
6031 * HTTP_ProcessHeader (internal)
6033 * Stuff header into header tables according to <dwModifier>
6037 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6039 static DWORD HTTP_ProcessHeader(http_request_t *request, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
6041 LPHTTPHEADERW lphttpHdr = NULL;
6042 INT index = -1;
6043 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
6044 DWORD res = ERROR_HTTP_INVALID_HEADER;
6046 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
6048 /* REPLACE wins out over ADD */
6049 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6050 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
6052 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
6053 index = -1;
6054 else
6055 index = HTTP_GetCustomHeaderIndex(request, field, 0, request_only);
6057 if (index >= 0)
6059 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
6060 return ERROR_HTTP_INVALID_HEADER;
6061 lphttpHdr = &request->custHeaders[index];
6063 else if (value)
6065 HTTPHEADERW hdr;
6067 hdr.lpszField = (LPWSTR)field;
6068 hdr.lpszValue = (LPWSTR)value;
6069 hdr.wFlags = hdr.wCount = 0;
6071 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6072 hdr.wFlags |= HDR_ISREQUEST;
6074 return HTTP_InsertCustomHeader(request, &hdr);
6076 /* no value to delete */
6077 else return ERROR_SUCCESS;
6079 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6080 lphttpHdr->wFlags |= HDR_ISREQUEST;
6081 else
6082 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
6084 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6086 HTTP_DeleteCustomHeader( request, index );
6088 if (value && value[0])
6090 HTTPHEADERW hdr;
6092 hdr.lpszField = (LPWSTR)field;
6093 hdr.lpszValue = (LPWSTR)value;
6094 hdr.wFlags = hdr.wCount = 0;
6096 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6097 hdr.wFlags |= HDR_ISREQUEST;
6099 return HTTP_InsertCustomHeader(request, &hdr);
6102 return ERROR_SUCCESS;
6104 else if (dwModifier & COALESCEFLAGS)
6106 LPWSTR lpsztmp;
6107 WCHAR ch = 0;
6108 INT len = 0;
6109 INT origlen = strlenW(lphttpHdr->lpszValue);
6110 INT valuelen = strlenW(value);
6112 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
6114 ch = ',';
6115 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6117 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6119 ch = ';';
6120 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6123 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
6125 lpsztmp = heap_realloc(lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
6126 if (lpsztmp)
6128 lphttpHdr->lpszValue = lpsztmp;
6129 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6130 if (ch > 0)
6132 lphttpHdr->lpszValue[origlen] = ch;
6133 origlen++;
6134 lphttpHdr->lpszValue[origlen] = ' ';
6135 origlen++;
6138 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
6139 lphttpHdr->lpszValue[len] = '\0';
6140 res = ERROR_SUCCESS;
6142 else
6144 WARN("heap_realloc (%d bytes) failed\n",len+1);
6145 res = ERROR_OUTOFMEMORY;
6148 TRACE("<-- %d\n", res);
6149 return res;
6152 /***********************************************************************
6153 * HTTP_GetCustomHeaderIndex (internal)
6155 * Return index of custom header from header array
6158 static INT HTTP_GetCustomHeaderIndex(http_request_t *request, LPCWSTR lpszField,
6159 int requested_index, BOOL request_only)
6161 DWORD index;
6163 TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
6165 for (index = 0; index < request->nCustHeaders; index++)
6167 if (strcmpiW(request->custHeaders[index].lpszField, lpszField))
6168 continue;
6170 if (request_only && !(request->custHeaders[index].wFlags & HDR_ISREQUEST))
6171 continue;
6173 if (!request_only && (request->custHeaders[index].wFlags & HDR_ISREQUEST))
6174 continue;
6176 if (requested_index == 0)
6177 break;
6178 requested_index --;
6181 if (index >= request->nCustHeaders)
6182 index = -1;
6184 TRACE("Return: %d\n", index);
6185 return index;
6189 /***********************************************************************
6190 * HTTP_InsertCustomHeader (internal)
6192 * Insert header into array
6195 static DWORD HTTP_InsertCustomHeader(http_request_t *request, LPHTTPHEADERW lpHdr)
6197 INT count;
6198 LPHTTPHEADERW lph = NULL;
6200 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
6201 count = request->nCustHeaders + 1;
6202 if (count > 1)
6203 lph = heap_realloc_zero(request->custHeaders, sizeof(HTTPHEADERW) * count);
6204 else
6205 lph = heap_alloc_zero(sizeof(HTTPHEADERW) * count);
6207 if (!lph)
6208 return ERROR_OUTOFMEMORY;
6210 request->custHeaders = lph;
6211 request->custHeaders[count-1].lpszField = heap_strdupW(lpHdr->lpszField);
6212 request->custHeaders[count-1].lpszValue = heap_strdupW(lpHdr->lpszValue);
6213 request->custHeaders[count-1].wFlags = lpHdr->wFlags;
6214 request->custHeaders[count-1].wCount= lpHdr->wCount;
6215 request->nCustHeaders++;
6217 return ERROR_SUCCESS;
6221 /***********************************************************************
6222 * HTTP_DeleteCustomHeader (internal)
6224 * Delete header from array
6225 * If this function is called, the indexs may change.
6227 static BOOL HTTP_DeleteCustomHeader(http_request_t *request, DWORD index)
6229 if( request->nCustHeaders <= 0 )
6230 return FALSE;
6231 if( index >= request->nCustHeaders )
6232 return FALSE;
6233 request->nCustHeaders--;
6235 heap_free(request->custHeaders[index].lpszField);
6236 heap_free(request->custHeaders[index].lpszValue);
6238 memmove( &request->custHeaders[index], &request->custHeaders[index+1],
6239 (request->nCustHeaders - index)* sizeof(HTTPHEADERW) );
6240 memset( &request->custHeaders[request->nCustHeaders], 0, sizeof(HTTPHEADERW) );
6242 return TRUE;
6246 /***********************************************************************
6247 * HTTP_VerifyValidHeader (internal)
6249 * Verify the given header is not invalid for the given http request
6252 static BOOL HTTP_VerifyValidHeader(http_request_t *request, LPCWSTR field)
6254 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
6255 if (!strcmpW(request->version, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
6256 return ERROR_HTTP_INVALID_HEADER;
6258 return ERROR_SUCCESS;
6261 /***********************************************************************
6262 * IsHostInProxyBypassList (@)
6264 * Undocumented
6267 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
6269 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
6270 return FALSE;