wininet: Get rid of no longer needed get_avail_data from data stream implementations.
[wine.git] / dlls / wininet / http.c
blobfd58b1f3e166cfd2882b99ea4ccd9cd28f8eac43
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"
32 #include <stdlib.h>
34 #ifdef HAVE_ZLIB
35 # include <zlib.h>
36 #endif
38 #include "winsock2.h"
39 #include "ws2ipdef.h"
41 #include <stdarg.h>
42 #include <stdio.h>
43 #include <time.h>
44 #include <assert.h>
46 #include "windef.h"
47 #include "winbase.h"
48 #include "wininet.h"
49 #include "winerror.h"
50 #include "winternl.h"
51 #define NO_SHLWAPI_STREAM
52 #define NO_SHLWAPI_REG
53 #define NO_SHLWAPI_STRFCNS
54 #define NO_SHLWAPI_GDI
55 #include "shlwapi.h"
56 #include "sspi.h"
57 #include "wincrypt.h"
58 #include "winuser.h"
60 #include "internet.h"
61 #include "wine/debug.h"
62 #include "wine/exception.h"
63 #include "wine/unicode.h"
65 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
67 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
68 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
69 static const WCHAR szOK[] = {'O','K',0};
70 static const WCHAR hostW[] = { 'H','o','s','t',0 };
71 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
72 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
73 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
74 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
75 static const WCHAR szGET[] = { 'G','E','T', 0 };
76 static const WCHAR szHEAD[] = { 'H','E','A','D', 0 };
78 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
79 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
80 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
81 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
82 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
83 static const WCHAR szAge[] = { 'A','g','e',0 };
84 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
85 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
86 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
87 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
88 static const WCHAR szContent_Disposition[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
89 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
90 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
91 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
92 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
93 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
94 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
95 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
96 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 };
97 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
98 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
99 static const WCHAR szDate[] = { 'D','a','t','e',0 };
100 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
101 static const WCHAR szETag[] = { 'E','T','a','g',0 };
102 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
103 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
104 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
105 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
106 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
107 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
108 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
109 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
110 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
111 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
112 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
113 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
114 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
115 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
116 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
117 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
118 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
119 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
120 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
121 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
122 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
123 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 };
124 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
125 static const WCHAR szURI[] = { 'U','R','I',0 };
126 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
127 static const WCHAR szVary[] = { 'V','a','r','y',0 };
128 static const WCHAR szVia[] = { 'V','i','a',0 };
129 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
130 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
132 static const WCHAR emptyW[] = {0};
134 #define HTTP_REFERER szReferer
135 #define HTTP_ACCEPT szAccept
136 #define HTTP_USERAGENT szUser_Agent
138 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
139 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
140 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
141 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
142 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
143 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
144 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
146 #define COLLECT_TIME 60000
148 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
150 struct HttpAuthInfo
152 LPWSTR scheme;
153 CredHandle cred;
154 CtxtHandle ctx;
155 TimeStamp exp;
156 ULONG attr;
157 ULONG max_token;
158 void *auth_data;
159 unsigned int auth_data_len;
160 BOOL finished; /* finished authenticating */
164 typedef struct _basicAuthorizationData
166 struct list entry;
168 LPWSTR host;
169 LPWSTR realm;
170 LPSTR authorization;
171 UINT authorizationLen;
172 } basicAuthorizationData;
174 typedef struct _authorizationData
176 struct list entry;
178 LPWSTR host;
179 LPWSTR scheme;
180 LPWSTR domain;
181 UINT domain_len;
182 LPWSTR user;
183 UINT user_len;
184 LPWSTR password;
185 UINT password_len;
186 } authorizationData;
188 static struct list basicAuthorizationCache = LIST_INIT(basicAuthorizationCache);
189 static struct list authorizationCache = LIST_INIT(authorizationCache);
191 static CRITICAL_SECTION authcache_cs;
192 static CRITICAL_SECTION_DEBUG critsect_debug =
194 0, 0, &authcache_cs,
195 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
196 0, 0, { (DWORD_PTR)(__FILE__ ": authcache_cs") }
198 static CRITICAL_SECTION authcache_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
200 static DWORD HTTP_GetResponseHeaders(http_request_t *req, INT *len);
201 static DWORD HTTP_ProcessHeader(http_request_t *req, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
202 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
203 static DWORD HTTP_InsertCustomHeader(http_request_t *req, LPHTTPHEADERW lpHdr);
204 static INT HTTP_GetCustomHeaderIndex(http_request_t *req, LPCWSTR lpszField, INT index, BOOL Request);
205 static BOOL HTTP_DeleteCustomHeader(http_request_t *req, DWORD index);
206 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
207 static DWORD HTTP_HttpQueryInfoW(http_request_t*, DWORD, LPVOID, LPDWORD, LPDWORD);
208 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
209 static BOOL drain_content(http_request_t*,BOOL);
211 static CRITICAL_SECTION connection_pool_cs;
212 static CRITICAL_SECTION_DEBUG connection_pool_debug =
214 0, 0, &connection_pool_cs,
215 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
216 0, 0, { (DWORD_PTR)(__FILE__ ": connection_pool_cs") }
218 static CRITICAL_SECTION connection_pool_cs = { &connection_pool_debug, -1, 0, 0, 0, 0 };
220 static struct list connection_pool = LIST_INIT(connection_pool);
221 static BOOL collector_running;
223 void server_addref(server_t *server)
225 InterlockedIncrement(&server->ref);
228 void server_release(server_t *server)
230 if(InterlockedDecrement(&server->ref))
231 return;
233 list_remove(&server->entry);
235 if(server->cert_chain)
236 CertFreeCertificateChain(server->cert_chain);
237 heap_free(server->name);
238 heap_free(server->scheme_host_port);
239 heap_free(server);
242 static BOOL process_host_port(server_t *server)
244 BOOL default_port;
245 size_t name_len;
246 WCHAR *buf;
248 static const WCHAR httpW[] = {'h','t','t','p',0};
249 static const WCHAR httpsW[] = {'h','t','t','p','s',0};
250 static const WCHAR formatW[] = {'%','s',':','/','/','%','s',':','%','u',0};
252 name_len = strlenW(server->name);
253 buf = heap_alloc((name_len + 10 /* strlen("://:<port>") */)*sizeof(WCHAR) + sizeof(httpsW));
254 if(!buf)
255 return FALSE;
257 sprintfW(buf, formatW, server->is_https ? httpsW : httpW, server->name, server->port);
258 server->scheme_host_port = buf;
260 server->host_port = server->scheme_host_port + 7 /* strlen("http://") */;
261 if(server->is_https)
262 server->host_port++;
264 default_port = server->port == (server->is_https ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT);
265 server->canon_host_port = default_port ? server->name : server->host_port;
266 return TRUE;
269 server_t *get_server(substr_t name, INTERNET_PORT port, BOOL is_https, BOOL do_create)
271 server_t *iter, *server = NULL;
273 EnterCriticalSection(&connection_pool_cs);
275 LIST_FOR_EACH_ENTRY(iter, &connection_pool, server_t, entry) {
276 if(iter->port == port && name.len == strlenW(iter->name) && !strncmpW(iter->name, name.str, name.len)
277 && iter->is_https == is_https) {
278 server = iter;
279 server_addref(server);
280 break;
284 if(!server && do_create) {
285 server = heap_alloc_zero(sizeof(*server));
286 if(server) {
287 server->ref = 2; /* list reference and return */
288 server->port = port;
289 server->is_https = is_https;
290 list_init(&server->conn_pool);
291 server->name = heap_strndupW(name.str, name.len);
292 if(server->name && process_host_port(server)) {
293 list_add_head(&connection_pool, &server->entry);
294 }else {
295 heap_free(server);
296 server = NULL;
301 LeaveCriticalSection(&connection_pool_cs);
303 return server;
306 BOOL collect_connections(collect_type_t collect_type)
308 netconn_t *netconn, *netconn_safe;
309 server_t *server, *server_safe;
310 BOOL remaining = FALSE;
311 DWORD64 now;
313 now = GetTickCount64();
315 LIST_FOR_EACH_ENTRY_SAFE(server, server_safe, &connection_pool, server_t, entry) {
316 LIST_FOR_EACH_ENTRY_SAFE(netconn, netconn_safe, &server->conn_pool, netconn_t, pool_entry) {
317 if(collect_type > COLLECT_TIMEOUT || netconn->keep_until < now) {
318 TRACE("freeing %p\n", netconn);
319 list_remove(&netconn->pool_entry);
320 free_netconn(netconn);
321 }else {
322 remaining = TRUE;
326 if(collect_type == COLLECT_CLEANUP) {
327 list_remove(&server->entry);
328 list_init(&server->entry);
329 server_release(server);
333 return remaining;
336 static DWORD WINAPI collect_connections_proc(void *arg)
338 BOOL remaining_conns;
340 do {
341 /* FIXME: Use more sophisticated method */
342 Sleep(5000);
344 EnterCriticalSection(&connection_pool_cs);
346 remaining_conns = collect_connections(COLLECT_TIMEOUT);
347 if(!remaining_conns)
348 collector_running = FALSE;
350 LeaveCriticalSection(&connection_pool_cs);
351 }while(remaining_conns);
353 FreeLibraryAndExitThread(WININET_hModule, 0);
356 /***********************************************************************
357 * HTTP_GetHeader (internal)
359 * Headers section must be held
361 static LPHTTPHEADERW HTTP_GetHeader(http_request_t *req, LPCWSTR head)
363 int HeaderIndex = 0;
364 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
365 if (HeaderIndex == -1)
366 return NULL;
367 else
368 return &req->custHeaders[HeaderIndex];
371 static WCHAR *get_host_header( http_request_t *req )
373 HTTPHEADERW *header;
374 WCHAR *ret = NULL;
376 EnterCriticalSection( &req->headers_section );
377 if ((header = HTTP_GetHeader( req, hostW ))) ret = heap_strdupW( header->lpszValue );
378 else ret = heap_strdupW( req->server->canon_host_port );
379 LeaveCriticalSection( &req->headers_section );
380 return ret;
383 struct data_stream_vtbl_t {
384 BOOL (*end_of_data)(data_stream_t*,http_request_t*);
385 DWORD (*read)(data_stream_t*,http_request_t*,BYTE*,DWORD,DWORD*,BOOL);
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;
398 enum {
399 CHUNKED_STREAM_STATE_READING_CHUNK_SIZE,
400 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE,
401 CHUNKED_STREAM_STATE_READING_CHUNK,
402 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA,
403 CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END,
404 CHUNKED_STREAM_STATE_END_OF_STREAM
405 } state;
406 } chunked_stream_t;
408 static inline void destroy_data_stream(data_stream_t *stream)
410 stream->vtbl->destroy(stream);
413 static void reset_data_stream(http_request_t *req)
415 destroy_data_stream(req->data_stream);
416 req->data_stream = &req->netconn_stream.data_stream;
417 req->read_pos = req->read_size = req->netconn_stream.content_read = 0;
418 req->read_gzip = FALSE;
421 static void remove_header( http_request_t *request, const WCHAR *str, BOOL from_request )
423 int index;
424 EnterCriticalSection( &request->headers_section );
425 index = HTTP_GetCustomHeaderIndex( request, str, 0, from_request );
426 if (index != -1) HTTP_DeleteCustomHeader( request, index );
427 LeaveCriticalSection( &request->headers_section );
430 #ifdef HAVE_ZLIB
432 typedef struct {
433 data_stream_t stream;
434 data_stream_t *parent_stream;
435 z_stream zstream;
436 BYTE buf[READ_BUFFER_SIZE];
437 DWORD buf_size;
438 DWORD buf_pos;
439 BOOL end_of_data;
440 } gzip_stream_t;
442 static BOOL gzip_end_of_data(data_stream_t *stream, http_request_t *req)
444 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
445 return gzip_stream->end_of_data
446 || (!gzip_stream->buf_size && gzip_stream->parent_stream->vtbl->end_of_data(gzip_stream->parent_stream, req));
449 static DWORD gzip_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
450 DWORD *read, BOOL allow_blocking)
452 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
453 z_stream *zstream = &gzip_stream->zstream;
454 DWORD current_read, ret_read = 0;
455 int zres;
456 DWORD res = ERROR_SUCCESS;
458 TRACE("(%d %x)\n", size, allow_blocking);
460 while(size && !gzip_stream->end_of_data) {
461 if(!gzip_stream->buf_size) {
462 if(gzip_stream->buf_pos) {
463 if(gzip_stream->buf_size)
464 memmove(gzip_stream->buf, gzip_stream->buf+gzip_stream->buf_pos, gzip_stream->buf_size);
465 gzip_stream->buf_pos = 0;
467 res = gzip_stream->parent_stream->vtbl->read(gzip_stream->parent_stream, req, gzip_stream->buf+gzip_stream->buf_size,
468 sizeof(gzip_stream->buf)-gzip_stream->buf_size, &current_read, allow_blocking);
469 gzip_stream->buf_size += current_read;
470 if(res != ERROR_SUCCESS)
471 break;
473 if(!current_read) {
474 WARN("unexpected end of data\n");
475 gzip_stream->end_of_data = TRUE;
476 break;
480 zstream->next_in = gzip_stream->buf+gzip_stream->buf_pos;
481 zstream->avail_in = gzip_stream->buf_size;
482 zstream->next_out = buf+ret_read;
483 zstream->avail_out = size;
484 zres = inflate(&gzip_stream->zstream, 0);
485 current_read = size - zstream->avail_out;
486 size -= current_read;
487 ret_read += current_read;
488 gzip_stream->buf_size -= zstream->next_in - (gzip_stream->buf+gzip_stream->buf_pos);
489 gzip_stream->buf_pos = zstream->next_in-gzip_stream->buf;
490 if(zres == Z_STREAM_END) {
491 TRACE("end of data\n");
492 gzip_stream->end_of_data = TRUE;
493 inflateEnd(zstream);
494 }else if(zres != Z_OK) {
495 WARN("inflate failed %d: %s\n", zres, debugstr_a(zstream->msg));
496 if(!ret_read)
497 res = ERROR_INTERNET_DECODING_FAILED;
498 break;
501 if(ret_read)
502 allow_blocking = FALSE;
505 TRACE("read %u bytes\n", ret_read);
506 if(ret_read)
507 res = ERROR_SUCCESS;
508 *read = ret_read;
509 return res;
512 static BOOL gzip_drain_content(data_stream_t *stream, http_request_t *req)
514 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
515 return gzip_stream->parent_stream->vtbl->drain_content(gzip_stream->parent_stream, req);
518 static void gzip_destroy(data_stream_t *stream)
520 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
522 destroy_data_stream(gzip_stream->parent_stream);
524 if(!gzip_stream->end_of_data)
525 inflateEnd(&gzip_stream->zstream);
526 heap_free(gzip_stream);
529 static const data_stream_vtbl_t gzip_stream_vtbl = {
530 gzip_end_of_data,
531 gzip_read,
532 gzip_drain_content,
533 gzip_destroy
536 static voidpf wininet_zalloc(voidpf opaque, uInt items, uInt size)
538 return heap_alloc(items*size);
541 static void wininet_zfree(voidpf opaque, voidpf address)
543 heap_free(address);
546 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
548 gzip_stream_t *gzip_stream;
549 int zres;
551 gzip_stream = heap_alloc_zero(sizeof(gzip_stream_t));
552 if(!gzip_stream)
553 return ERROR_OUTOFMEMORY;
555 gzip_stream->stream.vtbl = &gzip_stream_vtbl;
556 gzip_stream->zstream.zalloc = wininet_zalloc;
557 gzip_stream->zstream.zfree = wininet_zfree;
559 zres = inflateInit2(&gzip_stream->zstream, is_gzip ? 0x1f : -15);
560 if(zres != Z_OK) {
561 ERR("inflateInit failed: %d\n", zres);
562 heap_free(gzip_stream);
563 return ERROR_OUTOFMEMORY;
566 remove_header(req, szContent_Length, FALSE);
568 if(req->read_size) {
569 memcpy(gzip_stream->buf, req->read_buf+req->read_pos, req->read_size);
570 gzip_stream->buf_size = req->read_size;
571 req->read_pos = req->read_size = 0;
574 req->read_gzip = TRUE;
575 gzip_stream->parent_stream = req->data_stream;
576 req->data_stream = &gzip_stream->stream;
577 return ERROR_SUCCESS;
580 #else
582 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
584 ERR("gzip stream not supported, missing zlib.\n");
585 return ERROR_SUCCESS;
588 #endif
590 /***********************************************************************
591 * HTTP_FreeTokens (internal)
593 * Frees table of pointers.
595 static void HTTP_FreeTokens(LPWSTR * token_array)
597 int i;
598 for (i = 0; token_array[i]; i++) heap_free(token_array[i]);
599 heap_free(token_array);
602 static void HTTP_FixURL(http_request_t *request)
604 static const WCHAR szSlash[] = { '/',0 };
605 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
607 /* If we don't have a path we set it to root */
608 if (NULL == request->path)
609 request->path = heap_strdupW(szSlash);
610 else /* remove \r and \n*/
612 int nLen = strlenW(request->path);
613 while ((nLen >0 ) && ((request->path[nLen-1] == '\r')||(request->path[nLen-1] == '\n')))
615 nLen--;
616 request->path[nLen]='\0';
618 /* Replace '\' with '/' */
619 while (nLen>0) {
620 nLen--;
621 if (request->path[nLen] == '\\') request->path[nLen]='/';
625 if(CSTR_EQUAL != CompareStringW( LOCALE_INVARIANT, NORM_IGNORECASE,
626 request->path, strlenW(request->path), szHttp, strlenW(szHttp) )
627 && request->path[0] != '/') /* not an absolute path ?? --> fix it !! */
629 WCHAR *fixurl = heap_alloc((strlenW(request->path) + 2)*sizeof(WCHAR));
630 *fixurl = '/';
631 strcpyW(fixurl + 1, request->path);
632 heap_free( request->path );
633 request->path = fixurl;
637 static WCHAR* build_request_header(http_request_t *request, const WCHAR *verb,
638 const WCHAR *path, const WCHAR *version, BOOL use_cr)
640 static const WCHAR szSpace[] = {' ',0};
641 static const WCHAR szColon[] = {':',' ',0};
642 static const WCHAR szCr[] = {'\r',0};
643 static const WCHAR szLf[] = {'\n',0};
644 LPWSTR requestString;
645 DWORD len, n;
646 LPCWSTR *req;
647 UINT i;
649 EnterCriticalSection( &request->headers_section );
651 /* allocate space for an array of all the string pointers to be added */
652 len = request->nCustHeaders * 5 + 10;
653 if (!(req = heap_alloc( len * sizeof(const WCHAR *) )))
655 LeaveCriticalSection( &request->headers_section );
656 return NULL;
659 /* add the verb, path and HTTP version string */
660 n = 0;
661 req[n++] = verb;
662 req[n++] = szSpace;
663 req[n++] = path;
664 req[n++] = szSpace;
665 req[n++] = version;
666 if (use_cr)
667 req[n++] = szCr;
668 req[n++] = szLf;
670 /* Append custom request headers */
671 for (i = 0; i < request->nCustHeaders; i++)
673 if (request->custHeaders[i].wFlags & HDR_ISREQUEST)
675 req[n++] = request->custHeaders[i].lpszField;
676 req[n++] = szColon;
677 req[n++] = request->custHeaders[i].lpszValue;
678 if (use_cr)
679 req[n++] = szCr;
680 req[n++] = szLf;
682 TRACE("Adding custom header %s (%s)\n",
683 debugstr_w(request->custHeaders[i].lpszField),
684 debugstr_w(request->custHeaders[i].lpszValue));
687 if (use_cr)
688 req[n++] = szCr;
689 req[n++] = szLf;
690 req[n] = NULL;
692 requestString = HTTP_build_req( req, 4 );
693 heap_free( req );
694 LeaveCriticalSection( &request->headers_section );
695 return requestString;
698 static WCHAR* build_response_header(http_request_t *request, BOOL use_cr)
700 static const WCHAR colonW[] = { ':',' ',0 };
701 static const WCHAR crW[] = { '\r',0 };
702 static const WCHAR lfW[] = { '\n',0 };
703 static const WCHAR status_fmt[] = { ' ','%','u',' ',0 };
704 const WCHAR **req;
705 WCHAR *ret, buf[14];
706 DWORD i, n = 0;
708 EnterCriticalSection( &request->headers_section );
710 if (!(req = heap_alloc( (request->nCustHeaders * 5 + 8) * sizeof(WCHAR *) )))
712 LeaveCriticalSection( &request->headers_section );
713 return NULL;
716 if (request->status_code)
718 req[n++] = request->version;
719 sprintfW(buf, status_fmt, request->status_code);
720 req[n++] = buf;
721 req[n++] = request->statusText;
722 if (use_cr)
723 req[n++] = crW;
724 req[n++] = lfW;
727 for(i = 0; i < request->nCustHeaders; i++)
729 if(!(request->custHeaders[i].wFlags & HDR_ISREQUEST)
730 && strcmpW(request->custHeaders[i].lpszField, szStatus))
732 req[n++] = request->custHeaders[i].lpszField;
733 req[n++] = colonW;
734 req[n++] = request->custHeaders[i].lpszValue;
735 if(use_cr)
736 req[n++] = crW;
737 req[n++] = lfW;
739 TRACE("Adding custom header %s (%s)\n",
740 debugstr_w(request->custHeaders[i].lpszField),
741 debugstr_w(request->custHeaders[i].lpszValue));
744 if(use_cr)
745 req[n++] = crW;
746 req[n++] = lfW;
747 req[n] = NULL;
749 ret = HTTP_build_req(req, 0);
750 heap_free(req);
751 LeaveCriticalSection( &request->headers_section );
752 return ret;
755 static void HTTP_ProcessCookies( http_request_t *request )
757 int HeaderIndex;
758 int numCookies = 0;
759 LPHTTPHEADERW setCookieHeader;
761 if(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES)
762 return;
764 EnterCriticalSection( &request->headers_section );
766 while((HeaderIndex = HTTP_GetCustomHeaderIndex(request, szSet_Cookie, numCookies++, FALSE)) != -1)
768 const WCHAR *data;
769 substr_t name;
771 setCookieHeader = &request->custHeaders[HeaderIndex];
773 if (!setCookieHeader->lpszValue)
774 continue;
776 data = strchrW(setCookieHeader->lpszValue, '=');
777 if(!data)
778 continue;
780 name = substr(setCookieHeader->lpszValue, data - setCookieHeader->lpszValue);
781 data++;
782 set_cookie(substrz(request->server->name), substrz(request->path), name, substrz(data), INTERNET_COOKIE_HTTPONLY);
785 LeaveCriticalSection( &request->headers_section );
788 static void strip_spaces(LPWSTR start)
790 LPWSTR str = start;
791 LPWSTR end;
793 while (*str == ' ')
794 str++;
796 if (str != start)
797 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
799 end = start + strlenW(start) - 1;
800 while (end >= start && *end == ' ')
802 *end = '\0';
803 end--;
807 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue, LPWSTR *pszRealm )
809 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
810 static const WCHAR szRealm[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
811 BOOL is_basic;
812 is_basic = !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
813 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
814 if (is_basic && pszRealm)
816 LPCWSTR token;
817 LPCWSTR ptr = &pszAuthValue[ARRAYSIZE(szBasic)];
818 LPCWSTR realm;
819 ptr++;
820 *pszRealm=NULL;
821 token = strchrW(ptr,'=');
822 if (!token)
823 return TRUE;
824 realm = ptr;
825 while (*realm == ' ')
826 realm++;
827 if(!strncmpiW(realm, szRealm, ARRAYSIZE(szRealm)) &&
828 (realm[ARRAYSIZE(szRealm)] == ' ' || realm[ARRAYSIZE(szRealm)] == '='))
830 token++;
831 while (*token == ' ')
832 token++;
833 if (*token == '\0')
834 return TRUE;
835 *pszRealm = heap_strdupW(token);
836 strip_spaces(*pszRealm);
840 return is_basic;
843 static void destroy_authinfo( struct HttpAuthInfo *authinfo )
845 if (!authinfo) return;
847 if (SecIsValidHandle(&authinfo->ctx))
848 DeleteSecurityContext(&authinfo->ctx);
849 if (SecIsValidHandle(&authinfo->cred))
850 FreeCredentialsHandle(&authinfo->cred);
852 heap_free(authinfo->auth_data);
853 heap_free(authinfo->scheme);
854 heap_free(authinfo);
857 static UINT retrieve_cached_basic_authorization(const WCHAR *host, const WCHAR *realm, char **auth_data)
859 basicAuthorizationData *ad;
860 UINT rc = 0;
862 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host),debugstr_w(realm));
864 EnterCriticalSection(&authcache_cs);
865 LIST_FOR_EACH_ENTRY(ad, &basicAuthorizationCache, basicAuthorizationData, entry)
867 if (!strcmpiW(host, ad->host) && (!realm || !strcmpW(realm, ad->realm)))
869 TRACE("Authorization found in cache\n");
870 *auth_data = heap_alloc(ad->authorizationLen);
871 memcpy(*auth_data,ad->authorization,ad->authorizationLen);
872 rc = ad->authorizationLen;
873 break;
876 LeaveCriticalSection(&authcache_cs);
877 return rc;
880 static void cache_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR auth_data, UINT auth_data_len)
882 struct list *cursor;
883 basicAuthorizationData* ad = NULL;
885 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host),debugstr_w(realm),debugstr_an(auth_data,auth_data_len));
887 EnterCriticalSection(&authcache_cs);
888 LIST_FOR_EACH(cursor, &basicAuthorizationCache)
890 basicAuthorizationData *check = LIST_ENTRY(cursor,basicAuthorizationData,entry);
891 if (!strcmpiW(host,check->host) && !strcmpW(realm,check->realm))
893 ad = check;
894 break;
898 if (ad)
900 TRACE("Found match in cache, replacing\n");
901 heap_free(ad->authorization);
902 ad->authorization = heap_alloc(auth_data_len);
903 memcpy(ad->authorization, auth_data, auth_data_len);
904 ad->authorizationLen = auth_data_len;
906 else
908 ad = heap_alloc(sizeof(basicAuthorizationData));
909 ad->host = heap_strdupW(host);
910 ad->realm = heap_strdupW(realm);
911 ad->authorization = heap_alloc(auth_data_len);
912 memcpy(ad->authorization, auth_data, auth_data_len);
913 ad->authorizationLen = auth_data_len;
914 list_add_head(&basicAuthorizationCache,&ad->entry);
915 TRACE("authorization cached\n");
917 LeaveCriticalSection(&authcache_cs);
920 static BOOL retrieve_cached_authorization(LPWSTR host, LPWSTR scheme,
921 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
923 authorizationData *ad;
925 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
927 EnterCriticalSection(&authcache_cs);
928 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry) {
929 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
930 TRACE("Authorization found in cache\n");
932 nt_auth_identity->User = heap_strdupW(ad->user);
933 nt_auth_identity->Password = heap_strdupW(ad->password);
934 nt_auth_identity->Domain = heap_alloc(sizeof(WCHAR)*ad->domain_len);
935 if(!nt_auth_identity->User || !nt_auth_identity->Password ||
936 (!nt_auth_identity->Domain && ad->domain_len)) {
937 heap_free(nt_auth_identity->User);
938 heap_free(nt_auth_identity->Password);
939 heap_free(nt_auth_identity->Domain);
940 break;
943 nt_auth_identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
944 nt_auth_identity->UserLength = ad->user_len;
945 nt_auth_identity->PasswordLength = ad->password_len;
946 memcpy(nt_auth_identity->Domain, ad->domain, sizeof(WCHAR)*ad->domain_len);
947 nt_auth_identity->DomainLength = ad->domain_len;
948 LeaveCriticalSection(&authcache_cs);
949 return TRUE;
952 LeaveCriticalSection(&authcache_cs);
954 return FALSE;
957 static void cache_authorization(LPWSTR host, LPWSTR scheme,
958 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
960 authorizationData *ad;
961 BOOL found = FALSE;
963 TRACE("Caching authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
965 EnterCriticalSection(&authcache_cs);
966 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry)
967 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
968 found = TRUE;
969 break;
972 if(found) {
973 heap_free(ad->user);
974 heap_free(ad->password);
975 heap_free(ad->domain);
976 } else {
977 ad = heap_alloc(sizeof(authorizationData));
978 if(!ad) {
979 LeaveCriticalSection(&authcache_cs);
980 return;
983 ad->host = heap_strdupW(host);
984 ad->scheme = heap_strdupW(scheme);
985 list_add_head(&authorizationCache, &ad->entry);
988 ad->user = heap_strndupW(nt_auth_identity->User, nt_auth_identity->UserLength);
989 ad->password = heap_strndupW(nt_auth_identity->Password, nt_auth_identity->PasswordLength);
990 ad->domain = heap_strndupW(nt_auth_identity->Domain, nt_auth_identity->DomainLength);
991 ad->user_len = nt_auth_identity->UserLength;
992 ad->password_len = nt_auth_identity->PasswordLength;
993 ad->domain_len = nt_auth_identity->DomainLength;
995 if(!ad->host || !ad->scheme || !ad->user || !ad->password
996 || (nt_auth_identity->Domain && !ad->domain)) {
997 heap_free(ad->host);
998 heap_free(ad->scheme);
999 heap_free(ad->user);
1000 heap_free(ad->password);
1001 heap_free(ad->domain);
1002 list_remove(&ad->entry);
1003 heap_free(ad);
1006 LeaveCriticalSection(&authcache_cs);
1009 static BOOL HTTP_DoAuthorization( http_request_t *request, LPCWSTR pszAuthValue,
1010 struct HttpAuthInfo **ppAuthInfo,
1011 LPWSTR domain_and_username, LPWSTR password,
1012 LPWSTR host )
1014 SECURITY_STATUS sec_status;
1015 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
1016 BOOL first = FALSE;
1017 LPWSTR szRealm = NULL;
1019 TRACE("%s\n", debugstr_w(pszAuthValue));
1021 if (!pAuthInfo)
1023 TimeStamp exp;
1025 first = TRUE;
1026 pAuthInfo = heap_alloc(sizeof(*pAuthInfo));
1027 if (!pAuthInfo)
1028 return FALSE;
1030 SecInvalidateHandle(&pAuthInfo->cred);
1031 SecInvalidateHandle(&pAuthInfo->ctx);
1032 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
1033 pAuthInfo->attr = 0;
1034 pAuthInfo->auth_data = NULL;
1035 pAuthInfo->auth_data_len = 0;
1036 pAuthInfo->finished = FALSE;
1038 if (is_basic_auth_value(pszAuthValue,NULL))
1040 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
1041 pAuthInfo->scheme = heap_strdupW(szBasic);
1042 if (!pAuthInfo->scheme)
1044 heap_free(pAuthInfo);
1045 return FALSE;
1048 else
1050 PVOID pAuthData;
1051 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
1053 pAuthInfo->scheme = heap_strdupW(pszAuthValue);
1054 if (!pAuthInfo->scheme)
1056 heap_free(pAuthInfo);
1057 return FALSE;
1060 if (domain_and_username)
1062 WCHAR *user = strchrW(domain_and_username, '\\');
1063 WCHAR *domain = domain_and_username;
1065 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1067 pAuthData = &nt_auth_identity;
1069 if (user) user++;
1070 else
1072 user = domain_and_username;
1073 domain = NULL;
1076 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1077 nt_auth_identity.User = user;
1078 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
1079 nt_auth_identity.Domain = domain;
1080 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
1081 nt_auth_identity.Password = password;
1082 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
1084 cache_authorization(host, pAuthInfo->scheme, &nt_auth_identity);
1086 else if(retrieve_cached_authorization(host, pAuthInfo->scheme, &nt_auth_identity))
1087 pAuthData = &nt_auth_identity;
1088 else
1089 /* use default credentials */
1090 pAuthData = NULL;
1092 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
1093 SECPKG_CRED_OUTBOUND, NULL,
1094 pAuthData, NULL,
1095 NULL, &pAuthInfo->cred,
1096 &exp);
1098 if(pAuthData && !domain_and_username) {
1099 heap_free(nt_auth_identity.User);
1100 heap_free(nt_auth_identity.Domain);
1101 heap_free(nt_auth_identity.Password);
1104 if (sec_status == SEC_E_OK)
1106 PSecPkgInfoW sec_pkg_info;
1107 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
1108 if (sec_status == SEC_E_OK)
1110 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
1111 FreeContextBuffer(sec_pkg_info);
1114 if (sec_status != SEC_E_OK)
1116 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1117 debugstr_w(pAuthInfo->scheme), sec_status);
1118 heap_free(pAuthInfo->scheme);
1119 heap_free(pAuthInfo);
1120 return FALSE;
1123 *ppAuthInfo = pAuthInfo;
1125 else if (pAuthInfo->finished)
1126 return FALSE;
1128 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
1129 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
1131 ERR("authentication scheme changed from %s to %s\n",
1132 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
1133 return FALSE;
1136 if (is_basic_auth_value(pszAuthValue,&szRealm))
1138 int userlen;
1139 int passlen;
1140 char *auth_data = NULL;
1141 UINT auth_data_len = 0;
1143 TRACE("basic authentication realm %s\n",debugstr_w(szRealm));
1145 if (!domain_and_username)
1147 if (host && szRealm)
1148 auth_data_len = retrieve_cached_basic_authorization(host, szRealm,&auth_data);
1149 if (auth_data_len == 0)
1151 heap_free(szRealm);
1152 return FALSE;
1155 else
1157 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
1158 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
1160 /* length includes a nul terminator, which will be re-used for the ':' */
1161 auth_data = heap_alloc(userlen + 1 + passlen);
1162 if (!auth_data)
1164 heap_free(szRealm);
1165 return FALSE;
1168 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
1169 auth_data[userlen] = ':';
1170 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
1171 auth_data_len = userlen + 1 + passlen;
1172 if (host && szRealm)
1173 cache_basic_authorization(host, szRealm, auth_data, auth_data_len);
1176 pAuthInfo->auth_data = auth_data;
1177 pAuthInfo->auth_data_len = auth_data_len;
1178 pAuthInfo->finished = TRUE;
1179 heap_free(szRealm);
1180 return TRUE;
1182 else
1184 LPCWSTR pszAuthData;
1185 SecBufferDesc out_desc, in_desc;
1186 SecBuffer out, in;
1187 unsigned char *buffer;
1188 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
1189 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
1191 in.BufferType = SECBUFFER_TOKEN;
1192 in.cbBuffer = 0;
1193 in.pvBuffer = NULL;
1195 in_desc.ulVersion = 0;
1196 in_desc.cBuffers = 1;
1197 in_desc.pBuffers = &in;
1199 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
1200 if (*pszAuthData == ' ')
1202 pszAuthData++;
1203 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
1204 in.pvBuffer = heap_alloc(in.cbBuffer);
1205 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
1208 buffer = heap_alloc(pAuthInfo->max_token);
1210 out.BufferType = SECBUFFER_TOKEN;
1211 out.cbBuffer = pAuthInfo->max_token;
1212 out.pvBuffer = buffer;
1214 out_desc.ulVersion = 0;
1215 out_desc.cBuffers = 1;
1216 out_desc.pBuffers = &out;
1218 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
1219 first ? NULL : &pAuthInfo->ctx,
1220 first ? request->server->name : NULL,
1221 context_req, 0, SECURITY_NETWORK_DREP,
1222 in.pvBuffer ? &in_desc : NULL,
1223 0, &pAuthInfo->ctx, &out_desc,
1224 &pAuthInfo->attr, &pAuthInfo->exp);
1225 if (sec_status == SEC_E_OK)
1227 pAuthInfo->finished = TRUE;
1228 pAuthInfo->auth_data = out.pvBuffer;
1229 pAuthInfo->auth_data_len = out.cbBuffer;
1230 TRACE("sending last auth packet\n");
1232 else if (sec_status == SEC_I_CONTINUE_NEEDED)
1234 pAuthInfo->auth_data = out.pvBuffer;
1235 pAuthInfo->auth_data_len = out.cbBuffer;
1236 TRACE("sending next auth packet\n");
1238 else
1240 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
1241 heap_free(out.pvBuffer);
1242 destroy_authinfo(pAuthInfo);
1243 *ppAuthInfo = NULL;
1244 return FALSE;
1248 return TRUE;
1251 /***********************************************************************
1252 * HTTP_HttpAddRequestHeadersW (internal)
1254 static DWORD HTTP_HttpAddRequestHeadersW(http_request_t *request,
1255 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1257 LPWSTR lpszStart;
1258 LPWSTR lpszEnd;
1259 LPWSTR buffer;
1260 DWORD len, res = ERROR_HTTP_INVALID_HEADER;
1262 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
1264 if( dwHeaderLength == ~0U )
1265 len = strlenW(lpszHeader);
1266 else
1267 len = dwHeaderLength;
1268 buffer = heap_alloc(sizeof(WCHAR)*(len+1));
1269 lstrcpynW( buffer, lpszHeader, len + 1);
1271 lpszStart = buffer;
1275 LPWSTR * pFieldAndValue;
1277 lpszEnd = lpszStart;
1279 while (*lpszEnd != '\0')
1281 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1282 break;
1283 lpszEnd++;
1286 if (*lpszStart == '\0')
1287 break;
1289 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1291 *lpszEnd = '\0';
1292 lpszEnd++; /* Jump over newline */
1294 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
1295 if (*lpszStart == '\0')
1297 /* Skip 0-length headers */
1298 lpszStart = lpszEnd;
1299 res = ERROR_SUCCESS;
1300 continue;
1302 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
1303 if (pFieldAndValue)
1305 res = HTTP_ProcessHeader(request, pFieldAndValue[0],
1306 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
1307 HTTP_FreeTokens(pFieldAndValue);
1310 lpszStart = lpszEnd;
1311 } while (res == ERROR_SUCCESS);
1313 heap_free(buffer);
1314 return res;
1317 /***********************************************************************
1318 * HttpAddRequestHeadersW (WININET.@)
1320 * Adds one or more HTTP header to the request handler
1322 * NOTE
1323 * On Windows if dwHeaderLength includes the trailing '\0', then
1324 * HttpAddRequestHeadersW() adds it too. However this results in an
1325 * invalid HTTP header which is rejected by some servers so we probably
1326 * don't need to match Windows on that point.
1328 * RETURNS
1329 * TRUE on success
1330 * FALSE on failure
1333 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
1334 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1336 http_request_t *request;
1337 DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
1339 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1341 if (!lpszHeader)
1342 return TRUE;
1344 request = (http_request_t*) get_handle_object( hHttpRequest );
1345 if (request && request->hdr.htype == WH_HHTTPREQ)
1346 res = HTTP_HttpAddRequestHeadersW( request, lpszHeader, dwHeaderLength, dwModifier );
1347 if( request )
1348 WININET_Release( &request->hdr );
1350 if(res != ERROR_SUCCESS)
1351 SetLastError(res);
1352 return res == ERROR_SUCCESS;
1355 /***********************************************************************
1356 * HttpAddRequestHeadersA (WININET.@)
1358 * Adds one or more HTTP header to the request handler
1360 * RETURNS
1361 * TRUE on success
1362 * FALSE on failure
1365 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
1366 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1368 WCHAR *headers = NULL;
1369 BOOL r;
1371 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1373 if(lpszHeader)
1374 headers = heap_strndupAtoW(lpszHeader, dwHeaderLength, &dwHeaderLength);
1376 r = HttpAddRequestHeadersW(hHttpRequest, headers, dwHeaderLength, dwModifier);
1378 heap_free(headers);
1379 return r;
1382 static void free_accept_types( WCHAR **accept_types )
1384 WCHAR *ptr, **types = accept_types;
1386 if (!types) return;
1387 while ((ptr = *types))
1389 heap_free( ptr );
1390 types++;
1392 heap_free( accept_types );
1395 static WCHAR **convert_accept_types( const char **accept_types )
1397 unsigned int count;
1398 const char **types = accept_types;
1399 WCHAR **typesW;
1400 BOOL invalid_pointer = FALSE;
1402 if (!types) return NULL;
1403 count = 0;
1404 while (*types)
1406 __TRY
1408 /* find out how many there are */
1409 if (*types && **types)
1411 TRACE("accept type: %s\n", debugstr_a(*types));
1412 count++;
1415 __EXCEPT_PAGE_FAULT
1417 WARN("invalid accept type pointer\n");
1418 invalid_pointer = TRUE;
1420 __ENDTRY;
1421 types++;
1423 if (invalid_pointer) return NULL;
1424 if (!(typesW = heap_alloc( sizeof(WCHAR *) * (count + 1) ))) return NULL;
1425 count = 0;
1426 types = accept_types;
1427 while (*types)
1429 if (*types && **types) typesW[count++] = heap_strdupAtoW( *types );
1430 types++;
1432 typesW[count] = NULL;
1433 return typesW;
1436 /***********************************************************************
1437 * HttpOpenRequestA (WININET.@)
1439 * Open a HTTP request handle
1441 * RETURNS
1442 * HINTERNET a HTTP request handle on success
1443 * NULL on failure
1446 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
1447 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
1448 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
1449 DWORD dwFlags, DWORD_PTR dwContext)
1451 LPWSTR szVerb = NULL, szObjectName = NULL;
1452 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
1453 HINTERNET rc = NULL;
1455 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
1456 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
1457 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
1458 dwFlags, dwContext);
1460 if (lpszVerb)
1462 szVerb = heap_strdupAtoW(lpszVerb);
1463 if ( !szVerb )
1464 goto end;
1467 if (lpszObjectName)
1469 szObjectName = heap_strdupAtoW(lpszObjectName);
1470 if ( !szObjectName )
1471 goto end;
1474 if (lpszVersion)
1476 szVersion = heap_strdupAtoW(lpszVersion);
1477 if ( !szVersion )
1478 goto end;
1481 if (lpszReferrer)
1483 szReferrer = heap_strdupAtoW(lpszReferrer);
1484 if ( !szReferrer )
1485 goto end;
1488 szAcceptTypes = convert_accept_types( lpszAcceptTypes );
1489 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName, szVersion, szReferrer,
1490 (const WCHAR **)szAcceptTypes, dwFlags, dwContext);
1492 end:
1493 free_accept_types(szAcceptTypes);
1494 heap_free(szReferrer);
1495 heap_free(szVersion);
1496 heap_free(szObjectName);
1497 heap_free(szVerb);
1498 return rc;
1501 /***********************************************************************
1502 * HTTP_EncodeBase64
1504 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1506 UINT n = 0, x;
1507 static const CHAR HTTP_Base64Enc[] =
1508 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1510 while( len > 0 )
1512 /* first 6 bits, all from bin[0] */
1513 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1514 x = (bin[0] & 3) << 4;
1516 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1517 if( len == 1 )
1519 base64[n++] = HTTP_Base64Enc[x];
1520 base64[n++] = '=';
1521 base64[n++] = '=';
1522 break;
1524 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1525 x = ( bin[1] & 0x0f ) << 2;
1527 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1528 if( len == 2 )
1530 base64[n++] = HTTP_Base64Enc[x];
1531 base64[n++] = '=';
1532 break;
1534 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1536 /* last 6 bits, all from bin [2] */
1537 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1538 bin += 3;
1539 len -= 3;
1541 base64[n] = 0;
1542 return n;
1545 static const signed char HTTP_Base64Dec[] =
1547 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x00 */
1548 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x10 */
1549 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 0x20 */
1550 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, /* 0x30 */
1551 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 0x40 */
1552 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 0x50 */
1553 -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 0x60 */
1554 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 /* 0x70 */
1557 /***********************************************************************
1558 * HTTP_DecodeBase64
1560 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1562 unsigned int n = 0;
1564 while(*base64)
1566 signed char in[4];
1568 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1569 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1570 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1571 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1573 WARN("invalid base64: %s\n", debugstr_w(base64));
1574 return 0;
1576 if (bin)
1577 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1578 n++;
1580 if ((base64[2] == '=') && (base64[3] == '='))
1581 break;
1582 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1583 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1585 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1586 return 0;
1588 if (bin)
1589 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1590 n++;
1592 if (base64[3] == '=')
1593 break;
1594 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1595 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1597 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1598 return 0;
1600 if (bin)
1601 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1602 n++;
1604 base64 += 4;
1607 return n;
1610 static WCHAR *encode_auth_data( const WCHAR *scheme, const char *data, UINT data_len )
1612 WCHAR *ret;
1613 UINT len, scheme_len = strlenW( scheme );
1615 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1616 len = scheme_len + 1 + ((data_len + 2) * 4) / 3;
1617 if (!(ret = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return NULL;
1618 memcpy( ret, scheme, scheme_len * sizeof(WCHAR) );
1619 ret[scheme_len] = ' ';
1620 HTTP_EncodeBase64( data, data_len, ret + scheme_len + 1 );
1621 return ret;
1625 /***********************************************************************
1626 * HTTP_InsertAuthorization
1628 * Insert or delete the authorization field in the request header.
1630 static BOOL HTTP_InsertAuthorization( http_request_t *request, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1632 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1633 WCHAR *host, *authorization = NULL;
1635 if (pAuthInfo)
1637 if (pAuthInfo->auth_data_len)
1639 if (!(authorization = encode_auth_data(pAuthInfo->scheme, pAuthInfo->auth_data, pAuthInfo->auth_data_len)))
1640 return FALSE;
1642 /* clear the data as it isn't valid now that it has been sent to the
1643 * server, unless it's Basic authentication which doesn't do
1644 * connection tracking */
1645 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1647 heap_free(pAuthInfo->auth_data);
1648 pAuthInfo->auth_data = NULL;
1649 pAuthInfo->auth_data_len = 0;
1653 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1655 HTTP_ProcessHeader(request, header, authorization,
1656 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
1657 heap_free(authorization);
1659 else if (!strcmpW(header, szAuthorization) && (host = get_host_header(request)))
1661 UINT data_len;
1662 char *data;
1664 if ((data_len = retrieve_cached_basic_authorization(host, NULL, &data)))
1666 TRACE("Found cached basic authorization for %s\n", debugstr_w(host));
1668 if (!(authorization = encode_auth_data(wszBasic, data, data_len)))
1670 heap_free(data);
1671 heap_free(host);
1672 return FALSE;
1675 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1677 HTTP_ProcessHeader(request, header, authorization,
1678 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD);
1679 heap_free(data);
1680 heap_free(authorization);
1682 heap_free(host);
1684 return TRUE;
1687 static WCHAR *build_proxy_path_url(http_request_t *req)
1689 DWORD size, len;
1690 WCHAR *url;
1692 len = strlenW(req->server->scheme_host_port);
1693 size = len + strlenW(req->path) + 1;
1694 if(*req->path != '/')
1695 size++;
1696 url = heap_alloc(size * sizeof(WCHAR));
1697 if(!url)
1698 return NULL;
1700 memcpy(url, req->server->scheme_host_port, len*sizeof(WCHAR));
1701 if(*req->path != '/')
1702 url[len++] = '/';
1704 strcpyW(url+len, req->path);
1706 TRACE("url=%s\n", debugstr_w(url));
1707 return url;
1710 static BOOL HTTP_DomainMatches(LPCWSTR server, substr_t domain)
1712 static const WCHAR localW[] = { '<','l','o','c','a','l','>',0 };
1713 const WCHAR *dot, *ptr;
1714 int len;
1716 if(domain.len == sizeof(localW)/sizeof(WCHAR)-1 && !strncmpiW(domain.str, localW, domain.len) && !strchrW(server, '.' ))
1717 return TRUE;
1719 if(domain.len && *domain.str != '*')
1720 return domain.len == strlenW(server) && !strncmpiW(server, domain.str, domain.len);
1722 if(domain.len < 2 || domain.str[1] != '.')
1723 return FALSE;
1725 /* For a hostname to match a wildcard, the last domain must match
1726 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1727 * hostname is www.foo.a.b, it matches, but a.b does not.
1729 dot = strchrW(server, '.');
1730 if(!dot)
1731 return FALSE;
1733 len = strlenW(dot + 1);
1734 if(len <= domain.len - 2)
1735 return FALSE;
1737 /* The server's domain is longer than the wildcard, so it
1738 * could be a subdomain. Compare the last portion of the
1739 * server's domain.
1741 ptr = dot + 1 + len - domain.len + 2;
1742 if(!strncmpiW(ptr, domain.str+2, domain.len-2))
1743 /* This is only a match if the preceding character is
1744 * a '.', i.e. that it is a matching domain. E.g.
1745 * if domain is '*.b.c' and server is 'www.ab.c' they
1746 * do not match.
1748 return *(ptr - 1) == '.';
1750 return len == domain.len-2 && !strncmpiW(dot + 1, domain.str + 2, len);
1753 static BOOL HTTP_ShouldBypassProxy(appinfo_t *lpwai, LPCWSTR server)
1755 LPCWSTR ptr;
1756 BOOL ret = FALSE;
1758 if (!lpwai->proxyBypass) return FALSE;
1759 ptr = lpwai->proxyBypass;
1760 while(1) {
1761 LPCWSTR tmp = ptr;
1763 ptr = strchrW( ptr, ';' );
1764 if (!ptr)
1765 ptr = strchrW( tmp, ' ' );
1766 if (!ptr)
1767 ptr = tmp + strlenW(tmp);
1768 ret = HTTP_DomainMatches( server, substr(tmp, ptr-tmp) );
1769 if (ret || !*ptr)
1770 break;
1771 ptr++;
1773 return ret;
1776 /***********************************************************************
1777 * HTTP_DealWithProxy
1779 static BOOL HTTP_DealWithProxy(appinfo_t *hIC, http_session_t *session, http_request_t *request)
1781 static const WCHAR protoHttp[] = { 'h','t','t','p',0 };
1782 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1783 static WCHAR szNul[] = { 0 };
1784 URL_COMPONENTSW UrlComponents = { sizeof(UrlComponents) };
1785 server_t *new_server = NULL;
1786 WCHAR *proxy;
1788 proxy = INTERNET_FindProxyForProtocol(hIC->proxy, protoHttp);
1789 if(!proxy)
1790 return FALSE;
1791 if(CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1792 proxy, strlenW(szHttp), szHttp, strlenW(szHttp))) {
1793 WCHAR *proxy_url = heap_alloc(strlenW(proxy)*sizeof(WCHAR) + sizeof(szHttp));
1794 if(!proxy_url) {
1795 heap_free(proxy);
1796 return FALSE;
1798 strcpyW(proxy_url, szHttp);
1799 strcatW(proxy_url, proxy);
1800 heap_free(proxy);
1801 proxy = proxy_url;
1804 UrlComponents.dwHostNameLength = 1;
1805 if(InternetCrackUrlW(proxy, 0, 0, &UrlComponents) && UrlComponents.dwHostNameLength) {
1806 if( !request->path )
1807 request->path = szNul;
1809 new_server = get_server(substr(UrlComponents.lpszHostName, UrlComponents.dwHostNameLength),
1810 UrlComponents.nPort, UrlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
1812 heap_free(proxy);
1813 if(!new_server)
1814 return FALSE;
1816 request->proxy = new_server;
1818 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server->name), new_server->port);
1819 return TRUE;
1822 static DWORD HTTP_ResolveName(http_request_t *request)
1824 server_t *server = request->proxy ? request->proxy : request->server;
1825 int addr_len;
1827 if(server->addr_len)
1828 return ERROR_SUCCESS;
1830 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1831 INTERNET_STATUS_RESOLVING_NAME,
1832 server->name,
1833 (strlenW(server->name)+1) * sizeof(WCHAR));
1835 addr_len = sizeof(server->addr);
1836 if (!GetAddress(server->name, server->port, (SOCKADDR*)&server->addr, &addr_len, server->addr_str))
1837 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1839 server->addr_len = addr_len;
1840 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1841 INTERNET_STATUS_NAME_RESOLVED,
1842 server->addr_str, strlen(server->addr_str)+1);
1844 TRACE("resolved %s to %s\n", debugstr_w(server->name), server->addr_str);
1845 return ERROR_SUCCESS;
1848 static WCHAR *compose_request_url(http_request_t *req)
1850 static const WCHAR http[] = { 'h','t','t','p',':','/','/',0 };
1851 static const WCHAR https[] = { 'h','t','t','p','s',':','/','/',0 };
1852 const WCHAR *host, *scheme;
1853 WCHAR *buf, *ptr;
1854 size_t len;
1856 host = req->server->canon_host_port;
1858 if (req->server->is_https)
1859 scheme = https;
1860 else
1861 scheme = http;
1863 len = strlenW(scheme) + strlenW(host) + (req->path[0] != '/' ? 1 : 0) + strlenW(req->path);
1864 ptr = buf = heap_alloc((len+1) * sizeof(WCHAR));
1865 if(buf) {
1866 strcpyW(ptr, scheme);
1867 ptr += strlenW(ptr);
1869 strcpyW(ptr, host);
1870 ptr += strlenW(ptr);
1872 if(req->path[0] != '/')
1873 *ptr++ = '/';
1875 strcpyW(ptr, req->path);
1876 ptr += strlenW(ptr);
1877 *ptr = 0;
1880 return buf;
1884 /***********************************************************************
1885 * HTTPREQ_Destroy (internal)
1887 * Deallocate request handle
1890 static void HTTPREQ_Destroy(object_header_t *hdr)
1892 http_request_t *request = (http_request_t*) hdr;
1893 DWORD i;
1895 TRACE("\n");
1897 if(request->hCacheFile)
1898 CloseHandle(request->hCacheFile);
1899 if(request->req_file)
1900 req_file_release(request->req_file);
1902 request->headers_section.DebugInfo->Spare[0] = 0;
1903 DeleteCriticalSection( &request->headers_section );
1904 request->read_section.DebugInfo->Spare[0] = 0;
1905 DeleteCriticalSection( &request->read_section );
1906 WININET_Release(&request->session->hdr);
1908 destroy_authinfo(request->authInfo);
1909 destroy_authinfo(request->proxyAuthInfo);
1911 if(request->server)
1912 server_release(request->server);
1913 if(request->proxy)
1914 server_release(request->proxy);
1916 heap_free(request->path);
1917 heap_free(request->verb);
1918 heap_free(request->version);
1919 heap_free(request->statusText);
1921 for (i = 0; i < request->nCustHeaders; i++)
1923 heap_free(request->custHeaders[i].lpszField);
1924 heap_free(request->custHeaders[i].lpszValue);
1926 destroy_data_stream(request->data_stream);
1927 heap_free(request->custHeaders);
1930 static void http_release_netconn(http_request_t *req, BOOL reuse)
1932 TRACE("%p %p %x\n",req, req->netconn, reuse);
1934 if(!is_valid_netconn(req->netconn))
1935 return;
1937 if(reuse && req->netconn->keep_alive) {
1938 BOOL run_collector;
1940 EnterCriticalSection(&connection_pool_cs);
1942 list_add_head(&req->netconn->server->conn_pool, &req->netconn->pool_entry);
1943 req->netconn->keep_until = GetTickCount64() + COLLECT_TIME;
1944 req->netconn = NULL;
1946 run_collector = !collector_running;
1947 collector_running = TRUE;
1949 LeaveCriticalSection(&connection_pool_cs);
1951 if(run_collector) {
1952 HANDLE thread = NULL;
1953 HMODULE module;
1955 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR*)WININET_hModule, &module);
1956 if(module)
1957 thread = CreateThread(NULL, 0, collect_connections_proc, NULL, 0, NULL);
1958 if(!thread) {
1959 EnterCriticalSection(&connection_pool_cs);
1960 collector_running = FALSE;
1961 LeaveCriticalSection(&connection_pool_cs);
1963 if(module)
1964 FreeLibrary(module);
1966 else
1967 CloseHandle(thread);
1969 return;
1972 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1973 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1975 close_netconn(req->netconn);
1977 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1978 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1981 static BOOL HTTP_KeepAlive(http_request_t *request)
1983 WCHAR szVersion[10];
1984 WCHAR szConnectionResponse[20];
1985 DWORD dwBufferSize = sizeof(szVersion);
1986 BOOL keepalive = FALSE;
1988 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
1989 * the connection is keep-alive by default */
1990 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_VERSION, szVersion, &dwBufferSize, NULL) == ERROR_SUCCESS
1991 && !strcmpiW(szVersion, g_szHttp1_1))
1993 keepalive = TRUE;
1996 dwBufferSize = sizeof(szConnectionResponse);
1997 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS
1998 || HTTP_HttpQueryInfoW(request, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS)
2000 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
2003 return keepalive;
2006 static void HTTPREQ_CloseConnection(object_header_t *hdr)
2008 http_request_t *req = (http_request_t*)hdr;
2010 http_release_netconn(req, drain_content(req, FALSE));
2013 static DWORD str_to_buffer(const WCHAR *str, void *buffer, DWORD *size, BOOL unicode)
2015 int len;
2016 if (unicode)
2018 WCHAR *buf = buffer;
2020 if (str) len = strlenW(str);
2021 else len = 0;
2022 if (*size < (len + 1) * sizeof(WCHAR))
2024 *size = (len + 1) * sizeof(WCHAR);
2025 return ERROR_INSUFFICIENT_BUFFER;
2027 if (str) strcpyW(buf, str);
2028 else buf[0] = 0;
2030 *size = len;
2031 return ERROR_SUCCESS;
2033 else
2035 char *buf = buffer;
2037 if (str) len = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
2038 else len = 1;
2039 if (*size < len)
2041 *size = len;
2042 return ERROR_INSUFFICIENT_BUFFER;
2044 if (str) WideCharToMultiByte(CP_ACP, 0, str, -1, buf, *size, NULL, NULL);
2045 else buf[0] = 0;
2047 *size = len - 1;
2048 return ERROR_SUCCESS;
2052 static DWORD HTTPREQ_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2054 http_request_t *req = (http_request_t*)hdr;
2056 switch(option) {
2057 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO:
2059 INTERNET_DIAGNOSTIC_SOCKET_INFO *info = buffer;
2061 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2063 if (*size < sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO))
2064 return ERROR_INSUFFICIENT_BUFFER;
2065 *size = sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO);
2066 /* FIXME: can't get a SOCKET from our connection since we don't use
2067 * winsock
2069 info->Socket = 0;
2070 /* FIXME: get source port from req->netConnection */
2071 info->SourcePort = 0;
2072 info->DestPort = req->server->port;
2073 info->Flags = 0;
2074 if (HTTP_KeepAlive(req))
2075 info->Flags |= IDSI_FLAG_KEEP_ALIVE;
2076 if (req->proxy)
2077 info->Flags |= IDSI_FLAG_PROXY;
2078 if (is_valid_netconn(req->netconn) && req->netconn->secure)
2079 info->Flags |= IDSI_FLAG_SECURE;
2081 return ERROR_SUCCESS;
2084 case 98:
2085 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2086 /* fall through */
2087 case INTERNET_OPTION_SECURITY_FLAGS:
2089 DWORD flags;
2091 if (*size < sizeof(ULONG))
2092 return ERROR_INSUFFICIENT_BUFFER;
2094 *size = sizeof(DWORD);
2095 flags = is_valid_netconn(req->netconn) ? req->netconn->security_flags : req->security_flags | req->server->security_flags;
2096 *(DWORD *)buffer = flags;
2098 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags);
2099 return ERROR_SUCCESS;
2102 case INTERNET_OPTION_HANDLE_TYPE:
2103 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2105 if (*size < sizeof(ULONG))
2106 return ERROR_INSUFFICIENT_BUFFER;
2108 *size = sizeof(DWORD);
2109 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
2110 return ERROR_SUCCESS;
2112 case INTERNET_OPTION_URL: {
2113 WCHAR *url;
2114 DWORD res;
2116 TRACE("INTERNET_OPTION_URL\n");
2118 url = compose_request_url(req);
2119 if(!url)
2120 return ERROR_OUTOFMEMORY;
2122 res = str_to_buffer(url, buffer, size, unicode);
2123 heap_free(url);
2124 return res;
2126 case INTERNET_OPTION_USER_AGENT:
2127 return str_to_buffer(req->session->appInfo->agent, buffer, size, unicode);
2128 case INTERNET_OPTION_USERNAME:
2129 return str_to_buffer(req->session->userName, buffer, size, unicode);
2130 case INTERNET_OPTION_PASSWORD:
2131 return str_to_buffer(req->session->password, buffer, size, unicode);
2132 case INTERNET_OPTION_PROXY_USERNAME:
2133 return str_to_buffer(req->session->appInfo->proxyUsername, buffer, size, unicode);
2134 case INTERNET_OPTION_PROXY_PASSWORD:
2135 return str_to_buffer(req->session->appInfo->proxyPassword, buffer, size, unicode);
2137 case INTERNET_OPTION_CACHE_TIMESTAMPS: {
2138 INTERNET_CACHE_ENTRY_INFOW *info;
2139 INTERNET_CACHE_TIMESTAMPS *ts = buffer;
2140 DWORD nbytes, error;
2141 BOOL ret;
2143 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2145 if(!req->req_file)
2146 return ERROR_FILE_NOT_FOUND;
2148 if (*size < sizeof(*ts))
2150 *size = sizeof(*ts);
2151 return ERROR_INSUFFICIENT_BUFFER;
2154 nbytes = 0;
2155 ret = GetUrlCacheEntryInfoW(req->req_file->url, NULL, &nbytes);
2156 error = GetLastError();
2157 if (!ret && error == ERROR_INSUFFICIENT_BUFFER)
2159 if (!(info = heap_alloc(nbytes)))
2160 return ERROR_OUTOFMEMORY;
2162 GetUrlCacheEntryInfoW(req->req_file->url, info, &nbytes);
2164 ts->ftExpires = info->ExpireTime;
2165 ts->ftLastModified = info->LastModifiedTime;
2167 heap_free(info);
2168 *size = sizeof(*ts);
2169 return ERROR_SUCCESS;
2171 return error;
2174 case INTERNET_OPTION_DATAFILE_NAME: {
2175 DWORD req_size;
2177 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2179 if(!req->req_file) {
2180 *size = 0;
2181 return ERROR_INTERNET_ITEM_NOT_FOUND;
2184 if(unicode) {
2185 req_size = (lstrlenW(req->req_file->file_name)+1) * sizeof(WCHAR);
2186 if(*size < req_size)
2187 return ERROR_INSUFFICIENT_BUFFER;
2189 *size = req_size;
2190 memcpy(buffer, req->req_file->file_name, *size);
2191 return ERROR_SUCCESS;
2192 }else {
2193 req_size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name, -1, NULL, 0, NULL, NULL);
2194 if (req_size > *size)
2195 return ERROR_INSUFFICIENT_BUFFER;
2197 *size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name,
2198 -1, buffer, *size, NULL, NULL);
2199 return ERROR_SUCCESS;
2203 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
2204 PCCERT_CONTEXT context;
2206 if(!req->netconn)
2207 return ERROR_INTERNET_INVALID_OPERATION;
2209 if(*size < sizeof(INTERNET_CERTIFICATE_INFOA)) {
2210 *size = sizeof(INTERNET_CERTIFICATE_INFOA);
2211 return ERROR_INSUFFICIENT_BUFFER;
2214 context = (PCCERT_CONTEXT)NETCON_GetCert(req->netconn);
2215 if(context) {
2216 INTERNET_CERTIFICATE_INFOA *info = (INTERNET_CERTIFICATE_INFOA*)buffer;
2217 DWORD len;
2219 memset(info, 0, sizeof(*info));
2220 info->ftExpiry = context->pCertInfo->NotAfter;
2221 info->ftStart = context->pCertInfo->NotBefore;
2222 len = CertNameToStrA(context->dwCertEncodingType,
2223 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2224 info->lpszSubjectInfo = LocalAlloc(0, len);
2225 if(info->lpszSubjectInfo)
2226 CertNameToStrA(context->dwCertEncodingType,
2227 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2228 info->lpszSubjectInfo, len);
2229 len = CertNameToStrA(context->dwCertEncodingType,
2230 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2231 info->lpszIssuerInfo = LocalAlloc(0, len);
2232 if(info->lpszIssuerInfo)
2233 CertNameToStrA(context->dwCertEncodingType,
2234 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2235 info->lpszIssuerInfo, len);
2236 info->dwKeySize = NETCON_GetCipherStrength(req->netconn);
2237 CertFreeCertificateContext(context);
2238 return ERROR_SUCCESS;
2240 return ERROR_NOT_SUPPORTED;
2242 case INTERNET_OPTION_CONNECT_TIMEOUT:
2243 if (*size < sizeof(DWORD))
2244 return ERROR_INSUFFICIENT_BUFFER;
2246 *size = sizeof(DWORD);
2247 *(DWORD *)buffer = req->connect_timeout;
2248 return ERROR_SUCCESS;
2249 case INTERNET_OPTION_REQUEST_FLAGS: {
2250 DWORD flags = 0;
2252 if (*size < sizeof(DWORD))
2253 return ERROR_INSUFFICIENT_BUFFER;
2255 /* FIXME: Add support for:
2256 * INTERNET_REQFLAG_FROM_CACHE
2257 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2260 if(req->proxy)
2261 flags |= INTERNET_REQFLAG_VIA_PROXY;
2262 if(!req->status_code)
2263 flags |= INTERNET_REQFLAG_NO_HEADERS;
2265 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags);
2267 *size = sizeof(DWORD);
2268 *(DWORD*)buffer = flags;
2269 return ERROR_SUCCESS;
2273 return INET_QueryOption(hdr, option, buffer, size, unicode);
2276 static DWORD HTTPREQ_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
2278 http_request_t *req = (http_request_t*)hdr;
2280 switch(option) {
2281 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2282 TRACE("Undocumented option 99\n");
2284 if (!buffer || size != sizeof(DWORD))
2285 return ERROR_INVALID_PARAMETER;
2286 if(*(DWORD*)buffer & ~SECURITY_SET_MASK)
2287 return ERROR_INTERNET_OPTION_NOT_SETTABLE;
2289 /* fall through */
2290 case INTERNET_OPTION_SECURITY_FLAGS:
2292 DWORD flags;
2294 if (!buffer || size != sizeof(DWORD))
2295 return ERROR_INVALID_PARAMETER;
2296 flags = *(DWORD *)buffer;
2297 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags);
2298 flags &= SECURITY_SET_MASK;
2299 req->security_flags |= flags;
2300 if(is_valid_netconn(req->netconn))
2301 req->netconn->security_flags |= flags;
2302 return ERROR_SUCCESS;
2304 case INTERNET_OPTION_CONNECT_TIMEOUT:
2305 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2306 req->connect_timeout = *(DWORD *)buffer;
2307 return ERROR_SUCCESS;
2309 case INTERNET_OPTION_SEND_TIMEOUT:
2310 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2311 req->send_timeout = *(DWORD *)buffer;
2312 return ERROR_SUCCESS;
2314 case INTERNET_OPTION_RECEIVE_TIMEOUT:
2315 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2316 req->receive_timeout = *(DWORD *)buffer;
2317 return ERROR_SUCCESS;
2319 case INTERNET_OPTION_USERNAME:
2320 heap_free(req->session->userName);
2321 if (!(req->session->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2322 return ERROR_SUCCESS;
2324 case INTERNET_OPTION_PASSWORD:
2325 heap_free(req->session->password);
2326 if (!(req->session->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2327 return ERROR_SUCCESS;
2329 case INTERNET_OPTION_PROXY_USERNAME:
2330 heap_free(req->session->appInfo->proxyUsername);
2331 if (!(req->session->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2332 return ERROR_SUCCESS;
2334 case INTERNET_OPTION_PROXY_PASSWORD:
2335 heap_free(req->session->appInfo->proxyPassword);
2336 if (!(req->session->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2337 return ERROR_SUCCESS;
2339 case INTERNET_OPTION_HTTP_DECODING:
2340 if(size != sizeof(BOOL))
2341 return ERROR_INVALID_PARAMETER;
2342 req->decoding = *(BOOL*)buffer;
2343 return ERROR_SUCCESS;
2346 return INET_SetOption(hdr, option, buffer, size);
2349 static void commit_cache_entry(http_request_t *req)
2351 WCHAR *header;
2352 DWORD header_len;
2353 BOOL res;
2355 TRACE("%p\n", req);
2357 CloseHandle(req->hCacheFile);
2358 req->hCacheFile = NULL;
2360 header = build_response_header(req, TRUE);
2361 header_len = (header ? strlenW(header) : 0);
2362 res = CommitUrlCacheEntryW(req->req_file->url, req->req_file->file_name, req->expires,
2363 req->last_modified, NORMAL_CACHE_ENTRY,
2364 header, header_len, NULL, 0);
2365 if(res)
2366 req->req_file->is_committed = TRUE;
2367 else
2368 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2369 heap_free(header);
2372 static void create_cache_entry(http_request_t *req)
2374 static const WCHAR no_cacheW[] = {'n','o','-','c','a','c','h','e',0};
2375 static const WCHAR no_storeW[] = {'n','o','-','s','t','o','r','e',0};
2377 WCHAR file_name[MAX_PATH+1];
2378 WCHAR *url;
2379 BOOL b = TRUE;
2381 /* FIXME: We should free previous cache file earlier */
2382 if(req->req_file) {
2383 req_file_release(req->req_file);
2384 req->req_file = NULL;
2386 if(req->hCacheFile) {
2387 CloseHandle(req->hCacheFile);
2388 req->hCacheFile = NULL;
2391 if(req->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE)
2392 b = FALSE;
2394 if(b) {
2395 int header_idx;
2397 EnterCriticalSection( &req->headers_section );
2399 header_idx = HTTP_GetCustomHeaderIndex(req, szCache_Control, 0, FALSE);
2400 if(header_idx != -1) {
2401 WCHAR *ptr;
2403 for(ptr=req->custHeaders[header_idx].lpszValue; *ptr; ) {
2404 WCHAR *end;
2406 while(*ptr==' ' || *ptr=='\t')
2407 ptr++;
2409 end = strchrW(ptr, ',');
2410 if(!end)
2411 end = ptr + strlenW(ptr);
2413 if(!strncmpiW(ptr, no_cacheW, sizeof(no_cacheW)/sizeof(*no_cacheW)-1)
2414 || !strncmpiW(ptr, no_storeW, sizeof(no_storeW)/sizeof(*no_storeW)-1)) {
2415 b = FALSE;
2416 break;
2419 ptr = end;
2420 if(*ptr == ',')
2421 ptr++;
2425 LeaveCriticalSection( &req->headers_section );
2428 if(!b) {
2429 if(!(req->hdr.dwFlags & INTERNET_FLAG_NEED_FILE))
2430 return;
2432 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2435 url = compose_request_url(req);
2436 if(!url) {
2437 WARN("Could not get URL\n");
2438 return;
2441 b = CreateUrlCacheEntryW(url, req->contentLength == ~0u ? 0 : req->contentLength, NULL, file_name, 0);
2442 if(!b) {
2443 WARN("Could not create cache entry: %08x\n", GetLastError());
2444 return;
2447 create_req_file(file_name, &req->req_file);
2448 req->req_file->url = url;
2450 req->hCacheFile = CreateFileW(file_name, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
2451 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2452 if(req->hCacheFile == INVALID_HANDLE_VALUE) {
2453 WARN("Could not create file: %u\n", GetLastError());
2454 req->hCacheFile = NULL;
2455 return;
2458 if(req->read_size) {
2459 DWORD written;
2461 b = WriteFile(req->hCacheFile, req->read_buf+req->read_pos, req->read_size, &written, NULL);
2462 if(!b)
2463 FIXME("WriteFile failed: %u\n", GetLastError());
2465 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2466 commit_cache_entry(req);
2470 /* read some more data into the read buffer (the read section must be held) */
2471 static DWORD read_more_data( http_request_t *req, int maxlen )
2473 DWORD res;
2474 int len;
2476 if (req->read_pos)
2478 /* move existing data to the start of the buffer */
2479 if(req->read_size)
2480 memmove( req->read_buf, req->read_buf + req->read_pos, req->read_size );
2481 req->read_pos = 0;
2484 if (maxlen == -1) maxlen = sizeof(req->read_buf);
2486 res = NETCON_recv( req->netconn, req->read_buf + req->read_size,
2487 maxlen - req->read_size, TRUE, &len );
2488 if(res == ERROR_SUCCESS)
2489 req->read_size += len;
2491 return res;
2494 /* remove some amount of data from the read buffer (the read section must be held) */
2495 static void remove_data( http_request_t *req, int count )
2497 if (!(req->read_size -= count)) req->read_pos = 0;
2498 else req->read_pos += count;
2501 static DWORD read_line( http_request_t *req, LPSTR buffer, DWORD *len )
2503 int count, bytes_read, pos = 0;
2504 DWORD res;
2506 EnterCriticalSection( &req->read_section );
2507 for (;;)
2509 BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
2511 if (eol)
2513 count = eol - (req->read_buf + req->read_pos);
2514 bytes_read = count + 1;
2516 else count = bytes_read = req->read_size;
2518 count = min( count, *len - pos );
2519 memcpy( buffer + pos, req->read_buf + req->read_pos, count );
2520 pos += count;
2521 remove_data( req, bytes_read );
2522 if (eol) break;
2524 if ((res = read_more_data( req, -1 )))
2526 WARN( "read failed %u\n", res );
2527 LeaveCriticalSection( &req->read_section );
2528 return res;
2530 if (!req->read_size)
2532 *len = 0;
2533 TRACE( "returning empty string\n" );
2534 LeaveCriticalSection( &req->read_section );
2535 return ERROR_SUCCESS;
2538 LeaveCriticalSection( &req->read_section );
2540 if (pos < *len)
2542 if (pos && buffer[pos - 1] == '\r') pos--;
2543 *len = pos + 1;
2545 buffer[*len - 1] = 0;
2546 TRACE( "returning %s\n", debugstr_a(buffer));
2547 return ERROR_SUCCESS;
2550 /* check if we have reached the end of the data to read (the read section must be held) */
2551 static BOOL end_of_read_data( http_request_t *req )
2553 return !req->read_size && req->data_stream->vtbl->end_of_data(req->data_stream, req);
2556 static DWORD read_http_stream(http_request_t *req, BYTE *buf, DWORD size, DWORD *read, BOOL allow_blocking)
2558 DWORD res;
2560 res = req->data_stream->vtbl->read(req->data_stream, req, buf, size, read, allow_blocking);
2561 if(res != ERROR_SUCCESS)
2562 *read = 0;
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((res == ERROR_SUCCESS && !*read) || 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, BOOL allow_blocking, 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, allow_blocking);
2598 if(res != ERROR_SUCCESS)
2599 return res;
2601 req->read_size += read;
2603 TRACE("read %u bytes, read_size %u\n", read, req->read_size);
2604 if(read_bytes)
2605 *read_bytes = read;
2606 return res;
2609 static BOOL netconn_end_of_data(data_stream_t *stream, http_request_t *req)
2611 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2612 return netconn_stream->content_read == netconn_stream->content_length || !is_valid_netconn(req->netconn);
2615 static DWORD netconn_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2616 DWORD *read, BOOL allow_blocking)
2618 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2619 DWORD res = ERROR_SUCCESS;
2620 int ret = 0;
2622 size = min(size, netconn_stream->content_length-netconn_stream->content_read);
2624 if(size && is_valid_netconn(req->netconn)) {
2625 res = NETCON_recv(req->netconn, buf, size, allow_blocking, &ret);
2626 if(res == ERROR_SUCCESS) {
2627 if(!ret)
2628 netconn_stream->content_length = netconn_stream->content_read;
2629 netconn_stream->content_read += ret;
2633 TRACE("res %u read %u bytes\n", res, ret);
2634 *read = ret;
2635 return res;
2638 static BOOL netconn_drain_content(data_stream_t *stream, http_request_t *req)
2640 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2641 BYTE buf[1024];
2642 int len, res;
2643 size_t size;
2645 if(netconn_stream->content_length == ~0u)
2646 return FALSE;
2648 while(netconn_stream->content_read < netconn_stream->content_length) {
2649 size = min(sizeof(buf), netconn_stream->content_length-netconn_stream->content_read);
2650 res = NETCON_recv(req->netconn, buf, size, FALSE, &len);
2651 if(res || !len)
2652 return FALSE;
2654 netconn_stream->content_read += len;
2657 return TRUE;
2660 static void netconn_destroy(data_stream_t *stream)
2664 static const data_stream_vtbl_t netconn_stream_vtbl = {
2665 netconn_end_of_data,
2666 netconn_read,
2667 netconn_drain_content,
2668 netconn_destroy
2671 static char next_chunked_data_char(chunked_stream_t *stream)
2673 assert(stream->buf_size);
2675 stream->buf_size--;
2676 return stream->buf[stream->buf_pos++];
2679 static BOOL chunked_end_of_data(data_stream_t *stream, http_request_t *req)
2681 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2682 return chunked_stream->state == CHUNKED_STREAM_STATE_END_OF_STREAM;
2685 static DWORD chunked_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2686 DWORD *read, BOOL allow_blocking)
2688 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2689 DWORD ret_read = 0, res = ERROR_SUCCESS;
2690 BOOL continue_read = TRUE;
2691 int read_bytes;
2692 char ch;
2694 do {
2695 TRACE("state %d\n", chunked_stream->state);
2697 /* Ensure that we have data in the buffer for states that need it. */
2698 if(!chunked_stream->buf_size) {
2699 switch(chunked_stream->state) {
2700 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE:
2701 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE:
2702 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA:
2703 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END:
2704 chunked_stream->buf_pos = 0;
2705 res = NETCON_recv(req->netconn, chunked_stream->buf, sizeof(chunked_stream->buf), allow_blocking, &read_bytes);
2706 if(res == ERROR_SUCCESS && read_bytes) {
2707 chunked_stream->buf_size += read_bytes;
2708 }else if(res == WSAEWOULDBLOCK) {
2709 if(ret_read)
2710 res = ERROR_SUCCESS;
2711 continue_read = FALSE;
2712 continue;
2713 }else {
2714 chunked_stream->state = CHUNKED_STREAM_STATE_END_OF_STREAM;
2716 break;
2717 default:
2718 break;
2722 switch(chunked_stream->state) {
2723 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE:
2724 ch = next_chunked_data_char(chunked_stream);
2726 if(ch >= '0' && ch <= '9') {
2727 chunked_stream->chunk_size = chunked_stream->chunk_size * 16 + ch - '0';
2728 }else if(ch >= 'a' && ch <= 'f') {
2729 chunked_stream->chunk_size = chunked_stream->chunk_size * 16 + ch - 'a' + 10;
2730 }else if (ch >= 'A' && ch <= 'F') {
2731 chunked_stream->chunk_size = chunked_stream->chunk_size * 16 + ch - 'A' + 10;
2732 }else if (ch == ';' || ch == '\r' || ch == '\n') {
2733 TRACE("reading %u byte chunk\n", chunked_stream->chunk_size);
2734 chunked_stream->buf_size++;
2735 chunked_stream->buf_pos--;
2736 if(req->contentLength == ~0u) req->contentLength = chunked_stream->chunk_size;
2737 else req->contentLength += chunked_stream->chunk_size;
2738 chunked_stream->state = CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE;
2740 break;
2742 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE:
2743 ch = next_chunked_data_char(chunked_stream);
2744 if(ch == '\n')
2745 chunked_stream->state = chunked_stream->chunk_size
2746 ? CHUNKED_STREAM_STATE_READING_CHUNK
2747 : CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END;
2748 else if(ch != '\r')
2749 WARN("unexpected char '%c'\n", ch);
2750 break;
2752 case CHUNKED_STREAM_STATE_READING_CHUNK:
2753 assert(chunked_stream->chunk_size);
2754 if(!size) {
2755 continue_read = FALSE;
2756 break;
2758 read_bytes = min(size, chunked_stream->chunk_size);
2760 if(chunked_stream->buf_size) {
2761 if(read_bytes > chunked_stream->buf_size)
2762 read_bytes = chunked_stream->buf_size;
2764 memcpy(buf+ret_read, chunked_stream->buf+chunked_stream->buf_pos, read_bytes);
2765 chunked_stream->buf_pos += read_bytes;
2766 chunked_stream->buf_size -= read_bytes;
2767 }else {
2768 res = NETCON_recv(req->netconn, (char*)buf+ret_read, read_bytes,
2769 allow_blocking, (int*)&read_bytes);
2770 if(res != ERROR_SUCCESS) {
2771 continue_read = FALSE;
2772 break;
2775 if(!read_bytes) {
2776 chunked_stream->state = CHUNKED_STREAM_STATE_END_OF_STREAM;
2777 continue;
2781 chunked_stream->chunk_size -= read_bytes;
2782 size -= read_bytes;
2783 ret_read += read_bytes;
2784 if(!chunked_stream->chunk_size)
2785 chunked_stream->state = CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA;
2786 allow_blocking = FALSE;
2787 break;
2789 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA:
2790 ch = next_chunked_data_char(chunked_stream);
2791 if(ch == '\n')
2792 chunked_stream->state = CHUNKED_STREAM_STATE_READING_CHUNK_SIZE;
2793 else if(ch != '\r')
2794 WARN("unexpected char '%c'\n", ch);
2795 break;
2797 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END:
2798 ch = next_chunked_data_char(chunked_stream);
2799 if(ch == '\n')
2800 chunked_stream->state = CHUNKED_STREAM_STATE_END_OF_STREAM;
2801 else if(ch != '\r')
2802 WARN("unexpected char '%c'\n", ch);
2803 break;
2805 case CHUNKED_STREAM_STATE_END_OF_STREAM:
2806 continue_read = FALSE;
2807 break;
2809 } while(continue_read);
2811 if(ret_read)
2812 res = ERROR_SUCCESS;
2813 if(res != ERROR_SUCCESS)
2814 return res;
2816 TRACE("read %d bytes\n", ret_read);
2817 *read = ret_read;
2818 return ERROR_SUCCESS;
2821 static BOOL chunked_drain_content(data_stream_t *stream, http_request_t *req)
2823 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2824 return chunked_stream->state == CHUNKED_STREAM_STATE_END_OF_STREAM;
2827 static void chunked_destroy(data_stream_t *stream)
2829 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2830 heap_free(chunked_stream);
2833 static const data_stream_vtbl_t chunked_stream_vtbl = {
2834 chunked_end_of_data,
2835 chunked_read,
2836 chunked_drain_content,
2837 chunked_destroy
2840 /* set the request content length based on the headers */
2841 static DWORD set_content_length(http_request_t *request)
2843 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
2844 static const WCHAR headW[] = {'H','E','A','D',0};
2845 WCHAR encoding[20];
2846 DWORD size;
2848 if(request->status_code == HTTP_STATUS_NO_CONTENT || !strcmpW(request->verb, headW)) {
2849 request->contentLength = request->netconn_stream.content_length = 0;
2850 return ERROR_SUCCESS;
2853 size = sizeof(request->contentLength);
2854 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2855 &request->contentLength, &size, NULL) != ERROR_SUCCESS)
2856 request->contentLength = ~0u;
2857 request->netconn_stream.content_length = request->contentLength;
2858 request->netconn_stream.content_read = request->read_size;
2860 size = sizeof(encoding);
2861 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) == ERROR_SUCCESS &&
2862 !strcmpiW(encoding, szChunked))
2864 chunked_stream_t *chunked_stream;
2866 chunked_stream = heap_alloc(sizeof(*chunked_stream));
2867 if(!chunked_stream)
2868 return ERROR_OUTOFMEMORY;
2870 chunked_stream->data_stream.vtbl = &chunked_stream_vtbl;
2871 chunked_stream->buf_size = chunked_stream->buf_pos = 0;
2872 chunked_stream->chunk_size = 0;
2873 chunked_stream->state = CHUNKED_STREAM_STATE_READING_CHUNK_SIZE;
2875 if(request->read_size) {
2876 memcpy(chunked_stream->buf, request->read_buf+request->read_pos, request->read_size);
2877 chunked_stream->buf_size = request->read_size;
2878 request->read_size = request->read_pos = 0;
2881 request->data_stream = &chunked_stream->data_stream;
2882 request->contentLength = ~0u;
2885 if(request->decoding) {
2886 int encoding_idx;
2888 static const WCHAR deflateW[] = {'d','e','f','l','a','t','e',0};
2889 static const WCHAR gzipW[] = {'g','z','i','p',0};
2891 EnterCriticalSection( &request->headers_section );
2893 encoding_idx = HTTP_GetCustomHeaderIndex(request, szContent_Encoding, 0, FALSE);
2894 if(encoding_idx != -1) {
2895 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, gzipW)) {
2896 HTTP_DeleteCustomHeader(request, encoding_idx);
2897 LeaveCriticalSection( &request->headers_section );
2898 return init_gzip_stream(request, TRUE);
2900 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, deflateW)) {
2901 HTTP_DeleteCustomHeader(request, encoding_idx);
2902 LeaveCriticalSection( &request->headers_section );
2903 return init_gzip_stream(request, FALSE);
2907 LeaveCriticalSection( &request->headers_section );
2910 return ERROR_SUCCESS;
2913 static void send_request_complete(http_request_t *req, DWORD_PTR result, DWORD error)
2915 INTERNET_ASYNC_RESULT iar;
2917 iar.dwResult = result;
2918 iar.dwError = error;
2920 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2921 sizeof(INTERNET_ASYNC_RESULT));
2924 static void HTTP_ReceiveRequestData(http_request_t *req)
2926 DWORD res, read = 0;
2928 TRACE("%p\n", req);
2930 EnterCriticalSection( &req->read_section );
2932 res = refill_read_buffer(req, FALSE, &read);
2933 if(res == ERROR_SUCCESS)
2934 read += req->read_size;
2936 LeaveCriticalSection( &req->read_section );
2938 if(res != WSAEWOULDBLOCK && (res != ERROR_SUCCESS || !read)) {
2939 WARN("res %u read %u, closing connection\n", res, read);
2940 http_release_netconn(req, FALSE);
2943 if(res != ERROR_SUCCESS && res != WSAEWOULDBLOCK) {
2944 send_request_complete(req, 0, res);
2945 return;
2948 send_request_complete(req, req->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)req->hdr.hInternet : 1, 0);
2951 /* read data from the http connection (the read section must be held) */
2952 static DWORD HTTPREQ_Read(http_request_t *req, void *buffer, DWORD size, DWORD *read, BOOL allow_blocking)
2954 DWORD current_read = 0, ret_read = 0;
2955 DWORD res = ERROR_SUCCESS;
2957 EnterCriticalSection( &req->read_section );
2959 if(req->read_size) {
2960 ret_read = min(size, req->read_size);
2961 memcpy(buffer, req->read_buf+req->read_pos, ret_read);
2962 req->read_size -= ret_read;
2963 req->read_pos += ret_read;
2964 allow_blocking = FALSE;
2967 if(ret_read < size) {
2968 res = read_http_stream(req, (BYTE*)buffer+ret_read, size-ret_read, &current_read, allow_blocking);
2969 if(res == ERROR_SUCCESS)
2970 ret_read += current_read;
2971 else if(res == WSAEWOULDBLOCK && ret_read)
2972 res = ERROR_SUCCESS;
2975 LeaveCriticalSection( &req->read_section );
2977 *read = ret_read;
2978 TRACE( "retrieved %u bytes (%u)\n", ret_read, req->contentLength );
2980 if(res != WSAEWOULDBLOCK && (!ret_read || res != ERROR_SUCCESS))
2981 http_release_netconn(req, res == ERROR_SUCCESS);
2983 return res;
2986 static BOOL drain_content(http_request_t *req, BOOL blocking)
2988 BOOL ret;
2990 if(!is_valid_netconn(req->netconn) || req->contentLength == -1)
2991 return FALSE;
2993 if(!strcmpW(req->verb, szHEAD))
2994 return TRUE;
2996 if(!blocking)
2997 return req->data_stream->vtbl->drain_content(req->data_stream, req);
2999 EnterCriticalSection( &req->read_section );
3001 while(1) {
3002 DWORD bytes_read, res;
3003 BYTE buf[4096];
3005 res = HTTPREQ_Read(req, buf, sizeof(buf), &bytes_read, TRUE);
3006 if(res != ERROR_SUCCESS) {
3007 ret = FALSE;
3008 break;
3010 if(!bytes_read) {
3011 ret = TRUE;
3012 break;
3016 LeaveCriticalSection( &req->read_section );
3017 return ret;
3020 typedef struct {
3021 task_header_t hdr;
3022 void *buf;
3023 DWORD size;
3024 DWORD read_pos;
3025 DWORD *ret_read;
3026 } read_file_task_t;
3028 static void async_read_file_proc(task_header_t *hdr)
3030 read_file_task_t *task = (read_file_task_t*)hdr;
3031 http_request_t *req = (http_request_t*)task->hdr.hdr;
3032 DWORD res = ERROR_SUCCESS, read = task->read_pos, complete_arg = 0;
3034 TRACE("req %p buf %p size %u read_pos %u ret_read %p\n", req, task->buf, task->size, task->read_pos, task->ret_read);
3036 if(task->buf) {
3037 DWORD read_bytes;
3038 while (read < task->size) {
3039 res = HTTPREQ_Read(req, (char*)task->buf + read, task->size - read, &read_bytes, TRUE);
3040 if (res != ERROR_SUCCESS || !read_bytes)
3041 break;
3042 read += read_bytes;
3044 }else {
3045 EnterCriticalSection(&req->read_section);
3046 res = refill_read_buffer(req, TRUE, &read);
3047 LeaveCriticalSection(&req->read_section);
3049 if(task->ret_read)
3050 complete_arg = read; /* QueryDataAvailable reports read bytes in request complete notification */
3051 if(res != ERROR_SUCCESS || !read)
3052 http_release_netconn(req, drain_content(req, FALSE));
3055 TRACE("res %u read %u\n", res, read);
3057 if(task->ret_read)
3058 *task->ret_read = read;
3060 /* FIXME: We should report bytes transferred before decoding content. */
3061 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED, &read, sizeof(read));
3063 if(res != ERROR_SUCCESS)
3064 complete_arg = res;
3065 send_request_complete(req, res == ERROR_SUCCESS, complete_arg);
3068 static DWORD async_read(http_request_t *req, void *buf, DWORD size, DWORD read_pos, DWORD *ret_read)
3070 read_file_task_t *task;
3072 task = alloc_async_task(&req->hdr, async_read_file_proc, sizeof(*task));
3073 if(!task)
3074 return ERROR_OUTOFMEMORY;
3076 task->buf = buf;
3077 task->size = size;
3078 task->read_pos = read_pos;
3079 task->ret_read = ret_read;
3081 INTERNET_AsyncCall(&task->hdr);
3082 return ERROR_IO_PENDING;
3085 static DWORD HTTPREQ_ReadFile(object_header_t *hdr, void *buf, DWORD size, DWORD *ret_read,
3086 DWORD flags, DWORD_PTR context)
3088 http_request_t *req = (http_request_t*)hdr;
3089 DWORD res = ERROR_SUCCESS, read = 0, cread, error = ERROR_SUCCESS;
3090 BOOL allow_blocking, notify_received = FALSE;
3092 TRACE("(%p %p %u %x)\n", req, buf, size, flags);
3094 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3095 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3097 allow_blocking = !(req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC);
3099 if(allow_blocking || TryEnterCriticalSection(&req->read_section)) {
3100 if(allow_blocking)
3101 EnterCriticalSection(&req->read_section);
3102 if(hdr->dwError == ERROR_SUCCESS)
3103 hdr->dwError = INTERNET_HANDLE_IN_USE;
3104 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3105 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3107 if(req->read_size) {
3108 read = min(size, req->read_size);
3109 memcpy(buf, req->read_buf + req->read_pos, read);
3110 req->read_size -= read;
3111 req->read_pos += read;
3114 if(read < size && (!read || !(flags & IRF_NO_WAIT)) && !end_of_read_data(req)) {
3115 LeaveCriticalSection(&req->read_section);
3116 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3117 EnterCriticalSection( &req->read_section );
3118 notify_received = TRUE;
3120 while(read < size) {
3121 res = HTTPREQ_Read(req, (char*)buf+read, size-read, &cread, allow_blocking);
3122 read += cread;
3123 if (res != ERROR_SUCCESS || !cread)
3124 break;
3128 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3129 hdr->dwError = ERROR_SUCCESS;
3130 else
3131 error = hdr->dwError;
3133 LeaveCriticalSection( &req->read_section );
3134 }else {
3135 res = WSAEWOULDBLOCK;
3138 if(res == WSAEWOULDBLOCK) {
3139 if(!(flags & IRF_NO_WAIT))
3140 return async_read(req, buf, size, read, ret_read);
3141 if(!read)
3142 return async_read(req, NULL, 0, 0, NULL);
3143 res = ERROR_SUCCESS;
3146 *ret_read = read;
3147 if (res != ERROR_SUCCESS)
3148 return res;
3150 if(notify_received)
3151 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3152 &read, sizeof(read));
3153 return error;
3156 static DWORD HTTPREQ_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
3158 DWORD res;
3159 http_request_t *request = (http_request_t*)hdr;
3161 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3163 *written = 0;
3164 res = NETCON_send(request->netconn, buffer, size, 0, (LPINT)written);
3165 if (res == ERROR_SUCCESS)
3166 request->bytesWritten += *written;
3168 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
3169 return res;
3172 static DWORD HTTPREQ_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
3174 http_request_t *req = (http_request_t*)hdr;
3175 DWORD res = ERROR_SUCCESS, avail = 0, error = ERROR_SUCCESS;
3176 BOOL allow_blocking, notify_received = FALSE;
3178 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
3180 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3181 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3183 *available = 0;
3184 allow_blocking = !(req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC);
3186 if(allow_blocking || TryEnterCriticalSection(&req->read_section)) {
3187 if(allow_blocking)
3188 EnterCriticalSection(&req->read_section);
3189 if(hdr->dwError == ERROR_SUCCESS)
3190 hdr->dwError = INTERNET_HANDLE_IN_USE;
3191 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3192 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3194 avail = req->read_size;
3196 if(!avail && !end_of_read_data(req)) {
3197 LeaveCriticalSection(&req->read_section);
3198 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3199 EnterCriticalSection( &req->read_section );
3200 notify_received = TRUE;
3202 res = refill_read_buffer(req, allow_blocking, &avail);
3205 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3206 hdr->dwError = ERROR_SUCCESS;
3207 else
3208 error = hdr->dwError;
3210 LeaveCriticalSection( &req->read_section );
3211 }else {
3212 res = WSAEWOULDBLOCK;
3215 if(res == WSAEWOULDBLOCK)
3216 return async_read(req, NULL, 0, 0, available);
3218 if (res != ERROR_SUCCESS)
3219 return res;
3221 *available = avail;
3222 if(notify_received)
3223 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3224 &avail, sizeof(avail));
3225 return error;
3228 static DWORD HTTPREQ_LockRequestFile(object_header_t *hdr, req_file_t **ret)
3230 http_request_t *req = (http_request_t*)hdr;
3232 TRACE("(%p)\n", req);
3234 if(!req->req_file) {
3235 WARN("No cache file name available\n");
3236 return ERROR_FILE_NOT_FOUND;
3239 *ret = req_file_addref(req->req_file);
3240 return ERROR_SUCCESS;
3243 static const object_vtbl_t HTTPREQVtbl = {
3244 HTTPREQ_Destroy,
3245 HTTPREQ_CloseConnection,
3246 HTTPREQ_QueryOption,
3247 HTTPREQ_SetOption,
3248 HTTPREQ_ReadFile,
3249 HTTPREQ_WriteFile,
3250 HTTPREQ_QueryDataAvailable,
3251 NULL,
3252 HTTPREQ_LockRequestFile
3255 /***********************************************************************
3256 * HTTP_HttpOpenRequestW (internal)
3258 * Open a HTTP request handle
3260 * RETURNS
3261 * HINTERNET a HTTP request handle on success
3262 * NULL on failure
3265 static DWORD HTTP_HttpOpenRequestW(http_session_t *session,
3266 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3267 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3268 DWORD dwFlags, DWORD_PTR dwContext, HINTERNET *ret)
3270 appinfo_t *hIC = session->appInfo;
3271 http_request_t *request;
3272 DWORD port, len;
3274 TRACE("-->\n");
3276 request = alloc_object(&session->hdr, &HTTPREQVtbl, sizeof(http_request_t));
3277 if(!request)
3278 return ERROR_OUTOFMEMORY;
3280 request->hdr.htype = WH_HHTTPREQ;
3281 request->hdr.dwFlags = dwFlags;
3282 request->hdr.dwContext = dwContext;
3283 request->contentLength = ~0u;
3285 request->netconn_stream.data_stream.vtbl = &netconn_stream_vtbl;
3286 request->data_stream = &request->netconn_stream.data_stream;
3287 request->connect_timeout = session->connect_timeout;
3288 request->send_timeout = session->send_timeout;
3289 request->receive_timeout = session->receive_timeout;
3291 InitializeCriticalSection( &request->headers_section );
3292 request->headers_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.headers_section");
3294 InitializeCriticalSection( &request->read_section );
3295 request->read_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.read_section");
3297 WININET_AddRef( &session->hdr );
3298 request->session = session;
3299 list_add_head( &session->hdr.children, &request->hdr.entry );
3301 port = session->hostPort;
3302 if (port == INTERNET_INVALID_PORT_NUMBER)
3303 port = (session->hdr.dwFlags & INTERNET_FLAG_SECURE) ?
3304 INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;
3306 request->server = get_server(substrz(session->hostName), port, (dwFlags & INTERNET_FLAG_SECURE) != 0, TRUE);
3307 if(!request->server) {
3308 WININET_Release(&request->hdr);
3309 return ERROR_OUTOFMEMORY;
3312 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_CN_INVALID)
3313 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
3314 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_DATE_INVALID)
3315 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
3317 if (lpszObjectName && *lpszObjectName) {
3318 HRESULT rc;
3319 WCHAR dummy;
3321 len = 1;
3322 rc = UrlCanonicalizeW(lpszObjectName, &dummy, &len, URL_ESCAPE_SPACES_ONLY);
3323 if (rc != E_POINTER)
3324 len = strlenW(lpszObjectName)+1;
3325 request->path = heap_alloc(len*sizeof(WCHAR));
3326 rc = UrlCanonicalizeW(lpszObjectName, request->path, &len,
3327 URL_ESCAPE_SPACES_ONLY);
3328 if (rc != S_OK)
3330 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
3331 strcpyW(request->path,lpszObjectName);
3333 }else {
3334 static const WCHAR slashW[] = {'/',0};
3336 request->path = heap_strdupW(slashW);
3339 if (lpszReferrer && *lpszReferrer)
3340 HTTP_ProcessHeader(request, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3342 if (lpszAcceptTypes)
3344 int i;
3345 for (i = 0; lpszAcceptTypes[i]; i++)
3347 if (!*lpszAcceptTypes[i]) continue;
3348 HTTP_ProcessHeader(request, HTTP_ACCEPT, lpszAcceptTypes[i],
3349 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
3350 HTTP_ADDHDR_FLAG_REQ |
3351 (i == 0 ? (HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD) : 0));
3355 request->verb = heap_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
3356 request->version = heap_strdupW(lpszVersion && *lpszVersion ? lpszVersion : g_szHttp1_1);
3358 if (hIC->proxy && hIC->proxy[0] && !HTTP_ShouldBypassProxy(hIC, session->hostName))
3359 HTTP_DealWithProxy( hIC, session, request );
3361 INTERNET_SendCallback(&session->hdr, dwContext,
3362 INTERNET_STATUS_HANDLE_CREATED, &request->hdr.hInternet,
3363 sizeof(HINTERNET));
3365 TRACE("<-- (%p)\n", request);
3367 *ret = request->hdr.hInternet;
3368 return ERROR_SUCCESS;
3371 /***********************************************************************
3372 * HttpOpenRequestW (WININET.@)
3374 * Open a HTTP request handle
3376 * RETURNS
3377 * HINTERNET a HTTP request handle on success
3378 * NULL on failure
3381 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
3382 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3383 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3384 DWORD dwFlags, DWORD_PTR dwContext)
3386 http_session_t *session;
3387 HINTERNET handle = NULL;
3388 DWORD res;
3390 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
3391 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
3392 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
3393 dwFlags, dwContext);
3394 if(lpszAcceptTypes!=NULL)
3396 int i;
3397 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
3398 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
3401 session = (http_session_t*) get_handle_object( hHttpSession );
3402 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
3404 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3405 goto lend;
3409 * My tests seem to show that the windows version does not
3410 * become asynchronous until after this point. And anyhow
3411 * if this call was asynchronous then how would you get the
3412 * necessary HINTERNET pointer returned by this function.
3415 res = HTTP_HttpOpenRequestW(session, lpszVerb, lpszObjectName,
3416 lpszVersion, lpszReferrer, lpszAcceptTypes,
3417 dwFlags, dwContext, &handle);
3418 lend:
3419 if( session )
3420 WININET_Release( &session->hdr );
3421 TRACE("returning %p\n", handle);
3422 if(res != ERROR_SUCCESS)
3423 SetLastError(res);
3424 return handle;
3427 static const LPCWSTR header_lookup[] = {
3428 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
3429 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3430 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3431 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
3432 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3433 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3434 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3435 szAllow, /* HTTP_QUERY_ALLOW = 7 */
3436 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
3437 szDate, /* HTTP_QUERY_DATE = 9 */
3438 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
3439 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3440 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
3441 szURI, /* HTTP_QUERY_URI = 13 */
3442 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
3443 NULL, /* HTTP_QUERY_COST = 15 */
3444 NULL, /* HTTP_QUERY_LINK = 16 */
3445 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
3446 NULL, /* HTTP_QUERY_VERSION = 18 */
3447 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
3448 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
3449 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
3450 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3451 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
3452 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
3453 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3454 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3455 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3456 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
3457 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3458 NULL, /* HTTP_QUERY_FORWARDED = 30 */
3459 NULL, /* HTTP_QUERY_FROM = 31 */
3460 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3461 szLocation, /* HTTP_QUERY_LOCATION = 33 */
3462 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
3463 szReferer, /* HTTP_QUERY_REFERER = 35 */
3464 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
3465 szServer, /* HTTP_QUERY_SERVER = 37 */
3466 NULL, /* HTTP_TITLE = 38 */
3467 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
3468 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3469 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3470 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3471 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
3472 szCookie, /* HTTP_QUERY_COOKIE = 44 */
3473 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3474 NULL, /* HTTP_QUERY_REFRESH = 46 */
3475 szContent_Disposition, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3476 szAge, /* HTTP_QUERY_AGE = 48 */
3477 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3478 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
3479 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3480 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3481 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3482 szETag, /* HTTP_QUERY_ETAG = 54 */
3483 hostW, /* HTTP_QUERY_HOST = 55 */
3484 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
3485 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3486 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
3487 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3488 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3489 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3490 szRange, /* HTTP_QUERY_RANGE = 62 */
3491 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3492 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
3493 szVary, /* HTTP_QUERY_VARY = 65 */
3494 szVia, /* HTTP_QUERY_VIA = 66 */
3495 szWarning, /* HTTP_QUERY_WARNING = 67 */
3496 szExpect, /* HTTP_QUERY_EXPECT = 68 */
3497 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3498 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3501 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3503 /***********************************************************************
3504 * HTTP_HttpQueryInfoW (internal)
3506 static DWORD HTTP_HttpQueryInfoW(http_request_t *request, DWORD dwInfoLevel,
3507 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3509 LPHTTPHEADERW lphttpHdr = NULL;
3510 BOOL request_only = !!(dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS);
3511 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
3512 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
3513 INT index = -1;
3515 EnterCriticalSection( &request->headers_section );
3517 /* Find requested header structure */
3518 switch (level)
3520 case HTTP_QUERY_CUSTOM:
3521 if (!lpBuffer)
3523 LeaveCriticalSection( &request->headers_section );
3524 return ERROR_INVALID_PARAMETER;
3526 index = HTTP_GetCustomHeaderIndex(request, lpBuffer, requested_index, request_only);
3527 break;
3528 case HTTP_QUERY_RAW_HEADERS_CRLF:
3530 LPWSTR headers;
3531 DWORD len = 0;
3532 DWORD res = ERROR_INVALID_PARAMETER;
3534 if (request_only)
3535 headers = build_request_header(request, request->verb, request->path, request->version, TRUE);
3536 else
3537 headers = build_response_header(request, TRUE);
3538 if (!headers)
3540 LeaveCriticalSection( &request->headers_section );
3541 return ERROR_OUTOFMEMORY;
3544 len = strlenW(headers) * sizeof(WCHAR);
3545 if (len + sizeof(WCHAR) > *lpdwBufferLength)
3547 len += sizeof(WCHAR);
3548 res = ERROR_INSUFFICIENT_BUFFER;
3550 else if (lpBuffer)
3552 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3553 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
3554 res = ERROR_SUCCESS;
3556 *lpdwBufferLength = len;
3558 heap_free(headers);
3559 LeaveCriticalSection( &request->headers_section );
3560 return res;
3562 case HTTP_QUERY_RAW_HEADERS:
3564 LPWSTR headers;
3565 DWORD len;
3567 if (request_only)
3568 headers = build_request_header(request, request->verb, request->path, request->version, FALSE);
3569 else
3570 headers = build_response_header(request, FALSE);
3572 if (!headers)
3574 LeaveCriticalSection( &request->headers_section );
3575 return ERROR_OUTOFMEMORY;
3578 len = strlenW(headers) * sizeof(WCHAR);
3579 if (len > *lpdwBufferLength)
3581 *lpdwBufferLength = len;
3582 heap_free(headers);
3583 LeaveCriticalSection( &request->headers_section );
3584 return ERROR_INSUFFICIENT_BUFFER;
3587 if (lpBuffer)
3589 DWORD i;
3591 TRACE("returning data: %s\n", debugstr_wn(headers, len / sizeof(WCHAR)));
3593 for (i = 0; i < len / sizeof(WCHAR); i++)
3595 if (headers[i] == '\n')
3596 headers[i] = 0;
3598 memcpy(lpBuffer, headers, len);
3600 *lpdwBufferLength = len - sizeof(WCHAR);
3602 heap_free(headers);
3603 LeaveCriticalSection( &request->headers_section );
3604 return ERROR_SUCCESS;
3606 case HTTP_QUERY_STATUS_TEXT:
3607 if (request->statusText)
3609 DWORD len = strlenW(request->statusText);
3610 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3612 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3613 LeaveCriticalSection( &request->headers_section );
3614 return ERROR_INSUFFICIENT_BUFFER;
3616 if (lpBuffer)
3618 memcpy(lpBuffer, request->statusText, (len + 1) * sizeof(WCHAR));
3619 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3621 *lpdwBufferLength = len * sizeof(WCHAR);
3622 LeaveCriticalSection( &request->headers_section );
3623 return ERROR_SUCCESS;
3625 break;
3626 case HTTP_QUERY_VERSION:
3627 if (request->version)
3629 DWORD len = strlenW(request->version);
3630 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3632 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3633 LeaveCriticalSection( &request->headers_section );
3634 return ERROR_INSUFFICIENT_BUFFER;
3636 if (lpBuffer)
3638 memcpy(lpBuffer, request->version, (len + 1) * sizeof(WCHAR));
3639 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3641 *lpdwBufferLength = len * sizeof(WCHAR);
3642 LeaveCriticalSection( &request->headers_section );
3643 return ERROR_SUCCESS;
3645 break;
3646 case HTTP_QUERY_CONTENT_ENCODING:
3647 index = HTTP_GetCustomHeaderIndex(request, header_lookup[request->read_gzip ? HTTP_QUERY_CONTENT_TYPE : level],
3648 requested_index,request_only);
3649 break;
3650 case HTTP_QUERY_STATUS_CODE: {
3651 DWORD res = ERROR_SUCCESS;
3653 if(request_only)
3655 LeaveCriticalSection( &request->headers_section );
3656 return ERROR_HTTP_INVALID_QUERY_REQUEST;
3659 if(requested_index)
3660 break;
3662 if(dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) {
3663 if(*lpdwBufferLength >= sizeof(DWORD))
3664 *(DWORD*)lpBuffer = request->status_code;
3665 else
3666 res = ERROR_INSUFFICIENT_BUFFER;
3667 *lpdwBufferLength = sizeof(DWORD);
3668 }else {
3669 WCHAR buf[12];
3670 DWORD size;
3671 static const WCHAR formatW[] = {'%','u',0};
3673 size = sprintfW(buf, formatW, request->status_code) * sizeof(WCHAR);
3675 if(size <= *lpdwBufferLength) {
3676 memcpy(lpBuffer, buf, size+sizeof(WCHAR));
3677 }else {
3678 size += sizeof(WCHAR);
3679 res = ERROR_INSUFFICIENT_BUFFER;
3682 *lpdwBufferLength = size;
3684 LeaveCriticalSection( &request->headers_section );
3685 return res;
3687 default:
3688 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
3690 if (level < LAST_TABLE_HEADER && header_lookup[level])
3691 index = HTTP_GetCustomHeaderIndex(request, header_lookup[level],
3692 requested_index,request_only);
3695 if (index >= 0)
3696 lphttpHdr = &request->custHeaders[index];
3698 /* Ensure header satisfies requested attributes */
3699 if (!lphttpHdr ||
3700 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
3701 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
3703 LeaveCriticalSection( &request->headers_section );
3704 return ERROR_HTTP_HEADER_NOT_FOUND;
3707 /* coalesce value to requested type */
3708 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
3710 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
3711 TRACE(" returning number: %d\n", *(int *)lpBuffer);
3713 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
3715 time_t tmpTime;
3716 struct tm tmpTM;
3717 SYSTEMTIME *STHook;
3719 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
3721 tmpTM = *gmtime(&tmpTime);
3722 STHook = (SYSTEMTIME *)lpBuffer;
3723 STHook->wDay = tmpTM.tm_mday;
3724 STHook->wHour = tmpTM.tm_hour;
3725 STHook->wMilliseconds = 0;
3726 STHook->wMinute = tmpTM.tm_min;
3727 STHook->wDayOfWeek = tmpTM.tm_wday;
3728 STHook->wMonth = tmpTM.tm_mon + 1;
3729 STHook->wSecond = tmpTM.tm_sec;
3730 STHook->wYear = 1900+tmpTM.tm_year;
3732 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3733 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
3734 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
3736 else if (lphttpHdr->lpszValue)
3738 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
3740 if (len > *lpdwBufferLength)
3742 *lpdwBufferLength = len;
3743 LeaveCriticalSection( &request->headers_section );
3744 return ERROR_INSUFFICIENT_BUFFER;
3746 if (lpBuffer)
3748 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
3749 TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
3751 *lpdwBufferLength = len - sizeof(WCHAR);
3753 if (lpdwIndex) (*lpdwIndex)++;
3755 LeaveCriticalSection( &request->headers_section );
3756 return ERROR_SUCCESS;
3759 /***********************************************************************
3760 * HttpQueryInfoW (WININET.@)
3762 * Queries for information about an HTTP request
3764 * RETURNS
3765 * TRUE on success
3766 * FALSE on failure
3769 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3770 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3772 http_request_t *request;
3773 DWORD res;
3775 if (TRACE_ON(wininet)) {
3776 #define FE(x) { x, #x }
3777 static const wininet_flag_info query_flags[] = {
3778 FE(HTTP_QUERY_MIME_VERSION),
3779 FE(HTTP_QUERY_CONTENT_TYPE),
3780 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
3781 FE(HTTP_QUERY_CONTENT_ID),
3782 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
3783 FE(HTTP_QUERY_CONTENT_LENGTH),
3784 FE(HTTP_QUERY_CONTENT_LANGUAGE),
3785 FE(HTTP_QUERY_ALLOW),
3786 FE(HTTP_QUERY_PUBLIC),
3787 FE(HTTP_QUERY_DATE),
3788 FE(HTTP_QUERY_EXPIRES),
3789 FE(HTTP_QUERY_LAST_MODIFIED),
3790 FE(HTTP_QUERY_MESSAGE_ID),
3791 FE(HTTP_QUERY_URI),
3792 FE(HTTP_QUERY_DERIVED_FROM),
3793 FE(HTTP_QUERY_COST),
3794 FE(HTTP_QUERY_LINK),
3795 FE(HTTP_QUERY_PRAGMA),
3796 FE(HTTP_QUERY_VERSION),
3797 FE(HTTP_QUERY_STATUS_CODE),
3798 FE(HTTP_QUERY_STATUS_TEXT),
3799 FE(HTTP_QUERY_RAW_HEADERS),
3800 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
3801 FE(HTTP_QUERY_CONNECTION),
3802 FE(HTTP_QUERY_ACCEPT),
3803 FE(HTTP_QUERY_ACCEPT_CHARSET),
3804 FE(HTTP_QUERY_ACCEPT_ENCODING),
3805 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
3806 FE(HTTP_QUERY_AUTHORIZATION),
3807 FE(HTTP_QUERY_CONTENT_ENCODING),
3808 FE(HTTP_QUERY_FORWARDED),
3809 FE(HTTP_QUERY_FROM),
3810 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
3811 FE(HTTP_QUERY_LOCATION),
3812 FE(HTTP_QUERY_ORIG_URI),
3813 FE(HTTP_QUERY_REFERER),
3814 FE(HTTP_QUERY_RETRY_AFTER),
3815 FE(HTTP_QUERY_SERVER),
3816 FE(HTTP_QUERY_TITLE),
3817 FE(HTTP_QUERY_USER_AGENT),
3818 FE(HTTP_QUERY_WWW_AUTHENTICATE),
3819 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
3820 FE(HTTP_QUERY_ACCEPT_RANGES),
3821 FE(HTTP_QUERY_SET_COOKIE),
3822 FE(HTTP_QUERY_COOKIE),
3823 FE(HTTP_QUERY_REQUEST_METHOD),
3824 FE(HTTP_QUERY_REFRESH),
3825 FE(HTTP_QUERY_CONTENT_DISPOSITION),
3826 FE(HTTP_QUERY_AGE),
3827 FE(HTTP_QUERY_CACHE_CONTROL),
3828 FE(HTTP_QUERY_CONTENT_BASE),
3829 FE(HTTP_QUERY_CONTENT_LOCATION),
3830 FE(HTTP_QUERY_CONTENT_MD5),
3831 FE(HTTP_QUERY_CONTENT_RANGE),
3832 FE(HTTP_QUERY_ETAG),
3833 FE(HTTP_QUERY_HOST),
3834 FE(HTTP_QUERY_IF_MATCH),
3835 FE(HTTP_QUERY_IF_NONE_MATCH),
3836 FE(HTTP_QUERY_IF_RANGE),
3837 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
3838 FE(HTTP_QUERY_MAX_FORWARDS),
3839 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
3840 FE(HTTP_QUERY_RANGE),
3841 FE(HTTP_QUERY_TRANSFER_ENCODING),
3842 FE(HTTP_QUERY_UPGRADE),
3843 FE(HTTP_QUERY_VARY),
3844 FE(HTTP_QUERY_VIA),
3845 FE(HTTP_QUERY_WARNING),
3846 FE(HTTP_QUERY_CUSTOM)
3848 static const wininet_flag_info modifier_flags[] = {
3849 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
3850 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
3851 FE(HTTP_QUERY_FLAG_NUMBER),
3852 FE(HTTP_QUERY_FLAG_COALESCE)
3854 #undef FE
3855 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
3856 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
3857 DWORD i;
3859 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, info);
3860 TRACE(" Attribute:");
3861 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
3862 if (query_flags[i].val == info) {
3863 TRACE(" %s", query_flags[i].name);
3864 break;
3867 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
3868 TRACE(" Unknown (%08x)", info);
3871 TRACE(" Modifier:");
3872 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
3873 if (modifier_flags[i].val & info_mod) {
3874 TRACE(" %s", modifier_flags[i].name);
3875 info_mod &= ~ modifier_flags[i].val;
3879 if (info_mod) {
3880 TRACE(" Unknown (%08x)", info_mod);
3882 TRACE("\n");
3885 request = (http_request_t*) get_handle_object( hHttpRequest );
3886 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
3888 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3889 goto lend;
3892 if (lpBuffer == NULL)
3893 *lpdwBufferLength = 0;
3894 res = HTTP_HttpQueryInfoW( request, dwInfoLevel,
3895 lpBuffer, lpdwBufferLength, lpdwIndex);
3897 lend:
3898 if( request )
3899 WININET_Release( &request->hdr );
3901 TRACE("%u <--\n", res);
3902 if(res != ERROR_SUCCESS)
3903 SetLastError(res);
3904 return res == ERROR_SUCCESS;
3907 /***********************************************************************
3908 * HttpQueryInfoA (WININET.@)
3910 * Queries for information about an HTTP request
3912 * RETURNS
3913 * TRUE on success
3914 * FALSE on failure
3917 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3918 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3920 BOOL result;
3921 DWORD len;
3922 WCHAR* bufferW;
3924 TRACE("%p %x\n", hHttpRequest, dwInfoLevel);
3926 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
3927 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
3929 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
3930 lpdwBufferLength, lpdwIndex );
3933 if (lpBuffer)
3935 DWORD alloclen;
3936 len = (*lpdwBufferLength)*sizeof(WCHAR);
3937 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3939 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
3940 if (alloclen < len)
3941 alloclen = len;
3943 else
3944 alloclen = len;
3945 bufferW = heap_alloc(alloclen);
3946 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3947 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3948 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
3949 } else
3951 bufferW = NULL;
3952 len = 0;
3955 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
3956 &len, lpdwIndex );
3957 if( result )
3959 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
3960 lpBuffer, *lpdwBufferLength, NULL, NULL );
3961 *lpdwBufferLength = len - 1;
3963 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
3965 else
3966 /* since the strings being returned from HttpQueryInfoW should be
3967 * only ASCII characters, it is reasonable to assume that all of
3968 * the Unicode characters can be reduced to a single byte */
3969 *lpdwBufferLength = len / sizeof(WCHAR);
3971 heap_free( bufferW );
3972 return result;
3975 static WCHAR *get_redirect_url(http_request_t *request)
3977 static WCHAR szHttp[] = {'h','t','t','p',0};
3978 static WCHAR szHttps[] = {'h','t','t','p','s',0};
3979 http_session_t *session = request->session;
3980 URL_COMPONENTSW urlComponents = { sizeof(urlComponents) };
3981 WCHAR *orig_url = NULL, *redirect_url = NULL, *combined_url = NULL;
3982 DWORD url_length = 0, res;
3983 BOOL b;
3985 url_length = 0;
3986 res = HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, redirect_url, &url_length, NULL);
3987 if(res == ERROR_INSUFFICIENT_BUFFER) {
3988 redirect_url = heap_alloc(url_length);
3989 res = HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, redirect_url, &url_length, NULL);
3991 if(res != ERROR_SUCCESS) {
3992 heap_free(redirect_url);
3993 return NULL;
3996 urlComponents.lpszScheme = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
3997 urlComponents.lpszHostName = request->server->name;
3998 urlComponents.nPort = request->server->port;
3999 urlComponents.lpszUserName = session->userName;
4000 urlComponents.lpszUrlPath = request->path;
4002 b = InternetCreateUrlW(&urlComponents, 0, NULL, &url_length);
4003 if(!b && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
4004 orig_url = heap_alloc(url_length);
4006 /* convert from bytes to characters */
4007 url_length = url_length / sizeof(WCHAR) - 1;
4008 b = InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length);
4011 if(b) {
4012 url_length = 0;
4013 b = InternetCombineUrlW(orig_url, redirect_url, NULL, &url_length, ICU_ENCODE_SPACES_ONLY);
4014 if(!b && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
4015 combined_url = heap_alloc(url_length * sizeof(WCHAR));
4016 b = InternetCombineUrlW(orig_url, redirect_url, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY);
4017 if(!b) {
4018 heap_free(combined_url);
4019 combined_url = NULL;
4024 heap_free(orig_url);
4025 heap_free(redirect_url);
4026 return combined_url;
4030 /***********************************************************************
4031 * HTTP_HandleRedirect (internal)
4033 static DWORD HTTP_HandleRedirect(http_request_t *request, LPCWSTR lpszUrl)
4035 http_session_t *session = request->session;
4036 WCHAR *path;
4038 if(lpszUrl[0]=='/')
4040 /* if it's an absolute path, keep the same session info */
4041 path = heap_strdupW(lpszUrl);
4043 else
4045 URL_COMPONENTSW urlComponents = { sizeof(urlComponents) };
4046 BOOL custom_port = FALSE;
4047 substr_t host;
4049 urlComponents.dwHostNameLength = 1;
4050 urlComponents.dwUserNameLength = 1;
4051 urlComponents.dwUrlPathLength = 1;
4052 if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
4053 return INTERNET_GetLastError();
4055 if(urlComponents.nScheme == INTERNET_SCHEME_HTTP) {
4056 if(request->hdr.dwFlags & INTERNET_FLAG_SECURE) {
4057 TRACE("redirect from secure page to non-secure page\n");
4058 /* FIXME: warn about from secure redirect to non-secure page */
4059 request->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
4062 custom_port = urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT;
4063 }else if(urlComponents.nScheme == INTERNET_SCHEME_HTTPS) {
4064 if(!(request->hdr.dwFlags & INTERNET_FLAG_SECURE)) {
4065 TRACE("redirect from non-secure page to secure page\n");
4066 /* FIXME: notify about redirect to secure page */
4067 request->hdr.dwFlags |= INTERNET_FLAG_SECURE;
4070 custom_port = urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT;
4073 heap_free(session->hostName);
4075 session->hostName = heap_strndupW(urlComponents.lpszHostName, urlComponents.dwHostNameLength);
4076 session->hostPort = urlComponents.nPort;
4078 heap_free(session->userName);
4079 session->userName = NULL;
4080 if (urlComponents.dwUserNameLength)
4081 session->userName = heap_strndupW(urlComponents.lpszUserName, urlComponents.dwUserNameLength);
4083 reset_data_stream(request);
4085 host = substr(urlComponents.lpszHostName, urlComponents.dwHostNameLength);
4087 if(host.len != strlenW(request->server->name) || strncmpiW(request->server->name, host.str, host.len)
4088 || request->server->port != urlComponents.nPort) {
4089 server_t *new_server;
4091 new_server = get_server(host, urlComponents.nPort, urlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
4092 server_release(request->server);
4093 request->server = new_server;
4096 if (custom_port)
4097 HTTP_ProcessHeader(request, hostW, request->server->host_port, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4098 else
4099 HTTP_ProcessHeader(request, hostW, request->server->name, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4101 path = heap_strndupW(urlComponents.lpszUrlPath, urlComponents.dwUrlPathLength);
4103 heap_free(request->path);
4104 request->path = NULL;
4105 if (*path)
4107 DWORD needed = 1;
4108 HRESULT rc;
4109 WCHAR dummy = 0;
4111 rc = UrlEscapeW(path, &dummy, &needed, URL_ESCAPE_SPACES_ONLY);
4112 if (rc != E_POINTER)
4113 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4114 request->path = heap_alloc(needed*sizeof(WCHAR));
4115 rc = UrlEscapeW(path, request->path, &needed,
4116 URL_ESCAPE_SPACES_ONLY);
4117 if (rc != S_OK)
4119 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4120 strcpyW(request->path, path);
4124 heap_free(path);
4126 /* Remove custom content-type/length headers on redirects. */
4127 remove_header(request, szContent_Type, TRUE);
4128 remove_header(request, szContent_Length, TRUE);
4130 return ERROR_SUCCESS;
4133 /***********************************************************************
4134 * HTTP_build_req (internal)
4136 * concatenate all the strings in the request together
4138 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
4140 LPCWSTR *t;
4141 LPWSTR str;
4143 for( t = list; *t ; t++ )
4144 len += strlenW( *t );
4145 len++;
4147 str = heap_alloc(len*sizeof(WCHAR));
4148 *str = 0;
4150 for( t = list; *t ; t++ )
4151 strcatW( str, *t );
4153 return str;
4156 static void HTTP_InsertCookies(http_request_t *request)
4158 WCHAR *cookies;
4159 DWORD res;
4161 res = get_cookie_header(request->server->name, request->path, &cookies);
4162 if(res != ERROR_SUCCESS || !cookies)
4163 return;
4165 HTTP_HttpAddRequestHeadersW(request, cookies, strlenW(cookies),
4166 HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
4167 heap_free(cookies);
4170 static WORD HTTP_ParseWkday(LPCWSTR day)
4172 static const WCHAR days[7][4] = {{ 's','u','n',0 },
4173 { 'm','o','n',0 },
4174 { 't','u','e',0 },
4175 { 'w','e','d',0 },
4176 { 't','h','u',0 },
4177 { 'f','r','i',0 },
4178 { 's','a','t',0 }};
4179 unsigned int i;
4180 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4181 if (!strcmpiW(day, days[i]))
4182 return i;
4184 /* Invalid */
4185 return 7;
4188 static WORD HTTP_ParseMonth(LPCWSTR month)
4190 static const WCHAR jan[] = { 'j','a','n',0 };
4191 static const WCHAR feb[] = { 'f','e','b',0 };
4192 static const WCHAR mar[] = { 'm','a','r',0 };
4193 static const WCHAR apr[] = { 'a','p','r',0 };
4194 static const WCHAR may[] = { 'm','a','y',0 };
4195 static const WCHAR jun[] = { 'j','u','n',0 };
4196 static const WCHAR jul[] = { 'j','u','l',0 };
4197 static const WCHAR aug[] = { 'a','u','g',0 };
4198 static const WCHAR sep[] = { 's','e','p',0 };
4199 static const WCHAR oct[] = { 'o','c','t',0 };
4200 static const WCHAR nov[] = { 'n','o','v',0 };
4201 static const WCHAR dec[] = { 'd','e','c',0 };
4203 if (!strcmpiW(month, jan)) return 1;
4204 if (!strcmpiW(month, feb)) return 2;
4205 if (!strcmpiW(month, mar)) return 3;
4206 if (!strcmpiW(month, apr)) return 4;
4207 if (!strcmpiW(month, may)) return 5;
4208 if (!strcmpiW(month, jun)) return 6;
4209 if (!strcmpiW(month, jul)) return 7;
4210 if (!strcmpiW(month, aug)) return 8;
4211 if (!strcmpiW(month, sep)) return 9;
4212 if (!strcmpiW(month, oct)) return 10;
4213 if (!strcmpiW(month, nov)) return 11;
4214 if (!strcmpiW(month, dec)) return 12;
4215 /* Invalid */
4216 return 0;
4219 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4220 * optionally preceded by whitespace.
4221 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4222 * st, and sets *str to the first character after the time format.
4224 static BOOL HTTP_ParseTime(SYSTEMTIME *st, LPCWSTR *str)
4226 LPCWSTR ptr = *str;
4227 WCHAR *nextPtr;
4228 unsigned long num;
4230 while (isspaceW(*ptr))
4231 ptr++;
4233 num = strtoulW(ptr, &nextPtr, 10);
4234 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4236 ERR("unexpected time format %s\n", debugstr_w(ptr));
4237 return FALSE;
4239 if (num > 23)
4241 ERR("unexpected hour in time format %s\n", debugstr_w(ptr));
4242 return FALSE;
4244 ptr = nextPtr + 1;
4245 st->wHour = (WORD)num;
4246 num = strtoulW(ptr, &nextPtr, 10);
4247 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4249 ERR("unexpected time format %s\n", debugstr_w(ptr));
4250 return FALSE;
4252 if (num > 59)
4254 ERR("unexpected minute in time format %s\n", debugstr_w(ptr));
4255 return FALSE;
4257 ptr = nextPtr + 1;
4258 st->wMinute = (WORD)num;
4259 num = strtoulW(ptr, &nextPtr, 10);
4260 if (!nextPtr || nextPtr <= ptr)
4262 ERR("unexpected time format %s\n", debugstr_w(ptr));
4263 return FALSE;
4265 if (num > 59)
4267 ERR("unexpected second in time format %s\n", debugstr_w(ptr));
4268 return FALSE;
4270 ptr = nextPtr + 1;
4271 *str = ptr;
4272 st->wSecond = (WORD)num;
4273 return TRUE;
4276 static BOOL HTTP_ParseDateAsAsctime(LPCWSTR value, FILETIME *ft)
4278 static const WCHAR gmt[]= { 'G','M','T',0 };
4279 WCHAR day[4], *dayPtr, month[4], *monthPtr, *nextPtr;
4280 LPCWSTR ptr;
4281 SYSTEMTIME st = { 0 };
4282 unsigned long num;
4284 for (ptr = value, dayPtr = day; *ptr && !isspaceW(*ptr) &&
4285 dayPtr - day < sizeof(day) / sizeof(day[0]) - 1; ptr++, dayPtr++)
4286 *dayPtr = *ptr;
4287 *dayPtr = 0;
4288 st.wDayOfWeek = HTTP_ParseWkday(day);
4289 if (st.wDayOfWeek >= 7)
4291 ERR("unexpected weekday %s\n", debugstr_w(day));
4292 return FALSE;
4295 while (isspaceW(*ptr))
4296 ptr++;
4298 for (monthPtr = month; !isspace(*ptr) &&
4299 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4300 monthPtr++, ptr++)
4301 *monthPtr = *ptr;
4302 *monthPtr = 0;
4303 st.wMonth = HTTP_ParseMonth(month);
4304 if (!st.wMonth || st.wMonth > 12)
4306 ERR("unexpected month %s\n", debugstr_w(month));
4307 return FALSE;
4310 while (isspaceW(*ptr))
4311 ptr++;
4313 num = strtoulW(ptr, &nextPtr, 10);
4314 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4316 ERR("unexpected day %s\n", debugstr_w(ptr));
4317 return FALSE;
4319 ptr = nextPtr;
4320 st.wDay = (WORD)num;
4322 while (isspaceW(*ptr))
4323 ptr++;
4325 if (!HTTP_ParseTime(&st, &ptr))
4326 return FALSE;
4328 while (isspaceW(*ptr))
4329 ptr++;
4331 num = strtoulW(ptr, &nextPtr, 10);
4332 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4334 ERR("unexpected year %s\n", debugstr_w(ptr));
4335 return FALSE;
4337 ptr = nextPtr;
4338 st.wYear = (WORD)num;
4340 while (isspaceW(*ptr))
4341 ptr++;
4343 /* asctime() doesn't report a timezone, but some web servers do, so accept
4344 * with or without GMT.
4346 if (*ptr && strcmpW(ptr, gmt))
4348 ERR("unexpected timezone %s\n", debugstr_w(ptr));
4349 return FALSE;
4351 return SystemTimeToFileTime(&st, ft);
4354 static BOOL HTTP_ParseRfc1123Date(LPCWSTR value, FILETIME *ft)
4356 static const WCHAR gmt[]= { 'G','M','T',0 };
4357 WCHAR *nextPtr, day[4], month[4], *monthPtr;
4358 LPCWSTR ptr;
4359 unsigned long num;
4360 SYSTEMTIME st = { 0 };
4362 ptr = strchrW(value, ',');
4363 if (!ptr)
4364 return FALSE;
4365 if (ptr - value != 3)
4367 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4368 return FALSE;
4370 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4371 day[3] = 0;
4372 st.wDayOfWeek = HTTP_ParseWkday(day);
4373 if (st.wDayOfWeek > 6)
4375 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4376 return FALSE;
4378 ptr++;
4380 while (isspaceW(*ptr))
4381 ptr++;
4383 num = strtoulW(ptr, &nextPtr, 10);
4384 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4386 WARN("unexpected day %s\n", debugstr_w(value));
4387 return FALSE;
4389 ptr = nextPtr;
4390 st.wDay = (WORD)num;
4392 while (isspaceW(*ptr))
4393 ptr++;
4395 for (monthPtr = month; !isspace(*ptr) &&
4396 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4397 monthPtr++, ptr++)
4398 *monthPtr = *ptr;
4399 *monthPtr = 0;
4400 st.wMonth = HTTP_ParseMonth(month);
4401 if (!st.wMonth || st.wMonth > 12)
4403 WARN("unexpected month %s\n", debugstr_w(month));
4404 return FALSE;
4407 while (isspaceW(*ptr))
4408 ptr++;
4410 num = strtoulW(ptr, &nextPtr, 10);
4411 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4413 ERR("unexpected year %s\n", debugstr_w(value));
4414 return FALSE;
4416 ptr = nextPtr;
4417 st.wYear = (WORD)num;
4419 if (!HTTP_ParseTime(&st, &ptr))
4420 return FALSE;
4422 while (isspaceW(*ptr))
4423 ptr++;
4425 if (strcmpW(ptr, gmt))
4427 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4428 return FALSE;
4430 return SystemTimeToFileTime(&st, ft);
4433 static WORD HTTP_ParseWeekday(LPCWSTR day)
4435 static const WCHAR days[7][10] = {{ 's','u','n','d','a','y',0 },
4436 { 'm','o','n','d','a','y',0 },
4437 { 't','u','e','s','d','a','y',0 },
4438 { 'w','e','d','n','e','s','d','a','y',0 },
4439 { 't','h','u','r','s','d','a','y',0 },
4440 { 'f','r','i','d','a','y',0 },
4441 { 's','a','t','u','r','d','a','y',0 }};
4442 unsigned int i;
4443 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4444 if (!strcmpiW(day, days[i]))
4445 return i;
4447 /* Invalid */
4448 return 7;
4451 static BOOL HTTP_ParseRfc850Date(LPCWSTR value, FILETIME *ft)
4453 static const WCHAR gmt[]= { 'G','M','T',0 };
4454 WCHAR *nextPtr, day[10], month[4], *monthPtr;
4455 LPCWSTR ptr;
4456 unsigned long num;
4457 SYSTEMTIME st = { 0 };
4459 ptr = strchrW(value, ',');
4460 if (!ptr)
4461 return FALSE;
4462 if (ptr - value == 3)
4464 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4465 day[3] = 0;
4466 st.wDayOfWeek = HTTP_ParseWkday(day);
4467 if (st.wDayOfWeek > 6)
4469 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4470 return FALSE;
4473 else if (ptr - value < sizeof(day) / sizeof(day[0]))
4475 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4476 day[ptr - value + 1] = 0;
4477 st.wDayOfWeek = HTTP_ParseWeekday(day);
4478 if (st.wDayOfWeek > 6)
4480 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4481 return FALSE;
4484 else
4486 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4487 return FALSE;
4489 ptr++;
4491 while (isspaceW(*ptr))
4492 ptr++;
4494 num = strtoulW(ptr, &nextPtr, 10);
4495 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4497 ERR("unexpected day %s\n", debugstr_w(value));
4498 return FALSE;
4500 ptr = nextPtr;
4501 st.wDay = (WORD)num;
4503 if (*ptr != '-')
4505 ERR("unexpected month format %s\n", debugstr_w(ptr));
4506 return FALSE;
4508 ptr++;
4510 for (monthPtr = month; *ptr != '-' &&
4511 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4512 monthPtr++, ptr++)
4513 *monthPtr = *ptr;
4514 *monthPtr = 0;
4515 st.wMonth = HTTP_ParseMonth(month);
4516 if (!st.wMonth || st.wMonth > 12)
4518 ERR("unexpected month %s\n", debugstr_w(month));
4519 return FALSE;
4522 if (*ptr != '-')
4524 ERR("unexpected year format %s\n", debugstr_w(ptr));
4525 return FALSE;
4527 ptr++;
4529 num = strtoulW(ptr, &nextPtr, 10);
4530 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4532 ERR("unexpected year %s\n", debugstr_w(value));
4533 return FALSE;
4535 ptr = nextPtr;
4536 st.wYear = (WORD)num;
4538 if (!HTTP_ParseTime(&st, &ptr))
4539 return FALSE;
4541 while (isspaceW(*ptr))
4542 ptr++;
4544 if (strcmpW(ptr, gmt))
4546 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4547 return FALSE;
4549 return SystemTimeToFileTime(&st, ft);
4552 static BOOL HTTP_ParseDate(LPCWSTR value, FILETIME *ft)
4554 static const WCHAR zero[] = { '0',0 };
4555 BOOL ret;
4557 if (!strcmpW(value, zero))
4559 ft->dwLowDateTime = ft->dwHighDateTime = 0;
4560 ret = TRUE;
4562 else if (strchrW(value, ','))
4564 ret = HTTP_ParseRfc1123Date(value, ft);
4565 if (!ret)
4567 ret = HTTP_ParseRfc850Date(value, ft);
4568 if (!ret)
4569 ERR("unexpected date format %s\n", debugstr_w(value));
4572 else
4574 ret = HTTP_ParseDateAsAsctime(value, ft);
4575 if (!ret)
4576 ERR("unexpected date format %s\n", debugstr_w(value));
4578 return ret;
4581 static void HTTP_ProcessExpires(http_request_t *request)
4583 BOOL expirationFound = FALSE;
4584 int headerIndex;
4586 EnterCriticalSection( &request->headers_section );
4588 /* Look for a Cache-Control header with a max-age directive, as it takes
4589 * precedence over the Expires header.
4591 headerIndex = HTTP_GetCustomHeaderIndex(request, szCache_Control, 0, FALSE);
4592 if (headerIndex != -1)
4594 LPHTTPHEADERW ccHeader = &request->custHeaders[headerIndex];
4595 LPWSTR ptr;
4597 for (ptr = ccHeader->lpszValue; ptr && *ptr; )
4599 LPWSTR comma = strchrW(ptr, ','), end, equal;
4601 if (comma)
4602 end = comma;
4603 else
4604 end = ptr + strlenW(ptr);
4605 for (equal = end - 1; equal > ptr && *equal != '='; equal--)
4607 if (*equal == '=')
4609 static const WCHAR max_age[] = {
4610 'm','a','x','-','a','g','e',0 };
4612 if (!strncmpiW(ptr, max_age, equal - ptr - 1))
4614 LPWSTR nextPtr;
4615 unsigned long age;
4617 age = strtoulW(equal + 1, &nextPtr, 10);
4618 if (nextPtr > equal + 1)
4620 LARGE_INTEGER ft;
4622 NtQuerySystemTime( &ft );
4623 /* Age is in seconds, FILETIME resolution is in
4624 * 100 nanosecond intervals.
4626 ft.QuadPart += age * (ULONGLONG)1000000;
4627 request->expires.dwLowDateTime = ft.u.LowPart;
4628 request->expires.dwHighDateTime = ft.u.HighPart;
4629 expirationFound = TRUE;
4633 if (comma)
4635 ptr = comma + 1;
4636 while (isspaceW(*ptr))
4637 ptr++;
4639 else
4640 ptr = NULL;
4643 if (!expirationFound)
4645 headerIndex = HTTP_GetCustomHeaderIndex(request, szExpires, 0, FALSE);
4646 if (headerIndex != -1)
4648 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4649 FILETIME ft;
4651 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4653 expirationFound = TRUE;
4654 request->expires = ft;
4658 if (!expirationFound)
4660 LARGE_INTEGER t;
4662 /* With no known age, default to 10 minutes until expiration. */
4663 NtQuerySystemTime( &t );
4664 t.QuadPart += 10 * 60 * (ULONGLONG)10000000;
4665 request->expires.dwLowDateTime = t.u.LowPart;
4666 request->expires.dwHighDateTime = t.u.HighPart;
4669 LeaveCriticalSection( &request->headers_section );
4672 static void HTTP_ProcessLastModified(http_request_t *request)
4674 int headerIndex;
4676 EnterCriticalSection( &request->headers_section );
4678 headerIndex = HTTP_GetCustomHeaderIndex(request, szLast_Modified, 0, FALSE);
4679 if (headerIndex != -1)
4681 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4682 FILETIME ft;
4684 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4685 request->last_modified = ft;
4688 LeaveCriticalSection( &request->headers_section );
4691 static void http_process_keep_alive(http_request_t *req)
4693 int index;
4695 EnterCriticalSection( &req->headers_section );
4697 if ((index = HTTP_GetCustomHeaderIndex(req, szConnection, 0, FALSE)) != -1)
4698 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4699 else if ((index = HTTP_GetCustomHeaderIndex(req, szProxy_Connection, 0, FALSE)) != -1)
4700 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4701 else
4702 req->netconn->keep_alive = !strcmpiW(req->version, g_szHttp1_1);
4704 LeaveCriticalSection( &req->headers_section );
4707 static DWORD open_http_connection(http_request_t *request, BOOL *reusing)
4709 const BOOL is_https = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) != 0;
4710 netconn_t *netconn = NULL;
4711 DWORD res;
4713 reset_data_stream(request);
4715 if (request->netconn)
4717 if (is_valid_netconn(request->netconn) && NETCON_is_alive(request->netconn))
4719 *reusing = TRUE;
4720 return ERROR_SUCCESS;
4722 else
4724 free_netconn(request->netconn);
4725 request->netconn = NULL;
4729 res = HTTP_ResolveName(request);
4730 if(res != ERROR_SUCCESS)
4731 return res;
4733 EnterCriticalSection(&connection_pool_cs);
4735 while(!list_empty(&request->server->conn_pool)) {
4736 netconn = LIST_ENTRY(list_head(&request->server->conn_pool), netconn_t, pool_entry);
4737 list_remove(&netconn->pool_entry);
4739 if(is_valid_netconn(netconn) && NETCON_is_alive(netconn))
4740 break;
4742 TRACE("connection %p closed during idle\n", netconn);
4743 free_netconn(netconn);
4744 netconn = NULL;
4747 LeaveCriticalSection(&connection_pool_cs);
4749 if(netconn) {
4750 TRACE("<-- reusing %p netconn\n", netconn);
4751 request->netconn = netconn;
4752 *reusing = TRUE;
4753 return ERROR_SUCCESS;
4756 TRACE("connecting to %s, proxy %s\n", debugstr_w(request->server->name),
4757 request->proxy ? debugstr_w(request->proxy->name) : "(null)");
4759 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4760 INTERNET_STATUS_CONNECTING_TO_SERVER,
4761 request->server->addr_str,
4762 strlen(request->server->addr_str)+1);
4764 res = create_netconn(is_https, request->proxy ? request->proxy : request->server, request->security_flags,
4765 (request->hdr.ErrorMask & INTERNET_ERROR_MASK_COMBINED_SEC_CERT) != 0,
4766 request->connect_timeout, &netconn);
4767 if(res != ERROR_SUCCESS) {
4768 ERR("create_netconn failed: %u\n", res);
4769 return res;
4772 request->netconn = netconn;
4774 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4775 INTERNET_STATUS_CONNECTED_TO_SERVER,
4776 request->server->addr_str, strlen(request->server->addr_str)+1);
4778 *reusing = FALSE;
4779 TRACE("Created connection to %s: %p\n", debugstr_w(request->server->name), netconn);
4780 return ERROR_SUCCESS;
4783 static char *build_ascii_request( const WCHAR *str, void *data, DWORD data_len, DWORD *out_len )
4785 int len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
4786 char *ret;
4788 if (!(ret = heap_alloc( len + data_len ))) return NULL;
4789 WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
4790 if (data_len) memcpy( ret + len - 1, data, data_len );
4791 *out_len = len + data_len - 1;
4792 ret[*out_len] = 0;
4793 return ret;
4796 static void set_content_length_header( http_request_t *request, DWORD len, DWORD flags )
4798 static const WCHAR fmtW[] =
4799 {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','u','\r','\n',0};
4800 WCHAR buf[sizeof(fmtW)/sizeof(fmtW[0]) + 10];
4802 sprintfW( buf, fmtW, len );
4803 HTTP_HttpAddRequestHeadersW( request, buf, ~0u, flags );
4806 /***********************************************************************
4807 * HTTP_HttpSendRequestW (internal)
4809 * Sends the specified request to the HTTP server
4811 * RETURNS
4812 * ERROR_SUCCESS on success
4813 * win32 error code on failure
4816 static DWORD HTTP_HttpSendRequestW(http_request_t *request, LPCWSTR lpszHeaders,
4817 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
4818 DWORD dwContentLength, BOOL bEndRequest)
4820 BOOL redirected = FALSE, secure_proxy_connect = FALSE, loop_next;
4821 LPWSTR requestString = NULL;
4822 INT responseLen, cnt;
4823 DWORD res;
4825 TRACE("--> %p\n", request);
4827 assert(request->hdr.htype == WH_HHTTPREQ);
4829 /* if the verb is NULL default to GET */
4830 if (!request->verb)
4831 request->verb = heap_strdupW(szGET);
4833 HTTP_ProcessHeader(request, hostW, request->server->canon_host_port,
4834 HTTP_ADDREQ_FLAG_ADD_IF_NEW | HTTP_ADDHDR_FLAG_REQ);
4836 if (dwContentLength || strcmpW(request->verb, szGET))
4838 set_content_length_header(request, dwContentLength, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4839 request->bytesToWrite = dwContentLength;
4841 if (request->session->appInfo->agent)
4843 WCHAR *agent_header;
4844 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4845 int len;
4847 len = strlenW(request->session->appInfo->agent) + strlenW(user_agent);
4848 agent_header = heap_alloc(len * sizeof(WCHAR));
4849 sprintfW(agent_header, user_agent, request->session->appInfo->agent);
4851 HTTP_HttpAddRequestHeadersW(request, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4852 heap_free(agent_header);
4854 if (request->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
4856 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4857 HTTP_HttpAddRequestHeadersW(request, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4859 if ((request->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && strcmpW(request->verb, szGET))
4861 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4862 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4863 HTTP_HttpAddRequestHeadersW(request, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4866 /* add the headers the caller supplied */
4867 if( lpszHeaders && dwHeaderLength )
4868 HTTP_HttpAddRequestHeadersW(request, lpszHeaders, dwHeaderLength, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
4872 DWORD len, data_len = dwOptionalLength;
4873 BOOL reusing_connection;
4874 char *ascii_req;
4876 loop_next = FALSE;
4878 if(redirected) {
4879 request->contentLength = ~0u;
4880 request->bytesToWrite = 0;
4883 if (TRACE_ON(wininet))
4885 HTTPHEADERW *host;
4887 EnterCriticalSection( &request->headers_section );
4888 host = HTTP_GetHeader( request, hostW );
4889 TRACE("Going to url %s %s\n", debugstr_w(host->lpszValue), debugstr_w(request->path));
4890 LeaveCriticalSection( &request->headers_section );
4893 HTTP_FixURL(request);
4894 if (request->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
4896 HTTP_ProcessHeader(request, szConnection, szKeepAlive,
4897 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD);
4899 HTTP_InsertAuthorization(request, request->authInfo, szAuthorization);
4900 HTTP_InsertAuthorization(request, request->proxyAuthInfo, szProxy_Authorization);
4902 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
4903 HTTP_InsertCookies(request);
4905 res = open_http_connection(request, &reusing_connection);
4906 if (res != ERROR_SUCCESS)
4907 break;
4909 if (!reusing_connection && (request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4911 if (request->proxy) secure_proxy_connect = TRUE;
4912 else
4914 res = NETCON_secure_connect(request->netconn, request->server);
4915 if (res != ERROR_SUCCESS)
4917 WARN("failed to upgrade to secure connection\n");
4918 http_release_netconn(request, FALSE);
4919 break;
4923 if (secure_proxy_connect)
4925 static const WCHAR connectW[] = {'C','O','N','N','E','C','T',0};
4926 const WCHAR *target = request->server->host_port;
4928 if (HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE) >= 0)
4929 set_content_length_header(request, 0, HTTP_ADDREQ_FLAG_REPLACE);
4931 requestString = build_request_header(request, connectW, target, g_szHttp1_1, TRUE);
4933 else if (request->proxy && !(request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4935 WCHAR *url = build_proxy_path_url(request);
4936 requestString = build_request_header(request, request->verb, url, request->version, TRUE);
4937 heap_free(url);
4939 else
4941 if (request->proxy && HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE) >= 0)
4942 set_content_length_header(request, dwContentLength, HTTP_ADDREQ_FLAG_REPLACE);
4944 requestString = build_request_header(request, request->verb, request->path, request->version, TRUE);
4947 TRACE("Request header -> %s\n", debugstr_w(requestString) );
4949 /* send the request as ASCII, tack on the optional data */
4950 if (!lpOptional || redirected || secure_proxy_connect)
4951 data_len = 0;
4953 ascii_req = build_ascii_request( requestString, lpOptional, data_len, &len );
4954 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
4956 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4957 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
4959 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
4960 res = NETCON_send(request->netconn, ascii_req, len, 0, &cnt);
4961 heap_free( ascii_req );
4962 if(res != ERROR_SUCCESS) {
4963 TRACE("send failed: %u\n", res);
4964 if(!reusing_connection)
4965 break;
4966 http_release_netconn(request, FALSE);
4967 loop_next = TRUE;
4968 continue;
4971 request->bytesWritten = data_len;
4973 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4974 INTERNET_STATUS_REQUEST_SENT,
4975 &len, sizeof(DWORD));
4977 if (bEndRequest)
4979 DWORD dwBufferSize;
4981 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4982 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
4984 if (HTTP_GetResponseHeaders(request, &responseLen))
4986 http_release_netconn(request, FALSE);
4987 res = ERROR_INTERNET_CONNECTION_ABORTED;
4988 goto lend;
4990 /* FIXME: We should know that connection is closed before sending
4991 * headers. Otherwise wrong callbacks are executed */
4992 if(!responseLen && reusing_connection) {
4993 TRACE("Connection closed by server, reconnecting\n");
4994 http_release_netconn(request, FALSE);
4995 loop_next = TRUE;
4996 continue;
4999 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5000 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
5001 sizeof(DWORD));
5003 http_process_keep_alive(request);
5004 HTTP_ProcessCookies(request);
5005 HTTP_ProcessExpires(request);
5006 HTTP_ProcessLastModified(request);
5008 res = set_content_length(request);
5009 if(res != ERROR_SUCCESS)
5010 goto lend;
5011 if(!request->contentLength)
5012 http_release_netconn(request, TRUE);
5014 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
5016 WCHAR *new_url;
5018 switch(request->status_code) {
5019 case HTTP_STATUS_REDIRECT:
5020 case HTTP_STATUS_MOVED:
5021 case HTTP_STATUS_REDIRECT_KEEP_VERB:
5022 case HTTP_STATUS_REDIRECT_METHOD:
5023 new_url = get_redirect_url(request);
5024 if(!new_url)
5025 break;
5027 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5028 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5030 heap_free(request->verb);
5031 request->verb = heap_strdupW(szGET);
5033 http_release_netconn(request, drain_content(request, FALSE));
5034 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5035 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5036 res = HTTP_HandleRedirect(request, new_url);
5037 heap_free(new_url);
5038 if (res == ERROR_SUCCESS) {
5039 heap_free(requestString);
5040 loop_next = TRUE;
5042 redirected = TRUE;
5045 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
5047 WCHAR szAuthValue[2048];
5048 dwBufferSize=2048;
5049 if (request->status_code == HTTP_STATUS_DENIED)
5051 WCHAR *host = heap_strdupW( request->server->canon_host_port );
5052 DWORD dwIndex = 0;
5053 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5055 if (HTTP_DoAuthorization(request, szAuthValue,
5056 &request->authInfo,
5057 request->session->userName,
5058 request->session->password, host))
5060 heap_free(requestString);
5061 if(!drain_content(request, TRUE)) {
5062 FIXME("Could not drain content\n");
5063 http_release_netconn(request, FALSE);
5065 loop_next = TRUE;
5066 break;
5069 heap_free( host );
5071 if(!loop_next) {
5072 TRACE("Cleaning wrong authorization data\n");
5073 destroy_authinfo(request->authInfo);
5074 request->authInfo = NULL;
5077 if (request->status_code == HTTP_STATUS_PROXY_AUTH_REQ)
5079 DWORD dwIndex = 0;
5080 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5082 if (HTTP_DoAuthorization(request, szAuthValue,
5083 &request->proxyAuthInfo,
5084 request->session->appInfo->proxyUsername,
5085 request->session->appInfo->proxyPassword,
5086 NULL))
5088 heap_free(requestString);
5089 if(!drain_content(request, TRUE)) {
5090 FIXME("Could not drain content\n");
5091 http_release_netconn(request, FALSE);
5093 loop_next = TRUE;
5094 break;
5098 if(!loop_next) {
5099 TRACE("Cleaning wrong proxy authorization data\n");
5100 destroy_authinfo(request->proxyAuthInfo);
5101 request->proxyAuthInfo = NULL;
5105 if (secure_proxy_connect && request->status_code == HTTP_STATUS_OK)
5107 res = NETCON_secure_connect(request->netconn, request->server);
5108 if (res != ERROR_SUCCESS)
5110 WARN("failed to upgrade to secure proxy connection\n");
5111 http_release_netconn( request, FALSE );
5112 break;
5114 remove_header(request, szProxy_Authorization, TRUE);
5115 destroy_authinfo(request->proxyAuthInfo);
5116 request->proxyAuthInfo = NULL;
5118 secure_proxy_connect = FALSE;
5119 loop_next = TRUE;
5122 else
5123 res = ERROR_SUCCESS;
5125 while (loop_next);
5127 lend:
5128 heap_free(requestString);
5130 /* TODO: send notification for P3P header */
5132 if(res == ERROR_SUCCESS)
5133 create_cache_entry(request);
5135 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5137 if (res == ERROR_SUCCESS) {
5138 if(bEndRequest && request->contentLength && request->bytesWritten == request->bytesToWrite)
5139 HTTP_ReceiveRequestData(request);
5140 else
5141 send_request_complete(request,
5142 request->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)request->hdr.hInternet : 1, 0);
5143 }else {
5144 send_request_complete(request, 0, res);
5148 TRACE("<--\n");
5149 return res;
5152 typedef struct {
5153 task_header_t hdr;
5154 WCHAR *headers;
5155 DWORD headers_len;
5156 void *optional;
5157 DWORD optional_len;
5158 DWORD content_len;
5159 BOOL end_request;
5160 } send_request_task_t;
5162 /***********************************************************************
5164 * Helper functions for the HttpSendRequest(Ex) functions
5167 static void AsyncHttpSendRequestProc(task_header_t *hdr)
5169 send_request_task_t *task = (send_request_task_t*)hdr;
5170 http_request_t *request = (http_request_t*)task->hdr.hdr;
5172 TRACE("%p\n", request);
5174 HTTP_HttpSendRequestW(request, task->headers, task->headers_len, task->optional,
5175 task->optional_len, task->content_len, task->end_request);
5177 heap_free(task->headers);
5181 static DWORD HTTP_HttpEndRequestW(http_request_t *request, DWORD dwFlags, DWORD_PTR dwContext)
5183 INT responseLen;
5184 DWORD res = ERROR_SUCCESS;
5186 if(!is_valid_netconn(request->netconn)) {
5187 WARN("Not connected\n");
5188 send_request_complete(request, 0, ERROR_INTERNET_OPERATION_CANCELLED);
5189 return ERROR_INTERNET_OPERATION_CANCELLED;
5192 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5193 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5195 if (HTTP_GetResponseHeaders(request, &responseLen) || !responseLen)
5196 res = ERROR_HTTP_HEADER_NOT_FOUND;
5198 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5199 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
5201 /* process cookies here. Is this right? */
5202 http_process_keep_alive(request);
5203 HTTP_ProcessCookies(request);
5204 HTTP_ProcessExpires(request);
5205 HTTP_ProcessLastModified(request);
5207 if ((res = set_content_length(request)) == ERROR_SUCCESS) {
5208 if(!request->contentLength)
5209 http_release_netconn(request, TRUE);
5212 if (res == ERROR_SUCCESS && !(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
5214 switch(request->status_code) {
5215 case HTTP_STATUS_REDIRECT:
5216 case HTTP_STATUS_MOVED:
5217 case HTTP_STATUS_REDIRECT_METHOD:
5218 case HTTP_STATUS_REDIRECT_KEEP_VERB: {
5219 WCHAR *new_url;
5221 new_url = get_redirect_url(request);
5222 if(!new_url)
5223 break;
5225 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5226 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5228 heap_free(request->verb);
5229 request->verb = heap_strdupW(szGET);
5231 http_release_netconn(request, drain_content(request, FALSE));
5232 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5233 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5234 res = HTTP_HandleRedirect(request, new_url);
5235 heap_free(new_url);
5236 if (res == ERROR_SUCCESS)
5237 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, TRUE);
5242 if(res == ERROR_SUCCESS)
5243 create_cache_entry(request);
5245 if (res == ERROR_SUCCESS && request->contentLength)
5246 HTTP_ReceiveRequestData(request);
5247 else
5248 send_request_complete(request, res == ERROR_SUCCESS, res);
5250 return res;
5253 /***********************************************************************
5254 * HttpEndRequestA (WININET.@)
5256 * Ends an HTTP request that was started by HttpSendRequestEx
5258 * RETURNS
5259 * TRUE if successful
5260 * FALSE on failure
5263 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
5264 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5266 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5268 if (lpBuffersOut)
5270 SetLastError(ERROR_INVALID_PARAMETER);
5271 return FALSE;
5274 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
5277 typedef struct {
5278 task_header_t hdr;
5279 DWORD flags;
5280 DWORD context;
5281 } end_request_task_t;
5283 static void AsyncHttpEndRequestProc(task_header_t *hdr)
5285 end_request_task_t *task = (end_request_task_t*)hdr;
5286 http_request_t *req = (http_request_t*)task->hdr.hdr;
5288 TRACE("%p\n", req);
5290 HTTP_HttpEndRequestW(req, task->flags, task->context);
5293 /***********************************************************************
5294 * HttpEndRequestW (WININET.@)
5296 * Ends an HTTP request that was started by HttpSendRequestEx
5298 * RETURNS
5299 * TRUE if successful
5300 * FALSE on failure
5303 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
5304 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5306 http_request_t *request;
5307 DWORD res;
5309 TRACE("%p %p %x %lx -->\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5311 if (lpBuffersOut)
5313 SetLastError(ERROR_INVALID_PARAMETER);
5314 return FALSE;
5317 request = (http_request_t*) get_handle_object( hRequest );
5319 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5321 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
5322 if (request)
5323 WININET_Release( &request->hdr );
5324 return FALSE;
5326 request->hdr.dwFlags |= dwFlags;
5328 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5330 end_request_task_t *task;
5332 task = alloc_async_task(&request->hdr, AsyncHttpEndRequestProc, sizeof(*task));
5333 task->flags = dwFlags;
5334 task->context = dwContext;
5336 INTERNET_AsyncCall(&task->hdr);
5337 res = ERROR_IO_PENDING;
5339 else
5340 res = HTTP_HttpEndRequestW(request, dwFlags, dwContext);
5342 WININET_Release( &request->hdr );
5343 TRACE("%u <--\n", res);
5344 if(res != ERROR_SUCCESS)
5345 SetLastError(res);
5346 return res == ERROR_SUCCESS;
5349 /***********************************************************************
5350 * HttpSendRequestExA (WININET.@)
5352 * Sends the specified request to the HTTP server and allows chunked
5353 * transfers.
5355 * RETURNS
5356 * Success: TRUE
5357 * Failure: FALSE, call GetLastError() for more information.
5359 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
5360 LPINTERNET_BUFFERSA lpBuffersIn,
5361 LPINTERNET_BUFFERSA lpBuffersOut,
5362 DWORD dwFlags, DWORD_PTR dwContext)
5364 INTERNET_BUFFERSW BuffersInW;
5365 BOOL rc = FALSE;
5366 DWORD headerlen;
5367 LPWSTR header = NULL;
5369 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5370 lpBuffersOut, dwFlags, dwContext);
5372 if (lpBuffersIn)
5374 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
5375 if (lpBuffersIn->lpcszHeader)
5377 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
5378 lpBuffersIn->dwHeadersLength,0,0);
5379 header = heap_alloc(headerlen*sizeof(WCHAR));
5380 if (!(BuffersInW.lpcszHeader = header))
5382 SetLastError(ERROR_OUTOFMEMORY);
5383 return FALSE;
5385 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
5386 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5387 header, headerlen);
5389 else
5390 BuffersInW.lpcszHeader = NULL;
5391 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
5392 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
5393 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
5394 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
5395 BuffersInW.Next = NULL;
5398 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
5400 heap_free(header);
5401 return rc;
5404 /***********************************************************************
5405 * HttpSendRequestExW (WININET.@)
5407 * Sends the specified request to the HTTP server and allows chunked
5408 * transfers
5410 * RETURNS
5411 * Success: TRUE
5412 * Failure: FALSE, call GetLastError() for more information.
5414 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
5415 LPINTERNET_BUFFERSW lpBuffersIn,
5416 LPINTERNET_BUFFERSW lpBuffersOut,
5417 DWORD dwFlags, DWORD_PTR dwContext)
5419 http_request_t *request;
5420 http_session_t *session;
5421 appinfo_t *hIC;
5422 DWORD res;
5424 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5425 lpBuffersOut, dwFlags, dwContext);
5427 request = (http_request_t*) get_handle_object( hRequest );
5429 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5431 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5432 goto lend;
5435 session = request->session;
5436 assert(session->hdr.htype == WH_HHTTPSESSION);
5437 hIC = session->appInfo;
5438 assert(hIC->hdr.htype == WH_HINIT);
5440 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5442 send_request_task_t *task;
5444 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5445 if (lpBuffersIn)
5447 DWORD size = 0;
5449 if (lpBuffersIn->lpcszHeader)
5451 if (lpBuffersIn->dwHeadersLength == ~0u)
5452 size = (strlenW( lpBuffersIn->lpcszHeader ) + 1) * sizeof(WCHAR);
5453 else
5454 size = lpBuffersIn->dwHeadersLength * sizeof(WCHAR);
5456 task->headers = heap_alloc(size);
5457 memcpy(task->headers, lpBuffersIn->lpcszHeader, size);
5459 else task->headers = NULL;
5461 task->headers_len = size / sizeof(WCHAR);
5462 task->optional = lpBuffersIn->lpvBuffer;
5463 task->optional_len = lpBuffersIn->dwBufferLength;
5464 task->content_len = lpBuffersIn->dwBufferTotal;
5466 else
5468 task->headers = NULL;
5469 task->headers_len = 0;
5470 task->optional = NULL;
5471 task->optional_len = 0;
5472 task->content_len = 0;
5475 task->end_request = FALSE;
5477 INTERNET_AsyncCall(&task->hdr);
5478 res = ERROR_IO_PENDING;
5480 else
5482 if (lpBuffersIn)
5483 res = HTTP_HttpSendRequestW(request, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5484 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
5485 lpBuffersIn->dwBufferTotal, FALSE);
5486 else
5487 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, FALSE);
5490 lend:
5491 if ( request )
5492 WININET_Release( &request->hdr );
5494 TRACE("<---\n");
5495 SetLastError(res);
5496 return res == ERROR_SUCCESS;
5499 /***********************************************************************
5500 * HttpSendRequestW (WININET.@)
5502 * Sends the specified request to the HTTP server
5504 * RETURNS
5505 * TRUE on success
5506 * FALSE on failure
5509 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
5510 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5512 http_request_t *request;
5513 http_session_t *session = NULL;
5514 appinfo_t *hIC = NULL;
5515 DWORD res = ERROR_SUCCESS;
5517 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
5518 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
5520 request = (http_request_t*) get_handle_object( hHttpRequest );
5521 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5523 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5524 goto lend;
5527 session = request->session;
5528 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
5530 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5531 goto lend;
5534 hIC = session->appInfo;
5535 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
5537 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5538 goto lend;
5541 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5543 send_request_task_t *task;
5545 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5546 if (lpszHeaders)
5548 DWORD size;
5550 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
5551 else size = dwHeaderLength * sizeof(WCHAR);
5553 task->headers = heap_alloc(size);
5554 memcpy(task->headers, lpszHeaders, size);
5556 else
5557 task->headers = NULL;
5558 task->headers_len = dwHeaderLength;
5559 task->optional = lpOptional;
5560 task->optional_len = dwOptionalLength;
5561 task->content_len = dwOptionalLength;
5562 task->end_request = TRUE;
5564 INTERNET_AsyncCall(&task->hdr);
5565 res = ERROR_IO_PENDING;
5567 else
5569 res = HTTP_HttpSendRequestW(request, lpszHeaders,
5570 dwHeaderLength, lpOptional, dwOptionalLength,
5571 dwOptionalLength, TRUE);
5573 lend:
5574 if( request )
5575 WININET_Release( &request->hdr );
5577 SetLastError(res);
5578 return res == ERROR_SUCCESS;
5581 /***********************************************************************
5582 * HttpSendRequestA (WININET.@)
5584 * Sends the specified request to the HTTP server
5586 * RETURNS
5587 * TRUE on success
5588 * FALSE on failure
5591 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
5592 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5594 BOOL result;
5595 LPWSTR szHeaders=NULL;
5596 DWORD nLen=dwHeaderLength;
5597 if(lpszHeaders!=NULL)
5599 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
5600 szHeaders = heap_alloc(nLen*sizeof(WCHAR));
5601 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
5603 result = HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
5604 heap_free(szHeaders);
5605 return result;
5608 /***********************************************************************
5609 * HTTPSESSION_Destroy (internal)
5611 * Deallocate session handle
5614 static void HTTPSESSION_Destroy(object_header_t *hdr)
5616 http_session_t *session = (http_session_t*) hdr;
5618 TRACE("%p\n", session);
5620 WININET_Release(&session->appInfo->hdr);
5622 heap_free(session->hostName);
5623 heap_free(session->password);
5624 heap_free(session->userName);
5627 static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
5629 http_session_t *ses = (http_session_t *)hdr;
5631 switch(option) {
5632 case INTERNET_OPTION_HANDLE_TYPE:
5633 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5635 if (*size < sizeof(ULONG))
5636 return ERROR_INSUFFICIENT_BUFFER;
5638 *size = sizeof(DWORD);
5639 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
5640 return ERROR_SUCCESS;
5641 case INTERNET_OPTION_CONNECT_TIMEOUT:
5642 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5644 if (*size < sizeof(DWORD))
5645 return ERROR_INSUFFICIENT_BUFFER;
5647 *size = sizeof(DWORD);
5648 *(DWORD *)buffer = ses->connect_timeout;
5649 return ERROR_SUCCESS;
5651 case INTERNET_OPTION_SEND_TIMEOUT:
5652 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5654 if (*size < sizeof(DWORD))
5655 return ERROR_INSUFFICIENT_BUFFER;
5657 *size = sizeof(DWORD);
5658 *(DWORD *)buffer = ses->send_timeout;
5659 return ERROR_SUCCESS;
5661 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5662 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5664 if (*size < sizeof(DWORD))
5665 return ERROR_INSUFFICIENT_BUFFER;
5667 *size = sizeof(DWORD);
5668 *(DWORD *)buffer = ses->receive_timeout;
5669 return ERROR_SUCCESS;
5672 return INET_QueryOption(hdr, option, buffer, size, unicode);
5675 static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
5677 http_session_t *ses = (http_session_t*)hdr;
5679 switch(option) {
5680 case INTERNET_OPTION_USERNAME:
5682 heap_free(ses->userName);
5683 if (!(ses->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5684 return ERROR_SUCCESS;
5686 case INTERNET_OPTION_PASSWORD:
5688 heap_free(ses->password);
5689 if (!(ses->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5690 return ERROR_SUCCESS;
5692 case INTERNET_OPTION_PROXY_USERNAME:
5694 heap_free(ses->appInfo->proxyUsername);
5695 if (!(ses->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5696 return ERROR_SUCCESS;
5698 case INTERNET_OPTION_PROXY_PASSWORD:
5700 heap_free(ses->appInfo->proxyPassword);
5701 if (!(ses->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5702 return ERROR_SUCCESS;
5704 case INTERNET_OPTION_CONNECT_TIMEOUT:
5706 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5707 ses->connect_timeout = *(DWORD *)buffer;
5708 return ERROR_SUCCESS;
5710 case INTERNET_OPTION_SEND_TIMEOUT:
5712 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5713 ses->send_timeout = *(DWORD *)buffer;
5714 return ERROR_SUCCESS;
5716 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5718 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5719 ses->receive_timeout = *(DWORD *)buffer;
5720 return ERROR_SUCCESS;
5722 default: break;
5725 return INET_SetOption(hdr, option, buffer, size);
5728 static const object_vtbl_t HTTPSESSIONVtbl = {
5729 HTTPSESSION_Destroy,
5730 NULL,
5731 HTTPSESSION_QueryOption,
5732 HTTPSESSION_SetOption,
5733 NULL,
5734 NULL,
5735 NULL,
5736 NULL
5740 /***********************************************************************
5741 * HTTP_Connect (internal)
5743 * Create http session handle
5745 * RETURNS
5746 * HINTERNET a session handle on success
5747 * NULL on failure
5750 DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
5751 INTERNET_PORT serverPort, LPCWSTR lpszUserName,
5752 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
5753 DWORD dwInternalFlags, HINTERNET *ret)
5755 http_session_t *session = NULL;
5757 TRACE("-->\n");
5759 if (!lpszServerName || !lpszServerName[0])
5760 return ERROR_INVALID_PARAMETER;
5762 assert( hIC->hdr.htype == WH_HINIT );
5764 session = alloc_object(&hIC->hdr, &HTTPSESSIONVtbl, sizeof(http_session_t));
5765 if (!session)
5766 return ERROR_OUTOFMEMORY;
5769 * According to my tests. The name is not resolved until a request is sent
5772 session->hdr.htype = WH_HHTTPSESSION;
5773 session->hdr.dwFlags = dwFlags;
5774 session->hdr.dwContext = dwContext;
5775 session->hdr.dwInternalFlags |= dwInternalFlags;
5777 WININET_AddRef( &hIC->hdr );
5778 session->appInfo = hIC;
5779 list_add_head( &hIC->hdr.children, &session->hdr.entry );
5781 session->hostName = heap_strdupW(lpszServerName);
5782 if (lpszUserName && lpszUserName[0])
5783 session->userName = heap_strdupW(lpszUserName);
5784 if (lpszPassword && lpszPassword[0])
5785 session->password = heap_strdupW(lpszPassword);
5786 session->hostPort = serverPort;
5787 session->connect_timeout = hIC->connect_timeout;
5788 session->send_timeout = 0;
5789 session->receive_timeout = 0;
5791 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5792 if (!(session->hdr.dwInternalFlags & INET_OPENURL))
5794 INTERNET_SendCallback(&hIC->hdr, dwContext,
5795 INTERNET_STATUS_HANDLE_CREATED, &session->hdr.hInternet,
5796 sizeof(HINTERNET));
5800 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5801 * windows
5804 TRACE("%p --> %p\n", hIC, session);
5806 *ret = session->hdr.hInternet;
5807 return ERROR_SUCCESS;
5810 /***********************************************************************
5811 * HTTP_clear_response_headers (internal)
5813 * clear out any old response headers
5815 static void HTTP_clear_response_headers( http_request_t *request )
5817 DWORD i;
5819 EnterCriticalSection( &request->headers_section );
5821 for( i=0; i<request->nCustHeaders; i++)
5823 if( !request->custHeaders[i].lpszField )
5824 continue;
5825 if( !request->custHeaders[i].lpszValue )
5826 continue;
5827 if ( request->custHeaders[i].wFlags & HDR_ISREQUEST )
5828 continue;
5829 HTTP_DeleteCustomHeader( request, i );
5830 i--;
5833 LeaveCriticalSection( &request->headers_section );
5836 /***********************************************************************
5837 * HTTP_GetResponseHeaders (internal)
5839 * Read server response
5841 * RETURNS
5843 * TRUE on success
5844 * FALSE on error
5846 static DWORD HTTP_GetResponseHeaders(http_request_t *request, INT *len)
5848 INT cbreaks = 0;
5849 WCHAR buffer[MAX_REPLY_LEN];
5850 DWORD buflen = MAX_REPLY_LEN;
5851 INT rc = 0;
5852 char bufferA[MAX_REPLY_LEN];
5853 LPWSTR status_code = NULL, status_text = NULL;
5854 DWORD res = ERROR_HTTP_INVALID_SERVER_RESPONSE;
5855 BOOL codeHundred = FALSE;
5857 TRACE("-->\n");
5859 if(!is_valid_netconn(request->netconn))
5860 goto lend;
5862 /* clear old response headers (eg. from a redirect response) */
5863 HTTP_clear_response_headers( request );
5865 NETCON_set_timeout( request->netconn, FALSE, request->receive_timeout );
5866 do {
5868 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5870 buflen = MAX_REPLY_LEN;
5871 if ((res = read_line(request, bufferA, &buflen)))
5872 goto lend;
5874 if (!buflen) goto lend;
5876 rc += buflen;
5877 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5878 /* check is this a status code line? */
5879 if (!strncmpW(buffer, g_szHttp1_0, 4))
5881 /* split the version from the status code */
5882 status_code = strchrW( buffer, ' ' );
5883 if( !status_code )
5884 goto lend;
5885 *status_code++=0;
5887 /* split the status code from the status text */
5888 status_text = strchrW( status_code, ' ' );
5889 if( status_text )
5890 *status_text++=0;
5892 request->status_code = atoiW(status_code);
5894 TRACE("version [%s] status code [%s] status text [%s]\n",
5895 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
5897 codeHundred = request->status_code == HTTP_STATUS_CONTINUE;
5899 else if (!codeHundred)
5901 WARN("No status line at head of response (%s)\n", debugstr_w(buffer));
5903 heap_free(request->version);
5904 heap_free(request->statusText);
5906 request->status_code = HTTP_STATUS_OK;
5907 request->version = heap_strdupW(g_szHttp1_0);
5908 request->statusText = heap_strdupW(szOK);
5910 goto lend;
5912 } while (codeHundred);
5914 /* Add status code */
5915 HTTP_ProcessHeader(request, szStatus, status_code,
5916 HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD);
5918 heap_free(request->version);
5919 heap_free(request->statusText);
5921 request->version = heap_strdupW(buffer);
5922 request->statusText = heap_strdupW(status_text ? status_text : emptyW);
5924 /* Restore the spaces */
5925 *(status_code-1) = ' ';
5926 if (status_text)
5927 *(status_text-1) = ' ';
5929 /* Parse each response line */
5932 buflen = MAX_REPLY_LEN;
5933 if (!read_line(request, bufferA, &buflen) && buflen)
5935 LPWSTR * pFieldAndValue;
5937 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
5939 if (!bufferA[0]) break;
5940 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5942 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
5943 if (pFieldAndValue)
5945 HTTP_ProcessHeader(request, pFieldAndValue[0], pFieldAndValue[1],
5946 HTTP_ADDREQ_FLAG_ADD );
5947 HTTP_FreeTokens(pFieldAndValue);
5950 else
5952 cbreaks++;
5953 if (cbreaks >= 2)
5954 break;
5956 }while(1);
5958 res = ERROR_SUCCESS;
5960 lend:
5962 *len = rc;
5963 TRACE("<--\n");
5964 return res;
5967 /***********************************************************************
5968 * HTTP_InterpretHttpHeader (internal)
5970 * Parse server response
5972 * RETURNS
5974 * Pointer to array of field, value, NULL on success.
5975 * NULL on error.
5977 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
5979 LPWSTR * pTokenPair;
5980 LPWSTR pszColon;
5981 INT len;
5983 pTokenPair = heap_alloc_zero(sizeof(*pTokenPair)*3);
5985 pszColon = strchrW(buffer, ':');
5986 /* must have two tokens */
5987 if (!pszColon)
5989 HTTP_FreeTokens(pTokenPair);
5990 if (buffer[0])
5991 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
5992 return NULL;
5995 pTokenPair[0] = heap_alloc((pszColon - buffer + 1) * sizeof(WCHAR));
5996 if (!pTokenPair[0])
5998 HTTP_FreeTokens(pTokenPair);
5999 return NULL;
6001 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
6002 pTokenPair[0][pszColon - buffer] = '\0';
6004 /* skip colon */
6005 pszColon++;
6006 len = strlenW(pszColon);
6007 pTokenPair[1] = heap_alloc((len + 1) * sizeof(WCHAR));
6008 if (!pTokenPair[1])
6010 HTTP_FreeTokens(pTokenPair);
6011 return NULL;
6013 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
6015 strip_spaces(pTokenPair[0]);
6016 strip_spaces(pTokenPair[1]);
6018 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
6019 return pTokenPair;
6022 /***********************************************************************
6023 * HTTP_ProcessHeader (internal)
6025 * Stuff header into header tables according to <dwModifier>
6029 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6031 static DWORD HTTP_ProcessHeader(http_request_t *request, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
6033 LPHTTPHEADERW lphttpHdr = NULL;
6034 INT index;
6035 BOOL request_only = !!(dwModifier & HTTP_ADDHDR_FLAG_REQ);
6036 DWORD res = ERROR_HTTP_INVALID_HEADER;
6038 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
6040 EnterCriticalSection( &request->headers_section );
6042 /* REPLACE wins out over ADD */
6043 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6044 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
6046 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
6047 index = -1;
6048 else
6049 index = HTTP_GetCustomHeaderIndex(request, field, 0, request_only);
6051 if (index >= 0)
6053 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
6055 LeaveCriticalSection( &request->headers_section );
6056 return ERROR_HTTP_INVALID_HEADER;
6058 lphttpHdr = &request->custHeaders[index];
6060 else if (value)
6062 HTTPHEADERW hdr;
6064 hdr.lpszField = (LPWSTR)field;
6065 hdr.lpszValue = (LPWSTR)value;
6066 hdr.wFlags = hdr.wCount = 0;
6068 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6069 hdr.wFlags |= HDR_ISREQUEST;
6071 res = HTTP_InsertCustomHeader(request, &hdr);
6072 LeaveCriticalSection( &request->headers_section );
6073 return res;
6075 /* no value to delete */
6076 else
6078 LeaveCriticalSection( &request->headers_section );
6079 return ERROR_SUCCESS;
6082 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6083 lphttpHdr->wFlags |= HDR_ISREQUEST;
6084 else
6085 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
6087 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6089 HTTP_DeleteCustomHeader( request, index );
6091 if (value && value[0])
6093 HTTPHEADERW hdr;
6095 hdr.lpszField = (LPWSTR)field;
6096 hdr.lpszValue = (LPWSTR)value;
6097 hdr.wFlags = hdr.wCount = 0;
6099 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6100 hdr.wFlags |= HDR_ISREQUEST;
6102 res = HTTP_InsertCustomHeader(request, &hdr);
6103 LeaveCriticalSection( &request->headers_section );
6104 return res;
6107 LeaveCriticalSection( &request->headers_section );
6108 return ERROR_SUCCESS;
6110 else if (dwModifier & COALESCEFLAGS)
6112 LPWSTR lpsztmp;
6113 WCHAR ch = 0;
6114 INT len = 0;
6115 INT origlen = strlenW(lphttpHdr->lpszValue);
6116 INT valuelen = strlenW(value);
6118 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
6120 ch = ',';
6121 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6123 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6125 ch = ';';
6126 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6129 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
6131 lpsztmp = heap_realloc(lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
6132 if (lpsztmp)
6134 lphttpHdr->lpszValue = lpsztmp;
6135 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6136 if (ch > 0)
6138 lphttpHdr->lpszValue[origlen] = ch;
6139 origlen++;
6140 lphttpHdr->lpszValue[origlen] = ' ';
6141 origlen++;
6144 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
6145 lphttpHdr->lpszValue[len] = '\0';
6146 res = ERROR_SUCCESS;
6148 else
6150 WARN("heap_realloc (%d bytes) failed\n",len+1);
6151 res = ERROR_OUTOFMEMORY;
6154 TRACE("<-- %d\n", res);
6155 LeaveCriticalSection( &request->headers_section );
6156 return res;
6159 /***********************************************************************
6160 * HTTP_GetCustomHeaderIndex (internal)
6162 * Return index of custom header from header array
6163 * Headers section must be held
6165 static INT HTTP_GetCustomHeaderIndex(http_request_t *request, LPCWSTR lpszField,
6166 int requested_index, BOOL request_only)
6168 DWORD index;
6170 TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
6172 for (index = 0; index < request->nCustHeaders; index++)
6174 if (strcmpiW(request->custHeaders[index].lpszField, lpszField))
6175 continue;
6177 if (request_only && !(request->custHeaders[index].wFlags & HDR_ISREQUEST))
6178 continue;
6180 if (!request_only && (request->custHeaders[index].wFlags & HDR_ISREQUEST))
6181 continue;
6183 if (requested_index == 0)
6184 break;
6185 requested_index --;
6188 if (index >= request->nCustHeaders)
6189 index = -1;
6191 TRACE("Return: %d\n", index);
6192 return index;
6196 /***********************************************************************
6197 * HTTP_InsertCustomHeader (internal)
6199 * Insert header into array
6200 * Headers section must be held
6202 static DWORD HTTP_InsertCustomHeader(http_request_t *request, LPHTTPHEADERW lpHdr)
6204 INT count;
6205 LPHTTPHEADERW lph = NULL;
6207 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
6208 count = request->nCustHeaders + 1;
6209 if (count > 1)
6210 lph = heap_realloc_zero(request->custHeaders, sizeof(HTTPHEADERW) * count);
6211 else
6212 lph = heap_alloc_zero(sizeof(HTTPHEADERW) * count);
6214 if (!lph)
6215 return ERROR_OUTOFMEMORY;
6217 request->custHeaders = lph;
6218 request->custHeaders[count-1].lpszField = heap_strdupW(lpHdr->lpszField);
6219 request->custHeaders[count-1].lpszValue = heap_strdupW(lpHdr->lpszValue);
6220 request->custHeaders[count-1].wFlags = lpHdr->wFlags;
6221 request->custHeaders[count-1].wCount= lpHdr->wCount;
6222 request->nCustHeaders++;
6224 return ERROR_SUCCESS;
6228 /***********************************************************************
6229 * HTTP_DeleteCustomHeader (internal)
6231 * Delete header from array
6232 * If this function is called, the index may change.
6233 * Headers section must be held
6235 static BOOL HTTP_DeleteCustomHeader(http_request_t *request, DWORD index)
6237 if( request->nCustHeaders <= 0 )
6238 return FALSE;
6239 if( index >= request->nCustHeaders )
6240 return FALSE;
6241 request->nCustHeaders--;
6243 heap_free(request->custHeaders[index].lpszField);
6244 heap_free(request->custHeaders[index].lpszValue);
6246 memmove( &request->custHeaders[index], &request->custHeaders[index+1],
6247 (request->nCustHeaders - index)* sizeof(HTTPHEADERW) );
6248 memset( &request->custHeaders[request->nCustHeaders], 0, sizeof(HTTPHEADERW) );
6250 return TRUE;
6254 /***********************************************************************
6255 * IsHostInProxyBypassList (@)
6257 * Undocumented
6260 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
6262 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
6263 return FALSE;