wininet: Moved inet_ntop call to GetAddress.
[wine.git] / dlls / wininet / http.c
blobb878cabe233287c60ddff1339f8e393f78bfceef
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 #ifdef HAVE_ZLIB
33 # define Z_SOLO
34 # include <zlib.h>
35 #endif
37 #include "ws2tcpip.h"
39 #include <stdarg.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <time.h>
43 #include <assert.h>
44 #include "windef.h"
45 #include "winbase.h"
46 #include "wininet.h"
47 #include "winerror.h"
48 #include "winternl.h"
49 #define NO_SHLWAPI_STREAM
50 #define NO_SHLWAPI_REG
51 #define NO_SHLWAPI_STRFCNS
52 #define NO_SHLWAPI_GDI
53 #include "shlwapi.h"
54 #include "sspi.h"
55 #include "wincrypt.h"
56 #include "winuser.h"
58 #include "internet.h"
59 #include "wine/debug.h"
60 #include "wine/exception.h"
61 #include "wine/unicode.h"
63 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
65 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
66 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
67 static const WCHAR szOK[] = {'O','K',0};
68 static const WCHAR hostW[] = { 'H','o','s','t',0 };
69 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
70 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
71 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
72 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
73 static const WCHAR szGET[] = { 'G','E','T', 0 };
74 static const WCHAR szHEAD[] = { 'H','E','A','D', 0 };
76 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
77 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
78 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
79 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
80 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
81 static const WCHAR szAge[] = { 'A','g','e',0 };
82 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
83 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
84 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
85 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
86 static const WCHAR szContent_Disposition[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
87 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
88 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
89 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
90 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
91 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
92 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
93 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
94 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 };
95 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
96 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
97 static const WCHAR szDate[] = { 'D','a','t','e',0 };
98 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
99 static const WCHAR szETag[] = { 'E','T','a','g',0 };
100 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
101 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
102 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
103 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
104 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
105 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
106 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
107 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
108 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
109 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
110 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
111 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
112 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
113 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
114 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
115 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
116 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
117 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
118 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
119 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
120 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
121 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 };
122 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
123 static const WCHAR szURI[] = { 'U','R','I',0 };
124 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
125 static const WCHAR szVary[] = { 'V','a','r','y',0 };
126 static const WCHAR szVia[] = { 'V','i','a',0 };
127 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
128 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
130 static const WCHAR emptyW[] = {0};
132 #define HTTP_REFERER szReferer
133 #define HTTP_ACCEPT szAccept
134 #define HTTP_USERAGENT szUser_Agent
136 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
137 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
138 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
139 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
140 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
141 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
142 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
144 #define COLLECT_TIME 60000
146 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
148 struct HttpAuthInfo
150 LPWSTR scheme;
151 CredHandle cred;
152 CtxtHandle ctx;
153 TimeStamp exp;
154 ULONG attr;
155 ULONG max_token;
156 void *auth_data;
157 unsigned int auth_data_len;
158 BOOL finished; /* finished authenticating */
162 typedef struct _basicAuthorizationData
164 struct list entry;
166 LPWSTR host;
167 LPWSTR realm;
168 LPSTR authorization;
169 UINT authorizationLen;
170 } basicAuthorizationData;
172 typedef struct _authorizationData
174 struct list entry;
176 LPWSTR host;
177 LPWSTR scheme;
178 LPWSTR domain;
179 UINT domain_len;
180 LPWSTR user;
181 UINT user_len;
182 LPWSTR password;
183 UINT password_len;
184 } authorizationData;
186 static struct list basicAuthorizationCache = LIST_INIT(basicAuthorizationCache);
187 static struct list authorizationCache = LIST_INIT(authorizationCache);
189 static CRITICAL_SECTION authcache_cs;
190 static CRITICAL_SECTION_DEBUG critsect_debug =
192 0, 0, &authcache_cs,
193 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
194 0, 0, { (DWORD_PTR)(__FILE__ ": authcache_cs") }
196 static CRITICAL_SECTION authcache_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
198 static DWORD HTTP_GetResponseHeaders(http_request_t *req, INT *len);
199 static DWORD HTTP_ProcessHeader(http_request_t *req, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
200 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
201 static DWORD HTTP_InsertCustomHeader(http_request_t *req, LPHTTPHEADERW lpHdr);
202 static INT HTTP_GetCustomHeaderIndex(http_request_t *req, LPCWSTR lpszField, INT index, BOOL Request);
203 static BOOL HTTP_DeleteCustomHeader(http_request_t *req, DWORD index);
204 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
205 static DWORD HTTP_HttpQueryInfoW(http_request_t*, DWORD, LPVOID, LPDWORD, LPDWORD);
206 static LPWSTR HTTP_GetRedirectURL(http_request_t *req, LPCWSTR lpszUrl);
207 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
208 static BOOL HTTP_VerifyValidHeader(http_request_t *req, LPCWSTR field);
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(const WCHAR *name, INTERNET_PORT port, BOOL is_https, BOOL do_create)
271 server_t *iter, *server = NULL;
273 if(port == INTERNET_INVALID_PORT_NUMBER)
274 port = INTERNET_DEFAULT_HTTP_PORT;
276 EnterCriticalSection(&connection_pool_cs);
278 LIST_FOR_EACH_ENTRY(iter, &connection_pool, server_t, entry) {
279 if(iter->port == port && !strcmpW(iter->name, name) && iter->is_https == is_https) {
280 server = iter;
281 server_addref(server);
282 break;
286 if(!server && do_create) {
287 server = heap_alloc_zero(sizeof(*server));
288 if(server) {
289 server->ref = 2; /* list reference and return */
290 server->port = port;
291 server->is_https = is_https;
292 list_init(&server->conn_pool);
293 server->name = heap_strdupW(name);
294 if(server->name && process_host_port(server)) {
295 list_add_head(&connection_pool, &server->entry);
296 }else {
297 heap_free(server);
298 server = NULL;
303 LeaveCriticalSection(&connection_pool_cs);
305 return server;
308 BOOL collect_connections(collect_type_t collect_type)
310 netconn_t *netconn, *netconn_safe;
311 server_t *server, *server_safe;
312 BOOL remaining = FALSE;
313 DWORD64 now;
315 now = GetTickCount64();
317 LIST_FOR_EACH_ENTRY_SAFE(server, server_safe, &connection_pool, server_t, entry) {
318 LIST_FOR_EACH_ENTRY_SAFE(netconn, netconn_safe, &server->conn_pool, netconn_t, pool_entry) {
319 if(collect_type > COLLECT_TIMEOUT || netconn->keep_until < now) {
320 TRACE("freeing %p\n", netconn);
321 list_remove(&netconn->pool_entry);
322 free_netconn(netconn);
323 }else {
324 remaining = TRUE;
328 if(collect_type == COLLECT_CLEANUP) {
329 list_remove(&server->entry);
330 list_init(&server->entry);
331 server_release(server);
335 return remaining;
338 static DWORD WINAPI collect_connections_proc(void *arg)
340 BOOL remaining_conns;
342 do {
343 /* FIXME: Use more sophisticated method */
344 Sleep(5000);
346 EnterCriticalSection(&connection_pool_cs);
348 remaining_conns = collect_connections(COLLECT_TIMEOUT);
349 if(!remaining_conns)
350 collector_running = FALSE;
352 LeaveCriticalSection(&connection_pool_cs);
353 }while(remaining_conns);
355 FreeLibraryAndExitThread(WININET_hModule, 0);
358 /***********************************************************************
359 * HTTP_GetHeader (internal)
361 * Headers section must be held
363 static LPHTTPHEADERW HTTP_GetHeader(http_request_t *req, LPCWSTR head)
365 int HeaderIndex = 0;
366 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
367 if (HeaderIndex == -1)
368 return NULL;
369 else
370 return &req->custHeaders[HeaderIndex];
373 static WCHAR *get_host_header( http_request_t *req )
375 HTTPHEADERW *header;
376 WCHAR *ret = NULL;
378 EnterCriticalSection( &req->headers_section );
379 if ((header = HTTP_GetHeader( req, hostW ))) ret = heap_strdupW( header->lpszValue );
380 LeaveCriticalSection( &req->headers_section );
381 return ret;
384 struct data_stream_vtbl_t {
385 DWORD (*get_avail_data)(data_stream_t*,http_request_t*);
386 BOOL (*end_of_data)(data_stream_t*,http_request_t*);
387 DWORD (*read)(data_stream_t*,http_request_t*,BYTE*,DWORD,DWORD*,blocking_mode_t);
388 BOOL (*drain_content)(data_stream_t*,http_request_t*);
389 void (*destroy)(data_stream_t*);
392 typedef struct {
393 data_stream_t data_stream;
395 BYTE buf[READ_BUFFER_SIZE];
396 DWORD buf_size;
397 DWORD buf_pos;
398 DWORD chunk_size;
399 BOOL end_of_data;
400 } chunked_stream_t;
402 static inline void destroy_data_stream(data_stream_t *stream)
404 stream->vtbl->destroy(stream);
407 static void reset_data_stream(http_request_t *req)
409 destroy_data_stream(req->data_stream);
410 req->data_stream = &req->netconn_stream.data_stream;
411 req->read_pos = req->read_size = req->netconn_stream.content_read = 0;
412 req->read_chunked = req->read_gzip = FALSE;
415 static void remove_header( http_request_t *request, const WCHAR *str, BOOL from_request )
417 int index;
418 EnterCriticalSection( &request->headers_section );
419 index = HTTP_GetCustomHeaderIndex( request, str, 0, from_request );
420 if (index != -1) HTTP_DeleteCustomHeader( request, index );
421 LeaveCriticalSection( &request->headers_section );
424 #ifdef HAVE_ZLIB
426 typedef struct {
427 data_stream_t stream;
428 data_stream_t *parent_stream;
429 z_stream zstream;
430 BYTE buf[READ_BUFFER_SIZE];
431 DWORD buf_size;
432 DWORD buf_pos;
433 BOOL end_of_data;
434 } gzip_stream_t;
436 static DWORD gzip_get_avail_data(data_stream_t *stream, http_request_t *req)
438 /* Allow reading only from read buffer */
439 return 0;
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, blocking_mode_t blocking_mode)
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 %d)\n", size, blocking_mode);
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, blocking_mode);
469 gzip_stream->buf_size += current_read;
470 if(res != ERROR_SUCCESS)
471 break;
473 if(!current_read) {
474 if(blocking_mode != BLOCKING_DISALLOW) {
475 WARN("unexpected end of data\n");
476 gzip_stream->end_of_data = TRUE;
478 break;
482 zstream->next_in = gzip_stream->buf+gzip_stream->buf_pos;
483 zstream->avail_in = gzip_stream->buf_size;
484 zstream->next_out = buf+ret_read;
485 zstream->avail_out = size;
486 zres = inflate(&gzip_stream->zstream, 0);
487 current_read = size - zstream->avail_out;
488 size -= current_read;
489 ret_read += current_read;
490 gzip_stream->buf_size -= zstream->next_in - (gzip_stream->buf+gzip_stream->buf_pos);
491 gzip_stream->buf_pos = zstream->next_in-gzip_stream->buf;
492 if(zres == Z_STREAM_END) {
493 TRACE("end of data\n");
494 gzip_stream->end_of_data = TRUE;
495 inflateEnd(zstream);
496 }else if(zres != Z_OK) {
497 WARN("inflate failed %d: %s\n", zres, debugstr_a(zstream->msg));
498 if(!ret_read)
499 res = ERROR_INTERNET_DECODING_FAILED;
500 break;
503 if(ret_read && blocking_mode == BLOCKING_ALLOW)
504 blocking_mode = BLOCKING_DISALLOW;
507 TRACE("read %u bytes\n", ret_read);
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_get_avail_data,
531 gzip_end_of_data,
532 gzip_read,
533 gzip_drain_content,
534 gzip_destroy
537 static voidpf wininet_zalloc(voidpf opaque, uInt items, uInt size)
539 return heap_alloc(items*size);
542 static void wininet_zfree(voidpf opaque, voidpf address)
544 heap_free(address);
547 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
549 gzip_stream_t *gzip_stream;
550 int zres;
552 gzip_stream = heap_alloc_zero(sizeof(gzip_stream_t));
553 if(!gzip_stream)
554 return ERROR_OUTOFMEMORY;
556 gzip_stream->stream.vtbl = &gzip_stream_vtbl;
557 gzip_stream->zstream.zalloc = wininet_zalloc;
558 gzip_stream->zstream.zfree = wininet_zfree;
560 zres = inflateInit2(&gzip_stream->zstream, is_gzip ? 0x1f : -15);
561 if(zres != Z_OK) {
562 ERR("inflateInit failed: %d\n", zres);
563 heap_free(gzip_stream);
564 return ERROR_OUTOFMEMORY;
567 remove_header(req, szContent_Length, FALSE);
569 if(req->read_size) {
570 memcpy(gzip_stream->buf, req->read_buf+req->read_pos, req->read_size);
571 gzip_stream->buf_size = req->read_size;
572 req->read_pos = req->read_size = 0;
575 req->read_gzip = TRUE;
576 gzip_stream->parent_stream = req->data_stream;
577 req->data_stream = &gzip_stream->stream;
578 return ERROR_SUCCESS;
581 #else
583 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
585 ERR("gzip stream not supported, missing zlib.\n");
586 return ERROR_SUCCESS;
589 #endif
591 /***********************************************************************
592 * HTTP_FreeTokens (internal)
594 * Frees table of pointers.
596 static void HTTP_FreeTokens(LPWSTR * token_array)
598 int i;
599 for (i = 0; token_array[i]; i++) heap_free(token_array[i]);
600 heap_free(token_array);
603 static void HTTP_FixURL(http_request_t *request)
605 static const WCHAR szSlash[] = { '/',0 };
606 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
608 /* If we don't have a path we set it to root */
609 if (NULL == request->path)
610 request->path = heap_strdupW(szSlash);
611 else /* remove \r and \n*/
613 int nLen = strlenW(request->path);
614 while ((nLen >0 ) && ((request->path[nLen-1] == '\r')||(request->path[nLen-1] == '\n')))
616 nLen--;
617 request->path[nLen]='\0';
619 /* Replace '\' with '/' */
620 while (nLen>0) {
621 nLen--;
622 if (request->path[nLen] == '\\') request->path[nLen]='/';
626 if(CSTR_EQUAL != CompareStringW( LOCALE_INVARIANT, NORM_IGNORECASE,
627 request->path, strlenW(request->path), szHttp, strlenW(szHttp) )
628 && request->path[0] != '/') /* not an absolute path ?? --> fix it !! */
630 WCHAR *fixurl = heap_alloc((strlenW(request->path) + 2)*sizeof(WCHAR));
631 *fixurl = '/';
632 strcpyW(fixurl + 1, request->path);
633 heap_free( request->path );
634 request->path = fixurl;
638 static WCHAR* build_request_header(http_request_t *request, const WCHAR *verb,
639 const WCHAR *path, const WCHAR *version, BOOL use_cr)
641 static const WCHAR szSpace[] = {' ',0};
642 static const WCHAR szColon[] = {':',' ',0};
643 static const WCHAR szCr[] = {'\r',0};
644 static const WCHAR szLf[] = {'\n',0};
645 LPWSTR requestString;
646 DWORD len, n;
647 LPCWSTR *req;
648 UINT i;
650 EnterCriticalSection( &request->headers_section );
652 /* allocate space for an array of all the string pointers to be added */
653 len = request->nCustHeaders * 5 + 10;
654 if (!(req = heap_alloc( len * sizeof(const WCHAR *) )))
656 LeaveCriticalSection( &request->headers_section );
657 return NULL;
660 /* add the verb, path and HTTP version string */
661 n = 0;
662 req[n++] = verb;
663 req[n++] = szSpace;
664 req[n++] = path;
665 req[n++] = szSpace;
666 req[n++] = version;
667 if (use_cr)
668 req[n++] = szCr;
669 req[n++] = szLf;
671 /* Append custom request headers */
672 for (i = 0; i < request->nCustHeaders; i++)
674 if (request->custHeaders[i].wFlags & HDR_ISREQUEST)
676 req[n++] = request->custHeaders[i].lpszField;
677 req[n++] = szColon;
678 req[n++] = request->custHeaders[i].lpszValue;
679 if (use_cr)
680 req[n++] = szCr;
681 req[n++] = szLf;
683 TRACE("Adding custom header %s (%s)\n",
684 debugstr_w(request->custHeaders[i].lpszField),
685 debugstr_w(request->custHeaders[i].lpszValue));
688 if (use_cr)
689 req[n++] = szCr;
690 req[n++] = szLf;
691 req[n] = NULL;
693 requestString = HTTP_build_req( req, 4 );
694 heap_free( req );
695 LeaveCriticalSection( &request->headers_section );
696 return requestString;
699 static WCHAR* build_response_header(http_request_t *request, BOOL use_cr)
701 static const WCHAR colonW[] = { ':',' ',0 };
702 static const WCHAR crW[] = { '\r',0 };
703 static const WCHAR lfW[] = { '\n',0 };
704 static const WCHAR status_fmt[] = { ' ','%','u',' ',0 };
705 const WCHAR **req;
706 WCHAR *ret, buf[14];
707 DWORD i, n = 0;
709 EnterCriticalSection( &request->headers_section );
711 if (!(req = heap_alloc( (request->nCustHeaders * 5 + 8) * sizeof(WCHAR *) )))
713 LeaveCriticalSection( &request->headers_section );
714 return NULL;
717 if (request->status_code)
719 req[n++] = request->version;
720 sprintfW(buf, status_fmt, request->status_code);
721 req[n++] = buf;
722 req[n++] = request->statusText;
723 if (use_cr)
724 req[n++] = crW;
725 req[n++] = lfW;
728 for(i = 0; i < request->nCustHeaders; i++)
730 if(!(request->custHeaders[i].wFlags & HDR_ISREQUEST)
731 && strcmpW(request->custHeaders[i].lpszField, szStatus))
733 req[n++] = request->custHeaders[i].lpszField;
734 req[n++] = colonW;
735 req[n++] = request->custHeaders[i].lpszValue;
736 if(use_cr)
737 req[n++] = crW;
738 req[n++] = lfW;
740 TRACE("Adding custom header %s (%s)\n",
741 debugstr_w(request->custHeaders[i].lpszField),
742 debugstr_w(request->custHeaders[i].lpszValue));
745 if(use_cr)
746 req[n++] = crW;
747 req[n++] = lfW;
748 req[n] = NULL;
750 ret = HTTP_build_req(req, 0);
751 heap_free(req);
752 LeaveCriticalSection( &request->headers_section );
753 return ret;
756 static void HTTP_ProcessCookies( http_request_t *request )
758 int HeaderIndex;
759 int numCookies = 0;
760 LPHTTPHEADERW setCookieHeader;
762 if(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES)
763 return;
765 EnterCriticalSection( &request->headers_section );
767 while((HeaderIndex = HTTP_GetCustomHeaderIndex(request, szSet_Cookie, numCookies++, FALSE)) != -1)
769 HTTPHEADERW *host;
770 const WCHAR *data;
771 WCHAR *name;
773 setCookieHeader = &request->custHeaders[HeaderIndex];
775 if (!setCookieHeader->lpszValue)
776 continue;
778 host = HTTP_GetHeader(request, hostW);
779 if(!host)
780 continue;
782 data = strchrW(setCookieHeader->lpszValue, '=');
783 if(!data)
784 continue;
786 name = heap_strndupW(setCookieHeader->lpszValue, data-setCookieHeader->lpszValue);
787 if(!name)
788 continue;
790 data++;
791 set_cookie(host->lpszValue, request->path, name, data, INTERNET_COOKIE_HTTPONLY);
792 heap_free(name);
795 LeaveCriticalSection( &request->headers_section );
798 static void strip_spaces(LPWSTR start)
800 LPWSTR str = start;
801 LPWSTR end;
803 while (*str == ' ')
804 str++;
806 if (str != start)
807 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
809 end = start + strlenW(start) - 1;
810 while (end >= start && *end == ' ')
812 *end = '\0';
813 end--;
817 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue, LPWSTR *pszRealm )
819 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
820 static const WCHAR szRealm[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
821 BOOL is_basic;
822 is_basic = !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
823 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
824 if (is_basic && pszRealm)
826 LPCWSTR token;
827 LPCWSTR ptr = &pszAuthValue[ARRAYSIZE(szBasic)];
828 LPCWSTR realm;
829 ptr++;
830 *pszRealm=NULL;
831 token = strchrW(ptr,'=');
832 if (!token)
833 return TRUE;
834 realm = ptr;
835 while (*realm == ' ')
836 realm++;
837 if(!strncmpiW(realm, szRealm, ARRAYSIZE(szRealm)) &&
838 (realm[ARRAYSIZE(szRealm)] == ' ' || realm[ARRAYSIZE(szRealm)] == '='))
840 token++;
841 while (*token == ' ')
842 token++;
843 if (*token == '\0')
844 return TRUE;
845 *pszRealm = heap_strdupW(token);
846 strip_spaces(*pszRealm);
850 return is_basic;
853 static void destroy_authinfo( struct HttpAuthInfo *authinfo )
855 if (!authinfo) return;
857 if (SecIsValidHandle(&authinfo->ctx))
858 DeleteSecurityContext(&authinfo->ctx);
859 if (SecIsValidHandle(&authinfo->cred))
860 FreeCredentialsHandle(&authinfo->cred);
862 heap_free(authinfo->auth_data);
863 heap_free(authinfo->scheme);
864 heap_free(authinfo);
867 static UINT retrieve_cached_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR *auth_data)
869 basicAuthorizationData *ad;
870 UINT rc = 0;
872 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host),debugstr_w(realm));
874 EnterCriticalSection(&authcache_cs);
875 LIST_FOR_EACH_ENTRY(ad, &basicAuthorizationCache, basicAuthorizationData, entry)
877 if (!strcmpiW(host,ad->host) && !strcmpW(realm,ad->realm))
879 TRACE("Authorization found in cache\n");
880 *auth_data = heap_alloc(ad->authorizationLen);
881 memcpy(*auth_data,ad->authorization,ad->authorizationLen);
882 rc = ad->authorizationLen;
883 break;
886 LeaveCriticalSection(&authcache_cs);
887 return rc;
890 static void cache_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR auth_data, UINT auth_data_len)
892 struct list *cursor;
893 basicAuthorizationData* ad = NULL;
895 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host),debugstr_w(realm),debugstr_an(auth_data,auth_data_len));
897 EnterCriticalSection(&authcache_cs);
898 LIST_FOR_EACH(cursor, &basicAuthorizationCache)
900 basicAuthorizationData *check = LIST_ENTRY(cursor,basicAuthorizationData,entry);
901 if (!strcmpiW(host,check->host) && !strcmpW(realm,check->realm))
903 ad = check;
904 break;
908 if (ad)
910 TRACE("Found match in cache, replacing\n");
911 heap_free(ad->authorization);
912 ad->authorization = heap_alloc(auth_data_len);
913 memcpy(ad->authorization, auth_data, auth_data_len);
914 ad->authorizationLen = auth_data_len;
916 else
918 ad = heap_alloc(sizeof(basicAuthorizationData));
919 ad->host = heap_strdupW(host);
920 ad->realm = heap_strdupW(realm);
921 ad->authorization = heap_alloc(auth_data_len);
922 memcpy(ad->authorization, auth_data, auth_data_len);
923 ad->authorizationLen = auth_data_len;
924 list_add_head(&basicAuthorizationCache,&ad->entry);
925 TRACE("authorization cached\n");
927 LeaveCriticalSection(&authcache_cs);
930 static BOOL retrieve_cached_authorization(LPWSTR host, LPWSTR scheme,
931 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
933 authorizationData *ad;
935 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
937 EnterCriticalSection(&authcache_cs);
938 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry) {
939 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
940 TRACE("Authorization found in cache\n");
942 nt_auth_identity->User = heap_strdupW(ad->user);
943 nt_auth_identity->Password = heap_strdupW(ad->password);
944 nt_auth_identity->Domain = heap_alloc(sizeof(WCHAR)*ad->domain_len);
945 if(!nt_auth_identity->User || !nt_auth_identity->Password ||
946 (!nt_auth_identity->Domain && ad->domain_len)) {
947 heap_free(nt_auth_identity->User);
948 heap_free(nt_auth_identity->Password);
949 heap_free(nt_auth_identity->Domain);
950 break;
953 nt_auth_identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
954 nt_auth_identity->UserLength = ad->user_len;
955 nt_auth_identity->PasswordLength = ad->password_len;
956 memcpy(nt_auth_identity->Domain, ad->domain, sizeof(WCHAR)*ad->domain_len);
957 nt_auth_identity->DomainLength = ad->domain_len;
958 LeaveCriticalSection(&authcache_cs);
959 return TRUE;
962 LeaveCriticalSection(&authcache_cs);
964 return FALSE;
967 static void cache_authorization(LPWSTR host, LPWSTR scheme,
968 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
970 authorizationData *ad;
971 BOOL found = FALSE;
973 TRACE("Caching authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
975 EnterCriticalSection(&authcache_cs);
976 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry)
977 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
978 found = TRUE;
979 break;
982 if(found) {
983 heap_free(ad->user);
984 heap_free(ad->password);
985 heap_free(ad->domain);
986 } else {
987 ad = heap_alloc(sizeof(authorizationData));
988 if(!ad) {
989 LeaveCriticalSection(&authcache_cs);
990 return;
993 ad->host = heap_strdupW(host);
994 ad->scheme = heap_strdupW(scheme);
995 list_add_head(&authorizationCache, &ad->entry);
998 ad->user = heap_strndupW(nt_auth_identity->User, nt_auth_identity->UserLength);
999 ad->password = heap_strndupW(nt_auth_identity->Password, nt_auth_identity->PasswordLength);
1000 ad->domain = heap_strndupW(nt_auth_identity->Domain, nt_auth_identity->DomainLength);
1001 ad->user_len = nt_auth_identity->UserLength;
1002 ad->password_len = nt_auth_identity->PasswordLength;
1003 ad->domain_len = nt_auth_identity->DomainLength;
1005 if(!ad->host || !ad->scheme || !ad->user || !ad->password
1006 || (nt_auth_identity->Domain && !ad->domain)) {
1007 heap_free(ad->host);
1008 heap_free(ad->scheme);
1009 heap_free(ad->user);
1010 heap_free(ad->password);
1011 heap_free(ad->domain);
1012 list_remove(&ad->entry);
1013 heap_free(ad);
1016 LeaveCriticalSection(&authcache_cs);
1019 static BOOL HTTP_DoAuthorization( http_request_t *request, LPCWSTR pszAuthValue,
1020 struct HttpAuthInfo **ppAuthInfo,
1021 LPWSTR domain_and_username, LPWSTR password,
1022 LPWSTR host )
1024 SECURITY_STATUS sec_status;
1025 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
1026 BOOL first = FALSE;
1027 LPWSTR szRealm = NULL;
1029 TRACE("%s\n", debugstr_w(pszAuthValue));
1031 if (!pAuthInfo)
1033 TimeStamp exp;
1035 first = TRUE;
1036 pAuthInfo = heap_alloc(sizeof(*pAuthInfo));
1037 if (!pAuthInfo)
1038 return FALSE;
1040 SecInvalidateHandle(&pAuthInfo->cred);
1041 SecInvalidateHandle(&pAuthInfo->ctx);
1042 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
1043 pAuthInfo->attr = 0;
1044 pAuthInfo->auth_data = NULL;
1045 pAuthInfo->auth_data_len = 0;
1046 pAuthInfo->finished = FALSE;
1048 if (is_basic_auth_value(pszAuthValue,NULL))
1050 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
1051 pAuthInfo->scheme = heap_strdupW(szBasic);
1052 if (!pAuthInfo->scheme)
1054 heap_free(pAuthInfo);
1055 return FALSE;
1058 else
1060 PVOID pAuthData;
1061 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
1063 pAuthInfo->scheme = heap_strdupW(pszAuthValue);
1064 if (!pAuthInfo->scheme)
1066 heap_free(pAuthInfo);
1067 return FALSE;
1070 if (domain_and_username)
1072 WCHAR *user = strchrW(domain_and_username, '\\');
1073 WCHAR *domain = domain_and_username;
1075 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1077 pAuthData = &nt_auth_identity;
1079 if (user) user++;
1080 else
1082 user = domain_and_username;
1083 domain = NULL;
1086 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1087 nt_auth_identity.User = user;
1088 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
1089 nt_auth_identity.Domain = domain;
1090 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
1091 nt_auth_identity.Password = password;
1092 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
1094 cache_authorization(host, pAuthInfo->scheme, &nt_auth_identity);
1096 else if(retrieve_cached_authorization(host, pAuthInfo->scheme, &nt_auth_identity))
1097 pAuthData = &nt_auth_identity;
1098 else
1099 /* use default credentials */
1100 pAuthData = NULL;
1102 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
1103 SECPKG_CRED_OUTBOUND, NULL,
1104 pAuthData, NULL,
1105 NULL, &pAuthInfo->cred,
1106 &exp);
1108 if(pAuthData && !domain_and_username) {
1109 heap_free(nt_auth_identity.User);
1110 heap_free(nt_auth_identity.Domain);
1111 heap_free(nt_auth_identity.Password);
1114 if (sec_status == SEC_E_OK)
1116 PSecPkgInfoW sec_pkg_info;
1117 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
1118 if (sec_status == SEC_E_OK)
1120 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
1121 FreeContextBuffer(sec_pkg_info);
1124 if (sec_status != SEC_E_OK)
1126 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1127 debugstr_w(pAuthInfo->scheme), sec_status);
1128 heap_free(pAuthInfo->scheme);
1129 heap_free(pAuthInfo);
1130 return FALSE;
1133 *ppAuthInfo = pAuthInfo;
1135 else if (pAuthInfo->finished)
1136 return FALSE;
1138 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
1139 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
1141 ERR("authentication scheme changed from %s to %s\n",
1142 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
1143 return FALSE;
1146 if (is_basic_auth_value(pszAuthValue,&szRealm))
1148 int userlen;
1149 int passlen;
1150 char *auth_data = NULL;
1151 UINT auth_data_len = 0;
1153 TRACE("basic authentication realm %s\n",debugstr_w(szRealm));
1155 if (!domain_and_username)
1157 if (host && szRealm)
1158 auth_data_len = retrieve_cached_basic_authorization(host, szRealm,&auth_data);
1159 if (auth_data_len == 0)
1161 heap_free(szRealm);
1162 return FALSE;
1165 else
1167 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
1168 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
1170 /* length includes a nul terminator, which will be re-used for the ':' */
1171 auth_data = heap_alloc(userlen + 1 + passlen);
1172 if (!auth_data)
1174 heap_free(szRealm);
1175 return FALSE;
1178 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
1179 auth_data[userlen] = ':';
1180 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
1181 auth_data_len = userlen + 1 + passlen;
1182 if (host && szRealm)
1183 cache_basic_authorization(host, szRealm, auth_data, auth_data_len);
1186 pAuthInfo->auth_data = auth_data;
1187 pAuthInfo->auth_data_len = auth_data_len;
1188 pAuthInfo->finished = TRUE;
1189 heap_free(szRealm);
1190 return TRUE;
1192 else
1194 LPCWSTR pszAuthData;
1195 SecBufferDesc out_desc, in_desc;
1196 SecBuffer out, in;
1197 unsigned char *buffer;
1198 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
1199 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
1201 in.BufferType = SECBUFFER_TOKEN;
1202 in.cbBuffer = 0;
1203 in.pvBuffer = NULL;
1205 in_desc.ulVersion = 0;
1206 in_desc.cBuffers = 1;
1207 in_desc.pBuffers = &in;
1209 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
1210 if (*pszAuthData == ' ')
1212 pszAuthData++;
1213 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
1214 in.pvBuffer = heap_alloc(in.cbBuffer);
1215 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
1218 buffer = heap_alloc(pAuthInfo->max_token);
1220 out.BufferType = SECBUFFER_TOKEN;
1221 out.cbBuffer = pAuthInfo->max_token;
1222 out.pvBuffer = buffer;
1224 out_desc.ulVersion = 0;
1225 out_desc.cBuffers = 1;
1226 out_desc.pBuffers = &out;
1228 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
1229 first ? NULL : &pAuthInfo->ctx,
1230 first ? request->server->name : NULL,
1231 context_req, 0, SECURITY_NETWORK_DREP,
1232 in.pvBuffer ? &in_desc : NULL,
1233 0, &pAuthInfo->ctx, &out_desc,
1234 &pAuthInfo->attr, &pAuthInfo->exp);
1235 if (sec_status == SEC_E_OK)
1237 pAuthInfo->finished = TRUE;
1238 pAuthInfo->auth_data = out.pvBuffer;
1239 pAuthInfo->auth_data_len = out.cbBuffer;
1240 TRACE("sending last auth packet\n");
1242 else if (sec_status == SEC_I_CONTINUE_NEEDED)
1244 pAuthInfo->auth_data = out.pvBuffer;
1245 pAuthInfo->auth_data_len = out.cbBuffer;
1246 TRACE("sending next auth packet\n");
1248 else
1250 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
1251 heap_free(out.pvBuffer);
1252 destroy_authinfo(pAuthInfo);
1253 *ppAuthInfo = NULL;
1254 return FALSE;
1258 return TRUE;
1261 /***********************************************************************
1262 * HTTP_HttpAddRequestHeadersW (internal)
1264 static DWORD HTTP_HttpAddRequestHeadersW(http_request_t *request,
1265 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1267 LPWSTR lpszStart;
1268 LPWSTR lpszEnd;
1269 LPWSTR buffer;
1270 DWORD len, res = ERROR_HTTP_INVALID_HEADER;
1272 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
1274 if( dwHeaderLength == ~0U )
1275 len = strlenW(lpszHeader);
1276 else
1277 len = dwHeaderLength;
1278 buffer = heap_alloc(sizeof(WCHAR)*(len+1));
1279 lstrcpynW( buffer, lpszHeader, len + 1);
1281 lpszStart = buffer;
1285 LPWSTR * pFieldAndValue;
1287 lpszEnd = lpszStart;
1289 while (*lpszEnd != '\0')
1291 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1292 break;
1293 lpszEnd++;
1296 if (*lpszStart == '\0')
1297 break;
1299 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1301 *lpszEnd = '\0';
1302 lpszEnd++; /* Jump over newline */
1304 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
1305 if (*lpszStart == '\0')
1307 /* Skip 0-length headers */
1308 lpszStart = lpszEnd;
1309 res = ERROR_SUCCESS;
1310 continue;
1312 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
1313 if (pFieldAndValue)
1315 res = HTTP_VerifyValidHeader(request, pFieldAndValue[0]);
1316 if (res == ERROR_SUCCESS)
1317 res = HTTP_ProcessHeader(request, pFieldAndValue[0],
1318 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
1319 HTTP_FreeTokens(pFieldAndValue);
1322 lpszStart = lpszEnd;
1323 } while (res == ERROR_SUCCESS);
1325 heap_free(buffer);
1326 return res;
1329 /***********************************************************************
1330 * HttpAddRequestHeadersW (WININET.@)
1332 * Adds one or more HTTP header to the request handler
1334 * NOTE
1335 * On Windows if dwHeaderLength includes the trailing '\0', then
1336 * HttpAddRequestHeadersW() adds it too. However this results in an
1337 * invalid HTTP header which is rejected by some servers so we probably
1338 * don't need to match Windows on that point.
1340 * RETURNS
1341 * TRUE on success
1342 * FALSE on failure
1345 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
1346 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1348 http_request_t *request;
1349 DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
1351 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1353 if (!lpszHeader)
1354 return TRUE;
1356 request = (http_request_t*) get_handle_object( hHttpRequest );
1357 if (request && request->hdr.htype == WH_HHTTPREQ)
1358 res = HTTP_HttpAddRequestHeadersW( request, lpszHeader, dwHeaderLength, dwModifier );
1359 if( request )
1360 WININET_Release( &request->hdr );
1362 if(res != ERROR_SUCCESS)
1363 SetLastError(res);
1364 return res == ERROR_SUCCESS;
1367 /***********************************************************************
1368 * HttpAddRequestHeadersA (WININET.@)
1370 * Adds one or more HTTP header to the request handler
1372 * RETURNS
1373 * TRUE on success
1374 * FALSE on failure
1377 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
1378 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1380 DWORD len;
1381 LPWSTR hdr;
1382 BOOL r;
1384 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1386 len = MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, NULL, 0 );
1387 hdr = heap_alloc(len*sizeof(WCHAR));
1388 MultiByteToWideChar( CP_ACP, 0, lpszHeader, dwHeaderLength, hdr, len );
1389 if( dwHeaderLength != ~0U )
1390 dwHeaderLength = len;
1392 r = HttpAddRequestHeadersW( hHttpRequest, hdr, dwHeaderLength, dwModifier );
1394 heap_free( hdr );
1395 return r;
1398 static void free_accept_types( WCHAR **accept_types )
1400 WCHAR *ptr, **types = accept_types;
1402 if (!types) return;
1403 while ((ptr = *types))
1405 heap_free( ptr );
1406 types++;
1408 heap_free( accept_types );
1411 static WCHAR **convert_accept_types( const char **accept_types )
1413 unsigned int count;
1414 const char **types = accept_types;
1415 WCHAR **typesW;
1416 BOOL invalid_pointer = FALSE;
1418 if (!types) return NULL;
1419 count = 0;
1420 while (*types)
1422 __TRY
1424 /* find out how many there are */
1425 if (*types && **types)
1427 TRACE("accept type: %s\n", debugstr_a(*types));
1428 count++;
1431 __EXCEPT_PAGE_FAULT
1433 WARN("invalid accept type pointer\n");
1434 invalid_pointer = TRUE;
1436 __ENDTRY;
1437 types++;
1439 if (invalid_pointer) return NULL;
1440 if (!(typesW = heap_alloc( sizeof(WCHAR *) * (count + 1) ))) return NULL;
1441 count = 0;
1442 types = accept_types;
1443 while (*types)
1445 if (*types && **types) typesW[count++] = heap_strdupAtoW( *types );
1446 types++;
1448 typesW[count] = NULL;
1449 return typesW;
1452 /***********************************************************************
1453 * HttpOpenRequestA (WININET.@)
1455 * Open a HTTP request handle
1457 * RETURNS
1458 * HINTERNET a HTTP request handle on success
1459 * NULL on failure
1462 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
1463 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
1464 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
1465 DWORD dwFlags, DWORD_PTR dwContext)
1467 LPWSTR szVerb = NULL, szObjectName = NULL;
1468 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
1469 HINTERNET rc = NULL;
1471 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
1472 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
1473 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
1474 dwFlags, dwContext);
1476 if (lpszVerb)
1478 szVerb = heap_strdupAtoW(lpszVerb);
1479 if ( !szVerb )
1480 goto end;
1483 if (lpszObjectName)
1485 szObjectName = heap_strdupAtoW(lpszObjectName);
1486 if ( !szObjectName )
1487 goto end;
1490 if (lpszVersion)
1492 szVersion = heap_strdupAtoW(lpszVersion);
1493 if ( !szVersion )
1494 goto end;
1497 if (lpszReferrer)
1499 szReferrer = heap_strdupAtoW(lpszReferrer);
1500 if ( !szReferrer )
1501 goto end;
1504 szAcceptTypes = convert_accept_types( lpszAcceptTypes );
1505 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName, szVersion, szReferrer,
1506 (const WCHAR **)szAcceptTypes, dwFlags, dwContext);
1508 end:
1509 free_accept_types(szAcceptTypes);
1510 heap_free(szReferrer);
1511 heap_free(szVersion);
1512 heap_free(szObjectName);
1513 heap_free(szVerb);
1514 return rc;
1517 /***********************************************************************
1518 * HTTP_EncodeBase64
1520 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1522 UINT n = 0, x;
1523 static const CHAR HTTP_Base64Enc[] =
1524 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1526 while( len > 0 )
1528 /* first 6 bits, all from bin[0] */
1529 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1530 x = (bin[0] & 3) << 4;
1532 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1533 if( len == 1 )
1535 base64[n++] = HTTP_Base64Enc[x];
1536 base64[n++] = '=';
1537 base64[n++] = '=';
1538 break;
1540 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1541 x = ( bin[1] & 0x0f ) << 2;
1543 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1544 if( len == 2 )
1546 base64[n++] = HTTP_Base64Enc[x];
1547 base64[n++] = '=';
1548 break;
1550 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1552 /* last 6 bits, all from bin [2] */
1553 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1554 bin += 3;
1555 len -= 3;
1557 base64[n] = 0;
1558 return n;
1561 #define CH(x) (((x) >= 'A' && (x) <= 'Z') ? (x) - 'A' : \
1562 ((x) >= 'a' && (x) <= 'z') ? (x) - 'a' + 26 : \
1563 ((x) >= '0' && (x) <= '9') ? (x) - '0' + 52 : \
1564 ((x) == '+') ? 62 : ((x) == '/') ? 63 : -1)
1565 static const signed char HTTP_Base64Dec[256] =
1567 CH( 0),CH( 1),CH( 2),CH( 3),CH( 4),CH( 5),CH( 6),CH( 7),CH( 8),CH( 9),
1568 CH(10),CH(11),CH(12),CH(13),CH(14),CH(15),CH(16),CH(17),CH(18),CH(19),
1569 CH(20),CH(21),CH(22),CH(23),CH(24),CH(25),CH(26),CH(27),CH(28),CH(29),
1570 CH(30),CH(31),CH(32),CH(33),CH(34),CH(35),CH(36),CH(37),CH(38),CH(39),
1571 CH(40),CH(41),CH(42),CH(43),CH(44),CH(45),CH(46),CH(47),CH(48),CH(49),
1572 CH(50),CH(51),CH(52),CH(53),CH(54),CH(55),CH(56),CH(57),CH(58),CH(59),
1573 CH(60),CH(61),CH(62),CH(63),CH(64),CH(65),CH(66),CH(67),CH(68),CH(69),
1574 CH(70),CH(71),CH(72),CH(73),CH(74),CH(75),CH(76),CH(77),CH(78),CH(79),
1575 CH(80),CH(81),CH(82),CH(83),CH(84),CH(85),CH(86),CH(87),CH(88),CH(89),
1576 CH(90),CH(91),CH(92),CH(93),CH(94),CH(95),CH(96),CH(97),CH(98),CH(99),
1577 CH(100),CH(101),CH(102),CH(103),CH(104),CH(105),CH(106),CH(107),CH(108),CH(109),
1578 CH(110),CH(111),CH(112),CH(113),CH(114),CH(115),CH(116),CH(117),CH(118),CH(119),
1579 CH(120),CH(121),CH(122),CH(123),CH(124),CH(125),CH(126),CH(127),CH(128),CH(129),
1580 CH(130),CH(131),CH(132),CH(133),CH(134),CH(135),CH(136),CH(137),CH(138),CH(139),
1581 CH(140),CH(141),CH(142),CH(143),CH(144),CH(145),CH(146),CH(147),CH(148),CH(149),
1582 CH(150),CH(151),CH(152),CH(153),CH(154),CH(155),CH(156),CH(157),CH(158),CH(159),
1583 CH(160),CH(161),CH(162),CH(163),CH(164),CH(165),CH(166),CH(167),CH(168),CH(169),
1584 CH(170),CH(171),CH(172),CH(173),CH(174),CH(175),CH(176),CH(177),CH(178),CH(179),
1585 CH(180),CH(181),CH(182),CH(183),CH(184),CH(185),CH(186),CH(187),CH(188),CH(189),
1586 CH(190),CH(191),CH(192),CH(193),CH(194),CH(195),CH(196),CH(197),CH(198),CH(199),
1587 CH(200),CH(201),CH(202),CH(203),CH(204),CH(205),CH(206),CH(207),CH(208),CH(209),
1588 CH(210),CH(211),CH(212),CH(213),CH(214),CH(215),CH(216),CH(217),CH(218),CH(219),
1589 CH(220),CH(221),CH(222),CH(223),CH(224),CH(225),CH(226),CH(227),CH(228),CH(229),
1590 CH(230),CH(231),CH(232),CH(233),CH(234),CH(235),CH(236),CH(237),CH(238),CH(239),
1591 CH(240),CH(241),CH(242),CH(243),CH(244),CH(245),CH(246),CH(247),CH(248), CH(249),
1592 CH(250),CH(251),CH(252),CH(253),CH(254),CH(255),
1594 #undef CH
1596 /***********************************************************************
1597 * HTTP_DecodeBase64
1599 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1601 unsigned int n = 0;
1603 while(*base64)
1605 signed char in[4];
1607 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1608 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1609 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1610 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1612 WARN("invalid base64: %s\n", debugstr_w(base64));
1613 return 0;
1615 if (bin)
1616 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1617 n++;
1619 if ((base64[2] == '=') && (base64[3] == '='))
1620 break;
1621 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1622 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1624 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1625 return 0;
1627 if (bin)
1628 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1629 n++;
1631 if (base64[3] == '=')
1632 break;
1633 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1634 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1636 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1637 return 0;
1639 if (bin)
1640 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1641 n++;
1643 base64 += 4;
1646 return n;
1649 /***********************************************************************
1650 * HTTP_InsertAuthorization
1652 * Insert or delete the authorization field in the request header.
1654 static BOOL HTTP_InsertAuthorization( http_request_t *request, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1656 if (pAuthInfo)
1658 static const WCHAR wszSpace[] = {' ',0};
1659 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1660 unsigned int len;
1661 WCHAR *authorization = NULL;
1663 if (pAuthInfo->auth_data_len)
1665 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1666 len = strlenW(pAuthInfo->scheme)+1+((pAuthInfo->auth_data_len+2)*4)/3;
1667 authorization = heap_alloc((len+1)*sizeof(WCHAR));
1668 if (!authorization)
1669 return FALSE;
1671 strcpyW(authorization, pAuthInfo->scheme);
1672 strcatW(authorization, wszSpace);
1673 HTTP_EncodeBase64(pAuthInfo->auth_data,
1674 pAuthInfo->auth_data_len,
1675 authorization+strlenW(authorization));
1677 /* clear the data as it isn't valid now that it has been sent to the
1678 * server, unless it's Basic authentication which doesn't do
1679 * connection tracking */
1680 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1682 heap_free(pAuthInfo->auth_data);
1683 pAuthInfo->auth_data = NULL;
1684 pAuthInfo->auth_data_len = 0;
1688 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1690 HTTP_ProcessHeader(request, header, authorization, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
1691 heap_free(authorization);
1693 return TRUE;
1696 static WCHAR *build_proxy_path_url(http_request_t *req)
1698 DWORD size, len;
1699 WCHAR *url;
1701 len = strlenW(req->server->scheme_host_port);
1702 size = len + strlenW(req->path) + 1;
1703 if(*req->path != '/')
1704 size++;
1705 url = heap_alloc(size * sizeof(WCHAR));
1706 if(!url)
1707 return NULL;
1709 memcpy(url, req->server->scheme_host_port, len*sizeof(WCHAR));
1710 if(*req->path != '/')
1711 url[len++] = '/';
1713 strcpyW(url+len, req->path);
1715 TRACE("url=%s\n", debugstr_w(url));
1716 return url;
1719 static BOOL HTTP_DomainMatches(LPCWSTR server, LPCWSTR domain)
1721 static const WCHAR localW[] = { '<','l','o','c','a','l','>',0 };
1722 BOOL ret = FALSE;
1724 if (!strcmpiW( domain, localW ) && !strchrW( server, '.' ))
1725 ret = TRUE;
1726 else if (*domain == '*')
1728 if (domain[1] == '.')
1730 LPCWSTR dot;
1732 /* For a hostname to match a wildcard, the last domain must match
1733 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1734 * hostname is www.foo.a.b, it matches, but a.b does not.
1736 dot = strchrW( server, '.' );
1737 if (dot)
1739 int len = strlenW( dot + 1 );
1741 if (len > strlenW( domain + 2 ))
1743 LPCWSTR ptr;
1745 /* The server's domain is longer than the wildcard, so it
1746 * could be a subdomain. Compare the last portion of the
1747 * server's domain.
1749 ptr = dot + len + 1 - strlenW( domain + 2 );
1750 if (!strcmpiW( ptr, domain + 2 ))
1752 /* This is only a match if the preceding character is
1753 * a '.', i.e. that it is a matching domain. E.g.
1754 * if domain is '*.b.c' and server is 'www.ab.c' they
1755 * do not match.
1757 ret = *(ptr - 1) == '.';
1760 else
1761 ret = !strcmpiW( dot + 1, domain + 2 );
1765 else
1766 ret = !strcmpiW( server, domain );
1767 return ret;
1770 static BOOL HTTP_ShouldBypassProxy(appinfo_t *lpwai, LPCWSTR server)
1772 LPCWSTR ptr;
1773 BOOL ret = FALSE;
1775 if (!lpwai->proxyBypass) return FALSE;
1776 ptr = lpwai->proxyBypass;
1777 do {
1778 LPCWSTR tmp = ptr;
1780 ptr = strchrW( ptr, ';' );
1781 if (!ptr)
1782 ptr = strchrW( tmp, ' ' );
1783 if (ptr)
1785 if (ptr - tmp < INTERNET_MAX_HOST_NAME_LENGTH)
1787 WCHAR domain[INTERNET_MAX_HOST_NAME_LENGTH];
1789 memcpy( domain, tmp, (ptr - tmp) * sizeof(WCHAR) );
1790 domain[ptr - tmp] = 0;
1791 ret = HTTP_DomainMatches( server, domain );
1793 ptr += 1;
1795 else if (*tmp)
1796 ret = HTTP_DomainMatches( server, tmp );
1797 } while (ptr && !ret);
1798 return ret;
1801 /***********************************************************************
1802 * HTTP_DealWithProxy
1804 static BOOL HTTP_DealWithProxy(appinfo_t *hIC, http_session_t *session, http_request_t *request)
1806 static const WCHAR protoHttp[] = { 'h','t','t','p',0 };
1807 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1808 static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',0 };
1809 WCHAR buf[INTERNET_MAX_HOST_NAME_LENGTH];
1810 WCHAR protoProxy[INTERNET_MAX_URL_LENGTH];
1811 DWORD protoProxyLen = INTERNET_MAX_URL_LENGTH;
1812 WCHAR proxy[INTERNET_MAX_URL_LENGTH];
1813 static WCHAR szNul[] = { 0 };
1814 URL_COMPONENTSW UrlComponents;
1815 server_t *new_server;
1816 BOOL is_https;
1818 memset( &UrlComponents, 0, sizeof UrlComponents );
1819 UrlComponents.dwStructSize = sizeof UrlComponents;
1820 UrlComponents.lpszHostName = buf;
1821 UrlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
1823 if (!INTERNET_FindProxyForProtocol(hIC->proxy, protoHttp, protoProxy, &protoProxyLen))
1824 return FALSE;
1825 if( CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1826 protoProxy,strlenW(szHttp),szHttp,strlenW(szHttp)) )
1827 sprintfW(proxy, szFormat, protoProxy);
1828 else
1829 strcpyW(proxy, protoProxy);
1830 if( !InternetCrackUrlW(proxy, 0, 0, &UrlComponents) )
1831 return FALSE;
1832 if( UrlComponents.dwHostNameLength == 0 )
1833 return FALSE;
1835 if( !request->path )
1836 request->path = szNul;
1838 is_https = (UrlComponents.nScheme == INTERNET_SCHEME_HTTPS);
1839 if (is_https && UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
1840 UrlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
1842 new_server = get_server(UrlComponents.lpszHostName, UrlComponents.nPort, is_https, TRUE);
1843 if(!new_server)
1844 return FALSE;
1846 request->proxy = new_server;
1848 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server->name), new_server->port);
1849 return TRUE;
1852 static DWORD HTTP_ResolveName(http_request_t *request)
1854 server_t *server = request->proxy ? request->proxy : request->server;
1855 int addr_len;
1857 if(server->addr_len)
1858 return ERROR_SUCCESS;
1860 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1861 INTERNET_STATUS_RESOLVING_NAME,
1862 server->name,
1863 (strlenW(server->name)+1) * sizeof(WCHAR));
1865 addr_len = sizeof(server->addr);
1866 if (!GetAddress(server->name, server->port, (SOCKADDR*)&server->addr, &addr_len, server->addr_str))
1867 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1869 server->addr_len = addr_len;
1870 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1871 INTERNET_STATUS_NAME_RESOLVED,
1872 server->addr_str, strlen(server->addr_str)+1);
1874 TRACE("resolved %s to %s\n", debugstr_w(server->name), server->addr_str);
1875 return ERROR_SUCCESS;
1878 static BOOL HTTP_GetRequestURL(http_request_t *req, LPWSTR buf)
1880 static const WCHAR http[] = { 'h','t','t','p',':','/','/',0 };
1881 static const WCHAR https[] = { 'h','t','t','p','s',':','/','/',0 };
1882 static const WCHAR slash[] = { '/',0 };
1883 LPHTTPHEADERW host_header;
1884 LPCWSTR scheme;
1886 host_header = HTTP_GetHeader(req, hostW);
1887 if(!host_header)
1888 return FALSE;
1890 EnterCriticalSection( &req->headers_section );
1892 if (req->hdr.dwFlags & INTERNET_FLAG_SECURE)
1893 scheme = https;
1894 else
1895 scheme = http;
1896 strcpyW(buf, scheme);
1897 strcatW(buf, host_header->lpszValue);
1898 if (req->path[0] != '/')
1899 strcatW(buf, slash);
1900 strcatW(buf, req->path);
1902 LeaveCriticalSection( &req->headers_section );
1903 return TRUE;
1907 /***********************************************************************
1908 * HTTPREQ_Destroy (internal)
1910 * Deallocate request handle
1913 static void HTTPREQ_Destroy(object_header_t *hdr)
1915 http_request_t *request = (http_request_t*) hdr;
1916 DWORD i;
1918 TRACE("\n");
1920 if(request->hCacheFile)
1921 CloseHandle(request->hCacheFile);
1922 if(request->req_file)
1923 req_file_release(request->req_file);
1925 request->headers_section.DebugInfo->Spare[0] = 0;
1926 DeleteCriticalSection( &request->headers_section );
1927 request->read_section.DebugInfo->Spare[0] = 0;
1928 DeleteCriticalSection( &request->read_section );
1929 WININET_Release(&request->session->hdr);
1931 destroy_authinfo(request->authInfo);
1932 destroy_authinfo(request->proxyAuthInfo);
1934 if(request->server)
1935 server_release(request->server);
1936 if(request->proxy)
1937 server_release(request->proxy);
1939 heap_free(request->path);
1940 heap_free(request->verb);
1941 heap_free(request->version);
1942 heap_free(request->statusText);
1944 for (i = 0; i < request->nCustHeaders; i++)
1946 heap_free(request->custHeaders[i].lpszField);
1947 heap_free(request->custHeaders[i].lpszValue);
1949 destroy_data_stream(request->data_stream);
1950 heap_free(request->custHeaders);
1953 static void http_release_netconn(http_request_t *req, BOOL reuse)
1955 TRACE("%p %p %x\n",req, req->netconn, reuse);
1957 if(!is_valid_netconn(req->netconn))
1958 return;
1960 if(reuse && req->netconn->keep_alive) {
1961 BOOL run_collector;
1963 EnterCriticalSection(&connection_pool_cs);
1965 list_add_head(&req->netconn->server->conn_pool, &req->netconn->pool_entry);
1966 req->netconn->keep_until = GetTickCount64() + COLLECT_TIME;
1967 req->netconn = NULL;
1969 run_collector = !collector_running;
1970 collector_running = TRUE;
1972 LeaveCriticalSection(&connection_pool_cs);
1974 if(run_collector) {
1975 HANDLE thread = NULL;
1976 HMODULE module;
1978 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR*)WININET_hModule, &module);
1979 if(module)
1980 thread = CreateThread(NULL, 0, collect_connections_proc, NULL, 0, NULL);
1981 if(!thread) {
1982 EnterCriticalSection(&connection_pool_cs);
1983 collector_running = FALSE;
1984 LeaveCriticalSection(&connection_pool_cs);
1986 if(module)
1987 FreeLibrary(module);
1989 else
1990 CloseHandle(thread);
1992 return;
1995 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1996 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1998 close_netconn(req->netconn);
2000 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
2001 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
2004 static BOOL HTTP_KeepAlive(http_request_t *request)
2006 WCHAR szVersion[10];
2007 WCHAR szConnectionResponse[20];
2008 DWORD dwBufferSize = sizeof(szVersion);
2009 BOOL keepalive = FALSE;
2011 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
2012 * the connection is keep-alive by default */
2013 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_VERSION, szVersion, &dwBufferSize, NULL) == ERROR_SUCCESS
2014 && !strcmpiW(szVersion, g_szHttp1_1))
2016 keepalive = TRUE;
2019 dwBufferSize = sizeof(szConnectionResponse);
2020 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS
2021 || HTTP_HttpQueryInfoW(request, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS)
2023 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
2026 return keepalive;
2029 static void HTTPREQ_CloseConnection(object_header_t *hdr)
2031 http_request_t *req = (http_request_t*)hdr;
2033 http_release_netconn(req, drain_content(req, FALSE));
2036 static DWORD str_to_buffer(const WCHAR *str, void *buffer, DWORD *size, BOOL unicode)
2038 int len;
2039 if (unicode)
2041 WCHAR *buf = buffer;
2043 if (str) len = strlenW(str);
2044 else len = 0;
2045 if (*size < (len + 1) * sizeof(WCHAR))
2047 *size = (len + 1) * sizeof(WCHAR);
2048 return ERROR_INSUFFICIENT_BUFFER;
2050 if (str) strcpyW(buf, str);
2051 else buf[0] = 0;
2053 *size = len;
2054 return ERROR_SUCCESS;
2056 else
2058 char *buf = buffer;
2060 if (str) len = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
2061 else len = 1;
2062 if (*size < len)
2064 *size = len;
2065 return ERROR_INSUFFICIENT_BUFFER;
2067 if (str) WideCharToMultiByte(CP_ACP, 0, str, -1, buf, *size, NULL, NULL);
2068 else buf[0] = 0;
2070 *size = len - 1;
2071 return ERROR_SUCCESS;
2075 static DWORD HTTPREQ_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2077 http_request_t *req = (http_request_t*)hdr;
2079 switch(option) {
2080 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO:
2082 INTERNET_DIAGNOSTIC_SOCKET_INFO *info = buffer;
2084 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2086 if (*size < sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO))
2087 return ERROR_INSUFFICIENT_BUFFER;
2088 *size = sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO);
2089 /* FIXME: can't get a SOCKET from our connection since we don't use
2090 * winsock
2092 info->Socket = 0;
2093 /* FIXME: get source port from req->netConnection */
2094 info->SourcePort = 0;
2095 info->DestPort = req->server->port;
2096 info->Flags = 0;
2097 if (HTTP_KeepAlive(req))
2098 info->Flags |= IDSI_FLAG_KEEP_ALIVE;
2099 if (req->proxy)
2100 info->Flags |= IDSI_FLAG_PROXY;
2101 if (is_valid_netconn(req->netconn) && req->netconn->secure)
2102 info->Flags |= IDSI_FLAG_SECURE;
2104 return ERROR_SUCCESS;
2107 case 98:
2108 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2109 /* fall through */
2110 case INTERNET_OPTION_SECURITY_FLAGS:
2112 DWORD flags;
2114 if (*size < sizeof(ULONG))
2115 return ERROR_INSUFFICIENT_BUFFER;
2117 *size = sizeof(DWORD);
2118 flags = is_valid_netconn(req->netconn) ? req->netconn->security_flags : req->security_flags | req->server->security_flags;
2119 *(DWORD *)buffer = flags;
2121 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags);
2122 return ERROR_SUCCESS;
2125 case INTERNET_OPTION_HANDLE_TYPE:
2126 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2128 if (*size < sizeof(ULONG))
2129 return ERROR_INSUFFICIENT_BUFFER;
2131 *size = sizeof(DWORD);
2132 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
2133 return ERROR_SUCCESS;
2135 case INTERNET_OPTION_URL: {
2136 static const WCHAR httpW[] = {'h','t','t','p',':','/','/',0};
2137 WCHAR url[INTERNET_MAX_URL_LENGTH];
2138 HTTPHEADERW *host;
2140 TRACE("INTERNET_OPTION_URL\n");
2142 EnterCriticalSection( &req->headers_section );
2143 host = HTTP_GetHeader(req, hostW);
2144 strcpyW(url, httpW);
2145 strcatW(url, host->lpszValue);
2146 strcatW(url, req->path);
2147 LeaveCriticalSection( &req->headers_section );
2149 TRACE("INTERNET_OPTION_URL: %s\n",debugstr_w(url));
2150 return str_to_buffer(url, buffer, size, unicode);
2152 case INTERNET_OPTION_USER_AGENT:
2153 return str_to_buffer(req->session->appInfo->agent, buffer, size, unicode);
2154 case INTERNET_OPTION_USERNAME:
2155 return str_to_buffer(req->session->userName, buffer, size, unicode);
2156 case INTERNET_OPTION_PASSWORD:
2157 return str_to_buffer(req->session->password, buffer, size, unicode);
2158 case INTERNET_OPTION_PROXY_USERNAME:
2159 return str_to_buffer(req->session->appInfo->proxyUsername, buffer, size, unicode);
2160 case INTERNET_OPTION_PROXY_PASSWORD:
2161 return str_to_buffer(req->session->appInfo->proxyPassword, buffer, size, unicode);
2163 case INTERNET_OPTION_CACHE_TIMESTAMPS: {
2164 INTERNET_CACHE_ENTRY_INFOW *info;
2165 INTERNET_CACHE_TIMESTAMPS *ts = buffer;
2166 WCHAR url[INTERNET_MAX_URL_LENGTH];
2167 DWORD nbytes, error;
2168 BOOL ret;
2170 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2172 if (*size < sizeof(*ts))
2174 *size = sizeof(*ts);
2175 return ERROR_INSUFFICIENT_BUFFER;
2177 nbytes = 0;
2178 HTTP_GetRequestURL(req, url);
2179 ret = GetUrlCacheEntryInfoW(url, NULL, &nbytes);
2180 error = GetLastError();
2181 if (!ret && error == ERROR_INSUFFICIENT_BUFFER)
2183 if (!(info = heap_alloc(nbytes)))
2184 return ERROR_OUTOFMEMORY;
2186 GetUrlCacheEntryInfoW(url, info, &nbytes);
2188 ts->ftExpires = info->ExpireTime;
2189 ts->ftLastModified = info->LastModifiedTime;
2191 heap_free(info);
2192 *size = sizeof(*ts);
2193 return ERROR_SUCCESS;
2195 return error;
2198 case INTERNET_OPTION_DATAFILE_NAME: {
2199 DWORD req_size;
2201 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2203 if(!req->req_file) {
2204 *size = 0;
2205 return ERROR_INTERNET_ITEM_NOT_FOUND;
2208 if(unicode) {
2209 req_size = (lstrlenW(req->req_file->file_name)+1) * sizeof(WCHAR);
2210 if(*size < req_size)
2211 return ERROR_INSUFFICIENT_BUFFER;
2213 *size = req_size;
2214 memcpy(buffer, req->req_file->file_name, *size);
2215 return ERROR_SUCCESS;
2216 }else {
2217 req_size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name, -1, NULL, 0, NULL, NULL);
2218 if (req_size > *size)
2219 return ERROR_INSUFFICIENT_BUFFER;
2221 *size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name,
2222 -1, buffer, *size, NULL, NULL);
2223 return ERROR_SUCCESS;
2227 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
2228 PCCERT_CONTEXT context;
2230 if(!req->netconn)
2231 return ERROR_INTERNET_INVALID_OPERATION;
2233 if(*size < sizeof(INTERNET_CERTIFICATE_INFOA)) {
2234 *size = sizeof(INTERNET_CERTIFICATE_INFOA);
2235 return ERROR_INSUFFICIENT_BUFFER;
2238 context = (PCCERT_CONTEXT)NETCON_GetCert(req->netconn);
2239 if(context) {
2240 INTERNET_CERTIFICATE_INFOA *info = (INTERNET_CERTIFICATE_INFOA*)buffer;
2241 DWORD len;
2243 memset(info, 0, sizeof(*info));
2244 info->ftExpiry = context->pCertInfo->NotAfter;
2245 info->ftStart = context->pCertInfo->NotBefore;
2246 len = CertNameToStrA(context->dwCertEncodingType,
2247 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2248 info->lpszSubjectInfo = LocalAlloc(0, len);
2249 if(info->lpszSubjectInfo)
2250 CertNameToStrA(context->dwCertEncodingType,
2251 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2252 info->lpszSubjectInfo, len);
2253 len = CertNameToStrA(context->dwCertEncodingType,
2254 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2255 info->lpszIssuerInfo = LocalAlloc(0, len);
2256 if(info->lpszIssuerInfo)
2257 CertNameToStrA(context->dwCertEncodingType,
2258 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2259 info->lpszIssuerInfo, len);
2260 info->dwKeySize = NETCON_GetCipherStrength(req->netconn);
2261 CertFreeCertificateContext(context);
2262 return ERROR_SUCCESS;
2264 return ERROR_NOT_SUPPORTED;
2266 case INTERNET_OPTION_CONNECT_TIMEOUT:
2267 if (*size < sizeof(DWORD))
2268 return ERROR_INSUFFICIENT_BUFFER;
2270 *size = sizeof(DWORD);
2271 *(DWORD *)buffer = req->connect_timeout;
2272 return ERROR_SUCCESS;
2273 case INTERNET_OPTION_REQUEST_FLAGS: {
2274 DWORD flags = 0;
2276 if (*size < sizeof(DWORD))
2277 return ERROR_INSUFFICIENT_BUFFER;
2279 /* FIXME: Add support for:
2280 * INTERNET_REQFLAG_FROM_CACHE
2281 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2284 if(req->proxy)
2285 flags |= INTERNET_REQFLAG_VIA_PROXY;
2286 if(!req->status_code)
2287 flags |= INTERNET_REQFLAG_NO_HEADERS;
2289 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags);
2291 *size = sizeof(DWORD);
2292 *(DWORD*)buffer = flags;
2293 return ERROR_SUCCESS;
2297 return INET_QueryOption(hdr, option, buffer, size, unicode);
2300 static DWORD HTTPREQ_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
2302 http_request_t *req = (http_request_t*)hdr;
2304 switch(option) {
2305 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2306 TRACE("Undocumented option 99\n");
2308 if (!buffer || size != sizeof(DWORD))
2309 return ERROR_INVALID_PARAMETER;
2310 if(*(DWORD*)buffer & ~SECURITY_SET_MASK)
2311 return ERROR_INTERNET_OPTION_NOT_SETTABLE;
2313 /* fall through */
2314 case INTERNET_OPTION_SECURITY_FLAGS:
2316 DWORD flags;
2318 if (!buffer || size != sizeof(DWORD))
2319 return ERROR_INVALID_PARAMETER;
2320 flags = *(DWORD *)buffer;
2321 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags);
2322 flags &= SECURITY_SET_MASK;
2323 req->security_flags |= flags;
2324 if(is_valid_netconn(req->netconn))
2325 req->netconn->security_flags |= flags;
2326 return ERROR_SUCCESS;
2328 case INTERNET_OPTION_CONNECT_TIMEOUT:
2329 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2330 req->connect_timeout = *(DWORD *)buffer;
2331 return ERROR_SUCCESS;
2333 case INTERNET_OPTION_SEND_TIMEOUT:
2334 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2335 req->send_timeout = *(DWORD *)buffer;
2336 return ERROR_SUCCESS;
2338 case INTERNET_OPTION_RECEIVE_TIMEOUT:
2339 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2340 req->receive_timeout = *(DWORD *)buffer;
2341 return ERROR_SUCCESS;
2343 case INTERNET_OPTION_USERNAME:
2344 heap_free(req->session->userName);
2345 if (!(req->session->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2346 return ERROR_SUCCESS;
2348 case INTERNET_OPTION_PASSWORD:
2349 heap_free(req->session->password);
2350 if (!(req->session->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2351 return ERROR_SUCCESS;
2353 case INTERNET_OPTION_PROXY_USERNAME:
2354 heap_free(req->session->appInfo->proxyUsername);
2355 if (!(req->session->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2356 return ERROR_SUCCESS;
2358 case INTERNET_OPTION_PROXY_PASSWORD:
2359 heap_free(req->session->appInfo->proxyPassword);
2360 if (!(req->session->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2361 return ERROR_SUCCESS;
2363 case INTERNET_OPTION_HTTP_DECODING:
2364 if(size != sizeof(BOOL))
2365 return ERROR_INVALID_PARAMETER;
2366 req->decoding = *(BOOL*)buffer;
2367 return ERROR_SUCCESS;
2370 return INET_SetOption(hdr, option, buffer, size);
2373 static void commit_cache_entry(http_request_t *req)
2375 WCHAR url[INTERNET_MAX_URL_LENGTH];
2377 TRACE("%p\n", req);
2379 CloseHandle(req->hCacheFile);
2380 req->hCacheFile = NULL;
2382 if(HTTP_GetRequestURL(req, url)) {
2383 WCHAR *header;
2384 DWORD header_len;
2385 BOOL res;
2387 header = build_response_header(req, TRUE);
2388 header_len = (header ? strlenW(header) : 0);
2389 res = CommitUrlCacheEntryW(url, req->req_file->file_name, req->expires,
2390 req->last_modified, NORMAL_CACHE_ENTRY,
2391 header, header_len, NULL, 0);
2392 if(res)
2393 req->req_file->is_committed = TRUE;
2394 else
2395 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2396 heap_free(header);
2400 static void create_cache_entry(http_request_t *req)
2402 static const WCHAR no_cacheW[] = {'n','o','-','c','a','c','h','e',0};
2403 static const WCHAR no_storeW[] = {'n','o','-','s','t','o','r','e',0};
2405 WCHAR url[INTERNET_MAX_URL_LENGTH];
2406 WCHAR file_name[MAX_PATH+1];
2407 BOOL b = TRUE;
2409 /* FIXME: We should free previous cache file earlier */
2410 if(req->req_file) {
2411 req_file_release(req->req_file);
2412 req->req_file = NULL;
2414 if(req->hCacheFile) {
2415 CloseHandle(req->hCacheFile);
2416 req->hCacheFile = NULL;
2419 if(req->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE)
2420 b = FALSE;
2422 if(b) {
2423 int header_idx;
2425 EnterCriticalSection( &req->headers_section );
2427 header_idx = HTTP_GetCustomHeaderIndex(req, szCache_Control, 0, FALSE);
2428 if(header_idx != -1) {
2429 WCHAR *ptr;
2431 for(ptr=req->custHeaders[header_idx].lpszValue; *ptr; ) {
2432 WCHAR *end;
2434 while(*ptr==' ' || *ptr=='\t')
2435 ptr++;
2437 end = strchrW(ptr, ',');
2438 if(!end)
2439 end = ptr + strlenW(ptr);
2441 if(!strncmpiW(ptr, no_cacheW, sizeof(no_cacheW)/sizeof(*no_cacheW)-1)
2442 || !strncmpiW(ptr, no_storeW, sizeof(no_storeW)/sizeof(*no_storeW)-1)) {
2443 b = FALSE;
2444 break;
2447 ptr = end;
2448 if(*ptr == ',')
2449 ptr++;
2453 LeaveCriticalSection( &req->headers_section );
2456 if(!b) {
2457 if(!(req->hdr.dwFlags & INTERNET_FLAG_NEED_FILE))
2458 return;
2460 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2463 b = HTTP_GetRequestURL(req, url);
2464 if(!b) {
2465 WARN("Could not get URL\n");
2466 return;
2469 b = CreateUrlCacheEntryW(url, req->contentLength == ~0u ? 0 : req->contentLength, NULL, file_name, 0);
2470 if(!b) {
2471 WARN("Could not create cache entry: %08x\n", GetLastError());
2472 return;
2475 create_req_file(file_name, &req->req_file);
2477 req->hCacheFile = CreateFileW(file_name, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
2478 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2479 if(req->hCacheFile == INVALID_HANDLE_VALUE) {
2480 WARN("Could not create file: %u\n", GetLastError());
2481 req->hCacheFile = NULL;
2482 return;
2485 if(req->read_size) {
2486 DWORD written;
2488 b = WriteFile(req->hCacheFile, req->read_buf+req->read_pos, req->read_size, &written, NULL);
2489 if(!b)
2490 FIXME("WriteFile failed: %u\n", GetLastError());
2492 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2493 commit_cache_entry(req);
2497 /* read some more data into the read buffer (the read section must be held) */
2498 static DWORD read_more_data( http_request_t *req, int maxlen )
2500 DWORD res;
2501 int len;
2503 if (req->read_pos)
2505 /* move existing data to the start of the buffer */
2506 if(req->read_size)
2507 memmove( req->read_buf, req->read_buf + req->read_pos, req->read_size );
2508 req->read_pos = 0;
2511 if (maxlen == -1) maxlen = sizeof(req->read_buf);
2513 res = NETCON_recv( req->netconn, req->read_buf + req->read_size,
2514 maxlen - req->read_size, BLOCKING_ALLOW, &len );
2515 if(res == ERROR_SUCCESS)
2516 req->read_size += len;
2518 return res;
2521 /* remove some amount of data from the read buffer (the read section must be held) */
2522 static void remove_data( http_request_t *req, int count )
2524 if (!(req->read_size -= count)) req->read_pos = 0;
2525 else req->read_pos += count;
2528 static DWORD read_line( http_request_t *req, LPSTR buffer, DWORD *len )
2530 int count, bytes_read, pos = 0;
2531 DWORD res;
2533 EnterCriticalSection( &req->read_section );
2534 for (;;)
2536 BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
2538 if (eol)
2540 count = eol - (req->read_buf + req->read_pos);
2541 bytes_read = count + 1;
2543 else count = bytes_read = req->read_size;
2545 count = min( count, *len - pos );
2546 memcpy( buffer + pos, req->read_buf + req->read_pos, count );
2547 pos += count;
2548 remove_data( req, bytes_read );
2549 if (eol) break;
2551 if ((res = read_more_data( req, -1 )))
2553 WARN( "read failed %u\n", res );
2554 LeaveCriticalSection( &req->read_section );
2555 return res;
2557 if (!req->read_size)
2559 *len = 0;
2560 TRACE( "returning empty string\n" );
2561 LeaveCriticalSection( &req->read_section );
2562 return ERROR_SUCCESS;
2565 LeaveCriticalSection( &req->read_section );
2567 if (pos < *len)
2569 if (pos && buffer[pos - 1] == '\r') pos--;
2570 *len = pos + 1;
2572 buffer[*len - 1] = 0;
2573 TRACE( "returning %s\n", debugstr_a(buffer));
2574 return ERROR_SUCCESS;
2577 /* check if we have reached the end of the data to read (the read section must be held) */
2578 static BOOL end_of_read_data( http_request_t *req )
2580 return !req->read_size && req->data_stream->vtbl->end_of_data(req->data_stream, req);
2583 static DWORD read_http_stream(http_request_t *req, BYTE *buf, DWORD size, DWORD *read, blocking_mode_t blocking_mode)
2585 DWORD res;
2587 res = req->data_stream->vtbl->read(req->data_stream, req, buf, size, read, blocking_mode);
2588 assert(*read <= size);
2590 if(req->hCacheFile) {
2591 if(*read) {
2592 BOOL bres;
2593 DWORD written;
2595 bres = WriteFile(req->hCacheFile, buf, *read, &written, NULL);
2596 if(!bres)
2597 FIXME("WriteFile failed: %u\n", GetLastError());
2600 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2601 commit_cache_entry(req);
2604 return res;
2607 /* fetch some more data into the read buffer (the read section must be held) */
2608 static DWORD refill_read_buffer(http_request_t *req, blocking_mode_t blocking_mode, DWORD *read_bytes)
2610 DWORD res, read=0;
2612 if(req->read_size == sizeof(req->read_buf))
2613 return ERROR_SUCCESS;
2615 if(req->read_pos) {
2616 if(req->read_size)
2617 memmove(req->read_buf, req->read_buf+req->read_pos, req->read_size);
2618 req->read_pos = 0;
2621 res = read_http_stream(req, req->read_buf+req->read_size, sizeof(req->read_buf) - req->read_size,
2622 &read, blocking_mode);
2623 req->read_size += read;
2625 TRACE("read %u bytes, read_size %u\n", read, req->read_size);
2626 if(read_bytes)
2627 *read_bytes = read;
2628 return res;
2631 /* return the size of data available to be read immediately (the read section must be held) */
2632 static DWORD get_avail_data( http_request_t *req )
2634 return req->read_size + req->data_stream->vtbl->get_avail_data(req->data_stream, req);
2637 static DWORD netconn_get_avail_data(data_stream_t *stream, http_request_t *req)
2639 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2640 DWORD avail = 0;
2642 if(is_valid_netconn(req->netconn))
2643 NETCON_query_data_available(req->netconn, &avail);
2644 return netconn_stream->content_length == ~0u
2645 ? avail
2646 : min(avail, netconn_stream->content_length-netconn_stream->content_read);
2649 static BOOL netconn_end_of_data(data_stream_t *stream, http_request_t *req)
2651 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2652 return netconn_stream->content_read == netconn_stream->content_length || !is_valid_netconn(req->netconn);
2655 static DWORD netconn_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2656 DWORD *read, blocking_mode_t blocking_mode)
2658 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2659 DWORD res = ERROR_SUCCESS;
2660 int len = 0;
2662 size = min(size, netconn_stream->content_length-netconn_stream->content_read);
2664 if(size && is_valid_netconn(req->netconn)) {
2665 if((res = NETCON_recv(req->netconn, buf, size, blocking_mode, &len))) {
2666 len = 0;
2667 if(blocking_mode == BLOCKING_DISALLOW && res == WSAEWOULDBLOCK)
2668 res = ERROR_SUCCESS;
2669 else
2670 netconn_stream->content_length = netconn_stream->content_read;
2671 }else if(!len) {
2672 netconn_stream->content_length = netconn_stream->content_read;
2676 netconn_stream->content_read += *read = len;
2677 TRACE("read %u bytes\n", len);
2678 return res;
2681 static BOOL netconn_drain_content(data_stream_t *stream, http_request_t *req)
2683 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2684 BYTE buf[1024];
2685 int len;
2687 if(netconn_end_of_data(stream, req))
2688 return TRUE;
2690 do {
2691 if(NETCON_recv(req->netconn, buf, sizeof(buf), BLOCKING_DISALLOW, &len) != ERROR_SUCCESS)
2692 return FALSE;
2694 netconn_stream->content_read += len;
2695 }while(netconn_stream->content_read < netconn_stream->content_length);
2697 return TRUE;
2700 static void netconn_destroy(data_stream_t *stream)
2704 static const data_stream_vtbl_t netconn_stream_vtbl = {
2705 netconn_get_avail_data,
2706 netconn_end_of_data,
2707 netconn_read,
2708 netconn_drain_content,
2709 netconn_destroy
2712 /* read some more data into the read buffer (the read section must be held) */
2713 static DWORD read_more_chunked_data(chunked_stream_t *stream, http_request_t *req, int maxlen)
2715 DWORD res;
2716 int len;
2718 assert(!stream->end_of_data);
2720 if (stream->buf_pos)
2722 /* move existing data to the start of the buffer */
2723 if(stream->buf_size)
2724 memmove(stream->buf, stream->buf + stream->buf_pos, stream->buf_size);
2725 stream->buf_pos = 0;
2728 if (maxlen == -1) maxlen = sizeof(stream->buf);
2730 res = NETCON_recv( req->netconn, stream->buf + stream->buf_size,
2731 maxlen - stream->buf_size, BLOCKING_ALLOW, &len );
2732 if(res == ERROR_SUCCESS)
2733 stream->buf_size += len;
2735 return res;
2738 /* remove some amount of data from the read buffer (the read section must be held) */
2739 static void remove_chunked_data(chunked_stream_t *stream, int count)
2741 if (!(stream->buf_size -= count)) stream->buf_pos = 0;
2742 else stream->buf_pos += count;
2745 /* discard data contents until we reach end of line (the read section must be held) */
2746 static DWORD discard_chunked_eol(chunked_stream_t *stream, http_request_t *req)
2748 DWORD res;
2752 BYTE *eol = memchr(stream->buf + stream->buf_pos, '\n', stream->buf_size);
2753 if (eol)
2755 remove_chunked_data(stream, (eol + 1) - (stream->buf + stream->buf_pos));
2756 break;
2758 stream->buf_pos = stream->buf_size = 0; /* discard everything */
2759 if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
2760 } while (stream->buf_size);
2761 return ERROR_SUCCESS;
2764 /* read the size of the next chunk (the read section must be held) */
2765 static DWORD start_next_chunk(chunked_stream_t *stream, http_request_t *req)
2767 DWORD chunk_size = 0, res;
2769 assert(!stream->chunk_size || stream->chunk_size == ~0u);
2771 if (stream->end_of_data) return ERROR_SUCCESS;
2773 /* read terminator for the previous chunk */
2774 if(!stream->chunk_size && (res = discard_chunked_eol(stream, req)) != ERROR_SUCCESS)
2775 return res;
2777 for (;;)
2779 while (stream->buf_size)
2781 char ch = stream->buf[stream->buf_pos];
2782 if (ch >= '0' && ch <= '9') chunk_size = chunk_size * 16 + ch - '0';
2783 else if (ch >= 'a' && ch <= 'f') chunk_size = chunk_size * 16 + ch - 'a' + 10;
2784 else if (ch >= 'A' && ch <= 'F') chunk_size = chunk_size * 16 + ch - 'A' + 10;
2785 else if (ch == ';' || ch == '\r' || ch == '\n')
2787 TRACE( "reading %u byte chunk\n", chunk_size );
2788 stream->chunk_size = chunk_size;
2789 if (req->contentLength == ~0u) req->contentLength = chunk_size;
2790 else req->contentLength += chunk_size;
2792 if (!chunk_size) stream->end_of_data = TRUE;
2793 return discard_chunked_eol(stream, req);
2795 remove_chunked_data(stream, 1);
2797 if ((res = read_more_chunked_data(stream, req, -1)) != ERROR_SUCCESS) return res;
2798 if (!stream->buf_size)
2800 stream->chunk_size = 0;
2801 return ERROR_SUCCESS;
2806 static DWORD chunked_get_avail_data(data_stream_t *stream, http_request_t *req)
2808 /* Allow reading only from read buffer */
2809 return 0;
2812 static BOOL chunked_end_of_data(data_stream_t *stream, http_request_t *req)
2814 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2815 return chunked_stream->end_of_data;
2818 static DWORD chunked_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2819 DWORD *read, blocking_mode_t blocking_mode)
2821 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2822 DWORD read_bytes = 0, ret_read = 0, res = ERROR_SUCCESS;
2824 if(!chunked_stream->chunk_size || chunked_stream->chunk_size == ~0u) {
2825 res = start_next_chunk(chunked_stream, req);
2826 if(res != ERROR_SUCCESS)
2827 return res;
2830 while(size && chunked_stream->chunk_size && !chunked_stream->end_of_data) {
2831 if(chunked_stream->buf_size) {
2832 read_bytes = min(size, min(chunked_stream->buf_size, chunked_stream->chunk_size));
2834 /* this could block */
2835 if(blocking_mode == BLOCKING_DISALLOW && read_bytes == chunked_stream->chunk_size)
2836 break;
2838 memcpy(buf+ret_read, chunked_stream->buf+chunked_stream->buf_pos, read_bytes);
2839 remove_chunked_data(chunked_stream, read_bytes);
2840 }else {
2841 read_bytes = min(size, chunked_stream->chunk_size);
2843 if(blocking_mode == BLOCKING_DISALLOW) {
2844 DWORD avail;
2846 if(!is_valid_netconn(req->netconn) || !NETCON_query_data_available(req->netconn, &avail) || !avail)
2847 break;
2848 if(read_bytes > avail)
2849 read_bytes = avail;
2851 /* this could block */
2852 if(read_bytes == chunked_stream->chunk_size)
2853 break;
2856 res = NETCON_recv(req->netconn, (char *)buf+ret_read, read_bytes, BLOCKING_ALLOW, (int*)&read_bytes);
2857 if(res != ERROR_SUCCESS)
2858 break;
2861 chunked_stream->chunk_size -= read_bytes;
2862 size -= read_bytes;
2863 ret_read += read_bytes;
2864 if(size && !chunked_stream->chunk_size) {
2865 assert(blocking_mode != BLOCKING_DISALLOW);
2866 res = start_next_chunk(chunked_stream, req);
2867 if(res != ERROR_SUCCESS)
2868 break;
2871 if(blocking_mode == BLOCKING_ALLOW)
2872 blocking_mode = BLOCKING_DISALLOW;
2875 TRACE("read %u bytes\n", ret_read);
2876 *read = ret_read;
2877 return res;
2880 static BOOL chunked_drain_content(data_stream_t *stream, http_request_t *req)
2882 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2884 remove_chunked_data(chunked_stream, chunked_stream->buf_size);
2885 return chunked_stream->end_of_data;
2888 static void chunked_destroy(data_stream_t *stream)
2890 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2891 heap_free(chunked_stream);
2894 static const data_stream_vtbl_t chunked_stream_vtbl = {
2895 chunked_get_avail_data,
2896 chunked_end_of_data,
2897 chunked_read,
2898 chunked_drain_content,
2899 chunked_destroy
2902 /* set the request content length based on the headers */
2903 static DWORD set_content_length(http_request_t *request)
2905 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
2906 static const WCHAR headW[] = {'H','E','A','D',0};
2907 WCHAR encoding[20];
2908 DWORD size;
2910 if(request->status_code == HTTP_STATUS_NO_CONTENT || !strcmpW(request->verb, headW)) {
2911 request->contentLength = request->netconn_stream.content_length = 0;
2912 return ERROR_SUCCESS;
2915 size = sizeof(request->contentLength);
2916 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2917 &request->contentLength, &size, NULL) != ERROR_SUCCESS)
2918 request->contentLength = ~0u;
2919 request->netconn_stream.content_length = request->contentLength;
2920 request->netconn_stream.content_read = request->read_size;
2922 size = sizeof(encoding);
2923 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) == ERROR_SUCCESS &&
2924 !strcmpiW(encoding, szChunked))
2926 chunked_stream_t *chunked_stream;
2928 chunked_stream = heap_alloc(sizeof(*chunked_stream));
2929 if(!chunked_stream)
2930 return ERROR_OUTOFMEMORY;
2932 chunked_stream->data_stream.vtbl = &chunked_stream_vtbl;
2933 chunked_stream->buf_size = chunked_stream->buf_pos = 0;
2934 chunked_stream->chunk_size = ~0u;
2935 chunked_stream->end_of_data = FALSE;
2937 if(request->read_size) {
2938 memcpy(chunked_stream->buf, request->read_buf+request->read_pos, request->read_size);
2939 chunked_stream->buf_size = request->read_size;
2940 request->read_size = request->read_pos = 0;
2943 request->data_stream = &chunked_stream->data_stream;
2944 request->contentLength = ~0u;
2945 request->read_chunked = TRUE;
2948 if(request->decoding) {
2949 int encoding_idx;
2951 static const WCHAR deflateW[] = {'d','e','f','l','a','t','e',0};
2952 static const WCHAR gzipW[] = {'g','z','i','p',0};
2954 EnterCriticalSection( &request->headers_section );
2956 encoding_idx = HTTP_GetCustomHeaderIndex(request, szContent_Encoding, 0, FALSE);
2957 if(encoding_idx != -1) {
2958 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, gzipW)) {
2959 HTTP_DeleteCustomHeader(request, encoding_idx);
2960 LeaveCriticalSection( &request->headers_section );
2961 return init_gzip_stream(request, TRUE);
2963 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, deflateW)) {
2964 HTTP_DeleteCustomHeader(request, encoding_idx);
2965 LeaveCriticalSection( &request->headers_section );
2966 return init_gzip_stream(request, FALSE);
2970 LeaveCriticalSection( &request->headers_section );
2973 return ERROR_SUCCESS;
2976 static void send_request_complete(http_request_t *req, DWORD_PTR result, DWORD error)
2978 INTERNET_ASYNC_RESULT iar;
2980 iar.dwResult = result;
2981 iar.dwError = error;
2983 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2984 sizeof(INTERNET_ASYNC_RESULT));
2987 static void HTTP_ReceiveRequestData(http_request_t *req, BOOL first_notif, DWORD *ret_size)
2989 DWORD res, read = 0, avail = 0;
2990 blocking_mode_t mode;
2992 TRACE("%p\n", req);
2994 EnterCriticalSection( &req->read_section );
2996 mode = first_notif && req->read_size ? BLOCKING_DISALLOW : BLOCKING_ALLOW;
2997 res = refill_read_buffer(req, mode, &read);
2998 if(res == ERROR_SUCCESS)
2999 avail = get_avail_data(req);
3001 LeaveCriticalSection( &req->read_section );
3003 if(res != ERROR_SUCCESS || (mode != BLOCKING_DISALLOW && !read)) {
3004 WARN("res %u read %u, closing connection\n", res, read);
3005 http_release_netconn(req, FALSE);
3008 if(res != ERROR_SUCCESS) {
3009 send_request_complete(req, 0, res);
3010 return;
3013 if(ret_size)
3014 *ret_size = avail;
3015 if(first_notif)
3016 avail = 0;
3018 send_request_complete(req, req->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)req->hdr.hInternet : 1, avail);
3021 /* read data from the http connection (the read section must be held) */
3022 static DWORD HTTPREQ_Read(http_request_t *req, void *buffer, DWORD size, DWORD *read, BOOL sync)
3024 DWORD current_read = 0, ret_read = 0;
3025 blocking_mode_t blocking_mode;
3026 DWORD res = ERROR_SUCCESS;
3028 blocking_mode = req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC ? BLOCKING_ALLOW : BLOCKING_WAITALL;
3030 EnterCriticalSection( &req->read_section );
3032 if(req->read_size) {
3033 ret_read = min(size, req->read_size);
3034 memcpy(buffer, req->read_buf+req->read_pos, ret_read);
3035 req->read_size -= ret_read;
3036 req->read_pos += ret_read;
3037 if(blocking_mode == BLOCKING_ALLOW)
3038 blocking_mode = BLOCKING_DISALLOW;
3041 if(ret_read < size) {
3042 res = read_http_stream(req, (BYTE*)buffer+ret_read, size-ret_read, &current_read, blocking_mode);
3043 ret_read += current_read;
3046 LeaveCriticalSection( &req->read_section );
3048 *read = ret_read;
3049 TRACE( "retrieved %u bytes (%u)\n", ret_read, req->contentLength );
3051 if(size && !ret_read)
3052 http_release_netconn(req, res == ERROR_SUCCESS);
3054 return res;
3057 static BOOL drain_content(http_request_t *req, BOOL blocking)
3059 BOOL ret;
3061 if(!is_valid_netconn(req->netconn) || req->contentLength == -1)
3062 return FALSE;
3064 if(!strcmpW(req->verb, szHEAD))
3065 return TRUE;
3067 if(!blocking)
3068 return req->data_stream->vtbl->drain_content(req->data_stream, req);
3070 EnterCriticalSection( &req->read_section );
3072 while(1) {
3073 DWORD bytes_read, res;
3074 BYTE buf[4096];
3076 res = HTTPREQ_Read(req, buf, sizeof(buf), &bytes_read, TRUE);
3077 if(res != ERROR_SUCCESS) {
3078 ret = FALSE;
3079 break;
3081 if(!bytes_read) {
3082 ret = TRUE;
3083 break;
3087 LeaveCriticalSection( &req->read_section );
3088 return ret;
3091 static DWORD HTTPREQ_ReadFile(object_header_t *hdr, void *buffer, DWORD size, DWORD *read)
3093 http_request_t *req = (http_request_t*)hdr;
3094 DWORD res;
3096 EnterCriticalSection( &req->read_section );
3097 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3098 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3100 res = HTTPREQ_Read(req, buffer, size, read, TRUE);
3101 if(res == ERROR_SUCCESS)
3102 res = hdr->dwError;
3103 LeaveCriticalSection( &req->read_section );
3105 return res;
3108 typedef struct {
3109 task_header_t hdr;
3110 void *buf;
3111 DWORD size;
3112 DWORD *ret_read;
3113 } read_file_ex_task_t;
3115 static void AsyncReadFileExProc(task_header_t *hdr)
3117 read_file_ex_task_t *task = (read_file_ex_task_t*)hdr;
3118 http_request_t *req = (http_request_t*)task->hdr.hdr;
3119 DWORD res;
3121 TRACE("INTERNETREADFILEEXW %p\n", task->hdr.hdr);
3123 res = HTTPREQ_Read(req, task->buf, task->size, task->ret_read, TRUE);
3124 send_request_complete(req, res == ERROR_SUCCESS, res);
3127 static DWORD HTTPREQ_ReadFileEx(object_header_t *hdr, void *buf, DWORD size, DWORD *ret_read,
3128 DWORD flags, DWORD_PTR context)
3131 http_request_t *req = (http_request_t*)hdr;
3132 DWORD res, read, cread, error = ERROR_SUCCESS;
3134 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3135 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3137 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3139 if (hdr->dwFlags & INTERNET_FLAG_ASYNC)
3141 read_file_ex_task_t *task;
3143 if (TryEnterCriticalSection( &req->read_section ))
3145 if (get_avail_data(req))
3147 res = HTTPREQ_Read(req, buf, size, &read, FALSE);
3148 LeaveCriticalSection( &req->read_section );
3149 goto done;
3151 LeaveCriticalSection( &req->read_section );
3154 task = alloc_async_task(&req->hdr, AsyncReadFileExProc, sizeof(*task));
3155 task->buf = buf;
3156 task->size = size;
3157 task->ret_read = ret_read;
3159 INTERNET_AsyncCall(&task->hdr);
3161 return ERROR_IO_PENDING;
3164 read = 0;
3166 EnterCriticalSection( &req->read_section );
3167 if(hdr->dwError == ERROR_SUCCESS)
3168 hdr->dwError = INTERNET_HANDLE_IN_USE;
3169 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3170 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3172 while(1) {
3173 res = HTTPREQ_Read(req, (char*)buf+read, size-read, &cread, !(flags & IRF_NO_WAIT));
3174 if(res != ERROR_SUCCESS)
3175 break;
3177 read += cread;
3178 if(read == size || end_of_read_data(req))
3179 break;
3181 LeaveCriticalSection( &req->read_section );
3183 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3184 &cread, sizeof(cread));
3185 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
3186 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3188 EnterCriticalSection( &req->read_section );
3191 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3192 hdr->dwError = ERROR_SUCCESS;
3193 else
3194 error = hdr->dwError;
3196 LeaveCriticalSection( &req->read_section );
3198 done:
3199 *ret_read = read;
3200 if (res == ERROR_SUCCESS) {
3201 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3202 &read, sizeof(read));
3205 return res==ERROR_SUCCESS ? error : res;
3208 static DWORD HTTPREQ_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
3210 DWORD res;
3211 http_request_t *request = (http_request_t*)hdr;
3213 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3215 *written = 0;
3216 res = NETCON_send(request->netconn, buffer, size, 0, (LPINT)written);
3217 if (res == ERROR_SUCCESS)
3218 request->bytesWritten += *written;
3220 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
3221 return res;
3224 typedef struct {
3225 task_header_t hdr;
3226 DWORD *ret_size;
3227 } http_data_available_task_t;
3229 static void AsyncQueryDataAvailableProc(task_header_t *hdr)
3231 http_data_available_task_t *task = (http_data_available_task_t*)hdr;
3233 HTTP_ReceiveRequestData((http_request_t*)task->hdr.hdr, FALSE, task->ret_size);
3236 static DWORD HTTPREQ_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
3238 http_request_t *req = (http_request_t*)hdr;
3240 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
3242 if (req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3244 http_data_available_task_t *task;
3246 /* never wait, if we can't enter the section we queue an async request right away */
3247 if (TryEnterCriticalSection( &req->read_section ))
3249 refill_read_buffer(req, BLOCKING_DISALLOW, NULL);
3250 if ((*available = get_avail_data( req ))) goto done;
3251 if (end_of_read_data( req )) goto done;
3252 LeaveCriticalSection( &req->read_section );
3255 task = alloc_async_task(&req->hdr, AsyncQueryDataAvailableProc, sizeof(*task));
3256 task->ret_size = available;
3257 INTERNET_AsyncCall(&task->hdr);
3258 return ERROR_IO_PENDING;
3261 EnterCriticalSection( &req->read_section );
3263 if (!(*available = get_avail_data( req )) && !end_of_read_data( req ))
3265 refill_read_buffer( req, BLOCKING_ALLOW, NULL );
3266 *available = get_avail_data( req );
3269 done:
3270 LeaveCriticalSection( &req->read_section );
3272 TRACE( "returning %u\n", *available );
3273 return ERROR_SUCCESS;
3276 static DWORD HTTPREQ_LockRequestFile(object_header_t *hdr, req_file_t **ret)
3278 http_request_t *req = (http_request_t*)hdr;
3280 TRACE("(%p)\n", req);
3282 if(!req->req_file) {
3283 WARN("No cache file name available\n");
3284 return ERROR_FILE_NOT_FOUND;
3287 *ret = req_file_addref(req->req_file);
3288 return ERROR_SUCCESS;
3291 static const object_vtbl_t HTTPREQVtbl = {
3292 HTTPREQ_Destroy,
3293 HTTPREQ_CloseConnection,
3294 HTTPREQ_QueryOption,
3295 HTTPREQ_SetOption,
3296 HTTPREQ_ReadFile,
3297 HTTPREQ_ReadFileEx,
3298 HTTPREQ_WriteFile,
3299 HTTPREQ_QueryDataAvailable,
3300 NULL,
3301 HTTPREQ_LockRequestFile
3304 /***********************************************************************
3305 * HTTP_HttpOpenRequestW (internal)
3307 * Open a HTTP request handle
3309 * RETURNS
3310 * HINTERNET a HTTP request handle on success
3311 * NULL on failure
3314 static DWORD HTTP_HttpOpenRequestW(http_session_t *session,
3315 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3316 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3317 DWORD dwFlags, DWORD_PTR dwContext, HINTERNET *ret)
3319 appinfo_t *hIC = session->appInfo;
3320 http_request_t *request;
3321 DWORD len;
3323 TRACE("-->\n");
3325 request = alloc_object(&session->hdr, &HTTPREQVtbl, sizeof(http_request_t));
3326 if(!request)
3327 return ERROR_OUTOFMEMORY;
3329 request->hdr.htype = WH_HHTTPREQ;
3330 request->hdr.dwFlags = dwFlags;
3331 request->hdr.dwContext = dwContext;
3332 request->contentLength = ~0u;
3334 request->netconn_stream.data_stream.vtbl = &netconn_stream_vtbl;
3335 request->data_stream = &request->netconn_stream.data_stream;
3336 request->connect_timeout = session->connect_timeout;
3337 request->send_timeout = session->send_timeout;
3338 request->receive_timeout = session->receive_timeout;
3340 InitializeCriticalSection( &request->headers_section );
3341 request->headers_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.headers_section");
3343 InitializeCriticalSection( &request->read_section );
3344 request->read_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.read_section");
3346 WININET_AddRef( &session->hdr );
3347 request->session = session;
3348 list_add_head( &session->hdr.children, &request->hdr.entry );
3350 request->server = get_server(session->hostName, session->hostPort, (dwFlags & INTERNET_FLAG_SECURE) != 0, TRUE);
3351 if(!request->server) {
3352 WININET_Release(&request->hdr);
3353 return ERROR_OUTOFMEMORY;
3356 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_CN_INVALID)
3357 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
3358 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_DATE_INVALID)
3359 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
3361 if (lpszObjectName && *lpszObjectName) {
3362 HRESULT rc;
3364 len = 0;
3365 rc = UrlEscapeW(lpszObjectName, NULL, &len, URL_ESCAPE_SPACES_ONLY);
3366 if (rc != E_POINTER)
3367 len = strlenW(lpszObjectName)+1;
3368 request->path = heap_alloc(len*sizeof(WCHAR));
3369 rc = UrlEscapeW(lpszObjectName, request->path, &len,
3370 URL_ESCAPE_SPACES_ONLY);
3371 if (rc != S_OK)
3373 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
3374 strcpyW(request->path,lpszObjectName);
3376 }else {
3377 static const WCHAR slashW[] = {'/',0};
3379 request->path = heap_strdupW(slashW);
3382 if (lpszReferrer && *lpszReferrer)
3383 HTTP_ProcessHeader(request, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3385 if (lpszAcceptTypes)
3387 int i;
3388 for (i = 0; lpszAcceptTypes[i]; i++)
3390 if (!*lpszAcceptTypes[i]) continue;
3391 HTTP_ProcessHeader(request, HTTP_ACCEPT, lpszAcceptTypes[i],
3392 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
3393 HTTP_ADDHDR_FLAG_REQ |
3394 (i == 0 ? HTTP_ADDHDR_FLAG_REPLACE : 0));
3398 request->verb = heap_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
3399 request->version = heap_strdupW(lpszVersion && *lpszVersion ? lpszVersion : g_szHttp1_1);
3401 HTTP_ProcessHeader(request, hostW, request->server->canon_host_port, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3403 if (hIC->proxy && hIC->proxy[0] && !HTTP_ShouldBypassProxy(hIC, session->hostName))
3404 HTTP_DealWithProxy( hIC, session, request );
3406 INTERNET_SendCallback(&session->hdr, dwContext,
3407 INTERNET_STATUS_HANDLE_CREATED, &request->hdr.hInternet,
3408 sizeof(HINTERNET));
3410 TRACE("<-- (%p)\n", request);
3412 *ret = request->hdr.hInternet;
3413 return ERROR_SUCCESS;
3416 /***********************************************************************
3417 * HttpOpenRequestW (WININET.@)
3419 * Open a HTTP request handle
3421 * RETURNS
3422 * HINTERNET a HTTP request handle on success
3423 * NULL on failure
3426 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
3427 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3428 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3429 DWORD dwFlags, DWORD_PTR dwContext)
3431 http_session_t *session;
3432 HINTERNET handle = NULL;
3433 DWORD res;
3435 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
3436 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
3437 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
3438 dwFlags, dwContext);
3439 if(lpszAcceptTypes!=NULL)
3441 int i;
3442 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
3443 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
3446 session = (http_session_t*) get_handle_object( hHttpSession );
3447 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
3449 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3450 goto lend;
3454 * My tests seem to show that the windows version does not
3455 * become asynchronous until after this point. And anyhow
3456 * if this call was asynchronous then how would you get the
3457 * necessary HINTERNET pointer returned by this function.
3460 res = HTTP_HttpOpenRequestW(session, lpszVerb, lpszObjectName,
3461 lpszVersion, lpszReferrer, lpszAcceptTypes,
3462 dwFlags, dwContext, &handle);
3463 lend:
3464 if( session )
3465 WININET_Release( &session->hdr );
3466 TRACE("returning %p\n", handle);
3467 if(res != ERROR_SUCCESS)
3468 SetLastError(res);
3469 return handle;
3472 static const LPCWSTR header_lookup[] = {
3473 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
3474 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3475 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3476 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
3477 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3478 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3479 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3480 szAllow, /* HTTP_QUERY_ALLOW = 7 */
3481 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
3482 szDate, /* HTTP_QUERY_DATE = 9 */
3483 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
3484 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3485 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
3486 szURI, /* HTTP_QUERY_URI = 13 */
3487 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
3488 NULL, /* HTTP_QUERY_COST = 15 */
3489 NULL, /* HTTP_QUERY_LINK = 16 */
3490 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
3491 NULL, /* HTTP_QUERY_VERSION = 18 */
3492 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
3493 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
3494 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
3495 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3496 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
3497 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
3498 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3499 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3500 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3501 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
3502 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3503 NULL, /* HTTP_QUERY_FORWARDED = 30 */
3504 NULL, /* HTTP_QUERY_FROM = 31 */
3505 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3506 szLocation, /* HTTP_QUERY_LOCATION = 33 */
3507 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
3508 szReferer, /* HTTP_QUERY_REFERER = 35 */
3509 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
3510 szServer, /* HTTP_QUERY_SERVER = 37 */
3511 NULL, /* HTTP_TITLE = 38 */
3512 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
3513 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3514 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3515 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3516 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
3517 szCookie, /* HTTP_QUERY_COOKIE = 44 */
3518 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3519 NULL, /* HTTP_QUERY_REFRESH = 46 */
3520 szContent_Disposition, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3521 szAge, /* HTTP_QUERY_AGE = 48 */
3522 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3523 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
3524 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3525 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3526 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3527 szETag, /* HTTP_QUERY_ETAG = 54 */
3528 hostW, /* HTTP_QUERY_HOST = 55 */
3529 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
3530 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3531 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
3532 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3533 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3534 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3535 szRange, /* HTTP_QUERY_RANGE = 62 */
3536 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3537 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
3538 szVary, /* HTTP_QUERY_VARY = 65 */
3539 szVia, /* HTTP_QUERY_VIA = 66 */
3540 szWarning, /* HTTP_QUERY_WARNING = 67 */
3541 szExpect, /* HTTP_QUERY_EXPECT = 68 */
3542 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3543 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3546 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3548 /***********************************************************************
3549 * HTTP_HttpQueryInfoW (internal)
3551 static DWORD HTTP_HttpQueryInfoW(http_request_t *request, DWORD dwInfoLevel,
3552 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3554 LPHTTPHEADERW lphttpHdr = NULL;
3555 BOOL request_only = dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS;
3556 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
3557 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
3558 INT index = -1;
3560 EnterCriticalSection( &request->headers_section );
3562 /* Find requested header structure */
3563 switch (level)
3565 case HTTP_QUERY_CUSTOM:
3566 if (!lpBuffer)
3568 LeaveCriticalSection( &request->headers_section );
3569 return ERROR_INVALID_PARAMETER;
3571 index = HTTP_GetCustomHeaderIndex(request, lpBuffer, requested_index, request_only);
3572 break;
3573 case HTTP_QUERY_RAW_HEADERS_CRLF:
3575 LPWSTR headers;
3576 DWORD len = 0;
3577 DWORD res = ERROR_INVALID_PARAMETER;
3579 if (request_only)
3580 headers = build_request_header(request, request->verb, request->path, request->version, TRUE);
3581 else
3582 headers = build_response_header(request, TRUE);
3583 if (!headers)
3585 LeaveCriticalSection( &request->headers_section );
3586 return ERROR_OUTOFMEMORY;
3589 len = strlenW(headers) * sizeof(WCHAR);
3590 if (len + sizeof(WCHAR) > *lpdwBufferLength)
3592 len += sizeof(WCHAR);
3593 res = ERROR_INSUFFICIENT_BUFFER;
3595 else if (lpBuffer)
3597 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3598 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
3599 res = ERROR_SUCCESS;
3601 *lpdwBufferLength = len;
3603 heap_free(headers);
3604 LeaveCriticalSection( &request->headers_section );
3605 return res;
3607 case HTTP_QUERY_RAW_HEADERS:
3609 LPWSTR headers;
3610 DWORD len;
3612 if (request_only)
3613 headers = build_request_header(request, request->verb, request->path, request->version, FALSE);
3614 else
3615 headers = build_response_header(request, FALSE);
3617 if (!headers)
3619 LeaveCriticalSection( &request->headers_section );
3620 return ERROR_OUTOFMEMORY;
3623 len = strlenW(headers) * sizeof(WCHAR);
3624 if (len > *lpdwBufferLength)
3626 *lpdwBufferLength = len;
3627 heap_free(headers);
3628 LeaveCriticalSection( &request->headers_section );
3629 return ERROR_INSUFFICIENT_BUFFER;
3632 if (lpBuffer)
3634 DWORD i;
3636 TRACE("returning data: %s\n", debugstr_wn(headers, len / sizeof(WCHAR)));
3638 for (i = 0; i < len / sizeof(WCHAR); i++)
3640 if (headers[i] == '\n')
3641 headers[i] = 0;
3643 memcpy(lpBuffer, headers, len);
3645 *lpdwBufferLength = len - sizeof(WCHAR);
3647 heap_free(headers);
3648 LeaveCriticalSection( &request->headers_section );
3649 return ERROR_SUCCESS;
3651 case HTTP_QUERY_STATUS_TEXT:
3652 if (request->statusText)
3654 DWORD len = strlenW(request->statusText);
3655 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3657 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3658 LeaveCriticalSection( &request->headers_section );
3659 return ERROR_INSUFFICIENT_BUFFER;
3661 if (lpBuffer)
3663 memcpy(lpBuffer, request->statusText, (len + 1) * sizeof(WCHAR));
3664 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3666 *lpdwBufferLength = len * sizeof(WCHAR);
3667 LeaveCriticalSection( &request->headers_section );
3668 return ERROR_SUCCESS;
3670 break;
3671 case HTTP_QUERY_VERSION:
3672 if (request->version)
3674 DWORD len = strlenW(request->version);
3675 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3677 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3678 LeaveCriticalSection( &request->headers_section );
3679 return ERROR_INSUFFICIENT_BUFFER;
3681 if (lpBuffer)
3683 memcpy(lpBuffer, request->version, (len + 1) * sizeof(WCHAR));
3684 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3686 *lpdwBufferLength = len * sizeof(WCHAR);
3687 LeaveCriticalSection( &request->headers_section );
3688 return ERROR_SUCCESS;
3690 break;
3691 case HTTP_QUERY_CONTENT_ENCODING:
3692 index = HTTP_GetCustomHeaderIndex(request, header_lookup[request->read_gzip ? HTTP_QUERY_CONTENT_TYPE : level],
3693 requested_index,request_only);
3694 break;
3695 case HTTP_QUERY_STATUS_CODE: {
3696 DWORD res = ERROR_SUCCESS;
3698 if(request_only)
3700 LeaveCriticalSection( &request->headers_section );
3701 return ERROR_HTTP_INVALID_QUERY_REQUEST;
3704 if(requested_index)
3705 break;
3707 if(dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) {
3708 if(*lpdwBufferLength >= sizeof(DWORD))
3709 *(DWORD*)lpBuffer = request->status_code;
3710 else
3711 res = ERROR_INSUFFICIENT_BUFFER;
3712 *lpdwBufferLength = sizeof(DWORD);
3713 }else {
3714 WCHAR buf[12];
3715 DWORD size;
3716 static const WCHAR formatW[] = {'%','u',0};
3718 size = sprintfW(buf, formatW, request->status_code) * sizeof(WCHAR);
3720 if(size <= *lpdwBufferLength) {
3721 memcpy(lpBuffer, buf, size+sizeof(WCHAR));
3722 }else {
3723 size += sizeof(WCHAR);
3724 res = ERROR_INSUFFICIENT_BUFFER;
3727 *lpdwBufferLength = size;
3729 LeaveCriticalSection( &request->headers_section );
3730 return res;
3732 default:
3733 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
3735 if (level < LAST_TABLE_HEADER && header_lookup[level])
3736 index = HTTP_GetCustomHeaderIndex(request, header_lookup[level],
3737 requested_index,request_only);
3740 if (index >= 0)
3741 lphttpHdr = &request->custHeaders[index];
3743 /* Ensure header satisfies requested attributes */
3744 if (!lphttpHdr ||
3745 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
3746 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
3748 LeaveCriticalSection( &request->headers_section );
3749 return ERROR_HTTP_HEADER_NOT_FOUND;
3752 /* coalesce value to requested type */
3753 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
3755 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
3756 TRACE(" returning number: %d\n", *(int *)lpBuffer);
3758 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
3760 time_t tmpTime;
3761 struct tm tmpTM;
3762 SYSTEMTIME *STHook;
3764 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
3766 tmpTM = *gmtime(&tmpTime);
3767 STHook = (SYSTEMTIME *)lpBuffer;
3768 STHook->wDay = tmpTM.tm_mday;
3769 STHook->wHour = tmpTM.tm_hour;
3770 STHook->wMilliseconds = 0;
3771 STHook->wMinute = tmpTM.tm_min;
3772 STHook->wDayOfWeek = tmpTM.tm_wday;
3773 STHook->wMonth = tmpTM.tm_mon + 1;
3774 STHook->wSecond = tmpTM.tm_sec;
3775 STHook->wYear = 1900+tmpTM.tm_year;
3777 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3778 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
3779 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
3781 else if (lphttpHdr->lpszValue)
3783 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
3785 if (len > *lpdwBufferLength)
3787 *lpdwBufferLength = len;
3788 LeaveCriticalSection( &request->headers_section );
3789 return ERROR_INSUFFICIENT_BUFFER;
3791 if (lpBuffer)
3793 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
3794 TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
3796 *lpdwBufferLength = len - sizeof(WCHAR);
3798 if (lpdwIndex) (*lpdwIndex)++;
3800 LeaveCriticalSection( &request->headers_section );
3801 return ERROR_SUCCESS;
3804 /***********************************************************************
3805 * HttpQueryInfoW (WININET.@)
3807 * Queries for information about an HTTP request
3809 * RETURNS
3810 * TRUE on success
3811 * FALSE on failure
3814 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3815 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3817 http_request_t *request;
3818 DWORD res;
3820 if (TRACE_ON(wininet)) {
3821 #define FE(x) { x, #x }
3822 static const wininet_flag_info query_flags[] = {
3823 FE(HTTP_QUERY_MIME_VERSION),
3824 FE(HTTP_QUERY_CONTENT_TYPE),
3825 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
3826 FE(HTTP_QUERY_CONTENT_ID),
3827 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
3828 FE(HTTP_QUERY_CONTENT_LENGTH),
3829 FE(HTTP_QUERY_CONTENT_LANGUAGE),
3830 FE(HTTP_QUERY_ALLOW),
3831 FE(HTTP_QUERY_PUBLIC),
3832 FE(HTTP_QUERY_DATE),
3833 FE(HTTP_QUERY_EXPIRES),
3834 FE(HTTP_QUERY_LAST_MODIFIED),
3835 FE(HTTP_QUERY_MESSAGE_ID),
3836 FE(HTTP_QUERY_URI),
3837 FE(HTTP_QUERY_DERIVED_FROM),
3838 FE(HTTP_QUERY_COST),
3839 FE(HTTP_QUERY_LINK),
3840 FE(HTTP_QUERY_PRAGMA),
3841 FE(HTTP_QUERY_VERSION),
3842 FE(HTTP_QUERY_STATUS_CODE),
3843 FE(HTTP_QUERY_STATUS_TEXT),
3844 FE(HTTP_QUERY_RAW_HEADERS),
3845 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
3846 FE(HTTP_QUERY_CONNECTION),
3847 FE(HTTP_QUERY_ACCEPT),
3848 FE(HTTP_QUERY_ACCEPT_CHARSET),
3849 FE(HTTP_QUERY_ACCEPT_ENCODING),
3850 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
3851 FE(HTTP_QUERY_AUTHORIZATION),
3852 FE(HTTP_QUERY_CONTENT_ENCODING),
3853 FE(HTTP_QUERY_FORWARDED),
3854 FE(HTTP_QUERY_FROM),
3855 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
3856 FE(HTTP_QUERY_LOCATION),
3857 FE(HTTP_QUERY_ORIG_URI),
3858 FE(HTTP_QUERY_REFERER),
3859 FE(HTTP_QUERY_RETRY_AFTER),
3860 FE(HTTP_QUERY_SERVER),
3861 FE(HTTP_QUERY_TITLE),
3862 FE(HTTP_QUERY_USER_AGENT),
3863 FE(HTTP_QUERY_WWW_AUTHENTICATE),
3864 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
3865 FE(HTTP_QUERY_ACCEPT_RANGES),
3866 FE(HTTP_QUERY_SET_COOKIE),
3867 FE(HTTP_QUERY_COOKIE),
3868 FE(HTTP_QUERY_REQUEST_METHOD),
3869 FE(HTTP_QUERY_REFRESH),
3870 FE(HTTP_QUERY_CONTENT_DISPOSITION),
3871 FE(HTTP_QUERY_AGE),
3872 FE(HTTP_QUERY_CACHE_CONTROL),
3873 FE(HTTP_QUERY_CONTENT_BASE),
3874 FE(HTTP_QUERY_CONTENT_LOCATION),
3875 FE(HTTP_QUERY_CONTENT_MD5),
3876 FE(HTTP_QUERY_CONTENT_RANGE),
3877 FE(HTTP_QUERY_ETAG),
3878 FE(HTTP_QUERY_HOST),
3879 FE(HTTP_QUERY_IF_MATCH),
3880 FE(HTTP_QUERY_IF_NONE_MATCH),
3881 FE(HTTP_QUERY_IF_RANGE),
3882 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
3883 FE(HTTP_QUERY_MAX_FORWARDS),
3884 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
3885 FE(HTTP_QUERY_RANGE),
3886 FE(HTTP_QUERY_TRANSFER_ENCODING),
3887 FE(HTTP_QUERY_UPGRADE),
3888 FE(HTTP_QUERY_VARY),
3889 FE(HTTP_QUERY_VIA),
3890 FE(HTTP_QUERY_WARNING),
3891 FE(HTTP_QUERY_CUSTOM)
3893 static const wininet_flag_info modifier_flags[] = {
3894 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
3895 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
3896 FE(HTTP_QUERY_FLAG_NUMBER),
3897 FE(HTTP_QUERY_FLAG_COALESCE)
3899 #undef FE
3900 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
3901 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
3902 DWORD i;
3904 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, info);
3905 TRACE(" Attribute:");
3906 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
3907 if (query_flags[i].val == info) {
3908 TRACE(" %s", query_flags[i].name);
3909 break;
3912 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
3913 TRACE(" Unknown (%08x)", info);
3916 TRACE(" Modifier:");
3917 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
3918 if (modifier_flags[i].val & info_mod) {
3919 TRACE(" %s", modifier_flags[i].name);
3920 info_mod &= ~ modifier_flags[i].val;
3924 if (info_mod) {
3925 TRACE(" Unknown (%08x)", info_mod);
3927 TRACE("\n");
3930 request = (http_request_t*) get_handle_object( hHttpRequest );
3931 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
3933 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3934 goto lend;
3937 if (lpBuffer == NULL)
3938 *lpdwBufferLength = 0;
3939 res = HTTP_HttpQueryInfoW( request, dwInfoLevel,
3940 lpBuffer, lpdwBufferLength, lpdwIndex);
3942 lend:
3943 if( request )
3944 WININET_Release( &request->hdr );
3946 TRACE("%u <--\n", res);
3947 if(res != ERROR_SUCCESS)
3948 SetLastError(res);
3949 return res == ERROR_SUCCESS;
3952 /***********************************************************************
3953 * HttpQueryInfoA (WININET.@)
3955 * Queries for information about an HTTP request
3957 * RETURNS
3958 * TRUE on success
3959 * FALSE on failure
3962 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3963 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3965 BOOL result;
3966 DWORD len;
3967 WCHAR* bufferW;
3969 TRACE("%p %x\n", hHttpRequest, dwInfoLevel);
3971 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
3972 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
3974 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
3975 lpdwBufferLength, lpdwIndex );
3978 if (lpBuffer)
3980 DWORD alloclen;
3981 len = (*lpdwBufferLength)*sizeof(WCHAR);
3982 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3984 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
3985 if (alloclen < len)
3986 alloclen = len;
3988 else
3989 alloclen = len;
3990 bufferW = heap_alloc(alloclen);
3991 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3992 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3993 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
3994 } else
3996 bufferW = NULL;
3997 len = 0;
4000 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
4001 &len, lpdwIndex );
4002 if( result )
4004 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
4005 lpBuffer, *lpdwBufferLength, NULL, NULL );
4006 *lpdwBufferLength = len - 1;
4008 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
4010 else
4011 /* since the strings being returned from HttpQueryInfoW should be
4012 * only ASCII characters, it is reasonable to assume that all of
4013 * the Unicode characters can be reduced to a single byte */
4014 *lpdwBufferLength = len / sizeof(WCHAR);
4016 heap_free( bufferW );
4017 return result;
4020 /***********************************************************************
4021 * HTTP_GetRedirectURL (internal)
4023 static LPWSTR HTTP_GetRedirectURL(http_request_t *request, LPCWSTR lpszUrl)
4025 static WCHAR szHttp[] = {'h','t','t','p',0};
4026 static WCHAR szHttps[] = {'h','t','t','p','s',0};
4027 http_session_t *session = request->session;
4028 URL_COMPONENTSW urlComponents;
4029 DWORD url_length = 0;
4030 LPWSTR orig_url;
4031 LPWSTR combined_url;
4033 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
4034 urlComponents.lpszScheme = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
4035 urlComponents.dwSchemeLength = 0;
4036 urlComponents.lpszHostName = request->server->name;
4037 urlComponents.dwHostNameLength = 0;
4038 urlComponents.nPort = request->server->port;
4039 urlComponents.lpszUserName = session->userName;
4040 urlComponents.dwUserNameLength = 0;
4041 urlComponents.lpszPassword = NULL;
4042 urlComponents.dwPasswordLength = 0;
4043 urlComponents.lpszUrlPath = request->path;
4044 urlComponents.dwUrlPathLength = 0;
4045 urlComponents.lpszExtraInfo = NULL;
4046 urlComponents.dwExtraInfoLength = 0;
4048 if (!InternetCreateUrlW(&urlComponents, 0, NULL, &url_length) &&
4049 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
4050 return NULL;
4052 orig_url = heap_alloc(url_length);
4054 /* convert from bytes to characters */
4055 url_length = url_length / sizeof(WCHAR) - 1;
4056 if (!InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length))
4058 heap_free(orig_url);
4059 return NULL;
4062 url_length = 0;
4063 if (!InternetCombineUrlW(orig_url, lpszUrl, NULL, &url_length, ICU_ENCODE_SPACES_ONLY) &&
4064 (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
4066 heap_free(orig_url);
4067 return NULL;
4069 combined_url = heap_alloc(url_length * sizeof(WCHAR));
4071 if (!InternetCombineUrlW(orig_url, lpszUrl, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY))
4073 heap_free(orig_url);
4074 heap_free(combined_url);
4075 return NULL;
4077 heap_free(orig_url);
4078 return combined_url;
4082 /***********************************************************************
4083 * HTTP_HandleRedirect (internal)
4085 static DWORD HTTP_HandleRedirect(http_request_t *request, LPCWSTR lpszUrl)
4087 http_session_t *session = request->session;
4088 WCHAR path[INTERNET_MAX_PATH_LENGTH];
4090 if(lpszUrl[0]=='/')
4092 /* if it's an absolute path, keep the same session info */
4093 lstrcpynW(path, lpszUrl, INTERNET_MAX_URL_LENGTH);
4095 else
4097 URL_COMPONENTSW urlComponents;
4098 WCHAR protocol[INTERNET_MAX_SCHEME_LENGTH];
4099 WCHAR hostName[INTERNET_MAX_HOST_NAME_LENGTH];
4100 WCHAR userName[INTERNET_MAX_USER_NAME_LENGTH];
4101 BOOL custom_port = FALSE;
4103 static const WCHAR httpW[] = {'h','t','t','p',0};
4104 static const WCHAR httpsW[] = {'h','t','t','p','s',0};
4106 userName[0] = 0;
4107 hostName[0] = 0;
4108 protocol[0] = 0;
4110 urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
4111 urlComponents.lpszScheme = protocol;
4112 urlComponents.dwSchemeLength = INTERNET_MAX_SCHEME_LENGTH;
4113 urlComponents.lpszHostName = hostName;
4114 urlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
4115 urlComponents.lpszUserName = userName;
4116 urlComponents.dwUserNameLength = INTERNET_MAX_USER_NAME_LENGTH;
4117 urlComponents.lpszPassword = NULL;
4118 urlComponents.dwPasswordLength = 0;
4119 urlComponents.lpszUrlPath = path;
4120 urlComponents.dwUrlPathLength = INTERNET_MAX_PATH_LENGTH;
4121 urlComponents.lpszExtraInfo = NULL;
4122 urlComponents.dwExtraInfoLength = 0;
4123 if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
4124 return INTERNET_GetLastError();
4126 if(!strcmpiW(protocol, httpW)) {
4127 if(request->hdr.dwFlags & INTERNET_FLAG_SECURE) {
4128 TRACE("redirect from secure page to non-secure page\n");
4129 /* FIXME: warn about from secure redirect to non-secure page */
4130 request->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
4133 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4134 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
4135 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT)
4136 custom_port = TRUE;
4137 }else if(!strcmpiW(protocol, httpsW)) {
4138 if(!(request->hdr.dwFlags & INTERNET_FLAG_SECURE)) {
4139 TRACE("redirect from non-secure page to secure page\n");
4140 /* FIXME: notify about redirect to secure page */
4141 request->hdr.dwFlags |= INTERNET_FLAG_SECURE;
4144 if(urlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
4145 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
4146 else if(urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT)
4147 custom_port = TRUE;
4150 heap_free(session->hostName);
4152 session->hostName = heap_strdupW(hostName);
4153 session->hostPort = urlComponents.nPort;
4155 heap_free(session->userName);
4156 session->userName = NULL;
4157 if (userName[0])
4158 session->userName = heap_strdupW(userName);
4160 reset_data_stream(request);
4162 if(strcmpiW(request->server->name, hostName) || request->server->port != urlComponents.nPort) {
4163 server_t *new_server;
4165 new_server = get_server(hostName, urlComponents.nPort, urlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
4166 server_release(request->server);
4167 request->server = new_server;
4170 if (custom_port)
4171 HTTP_ProcessHeader(request, hostW, request->server->host_port, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4172 else
4173 HTTP_ProcessHeader(request, hostW, request->server->name, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4175 heap_free(request->path);
4176 request->path=NULL;
4177 if (*path)
4179 DWORD needed = 0;
4180 HRESULT rc;
4182 rc = UrlEscapeW(path, NULL, &needed, URL_ESCAPE_SPACES_ONLY);
4183 if (rc != E_POINTER)
4184 needed = strlenW(path)+1;
4185 request->path = heap_alloc(needed*sizeof(WCHAR));
4186 rc = UrlEscapeW(path, request->path, &needed,
4187 URL_ESCAPE_SPACES_ONLY);
4188 if (rc != S_OK)
4190 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4191 strcpyW(request->path,path);
4195 /* Remove custom content-type/length headers on redirects. */
4196 remove_header(request, szContent_Type, TRUE);
4197 remove_header(request, szContent_Length, TRUE);
4199 return ERROR_SUCCESS;
4202 /***********************************************************************
4203 * HTTP_build_req (internal)
4205 * concatenate all the strings in the request together
4207 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
4209 LPCWSTR *t;
4210 LPWSTR str;
4212 for( t = list; *t ; t++ )
4213 len += strlenW( *t );
4214 len++;
4216 str = heap_alloc(len*sizeof(WCHAR));
4217 *str = 0;
4219 for( t = list; *t ; t++ )
4220 strcatW( str, *t );
4222 return str;
4225 static void HTTP_InsertCookies(http_request_t *request)
4227 WCHAR *cookies;
4228 DWORD res;
4230 res = get_cookie_header(request->server->name, request->path, &cookies);
4231 if(res != ERROR_SUCCESS || !cookies)
4232 return;
4234 get_cookie_header(request->server->name, request->path, &cookies);
4235 HTTP_HttpAddRequestHeadersW(request, cookies, strlenW(cookies), HTTP_ADDREQ_FLAG_REPLACE);
4236 heap_free(cookies);
4239 static WORD HTTP_ParseWkday(LPCWSTR day)
4241 static const WCHAR days[7][4] = {{ 's','u','n',0 },
4242 { 'm','o','n',0 },
4243 { 't','u','e',0 },
4244 { 'w','e','d',0 },
4245 { 't','h','u',0 },
4246 { 'f','r','i',0 },
4247 { 's','a','t',0 }};
4248 unsigned int i;
4249 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4250 if (!strcmpiW(day, days[i]))
4251 return i;
4253 /* Invalid */
4254 return 7;
4257 static WORD HTTP_ParseMonth(LPCWSTR month)
4259 static const WCHAR jan[] = { 'j','a','n',0 };
4260 static const WCHAR feb[] = { 'f','e','b',0 };
4261 static const WCHAR mar[] = { 'm','a','r',0 };
4262 static const WCHAR apr[] = { 'a','p','r',0 };
4263 static const WCHAR may[] = { 'm','a','y',0 };
4264 static const WCHAR jun[] = { 'j','u','n',0 };
4265 static const WCHAR jul[] = { 'j','u','l',0 };
4266 static const WCHAR aug[] = { 'a','u','g',0 };
4267 static const WCHAR sep[] = { 's','e','p',0 };
4268 static const WCHAR oct[] = { 'o','c','t',0 };
4269 static const WCHAR nov[] = { 'n','o','v',0 };
4270 static const WCHAR dec[] = { 'd','e','c',0 };
4272 if (!strcmpiW(month, jan)) return 1;
4273 if (!strcmpiW(month, feb)) return 2;
4274 if (!strcmpiW(month, mar)) return 3;
4275 if (!strcmpiW(month, apr)) return 4;
4276 if (!strcmpiW(month, may)) return 5;
4277 if (!strcmpiW(month, jun)) return 6;
4278 if (!strcmpiW(month, jul)) return 7;
4279 if (!strcmpiW(month, aug)) return 8;
4280 if (!strcmpiW(month, sep)) return 9;
4281 if (!strcmpiW(month, oct)) return 10;
4282 if (!strcmpiW(month, nov)) return 11;
4283 if (!strcmpiW(month, dec)) return 12;
4284 /* Invalid */
4285 return 0;
4288 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4289 * optionally preceded by whitespace.
4290 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4291 * st, and sets *str to the first character after the time format.
4293 static BOOL HTTP_ParseTime(SYSTEMTIME *st, LPCWSTR *str)
4295 LPCWSTR ptr = *str;
4296 WCHAR *nextPtr;
4297 unsigned long num;
4299 while (isspaceW(*ptr))
4300 ptr++;
4302 num = strtoulW(ptr, &nextPtr, 10);
4303 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4305 ERR("unexpected time format %s\n", debugstr_w(ptr));
4306 return FALSE;
4308 if (num > 23)
4310 ERR("unexpected hour in time format %s\n", debugstr_w(ptr));
4311 return FALSE;
4313 ptr = nextPtr + 1;
4314 st->wHour = (WORD)num;
4315 num = strtoulW(ptr, &nextPtr, 10);
4316 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4318 ERR("unexpected time format %s\n", debugstr_w(ptr));
4319 return FALSE;
4321 if (num > 59)
4323 ERR("unexpected minute in time format %s\n", debugstr_w(ptr));
4324 return FALSE;
4326 ptr = nextPtr + 1;
4327 st->wMinute = (WORD)num;
4328 num = strtoulW(ptr, &nextPtr, 10);
4329 if (!nextPtr || nextPtr <= ptr)
4331 ERR("unexpected time format %s\n", debugstr_w(ptr));
4332 return FALSE;
4334 if (num > 59)
4336 ERR("unexpected second in time format %s\n", debugstr_w(ptr));
4337 return FALSE;
4339 ptr = nextPtr + 1;
4340 *str = ptr;
4341 st->wSecond = (WORD)num;
4342 return TRUE;
4345 static BOOL HTTP_ParseDateAsAsctime(LPCWSTR value, FILETIME *ft)
4347 static const WCHAR gmt[]= { 'G','M','T',0 };
4348 WCHAR day[4], *dayPtr, month[4], *monthPtr, *nextPtr;
4349 LPCWSTR ptr;
4350 SYSTEMTIME st = { 0 };
4351 unsigned long num;
4353 for (ptr = value, dayPtr = day; *ptr && !isspaceW(*ptr) &&
4354 dayPtr - day < sizeof(day) / sizeof(day[0]) - 1; ptr++, dayPtr++)
4355 *dayPtr = *ptr;
4356 *dayPtr = 0;
4357 st.wDayOfWeek = HTTP_ParseWkday(day);
4358 if (st.wDayOfWeek >= 7)
4360 ERR("unexpected weekday %s\n", debugstr_w(day));
4361 return FALSE;
4364 while (isspaceW(*ptr))
4365 ptr++;
4367 for (monthPtr = month; !isspace(*ptr) &&
4368 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4369 monthPtr++, ptr++)
4370 *monthPtr = *ptr;
4371 *monthPtr = 0;
4372 st.wMonth = HTTP_ParseMonth(month);
4373 if (!st.wMonth || st.wMonth > 12)
4375 ERR("unexpected month %s\n", debugstr_w(month));
4376 return FALSE;
4379 while (isspaceW(*ptr))
4380 ptr++;
4382 num = strtoulW(ptr, &nextPtr, 10);
4383 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4385 ERR("unexpected day %s\n", debugstr_w(ptr));
4386 return FALSE;
4388 ptr = nextPtr;
4389 st.wDay = (WORD)num;
4391 while (isspaceW(*ptr))
4392 ptr++;
4394 if (!HTTP_ParseTime(&st, &ptr))
4395 return FALSE;
4397 while (isspaceW(*ptr))
4398 ptr++;
4400 num = strtoulW(ptr, &nextPtr, 10);
4401 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4403 ERR("unexpected year %s\n", debugstr_w(ptr));
4404 return FALSE;
4406 ptr = nextPtr;
4407 st.wYear = (WORD)num;
4409 while (isspaceW(*ptr))
4410 ptr++;
4412 /* asctime() doesn't report a timezone, but some web servers do, so accept
4413 * with or without GMT.
4415 if (*ptr && strcmpW(ptr, gmt))
4417 ERR("unexpected timezone %s\n", debugstr_w(ptr));
4418 return FALSE;
4420 return SystemTimeToFileTime(&st, ft);
4423 static BOOL HTTP_ParseRfc1123Date(LPCWSTR value, FILETIME *ft)
4425 static const WCHAR gmt[]= { 'G','M','T',0 };
4426 WCHAR *nextPtr, day[4], month[4], *monthPtr;
4427 LPCWSTR ptr;
4428 unsigned long num;
4429 SYSTEMTIME st = { 0 };
4431 ptr = strchrW(value, ',');
4432 if (!ptr)
4433 return FALSE;
4434 if (ptr - value != 3)
4436 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4437 return FALSE;
4439 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4440 day[3] = 0;
4441 st.wDayOfWeek = HTTP_ParseWkday(day);
4442 if (st.wDayOfWeek > 6)
4444 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4445 return FALSE;
4447 ptr++;
4449 while (isspaceW(*ptr))
4450 ptr++;
4452 num = strtoulW(ptr, &nextPtr, 10);
4453 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4455 WARN("unexpected day %s\n", debugstr_w(value));
4456 return FALSE;
4458 ptr = nextPtr;
4459 st.wDay = (WORD)num;
4461 while (isspaceW(*ptr))
4462 ptr++;
4464 for (monthPtr = month; !isspace(*ptr) &&
4465 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4466 monthPtr++, ptr++)
4467 *monthPtr = *ptr;
4468 *monthPtr = 0;
4469 st.wMonth = HTTP_ParseMonth(month);
4470 if (!st.wMonth || st.wMonth > 12)
4472 WARN("unexpected month %s\n", debugstr_w(month));
4473 return FALSE;
4476 while (isspaceW(*ptr))
4477 ptr++;
4479 num = strtoulW(ptr, &nextPtr, 10);
4480 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4482 ERR("unexpected year %s\n", debugstr_w(value));
4483 return FALSE;
4485 ptr = nextPtr;
4486 st.wYear = (WORD)num;
4488 if (!HTTP_ParseTime(&st, &ptr))
4489 return FALSE;
4491 while (isspaceW(*ptr))
4492 ptr++;
4494 if (strcmpW(ptr, gmt))
4496 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4497 return FALSE;
4499 return SystemTimeToFileTime(&st, ft);
4502 static WORD HTTP_ParseWeekday(LPCWSTR day)
4504 static const WCHAR days[7][10] = {{ 's','u','n','d','a','y',0 },
4505 { 'm','o','n','d','a','y',0 },
4506 { 't','u','e','s','d','a','y',0 },
4507 { 'w','e','d','n','e','s','d','a','y',0 },
4508 { 't','h','u','r','s','d','a','y',0 },
4509 { 'f','r','i','d','a','y',0 },
4510 { 's','a','t','u','r','d','a','y',0 }};
4511 unsigned int i;
4512 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4513 if (!strcmpiW(day, days[i]))
4514 return i;
4516 /* Invalid */
4517 return 7;
4520 static BOOL HTTP_ParseRfc850Date(LPCWSTR value, FILETIME *ft)
4522 static const WCHAR gmt[]= { 'G','M','T',0 };
4523 WCHAR *nextPtr, day[10], month[4], *monthPtr;
4524 LPCWSTR ptr;
4525 unsigned long num;
4526 SYSTEMTIME st = { 0 };
4528 ptr = strchrW(value, ',');
4529 if (!ptr)
4530 return FALSE;
4531 if (ptr - value == 3)
4533 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4534 day[3] = 0;
4535 st.wDayOfWeek = HTTP_ParseWkday(day);
4536 if (st.wDayOfWeek > 6)
4538 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4539 return FALSE;
4542 else if (ptr - value < sizeof(day) / sizeof(day[0]))
4544 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4545 day[ptr - value + 1] = 0;
4546 st.wDayOfWeek = HTTP_ParseWeekday(day);
4547 if (st.wDayOfWeek > 6)
4549 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4550 return FALSE;
4553 else
4555 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4556 return FALSE;
4558 ptr++;
4560 while (isspaceW(*ptr))
4561 ptr++;
4563 num = strtoulW(ptr, &nextPtr, 10);
4564 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4566 ERR("unexpected day %s\n", debugstr_w(value));
4567 return FALSE;
4569 ptr = nextPtr;
4570 st.wDay = (WORD)num;
4572 if (*ptr != '-')
4574 ERR("unexpected month format %s\n", debugstr_w(ptr));
4575 return FALSE;
4577 ptr++;
4579 for (monthPtr = month; *ptr != '-' &&
4580 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4581 monthPtr++, ptr++)
4582 *monthPtr = *ptr;
4583 *monthPtr = 0;
4584 st.wMonth = HTTP_ParseMonth(month);
4585 if (!st.wMonth || st.wMonth > 12)
4587 ERR("unexpected month %s\n", debugstr_w(month));
4588 return FALSE;
4591 if (*ptr != '-')
4593 ERR("unexpected year format %s\n", debugstr_w(ptr));
4594 return FALSE;
4596 ptr++;
4598 num = strtoulW(ptr, &nextPtr, 10);
4599 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4601 ERR("unexpected year %s\n", debugstr_w(value));
4602 return FALSE;
4604 ptr = nextPtr;
4605 st.wYear = (WORD)num;
4607 if (!HTTP_ParseTime(&st, &ptr))
4608 return FALSE;
4610 while (isspaceW(*ptr))
4611 ptr++;
4613 if (strcmpW(ptr, gmt))
4615 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4616 return FALSE;
4618 return SystemTimeToFileTime(&st, ft);
4621 static BOOL HTTP_ParseDate(LPCWSTR value, FILETIME *ft)
4623 static const WCHAR zero[] = { '0',0 };
4624 BOOL ret;
4626 if (!strcmpW(value, zero))
4628 ft->dwLowDateTime = ft->dwHighDateTime = 0;
4629 ret = TRUE;
4631 else if (strchrW(value, ','))
4633 ret = HTTP_ParseRfc1123Date(value, ft);
4634 if (!ret)
4636 ret = HTTP_ParseRfc850Date(value, ft);
4637 if (!ret)
4638 ERR("unexpected date format %s\n", debugstr_w(value));
4641 else
4643 ret = HTTP_ParseDateAsAsctime(value, ft);
4644 if (!ret)
4645 ERR("unexpected date format %s\n", debugstr_w(value));
4647 return ret;
4650 static void HTTP_ProcessExpires(http_request_t *request)
4652 BOOL expirationFound = FALSE;
4653 int headerIndex;
4655 EnterCriticalSection( &request->headers_section );
4657 /* Look for a Cache-Control header with a max-age directive, as it takes
4658 * precedence over the Expires header.
4660 headerIndex = HTTP_GetCustomHeaderIndex(request, szCache_Control, 0, FALSE);
4661 if (headerIndex != -1)
4663 LPHTTPHEADERW ccHeader = &request->custHeaders[headerIndex];
4664 LPWSTR ptr;
4666 for (ptr = ccHeader->lpszValue; ptr && *ptr; )
4668 LPWSTR comma = strchrW(ptr, ','), end, equal;
4670 if (comma)
4671 end = comma;
4672 else
4673 end = ptr + strlenW(ptr);
4674 for (equal = end - 1; equal > ptr && *equal != '='; equal--)
4676 if (*equal == '=')
4678 static const WCHAR max_age[] = {
4679 'm','a','x','-','a','g','e',0 };
4681 if (!strncmpiW(ptr, max_age, equal - ptr - 1))
4683 LPWSTR nextPtr;
4684 unsigned long age;
4686 age = strtoulW(equal + 1, &nextPtr, 10);
4687 if (nextPtr > equal + 1)
4689 LARGE_INTEGER ft;
4691 NtQuerySystemTime( &ft );
4692 /* Age is in seconds, FILETIME resolution is in
4693 * 100 nanosecond intervals.
4695 ft.QuadPart += age * (ULONGLONG)1000000;
4696 request->expires.dwLowDateTime = ft.u.LowPart;
4697 request->expires.dwHighDateTime = ft.u.HighPart;
4698 expirationFound = TRUE;
4702 if (comma)
4704 ptr = comma + 1;
4705 while (isspaceW(*ptr))
4706 ptr++;
4708 else
4709 ptr = NULL;
4712 if (!expirationFound)
4714 headerIndex = HTTP_GetCustomHeaderIndex(request, szExpires, 0, FALSE);
4715 if (headerIndex != -1)
4717 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4718 FILETIME ft;
4720 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4722 expirationFound = TRUE;
4723 request->expires = ft;
4727 if (!expirationFound)
4729 LARGE_INTEGER t;
4731 /* With no known age, default to 10 minutes until expiration. */
4732 NtQuerySystemTime( &t );
4733 t.QuadPart += 10 * 60 * (ULONGLONG)10000000;
4734 request->expires.dwLowDateTime = t.u.LowPart;
4735 request->expires.dwHighDateTime = t.u.HighPart;
4738 LeaveCriticalSection( &request->headers_section );
4741 static void HTTP_ProcessLastModified(http_request_t *request)
4743 int headerIndex;
4745 EnterCriticalSection( &request->headers_section );
4747 headerIndex = HTTP_GetCustomHeaderIndex(request, szLast_Modified, 0, FALSE);
4748 if (headerIndex != -1)
4750 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4751 FILETIME ft;
4753 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4754 request->last_modified = ft;
4757 LeaveCriticalSection( &request->headers_section );
4760 static void http_process_keep_alive(http_request_t *req)
4762 int index;
4764 EnterCriticalSection( &req->headers_section );
4766 if ((index = HTTP_GetCustomHeaderIndex(req, szConnection, 0, FALSE)) != -1)
4767 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4768 else if ((index = HTTP_GetCustomHeaderIndex(req, szProxy_Connection, 0, FALSE)) != -1)
4769 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4770 else
4771 req->netconn->keep_alive = !strcmpiW(req->version, g_szHttp1_1);
4773 LeaveCriticalSection( &req->headers_section );
4776 static DWORD open_http_connection(http_request_t *request, BOOL *reusing)
4778 const BOOL is_https = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) != 0;
4779 netconn_t *netconn = NULL;
4780 DWORD res;
4782 reset_data_stream(request);
4784 if (request->netconn)
4786 if (is_valid_netconn(request->netconn) && NETCON_is_alive(request->netconn))
4788 *reusing = TRUE;
4789 return ERROR_SUCCESS;
4791 else
4793 free_netconn(request->netconn);
4794 request->netconn = NULL;
4798 res = HTTP_ResolveName(request);
4799 if(res != ERROR_SUCCESS)
4800 return res;
4802 EnterCriticalSection(&connection_pool_cs);
4804 while(!list_empty(&request->server->conn_pool)) {
4805 netconn = LIST_ENTRY(list_head(&request->server->conn_pool), netconn_t, pool_entry);
4806 list_remove(&netconn->pool_entry);
4808 if(is_valid_netconn(netconn) && NETCON_is_alive(netconn))
4809 break;
4811 TRACE("connection %p closed during idle\n", netconn);
4812 free_netconn(netconn);
4813 netconn = NULL;
4816 LeaveCriticalSection(&connection_pool_cs);
4818 if(netconn) {
4819 TRACE("<-- reusing %p netconn\n", netconn);
4820 request->netconn = netconn;
4821 *reusing = TRUE;
4822 return ERROR_SUCCESS;
4825 TRACE("connecting to %s, proxy %s\n", debugstr_w(request->server->name),
4826 request->proxy ? debugstr_w(request->proxy->name) : "(null)");
4828 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4829 INTERNET_STATUS_CONNECTING_TO_SERVER,
4830 request->server->addr_str,
4831 strlen(request->server->addr_str)+1);
4833 res = create_netconn(is_https, request->proxy ? request->proxy : request->server, request->security_flags,
4834 (request->hdr.ErrorMask & INTERNET_ERROR_MASK_COMBINED_SEC_CERT) != 0,
4835 request->connect_timeout, &netconn);
4836 if(res != ERROR_SUCCESS) {
4837 ERR("create_netconn failed: %u\n", res);
4838 return res;
4841 request->netconn = netconn;
4843 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4844 INTERNET_STATUS_CONNECTED_TO_SERVER,
4845 request->server->addr_str, strlen(request->server->addr_str)+1);
4847 *reusing = FALSE;
4848 TRACE("Created connection to %s: %p\n", debugstr_w(request->server->name), netconn);
4849 return ERROR_SUCCESS;
4852 static char *build_ascii_request( const WCHAR *str, void *data, DWORD data_len, DWORD *out_len )
4854 int len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
4855 char *ret;
4857 if (!(ret = heap_alloc( len + data_len ))) return NULL;
4858 WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
4859 if (data_len) memcpy( ret + len - 1, data, data_len );
4860 *out_len = len + data_len - 1;
4861 ret[*out_len] = 0;
4862 return ret;
4865 /***********************************************************************
4866 * HTTP_HttpSendRequestW (internal)
4868 * Sends the specified request to the HTTP server
4870 * RETURNS
4871 * ERROR_SUCCESS on success
4872 * win32 error code on failure
4875 static DWORD HTTP_HttpSendRequestW(http_request_t *request, LPCWSTR lpszHeaders,
4876 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
4877 DWORD dwContentLength, BOOL bEndRequest)
4879 static const WCHAR szContentLength[] =
4880 { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','l','i','\r','\n',0 };
4881 BOOL redirected = FALSE, secure_proxy_connect = FALSE, loop_next;
4882 LPWSTR requestString = NULL;
4883 INT responseLen, cnt;
4884 WCHAR contentLengthStr[sizeof szContentLength/2 /* includes \r\n */ + 20 /* int */ ];
4885 DWORD res;
4887 TRACE("--> %p\n", request);
4889 assert(request->hdr.htype == WH_HHTTPREQ);
4891 /* if the verb is NULL default to GET */
4892 if (!request->verb)
4893 request->verb = heap_strdupW(szGET);
4895 if (dwContentLength || strcmpW(request->verb, szGET))
4897 sprintfW(contentLengthStr, szContentLength, dwContentLength);
4898 HTTP_HttpAddRequestHeadersW(request, contentLengthStr, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4899 request->bytesToWrite = dwContentLength;
4901 if (request->session->appInfo->agent)
4903 WCHAR *agent_header;
4904 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4905 int len;
4907 len = strlenW(request->session->appInfo->agent) + strlenW(user_agent);
4908 agent_header = heap_alloc(len * sizeof(WCHAR));
4909 sprintfW(agent_header, user_agent, request->session->appInfo->agent);
4911 HTTP_HttpAddRequestHeadersW(request, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4912 heap_free(agent_header);
4914 if (request->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
4916 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4917 HTTP_HttpAddRequestHeadersW(request, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4919 if ((request->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && strcmpW(request->verb, szGET))
4921 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4922 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4923 HTTP_HttpAddRequestHeadersW(request, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4926 /* add the headers the caller supplied */
4927 if( lpszHeaders && dwHeaderLength )
4928 HTTP_HttpAddRequestHeadersW(request, lpszHeaders, dwHeaderLength, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
4932 DWORD len, data_len = dwOptionalLength;
4933 BOOL reusing_connection;
4934 char *ascii_req;
4936 loop_next = FALSE;
4938 if(redirected) {
4939 request->contentLength = ~0u;
4940 request->bytesToWrite = 0;
4943 if (TRACE_ON(wininet))
4945 HTTPHEADERW *host;
4947 EnterCriticalSection( &request->headers_section );
4948 host = HTTP_GetHeader( request, hostW );
4949 TRACE("Going to url %s %s\n", debugstr_w(host->lpszValue), debugstr_w(request->path));
4950 LeaveCriticalSection( &request->headers_section );
4953 HTTP_FixURL(request);
4954 if (request->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
4956 HTTP_ProcessHeader(request, szConnection, szKeepAlive, HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE);
4958 HTTP_InsertAuthorization(request, request->authInfo, szAuthorization);
4959 HTTP_InsertAuthorization(request, request->proxyAuthInfo, szProxy_Authorization);
4961 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
4962 HTTP_InsertCookies(request);
4964 res = open_http_connection(request, &reusing_connection);
4965 if (res != ERROR_SUCCESS)
4966 break;
4968 if (!reusing_connection && (request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4970 if (request->proxy) secure_proxy_connect = TRUE;
4971 else
4973 res = NETCON_secure_connect(request->netconn, request->server);
4974 if (res != ERROR_SUCCESS)
4976 WARN("failed to upgrade to secure connection\n");
4977 http_release_netconn(request, FALSE);
4978 break;
4982 if (secure_proxy_connect)
4984 static const WCHAR connectW[] = {'C','O','N','N','E','C','T',0};
4985 const WCHAR *target = request->server->host_port;
4986 requestString = build_request_header(request, connectW, target, g_szHttp1_1, TRUE);
4988 else if (request->proxy && !(request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4990 WCHAR *url = build_proxy_path_url(request);
4991 requestString = build_request_header(request, request->verb, url, request->version, TRUE);
4992 heap_free(url);
4994 else
4995 requestString = build_request_header(request, request->verb, request->path, request->version, TRUE);
4997 TRACE("Request header -> %s\n", debugstr_w(requestString) );
4999 /* send the request as ASCII, tack on the optional data */
5000 if (!lpOptional || redirected || secure_proxy_connect)
5001 data_len = 0;
5003 ascii_req = build_ascii_request( requestString, lpOptional, data_len, &len );
5004 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
5006 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5007 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
5009 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
5010 res = NETCON_send(request->netconn, ascii_req, len, 0, &cnt);
5011 heap_free( ascii_req );
5012 if(res != ERROR_SUCCESS) {
5013 TRACE("send failed: %u\n", res);
5014 if(!reusing_connection)
5015 break;
5016 http_release_netconn(request, FALSE);
5017 loop_next = TRUE;
5018 continue;
5021 request->bytesWritten = data_len;
5023 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5024 INTERNET_STATUS_REQUEST_SENT,
5025 &len, sizeof(DWORD));
5027 if (bEndRequest)
5029 DWORD dwBufferSize;
5031 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5032 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5034 if (HTTP_GetResponseHeaders(request, &responseLen))
5036 http_release_netconn(request, FALSE);
5037 res = ERROR_INTERNET_CONNECTION_ABORTED;
5038 goto lend;
5040 /* FIXME: We should know that connection is closed before sending
5041 * headers. Otherwise wrong callbacks are executed */
5042 if(!responseLen && reusing_connection) {
5043 TRACE("Connection closed by server, reconnecting\n");
5044 http_release_netconn(request, FALSE);
5045 loop_next = TRUE;
5046 continue;
5049 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5050 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
5051 sizeof(DWORD));
5053 http_process_keep_alive(request);
5054 HTTP_ProcessCookies(request);
5055 HTTP_ProcessExpires(request);
5056 HTTP_ProcessLastModified(request);
5058 res = set_content_length(request);
5059 if(res != ERROR_SUCCESS)
5060 goto lend;
5061 if(!request->contentLength)
5062 http_release_netconn(request, TRUE);
5064 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
5066 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5067 dwBufferSize=sizeof(szNewLocation);
5068 switch(request->status_code) {
5069 case HTTP_STATUS_REDIRECT:
5070 case HTTP_STATUS_MOVED:
5071 case HTTP_STATUS_REDIRECT_KEEP_VERB:
5072 case HTTP_STATUS_REDIRECT_METHOD:
5073 if(HTTP_HttpQueryInfoW(request,HTTP_QUERY_LOCATION,szNewLocation,&dwBufferSize,NULL) != ERROR_SUCCESS)
5074 break;
5076 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5077 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5079 heap_free(request->verb);
5080 request->verb = heap_strdupW(szGET);
5082 http_release_netconn(request, drain_content(request, FALSE));
5083 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5085 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5086 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5087 res = HTTP_HandleRedirect(request, new_url);
5088 if (res == ERROR_SUCCESS)
5090 heap_free(requestString);
5091 loop_next = TRUE;
5093 heap_free( new_url );
5095 redirected = TRUE;
5098 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
5100 WCHAR szAuthValue[2048];
5101 dwBufferSize=2048;
5102 if (request->status_code == HTTP_STATUS_DENIED)
5104 WCHAR *host = get_host_header( request );
5105 DWORD dwIndex = 0;
5106 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5108 if (HTTP_DoAuthorization(request, szAuthValue,
5109 &request->authInfo,
5110 request->session->userName,
5111 request->session->password, host))
5113 heap_free(requestString);
5114 if(!drain_content(request, TRUE)) {
5115 FIXME("Could not drain content\n");
5116 http_release_netconn(request, FALSE);
5118 loop_next = TRUE;
5119 break;
5122 heap_free( host );
5124 if(!loop_next) {
5125 TRACE("Cleaning wrong authorization data\n");
5126 destroy_authinfo(request->authInfo);
5127 request->authInfo = NULL;
5130 if (request->status_code == HTTP_STATUS_PROXY_AUTH_REQ)
5132 DWORD dwIndex = 0;
5133 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5135 if (HTTP_DoAuthorization(request, szAuthValue,
5136 &request->proxyAuthInfo,
5137 request->session->appInfo->proxyUsername,
5138 request->session->appInfo->proxyPassword,
5139 NULL))
5141 heap_free(requestString);
5142 if(!drain_content(request, TRUE)) {
5143 FIXME("Could not drain content\n");
5144 http_release_netconn(request, FALSE);
5146 loop_next = TRUE;
5147 break;
5151 if(!loop_next) {
5152 TRACE("Cleaning wrong proxy authorization data\n");
5153 destroy_authinfo(request->proxyAuthInfo);
5154 request->proxyAuthInfo = NULL;
5158 if (secure_proxy_connect && request->status_code == HTTP_STATUS_OK)
5160 res = NETCON_secure_connect(request->netconn, request->server);
5161 if (res != ERROR_SUCCESS)
5163 WARN("failed to upgrade to secure proxy connection\n");
5164 http_release_netconn( request, FALSE );
5165 break;
5167 remove_header(request, szProxy_Authorization, TRUE);
5168 destroy_authinfo(request->proxyAuthInfo);
5169 request->proxyAuthInfo = NULL;
5171 secure_proxy_connect = FALSE;
5172 loop_next = TRUE;
5175 else
5176 res = ERROR_SUCCESS;
5178 while (loop_next);
5180 lend:
5181 heap_free(requestString);
5183 /* TODO: send notification for P3P header */
5185 if(res == ERROR_SUCCESS)
5186 create_cache_entry(request);
5188 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5190 if (res == ERROR_SUCCESS) {
5191 if(bEndRequest && request->contentLength && request->bytesWritten == request->bytesToWrite)
5192 HTTP_ReceiveRequestData(request, TRUE, NULL);
5193 else
5194 send_request_complete(request,
5195 request->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)request->hdr.hInternet : 1, 0);
5196 }else {
5197 send_request_complete(request, 0, res);
5201 TRACE("<--\n");
5202 return res;
5205 typedef struct {
5206 task_header_t hdr;
5207 WCHAR *headers;
5208 DWORD headers_len;
5209 void *optional;
5210 DWORD optional_len;
5211 DWORD content_len;
5212 BOOL end_request;
5213 } send_request_task_t;
5215 /***********************************************************************
5217 * Helper functions for the HttpSendRequest(Ex) functions
5220 static void AsyncHttpSendRequestProc(task_header_t *hdr)
5222 send_request_task_t *task = (send_request_task_t*)hdr;
5223 http_request_t *request = (http_request_t*)task->hdr.hdr;
5225 TRACE("%p\n", request);
5227 HTTP_HttpSendRequestW(request, task->headers, task->headers_len, task->optional,
5228 task->optional_len, task->content_len, task->end_request);
5230 heap_free(task->headers);
5234 static DWORD HTTP_HttpEndRequestW(http_request_t *request, DWORD dwFlags, DWORD_PTR dwContext)
5236 DWORD dwBufferSize;
5237 INT responseLen;
5238 DWORD res = ERROR_SUCCESS;
5240 if(!is_valid_netconn(request->netconn)) {
5241 WARN("Not connected\n");
5242 send_request_complete(request, 0, ERROR_INTERNET_OPERATION_CANCELLED);
5243 return ERROR_INTERNET_OPERATION_CANCELLED;
5246 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5247 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5249 if (HTTP_GetResponseHeaders(request, &responseLen) || !responseLen)
5250 res = ERROR_HTTP_HEADER_NOT_FOUND;
5252 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5253 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
5255 /* process cookies here. Is this right? */
5256 http_process_keep_alive(request);
5257 HTTP_ProcessCookies(request);
5258 HTTP_ProcessExpires(request);
5259 HTTP_ProcessLastModified(request);
5261 if ((res = set_content_length(request)) == ERROR_SUCCESS) {
5262 if(!request->contentLength)
5263 http_release_netconn(request, TRUE);
5266 if (res == ERROR_SUCCESS && !(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
5268 switch(request->status_code) {
5269 case HTTP_STATUS_REDIRECT:
5270 case HTTP_STATUS_MOVED:
5271 case HTTP_STATUS_REDIRECT_METHOD:
5272 case HTTP_STATUS_REDIRECT_KEEP_VERB: {
5273 WCHAR *new_url, szNewLocation[INTERNET_MAX_URL_LENGTH];
5274 dwBufferSize=sizeof(szNewLocation);
5275 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, szNewLocation, &dwBufferSize, NULL) != ERROR_SUCCESS)
5276 break;
5278 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5279 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5281 heap_free(request->verb);
5282 request->verb = heap_strdupW(szGET);
5284 http_release_netconn(request, drain_content(request, FALSE));
5285 if ((new_url = HTTP_GetRedirectURL( request, szNewLocation )))
5287 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5288 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5289 res = HTTP_HandleRedirect(request, new_url);
5290 if (res == ERROR_SUCCESS)
5291 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, TRUE);
5292 heap_free( new_url );
5298 if(res == ERROR_SUCCESS)
5299 create_cache_entry(request);
5301 if (res == ERROR_SUCCESS && request->contentLength)
5302 HTTP_ReceiveRequestData(request, TRUE, NULL);
5303 else
5304 send_request_complete(request, res == ERROR_SUCCESS, res);
5306 return res;
5309 /***********************************************************************
5310 * HttpEndRequestA (WININET.@)
5312 * Ends an HTTP request that was started by HttpSendRequestEx
5314 * RETURNS
5315 * TRUE if successful
5316 * FALSE on failure
5319 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
5320 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5322 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5324 if (lpBuffersOut)
5326 SetLastError(ERROR_INVALID_PARAMETER);
5327 return FALSE;
5330 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
5333 typedef struct {
5334 task_header_t hdr;
5335 DWORD flags;
5336 DWORD context;
5337 } end_request_task_t;
5339 static void AsyncHttpEndRequestProc(task_header_t *hdr)
5341 end_request_task_t *task = (end_request_task_t*)hdr;
5342 http_request_t *req = (http_request_t*)task->hdr.hdr;
5344 TRACE("%p\n", req);
5346 HTTP_HttpEndRequestW(req, task->flags, task->context);
5349 /***********************************************************************
5350 * HttpEndRequestW (WININET.@)
5352 * Ends an HTTP request that was started by HttpSendRequestEx
5354 * RETURNS
5355 * TRUE if successful
5356 * FALSE on failure
5359 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
5360 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5362 http_request_t *request;
5363 DWORD res;
5365 TRACE("%p %p %x %lx -->\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5367 if (lpBuffersOut)
5369 SetLastError(ERROR_INVALID_PARAMETER);
5370 return FALSE;
5373 request = (http_request_t*) get_handle_object( hRequest );
5375 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5377 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
5378 if (request)
5379 WININET_Release( &request->hdr );
5380 return FALSE;
5382 request->hdr.dwFlags |= dwFlags;
5384 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5386 end_request_task_t *task;
5388 task = alloc_async_task(&request->hdr, AsyncHttpEndRequestProc, sizeof(*task));
5389 task->flags = dwFlags;
5390 task->context = dwContext;
5392 INTERNET_AsyncCall(&task->hdr);
5393 res = ERROR_IO_PENDING;
5395 else
5396 res = HTTP_HttpEndRequestW(request, dwFlags, dwContext);
5398 WININET_Release( &request->hdr );
5399 TRACE("%u <--\n", res);
5400 if(res != ERROR_SUCCESS)
5401 SetLastError(res);
5402 return res == ERROR_SUCCESS;
5405 /***********************************************************************
5406 * HttpSendRequestExA (WININET.@)
5408 * Sends the specified request to the HTTP server and allows chunked
5409 * transfers.
5411 * RETURNS
5412 * Success: TRUE
5413 * Failure: FALSE, call GetLastError() for more information.
5415 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
5416 LPINTERNET_BUFFERSA lpBuffersIn,
5417 LPINTERNET_BUFFERSA lpBuffersOut,
5418 DWORD dwFlags, DWORD_PTR dwContext)
5420 INTERNET_BUFFERSW BuffersInW;
5421 BOOL rc = FALSE;
5422 DWORD headerlen;
5423 LPWSTR header = NULL;
5425 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5426 lpBuffersOut, dwFlags, dwContext);
5428 if (lpBuffersIn)
5430 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
5431 if (lpBuffersIn->lpcszHeader)
5433 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
5434 lpBuffersIn->dwHeadersLength,0,0);
5435 header = heap_alloc(headerlen*sizeof(WCHAR));
5436 if (!(BuffersInW.lpcszHeader = header))
5438 SetLastError(ERROR_OUTOFMEMORY);
5439 return FALSE;
5441 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
5442 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5443 header, headerlen);
5445 else
5446 BuffersInW.lpcszHeader = NULL;
5447 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
5448 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
5449 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
5450 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
5451 BuffersInW.Next = NULL;
5454 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
5456 heap_free(header);
5457 return rc;
5460 /***********************************************************************
5461 * HttpSendRequestExW (WININET.@)
5463 * Sends the specified request to the HTTP server and allows chunked
5464 * transfers
5466 * RETURNS
5467 * Success: TRUE
5468 * Failure: FALSE, call GetLastError() for more information.
5470 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
5471 LPINTERNET_BUFFERSW lpBuffersIn,
5472 LPINTERNET_BUFFERSW lpBuffersOut,
5473 DWORD dwFlags, DWORD_PTR dwContext)
5475 http_request_t *request;
5476 http_session_t *session;
5477 appinfo_t *hIC;
5478 DWORD res;
5480 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5481 lpBuffersOut, dwFlags, dwContext);
5483 request = (http_request_t*) get_handle_object( hRequest );
5485 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5487 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5488 goto lend;
5491 session = request->session;
5492 assert(session->hdr.htype == WH_HHTTPSESSION);
5493 hIC = session->appInfo;
5494 assert(hIC->hdr.htype == WH_HINIT);
5496 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5498 send_request_task_t *task;
5500 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5501 if (lpBuffersIn)
5503 DWORD size = 0;
5505 if (lpBuffersIn->lpcszHeader)
5507 if (lpBuffersIn->dwHeadersLength == ~0u)
5508 size = (strlenW( lpBuffersIn->lpcszHeader ) + 1) * sizeof(WCHAR);
5509 else
5510 size = lpBuffersIn->dwHeadersLength * sizeof(WCHAR);
5512 task->headers = heap_alloc(size);
5513 memcpy(task->headers, lpBuffersIn->lpcszHeader, size);
5515 else task->headers = NULL;
5517 task->headers_len = size / sizeof(WCHAR);
5518 task->optional = lpBuffersIn->lpvBuffer;
5519 task->optional_len = lpBuffersIn->dwBufferLength;
5520 task->content_len = lpBuffersIn->dwBufferTotal;
5522 else
5524 task->headers = NULL;
5525 task->headers_len = 0;
5526 task->optional = NULL;
5527 task->optional_len = 0;
5528 task->content_len = 0;
5531 task->end_request = FALSE;
5533 INTERNET_AsyncCall(&task->hdr);
5534 res = ERROR_IO_PENDING;
5536 else
5538 if (lpBuffersIn)
5539 res = HTTP_HttpSendRequestW(request, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5540 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
5541 lpBuffersIn->dwBufferTotal, FALSE);
5542 else
5543 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, FALSE);
5546 lend:
5547 if ( request )
5548 WININET_Release( &request->hdr );
5550 TRACE("<---\n");
5551 SetLastError(res);
5552 return res == ERROR_SUCCESS;
5555 /***********************************************************************
5556 * HttpSendRequestW (WININET.@)
5558 * Sends the specified request to the HTTP server
5560 * RETURNS
5561 * TRUE on success
5562 * FALSE on failure
5565 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
5566 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5568 http_request_t *request;
5569 http_session_t *session = NULL;
5570 appinfo_t *hIC = NULL;
5571 DWORD res = ERROR_SUCCESS;
5573 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
5574 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
5576 request = (http_request_t*) get_handle_object( hHttpRequest );
5577 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5579 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5580 goto lend;
5583 session = request->session;
5584 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
5586 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5587 goto lend;
5590 hIC = session->appInfo;
5591 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
5593 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5594 goto lend;
5597 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5599 send_request_task_t *task;
5601 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5602 if (lpszHeaders)
5604 DWORD size;
5606 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
5607 else size = dwHeaderLength * sizeof(WCHAR);
5609 task->headers = heap_alloc(size);
5610 memcpy(task->headers, lpszHeaders, size);
5612 else
5613 task->headers = NULL;
5614 task->headers_len = dwHeaderLength;
5615 task->optional = lpOptional;
5616 task->optional_len = dwOptionalLength;
5617 task->content_len = dwOptionalLength;
5618 task->end_request = TRUE;
5620 INTERNET_AsyncCall(&task->hdr);
5621 res = ERROR_IO_PENDING;
5623 else
5625 res = HTTP_HttpSendRequestW(request, lpszHeaders,
5626 dwHeaderLength, lpOptional, dwOptionalLength,
5627 dwOptionalLength, TRUE);
5629 lend:
5630 if( request )
5631 WININET_Release( &request->hdr );
5633 SetLastError(res);
5634 return res == ERROR_SUCCESS;
5637 /***********************************************************************
5638 * HttpSendRequestA (WININET.@)
5640 * Sends the specified request to the HTTP server
5642 * RETURNS
5643 * TRUE on success
5644 * FALSE on failure
5647 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
5648 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5650 BOOL result;
5651 LPWSTR szHeaders=NULL;
5652 DWORD nLen=dwHeaderLength;
5653 if(lpszHeaders!=NULL)
5655 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
5656 szHeaders = heap_alloc(nLen*sizeof(WCHAR));
5657 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
5659 result = HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
5660 heap_free(szHeaders);
5661 return result;
5664 /***********************************************************************
5665 * HTTPSESSION_Destroy (internal)
5667 * Deallocate session handle
5670 static void HTTPSESSION_Destroy(object_header_t *hdr)
5672 http_session_t *session = (http_session_t*) hdr;
5674 TRACE("%p\n", session);
5676 WININET_Release(&session->appInfo->hdr);
5678 heap_free(session->hostName);
5679 heap_free(session->password);
5680 heap_free(session->userName);
5683 static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
5685 http_session_t *ses = (http_session_t *)hdr;
5687 switch(option) {
5688 case INTERNET_OPTION_HANDLE_TYPE:
5689 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5691 if (*size < sizeof(ULONG))
5692 return ERROR_INSUFFICIENT_BUFFER;
5694 *size = sizeof(DWORD);
5695 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
5696 return ERROR_SUCCESS;
5697 case INTERNET_OPTION_CONNECT_TIMEOUT:
5698 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5700 if (*size < sizeof(DWORD))
5701 return ERROR_INSUFFICIENT_BUFFER;
5703 *size = sizeof(DWORD);
5704 *(DWORD *)buffer = ses->connect_timeout;
5705 return ERROR_SUCCESS;
5707 case INTERNET_OPTION_SEND_TIMEOUT:
5708 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5710 if (*size < sizeof(DWORD))
5711 return ERROR_INSUFFICIENT_BUFFER;
5713 *size = sizeof(DWORD);
5714 *(DWORD *)buffer = ses->send_timeout;
5715 return ERROR_SUCCESS;
5717 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5718 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5720 if (*size < sizeof(DWORD))
5721 return ERROR_INSUFFICIENT_BUFFER;
5723 *size = sizeof(DWORD);
5724 *(DWORD *)buffer = ses->receive_timeout;
5725 return ERROR_SUCCESS;
5728 return INET_QueryOption(hdr, option, buffer, size, unicode);
5731 static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
5733 http_session_t *ses = (http_session_t*)hdr;
5735 switch(option) {
5736 case INTERNET_OPTION_USERNAME:
5738 heap_free(ses->userName);
5739 if (!(ses->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5740 return ERROR_SUCCESS;
5742 case INTERNET_OPTION_PASSWORD:
5744 heap_free(ses->password);
5745 if (!(ses->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5746 return ERROR_SUCCESS;
5748 case INTERNET_OPTION_PROXY_USERNAME:
5750 heap_free(ses->appInfo->proxyUsername);
5751 if (!(ses->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5752 return ERROR_SUCCESS;
5754 case INTERNET_OPTION_PROXY_PASSWORD:
5756 heap_free(ses->appInfo->proxyPassword);
5757 if (!(ses->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5758 return ERROR_SUCCESS;
5760 case INTERNET_OPTION_CONNECT_TIMEOUT:
5762 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5763 ses->connect_timeout = *(DWORD *)buffer;
5764 return ERROR_SUCCESS;
5766 case INTERNET_OPTION_SEND_TIMEOUT:
5768 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5769 ses->send_timeout = *(DWORD *)buffer;
5770 return ERROR_SUCCESS;
5772 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5774 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5775 ses->receive_timeout = *(DWORD *)buffer;
5776 return ERROR_SUCCESS;
5778 default: break;
5781 return INET_SetOption(hdr, option, buffer, size);
5784 static const object_vtbl_t HTTPSESSIONVtbl = {
5785 HTTPSESSION_Destroy,
5786 NULL,
5787 HTTPSESSION_QueryOption,
5788 HTTPSESSION_SetOption,
5789 NULL,
5790 NULL,
5791 NULL,
5792 NULL,
5793 NULL
5797 /***********************************************************************
5798 * HTTP_Connect (internal)
5800 * Create http session handle
5802 * RETURNS
5803 * HINTERNET a session handle on success
5804 * NULL on failure
5807 DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
5808 INTERNET_PORT serverPort, LPCWSTR lpszUserName,
5809 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
5810 DWORD dwInternalFlags, HINTERNET *ret)
5812 http_session_t *session = NULL;
5814 TRACE("-->\n");
5816 if (!lpszServerName || !lpszServerName[0])
5817 return ERROR_INVALID_PARAMETER;
5819 assert( hIC->hdr.htype == WH_HINIT );
5821 session = alloc_object(&hIC->hdr, &HTTPSESSIONVtbl, sizeof(http_session_t));
5822 if (!session)
5823 return ERROR_OUTOFMEMORY;
5826 * According to my tests. The name is not resolved until a request is sent
5829 session->hdr.htype = WH_HHTTPSESSION;
5830 session->hdr.dwFlags = dwFlags;
5831 session->hdr.dwContext = dwContext;
5832 session->hdr.dwInternalFlags |= dwInternalFlags;
5834 WININET_AddRef( &hIC->hdr );
5835 session->appInfo = hIC;
5836 list_add_head( &hIC->hdr.children, &session->hdr.entry );
5838 session->hostName = heap_strdupW(lpszServerName);
5839 if (lpszUserName && lpszUserName[0])
5840 session->userName = heap_strdupW(lpszUserName);
5841 if (lpszPassword && lpszPassword[0])
5842 session->password = heap_strdupW(lpszPassword);
5843 session->hostPort = serverPort;
5844 session->connect_timeout = hIC->connect_timeout;
5845 session->send_timeout = INFINITE;
5846 session->receive_timeout = INFINITE;
5848 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5849 if (!(session->hdr.dwInternalFlags & INET_OPENURL))
5851 INTERNET_SendCallback(&hIC->hdr, dwContext,
5852 INTERNET_STATUS_HANDLE_CREATED, &session->hdr.hInternet,
5853 sizeof(HINTERNET));
5857 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5858 * windows
5861 TRACE("%p --> %p\n", hIC, session);
5863 *ret = session->hdr.hInternet;
5864 return ERROR_SUCCESS;
5867 /***********************************************************************
5868 * HTTP_clear_response_headers (internal)
5870 * clear out any old response headers
5872 static void HTTP_clear_response_headers( http_request_t *request )
5874 DWORD i;
5876 EnterCriticalSection( &request->headers_section );
5878 for( i=0; i<request->nCustHeaders; i++)
5880 if( !request->custHeaders[i].lpszField )
5881 continue;
5882 if( !request->custHeaders[i].lpszValue )
5883 continue;
5884 if ( request->custHeaders[i].wFlags & HDR_ISREQUEST )
5885 continue;
5886 HTTP_DeleteCustomHeader( request, i );
5887 i--;
5890 LeaveCriticalSection( &request->headers_section );
5893 /***********************************************************************
5894 * HTTP_GetResponseHeaders (internal)
5896 * Read server response
5898 * RETURNS
5900 * TRUE on success
5901 * FALSE on error
5903 static DWORD HTTP_GetResponseHeaders(http_request_t *request, INT *len)
5905 INT cbreaks = 0;
5906 WCHAR buffer[MAX_REPLY_LEN];
5907 DWORD buflen = MAX_REPLY_LEN;
5908 INT rc = 0;
5909 char bufferA[MAX_REPLY_LEN];
5910 LPWSTR status_code = NULL, status_text = NULL;
5911 DWORD res = ERROR_HTTP_INVALID_SERVER_RESPONSE;
5912 BOOL codeHundred = FALSE;
5914 TRACE("-->\n");
5916 if(!is_valid_netconn(request->netconn))
5917 goto lend;
5919 /* clear old response headers (eg. from a redirect response) */
5920 HTTP_clear_response_headers( request );
5922 NETCON_set_timeout( request->netconn, FALSE, request->receive_timeout );
5923 do {
5925 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5927 buflen = MAX_REPLY_LEN;
5928 if ((res = read_line(request, bufferA, &buflen)))
5929 goto lend;
5931 if (!buflen) goto lend;
5933 rc += buflen;
5934 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5935 /* check is this a status code line? */
5936 if (!strncmpW(buffer, g_szHttp1_0, 4))
5938 /* split the version from the status code */
5939 status_code = strchrW( buffer, ' ' );
5940 if( !status_code )
5941 goto lend;
5942 *status_code++=0;
5944 /* split the status code from the status text */
5945 status_text = strchrW( status_code, ' ' );
5946 if( status_text )
5947 *status_text++=0;
5949 request->status_code = atoiW(status_code);
5951 TRACE("version [%s] status code [%s] status text [%s]\n",
5952 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
5954 codeHundred = request->status_code == HTTP_STATUS_CONTINUE;
5956 else if (!codeHundred)
5958 WARN("No status line at head of response (%s)\n", debugstr_w(buffer));
5960 heap_free(request->version);
5961 heap_free(request->statusText);
5963 request->status_code = HTTP_STATUS_OK;
5964 request->version = heap_strdupW(g_szHttp1_0);
5965 request->statusText = heap_strdupW(szOK);
5967 goto lend;
5969 } while (codeHundred);
5971 /* Add status code */
5972 HTTP_ProcessHeader(request, szStatus, status_code,
5973 HTTP_ADDHDR_FLAG_REPLACE);
5975 heap_free(request->version);
5976 heap_free(request->statusText);
5978 request->version = heap_strdupW(buffer);
5979 request->statusText = heap_strdupW(status_text ? status_text : emptyW);
5981 /* Restore the spaces */
5982 *(status_code-1) = ' ';
5983 if (status_text)
5984 *(status_text-1) = ' ';
5986 /* Parse each response line */
5989 buflen = MAX_REPLY_LEN;
5990 if (!read_line(request, bufferA, &buflen) && buflen)
5992 LPWSTR * pFieldAndValue;
5994 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
5996 if (!bufferA[0]) break;
5997 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5999 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
6000 if (pFieldAndValue)
6002 HTTP_ProcessHeader(request, pFieldAndValue[0], pFieldAndValue[1],
6003 HTTP_ADDREQ_FLAG_ADD );
6004 HTTP_FreeTokens(pFieldAndValue);
6007 else
6009 cbreaks++;
6010 if (cbreaks >= 2)
6011 break;
6013 }while(1);
6015 res = ERROR_SUCCESS;
6017 lend:
6019 *len = rc;
6020 TRACE("<--\n");
6021 return res;
6024 /***********************************************************************
6025 * HTTP_InterpretHttpHeader (internal)
6027 * Parse server response
6029 * RETURNS
6031 * Pointer to array of field, value, NULL on success.
6032 * NULL on error.
6034 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
6036 LPWSTR * pTokenPair;
6037 LPWSTR pszColon;
6038 INT len;
6040 pTokenPair = heap_alloc_zero(sizeof(*pTokenPair)*3);
6042 pszColon = strchrW(buffer, ':');
6043 /* must have two tokens */
6044 if (!pszColon)
6046 HTTP_FreeTokens(pTokenPair);
6047 if (buffer[0])
6048 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
6049 return NULL;
6052 pTokenPair[0] = heap_alloc((pszColon - buffer + 1) * sizeof(WCHAR));
6053 if (!pTokenPair[0])
6055 HTTP_FreeTokens(pTokenPair);
6056 return NULL;
6058 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
6059 pTokenPair[0][pszColon - buffer] = '\0';
6061 /* skip colon */
6062 pszColon++;
6063 len = strlenW(pszColon);
6064 pTokenPair[1] = heap_alloc((len + 1) * sizeof(WCHAR));
6065 if (!pTokenPair[1])
6067 HTTP_FreeTokens(pTokenPair);
6068 return NULL;
6070 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
6072 strip_spaces(pTokenPair[0]);
6073 strip_spaces(pTokenPair[1]);
6075 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
6076 return pTokenPair;
6079 /***********************************************************************
6080 * HTTP_ProcessHeader (internal)
6082 * Stuff header into header tables according to <dwModifier>
6086 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6088 static DWORD HTTP_ProcessHeader(http_request_t *request, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
6090 LPHTTPHEADERW lphttpHdr = NULL;
6091 INT index;
6092 BOOL request_only = dwModifier & HTTP_ADDHDR_FLAG_REQ;
6093 DWORD res = ERROR_HTTP_INVALID_HEADER;
6095 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
6097 EnterCriticalSection( &request->headers_section );
6099 /* REPLACE wins out over ADD */
6100 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6101 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
6103 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
6104 index = -1;
6105 else
6106 index = HTTP_GetCustomHeaderIndex(request, field, 0, request_only);
6108 if (index >= 0)
6110 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
6112 LeaveCriticalSection( &request->headers_section );
6113 return ERROR_HTTP_INVALID_HEADER;
6115 lphttpHdr = &request->custHeaders[index];
6117 else if (value)
6119 HTTPHEADERW hdr;
6121 hdr.lpszField = (LPWSTR)field;
6122 hdr.lpszValue = (LPWSTR)value;
6123 hdr.wFlags = hdr.wCount = 0;
6125 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6126 hdr.wFlags |= HDR_ISREQUEST;
6128 res = HTTP_InsertCustomHeader(request, &hdr);
6129 LeaveCriticalSection( &request->headers_section );
6130 return res;
6132 /* no value to delete */
6133 else
6135 LeaveCriticalSection( &request->headers_section );
6136 return ERROR_SUCCESS;
6139 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6140 lphttpHdr->wFlags |= HDR_ISREQUEST;
6141 else
6142 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
6144 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6146 HTTP_DeleteCustomHeader( request, index );
6148 if (value && value[0])
6150 HTTPHEADERW hdr;
6152 hdr.lpszField = (LPWSTR)field;
6153 hdr.lpszValue = (LPWSTR)value;
6154 hdr.wFlags = hdr.wCount = 0;
6156 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6157 hdr.wFlags |= HDR_ISREQUEST;
6159 res = HTTP_InsertCustomHeader(request, &hdr);
6160 LeaveCriticalSection( &request->headers_section );
6161 return res;
6164 LeaveCriticalSection( &request->headers_section );
6165 return ERROR_SUCCESS;
6167 else if (dwModifier & COALESCEFLAGS)
6169 LPWSTR lpsztmp;
6170 WCHAR ch = 0;
6171 INT len = 0;
6172 INT origlen = strlenW(lphttpHdr->lpszValue);
6173 INT valuelen = strlenW(value);
6175 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
6177 ch = ',';
6178 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6180 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6182 ch = ';';
6183 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6186 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
6188 lpsztmp = heap_realloc(lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
6189 if (lpsztmp)
6191 lphttpHdr->lpszValue = lpsztmp;
6192 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6193 if (ch > 0)
6195 lphttpHdr->lpszValue[origlen] = ch;
6196 origlen++;
6197 lphttpHdr->lpszValue[origlen] = ' ';
6198 origlen++;
6201 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
6202 lphttpHdr->lpszValue[len] = '\0';
6203 res = ERROR_SUCCESS;
6205 else
6207 WARN("heap_realloc (%d bytes) failed\n",len+1);
6208 res = ERROR_OUTOFMEMORY;
6211 TRACE("<-- %d\n", res);
6212 LeaveCriticalSection( &request->headers_section );
6213 return res;
6216 /***********************************************************************
6217 * HTTP_GetCustomHeaderIndex (internal)
6219 * Return index of custom header from header array
6220 * Headers section must be held
6222 static INT HTTP_GetCustomHeaderIndex(http_request_t *request, LPCWSTR lpszField,
6223 int requested_index, BOOL request_only)
6225 DWORD index;
6227 TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
6229 for (index = 0; index < request->nCustHeaders; index++)
6231 if (strcmpiW(request->custHeaders[index].lpszField, lpszField))
6232 continue;
6234 if (request_only && !(request->custHeaders[index].wFlags & HDR_ISREQUEST))
6235 continue;
6237 if (!request_only && (request->custHeaders[index].wFlags & HDR_ISREQUEST))
6238 continue;
6240 if (requested_index == 0)
6241 break;
6242 requested_index --;
6245 if (index >= request->nCustHeaders)
6246 index = -1;
6248 TRACE("Return: %d\n", index);
6249 return index;
6253 /***********************************************************************
6254 * HTTP_InsertCustomHeader (internal)
6256 * Insert header into array
6257 * Headers section must be held
6259 static DWORD HTTP_InsertCustomHeader(http_request_t *request, LPHTTPHEADERW lpHdr)
6261 INT count;
6262 LPHTTPHEADERW lph = NULL;
6264 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
6265 count = request->nCustHeaders + 1;
6266 if (count > 1)
6267 lph = heap_realloc_zero(request->custHeaders, sizeof(HTTPHEADERW) * count);
6268 else
6269 lph = heap_alloc_zero(sizeof(HTTPHEADERW) * count);
6271 if (!lph)
6272 return ERROR_OUTOFMEMORY;
6274 request->custHeaders = lph;
6275 request->custHeaders[count-1].lpszField = heap_strdupW(lpHdr->lpszField);
6276 request->custHeaders[count-1].lpszValue = heap_strdupW(lpHdr->lpszValue);
6277 request->custHeaders[count-1].wFlags = lpHdr->wFlags;
6278 request->custHeaders[count-1].wCount= lpHdr->wCount;
6279 request->nCustHeaders++;
6281 return ERROR_SUCCESS;
6285 /***********************************************************************
6286 * HTTP_DeleteCustomHeader (internal)
6288 * Delete header from array
6289 * If this function is called, the index may change.
6290 * Headers section must be held
6292 static BOOL HTTP_DeleteCustomHeader(http_request_t *request, DWORD index)
6294 if( request->nCustHeaders <= 0 )
6295 return FALSE;
6296 if( index >= request->nCustHeaders )
6297 return FALSE;
6298 request->nCustHeaders--;
6300 heap_free(request->custHeaders[index].lpszField);
6301 heap_free(request->custHeaders[index].lpszValue);
6303 memmove( &request->custHeaders[index], &request->custHeaders[index+1],
6304 (request->nCustHeaders - index)* sizeof(HTTPHEADERW) );
6305 memset( &request->custHeaders[request->nCustHeaders], 0, sizeof(HTTPHEADERW) );
6307 return TRUE;
6311 /***********************************************************************
6312 * HTTP_VerifyValidHeader (internal)
6314 * Verify the given header is not invalid for the given http request
6317 static BOOL HTTP_VerifyValidHeader(http_request_t *request, LPCWSTR field)
6319 /* Accept-Encoding is stripped from HTTP/1.0 requests. It is invalid */
6320 if (!strcmpW(request->version, g_szHttp1_0) && !strcmpiW(field, szAccept_Encoding))
6321 return ERROR_HTTP_INVALID_HEADER;
6323 return ERROR_SUCCESS;
6326 /***********************************************************************
6327 * IsHostInProxyBypassList (@)
6329 * Undocumented
6332 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
6334 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
6335 return FALSE;