wininet: Don't update *lpdwIndex if HttpQueryInfoW fails with ERROR_INSUFFICIENT_BUFFER.
[wine/wine-gecko.git] / dlls / wininet / http.c
blobd2b3de9b12b10918d77c7b10a2b9f367f0c4ee54
1 /*
2 * Wininet - HTTP Implementation
4 * Copyright 1999 Corel Corporation
5 * Copyright 2002 CodeWeavers Inc.
6 * Copyright 2002 TransGaming Technologies Inc.
7 * Copyright 2004 Mike McCormack for CodeWeavers
8 * Copyright 2005 Aric Stewart for CodeWeavers
9 * Copyright 2006 Robert Shearman for CodeWeavers
10 * Copyright 2011 Jacek Caban for CodeWeavers
12 * Ulrich Czekalla
13 * David Hammerton
15 * This library is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU Lesser General Public
17 * License as published by the Free Software Foundation; either
18 * version 2.1 of the License, or (at your option) any later version.
20 * This library is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 * Lesser General Public License for more details.
25 * You should have received a copy of the GNU Lesser General Public
26 * License along with this library; if not, write to the Free Software
27 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
30 #include "config.h"
31 #include "wine/port.h"
33 #if defined(__MINGW32__) || defined (_MSC_VER)
34 #include <ws2tcpip.h>
35 #endif
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_SOCKET_H
39 # include <sys/socket.h>
40 #endif
41 #ifdef HAVE_ARPA_INET_H
42 # include <arpa/inet.h>
43 #endif
44 #include <stdarg.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #ifdef HAVE_UNISTD_H
48 # include <unistd.h>
49 #endif
50 #include <time.h>
51 #include <assert.h>
52 #ifdef HAVE_ZLIB
53 # include <zlib.h>
54 #endif
56 #include "windef.h"
57 #include "winbase.h"
58 #include "wininet.h"
59 #include "winerror.h"
60 #include "winternl.h"
61 #define NO_SHLWAPI_STREAM
62 #define NO_SHLWAPI_REG
63 #define NO_SHLWAPI_STRFCNS
64 #define NO_SHLWAPI_GDI
65 #include "shlwapi.h"
66 #include "sspi.h"
67 #include "wincrypt.h"
68 #include "winuser.h"
70 #include "internet.h"
71 #include "wine/debug.h"
72 #include "wine/exception.h"
73 #include "wine/unicode.h"
75 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
77 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
78 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
79 static const WCHAR szOK[] = {'O','K',0};
80 static const WCHAR szDefaultHeader[] = {'H','T','T','P','/','1','.','0',' ','2','0','0',' ','O','K',0};
81 static const WCHAR hostW[] = { 'H','o','s','t',0 };
82 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
83 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
84 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
85 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
86 static const WCHAR szGET[] = { 'G','E','T', 0 };
87 static const WCHAR szHEAD[] = { 'H','E','A','D', 0 };
88 static const WCHAR szCrLf[] = {'\r','\n', 0};
90 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
91 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
92 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
93 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
94 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
95 static const WCHAR szAge[] = { 'A','g','e',0 };
96 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
97 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
98 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
99 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
100 static const WCHAR szContent_Disposition[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
101 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
102 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
103 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
104 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
105 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
106 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
107 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
108 static const WCHAR szContent_Transfer_Encoding[] = { 'C','o','n','t','e','n','t','-','T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
109 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
110 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
111 static const WCHAR szDate[] = { 'D','a','t','e',0 };
112 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
113 static const WCHAR szETag[] = { 'E','T','a','g',0 };
114 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
115 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
116 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
117 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
118 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
119 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
120 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
121 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
122 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
123 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
124 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
125 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
126 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
127 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
128 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
129 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
130 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
131 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
132 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
133 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
134 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
135 static const WCHAR szUnless_Modified_Since[] = { 'U','n','l','e','s','s','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
136 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
137 static const WCHAR szURI[] = { 'U','R','I',0 };
138 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
139 static const WCHAR szVary[] = { 'V','a','r','y',0 };
140 static const WCHAR szVia[] = { 'V','i','a',0 };
141 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
142 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
144 static const WCHAR emptyW[] = {0};
146 #define HTTP_REFERER szReferer
147 #define HTTP_ACCEPT szAccept
148 #define HTTP_USERAGENT szUser_Agent
150 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
151 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
152 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
153 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
154 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
155 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
156 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
158 #define COLLECT_TIME 60000
160 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
162 struct HttpAuthInfo
164 LPWSTR scheme;
165 CredHandle cred;
166 CtxtHandle ctx;
167 TimeStamp exp;
168 ULONG attr;
169 ULONG max_token;
170 void *auth_data;
171 unsigned int auth_data_len;
172 BOOL finished; /* finished authenticating */
176 typedef struct _basicAuthorizationData
178 struct list entry;
180 LPWSTR host;
181 LPWSTR realm;
182 LPSTR authorization;
183 UINT authorizationLen;
184 } basicAuthorizationData;
186 typedef struct _authorizationData
188 struct list entry;
190 LPWSTR host;
191 LPWSTR scheme;
192 LPWSTR domain;
193 UINT domain_len;
194 LPWSTR user;
195 UINT user_len;
196 LPWSTR password;
197 UINT password_len;
198 } authorizationData;
200 static struct list basicAuthorizationCache = LIST_INIT(basicAuthorizationCache);
201 static struct list authorizationCache = LIST_INIT(authorizationCache);
203 static CRITICAL_SECTION authcache_cs;
204 static CRITICAL_SECTION_DEBUG critsect_debug =
206 0, 0, &authcache_cs,
207 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
208 0, 0, { (DWORD_PTR)(__FILE__ ": authcache_cs") }
210 static CRITICAL_SECTION authcache_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
212 static DWORD HTTP_GetResponseHeaders(http_request_t *req, INT *len);
213 static DWORD HTTP_ProcessHeader(http_request_t *req, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
214 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
215 static DWORD HTTP_InsertCustomHeader(http_request_t *req, LPHTTPHEADERW lpHdr);
216 static INT HTTP_GetCustomHeaderIndex(http_request_t *req, LPCWSTR lpszField, INT index, BOOL Request);
217 static BOOL HTTP_DeleteCustomHeader(http_request_t *req, DWORD index);
218 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
219 static DWORD HTTP_HttpQueryInfoW(http_request_t*, DWORD, LPVOID, LPDWORD, LPDWORD);
220 static LPWSTR HTTP_GetRedirectURL(http_request_t *req, LPCWSTR lpszUrl);
221 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
222 static BOOL HTTP_VerifyValidHeader(http_request_t *req, LPCWSTR field);
223 static BOOL drain_content(http_request_t*,BOOL);
225 static CRITICAL_SECTION connection_pool_cs;
226 static CRITICAL_SECTION_DEBUG connection_pool_debug =
228 0, 0, &connection_pool_cs,
229 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
230 0, 0, { (DWORD_PTR)(__FILE__ ": connection_pool_cs") }
232 static CRITICAL_SECTION connection_pool_cs = { &connection_pool_debug, -1, 0, 0, 0, 0 };
234 static struct list connection_pool = LIST_INIT(connection_pool);
235 static BOOL collector_running;
237 void server_addref(server_t *server)
239 InterlockedIncrement(&server->ref);
242 void server_release(server_t *server)
244 if(InterlockedDecrement(&server->ref))
245 return;
247 list_remove(&server->entry);
249 if(server->cert_chain)
250 CertFreeCertificateChain(server->cert_chain);
251 heap_free(server->name);
252 heap_free(server->scheme_host_port);
253 heap_free(server);
256 static BOOL process_host_port(server_t *server)
258 BOOL default_port;
259 size_t name_len;
260 WCHAR *buf;
262 static const WCHAR httpW[] = {'h','t','t','p',0};
263 static const WCHAR httpsW[] = {'h','t','t','p','s',0};
264 static const WCHAR formatW[] = {'%','s',':','/','/','%','s',':','%','u',0};
266 name_len = strlenW(server->name);
267 buf = heap_alloc((name_len + 10 /* strlen("://:<port>") */)*sizeof(WCHAR) + sizeof(httpsW));
268 if(!buf)
269 return FALSE;
271 sprintfW(buf, formatW, server->is_https ? httpsW : httpW, server->name, server->port);
272 server->scheme_host_port = buf;
274 server->host_port = server->scheme_host_port + 7 /* strlen("http://") */;
275 if(server->is_https)
276 server->host_port++;
278 default_port = server->port == (server->is_https ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT);
279 server->canon_host_port = default_port ? server->name : server->host_port;
280 return TRUE;
283 server_t *get_server(const WCHAR *name, INTERNET_PORT port, BOOL is_https, BOOL do_create)
285 server_t *iter, *server = NULL;
287 if(port == INTERNET_INVALID_PORT_NUMBER)
288 port = INTERNET_DEFAULT_HTTP_PORT;
290 EnterCriticalSection(&connection_pool_cs);
292 LIST_FOR_EACH_ENTRY(iter, &connection_pool, server_t, entry) {
293 if(iter->port == port && !strcmpW(iter->name, name) && iter->is_https == is_https) {
294 server = iter;
295 server_addref(server);
296 break;
300 if(!server && do_create) {
301 server = heap_alloc_zero(sizeof(*server));
302 if(server) {
303 server->ref = 2; /* list reference and return */
304 server->port = port;
305 server->is_https = is_https;
306 list_init(&server->conn_pool);
307 server->name = heap_strdupW(name);
308 if(server->name && process_host_port(server)) {
309 list_add_head(&connection_pool, &server->entry);
310 }else {
311 heap_free(server);
312 server = NULL;
317 LeaveCriticalSection(&connection_pool_cs);
319 return server;
322 BOOL collect_connections(collect_type_t collect_type)
324 netconn_t *netconn, *netconn_safe;
325 server_t *server, *server_safe;
326 BOOL remaining = FALSE;
327 DWORD64 now;
329 now = GetTickCount64();
331 LIST_FOR_EACH_ENTRY_SAFE(server, server_safe, &connection_pool, server_t, entry) {
332 LIST_FOR_EACH_ENTRY_SAFE(netconn, netconn_safe, &server->conn_pool, netconn_t, pool_entry) {
333 if(collect_type > COLLECT_TIMEOUT || netconn->keep_until < now) {
334 TRACE("freeing %p\n", netconn);
335 list_remove(&netconn->pool_entry);
336 free_netconn(netconn);
337 }else {
338 remaining = TRUE;
342 if(collect_type == COLLECT_CLEANUP) {
343 list_remove(&server->entry);
344 list_init(&server->entry);
345 server_release(server);
349 return remaining;
352 static DWORD WINAPI collect_connections_proc(void *arg)
354 BOOL remaining_conns;
356 do {
357 /* FIXME: Use more sophisticated method */
358 Sleep(5000);
360 EnterCriticalSection(&connection_pool_cs);
362 remaining_conns = collect_connections(COLLECT_TIMEOUT);
363 if(!remaining_conns)
364 collector_running = FALSE;
366 LeaveCriticalSection(&connection_pool_cs);
367 }while(remaining_conns);
369 FreeLibraryAndExitThread(WININET_hModule, 0);
372 static LPHTTPHEADERW HTTP_GetHeader(http_request_t *req, LPCWSTR head)
374 int HeaderIndex = 0;
375 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
376 if (HeaderIndex == -1)
377 return NULL;
378 else
379 return &req->custHeaders[HeaderIndex];
382 struct data_stream_vtbl_t {
383 DWORD (*get_avail_data)(data_stream_t*,http_request_t*);
384 BOOL (*end_of_data)(data_stream_t*,http_request_t*);
385 DWORD (*read)(data_stream_t*,http_request_t*,BYTE*,DWORD,DWORD*,blocking_mode_t);
386 BOOL (*drain_content)(data_stream_t*,http_request_t*);
387 void (*destroy)(data_stream_t*);
390 typedef struct {
391 data_stream_t data_stream;
393 BYTE buf[READ_BUFFER_SIZE];
394 DWORD buf_size;
395 DWORD buf_pos;
396 DWORD chunk_size;
397 BOOL end_of_data;
398 } chunked_stream_t;
400 static inline void destroy_data_stream(data_stream_t *stream)
402 stream->vtbl->destroy(stream);
405 static void reset_data_stream(http_request_t *req)
407 destroy_data_stream(req->data_stream);
408 req->data_stream = &req->netconn_stream.data_stream;
409 req->read_pos = req->read_size = req->netconn_stream.content_read = 0;
410 req->read_chunked = req->read_gzip = FALSE;
413 #ifdef HAVE_ZLIB
415 typedef struct {
416 data_stream_t stream;
417 data_stream_t *parent_stream;
418 z_stream zstream;
419 BYTE buf[READ_BUFFER_SIZE];
420 DWORD buf_size;
421 DWORD buf_pos;
422 BOOL end_of_data;
423 } gzip_stream_t;
425 static DWORD gzip_get_avail_data(data_stream_t *stream, http_request_t *req)
427 /* Allow reading only from read buffer */
428 return 0;
431 static BOOL gzip_end_of_data(data_stream_t *stream, http_request_t *req)
433 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
434 return gzip_stream->end_of_data
435 || (!gzip_stream->buf_size && gzip_stream->parent_stream->vtbl->end_of_data(gzip_stream->parent_stream, req));
438 static DWORD gzip_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
439 DWORD *read, blocking_mode_t blocking_mode)
441 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
442 z_stream *zstream = &gzip_stream->zstream;
443 DWORD current_read, ret_read = 0;
444 int zres;
445 DWORD res = ERROR_SUCCESS;
447 TRACE("(%d %d)\n", size, blocking_mode);
449 while(size && !gzip_stream->end_of_data) {
450 if(!gzip_stream->buf_size) {
451 if(gzip_stream->buf_pos) {
452 if(gzip_stream->buf_size)
453 memmove(gzip_stream->buf, gzip_stream->buf+gzip_stream->buf_pos, gzip_stream->buf_size);
454 gzip_stream->buf_pos = 0;
456 res = gzip_stream->parent_stream->vtbl->read(gzip_stream->parent_stream, req, gzip_stream->buf+gzip_stream->buf_size,
457 sizeof(gzip_stream->buf)-gzip_stream->buf_size, &current_read, blocking_mode);
458 gzip_stream->buf_size += current_read;
459 if(res != ERROR_SUCCESS)
460 break;
462 if(!current_read) {
463 if(blocking_mode != BLOCKING_DISALLOW) {
464 WARN("unexpected end of data\n");
465 gzip_stream->end_of_data = TRUE;
467 break;
471 zstream->next_in = gzip_stream->buf+gzip_stream->buf_pos;
472 zstream->avail_in = gzip_stream->buf_size;
473 zstream->next_out = buf+ret_read;
474 zstream->avail_out = size;
475 zres = inflate(&gzip_stream->zstream, 0);
476 current_read = size - zstream->avail_out;
477 size -= current_read;
478 ret_read += current_read;
479 gzip_stream->buf_size -= zstream->next_in - (gzip_stream->buf+gzip_stream->buf_pos);
480 gzip_stream->buf_pos = zstream->next_in-gzip_stream->buf;
481 if(zres == Z_STREAM_END) {
482 TRACE("end of data\n");
483 gzip_stream->end_of_data = TRUE;
484 inflateEnd(zstream);
485 }else if(zres != Z_OK) {
486 WARN("inflate failed %d: %s\n", zres, debugstr_a(zstream->msg));
487 if(!ret_read)
488 res = ERROR_INTERNET_DECODING_FAILED;
489 break;
492 if(ret_read && blocking_mode == BLOCKING_ALLOW)
493 blocking_mode = BLOCKING_DISALLOW;
496 TRACE("read %u bytes\n", ret_read);
497 *read = ret_read;
498 return res;
501 static BOOL gzip_drain_content(data_stream_t *stream, http_request_t *req)
503 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
504 return gzip_stream->parent_stream->vtbl->drain_content(gzip_stream->parent_stream, req);
507 static void gzip_destroy(data_stream_t *stream)
509 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
511 destroy_data_stream(gzip_stream->parent_stream);
513 if(!gzip_stream->end_of_data)
514 inflateEnd(&gzip_stream->zstream);
515 heap_free(gzip_stream);
518 static const data_stream_vtbl_t gzip_stream_vtbl = {
519 gzip_get_avail_data,
520 gzip_end_of_data,
521 gzip_read,
522 gzip_drain_content,
523 gzip_destroy
526 static voidpf wininet_zalloc(voidpf opaque, uInt items, uInt size)
528 return heap_alloc(items*size);
531 static void wininet_zfree(voidpf opaque, voidpf address)
533 heap_free(address);
536 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
538 gzip_stream_t *gzip_stream;
539 int index, zres;
541 gzip_stream = heap_alloc_zero(sizeof(gzip_stream_t));
542 if(!gzip_stream)
543 return ERROR_OUTOFMEMORY;
545 gzip_stream->stream.vtbl = &gzip_stream_vtbl;
546 gzip_stream->zstream.zalloc = wininet_zalloc;
547 gzip_stream->zstream.zfree = wininet_zfree;
549 zres = inflateInit2(&gzip_stream->zstream, is_gzip ? 0x1f : -15);
550 if(zres != Z_OK) {
551 ERR("inflateInit failed: %d\n", zres);
552 heap_free(gzip_stream);
553 return ERROR_OUTOFMEMORY;
556 index = HTTP_GetCustomHeaderIndex(req, szContent_Length, 0, FALSE);
557 if(index != -1)
558 HTTP_DeleteCustomHeader(req, index);
560 if(req->read_size) {
561 memcpy(gzip_stream->buf, req->read_buf+req->read_pos, req->read_size);
562 gzip_stream->buf_size = req->read_size;
563 req->read_pos = req->read_size = 0;
566 req->read_gzip = TRUE;
567 gzip_stream->parent_stream = req->data_stream;
568 req->data_stream = &gzip_stream->stream;
569 return ERROR_SUCCESS;
572 #else
574 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
576 ERR("gzip stream not supported, missing zlib.\n");
577 return ERROR_SUCCESS;
580 #endif
582 /***********************************************************************
583 * HTTP_FreeTokens (internal)
585 * Frees table of pointers.
587 static void HTTP_FreeTokens(LPWSTR * token_array)
589 int i;
590 for (i = 0; token_array[i]; i++) heap_free(token_array[i]);
591 heap_free(token_array);
594 static void HTTP_FixURL(http_request_t *request)
596 static const WCHAR szSlash[] = { '/',0 };
597 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
599 /* If we don't have a path we set it to root */
600 if (NULL == request->path)
601 request->path = heap_strdupW(szSlash);
602 else /* remove \r and \n*/
604 int nLen = strlenW(request->path);
605 while ((nLen >0 ) && ((request->path[nLen-1] == '\r')||(request->path[nLen-1] == '\n')))
607 nLen--;
608 request->path[nLen]='\0';
610 /* Replace '\' with '/' */
611 while (nLen>0) {
612 nLen--;
613 if (request->path[nLen] == '\\') request->path[nLen]='/';
617 if(CSTR_EQUAL != CompareStringW( LOCALE_INVARIANT, NORM_IGNORECASE,
618 request->path, strlenW(request->path), szHttp, strlenW(szHttp) )
619 && request->path[0] != '/') /* not an absolute path ?? --> fix it !! */
621 WCHAR *fixurl = heap_alloc((strlenW(request->path) + 2)*sizeof(WCHAR));
622 *fixurl = '/';
623 strcpyW(fixurl + 1, request->path);
624 heap_free( request->path );
625 request->path = fixurl;
629 static WCHAR* build_request_header(http_request_t *request, const WCHAR *verb,
630 const WCHAR *path, const WCHAR *version, BOOL use_cr)
632 LPWSTR requestString;
633 DWORD len, n;
634 LPCWSTR *req;
635 UINT i;
637 static const WCHAR szSpace[] = { ' ',0 };
638 static const WCHAR szColon[] = { ':',' ',0 };
639 static const WCHAR szCr[] = { '\r',0 };
640 static const WCHAR szLf[] = { '\n',0 };
642 /* allocate space for an array of all the string pointers to be added */
643 len = (request->nCustHeaders)*5 + 10;
644 req = heap_alloc(len*sizeof(LPCWSTR));
646 /* add the verb, path and HTTP version string */
647 n = 0;
648 req[n++] = verb;
649 req[n++] = szSpace;
650 req[n++] = path;
651 req[n++] = szSpace;
652 req[n++] = version;
653 if (use_cr)
654 req[n++] = szCr;
655 req[n++] = szLf;
657 /* Append custom request headers */
658 for (i = 0; i < request->nCustHeaders; i++)
660 if (request->custHeaders[i].wFlags & HDR_ISREQUEST)
662 req[n++] = request->custHeaders[i].lpszField;
663 req[n++] = szColon;
664 req[n++] = request->custHeaders[i].lpszValue;
665 if (use_cr)
666 req[n++] = szCr;
667 req[n++] = szLf;
669 TRACE("Adding custom header %s (%s)\n",
670 debugstr_w(request->custHeaders[i].lpszField),
671 debugstr_w(request->custHeaders[i].lpszValue));
674 if (use_cr)
675 req[n++] = szCr;
676 req[n++] = szLf;
677 req[n] = NULL;
679 requestString = HTTP_build_req( req, 4 );
680 heap_free( req );
681 return requestString;
684 static WCHAR* build_response_header(http_request_t *request, BOOL use_cr)
686 static const WCHAR colonW[] = { ':',' ',0 };
687 static const WCHAR crW[] = { '\r',0 };
688 static const WCHAR lfW[] = { '\n',0 };
689 static const WCHAR status_fmt[] = { ' ','%','u',' ',0 };
691 const WCHAR **req;
692 WCHAR *ret, buf[14];
693 DWORD i, n = 0;
695 req = heap_alloc((request->nCustHeaders*5+8)*sizeof(WCHAR*));
696 if(!req)
697 return NULL;
699 if (request->status_code)
701 req[n++] = request->version;
702 sprintfW(buf, status_fmt, request->status_code);
703 req[n++] = buf;
704 req[n++] = request->statusText;
705 if (use_cr)
706 req[n++] = crW;
707 req[n++] = lfW;
710 for(i = 0; i < request->nCustHeaders; i++)
712 if(!(request->custHeaders[i].wFlags & HDR_ISREQUEST)
713 && strcmpW(request->custHeaders[i].lpszField, szStatus))
715 req[n++] = request->custHeaders[i].lpszField;
716 req[n++] = colonW;
717 req[n++] = request->custHeaders[i].lpszValue;
718 if(use_cr)
719 req[n++] = crW;
720 req[n++] = lfW;
722 TRACE("Adding custom header %s (%s)\n",
723 debugstr_w(request->custHeaders[i].lpszField),
724 debugstr_w(request->custHeaders[i].lpszValue));
727 if(use_cr)
728 req[n++] = crW;
729 req[n++] = lfW;
730 req[n] = NULL;
732 ret = HTTP_build_req(req, 0);
733 heap_free(req);
734 return ret;
737 static void HTTP_ProcessCookies( http_request_t *request )
739 int HeaderIndex;
740 int numCookies = 0;
741 LPHTTPHEADERW setCookieHeader;
743 if(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES)
744 return;
746 while((HeaderIndex = HTTP_GetCustomHeaderIndex(request, szSet_Cookie, numCookies++, FALSE)) != -1)
748 HTTPHEADERW *host;
749 const WCHAR *data;
750 WCHAR *name;
752 setCookieHeader = &request->custHeaders[HeaderIndex];
754 if (!setCookieHeader->lpszValue)
755 continue;
757 host = HTTP_GetHeader(request, hostW);
758 if(!host)
759 continue;
761 data = strchrW(setCookieHeader->lpszValue, '=');
762 if(!data)
763 continue;
765 name = heap_strndupW(setCookieHeader->lpszValue, data-setCookieHeader->lpszValue);
766 if(!name)
767 continue;
769 data++;
770 set_cookie(host->lpszValue, request->path, name, data);
771 heap_free(name);
775 static void strip_spaces(LPWSTR start)
777 LPWSTR str = start;
778 LPWSTR end;
780 while (*str == ' ' && *str != '\0')
781 str++;
783 if (str != start)
784 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
786 end = start + strlenW(start) - 1;
787 while (end >= start && *end == ' ')
789 *end = '\0';
790 end--;
794 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue, LPWSTR *pszRealm )
796 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
797 static const WCHAR szRealm[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
798 BOOL is_basic;
799 is_basic = !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
800 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
801 if (is_basic && pszRealm)
803 LPCWSTR token;
804 LPCWSTR ptr = &pszAuthValue[ARRAYSIZE(szBasic)];
805 LPCWSTR realm;
806 ptr++;
807 *pszRealm=NULL;
808 token = strchrW(ptr,'=');
809 if (!token)
810 return TRUE;
811 realm = ptr;
812 while (*realm == ' ' && *realm != '\0')
813 realm++;
814 if(!strncmpiW(realm, szRealm, ARRAYSIZE(szRealm)) &&
815 (realm[ARRAYSIZE(szRealm)] == ' ' || realm[ARRAYSIZE(szRealm)] == '='))
817 token++;
818 while (*token == ' ' && *token != '\0')
819 token++;
820 if (*token == '\0')
821 return TRUE;
822 *pszRealm = heap_strdupW(token);
823 strip_spaces(*pszRealm);
827 return is_basic;
830 static void destroy_authinfo( struct HttpAuthInfo *authinfo )
832 if (!authinfo) return;
834 if (SecIsValidHandle(&authinfo->ctx))
835 DeleteSecurityContext(&authinfo->ctx);
836 if (SecIsValidHandle(&authinfo->cred))
837 FreeCredentialsHandle(&authinfo->cred);
839 heap_free(authinfo->auth_data);
840 heap_free(authinfo->scheme);
841 heap_free(authinfo);
844 static UINT retrieve_cached_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR *auth_data)
846 basicAuthorizationData *ad;
847 UINT rc = 0;
849 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host),debugstr_w(realm));
851 EnterCriticalSection(&authcache_cs);
852 LIST_FOR_EACH_ENTRY(ad, &basicAuthorizationCache, basicAuthorizationData, entry)
854 if (!strcmpiW(host,ad->host) && !strcmpW(realm,ad->realm))
856 TRACE("Authorization found in cache\n");
857 *auth_data = heap_alloc(ad->authorizationLen);
858 memcpy(*auth_data,ad->authorization,ad->authorizationLen);
859 rc = ad->authorizationLen;
860 break;
863 LeaveCriticalSection(&authcache_cs);
864 return rc;
867 static void cache_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR auth_data, UINT auth_data_len)
869 struct list *cursor;
870 basicAuthorizationData* ad = NULL;
872 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host),debugstr_w(realm),debugstr_an(auth_data,auth_data_len));
874 EnterCriticalSection(&authcache_cs);
875 LIST_FOR_EACH(cursor, &basicAuthorizationCache)
877 basicAuthorizationData *check = LIST_ENTRY(cursor,basicAuthorizationData,entry);
878 if (!strcmpiW(host,check->host) && !strcmpW(realm,check->realm))
880 ad = check;
881 break;
885 if (ad)
887 TRACE("Found match in cache, replacing\n");
888 heap_free(ad->authorization);
889 ad->authorization = heap_alloc(auth_data_len);
890 memcpy(ad->authorization, auth_data, auth_data_len);
891 ad->authorizationLen = auth_data_len;
893 else
895 ad = heap_alloc(sizeof(basicAuthorizationData));
896 ad->host = heap_strdupW(host);
897 ad->realm = heap_strdupW(realm);
898 ad->authorization = heap_alloc(auth_data_len);
899 memcpy(ad->authorization, auth_data, auth_data_len);
900 ad->authorizationLen = auth_data_len;
901 list_add_head(&basicAuthorizationCache,&ad->entry);
902 TRACE("authorization cached\n");
904 LeaveCriticalSection(&authcache_cs);
907 static BOOL retrieve_cached_authorization(LPWSTR host, LPWSTR scheme,
908 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
910 authorizationData *ad;
912 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
914 EnterCriticalSection(&authcache_cs);
915 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry) {
916 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
917 TRACE("Authorization found in cache\n");
919 nt_auth_identity->User = heap_strdupW(ad->user);
920 nt_auth_identity->Password = heap_strdupW(ad->password);
921 nt_auth_identity->Domain = heap_alloc(sizeof(WCHAR)*ad->domain_len);
922 if(!nt_auth_identity->User || !nt_auth_identity->Password ||
923 (!nt_auth_identity->Domain && ad->domain_len)) {
924 heap_free(nt_auth_identity->User);
925 heap_free(nt_auth_identity->Password);
926 heap_free(nt_auth_identity->Domain);
927 break;
930 nt_auth_identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
931 nt_auth_identity->UserLength = ad->user_len;
932 nt_auth_identity->PasswordLength = ad->password_len;
933 memcpy(nt_auth_identity->Domain, ad->domain, sizeof(WCHAR)*ad->domain_len);
934 nt_auth_identity->DomainLength = ad->domain_len;
935 LeaveCriticalSection(&authcache_cs);
936 return TRUE;
939 LeaveCriticalSection(&authcache_cs);
941 return FALSE;
944 static void cache_authorization(LPWSTR host, LPWSTR scheme,
945 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
947 authorizationData *ad;
948 BOOL found = FALSE;
950 TRACE("Caching authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
952 EnterCriticalSection(&authcache_cs);
953 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry)
954 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
955 found = TRUE;
956 break;
959 if(found) {
960 heap_free(ad->user);
961 heap_free(ad->password);
962 heap_free(ad->domain);
963 } else {
964 ad = heap_alloc(sizeof(authorizationData));
965 if(!ad) {
966 LeaveCriticalSection(&authcache_cs);
967 return;
970 ad->host = heap_strdupW(host);
971 ad->scheme = heap_strdupW(scheme);
972 list_add_head(&authorizationCache, &ad->entry);
975 ad->user = heap_strndupW(nt_auth_identity->User, nt_auth_identity->UserLength);
976 ad->password = heap_strndupW(nt_auth_identity->Password, nt_auth_identity->PasswordLength);
977 ad->domain = heap_strndupW(nt_auth_identity->Domain, nt_auth_identity->DomainLength);
978 ad->user_len = nt_auth_identity->UserLength;
979 ad->password_len = nt_auth_identity->PasswordLength;
980 ad->domain_len = nt_auth_identity->DomainLength;
982 if(!ad->host || !ad->scheme || !ad->user || !ad->password
983 || (nt_auth_identity->Domain && !ad->domain)) {
984 heap_free(ad->host);
985 heap_free(ad->scheme);
986 heap_free(ad->user);
987 heap_free(ad->password);
988 heap_free(ad->domain);
989 list_remove(&ad->entry);
990 heap_free(ad);
993 LeaveCriticalSection(&authcache_cs);
996 static BOOL HTTP_DoAuthorization( http_request_t *request, LPCWSTR pszAuthValue,
997 struct HttpAuthInfo **ppAuthInfo,
998 LPWSTR domain_and_username, LPWSTR password,
999 LPWSTR host )
1001 SECURITY_STATUS sec_status;
1002 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
1003 BOOL first = FALSE;
1004 LPWSTR szRealm = NULL;
1006 TRACE("%s\n", debugstr_w(pszAuthValue));
1008 if (!pAuthInfo)
1010 TimeStamp exp;
1012 first = TRUE;
1013 pAuthInfo = heap_alloc(sizeof(*pAuthInfo));
1014 if (!pAuthInfo)
1015 return FALSE;
1017 SecInvalidateHandle(&pAuthInfo->cred);
1018 SecInvalidateHandle(&pAuthInfo->ctx);
1019 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
1020 pAuthInfo->attr = 0;
1021 pAuthInfo->auth_data = NULL;
1022 pAuthInfo->auth_data_len = 0;
1023 pAuthInfo->finished = FALSE;
1025 if (is_basic_auth_value(pszAuthValue,NULL))
1027 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
1028 pAuthInfo->scheme = heap_strdupW(szBasic);
1029 if (!pAuthInfo->scheme)
1031 heap_free(pAuthInfo);
1032 return FALSE;
1035 else
1037 PVOID pAuthData;
1038 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
1040 pAuthInfo->scheme = heap_strdupW(pszAuthValue);
1041 if (!pAuthInfo->scheme)
1043 heap_free(pAuthInfo);
1044 return FALSE;
1047 if (domain_and_username)
1049 WCHAR *user = strchrW(domain_and_username, '\\');
1050 WCHAR *domain = domain_and_username;
1052 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1054 pAuthData = &nt_auth_identity;
1056 if (user) user++;
1057 else
1059 user = domain_and_username;
1060 domain = NULL;
1063 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1064 nt_auth_identity.User = user;
1065 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
1066 nt_auth_identity.Domain = domain;
1067 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
1068 nt_auth_identity.Password = password;
1069 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
1071 cache_authorization(host, pAuthInfo->scheme, &nt_auth_identity);
1073 else if(retrieve_cached_authorization(host, pAuthInfo->scheme, &nt_auth_identity))
1074 pAuthData = &nt_auth_identity;
1075 else
1076 /* use default credentials */
1077 pAuthData = NULL;
1079 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
1080 SECPKG_CRED_OUTBOUND, NULL,
1081 pAuthData, NULL,
1082 NULL, &pAuthInfo->cred,
1083 &exp);
1085 if(pAuthData && !domain_and_username) {
1086 heap_free(nt_auth_identity.User);
1087 heap_free(nt_auth_identity.Domain);
1088 heap_free(nt_auth_identity.Password);
1091 if (sec_status == SEC_E_OK)
1093 PSecPkgInfoW sec_pkg_info;
1094 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
1095 if (sec_status == SEC_E_OK)
1097 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
1098 FreeContextBuffer(sec_pkg_info);
1101 if (sec_status != SEC_E_OK)
1103 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1104 debugstr_w(pAuthInfo->scheme), sec_status);
1105 heap_free(pAuthInfo->scheme);
1106 heap_free(pAuthInfo);
1107 return FALSE;
1110 *ppAuthInfo = pAuthInfo;
1112 else if (pAuthInfo->finished)
1113 return FALSE;
1115 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
1116 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
1118 ERR("authentication scheme changed from %s to %s\n",
1119 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
1120 return FALSE;
1123 if (is_basic_auth_value(pszAuthValue,&szRealm))
1125 int userlen;
1126 int passlen;
1127 char *auth_data = NULL;
1128 UINT auth_data_len = 0;
1130 TRACE("basic authentication realm %s\n",debugstr_w(szRealm));
1132 if (!domain_and_username)
1134 if (host && szRealm)
1135 auth_data_len = retrieve_cached_basic_authorization(host, szRealm,&auth_data);
1136 if (auth_data_len == 0)
1138 heap_free(szRealm);
1139 return FALSE;
1142 else
1144 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
1145 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
1147 /* length includes a nul terminator, which will be re-used for the ':' */
1148 auth_data = heap_alloc(userlen + 1 + passlen);
1149 if (!auth_data)
1151 heap_free(szRealm);
1152 return FALSE;
1155 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
1156 auth_data[userlen] = ':';
1157 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
1158 auth_data_len = userlen + 1 + passlen;
1159 if (host && szRealm)
1160 cache_basic_authorization(host, szRealm, auth_data, auth_data_len);
1163 pAuthInfo->auth_data = auth_data;
1164 pAuthInfo->auth_data_len = auth_data_len;
1165 pAuthInfo->finished = TRUE;
1166 heap_free(szRealm);
1167 return TRUE;
1169 else
1171 LPCWSTR pszAuthData;
1172 SecBufferDesc out_desc, in_desc;
1173 SecBuffer out, in;
1174 unsigned char *buffer;
1175 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
1176 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
1178 in.BufferType = SECBUFFER_TOKEN;
1179 in.cbBuffer = 0;
1180 in.pvBuffer = NULL;
1182 in_desc.ulVersion = 0;
1183 in_desc.cBuffers = 1;
1184 in_desc.pBuffers = &in;
1186 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
1187 if (*pszAuthData == ' ')
1189 pszAuthData++;
1190 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
1191 in.pvBuffer = heap_alloc(in.cbBuffer);
1192 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
1195 buffer = heap_alloc(pAuthInfo->max_token);
1197 out.BufferType = SECBUFFER_TOKEN;
1198 out.cbBuffer = pAuthInfo->max_token;
1199 out.pvBuffer = buffer;
1201 out_desc.ulVersion = 0;
1202 out_desc.cBuffers = 1;
1203 out_desc.pBuffers = &out;
1205 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
1206 first ? NULL : &pAuthInfo->ctx,
1207 first ? request->server->name : NULL,
1208 context_req, 0, SECURITY_NETWORK_DREP,
1209 in.pvBuffer ? &in_desc : NULL,
1210 0, &pAuthInfo->ctx, &out_desc,
1211 &pAuthInfo->attr, &pAuthInfo->exp);
1212 if (sec_status == SEC_E_OK)
1214 pAuthInfo->finished = TRUE;
1215 pAuthInfo->auth_data = out.pvBuffer;
1216 pAuthInfo->auth_data_len = out.cbBuffer;
1217 TRACE("sending last auth packet\n");
1219 else if (sec_status == SEC_I_CONTINUE_NEEDED)
1221 pAuthInfo->auth_data = out.pvBuffer;
1222 pAuthInfo->auth_data_len = out.cbBuffer;
1223 TRACE("sending next auth packet\n");
1225 else
1227 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
1228 heap_free(out.pvBuffer);
1229 destroy_authinfo(pAuthInfo);
1230 *ppAuthInfo = NULL;
1231 return FALSE;
1235 return TRUE;
1238 /***********************************************************************
1239 * HTTP_HttpAddRequestHeadersW (internal)
1241 static DWORD HTTP_HttpAddRequestHeadersW(http_request_t *request,
1242 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1244 LPWSTR lpszStart;
1245 LPWSTR lpszEnd;
1246 LPWSTR buffer;
1247 DWORD len, res = ERROR_HTTP_INVALID_HEADER;
1249 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
1251 if( dwHeaderLength == ~0U )
1252 len = strlenW(lpszHeader);
1253 else
1254 len = dwHeaderLength;
1255 buffer = heap_alloc(sizeof(WCHAR)*(len+1));
1256 lstrcpynW( buffer, lpszHeader, len + 1);
1258 lpszStart = buffer;
1262 LPWSTR * pFieldAndValue;
1264 lpszEnd = lpszStart;
1266 while (*lpszEnd != '\0')
1268 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1269 break;
1270 lpszEnd++;
1273 if (*lpszStart == '\0')
1274 break;
1276 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1278 *lpszEnd = '\0';
1279 lpszEnd++; /* Jump over newline */
1281 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
1282 if (*lpszStart == '\0')
1284 /* Skip 0-length headers */
1285 lpszStart = lpszEnd;
1286 res = ERROR_SUCCESS;
1287 continue;
1289 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
1290 if (pFieldAndValue)
1292 res = HTTP_VerifyValidHeader(request, pFieldAndValue[0]);
1293 if (res == ERROR_SUCCESS)
1294 res = HTTP_ProcessHeader(request, pFieldAndValue[0],
1295 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
1296 HTTP_FreeTokens(pFieldAndValue);
1299 lpszStart = lpszEnd;
1300 } while (res == ERROR_SUCCESS);
1302 heap_free(buffer);
1303 return res;
1306 /***********************************************************************
1307 * HttpAddRequestHeadersW (WININET.@)
1309 * Adds one or more HTTP header to the request handler
1311 * NOTE
1312 * On Windows if dwHeaderLength includes the trailing '\0', then
1313 * HttpAddRequestHeadersW() adds it too. However this results in an
1314 * invalid HTTP header which is rejected by some servers so we probably
1315 * don't need to match Windows on that point.
1317 * RETURNS
1318 * TRUE on success
1319 * FALSE on failure
1322 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
1323 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1325 http_request_t *request;
1326 DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
1328 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1330 if (!lpszHeader)
1331 return TRUE;
1333 request = (http_request_t*) get_handle_object( hHttpRequest );
1334 if (request && request->hdr.htype == WH_HHTTPREQ)
1335 res = HTTP_HttpAddRequestHeadersW( request, lpszHeader, dwHeaderLength, dwModifier );
1336 if( request )
1337 WININET_Release( &request->hdr );
1339 if(res != ERROR_SUCCESS)
1340 SetLastError(res);
1341 return res == ERROR_SUCCESS;
1344 /***********************************************************************
1345 * HttpAddRequestHeadersA (WININET.@)
1347 * Adds one or more HTTP header to the request handler
1349 * RETURNS
1350 * TRUE on success
1351 * FALSE on failure
1354 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
1355 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1357 DWORD len;
1358 LPWSTR hdr;
1359 BOOL r;
1361 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1363 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
1364 hdr = heap_alloc(len*sizeof(WCHAR));
1365 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
1366 if( dwHeaderLength != ~0U )
1367 dwHeaderLength = len;
1369 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
1371 heap_free( hdr );
1372 return r;
1375 static void free_accept_types( WCHAR **accept_types )
1377 WCHAR *ptr, **types = accept_types;
1379 if (!types) return;
1380 while ((ptr = *types))
1382 heap_free( ptr );
1383 types++;
1385 heap_free( accept_types );
1388 static WCHAR **convert_accept_types( const char **accept_types )
1390 unsigned int count;
1391 const char **types = accept_types;
1392 WCHAR **typesW;
1393 BOOL invalid_pointer = FALSE;
1395 if (!types) return NULL;
1396 count = 0;
1397 while (*types)
1399 __TRY
1401 /* find out how many there are */
1402 if (*types && **types)
1404 TRACE("accept type: %s\n", debugstr_a(*types));
1405 count++;
1408 __EXCEPT_PAGE_FAULT
1410 WARN("invalid accept type pointer\n");
1411 invalid_pointer = TRUE;
1413 __ENDTRY;
1414 types++;
1416 if (invalid_pointer) return NULL;
1417 if (!(typesW = heap_alloc( sizeof(WCHAR *) * (count + 1) ))) return NULL;
1418 count = 0;
1419 types = accept_types;
1420 while (*types)
1422 if (*types && **types) typesW[count++] = heap_strdupAtoW( *types );
1423 types++;
1425 typesW[count] = NULL;
1426 return typesW;
1429 /***********************************************************************
1430 * HttpOpenRequestA (WININET.@)
1432 * Open a HTTP request handle
1434 * RETURNS
1435 * HINTERNET a HTTP request handle on success
1436 * NULL on failure
1439 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
1440 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
1441 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
1442 DWORD dwFlags, DWORD_PTR dwContext)
1444 LPWSTR szVerb = NULL, szObjectName = NULL;
1445 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
1446 HINTERNET rc = NULL;
1448 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
1449 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
1450 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
1451 dwFlags, dwContext);
1453 if (lpszVerb)
1455 szVerb = heap_strdupAtoW(lpszVerb);
1456 if ( !szVerb )
1457 goto end;
1460 if (lpszObjectName)
1462 szObjectName = heap_strdupAtoW(lpszObjectName);
1463 if ( !szObjectName )
1464 goto end;
1467 if (lpszVersion)
1469 szVersion = heap_strdupAtoW(lpszVersion);
1470 if ( !szVersion )
1471 goto end;
1474 if (lpszReferrer)
1476 szReferrer = heap_strdupAtoW(lpszReferrer);
1477 if ( !szReferrer )
1478 goto end;
1481 szAcceptTypes = convert_accept_types( lpszAcceptTypes );
1482 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName, szVersion, szReferrer,
1483 (const WCHAR **)szAcceptTypes, dwFlags, dwContext);
1485 end:
1486 free_accept_types(szAcceptTypes);
1487 heap_free(szReferrer);
1488 heap_free(szVersion);
1489 heap_free(szObjectName);
1490 heap_free(szVerb);
1491 return rc;
1494 /***********************************************************************
1495 * HTTP_EncodeBase64
1497 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1499 UINT n = 0, x;
1500 static const CHAR HTTP_Base64Enc[] =
1501 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1503 while( len > 0 )
1505 /* first 6 bits, all from bin[0] */
1506 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1507 x = (bin[0] & 3) << 4;
1509 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1510 if( len == 1 )
1512 base64[n++] = HTTP_Base64Enc[x];
1513 base64[n++] = '=';
1514 base64[n++] = '=';
1515 break;
1517 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1518 x = ( bin[1] & 0x0f ) << 2;
1520 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1521 if( len == 2 )
1523 base64[n++] = HTTP_Base64Enc[x];
1524 base64[n++] = '=';
1525 break;
1527 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1529 /* last 6 bits, all from bin [2] */
1530 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1531 bin += 3;
1532 len -= 3;
1534 base64[n] = 0;
1535 return n;
1538 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1539 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1540 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1541 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1542 static const signed char HTTP_Base64Dec[256] =
1544 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1545 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1546 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1547 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1548 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1549 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1550 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1551 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1552 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1553 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1554 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1555 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1556 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1557 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1558 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1559 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1560 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1561 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1562 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1563 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1564 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1565 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1566 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1567 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1568 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1569 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1571 #undef CH
1573 /***********************************************************************
1574 * HTTP_DecodeBase64
1576 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1578 unsigned int n = 0;
1580 while(*base64)
1582 signed char in[4];
1584 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1585 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1586 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1587 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1589 WARN("invalid base64: %s\n", debugstr_w(base64));
1590 return 0;
1592 if (bin)
1593 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1594 n++;
1596 if ((base64[2] == '=') && (base64[3] == '='))
1597 break;
1598 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1599 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1601 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1602 return 0;
1604 if (bin)
1605 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1606 n++;
1608 if (base64[3] == '=')
1609 break;
1610 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1611 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1613 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1614 return 0;
1616 if (bin)
1617 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1618 n++;
1620 base64 += 4;
1623 return n;
1626 /***********************************************************************
1627 * HTTP_InsertAuthorization
1629 * Insert or delete the authorization field in the request header.
1631 static BOOL HTTP_InsertAuthorization( http_request_t *request, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1633 if (pAuthInfo)
1635 static const WCHAR wszSpace[] = {' ',0};
1636 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1637 unsigned int len;
1638 WCHAR *authorization = NULL;
1640 if (pAuthInfo->auth_data_len)
1642 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1643 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1644 authorization = heap_alloc((len+1)*sizeof(WCHAR));
1645 if (!authorization)
1646 return FALSE;
1648 strcpyW(authorization, pAuthInfo->scheme);
1649 strcatW(authorization, wszSpace);
1650 HTTP_EncodeBase64(pAuthInfo->auth_data,
1651 pAuthInfo->auth_data_len,
1652 authorization+strlenW(authorization));
1654 /* clear the data as it isn't valid now that it has been sent to the
1655 * server, unless it's Basic authentication which doesn't do
1656 * connection tracking */
1657 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1659 heap_free(pAuthInfo->auth_data);
1660 pAuthInfo->auth_data = NULL;
1661 pAuthInfo->auth_data_len = 0;
1665 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1667 HTTP_ProcessHeader(request, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1668 heap_free(authorization);
1670 return TRUE;
1673 static WCHAR *build_proxy_path_url(http_request_t *req)
1675 DWORD size, len;
1676 WCHAR *url;
1678 len = strlenW(req->server->scheme_host_port);
1679 size = len + strlenW(req->path) + 1;
1680 if(*req->path != '/')
1681 size++;
1682 url = heap_alloc(size * sizeof(WCHAR));
1683 if(!url)
1684 return NULL;
1686 memcpy(url, req->server->scheme_host_port, len*sizeof(WCHAR));
1687 if(*req->path != '/')
1688 url[len++] = '/';
1690 strcpyW(url+len, req->path);
1692 TRACE("url=%s\n", debugstr_w(url));
1693 return url;
1696 static BOOL HTTP_DomainMatches(LPCWSTR server, LPCWSTR domain)
1698 static const WCHAR localW[] = { '<','l','o','c','a','l','>',0 };
1699 BOOL ret = FALSE;
1701 if (!strcmpiW( domain, localW ) && !strchrW( server, '.' ))
1702 ret = TRUE;
1703 else if (*domain == '*')
1705 if (domain[1] == '.')
1707 LPCWSTR dot;
1709 /* For a hostname to match a wildcard, the last domain must match
1710 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1711 * hostname is www.foo.a.b, it matches, but a.b does not.
1713 dot = strchrW( server, '.' );
1714 if (dot)
1716 int len = strlenW( dot + 1 );
1718 if (len > strlenW( domain + 2 ))
1720 LPCWSTR ptr;
1722 /* The server's domain is longer than the wildcard, so it
1723 * could be a subdomain. Compare the last portion of the
1724 * server's domain.
1726 ptr = dot + len + 1 - strlenW( domain + 2 );
1727 if (!strcmpiW( ptr, domain + 2 ))
1729 /* This is only a match if the preceding character is
1730 * a '.', i.e. that it is a matching domain. E.g.
1731 * if domain is '*.b.c' and server is 'www.ab.c' they
1732 * do not match.
1734 ret = *(ptr - 1) == '.';
1737 else
1738 ret = !strcmpiW( dot + 1, domain + 2 );
1742 else
1743 ret = !strcmpiW( server, domain );
1744 return ret;
1747 static BOOL HTTP_ShouldBypassProxy(appinfo_t *lpwai, LPCWSTR server)
1749 LPCWSTR ptr;
1750 BOOL ret = FALSE;
1752 if (!lpwai->proxyBypass) return FALSE;
1753 ptr = lpwai->proxyBypass;
1754 do {
1755 LPCWSTR tmp = ptr;
1757 ptr = strchrW( ptr, ';' );
1758 if (!ptr)
1759 ptr = strchrW( tmp, ' ' );
1760 if (ptr)
1762 if (ptr - tmp < INTERNET_MAX_HOST_NAME_LENGTH)
1764 WCHAR domain[INTERNET_MAX_HOST_NAME_LENGTH];
1766 memcpy( domain, tmp, (ptr - tmp) * sizeof(WCHAR) );
1767 domain[ptr - tmp] = 0;
1768 ret = HTTP_DomainMatches( server, domain );
1770 ptr += 1;
1772 else if (*tmp)
1773 ret = HTTP_DomainMatches( server, tmp );
1774 } while (ptr && !ret);
1775 return ret;
1778 /***********************************************************************
1779 * HTTP_DealWithProxy
1781 static BOOL HTTP_DealWithProxy(appinfo_t *hIC, http_session_t *session, http_request_t *request)
1783 static const WCHAR protoHttp[] = { 'h','t','t','p',0 };
1784 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1785 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1786 WCHAR buf[INTERNET_MAX_HOST_NAME_LENGTH];
1787 WCHAR protoProxy[INTERNET_MAX_URL_LENGTH];
1788 DWORD protoProxyLen = INTERNET_MAX_URL_LENGTH;
1789 WCHAR proxy[INTERNET_MAX_URL_LENGTH];
1790 static WCHAR szNul[] = { 0 };
1791 URL_COMPONENTSW UrlComponents;
1792 server_t *new_server;
1793 BOOL is_https;
1795 memset( &UrlComponents, 0, sizeof UrlComponents );
1796 UrlComponents.dwStructSize = sizeof UrlComponents;
1797 UrlComponents.lpszHostName = buf;
1798 UrlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
1800 if (!INTERNET_FindProxyForProtocol(hIC->proxy, protoHttp, protoProxy, &protoProxyLen))
1801 return FALSE;
1802 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1803 protoProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1804 sprintfW(proxy, szFormat, protoProxy);
1805 else
1806 strcpyW(proxy, protoProxy);
1807 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1808 return FALSE;
1809 if( UrlComponents.dwHostNameLength == 0 )
1810 return FALSE;
1812 if( !request->path )
1813 request->path = szNul;
1815 is_https = (UrlComponents.nScheme == INTERNET_SCHEME_HTTPS);
1816 if (is_https && UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1817 UrlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
1819 new_server = get_server(UrlComponents.lpszHostName, UrlComponents.nPort, is_https, TRUE);
1820 if(!new_server)
1821 return FALSE;
1823 request->proxy = new_server;
1825 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server->name), new_server->port);
1826 return TRUE;
1829 static DWORD HTTP_ResolveName(http_request_t *request)
1831 server_t *server = request->proxy ? request->proxy : request->server;
1832 socklen_t addr_len;
1833 void *addr;
1835 if(server->addr_len)
1836 return ERROR_SUCCESS;
1838 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1839 INTERNET_STATUS_RESOLVING_NAME,
1840 server->name,
1841 (strlenW(server->name)+1) * sizeof(WCHAR));
1843 addr_len = sizeof(server->addr);
1844 if (!GetAddress(server->name, server->port, (struct sockaddr *)&server->addr, &addr_len))
1845 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1847 switch(server->addr.ss_family) {
1848 case AF_INET:
1849 addr = &((struct sockaddr_in *)&server->addr)->sin_addr;
1850 break;
1851 case AF_INET6:
1852 addr = &((struct sockaddr_in6 *)&server->addr)->sin6_addr;
1853 break;
1854 default:
1855 WARN("unsupported family %d\n", server->addr.ss_family);
1856 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1859 server->addr_len = addr_len;
1860 inet_ntop(server->addr.ss_family, addr, server->addr_str, sizeof(server->addr_str));
1861 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1862 INTERNET_STATUS_NAME_RESOLVED,
1863 server->addr_str, strlen(server->addr_str)+1);
1865 TRACE("resolved %s to %s\n", debugstr_w(server->name), server->addr_str);
1866 return ERROR_SUCCESS;
1869 static BOOL HTTP_GetRequestURL(http_request_t *req, LPWSTR buf)
1871 static const WCHAR http[] = { 'h','t','t','p',':','/','/',0 };
1872 static const WCHAR https[] = { 'h','t','t','p','s',':','/','/',0 };
1873 static const WCHAR slash[] = { '/',0 };
1874 LPHTTPHEADERW host_header;
1875 LPCWSTR scheme;
1877 host_header = HTTP_GetHeader(req, hostW);
1878 if(!host_header)
1879 return FALSE;
1881 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1882 scheme = https;
1883 else
1884 scheme = http;
1885 strcpyW(buf, scheme);
1886 strcatW(buf, host_header->lpszValue);
1887 if (req->path[0] != '/')
1888 strcatW(buf, slash);
1889 strcatW(buf, req->path);
1890 return TRUE;
1894 /***********************************************************************
1895 * HTTPREQ_Destroy (internal)
1897 * Deallocate request handle
1900 static void HTTPREQ_Destroy(object_header_t *hdr)
1902 http_request_t *request = (http_request_t*) hdr;
1903 DWORD i;
1905 TRACE("\n");
1907 if(request->hCacheFile)
1908 CloseHandle(request->hCacheFile);
1909 if(request->req_file)
1910 req_file_release(request->req_file);
1912 request->read_section.DebugInfo->Spare[0] = 0;
1913 DeleteCriticalSection( &request->read_section );
1914 WININET_Release(&request->session->hdr);
1916 destroy_authinfo(request->authInfo);
1917 destroy_authinfo(request->proxyAuthInfo);
1919 if(request->server)
1920 server_release(request->server);
1921 if(request->proxy)
1922 server_release(request->proxy);
1924 heap_free(request->path);
1925 heap_free(request->verb);
1926 heap_free(request->version);
1927 heap_free(request->statusText);
1929 for (i = 0; i < request->nCustHeaders; i++)
1931 heap_free(request->custHeaders[i].lpszField);
1932 heap_free(request->custHeaders[i].lpszValue);
1934 destroy_data_stream(request->data_stream);
1935 heap_free(request->custHeaders);
1938 static void http_release_netconn(http_request_t *req, BOOL reuse)
1940 TRACE("%p %p %x\n",req, req->netconn, reuse);
1942 if(!is_valid_netconn(req->netconn))
1943 return;
1945 if(reuse && req->netconn->keep_alive) {
1946 BOOL run_collector;
1948 EnterCriticalSection(&connection_pool_cs);
1950 list_add_head(&req->netconn->server->conn_pool, &req->netconn->pool_entry);
1951 req->netconn->keep_until = GetTickCount64() + COLLECT_TIME;
1952 req->netconn = NULL;
1954 run_collector = !collector_running;
1955 collector_running = TRUE;
1957 LeaveCriticalSection(&connection_pool_cs);
1959 if(run_collector) {
1960 HANDLE thread = NULL;
1961 HMODULE module;
1963 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR*)WININET_hModule, &module);
1964 if(module)
1965 thread = CreateThread(NULL, 0, collect_connections_proc, NULL, 0, NULL);
1966 if(!thread) {
1967 EnterCriticalSection(&connection_pool_cs);
1968 collector_running = FALSE;
1969 LeaveCriticalSection(&connection_pool_cs);
1971 if(module)
1972 FreeLibrary(module);
1974 else
1975 CloseHandle(thread);
1977 return;
1980 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1981 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1983 close_netconn(req->netconn);
1985 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1986 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1989 static BOOL HTTP_KeepAlive(http_request_t *request)
1991 WCHAR szVersion[10];
1992 WCHAR szConnectionResponse[20];
1993 DWORD dwBufferSize = sizeof(szVersion);
1994 BOOL keepalive = FALSE;
1996 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
1997 * the connection is keep-alive by default */
1998 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_VERSION, szVersion, &dwBufferSize, NULL) == ERROR_SUCCESS
1999 && !strcmpiW(szVersion, g_szHttp1_1))
2001 keepalive = TRUE;
2004 dwBufferSize = sizeof(szConnectionResponse);
2005 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS
2006 || HTTP_HttpQueryInfoW(request, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS)
2008 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
2011 return keepalive;
2014 static void HTTPREQ_CloseConnection(object_header_t *hdr)
2016 http_request_t *req = (http_request_t*)hdr;
2018 http_release_netconn(req, drain_content(req, FALSE));
2021 static DWORD str_to_buffer(const WCHAR *str, void *buffer, DWORD *size, BOOL unicode)
2023 int len;
2024 if (unicode)
2026 WCHAR *buf = buffer;
2028 if (str) len = strlenW(str);
2029 else len = 0;
2030 if (*size < (len + 1) * sizeof(WCHAR))
2032 *size = (len + 1) * sizeof(WCHAR);
2033 return ERROR_INSUFFICIENT_BUFFER;
2035 if (str) strcpyW(buf, str);
2036 else buf[0] = 0;
2038 *size = len;
2039 return ERROR_SUCCESS;
2041 else
2043 char *buf = buffer;
2045 if (str) len = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
2046 else len = 1;
2047 if (*size < len)
2049 *size = len;
2050 return ERROR_INSUFFICIENT_BUFFER;
2052 if (str) WideCharToMultiByte(CP_ACP, 0, str, -1, buf, *size, NULL, NULL);
2053 else buf[0] = 0;
2055 *size = len - 1;
2056 return ERROR_SUCCESS;
2060 static DWORD HTTPREQ_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2062 http_request_t *req = (http_request_t*)hdr;
2064 switch(option) {
2065 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO:
2067 INTERNET_DIAGNOSTIC_SOCKET_INFO *info = buffer;
2069 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2071 if (*size < sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO))
2072 return ERROR_INSUFFICIENT_BUFFER;
2073 *size = sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO);
2074 /* FIXME: can't get a SOCKET from our connection since we don't use
2075 * winsock
2077 info->Socket = 0;
2078 /* FIXME: get source port from req->netConnection */
2079 info->SourcePort = 0;
2080 info->DestPort = req->server->port;
2081 info->Flags = 0;
2082 if (HTTP_KeepAlive(req))
2083 info->Flags |= IDSI_FLAG_KEEP_ALIVE;
2084 if (req->proxy)
2085 info->Flags |= IDSI_FLAG_PROXY;
2086 if (is_valid_netconn(req->netconn) && req->netconn->secure)
2087 info->Flags |= IDSI_FLAG_SECURE;
2089 return ERROR_SUCCESS;
2092 case 98:
2093 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2094 /* fall through */
2095 case INTERNET_OPTION_SECURITY_FLAGS:
2097 DWORD flags;
2099 if (*size < sizeof(ULONG))
2100 return ERROR_INSUFFICIENT_BUFFER;
2102 *size = sizeof(DWORD);
2103 flags = is_valid_netconn(req->netconn) ? req->netconn->security_flags : req->security_flags | req->server->security_flags;
2104 *(DWORD *)buffer = flags;
2106 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags);
2107 return ERROR_SUCCESS;
2110 case INTERNET_OPTION_HANDLE_TYPE:
2111 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2113 if (*size < sizeof(ULONG))
2114 return ERROR_INSUFFICIENT_BUFFER;
2116 *size = sizeof(DWORD);
2117 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
2118 return ERROR_SUCCESS;
2120 case INTERNET_OPTION_URL: {
2121 WCHAR url[INTERNET_MAX_URL_LENGTH];
2122 HTTPHEADERW *host;
2124 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
2126 TRACE("INTERNET_OPTION_URL\n");
2128 host = HTTP_GetHeader(req, hostW);
2129 strcpyW(url, httpW);
2130 strcatW(url, host->lpszValue);
2131 strcatW(url, req->path);
2133 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
2134 return str_to_buffer(url, buffer, size, unicode);
2136 case INTERNET_OPTION_USER_AGENT:
2137 return str_to_buffer(req->session->appInfo->agent, buffer, size, unicode);
2138 case INTERNET_OPTION_USERNAME:
2139 return str_to_buffer(req->session->userName, buffer, size, unicode);
2140 case INTERNET_OPTION_PASSWORD:
2141 return str_to_buffer(req->session->password, buffer, size, unicode);
2142 case INTERNET_OPTION_PROXY_USERNAME:
2143 return str_to_buffer(req->session->appInfo->proxyUsername, buffer, size, unicode);
2144 case INTERNET_OPTION_PROXY_PASSWORD:
2145 return str_to_buffer(req->session->appInfo->proxyPassword, buffer, size, unicode);
2147 case INTERNET_OPTION_CACHE_TIMESTAMPS: {
2148 INTERNET_CACHE_ENTRY_INFOW *info;
2149 INTERNET_CACHE_TIMESTAMPS *ts = buffer;
2150 WCHAR url[INTERNET_MAX_URL_LENGTH];
2151 DWORD nbytes, error;
2152 BOOL ret;
2154 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2156 if (*size < sizeof(*ts))
2158 *size = sizeof(*ts);
2159 return ERROR_INSUFFICIENT_BUFFER;
2161 nbytes = 0;
2162 HTTP_GetRequestURL(req, url);
2163 ret = GetUrlCacheEntryInfoW(url, NULL, &nbytes);
2164 error = GetLastError();
2165 if (!ret && error == ERROR_INSUFFICIENT_BUFFER)
2167 if (!(info = heap_alloc(nbytes)))
2168 return ERROR_OUTOFMEMORY;
2170 GetUrlCacheEntryInfoW(url, info, &nbytes);
2172 ts->ftExpires = info->ExpireTime;
2173 ts->ftLastModified = info->LastModifiedTime;
2175 heap_free(info);
2176 *size = sizeof(*ts);
2177 return ERROR_SUCCESS;
2179 return error;
2182 case INTERNET_OPTION_DATAFILE_NAME: {
2183 DWORD req_size;
2185 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2187 if(!req->req_file) {
2188 *size = 0;
2189 return ERROR_INTERNET_ITEM_NOT_FOUND;
2192 if(unicode) {
2193 req_size = (lstrlenW(req->req_file->file_name)+1) * sizeof(WCHAR);
2194 if(*size < req_size)
2195 return ERROR_INSUFFICIENT_BUFFER;
2197 *size = req_size;
2198 memcpy(buffer, req->req_file->file_name, *size);
2199 return ERROR_SUCCESS;
2200 }else {
2201 req_size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name, -1, NULL, 0, NULL, NULL);
2202 if (req_size > *size)
2203 return ERROR_INSUFFICIENT_BUFFER;
2205 *size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name,
2206 -1, buffer, *size, NULL, NULL);
2207 return ERROR_SUCCESS;
2211 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
2212 PCCERT_CONTEXT context;
2214 if(!req->netconn)
2215 return ERROR_INTERNET_INVALID_OPERATION;
2217 if(*size < sizeof(INTERNET_CERTIFICATE_INFOA)) {
2218 *size = sizeof(INTERNET_CERTIFICATE_INFOA);
2219 return ERROR_INSUFFICIENT_BUFFER;
2222 context = (PCCERT_CONTEXT)NETCON_GetCert(req->netconn);
2223 if(context) {
2224 INTERNET_CERTIFICATE_INFOA *info = (INTERNET_CERTIFICATE_INFOA*)buffer;
2225 DWORD len;
2227 memset(info, 0, sizeof(*info));
2228 info->ftExpiry = context->pCertInfo->NotAfter;
2229 info->ftStart = context->pCertInfo->NotBefore;
2230 len = CertNameToStrA(context->dwCertEncodingType,
2231 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2232 info->lpszSubjectInfo = LocalAlloc(0, len);
2233 if(info->lpszSubjectInfo)
2234 CertNameToStrA(context->dwCertEncodingType,
2235 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2236 info->lpszSubjectInfo, len);
2237 len = CertNameToStrA(context->dwCertEncodingType,
2238 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2239 info->lpszIssuerInfo = LocalAlloc(0, len);
2240 if(info->lpszIssuerInfo)
2241 CertNameToStrA(context->dwCertEncodingType,
2242 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2243 info->lpszIssuerInfo, len);
2244 info->dwKeySize = NETCON_GetCipherStrength(req->netconn);
2245 CertFreeCertificateContext(context);
2246 return ERROR_SUCCESS;
2248 return ERROR_NOT_SUPPORTED;
2250 case INTERNET_OPTION_CONNECT_TIMEOUT:
2251 if (*size < sizeof(DWORD))
2252 return ERROR_INSUFFICIENT_BUFFER;
2254 *size = sizeof(DWORD);
2255 *(DWORD *)buffer = req->connect_timeout;
2256 return ERROR_SUCCESS;
2257 case INTERNET_OPTION_REQUEST_FLAGS: {
2258 DWORD flags = 0;
2260 if (*size < sizeof(DWORD))
2261 return ERROR_INSUFFICIENT_BUFFER;
2263 /* FIXME: Add support for:
2264 * INTERNET_REQFLAG_FROM_CACHE
2265 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2268 if(req->proxy)
2269 flags |= INTERNET_REQFLAG_VIA_PROXY;
2270 if(!req->status_code)
2271 flags |= INTERNET_REQFLAG_NO_HEADERS;
2273 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags);
2275 *size = sizeof(DWORD);
2276 *(DWORD*)buffer = flags;
2277 return ERROR_SUCCESS;
2281 return INET_QueryOption(hdr, option, buffer, size, unicode);
2284 static DWORD HTTPREQ_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
2286 http_request_t *req = (http_request_t*)hdr;
2288 switch(option) {
2289 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2290 TRACE("Undocumented option 99\n");
2292 if (!buffer || size != sizeof(DWORD))
2293 return ERROR_INVALID_PARAMETER;
2294 if(*(DWORD*)buffer & ~SECURITY_SET_MASK)
2295 return ERROR_INTERNET_OPTION_NOT_SETTABLE;
2297 /* fall through */
2298 case INTERNET_OPTION_SECURITY_FLAGS:
2300 DWORD flags;
2302 if (!buffer || size != sizeof(DWORD))
2303 return ERROR_INVALID_PARAMETER;
2304 flags = *(DWORD *)buffer;
2305 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags);
2306 flags &= SECURITY_SET_MASK;
2307 req->security_flags |= flags;
2308 if(is_valid_netconn(req->netconn))
2309 req->netconn->security_flags |= flags;
2310 return ERROR_SUCCESS;
2312 case INTERNET_OPTION_CONNECT_TIMEOUT:
2313 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2314 req->connect_timeout = *(DWORD *)buffer;
2315 return ERROR_SUCCESS;
2317 case INTERNET_OPTION_SEND_TIMEOUT:
2318 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2319 req->send_timeout = *(DWORD *)buffer;
2320 return ERROR_SUCCESS;
2322 case INTERNET_OPTION_RECEIVE_TIMEOUT:
2323 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2324 req->receive_timeout = *(DWORD *)buffer;
2325 return ERROR_SUCCESS;
2327 case INTERNET_OPTION_USERNAME:
2328 heap_free(req->session->userName);
2329 if (!(req->session->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2330 return ERROR_SUCCESS;
2332 case INTERNET_OPTION_PASSWORD:
2333 heap_free(req->session->password);
2334 if (!(req->session->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2335 return ERROR_SUCCESS;
2337 case INTERNET_OPTION_PROXY_USERNAME:
2338 heap_free(req->session->appInfo->proxyUsername);
2339 if (!(req->session->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2340 return ERROR_SUCCESS;
2342 case INTERNET_OPTION_PROXY_PASSWORD:
2343 heap_free(req->session->appInfo->proxyPassword);
2344 if (!(req->session->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2345 return ERROR_SUCCESS;
2347 case INTERNET_OPTION_HTTP_DECODING:
2348 if(size != sizeof(BOOL))
2349 return ERROR_INVALID_PARAMETER;
2350 req->decoding = *(BOOL*)buffer;
2351 return ERROR_SUCCESS;
2354 return INET_SetOption(hdr, option, buffer, size);
2357 static void commit_cache_entry(http_request_t *req)
2359 WCHAR url[INTERNET_MAX_URL_LENGTH];
2361 TRACE("%p\n", req);
2363 CloseHandle(req->hCacheFile);
2364 req->hCacheFile = NULL;
2366 if(HTTP_GetRequestURL(req, url)) {
2367 WCHAR *header;
2368 DWORD header_len;
2369 BOOL res;
2371 header = build_response_header(req, TRUE);
2372 header_len = (header ? strlenW(header) : 0);
2373 res = CommitUrlCacheEntryW(url, req->req_file->file_name, req->expires,
2374 req->last_modified, NORMAL_CACHE_ENTRY,
2375 header, header_len, NULL, 0);
2376 if(res)
2377 req->req_file->is_committed = TRUE;
2378 else
2379 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2380 heap_free(header);
2384 static void create_cache_entry(http_request_t *req)
2386 static const WCHAR no_cacheW[] = {'n','o','-','c','a','c','h','e',0};
2387 static const WCHAR no_storeW[] = {'n','o','-','s','t','o','r','e',0};
2389 WCHAR url[INTERNET_MAX_URL_LENGTH];
2390 WCHAR file_name[MAX_PATH+1];
2391 BOOL b = TRUE;
2393 /* FIXME: We should free previous cache file earlier */
2394 if(req->req_file) {
2395 req_file_release(req->req_file);
2396 req->req_file = NULL;
2398 if(req->hCacheFile) {
2399 CloseHandle(req->hCacheFile);
2400 req->hCacheFile = NULL;
2403 if(req->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE)
2404 b = FALSE;
2406 if(b) {
2407 int header_idx = HTTP_GetCustomHeaderIndex(req, szCache_Control, 0, FALSE);
2408 if(header_idx != -1) {
2409 WCHAR *ptr;
2411 for(ptr=req->custHeaders[header_idx].lpszValue; *ptr; ) {
2412 WCHAR *end;
2414 while(*ptr==' ' || *ptr=='\t')
2415 ptr++;
2417 end = strchrW(ptr, ',');
2418 if(!end)
2419 end = ptr + strlenW(ptr);
2421 if(!strncmpiW(ptr, no_cacheW, sizeof(no_cacheW)/sizeof(*no_cacheW)-1)
2422 || !strncmpiW(ptr, no_storeW, sizeof(no_storeW)/sizeof(*no_storeW)-1)) {
2423 b = FALSE;
2424 break;
2427 ptr = end;
2428 if(*ptr == ',')
2429 ptr++;
2434 if(!b) {
2435 if(!(req->hdr.dwFlags & INTERNET_FLAG_NEED_FILE))
2436 return;
2438 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2441 b = HTTP_GetRequestURL(req, url);
2442 if(!b) {
2443 WARN("Could not get URL\n");
2444 return;
2447 b = CreateUrlCacheEntryW(url, req->contentLength == ~0u ? 0 : req->contentLength, NULL, file_name, 0);
2448 if(!b) {
2449 WARN("Could not create cache entry: %08x\n", GetLastError());
2450 return;
2453 create_req_file(file_name, &req->req_file);
2455 req->hCacheFile = CreateFileW(file_name, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
2456 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2457 if(req->hCacheFile == INVALID_HANDLE_VALUE) {
2458 WARN("Could not create file: %u\n", GetLastError());
2459 req->hCacheFile = NULL;
2460 return;
2463 if(req->read_size) {
2464 DWORD written;
2466 b = WriteFile(req->hCacheFile, req->read_buf+req->read_pos, req->read_size, &written, NULL);
2467 if(!b)
2468 FIXME("WriteFile failed: %u\n", GetLastError());
2470 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2471 commit_cache_entry(req);
2475 /* read some more data into the read buffer (the read section must be held) */
2476 static DWORD read_more_data( http_request_t *req, int maxlen )
2478 DWORD res;
2479 int len;
2481 if (req->read_pos)
2483 /* move existing data to the start of the buffer */
2484 if(req->read_size)
2485 memmove( req->read_buf, req->read_buf + req->read_pos, req->read_size );
2486 req->read_pos = 0;
2489 if (maxlen == -1) maxlen = sizeof(req->read_buf);
2491 res = NETCON_recv( req->netconn, req->read_buf + req->read_size,
2492 maxlen - req->read_size, BLOCKING_ALLOW, &len );
2493 if(res == ERROR_SUCCESS)
2494 req->read_size += len;
2496 return res;
2499 /* remove some amount of data from the read buffer (the read section must be held) */
2500 static void remove_data( http_request_t *req, int count )
2502 if (!(req->read_size -= count)) req->read_pos = 0;
2503 else req->read_pos += count;
2506 static DWORD read_line( http_request_t *req, LPSTR buffer, DWORD *len )
2508 int count, bytes_read, pos = 0;
2509 DWORD res;
2511 EnterCriticalSection( &req->read_section );
2512 for (;;)
2514 BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
2516 if (eol)
2518 count = eol - (req->read_buf + req->read_pos);
2519 bytes_read = count + 1;
2521 else count = bytes_read = req->read_size;
2523 count = min( count, *len - pos );
2524 memcpy( buffer + pos, req->read_buf + req->read_pos, count );
2525 pos += count;
2526 remove_data( req, bytes_read );
2527 if (eol) break;
2529 if ((res = read_more_data( req, -1 )))
2531 WARN( "read failed %u\n", res );
2532 LeaveCriticalSection( &req->read_section );
2533 return res;
2535 if (!req->read_size)
2537 *len = 0;
2538 TRACE( "returning empty string\n" );
2539 LeaveCriticalSection( &req->read_section );
2540 return ERROR_SUCCESS;
2543 LeaveCriticalSection( &req->read_section );
2545 if (pos < *len)
2547 if (pos && buffer[pos - 1] == '\r') pos--;
2548 *len = pos + 1;
2550 buffer[*len - 1] = 0;
2551 TRACE( "returning %s\n", debugstr_a(buffer));
2552 return ERROR_SUCCESS;
2555 /* check if we have reached the end of the data to read (the read section must be held) */
2556 static BOOL end_of_read_data( http_request_t *req )
2558 return !req->read_size && req->data_stream->vtbl->end_of_data(req->data_stream, req);
2561 static DWORD read_http_stream(http_request_t *req, BYTE *buf, DWORD size, DWORD *read, blocking_mode_t blocking_mode)
2563 DWORD res;
2565 res = req->data_stream->vtbl->read(req->data_stream, req, buf, size, read, blocking_mode);
2566 assert(*read <= size);
2568 if(req->hCacheFile) {
2569 if(*read) {
2570 BOOL bres;
2571 DWORD written;
2573 bres = WriteFile(req->hCacheFile, buf, *read, &written, NULL);
2574 if(!bres)
2575 FIXME("WriteFile failed: %u\n", GetLastError());
2578 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2579 commit_cache_entry(req);
2582 return res;
2585 /* fetch some more data into the read buffer (the read section must be held) */
2586 static DWORD refill_read_buffer(http_request_t *req, blocking_mode_t blocking_mode, DWORD *read_bytes)
2588 DWORD res, read=0;
2590 if(req->read_size == sizeof(req->read_buf))
2591 return ERROR_SUCCESS;
2593 if(req->read_pos) {
2594 if(req->read_size)
2595 memmove(req->read_buf, req->read_buf+req->read_pos, req->read_size);
2596 req->read_pos = 0;
2599 res = read_http_stream(req, req->read_buf+req->read_size, sizeof(req->read_buf) - req->read_size,
2600 &read, blocking_mode);
2601 req->read_size += read;
2603 TRACE("read %u bytes, read_size %u\n", read, req->read_size);
2604 if(read_bytes)
2605 *read_bytes = read;
2606 return res;
2609 /* return the size of data available to be read immediately (the read section must be held) */
2610 static DWORD get_avail_data( http_request_t *req )
2612 return req->read_size + req->data_stream->vtbl->get_avail_data(req->data_stream, req);
2615 static DWORD netconn_get_avail_data(data_stream_t *stream, http_request_t *req)
2617 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2618 DWORD avail = 0;
2620 if(is_valid_netconn(req->netconn))
2621 NETCON_query_data_available(req->netconn, &avail);
2622 return netconn_stream->content_length == ~0u
2623 ? avail
2624 : min(avail, netconn_stream->content_length-netconn_stream->content_read);
2627 static BOOL netconn_end_of_data(data_stream_t *stream, http_request_t *req)
2629 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2630 return netconn_stream->content_read == netconn_stream->content_length || !is_valid_netconn(req->netconn);
2633 static DWORD netconn_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2634 DWORD *read, blocking_mode_t blocking_mode)
2636 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2637 DWORD res = ERROR_SUCCESS;
2638 int len = 0;
2640 size = min(size, netconn_stream->content_length-netconn_stream->content_read);
2642 if(size && is_valid_netconn(req->netconn)) {
2643 if((res = NETCON_recv(req->netconn, buf, size, blocking_mode, &len))) {
2644 len = 0;
2645 if(blocking_mode == BLOCKING_DISALLOW && res == WSAEWOULDBLOCK)
2646 res = ERROR_SUCCESS;
2647 else
2648 netconn_stream->content_length = netconn_stream->content_read;
2649 }else if(!len) {
2650 netconn_stream->content_length = netconn_stream->content_read;
2654 netconn_stream->content_read += *read = len;
2655 TRACE("read %u bytes\n", len);
2656 return res;
2659 static BOOL netconn_drain_content(data_stream_t *stream, http_request_t *req)
2661 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2662 BYTE buf[1024];
2663 int len;
2665 if(netconn_end_of_data(stream, req))
2666 return TRUE;
2668 do {
2669 if(NETCON_recv(req->netconn, buf, sizeof(buf), BLOCKING_DISALLOW, &len) != ERROR_SUCCESS)
2670 return FALSE;
2672 netconn_stream->content_read += len;
2673 }while(netconn_stream->content_read < netconn_stream->content_length);
2675 return TRUE;
2678 static void netconn_destroy(data_stream_t *stream)
2682 static const data_stream_vtbl_t netconn_stream_vtbl = {
2683 netconn_get_avail_data,
2684 netconn_end_of_data,
2685 netconn_read,
2686 netconn_drain_content,
2687 netconn_destroy
2690 /* read some more data into the read buffer (the read section must be held) */
2691 static DWORD read_more_chunked_data(chunked_stream_t *stream, http_request_t *req, int maxlen)
2693 DWORD res;
2694 int len;
2696 assert(!stream->end_of_data);
2698 if (stream->buf_pos)
2700 /* move existing data to the start of the buffer */
2701 if(stream->buf_size)
2702 memmove(stream->buf, stream->buf + stream->buf_pos, stream->buf_size);
2703 stream->buf_pos = 0;
2706 if (maxlen == -1) maxlen = sizeof(stream->buf);
2708 res = NETCON_recv( req->netconn, stream->buf + stream->buf_size,
2709 maxlen - stream->buf_size, BLOCKING_ALLOW, &len );
2710 if(res == ERROR_SUCCESS)
2711 stream->buf_size += len;
2713 return res;
2716 /* remove some amount of data from the read buffer (the read section must be held) */
2717 static void remove_chunked_data(chunked_stream_t *stream, int count)
2719 if (!(stream->buf_size -= count)) stream->buf_pos = 0;
2720 else stream->buf_pos += count;
2723 /* discard data contents until we reach end of line (the read section must be held) */
2724 static DWORD discard_chunked_eol(chunked_stream_t *stream, http_request_t *req)
2726 DWORD res;
2730 BYTE *eol = memchr(stream->buf + stream->buf_pos, '\n', stream->buf_size);
2731 if (eol)
2733 remove_chunked_data(stream, (eol + 1) - (stream->buf + stream->buf_pos));
2734 break;
2736 stream->buf_pos = stream->buf_size = 0; /* discard everything */
2737 if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
2738 } while (stream->buf_size);
2739 return ERROR_SUCCESS;
2742 /* read the size of the next chunk (the read section must be held) */
2743 static DWORD start_next_chunk(chunked_stream_t *stream, http_request_t *req)
2745 DWORD chunk_size = 0, res;
2747 assert(!stream->chunk_size || stream->chunk_size == ~0u);
2749 if (stream->end_of_data) return ERROR_SUCCESS;
2751 /* read terminator for the previous chunk */
2752 if(!stream->chunk_size && (res = discard_chunked_eol(stream, req)) != ERROR_SUCCESS)
2753 return res;
2755 for (;;)
2757 while (stream->buf_size)
2759 char ch = stream->buf[stream->buf_pos];
2760 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
2761 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
2762 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
2763 else if (ch == ';' || ch == '\r' || ch == '\n')
2765 TRACE( "reading %u byte chunk\n", chunk_size );
2766 stream->chunk_size = chunk_size;
2767 if (req->contentLength == ~0u) req->contentLength = chunk_size;
2768 else req->contentLength += chunk_size;
2770 if (!chunk_size) stream->end_of_data = TRUE;
2771 return discard_chunked_eol(stream, req);
2773 remove_chunked_data(stream, 1);
2775 if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
2776 if (!stream->buf_size)
2778 stream->chunk_size = 0;
2779 return ERROR_SUCCESS;
2784 static DWORD chunked_get_avail_data(data_stream_t *stream, http_request_t *req)
2786 /* Allow reading only from read buffer */
2787 return 0;
2790 static BOOL chunked_end_of_data(data_stream_t *stream, http_request_t *req)
2792 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2793 return chunked_stream->end_of_data;
2796 static DWORD chunked_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2797 DWORD *read, blocking_mode_t blocking_mode)
2799 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2800 DWORD read_bytes = 0, ret_read = 0, res = ERROR_SUCCESS;
2802 if(!chunked_stream->chunk_size || chunked_stream->chunk_size == ~0u) {
2803 res = start_next_chunk(chunked_stream, req);
2804 if(res != ERROR_SUCCESS)
2805 return res;
2808 while(size && chunked_stream->chunk_size && !chunked_stream->end_of_data) {
2809 if(chunked_stream->buf_size) {
2810 read_bytes = min(size, min(chunked_stream->buf_size, chunked_stream->chunk_size));
2812 /* this could block */
2813 if(blocking_mode == BLOCKING_DISALLOW && read_bytes == chunked_stream->chunk_size)
2814 break;
2816 memcpy(buf+ret_read, chunked_stream->buf+chunked_stream->buf_pos, read_bytes);
2817 remove_chunked_data(chunked_stream, read_bytes);
2818 }else {
2819 read_bytes = min(size, chunked_stream->chunk_size);
2821 if(blocking_mode == BLOCKING_DISALLOW) {
2822 DWORD avail;
2824 if(!is_valid_netconn(req->netconn) || !NETCON_query_data_available(req->netconn, &avail) || !avail)
2825 break;
2826 if(read_bytes > avail)
2827 read_bytes = avail;
2829 /* this could block */
2830 if(read_bytes == chunked_stream->chunk_size)
2831 break;
2834 res = NETCON_recv(req->netconn, (char *)buf+ret_read, read_bytes, BLOCKING_ALLOW, (int*)&read_bytes);
2835 if(res != ERROR_SUCCESS)
2836 break;
2839 chunked_stream->chunk_size -= read_bytes;
2840 size -= read_bytes;
2841 ret_read += read_bytes;
2842 if(size && !chunked_stream->chunk_size) {
2843 assert(blocking_mode != BLOCKING_DISALLOW);
2844 res = start_next_chunk(chunked_stream, req);
2845 if(res != ERROR_SUCCESS)
2846 break;
2849 if(blocking_mode == BLOCKING_ALLOW)
2850 blocking_mode = BLOCKING_DISALLOW;
2853 TRACE("read %u bytes\n", ret_read);
2854 *read = ret_read;
2855 return res;
2858 static BOOL chunked_drain_content(data_stream_t *stream, http_request_t *req)
2860 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2862 remove_chunked_data(chunked_stream, chunked_stream->buf_size);
2863 return chunked_stream->end_of_data;
2866 static void chunked_destroy(data_stream_t *stream)
2868 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2869 heap_free(chunked_stream);
2872 static const data_stream_vtbl_t chunked_stream_vtbl = {
2873 chunked_get_avail_data,
2874 chunked_end_of_data,
2875 chunked_read,
2876 chunked_drain_content,
2877 chunked_destroy
2880 /* set the request content length based on the headers */
2881 static DWORD set_content_length(http_request_t *request)
2883 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
2884 WCHAR encoding[20];
2885 DWORD size;
2887 if(request->status_code == HTTP_STATUS_NO_CONTENT) {
2888 request->contentLength = request->netconn_stream.content_length = 0;
2889 return ERROR_SUCCESS;
2892 size = sizeof(request->contentLength);
2893 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2894 &request->contentLength, &size, NULL) != ERROR_SUCCESS)
2895 request->contentLength = ~0u;
2896 request->netconn_stream.content_length = request->contentLength;
2897 request->netconn_stream.content_read = request->read_size;
2899 size = sizeof(encoding);
2900 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) == ERROR_SUCCESS &&
2901 !strcmpiW(encoding, szChunked))
2903 chunked_stream_t *chunked_stream;
2905 chunked_stream = heap_alloc(sizeof(*chunked_stream));
2906 if(!chunked_stream)
2907 return ERROR_OUTOFMEMORY;
2909 chunked_stream->data_stream.vtbl = &chunked_stream_vtbl;
2910 chunked_stream->buf_size = chunked_stream->buf_pos = 0;
2911 chunked_stream->chunk_size = ~0u;
2912 chunked_stream->end_of_data = FALSE;
2914 if(request->read_size) {
2915 memcpy(chunked_stream->buf, request->read_buf+request->read_pos, request->read_size);
2916 chunked_stream->buf_size = request->read_size;
2917 request->read_size = request->read_pos = 0;
2920 request->data_stream = &chunked_stream->data_stream;
2921 request->contentLength = ~0u;
2922 request->read_chunked = TRUE;
2925 if(request->decoding) {
2926 int encoding_idx;
2928 static const WCHAR deflateW[] = {'d','e','f','l','a','t','e',0};
2929 static const WCHAR gzipW[] = {'g','z','i','p',0};
2931 encoding_idx = HTTP_GetCustomHeaderIndex(request, szContent_Encoding, 0, FALSE);
2932 if(encoding_idx != -1) {
2933 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, gzipW)) {
2934 HTTP_DeleteCustomHeader(request, encoding_idx);
2935 return init_gzip_stream(request, TRUE);
2937 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, deflateW)) {
2938 HTTP_DeleteCustomHeader(request, encoding_idx);
2939 return init_gzip_stream(request, FALSE);
2944 return ERROR_SUCCESS;
2947 static void send_request_complete(http_request_t *req, DWORD_PTR result, DWORD error)
2949 INTERNET_ASYNC_RESULT iar;
2951 iar.dwResult = result;
2952 iar.dwError = error;
2954 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2955 sizeof(INTERNET_ASYNC_RESULT));
2958 static void HTTP_ReceiveRequestData(http_request_t *req, BOOL first_notif, DWORD *ret_size)
2960 DWORD res, read = 0, avail = 0;
2961 blocking_mode_t mode;
2963 TRACE("%p\n", req);
2965 EnterCriticalSection( &req->read_section );
2967 mode = first_notif && req->read_size ? BLOCKING_DISALLOW : BLOCKING_ALLOW;
2968 res = refill_read_buffer(req, mode, &read);
2969 if(res == ERROR_SUCCESS)
2970 avail = get_avail_data(req);
2972 LeaveCriticalSection( &req->read_section );
2974 if(res != ERROR_SUCCESS || (mode != BLOCKING_DISALLOW && !read)) {
2975 WARN("res %u read %u, closing connection\n", res, read);
2976 http_release_netconn(req, FALSE);
2979 if(res != ERROR_SUCCESS) {
2980 send_request_complete(req, 0, res);
2981 return;
2984 if(ret_size)
2985 *ret_size = avail;
2986 if(first_notif)
2987 avail = 0;
2989 send_request_complete(req, req->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)req->hdr.hInternet : 1, avail);
2992 /* read data from the http connection (the read section must be held) */
2993 static DWORD HTTPREQ_Read(http_request_t *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
2995 DWORD current_read = 0, ret_read = 0;
2996 blocking_mode_t blocking_mode;
2997 DWORD res = ERROR_SUCCESS;
2999 blocking_mode = req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC ? BLOCKING_ALLOW : BLOCKING_WAITALL;
3001 EnterCriticalSection( &req->read_section );
3003 if(req->read_size) {
3004 ret_read = min(size, req->read_size);
3005 memcpy(buffer, req->read_buf+req->read_pos, ret_read);
3006 req->read_size -= ret_read;
3007 req->read_pos += ret_read;
3008 if(blocking_mode == BLOCKING_ALLOW)
3009 blocking_mode = BLOCKING_DISALLOW;
3012 if(ret_read < size) {
3013 res = read_http_stream(req, (BYTE*)buffer+ret_read, size-ret_read, &current_read, blocking_mode);
3014 ret_read += current_read;
3017 LeaveCriticalSection( &req->read_section );
3019 *read = ret_read;
3020 TRACE( "retrieved %u bytes (%u)\n", ret_read, req->contentLength );
3022 if(size && !ret_read)
3023 http_release_netconn(req, res == ERROR_SUCCESS);
3025 return res;
3028 static BOOL drain_content(http_request_t *req, BOOL blocking)
3030 BOOL ret;
3032 if(!is_valid_netconn(req->netconn) || req->contentLength == -1)
3033 return FALSE;
3035 if(!strcmpW(req->verb, szHEAD))
3036 return TRUE;
3038 if(!blocking)
3039 return req->data_stream->vtbl->drain_content(req->data_stream, req);
3041 EnterCriticalSection( &req->read_section );
3043 while(1) {
3044 DWORD bytes_read, res;
3045 BYTE buf[4096];
3047 res = HTTPREQ_Read(req, buf, sizeof(buf), &bytes_read, TRUE);
3048 if(res != ERROR_SUCCESS) {
3049 ret = FALSE;
3050 break;
3052 if(!bytes_read) {
3053 ret = TRUE;
3054 break;
3058 LeaveCriticalSection( &req->read_section );
3059 return ret;
3062 static DWORD HTTPREQ_ReadFile(object_header_t *hdr, void *buffer, DWORD size, DWORD *read)
3064 http_request_t *req = (http_request_t*)hdr;
3065 DWORD res;
3067 EnterCriticalSection( &req->read_section );
3068 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3069 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3071 res = HTTPREQ_Read(req, buffer, size, read, TRUE);
3072 if(res == ERROR_SUCCESS)
3073 res = hdr->dwError;
3074 LeaveCriticalSection( &req->read_section );
3076 return res;
3079 typedef struct {
3080 task_header_t hdr;
3081 void *buf;
3082 DWORD size;
3083 DWORD *ret_read;
3084 } read_file_ex_task_t;
3086 static void AsyncReadFileExProc(task_header_t *hdr)
3088 read_file_ex_task_t *task = (read_file_ex_task_t*)hdr;
3089 http_request_t *req = (http_request_t*)task->hdr.hdr;
3090 DWORD res;
3092 TRACE("INTERNETREADFILEEXW %p\n", task->hdr.hdr);
3094 res = HTTPREQ_Read(req, task->buf, task->size, task->ret_read, TRUE);
3095 send_request_complete(req, res == ERROR_SUCCESS, res);
3098 static DWORD HTTPREQ_ReadFileEx(object_header_t *hdr, void *buf, DWORD size, DWORD *ret_read,
3099 DWORD flags, DWORD_PTR context)
3102 http_request_t *req = (http_request_t*)hdr;
3103 DWORD res, read, cread, error = ERROR_SUCCESS;
3105 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3106 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3108 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3110 if (hdr->dwFlags & INTERNET_FLAG_ASYNC)
3112 read_file_ex_task_t *task;
3114 if (TryEnterCriticalSection( &req->read_section ))
3116 if (get_avail_data(req))
3118 res = HTTPREQ_Read(req, buf, size, &read, FALSE);
3119 LeaveCriticalSection( &req->read_section );
3120 goto done;
3122 LeaveCriticalSection( &req->read_section );
3125 task = alloc_async_task(&req->hdr, AsyncReadFileExProc, sizeof(*task));
3126 task->buf = buf;
3127 task->size = size;
3128 task->ret_read = ret_read;
3130 INTERNET_AsyncCall(&task->hdr);
3132 return ERROR_IO_PENDING;
3135 read = 0;
3137 EnterCriticalSection( &req->read_section );
3138 if(hdr->dwError == ERROR_SUCCESS)
3139 hdr->dwError = INTERNET_HANDLE_IN_USE;
3140 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3141 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3143 while(1) {
3144 res = HTTPREQ_Read(req, (char*)buf+read, size-read, &cread, !(flags & IRF_NO_WAIT));
3145 if(res != ERROR_SUCCESS)
3146 break;
3148 read += cread;
3149 if(read == size || end_of_read_data(req))
3150 break;
3152 LeaveCriticalSection( &req->read_section );
3154 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3155 &cread, sizeof(cread));
3156 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
3157 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3159 EnterCriticalSection( &req->read_section );
3162 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3163 hdr->dwError = ERROR_SUCCESS;
3164 else
3165 error = hdr->dwError;
3167 LeaveCriticalSection( &req->read_section );
3169 done:
3170 *ret_read = read;
3171 if (res == ERROR_SUCCESS) {
3172 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3173 &read, sizeof(read));
3176 return res==ERROR_SUCCESS ? error : res;
3179 static DWORD HTTPREQ_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
3181 DWORD res;
3182 http_request_t *request = (http_request_t*)hdr;
3184 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3186 *written = 0;
3187 res = NETCON_send(request->netconn, buffer, size, 0, (LPINT)written);
3188 if (res == ERROR_SUCCESS)
3189 request->bytesWritten += *written;
3191 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
3192 return res;
3195 typedef struct {
3196 task_header_t hdr;
3197 DWORD *ret_size;
3198 } http_data_available_task_t;
3200 static void AsyncQueryDataAvailableProc(task_header_t *hdr)
3202 http_data_available_task_t *task = (http_data_available_task_t*)hdr;
3204 HTTP_ReceiveRequestData((http_request_t*)task->hdr.hdr, FALSE, task->ret_size);
3207 static DWORD HTTPREQ_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
3209 http_request_t *req = (http_request_t*)hdr;
3211 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
3213 if (req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3215 http_data_available_task_t *task;
3217 /* never wait, if we can't enter the section we queue an async request right away */
3218 if (TryEnterCriticalSection( &req->read_section ))
3220 refill_read_buffer(req, BLOCKING_DISALLOW, NULL);
3221 if ((*available = get_avail_data( req ))) goto done;
3222 if (end_of_read_data( req )) goto done;
3223 LeaveCriticalSection( &req->read_section );
3226 task = alloc_async_task(&req->hdr, AsyncQueryDataAvailableProc, sizeof(*task));
3227 task->ret_size = available;
3228 INTERNET_AsyncCall(&task->hdr);
3229 return ERROR_IO_PENDING;
3232 EnterCriticalSection( &req->read_section );
3234 if (!(*available = get_avail_data( req )) && !end_of_read_data( req ))
3236 refill_read_buffer( req, BLOCKING_ALLOW, NULL );
3237 *available = get_avail_data( req );
3240 done:
3241 LeaveCriticalSection( &req->read_section );
3243 TRACE( "returning %u\n", *available );
3244 return ERROR_SUCCESS;
3247 static DWORD HTTPREQ_LockRequestFile(object_header_t *hdr, req_file_t **ret)
3249 http_request_t *req = (http_request_t*)hdr;
3251 TRACE("(%p)\n", req);
3253 if(!req->req_file) {
3254 WARN("No cache file name available\n");
3255 return ERROR_FILE_NOT_FOUND;
3258 *ret = req_file_addref(req->req_file);
3259 return ERROR_SUCCESS;
3262 static const object_vtbl_t HTTPREQVtbl = {
3263 HTTPREQ_Destroy,
3264 HTTPREQ_CloseConnection,
3265 HTTPREQ_QueryOption,
3266 HTTPREQ_SetOption,
3267 HTTPREQ_ReadFile,
3268 HTTPREQ_ReadFileEx,
3269 HTTPREQ_WriteFile,
3270 HTTPREQ_QueryDataAvailable,
3271 NULL,
3272 HTTPREQ_LockRequestFile
3275 /***********************************************************************
3276 * HTTP_HttpOpenRequestW (internal)
3278 * Open a HTTP request handle
3280 * RETURNS
3281 * HINTERNET a HTTP request handle on success
3282 * NULL on failure
3285 static DWORD HTTP_HttpOpenRequestW(http_session_t *session,
3286 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3287 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3288 DWORD dwFlags, DWORD_PTR dwContext, HINTERNET *ret)
3290 appinfo_t *hIC = session->appInfo;
3291 http_request_t *request;
3292 DWORD len;
3294 TRACE("-->\n");
3296 request = alloc_object(&session->hdr, &HTTPREQVtbl, sizeof(http_request_t));
3297 if(!request)
3298 return ERROR_OUTOFMEMORY;
3300 request->hdr.htype = WH_HHTTPREQ;
3301 request->hdr.dwFlags = dwFlags;
3302 request->hdr.dwContext = dwContext;
3303 request->contentLength = ~0u;
3305 request->netconn_stream.data_stream.vtbl = &netconn_stream_vtbl;
3306 request->data_stream = &request->netconn_stream.data_stream;
3307 request->connect_timeout = session->connect_timeout;
3308 request->send_timeout = session->send_timeout;
3309 request->receive_timeout = session->receive_timeout;
3311 InitializeCriticalSection( &request->read_section );
3312 request->read_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.read_section");
3314 WININET_AddRef( &session->hdr );
3315 request->session = session;
3316 list_add_head( &session->hdr.children, &request->hdr.entry );
3318 request->server = get_server(session->hostName, session->hostPort, (dwFlags & INTERNET_FLAG_SECURE) != 0, TRUE);
3319 if(!request->server) {
3320 WININET_Release(&request->hdr);
3321 return ERROR_OUTOFMEMORY;
3324 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_CN_INVALID)
3325 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
3326 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_DATE_INVALID)
3327 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
3329 if (lpszObjectName && *lpszObjectName) {
3330 HRESULT rc;
3332 len = 0;
3333 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
3334 if (rc != E_POINTER)
3335 len = strlenW(lpszObjectName)+1;
3336 request->path = heap_alloc(len*sizeof(WCHAR));
3337 rc = UrlEscapeW(lpszObjectName, request->path, &len,
3338 URL_ESCAPE_SPACES_ONLY);
3339 if (rc != S_OK)
3341 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
3342 strcpyW(request->path,lpszObjectName);
3344 }else {
3345 static const WCHAR slashW[] = {'/',0};
3347 request->path = heap_strdupW(slashW);
3350 if (lpszReferrer && *lpszReferrer)
3351 HTTP_ProcessHeader(request, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3353 if (lpszAcceptTypes)
3355 int i;
3356 for (i = 0; lpszAcceptTypes[i]; i++)
3358 if (!*lpszAcceptTypes[i]) continue;
3359 HTTP_ProcessHeader(request, HTTP_ACCEPT, lpszAcceptTypes[i],
3360 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
3361 HTTP_ADDHDR_FLAG_REQ |
3362 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
3366 request->verb = heap_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
3367 request->version = heap_strdupW(lpszVersion && *lpszVersion ? lpszVersion : g_szHttp1_1);
3369 HTTP_ProcessHeader(request, hostW, request->server->canon_host_port, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3371 if (session->hostPort == INTERNET_INVALID_PORT_NUMBER)
3372 session->hostPort = INTERNET_DEFAULT_HTTP_PORT;
3374 if (hIC->proxy && hIC->proxy[0] && !HTTP_ShouldBypassProxy(hIC, session->hostName))
3375 HTTP_DealWithProxy( hIC, session, request );
3377 INTERNET_SendCallback(&session->hdr, dwContext,
3378 INTERNET_STATUS_HANDLE_CREATED, &request->hdr.hInternet,
3379 sizeof(HINTERNET));
3381 TRACE("<-- (%p)\n", request);
3383 *ret = request->hdr.hInternet;
3384 return ERROR_SUCCESS;
3387 /***********************************************************************
3388 * HttpOpenRequestW (WININET.@)
3390 * Open a HTTP request handle
3392 * RETURNS
3393 * HINTERNET a HTTP request handle on success
3394 * NULL on failure
3397 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
3398 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3399 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3400 DWORD dwFlags, DWORD_PTR dwContext)
3402 http_session_t *session;
3403 HINTERNET handle = NULL;
3404 DWORD res;
3406 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
3407 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
3408 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
3409 dwFlags, dwContext);
3410 if(lpszAcceptTypes!=NULL)
3412 int i;
3413 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
3414 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
3417 session = (http_session_t*) get_handle_object( hHttpSession );
3418 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
3420 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3421 goto lend;
3425 * My tests seem to show that the windows version does not
3426 * become asynchronous until after this point. And anyhow
3427 * if this call was asynchronous then how would you get the
3428 * necessary HINTERNET pointer returned by this function.
3431 res = HTTP_HttpOpenRequestW(session, lpszVerb, lpszObjectName,
3432 lpszVersion, lpszReferrer, lpszAcceptTypes,
3433 dwFlags, dwContext, &handle);
3434 lend:
3435 if( session )
3436 WININET_Release( &session->hdr );
3437 TRACE("returning %p\n", handle);
3438 if(res != ERROR_SUCCESS)
3439 SetLastError(res);
3440 return handle;
3443 static const LPCWSTR header_lookup[] = {
3444 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
3445 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3446 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3447 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
3448 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3449 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3450 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3451 szAllow, /* HTTP_QUERY_ALLOW = 7 */
3452 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
3453 szDate, /* HTTP_QUERY_DATE = 9 */
3454 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
3455 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3456 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
3457 szURI, /* HTTP_QUERY_URI = 13 */
3458 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
3459 NULL, /* HTTP_QUERY_COST = 15 */
3460 NULL, /* HTTP_QUERY_LINK = 16 */
3461 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
3462 NULL, /* HTTP_QUERY_VERSION = 18 */
3463 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
3464 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
3465 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
3466 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3467 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
3468 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
3469 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3470 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3471 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3472 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
3473 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3474 NULL, /* HTTP_QUERY_FORWARDED = 30 */
3475 NULL, /* HTTP_QUERY_FROM = 31 */
3476 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3477 szLocation, /* HTTP_QUERY_LOCATION = 33 */
3478 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
3479 szReferer, /* HTTP_QUERY_REFERER = 35 */
3480 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
3481 szServer, /* HTTP_QUERY_SERVER = 37 */
3482 NULL, /* HTTP_TITLE = 38 */
3483 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
3484 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3485 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3486 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3487 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
3488 szCookie, /* HTTP_QUERY_COOKIE = 44 */
3489 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3490 NULL, /* HTTP_QUERY_REFRESH = 46 */
3491 szContent_Disposition, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3492 szAge, /* HTTP_QUERY_AGE = 48 */
3493 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3494 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
3495 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3496 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3497 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3498 szETag, /* HTTP_QUERY_ETAG = 54 */
3499 hostW, /* HTTP_QUERY_HOST = 55 */
3500 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
3501 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3502 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
3503 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3504 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3505 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3506 szRange, /* HTTP_QUERY_RANGE = 62 */
3507 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3508 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
3509 szVary, /* HTTP_QUERY_VARY = 65 */
3510 szVia, /* HTTP_QUERY_VIA = 66 */
3511 szWarning, /* HTTP_QUERY_WARNING = 67 */
3512 szExpect, /* HTTP_QUERY_EXPECT = 68 */
3513 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3514 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3517 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3519 /***********************************************************************
3520 * HTTP_HttpQueryInfoW (internal)
3522 static DWORD HTTP_HttpQueryInfoW(http_request_t *request, DWORD dwInfoLevel,
3523 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3525 LPHTTPHEADERW lphttpHdr = NULL;
3526 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
3527 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
3528 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
3529 INT index = -1;
3531 /* Find requested header structure */
3532 switch (level)
3534 case HTTP_QUERY_CUSTOM:
3535 if (!lpBuffer) return ERROR_INVALID_PARAMETER;
3536 index = HTTP_GetCustomHeaderIndex(request, lpBuffer, requested_index, request_only);
3537 break;
3538 case HTTP_QUERY_RAW_HEADERS_CRLF:
3540 LPWSTR headers;
3541 DWORD len = 0;
3542 DWORD res = ERROR_INVALID_PARAMETER;
3544 if (request_only)
3545 headers = build_request_header(request, request->verb, request->path, request->version, TRUE);
3546 else
3547 headers = build_response_header(request, TRUE);
3548 if (!headers)
3549 return ERROR_OUTOFMEMORY;
3551 len = strlenW(headers) * sizeof(WCHAR);
3552 if (len + sizeof(WCHAR) > *lpdwBufferLength)
3554 len += sizeof(WCHAR);
3555 res = ERROR_INSUFFICIENT_BUFFER;
3557 else if (lpBuffer)
3559 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3560 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
3561 res = ERROR_SUCCESS;
3563 *lpdwBufferLength = len;
3565 heap_free(headers);
3566 return res;
3568 case HTTP_QUERY_RAW_HEADERS:
3570 LPWSTR headers;
3571 DWORD len;
3573 if (request_only)
3574 headers = build_request_header(request, request->verb, request->path, request->version, FALSE);
3575 else
3576 headers = build_response_header(request, FALSE);
3577 if (!headers)
3578 return ERROR_OUTOFMEMORY;
3580 len = strlenW(headers) * sizeof(WCHAR);
3581 if (len > *lpdwBufferLength)
3583 *lpdwBufferLength = len;
3584 heap_free(headers);
3585 return ERROR_INSUFFICIENT_BUFFER;
3588 if (lpBuffer)
3590 DWORD i;
3592 TRACE("returning data: %s\n", debugstr_wn(headers, len / sizeof(WCHAR)));
3594 for (i=0; i<len; i++)
3596 if (headers[i] == '\n')
3597 headers[i] = 0;
3599 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3601 *lpdwBufferLength = len - sizeof(WCHAR);
3603 heap_free(headers);
3604 return ERROR_SUCCESS;
3606 case HTTP_QUERY_STATUS_TEXT:
3607 if (request->statusText)
3609 DWORD len = strlenW(request->statusText);
3610 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3612 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3613 return ERROR_INSUFFICIENT_BUFFER;
3615 if (lpBuffer)
3617 memcpy(lpBuffer, request->statusText, (len + 1) * sizeof(WCHAR));
3618 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3620 *lpdwBufferLength = len * sizeof(WCHAR);
3621 return ERROR_SUCCESS;
3623 break;
3624 case HTTP_QUERY_VERSION:
3625 if (request->version)
3627 DWORD len = strlenW(request->version);
3628 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3630 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3631 return ERROR_INSUFFICIENT_BUFFER;
3633 if (lpBuffer)
3635 memcpy(lpBuffer, request->version, (len + 1) * sizeof(WCHAR));
3636 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3638 *lpdwBufferLength = len * sizeof(WCHAR);
3639 return ERROR_SUCCESS;
3641 break;
3642 case HTTP_QUERY_CONTENT_ENCODING:
3643 index = HTTP_GetCustomHeaderIndex(request, header_lookup[request->read_gzip ? HTTP_QUERY_CONTENT_TYPE : level],
3644 requested_index,request_only);
3645 break;
3646 case HTTP_QUERY_STATUS_CODE: {
3647 DWORD res = ERROR_SUCCESS;
3649 if(request_only)
3650 return ERROR_HTTP_INVALID_QUERY_REQUEST;
3652 if(requested_index)
3653 break;
3655 if(dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) {
3656 if(*lpdwBufferLength >= sizeof(DWORD))
3657 *(DWORD*)lpBuffer = request->status_code;
3658 else
3659 res = ERROR_INSUFFICIENT_BUFFER;
3660 *lpdwBufferLength = sizeof(DWORD);
3661 }else {
3662 WCHAR buf[12];
3663 DWORD size;
3664 static const WCHAR formatW[] = {'%','u',0};
3666 size = sprintfW(buf, formatW, request->status_code) * sizeof(WCHAR);
3668 if(size <= *lpdwBufferLength) {
3669 memcpy(lpBuffer, buf, size+sizeof(WCHAR));
3670 }else {
3671 size += sizeof(WCHAR);
3672 res = ERROR_INSUFFICIENT_BUFFER;
3675 *lpdwBufferLength = size;
3677 return res;
3679 default:
3680 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
3682 if (level < LAST_TABLE_HEADER && header_lookup[level])
3683 index = HTTP_GetCustomHeaderIndex(request, header_lookup[level],
3684 requested_index,request_only);
3687 if (index >= 0)
3688 lphttpHdr = &request->custHeaders[index];
3690 /* Ensure header satisfies requested attributes */
3691 if (!lphttpHdr ||
3692 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
3693 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
3695 return ERROR_HTTP_HEADER_NOT_FOUND;
3698 /* coalesce value to requested type */
3699 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
3701 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
3702 TRACE(" returning number: %d\n", *(int *)lpBuffer);
3704 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
3706 time_t tmpTime;
3707 struct tm tmpTM;
3708 SYSTEMTIME *STHook;
3710 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
3712 tmpTM = *gmtime(&tmpTime);
3713 STHook = (SYSTEMTIME *)lpBuffer;
3714 STHook->wDay = tmpTM.tm_mday;
3715 STHook->wHour = tmpTM.tm_hour;
3716 STHook->wMilliseconds = 0;
3717 STHook->wMinute = tmpTM.tm_min;
3718 STHook->wDayOfWeek = tmpTM.tm_wday;
3719 STHook->wMonth = tmpTM.tm_mon + 1;
3720 STHook->wSecond = tmpTM.tm_sec;
3721 STHook->wYear = 1900+tmpTM.tm_year;
3723 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3724 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
3725 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
3727 else if (lphttpHdr->lpszValue)
3729 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
3731 if (len > *lpdwBufferLength)
3733 *lpdwBufferLength = len;
3734 return ERROR_INSUFFICIENT_BUFFER;
3736 if (lpBuffer)
3738 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
3739 TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
3741 *lpdwBufferLength = len - sizeof(WCHAR);
3743 if (lpdwIndex) (*lpdwIndex)++;
3744 return ERROR_SUCCESS;
3747 /***********************************************************************
3748 * HttpQueryInfoW (WININET.@)
3750 * Queries for information about an HTTP request
3752 * RETURNS
3753 * TRUE on success
3754 * FALSE on failure
3757 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3758 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3760 http_request_t *request;
3761 DWORD res;
3763 if (TRACE_ON(wininet)) {
3764 #define FE(x) { x, #x }
3765 static const wininet_flag_info query_flags[] = {
3766 FE(HTTP_QUERY_MIME_VERSION),
3767 FE(HTTP_QUERY_CONTENT_TYPE),
3768 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
3769 FE(HTTP_QUERY_CONTENT_ID),
3770 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
3771 FE(HTTP_QUERY_CONTENT_LENGTH),
3772 FE(HTTP_QUERY_CONTENT_LANGUAGE),
3773 FE(HTTP_QUERY_ALLOW),
3774 FE(HTTP_QUERY_PUBLIC),
3775 FE(HTTP_QUERY_DATE),
3776 FE(HTTP_QUERY_EXPIRES),
3777 FE(HTTP_QUERY_LAST_MODIFIED),
3778 FE(HTTP_QUERY_MESSAGE_ID),
3779 FE(HTTP_QUERY_URI),
3780 FE(HTTP_QUERY_DERIVED_FROM),
3781 FE(HTTP_QUERY_COST),
3782 FE(HTTP_QUERY_LINK),
3783 FE(HTTP_QUERY_PRAGMA),
3784 FE(HTTP_QUERY_VERSION),
3785 FE(HTTP_QUERY_STATUS_CODE),
3786 FE(HTTP_QUERY_STATUS_TEXT),
3787 FE(HTTP_QUERY_RAW_HEADERS),
3788 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
3789 FE(HTTP_QUERY_CONNECTION),
3790 FE(HTTP_QUERY_ACCEPT),
3791 FE(HTTP_QUERY_ACCEPT_CHARSET),
3792 FE(HTTP_QUERY_ACCEPT_ENCODING),
3793 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
3794 FE(HTTP_QUERY_AUTHORIZATION),
3795 FE(HTTP_QUERY_CONTENT_ENCODING),
3796 FE(HTTP_QUERY_FORWARDED),
3797 FE(HTTP_QUERY_FROM),
3798 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
3799 FE(HTTP_QUERY_LOCATION),
3800 FE(HTTP_QUERY_ORIG_URI),
3801 FE(HTTP_QUERY_REFERER),
3802 FE(HTTP_QUERY_RETRY_AFTER),
3803 FE(HTTP_QUERY_SERVER),
3804 FE(HTTP_QUERY_TITLE),
3805 FE(HTTP_QUERY_USER_AGENT),
3806 FE(HTTP_QUERY_WWW_AUTHENTICATE),
3807 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
3808 FE(HTTP_QUERY_ACCEPT_RANGES),
3809 FE(HTTP_QUERY_SET_COOKIE),
3810 FE(HTTP_QUERY_COOKIE),
3811 FE(HTTP_QUERY_REQUEST_METHOD),
3812 FE(HTTP_QUERY_REFRESH),
3813 FE(HTTP_QUERY_CONTENT_DISPOSITION),
3814 FE(HTTP_QUERY_AGE),
3815 FE(HTTP_QUERY_CACHE_CONTROL),
3816 FE(HTTP_QUERY_CONTENT_BASE),
3817 FE(HTTP_QUERY_CONTENT_LOCATION),
3818 FE(HTTP_QUERY_CONTENT_MD5),
3819 FE(HTTP_QUERY_CONTENT_RANGE),
3820 FE(HTTP_QUERY_ETAG),
3821 FE(HTTP_QUERY_HOST),
3822 FE(HTTP_QUERY_IF_MATCH),
3823 FE(HTTP_QUERY_IF_NONE_MATCH),
3824 FE(HTTP_QUERY_IF_RANGE),
3825 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
3826 FE(HTTP_QUERY_MAX_FORWARDS),
3827 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
3828 FE(HTTP_QUERY_RANGE),
3829 FE(HTTP_QUERY_TRANSFER_ENCODING),
3830 FE(HTTP_QUERY_UPGRADE),
3831 FE(HTTP_QUERY_VARY),
3832 FE(HTTP_QUERY_VIA),
3833 FE(HTTP_QUERY_WARNING),
3834 FE(HTTP_QUERY_CUSTOM)
3836 static const wininet_flag_info modifier_flags[] = {
3837 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
3838 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
3839 FE(HTTP_QUERY_FLAG_NUMBER),
3840 FE(HTTP_QUERY_FLAG_COALESCE)
3842 #undef FE
3843 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
3844 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
3845 DWORD i;
3847 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, info);
3848 TRACE(" Attribute:");
3849 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
3850 if (query_flags[i].val == info) {
3851 TRACE(" %s", query_flags[i].name);
3852 break;
3855 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
3856 TRACE(" Unknown (%08x)", info);
3859 TRACE(" Modifier:");
3860 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
3861 if (modifier_flags[i].val & info_mod) {
3862 TRACE(" %s", modifier_flags[i].name);
3863 info_mod &= ~ modifier_flags[i].val;
3867 if (info_mod) {
3868 TRACE(" Unknown (%08x)", info_mod);
3870 TRACE("\n");
3873 request = (http_request_t*) get_handle_object( hHttpRequest );
3874 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
3876 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3877 goto lend;
3880 if (lpBuffer == NULL)
3881 *lpdwBufferLength = 0;
3882 res = HTTP_HttpQueryInfoW( request, dwInfoLevel,
3883 lpBuffer, lpdwBufferLength, lpdwIndex);
3885 lend:
3886 if( request )
3887 WININET_Release( &request->hdr );
3889 TRACE("%u <--\n", res);
3890 if(res != ERROR_SUCCESS)
3891 SetLastError(res);
3892 return res == ERROR_SUCCESS;
3895 /***********************************************************************
3896 * HttpQueryInfoA (WININET.@)
3898 * Queries for information about an HTTP request
3900 * RETURNS
3901 * TRUE on success
3902 * FALSE on failure
3905 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3906 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3908 BOOL result;
3909 DWORD len;
3910 WCHAR* bufferW;
3912 TRACE("%p %x\n", hHttpRequest, dwInfoLevel);
3914 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
3915 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
3917 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
3918 lpdwBufferLength, lpdwIndex );
3921 if (lpBuffer)
3923 DWORD alloclen;
3924 len = (*lpdwBufferLength)*sizeof(WCHAR);
3925 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3927 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
3928 if (alloclen < len)
3929 alloclen = len;
3931 else
3932 alloclen = len;
3933 bufferW = heap_alloc(alloclen);
3934 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3935 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3936 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
3937 } else
3939 bufferW = NULL;
3940 len = 0;
3943 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
3944 &len, lpdwIndex );
3945 if( result )
3947 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
3948 lpBuffer, *lpdwBufferLength, NULL, NULL );
3949 *lpdwBufferLength = len - 1;
3951 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
3953 else
3954 /* since the strings being returned from HttpQueryInfoW should be
3955 * only ASCII characters, it is reasonable to assume that all of
3956 * the Unicode characters can be reduced to a single byte */
3957 *lpdwBufferLength = len / sizeof(WCHAR);
3959 heap_free( bufferW );
3960 return result;
3963 /***********************************************************************
3964 * HTTP_GetRedirectURL (internal)
3966 static LPWSTR HTTP_GetRedirectURL(http_request_t *request, LPCWSTR lpszUrl)
3968 static WCHAR szHttp[] = {'h','t','t','p',0};
3969 static WCHAR szHttps[] = {'h','t','t','p','s',0};
3970 http_session_t *session = request->session;
3971 URL_COMPONENTSW urlComponents;
3972 DWORD url_length = 0;
3973 LPWSTR orig_url;
3974 LPWSTR combined_url;
3976 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3977 urlComponents.lpszScheme = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
3978 urlComponents.dwSchemeLength = 0;
3979 urlComponents.lpszHostName = session->hostName;
3980 urlComponents.dwHostNameLength = 0;
3981 urlComponents.nPort = session->hostPort;
3982 urlComponents.lpszUserName = session->userName;
3983 urlComponents.dwUserNameLength = 0;
3984 urlComponents.lpszPassword = NULL;
3985 urlComponents.dwPasswordLength = 0;
3986 urlComponents.lpszUrlPath = request->path;
3987 urlComponents.dwUrlPathLength = 0;
3988 urlComponents.lpszExtraInfo = NULL;
3989 urlComponents.dwExtraInfoLength = 0;
3991 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
3992 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
3993 return NULL;
3995 orig_url = heap_alloc(url_length);
3997 /* convert from bytes to characters */
3998 url_length = url_length / sizeof(WCHAR) - 1;
3999 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
4001 heap_free(orig_url);
4002 return NULL;
4005 url_length = 0;
4006 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
4007 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
4009 heap_free(orig_url);
4010 return NULL;
4012 combined_url = heap_alloc(url_length * sizeof(WCHAR));
4014 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
4016 heap_free(orig_url);
4017 heap_free(combined_url);
4018 return NULL;
4020 heap_free(orig_url);
4021 return combined_url;
4025 /***********************************************************************
4026 * HTTP_HandleRedirect (internal)
4028 static DWORD HTTP_HandleRedirect(http_request_t *request, LPCWSTR lpszUrl)
4030 http_session_t *session = request->session;
4031 WCHAR path[INTERNET_MAX_PATH_LENGTH];
4032 int index;
4034 if(lpszUrl[0]=='/')
4036 /* if it's an absolute path, keep the same session info */
4037 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
4039 else
4041 URL_COMPONENTSW urlComponents;
4042 WCHAR protocol[INTERNET_MAX_SCHEME_LENGTH];
4043 WCHAR hostName[INTERNET_MAX_HOST_NAME_LENGTH];
4044 WCHAR userName[INTERNET_MAX_USER_NAME_LENGTH];
4045 BOOL custom_port = FALSE;
4047 static const WCHAR httpW[] = {'h','t','t','p',0};
4048 static const WCHAR httpsW[] = {'h','t','t','p','s',0};
4050 userName[0] = 0;
4051 hostName[0] = 0;
4052 protocol[0] = 0;
4054 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
4055 urlComponents.lpszScheme = protocol;
4056 urlComponents.dwSchemeLength = INTERNET_MAX_SCHEME_LENGTH;
4057 urlComponents.lpszHostName = hostName;
4058 urlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
4059 urlComponents.lpszUserName = userName;
4060 urlComponents.dwUserNameLength = INTERNET_MAX_USER_NAME_LENGTH;
4061 urlComponents.lpszPassword = NULL;
4062 urlComponents.dwPasswordLength = 0;
4063 urlComponents.lpszUrlPath = path;
4064 urlComponents.dwUrlPathLength = INTERNET_MAX_PATH_LENGTH;
4065 urlComponents.lpszExtraInfo = NULL;
4066 urlComponents.dwExtraInfoLength = 0;
4067 if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
4068 return INTERNET_GetLastError();
4070 if(!strcmpiW(protocol, httpW)) {
4071 if(request->hdr.dwFlags & INTERNET_FLAG_SECURE) {
4072 TRACE("redirect from secure page to non-secure page\n");
4073 /* FIXME: warn about from secure redirect to non-secure page */
4074 request->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
4077 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4078 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
4079 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT)
4080 custom_port = TRUE;
4081 }else if(!strcmpiW(protocol, httpsW)) {
4082 if(!(request->hdr.dwFlags & INTERNET_FLAG_SECURE)) {
4083 TRACE("redirect from non-secure page to secure page\n");
4084 /* FIXME: notify about redirect to secure page */
4085 request->hdr.dwFlags |= INTERNET_FLAG_SECURE;
4088 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4089 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
4090 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
4091 custom_port = TRUE;
4094 heap_free(session->hostName);
4096 if(custom_port) {
4097 int len;
4098 static const WCHAR fmt[] = {'%','s',':','%','u',0};
4099 len = lstrlenW(hostName);
4100 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
4101 session->hostName = heap_alloc(len*sizeof(WCHAR));
4102 sprintfW(session->hostName, fmt, hostName, urlComponents.nPort);
4104 else
4105 session->hostName = heap_strdupW(hostName);
4107 HTTP_ProcessHeader(request, hostW, session->hostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4109 heap_free(session->userName);
4110 session->userName = NULL;
4111 if (userName[0])
4112 session->userName = heap_strdupW(userName);
4114 reset_data_stream(request);
4116 if(strcmpiW(request->server->name, hostName) || request->server->port != urlComponents.nPort) {
4117 server_t *new_server;
4119 new_server = get_server(hostName, urlComponents.nPort, urlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
4120 server_release(request->server);
4121 request->server = new_server;
4124 heap_free(request->path);
4125 request->path=NULL;
4126 if (*path)
4128 DWORD needed = 0;
4129 HRESULT rc;
4131 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
4132 if (rc != E_POINTER)
4133 needed = strlenW(path)+1;
4134 request->path = heap_alloc(needed*sizeof(WCHAR));
4135 rc = UrlEscapeW(path, request->path, &needed,
4136 URL_ESCAPE_SPACES_ONLY);
4137 if (rc != S_OK)
4139 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4140 strcpyW(request->path,path);
4144 /* Remove custom content-type/length headers on redirects. */
4145 index = HTTP_GetCustomHeaderIndex(request, szContent_Type, 0, TRUE);
4146 if (0 <= index)
4147 HTTP_DeleteCustomHeader(request, index);
4148 index = HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE);
4149 if (0 <= index)
4150 HTTP_DeleteCustomHeader(request, index);
4152 return ERROR_SUCCESS;
4155 /***********************************************************************
4156 * HTTP_build_req (internal)
4158 * concatenate all the strings in the request together
4160 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
4162 LPCWSTR *t;
4163 LPWSTR str;
4165 for( t = list; *t ; t++ )
4166 len += strlenW( *t );
4167 len++;
4169 str = heap_alloc(len*sizeof(WCHAR));
4170 *str = 0;
4172 for( t = list; *t ; t++ )
4173 strcatW( str, *t );
4175 return str;
4178 static void HTTP_InsertCookies(http_request_t *request)
4180 DWORD cookie_size, size, cnt = 0;
4181 HTTPHEADERW *host;
4182 WCHAR *cookies;
4184 static const WCHAR cookieW[] = {'C','o','o','k','i','e',':',' ',0};
4186 host = HTTP_GetHeader(request, hostW);
4187 if(!host)
4188 return;
4190 if(get_cookie(host->lpszValue, request->path, NULL, &cookie_size) != ERROR_SUCCESS)
4191 return;
4193 size = sizeof(cookieW) + cookie_size * sizeof(WCHAR) + sizeof(szCrLf);
4194 if(!(cookies = heap_alloc(size)))
4195 return;
4197 cnt += sprintfW(cookies, cookieW);
4198 get_cookie(host->lpszValue, request->path, cookies+cnt, &cookie_size);
4199 strcatW(cookies, szCrLf);
4201 HTTP_HttpAddRequestHeadersW(request, cookies, strlenW(cookies), HTTP_ADDREQ_FLAG_REPLACE);
4203 heap_free(cookies);
4206 static WORD HTTP_ParseWkday(LPCWSTR day)
4208 static const WCHAR days[7][4] = {{ 's','u','n',0 },
4209 { 'm','o','n',0 },
4210 { 't','u','e',0 },
4211 { 'w','e','d',0 },
4212 { 't','h','u',0 },
4213 { 'f','r','i',0 },
4214 { 's','a','t',0 }};
4215 unsigned int i;
4216 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4217 if (!strcmpiW(day, days[i]))
4218 return i;
4220 /* Invalid */
4221 return 7;
4224 static WORD HTTP_ParseMonth(LPCWSTR month)
4226 static const WCHAR jan[] = { 'j','a','n',0 };
4227 static const WCHAR feb[] = { 'f','e','b',0 };
4228 static const WCHAR mar[] = { 'm','a','r',0 };
4229 static const WCHAR apr[] = { 'a','p','r',0 };
4230 static const WCHAR may[] = { 'm','a','y',0 };
4231 static const WCHAR jun[] = { 'j','u','n',0 };
4232 static const WCHAR jul[] = { 'j','u','l',0 };
4233 static const WCHAR aug[] = { 'a','u','g',0 };
4234 static const WCHAR sep[] = { 's','e','p',0 };
4235 static const WCHAR oct[] = { 'o','c','t',0 };
4236 static const WCHAR nov[] = { 'n','o','v',0 };
4237 static const WCHAR dec[] = { 'd','e','c',0 };
4239 if (!strcmpiW(month, jan)) return 1;
4240 if (!strcmpiW(month, feb)) return 2;
4241 if (!strcmpiW(month, mar)) return 3;
4242 if (!strcmpiW(month, apr)) return 4;
4243 if (!strcmpiW(month, may)) return 5;
4244 if (!strcmpiW(month, jun)) return 6;
4245 if (!strcmpiW(month, jul)) return 7;
4246 if (!strcmpiW(month, aug)) return 8;
4247 if (!strcmpiW(month, sep)) return 9;
4248 if (!strcmpiW(month, oct)) return 10;
4249 if (!strcmpiW(month, nov)) return 11;
4250 if (!strcmpiW(month, dec)) return 12;
4251 /* Invalid */
4252 return 0;
4255 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4256 * optionally preceded by whitespace.
4257 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4258 * st, and sets *str to the first character after the time format.
4260 static BOOL HTTP_ParseTime(SYSTEMTIME *st, LPCWSTR *str)
4262 LPCWSTR ptr = *str;
4263 WCHAR *nextPtr;
4264 unsigned long num;
4266 while (isspaceW(*ptr))
4267 ptr++;
4269 num = strtoulW(ptr, &nextPtr, 10);
4270 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4272 ERR("unexpected time format %s\n", debugstr_w(ptr));
4273 return FALSE;
4275 if (num > 23)
4277 ERR("unexpected hour in time format %s\n", debugstr_w(ptr));
4278 return FALSE;
4280 ptr = nextPtr + 1;
4281 st->wHour = (WORD)num;
4282 num = strtoulW(ptr, &nextPtr, 10);
4283 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4285 ERR("unexpected time format %s\n", debugstr_w(ptr));
4286 return FALSE;
4288 if (num > 59)
4290 ERR("unexpected minute in time format %s\n", debugstr_w(ptr));
4291 return FALSE;
4293 ptr = nextPtr + 1;
4294 st->wMinute = (WORD)num;
4295 num = strtoulW(ptr, &nextPtr, 10);
4296 if (!nextPtr || nextPtr <= ptr)
4298 ERR("unexpected time format %s\n", debugstr_w(ptr));
4299 return FALSE;
4301 if (num > 59)
4303 ERR("unexpected second in time format %s\n", debugstr_w(ptr));
4304 return FALSE;
4306 ptr = nextPtr + 1;
4307 *str = ptr;
4308 st->wSecond = (WORD)num;
4309 return TRUE;
4312 static BOOL HTTP_ParseDateAsAsctime(LPCWSTR value, FILETIME *ft)
4314 static const WCHAR gmt[]= { 'G','M','T',0 };
4315 WCHAR day[4], *dayPtr, month[4], *monthPtr, *nextPtr;
4316 LPCWSTR ptr;
4317 SYSTEMTIME st = { 0 };
4318 unsigned long num;
4320 for (ptr = value, dayPtr = day; *ptr && !isspaceW(*ptr) &&
4321 dayPtr - day < sizeof(day) / sizeof(day[0]) - 1; ptr++, dayPtr++)
4322 *dayPtr = *ptr;
4323 *dayPtr = 0;
4324 st.wDayOfWeek = HTTP_ParseWkday(day);
4325 if (st.wDayOfWeek >= 7)
4327 ERR("unexpected weekday %s\n", debugstr_w(day));
4328 return FALSE;
4331 while (isspaceW(*ptr))
4332 ptr++;
4334 for (monthPtr = month; !isspace(*ptr) &&
4335 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4336 monthPtr++, ptr++)
4337 *monthPtr = *ptr;
4338 *monthPtr = 0;
4339 st.wMonth = HTTP_ParseMonth(month);
4340 if (!st.wMonth || st.wMonth > 12)
4342 ERR("unexpected month %s\n", debugstr_w(month));
4343 return FALSE;
4346 while (isspaceW(*ptr))
4347 ptr++;
4349 num = strtoulW(ptr, &nextPtr, 10);
4350 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4352 ERR("unexpected day %s\n", debugstr_w(ptr));
4353 return FALSE;
4355 ptr = nextPtr;
4356 st.wDay = (WORD)num;
4358 while (isspaceW(*ptr))
4359 ptr++;
4361 if (!HTTP_ParseTime(&st, &ptr))
4362 return FALSE;
4364 while (isspaceW(*ptr))
4365 ptr++;
4367 num = strtoulW(ptr, &nextPtr, 10);
4368 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4370 ERR("unexpected year %s\n", debugstr_w(ptr));
4371 return FALSE;
4373 ptr = nextPtr;
4374 st.wYear = (WORD)num;
4376 while (isspaceW(*ptr))
4377 ptr++;
4379 /* asctime() doesn't report a timezone, but some web servers do, so accept
4380 * with or without GMT.
4382 if (*ptr && strcmpW(ptr, gmt))
4384 ERR("unexpected timezone %s\n", debugstr_w(ptr));
4385 return FALSE;
4387 return SystemTimeToFileTime(&st, ft);
4390 static BOOL HTTP_ParseRfc1123Date(LPCWSTR value, FILETIME *ft)
4392 static const WCHAR gmt[]= { 'G','M','T',0 };
4393 WCHAR *nextPtr, day[4], month[4], *monthPtr;
4394 LPCWSTR ptr;
4395 unsigned long num;
4396 SYSTEMTIME st = { 0 };
4398 ptr = strchrW(value, ',');
4399 if (!ptr)
4400 return FALSE;
4401 if (ptr - value != 3)
4403 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4404 return FALSE;
4406 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4407 day[3] = 0;
4408 st.wDayOfWeek = HTTP_ParseWkday(day);
4409 if (st.wDayOfWeek > 6)
4411 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4412 return FALSE;
4414 ptr++;
4416 while (isspaceW(*ptr))
4417 ptr++;
4419 num = strtoulW(ptr, &nextPtr, 10);
4420 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4422 WARN("unexpected day %s\n", debugstr_w(value));
4423 return FALSE;
4425 ptr = nextPtr;
4426 st.wDay = (WORD)num;
4428 while (isspaceW(*ptr))
4429 ptr++;
4431 for (monthPtr = month; !isspace(*ptr) &&
4432 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4433 monthPtr++, ptr++)
4434 *monthPtr = *ptr;
4435 *monthPtr = 0;
4436 st.wMonth = HTTP_ParseMonth(month);
4437 if (!st.wMonth || st.wMonth > 12)
4439 WARN("unexpected month %s\n", debugstr_w(month));
4440 return FALSE;
4443 while (isspaceW(*ptr))
4444 ptr++;
4446 num = strtoulW(ptr, &nextPtr, 10);
4447 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4449 ERR("unexpected year %s\n", debugstr_w(value));
4450 return FALSE;
4452 ptr = nextPtr;
4453 st.wYear = (WORD)num;
4455 if (!HTTP_ParseTime(&st, &ptr))
4456 return FALSE;
4458 while (isspaceW(*ptr))
4459 ptr++;
4461 if (strcmpW(ptr, gmt))
4463 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4464 return FALSE;
4466 return SystemTimeToFileTime(&st, ft);
4469 static WORD HTTP_ParseWeekday(LPCWSTR day)
4471 static const WCHAR days[7][10] = {{ 's','u','n','d','a','y',0 },
4472 { 'm','o','n','d','a','y',0 },
4473 { 't','u','e','s','d','a','y',0 },
4474 { 'w','e','d','n','e','s','d','a','y',0 },
4475 { 't','h','u','r','s','d','a','y',0 },
4476 { 'f','r','i','d','a','y',0 },
4477 { 's','a','t','u','r','d','a','y',0 }};
4478 unsigned int i;
4479 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4480 if (!strcmpiW(day, days[i]))
4481 return i;
4483 /* Invalid */
4484 return 7;
4487 static BOOL HTTP_ParseRfc850Date(LPCWSTR value, FILETIME *ft)
4489 static const WCHAR gmt[]= { 'G','M','T',0 };
4490 WCHAR *nextPtr, day[10], month[4], *monthPtr;
4491 LPCWSTR ptr;
4492 unsigned long num;
4493 SYSTEMTIME st = { 0 };
4495 ptr = strchrW(value, ',');
4496 if (!ptr)
4497 return FALSE;
4498 if (ptr - value == 3)
4500 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4501 day[3] = 0;
4502 st.wDayOfWeek = HTTP_ParseWkday(day);
4503 if (st.wDayOfWeek > 6)
4505 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4506 return FALSE;
4509 else if (ptr - value < sizeof(day) / sizeof(day[0]))
4511 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4512 day[ptr - value + 1] = 0;
4513 st.wDayOfWeek = HTTP_ParseWeekday(day);
4514 if (st.wDayOfWeek > 6)
4516 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4517 return FALSE;
4520 else
4522 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4523 return FALSE;
4525 ptr++;
4527 while (isspaceW(*ptr))
4528 ptr++;
4530 num = strtoulW(ptr, &nextPtr, 10);
4531 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4533 ERR("unexpected day %s\n", debugstr_w(value));
4534 return FALSE;
4536 ptr = nextPtr;
4537 st.wDay = (WORD)num;
4539 if (*ptr != '-')
4541 ERR("unexpected month format %s\n", debugstr_w(ptr));
4542 return FALSE;
4544 ptr++;
4546 for (monthPtr = month; *ptr != '-' &&
4547 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4548 monthPtr++, ptr++)
4549 *monthPtr = *ptr;
4550 *monthPtr = 0;
4551 st.wMonth = HTTP_ParseMonth(month);
4552 if (!st.wMonth || st.wMonth > 12)
4554 ERR("unexpected month %s\n", debugstr_w(month));
4555 return FALSE;
4558 if (*ptr != '-')
4560 ERR("unexpected year format %s\n", debugstr_w(ptr));
4561 return FALSE;
4563 ptr++;
4565 num = strtoulW(ptr, &nextPtr, 10);
4566 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4568 ERR("unexpected year %s\n", debugstr_w(value));
4569 return FALSE;
4571 ptr = nextPtr;
4572 st.wYear = (WORD)num;
4574 if (!HTTP_ParseTime(&st, &ptr))
4575 return FALSE;
4577 while (isspaceW(*ptr))
4578 ptr++;
4580 if (strcmpW(ptr, gmt))
4582 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4583 return FALSE;
4585 return SystemTimeToFileTime(&st, ft);
4588 static BOOL HTTP_ParseDate(LPCWSTR value, FILETIME *ft)
4590 static const WCHAR zero[] = { '0',0 };
4591 BOOL ret;
4593 if (!strcmpW(value, zero))
4595 ft->dwLowDateTime = ft->dwHighDateTime = 0;
4596 ret = TRUE;
4598 else if (strchrW(value, ','))
4600 ret = HTTP_ParseRfc1123Date(value, ft);
4601 if (!ret)
4603 ret = HTTP_ParseRfc850Date(value, ft);
4604 if (!ret)
4605 ERR("unexpected date format %s\n", debugstr_w(value));
4608 else
4610 ret = HTTP_ParseDateAsAsctime(value, ft);
4611 if (!ret)
4612 ERR("unexpected date format %s\n", debugstr_w(value));
4614 return ret;
4617 static void HTTP_ProcessExpires(http_request_t *request)
4619 BOOL expirationFound = FALSE;
4620 int headerIndex;
4622 /* Look for a Cache-Control header with a max-age directive, as it takes
4623 * precedence over the Expires header.
4625 headerIndex = HTTP_GetCustomHeaderIndex(request, szCache_Control, 0, FALSE);
4626 if (headerIndex != -1)
4628 LPHTTPHEADERW ccHeader = &request->custHeaders[headerIndex];
4629 LPWSTR ptr;
4631 for (ptr = ccHeader->lpszValue; ptr && *ptr; )
4633 LPWSTR comma = strchrW(ptr, ','), end, equal;
4635 if (comma)
4636 end = comma;
4637 else
4638 end = ptr + strlenW(ptr);
4639 for (equal = end - 1; equal > ptr && *equal != '='; equal--)
4641 if (*equal == '=')
4643 static const WCHAR max_age[] = {
4644 'm','a','x','-','a','g','e',0 };
4646 if (!strncmpiW(ptr, max_age, equal - ptr - 1))
4648 LPWSTR nextPtr;
4649 unsigned long age;
4651 age = strtoulW(equal + 1, &nextPtr, 10);
4652 if (nextPtr > equal + 1)
4654 LARGE_INTEGER ft;
4656 NtQuerySystemTime( &ft );
4657 /* Age is in seconds, FILETIME resolution is in
4658 * 100 nanosecond intervals.
4660 ft.QuadPart += age * (ULONGLONG)1000000;
4661 request->expires.dwLowDateTime = ft.u.LowPart;
4662 request->expires.dwHighDateTime = ft.u.HighPart;
4663 expirationFound = TRUE;
4667 if (comma)
4669 ptr = comma + 1;
4670 while (isspaceW(*ptr))
4671 ptr++;
4673 else
4674 ptr = NULL;
4677 if (!expirationFound)
4679 headerIndex = HTTP_GetCustomHeaderIndex(request, szExpires, 0, FALSE);
4680 if (headerIndex != -1)
4682 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4683 FILETIME ft;
4685 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4687 expirationFound = TRUE;
4688 request->expires = ft;
4692 if (!expirationFound)
4694 LARGE_INTEGER t;
4696 /* With no known age, default to 10 minutes until expiration. */
4697 NtQuerySystemTime( &t );
4698 t.QuadPart += 10 * 60 * (ULONGLONG)10000000;
4699 request->expires.dwLowDateTime = t.u.LowPart;
4700 request->expires.dwHighDateTime = t.u.HighPart;
4704 static void HTTP_ProcessLastModified(http_request_t *request)
4706 int headerIndex;
4708 headerIndex = HTTP_GetCustomHeaderIndex(request, szLast_Modified, 0, FALSE);
4709 if (headerIndex != -1)
4711 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4712 FILETIME ft;
4714 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4715 request->last_modified = ft;
4719 static void http_process_keep_alive(http_request_t *req)
4721 int index;
4723 if ((index = HTTP_GetCustomHeaderIndex(req, szConnection, 0, FALSE)) != -1)
4724 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4725 else if ((index = HTTP_GetCustomHeaderIndex(req, szProxy_Connection, 0, FALSE)) != -1)
4726 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4727 else
4728 req->netconn->keep_alive = !strcmpiW(req->version, g_szHttp1_1);
4731 static DWORD open_http_connection(http_request_t *request, BOOL *reusing)
4733 const BOOL is_https = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) != 0;
4734 netconn_t *netconn = NULL;
4735 DWORD res;
4737 reset_data_stream(request);
4739 if (request->netconn)
4741 if (is_valid_netconn(request->netconn) && NETCON_is_alive(request->netconn))
4743 *reusing = TRUE;
4744 return ERROR_SUCCESS;
4746 else
4748 free_netconn(request->netconn);
4749 request->netconn = NULL;
4753 res = HTTP_ResolveName(request);
4754 if(res != ERROR_SUCCESS)
4755 return res;
4757 EnterCriticalSection(&connection_pool_cs);
4759 while(!list_empty(&request->server->conn_pool)) {
4760 netconn = LIST_ENTRY(list_head(&request->server->conn_pool), netconn_t, pool_entry);
4761 list_remove(&netconn->pool_entry);
4763 if(is_valid_netconn(netconn) && NETCON_is_alive(netconn))
4764 break;
4766 TRACE("connection %p closed during idle\n", netconn);
4767 free_netconn(netconn);
4768 netconn = NULL;
4771 LeaveCriticalSection(&connection_pool_cs);
4773 if(netconn) {
4774 TRACE("<-- reusing %p netconn\n", netconn);
4775 request->netconn = netconn;
4776 *reusing = TRUE;
4777 return ERROR_SUCCESS;
4780 TRACE("connecting to %s, proxy %s\n", debugstr_w(request->server->name),
4781 request->proxy ? debugstr_w(request->proxy->name) : "(null)");
4783 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4784 INTERNET_STATUS_CONNECTING_TO_SERVER,
4785 request->server->addr_str,
4786 strlen(request->server->addr_str)+1);
4788 res = create_netconn(is_https, request->proxy ? request->proxy : request->server, request->security_flags,
4789 (request->hdr.ErrorMask & INTERNET_ERROR_MASK_COMBINED_SEC_CERT) != 0,
4790 request->connect_timeout, &netconn);
4791 if(res != ERROR_SUCCESS) {
4792 ERR("create_netconn failed: %u\n", res);
4793 return res;
4796 request->netconn = netconn;
4798 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4799 INTERNET_STATUS_CONNECTED_TO_SERVER,
4800 request->server->addr_str, strlen(request->server->addr_str)+1);
4802 *reusing = FALSE;
4803 TRACE("Created connection to %s: %p\n", debugstr_w(request->server->name), netconn);
4804 return ERROR_SUCCESS;
4807 static char *build_ascii_request( const WCHAR *str, void *data, DWORD data_len, DWORD *out_len )
4809 int len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
4810 char *ret;
4812 if (!(ret = heap_alloc( len + data_len ))) return NULL;
4813 WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
4814 if (data_len) memcpy( ret + len - 1, data, data_len );
4815 *out_len = len + data_len - 1;
4816 ret[*out_len] = 0;
4817 return ret;
4820 /***********************************************************************
4821 * HTTP_HttpSendRequestW (internal)
4823 * Sends the specified request to the HTTP server
4825 * RETURNS
4826 * ERROR_SUCCESS on success
4827 * win32 error code on failure
4830 static DWORD HTTP_HttpSendRequestW(http_request_t *request, LPCWSTR lpszHeaders,
4831 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
4832 DWORD dwContentLength, BOOL bEndRequest)
4834 static const WCHAR szContentLength[] =
4835 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
4836 BOOL redirected = FALSE, secure_proxy_connect = FALSE, loop_next;
4837 LPWSTR requestString = NULL;
4838 INT responseLen, cnt;
4839 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
4840 DWORD res;
4842 TRACE("--> %p\n", request);
4844 assert(request->hdr.htype == WH_HHTTPREQ);
4846 /* if the verb is NULL default to GET */
4847 if (!request->verb)
4848 request->verb = heap_strdupW(szGET);
4850 if (dwContentLength || strcmpW(request->verb, szGET))
4852 sprintfW(contentLengthStr, szContentLength, dwContentLength);
4853 HTTP_HttpAddRequestHeadersW(request, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4854 request->bytesToWrite = dwContentLength;
4856 if (request->session->appInfo->agent)
4858 WCHAR *agent_header;
4859 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4860 int len;
4862 len = strlenW(request->session->appInfo->agent) + strlenW(user_agent);
4863 agent_header = heap_alloc(len * sizeof(WCHAR));
4864 sprintfW(agent_header, user_agent, request->session->appInfo->agent);
4866 HTTP_HttpAddRequestHeadersW(request, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4867 heap_free(agent_header);
4869 if (request->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
4871 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4872 HTTP_HttpAddRequestHeadersW(request, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4874 if ((request->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && strcmpW(request->verb, szGET))
4876 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4877 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4878 HTTP_HttpAddRequestHeadersW(request, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4881 /* add the headers the caller supplied */
4882 if( lpszHeaders && dwHeaderLength )
4883 HTTP_HttpAddRequestHeadersW(request, lpszHeaders, dwHeaderLength, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
4887 DWORD len, data_len = dwOptionalLength;
4888 BOOL reusing_connection;
4889 char *ascii_req;
4891 loop_next = FALSE;
4893 if(redirected) {
4894 request->contentLength = ~0u;
4895 request->bytesToWrite = 0;
4898 if (TRACE_ON(wininet))
4900 LPHTTPHEADERW Host = HTTP_GetHeader(request, hostW);
4901 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(request->path));
4904 HTTP_FixURL(request);
4905 if (request->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
4907 HTTP_ProcessHeader(request, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
4909 HTTP_InsertAuthorization(request, request->authInfo, szAuthorization);
4910 HTTP_InsertAuthorization(request, request->proxyAuthInfo, szProxy_Authorization);
4912 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
4913 HTTP_InsertCookies(request);
4915 res = open_http_connection(request, &reusing_connection);
4916 if (res != ERROR_SUCCESS)
4917 break;
4919 if (!reusing_connection && (request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4921 if (request->proxy) secure_proxy_connect = TRUE;
4922 else
4924 res = NETCON_secure_connect(request->netconn, request->server);
4925 if (res != ERROR_SUCCESS)
4927 WARN("failed to upgrade to secure connection\n");
4928 http_release_netconn(request, FALSE);
4929 break;
4933 if (secure_proxy_connect)
4935 static const WCHAR connectW[] = {'C','O','N','N','E','C','T',0};
4936 const WCHAR *target = request->server->host_port;
4937 requestString = build_request_header(request, connectW, target, g_szHttp1_1, TRUE);
4939 else if (request->proxy && !(request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4941 WCHAR *url = build_proxy_path_url(request);
4942 requestString = build_request_header(request, request->verb, url, request->version, TRUE);
4943 heap_free(url);
4945 else
4946 requestString = build_request_header(request, request->verb, request->path, request->version, TRUE);
4948 TRACE("Request header -> %s\n", debugstr_w(requestString) );
4950 /* send the request as ASCII, tack on the optional data */
4951 if (!lpOptional || redirected || secure_proxy_connect)
4952 data_len = 0;
4954 ascii_req = build_ascii_request( requestString, lpOptional, data_len, &len );
4955 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
4957 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4958 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
4960 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
4961 res = NETCON_send(request->netconn, ascii_req, len, 0, &cnt);
4962 heap_free( ascii_req );
4963 if(res != ERROR_SUCCESS) {
4964 TRACE("send failed: %u\n", res);
4965 if(!reusing_connection)
4966 break;
4967 http_release_netconn(request, FALSE);
4968 loop_next = TRUE;
4969 continue;
4972 request->bytesWritten = data_len;
4974 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4975 INTERNET_STATUS_REQUEST_SENT,
4976 &len, sizeof(DWORD));
4978 if (bEndRequest)
4980 DWORD dwBufferSize;
4982 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4983 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
4985 if (HTTP_GetResponseHeaders(request, &responseLen))
4987 http_release_netconn(request, FALSE);
4988 res = ERROR_INTERNET_CONNECTION_ABORTED;
4989 goto lend;
4991 /* FIXME: We should know that connection is closed before sending
4992 * headers. Otherwise wrong callbacks are executed */
4993 if(!responseLen && reusing_connection) {
4994 TRACE("Connection closed by server, reconnecting\n");
4995 http_release_netconn(request, FALSE);
4996 loop_next = TRUE;
4997 continue;
5000 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5001 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
5002 sizeof(DWORD));
5004 http_process_keep_alive(request);
5005 HTTP_ProcessCookies(request);
5006 HTTP_ProcessExpires(request);
5007 HTTP_ProcessLastModified(request);
5009 res = set_content_length(request);
5010 if(res != ERROR_SUCCESS)
5011 goto lend;
5012 if(!request->contentLength)
5013 http_release_netconn(request, TRUE);
5015 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
5017 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5018 dwBufferSize=sizeof(szNewLocation);
5019 switch(request->status_code) {
5020 case HTTP_STATUS_REDIRECT:
5021 case HTTP_STATUS_MOVED:
5022 case HTTP_STATUS_REDIRECT_KEEP_VERB:
5023 case HTTP_STATUS_REDIRECT_METHOD:
5024 if(HTTP_HttpQueryInfoW(request,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL) != ERROR_SUCCESS)
5025 break;
5027 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5028 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5030 heap_free(request->verb);
5031 request->verb = heap_strdupW(szGET);
5033 http_release_netconn(request, drain_content(request, FALSE));
5034 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5036 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5037 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5038 res = HTTP_HandleRedirect(request, new_url);
5039 if (res == ERROR_SUCCESS)
5041 heap_free(requestString);
5042 loop_next = TRUE;
5044 heap_free( new_url );
5046 redirected = TRUE;
5049 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
5051 WCHAR szAuthValue[2048];
5052 dwBufferSize=2048;
5053 if (request->status_code == HTTP_STATUS_DENIED)
5055 LPHTTPHEADERW Host = HTTP_GetHeader(request, hostW);
5056 DWORD dwIndex = 0;
5057 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5059 if (HTTP_DoAuthorization(request, szAuthValue,
5060 &request->authInfo,
5061 request->session->userName,
5062 request->session->password,
5063 Host->lpszValue))
5065 heap_free(requestString);
5066 if(!drain_content(request, TRUE)) {
5067 FIXME("Could not drain content\n");
5068 http_release_netconn(request, FALSE);
5070 loop_next = TRUE;
5071 break;
5075 if(!loop_next) {
5076 TRACE("Cleaning wrong authorization data\n");
5077 destroy_authinfo(request->authInfo);
5078 request->authInfo = NULL;
5081 if (request->status_code == HTTP_STATUS_PROXY_AUTH_REQ)
5083 DWORD dwIndex = 0;
5084 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5086 if (HTTP_DoAuthorization(request, szAuthValue,
5087 &request->proxyAuthInfo,
5088 request->session->appInfo->proxyUsername,
5089 request->session->appInfo->proxyPassword,
5090 NULL))
5092 heap_free(requestString);
5093 if(!drain_content(request, TRUE)) {
5094 FIXME("Could not drain content\n");
5095 http_release_netconn(request, FALSE);
5097 loop_next = TRUE;
5098 break;
5102 if(!loop_next) {
5103 TRACE("Cleaning wrong proxy authorization data\n");
5104 destroy_authinfo(request->proxyAuthInfo);
5105 request->proxyAuthInfo = NULL;
5109 if (secure_proxy_connect && request->status_code == HTTP_STATUS_OK)
5111 int index;
5113 res = NETCON_secure_connect(request->netconn, request->server);
5114 if (res != ERROR_SUCCESS)
5116 WARN("failed to upgrade to secure proxy connection\n");
5117 http_release_netconn( request, FALSE );
5118 break;
5120 index = HTTP_GetCustomHeaderIndex(request, szProxy_Authorization, 0, TRUE);
5121 if (index != -1) HTTP_DeleteCustomHeader(request, index);
5122 destroy_authinfo(request->proxyAuthInfo);
5123 request->proxyAuthInfo = NULL;
5125 secure_proxy_connect = FALSE;
5126 loop_next = TRUE;
5129 else
5130 res = ERROR_SUCCESS;
5132 while (loop_next);
5134 lend:
5135 heap_free(requestString);
5137 /* TODO: send notification for P3P header */
5139 if(res == ERROR_SUCCESS)
5140 create_cache_entry(request);
5142 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5144 if (res == ERROR_SUCCESS) {
5145 if(bEndRequest && request->contentLength && request->bytesWritten == request->bytesToWrite)
5146 HTTP_ReceiveRequestData(request, TRUE, NULL);
5147 else
5148 send_request_complete(request,
5149 request->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)request->hdr.hInternet : 1, 0);
5150 }else {
5151 send_request_complete(request, 0, res);
5155 TRACE("<--\n");
5156 return res;
5159 typedef struct {
5160 task_header_t hdr;
5161 WCHAR *headers;
5162 DWORD headers_len;
5163 void *optional;
5164 DWORD optional_len;
5165 DWORD content_len;
5166 BOOL end_request;
5167 } send_request_task_t;
5169 /***********************************************************************
5171 * Helper functions for the HttpSendRequest(Ex) functions
5174 static void AsyncHttpSendRequestProc(task_header_t *hdr)
5176 send_request_task_t *task = (send_request_task_t*)hdr;
5177 http_request_t *request = (http_request_t*)task->hdr.hdr;
5179 TRACE("%p\n", request);
5181 HTTP_HttpSendRequestW(request, task->headers, task->headers_len, task->optional,
5182 task->optional_len, task->content_len, task->end_request);
5184 heap_free(task->headers);
5188 static DWORD HTTP_HttpEndRequestW(http_request_t *request, DWORD dwFlags, DWORD_PTR dwContext)
5190 DWORD dwBufferSize;
5191 INT responseLen;
5192 DWORD res = ERROR_SUCCESS;
5194 if(!is_valid_netconn(request->netconn)) {
5195 WARN("Not connected\n");
5196 send_request_complete(request, 0, ERROR_INTERNET_OPERATION_CANCELLED);
5197 return ERROR_INTERNET_OPERATION_CANCELLED;
5200 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5201 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5203 if (HTTP_GetResponseHeaders(request, &responseLen) || !responseLen)
5204 res = ERROR_HTTP_HEADER_NOT_FOUND;
5206 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5207 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
5209 /* process cookies here. Is this right? */
5210 http_process_keep_alive(request);
5211 HTTP_ProcessCookies(request);
5212 HTTP_ProcessExpires(request);
5213 HTTP_ProcessLastModified(request);
5215 if ((res = set_content_length(request)) == ERROR_SUCCESS) {
5216 if(!request->contentLength)
5217 http_release_netconn(request, TRUE);
5220 if (res == ERROR_SUCCESS && !(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
5222 switch(request->status_code) {
5223 case HTTP_STATUS_REDIRECT:
5224 case HTTP_STATUS_MOVED:
5225 case HTTP_STATUS_REDIRECT_METHOD:
5226 case HTTP_STATUS_REDIRECT_KEEP_VERB: {
5227 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5228 dwBufferSize=sizeof(szNewLocation);
5229 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, szNewLocation, &dwBufferSize, NULL) != ERROR_SUCCESS)
5230 break;
5232 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5233 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5235 heap_free(request->verb);
5236 request->verb = heap_strdupW(szGET);
5238 http_release_netconn(request, drain_content(request, FALSE));
5239 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5241 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5242 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5243 res = HTTP_HandleRedirect(request, new_url);
5244 if (res == ERROR_SUCCESS)
5245 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, TRUE);
5246 heap_free( new_url );
5252 if(res == ERROR_SUCCESS)
5253 create_cache_entry(request);
5255 if (res == ERROR_SUCCESS && request->contentLength)
5256 HTTP_ReceiveRequestData(request, TRUE, NULL);
5257 else
5258 send_request_complete(request, res == ERROR_SUCCESS, res);
5260 return res;
5263 /***********************************************************************
5264 * HttpEndRequestA (WININET.@)
5266 * Ends an HTTP request that was started by HttpSendRequestEx
5268 * RETURNS
5269 * TRUE if successful
5270 * FALSE on failure
5273 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
5274 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5276 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5278 if (lpBuffersOut)
5280 SetLastError(ERROR_INVALID_PARAMETER);
5281 return FALSE;
5284 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
5287 typedef struct {
5288 task_header_t hdr;
5289 DWORD flags;
5290 DWORD context;
5291 } end_request_task_t;
5293 static void AsyncHttpEndRequestProc(task_header_t *hdr)
5295 end_request_task_t *task = (end_request_task_t*)hdr;
5296 http_request_t *req = (http_request_t*)task->hdr.hdr;
5298 TRACE("%p\n", req);
5300 HTTP_HttpEndRequestW(req, task->flags, task->context);
5303 /***********************************************************************
5304 * HttpEndRequestW (WININET.@)
5306 * Ends an HTTP request that was started by HttpSendRequestEx
5308 * RETURNS
5309 * TRUE if successful
5310 * FALSE on failure
5313 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
5314 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5316 http_request_t *request;
5317 DWORD res;
5319 TRACE("%p %p %x %lx -->\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5321 if (lpBuffersOut)
5323 SetLastError(ERROR_INVALID_PARAMETER);
5324 return FALSE;
5327 request = (http_request_t*) get_handle_object( hRequest );
5329 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5331 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
5332 if (request)
5333 WININET_Release( &request->hdr );
5334 return FALSE;
5336 request->hdr.dwFlags |= dwFlags;
5338 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5340 end_request_task_t *task;
5342 task = alloc_async_task(&request->hdr, AsyncHttpEndRequestProc, sizeof(*task));
5343 task->flags = dwFlags;
5344 task->context = dwContext;
5346 INTERNET_AsyncCall(&task->hdr);
5347 res = ERROR_IO_PENDING;
5349 else
5350 res = HTTP_HttpEndRequestW(request, dwFlags, dwContext);
5352 WININET_Release( &request->hdr );
5353 TRACE("%u <--\n", res);
5354 if(res != ERROR_SUCCESS)
5355 SetLastError(res);
5356 return res == ERROR_SUCCESS;
5359 /***********************************************************************
5360 * HttpSendRequestExA (WININET.@)
5362 * Sends the specified request to the HTTP server and allows chunked
5363 * transfers.
5365 * RETURNS
5366 * Success: TRUE
5367 * Failure: FALSE, call GetLastError() for more information.
5369 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
5370 LPINTERNET_BUFFERSA lpBuffersIn,
5371 LPINTERNET_BUFFERSA lpBuffersOut,
5372 DWORD dwFlags, DWORD_PTR dwContext)
5374 INTERNET_BUFFERSW BuffersInW;
5375 BOOL rc = FALSE;
5376 DWORD headerlen;
5377 LPWSTR header = NULL;
5379 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5380 lpBuffersOut, dwFlags, dwContext);
5382 if (lpBuffersIn)
5384 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
5385 if (lpBuffersIn->lpcszHeader)
5387 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
5388 lpBuffersIn->dwHeadersLength,0,0);
5389 header = heap_alloc(headerlen*sizeof(WCHAR));
5390 if (!(BuffersInW.lpcszHeader = header))
5392 SetLastError(ERROR_OUTOFMEMORY);
5393 return FALSE;
5395 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
5396 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5397 header, headerlen);
5399 else
5400 BuffersInW.lpcszHeader = NULL;
5401 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
5402 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
5403 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
5404 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
5405 BuffersInW.Next = NULL;
5408 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
5410 heap_free(header);
5411 return rc;
5414 /***********************************************************************
5415 * HttpSendRequestExW (WININET.@)
5417 * Sends the specified request to the HTTP server and allows chunked
5418 * transfers
5420 * RETURNS
5421 * Success: TRUE
5422 * Failure: FALSE, call GetLastError() for more information.
5424 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
5425 LPINTERNET_BUFFERSW lpBuffersIn,
5426 LPINTERNET_BUFFERSW lpBuffersOut,
5427 DWORD dwFlags, DWORD_PTR dwContext)
5429 http_request_t *request;
5430 http_session_t *session;
5431 appinfo_t *hIC;
5432 DWORD res;
5434 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5435 lpBuffersOut, dwFlags, dwContext);
5437 request = (http_request_t*) get_handle_object( hRequest );
5439 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5441 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5442 goto lend;
5445 session = request->session;
5446 assert(session->hdr.htype == WH_HHTTPSESSION);
5447 hIC = session->appInfo;
5448 assert(hIC->hdr.htype == WH_HINIT);
5450 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5452 send_request_task_t *task;
5454 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5455 if (lpBuffersIn)
5457 DWORD size = 0;
5459 if (lpBuffersIn->lpcszHeader)
5461 if (lpBuffersIn->dwHeadersLength == ~0u)
5462 size = (strlenW( lpBuffersIn->lpcszHeader ) + 1) * sizeof(WCHAR);
5463 else
5464 size = lpBuffersIn->dwHeadersLength * sizeof(WCHAR);
5466 task->headers = heap_alloc(size);
5467 memcpy(task->headers, lpBuffersIn->lpcszHeader, size);
5469 else task->headers = NULL;
5471 task->headers_len = size / sizeof(WCHAR);
5472 task->optional = lpBuffersIn->lpvBuffer;
5473 task->optional_len = lpBuffersIn->dwBufferLength;
5474 task->content_len = lpBuffersIn->dwBufferTotal;
5476 else
5478 task->headers = NULL;
5479 task->headers_len = 0;
5480 task->optional = NULL;
5481 task->optional_len = 0;
5482 task->content_len = 0;
5485 task->end_request = FALSE;
5487 INTERNET_AsyncCall(&task->hdr);
5488 res = ERROR_IO_PENDING;
5490 else
5492 if (lpBuffersIn)
5493 res = HTTP_HttpSendRequestW(request, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5494 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
5495 lpBuffersIn->dwBufferTotal, FALSE);
5496 else
5497 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, FALSE);
5500 lend:
5501 if ( request )
5502 WININET_Release( &request->hdr );
5504 TRACE("<---\n");
5505 SetLastError(res);
5506 return res == ERROR_SUCCESS;
5509 /***********************************************************************
5510 * HttpSendRequestW (WININET.@)
5512 * Sends the specified request to the HTTP server
5514 * RETURNS
5515 * TRUE on success
5516 * FALSE on failure
5519 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
5520 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5522 http_request_t *request;
5523 http_session_t *session = NULL;
5524 appinfo_t *hIC = NULL;
5525 DWORD res = ERROR_SUCCESS;
5527 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
5528 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
5530 request = (http_request_t*) get_handle_object( hHttpRequest );
5531 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5533 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5534 goto lend;
5537 session = request->session;
5538 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
5540 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5541 goto lend;
5544 hIC = session->appInfo;
5545 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
5547 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5548 goto lend;
5551 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5553 send_request_task_t *task;
5555 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5556 if (lpszHeaders)
5558 DWORD size;
5560 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
5561 else size = dwHeaderLength * sizeof(WCHAR);
5563 task->headers = heap_alloc(size);
5564 memcpy(task->headers, lpszHeaders, size);
5566 else
5567 task->headers = NULL;
5568 task->headers_len = dwHeaderLength;
5569 task->optional = lpOptional;
5570 task->optional_len = dwOptionalLength;
5571 task->content_len = dwOptionalLength;
5572 task->end_request = TRUE;
5574 INTERNET_AsyncCall(&task->hdr);
5575 res = ERROR_IO_PENDING;
5577 else
5579 res = HTTP_HttpSendRequestW(request, lpszHeaders,
5580 dwHeaderLength, lpOptional, dwOptionalLength,
5581 dwOptionalLength, TRUE);
5583 lend:
5584 if( request )
5585 WININET_Release( &request->hdr );
5587 SetLastError(res);
5588 return res == ERROR_SUCCESS;
5591 /***********************************************************************
5592 * HttpSendRequestA (WININET.@)
5594 * Sends the specified request to the HTTP server
5596 * RETURNS
5597 * TRUE on success
5598 * FALSE on failure
5601 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
5602 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5604 BOOL result;
5605 LPWSTR szHeaders=NULL;
5606 DWORD nLen=dwHeaderLength;
5607 if(lpszHeaders!=NULL)
5609 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
5610 szHeaders = heap_alloc(nLen*sizeof(WCHAR));
5611 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
5613 result = HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
5614 heap_free(szHeaders);
5615 return result;
5618 /***********************************************************************
5619 * HTTPSESSION_Destroy (internal)
5621 * Deallocate session handle
5624 static void HTTPSESSION_Destroy(object_header_t *hdr)
5626 http_session_t *session = (http_session_t*) hdr;
5628 TRACE("%p\n", session);
5630 WININET_Release(&session->appInfo->hdr);
5632 heap_free(session->hostName);
5633 heap_free(session->password);
5634 heap_free(session->userName);
5637 static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
5639 http_session_t *ses = (http_session_t *)hdr;
5641 switch(option) {
5642 case INTERNET_OPTION_HANDLE_TYPE:
5643 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5645 if (*size < sizeof(ULONG))
5646 return ERROR_INSUFFICIENT_BUFFER;
5648 *size = sizeof(DWORD);
5649 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
5650 return ERROR_SUCCESS;
5651 case INTERNET_OPTION_CONNECT_TIMEOUT:
5652 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5654 if (*size < sizeof(DWORD))
5655 return ERROR_INSUFFICIENT_BUFFER;
5657 *size = sizeof(DWORD);
5658 *(DWORD *)buffer = ses->connect_timeout;
5659 return ERROR_SUCCESS;
5661 case INTERNET_OPTION_SEND_TIMEOUT:
5662 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5664 if (*size < sizeof(DWORD))
5665 return ERROR_INSUFFICIENT_BUFFER;
5667 *size = sizeof(DWORD);
5668 *(DWORD *)buffer = ses->send_timeout;
5669 return ERROR_SUCCESS;
5671 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5672 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5674 if (*size < sizeof(DWORD))
5675 return ERROR_INSUFFICIENT_BUFFER;
5677 *size = sizeof(DWORD);
5678 *(DWORD *)buffer = ses->receive_timeout;
5679 return ERROR_SUCCESS;
5682 return INET_QueryOption(hdr, option, buffer, size, unicode);
5685 static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
5687 http_session_t *ses = (http_session_t*)hdr;
5689 switch(option) {
5690 case INTERNET_OPTION_USERNAME:
5692 heap_free(ses->userName);
5693 if (!(ses->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5694 return ERROR_SUCCESS;
5696 case INTERNET_OPTION_PASSWORD:
5698 heap_free(ses->password);
5699 if (!(ses->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5700 return ERROR_SUCCESS;
5702 case INTERNET_OPTION_PROXY_USERNAME:
5704 heap_free(ses->appInfo->proxyUsername);
5705 if (!(ses->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5706 return ERROR_SUCCESS;
5708 case INTERNET_OPTION_PROXY_PASSWORD:
5710 heap_free(ses->appInfo->proxyPassword);
5711 if (!(ses->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5712 return ERROR_SUCCESS;
5714 case INTERNET_OPTION_CONNECT_TIMEOUT:
5716 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5717 ses->connect_timeout = *(DWORD *)buffer;
5718 return ERROR_SUCCESS;
5720 case INTERNET_OPTION_SEND_TIMEOUT:
5722 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5723 ses->send_timeout = *(DWORD *)buffer;
5724 return ERROR_SUCCESS;
5726 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5728 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5729 ses->receive_timeout = *(DWORD *)buffer;
5730 return ERROR_SUCCESS;
5732 default: break;
5735 return INET_SetOption(hdr, option, buffer, size);
5738 static const object_vtbl_t HTTPSESSIONVtbl = {
5739 HTTPSESSION_Destroy,
5740 NULL,
5741 HTTPSESSION_QueryOption,
5742 HTTPSESSION_SetOption,
5743 NULL,
5744 NULL,
5745 NULL,
5746 NULL,
5747 NULL
5751 /***********************************************************************
5752 * HTTP_Connect (internal)
5754 * Create http session handle
5756 * RETURNS
5757 * HINTERNET a session handle on success
5758 * NULL on failure
5761 DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
5762 INTERNET_PORT serverPort, LPCWSTR lpszUserName,
5763 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
5764 DWORD dwInternalFlags, HINTERNET *ret)
5766 http_session_t *session = NULL;
5768 TRACE("-->\n");
5770 if (!lpszServerName || !lpszServerName[0])
5771 return ERROR_INVALID_PARAMETER;
5773 assert( hIC->hdr.htype == WH_HINIT );
5775 session = alloc_object(&hIC->hdr, &HTTPSESSIONVtbl, sizeof(http_session_t));
5776 if (!session)
5777 return ERROR_OUTOFMEMORY;
5780 * According to my tests. The name is not resolved until a request is sent
5783 session->hdr.htype = WH_HHTTPSESSION;
5784 session->hdr.dwFlags = dwFlags;
5785 session->hdr.dwContext = dwContext;
5786 session->hdr.dwInternalFlags |= dwInternalFlags;
5788 WININET_AddRef( &hIC->hdr );
5789 session->appInfo = hIC;
5790 list_add_head( &hIC->hdr.children, &session->hdr.entry );
5792 session->hostName = heap_strdupW(lpszServerName);
5793 if (lpszUserName && lpszUserName[0])
5794 session->userName = heap_strdupW(lpszUserName);
5795 if (lpszPassword && lpszPassword[0])
5796 session->password = heap_strdupW(lpszPassword);
5797 session->hostPort = serverPort;
5798 session->connect_timeout = hIC->connect_timeout;
5799 session->send_timeout = INFINITE;
5800 session->receive_timeout = INFINITE;
5802 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5803 if (!(session->hdr.dwInternalFlags & INET_OPENURL))
5805 INTERNET_SendCallback(&hIC->hdr, dwContext,
5806 INTERNET_STATUS_HANDLE_CREATED, &session->hdr.hInternet,
5807 sizeof(HINTERNET));
5811 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5812 * windows
5815 TRACE("%p --> %p\n", hIC, session);
5817 *ret = session->hdr.hInternet;
5818 return ERROR_SUCCESS;
5821 /***********************************************************************
5822 * HTTP_clear_response_headers (internal)
5824 * clear out any old response headers
5826 static void HTTP_clear_response_headers( http_request_t *request )
5828 DWORD i;
5830 for( i=0; i<request->nCustHeaders; i++)
5832 if( !request->custHeaders[i].lpszField )
5833 continue;
5834 if( !request->custHeaders[i].lpszValue )
5835 continue;
5836 if ( request->custHeaders[i].wFlags & HDR_ISREQUEST )
5837 continue;
5838 HTTP_DeleteCustomHeader( request, i );
5839 i--;
5843 /***********************************************************************
5844 * HTTP_GetResponseHeaders (internal)
5846 * Read server response
5848 * RETURNS
5850 * TRUE on success
5851 * FALSE on error
5853 static DWORD HTTP_GetResponseHeaders(http_request_t *request, INT *len)
5855 INT cbreaks = 0;
5856 WCHAR buffer[MAX_REPLY_LEN];
5857 DWORD buflen = MAX_REPLY_LEN;
5858 INT rc = 0;
5859 char bufferA[MAX_REPLY_LEN];
5860 LPWSTR status_code = NULL, status_text = NULL;
5861 DWORD res = ERROR_HTTP_INVALID_SERVER_RESPONSE;
5862 BOOL codeHundred = FALSE;
5864 TRACE("-->\n");
5866 if(!is_valid_netconn(request->netconn))
5867 goto lend;
5869 /* clear old response headers (eg. from a redirect response) */
5870 HTTP_clear_response_headers( request );
5872 NETCON_set_timeout( request->netconn, FALSE, request->receive_timeout );
5873 do {
5875 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5877 buflen = MAX_REPLY_LEN;
5878 if ((res = read_line(request, bufferA, &buflen)))
5879 goto lend;
5881 if (!buflen) goto lend;
5883 rc += buflen;
5884 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5885 /* check is this a status code line? */
5886 if (!strncmpW(buffer, g_szHttp1_0, 4))
5888 /* split the version from the status code */
5889 status_code = strchrW( buffer, ' ' );
5890 if( !status_code )
5891 goto lend;
5892 *status_code++=0;
5894 /* split the status code from the status text */
5895 status_text = strchrW( status_code, ' ' );
5896 if( status_text )
5897 *status_text++=0;
5899 request->status_code = atoiW(status_code);
5901 TRACE("version [%s] status code [%s] status text [%s]\n",
5902 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
5904 codeHundred = request->status_code == HTTP_STATUS_CONTINUE;
5906 else if (!codeHundred)
5908 WARN("No status line at head of response (%s)\n", debugstr_w(buffer));
5910 heap_free(request->version);
5911 heap_free(request->statusText);
5913 request->status_code = HTTP_STATUS_OK;
5914 request->version = heap_strdupW(g_szHttp1_0);
5915 request->statusText = heap_strdupW(szOK);
5917 goto lend;
5919 } while (codeHundred);
5921 /* Add status code */
5922 HTTP_ProcessHeader(request, szStatus, status_code,
5923 HTTP_ADDHDR_FLAG_REPLACE);
5925 heap_free(request->version);
5926 heap_free(request->statusText);
5928 request->version = heap_strdupW(buffer);
5929 request->statusText = heap_strdupW(status_text ? status_text : emptyW);
5931 /* Restore the spaces */
5932 *(status_code-1) = ' ';
5933 if (status_text)
5934 *(status_text-1) = ' ';
5936 /* Parse each response line */
5939 buflen = MAX_REPLY_LEN;
5940 if (!read_line(request, bufferA, &buflen) && buflen)
5942 LPWSTR * pFieldAndValue;
5944 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
5946 if (!bufferA[0]) break;
5947 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5949 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
5950 if (pFieldAndValue)
5952 HTTP_ProcessHeader(request, pFieldAndValue[0], pFieldAndValue[1],
5953 HTTP_ADDREQ_FLAG_ADD );
5954 HTTP_FreeTokens(pFieldAndValue);
5957 else
5959 cbreaks++;
5960 if (cbreaks >= 2)
5961 break;
5963 }while(1);
5965 res = ERROR_SUCCESS;
5967 lend:
5969 *len = rc;
5970 TRACE("<--\n");
5971 return res;
5974 /***********************************************************************
5975 * HTTP_InterpretHttpHeader (internal)
5977 * Parse server response
5979 * RETURNS
5981 * Pointer to array of field, value, NULL on success.
5982 * NULL on error.
5984 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
5986 LPWSTR * pTokenPair;
5987 LPWSTR pszColon;
5988 INT len;
5990 pTokenPair = heap_alloc_zero(sizeof(*pTokenPair)*3);
5992 pszColon = strchrW(buffer, ':');
5993 /* must have two tokens */
5994 if (!pszColon)
5996 HTTP_FreeTokens(pTokenPair);
5997 if (buffer[0])
5998 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
5999 return NULL;
6002 pTokenPair[0] = heap_alloc((pszColon - buffer + 1) * sizeof(WCHAR));
6003 if (!pTokenPair[0])
6005 HTTP_FreeTokens(pTokenPair);
6006 return NULL;
6008 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
6009 pTokenPair[0][pszColon - buffer] = '\0';
6011 /* skip colon */
6012 pszColon++;
6013 len = strlenW(pszColon);
6014 pTokenPair[1] = heap_alloc((len + 1) * sizeof(WCHAR));
6015 if (!pTokenPair[1])
6017 HTTP_FreeTokens(pTokenPair);
6018 return NULL;
6020 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
6022 strip_spaces(pTokenPair[0]);
6023 strip_spaces(pTokenPair[1]);
6025 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
6026 return pTokenPair;
6029 /***********************************************************************
6030 * HTTP_ProcessHeader (internal)
6032 * Stuff header into header tables according to <dwModifier>
6036 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6038 static DWORD HTTP_ProcessHeader(http_request_t *request, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
6040 LPHTTPHEADERW lphttpHdr = NULL;
6041 INT index = -1;
6042 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
6043 DWORD res = ERROR_HTTP_INVALID_HEADER;
6045 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
6047 /* REPLACE wins out over ADD */
6048 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6049 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
6051 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
6052 index = -1;
6053 else
6054 index = HTTP_GetCustomHeaderIndex(request, field, 0, request_only);
6056 if (index >= 0)
6058 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
6059 return ERROR_HTTP_INVALID_HEADER;
6060 lphttpHdr = &request->custHeaders[index];
6062 else if (value)
6064 HTTPHEADERW hdr;
6066 hdr.lpszField = (LPWSTR)field;
6067 hdr.lpszValue = (LPWSTR)value;
6068 hdr.wFlags = hdr.wCount = 0;
6070 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6071 hdr.wFlags |= HDR_ISREQUEST;
6073 return HTTP_InsertCustomHeader(request, &hdr);
6075 /* no value to delete */
6076 else return ERROR_SUCCESS;
6078 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6079 lphttpHdr->wFlags |= HDR_ISREQUEST;
6080 else
6081 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
6083 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6085 HTTP_DeleteCustomHeader( request, index );
6087 if (value && value[0])
6089 HTTPHEADERW hdr;
6091 hdr.lpszField = (LPWSTR)field;
6092 hdr.lpszValue = (LPWSTR)value;
6093 hdr.wFlags = hdr.wCount = 0;
6095 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6096 hdr.wFlags |= HDR_ISREQUEST;
6098 return HTTP_InsertCustomHeader(request, &hdr);
6101 return ERROR_SUCCESS;
6103 else if (dwModifier & COALESCEFLAGS)
6105 LPWSTR lpsztmp;
6106 WCHAR ch = 0;
6107 INT len = 0;
6108 INT origlen = strlenW(lphttpHdr->lpszValue);
6109 INT valuelen = strlenW(value);
6111 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
6113 ch = ',';
6114 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6116 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6118 ch = ';';
6119 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6122 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
6124 lpsztmp = heap_realloc(lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
6125 if (lpsztmp)
6127 lphttpHdr->lpszValue = lpsztmp;
6128 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6129 if (ch > 0)
6131 lphttpHdr->lpszValue[origlen] = ch;
6132 origlen++;
6133 lphttpHdr->lpszValue[origlen] = ' ';
6134 origlen++;
6137 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
6138 lphttpHdr->lpszValue[len] = '\0';
6139 res = ERROR_SUCCESS;
6141 else
6143 WARN("heap_realloc (%d bytes) failed\n",len+1);
6144 res = ERROR_OUTOFMEMORY;
6147 TRACE("<-- %d\n", res);
6148 return res;
6151 /***********************************************************************
6152 * HTTP_GetCustomHeaderIndex (internal)
6154 * Return index of custom header from header array
6157 static INT HTTP_GetCustomHeaderIndex(http_request_t *request, LPCWSTR lpszField,
6158 int requested_index, BOOL request_only)
6160 DWORD index;
6162 TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
6164 for (index = 0; index < request->nCustHeaders; index++)
6166 if (strcmpiW(request->custHeaders[index].lpszField, lpszField))
6167 continue;
6169 if (request_only && !(request->custHeaders[index].wFlags & HDR_ISREQUEST))
6170 continue;
6172 if (!request_only && (request->custHeaders[index].wFlags & HDR_ISREQUEST))
6173 continue;
6175 if (requested_index == 0)
6176 break;
6177 requested_index --;
6180 if (index >= request->nCustHeaders)
6181 index = -1;
6183 TRACE("Return: %d\n", index);
6184 return index;
6188 /***********************************************************************
6189 * HTTP_InsertCustomHeader (internal)
6191 * Insert header into array
6194 static DWORD HTTP_InsertCustomHeader(http_request_t *request, LPHTTPHEADERW lpHdr)
6196 INT count;
6197 LPHTTPHEADERW lph = NULL;
6199 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
6200 count = request->nCustHeaders + 1;
6201 if (count > 1)
6202 lph = heap_realloc_zero(request->custHeaders, sizeof(HTTPHEADERW) * count);
6203 else
6204 lph = heap_alloc_zero(sizeof(HTTPHEADERW) * count);
6206 if (!lph)
6207 return ERROR_OUTOFMEMORY;
6209 request->custHeaders = lph;
6210 request->custHeaders[count-1].lpszField = heap_strdupW(lpHdr->lpszField);
6211 request->custHeaders[count-1].lpszValue = heap_strdupW(lpHdr->lpszValue);
6212 request->custHeaders[count-1].wFlags = lpHdr->wFlags;
6213 request->custHeaders[count-1].wCount= lpHdr->wCount;
6214 request->nCustHeaders++;
6216 return ERROR_SUCCESS;
6220 /***********************************************************************
6221 * HTTP_DeleteCustomHeader (internal)
6223 * Delete header from array
6224 * If this function is called, the indexs may change.
6226 static BOOL HTTP_DeleteCustomHeader(http_request_t *request, DWORD index)
6228 if( request->nCustHeaders <= 0 )
6229 return FALSE;
6230 if( index >= request->nCustHeaders )
6231 return FALSE;
6232 request->nCustHeaders--;
6234 heap_free(request->custHeaders[index].lpszField);
6235 heap_free(request->custHeaders[index].lpszValue);
6237 memmove( &request->custHeaders[index], &request->custHeaders[index+1],
6238 (request->nCustHeaders - index)* sizeof(HTTPHEADERW) );
6239 memset( &request->custHeaders[request->nCustHeaders], 0, sizeof(HTTPHEADERW) );
6241 return TRUE;
6245 /***********************************************************************
6246 * HTTP_VerifyValidHeader (internal)
6248 * Verify the given header is not invalid for the given http request
6251 static BOOL HTTP_VerifyValidHeader(http_request_t *request, LPCWSTR field)
6253 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
6254 if (!strcmpW(request->version, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
6255 return ERROR_HTTP_INVALID_HEADER;
6257 return ERROR_SUCCESS;
6260 /***********************************************************************
6261 * IsHostInProxyBypassList (@)
6263 * Undocumented
6266 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
6268 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
6269 return FALSE;