wininet: Use current server in HTTP_GetRedirectURL.
[wine/multimedia.git] / dlls / wininet / http.c
blob6c60c3a2f778bfe752674c48edffe229e45bd4e8
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 (hIC->proxy && hIC->proxy[0] && !HTTP_ShouldBypassProxy(hIC, session->hostName))
3372 HTTP_DealWithProxy( hIC, session, request );
3374 INTERNET_SendCallback(&session->hdr, dwContext,
3375 INTERNET_STATUS_HANDLE_CREATED, &request->hdr.hInternet,
3376 sizeof(HINTERNET));
3378 TRACE("<-- (%p)\n", request);
3380 *ret = request->hdr.hInternet;
3381 return ERROR_SUCCESS;
3384 /***********************************************************************
3385 * HttpOpenRequestW (WININET.@)
3387 * Open a HTTP request handle
3389 * RETURNS
3390 * HINTERNET a HTTP request handle on success
3391 * NULL on failure
3394 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
3395 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3396 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3397 DWORD dwFlags, DWORD_PTR dwContext)
3399 http_session_t *session;
3400 HINTERNET handle = NULL;
3401 DWORD res;
3403 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
3404 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
3405 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
3406 dwFlags, dwContext);
3407 if(lpszAcceptTypes!=NULL)
3409 int i;
3410 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
3411 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
3414 session = (http_session_t*) get_handle_object( hHttpSession );
3415 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
3417 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3418 goto lend;
3422 * My tests seem to show that the windows version does not
3423 * become asynchronous until after this point. And anyhow
3424 * if this call was asynchronous then how would you get the
3425 * necessary HINTERNET pointer returned by this function.
3428 res = HTTP_HttpOpenRequestW(session, lpszVerb, lpszObjectName,
3429 lpszVersion, lpszReferrer, lpszAcceptTypes,
3430 dwFlags, dwContext, &handle);
3431 lend:
3432 if( session )
3433 WININET_Release( &session->hdr );
3434 TRACE("returning %p\n", handle);
3435 if(res != ERROR_SUCCESS)
3436 SetLastError(res);
3437 return handle;
3440 static const LPCWSTR header_lookup[] = {
3441 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
3442 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3443 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3444 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
3445 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3446 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3447 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3448 szAllow, /* HTTP_QUERY_ALLOW = 7 */
3449 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
3450 szDate, /* HTTP_QUERY_DATE = 9 */
3451 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
3452 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3453 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
3454 szURI, /* HTTP_QUERY_URI = 13 */
3455 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
3456 NULL, /* HTTP_QUERY_COST = 15 */
3457 NULL, /* HTTP_QUERY_LINK = 16 */
3458 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
3459 NULL, /* HTTP_QUERY_VERSION = 18 */
3460 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
3461 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
3462 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
3463 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3464 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
3465 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
3466 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3467 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3468 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3469 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
3470 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3471 NULL, /* HTTP_QUERY_FORWARDED = 30 */
3472 NULL, /* HTTP_QUERY_FROM = 31 */
3473 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3474 szLocation, /* HTTP_QUERY_LOCATION = 33 */
3475 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
3476 szReferer, /* HTTP_QUERY_REFERER = 35 */
3477 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
3478 szServer, /* HTTP_QUERY_SERVER = 37 */
3479 NULL, /* HTTP_TITLE = 38 */
3480 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
3481 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3482 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3483 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3484 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
3485 szCookie, /* HTTP_QUERY_COOKIE = 44 */
3486 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3487 NULL, /* HTTP_QUERY_REFRESH = 46 */
3488 szContent_Disposition, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3489 szAge, /* HTTP_QUERY_AGE = 48 */
3490 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3491 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
3492 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3493 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3494 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3495 szETag, /* HTTP_QUERY_ETAG = 54 */
3496 hostW, /* HTTP_QUERY_HOST = 55 */
3497 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
3498 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3499 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
3500 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3501 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3502 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3503 szRange, /* HTTP_QUERY_RANGE = 62 */
3504 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3505 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
3506 szVary, /* HTTP_QUERY_VARY = 65 */
3507 szVia, /* HTTP_QUERY_VIA = 66 */
3508 szWarning, /* HTTP_QUERY_WARNING = 67 */
3509 szExpect, /* HTTP_QUERY_EXPECT = 68 */
3510 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3511 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3514 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3516 /***********************************************************************
3517 * HTTP_HttpQueryInfoW (internal)
3519 static DWORD HTTP_HttpQueryInfoW(http_request_t *request, DWORD dwInfoLevel,
3520 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3522 LPHTTPHEADERW lphttpHdr = NULL;
3523 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
3524 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
3525 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
3526 INT index = -1;
3528 /* Find requested header structure */
3529 switch (level)
3531 case HTTP_QUERY_CUSTOM:
3532 if (!lpBuffer) return ERROR_INVALID_PARAMETER;
3533 index = HTTP_GetCustomHeaderIndex(request, lpBuffer, requested_index, request_only);
3534 break;
3535 case HTTP_QUERY_RAW_HEADERS_CRLF:
3537 LPWSTR headers;
3538 DWORD len = 0;
3539 DWORD res = ERROR_INVALID_PARAMETER;
3541 if (request_only)
3542 headers = build_request_header(request, request->verb, request->path, request->version, TRUE);
3543 else
3544 headers = build_response_header(request, TRUE);
3545 if (!headers)
3546 return ERROR_OUTOFMEMORY;
3548 len = strlenW(headers) * sizeof(WCHAR);
3549 if (len + sizeof(WCHAR) > *lpdwBufferLength)
3551 len += sizeof(WCHAR);
3552 res = ERROR_INSUFFICIENT_BUFFER;
3554 else if (lpBuffer)
3556 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3557 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
3558 res = ERROR_SUCCESS;
3560 *lpdwBufferLength = len;
3562 heap_free(headers);
3563 return res;
3565 case HTTP_QUERY_RAW_HEADERS:
3567 LPWSTR headers;
3568 DWORD len;
3570 if (request_only)
3571 headers = build_request_header(request, request->verb, request->path, request->version, FALSE);
3572 else
3573 headers = build_response_header(request, FALSE);
3574 if (!headers)
3575 return ERROR_OUTOFMEMORY;
3577 len = strlenW(headers) * sizeof(WCHAR);
3578 if (len > *lpdwBufferLength)
3580 *lpdwBufferLength = len;
3581 heap_free(headers);
3582 return ERROR_INSUFFICIENT_BUFFER;
3585 if (lpBuffer)
3587 DWORD i;
3589 TRACE("returning data: %s\n", debugstr_wn(headers, len / sizeof(WCHAR)));
3591 for (i=0; i<len; i++)
3593 if (headers[i] == '\n')
3594 headers[i] = 0;
3596 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3598 *lpdwBufferLength = len - sizeof(WCHAR);
3600 heap_free(headers);
3601 return ERROR_SUCCESS;
3603 case HTTP_QUERY_STATUS_TEXT:
3604 if (request->statusText)
3606 DWORD len = strlenW(request->statusText);
3607 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3609 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3610 return ERROR_INSUFFICIENT_BUFFER;
3612 if (lpBuffer)
3614 memcpy(lpBuffer, request->statusText, (len + 1) * sizeof(WCHAR));
3615 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3617 *lpdwBufferLength = len * sizeof(WCHAR);
3618 return ERROR_SUCCESS;
3620 break;
3621 case HTTP_QUERY_VERSION:
3622 if (request->version)
3624 DWORD len = strlenW(request->version);
3625 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3627 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3628 return ERROR_INSUFFICIENT_BUFFER;
3630 if (lpBuffer)
3632 memcpy(lpBuffer, request->version, (len + 1) * sizeof(WCHAR));
3633 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3635 *lpdwBufferLength = len * sizeof(WCHAR);
3636 return ERROR_SUCCESS;
3638 break;
3639 case HTTP_QUERY_CONTENT_ENCODING:
3640 index = HTTP_GetCustomHeaderIndex(request, header_lookup[request->read_gzip ? HTTP_QUERY_CONTENT_TYPE : level],
3641 requested_index,request_only);
3642 break;
3643 case HTTP_QUERY_STATUS_CODE: {
3644 DWORD res = ERROR_SUCCESS;
3646 if(request_only)
3647 return ERROR_HTTP_INVALID_QUERY_REQUEST;
3649 if(requested_index)
3650 break;
3652 if(dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) {
3653 if(*lpdwBufferLength >= sizeof(DWORD))
3654 *(DWORD*)lpBuffer = request->status_code;
3655 else
3656 res = ERROR_INSUFFICIENT_BUFFER;
3657 *lpdwBufferLength = sizeof(DWORD);
3658 }else {
3659 WCHAR buf[12];
3660 DWORD size;
3661 static const WCHAR formatW[] = {'%','u',0};
3663 size = sprintfW(buf, formatW, request->status_code) * sizeof(WCHAR);
3665 if(size <= *lpdwBufferLength) {
3666 memcpy(lpBuffer, buf, size+sizeof(WCHAR));
3667 }else {
3668 size += sizeof(WCHAR);
3669 res = ERROR_INSUFFICIENT_BUFFER;
3672 *lpdwBufferLength = size;
3674 return res;
3676 default:
3677 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
3679 if (level < LAST_TABLE_HEADER && header_lookup[level])
3680 index = HTTP_GetCustomHeaderIndex(request, header_lookup[level],
3681 requested_index,request_only);
3684 if (index >= 0)
3685 lphttpHdr = &request->custHeaders[index];
3687 /* Ensure header satisfies requested attributes */
3688 if (!lphttpHdr ||
3689 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
3690 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
3692 return ERROR_HTTP_HEADER_NOT_FOUND;
3695 /* coalesce value to requested type */
3696 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
3698 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
3699 TRACE(" returning number: %d\n", *(int *)lpBuffer);
3701 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
3703 time_t tmpTime;
3704 struct tm tmpTM;
3705 SYSTEMTIME *STHook;
3707 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
3709 tmpTM = *gmtime(&tmpTime);
3710 STHook = (SYSTEMTIME *)lpBuffer;
3711 STHook->wDay = tmpTM.tm_mday;
3712 STHook->wHour = tmpTM.tm_hour;
3713 STHook->wMilliseconds = 0;
3714 STHook->wMinute = tmpTM.tm_min;
3715 STHook->wDayOfWeek = tmpTM.tm_wday;
3716 STHook->wMonth = tmpTM.tm_mon + 1;
3717 STHook->wSecond = tmpTM.tm_sec;
3718 STHook->wYear = 1900+tmpTM.tm_year;
3720 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3721 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
3722 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
3724 else if (lphttpHdr->lpszValue)
3726 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
3728 if (len > *lpdwBufferLength)
3730 *lpdwBufferLength = len;
3731 return ERROR_INSUFFICIENT_BUFFER;
3733 if (lpBuffer)
3735 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
3736 TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
3738 *lpdwBufferLength = len - sizeof(WCHAR);
3740 if (lpdwIndex) (*lpdwIndex)++;
3741 return ERROR_SUCCESS;
3744 /***********************************************************************
3745 * HttpQueryInfoW (WININET.@)
3747 * Queries for information about an HTTP request
3749 * RETURNS
3750 * TRUE on success
3751 * FALSE on failure
3754 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3755 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3757 http_request_t *request;
3758 DWORD res;
3760 if (TRACE_ON(wininet)) {
3761 #define FE(x) { x, #x }
3762 static const wininet_flag_info query_flags[] = {
3763 FE(HTTP_QUERY_MIME_VERSION),
3764 FE(HTTP_QUERY_CONTENT_TYPE),
3765 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
3766 FE(HTTP_QUERY_CONTENT_ID),
3767 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
3768 FE(HTTP_QUERY_CONTENT_LENGTH),
3769 FE(HTTP_QUERY_CONTENT_LANGUAGE),
3770 FE(HTTP_QUERY_ALLOW),
3771 FE(HTTP_QUERY_PUBLIC),
3772 FE(HTTP_QUERY_DATE),
3773 FE(HTTP_QUERY_EXPIRES),
3774 FE(HTTP_QUERY_LAST_MODIFIED),
3775 FE(HTTP_QUERY_MESSAGE_ID),
3776 FE(HTTP_QUERY_URI),
3777 FE(HTTP_QUERY_DERIVED_FROM),
3778 FE(HTTP_QUERY_COST),
3779 FE(HTTP_QUERY_LINK),
3780 FE(HTTP_QUERY_PRAGMA),
3781 FE(HTTP_QUERY_VERSION),
3782 FE(HTTP_QUERY_STATUS_CODE),
3783 FE(HTTP_QUERY_STATUS_TEXT),
3784 FE(HTTP_QUERY_RAW_HEADERS),
3785 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
3786 FE(HTTP_QUERY_CONNECTION),
3787 FE(HTTP_QUERY_ACCEPT),
3788 FE(HTTP_QUERY_ACCEPT_CHARSET),
3789 FE(HTTP_QUERY_ACCEPT_ENCODING),
3790 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
3791 FE(HTTP_QUERY_AUTHORIZATION),
3792 FE(HTTP_QUERY_CONTENT_ENCODING),
3793 FE(HTTP_QUERY_FORWARDED),
3794 FE(HTTP_QUERY_FROM),
3795 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
3796 FE(HTTP_QUERY_LOCATION),
3797 FE(HTTP_QUERY_ORIG_URI),
3798 FE(HTTP_QUERY_REFERER),
3799 FE(HTTP_QUERY_RETRY_AFTER),
3800 FE(HTTP_QUERY_SERVER),
3801 FE(HTTP_QUERY_TITLE),
3802 FE(HTTP_QUERY_USER_AGENT),
3803 FE(HTTP_QUERY_WWW_AUTHENTICATE),
3804 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
3805 FE(HTTP_QUERY_ACCEPT_RANGES),
3806 FE(HTTP_QUERY_SET_COOKIE),
3807 FE(HTTP_QUERY_COOKIE),
3808 FE(HTTP_QUERY_REQUEST_METHOD),
3809 FE(HTTP_QUERY_REFRESH),
3810 FE(HTTP_QUERY_CONTENT_DISPOSITION),
3811 FE(HTTP_QUERY_AGE),
3812 FE(HTTP_QUERY_CACHE_CONTROL),
3813 FE(HTTP_QUERY_CONTENT_BASE),
3814 FE(HTTP_QUERY_CONTENT_LOCATION),
3815 FE(HTTP_QUERY_CONTENT_MD5),
3816 FE(HTTP_QUERY_CONTENT_RANGE),
3817 FE(HTTP_QUERY_ETAG),
3818 FE(HTTP_QUERY_HOST),
3819 FE(HTTP_QUERY_IF_MATCH),
3820 FE(HTTP_QUERY_IF_NONE_MATCH),
3821 FE(HTTP_QUERY_IF_RANGE),
3822 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
3823 FE(HTTP_QUERY_MAX_FORWARDS),
3824 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
3825 FE(HTTP_QUERY_RANGE),
3826 FE(HTTP_QUERY_TRANSFER_ENCODING),
3827 FE(HTTP_QUERY_UPGRADE),
3828 FE(HTTP_QUERY_VARY),
3829 FE(HTTP_QUERY_VIA),
3830 FE(HTTP_QUERY_WARNING),
3831 FE(HTTP_QUERY_CUSTOM)
3833 static const wininet_flag_info modifier_flags[] = {
3834 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
3835 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
3836 FE(HTTP_QUERY_FLAG_NUMBER),
3837 FE(HTTP_QUERY_FLAG_COALESCE)
3839 #undef FE
3840 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
3841 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
3842 DWORD i;
3844 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, info);
3845 TRACE(" Attribute:");
3846 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
3847 if (query_flags[i].val == info) {
3848 TRACE(" %s", query_flags[i].name);
3849 break;
3852 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
3853 TRACE(" Unknown (%08x)", info);
3856 TRACE(" Modifier:");
3857 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
3858 if (modifier_flags[i].val & info_mod) {
3859 TRACE(" %s", modifier_flags[i].name);
3860 info_mod &= ~ modifier_flags[i].val;
3864 if (info_mod) {
3865 TRACE(" Unknown (%08x)", info_mod);
3867 TRACE("\n");
3870 request = (http_request_t*) get_handle_object( hHttpRequest );
3871 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
3873 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3874 goto lend;
3877 if (lpBuffer == NULL)
3878 *lpdwBufferLength = 0;
3879 res = HTTP_HttpQueryInfoW( request, dwInfoLevel,
3880 lpBuffer, lpdwBufferLength, lpdwIndex);
3882 lend:
3883 if( request )
3884 WININET_Release( &request->hdr );
3886 TRACE("%u <--\n", res);
3887 if(res != ERROR_SUCCESS)
3888 SetLastError(res);
3889 return res == ERROR_SUCCESS;
3892 /***********************************************************************
3893 * HttpQueryInfoA (WININET.@)
3895 * Queries for information about an HTTP request
3897 * RETURNS
3898 * TRUE on success
3899 * FALSE on failure
3902 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3903 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3905 BOOL result;
3906 DWORD len;
3907 WCHAR* bufferW;
3909 TRACE("%p %x\n", hHttpRequest, dwInfoLevel);
3911 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
3912 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
3914 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
3915 lpdwBufferLength, lpdwIndex );
3918 if (lpBuffer)
3920 DWORD alloclen;
3921 len = (*lpdwBufferLength)*sizeof(WCHAR);
3922 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3924 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
3925 if (alloclen < len)
3926 alloclen = len;
3928 else
3929 alloclen = len;
3930 bufferW = heap_alloc(alloclen);
3931 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3932 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3933 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
3934 } else
3936 bufferW = NULL;
3937 len = 0;
3940 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
3941 &len, lpdwIndex );
3942 if( result )
3944 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
3945 lpBuffer, *lpdwBufferLength, NULL, NULL );
3946 *lpdwBufferLength = len - 1;
3948 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
3950 else
3951 /* since the strings being returned from HttpQueryInfoW should be
3952 * only ASCII characters, it is reasonable to assume that all of
3953 * the Unicode characters can be reduced to a single byte */
3954 *lpdwBufferLength = len / sizeof(WCHAR);
3956 heap_free( bufferW );
3957 return result;
3960 /***********************************************************************
3961 * HTTP_GetRedirectURL (internal)
3963 static LPWSTR HTTP_GetRedirectURL(http_request_t *request, LPCWSTR lpszUrl)
3965 static WCHAR szHttp[] = {'h','t','t','p',0};
3966 static WCHAR szHttps[] = {'h','t','t','p','s',0};
3967 http_session_t *session = request->session;
3968 URL_COMPONENTSW urlComponents;
3969 DWORD url_length = 0;
3970 LPWSTR orig_url;
3971 LPWSTR combined_url;
3973 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3974 urlComponents.lpszScheme = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
3975 urlComponents.dwSchemeLength = 0;
3976 urlComponents.lpszHostName = request->server->name;
3977 urlComponents.dwHostNameLength = 0;
3978 urlComponents.nPort = request->server->port;
3979 urlComponents.lpszUserName = session->userName;
3980 urlComponents.dwUserNameLength = 0;
3981 urlComponents.lpszPassword = NULL;
3982 urlComponents.dwPasswordLength = 0;
3983 urlComponents.lpszUrlPath = request->path;
3984 urlComponents.dwUrlPathLength = 0;
3985 urlComponents.lpszExtraInfo = NULL;
3986 urlComponents.dwExtraInfoLength = 0;
3988 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
3989 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
3990 return NULL;
3992 orig_url = heap_alloc(url_length);
3994 /* convert from bytes to characters */
3995 url_length = url_length / sizeof(WCHAR) - 1;
3996 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
3998 heap_free(orig_url);
3999 return NULL;
4002 url_length = 0;
4003 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
4004 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
4006 heap_free(orig_url);
4007 return NULL;
4009 combined_url = heap_alloc(url_length * sizeof(WCHAR));
4011 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
4013 heap_free(orig_url);
4014 heap_free(combined_url);
4015 return NULL;
4017 heap_free(orig_url);
4018 return combined_url;
4022 /***********************************************************************
4023 * HTTP_HandleRedirect (internal)
4025 static DWORD HTTP_HandleRedirect(http_request_t *request, LPCWSTR lpszUrl)
4027 http_session_t *session = request->session;
4028 WCHAR path[INTERNET_MAX_PATH_LENGTH];
4029 int index;
4031 if(lpszUrl[0]=='/')
4033 /* if it's an absolute path, keep the same session info */
4034 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
4036 else
4038 URL_COMPONENTSW urlComponents;
4039 WCHAR protocol[INTERNET_MAX_SCHEME_LENGTH];
4040 WCHAR hostName[INTERNET_MAX_HOST_NAME_LENGTH];
4041 WCHAR userName[INTERNET_MAX_USER_NAME_LENGTH];
4042 BOOL custom_port = FALSE;
4044 static const WCHAR httpW[] = {'h','t','t','p',0};
4045 static const WCHAR httpsW[] = {'h','t','t','p','s',0};
4047 userName[0] = 0;
4048 hostName[0] = 0;
4049 protocol[0] = 0;
4051 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
4052 urlComponents.lpszScheme = protocol;
4053 urlComponents.dwSchemeLength = INTERNET_MAX_SCHEME_LENGTH;
4054 urlComponents.lpszHostName = hostName;
4055 urlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
4056 urlComponents.lpszUserName = userName;
4057 urlComponents.dwUserNameLength = INTERNET_MAX_USER_NAME_LENGTH;
4058 urlComponents.lpszPassword = NULL;
4059 urlComponents.dwPasswordLength = 0;
4060 urlComponents.lpszUrlPath = path;
4061 urlComponents.dwUrlPathLength = INTERNET_MAX_PATH_LENGTH;
4062 urlComponents.lpszExtraInfo = NULL;
4063 urlComponents.dwExtraInfoLength = 0;
4064 if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
4065 return INTERNET_GetLastError();
4067 if(!strcmpiW(protocol, httpW)) {
4068 if(request->hdr.dwFlags & INTERNET_FLAG_SECURE) {
4069 TRACE("redirect from secure page to non-secure page\n");
4070 /* FIXME: warn about from secure redirect to non-secure page */
4071 request->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
4074 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4075 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
4076 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT)
4077 custom_port = TRUE;
4078 }else if(!strcmpiW(protocol, httpsW)) {
4079 if(!(request->hdr.dwFlags & INTERNET_FLAG_SECURE)) {
4080 TRACE("redirect from non-secure page to secure page\n");
4081 /* FIXME: notify about redirect to secure page */
4082 request->hdr.dwFlags |= INTERNET_FLAG_SECURE;
4085 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4086 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
4087 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
4088 custom_port = TRUE;
4091 heap_free(session->hostName);
4093 if(custom_port) {
4094 int len;
4095 static const WCHAR fmt[] = {'%','s',':','%','u',0};
4096 len = lstrlenW(hostName);
4097 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
4098 session->hostName = heap_alloc(len*sizeof(WCHAR));
4099 sprintfW(session->hostName, fmt, hostName, urlComponents.nPort);
4101 else
4102 session->hostName = heap_strdupW(hostName);
4103 session->hostPort = urlComponents.nPort;
4105 HTTP_ProcessHeader(request, hostW, session->hostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4107 heap_free(session->userName);
4108 session->userName = NULL;
4109 if (userName[0])
4110 session->userName = heap_strdupW(userName);
4112 reset_data_stream(request);
4114 if(strcmpiW(request->server->name, hostName) || request->server->port != urlComponents.nPort) {
4115 server_t *new_server;
4117 new_server = get_server(hostName, urlComponents.nPort, urlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
4118 server_release(request->server);
4119 request->server = new_server;
4122 heap_free(request->path);
4123 request->path=NULL;
4124 if (*path)
4126 DWORD needed = 0;
4127 HRESULT rc;
4129 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
4130 if (rc != E_POINTER)
4131 needed = strlenW(path)+1;
4132 request->path = heap_alloc(needed*sizeof(WCHAR));
4133 rc = UrlEscapeW(path, request->path, &needed,
4134 URL_ESCAPE_SPACES_ONLY);
4135 if (rc != S_OK)
4137 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4138 strcpyW(request->path,path);
4142 /* Remove custom content-type/length headers on redirects. */
4143 index = HTTP_GetCustomHeaderIndex(request, szContent_Type, 0, TRUE);
4144 if (0 <= index)
4145 HTTP_DeleteCustomHeader(request, index);
4146 index = HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE);
4147 if (0 <= index)
4148 HTTP_DeleteCustomHeader(request, index);
4150 return ERROR_SUCCESS;
4153 /***********************************************************************
4154 * HTTP_build_req (internal)
4156 * concatenate all the strings in the request together
4158 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
4160 LPCWSTR *t;
4161 LPWSTR str;
4163 for( t = list; *t ; t++ )
4164 len += strlenW( *t );
4165 len++;
4167 str = heap_alloc(len*sizeof(WCHAR));
4168 *str = 0;
4170 for( t = list; *t ; t++ )
4171 strcatW( str, *t );
4173 return str;
4176 static void HTTP_InsertCookies(http_request_t *request)
4178 DWORD cookie_size, size, cnt = 0;
4179 HTTPHEADERW *host;
4180 WCHAR *cookies;
4182 static const WCHAR cookieW[] = {'C','o','o','k','i','e',':',' ',0};
4184 host = HTTP_GetHeader(request, hostW);
4185 if(!host)
4186 return;
4188 if(get_cookie(host->lpszValue, request->path, NULL, &cookie_size) != ERROR_SUCCESS)
4189 return;
4191 size = sizeof(cookieW) + cookie_size * sizeof(WCHAR) + sizeof(szCrLf);
4192 if(!(cookies = heap_alloc(size)))
4193 return;
4195 cnt += sprintfW(cookies, cookieW);
4196 get_cookie(host->lpszValue, request->path, cookies+cnt, &cookie_size);
4197 strcatW(cookies, szCrLf);
4199 HTTP_HttpAddRequestHeadersW(request, cookies, strlenW(cookies), HTTP_ADDREQ_FLAG_REPLACE);
4201 heap_free(cookies);
4204 static WORD HTTP_ParseWkday(LPCWSTR day)
4206 static const WCHAR days[7][4] = {{ 's','u','n',0 },
4207 { 'm','o','n',0 },
4208 { 't','u','e',0 },
4209 { 'w','e','d',0 },
4210 { 't','h','u',0 },
4211 { 'f','r','i',0 },
4212 { 's','a','t',0 }};
4213 unsigned int i;
4214 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4215 if (!strcmpiW(day, days[i]))
4216 return i;
4218 /* Invalid */
4219 return 7;
4222 static WORD HTTP_ParseMonth(LPCWSTR month)
4224 static const WCHAR jan[] = { 'j','a','n',0 };
4225 static const WCHAR feb[] = { 'f','e','b',0 };
4226 static const WCHAR mar[] = { 'm','a','r',0 };
4227 static const WCHAR apr[] = { 'a','p','r',0 };
4228 static const WCHAR may[] = { 'm','a','y',0 };
4229 static const WCHAR jun[] = { 'j','u','n',0 };
4230 static const WCHAR jul[] = { 'j','u','l',0 };
4231 static const WCHAR aug[] = { 'a','u','g',0 };
4232 static const WCHAR sep[] = { 's','e','p',0 };
4233 static const WCHAR oct[] = { 'o','c','t',0 };
4234 static const WCHAR nov[] = { 'n','o','v',0 };
4235 static const WCHAR dec[] = { 'd','e','c',0 };
4237 if (!strcmpiW(month, jan)) return 1;
4238 if (!strcmpiW(month, feb)) return 2;
4239 if (!strcmpiW(month, mar)) return 3;
4240 if (!strcmpiW(month, apr)) return 4;
4241 if (!strcmpiW(month, may)) return 5;
4242 if (!strcmpiW(month, jun)) return 6;
4243 if (!strcmpiW(month, jul)) return 7;
4244 if (!strcmpiW(month, aug)) return 8;
4245 if (!strcmpiW(month, sep)) return 9;
4246 if (!strcmpiW(month, oct)) return 10;
4247 if (!strcmpiW(month, nov)) return 11;
4248 if (!strcmpiW(month, dec)) return 12;
4249 /* Invalid */
4250 return 0;
4253 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4254 * optionally preceded by whitespace.
4255 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4256 * st, and sets *str to the first character after the time format.
4258 static BOOL HTTP_ParseTime(SYSTEMTIME *st, LPCWSTR *str)
4260 LPCWSTR ptr = *str;
4261 WCHAR *nextPtr;
4262 unsigned long num;
4264 while (isspaceW(*ptr))
4265 ptr++;
4267 num = strtoulW(ptr, &nextPtr, 10);
4268 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4270 ERR("unexpected time format %s\n", debugstr_w(ptr));
4271 return FALSE;
4273 if (num > 23)
4275 ERR("unexpected hour in time format %s\n", debugstr_w(ptr));
4276 return FALSE;
4278 ptr = nextPtr + 1;
4279 st->wHour = (WORD)num;
4280 num = strtoulW(ptr, &nextPtr, 10);
4281 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4283 ERR("unexpected time format %s\n", debugstr_w(ptr));
4284 return FALSE;
4286 if (num > 59)
4288 ERR("unexpected minute in time format %s\n", debugstr_w(ptr));
4289 return FALSE;
4291 ptr = nextPtr + 1;
4292 st->wMinute = (WORD)num;
4293 num = strtoulW(ptr, &nextPtr, 10);
4294 if (!nextPtr || nextPtr <= ptr)
4296 ERR("unexpected time format %s\n", debugstr_w(ptr));
4297 return FALSE;
4299 if (num > 59)
4301 ERR("unexpected second in time format %s\n", debugstr_w(ptr));
4302 return FALSE;
4304 ptr = nextPtr + 1;
4305 *str = ptr;
4306 st->wSecond = (WORD)num;
4307 return TRUE;
4310 static BOOL HTTP_ParseDateAsAsctime(LPCWSTR value, FILETIME *ft)
4312 static const WCHAR gmt[]= { 'G','M','T',0 };
4313 WCHAR day[4], *dayPtr, month[4], *monthPtr, *nextPtr;
4314 LPCWSTR ptr;
4315 SYSTEMTIME st = { 0 };
4316 unsigned long num;
4318 for (ptr = value, dayPtr = day; *ptr && !isspaceW(*ptr) &&
4319 dayPtr - day < sizeof(day) / sizeof(day[0]) - 1; ptr++, dayPtr++)
4320 *dayPtr = *ptr;
4321 *dayPtr = 0;
4322 st.wDayOfWeek = HTTP_ParseWkday(day);
4323 if (st.wDayOfWeek >= 7)
4325 ERR("unexpected weekday %s\n", debugstr_w(day));
4326 return FALSE;
4329 while (isspaceW(*ptr))
4330 ptr++;
4332 for (monthPtr = month; !isspace(*ptr) &&
4333 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4334 monthPtr++, ptr++)
4335 *monthPtr = *ptr;
4336 *monthPtr = 0;
4337 st.wMonth = HTTP_ParseMonth(month);
4338 if (!st.wMonth || st.wMonth > 12)
4340 ERR("unexpected month %s\n", debugstr_w(month));
4341 return FALSE;
4344 while (isspaceW(*ptr))
4345 ptr++;
4347 num = strtoulW(ptr, &nextPtr, 10);
4348 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4350 ERR("unexpected day %s\n", debugstr_w(ptr));
4351 return FALSE;
4353 ptr = nextPtr;
4354 st.wDay = (WORD)num;
4356 while (isspaceW(*ptr))
4357 ptr++;
4359 if (!HTTP_ParseTime(&st, &ptr))
4360 return FALSE;
4362 while (isspaceW(*ptr))
4363 ptr++;
4365 num = strtoulW(ptr, &nextPtr, 10);
4366 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4368 ERR("unexpected year %s\n", debugstr_w(ptr));
4369 return FALSE;
4371 ptr = nextPtr;
4372 st.wYear = (WORD)num;
4374 while (isspaceW(*ptr))
4375 ptr++;
4377 /* asctime() doesn't report a timezone, but some web servers do, so accept
4378 * with or without GMT.
4380 if (*ptr && strcmpW(ptr, gmt))
4382 ERR("unexpected timezone %s\n", debugstr_w(ptr));
4383 return FALSE;
4385 return SystemTimeToFileTime(&st, ft);
4388 static BOOL HTTP_ParseRfc1123Date(LPCWSTR value, FILETIME *ft)
4390 static const WCHAR gmt[]= { 'G','M','T',0 };
4391 WCHAR *nextPtr, day[4], month[4], *monthPtr;
4392 LPCWSTR ptr;
4393 unsigned long num;
4394 SYSTEMTIME st = { 0 };
4396 ptr = strchrW(value, ',');
4397 if (!ptr)
4398 return FALSE;
4399 if (ptr - value != 3)
4401 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4402 return FALSE;
4404 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4405 day[3] = 0;
4406 st.wDayOfWeek = HTTP_ParseWkday(day);
4407 if (st.wDayOfWeek > 6)
4409 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4410 return FALSE;
4412 ptr++;
4414 while (isspaceW(*ptr))
4415 ptr++;
4417 num = strtoulW(ptr, &nextPtr, 10);
4418 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4420 WARN("unexpected day %s\n", debugstr_w(value));
4421 return FALSE;
4423 ptr = nextPtr;
4424 st.wDay = (WORD)num;
4426 while (isspaceW(*ptr))
4427 ptr++;
4429 for (monthPtr = month; !isspace(*ptr) &&
4430 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4431 monthPtr++, ptr++)
4432 *monthPtr = *ptr;
4433 *monthPtr = 0;
4434 st.wMonth = HTTP_ParseMonth(month);
4435 if (!st.wMonth || st.wMonth > 12)
4437 WARN("unexpected month %s\n", debugstr_w(month));
4438 return FALSE;
4441 while (isspaceW(*ptr))
4442 ptr++;
4444 num = strtoulW(ptr, &nextPtr, 10);
4445 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4447 ERR("unexpected year %s\n", debugstr_w(value));
4448 return FALSE;
4450 ptr = nextPtr;
4451 st.wYear = (WORD)num;
4453 if (!HTTP_ParseTime(&st, &ptr))
4454 return FALSE;
4456 while (isspaceW(*ptr))
4457 ptr++;
4459 if (strcmpW(ptr, gmt))
4461 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4462 return FALSE;
4464 return SystemTimeToFileTime(&st, ft);
4467 static WORD HTTP_ParseWeekday(LPCWSTR day)
4469 static const WCHAR days[7][10] = {{ 's','u','n','d','a','y',0 },
4470 { 'm','o','n','d','a','y',0 },
4471 { 't','u','e','s','d','a','y',0 },
4472 { 'w','e','d','n','e','s','d','a','y',0 },
4473 { 't','h','u','r','s','d','a','y',0 },
4474 { 'f','r','i','d','a','y',0 },
4475 { 's','a','t','u','r','d','a','y',0 }};
4476 unsigned int i;
4477 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4478 if (!strcmpiW(day, days[i]))
4479 return i;
4481 /* Invalid */
4482 return 7;
4485 static BOOL HTTP_ParseRfc850Date(LPCWSTR value, FILETIME *ft)
4487 static const WCHAR gmt[]= { 'G','M','T',0 };
4488 WCHAR *nextPtr, day[10], month[4], *monthPtr;
4489 LPCWSTR ptr;
4490 unsigned long num;
4491 SYSTEMTIME st = { 0 };
4493 ptr = strchrW(value, ',');
4494 if (!ptr)
4495 return FALSE;
4496 if (ptr - value == 3)
4498 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4499 day[3] = 0;
4500 st.wDayOfWeek = HTTP_ParseWkday(day);
4501 if (st.wDayOfWeek > 6)
4503 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4504 return FALSE;
4507 else if (ptr - value < sizeof(day) / sizeof(day[0]))
4509 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4510 day[ptr - value + 1] = 0;
4511 st.wDayOfWeek = HTTP_ParseWeekday(day);
4512 if (st.wDayOfWeek > 6)
4514 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4515 return FALSE;
4518 else
4520 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4521 return FALSE;
4523 ptr++;
4525 while (isspaceW(*ptr))
4526 ptr++;
4528 num = strtoulW(ptr, &nextPtr, 10);
4529 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4531 ERR("unexpected day %s\n", debugstr_w(value));
4532 return FALSE;
4534 ptr = nextPtr;
4535 st.wDay = (WORD)num;
4537 if (*ptr != '-')
4539 ERR("unexpected month format %s\n", debugstr_w(ptr));
4540 return FALSE;
4542 ptr++;
4544 for (monthPtr = month; *ptr != '-' &&
4545 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4546 monthPtr++, ptr++)
4547 *monthPtr = *ptr;
4548 *monthPtr = 0;
4549 st.wMonth = HTTP_ParseMonth(month);
4550 if (!st.wMonth || st.wMonth > 12)
4552 ERR("unexpected month %s\n", debugstr_w(month));
4553 return FALSE;
4556 if (*ptr != '-')
4558 ERR("unexpected year format %s\n", debugstr_w(ptr));
4559 return FALSE;
4561 ptr++;
4563 num = strtoulW(ptr, &nextPtr, 10);
4564 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4566 ERR("unexpected year %s\n", debugstr_w(value));
4567 return FALSE;
4569 ptr = nextPtr;
4570 st.wYear = (WORD)num;
4572 if (!HTTP_ParseTime(&st, &ptr))
4573 return FALSE;
4575 while (isspaceW(*ptr))
4576 ptr++;
4578 if (strcmpW(ptr, gmt))
4580 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4581 return FALSE;
4583 return SystemTimeToFileTime(&st, ft);
4586 static BOOL HTTP_ParseDate(LPCWSTR value, FILETIME *ft)
4588 static const WCHAR zero[] = { '0',0 };
4589 BOOL ret;
4591 if (!strcmpW(value, zero))
4593 ft->dwLowDateTime = ft->dwHighDateTime = 0;
4594 ret = TRUE;
4596 else if (strchrW(value, ','))
4598 ret = HTTP_ParseRfc1123Date(value, ft);
4599 if (!ret)
4601 ret = HTTP_ParseRfc850Date(value, ft);
4602 if (!ret)
4603 ERR("unexpected date format %s\n", debugstr_w(value));
4606 else
4608 ret = HTTP_ParseDateAsAsctime(value, ft);
4609 if (!ret)
4610 ERR("unexpected date format %s\n", debugstr_w(value));
4612 return ret;
4615 static void HTTP_ProcessExpires(http_request_t *request)
4617 BOOL expirationFound = FALSE;
4618 int headerIndex;
4620 /* Look for a Cache-Control header with a max-age directive, as it takes
4621 * precedence over the Expires header.
4623 headerIndex = HTTP_GetCustomHeaderIndex(request, szCache_Control, 0, FALSE);
4624 if (headerIndex != -1)
4626 LPHTTPHEADERW ccHeader = &request->custHeaders[headerIndex];
4627 LPWSTR ptr;
4629 for (ptr = ccHeader->lpszValue; ptr && *ptr; )
4631 LPWSTR comma = strchrW(ptr, ','), end, equal;
4633 if (comma)
4634 end = comma;
4635 else
4636 end = ptr + strlenW(ptr);
4637 for (equal = end - 1; equal > ptr && *equal != '='; equal--)
4639 if (*equal == '=')
4641 static const WCHAR max_age[] = {
4642 'm','a','x','-','a','g','e',0 };
4644 if (!strncmpiW(ptr, max_age, equal - ptr - 1))
4646 LPWSTR nextPtr;
4647 unsigned long age;
4649 age = strtoulW(equal + 1, &nextPtr, 10);
4650 if (nextPtr > equal + 1)
4652 LARGE_INTEGER ft;
4654 NtQuerySystemTime( &ft );
4655 /* Age is in seconds, FILETIME resolution is in
4656 * 100 nanosecond intervals.
4658 ft.QuadPart += age * (ULONGLONG)1000000;
4659 request->expires.dwLowDateTime = ft.u.LowPart;
4660 request->expires.dwHighDateTime = ft.u.HighPart;
4661 expirationFound = TRUE;
4665 if (comma)
4667 ptr = comma + 1;
4668 while (isspaceW(*ptr))
4669 ptr++;
4671 else
4672 ptr = NULL;
4675 if (!expirationFound)
4677 headerIndex = HTTP_GetCustomHeaderIndex(request, szExpires, 0, FALSE);
4678 if (headerIndex != -1)
4680 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4681 FILETIME ft;
4683 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4685 expirationFound = TRUE;
4686 request->expires = ft;
4690 if (!expirationFound)
4692 LARGE_INTEGER t;
4694 /* With no known age, default to 10 minutes until expiration. */
4695 NtQuerySystemTime( &t );
4696 t.QuadPart += 10 * 60 * (ULONGLONG)10000000;
4697 request->expires.dwLowDateTime = t.u.LowPart;
4698 request->expires.dwHighDateTime = t.u.HighPart;
4702 static void HTTP_ProcessLastModified(http_request_t *request)
4704 int headerIndex;
4706 headerIndex = HTTP_GetCustomHeaderIndex(request, szLast_Modified, 0, FALSE);
4707 if (headerIndex != -1)
4709 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4710 FILETIME ft;
4712 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4713 request->last_modified = ft;
4717 static void http_process_keep_alive(http_request_t *req)
4719 int index;
4721 if ((index = HTTP_GetCustomHeaderIndex(req, szConnection, 0, FALSE)) != -1)
4722 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4723 else if ((index = HTTP_GetCustomHeaderIndex(req, szProxy_Connection, 0, FALSE)) != -1)
4724 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4725 else
4726 req->netconn->keep_alive = !strcmpiW(req->version, g_szHttp1_1);
4729 static DWORD open_http_connection(http_request_t *request, BOOL *reusing)
4731 const BOOL is_https = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) != 0;
4732 netconn_t *netconn = NULL;
4733 DWORD res;
4735 reset_data_stream(request);
4737 if (request->netconn)
4739 if (is_valid_netconn(request->netconn) && NETCON_is_alive(request->netconn))
4741 *reusing = TRUE;
4742 return ERROR_SUCCESS;
4744 else
4746 free_netconn(request->netconn);
4747 request->netconn = NULL;
4751 res = HTTP_ResolveName(request);
4752 if(res != ERROR_SUCCESS)
4753 return res;
4755 EnterCriticalSection(&connection_pool_cs);
4757 while(!list_empty(&request->server->conn_pool)) {
4758 netconn = LIST_ENTRY(list_head(&request->server->conn_pool), netconn_t, pool_entry);
4759 list_remove(&netconn->pool_entry);
4761 if(is_valid_netconn(netconn) && NETCON_is_alive(netconn))
4762 break;
4764 TRACE("connection %p closed during idle\n", netconn);
4765 free_netconn(netconn);
4766 netconn = NULL;
4769 LeaveCriticalSection(&connection_pool_cs);
4771 if(netconn) {
4772 TRACE("<-- reusing %p netconn\n", netconn);
4773 request->netconn = netconn;
4774 *reusing = TRUE;
4775 return ERROR_SUCCESS;
4778 TRACE("connecting to %s, proxy %s\n", debugstr_w(request->server->name),
4779 request->proxy ? debugstr_w(request->proxy->name) : "(null)");
4781 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4782 INTERNET_STATUS_CONNECTING_TO_SERVER,
4783 request->server->addr_str,
4784 strlen(request->server->addr_str)+1);
4786 res = create_netconn(is_https, request->proxy ? request->proxy : request->server, request->security_flags,
4787 (request->hdr.ErrorMask & INTERNET_ERROR_MASK_COMBINED_SEC_CERT) != 0,
4788 request->connect_timeout, &netconn);
4789 if(res != ERROR_SUCCESS) {
4790 ERR("create_netconn failed: %u\n", res);
4791 return res;
4794 request->netconn = netconn;
4796 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4797 INTERNET_STATUS_CONNECTED_TO_SERVER,
4798 request->server->addr_str, strlen(request->server->addr_str)+1);
4800 *reusing = FALSE;
4801 TRACE("Created connection to %s: %p\n", debugstr_w(request->server->name), netconn);
4802 return ERROR_SUCCESS;
4805 static char *build_ascii_request( const WCHAR *str, void *data, DWORD data_len, DWORD *out_len )
4807 int len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
4808 char *ret;
4810 if (!(ret = heap_alloc( len + data_len ))) return NULL;
4811 WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
4812 if (data_len) memcpy( ret + len - 1, data, data_len );
4813 *out_len = len + data_len - 1;
4814 ret[*out_len] = 0;
4815 return ret;
4818 /***********************************************************************
4819 * HTTP_HttpSendRequestW (internal)
4821 * Sends the specified request to the HTTP server
4823 * RETURNS
4824 * ERROR_SUCCESS on success
4825 * win32 error code on failure
4828 static DWORD HTTP_HttpSendRequestW(http_request_t *request, LPCWSTR lpszHeaders,
4829 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
4830 DWORD dwContentLength, BOOL bEndRequest)
4832 static const WCHAR szContentLength[] =
4833 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
4834 BOOL redirected = FALSE, secure_proxy_connect = FALSE, loop_next;
4835 LPWSTR requestString = NULL;
4836 INT responseLen, cnt;
4837 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
4838 DWORD res;
4840 TRACE("--> %p\n", request);
4842 assert(request->hdr.htype == WH_HHTTPREQ);
4844 /* if the verb is NULL default to GET */
4845 if (!request->verb)
4846 request->verb = heap_strdupW(szGET);
4848 if (dwContentLength || strcmpW(request->verb, szGET))
4850 sprintfW(contentLengthStr, szContentLength, dwContentLength);
4851 HTTP_HttpAddRequestHeadersW(request, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4852 request->bytesToWrite = dwContentLength;
4854 if (request->session->appInfo->agent)
4856 WCHAR *agent_header;
4857 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4858 int len;
4860 len = strlenW(request->session->appInfo->agent) + strlenW(user_agent);
4861 agent_header = heap_alloc(len * sizeof(WCHAR));
4862 sprintfW(agent_header, user_agent, request->session->appInfo->agent);
4864 HTTP_HttpAddRequestHeadersW(request, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4865 heap_free(agent_header);
4867 if (request->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
4869 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4870 HTTP_HttpAddRequestHeadersW(request, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4872 if ((request->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && strcmpW(request->verb, szGET))
4874 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4875 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4876 HTTP_HttpAddRequestHeadersW(request, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4879 /* add the headers the caller supplied */
4880 if( lpszHeaders && dwHeaderLength )
4881 HTTP_HttpAddRequestHeadersW(request, lpszHeaders, dwHeaderLength, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
4885 DWORD len, data_len = dwOptionalLength;
4886 BOOL reusing_connection;
4887 char *ascii_req;
4889 loop_next = FALSE;
4891 if(redirected) {
4892 request->contentLength = ~0u;
4893 request->bytesToWrite = 0;
4896 if (TRACE_ON(wininet))
4898 LPHTTPHEADERW Host = HTTP_GetHeader(request, hostW);
4899 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(request->path));
4902 HTTP_FixURL(request);
4903 if (request->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
4905 HTTP_ProcessHeader(request, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
4907 HTTP_InsertAuthorization(request, request->authInfo, szAuthorization);
4908 HTTP_InsertAuthorization(request, request->proxyAuthInfo, szProxy_Authorization);
4910 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
4911 HTTP_InsertCookies(request);
4913 res = open_http_connection(request, &reusing_connection);
4914 if (res != ERROR_SUCCESS)
4915 break;
4917 if (!reusing_connection && (request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4919 if (request->proxy) secure_proxy_connect = TRUE;
4920 else
4922 res = NETCON_secure_connect(request->netconn, request->server);
4923 if (res != ERROR_SUCCESS)
4925 WARN("failed to upgrade to secure connection\n");
4926 http_release_netconn(request, FALSE);
4927 break;
4931 if (secure_proxy_connect)
4933 static const WCHAR connectW[] = {'C','O','N','N','E','C','T',0};
4934 const WCHAR *target = request->server->host_port;
4935 requestString = build_request_header(request, connectW, target, g_szHttp1_1, TRUE);
4937 else if (request->proxy && !(request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4939 WCHAR *url = build_proxy_path_url(request);
4940 requestString = build_request_header(request, request->verb, url, request->version, TRUE);
4941 heap_free(url);
4943 else
4944 requestString = build_request_header(request, request->verb, request->path, request->version, TRUE);
4946 TRACE("Request header -> %s\n", debugstr_w(requestString) );
4948 /* send the request as ASCII, tack on the optional data */
4949 if (!lpOptional || redirected || secure_proxy_connect)
4950 data_len = 0;
4952 ascii_req = build_ascii_request( requestString, lpOptional, data_len, &len );
4953 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
4955 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4956 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
4958 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
4959 res = NETCON_send(request->netconn, ascii_req, len, 0, &cnt);
4960 heap_free( ascii_req );
4961 if(res != ERROR_SUCCESS) {
4962 TRACE("send failed: %u\n", res);
4963 if(!reusing_connection)
4964 break;
4965 http_release_netconn(request, FALSE);
4966 loop_next = TRUE;
4967 continue;
4970 request->bytesWritten = data_len;
4972 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4973 INTERNET_STATUS_REQUEST_SENT,
4974 &len, sizeof(DWORD));
4976 if (bEndRequest)
4978 DWORD dwBufferSize;
4980 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4981 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
4983 if (HTTP_GetResponseHeaders(request, &responseLen))
4985 http_release_netconn(request, FALSE);
4986 res = ERROR_INTERNET_CONNECTION_ABORTED;
4987 goto lend;
4989 /* FIXME: We should know that connection is closed before sending
4990 * headers. Otherwise wrong callbacks are executed */
4991 if(!responseLen && reusing_connection) {
4992 TRACE("Connection closed by server, reconnecting\n");
4993 http_release_netconn(request, FALSE);
4994 loop_next = TRUE;
4995 continue;
4998 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4999 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
5000 sizeof(DWORD));
5002 http_process_keep_alive(request);
5003 HTTP_ProcessCookies(request);
5004 HTTP_ProcessExpires(request);
5005 HTTP_ProcessLastModified(request);
5007 res = set_content_length(request);
5008 if(res != ERROR_SUCCESS)
5009 goto lend;
5010 if(!request->contentLength)
5011 http_release_netconn(request, TRUE);
5013 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
5015 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5016 dwBufferSize=sizeof(szNewLocation);
5017 switch(request->status_code) {
5018 case HTTP_STATUS_REDIRECT:
5019 case HTTP_STATUS_MOVED:
5020 case HTTP_STATUS_REDIRECT_KEEP_VERB:
5021 case HTTP_STATUS_REDIRECT_METHOD:
5022 if(HTTP_HttpQueryInfoW(request,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL) != ERROR_SUCCESS)
5023 break;
5025 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5026 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5028 heap_free(request->verb);
5029 request->verb = heap_strdupW(szGET);
5031 http_release_netconn(request, drain_content(request, FALSE));
5032 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5034 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5035 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5036 res = HTTP_HandleRedirect(request, new_url);
5037 if (res == ERROR_SUCCESS)
5039 heap_free(requestString);
5040 loop_next = TRUE;
5042 heap_free( new_url );
5044 redirected = TRUE;
5047 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
5049 WCHAR szAuthValue[2048];
5050 dwBufferSize=2048;
5051 if (request->status_code == HTTP_STATUS_DENIED)
5053 LPHTTPHEADERW Host = HTTP_GetHeader(request, hostW);
5054 DWORD dwIndex = 0;
5055 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5057 if (HTTP_DoAuthorization(request, szAuthValue,
5058 &request->authInfo,
5059 request->session->userName,
5060 request->session->password,
5061 Host->lpszValue))
5063 heap_free(requestString);
5064 if(!drain_content(request, TRUE)) {
5065 FIXME("Could not drain content\n");
5066 http_release_netconn(request, FALSE);
5068 loop_next = TRUE;
5069 break;
5073 if(!loop_next) {
5074 TRACE("Cleaning wrong authorization data\n");
5075 destroy_authinfo(request->authInfo);
5076 request->authInfo = NULL;
5079 if (request->status_code == HTTP_STATUS_PROXY_AUTH_REQ)
5081 DWORD dwIndex = 0;
5082 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5084 if (HTTP_DoAuthorization(request, szAuthValue,
5085 &request->proxyAuthInfo,
5086 request->session->appInfo->proxyUsername,
5087 request->session->appInfo->proxyPassword,
5088 NULL))
5090 heap_free(requestString);
5091 if(!drain_content(request, TRUE)) {
5092 FIXME("Could not drain content\n");
5093 http_release_netconn(request, FALSE);
5095 loop_next = TRUE;
5096 break;
5100 if(!loop_next) {
5101 TRACE("Cleaning wrong proxy authorization data\n");
5102 destroy_authinfo(request->proxyAuthInfo);
5103 request->proxyAuthInfo = NULL;
5107 if (secure_proxy_connect && request->status_code == HTTP_STATUS_OK)
5109 int index;
5111 res = NETCON_secure_connect(request->netconn, request->server);
5112 if (res != ERROR_SUCCESS)
5114 WARN("failed to upgrade to secure proxy connection\n");
5115 http_release_netconn( request, FALSE );
5116 break;
5118 index = HTTP_GetCustomHeaderIndex(request, szProxy_Authorization, 0, TRUE);
5119 if (index != -1) HTTP_DeleteCustomHeader(request, index);
5120 destroy_authinfo(request->proxyAuthInfo);
5121 request->proxyAuthInfo = NULL;
5123 secure_proxy_connect = FALSE;
5124 loop_next = TRUE;
5127 else
5128 res = ERROR_SUCCESS;
5130 while (loop_next);
5132 lend:
5133 heap_free(requestString);
5135 /* TODO: send notification for P3P header */
5137 if(res == ERROR_SUCCESS)
5138 create_cache_entry(request);
5140 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5142 if (res == ERROR_SUCCESS) {
5143 if(bEndRequest && request->contentLength && request->bytesWritten == request->bytesToWrite)
5144 HTTP_ReceiveRequestData(request, TRUE, NULL);
5145 else
5146 send_request_complete(request,
5147 request->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)request->hdr.hInternet : 1, 0);
5148 }else {
5149 send_request_complete(request, 0, res);
5153 TRACE("<--\n");
5154 return res;
5157 typedef struct {
5158 task_header_t hdr;
5159 WCHAR *headers;
5160 DWORD headers_len;
5161 void *optional;
5162 DWORD optional_len;
5163 DWORD content_len;
5164 BOOL end_request;
5165 } send_request_task_t;
5167 /***********************************************************************
5169 * Helper functions for the HttpSendRequest(Ex) functions
5172 static void AsyncHttpSendRequestProc(task_header_t *hdr)
5174 send_request_task_t *task = (send_request_task_t*)hdr;
5175 http_request_t *request = (http_request_t*)task->hdr.hdr;
5177 TRACE("%p\n", request);
5179 HTTP_HttpSendRequestW(request, task->headers, task->headers_len, task->optional,
5180 task->optional_len, task->content_len, task->end_request);
5182 heap_free(task->headers);
5186 static DWORD HTTP_HttpEndRequestW(http_request_t *request, DWORD dwFlags, DWORD_PTR dwContext)
5188 DWORD dwBufferSize;
5189 INT responseLen;
5190 DWORD res = ERROR_SUCCESS;
5192 if(!is_valid_netconn(request->netconn)) {
5193 WARN("Not connected\n");
5194 send_request_complete(request, 0, ERROR_INTERNET_OPERATION_CANCELLED);
5195 return ERROR_INTERNET_OPERATION_CANCELLED;
5198 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5199 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5201 if (HTTP_GetResponseHeaders(request, &responseLen) || !responseLen)
5202 res = ERROR_HTTP_HEADER_NOT_FOUND;
5204 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5205 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
5207 /* process cookies here. Is this right? */
5208 http_process_keep_alive(request);
5209 HTTP_ProcessCookies(request);
5210 HTTP_ProcessExpires(request);
5211 HTTP_ProcessLastModified(request);
5213 if ((res = set_content_length(request)) == ERROR_SUCCESS) {
5214 if(!request->contentLength)
5215 http_release_netconn(request, TRUE);
5218 if (res == ERROR_SUCCESS && !(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
5220 switch(request->status_code) {
5221 case HTTP_STATUS_REDIRECT:
5222 case HTTP_STATUS_MOVED:
5223 case HTTP_STATUS_REDIRECT_METHOD:
5224 case HTTP_STATUS_REDIRECT_KEEP_VERB: {
5225 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5226 dwBufferSize=sizeof(szNewLocation);
5227 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, szNewLocation, &dwBufferSize, NULL) != ERROR_SUCCESS)
5228 break;
5230 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5231 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5233 heap_free(request->verb);
5234 request->verb = heap_strdupW(szGET);
5236 http_release_netconn(request, drain_content(request, FALSE));
5237 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5239 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5240 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5241 res = HTTP_HandleRedirect(request, new_url);
5242 if (res == ERROR_SUCCESS)
5243 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, TRUE);
5244 heap_free( new_url );
5250 if(res == ERROR_SUCCESS)
5251 create_cache_entry(request);
5253 if (res == ERROR_SUCCESS && request->contentLength)
5254 HTTP_ReceiveRequestData(request, TRUE, NULL);
5255 else
5256 send_request_complete(request, res == ERROR_SUCCESS, res);
5258 return res;
5261 /***********************************************************************
5262 * HttpEndRequestA (WININET.@)
5264 * Ends an HTTP request that was started by HttpSendRequestEx
5266 * RETURNS
5267 * TRUE if successful
5268 * FALSE on failure
5271 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
5272 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5274 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5276 if (lpBuffersOut)
5278 SetLastError(ERROR_INVALID_PARAMETER);
5279 return FALSE;
5282 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
5285 typedef struct {
5286 task_header_t hdr;
5287 DWORD flags;
5288 DWORD context;
5289 } end_request_task_t;
5291 static void AsyncHttpEndRequestProc(task_header_t *hdr)
5293 end_request_task_t *task = (end_request_task_t*)hdr;
5294 http_request_t *req = (http_request_t*)task->hdr.hdr;
5296 TRACE("%p\n", req);
5298 HTTP_HttpEndRequestW(req, task->flags, task->context);
5301 /***********************************************************************
5302 * HttpEndRequestW (WININET.@)
5304 * Ends an HTTP request that was started by HttpSendRequestEx
5306 * RETURNS
5307 * TRUE if successful
5308 * FALSE on failure
5311 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
5312 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5314 http_request_t *request;
5315 DWORD res;
5317 TRACE("%p %p %x %lx -->\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5319 if (lpBuffersOut)
5321 SetLastError(ERROR_INVALID_PARAMETER);
5322 return FALSE;
5325 request = (http_request_t*) get_handle_object( hRequest );
5327 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5329 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
5330 if (request)
5331 WININET_Release( &request->hdr );
5332 return FALSE;
5334 request->hdr.dwFlags |= dwFlags;
5336 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5338 end_request_task_t *task;
5340 task = alloc_async_task(&request->hdr, AsyncHttpEndRequestProc, sizeof(*task));
5341 task->flags = dwFlags;
5342 task->context = dwContext;
5344 INTERNET_AsyncCall(&task->hdr);
5345 res = ERROR_IO_PENDING;
5347 else
5348 res = HTTP_HttpEndRequestW(request, dwFlags, dwContext);
5350 WININET_Release( &request->hdr );
5351 TRACE("%u <--\n", res);
5352 if(res != ERROR_SUCCESS)
5353 SetLastError(res);
5354 return res == ERROR_SUCCESS;
5357 /***********************************************************************
5358 * HttpSendRequestExA (WININET.@)
5360 * Sends the specified request to the HTTP server and allows chunked
5361 * transfers.
5363 * RETURNS
5364 * Success: TRUE
5365 * Failure: FALSE, call GetLastError() for more information.
5367 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
5368 LPINTERNET_BUFFERSA lpBuffersIn,
5369 LPINTERNET_BUFFERSA lpBuffersOut,
5370 DWORD dwFlags, DWORD_PTR dwContext)
5372 INTERNET_BUFFERSW BuffersInW;
5373 BOOL rc = FALSE;
5374 DWORD headerlen;
5375 LPWSTR header = NULL;
5377 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5378 lpBuffersOut, dwFlags, dwContext);
5380 if (lpBuffersIn)
5382 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
5383 if (lpBuffersIn->lpcszHeader)
5385 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
5386 lpBuffersIn->dwHeadersLength,0,0);
5387 header = heap_alloc(headerlen*sizeof(WCHAR));
5388 if (!(BuffersInW.lpcszHeader = header))
5390 SetLastError(ERROR_OUTOFMEMORY);
5391 return FALSE;
5393 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
5394 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5395 header, headerlen);
5397 else
5398 BuffersInW.lpcszHeader = NULL;
5399 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
5400 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
5401 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
5402 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
5403 BuffersInW.Next = NULL;
5406 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
5408 heap_free(header);
5409 return rc;
5412 /***********************************************************************
5413 * HttpSendRequestExW (WININET.@)
5415 * Sends the specified request to the HTTP server and allows chunked
5416 * transfers
5418 * RETURNS
5419 * Success: TRUE
5420 * Failure: FALSE, call GetLastError() for more information.
5422 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
5423 LPINTERNET_BUFFERSW lpBuffersIn,
5424 LPINTERNET_BUFFERSW lpBuffersOut,
5425 DWORD dwFlags, DWORD_PTR dwContext)
5427 http_request_t *request;
5428 http_session_t *session;
5429 appinfo_t *hIC;
5430 DWORD res;
5432 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5433 lpBuffersOut, dwFlags, dwContext);
5435 request = (http_request_t*) get_handle_object( hRequest );
5437 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5439 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5440 goto lend;
5443 session = request->session;
5444 assert(session->hdr.htype == WH_HHTTPSESSION);
5445 hIC = session->appInfo;
5446 assert(hIC->hdr.htype == WH_HINIT);
5448 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5450 send_request_task_t *task;
5452 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5453 if (lpBuffersIn)
5455 DWORD size = 0;
5457 if (lpBuffersIn->lpcszHeader)
5459 if (lpBuffersIn->dwHeadersLength == ~0u)
5460 size = (strlenW( lpBuffersIn->lpcszHeader ) + 1) * sizeof(WCHAR);
5461 else
5462 size = lpBuffersIn->dwHeadersLength * sizeof(WCHAR);
5464 task->headers = heap_alloc(size);
5465 memcpy(task->headers, lpBuffersIn->lpcszHeader, size);
5467 else task->headers = NULL;
5469 task->headers_len = size / sizeof(WCHAR);
5470 task->optional = lpBuffersIn->lpvBuffer;
5471 task->optional_len = lpBuffersIn->dwBufferLength;
5472 task->content_len = lpBuffersIn->dwBufferTotal;
5474 else
5476 task->headers = NULL;
5477 task->headers_len = 0;
5478 task->optional = NULL;
5479 task->optional_len = 0;
5480 task->content_len = 0;
5483 task->end_request = FALSE;
5485 INTERNET_AsyncCall(&task->hdr);
5486 res = ERROR_IO_PENDING;
5488 else
5490 if (lpBuffersIn)
5491 res = HTTP_HttpSendRequestW(request, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5492 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
5493 lpBuffersIn->dwBufferTotal, FALSE);
5494 else
5495 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, FALSE);
5498 lend:
5499 if ( request )
5500 WININET_Release( &request->hdr );
5502 TRACE("<---\n");
5503 SetLastError(res);
5504 return res == ERROR_SUCCESS;
5507 /***********************************************************************
5508 * HttpSendRequestW (WININET.@)
5510 * Sends the specified request to the HTTP server
5512 * RETURNS
5513 * TRUE on success
5514 * FALSE on failure
5517 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
5518 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5520 http_request_t *request;
5521 http_session_t *session = NULL;
5522 appinfo_t *hIC = NULL;
5523 DWORD res = ERROR_SUCCESS;
5525 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
5526 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
5528 request = (http_request_t*) get_handle_object( hHttpRequest );
5529 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5531 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5532 goto lend;
5535 session = request->session;
5536 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
5538 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5539 goto lend;
5542 hIC = session->appInfo;
5543 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
5545 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5546 goto lend;
5549 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5551 send_request_task_t *task;
5553 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5554 if (lpszHeaders)
5556 DWORD size;
5558 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
5559 else size = dwHeaderLength * sizeof(WCHAR);
5561 task->headers = heap_alloc(size);
5562 memcpy(task->headers, lpszHeaders, size);
5564 else
5565 task->headers = NULL;
5566 task->headers_len = dwHeaderLength;
5567 task->optional = lpOptional;
5568 task->optional_len = dwOptionalLength;
5569 task->content_len = dwOptionalLength;
5570 task->end_request = TRUE;
5572 INTERNET_AsyncCall(&task->hdr);
5573 res = ERROR_IO_PENDING;
5575 else
5577 res = HTTP_HttpSendRequestW(request, lpszHeaders,
5578 dwHeaderLength, lpOptional, dwOptionalLength,
5579 dwOptionalLength, TRUE);
5581 lend:
5582 if( request )
5583 WININET_Release( &request->hdr );
5585 SetLastError(res);
5586 return res == ERROR_SUCCESS;
5589 /***********************************************************************
5590 * HttpSendRequestA (WININET.@)
5592 * Sends the specified request to the HTTP server
5594 * RETURNS
5595 * TRUE on success
5596 * FALSE on failure
5599 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
5600 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5602 BOOL result;
5603 LPWSTR szHeaders=NULL;
5604 DWORD nLen=dwHeaderLength;
5605 if(lpszHeaders!=NULL)
5607 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
5608 szHeaders = heap_alloc(nLen*sizeof(WCHAR));
5609 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
5611 result = HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
5612 heap_free(szHeaders);
5613 return result;
5616 /***********************************************************************
5617 * HTTPSESSION_Destroy (internal)
5619 * Deallocate session handle
5622 static void HTTPSESSION_Destroy(object_header_t *hdr)
5624 http_session_t *session = (http_session_t*) hdr;
5626 TRACE("%p\n", session);
5628 WININET_Release(&session->appInfo->hdr);
5630 heap_free(session->hostName);
5631 heap_free(session->password);
5632 heap_free(session->userName);
5635 static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
5637 http_session_t *ses = (http_session_t *)hdr;
5639 switch(option) {
5640 case INTERNET_OPTION_HANDLE_TYPE:
5641 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5643 if (*size < sizeof(ULONG))
5644 return ERROR_INSUFFICIENT_BUFFER;
5646 *size = sizeof(DWORD);
5647 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
5648 return ERROR_SUCCESS;
5649 case INTERNET_OPTION_CONNECT_TIMEOUT:
5650 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5652 if (*size < sizeof(DWORD))
5653 return ERROR_INSUFFICIENT_BUFFER;
5655 *size = sizeof(DWORD);
5656 *(DWORD *)buffer = ses->connect_timeout;
5657 return ERROR_SUCCESS;
5659 case INTERNET_OPTION_SEND_TIMEOUT:
5660 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5662 if (*size < sizeof(DWORD))
5663 return ERROR_INSUFFICIENT_BUFFER;
5665 *size = sizeof(DWORD);
5666 *(DWORD *)buffer = ses->send_timeout;
5667 return ERROR_SUCCESS;
5669 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5670 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5672 if (*size < sizeof(DWORD))
5673 return ERROR_INSUFFICIENT_BUFFER;
5675 *size = sizeof(DWORD);
5676 *(DWORD *)buffer = ses->receive_timeout;
5677 return ERROR_SUCCESS;
5680 return INET_QueryOption(hdr, option, buffer, size, unicode);
5683 static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
5685 http_session_t *ses = (http_session_t*)hdr;
5687 switch(option) {
5688 case INTERNET_OPTION_USERNAME:
5690 heap_free(ses->userName);
5691 if (!(ses->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5692 return ERROR_SUCCESS;
5694 case INTERNET_OPTION_PASSWORD:
5696 heap_free(ses->password);
5697 if (!(ses->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5698 return ERROR_SUCCESS;
5700 case INTERNET_OPTION_PROXY_USERNAME:
5702 heap_free(ses->appInfo->proxyUsername);
5703 if (!(ses->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5704 return ERROR_SUCCESS;
5706 case INTERNET_OPTION_PROXY_PASSWORD:
5708 heap_free(ses->appInfo->proxyPassword);
5709 if (!(ses->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5710 return ERROR_SUCCESS;
5712 case INTERNET_OPTION_CONNECT_TIMEOUT:
5714 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5715 ses->connect_timeout = *(DWORD *)buffer;
5716 return ERROR_SUCCESS;
5718 case INTERNET_OPTION_SEND_TIMEOUT:
5720 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5721 ses->send_timeout = *(DWORD *)buffer;
5722 return ERROR_SUCCESS;
5724 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5726 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5727 ses->receive_timeout = *(DWORD *)buffer;
5728 return ERROR_SUCCESS;
5730 default: break;
5733 return INET_SetOption(hdr, option, buffer, size);
5736 static const object_vtbl_t HTTPSESSIONVtbl = {
5737 HTTPSESSION_Destroy,
5738 NULL,
5739 HTTPSESSION_QueryOption,
5740 HTTPSESSION_SetOption,
5741 NULL,
5742 NULL,
5743 NULL,
5744 NULL,
5745 NULL
5749 /***********************************************************************
5750 * HTTP_Connect (internal)
5752 * Create http session handle
5754 * RETURNS
5755 * HINTERNET a session handle on success
5756 * NULL on failure
5759 DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
5760 INTERNET_PORT serverPort, LPCWSTR lpszUserName,
5761 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
5762 DWORD dwInternalFlags, HINTERNET *ret)
5764 http_session_t *session = NULL;
5766 TRACE("-->\n");
5768 if (!lpszServerName || !lpszServerName[0])
5769 return ERROR_INVALID_PARAMETER;
5771 assert( hIC->hdr.htype == WH_HINIT );
5773 session = alloc_object(&hIC->hdr, &HTTPSESSIONVtbl, sizeof(http_session_t));
5774 if (!session)
5775 return ERROR_OUTOFMEMORY;
5778 * According to my tests. The name is not resolved until a request is sent
5781 session->hdr.htype = WH_HHTTPSESSION;
5782 session->hdr.dwFlags = dwFlags;
5783 session->hdr.dwContext = dwContext;
5784 session->hdr.dwInternalFlags |= dwInternalFlags;
5786 WININET_AddRef( &hIC->hdr );
5787 session->appInfo = hIC;
5788 list_add_head( &hIC->hdr.children, &session->hdr.entry );
5790 session->hostName = heap_strdupW(lpszServerName);
5791 if (lpszUserName && lpszUserName[0])
5792 session->userName = heap_strdupW(lpszUserName);
5793 if (lpszPassword && lpszPassword[0])
5794 session->password = heap_strdupW(lpszPassword);
5795 session->hostPort = serverPort;
5796 session->connect_timeout = hIC->connect_timeout;
5797 session->send_timeout = INFINITE;
5798 session->receive_timeout = INFINITE;
5800 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5801 if (!(session->hdr.dwInternalFlags & INET_OPENURL))
5803 INTERNET_SendCallback(&hIC->hdr, dwContext,
5804 INTERNET_STATUS_HANDLE_CREATED, &session->hdr.hInternet,
5805 sizeof(HINTERNET));
5809 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5810 * windows
5813 TRACE("%p --> %p\n", hIC, session);
5815 *ret = session->hdr.hInternet;
5816 return ERROR_SUCCESS;
5819 /***********************************************************************
5820 * HTTP_clear_response_headers (internal)
5822 * clear out any old response headers
5824 static void HTTP_clear_response_headers( http_request_t *request )
5826 DWORD i;
5828 for( i=0; i<request->nCustHeaders; i++)
5830 if( !request->custHeaders[i].lpszField )
5831 continue;
5832 if( !request->custHeaders[i].lpszValue )
5833 continue;
5834 if ( request->custHeaders[i].wFlags & HDR_ISREQUEST )
5835 continue;
5836 HTTP_DeleteCustomHeader( request, i );
5837 i--;
5841 /***********************************************************************
5842 * HTTP_GetResponseHeaders (internal)
5844 * Read server response
5846 * RETURNS
5848 * TRUE on success
5849 * FALSE on error
5851 static DWORD HTTP_GetResponseHeaders(http_request_t *request, INT *len)
5853 INT cbreaks = 0;
5854 WCHAR buffer[MAX_REPLY_LEN];
5855 DWORD buflen = MAX_REPLY_LEN;
5856 INT rc = 0;
5857 char bufferA[MAX_REPLY_LEN];
5858 LPWSTR status_code = NULL, status_text = NULL;
5859 DWORD res = ERROR_HTTP_INVALID_SERVER_RESPONSE;
5860 BOOL codeHundred = FALSE;
5862 TRACE("-->\n");
5864 if(!is_valid_netconn(request->netconn))
5865 goto lend;
5867 /* clear old response headers (eg. from a redirect response) */
5868 HTTP_clear_response_headers( request );
5870 NETCON_set_timeout( request->netconn, FALSE, request->receive_timeout );
5871 do {
5873 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5875 buflen = MAX_REPLY_LEN;
5876 if ((res = read_line(request, bufferA, &buflen)))
5877 goto lend;
5879 if (!buflen) goto lend;
5881 rc += buflen;
5882 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5883 /* check is this a status code line? */
5884 if (!strncmpW(buffer, g_szHttp1_0, 4))
5886 /* split the version from the status code */
5887 status_code = strchrW( buffer, ' ' );
5888 if( !status_code )
5889 goto lend;
5890 *status_code++=0;
5892 /* split the status code from the status text */
5893 status_text = strchrW( status_code, ' ' );
5894 if( status_text )
5895 *status_text++=0;
5897 request->status_code = atoiW(status_code);
5899 TRACE("version [%s] status code [%s] status text [%s]\n",
5900 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
5902 codeHundred = request->status_code == HTTP_STATUS_CONTINUE;
5904 else if (!codeHundred)
5906 WARN("No status line at head of response (%s)\n", debugstr_w(buffer));
5908 heap_free(request->version);
5909 heap_free(request->statusText);
5911 request->status_code = HTTP_STATUS_OK;
5912 request->version = heap_strdupW(g_szHttp1_0);
5913 request->statusText = heap_strdupW(szOK);
5915 goto lend;
5917 } while (codeHundred);
5919 /* Add status code */
5920 HTTP_ProcessHeader(request, szStatus, status_code,
5921 HTTP_ADDHDR_FLAG_REPLACE);
5923 heap_free(request->version);
5924 heap_free(request->statusText);
5926 request->version = heap_strdupW(buffer);
5927 request->statusText = heap_strdupW(status_text ? status_text : emptyW);
5929 /* Restore the spaces */
5930 *(status_code-1) = ' ';
5931 if (status_text)
5932 *(status_text-1) = ' ';
5934 /* Parse each response line */
5937 buflen = MAX_REPLY_LEN;
5938 if (!read_line(request, bufferA, &buflen) && buflen)
5940 LPWSTR * pFieldAndValue;
5942 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
5944 if (!bufferA[0]) break;
5945 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5947 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
5948 if (pFieldAndValue)
5950 HTTP_ProcessHeader(request, pFieldAndValue[0], pFieldAndValue[1],
5951 HTTP_ADDREQ_FLAG_ADD );
5952 HTTP_FreeTokens(pFieldAndValue);
5955 else
5957 cbreaks++;
5958 if (cbreaks >= 2)
5959 break;
5961 }while(1);
5963 res = ERROR_SUCCESS;
5965 lend:
5967 *len = rc;
5968 TRACE("<--\n");
5969 return res;
5972 /***********************************************************************
5973 * HTTP_InterpretHttpHeader (internal)
5975 * Parse server response
5977 * RETURNS
5979 * Pointer to array of field, value, NULL on success.
5980 * NULL on error.
5982 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
5984 LPWSTR * pTokenPair;
5985 LPWSTR pszColon;
5986 INT len;
5988 pTokenPair = heap_alloc_zero(sizeof(*pTokenPair)*3);
5990 pszColon = strchrW(buffer, ':');
5991 /* must have two tokens */
5992 if (!pszColon)
5994 HTTP_FreeTokens(pTokenPair);
5995 if (buffer[0])
5996 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
5997 return NULL;
6000 pTokenPair[0] = heap_alloc((pszColon - buffer + 1) * sizeof(WCHAR));
6001 if (!pTokenPair[0])
6003 HTTP_FreeTokens(pTokenPair);
6004 return NULL;
6006 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
6007 pTokenPair[0][pszColon - buffer] = '\0';
6009 /* skip colon */
6010 pszColon++;
6011 len = strlenW(pszColon);
6012 pTokenPair[1] = heap_alloc((len + 1) * sizeof(WCHAR));
6013 if (!pTokenPair[1])
6015 HTTP_FreeTokens(pTokenPair);
6016 return NULL;
6018 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
6020 strip_spaces(pTokenPair[0]);
6021 strip_spaces(pTokenPair[1]);
6023 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
6024 return pTokenPair;
6027 /***********************************************************************
6028 * HTTP_ProcessHeader (internal)
6030 * Stuff header into header tables according to <dwModifier>
6034 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6036 static DWORD HTTP_ProcessHeader(http_request_t *request, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
6038 LPHTTPHEADERW lphttpHdr = NULL;
6039 INT index = -1;
6040 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
6041 DWORD res = ERROR_HTTP_INVALID_HEADER;
6043 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
6045 /* REPLACE wins out over ADD */
6046 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6047 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
6049 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
6050 index = -1;
6051 else
6052 index = HTTP_GetCustomHeaderIndex(request, field, 0, request_only);
6054 if (index >= 0)
6056 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
6057 return ERROR_HTTP_INVALID_HEADER;
6058 lphttpHdr = &request->custHeaders[index];
6060 else if (value)
6062 HTTPHEADERW hdr;
6064 hdr.lpszField = (LPWSTR)field;
6065 hdr.lpszValue = (LPWSTR)value;
6066 hdr.wFlags = hdr.wCount = 0;
6068 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6069 hdr.wFlags |= HDR_ISREQUEST;
6071 return HTTP_InsertCustomHeader(request, &hdr);
6073 /* no value to delete */
6074 else return ERROR_SUCCESS;
6076 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6077 lphttpHdr->wFlags |= HDR_ISREQUEST;
6078 else
6079 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
6081 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6083 HTTP_DeleteCustomHeader( request, index );
6085 if (value && value[0])
6087 HTTPHEADERW hdr;
6089 hdr.lpszField = (LPWSTR)field;
6090 hdr.lpszValue = (LPWSTR)value;
6091 hdr.wFlags = hdr.wCount = 0;
6093 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6094 hdr.wFlags |= HDR_ISREQUEST;
6096 return HTTP_InsertCustomHeader(request, &hdr);
6099 return ERROR_SUCCESS;
6101 else if (dwModifier & COALESCEFLAGS)
6103 LPWSTR lpsztmp;
6104 WCHAR ch = 0;
6105 INT len = 0;
6106 INT origlen = strlenW(lphttpHdr->lpszValue);
6107 INT valuelen = strlenW(value);
6109 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
6111 ch = ',';
6112 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6114 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6116 ch = ';';
6117 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6120 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
6122 lpsztmp = heap_realloc(lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
6123 if (lpsztmp)
6125 lphttpHdr->lpszValue = lpsztmp;
6126 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6127 if (ch > 0)
6129 lphttpHdr->lpszValue[origlen] = ch;
6130 origlen++;
6131 lphttpHdr->lpszValue[origlen] = ' ';
6132 origlen++;
6135 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
6136 lphttpHdr->lpszValue[len] = '\0';
6137 res = ERROR_SUCCESS;
6139 else
6141 WARN("heap_realloc (%d bytes) failed\n",len+1);
6142 res = ERROR_OUTOFMEMORY;
6145 TRACE("<-- %d\n", res);
6146 return res;
6149 /***********************************************************************
6150 * HTTP_GetCustomHeaderIndex (internal)
6152 * Return index of custom header from header array
6155 static INT HTTP_GetCustomHeaderIndex(http_request_t *request, LPCWSTR lpszField,
6156 int requested_index, BOOL request_only)
6158 DWORD index;
6160 TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
6162 for (index = 0; index < request->nCustHeaders; index++)
6164 if (strcmpiW(request->custHeaders[index].lpszField, lpszField))
6165 continue;
6167 if (request_only && !(request->custHeaders[index].wFlags & HDR_ISREQUEST))
6168 continue;
6170 if (!request_only && (request->custHeaders[index].wFlags & HDR_ISREQUEST))
6171 continue;
6173 if (requested_index == 0)
6174 break;
6175 requested_index --;
6178 if (index >= request->nCustHeaders)
6179 index = -1;
6181 TRACE("Return: %d\n", index);
6182 return index;
6186 /***********************************************************************
6187 * HTTP_InsertCustomHeader (internal)
6189 * Insert header into array
6192 static DWORD HTTP_InsertCustomHeader(http_request_t *request, LPHTTPHEADERW lpHdr)
6194 INT count;
6195 LPHTTPHEADERW lph = NULL;
6197 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
6198 count = request->nCustHeaders + 1;
6199 if (count > 1)
6200 lph = heap_realloc_zero(request->custHeaders, sizeof(HTTPHEADERW) * count);
6201 else
6202 lph = heap_alloc_zero(sizeof(HTTPHEADERW) * count);
6204 if (!lph)
6205 return ERROR_OUTOFMEMORY;
6207 request->custHeaders = lph;
6208 request->custHeaders[count-1].lpszField = heap_strdupW(lpHdr->lpszField);
6209 request->custHeaders[count-1].lpszValue = heap_strdupW(lpHdr->lpszValue);
6210 request->custHeaders[count-1].wFlags = lpHdr->wFlags;
6211 request->custHeaders[count-1].wCount= lpHdr->wCount;
6212 request->nCustHeaders++;
6214 return ERROR_SUCCESS;
6218 /***********************************************************************
6219 * HTTP_DeleteCustomHeader (internal)
6221 * Delete header from array
6222 * If this function is called, the indexs may change.
6224 static BOOL HTTP_DeleteCustomHeader(http_request_t *request, DWORD index)
6226 if( request->nCustHeaders <= 0 )
6227 return FALSE;
6228 if( index >= request->nCustHeaders )
6229 return FALSE;
6230 request->nCustHeaders--;
6232 heap_free(request->custHeaders[index].lpszField);
6233 heap_free(request->custHeaders[index].lpszValue);
6235 memmove( &request->custHeaders[index], &request->custHeaders[index+1],
6236 (request->nCustHeaders - index)* sizeof(HTTPHEADERW) );
6237 memset( &request->custHeaders[request->nCustHeaders], 0, sizeof(HTTPHEADERW) );
6239 return TRUE;
6243 /***********************************************************************
6244 * HTTP_VerifyValidHeader (internal)
6246 * Verify the given header is not invalid for the given http request
6249 static BOOL HTTP_VerifyValidHeader(http_request_t *request, LPCWSTR field)
6251 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
6252 if (!strcmpW(request->version, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
6253 return ERROR_HTTP_INVALID_HEADER;
6255 return ERROR_SUCCESS;
6258 /***********************************************************************
6259 * IsHostInProxyBypassList (@)
6261 * Undocumented
6264 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
6266 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
6267 return FALSE;