wininet: Get rid of no longer needed hack in gzip_read that prevents consuming the...
[wine/multimedia.git] / dlls / wininet / http.c
blobad5d9562f3b59832b6929d3b8cb86233e5890f20
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;
437 static DWORD gzip_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
438 DWORD *read, blocking_mode_t blocking_mode)
440 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
441 z_stream *zstream = &gzip_stream->zstream;
442 DWORD current_read, ret_read = 0;
443 int zres;
444 DWORD res = ERROR_SUCCESS;
446 while(size && !gzip_stream->end_of_data) {
447 if(!gzip_stream->buf_size) {
448 if(gzip_stream->buf_pos) {
449 if(gzip_stream->buf_size)
450 memmove(gzip_stream->buf, gzip_stream->buf+gzip_stream->buf_pos, gzip_stream->buf_size);
451 gzip_stream->buf_pos = 0;
453 res = gzip_stream->parent_stream->vtbl->read(gzip_stream->parent_stream, req, gzip_stream->buf+gzip_stream->buf_size,
454 sizeof(gzip_stream->buf)-gzip_stream->buf_size, &current_read, blocking_mode);
455 gzip_stream->buf_size += current_read;
456 if(res != ERROR_SUCCESS)
457 break;
459 if(!current_read) {
460 if(blocking_mode != BLOCKING_DISALLOW) {
461 WARN("unexpected end of data\n");
462 gzip_stream->end_of_data = TRUE;
464 break;
468 zstream->next_in = gzip_stream->buf+gzip_stream->buf_pos;
469 zstream->avail_in = gzip_stream->buf_size;
470 zstream->next_out = buf+ret_read;
471 zstream->avail_out = size;
472 zres = inflate(&gzip_stream->zstream, 0);
473 current_read = size - zstream->avail_out;
474 size -= current_read;
475 ret_read += current_read;
476 gzip_stream->buf_size -= zstream->next_in - (gzip_stream->buf+gzip_stream->buf_pos);
477 gzip_stream->buf_pos = zstream->next_in-gzip_stream->buf;
478 if(zres == Z_STREAM_END) {
479 TRACE("end of data\n");
480 gzip_stream->end_of_data = TRUE;
481 inflateEnd(zstream);
482 }else if(zres != Z_OK) {
483 WARN("inflate failed %d: %s\n", zres, debugstr_a(zstream->msg));
484 if(!ret_read)
485 res = ERROR_INTERNET_DECODING_FAILED;
486 break;
489 if(ret_read && blocking_mode == BLOCKING_ALLOW)
490 blocking_mode = BLOCKING_DISALLOW;
493 TRACE("read %u bytes\n", ret_read);
494 *read = ret_read;
495 return res;
498 static BOOL gzip_drain_content(data_stream_t *stream, http_request_t *req)
500 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
501 return gzip_stream->parent_stream->vtbl->drain_content(gzip_stream->parent_stream, req);
504 static void gzip_destroy(data_stream_t *stream)
506 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
508 destroy_data_stream(gzip_stream->parent_stream);
510 if(!gzip_stream->end_of_data)
511 inflateEnd(&gzip_stream->zstream);
512 heap_free(gzip_stream);
515 static const data_stream_vtbl_t gzip_stream_vtbl = {
516 gzip_get_avail_data,
517 gzip_end_of_data,
518 gzip_read,
519 gzip_drain_content,
520 gzip_destroy
523 static voidpf wininet_zalloc(voidpf opaque, uInt items, uInt size)
525 return heap_alloc(items*size);
528 static void wininet_zfree(voidpf opaque, voidpf address)
530 heap_free(address);
533 static DWORD init_gzip_stream(http_request_t *req)
535 gzip_stream_t *gzip_stream;
536 int index, zres;
538 gzip_stream = heap_alloc_zero(sizeof(gzip_stream_t));
539 if(!gzip_stream)
540 return ERROR_OUTOFMEMORY;
542 gzip_stream->stream.vtbl = &gzip_stream_vtbl;
543 gzip_stream->zstream.zalloc = wininet_zalloc;
544 gzip_stream->zstream.zfree = wininet_zfree;
546 zres = inflateInit2(&gzip_stream->zstream, 0x1f);
547 if(zres != Z_OK) {
548 ERR("inflateInit failed: %d\n", zres);
549 heap_free(gzip_stream);
550 return ERROR_OUTOFMEMORY;
553 index = HTTP_GetCustomHeaderIndex(req, szContent_Length, 0, FALSE);
554 if(index != -1)
555 HTTP_DeleteCustomHeader(req, index);
557 if(req->read_size) {
558 memcpy(gzip_stream->buf, req->read_buf+req->read_pos, req->read_size);
559 gzip_stream->buf_size = req->read_size;
560 req->read_pos = req->read_size = 0;
563 req->read_gzip = TRUE;
564 gzip_stream->parent_stream = req->data_stream;
565 req->data_stream = &gzip_stream->stream;
566 return ERROR_SUCCESS;
569 #else
571 static DWORD init_gzip_stream(http_request_t *req)
573 ERR("gzip stream not supported, missing zlib.\n");
574 return ERROR_SUCCESS;
577 #endif
579 /***********************************************************************
580 * HTTP_FreeTokens (internal)
582 * Frees table of pointers.
584 static void HTTP_FreeTokens(LPWSTR * token_array)
586 int i;
587 for (i = 0; token_array[i]; i++) heap_free(token_array[i]);
588 heap_free(token_array);
591 static void HTTP_FixURL(http_request_t *request)
593 static const WCHAR szSlash[] = { '/',0 };
594 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
596 /* If we don't have a path we set it to root */
597 if (NULL == request->path)
598 request->path = heap_strdupW(szSlash);
599 else /* remove \r and \n*/
601 int nLen = strlenW(request->path);
602 while ((nLen >0 ) && ((request->path[nLen-1] == '\r')||(request->path[nLen-1] == '\n')))
604 nLen--;
605 request->path[nLen]='\0';
607 /* Replace '\' with '/' */
608 while (nLen>0) {
609 nLen--;
610 if (request->path[nLen] == '\\') request->path[nLen]='/';
614 if(CSTR_EQUAL != CompareStringW( LOCALE_INVARIANT, NORM_IGNORECASE,
615 request->path, strlenW(request->path), szHttp, strlenW(szHttp) )
616 && request->path[0] != '/') /* not an absolute path ?? --> fix it !! */
618 WCHAR *fixurl = heap_alloc((strlenW(request->path) + 2)*sizeof(WCHAR));
619 *fixurl = '/';
620 strcpyW(fixurl + 1, request->path);
621 heap_free( request->path );
622 request->path = fixurl;
626 static WCHAR* build_request_header(http_request_t *request, const WCHAR *verb,
627 const WCHAR *path, const WCHAR *version, BOOL use_cr)
629 LPWSTR requestString;
630 DWORD len, n;
631 LPCWSTR *req;
632 UINT i;
634 static const WCHAR szSpace[] = { ' ',0 };
635 static const WCHAR szColon[] = { ':',' ',0 };
636 static const WCHAR szCr[] = { '\r',0 };
637 static const WCHAR szLf[] = { '\n',0 };
639 /* allocate space for an array of all the string pointers to be added */
640 len = (request->nCustHeaders)*5 + 10;
641 req = heap_alloc(len*sizeof(LPCWSTR));
643 /* add the verb, path and HTTP version string */
644 n = 0;
645 req[n++] = verb;
646 req[n++] = szSpace;
647 req[n++] = path;
648 req[n++] = szSpace;
649 req[n++] = version;
650 if (use_cr)
651 req[n++] = szCr;
652 req[n++] = szLf;
654 /* Append custom request headers */
655 for (i = 0; i < request->nCustHeaders; i++)
657 if (request->custHeaders[i].wFlags & HDR_ISREQUEST)
659 req[n++] = request->custHeaders[i].lpszField;
660 req[n++] = szColon;
661 req[n++] = request->custHeaders[i].lpszValue;
662 if (use_cr)
663 req[n++] = szCr;
664 req[n++] = szLf;
666 TRACE("Adding custom header %s (%s)\n",
667 debugstr_w(request->custHeaders[i].lpszField),
668 debugstr_w(request->custHeaders[i].lpszValue));
671 if (use_cr)
672 req[n++] = szCr;
673 req[n++] = szLf;
674 req[n] = NULL;
676 requestString = HTTP_build_req( req, 4 );
677 heap_free( req );
678 return requestString;
681 static WCHAR* build_response_header(http_request_t *request, BOOL use_cr)
683 static const WCHAR colonW[] = { ':',' ',0 };
684 static const WCHAR crW[] = { '\r',0 };
685 static const WCHAR lfW[] = { '\n',0 };
686 static const WCHAR status_fmt[] = { ' ','%','u',' ',0 };
688 const WCHAR **req;
689 WCHAR *ret, buf[14];
690 DWORD i, n = 0;
692 req = heap_alloc((request->nCustHeaders*5+8)*sizeof(WCHAR*));
693 if(!req)
694 return NULL;
696 if (request->status_code)
698 req[n++] = request->version;
699 sprintfW(buf, status_fmt, request->status_code);
700 req[n++] = buf;
701 req[n++] = request->statusText;
702 if (use_cr)
703 req[n++] = crW;
704 req[n++] = lfW;
707 for(i = 0; i < request->nCustHeaders; i++)
709 if(!(request->custHeaders[i].wFlags & HDR_ISREQUEST)
710 && strcmpW(request->custHeaders[i].lpszField, szStatus))
712 req[n++] = request->custHeaders[i].lpszField;
713 req[n++] = colonW;
714 req[n++] = request->custHeaders[i].lpszValue;
715 if(use_cr)
716 req[n++] = crW;
717 req[n++] = lfW;
719 TRACE("Adding custom header %s (%s)\n",
720 debugstr_w(request->custHeaders[i].lpszField),
721 debugstr_w(request->custHeaders[i].lpszValue));
724 if(use_cr)
725 req[n++] = crW;
726 req[n++] = lfW;
727 req[n] = NULL;
729 ret = HTTP_build_req(req, 0);
730 heap_free(req);
731 return ret;
734 static void HTTP_ProcessCookies( http_request_t *request )
736 int HeaderIndex;
737 int numCookies = 0;
738 LPHTTPHEADERW setCookieHeader;
740 if(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES)
741 return;
743 while((HeaderIndex = HTTP_GetCustomHeaderIndex(request, szSet_Cookie, numCookies++, FALSE)) != -1)
745 HTTPHEADERW *host;
746 const WCHAR *data;
747 WCHAR *name;
749 setCookieHeader = &request->custHeaders[HeaderIndex];
751 if (!setCookieHeader->lpszValue)
752 continue;
754 host = HTTP_GetHeader(request, hostW);
755 if(!host)
756 continue;
758 data = strchrW(setCookieHeader->lpszValue, '=');
759 if(!data)
760 continue;
762 name = heap_strndupW(setCookieHeader->lpszValue, data-setCookieHeader->lpszValue);
763 if(!name)
764 continue;
766 data++;
767 set_cookie(host->lpszValue, request->path, name, data);
768 heap_free(name);
772 static void strip_spaces(LPWSTR start)
774 LPWSTR str = start;
775 LPWSTR end;
777 while (*str == ' ' && *str != '\0')
778 str++;
780 if (str != start)
781 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
783 end = start + strlenW(start) - 1;
784 while (end >= start && *end == ' ')
786 *end = '\0';
787 end--;
791 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue, LPWSTR *pszRealm )
793 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
794 static const WCHAR szRealm[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
795 BOOL is_basic;
796 is_basic = !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
797 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
798 if (is_basic && pszRealm)
800 LPCWSTR token;
801 LPCWSTR ptr = &pszAuthValue[ARRAYSIZE(szBasic)];
802 LPCWSTR realm;
803 ptr++;
804 *pszRealm=NULL;
805 token = strchrW(ptr,'=');
806 if (!token)
807 return TRUE;
808 realm = ptr;
809 while (*realm == ' ' && *realm != '\0')
810 realm++;
811 if(!strncmpiW(realm, szRealm, ARRAYSIZE(szRealm)) &&
812 (realm[ARRAYSIZE(szRealm)] == ' ' || realm[ARRAYSIZE(szRealm)] == '='))
814 token++;
815 while (*token == ' ' && *token != '\0')
816 token++;
817 if (*token == '\0')
818 return TRUE;
819 *pszRealm = heap_strdupW(token);
820 strip_spaces(*pszRealm);
824 return is_basic;
827 static void destroy_authinfo( struct HttpAuthInfo *authinfo )
829 if (!authinfo) return;
831 if (SecIsValidHandle(&authinfo->ctx))
832 DeleteSecurityContext(&authinfo->ctx);
833 if (SecIsValidHandle(&authinfo->cred))
834 FreeCredentialsHandle(&authinfo->cred);
836 heap_free(authinfo->auth_data);
837 heap_free(authinfo->scheme);
838 heap_free(authinfo);
841 static UINT retrieve_cached_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR *auth_data)
843 basicAuthorizationData *ad;
844 UINT rc = 0;
846 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host),debugstr_w(realm));
848 EnterCriticalSection(&authcache_cs);
849 LIST_FOR_EACH_ENTRY(ad, &basicAuthorizationCache, basicAuthorizationData, entry)
851 if (!strcmpiW(host,ad->host) && !strcmpW(realm,ad->realm))
853 TRACE("Authorization found in cache\n");
854 *auth_data = heap_alloc(ad->authorizationLen);
855 memcpy(*auth_data,ad->authorization,ad->authorizationLen);
856 rc = ad->authorizationLen;
857 break;
860 LeaveCriticalSection(&authcache_cs);
861 return rc;
864 static void cache_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR auth_data, UINT auth_data_len)
866 struct list *cursor;
867 basicAuthorizationData* ad = NULL;
869 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host),debugstr_w(realm),debugstr_an(auth_data,auth_data_len));
871 EnterCriticalSection(&authcache_cs);
872 LIST_FOR_EACH(cursor, &basicAuthorizationCache)
874 basicAuthorizationData *check = LIST_ENTRY(cursor,basicAuthorizationData,entry);
875 if (!strcmpiW(host,check->host) && !strcmpW(realm,check->realm))
877 ad = check;
878 break;
882 if (ad)
884 TRACE("Found match in cache, replacing\n");
885 heap_free(ad->authorization);
886 ad->authorization = heap_alloc(auth_data_len);
887 memcpy(ad->authorization, auth_data, auth_data_len);
888 ad->authorizationLen = auth_data_len;
890 else
892 ad = heap_alloc(sizeof(basicAuthorizationData));
893 ad->host = heap_strdupW(host);
894 ad->realm = heap_strdupW(realm);
895 ad->authorization = heap_alloc(auth_data_len);
896 memcpy(ad->authorization, auth_data, auth_data_len);
897 ad->authorizationLen = auth_data_len;
898 list_add_head(&basicAuthorizationCache,&ad->entry);
899 TRACE("authorization cached\n");
901 LeaveCriticalSection(&authcache_cs);
904 static BOOL retrieve_cached_authorization(LPWSTR host, LPWSTR scheme,
905 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
907 authorizationData *ad;
909 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
911 EnterCriticalSection(&authcache_cs);
912 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry) {
913 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
914 TRACE("Authorization found in cache\n");
916 nt_auth_identity->User = heap_strdupW(ad->user);
917 nt_auth_identity->Password = heap_strdupW(ad->password);
918 nt_auth_identity->Domain = heap_alloc(sizeof(WCHAR)*ad->domain_len);
919 if(!nt_auth_identity->User || !nt_auth_identity->Password ||
920 (!nt_auth_identity->Domain && ad->domain_len)) {
921 heap_free(nt_auth_identity->User);
922 heap_free(nt_auth_identity->Password);
923 heap_free(nt_auth_identity->Domain);
924 break;
927 nt_auth_identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
928 nt_auth_identity->UserLength = ad->user_len;
929 nt_auth_identity->PasswordLength = ad->password_len;
930 memcpy(nt_auth_identity->Domain, ad->domain, sizeof(WCHAR)*ad->domain_len);
931 nt_auth_identity->DomainLength = ad->domain_len;
932 LeaveCriticalSection(&authcache_cs);
933 return TRUE;
936 LeaveCriticalSection(&authcache_cs);
938 return FALSE;
941 static void cache_authorization(LPWSTR host, LPWSTR scheme,
942 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
944 authorizationData *ad;
945 BOOL found = FALSE;
947 TRACE("Caching authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
949 EnterCriticalSection(&authcache_cs);
950 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry)
951 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
952 found = TRUE;
953 break;
956 if(found) {
957 heap_free(ad->user);
958 heap_free(ad->password);
959 heap_free(ad->domain);
960 } else {
961 ad = heap_alloc(sizeof(authorizationData));
962 if(!ad) {
963 LeaveCriticalSection(&authcache_cs);
964 return;
967 ad->host = heap_strdupW(host);
968 ad->scheme = heap_strdupW(scheme);
969 list_add_head(&authorizationCache, &ad->entry);
972 ad->user = heap_strndupW(nt_auth_identity->User, nt_auth_identity->UserLength);
973 ad->password = heap_strndupW(nt_auth_identity->Password, nt_auth_identity->PasswordLength);
974 ad->domain = heap_strndupW(nt_auth_identity->Domain, nt_auth_identity->DomainLength);
975 ad->user_len = nt_auth_identity->UserLength;
976 ad->password_len = nt_auth_identity->PasswordLength;
977 ad->domain_len = nt_auth_identity->DomainLength;
979 if(!ad->host || !ad->scheme || !ad->user || !ad->password
980 || (nt_auth_identity->Domain && !ad->domain)) {
981 heap_free(ad->host);
982 heap_free(ad->scheme);
983 heap_free(ad->user);
984 heap_free(ad->password);
985 heap_free(ad->domain);
986 list_remove(&ad->entry);
987 heap_free(ad);
990 LeaveCriticalSection(&authcache_cs);
993 static BOOL HTTP_DoAuthorization( http_request_t *request, LPCWSTR pszAuthValue,
994 struct HttpAuthInfo **ppAuthInfo,
995 LPWSTR domain_and_username, LPWSTR password,
996 LPWSTR host )
998 SECURITY_STATUS sec_status;
999 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
1000 BOOL first = FALSE;
1001 LPWSTR szRealm = NULL;
1003 TRACE("%s\n", debugstr_w(pszAuthValue));
1005 if (!pAuthInfo)
1007 TimeStamp exp;
1009 first = TRUE;
1010 pAuthInfo = heap_alloc(sizeof(*pAuthInfo));
1011 if (!pAuthInfo)
1012 return FALSE;
1014 SecInvalidateHandle(&pAuthInfo->cred);
1015 SecInvalidateHandle(&pAuthInfo->ctx);
1016 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
1017 pAuthInfo->attr = 0;
1018 pAuthInfo->auth_data = NULL;
1019 pAuthInfo->auth_data_len = 0;
1020 pAuthInfo->finished = FALSE;
1022 if (is_basic_auth_value(pszAuthValue,NULL))
1024 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
1025 pAuthInfo->scheme = heap_strdupW(szBasic);
1026 if (!pAuthInfo->scheme)
1028 heap_free(pAuthInfo);
1029 return FALSE;
1032 else
1034 PVOID pAuthData;
1035 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
1037 pAuthInfo->scheme = heap_strdupW(pszAuthValue);
1038 if (!pAuthInfo->scheme)
1040 heap_free(pAuthInfo);
1041 return FALSE;
1044 if (domain_and_username)
1046 WCHAR *user = strchrW(domain_and_username, '\\');
1047 WCHAR *domain = domain_and_username;
1049 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1051 pAuthData = &nt_auth_identity;
1053 if (user) user++;
1054 else
1056 user = domain_and_username;
1057 domain = NULL;
1060 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1061 nt_auth_identity.User = user;
1062 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
1063 nt_auth_identity.Domain = domain;
1064 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
1065 nt_auth_identity.Password = password;
1066 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
1068 cache_authorization(host, pAuthInfo->scheme, &nt_auth_identity);
1070 else if(retrieve_cached_authorization(host, pAuthInfo->scheme, &nt_auth_identity))
1071 pAuthData = &nt_auth_identity;
1072 else
1073 /* use default credentials */
1074 pAuthData = NULL;
1076 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
1077 SECPKG_CRED_OUTBOUND, NULL,
1078 pAuthData, NULL,
1079 NULL, &pAuthInfo->cred,
1080 &exp);
1082 if(pAuthData && !domain_and_username) {
1083 heap_free(nt_auth_identity.User);
1084 heap_free(nt_auth_identity.Domain);
1085 heap_free(nt_auth_identity.Password);
1088 if (sec_status == SEC_E_OK)
1090 PSecPkgInfoW sec_pkg_info;
1091 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
1092 if (sec_status == SEC_E_OK)
1094 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
1095 FreeContextBuffer(sec_pkg_info);
1098 if (sec_status != SEC_E_OK)
1100 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1101 debugstr_w(pAuthInfo->scheme), sec_status);
1102 heap_free(pAuthInfo->scheme);
1103 heap_free(pAuthInfo);
1104 return FALSE;
1107 *ppAuthInfo = pAuthInfo;
1109 else if (pAuthInfo->finished)
1110 return FALSE;
1112 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
1113 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
1115 ERR("authentication scheme changed from %s to %s\n",
1116 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
1117 return FALSE;
1120 if (is_basic_auth_value(pszAuthValue,&szRealm))
1122 int userlen;
1123 int passlen;
1124 char *auth_data = NULL;
1125 UINT auth_data_len = 0;
1127 TRACE("basic authentication realm %s\n",debugstr_w(szRealm));
1129 if (!domain_and_username)
1131 if (host && szRealm)
1132 auth_data_len = retrieve_cached_basic_authorization(host, szRealm,&auth_data);
1133 if (auth_data_len == 0)
1135 heap_free(szRealm);
1136 return FALSE;
1139 else
1141 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
1142 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
1144 /* length includes a nul terminator, which will be re-used for the ':' */
1145 auth_data = heap_alloc(userlen + 1 + passlen);
1146 if (!auth_data)
1148 heap_free(szRealm);
1149 return FALSE;
1152 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
1153 auth_data[userlen] = ':';
1154 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
1155 auth_data_len = userlen + 1 + passlen;
1156 if (host && szRealm)
1157 cache_basic_authorization(host, szRealm, auth_data, auth_data_len);
1160 pAuthInfo->auth_data = auth_data;
1161 pAuthInfo->auth_data_len = auth_data_len;
1162 pAuthInfo->finished = TRUE;
1163 heap_free(szRealm);
1164 return TRUE;
1166 else
1168 LPCWSTR pszAuthData;
1169 SecBufferDesc out_desc, in_desc;
1170 SecBuffer out, in;
1171 unsigned char *buffer;
1172 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
1173 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
1175 in.BufferType = SECBUFFER_TOKEN;
1176 in.cbBuffer = 0;
1177 in.pvBuffer = NULL;
1179 in_desc.ulVersion = 0;
1180 in_desc.cBuffers = 1;
1181 in_desc.pBuffers = &in;
1183 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
1184 if (*pszAuthData == ' ')
1186 pszAuthData++;
1187 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
1188 in.pvBuffer = heap_alloc(in.cbBuffer);
1189 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
1192 buffer = heap_alloc(pAuthInfo->max_token);
1194 out.BufferType = SECBUFFER_TOKEN;
1195 out.cbBuffer = pAuthInfo->max_token;
1196 out.pvBuffer = buffer;
1198 out_desc.ulVersion = 0;
1199 out_desc.cBuffers = 1;
1200 out_desc.pBuffers = &out;
1202 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
1203 first ? NULL : &pAuthInfo->ctx,
1204 first ? request->server->name : NULL,
1205 context_req, 0, SECURITY_NETWORK_DREP,
1206 in.pvBuffer ? &in_desc : NULL,
1207 0, &pAuthInfo->ctx, &out_desc,
1208 &pAuthInfo->attr, &pAuthInfo->exp);
1209 if (sec_status == SEC_E_OK)
1211 pAuthInfo->finished = TRUE;
1212 pAuthInfo->auth_data = out.pvBuffer;
1213 pAuthInfo->auth_data_len = out.cbBuffer;
1214 TRACE("sending last auth packet\n");
1216 else if (sec_status == SEC_I_CONTINUE_NEEDED)
1218 pAuthInfo->auth_data = out.pvBuffer;
1219 pAuthInfo->auth_data_len = out.cbBuffer;
1220 TRACE("sending next auth packet\n");
1222 else
1224 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
1225 heap_free(out.pvBuffer);
1226 destroy_authinfo(pAuthInfo);
1227 *ppAuthInfo = NULL;
1228 return FALSE;
1232 return TRUE;
1235 /***********************************************************************
1236 * HTTP_HttpAddRequestHeadersW (internal)
1238 static DWORD HTTP_HttpAddRequestHeadersW(http_request_t *request,
1239 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1241 LPWSTR lpszStart;
1242 LPWSTR lpszEnd;
1243 LPWSTR buffer;
1244 DWORD len, res = ERROR_HTTP_INVALID_HEADER;
1246 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
1248 if( dwHeaderLength == ~0U )
1249 len = strlenW(lpszHeader);
1250 else
1251 len = dwHeaderLength;
1252 buffer = heap_alloc(sizeof(WCHAR)*(len+1));
1253 lstrcpynW( buffer, lpszHeader, len + 1);
1255 lpszStart = buffer;
1259 LPWSTR * pFieldAndValue;
1261 lpszEnd = lpszStart;
1263 while (*lpszEnd != '\0')
1265 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1266 break;
1267 lpszEnd++;
1270 if (*lpszStart == '\0')
1271 break;
1273 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1275 *lpszEnd = '\0';
1276 lpszEnd++; /* Jump over newline */
1278 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
1279 if (*lpszStart == '\0')
1281 /* Skip 0-length headers */
1282 lpszStart = lpszEnd;
1283 res = ERROR_SUCCESS;
1284 continue;
1286 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
1287 if (pFieldAndValue)
1289 res = HTTP_VerifyValidHeader(request, pFieldAndValue[0]);
1290 if (res == ERROR_SUCCESS)
1291 res = HTTP_ProcessHeader(request, pFieldAndValue[0],
1292 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
1293 HTTP_FreeTokens(pFieldAndValue);
1296 lpszStart = lpszEnd;
1297 } while (res == ERROR_SUCCESS);
1299 heap_free(buffer);
1300 return res;
1303 /***********************************************************************
1304 * HttpAddRequestHeadersW (WININET.@)
1306 * Adds one or more HTTP header to the request handler
1308 * NOTE
1309 * On Windows if dwHeaderLength includes the trailing '\0', then
1310 * HttpAddRequestHeadersW() adds it too. However this results in an
1311 * invalid HTTP header which is rejected by some servers so we probably
1312 * don't need to match Windows on that point.
1314 * RETURNS
1315 * TRUE on success
1316 * FALSE on failure
1319 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
1320 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1322 http_request_t *request;
1323 DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
1325 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1327 if (!lpszHeader)
1328 return TRUE;
1330 request = (http_request_t*) get_handle_object( hHttpRequest );
1331 if (request && request->hdr.htype == WH_HHTTPREQ)
1332 res = HTTP_HttpAddRequestHeadersW( request, lpszHeader, dwHeaderLength, dwModifier );
1333 if( request )
1334 WININET_Release( &request->hdr );
1336 if(res != ERROR_SUCCESS)
1337 SetLastError(res);
1338 return res == ERROR_SUCCESS;
1341 /***********************************************************************
1342 * HttpAddRequestHeadersA (WININET.@)
1344 * Adds one or more HTTP header to the request handler
1346 * RETURNS
1347 * TRUE on success
1348 * FALSE on failure
1351 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
1352 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1354 DWORD len;
1355 LPWSTR hdr;
1356 BOOL r;
1358 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1360 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
1361 hdr = heap_alloc(len*sizeof(WCHAR));
1362 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
1363 if( dwHeaderLength != ~0U )
1364 dwHeaderLength = len;
1366 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
1368 heap_free( hdr );
1369 return r;
1372 static void free_accept_types( WCHAR **accept_types )
1374 WCHAR *ptr, **types = accept_types;
1376 if (!types) return;
1377 while ((ptr = *types))
1379 heap_free( ptr );
1380 types++;
1382 heap_free( accept_types );
1385 static WCHAR **convert_accept_types( const char **accept_types )
1387 unsigned int count;
1388 const char **types = accept_types;
1389 WCHAR **typesW;
1390 BOOL invalid_pointer = FALSE;
1392 if (!types) return NULL;
1393 count = 0;
1394 while (*types)
1396 __TRY
1398 /* find out how many there are */
1399 if (*types && **types)
1401 TRACE("accept type: %s\n", debugstr_a(*types));
1402 count++;
1405 __EXCEPT_PAGE_FAULT
1407 WARN("invalid accept type pointer\n");
1408 invalid_pointer = TRUE;
1410 __ENDTRY;
1411 types++;
1413 if (invalid_pointer) return NULL;
1414 if (!(typesW = heap_alloc( sizeof(WCHAR *) * (count + 1) ))) return NULL;
1415 count = 0;
1416 types = accept_types;
1417 while (*types)
1419 if (*types && **types) typesW[count++] = heap_strdupAtoW( *types );
1420 types++;
1422 typesW[count] = NULL;
1423 return typesW;
1426 /***********************************************************************
1427 * HttpOpenRequestA (WININET.@)
1429 * Open a HTTP request handle
1431 * RETURNS
1432 * HINTERNET a HTTP request handle on success
1433 * NULL on failure
1436 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
1437 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
1438 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
1439 DWORD dwFlags, DWORD_PTR dwContext)
1441 LPWSTR szVerb = NULL, szObjectName = NULL;
1442 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
1443 HINTERNET rc = NULL;
1445 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
1446 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
1447 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
1448 dwFlags, dwContext);
1450 if (lpszVerb)
1452 szVerb = heap_strdupAtoW(lpszVerb);
1453 if ( !szVerb )
1454 goto end;
1457 if (lpszObjectName)
1459 szObjectName = heap_strdupAtoW(lpszObjectName);
1460 if ( !szObjectName )
1461 goto end;
1464 if (lpszVersion)
1466 szVersion = heap_strdupAtoW(lpszVersion);
1467 if ( !szVersion )
1468 goto end;
1471 if (lpszReferrer)
1473 szReferrer = heap_strdupAtoW(lpszReferrer);
1474 if ( !szReferrer )
1475 goto end;
1478 szAcceptTypes = convert_accept_types( lpszAcceptTypes );
1479 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName, szVersion, szReferrer,
1480 (const WCHAR **)szAcceptTypes, dwFlags, dwContext);
1482 end:
1483 free_accept_types(szAcceptTypes);
1484 heap_free(szReferrer);
1485 heap_free(szVersion);
1486 heap_free(szObjectName);
1487 heap_free(szVerb);
1488 return rc;
1491 /***********************************************************************
1492 * HTTP_EncodeBase64
1494 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1496 UINT n = 0, x;
1497 static const CHAR HTTP_Base64Enc[] =
1498 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1500 while( len > 0 )
1502 /* first 6 bits, all from bin[0] */
1503 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1504 x = (bin[0] & 3) << 4;
1506 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1507 if( len == 1 )
1509 base64[n++] = HTTP_Base64Enc[x];
1510 base64[n++] = '=';
1511 base64[n++] = '=';
1512 break;
1514 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1515 x = ( bin[1] & 0x0f ) << 2;
1517 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1518 if( len == 2 )
1520 base64[n++] = HTTP_Base64Enc[x];
1521 base64[n++] = '=';
1522 break;
1524 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1526 /* last 6 bits, all from bin [2] */
1527 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1528 bin += 3;
1529 len -= 3;
1531 base64[n] = 0;
1532 return n;
1535 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1536 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1537 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1538 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1539 static const signed char HTTP_Base64Dec[256] =
1541 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1542 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1543 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1544 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1545 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1546 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1547 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1548 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1549 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1550 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1551 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1552 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1553 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1554 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1555 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1556 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1557 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1558 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1559 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1560 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1561 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1562 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1563 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1564 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1565 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1566 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1568 #undef CH
1570 /***********************************************************************
1571 * HTTP_DecodeBase64
1573 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1575 unsigned int n = 0;
1577 while(*base64)
1579 signed char in[4];
1581 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1582 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1583 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1584 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1586 WARN("invalid base64: %s\n", debugstr_w(base64));
1587 return 0;
1589 if (bin)
1590 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1591 n++;
1593 if ((base64[2] == '=') && (base64[3] == '='))
1594 break;
1595 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1596 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1598 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1599 return 0;
1601 if (bin)
1602 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1603 n++;
1605 if (base64[3] == '=')
1606 break;
1607 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1608 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1610 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1611 return 0;
1613 if (bin)
1614 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1615 n++;
1617 base64 += 4;
1620 return n;
1623 /***********************************************************************
1624 * HTTP_InsertAuthorization
1626 * Insert or delete the authorization field in the request header.
1628 static BOOL HTTP_InsertAuthorization( http_request_t *request, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1630 if (pAuthInfo)
1632 static const WCHAR wszSpace[] = {' ',0};
1633 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1634 unsigned int len;
1635 WCHAR *authorization = NULL;
1637 if (pAuthInfo->auth_data_len)
1639 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1640 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1641 authorization = heap_alloc((len+1)*sizeof(WCHAR));
1642 if (!authorization)
1643 return FALSE;
1645 strcpyW(authorization, pAuthInfo->scheme);
1646 strcatW(authorization, wszSpace);
1647 HTTP_EncodeBase64(pAuthInfo->auth_data,
1648 pAuthInfo->auth_data_len,
1649 authorization+strlenW(authorization));
1651 /* clear the data as it isn't valid now that it has been sent to the
1652 * server, unless it's Basic authentication which doesn't do
1653 * connection tracking */
1654 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1656 heap_free(pAuthInfo->auth_data);
1657 pAuthInfo->auth_data = NULL;
1658 pAuthInfo->auth_data_len = 0;
1662 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1664 HTTP_ProcessHeader(request, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1665 heap_free(authorization);
1667 return TRUE;
1670 static WCHAR *build_proxy_path_url(http_request_t *req)
1672 DWORD size, len;
1673 WCHAR *url;
1675 len = strlenW(req->server->scheme_host_port);
1676 size = len + strlenW(req->path) + 1;
1677 if(*req->path != '/')
1678 size++;
1679 url = heap_alloc(size * sizeof(WCHAR));
1680 if(!url)
1681 return NULL;
1683 memcpy(url, req->server->scheme_host_port, len*sizeof(WCHAR));
1684 if(*req->path != '/')
1685 url[len++] = '/';
1687 strcpyW(url+len, req->path);
1689 TRACE("url=%s\n", debugstr_w(url));
1690 return url;
1693 static BOOL HTTP_DomainMatches(LPCWSTR server, LPCWSTR domain)
1695 static const WCHAR localW[] = { '<','l','o','c','a','l','>',0 };
1696 BOOL ret = FALSE;
1698 if (!strcmpiW( domain, localW ) && !strchrW( server, '.' ))
1699 ret = TRUE;
1700 else if (*domain == '*')
1702 if (domain[1] == '.')
1704 LPCWSTR dot;
1706 /* For a hostname to match a wildcard, the last domain must match
1707 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1708 * hostname is www.foo.a.b, it matches, but a.b does not.
1710 dot = strchrW( server, '.' );
1711 if (dot)
1713 int len = strlenW( dot + 1 );
1715 if (len > strlenW( domain + 2 ))
1717 LPCWSTR ptr;
1719 /* The server's domain is longer than the wildcard, so it
1720 * could be a subdomain. Compare the last portion of the
1721 * server's domain.
1723 ptr = dot + len + 1 - strlenW( domain + 2 );
1724 if (!strcmpiW( ptr, domain + 2 ))
1726 /* This is only a match if the preceding character is
1727 * a '.', i.e. that it is a matching domain. E.g.
1728 * if domain is '*.b.c' and server is 'www.ab.c' they
1729 * do not match.
1731 ret = *(ptr - 1) == '.';
1734 else
1735 ret = !strcmpiW( dot + 1, domain + 2 );
1739 else
1740 ret = !strcmpiW( server, domain );
1741 return ret;
1744 static BOOL HTTP_ShouldBypassProxy(appinfo_t *lpwai, LPCWSTR server)
1746 LPCWSTR ptr;
1747 BOOL ret = FALSE;
1749 if (!lpwai->proxyBypass) return FALSE;
1750 ptr = lpwai->proxyBypass;
1751 do {
1752 LPCWSTR tmp = ptr;
1754 ptr = strchrW( ptr, ';' );
1755 if (!ptr)
1756 ptr = strchrW( tmp, ' ' );
1757 if (ptr)
1759 if (ptr - tmp < INTERNET_MAX_HOST_NAME_LENGTH)
1761 WCHAR domain[INTERNET_MAX_HOST_NAME_LENGTH];
1763 memcpy( domain, tmp, (ptr - tmp) * sizeof(WCHAR) );
1764 domain[ptr - tmp] = 0;
1765 ret = HTTP_DomainMatches( server, domain );
1767 ptr += 1;
1769 else if (*tmp)
1770 ret = HTTP_DomainMatches( server, tmp );
1771 } while (ptr && !ret);
1772 return ret;
1775 /***********************************************************************
1776 * HTTP_DealWithProxy
1778 static BOOL HTTP_DealWithProxy(appinfo_t *hIC, http_session_t *session, http_request_t *request)
1780 static const WCHAR protoHttp[] = { 'h','t','t','p',0 };
1781 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1782 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1783 WCHAR buf[INTERNET_MAX_HOST_NAME_LENGTH];
1784 WCHAR protoProxy[INTERNET_MAX_URL_LENGTH];
1785 DWORD protoProxyLen = INTERNET_MAX_URL_LENGTH;
1786 WCHAR proxy[INTERNET_MAX_URL_LENGTH];
1787 static WCHAR szNul[] = { 0 };
1788 URL_COMPONENTSW UrlComponents;
1789 server_t *new_server;
1790 BOOL is_https;
1792 memset( &UrlComponents, 0, sizeof UrlComponents );
1793 UrlComponents.dwStructSize = sizeof UrlComponents;
1794 UrlComponents.lpszHostName = buf;
1795 UrlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
1797 if (!INTERNET_FindProxyForProtocol(hIC->proxy, protoHttp, protoProxy, &protoProxyLen))
1798 return FALSE;
1799 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1800 protoProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1801 sprintfW(proxy, szFormat, protoProxy);
1802 else
1803 strcpyW(proxy, protoProxy);
1804 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1805 return FALSE;
1806 if( UrlComponents.dwHostNameLength == 0 )
1807 return FALSE;
1809 if( !request->path )
1810 request->path = szNul;
1812 is_https = (UrlComponents.nScheme == INTERNET_SCHEME_HTTPS);
1813 if (is_https && UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1814 UrlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
1816 new_server = get_server(UrlComponents.lpszHostName, UrlComponents.nPort, is_https, TRUE);
1817 if(!new_server)
1818 return FALSE;
1820 request->proxy = new_server;
1822 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server->name), new_server->port);
1823 return TRUE;
1826 static DWORD HTTP_ResolveName(http_request_t *request)
1828 server_t *server = request->proxy ? request->proxy : request->server;
1829 socklen_t addr_len;
1830 void *addr;
1832 if(server->addr_len)
1833 return ERROR_SUCCESS;
1835 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1836 INTERNET_STATUS_RESOLVING_NAME,
1837 server->name,
1838 (strlenW(server->name)+1) * sizeof(WCHAR));
1840 addr_len = sizeof(server->addr);
1841 if (!GetAddress(server->name, server->port, (struct sockaddr *)&server->addr, &addr_len))
1842 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1844 switch(server->addr.ss_family) {
1845 case AF_INET:
1846 addr = &((struct sockaddr_in *)&server->addr)->sin_addr;
1847 break;
1848 case AF_INET6:
1849 addr = &((struct sockaddr_in6 *)&server->addr)->sin6_addr;
1850 break;
1851 default:
1852 WARN("unsupported family %d\n", server->addr.ss_family);
1853 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1856 server->addr_len = addr_len;
1857 inet_ntop(server->addr.ss_family, addr, server->addr_str, sizeof(server->addr_str));
1858 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1859 INTERNET_STATUS_NAME_RESOLVED,
1860 server->addr_str, strlen(server->addr_str)+1);
1862 TRACE("resolved %s to %s\n", debugstr_w(server->name), server->addr_str);
1863 return ERROR_SUCCESS;
1866 static BOOL HTTP_GetRequestURL(http_request_t *req, LPWSTR buf)
1868 static const WCHAR http[] = { 'h','t','t','p',':','/','/',0 };
1869 static const WCHAR https[] = { 'h','t','t','p','s',':','/','/',0 };
1870 static const WCHAR slash[] = { '/',0 };
1871 LPHTTPHEADERW host_header;
1872 LPCWSTR scheme;
1874 host_header = HTTP_GetHeader(req, hostW);
1875 if(!host_header)
1876 return FALSE;
1878 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1879 scheme = https;
1880 else
1881 scheme = http;
1882 strcpyW(buf, scheme);
1883 strcatW(buf, host_header->lpszValue);
1884 if (req->path[0] != '/')
1885 strcatW(buf, slash);
1886 strcatW(buf, req->path);
1887 return TRUE;
1891 /***********************************************************************
1892 * HTTPREQ_Destroy (internal)
1894 * Deallocate request handle
1897 static void HTTPREQ_Destroy(object_header_t *hdr)
1899 http_request_t *request = (http_request_t*) hdr;
1900 DWORD i;
1902 TRACE("\n");
1904 if(request->hCacheFile)
1905 CloseHandle(request->hCacheFile);
1906 if(request->req_file)
1907 req_file_release(request->req_file);
1909 request->read_section.DebugInfo->Spare[0] = 0;
1910 DeleteCriticalSection( &request->read_section );
1911 WININET_Release(&request->session->hdr);
1913 destroy_authinfo(request->authInfo);
1914 destroy_authinfo(request->proxyAuthInfo);
1916 if(request->server)
1917 server_release(request->server);
1918 if(request->proxy)
1919 server_release(request->proxy);
1921 heap_free(request->path);
1922 heap_free(request->verb);
1923 heap_free(request->version);
1924 heap_free(request->statusText);
1926 for (i = 0; i < request->nCustHeaders; i++)
1928 heap_free(request->custHeaders[i].lpszField);
1929 heap_free(request->custHeaders[i].lpszValue);
1931 destroy_data_stream(request->data_stream);
1932 heap_free(request->custHeaders);
1935 static void http_release_netconn(http_request_t *req, BOOL reuse)
1937 TRACE("%p %p\n",req, req->netconn);
1939 if(!is_valid_netconn(req->netconn))
1940 return;
1942 if(reuse && req->netconn->keep_alive) {
1943 BOOL run_collector;
1945 EnterCriticalSection(&connection_pool_cs);
1947 list_add_head(&req->netconn->server->conn_pool, &req->netconn->pool_entry);
1948 req->netconn->keep_until = GetTickCount64() + COLLECT_TIME;
1949 req->netconn = NULL;
1951 run_collector = !collector_running;
1952 collector_running = TRUE;
1954 LeaveCriticalSection(&connection_pool_cs);
1956 if(run_collector) {
1957 HANDLE thread = NULL;
1958 HMODULE module;
1960 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR*)WININET_hModule, &module);
1961 if(module)
1962 thread = CreateThread(NULL, 0, collect_connections_proc, NULL, 0, NULL);
1963 if(!thread) {
1964 EnterCriticalSection(&connection_pool_cs);
1965 collector_running = FALSE;
1966 LeaveCriticalSection(&connection_pool_cs);
1968 if(module)
1969 FreeLibrary(module);
1971 else
1972 CloseHandle(thread);
1974 return;
1977 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1978 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1980 close_netconn(req->netconn);
1982 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1983 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1986 static BOOL HTTP_KeepAlive(http_request_t *request)
1988 WCHAR szVersion[10];
1989 WCHAR szConnectionResponse[20];
1990 DWORD dwBufferSize = sizeof(szVersion);
1991 BOOL keepalive = FALSE;
1993 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
1994 * the connection is keep-alive by default */
1995 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_VERSION, szVersion, &dwBufferSize, NULL) == ERROR_SUCCESS
1996 && !strcmpiW(szVersion, g_szHttp1_1))
1998 keepalive = TRUE;
2001 dwBufferSize = sizeof(szConnectionResponse);
2002 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS
2003 || HTTP_HttpQueryInfoW(request, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS)
2005 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
2008 return keepalive;
2011 static void HTTPREQ_CloseConnection(object_header_t *hdr)
2013 http_request_t *req = (http_request_t*)hdr;
2015 http_release_netconn(req, drain_content(req, FALSE));
2018 static DWORD str_to_buffer(const WCHAR *str, void *buffer, DWORD *size, BOOL unicode)
2020 int len;
2021 if (unicode)
2023 WCHAR *buf = buffer;
2025 if (str) len = strlenW(str);
2026 else len = 0;
2027 if (*size < (len + 1) * sizeof(WCHAR))
2029 *size = (len + 1) * sizeof(WCHAR);
2030 return ERROR_INSUFFICIENT_BUFFER;
2032 if (str) strcpyW(buf, str);
2033 else buf[0] = 0;
2035 *size = len;
2036 return ERROR_SUCCESS;
2038 else
2040 char *buf = buffer;
2042 if (str) len = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
2043 else len = 1;
2044 if (*size < len)
2046 *size = len;
2047 return ERROR_INSUFFICIENT_BUFFER;
2049 if (str) WideCharToMultiByte(CP_ACP, 0, str, -1, buf, *size, NULL, NULL);
2050 else buf[0] = 0;
2052 *size = len - 1;
2053 return ERROR_SUCCESS;
2057 static DWORD HTTPREQ_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2059 http_request_t *req = (http_request_t*)hdr;
2061 switch(option) {
2062 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO:
2064 INTERNET_DIAGNOSTIC_SOCKET_INFO *info = buffer;
2066 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2068 if (*size < sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO))
2069 return ERROR_INSUFFICIENT_BUFFER;
2070 *size = sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO);
2071 /* FIXME: can't get a SOCKET from our connection since we don't use
2072 * winsock
2074 info->Socket = 0;
2075 /* FIXME: get source port from req->netConnection */
2076 info->SourcePort = 0;
2077 info->DestPort = req->server->port;
2078 info->Flags = 0;
2079 if (HTTP_KeepAlive(req))
2080 info->Flags |= IDSI_FLAG_KEEP_ALIVE;
2081 if (req->proxy)
2082 info->Flags |= IDSI_FLAG_PROXY;
2083 if (is_valid_netconn(req->netconn) && req->netconn->secure)
2084 info->Flags |= IDSI_FLAG_SECURE;
2086 return ERROR_SUCCESS;
2089 case 98:
2090 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2091 /* fall through */
2092 case INTERNET_OPTION_SECURITY_FLAGS:
2094 DWORD flags;
2096 if (*size < sizeof(ULONG))
2097 return ERROR_INSUFFICIENT_BUFFER;
2099 *size = sizeof(DWORD);
2100 flags = is_valid_netconn(req->netconn) ? req->netconn->security_flags : req->security_flags | req->server->security_flags;
2101 *(DWORD *)buffer = flags;
2103 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags);
2104 return ERROR_SUCCESS;
2107 case INTERNET_OPTION_HANDLE_TYPE:
2108 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2110 if (*size < sizeof(ULONG))
2111 return ERROR_INSUFFICIENT_BUFFER;
2113 *size = sizeof(DWORD);
2114 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
2115 return ERROR_SUCCESS;
2117 case INTERNET_OPTION_URL: {
2118 WCHAR url[INTERNET_MAX_URL_LENGTH];
2119 HTTPHEADERW *host;
2121 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
2123 TRACE("INTERNET_OPTION_URL\n");
2125 host = HTTP_GetHeader(req, hostW);
2126 strcpyW(url, httpW);
2127 strcatW(url, host->lpszValue);
2128 strcatW(url, req->path);
2130 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
2131 return str_to_buffer(url, buffer, size, unicode);
2133 case INTERNET_OPTION_USER_AGENT:
2134 return str_to_buffer(req->session->appInfo->agent, buffer, size, unicode);
2135 case INTERNET_OPTION_USERNAME:
2136 return str_to_buffer(req->session->userName, buffer, size, unicode);
2137 case INTERNET_OPTION_PASSWORD:
2138 return str_to_buffer(req->session->password, buffer, size, unicode);
2139 case INTERNET_OPTION_PROXY_USERNAME:
2140 return str_to_buffer(req->session->appInfo->proxyUsername, buffer, size, unicode);
2141 case INTERNET_OPTION_PROXY_PASSWORD:
2142 return str_to_buffer(req->session->appInfo->proxyPassword, buffer, size, unicode);
2144 case INTERNET_OPTION_CACHE_TIMESTAMPS: {
2145 INTERNET_CACHE_ENTRY_INFOW *info;
2146 INTERNET_CACHE_TIMESTAMPS *ts = buffer;
2147 WCHAR url[INTERNET_MAX_URL_LENGTH];
2148 DWORD nbytes, error;
2149 BOOL ret;
2151 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2153 if (*size < sizeof(*ts))
2155 *size = sizeof(*ts);
2156 return ERROR_INSUFFICIENT_BUFFER;
2158 nbytes = 0;
2159 HTTP_GetRequestURL(req, url);
2160 ret = GetUrlCacheEntryInfoW(url, NULL, &nbytes);
2161 error = GetLastError();
2162 if (!ret && error == ERROR_INSUFFICIENT_BUFFER)
2164 if (!(info = heap_alloc(nbytes)))
2165 return ERROR_OUTOFMEMORY;
2167 GetUrlCacheEntryInfoW(url, info, &nbytes);
2169 ts->ftExpires = info->ExpireTime;
2170 ts->ftLastModified = info->LastModifiedTime;
2172 heap_free(info);
2173 *size = sizeof(*ts);
2174 return ERROR_SUCCESS;
2176 return error;
2179 case INTERNET_OPTION_DATAFILE_NAME: {
2180 DWORD req_size;
2182 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2184 if(!req->req_file) {
2185 *size = 0;
2186 return ERROR_INTERNET_ITEM_NOT_FOUND;
2189 if(unicode) {
2190 req_size = (lstrlenW(req->req_file->file_name)+1) * sizeof(WCHAR);
2191 if(*size < req_size)
2192 return ERROR_INSUFFICIENT_BUFFER;
2194 *size = req_size;
2195 memcpy(buffer, req->req_file->file_name, *size);
2196 return ERROR_SUCCESS;
2197 }else {
2198 req_size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name, -1, NULL, 0, NULL, NULL);
2199 if (req_size > *size)
2200 return ERROR_INSUFFICIENT_BUFFER;
2202 *size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name,
2203 -1, buffer, *size, NULL, NULL);
2204 return ERROR_SUCCESS;
2208 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
2209 PCCERT_CONTEXT context;
2211 if(!req->netconn)
2212 return ERROR_INTERNET_INVALID_OPERATION;
2214 if(*size < sizeof(INTERNET_CERTIFICATE_INFOA)) {
2215 *size = sizeof(INTERNET_CERTIFICATE_INFOA);
2216 return ERROR_INSUFFICIENT_BUFFER;
2219 context = (PCCERT_CONTEXT)NETCON_GetCert(req->netconn);
2220 if(context) {
2221 INTERNET_CERTIFICATE_INFOA *info = (INTERNET_CERTIFICATE_INFOA*)buffer;
2222 DWORD len;
2224 memset(info, 0, sizeof(*info));
2225 info->ftExpiry = context->pCertInfo->NotAfter;
2226 info->ftStart = context->pCertInfo->NotBefore;
2227 len = CertNameToStrA(context->dwCertEncodingType,
2228 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2229 info->lpszSubjectInfo = LocalAlloc(0, len);
2230 if(info->lpszSubjectInfo)
2231 CertNameToStrA(context->dwCertEncodingType,
2232 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2233 info->lpszSubjectInfo, len);
2234 len = CertNameToStrA(context->dwCertEncodingType,
2235 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2236 info->lpszIssuerInfo = LocalAlloc(0, len);
2237 if(info->lpszIssuerInfo)
2238 CertNameToStrA(context->dwCertEncodingType,
2239 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2240 info->lpszIssuerInfo, len);
2241 info->dwKeySize = NETCON_GetCipherStrength(req->netconn);
2242 CertFreeCertificateContext(context);
2243 return ERROR_SUCCESS;
2245 return ERROR_NOT_SUPPORTED;
2247 case INTERNET_OPTION_CONNECT_TIMEOUT:
2248 if (*size < sizeof(DWORD))
2249 return ERROR_INSUFFICIENT_BUFFER;
2251 *size = sizeof(DWORD);
2252 *(DWORD *)buffer = req->connect_timeout;
2253 return ERROR_SUCCESS;
2254 case INTERNET_OPTION_REQUEST_FLAGS: {
2255 DWORD flags = 0;
2257 if (*size < sizeof(DWORD))
2258 return ERROR_INSUFFICIENT_BUFFER;
2260 /* FIXME: Add support for:
2261 * INTERNET_REQFLAG_FROM_CACHE
2262 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2265 if(req->proxy)
2266 flags |= INTERNET_REQFLAG_VIA_PROXY;
2267 if(!req->status_code)
2268 flags |= INTERNET_REQFLAG_NO_HEADERS;
2270 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags);
2272 *size = sizeof(DWORD);
2273 *(DWORD*)buffer = flags;
2274 return ERROR_SUCCESS;
2278 return INET_QueryOption(hdr, option, buffer, size, unicode);
2281 static DWORD HTTPREQ_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
2283 http_request_t *req = (http_request_t*)hdr;
2285 switch(option) {
2286 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2287 TRACE("Undocumented option 99\n");
2289 if (!buffer || size != sizeof(DWORD))
2290 return ERROR_INVALID_PARAMETER;
2291 if(*(DWORD*)buffer & ~SECURITY_SET_MASK)
2292 return ERROR_INTERNET_OPTION_NOT_SETTABLE;
2294 /* fall through */
2295 case INTERNET_OPTION_SECURITY_FLAGS:
2297 DWORD flags;
2299 if (!buffer || size != sizeof(DWORD))
2300 return ERROR_INVALID_PARAMETER;
2301 flags = *(DWORD *)buffer;
2302 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags);
2303 flags &= SECURITY_SET_MASK;
2304 req->security_flags |= flags;
2305 if(is_valid_netconn(req->netconn))
2306 req->netconn->security_flags |= flags;
2307 return ERROR_SUCCESS;
2309 case INTERNET_OPTION_CONNECT_TIMEOUT:
2310 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2311 req->connect_timeout = *(DWORD *)buffer;
2312 return ERROR_SUCCESS;
2314 case INTERNET_OPTION_SEND_TIMEOUT:
2315 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2316 req->send_timeout = *(DWORD *)buffer;
2317 return ERROR_SUCCESS;
2319 case INTERNET_OPTION_RECEIVE_TIMEOUT:
2320 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2321 req->receive_timeout = *(DWORD *)buffer;
2322 return ERROR_SUCCESS;
2324 case INTERNET_OPTION_USERNAME:
2325 heap_free(req->session->userName);
2326 if (!(req->session->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2327 return ERROR_SUCCESS;
2329 case INTERNET_OPTION_PASSWORD:
2330 heap_free(req->session->password);
2331 if (!(req->session->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2332 return ERROR_SUCCESS;
2334 case INTERNET_OPTION_PROXY_USERNAME:
2335 heap_free(req->session->appInfo->proxyUsername);
2336 if (!(req->session->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2337 return ERROR_SUCCESS;
2339 case INTERNET_OPTION_PROXY_PASSWORD:
2340 heap_free(req->session->appInfo->proxyPassword);
2341 if (!(req->session->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2342 return ERROR_SUCCESS;
2344 case INTERNET_OPTION_HTTP_DECODING:
2345 if(size != sizeof(BOOL))
2346 return ERROR_INVALID_PARAMETER;
2347 req->decoding = *(BOOL*)buffer;
2348 return ERROR_SUCCESS;
2351 return INET_SetOption(hdr, option, buffer, size);
2354 static void commit_cache_entry(http_request_t *req)
2356 WCHAR url[INTERNET_MAX_URL_LENGTH];
2358 TRACE("%p\n", req);
2360 CloseHandle(req->hCacheFile);
2361 req->hCacheFile = NULL;
2363 if(HTTP_GetRequestURL(req, url)) {
2364 WCHAR *header;
2365 DWORD header_len;
2366 BOOL res;
2368 header = build_response_header(req, TRUE);
2369 header_len = (header ? strlenW(header) : 0);
2370 res = CommitUrlCacheEntryW(url, req->req_file->file_name, req->expires,
2371 req->last_modified, NORMAL_CACHE_ENTRY,
2372 header, header_len, NULL, 0);
2373 if(res)
2374 req->req_file->is_committed = TRUE;
2375 else
2376 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2377 heap_free(header);
2381 static void create_cache_entry(http_request_t *req)
2383 static const WCHAR no_cacheW[] = {'n','o','-','c','a','c','h','e',0};
2384 static const WCHAR no_storeW[] = {'n','o','-','s','t','o','r','e',0};
2386 WCHAR url[INTERNET_MAX_URL_LENGTH];
2387 WCHAR file_name[MAX_PATH+1];
2388 BOOL b = TRUE;
2390 /* FIXME: We should free previous cache file earlier */
2391 if(req->req_file) {
2392 req_file_release(req->req_file);
2393 req->req_file = NULL;
2395 if(req->hCacheFile) {
2396 CloseHandle(req->hCacheFile);
2397 req->hCacheFile = NULL;
2400 if(req->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE)
2401 b = FALSE;
2403 if(b) {
2404 int header_idx = HTTP_GetCustomHeaderIndex(req, szCache_Control, 0, FALSE);
2405 if(header_idx != -1) {
2406 WCHAR *ptr;
2408 for(ptr=req->custHeaders[header_idx].lpszValue; *ptr; ) {
2409 WCHAR *end;
2411 while(*ptr==' ' || *ptr=='\t')
2412 ptr++;
2414 end = strchrW(ptr, ',');
2415 if(!end)
2416 end = ptr + strlenW(ptr);
2418 if(!strncmpiW(ptr, no_cacheW, sizeof(no_cacheW)/sizeof(*no_cacheW)-1)
2419 || !strncmpiW(ptr, no_storeW, sizeof(no_storeW)/sizeof(*no_storeW)-1)) {
2420 b = FALSE;
2421 break;
2424 ptr = end;
2425 if(*ptr == ',')
2426 ptr++;
2431 if(!b) {
2432 if(!(req->hdr.dwFlags & INTERNET_FLAG_NEED_FILE))
2433 return;
2435 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2438 b = HTTP_GetRequestURL(req, url);
2439 if(!b) {
2440 WARN("Could not get URL\n");
2441 return;
2444 b = CreateUrlCacheEntryW(url, req->contentLength == ~0u ? 0 : req->contentLength, NULL, file_name, 0);
2445 if(!b) {
2446 WARN("Could not create cache entry: %08x\n", GetLastError());
2447 return;
2450 create_req_file(file_name, &req->req_file);
2452 req->hCacheFile = CreateFileW(file_name, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
2453 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2454 if(req->hCacheFile == INVALID_HANDLE_VALUE) {
2455 WARN("Could not create file: %u\n", GetLastError());
2456 req->hCacheFile = NULL;
2457 return;
2460 if(req->read_size) {
2461 DWORD written;
2463 b = WriteFile(req->hCacheFile, req->read_buf+req->read_pos, req->read_size, &written, NULL);
2464 if(!b)
2465 FIXME("WriteFile failed: %u\n", GetLastError());
2467 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2468 commit_cache_entry(req);
2472 /* read some more data into the read buffer (the read section must be held) */
2473 static DWORD read_more_data( http_request_t *req, int maxlen )
2475 DWORD res;
2476 int len;
2478 if (req->read_pos)
2480 /* move existing data to the start of the buffer */
2481 if(req->read_size)
2482 memmove( req->read_buf, req->read_buf + req->read_pos, req->read_size );
2483 req->read_pos = 0;
2486 if (maxlen == -1) maxlen = sizeof(req->read_buf);
2488 res = NETCON_recv( req->netconn, req->read_buf + req->read_size,
2489 maxlen - req->read_size, BLOCKING_ALLOW, &len );
2490 if(res == ERROR_SUCCESS)
2491 req->read_size += len;
2493 return res;
2496 /* remove some amount of data from the read buffer (the read section must be held) */
2497 static void remove_data( http_request_t *req, int count )
2499 if (!(req->read_size -= count)) req->read_pos = 0;
2500 else req->read_pos += count;
2503 static DWORD read_line( http_request_t *req, LPSTR buffer, DWORD *len )
2505 int count, bytes_read, pos = 0;
2506 DWORD res;
2508 EnterCriticalSection( &req->read_section );
2509 for (;;)
2511 BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
2513 if (eol)
2515 count = eol - (req->read_buf + req->read_pos);
2516 bytes_read = count + 1;
2518 else count = bytes_read = req->read_size;
2520 count = min( count, *len - pos );
2521 memcpy( buffer + pos, req->read_buf + req->read_pos, count );
2522 pos += count;
2523 remove_data( req, bytes_read );
2524 if (eol) break;
2526 if ((res = read_more_data( req, -1 )))
2528 WARN( "read failed %u\n", res );
2529 LeaveCriticalSection( &req->read_section );
2530 return res;
2532 if (!req->read_size)
2534 *len = 0;
2535 TRACE( "returning empty string\n" );
2536 LeaveCriticalSection( &req->read_section );
2537 return ERROR_SUCCESS;
2540 LeaveCriticalSection( &req->read_section );
2542 if (pos < *len)
2544 if (pos && buffer[pos - 1] == '\r') pos--;
2545 *len = pos + 1;
2547 buffer[*len - 1] = 0;
2548 TRACE( "returning %s\n", debugstr_a(buffer));
2549 return ERROR_SUCCESS;
2552 /* check if we have reached the end of the data to read (the read section must be held) */
2553 static BOOL end_of_read_data( http_request_t *req )
2555 return !req->read_size && req->data_stream->vtbl->end_of_data(req->data_stream, req);
2558 static DWORD read_http_stream(http_request_t *req, BYTE *buf, DWORD size, DWORD *read, blocking_mode_t blocking_mode)
2560 DWORD res;
2562 res = req->data_stream->vtbl->read(req->data_stream, req, buf, size, read, blocking_mode);
2563 assert(*read <= size);
2565 if(req->hCacheFile) {
2566 if(*read) {
2567 BOOL bres;
2568 DWORD written;
2570 bres = WriteFile(req->hCacheFile, buf, *read, &written, NULL);
2571 if(!bres)
2572 FIXME("WriteFile failed: %u\n", GetLastError());
2575 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2576 commit_cache_entry(req);
2579 return res;
2582 /* fetch some more data into the read buffer (the read section must be held) */
2583 static DWORD refill_read_buffer(http_request_t *req, blocking_mode_t blocking_mode, DWORD *read_bytes)
2585 DWORD res, read=0;
2587 if(req->read_size == sizeof(req->read_buf))
2588 return ERROR_SUCCESS;
2590 if(req->read_pos) {
2591 if(req->read_size)
2592 memmove(req->read_buf, req->read_buf+req->read_pos, req->read_size);
2593 req->read_pos = 0;
2596 res = read_http_stream(req, req->read_buf+req->read_size, sizeof(req->read_buf) - req->read_size,
2597 &read, blocking_mode);
2598 req->read_size += read;
2600 TRACE("read %u bytes, read_size %u\n", read, req->read_size);
2601 if(read_bytes)
2602 *read_bytes = read;
2603 return res;
2606 /* return the size of data available to be read immediately (the read section must be held) */
2607 static DWORD get_avail_data( http_request_t *req )
2609 return req->read_size + req->data_stream->vtbl->get_avail_data(req->data_stream, req);
2612 static DWORD netconn_get_avail_data(data_stream_t *stream, http_request_t *req)
2614 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2615 DWORD avail = 0;
2617 if(is_valid_netconn(req->netconn))
2618 NETCON_query_data_available(req->netconn, &avail);
2619 return netconn_stream->content_length == ~0u
2620 ? avail
2621 : min(avail, netconn_stream->content_length-netconn_stream->content_read);
2624 static BOOL netconn_end_of_data(data_stream_t *stream, http_request_t *req)
2626 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2627 return netconn_stream->content_read == netconn_stream->content_length || !is_valid_netconn(req->netconn);
2630 static DWORD netconn_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2631 DWORD *read, blocking_mode_t blocking_mode)
2633 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2634 DWORD res = ERROR_SUCCESS;
2635 int len = 0;
2637 size = min(size, netconn_stream->content_length-netconn_stream->content_read);
2639 if(size && is_valid_netconn(req->netconn)) {
2640 if((res = NETCON_recv(req->netconn, buf, size, blocking_mode, &len))) {
2641 len = 0;
2642 if(blocking_mode == BLOCKING_DISALLOW && res == WSAEWOULDBLOCK)
2643 res = ERROR_SUCCESS;
2644 else
2645 netconn_stream->content_length = netconn_stream->content_read;
2646 }else if(!len) {
2647 netconn_stream->content_length = netconn_stream->content_read;
2651 netconn_stream->content_read += *read = len;
2652 TRACE("read %u bytes\n", len);
2653 return res;
2656 static BOOL netconn_drain_content(data_stream_t *stream, http_request_t *req)
2658 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2659 BYTE buf[1024];
2660 int len;
2662 if(netconn_end_of_data(stream, req))
2663 return TRUE;
2665 do {
2666 if(NETCON_recv(req->netconn, buf, sizeof(buf), BLOCKING_DISALLOW, &len) != ERROR_SUCCESS)
2667 return FALSE;
2669 netconn_stream->content_read += len;
2670 }while(netconn_stream->content_read < netconn_stream->content_length);
2672 return TRUE;
2675 static void netconn_destroy(data_stream_t *stream)
2679 static const data_stream_vtbl_t netconn_stream_vtbl = {
2680 netconn_get_avail_data,
2681 netconn_end_of_data,
2682 netconn_read,
2683 netconn_drain_content,
2684 netconn_destroy
2687 /* read some more data into the read buffer (the read section must be held) */
2688 static DWORD read_more_chunked_data(chunked_stream_t *stream, http_request_t *req, int maxlen)
2690 DWORD res;
2691 int len;
2693 assert(!stream->end_of_data);
2695 if (stream->buf_pos)
2697 /* move existing data to the start of the buffer */
2698 if(stream->buf_size)
2699 memmove(stream->buf, stream->buf + stream->buf_pos, stream->buf_size);
2700 stream->buf_pos = 0;
2703 if (maxlen == -1) maxlen = sizeof(stream->buf);
2705 res = NETCON_recv( req->netconn, stream->buf + stream->buf_size,
2706 maxlen - stream->buf_size, BLOCKING_ALLOW, &len );
2707 if(res == ERROR_SUCCESS)
2708 stream->buf_size += len;
2710 return res;
2713 /* remove some amount of data from the read buffer (the read section must be held) */
2714 static void remove_chunked_data(chunked_stream_t *stream, int count)
2716 if (!(stream->buf_size -= count)) stream->buf_pos = 0;
2717 else stream->buf_pos += count;
2720 /* discard data contents until we reach end of line (the read section must be held) */
2721 static DWORD discard_chunked_eol(chunked_stream_t *stream, http_request_t *req)
2723 DWORD res;
2727 BYTE *eol = memchr(stream->buf + stream->buf_pos, '\n', stream->buf_size);
2728 if (eol)
2730 remove_chunked_data(stream, (eol + 1) - (stream->buf + stream->buf_pos));
2731 break;
2733 stream->buf_pos = stream->buf_size = 0; /* discard everything */
2734 if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
2735 } while (stream->buf_size);
2736 return ERROR_SUCCESS;
2739 /* read the size of the next chunk (the read section must be held) */
2740 static DWORD start_next_chunk(chunked_stream_t *stream, http_request_t *req)
2742 DWORD chunk_size = 0, res;
2744 assert(!stream->chunk_size || stream->chunk_size == ~0u);
2746 if (stream->end_of_data) return ERROR_SUCCESS;
2748 /* read terminator for the previous chunk */
2749 if(!stream->chunk_size && (res = discard_chunked_eol(stream, req)) != ERROR_SUCCESS)
2750 return res;
2752 for (;;)
2754 while (stream->buf_size)
2756 char ch = stream->buf[stream->buf_pos];
2757 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
2758 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
2759 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
2760 else if (ch == ';' || ch == '\r' || ch == '\n')
2762 TRACE( "reading %u byte chunk\n", chunk_size );
2763 stream->chunk_size = chunk_size;
2764 if (req->contentLength == ~0u) req->contentLength = chunk_size;
2765 else req->contentLength += chunk_size;
2767 if (!chunk_size) stream->end_of_data = TRUE;
2768 return discard_chunked_eol(stream, req);
2770 remove_chunked_data(stream, 1);
2772 if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
2773 if (!stream->buf_size)
2775 stream->chunk_size = 0;
2776 return ERROR_SUCCESS;
2781 static DWORD chunked_get_avail_data(data_stream_t *stream, http_request_t *req)
2783 /* Allow reading only from read buffer */
2784 return 0;
2787 static BOOL chunked_end_of_data(data_stream_t *stream, http_request_t *req)
2789 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2790 return chunked_stream->end_of_data;
2793 static DWORD chunked_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2794 DWORD *read, blocking_mode_t blocking_mode)
2796 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2797 DWORD read_bytes = 0, ret_read = 0, res = ERROR_SUCCESS;
2799 if(!chunked_stream->chunk_size || chunked_stream->chunk_size == ~0u) {
2800 res = start_next_chunk(chunked_stream, req);
2801 if(res != ERROR_SUCCESS)
2802 return res;
2805 while(size && chunked_stream->chunk_size && !chunked_stream->end_of_data) {
2806 if(chunked_stream->buf_size) {
2807 read_bytes = min(size, min(chunked_stream->buf_size, chunked_stream->chunk_size));
2809 /* this could block */
2810 if(blocking_mode == BLOCKING_DISALLOW && read_bytes == chunked_stream->chunk_size)
2811 break;
2813 memcpy(buf+ret_read, chunked_stream->buf+chunked_stream->buf_pos, read_bytes);
2814 remove_chunked_data(chunked_stream, read_bytes);
2815 }else {
2816 read_bytes = min(size, chunked_stream->chunk_size);
2818 if(blocking_mode == BLOCKING_DISALLOW) {
2819 DWORD avail;
2821 if(!is_valid_netconn(req->netconn) || !NETCON_query_data_available(req->netconn, &avail) || !avail)
2822 break;
2823 if(read_bytes > avail)
2824 read_bytes = avail;
2826 /* this could block */
2827 if(read_bytes == chunked_stream->chunk_size)
2828 break;
2831 res = NETCON_recv(req->netconn, (char *)buf+ret_read, read_bytes, BLOCKING_ALLOW, (int*)&read_bytes);
2832 if(res != ERROR_SUCCESS)
2833 break;
2836 chunked_stream->chunk_size -= read_bytes;
2837 size -= read_bytes;
2838 ret_read += read_bytes;
2839 if(size && !chunked_stream->chunk_size) {
2840 assert(blocking_mode != BLOCKING_DISALLOW);
2841 res = start_next_chunk(chunked_stream, req);
2842 if(res != ERROR_SUCCESS)
2843 break;
2846 if(blocking_mode == BLOCKING_ALLOW)
2847 blocking_mode = BLOCKING_DISALLOW;
2850 TRACE("read %u bytes\n", ret_read);
2851 *read = ret_read;
2852 return res;
2855 static BOOL chunked_drain_content(data_stream_t *stream, http_request_t *req)
2857 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2859 remove_chunked_data(chunked_stream, chunked_stream->buf_size);
2860 return chunked_stream->end_of_data;
2863 static void chunked_destroy(data_stream_t *stream)
2865 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2866 heap_free(chunked_stream);
2869 static const data_stream_vtbl_t chunked_stream_vtbl = {
2870 chunked_get_avail_data,
2871 chunked_end_of_data,
2872 chunked_read,
2873 chunked_drain_content,
2874 chunked_destroy
2877 /* set the request content length based on the headers */
2878 static DWORD set_content_length(http_request_t *request)
2880 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
2881 WCHAR encoding[20];
2882 DWORD size;
2884 if(request->status_code == HTTP_STATUS_NO_CONTENT) {
2885 request->contentLength = request->netconn_stream.content_length = 0;
2886 return ERROR_SUCCESS;
2889 size = sizeof(request->contentLength);
2890 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2891 &request->contentLength, &size, NULL) != ERROR_SUCCESS)
2892 request->contentLength = ~0u;
2893 request->netconn_stream.content_length = request->contentLength;
2894 request->netconn_stream.content_read = request->read_size;
2896 size = sizeof(encoding);
2897 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) == ERROR_SUCCESS &&
2898 !strcmpiW(encoding, szChunked))
2900 chunked_stream_t *chunked_stream;
2902 chunked_stream = heap_alloc(sizeof(*chunked_stream));
2903 if(!chunked_stream)
2904 return ERROR_OUTOFMEMORY;
2906 chunked_stream->data_stream.vtbl = &chunked_stream_vtbl;
2907 chunked_stream->buf_size = chunked_stream->buf_pos = 0;
2908 chunked_stream->chunk_size = ~0u;
2909 chunked_stream->end_of_data = FALSE;
2911 if(request->read_size) {
2912 memcpy(chunked_stream->buf, request->read_buf+request->read_pos, request->read_size);
2913 chunked_stream->buf_size = request->read_size;
2914 request->read_size = request->read_pos = 0;
2917 request->data_stream = &chunked_stream->data_stream;
2918 request->contentLength = ~0u;
2919 request->read_chunked = TRUE;
2922 if(request->decoding) {
2923 int encoding_idx;
2925 static const WCHAR gzipW[] = {'g','z','i','p',0};
2927 encoding_idx = HTTP_GetCustomHeaderIndex(request, szContent_Encoding, 0, FALSE);
2928 if(encoding_idx != -1 && !strcmpiW(request->custHeaders[encoding_idx].lpszValue, gzipW)) {
2929 HTTP_DeleteCustomHeader(request, encoding_idx);
2930 return init_gzip_stream(request);
2934 return ERROR_SUCCESS;
2937 static void send_request_complete(http_request_t *req, DWORD_PTR result, DWORD error)
2939 INTERNET_ASYNC_RESULT iar;
2941 iar.dwResult = result;
2942 iar.dwError = error;
2944 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2945 sizeof(INTERNET_ASYNC_RESULT));
2948 static void HTTP_ReceiveRequestData(http_request_t *req, BOOL first_notif, DWORD *ret_size)
2950 DWORD res, read = 0, avail = 0;
2951 blocking_mode_t mode;
2953 TRACE("%p\n", req);
2955 EnterCriticalSection( &req->read_section );
2957 mode = first_notif && req->read_size ? BLOCKING_DISALLOW : BLOCKING_ALLOW;
2958 res = refill_read_buffer(req, mode, &read);
2959 if(res == ERROR_SUCCESS)
2960 avail = get_avail_data(req);
2962 LeaveCriticalSection( &req->read_section );
2964 if(res != ERROR_SUCCESS || (mode != BLOCKING_DISALLOW && !read)) {
2965 WARN("res %u read %u, closing connection\n", res, read);
2966 http_release_netconn(req, FALSE);
2969 if(res != ERROR_SUCCESS) {
2970 send_request_complete(req, 0, res);
2971 return;
2974 if(ret_size)
2975 *ret_size = avail;
2976 if(first_notif)
2977 avail = 0;
2979 send_request_complete(req, req->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)req->hdr.hInternet : 1, avail);
2982 /* read data from the http connection (the read section must be held) */
2983 static DWORD HTTPREQ_Read(http_request_t *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
2985 DWORD current_read = 0, ret_read = 0;
2986 blocking_mode_t blocking_mode;
2987 DWORD res = ERROR_SUCCESS;
2989 blocking_mode = req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC ? BLOCKING_ALLOW : BLOCKING_WAITALL;
2991 EnterCriticalSection( &req->read_section );
2993 if(req->read_size) {
2994 ret_read = min(size, req->read_size);
2995 memcpy(buffer, req->read_buf+req->read_pos, ret_read);
2996 req->read_size -= ret_read;
2997 req->read_pos += ret_read;
2998 if(blocking_mode == BLOCKING_ALLOW)
2999 blocking_mode = BLOCKING_DISALLOW;
3002 if(ret_read < size) {
3003 res = read_http_stream(req, (BYTE*)buffer+ret_read, size-ret_read, &current_read, blocking_mode);
3004 ret_read += current_read;
3007 LeaveCriticalSection( &req->read_section );
3009 *read = ret_read;
3010 TRACE( "retrieved %u bytes (%u)\n", ret_read, req->contentLength );
3012 if(size && !ret_read)
3013 http_release_netconn(req, res == ERROR_SUCCESS);
3015 return res;
3018 static BOOL drain_content(http_request_t *req, BOOL blocking)
3020 BOOL ret;
3022 if(!is_valid_netconn(req->netconn) || req->contentLength == -1)
3023 return FALSE;
3025 if(!strcmpW(req->verb, szHEAD))
3026 return TRUE;
3028 if(!blocking)
3029 return req->data_stream->vtbl->drain_content(req->data_stream, req);
3031 EnterCriticalSection( &req->read_section );
3033 while(1) {
3034 DWORD bytes_read, res;
3035 BYTE buf[4096];
3037 res = HTTPREQ_Read(req, buf, sizeof(buf), &bytes_read, TRUE);
3038 if(res != ERROR_SUCCESS) {
3039 ret = FALSE;
3040 break;
3042 if(!bytes_read) {
3043 ret = TRUE;
3044 break;
3048 LeaveCriticalSection( &req->read_section );
3049 return ret;
3052 static DWORD HTTPREQ_ReadFile(object_header_t *hdr, void *buffer, DWORD size, DWORD *read)
3054 http_request_t *req = (http_request_t*)hdr;
3055 DWORD res;
3057 EnterCriticalSection( &req->read_section );
3058 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3059 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3061 res = HTTPREQ_Read(req, buffer, size, read, TRUE);
3062 if(res == ERROR_SUCCESS)
3063 res = hdr->dwError;
3064 LeaveCriticalSection( &req->read_section );
3066 return res;
3069 typedef struct {
3070 task_header_t hdr;
3071 void *buf;
3072 DWORD size;
3073 DWORD *ret_read;
3074 } read_file_ex_task_t;
3076 static void AsyncReadFileExProc(task_header_t *hdr)
3078 read_file_ex_task_t *task = (read_file_ex_task_t*)hdr;
3079 http_request_t *req = (http_request_t*)task->hdr.hdr;
3080 DWORD res;
3082 TRACE("INTERNETREADFILEEXW %p\n", task->hdr.hdr);
3084 res = HTTPREQ_Read(req, task->buf, task->size, task->ret_read, TRUE);
3085 send_request_complete(req, res == ERROR_SUCCESS, res);
3088 static DWORD HTTPREQ_ReadFileEx(object_header_t *hdr, void *buf, DWORD size, DWORD *ret_read,
3089 DWORD flags, DWORD_PTR context)
3092 http_request_t *req = (http_request_t*)hdr;
3093 DWORD res, read, cread, error = ERROR_SUCCESS;
3095 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3096 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3098 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3100 if (hdr->dwFlags & INTERNET_FLAG_ASYNC)
3102 read_file_ex_task_t *task;
3104 if (TryEnterCriticalSection( &req->read_section ))
3106 if (get_avail_data(req))
3108 res = HTTPREQ_Read(req, buf, size, &read, FALSE);
3109 LeaveCriticalSection( &req->read_section );
3110 goto done;
3112 LeaveCriticalSection( &req->read_section );
3115 task = alloc_async_task(&req->hdr, AsyncReadFileExProc, sizeof(*task));
3116 task->buf = buf;
3117 task->size = size;
3118 task->ret_read = ret_read;
3120 INTERNET_AsyncCall(&task->hdr);
3122 return ERROR_IO_PENDING;
3125 read = 0;
3127 EnterCriticalSection( &req->read_section );
3128 if(hdr->dwError == ERROR_SUCCESS)
3129 hdr->dwError = INTERNET_HANDLE_IN_USE;
3130 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3131 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3133 while(1) {
3134 res = HTTPREQ_Read(req, (char*)buf+read, size-read, &cread, !(flags & IRF_NO_WAIT));
3135 if(res != ERROR_SUCCESS)
3136 break;
3138 read += cread;
3139 if(read == size || end_of_read_data(req))
3140 break;
3142 LeaveCriticalSection( &req->read_section );
3144 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3145 &cread, sizeof(cread));
3146 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
3147 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3149 EnterCriticalSection( &req->read_section );
3152 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3153 hdr->dwError = ERROR_SUCCESS;
3154 else
3155 error = hdr->dwError;
3157 LeaveCriticalSection( &req->read_section );
3159 done:
3160 *ret_read = read;
3161 if (res == ERROR_SUCCESS) {
3162 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3163 &read, sizeof(read));
3166 return res==ERROR_SUCCESS ? error : res;
3169 static DWORD HTTPREQ_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
3171 DWORD res;
3172 http_request_t *request = (http_request_t*)hdr;
3174 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3176 *written = 0;
3177 res = NETCON_send(request->netconn, buffer, size, 0, (LPINT)written);
3178 if (res == ERROR_SUCCESS)
3179 request->bytesWritten += *written;
3181 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
3182 return res;
3185 typedef struct {
3186 task_header_t hdr;
3187 DWORD *ret_size;
3188 } http_data_available_task_t;
3190 static void AsyncQueryDataAvailableProc(task_header_t *hdr)
3192 http_data_available_task_t *task = (http_data_available_task_t*)hdr;
3194 HTTP_ReceiveRequestData((http_request_t*)task->hdr.hdr, FALSE, task->ret_size);
3197 static DWORD HTTPREQ_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
3199 http_request_t *req = (http_request_t*)hdr;
3201 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
3203 if (req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3205 http_data_available_task_t *task;
3207 /* never wait, if we can't enter the section we queue an async request right away */
3208 if (TryEnterCriticalSection( &req->read_section ))
3210 refill_read_buffer(req, BLOCKING_DISALLOW, NULL);
3211 if ((*available = get_avail_data( req ))) goto done;
3212 if (end_of_read_data( req )) goto done;
3213 LeaveCriticalSection( &req->read_section );
3216 task = alloc_async_task(&req->hdr, AsyncQueryDataAvailableProc, sizeof(*task));
3217 task->ret_size = available;
3218 INTERNET_AsyncCall(&task->hdr);
3219 return ERROR_IO_PENDING;
3222 EnterCriticalSection( &req->read_section );
3224 if (!(*available = get_avail_data( req )) && !end_of_read_data( req ))
3226 refill_read_buffer( req, BLOCKING_ALLOW, NULL );
3227 *available = get_avail_data( req );
3230 done:
3231 LeaveCriticalSection( &req->read_section );
3233 TRACE( "returning %u\n", *available );
3234 return ERROR_SUCCESS;
3237 static DWORD HTTPREQ_LockRequestFile(object_header_t *hdr, req_file_t **ret)
3239 http_request_t *req = (http_request_t*)hdr;
3241 TRACE("(%p)\n", req);
3243 if(!req->req_file) {
3244 WARN("No cache file name available\n");
3245 return ERROR_FILE_NOT_FOUND;
3248 *ret = req_file_addref(req->req_file);
3249 return ERROR_SUCCESS;
3252 static const object_vtbl_t HTTPREQVtbl = {
3253 HTTPREQ_Destroy,
3254 HTTPREQ_CloseConnection,
3255 HTTPREQ_QueryOption,
3256 HTTPREQ_SetOption,
3257 HTTPREQ_ReadFile,
3258 HTTPREQ_ReadFileEx,
3259 HTTPREQ_WriteFile,
3260 HTTPREQ_QueryDataAvailable,
3261 NULL,
3262 HTTPREQ_LockRequestFile
3265 /***********************************************************************
3266 * HTTP_HttpOpenRequestW (internal)
3268 * Open a HTTP request handle
3270 * RETURNS
3271 * HINTERNET a HTTP request handle on success
3272 * NULL on failure
3275 static DWORD HTTP_HttpOpenRequestW(http_session_t *session,
3276 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3277 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3278 DWORD dwFlags, DWORD_PTR dwContext, HINTERNET *ret)
3280 appinfo_t *hIC = session->appInfo;
3281 http_request_t *request;
3282 DWORD len, res = ERROR_SUCCESS;
3284 TRACE("-->\n");
3286 request = alloc_object(&session->hdr, &HTTPREQVtbl, sizeof(http_request_t));
3287 if(!request)
3288 return ERROR_OUTOFMEMORY;
3290 request->hdr.htype = WH_HHTTPREQ;
3291 request->hdr.dwFlags = dwFlags;
3292 request->hdr.dwContext = dwContext;
3293 request->contentLength = ~0u;
3295 request->netconn_stream.data_stream.vtbl = &netconn_stream_vtbl;
3296 request->data_stream = &request->netconn_stream.data_stream;
3297 request->connect_timeout = session->connect_timeout;
3298 request->send_timeout = session->send_timeout;
3299 request->receive_timeout = session->receive_timeout;
3301 InitializeCriticalSection( &request->read_section );
3302 request->read_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.read_section");
3304 WININET_AddRef( &session->hdr );
3305 request->session = session;
3306 list_add_head( &session->hdr.children, &request->hdr.entry );
3308 request->server = get_server(session->hostName, session->hostPort, (dwFlags & INTERNET_FLAG_SECURE) != 0, TRUE);
3309 if(!request->server) {
3310 WININET_Release(&request->hdr);
3311 return ERROR_OUTOFMEMORY;
3314 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_CN_INVALID)
3315 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
3316 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_DATE_INVALID)
3317 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
3319 if (lpszObjectName && *lpszObjectName) {
3320 HRESULT rc;
3322 len = 0;
3323 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
3324 if (rc != E_POINTER)
3325 len = strlenW(lpszObjectName)+1;
3326 request->path = heap_alloc(len*sizeof(WCHAR));
3327 rc = UrlEscapeW(lpszObjectName, request->path, &len,
3328 URL_ESCAPE_SPACES_ONLY);
3329 if (rc != S_OK)
3331 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
3332 strcpyW(request->path,lpszObjectName);
3334 }else {
3335 static const WCHAR slashW[] = {'/',0};
3337 request->path = heap_strdupW(slashW);
3340 if (lpszReferrer && *lpszReferrer)
3341 HTTP_ProcessHeader(request, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3343 if (lpszAcceptTypes)
3345 int i;
3346 for (i = 0; lpszAcceptTypes[i]; i++)
3348 if (!*lpszAcceptTypes[i]) continue;
3349 HTTP_ProcessHeader(request, HTTP_ACCEPT, lpszAcceptTypes[i],
3350 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
3351 HTTP_ADDHDR_FLAG_REQ |
3352 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
3356 request->verb = heap_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
3357 request->version = heap_strdupW(lpszVersion && *lpszVersion ? lpszVersion : g_szHttp1_1);
3359 HTTP_ProcessHeader(request, hostW, request->server->canon_host_port, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3361 if (session->hostPort == INTERNET_INVALID_PORT_NUMBER)
3362 session->hostPort = INTERNET_DEFAULT_HTTP_PORT;
3364 if (hIC->proxy && hIC->proxy[0] && !HTTP_ShouldBypassProxy(hIC, session->hostName))
3365 HTTP_DealWithProxy( hIC, session, request );
3367 INTERNET_SendCallback(&session->hdr, dwContext,
3368 INTERNET_STATUS_HANDLE_CREATED, &request->hdr.hInternet,
3369 sizeof(HINTERNET));
3371 TRACE("<-- %u (%p)\n", res, request);
3373 if(res != ERROR_SUCCESS) {
3374 WININET_Release( &request->hdr );
3375 *ret = NULL;
3376 return res;
3379 *ret = request->hdr.hInternet;
3380 return ERROR_SUCCESS;
3383 /***********************************************************************
3384 * HttpOpenRequestW (WININET.@)
3386 * Open a HTTP request handle
3388 * RETURNS
3389 * HINTERNET a HTTP request handle on success
3390 * NULL on failure
3393 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
3394 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3395 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3396 DWORD dwFlags, DWORD_PTR dwContext)
3398 http_session_t *session;
3399 HINTERNET handle = NULL;
3400 DWORD res;
3402 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
3403 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
3404 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
3405 dwFlags, dwContext);
3406 if(lpszAcceptTypes!=NULL)
3408 int i;
3409 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
3410 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
3413 session = (http_session_t*) get_handle_object( hHttpSession );
3414 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
3416 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3417 goto lend;
3421 * My tests seem to show that the windows version does not
3422 * become asynchronous until after this point. And anyhow
3423 * if this call was asynchronous then how would you get the
3424 * necessary HINTERNET pointer returned by this function.
3427 res = HTTP_HttpOpenRequestW(session, lpszVerb, lpszObjectName,
3428 lpszVersion, lpszReferrer, lpszAcceptTypes,
3429 dwFlags, dwContext, &handle);
3430 lend:
3431 if( session )
3432 WININET_Release( &session->hdr );
3433 TRACE("returning %p\n", handle);
3434 if(res != ERROR_SUCCESS)
3435 SetLastError(res);
3436 return handle;
3439 static const LPCWSTR header_lookup[] = {
3440 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
3441 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3442 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3443 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
3444 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3445 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3446 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3447 szAllow, /* HTTP_QUERY_ALLOW = 7 */
3448 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
3449 szDate, /* HTTP_QUERY_DATE = 9 */
3450 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
3451 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3452 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
3453 szURI, /* HTTP_QUERY_URI = 13 */
3454 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
3455 NULL, /* HTTP_QUERY_COST = 15 */
3456 NULL, /* HTTP_QUERY_LINK = 16 */
3457 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
3458 NULL, /* HTTP_QUERY_VERSION = 18 */
3459 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
3460 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
3461 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
3462 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3463 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
3464 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
3465 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3466 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3467 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3468 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
3469 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3470 NULL, /* HTTP_QUERY_FORWARDED = 30 */
3471 NULL, /* HTTP_QUERY_FROM = 31 */
3472 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3473 szLocation, /* HTTP_QUERY_LOCATION = 33 */
3474 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
3475 szReferer, /* HTTP_QUERY_REFERER = 35 */
3476 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
3477 szServer, /* HTTP_QUERY_SERVER = 37 */
3478 NULL, /* HTTP_TITLE = 38 */
3479 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
3480 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3481 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3482 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3483 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
3484 szCookie, /* HTTP_QUERY_COOKIE = 44 */
3485 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3486 NULL, /* HTTP_QUERY_REFRESH = 46 */
3487 szContent_Disposition, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3488 szAge, /* HTTP_QUERY_AGE = 48 */
3489 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3490 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
3491 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3492 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3493 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3494 szETag, /* HTTP_QUERY_ETAG = 54 */
3495 hostW, /* HTTP_QUERY_HOST = 55 */
3496 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
3497 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3498 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
3499 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3500 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3501 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3502 szRange, /* HTTP_QUERY_RANGE = 62 */
3503 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3504 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
3505 szVary, /* HTTP_QUERY_VARY = 65 */
3506 szVia, /* HTTP_QUERY_VIA = 66 */
3507 szWarning, /* HTTP_QUERY_WARNING = 67 */
3508 szExpect, /* HTTP_QUERY_EXPECT = 68 */
3509 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3510 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3513 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3515 /***********************************************************************
3516 * HTTP_HttpQueryInfoW (internal)
3518 static DWORD HTTP_HttpQueryInfoW(http_request_t *request, DWORD dwInfoLevel,
3519 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3521 LPHTTPHEADERW lphttpHdr = NULL;
3522 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
3523 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
3524 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
3525 INT index = -1;
3527 /* Find requested header structure */
3528 switch (level)
3530 case HTTP_QUERY_CUSTOM:
3531 if (!lpBuffer) return ERROR_INVALID_PARAMETER;
3532 index = HTTP_GetCustomHeaderIndex(request, lpBuffer, requested_index, request_only);
3533 break;
3534 case HTTP_QUERY_RAW_HEADERS_CRLF:
3536 LPWSTR headers;
3537 DWORD len = 0;
3538 DWORD res = ERROR_INVALID_PARAMETER;
3540 if (request_only)
3541 headers = build_request_header(request, request->verb, request->path, request->version, TRUE);
3542 else
3543 headers = build_response_header(request, TRUE);
3544 if (!headers)
3545 return ERROR_OUTOFMEMORY;
3547 len = strlenW(headers) * sizeof(WCHAR);
3548 if (len + sizeof(WCHAR) > *lpdwBufferLength)
3550 len += sizeof(WCHAR);
3551 res = ERROR_INSUFFICIENT_BUFFER;
3553 else if (lpBuffer)
3555 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3556 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
3557 res = ERROR_SUCCESS;
3559 *lpdwBufferLength = len;
3561 heap_free(headers);
3562 return res;
3564 case HTTP_QUERY_RAW_HEADERS:
3566 LPWSTR headers;
3567 DWORD len;
3569 if (request_only)
3570 headers = build_request_header(request, request->verb, request->path, request->version, FALSE);
3571 else
3572 headers = build_response_header(request, FALSE);
3573 if (!headers)
3574 return ERROR_OUTOFMEMORY;
3576 len = strlenW(headers) * sizeof(WCHAR);
3577 if (len > *lpdwBufferLength)
3579 *lpdwBufferLength = len;
3580 heap_free(headers);
3581 return ERROR_INSUFFICIENT_BUFFER;
3584 if (lpBuffer)
3586 DWORD i;
3588 TRACE("returning data: %s\n", debugstr_wn(headers, len / sizeof(WCHAR)));
3590 for (i=0; i<len; i++)
3592 if (headers[i] == '\n')
3593 headers[i] = 0;
3595 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3597 *lpdwBufferLength = len - sizeof(WCHAR);
3599 heap_free(headers);
3600 return ERROR_SUCCESS;
3602 case HTTP_QUERY_STATUS_TEXT:
3603 if (request->statusText)
3605 DWORD len = strlenW(request->statusText);
3606 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3608 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3609 return ERROR_INSUFFICIENT_BUFFER;
3611 if (lpBuffer)
3613 memcpy(lpBuffer, request->statusText, (len + 1) * sizeof(WCHAR));
3614 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3616 *lpdwBufferLength = len * sizeof(WCHAR);
3617 return ERROR_SUCCESS;
3619 break;
3620 case HTTP_QUERY_VERSION:
3621 if (request->version)
3623 DWORD len = strlenW(request->version);
3624 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3626 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3627 return ERROR_INSUFFICIENT_BUFFER;
3629 if (lpBuffer)
3631 memcpy(lpBuffer, request->version, (len + 1) * sizeof(WCHAR));
3632 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3634 *lpdwBufferLength = len * sizeof(WCHAR);
3635 return ERROR_SUCCESS;
3637 break;
3638 case HTTP_QUERY_CONTENT_ENCODING:
3639 index = HTTP_GetCustomHeaderIndex(request, header_lookup[request->read_gzip ? HTTP_QUERY_CONTENT_TYPE : level],
3640 requested_index,request_only);
3641 break;
3642 case HTTP_QUERY_STATUS_CODE: {
3643 DWORD res = ERROR_SUCCESS;
3645 if(request_only)
3646 return ERROR_HTTP_INVALID_QUERY_REQUEST;
3648 if(requested_index)
3649 break;
3651 if(dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) {
3652 if(*lpdwBufferLength >= sizeof(DWORD))
3653 *(DWORD*)lpBuffer = request->status_code;
3654 else
3655 res = ERROR_INSUFFICIENT_BUFFER;
3656 *lpdwBufferLength = sizeof(DWORD);
3657 }else {
3658 WCHAR buf[12];
3659 DWORD size;
3660 static const WCHAR formatW[] = {'%','u',0};
3662 size = sprintfW(buf, formatW, request->status_code) * sizeof(WCHAR);
3664 if(size <= *lpdwBufferLength) {
3665 memcpy(lpBuffer, buf, size+sizeof(WCHAR));
3666 }else {
3667 size += sizeof(WCHAR);
3668 res = ERROR_INSUFFICIENT_BUFFER;
3671 *lpdwBufferLength = size;
3673 return res;
3675 default:
3676 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
3678 if (level < LAST_TABLE_HEADER && header_lookup[level])
3679 index = HTTP_GetCustomHeaderIndex(request, header_lookup[level],
3680 requested_index,request_only);
3683 if (index >= 0)
3684 lphttpHdr = &request->custHeaders[index];
3686 /* Ensure header satisfies requested attributes */
3687 if (!lphttpHdr ||
3688 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
3689 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
3691 return ERROR_HTTP_HEADER_NOT_FOUND;
3694 if (lpdwIndex) (*lpdwIndex)++;
3696 /* coalesce value to requested type */
3697 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
3699 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
3700 TRACE(" returning number: %d\n", *(int *)lpBuffer);
3702 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
3704 time_t tmpTime;
3705 struct tm tmpTM;
3706 SYSTEMTIME *STHook;
3708 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
3710 tmpTM = *gmtime(&tmpTime);
3711 STHook = (SYSTEMTIME *)lpBuffer;
3712 STHook->wDay = tmpTM.tm_mday;
3713 STHook->wHour = tmpTM.tm_hour;
3714 STHook->wMilliseconds = 0;
3715 STHook->wMinute = tmpTM.tm_min;
3716 STHook->wDayOfWeek = tmpTM.tm_wday;
3717 STHook->wMonth = tmpTM.tm_mon + 1;
3718 STHook->wSecond = tmpTM.tm_sec;
3719 STHook->wYear = 1900+tmpTM.tm_year;
3721 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3722 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
3723 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
3725 else if (lphttpHdr->lpszValue)
3727 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
3729 if (len > *lpdwBufferLength)
3731 *lpdwBufferLength = len;
3732 return ERROR_INSUFFICIENT_BUFFER;
3734 if (lpBuffer)
3736 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
3737 TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
3739 *lpdwBufferLength = len - sizeof(WCHAR);
3741 return ERROR_SUCCESS;
3744 /***********************************************************************
3745 * HttpQueryInfoW (WININET.@)
3747 * Queries for information about an HTTP request
3749 * RETURNS
3750 * TRUE on success
3751 * FALSE on failure
3754 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3755 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3757 http_request_t *request;
3758 DWORD res;
3760 if (TRACE_ON(wininet)) {
3761 #define FE(x) { x, #x }
3762 static const wininet_flag_info query_flags[] = {
3763 FE(HTTP_QUERY_MIME_VERSION),
3764 FE(HTTP_QUERY_CONTENT_TYPE),
3765 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
3766 FE(HTTP_QUERY_CONTENT_ID),
3767 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
3768 FE(HTTP_QUERY_CONTENT_LENGTH),
3769 FE(HTTP_QUERY_CONTENT_LANGUAGE),
3770 FE(HTTP_QUERY_ALLOW),
3771 FE(HTTP_QUERY_PUBLIC),
3772 FE(HTTP_QUERY_DATE),
3773 FE(HTTP_QUERY_EXPIRES),
3774 FE(HTTP_QUERY_LAST_MODIFIED),
3775 FE(HTTP_QUERY_MESSAGE_ID),
3776 FE(HTTP_QUERY_URI),
3777 FE(HTTP_QUERY_DERIVED_FROM),
3778 FE(HTTP_QUERY_COST),
3779 FE(HTTP_QUERY_LINK),
3780 FE(HTTP_QUERY_PRAGMA),
3781 FE(HTTP_QUERY_VERSION),
3782 FE(HTTP_QUERY_STATUS_CODE),
3783 FE(HTTP_QUERY_STATUS_TEXT),
3784 FE(HTTP_QUERY_RAW_HEADERS),
3785 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
3786 FE(HTTP_QUERY_CONNECTION),
3787 FE(HTTP_QUERY_ACCEPT),
3788 FE(HTTP_QUERY_ACCEPT_CHARSET),
3789 FE(HTTP_QUERY_ACCEPT_ENCODING),
3790 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
3791 FE(HTTP_QUERY_AUTHORIZATION),
3792 FE(HTTP_QUERY_CONTENT_ENCODING),
3793 FE(HTTP_QUERY_FORWARDED),
3794 FE(HTTP_QUERY_FROM),
3795 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
3796 FE(HTTP_QUERY_LOCATION),
3797 FE(HTTP_QUERY_ORIG_URI),
3798 FE(HTTP_QUERY_REFERER),
3799 FE(HTTP_QUERY_RETRY_AFTER),
3800 FE(HTTP_QUERY_SERVER),
3801 FE(HTTP_QUERY_TITLE),
3802 FE(HTTP_QUERY_USER_AGENT),
3803 FE(HTTP_QUERY_WWW_AUTHENTICATE),
3804 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
3805 FE(HTTP_QUERY_ACCEPT_RANGES),
3806 FE(HTTP_QUERY_SET_COOKIE),
3807 FE(HTTP_QUERY_COOKIE),
3808 FE(HTTP_QUERY_REQUEST_METHOD),
3809 FE(HTTP_QUERY_REFRESH),
3810 FE(HTTP_QUERY_CONTENT_DISPOSITION),
3811 FE(HTTP_QUERY_AGE),
3812 FE(HTTP_QUERY_CACHE_CONTROL),
3813 FE(HTTP_QUERY_CONTENT_BASE),
3814 FE(HTTP_QUERY_CONTENT_LOCATION),
3815 FE(HTTP_QUERY_CONTENT_MD5),
3816 FE(HTTP_QUERY_CONTENT_RANGE),
3817 FE(HTTP_QUERY_ETAG),
3818 FE(HTTP_QUERY_HOST),
3819 FE(HTTP_QUERY_IF_MATCH),
3820 FE(HTTP_QUERY_IF_NONE_MATCH),
3821 FE(HTTP_QUERY_IF_RANGE),
3822 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
3823 FE(HTTP_QUERY_MAX_FORWARDS),
3824 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
3825 FE(HTTP_QUERY_RANGE),
3826 FE(HTTP_QUERY_TRANSFER_ENCODING),
3827 FE(HTTP_QUERY_UPGRADE),
3828 FE(HTTP_QUERY_VARY),
3829 FE(HTTP_QUERY_VIA),
3830 FE(HTTP_QUERY_WARNING),
3831 FE(HTTP_QUERY_CUSTOM)
3833 static const wininet_flag_info modifier_flags[] = {
3834 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
3835 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
3836 FE(HTTP_QUERY_FLAG_NUMBER),
3837 FE(HTTP_QUERY_FLAG_COALESCE)
3839 #undef FE
3840 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
3841 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
3842 DWORD i;
3844 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, info);
3845 TRACE(" Attribute:");
3846 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
3847 if (query_flags[i].val == info) {
3848 TRACE(" %s", query_flags[i].name);
3849 break;
3852 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
3853 TRACE(" Unknown (%08x)", info);
3856 TRACE(" Modifier:");
3857 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
3858 if (modifier_flags[i].val & info_mod) {
3859 TRACE(" %s", modifier_flags[i].name);
3860 info_mod &= ~ modifier_flags[i].val;
3864 if (info_mod) {
3865 TRACE(" Unknown (%08x)", info_mod);
3867 TRACE("\n");
3870 request = (http_request_t*) get_handle_object( hHttpRequest );
3871 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
3873 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3874 goto lend;
3877 if (lpBuffer == NULL)
3878 *lpdwBufferLength = 0;
3879 res = HTTP_HttpQueryInfoW( request, dwInfoLevel,
3880 lpBuffer, lpdwBufferLength, lpdwIndex);
3882 lend:
3883 if( request )
3884 WININET_Release( &request->hdr );
3886 TRACE("%u <--\n", res);
3887 if(res != ERROR_SUCCESS)
3888 SetLastError(res);
3889 return res == ERROR_SUCCESS;
3892 /***********************************************************************
3893 * HttpQueryInfoA (WININET.@)
3895 * Queries for information about an HTTP request
3897 * RETURNS
3898 * TRUE on success
3899 * FALSE on failure
3902 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3903 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3905 BOOL result;
3906 DWORD len;
3907 WCHAR* bufferW;
3909 TRACE("%p %x\n", hHttpRequest, dwInfoLevel);
3911 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
3912 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
3914 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
3915 lpdwBufferLength, lpdwIndex );
3918 if (lpBuffer)
3920 DWORD alloclen;
3921 len = (*lpdwBufferLength)*sizeof(WCHAR);
3922 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3924 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
3925 if (alloclen < len)
3926 alloclen = len;
3928 else
3929 alloclen = len;
3930 bufferW = heap_alloc(alloclen);
3931 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3932 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3933 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
3934 } else
3936 bufferW = NULL;
3937 len = 0;
3940 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
3941 &len, lpdwIndex );
3942 if( result )
3944 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
3945 lpBuffer, *lpdwBufferLength, NULL, NULL );
3946 *lpdwBufferLength = len - 1;
3948 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
3950 else
3951 /* since the strings being returned from HttpQueryInfoW should be
3952 * only ASCII characters, it is reasonable to assume that all of
3953 * the Unicode characters can be reduced to a single byte */
3954 *lpdwBufferLength = len / sizeof(WCHAR);
3956 heap_free( bufferW );
3957 return result;
3960 /***********************************************************************
3961 * HTTP_GetRedirectURL (internal)
3963 static LPWSTR HTTP_GetRedirectURL(http_request_t *request, LPCWSTR lpszUrl)
3965 static WCHAR szHttp[] = {'h','t','t','p',0};
3966 static WCHAR szHttps[] = {'h','t','t','p','s',0};
3967 http_session_t *session = request->session;
3968 URL_COMPONENTSW urlComponents;
3969 DWORD url_length = 0;
3970 LPWSTR orig_url;
3971 LPWSTR combined_url;
3973 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3974 urlComponents.lpszScheme = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
3975 urlComponents.dwSchemeLength = 0;
3976 urlComponents.lpszHostName = session->hostName;
3977 urlComponents.dwHostNameLength = 0;
3978 urlComponents.nPort = session->hostPort;
3979 urlComponents.lpszUserName = session->userName;
3980 urlComponents.dwUserNameLength = 0;
3981 urlComponents.lpszPassword = NULL;
3982 urlComponents.dwPasswordLength = 0;
3983 urlComponents.lpszUrlPath = request->path;
3984 urlComponents.dwUrlPathLength = 0;
3985 urlComponents.lpszExtraInfo = NULL;
3986 urlComponents.dwExtraInfoLength = 0;
3988 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
3989 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
3990 return NULL;
3992 orig_url = heap_alloc(url_length);
3994 /* convert from bytes to characters */
3995 url_length = url_length / sizeof(WCHAR) - 1;
3996 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
3998 heap_free(orig_url);
3999 return NULL;
4002 url_length = 0;
4003 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
4004 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
4006 heap_free(orig_url);
4007 return NULL;
4009 combined_url = heap_alloc(url_length * sizeof(WCHAR));
4011 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
4013 heap_free(orig_url);
4014 heap_free(combined_url);
4015 return NULL;
4017 heap_free(orig_url);
4018 return combined_url;
4022 /***********************************************************************
4023 * HTTP_HandleRedirect (internal)
4025 static DWORD HTTP_HandleRedirect(http_request_t *request, LPCWSTR lpszUrl)
4027 http_session_t *session = request->session;
4028 WCHAR path[INTERNET_MAX_PATH_LENGTH];
4029 int index;
4031 if(lpszUrl[0]=='/')
4033 /* if it's an absolute path, keep the same session info */
4034 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
4036 else
4038 URL_COMPONENTSW urlComponents;
4039 WCHAR protocol[INTERNET_MAX_SCHEME_LENGTH];
4040 WCHAR hostName[INTERNET_MAX_HOST_NAME_LENGTH];
4041 WCHAR userName[INTERNET_MAX_USER_NAME_LENGTH];
4042 BOOL custom_port = FALSE;
4044 static const WCHAR httpW[] = {'h','t','t','p',0};
4045 static const WCHAR httpsW[] = {'h','t','t','p','s',0};
4047 userName[0] = 0;
4048 hostName[0] = 0;
4049 protocol[0] = 0;
4051 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
4052 urlComponents.lpszScheme = protocol;
4053 urlComponents.dwSchemeLength = INTERNET_MAX_SCHEME_LENGTH;
4054 urlComponents.lpszHostName = hostName;
4055 urlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
4056 urlComponents.lpszUserName = userName;
4057 urlComponents.dwUserNameLength = INTERNET_MAX_USER_NAME_LENGTH;
4058 urlComponents.lpszPassword = NULL;
4059 urlComponents.dwPasswordLength = 0;
4060 urlComponents.lpszUrlPath = path;
4061 urlComponents.dwUrlPathLength = INTERNET_MAX_PATH_LENGTH;
4062 urlComponents.lpszExtraInfo = NULL;
4063 urlComponents.dwExtraInfoLength = 0;
4064 if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
4065 return INTERNET_GetLastError();
4067 if(!strcmpiW(protocol, httpW)) {
4068 if(request->hdr.dwFlags & INTERNET_FLAG_SECURE) {
4069 TRACE("redirect from secure page to non-secure page\n");
4070 /* FIXME: warn about from secure redirect to non-secure page */
4071 request->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
4074 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4075 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
4076 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT)
4077 custom_port = TRUE;
4078 }else if(!strcmpiW(protocol, httpsW)) {
4079 if(!(request->hdr.dwFlags & INTERNET_FLAG_SECURE)) {
4080 TRACE("redirect from non-secure page to secure page\n");
4081 /* FIXME: notify about redirect to secure page */
4082 request->hdr.dwFlags |= INTERNET_FLAG_SECURE;
4085 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4086 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
4087 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
4088 custom_port = TRUE;
4091 heap_free(session->hostName);
4093 if(custom_port) {
4094 int len;
4095 static const WCHAR fmt[] = {'%','s',':','%','u',0};
4096 len = lstrlenW(hostName);
4097 len += 7; /* 5 for strlen("65535") + 1 for ":" + 1 for '\0' */
4098 session->hostName = heap_alloc(len*sizeof(WCHAR));
4099 sprintfW(session->hostName, fmt, hostName, urlComponents.nPort);
4101 else
4102 session->hostName = heap_strdupW(hostName);
4104 HTTP_ProcessHeader(request, hostW, session->hostName, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4106 heap_free(session->userName);
4107 session->userName = NULL;
4108 if (userName[0])
4109 session->userName = heap_strdupW(userName);
4111 reset_data_stream(request);
4113 if(strcmpiW(request->server->name, hostName) || request->server->port != urlComponents.nPort) {
4114 server_t *new_server;
4116 new_server = get_server(hostName, urlComponents.nPort, urlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
4117 server_release(request->server);
4118 request->server = new_server;
4121 heap_free(request->path);
4122 request->path=NULL;
4123 if (*path)
4125 DWORD needed = 0;
4126 HRESULT rc;
4128 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
4129 if (rc != E_POINTER)
4130 needed = strlenW(path)+1;
4131 request->path = heap_alloc(needed*sizeof(WCHAR));
4132 rc = UrlEscapeW(path, request->path, &needed,
4133 URL_ESCAPE_SPACES_ONLY);
4134 if (rc != S_OK)
4136 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4137 strcpyW(request->path,path);
4141 /* Remove custom content-type/length headers on redirects. */
4142 index = HTTP_GetCustomHeaderIndex(request, szContent_Type, 0, TRUE);
4143 if (0 <= index)
4144 HTTP_DeleteCustomHeader(request, index);
4145 index = HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE);
4146 if (0 <= index)
4147 HTTP_DeleteCustomHeader(request, index);
4149 return ERROR_SUCCESS;
4152 /***********************************************************************
4153 * HTTP_build_req (internal)
4155 * concatenate all the strings in the request together
4157 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
4159 LPCWSTR *t;
4160 LPWSTR str;
4162 for( t = list; *t ; t++ )
4163 len += strlenW( *t );
4164 len++;
4166 str = heap_alloc(len*sizeof(WCHAR));
4167 *str = 0;
4169 for( t = list; *t ; t++ )
4170 strcatW( str, *t );
4172 return str;
4175 static DWORD HTTP_SecureProxyConnect(http_request_t *request)
4177 server_t *server = request->server;
4178 LPWSTR requestString;
4179 INT len;
4180 INT cnt;
4181 INT responseLen;
4182 char *ascii_req;
4183 DWORD res;
4185 static const WCHAR connectW[] = {'C','O','N','N','E','C','T',0};
4187 TRACE("\n");
4189 requestString = build_request_header( request, connectW, server->host_port, g_szHttp1_1, TRUE );
4191 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
4192 NULL, 0, NULL, NULL );
4193 len--; /* the nul terminator isn't needed */
4194 ascii_req = heap_alloc(len);
4195 WideCharToMultiByte( CP_ACP, 0, requestString, -1, ascii_req, len, NULL, NULL );
4196 heap_free( requestString );
4198 TRACE("full request -> %s\n", debugstr_an( ascii_req, len ) );
4200 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
4201 res = NETCON_send( request->netconn, ascii_req, len, 0, &cnt );
4202 heap_free( ascii_req );
4203 if (res != ERROR_SUCCESS)
4204 return res;
4206 if (HTTP_GetResponseHeaders( request, &responseLen ) || !responseLen)
4207 return ERROR_HTTP_INVALID_HEADER;
4209 return ERROR_SUCCESS;
4212 static void HTTP_InsertCookies(http_request_t *request)
4214 DWORD cookie_size, size, cnt = 0;
4215 HTTPHEADERW *host;
4216 WCHAR *cookies;
4218 static const WCHAR cookieW[] = {'C','o','o','k','i','e',':',' ',0};
4220 host = HTTP_GetHeader(request, hostW);
4221 if(!host)
4222 return;
4224 if(get_cookie(host->lpszValue, request->path, NULL, &cookie_size) != ERROR_SUCCESS)
4225 return;
4227 size = sizeof(cookieW) + cookie_size * sizeof(WCHAR) + sizeof(szCrLf);
4228 if(!(cookies = heap_alloc(size)))
4229 return;
4231 cnt += sprintfW(cookies, cookieW);
4232 get_cookie(host->lpszValue, request->path, cookies+cnt, &cookie_size);
4233 strcatW(cookies, szCrLf);
4235 HTTP_HttpAddRequestHeadersW(request, cookies, strlenW(cookies), HTTP_ADDREQ_FLAG_REPLACE);
4237 heap_free(cookies);
4240 static WORD HTTP_ParseWkday(LPCWSTR day)
4242 static const WCHAR days[7][4] = {{ 's','u','n',0 },
4243 { 'm','o','n',0 },
4244 { 't','u','e',0 },
4245 { 'w','e','d',0 },
4246 { 't','h','u',0 },
4247 { 'f','r','i',0 },
4248 { 's','a','t',0 }};
4249 unsigned int i;
4250 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4251 if (!strcmpiW(day, days[i]))
4252 return i;
4254 /* Invalid */
4255 return 7;
4258 static WORD HTTP_ParseMonth(LPCWSTR month)
4260 static const WCHAR jan[] = { 'j','a','n',0 };
4261 static const WCHAR feb[] = { 'f','e','b',0 };
4262 static const WCHAR mar[] = { 'm','a','r',0 };
4263 static const WCHAR apr[] = { 'a','p','r',0 };
4264 static const WCHAR may[] = { 'm','a','y',0 };
4265 static const WCHAR jun[] = { 'j','u','n',0 };
4266 static const WCHAR jul[] = { 'j','u','l',0 };
4267 static const WCHAR aug[] = { 'a','u','g',0 };
4268 static const WCHAR sep[] = { 's','e','p',0 };
4269 static const WCHAR oct[] = { 'o','c','t',0 };
4270 static const WCHAR nov[] = { 'n','o','v',0 };
4271 static const WCHAR dec[] = { 'd','e','c',0 };
4273 if (!strcmpiW(month, jan)) return 1;
4274 if (!strcmpiW(month, feb)) return 2;
4275 if (!strcmpiW(month, mar)) return 3;
4276 if (!strcmpiW(month, apr)) return 4;
4277 if (!strcmpiW(month, may)) return 5;
4278 if (!strcmpiW(month, jun)) return 6;
4279 if (!strcmpiW(month, jul)) return 7;
4280 if (!strcmpiW(month, aug)) return 8;
4281 if (!strcmpiW(month, sep)) return 9;
4282 if (!strcmpiW(month, oct)) return 10;
4283 if (!strcmpiW(month, nov)) return 11;
4284 if (!strcmpiW(month, dec)) return 12;
4285 /* Invalid */
4286 return 0;
4289 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4290 * optionally preceded by whitespace.
4291 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4292 * st, and sets *str to the first character after the time format.
4294 static BOOL HTTP_ParseTime(SYSTEMTIME *st, LPCWSTR *str)
4296 LPCWSTR ptr = *str;
4297 WCHAR *nextPtr;
4298 unsigned long num;
4300 while (isspaceW(*ptr))
4301 ptr++;
4303 num = strtoulW(ptr, &nextPtr, 10);
4304 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4306 ERR("unexpected time format %s\n", debugstr_w(ptr));
4307 return FALSE;
4309 if (num > 23)
4311 ERR("unexpected hour in time format %s\n", debugstr_w(ptr));
4312 return FALSE;
4314 ptr = nextPtr + 1;
4315 st->wHour = (WORD)num;
4316 num = strtoulW(ptr, &nextPtr, 10);
4317 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4319 ERR("unexpected time format %s\n", debugstr_w(ptr));
4320 return FALSE;
4322 if (num > 59)
4324 ERR("unexpected minute in time format %s\n", debugstr_w(ptr));
4325 return FALSE;
4327 ptr = nextPtr + 1;
4328 st->wMinute = (WORD)num;
4329 num = strtoulW(ptr, &nextPtr, 10);
4330 if (!nextPtr || nextPtr <= ptr)
4332 ERR("unexpected time format %s\n", debugstr_w(ptr));
4333 return FALSE;
4335 if (num > 59)
4337 ERR("unexpected second in time format %s\n", debugstr_w(ptr));
4338 return FALSE;
4340 ptr = nextPtr + 1;
4341 *str = ptr;
4342 st->wSecond = (WORD)num;
4343 return TRUE;
4346 static BOOL HTTP_ParseDateAsAsctime(LPCWSTR value, FILETIME *ft)
4348 static const WCHAR gmt[]= { 'G','M','T',0 };
4349 WCHAR day[4], *dayPtr, month[4], *monthPtr, *nextPtr;
4350 LPCWSTR ptr;
4351 SYSTEMTIME st = { 0 };
4352 unsigned long num;
4354 for (ptr = value, dayPtr = day; *ptr && !isspaceW(*ptr) &&
4355 dayPtr - day < sizeof(day) / sizeof(day[0]) - 1; ptr++, dayPtr++)
4356 *dayPtr = *ptr;
4357 *dayPtr = 0;
4358 st.wDayOfWeek = HTTP_ParseWkday(day);
4359 if (st.wDayOfWeek >= 7)
4361 ERR("unexpected weekday %s\n", debugstr_w(day));
4362 return FALSE;
4365 while (isspaceW(*ptr))
4366 ptr++;
4368 for (monthPtr = month; !isspace(*ptr) &&
4369 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4370 monthPtr++, ptr++)
4371 *monthPtr = *ptr;
4372 *monthPtr = 0;
4373 st.wMonth = HTTP_ParseMonth(month);
4374 if (!st.wMonth || st.wMonth > 12)
4376 ERR("unexpected month %s\n", debugstr_w(month));
4377 return FALSE;
4380 while (isspaceW(*ptr))
4381 ptr++;
4383 num = strtoulW(ptr, &nextPtr, 10);
4384 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4386 ERR("unexpected day %s\n", debugstr_w(ptr));
4387 return FALSE;
4389 ptr = nextPtr;
4390 st.wDay = (WORD)num;
4392 while (isspaceW(*ptr))
4393 ptr++;
4395 if (!HTTP_ParseTime(&st, &ptr))
4396 return FALSE;
4398 while (isspaceW(*ptr))
4399 ptr++;
4401 num = strtoulW(ptr, &nextPtr, 10);
4402 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4404 ERR("unexpected year %s\n", debugstr_w(ptr));
4405 return FALSE;
4407 ptr = nextPtr;
4408 st.wYear = (WORD)num;
4410 while (isspaceW(*ptr))
4411 ptr++;
4413 /* asctime() doesn't report a timezone, but some web servers do, so accept
4414 * with or without GMT.
4416 if (*ptr && strcmpW(ptr, gmt))
4418 ERR("unexpected timezone %s\n", debugstr_w(ptr));
4419 return FALSE;
4421 return SystemTimeToFileTime(&st, ft);
4424 static BOOL HTTP_ParseRfc1123Date(LPCWSTR value, FILETIME *ft)
4426 static const WCHAR gmt[]= { 'G','M','T',0 };
4427 WCHAR *nextPtr, day[4], month[4], *monthPtr;
4428 LPCWSTR ptr;
4429 unsigned long num;
4430 SYSTEMTIME st = { 0 };
4432 ptr = strchrW(value, ',');
4433 if (!ptr)
4434 return FALSE;
4435 if (ptr - value != 3)
4437 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4438 return FALSE;
4440 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4441 day[3] = 0;
4442 st.wDayOfWeek = HTTP_ParseWkday(day);
4443 if (st.wDayOfWeek > 6)
4445 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4446 return FALSE;
4448 ptr++;
4450 while (isspaceW(*ptr))
4451 ptr++;
4453 num = strtoulW(ptr, &nextPtr, 10);
4454 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4456 WARN("unexpected day %s\n", debugstr_w(value));
4457 return FALSE;
4459 ptr = nextPtr;
4460 st.wDay = (WORD)num;
4462 while (isspaceW(*ptr))
4463 ptr++;
4465 for (monthPtr = month; !isspace(*ptr) &&
4466 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4467 monthPtr++, ptr++)
4468 *monthPtr = *ptr;
4469 *monthPtr = 0;
4470 st.wMonth = HTTP_ParseMonth(month);
4471 if (!st.wMonth || st.wMonth > 12)
4473 WARN("unexpected month %s\n", debugstr_w(month));
4474 return FALSE;
4477 while (isspaceW(*ptr))
4478 ptr++;
4480 num = strtoulW(ptr, &nextPtr, 10);
4481 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4483 ERR("unexpected year %s\n", debugstr_w(value));
4484 return FALSE;
4486 ptr = nextPtr;
4487 st.wYear = (WORD)num;
4489 if (!HTTP_ParseTime(&st, &ptr))
4490 return FALSE;
4492 while (isspaceW(*ptr))
4493 ptr++;
4495 if (strcmpW(ptr, gmt))
4497 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4498 return FALSE;
4500 return SystemTimeToFileTime(&st, ft);
4503 static WORD HTTP_ParseWeekday(LPCWSTR day)
4505 static const WCHAR days[7][10] = {{ 's','u','n','d','a','y',0 },
4506 { 'm','o','n','d','a','y',0 },
4507 { 't','u','e','s','d','a','y',0 },
4508 { 'w','e','d','n','e','s','d','a','y',0 },
4509 { 't','h','u','r','s','d','a','y',0 },
4510 { 'f','r','i','d','a','y',0 },
4511 { 's','a','t','u','r','d','a','y',0 }};
4512 unsigned int i;
4513 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4514 if (!strcmpiW(day, days[i]))
4515 return i;
4517 /* Invalid */
4518 return 7;
4521 static BOOL HTTP_ParseRfc850Date(LPCWSTR value, FILETIME *ft)
4523 static const WCHAR gmt[]= { 'G','M','T',0 };
4524 WCHAR *nextPtr, day[10], month[4], *monthPtr;
4525 LPCWSTR ptr;
4526 unsigned long num;
4527 SYSTEMTIME st = { 0 };
4529 ptr = strchrW(value, ',');
4530 if (!ptr)
4531 return FALSE;
4532 if (ptr - value == 3)
4534 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4535 day[3] = 0;
4536 st.wDayOfWeek = HTTP_ParseWkday(day);
4537 if (st.wDayOfWeek > 6)
4539 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4540 return FALSE;
4543 else if (ptr - value < sizeof(day) / sizeof(day[0]))
4545 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4546 day[ptr - value + 1] = 0;
4547 st.wDayOfWeek = HTTP_ParseWeekday(day);
4548 if (st.wDayOfWeek > 6)
4550 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4551 return FALSE;
4554 else
4556 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4557 return FALSE;
4559 ptr++;
4561 while (isspaceW(*ptr))
4562 ptr++;
4564 num = strtoulW(ptr, &nextPtr, 10);
4565 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4567 ERR("unexpected day %s\n", debugstr_w(value));
4568 return FALSE;
4570 ptr = nextPtr;
4571 st.wDay = (WORD)num;
4573 if (*ptr != '-')
4575 ERR("unexpected month format %s\n", debugstr_w(ptr));
4576 return FALSE;
4578 ptr++;
4580 for (monthPtr = month; *ptr != '-' &&
4581 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4582 monthPtr++, ptr++)
4583 *monthPtr = *ptr;
4584 *monthPtr = 0;
4585 st.wMonth = HTTP_ParseMonth(month);
4586 if (!st.wMonth || st.wMonth > 12)
4588 ERR("unexpected month %s\n", debugstr_w(month));
4589 return FALSE;
4592 if (*ptr != '-')
4594 ERR("unexpected year format %s\n", debugstr_w(ptr));
4595 return FALSE;
4597 ptr++;
4599 num = strtoulW(ptr, &nextPtr, 10);
4600 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4602 ERR("unexpected year %s\n", debugstr_w(value));
4603 return FALSE;
4605 ptr = nextPtr;
4606 st.wYear = (WORD)num;
4608 if (!HTTP_ParseTime(&st, &ptr))
4609 return FALSE;
4611 while (isspaceW(*ptr))
4612 ptr++;
4614 if (strcmpW(ptr, gmt))
4616 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4617 return FALSE;
4619 return SystemTimeToFileTime(&st, ft);
4622 static BOOL HTTP_ParseDate(LPCWSTR value, FILETIME *ft)
4624 static const WCHAR zero[] = { '0',0 };
4625 BOOL ret;
4627 if (!strcmpW(value, zero))
4629 ft->dwLowDateTime = ft->dwHighDateTime = 0;
4630 ret = TRUE;
4632 else if (strchrW(value, ','))
4634 ret = HTTP_ParseRfc1123Date(value, ft);
4635 if (!ret)
4637 ret = HTTP_ParseRfc850Date(value, ft);
4638 if (!ret)
4639 ERR("unexpected date format %s\n", debugstr_w(value));
4642 else
4644 ret = HTTP_ParseDateAsAsctime(value, ft);
4645 if (!ret)
4646 ERR("unexpected date format %s\n", debugstr_w(value));
4648 return ret;
4651 static void HTTP_ProcessExpires(http_request_t *request)
4653 BOOL expirationFound = FALSE;
4654 int headerIndex;
4656 /* Look for a Cache-Control header with a max-age directive, as it takes
4657 * precedence over the Expires header.
4659 headerIndex = HTTP_GetCustomHeaderIndex(request, szCache_Control, 0, FALSE);
4660 if (headerIndex != -1)
4662 LPHTTPHEADERW ccHeader = &request->custHeaders[headerIndex];
4663 LPWSTR ptr;
4665 for (ptr = ccHeader->lpszValue; ptr && *ptr; )
4667 LPWSTR comma = strchrW(ptr, ','), end, equal;
4669 if (comma)
4670 end = comma;
4671 else
4672 end = ptr + strlenW(ptr);
4673 for (equal = end - 1; equal > ptr && *equal != '='; equal--)
4675 if (*equal == '=')
4677 static const WCHAR max_age[] = {
4678 'm','a','x','-','a','g','e',0 };
4680 if (!strncmpiW(ptr, max_age, equal - ptr - 1))
4682 LPWSTR nextPtr;
4683 unsigned long age;
4685 age = strtoulW(equal + 1, &nextPtr, 10);
4686 if (nextPtr > equal + 1)
4688 LARGE_INTEGER ft;
4690 NtQuerySystemTime( &ft );
4691 /* Age is in seconds, FILETIME resolution is in
4692 * 100 nanosecond intervals.
4694 ft.QuadPart += age * (ULONGLONG)1000000;
4695 request->expires.dwLowDateTime = ft.u.LowPart;
4696 request->expires.dwHighDateTime = ft.u.HighPart;
4697 expirationFound = TRUE;
4701 if (comma)
4703 ptr = comma + 1;
4704 while (isspaceW(*ptr))
4705 ptr++;
4707 else
4708 ptr = NULL;
4711 if (!expirationFound)
4713 headerIndex = HTTP_GetCustomHeaderIndex(request, szExpires, 0, FALSE);
4714 if (headerIndex != -1)
4716 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4717 FILETIME ft;
4719 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4721 expirationFound = TRUE;
4722 request->expires = ft;
4726 if (!expirationFound)
4728 LARGE_INTEGER t;
4730 /* With no known age, default to 10 minutes until expiration. */
4731 NtQuerySystemTime( &t );
4732 t.QuadPart += 10 * 60 * (ULONGLONG)10000000;
4733 request->expires.dwLowDateTime = t.u.LowPart;
4734 request->expires.dwHighDateTime = t.u.HighPart;
4738 static void HTTP_ProcessLastModified(http_request_t *request)
4740 int headerIndex;
4742 headerIndex = HTTP_GetCustomHeaderIndex(request, szLast_Modified, 0, FALSE);
4743 if (headerIndex != -1)
4745 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4746 FILETIME ft;
4748 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4749 request->last_modified = ft;
4753 static void http_process_keep_alive(http_request_t *req)
4755 int index;
4757 if ((index = HTTP_GetCustomHeaderIndex(req, szConnection, 0, FALSE)) != -1)
4758 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4759 else if ((index = HTTP_GetCustomHeaderIndex(req, szProxy_Connection, 0, FALSE)) != -1)
4760 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4761 else
4762 req->netconn->keep_alive = !strcmpiW(req->version, g_szHttp1_1);
4765 static DWORD open_http_connection(http_request_t *request, BOOL *reusing)
4767 const BOOL is_https = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) != 0;
4768 netconn_t *netconn = NULL;
4769 DWORD res;
4771 reset_data_stream(request);
4773 if (request->netconn)
4775 if (is_valid_netconn(request->netconn) && NETCON_is_alive(request->netconn))
4777 *reusing = TRUE;
4778 return ERROR_SUCCESS;
4780 else
4782 free_netconn(request->netconn);
4783 request->netconn = NULL;
4787 res = HTTP_ResolveName(request);
4788 if(res != ERROR_SUCCESS)
4789 return res;
4791 EnterCriticalSection(&connection_pool_cs);
4793 while(!list_empty(&request->server->conn_pool)) {
4794 netconn = LIST_ENTRY(list_head(&request->server->conn_pool), netconn_t, pool_entry);
4795 list_remove(&netconn->pool_entry);
4797 if(is_valid_netconn(netconn) && NETCON_is_alive(netconn))
4798 break;
4800 TRACE("connection %p closed during idle\n", netconn);
4801 free_netconn(netconn);
4802 netconn = NULL;
4805 LeaveCriticalSection(&connection_pool_cs);
4807 if(netconn) {
4808 TRACE("<-- reusing %p netconn\n", netconn);
4809 request->netconn = netconn;
4810 *reusing = TRUE;
4811 return ERROR_SUCCESS;
4814 TRACE("connecting to %s, proxy %s\n", debugstr_w(request->server->name),
4815 request->proxy ? debugstr_w(request->proxy->name) : "(null)");
4817 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4818 INTERNET_STATUS_CONNECTING_TO_SERVER,
4819 request->server->addr_str,
4820 strlen(request->server->addr_str)+1);
4822 res = create_netconn(is_https, request->proxy ? request->proxy : request->server, request->security_flags,
4823 (request->hdr.ErrorMask & INTERNET_ERROR_MASK_COMBINED_SEC_CERT) != 0,
4824 request->connect_timeout, &netconn);
4825 if(res != ERROR_SUCCESS) {
4826 ERR("create_netconn failed: %u\n", res);
4827 return res;
4830 request->netconn = netconn;
4832 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4833 INTERNET_STATUS_CONNECTED_TO_SERVER,
4834 request->server->addr_str, strlen(request->server->addr_str)+1);
4836 if(is_https) {
4837 /* Note: we differ from Microsoft's WinINet here. they seem to have
4838 * a bug that causes no status callbacks to be sent when starting
4839 * a tunnel to a proxy server using the CONNECT verb. i believe our
4840 * behaviour to be more correct and to not cause any incompatibilities
4841 * because using a secure connection through a proxy server is a rare
4842 * case that would be hard for anyone to depend on */
4843 if(request->proxy)
4844 res = HTTP_SecureProxyConnect(request);
4845 if(res == ERROR_SUCCESS)
4846 res = NETCON_secure_connect(request->netconn, request->server);
4849 if(res != ERROR_SUCCESS) {
4850 http_release_netconn(request, FALSE);
4851 return res;
4854 *reusing = FALSE;
4855 TRACE("Created connection to %s: %p\n", debugstr_w(request->server->name), netconn);
4856 return ERROR_SUCCESS;
4859 /***********************************************************************
4860 * HTTP_HttpSendRequestW (internal)
4862 * Sends the specified request to the HTTP server
4864 * RETURNS
4865 * ERROR_SUCCESS on success
4866 * win32 error code on failure
4869 static DWORD HTTP_HttpSendRequestW(http_request_t *request, LPCWSTR lpszHeaders,
4870 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
4871 DWORD dwContentLength, BOOL bEndRequest)
4873 INT cnt;
4874 BOOL redirected = FALSE;
4875 LPWSTR requestString = NULL;
4876 INT responseLen;
4877 BOOL loop_next;
4878 static const WCHAR szContentLength[] =
4879 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
4880 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
4881 DWORD res;
4883 TRACE("--> %p\n", request);
4885 assert(request->hdr.htype == WH_HHTTPREQ);
4887 /* if the verb is NULL default to GET */
4888 if (!request->verb)
4889 request->verb = heap_strdupW(szGET);
4891 if (dwContentLength || strcmpW(request->verb, szGET))
4893 sprintfW(contentLengthStr, szContentLength, dwContentLength);
4894 HTTP_HttpAddRequestHeadersW(request, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_REPLACE);
4895 request->bytesToWrite = dwContentLength;
4897 if (request->session->appInfo->agent)
4899 WCHAR *agent_header;
4900 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4901 int len;
4903 len = strlenW(request->session->appInfo->agent) + strlenW(user_agent);
4904 agent_header = heap_alloc(len * sizeof(WCHAR));
4905 sprintfW(agent_header, user_agent, request->session->appInfo->agent);
4907 HTTP_HttpAddRequestHeadersW(request, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4908 heap_free(agent_header);
4910 if (request->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
4912 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4913 HTTP_HttpAddRequestHeadersW(request, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4915 if ((request->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && strcmpW(request->verb, szGET))
4917 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4918 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4919 HTTP_HttpAddRequestHeadersW(request, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4922 /* add the headers the caller supplied */
4923 if( lpszHeaders && dwHeaderLength )
4924 HTTP_HttpAddRequestHeadersW(request, lpszHeaders, dwHeaderLength, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
4928 DWORD len;
4929 BOOL reusing_connection;
4930 char *ascii_req;
4932 loop_next = FALSE;
4934 if(redirected) {
4935 request->contentLength = ~0u;
4936 request->bytesToWrite = 0;
4939 if (TRACE_ON(wininet))
4941 LPHTTPHEADERW Host = HTTP_GetHeader(request, hostW);
4942 TRACE("Going to url %s %s\n", debugstr_w(Host->lpszValue), debugstr_w(request->path));
4945 HTTP_FixURL(request);
4946 if (request->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
4948 HTTP_ProcessHeader(request, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
4950 HTTP_InsertAuthorization(request, request->authInfo, szAuthorization);
4951 HTTP_InsertAuthorization(request, request->proxyAuthInfo, szProxy_Authorization);
4953 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
4954 HTTP_InsertCookies(request);
4956 if (request->proxy)
4958 WCHAR *url = build_proxy_path_url(request);
4959 requestString = build_request_header(request, request->verb, url, request->version, TRUE);
4960 heap_free(url);
4962 else
4963 requestString = build_request_header(request, request->verb, request->path, request->version, TRUE);
4966 TRACE("Request header -> %s\n", debugstr_w(requestString) );
4968 res = open_http_connection(request, &reusing_connection);
4969 if (res != ERROR_SUCCESS)
4970 break;
4972 /* send the request as ASCII, tack on the optional data */
4973 if (!lpOptional || redirected)
4974 dwOptionalLength = 0;
4975 len = WideCharToMultiByte( CP_ACP, 0, requestString, -1,
4976 NULL, 0, NULL, NULL );
4977 ascii_req = heap_alloc(len + dwOptionalLength);
4978 WideCharToMultiByte( CP_ACP, 0, requestString, -1,
4979 ascii_req, len, NULL, NULL );
4980 if( lpOptional )
4981 memcpy( &ascii_req[len-1], lpOptional, dwOptionalLength );
4982 len = (len + dwOptionalLength - 1);
4983 ascii_req[len] = 0;
4984 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
4986 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4987 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
4989 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
4990 res = NETCON_send(request->netconn, ascii_req, len, 0, &cnt);
4991 heap_free( ascii_req );
4992 if(res != ERROR_SUCCESS) {
4993 TRACE("send failed: %u\n", res);
4994 if(!reusing_connection)
4995 break;
4996 http_release_netconn(request, FALSE);
4997 loop_next = TRUE;
4998 continue;
5001 request->bytesWritten = dwOptionalLength;
5003 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5004 INTERNET_STATUS_REQUEST_SENT,
5005 &len, sizeof(DWORD));
5007 if (bEndRequest)
5009 DWORD dwBufferSize;
5011 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5012 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5014 if (HTTP_GetResponseHeaders(request, &responseLen))
5016 http_release_netconn(request, FALSE);
5017 res = ERROR_INTERNET_CONNECTION_ABORTED;
5018 goto lend;
5020 /* FIXME: We should know that connection is closed before sending
5021 * headers. Otherwise wrong callbacks are executed */
5022 if(!responseLen && reusing_connection) {
5023 TRACE("Connection closed by server, reconnecting\n");
5024 http_release_netconn(request, FALSE);
5025 loop_next = TRUE;
5026 continue;
5029 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5030 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
5031 sizeof(DWORD));
5033 http_process_keep_alive(request);
5034 HTTP_ProcessCookies(request);
5035 HTTP_ProcessExpires(request);
5036 HTTP_ProcessLastModified(request);
5038 res = set_content_length(request);
5039 if(res != ERROR_SUCCESS)
5040 goto lend;
5041 if(!request->contentLength)
5042 http_release_netconn(request, TRUE);
5044 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
5046 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5047 dwBufferSize=sizeof(szNewLocation);
5048 switch(request->status_code) {
5049 case HTTP_STATUS_REDIRECT:
5050 case HTTP_STATUS_MOVED:
5051 case HTTP_STATUS_REDIRECT_KEEP_VERB:
5052 case HTTP_STATUS_REDIRECT_METHOD:
5053 if(HTTP_HttpQueryInfoW(request,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL) != ERROR_SUCCESS)
5054 break;
5056 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5057 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5059 heap_free(request->verb);
5060 request->verb = heap_strdupW(szGET);
5062 http_release_netconn(request, drain_content(request, FALSE));
5063 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5065 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5066 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5067 res = HTTP_HandleRedirect(request, new_url);
5068 if (res == ERROR_SUCCESS)
5070 heap_free(requestString);
5071 loop_next = TRUE;
5073 heap_free( new_url );
5075 redirected = TRUE;
5078 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
5080 WCHAR szAuthValue[2048];
5081 dwBufferSize=2048;
5082 if (request->status_code == HTTP_STATUS_DENIED)
5084 LPHTTPHEADERW Host = HTTP_GetHeader(request, hostW);
5085 DWORD dwIndex = 0;
5086 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5088 if (HTTP_DoAuthorization(request, szAuthValue,
5089 &request->authInfo,
5090 request->session->userName,
5091 request->session->password,
5092 Host->lpszValue))
5094 heap_free(requestString);
5095 if(!drain_content(request, TRUE)) {
5096 FIXME("Could not drain content\n");
5097 http_release_netconn(request, FALSE);
5099 loop_next = TRUE;
5100 break;
5104 if(!loop_next) {
5105 TRACE("Cleaning wrong authorization data\n");
5106 destroy_authinfo(request->authInfo);
5107 request->authInfo = NULL;
5110 if (request->status_code == HTTP_STATUS_PROXY_AUTH_REQ)
5112 DWORD dwIndex = 0;
5113 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5115 if (HTTP_DoAuthorization(request, szAuthValue,
5116 &request->proxyAuthInfo,
5117 request->session->appInfo->proxyUsername,
5118 request->session->appInfo->proxyPassword,
5119 NULL))
5121 heap_free(requestString);
5122 if(!drain_content(request, TRUE)) {
5123 FIXME("Could not drain content\n");
5124 http_release_netconn(request, FALSE);
5126 loop_next = TRUE;
5127 break;
5131 if(!loop_next) {
5132 TRACE("Cleaning wrong proxy authorization data\n");
5133 destroy_authinfo(request->proxyAuthInfo);
5134 request->proxyAuthInfo = NULL;
5139 else
5140 res = ERROR_SUCCESS;
5142 while (loop_next);
5144 lend:
5145 heap_free(requestString);
5147 /* TODO: send notification for P3P header */
5149 if(res == ERROR_SUCCESS)
5150 create_cache_entry(request);
5152 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5154 if (res == ERROR_SUCCESS) {
5155 if(bEndRequest && request->contentLength && request->bytesWritten == request->bytesToWrite)
5156 HTTP_ReceiveRequestData(request, TRUE, NULL);
5157 else
5158 send_request_complete(request,
5159 request->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)request->hdr.hInternet : 1, 0);
5160 }else {
5161 send_request_complete(request, 0, res);
5165 TRACE("<--\n");
5166 return res;
5169 typedef struct {
5170 task_header_t hdr;
5171 WCHAR *headers;
5172 DWORD headers_len;
5173 void *optional;
5174 DWORD optional_len;
5175 DWORD content_len;
5176 BOOL end_request;
5177 } send_request_task_t;
5179 /***********************************************************************
5181 * Helper functions for the HttpSendRequest(Ex) functions
5184 static void AsyncHttpSendRequestProc(task_header_t *hdr)
5186 send_request_task_t *task = (send_request_task_t*)hdr;
5187 http_request_t *request = (http_request_t*)task->hdr.hdr;
5189 TRACE("%p\n", request);
5191 HTTP_HttpSendRequestW(request, task->headers, task->headers_len, task->optional,
5192 task->optional_len, task->content_len, task->end_request);
5194 heap_free(task->headers);
5198 static DWORD HTTP_HttpEndRequestW(http_request_t *request, DWORD dwFlags, DWORD_PTR dwContext)
5200 DWORD dwBufferSize;
5201 INT responseLen;
5202 DWORD res = ERROR_SUCCESS;
5204 if(!is_valid_netconn(request->netconn)) {
5205 WARN("Not connected\n");
5206 send_request_complete(request, 0, ERROR_INTERNET_OPERATION_CANCELLED);
5207 return ERROR_INTERNET_OPERATION_CANCELLED;
5210 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5211 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5213 if (HTTP_GetResponseHeaders(request, &responseLen) || !responseLen)
5214 res = ERROR_HTTP_HEADER_NOT_FOUND;
5216 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5217 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
5219 /* process cookies here. Is this right? */
5220 http_process_keep_alive(request);
5221 HTTP_ProcessCookies(request);
5222 HTTP_ProcessExpires(request);
5223 HTTP_ProcessLastModified(request);
5225 if ((res = set_content_length(request)) == ERROR_SUCCESS) {
5226 if(!request->contentLength)
5227 http_release_netconn(request, TRUE);
5230 if (res == ERROR_SUCCESS && !(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
5232 switch(request->status_code) {
5233 case HTTP_STATUS_REDIRECT:
5234 case HTTP_STATUS_MOVED:
5235 case HTTP_STATUS_REDIRECT_METHOD:
5236 case HTTP_STATUS_REDIRECT_KEEP_VERB: {
5237 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5238 dwBufferSize=sizeof(szNewLocation);
5239 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, szNewLocation, &dwBufferSize, NULL) != ERROR_SUCCESS)
5240 break;
5242 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5243 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5245 heap_free(request->verb);
5246 request->verb = heap_strdupW(szGET);
5248 http_release_netconn(request, drain_content(request, FALSE));
5249 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5251 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5252 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5253 res = HTTP_HandleRedirect(request, new_url);
5254 if (res == ERROR_SUCCESS)
5255 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, TRUE);
5256 heap_free( new_url );
5262 if(res == ERROR_SUCCESS)
5263 create_cache_entry(request);
5265 if (res == ERROR_SUCCESS && request->contentLength)
5266 HTTP_ReceiveRequestData(request, TRUE, NULL);
5267 else
5268 send_request_complete(request, res == ERROR_SUCCESS, res);
5270 return res;
5273 /***********************************************************************
5274 * HttpEndRequestA (WININET.@)
5276 * Ends an HTTP request that was started by HttpSendRequestEx
5278 * RETURNS
5279 * TRUE if successful
5280 * FALSE on failure
5283 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
5284 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5286 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5288 if (lpBuffersOut)
5290 SetLastError(ERROR_INVALID_PARAMETER);
5291 return FALSE;
5294 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
5297 typedef struct {
5298 task_header_t hdr;
5299 DWORD flags;
5300 DWORD context;
5301 } end_request_task_t;
5303 static void AsyncHttpEndRequestProc(task_header_t *hdr)
5305 end_request_task_t *task = (end_request_task_t*)hdr;
5306 http_request_t *req = (http_request_t*)task->hdr.hdr;
5308 TRACE("%p\n", req);
5310 HTTP_HttpEndRequestW(req, task->flags, task->context);
5313 /***********************************************************************
5314 * HttpEndRequestW (WININET.@)
5316 * Ends an HTTP request that was started by HttpSendRequestEx
5318 * RETURNS
5319 * TRUE if successful
5320 * FALSE on failure
5323 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
5324 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5326 http_request_t *request;
5327 DWORD res;
5329 TRACE("%p %p %x %lx -->\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5331 if (lpBuffersOut)
5333 SetLastError(ERROR_INVALID_PARAMETER);
5334 return FALSE;
5337 request = (http_request_t*) get_handle_object( hRequest );
5339 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5341 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
5342 if (request)
5343 WININET_Release( &request->hdr );
5344 return FALSE;
5346 request->hdr.dwFlags |= dwFlags;
5348 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5350 end_request_task_t *task;
5352 task = alloc_async_task(&request->hdr, AsyncHttpEndRequestProc, sizeof(*task));
5353 task->flags = dwFlags;
5354 task->context = dwContext;
5356 INTERNET_AsyncCall(&task->hdr);
5357 res = ERROR_IO_PENDING;
5359 else
5360 res = HTTP_HttpEndRequestW(request, dwFlags, dwContext);
5362 WININET_Release( &request->hdr );
5363 TRACE("%u <--\n", res);
5364 if(res != ERROR_SUCCESS)
5365 SetLastError(res);
5366 return res == ERROR_SUCCESS;
5369 /***********************************************************************
5370 * HttpSendRequestExA (WININET.@)
5372 * Sends the specified request to the HTTP server and allows chunked
5373 * transfers.
5375 * RETURNS
5376 * Success: TRUE
5377 * Failure: FALSE, call GetLastError() for more information.
5379 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
5380 LPINTERNET_BUFFERSA lpBuffersIn,
5381 LPINTERNET_BUFFERSA lpBuffersOut,
5382 DWORD dwFlags, DWORD_PTR dwContext)
5384 INTERNET_BUFFERSW BuffersInW;
5385 BOOL rc = FALSE;
5386 DWORD headerlen;
5387 LPWSTR header = NULL;
5389 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5390 lpBuffersOut, dwFlags, dwContext);
5392 if (lpBuffersIn)
5394 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
5395 if (lpBuffersIn->lpcszHeader)
5397 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
5398 lpBuffersIn->dwHeadersLength,0,0);
5399 header = heap_alloc(headerlen*sizeof(WCHAR));
5400 if (!(BuffersInW.lpcszHeader = header))
5402 SetLastError(ERROR_OUTOFMEMORY);
5403 return FALSE;
5405 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
5406 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5407 header, headerlen);
5409 else
5410 BuffersInW.lpcszHeader = NULL;
5411 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
5412 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
5413 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
5414 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
5415 BuffersInW.Next = NULL;
5418 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
5420 heap_free(header);
5421 return rc;
5424 /***********************************************************************
5425 * HttpSendRequestExW (WININET.@)
5427 * Sends the specified request to the HTTP server and allows chunked
5428 * transfers
5430 * RETURNS
5431 * Success: TRUE
5432 * Failure: FALSE, call GetLastError() for more information.
5434 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
5435 LPINTERNET_BUFFERSW lpBuffersIn,
5436 LPINTERNET_BUFFERSW lpBuffersOut,
5437 DWORD dwFlags, DWORD_PTR dwContext)
5439 http_request_t *request;
5440 http_session_t *session;
5441 appinfo_t *hIC;
5442 DWORD res;
5444 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5445 lpBuffersOut, dwFlags, dwContext);
5447 request = (http_request_t*) get_handle_object( hRequest );
5449 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5451 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5452 goto lend;
5455 session = request->session;
5456 assert(session->hdr.htype == WH_HHTTPSESSION);
5457 hIC = session->appInfo;
5458 assert(hIC->hdr.htype == WH_HINIT);
5460 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5462 send_request_task_t *task;
5464 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5465 if (lpBuffersIn)
5467 DWORD size = 0;
5469 if (lpBuffersIn->lpcszHeader)
5471 if (lpBuffersIn->dwHeadersLength == ~0u)
5472 size = (strlenW( lpBuffersIn->lpcszHeader ) + 1) * sizeof(WCHAR);
5473 else
5474 size = lpBuffersIn->dwHeadersLength * sizeof(WCHAR);
5476 task->headers = heap_alloc(size);
5477 memcpy(task->headers, lpBuffersIn->lpcszHeader, size);
5479 else task->headers = NULL;
5481 task->headers_len = size / sizeof(WCHAR);
5482 task->optional = lpBuffersIn->lpvBuffer;
5483 task->optional_len = lpBuffersIn->dwBufferLength;
5484 task->content_len = lpBuffersIn->dwBufferTotal;
5486 else
5488 task->headers = NULL;
5489 task->headers_len = 0;
5490 task->optional = NULL;
5491 task->optional_len = 0;
5492 task->content_len = 0;
5495 task->end_request = FALSE;
5497 INTERNET_AsyncCall(&task->hdr);
5498 res = ERROR_IO_PENDING;
5500 else
5502 if (lpBuffersIn)
5503 res = HTTP_HttpSendRequestW(request, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5504 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
5505 lpBuffersIn->dwBufferTotal, FALSE);
5506 else
5507 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, FALSE);
5510 lend:
5511 if ( request )
5512 WININET_Release( &request->hdr );
5514 TRACE("<---\n");
5515 SetLastError(res);
5516 return res == ERROR_SUCCESS;
5519 /***********************************************************************
5520 * HttpSendRequestW (WININET.@)
5522 * Sends the specified request to the HTTP server
5524 * RETURNS
5525 * TRUE on success
5526 * FALSE on failure
5529 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
5530 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5532 http_request_t *request;
5533 http_session_t *session = NULL;
5534 appinfo_t *hIC = NULL;
5535 DWORD res = ERROR_SUCCESS;
5537 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
5538 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
5540 request = (http_request_t*) get_handle_object( hHttpRequest );
5541 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5543 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5544 goto lend;
5547 session = request->session;
5548 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
5550 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5551 goto lend;
5554 hIC = session->appInfo;
5555 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
5557 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5558 goto lend;
5561 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5563 send_request_task_t *task;
5565 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5566 if (lpszHeaders)
5568 DWORD size;
5570 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
5571 else size = dwHeaderLength * sizeof(WCHAR);
5573 task->headers = heap_alloc(size);
5574 memcpy(task->headers, lpszHeaders, size);
5576 else
5577 task->headers = NULL;
5578 task->headers_len = dwHeaderLength;
5579 task->optional = lpOptional;
5580 task->optional_len = dwOptionalLength;
5581 task->content_len = dwOptionalLength;
5582 task->end_request = TRUE;
5584 INTERNET_AsyncCall(&task->hdr);
5585 res = ERROR_IO_PENDING;
5587 else
5589 res = HTTP_HttpSendRequestW(request, lpszHeaders,
5590 dwHeaderLength, lpOptional, dwOptionalLength,
5591 dwOptionalLength, TRUE);
5593 lend:
5594 if( request )
5595 WININET_Release( &request->hdr );
5597 SetLastError(res);
5598 return res == ERROR_SUCCESS;
5601 /***********************************************************************
5602 * HttpSendRequestA (WININET.@)
5604 * Sends the specified request to the HTTP server
5606 * RETURNS
5607 * TRUE on success
5608 * FALSE on failure
5611 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
5612 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5614 BOOL result;
5615 LPWSTR szHeaders=NULL;
5616 DWORD nLen=dwHeaderLength;
5617 if(lpszHeaders!=NULL)
5619 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
5620 szHeaders = heap_alloc(nLen*sizeof(WCHAR));
5621 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
5623 result = HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
5624 heap_free(szHeaders);
5625 return result;
5628 /***********************************************************************
5629 * HTTPSESSION_Destroy (internal)
5631 * Deallocate session handle
5634 static void HTTPSESSION_Destroy(object_header_t *hdr)
5636 http_session_t *session = (http_session_t*) hdr;
5638 TRACE("%p\n", session);
5640 WININET_Release(&session->appInfo->hdr);
5642 heap_free(session->hostName);
5643 heap_free(session->password);
5644 heap_free(session->userName);
5647 static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
5649 http_session_t *ses = (http_session_t *)hdr;
5651 switch(option) {
5652 case INTERNET_OPTION_HANDLE_TYPE:
5653 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5655 if (*size < sizeof(ULONG))
5656 return ERROR_INSUFFICIENT_BUFFER;
5658 *size = sizeof(DWORD);
5659 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
5660 return ERROR_SUCCESS;
5661 case INTERNET_OPTION_CONNECT_TIMEOUT:
5662 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5664 if (*size < sizeof(DWORD))
5665 return ERROR_INSUFFICIENT_BUFFER;
5667 *size = sizeof(DWORD);
5668 *(DWORD *)buffer = ses->connect_timeout;
5669 return ERROR_SUCCESS;
5671 case INTERNET_OPTION_SEND_TIMEOUT:
5672 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5674 if (*size < sizeof(DWORD))
5675 return ERROR_INSUFFICIENT_BUFFER;
5677 *size = sizeof(DWORD);
5678 *(DWORD *)buffer = ses->send_timeout;
5679 return ERROR_SUCCESS;
5681 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5682 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5684 if (*size < sizeof(DWORD))
5685 return ERROR_INSUFFICIENT_BUFFER;
5687 *size = sizeof(DWORD);
5688 *(DWORD *)buffer = ses->receive_timeout;
5689 return ERROR_SUCCESS;
5692 return INET_QueryOption(hdr, option, buffer, size, unicode);
5695 static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
5697 http_session_t *ses = (http_session_t*)hdr;
5699 switch(option) {
5700 case INTERNET_OPTION_USERNAME:
5702 heap_free(ses->userName);
5703 if (!(ses->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5704 return ERROR_SUCCESS;
5706 case INTERNET_OPTION_PASSWORD:
5708 heap_free(ses->password);
5709 if (!(ses->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5710 return ERROR_SUCCESS;
5712 case INTERNET_OPTION_PROXY_USERNAME:
5714 heap_free(ses->appInfo->proxyUsername);
5715 if (!(ses->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5716 return ERROR_SUCCESS;
5718 case INTERNET_OPTION_PROXY_PASSWORD:
5720 heap_free(ses->appInfo->proxyPassword);
5721 if (!(ses->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5722 return ERROR_SUCCESS;
5724 case INTERNET_OPTION_CONNECT_TIMEOUT:
5726 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5727 ses->connect_timeout = *(DWORD *)buffer;
5728 return ERROR_SUCCESS;
5730 case INTERNET_OPTION_SEND_TIMEOUT:
5732 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5733 ses->send_timeout = *(DWORD *)buffer;
5734 return ERROR_SUCCESS;
5736 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5738 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5739 ses->receive_timeout = *(DWORD *)buffer;
5740 return ERROR_SUCCESS;
5742 default: break;
5745 return INET_SetOption(hdr, option, buffer, size);
5748 static const object_vtbl_t HTTPSESSIONVtbl = {
5749 HTTPSESSION_Destroy,
5750 NULL,
5751 HTTPSESSION_QueryOption,
5752 HTTPSESSION_SetOption,
5753 NULL,
5754 NULL,
5755 NULL,
5756 NULL,
5757 NULL
5761 /***********************************************************************
5762 * HTTP_Connect (internal)
5764 * Create http session handle
5766 * RETURNS
5767 * HINTERNET a session handle on success
5768 * NULL on failure
5771 DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
5772 INTERNET_PORT serverPort, LPCWSTR lpszUserName,
5773 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
5774 DWORD dwInternalFlags, HINTERNET *ret)
5776 http_session_t *session = NULL;
5778 TRACE("-->\n");
5780 if (!lpszServerName || !lpszServerName[0])
5781 return ERROR_INVALID_PARAMETER;
5783 assert( hIC->hdr.htype == WH_HINIT );
5785 session = alloc_object(&hIC->hdr, &HTTPSESSIONVtbl, sizeof(http_session_t));
5786 if (!session)
5787 return ERROR_OUTOFMEMORY;
5790 * According to my tests. The name is not resolved until a request is sent
5793 session->hdr.htype = WH_HHTTPSESSION;
5794 session->hdr.dwFlags = dwFlags;
5795 session->hdr.dwContext = dwContext;
5796 session->hdr.dwInternalFlags |= dwInternalFlags;
5798 WININET_AddRef( &hIC->hdr );
5799 session->appInfo = hIC;
5800 list_add_head( &hIC->hdr.children, &session->hdr.entry );
5802 session->hostName = heap_strdupW(lpszServerName);
5803 if (lpszUserName && lpszUserName[0])
5804 session->userName = heap_strdupW(lpszUserName);
5805 if (lpszPassword && lpszPassword[0])
5806 session->password = heap_strdupW(lpszPassword);
5807 session->hostPort = serverPort;
5808 session->connect_timeout = hIC->connect_timeout;
5809 session->send_timeout = INFINITE;
5810 session->receive_timeout = INFINITE;
5812 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5813 if (!(session->hdr.dwInternalFlags & INET_OPENURL))
5815 INTERNET_SendCallback(&hIC->hdr, dwContext,
5816 INTERNET_STATUS_HANDLE_CREATED, &session->hdr.hInternet,
5817 sizeof(HINTERNET));
5821 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5822 * windows
5825 TRACE("%p --> %p\n", hIC, session);
5827 *ret = session->hdr.hInternet;
5828 return ERROR_SUCCESS;
5831 /***********************************************************************
5832 * HTTP_clear_response_headers (internal)
5834 * clear out any old response headers
5836 static void HTTP_clear_response_headers( http_request_t *request )
5838 DWORD i;
5840 for( i=0; i<request->nCustHeaders; i++)
5842 if( !request->custHeaders[i].lpszField )
5843 continue;
5844 if( !request->custHeaders[i].lpszValue )
5845 continue;
5846 if ( request->custHeaders[i].wFlags & HDR_ISREQUEST )
5847 continue;
5848 HTTP_DeleteCustomHeader( request, i );
5849 i--;
5853 /***********************************************************************
5854 * HTTP_GetResponseHeaders (internal)
5856 * Read server response
5858 * RETURNS
5860 * TRUE on success
5861 * FALSE on error
5863 static DWORD HTTP_GetResponseHeaders(http_request_t *request, INT *len)
5865 INT cbreaks = 0;
5866 WCHAR buffer[MAX_REPLY_LEN];
5867 DWORD buflen = MAX_REPLY_LEN;
5868 INT rc = 0;
5869 char bufferA[MAX_REPLY_LEN];
5870 LPWSTR status_code = NULL, status_text = NULL;
5871 DWORD res = ERROR_HTTP_INVALID_SERVER_RESPONSE;
5872 BOOL codeHundred = FALSE;
5874 TRACE("-->\n");
5876 if(!is_valid_netconn(request->netconn))
5877 goto lend;
5879 /* clear old response headers (eg. from a redirect response) */
5880 HTTP_clear_response_headers( request );
5882 NETCON_set_timeout( request->netconn, FALSE, request->receive_timeout );
5883 do {
5885 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5887 buflen = MAX_REPLY_LEN;
5888 if ((res = read_line(request, bufferA, &buflen)))
5889 goto lend;
5891 if (!buflen) goto lend;
5893 rc += buflen;
5894 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5895 /* check is this a status code line? */
5896 if (!strncmpW(buffer, g_szHttp1_0, 4))
5898 /* split the version from the status code */
5899 status_code = strchrW( buffer, ' ' );
5900 if( !status_code )
5901 goto lend;
5902 *status_code++=0;
5904 /* split the status code from the status text */
5905 status_text = strchrW( status_code, ' ' );
5906 if( status_text )
5907 *status_text++=0;
5909 request->status_code = atoiW(status_code);
5911 TRACE("version [%s] status code [%s] status text [%s]\n",
5912 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
5914 codeHundred = request->status_code == HTTP_STATUS_CONTINUE;
5916 else if (!codeHundred)
5918 WARN("No status line at head of response (%s)\n", debugstr_w(buffer));
5920 heap_free(request->version);
5921 heap_free(request->statusText);
5923 request->status_code = HTTP_STATUS_OK;
5924 request->version = heap_strdupW(g_szHttp1_0);
5925 request->statusText = heap_strdupW(szOK);
5927 goto lend;
5929 } while (codeHundred);
5931 /* Add status code */
5932 HTTP_ProcessHeader(request, szStatus, status_code,
5933 HTTP_ADDHDR_FLAG_REPLACE);
5935 heap_free(request->version);
5936 heap_free(request->statusText);
5938 request->version = heap_strdupW(buffer);
5939 request->statusText = heap_strdupW(status_text ? status_text : emptyW);
5941 /* Restore the spaces */
5942 *(status_code-1) = ' ';
5943 if (status_text)
5944 *(status_text-1) = ' ';
5946 /* Parse each response line */
5949 buflen = MAX_REPLY_LEN;
5950 if (!read_line(request, bufferA, &buflen) && buflen)
5952 LPWSTR * pFieldAndValue;
5954 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
5956 if (!bufferA[0]) break;
5957 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5959 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
5960 if (pFieldAndValue)
5962 HTTP_ProcessHeader(request, pFieldAndValue[0], pFieldAndValue[1],
5963 HTTP_ADDREQ_FLAG_ADD );
5964 HTTP_FreeTokens(pFieldAndValue);
5967 else
5969 cbreaks++;
5970 if (cbreaks >= 2)
5971 break;
5973 }while(1);
5975 res = ERROR_SUCCESS;
5977 lend:
5979 *len = rc;
5980 TRACE("<--\n");
5981 return res;
5984 /***********************************************************************
5985 * HTTP_InterpretHttpHeader (internal)
5987 * Parse server response
5989 * RETURNS
5991 * Pointer to array of field, value, NULL on success.
5992 * NULL on error.
5994 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
5996 LPWSTR * pTokenPair;
5997 LPWSTR pszColon;
5998 INT len;
6000 pTokenPair = heap_alloc_zero(sizeof(*pTokenPair)*3);
6002 pszColon = strchrW(buffer, ':');
6003 /* must have two tokens */
6004 if (!pszColon)
6006 HTTP_FreeTokens(pTokenPair);
6007 if (buffer[0])
6008 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
6009 return NULL;
6012 pTokenPair[0] = heap_alloc((pszColon - buffer + 1) * sizeof(WCHAR));
6013 if (!pTokenPair[0])
6015 HTTP_FreeTokens(pTokenPair);
6016 return NULL;
6018 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
6019 pTokenPair[0][pszColon - buffer] = '\0';
6021 /* skip colon */
6022 pszColon++;
6023 len = strlenW(pszColon);
6024 pTokenPair[1] = heap_alloc((len + 1) * sizeof(WCHAR));
6025 if (!pTokenPair[1])
6027 HTTP_FreeTokens(pTokenPair);
6028 return NULL;
6030 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
6032 strip_spaces(pTokenPair[0]);
6033 strip_spaces(pTokenPair[1]);
6035 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
6036 return pTokenPair;
6039 /***********************************************************************
6040 * HTTP_ProcessHeader (internal)
6042 * Stuff header into header tables according to <dwModifier>
6046 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6048 static DWORD HTTP_ProcessHeader(http_request_t *request, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
6050 LPHTTPHEADERW lphttpHdr = NULL;
6051 INT index = -1;
6052 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
6053 DWORD res = ERROR_HTTP_INVALID_HEADER;
6055 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
6057 /* REPLACE wins out over ADD */
6058 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6059 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
6061 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
6062 index = -1;
6063 else
6064 index = HTTP_GetCustomHeaderIndex(request, field, 0, request_only);
6066 if (index >= 0)
6068 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
6069 return ERROR_HTTP_INVALID_HEADER;
6070 lphttpHdr = &request->custHeaders[index];
6072 else if (value)
6074 HTTPHEADERW hdr;
6076 hdr.lpszField = (LPWSTR)field;
6077 hdr.lpszValue = (LPWSTR)value;
6078 hdr.wFlags = hdr.wCount = 0;
6080 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6081 hdr.wFlags |= HDR_ISREQUEST;
6083 return HTTP_InsertCustomHeader(request, &hdr);
6085 /* no value to delete */
6086 else return ERROR_SUCCESS;
6088 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6089 lphttpHdr->wFlags |= HDR_ISREQUEST;
6090 else
6091 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
6093 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6095 HTTP_DeleteCustomHeader( request, index );
6097 if (value && value[0])
6099 HTTPHEADERW hdr;
6101 hdr.lpszField = (LPWSTR)field;
6102 hdr.lpszValue = (LPWSTR)value;
6103 hdr.wFlags = hdr.wCount = 0;
6105 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6106 hdr.wFlags |= HDR_ISREQUEST;
6108 return HTTP_InsertCustomHeader(request, &hdr);
6111 return ERROR_SUCCESS;
6113 else if (dwModifier & COALESCEFLAGS)
6115 LPWSTR lpsztmp;
6116 WCHAR ch = 0;
6117 INT len = 0;
6118 INT origlen = strlenW(lphttpHdr->lpszValue);
6119 INT valuelen = strlenW(value);
6121 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
6123 ch = ',';
6124 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6126 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6128 ch = ';';
6129 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6132 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
6134 lpsztmp = heap_realloc(lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
6135 if (lpsztmp)
6137 lphttpHdr->lpszValue = lpsztmp;
6138 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6139 if (ch > 0)
6141 lphttpHdr->lpszValue[origlen] = ch;
6142 origlen++;
6143 lphttpHdr->lpszValue[origlen] = ' ';
6144 origlen++;
6147 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
6148 lphttpHdr->lpszValue[len] = '\0';
6149 res = ERROR_SUCCESS;
6151 else
6153 WARN("heap_realloc (%d bytes) failed\n",len+1);
6154 res = ERROR_OUTOFMEMORY;
6157 TRACE("<-- %d\n", res);
6158 return res;
6161 /***********************************************************************
6162 * HTTP_GetCustomHeaderIndex (internal)
6164 * Return index of custom header from header array
6167 static INT HTTP_GetCustomHeaderIndex(http_request_t *request, LPCWSTR lpszField,
6168 int requested_index, BOOL request_only)
6170 DWORD index;
6172 TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
6174 for (index = 0; index < request->nCustHeaders; index++)
6176 if (strcmpiW(request->custHeaders[index].lpszField, lpszField))
6177 continue;
6179 if (request_only && !(request->custHeaders[index].wFlags & HDR_ISREQUEST))
6180 continue;
6182 if (!request_only && (request->custHeaders[index].wFlags & HDR_ISREQUEST))
6183 continue;
6185 if (requested_index == 0)
6186 break;
6187 requested_index --;
6190 if (index >= request->nCustHeaders)
6191 index = -1;
6193 TRACE("Return: %d\n", index);
6194 return index;
6198 /***********************************************************************
6199 * HTTP_InsertCustomHeader (internal)
6201 * Insert header into array
6204 static DWORD HTTP_InsertCustomHeader(http_request_t *request, LPHTTPHEADERW lpHdr)
6206 INT count;
6207 LPHTTPHEADERW lph = NULL;
6209 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
6210 count = request->nCustHeaders + 1;
6211 if (count > 1)
6212 lph = heap_realloc_zero(request->custHeaders, sizeof(HTTPHEADERW) * count);
6213 else
6214 lph = heap_alloc_zero(sizeof(HTTPHEADERW) * count);
6216 if (!lph)
6217 return ERROR_OUTOFMEMORY;
6219 request->custHeaders = lph;
6220 request->custHeaders[count-1].lpszField = heap_strdupW(lpHdr->lpszField);
6221 request->custHeaders[count-1].lpszValue = heap_strdupW(lpHdr->lpszValue);
6222 request->custHeaders[count-1].wFlags = lpHdr->wFlags;
6223 request->custHeaders[count-1].wCount= lpHdr->wCount;
6224 request->nCustHeaders++;
6226 return ERROR_SUCCESS;
6230 /***********************************************************************
6231 * HTTP_DeleteCustomHeader (internal)
6233 * Delete header from array
6234 * If this function is called, the indexs may change.
6236 static BOOL HTTP_DeleteCustomHeader(http_request_t *request, DWORD index)
6238 if( request->nCustHeaders <= 0 )
6239 return FALSE;
6240 if( index >= request->nCustHeaders )
6241 return FALSE;
6242 request->nCustHeaders--;
6244 heap_free(request->custHeaders[index].lpszField);
6245 heap_free(request->custHeaders[index].lpszValue);
6247 memmove( &request->custHeaders[index], &request->custHeaders[index+1],
6248 (request->nCustHeaders - index)* sizeof(HTTPHEADERW) );
6249 memset( &request->custHeaders[request->nCustHeaders], 0, sizeof(HTTPHEADERW) );
6251 return TRUE;
6255 /***********************************************************************
6256 * HTTP_VerifyValidHeader (internal)
6258 * Verify the given header is not invalid for the given http request
6261 static BOOL HTTP_VerifyValidHeader(http_request_t *request, LPCWSTR field)
6263 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
6264 if (!strcmpW(request->version, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
6265 return ERROR_HTTP_INVALID_HEADER;
6267 return ERROR_SUCCESS;
6270 /***********************************************************************
6271 * IsHostInProxyBypassList (@)
6273 * Undocumented
6276 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
6278 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
6279 return FALSE;