ddraw/tests: Rewrite StructSizeTest().
[wine.git] / dlls / wininet / http.c
blob635b7d6915b5c0a4f533efdc2b7c734720848cdd
1 /*
2 * Wininet - HTTP Implementation
4 * Copyright 1999 Corel Corporation
5 * Copyright 2002 CodeWeavers Inc.
6 * Copyright 2002 TransGaming Technologies Inc.
7 * Copyright 2004 Mike McCormack for CodeWeavers
8 * Copyright 2005 Aric Stewart for CodeWeavers
9 * Copyright 2006 Robert Shearman for CodeWeavers
10 * Copyright 2011 Jacek Caban for CodeWeavers
12 * Ulrich Czekalla
13 * David Hammerton
15 * This library is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU Lesser General Public
17 * License as published by the Free Software Foundation; either
18 * version 2.1 of the License, or (at your option) any later version.
20 * This library is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 * Lesser General Public License for more details.
25 * You should have received a copy of the GNU Lesser General Public
26 * License along with this library; if not, write to the Free Software
27 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
30 #include "config.h"
32 #include <stdlib.h>
34 #ifdef HAVE_ZLIB
35 # include <zlib.h>
36 #endif
38 #include "winsock2.h"
39 #include "ws2ipdef.h"
41 #include <stdarg.h>
42 #include <stdio.h>
43 #include <time.h>
44 #include <assert.h>
46 #include "windef.h"
47 #include "winbase.h"
48 #include "wininet.h"
49 #include "winerror.h"
50 #include "winternl.h"
51 #define NO_SHLWAPI_STREAM
52 #define NO_SHLWAPI_REG
53 #define NO_SHLWAPI_STRFCNS
54 #define NO_SHLWAPI_GDI
55 #include "shlwapi.h"
56 #include "sspi.h"
57 #include "wincrypt.h"
58 #include "winuser.h"
60 #include "internet.h"
61 #include "wine/debug.h"
62 #include "wine/exception.h"
63 #include "wine/unicode.h"
65 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
67 static const WCHAR g_szHttp1_0[] = {'H','T','T','P','/','1','.','0',0};
68 static const WCHAR g_szHttp1_1[] = {'H','T','T','P','/','1','.','1',0};
69 static const WCHAR szOK[] = {'O','K',0};
70 static const WCHAR hostW[] = { 'H','o','s','t',0 };
71 static const WCHAR szAuthorization[] = { 'A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
72 static const WCHAR szProxy_Authorization[] = { 'P','r','o','x','y','-','A','u','t','h','o','r','i','z','a','t','i','o','n',0 };
73 static const WCHAR szStatus[] = { 'S','t','a','t','u','s',0 };
74 static const WCHAR szKeepAlive[] = {'K','e','e','p','-','A','l','i','v','e',0};
75 static const WCHAR szGET[] = { 'G','E','T', 0 };
76 static const WCHAR szHEAD[] = { 'H','E','A','D', 0 };
78 static const WCHAR szAccept[] = { 'A','c','c','e','p','t',0 };
79 static const WCHAR szAccept_Charset[] = { 'A','c','c','e','p','t','-','C','h','a','r','s','e','t', 0 };
80 static const WCHAR szAccept_Encoding[] = { 'A','c','c','e','p','t','-','E','n','c','o','d','i','n','g',0 };
81 static const WCHAR szAccept_Language[] = { 'A','c','c','e','p','t','-','L','a','n','g','u','a','g','e',0 };
82 static const WCHAR szAccept_Ranges[] = { 'A','c','c','e','p','t','-','R','a','n','g','e','s',0 };
83 static const WCHAR szAge[] = { 'A','g','e',0 };
84 static const WCHAR szAllow[] = { 'A','l','l','o','w',0 };
85 static const WCHAR szCache_Control[] = { 'C','a','c','h','e','-','C','o','n','t','r','o','l',0 };
86 static const WCHAR szConnection[] = { 'C','o','n','n','e','c','t','i','o','n',0 };
87 static const WCHAR szContent_Base[] = { 'C','o','n','t','e','n','t','-','B','a','s','e',0 };
88 static const WCHAR szContent_Disposition[] = { 'C','o','n','t','e','n','t','-','D','i','s','p','o','s','i','t','i','o','n',0 };
89 static const WCHAR szContent_Encoding[] = { 'C','o','n','t','e','n','t','-','E','n','c','o','d','i','n','g',0 };
90 static const WCHAR szContent_ID[] = { 'C','o','n','t','e','n','t','-','I','D',0 };
91 static const WCHAR szContent_Language[] = { 'C','o','n','t','e','n','t','-','L','a','n','g','u','a','g','e',0 };
92 static const WCHAR szContent_Length[] = { 'C','o','n','t','e','n','t','-','L','e','n','g','t','h',0 };
93 static const WCHAR szContent_Location[] = { 'C','o','n','t','e','n','t','-','L','o','c','a','t','i','o','n',0 };
94 static const WCHAR szContent_MD5[] = { 'C','o','n','t','e','n','t','-','M','D','5',0 };
95 static const WCHAR szContent_Range[] = { 'C','o','n','t','e','n','t','-','R','a','n','g','e',0 };
96 static const WCHAR szContent_Transfer_Encoding[] = { 'C','o','n','t','e','n','t','-','T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
97 static const WCHAR szContent_Type[] = { 'C','o','n','t','e','n','t','-','T','y','p','e',0 };
98 static const WCHAR szCookie[] = { 'C','o','o','k','i','e',0 };
99 static const WCHAR szDate[] = { 'D','a','t','e',0 };
100 static const WCHAR szFrom[] = { 'F','r','o','m',0 };
101 static const WCHAR szETag[] = { 'E','T','a','g',0 };
102 static const WCHAR szExpect[] = { 'E','x','p','e','c','t',0 };
103 static const WCHAR szExpires[] = { 'E','x','p','i','r','e','s',0 };
104 static const WCHAR szIf_Match[] = { 'I','f','-','M','a','t','c','h',0 };
105 static const WCHAR szIf_Modified_Since[] = { 'I','f','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
106 static const WCHAR szIf_None_Match[] = { 'I','f','-','N','o','n','e','-','M','a','t','c','h',0 };
107 static const WCHAR szIf_Range[] = { 'I','f','-','R','a','n','g','e',0 };
108 static const WCHAR szIf_Unmodified_Since[] = { 'I','f','-','U','n','m','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
109 static const WCHAR szLast_Modified[] = { 'L','a','s','t','-','M','o','d','i','f','i','e','d',0 };
110 static const WCHAR szLocation[] = { 'L','o','c','a','t','i','o','n',0 };
111 static const WCHAR szMax_Forwards[] = { 'M','a','x','-','F','o','r','w','a','r','d','s',0 };
112 static const WCHAR szMime_Version[] = { 'M','i','m','e','-','V','e','r','s','i','o','n',0 };
113 static const WCHAR szPragma[] = { 'P','r','a','g','m','a',0 };
114 static const WCHAR szProxy_Authenticate[] = { 'P','r','o','x','y','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
115 static const WCHAR szProxy_Connection[] = { 'P','r','o','x','y','-','C','o','n','n','e','c','t','i','o','n',0 };
116 static const WCHAR szPublic[] = { 'P','u','b','l','i','c',0 };
117 static const WCHAR szRange[] = { 'R','a','n','g','e',0 };
118 static const WCHAR szReferer[] = { 'R','e','f','e','r','e','r',0 };
119 static const WCHAR szRetry_After[] = { 'R','e','t','r','y','-','A','f','t','e','r',0 };
120 static const WCHAR szServer[] = { 'S','e','r','v','e','r',0 };
121 static const WCHAR szSet_Cookie[] = { 'S','e','t','-','C','o','o','k','i','e',0 };
122 static const WCHAR szTransfer_Encoding[] = { 'T','r','a','n','s','f','e','r','-','E','n','c','o','d','i','n','g',0 };
123 static const WCHAR szUnless_Modified_Since[] = { 'U','n','l','e','s','s','-','M','o','d','i','f','i','e','d','-','S','i','n','c','e',0 };
124 static const WCHAR szUpgrade[] = { 'U','p','g','r','a','d','e',0 };
125 static const WCHAR szURI[] = { 'U','R','I',0 };
126 static const WCHAR szUser_Agent[] = { 'U','s','e','r','-','A','g','e','n','t',0 };
127 static const WCHAR szVary[] = { 'V','a','r','y',0 };
128 static const WCHAR szVia[] = { 'V','i','a',0 };
129 static const WCHAR szWarning[] = { 'W','a','r','n','i','n','g',0 };
130 static const WCHAR szWWW_Authenticate[] = { 'W','W','W','-','A','u','t','h','e','n','t','i','c','a','t','e',0 };
132 static const WCHAR emptyW[] = {0};
134 #define HTTP_REFERER szReferer
135 #define HTTP_ACCEPT szAccept
136 #define HTTP_USERAGENT szUser_Agent
138 #define HTTP_ADDHDR_FLAG_ADD 0x20000000
139 #define HTTP_ADDHDR_FLAG_ADD_IF_NEW 0x10000000
140 #define HTTP_ADDHDR_FLAG_COALESCE 0x40000000
141 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA 0x40000000
142 #define HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON 0x01000000
143 #define HTTP_ADDHDR_FLAG_REPLACE 0x80000000
144 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
146 #define COLLECT_TIME 60000
148 #define ARRAYSIZE(array) (sizeof(array)/sizeof((array)[0]))
150 struct HttpAuthInfo
152 LPWSTR scheme;
153 CredHandle cred;
154 CtxtHandle ctx;
155 TimeStamp exp;
156 ULONG attr;
157 ULONG max_token;
158 void *auth_data;
159 unsigned int auth_data_len;
160 BOOL finished; /* finished authenticating */
164 typedef struct _basicAuthorizationData
166 struct list entry;
168 LPWSTR host;
169 LPWSTR realm;
170 LPSTR authorization;
171 UINT authorizationLen;
172 } basicAuthorizationData;
174 typedef struct _authorizationData
176 struct list entry;
178 LPWSTR host;
179 LPWSTR scheme;
180 LPWSTR domain;
181 UINT domain_len;
182 LPWSTR user;
183 UINT user_len;
184 LPWSTR password;
185 UINT password_len;
186 } authorizationData;
188 static struct list basicAuthorizationCache = LIST_INIT(basicAuthorizationCache);
189 static struct list authorizationCache = LIST_INIT(authorizationCache);
191 static CRITICAL_SECTION authcache_cs;
192 static CRITICAL_SECTION_DEBUG critsect_debug =
194 0, 0, &authcache_cs,
195 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
196 0, 0, { (DWORD_PTR)(__FILE__ ": authcache_cs") }
198 static CRITICAL_SECTION authcache_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
200 static DWORD HTTP_GetResponseHeaders(http_request_t *req, INT *len);
201 static DWORD HTTP_ProcessHeader(http_request_t *req, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
202 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
203 static DWORD HTTP_InsertCustomHeader(http_request_t *req, LPHTTPHEADERW lpHdr);
204 static INT HTTP_GetCustomHeaderIndex(http_request_t *req, LPCWSTR lpszField, INT index, BOOL Request);
205 static BOOL HTTP_DeleteCustomHeader(http_request_t *req, DWORD index);
206 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
207 static DWORD HTTP_HttpQueryInfoW(http_request_t*, DWORD, LPVOID, LPDWORD, LPDWORD);
208 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
209 static BOOL drain_content(http_request_t*,BOOL);
211 static CRITICAL_SECTION connection_pool_cs;
212 static CRITICAL_SECTION_DEBUG connection_pool_debug =
214 0, 0, &connection_pool_cs,
215 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
216 0, 0, { (DWORD_PTR)(__FILE__ ": connection_pool_cs") }
218 static CRITICAL_SECTION connection_pool_cs = { &connection_pool_debug, -1, 0, 0, 0, 0 };
220 static struct list connection_pool = LIST_INIT(connection_pool);
221 static BOOL collector_running;
223 void server_addref(server_t *server)
225 InterlockedIncrement(&server->ref);
228 void server_release(server_t *server)
230 if(InterlockedDecrement(&server->ref))
231 return;
233 list_remove(&server->entry);
235 if(server->cert_chain)
236 CertFreeCertificateChain(server->cert_chain);
237 heap_free(server->name);
238 heap_free(server->scheme_host_port);
239 heap_free(server);
242 static BOOL process_host_port(server_t *server)
244 BOOL default_port;
245 size_t name_len;
246 WCHAR *buf;
248 static const WCHAR httpW[] = {'h','t','t','p',0};
249 static const WCHAR httpsW[] = {'h','t','t','p','s',0};
250 static const WCHAR formatW[] = {'%','s',':','/','/','%','s',':','%','u',0};
252 name_len = strlenW(server->name);
253 buf = heap_alloc((name_len + 10 /* strlen("://:<port>") */)*sizeof(WCHAR) + sizeof(httpsW));
254 if(!buf)
255 return FALSE;
257 sprintfW(buf, formatW, server->is_https ? httpsW : httpW, server->name, server->port);
258 server->scheme_host_port = buf;
260 server->host_port = server->scheme_host_port + 7 /* strlen("http://") */;
261 if(server->is_https)
262 server->host_port++;
264 default_port = server->port == (server->is_https ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT);
265 server->canon_host_port = default_port ? server->name : server->host_port;
266 return TRUE;
269 server_t *get_server(substr_t name, INTERNET_PORT port, BOOL is_https, BOOL do_create)
271 server_t *iter, *server = NULL;
273 EnterCriticalSection(&connection_pool_cs);
275 LIST_FOR_EACH_ENTRY(iter, &connection_pool, server_t, entry) {
276 if(iter->port == port && name.len == strlenW(iter->name) && !strncmpW(iter->name, name.str, name.len)
277 && iter->is_https == is_https) {
278 server = iter;
279 server_addref(server);
280 break;
284 if(!server && do_create) {
285 server = heap_alloc_zero(sizeof(*server));
286 if(server) {
287 server->ref = 2; /* list reference and return */
288 server->port = port;
289 server->is_https = is_https;
290 list_init(&server->conn_pool);
291 server->name = heap_strndupW(name.str, name.len);
292 if(server->name && process_host_port(server)) {
293 list_add_head(&connection_pool, &server->entry);
294 }else {
295 heap_free(server);
296 server = NULL;
301 LeaveCriticalSection(&connection_pool_cs);
303 return server;
306 BOOL collect_connections(collect_type_t collect_type)
308 netconn_t *netconn, *netconn_safe;
309 server_t *server, *server_safe;
310 BOOL remaining = FALSE;
311 DWORD64 now;
313 now = GetTickCount64();
315 LIST_FOR_EACH_ENTRY_SAFE(server, server_safe, &connection_pool, server_t, entry) {
316 LIST_FOR_EACH_ENTRY_SAFE(netconn, netconn_safe, &server->conn_pool, netconn_t, pool_entry) {
317 if(collect_type > COLLECT_TIMEOUT || netconn->keep_until < now) {
318 TRACE("freeing %p\n", netconn);
319 list_remove(&netconn->pool_entry);
320 free_netconn(netconn);
321 }else {
322 remaining = TRUE;
326 if(collect_type == COLLECT_CLEANUP) {
327 list_remove(&server->entry);
328 list_init(&server->entry);
329 server_release(server);
333 return remaining;
336 static DWORD WINAPI collect_connections_proc(void *arg)
338 BOOL remaining_conns;
340 do {
341 /* FIXME: Use more sophisticated method */
342 Sleep(5000);
344 EnterCriticalSection(&connection_pool_cs);
346 remaining_conns = collect_connections(COLLECT_TIMEOUT);
347 if(!remaining_conns)
348 collector_running = FALSE;
350 LeaveCriticalSection(&connection_pool_cs);
351 }while(remaining_conns);
353 FreeLibraryAndExitThread(WININET_hModule, 0);
356 /***********************************************************************
357 * HTTP_GetHeader (internal)
359 * Headers section must be held
361 static LPHTTPHEADERW HTTP_GetHeader(http_request_t *req, LPCWSTR head)
363 int HeaderIndex = 0;
364 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
365 if (HeaderIndex == -1)
366 return NULL;
367 else
368 return &req->custHeaders[HeaderIndex];
371 static WCHAR *get_host_header( http_request_t *req )
373 HTTPHEADERW *header;
374 WCHAR *ret = NULL;
376 EnterCriticalSection( &req->headers_section );
377 if ((header = HTTP_GetHeader( req, hostW ))) ret = heap_strdupW( header->lpszValue );
378 else ret = heap_strdupW( req->server->canon_host_port );
379 LeaveCriticalSection( &req->headers_section );
380 return ret;
383 typedef enum {
384 BLOCKING_ALLOW,
385 BLOCKING_DISALLOW,
386 BLOCKING_WAITALL
387 } blocking_mode_t;
389 struct data_stream_vtbl_t {
390 DWORD (*get_avail_data)(data_stream_t*,http_request_t*);
391 BOOL (*end_of_data)(data_stream_t*,http_request_t*);
392 DWORD (*read)(data_stream_t*,http_request_t*,BYTE*,DWORD,DWORD*,blocking_mode_t);
393 BOOL (*drain_content)(data_stream_t*,http_request_t*);
394 void (*destroy)(data_stream_t*);
397 typedef struct {
398 data_stream_t data_stream;
400 BYTE buf[READ_BUFFER_SIZE];
401 DWORD buf_size;
402 DWORD buf_pos;
403 DWORD chunk_size;
405 enum {
406 CHUNKED_STREAM_STATE_READING_CHUNK_SIZE,
407 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE,
408 CHUNKED_STREAM_STATE_READING_CHUNK,
409 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA,
410 CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END,
411 CHUNKED_STREAM_STATE_END_OF_STREAM
412 } state;
413 } chunked_stream_t;
415 static inline void destroy_data_stream(data_stream_t *stream)
417 stream->vtbl->destroy(stream);
420 static void reset_data_stream(http_request_t *req)
422 destroy_data_stream(req->data_stream);
423 req->data_stream = &req->netconn_stream.data_stream;
424 req->read_pos = req->read_size = req->netconn_stream.content_read = 0;
425 req->read_gzip = FALSE;
428 static void remove_header( http_request_t *request, const WCHAR *str, BOOL from_request )
430 int index;
431 EnterCriticalSection( &request->headers_section );
432 index = HTTP_GetCustomHeaderIndex( request, str, 0, from_request );
433 if (index != -1) HTTP_DeleteCustomHeader( request, index );
434 LeaveCriticalSection( &request->headers_section );
437 #ifdef HAVE_ZLIB
439 typedef struct {
440 data_stream_t stream;
441 data_stream_t *parent_stream;
442 z_stream zstream;
443 BYTE buf[READ_BUFFER_SIZE];
444 DWORD buf_size;
445 DWORD buf_pos;
446 BOOL end_of_data;
447 } gzip_stream_t;
449 static DWORD gzip_get_avail_data(data_stream_t *stream, http_request_t *req)
451 /* Allow reading only from read buffer */
452 return 0;
455 static BOOL gzip_end_of_data(data_stream_t *stream, http_request_t *req)
457 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
458 return gzip_stream->end_of_data
459 || (!gzip_stream->buf_size && gzip_stream->parent_stream->vtbl->end_of_data(gzip_stream->parent_stream, req));
462 static DWORD gzip_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
463 DWORD *read, blocking_mode_t blocking_mode)
465 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
466 z_stream *zstream = &gzip_stream->zstream;
467 DWORD current_read, ret_read = 0;
468 int zres;
469 DWORD res = ERROR_SUCCESS;
471 TRACE("(%d %d)\n", size, blocking_mode);
473 while(size && !gzip_stream->end_of_data) {
474 if(!gzip_stream->buf_size) {
475 if(gzip_stream->buf_pos) {
476 if(gzip_stream->buf_size)
477 memmove(gzip_stream->buf, gzip_stream->buf+gzip_stream->buf_pos, gzip_stream->buf_size);
478 gzip_stream->buf_pos = 0;
480 res = gzip_stream->parent_stream->vtbl->read(gzip_stream->parent_stream, req, gzip_stream->buf+gzip_stream->buf_size,
481 sizeof(gzip_stream->buf)-gzip_stream->buf_size, &current_read, blocking_mode);
482 gzip_stream->buf_size += current_read;
483 if(res != ERROR_SUCCESS)
484 break;
486 if(!current_read) {
487 if(blocking_mode != BLOCKING_DISALLOW) {
488 WARN("unexpected end of data\n");
489 gzip_stream->end_of_data = TRUE;
491 break;
495 zstream->next_in = gzip_stream->buf+gzip_stream->buf_pos;
496 zstream->avail_in = gzip_stream->buf_size;
497 zstream->next_out = buf+ret_read;
498 zstream->avail_out = size;
499 zres = inflate(&gzip_stream->zstream, 0);
500 current_read = size - zstream->avail_out;
501 size -= current_read;
502 ret_read += current_read;
503 gzip_stream->buf_size -= zstream->next_in - (gzip_stream->buf+gzip_stream->buf_pos);
504 gzip_stream->buf_pos = zstream->next_in-gzip_stream->buf;
505 if(zres == Z_STREAM_END) {
506 TRACE("end of data\n");
507 gzip_stream->end_of_data = TRUE;
508 inflateEnd(zstream);
509 }else if(zres != Z_OK) {
510 WARN("inflate failed %d: %s\n", zres, debugstr_a(zstream->msg));
511 if(!ret_read)
512 res = ERROR_INTERNET_DECODING_FAILED;
513 break;
516 if(ret_read && blocking_mode == BLOCKING_ALLOW)
517 blocking_mode = BLOCKING_DISALLOW;
520 TRACE("read %u bytes\n", ret_read);
521 *read = ret_read;
522 return res;
525 static BOOL gzip_drain_content(data_stream_t *stream, http_request_t *req)
527 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
528 return gzip_stream->parent_stream->vtbl->drain_content(gzip_stream->parent_stream, req);
531 static void gzip_destroy(data_stream_t *stream)
533 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
535 destroy_data_stream(gzip_stream->parent_stream);
537 if(!gzip_stream->end_of_data)
538 inflateEnd(&gzip_stream->zstream);
539 heap_free(gzip_stream);
542 static const data_stream_vtbl_t gzip_stream_vtbl = {
543 gzip_get_avail_data,
544 gzip_end_of_data,
545 gzip_read,
546 gzip_drain_content,
547 gzip_destroy
550 static voidpf wininet_zalloc(voidpf opaque, uInt items, uInt size)
552 return heap_alloc(items*size);
555 static void wininet_zfree(voidpf opaque, voidpf address)
557 heap_free(address);
560 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
562 gzip_stream_t *gzip_stream;
563 int zres;
565 gzip_stream = heap_alloc_zero(sizeof(gzip_stream_t));
566 if(!gzip_stream)
567 return ERROR_OUTOFMEMORY;
569 gzip_stream->stream.vtbl = &gzip_stream_vtbl;
570 gzip_stream->zstream.zalloc = wininet_zalloc;
571 gzip_stream->zstream.zfree = wininet_zfree;
573 zres = inflateInit2(&gzip_stream->zstream, is_gzip ? 0x1f : -15);
574 if(zres != Z_OK) {
575 ERR("inflateInit failed: %d\n", zres);
576 heap_free(gzip_stream);
577 return ERROR_OUTOFMEMORY;
580 remove_header(req, szContent_Length, FALSE);
582 if(req->read_size) {
583 memcpy(gzip_stream->buf, req->read_buf+req->read_pos, req->read_size);
584 gzip_stream->buf_size = req->read_size;
585 req->read_pos = req->read_size = 0;
588 req->read_gzip = TRUE;
589 gzip_stream->parent_stream = req->data_stream;
590 req->data_stream = &gzip_stream->stream;
591 return ERROR_SUCCESS;
594 #else
596 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
598 ERR("gzip stream not supported, missing zlib.\n");
599 return ERROR_SUCCESS;
602 #endif
604 /***********************************************************************
605 * HTTP_FreeTokens (internal)
607 * Frees table of pointers.
609 static void HTTP_FreeTokens(LPWSTR * token_array)
611 int i;
612 for (i = 0; token_array[i]; i++) heap_free(token_array[i]);
613 heap_free(token_array);
616 static void HTTP_FixURL(http_request_t *request)
618 static const WCHAR szSlash[] = { '/',0 };
619 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
621 /* If we don't have a path we set it to root */
622 if (NULL == request->path)
623 request->path = heap_strdupW(szSlash);
624 else /* remove \r and \n*/
626 int nLen = strlenW(request->path);
627 while ((nLen >0 ) && ((request->path[nLen-1] == '\r')||(request->path[nLen-1] == '\n')))
629 nLen--;
630 request->path[nLen]='\0';
632 /* Replace '\' with '/' */
633 while (nLen>0) {
634 nLen--;
635 if (request->path[nLen] == '\\') request->path[nLen]='/';
639 if(CSTR_EQUAL != CompareStringW( LOCALE_INVARIANT, NORM_IGNORECASE,
640 request->path, strlenW(request->path), szHttp, strlenW(szHttp) )
641 && request->path[0] != '/') /* not an absolute path ?? --> fix it !! */
643 WCHAR *fixurl = heap_alloc((strlenW(request->path) + 2)*sizeof(WCHAR));
644 *fixurl = '/';
645 strcpyW(fixurl + 1, request->path);
646 heap_free( request->path );
647 request->path = fixurl;
651 static WCHAR* build_request_header(http_request_t *request, const WCHAR *verb,
652 const WCHAR *path, const WCHAR *version, BOOL use_cr)
654 static const WCHAR szSpace[] = {' ',0};
655 static const WCHAR szColon[] = {':',' ',0};
656 static const WCHAR szCr[] = {'\r',0};
657 static const WCHAR szLf[] = {'\n',0};
658 LPWSTR requestString;
659 DWORD len, n;
660 LPCWSTR *req;
661 UINT i;
663 EnterCriticalSection( &request->headers_section );
665 /* allocate space for an array of all the string pointers to be added */
666 len = request->nCustHeaders * 5 + 10;
667 if (!(req = heap_alloc( len * sizeof(const WCHAR *) )))
669 LeaveCriticalSection( &request->headers_section );
670 return NULL;
673 /* add the verb, path and HTTP version string */
674 n = 0;
675 req[n++] = verb;
676 req[n++] = szSpace;
677 req[n++] = path;
678 req[n++] = szSpace;
679 req[n++] = version;
680 if (use_cr)
681 req[n++] = szCr;
682 req[n++] = szLf;
684 /* Append custom request headers */
685 for (i = 0; i < request->nCustHeaders; i++)
687 if (request->custHeaders[i].wFlags & HDR_ISREQUEST)
689 req[n++] = request->custHeaders[i].lpszField;
690 req[n++] = szColon;
691 req[n++] = request->custHeaders[i].lpszValue;
692 if (use_cr)
693 req[n++] = szCr;
694 req[n++] = szLf;
696 TRACE("Adding custom header %s (%s)\n",
697 debugstr_w(request->custHeaders[i].lpszField),
698 debugstr_w(request->custHeaders[i].lpszValue));
701 if (use_cr)
702 req[n++] = szCr;
703 req[n++] = szLf;
704 req[n] = NULL;
706 requestString = HTTP_build_req( req, 4 );
707 heap_free( req );
708 LeaveCriticalSection( &request->headers_section );
709 return requestString;
712 static WCHAR* build_response_header(http_request_t *request, BOOL use_cr)
714 static const WCHAR colonW[] = { ':',' ',0 };
715 static const WCHAR crW[] = { '\r',0 };
716 static const WCHAR lfW[] = { '\n',0 };
717 static const WCHAR status_fmt[] = { ' ','%','u',' ',0 };
718 const WCHAR **req;
719 WCHAR *ret, buf[14];
720 DWORD i, n = 0;
722 EnterCriticalSection( &request->headers_section );
724 if (!(req = heap_alloc( (request->nCustHeaders * 5 + 8) * sizeof(WCHAR *) )))
726 LeaveCriticalSection( &request->headers_section );
727 return NULL;
730 if (request->status_code)
732 req[n++] = request->version;
733 sprintfW(buf, status_fmt, request->status_code);
734 req[n++] = buf;
735 req[n++] = request->statusText;
736 if (use_cr)
737 req[n++] = crW;
738 req[n++] = lfW;
741 for(i = 0; i < request->nCustHeaders; i++)
743 if(!(request->custHeaders[i].wFlags & HDR_ISREQUEST)
744 && strcmpW(request->custHeaders[i].lpszField, szStatus))
746 req[n++] = request->custHeaders[i].lpszField;
747 req[n++] = colonW;
748 req[n++] = request->custHeaders[i].lpszValue;
749 if(use_cr)
750 req[n++] = crW;
751 req[n++] = lfW;
753 TRACE("Adding custom header %s (%s)\n",
754 debugstr_w(request->custHeaders[i].lpszField),
755 debugstr_w(request->custHeaders[i].lpszValue));
758 if(use_cr)
759 req[n++] = crW;
760 req[n++] = lfW;
761 req[n] = NULL;
763 ret = HTTP_build_req(req, 0);
764 heap_free(req);
765 LeaveCriticalSection( &request->headers_section );
766 return ret;
769 static void HTTP_ProcessCookies( http_request_t *request )
771 int HeaderIndex;
772 int numCookies = 0;
773 LPHTTPHEADERW setCookieHeader;
775 if(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES)
776 return;
778 EnterCriticalSection( &request->headers_section );
780 while((HeaderIndex = HTTP_GetCustomHeaderIndex(request, szSet_Cookie, numCookies++, FALSE)) != -1)
782 const WCHAR *data;
783 substr_t name;
785 setCookieHeader = &request->custHeaders[HeaderIndex];
787 if (!setCookieHeader->lpszValue)
788 continue;
790 data = strchrW(setCookieHeader->lpszValue, '=');
791 if(!data)
792 continue;
794 name = substr(setCookieHeader->lpszValue, data - setCookieHeader->lpszValue);
795 data++;
796 set_cookie(substrz(request->server->name), substrz(request->path), name, substrz(data), INTERNET_COOKIE_HTTPONLY);
799 LeaveCriticalSection( &request->headers_section );
802 static void strip_spaces(LPWSTR start)
804 LPWSTR str = start;
805 LPWSTR end;
807 while (*str == ' ')
808 str++;
810 if (str != start)
811 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
813 end = start + strlenW(start) - 1;
814 while (end >= start && *end == ' ')
816 *end = '\0';
817 end--;
821 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue, LPWSTR *pszRealm )
823 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
824 static const WCHAR szRealm[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
825 BOOL is_basic;
826 is_basic = !strncmpiW(pszAuthValue, szBasic, ARRAYSIZE(szBasic)) &&
827 ((pszAuthValue[ARRAYSIZE(szBasic)] == ' ') || !pszAuthValue[ARRAYSIZE(szBasic)]);
828 if (is_basic && pszRealm)
830 LPCWSTR token;
831 LPCWSTR ptr = &pszAuthValue[ARRAYSIZE(szBasic)];
832 LPCWSTR realm;
833 ptr++;
834 *pszRealm=NULL;
835 token = strchrW(ptr,'=');
836 if (!token)
837 return TRUE;
838 realm = ptr;
839 while (*realm == ' ')
840 realm++;
841 if(!strncmpiW(realm, szRealm, ARRAYSIZE(szRealm)) &&
842 (realm[ARRAYSIZE(szRealm)] == ' ' || realm[ARRAYSIZE(szRealm)] == '='))
844 token++;
845 while (*token == ' ')
846 token++;
847 if (*token == '\0')
848 return TRUE;
849 *pszRealm = heap_strdupW(token);
850 strip_spaces(*pszRealm);
854 return is_basic;
857 static void destroy_authinfo( struct HttpAuthInfo *authinfo )
859 if (!authinfo) return;
861 if (SecIsValidHandle(&authinfo->ctx))
862 DeleteSecurityContext(&authinfo->ctx);
863 if (SecIsValidHandle(&authinfo->cred))
864 FreeCredentialsHandle(&authinfo->cred);
866 heap_free(authinfo->auth_data);
867 heap_free(authinfo->scheme);
868 heap_free(authinfo);
871 static UINT retrieve_cached_basic_authorization(const WCHAR *host, const WCHAR *realm, char **auth_data)
873 basicAuthorizationData *ad;
874 UINT rc = 0;
876 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host),debugstr_w(realm));
878 EnterCriticalSection(&authcache_cs);
879 LIST_FOR_EACH_ENTRY(ad, &basicAuthorizationCache, basicAuthorizationData, entry)
881 if (!strcmpiW(host, ad->host) && (!realm || !strcmpW(realm, ad->realm)))
883 TRACE("Authorization found in cache\n");
884 *auth_data = heap_alloc(ad->authorizationLen);
885 memcpy(*auth_data,ad->authorization,ad->authorizationLen);
886 rc = ad->authorizationLen;
887 break;
890 LeaveCriticalSection(&authcache_cs);
891 return rc;
894 static void cache_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR auth_data, UINT auth_data_len)
896 struct list *cursor;
897 basicAuthorizationData* ad = NULL;
899 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host),debugstr_w(realm),debugstr_an(auth_data,auth_data_len));
901 EnterCriticalSection(&authcache_cs);
902 LIST_FOR_EACH(cursor, &basicAuthorizationCache)
904 basicAuthorizationData *check = LIST_ENTRY(cursor,basicAuthorizationData,entry);
905 if (!strcmpiW(host,check->host) && !strcmpW(realm,check->realm))
907 ad = check;
908 break;
912 if (ad)
914 TRACE("Found match in cache, replacing\n");
915 heap_free(ad->authorization);
916 ad->authorization = heap_alloc(auth_data_len);
917 memcpy(ad->authorization, auth_data, auth_data_len);
918 ad->authorizationLen = auth_data_len;
920 else
922 ad = heap_alloc(sizeof(basicAuthorizationData));
923 ad->host = heap_strdupW(host);
924 ad->realm = heap_strdupW(realm);
925 ad->authorization = heap_alloc(auth_data_len);
926 memcpy(ad->authorization, auth_data, auth_data_len);
927 ad->authorizationLen = auth_data_len;
928 list_add_head(&basicAuthorizationCache,&ad->entry);
929 TRACE("authorization cached\n");
931 LeaveCriticalSection(&authcache_cs);
934 static BOOL retrieve_cached_authorization(LPWSTR host, LPWSTR scheme,
935 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
937 authorizationData *ad;
939 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
941 EnterCriticalSection(&authcache_cs);
942 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry) {
943 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
944 TRACE("Authorization found in cache\n");
946 nt_auth_identity->User = heap_strdupW(ad->user);
947 nt_auth_identity->Password = heap_strdupW(ad->password);
948 nt_auth_identity->Domain = heap_alloc(sizeof(WCHAR)*ad->domain_len);
949 if(!nt_auth_identity->User || !nt_auth_identity->Password ||
950 (!nt_auth_identity->Domain && ad->domain_len)) {
951 heap_free(nt_auth_identity->User);
952 heap_free(nt_auth_identity->Password);
953 heap_free(nt_auth_identity->Domain);
954 break;
957 nt_auth_identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
958 nt_auth_identity->UserLength = ad->user_len;
959 nt_auth_identity->PasswordLength = ad->password_len;
960 memcpy(nt_auth_identity->Domain, ad->domain, sizeof(WCHAR)*ad->domain_len);
961 nt_auth_identity->DomainLength = ad->domain_len;
962 LeaveCriticalSection(&authcache_cs);
963 return TRUE;
966 LeaveCriticalSection(&authcache_cs);
968 return FALSE;
971 static void cache_authorization(LPWSTR host, LPWSTR scheme,
972 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
974 authorizationData *ad;
975 BOOL found = FALSE;
977 TRACE("Caching authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
979 EnterCriticalSection(&authcache_cs);
980 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry)
981 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
982 found = TRUE;
983 break;
986 if(found) {
987 heap_free(ad->user);
988 heap_free(ad->password);
989 heap_free(ad->domain);
990 } else {
991 ad = heap_alloc(sizeof(authorizationData));
992 if(!ad) {
993 LeaveCriticalSection(&authcache_cs);
994 return;
997 ad->host = heap_strdupW(host);
998 ad->scheme = heap_strdupW(scheme);
999 list_add_head(&authorizationCache, &ad->entry);
1002 ad->user = heap_strndupW(nt_auth_identity->User, nt_auth_identity->UserLength);
1003 ad->password = heap_strndupW(nt_auth_identity->Password, nt_auth_identity->PasswordLength);
1004 ad->domain = heap_strndupW(nt_auth_identity->Domain, nt_auth_identity->DomainLength);
1005 ad->user_len = nt_auth_identity->UserLength;
1006 ad->password_len = nt_auth_identity->PasswordLength;
1007 ad->domain_len = nt_auth_identity->DomainLength;
1009 if(!ad->host || !ad->scheme || !ad->user || !ad->password
1010 || (nt_auth_identity->Domain && !ad->domain)) {
1011 heap_free(ad->host);
1012 heap_free(ad->scheme);
1013 heap_free(ad->user);
1014 heap_free(ad->password);
1015 heap_free(ad->domain);
1016 list_remove(&ad->entry);
1017 heap_free(ad);
1020 LeaveCriticalSection(&authcache_cs);
1023 static BOOL HTTP_DoAuthorization( http_request_t *request, LPCWSTR pszAuthValue,
1024 struct HttpAuthInfo **ppAuthInfo,
1025 LPWSTR domain_and_username, LPWSTR password,
1026 LPWSTR host )
1028 SECURITY_STATUS sec_status;
1029 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
1030 BOOL first = FALSE;
1031 LPWSTR szRealm = NULL;
1033 TRACE("%s\n", debugstr_w(pszAuthValue));
1035 if (!pAuthInfo)
1037 TimeStamp exp;
1039 first = TRUE;
1040 pAuthInfo = heap_alloc(sizeof(*pAuthInfo));
1041 if (!pAuthInfo)
1042 return FALSE;
1044 SecInvalidateHandle(&pAuthInfo->cred);
1045 SecInvalidateHandle(&pAuthInfo->ctx);
1046 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
1047 pAuthInfo->attr = 0;
1048 pAuthInfo->auth_data = NULL;
1049 pAuthInfo->auth_data_len = 0;
1050 pAuthInfo->finished = FALSE;
1052 if (is_basic_auth_value(pszAuthValue,NULL))
1054 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
1055 pAuthInfo->scheme = heap_strdupW(szBasic);
1056 if (!pAuthInfo->scheme)
1058 heap_free(pAuthInfo);
1059 return FALSE;
1062 else
1064 PVOID pAuthData;
1065 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
1067 pAuthInfo->scheme = heap_strdupW(pszAuthValue);
1068 if (!pAuthInfo->scheme)
1070 heap_free(pAuthInfo);
1071 return FALSE;
1074 if (domain_and_username)
1076 WCHAR *user = strchrW(domain_and_username, '\\');
1077 WCHAR *domain = domain_and_username;
1079 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1081 pAuthData = &nt_auth_identity;
1083 if (user) user++;
1084 else
1086 user = domain_and_username;
1087 domain = NULL;
1090 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1091 nt_auth_identity.User = user;
1092 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
1093 nt_auth_identity.Domain = domain;
1094 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
1095 nt_auth_identity.Password = password;
1096 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
1098 cache_authorization(host, pAuthInfo->scheme, &nt_auth_identity);
1100 else if(retrieve_cached_authorization(host, pAuthInfo->scheme, &nt_auth_identity))
1101 pAuthData = &nt_auth_identity;
1102 else
1103 /* use default credentials */
1104 pAuthData = NULL;
1106 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
1107 SECPKG_CRED_OUTBOUND, NULL,
1108 pAuthData, NULL,
1109 NULL, &pAuthInfo->cred,
1110 &exp);
1112 if(pAuthData && !domain_and_username) {
1113 heap_free(nt_auth_identity.User);
1114 heap_free(nt_auth_identity.Domain);
1115 heap_free(nt_auth_identity.Password);
1118 if (sec_status == SEC_E_OK)
1120 PSecPkgInfoW sec_pkg_info;
1121 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
1122 if (sec_status == SEC_E_OK)
1124 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
1125 FreeContextBuffer(sec_pkg_info);
1128 if (sec_status != SEC_E_OK)
1130 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1131 debugstr_w(pAuthInfo->scheme), sec_status);
1132 heap_free(pAuthInfo->scheme);
1133 heap_free(pAuthInfo);
1134 return FALSE;
1137 *ppAuthInfo = pAuthInfo;
1139 else if (pAuthInfo->finished)
1140 return FALSE;
1142 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
1143 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
1145 ERR("authentication scheme changed from %s to %s\n",
1146 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
1147 return FALSE;
1150 if (is_basic_auth_value(pszAuthValue,&szRealm))
1152 int userlen;
1153 int passlen;
1154 char *auth_data = NULL;
1155 UINT auth_data_len = 0;
1157 TRACE("basic authentication realm %s\n",debugstr_w(szRealm));
1159 if (!domain_and_username)
1161 if (host && szRealm)
1162 auth_data_len = retrieve_cached_basic_authorization(host, szRealm,&auth_data);
1163 if (auth_data_len == 0)
1165 heap_free(szRealm);
1166 return FALSE;
1169 else
1171 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
1172 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
1174 /* length includes a nul terminator, which will be re-used for the ':' */
1175 auth_data = heap_alloc(userlen + 1 + passlen);
1176 if (!auth_data)
1178 heap_free(szRealm);
1179 return FALSE;
1182 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
1183 auth_data[userlen] = ':';
1184 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
1185 auth_data_len = userlen + 1 + passlen;
1186 if (host && szRealm)
1187 cache_basic_authorization(host, szRealm, auth_data, auth_data_len);
1190 pAuthInfo->auth_data = auth_data;
1191 pAuthInfo->auth_data_len = auth_data_len;
1192 pAuthInfo->finished = TRUE;
1193 heap_free(szRealm);
1194 return TRUE;
1196 else
1198 LPCWSTR pszAuthData;
1199 SecBufferDesc out_desc, in_desc;
1200 SecBuffer out, in;
1201 unsigned char *buffer;
1202 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
1203 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
1205 in.BufferType = SECBUFFER_TOKEN;
1206 in.cbBuffer = 0;
1207 in.pvBuffer = NULL;
1209 in_desc.ulVersion = 0;
1210 in_desc.cBuffers = 1;
1211 in_desc.pBuffers = &in;
1213 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
1214 if (*pszAuthData == ' ')
1216 pszAuthData++;
1217 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
1218 in.pvBuffer = heap_alloc(in.cbBuffer);
1219 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
1222 buffer = heap_alloc(pAuthInfo->max_token);
1224 out.BufferType = SECBUFFER_TOKEN;
1225 out.cbBuffer = pAuthInfo->max_token;
1226 out.pvBuffer = buffer;
1228 out_desc.ulVersion = 0;
1229 out_desc.cBuffers = 1;
1230 out_desc.pBuffers = &out;
1232 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
1233 first ? NULL : &pAuthInfo->ctx,
1234 first ? request->server->name : NULL,
1235 context_req, 0, SECURITY_NETWORK_DREP,
1236 in.pvBuffer ? &in_desc : NULL,
1237 0, &pAuthInfo->ctx, &out_desc,
1238 &pAuthInfo->attr, &pAuthInfo->exp);
1239 if (sec_status == SEC_E_OK)
1241 pAuthInfo->finished = TRUE;
1242 pAuthInfo->auth_data = out.pvBuffer;
1243 pAuthInfo->auth_data_len = out.cbBuffer;
1244 TRACE("sending last auth packet\n");
1246 else if (sec_status == SEC_I_CONTINUE_NEEDED)
1248 pAuthInfo->auth_data = out.pvBuffer;
1249 pAuthInfo->auth_data_len = out.cbBuffer;
1250 TRACE("sending next auth packet\n");
1252 else
1254 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
1255 heap_free(out.pvBuffer);
1256 destroy_authinfo(pAuthInfo);
1257 *ppAuthInfo = NULL;
1258 return FALSE;
1262 return TRUE;
1265 /***********************************************************************
1266 * HTTP_HttpAddRequestHeadersW (internal)
1268 static DWORD HTTP_HttpAddRequestHeadersW(http_request_t *request,
1269 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1271 LPWSTR lpszStart;
1272 LPWSTR lpszEnd;
1273 LPWSTR buffer;
1274 DWORD len, res = ERROR_HTTP_INVALID_HEADER;
1276 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
1278 if( dwHeaderLength == ~0U )
1279 len = strlenW(lpszHeader);
1280 else
1281 len = dwHeaderLength;
1282 buffer = heap_alloc(sizeof(WCHAR)*(len+1));
1283 lstrcpynW( buffer, lpszHeader, len + 1);
1285 lpszStart = buffer;
1289 LPWSTR * pFieldAndValue;
1291 lpszEnd = lpszStart;
1293 while (*lpszEnd != '\0')
1295 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1296 break;
1297 lpszEnd++;
1300 if (*lpszStart == '\0')
1301 break;
1303 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1305 *lpszEnd = '\0';
1306 lpszEnd++; /* Jump over newline */
1308 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
1309 if (*lpszStart == '\0')
1311 /* Skip 0-length headers */
1312 lpszStart = lpszEnd;
1313 res = ERROR_SUCCESS;
1314 continue;
1316 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
1317 if (pFieldAndValue)
1319 res = HTTP_ProcessHeader(request, pFieldAndValue[0],
1320 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
1321 HTTP_FreeTokens(pFieldAndValue);
1324 lpszStart = lpszEnd;
1325 } while (res == ERROR_SUCCESS);
1327 heap_free(buffer);
1328 return res;
1331 /***********************************************************************
1332 * HttpAddRequestHeadersW (WININET.@)
1334 * Adds one or more HTTP header to the request handler
1336 * NOTE
1337 * On Windows if dwHeaderLength includes the trailing '\0', then
1338 * HttpAddRequestHeadersW() adds it too. However this results in an
1339 * invalid HTTP header which is rejected by some servers so we probably
1340 * don't need to match Windows on that point.
1342 * RETURNS
1343 * TRUE on success
1344 * FALSE on failure
1347 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
1348 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1350 http_request_t *request;
1351 DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
1353 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1355 if (!lpszHeader)
1356 return TRUE;
1358 request = (http_request_t*) get_handle_object( hHttpRequest );
1359 if (request && request->hdr.htype == WH_HHTTPREQ)
1360 res = HTTP_HttpAddRequestHeadersW( request, lpszHeader, dwHeaderLength, dwModifier );
1361 if( request )
1362 WININET_Release( &request->hdr );
1364 if(res != ERROR_SUCCESS)
1365 SetLastError(res);
1366 return res == ERROR_SUCCESS;
1369 /***********************************************************************
1370 * HttpAddRequestHeadersA (WININET.@)
1372 * Adds one or more HTTP header to the request handler
1374 * RETURNS
1375 * TRUE on success
1376 * FALSE on failure
1379 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
1380 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1382 WCHAR *headers = NULL;
1383 BOOL r;
1385 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1387 if(lpszHeader)
1388 headers = heap_strndupAtoW(lpszHeader, dwHeaderLength, &dwHeaderLength);
1390 r = HttpAddRequestHeadersW(hHttpRequest, headers, dwHeaderLength, dwModifier);
1392 heap_free(headers);
1393 return r;
1396 static void free_accept_types( WCHAR **accept_types )
1398 WCHAR *ptr, **types = accept_types;
1400 if (!types) return;
1401 while ((ptr = *types))
1403 heap_free( ptr );
1404 types++;
1406 heap_free( accept_types );
1409 static WCHAR **convert_accept_types( const char **accept_types )
1411 unsigned int count;
1412 const char **types = accept_types;
1413 WCHAR **typesW;
1414 BOOL invalid_pointer = FALSE;
1416 if (!types) return NULL;
1417 count = 0;
1418 while (*types)
1420 __TRY
1422 /* find out how many there are */
1423 if (*types && **types)
1425 TRACE("accept type: %s\n", debugstr_a(*types));
1426 count++;
1429 __EXCEPT_PAGE_FAULT
1431 WARN("invalid accept type pointer\n");
1432 invalid_pointer = TRUE;
1434 __ENDTRY;
1435 types++;
1437 if (invalid_pointer) return NULL;
1438 if (!(typesW = heap_alloc( sizeof(WCHAR *) * (count + 1) ))) return NULL;
1439 count = 0;
1440 types = accept_types;
1441 while (*types)
1443 if (*types && **types) typesW[count++] = heap_strdupAtoW( *types );
1444 types++;
1446 typesW[count] = NULL;
1447 return typesW;
1450 /***********************************************************************
1451 * HttpOpenRequestA (WININET.@)
1453 * Open a HTTP request handle
1455 * RETURNS
1456 * HINTERNET a HTTP request handle on success
1457 * NULL on failure
1460 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
1461 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
1462 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
1463 DWORD dwFlags, DWORD_PTR dwContext)
1465 LPWSTR szVerb = NULL, szObjectName = NULL;
1466 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
1467 HINTERNET rc = NULL;
1469 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
1470 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
1471 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
1472 dwFlags, dwContext);
1474 if (lpszVerb)
1476 szVerb = heap_strdupAtoW(lpszVerb);
1477 if ( !szVerb )
1478 goto end;
1481 if (lpszObjectName)
1483 szObjectName = heap_strdupAtoW(lpszObjectName);
1484 if ( !szObjectName )
1485 goto end;
1488 if (lpszVersion)
1490 szVersion = heap_strdupAtoW(lpszVersion);
1491 if ( !szVersion )
1492 goto end;
1495 if (lpszReferrer)
1497 szReferrer = heap_strdupAtoW(lpszReferrer);
1498 if ( !szReferrer )
1499 goto end;
1502 szAcceptTypes = convert_accept_types( lpszAcceptTypes );
1503 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName, szVersion, szReferrer,
1504 (const WCHAR **)szAcceptTypes, dwFlags, dwContext);
1506 end:
1507 free_accept_types(szAcceptTypes);
1508 heap_free(szReferrer);
1509 heap_free(szVersion);
1510 heap_free(szObjectName);
1511 heap_free(szVerb);
1512 return rc;
1515 /***********************************************************************
1516 * HTTP_EncodeBase64
1518 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1520 UINT n = 0, x;
1521 static const CHAR HTTP_Base64Enc[] =
1522 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1524 while( len > 0 )
1526 /* first 6 bits, all from bin[0] */
1527 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1528 x = (bin[0] & 3) << 4;
1530 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1531 if( len == 1 )
1533 base64[n++] = HTTP_Base64Enc[x];
1534 base64[n++] = '=';
1535 base64[n++] = '=';
1536 break;
1538 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1539 x = ( bin[1] & 0x0f ) << 2;
1541 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1542 if( len == 2 )
1544 base64[n++] = HTTP_Base64Enc[x];
1545 base64[n++] = '=';
1546 break;
1548 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1550 /* last 6 bits, all from bin [2] */
1551 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1552 bin += 3;
1553 len -= 3;
1555 base64[n] = 0;
1556 return n;
1559 static const signed char HTTP_Base64Dec[] =
1561 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x00 */
1562 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x10 */
1563 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 0x20 */
1564 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, /* 0x30 */
1565 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 0x40 */
1566 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 0x50 */
1567 -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 0x60 */
1568 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 /* 0x70 */
1571 /***********************************************************************
1572 * HTTP_DecodeBase64
1574 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1576 unsigned int n = 0;
1578 while(*base64)
1580 signed char in[4];
1582 if (base64[0] >= ARRAYSIZE(HTTP_Base64Dec) ||
1583 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1584 base64[1] >= ARRAYSIZE(HTTP_Base64Dec) ||
1585 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1587 WARN("invalid base64: %s\n", debugstr_w(base64));
1588 return 0;
1590 if (bin)
1591 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1592 n++;
1594 if ((base64[2] == '=') && (base64[3] == '='))
1595 break;
1596 if (base64[2] > ARRAYSIZE(HTTP_Base64Dec) ||
1597 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1599 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1600 return 0;
1602 if (bin)
1603 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1604 n++;
1606 if (base64[3] == '=')
1607 break;
1608 if (base64[3] > ARRAYSIZE(HTTP_Base64Dec) ||
1609 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1611 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1612 return 0;
1614 if (bin)
1615 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1616 n++;
1618 base64 += 4;
1621 return n;
1624 static WCHAR *encode_auth_data( const WCHAR *scheme, const char *data, UINT data_len )
1626 WCHAR *ret;
1627 UINT len, scheme_len = strlenW( scheme );
1629 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1630 len = scheme_len + 1 + ((data_len + 2) * 4) / 3;
1631 if (!(ret = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return NULL;
1632 memcpy( ret, scheme, scheme_len * sizeof(WCHAR) );
1633 ret[scheme_len] = ' ';
1634 HTTP_EncodeBase64( data, data_len, ret + scheme_len + 1 );
1635 return ret;
1639 /***********************************************************************
1640 * HTTP_InsertAuthorization
1642 * Insert or delete the authorization field in the request header.
1644 static BOOL HTTP_InsertAuthorization( http_request_t *request, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1646 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1647 WCHAR *host, *authorization = NULL;
1649 if (pAuthInfo)
1651 if (pAuthInfo->auth_data_len)
1653 if (!(authorization = encode_auth_data(pAuthInfo->scheme, pAuthInfo->auth_data, pAuthInfo->auth_data_len)))
1654 return FALSE;
1656 /* clear the data as it isn't valid now that it has been sent to the
1657 * server, unless it's Basic authentication which doesn't do
1658 * connection tracking */
1659 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1661 heap_free(pAuthInfo->auth_data);
1662 pAuthInfo->auth_data = NULL;
1663 pAuthInfo->auth_data_len = 0;
1667 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1669 HTTP_ProcessHeader(request, header, authorization,
1670 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
1671 heap_free(authorization);
1673 else if (!strcmpW(header, szAuthorization) && (host = get_host_header(request)))
1675 UINT data_len;
1676 char *data;
1678 if ((data_len = retrieve_cached_basic_authorization(host, NULL, &data)))
1680 TRACE("Found cached basic authorization for %s\n", debugstr_w(host));
1682 if (!(authorization = encode_auth_data(wszBasic, data, data_len)))
1684 heap_free(data);
1685 heap_free(host);
1686 return FALSE;
1689 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1691 HTTP_ProcessHeader(request, header, authorization,
1692 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD);
1693 heap_free(data);
1694 heap_free(authorization);
1696 heap_free(host);
1698 return TRUE;
1701 static WCHAR *build_proxy_path_url(http_request_t *req)
1703 DWORD size, len;
1704 WCHAR *url;
1706 len = strlenW(req->server->scheme_host_port);
1707 size = len + strlenW(req->path) + 1;
1708 if(*req->path != '/')
1709 size++;
1710 url = heap_alloc(size * sizeof(WCHAR));
1711 if(!url)
1712 return NULL;
1714 memcpy(url, req->server->scheme_host_port, len*sizeof(WCHAR));
1715 if(*req->path != '/')
1716 url[len++] = '/';
1718 strcpyW(url+len, req->path);
1720 TRACE("url=%s\n", debugstr_w(url));
1721 return url;
1724 static BOOL HTTP_DomainMatches(LPCWSTR server, substr_t domain)
1726 static const WCHAR localW[] = { '<','l','o','c','a','l','>',0 };
1727 const WCHAR *dot, *ptr;
1728 int len;
1730 if(domain.len == sizeof(localW)/sizeof(WCHAR)-1 && !strncmpiW(domain.str, localW, domain.len) && !strchrW(server, '.' ))
1731 return TRUE;
1733 if(domain.len && *domain.str != '*')
1734 return domain.len == strlenW(server) && !strncmpiW(server, domain.str, domain.len);
1736 if(domain.len < 2 || domain.str[1] != '.')
1737 return FALSE;
1739 /* For a hostname to match a wildcard, the last domain must match
1740 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1741 * hostname is www.foo.a.b, it matches, but a.b does not.
1743 dot = strchrW(server, '.');
1744 if(!dot)
1745 return FALSE;
1747 len = strlenW(dot + 1);
1748 if(len <= domain.len - 2)
1749 return FALSE;
1751 /* The server's domain is longer than the wildcard, so it
1752 * could be a subdomain. Compare the last portion of the
1753 * server's domain.
1755 ptr = dot + 1 + len - domain.len + 2;
1756 if(!strncmpiW(ptr, domain.str+2, domain.len-2))
1757 /* This is only a match if the preceding character is
1758 * a '.', i.e. that it is a matching domain. E.g.
1759 * if domain is '*.b.c' and server is 'www.ab.c' they
1760 * do not match.
1762 return *(ptr - 1) == '.';
1764 return len == domain.len-2 && !strncmpiW(dot + 1, domain.str + 2, len);
1767 static BOOL HTTP_ShouldBypassProxy(appinfo_t *lpwai, LPCWSTR server)
1769 LPCWSTR ptr;
1770 BOOL ret = FALSE;
1772 if (!lpwai->proxyBypass) return FALSE;
1773 ptr = lpwai->proxyBypass;
1774 while(1) {
1775 LPCWSTR tmp = ptr;
1777 ptr = strchrW( ptr, ';' );
1778 if (!ptr)
1779 ptr = strchrW( tmp, ' ' );
1780 if (!ptr)
1781 ptr = tmp + strlenW(tmp);
1782 ret = HTTP_DomainMatches( server, substr(tmp, ptr-tmp) );
1783 if (ret || !*ptr)
1784 break;
1785 ptr++;
1787 return ret;
1790 /***********************************************************************
1791 * HTTP_DealWithProxy
1793 static BOOL HTTP_DealWithProxy(appinfo_t *hIC, http_session_t *session, http_request_t *request)
1795 static const WCHAR protoHttp[] = { 'h','t','t','p',0 };
1796 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1797 static WCHAR szNul[] = { 0 };
1798 URL_COMPONENTSW UrlComponents = { sizeof(UrlComponents) };
1799 server_t *new_server = NULL;
1800 WCHAR *proxy;
1802 proxy = INTERNET_FindProxyForProtocol(hIC->proxy, protoHttp);
1803 if(!proxy)
1804 return FALSE;
1805 if(CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1806 proxy, strlenW(szHttp), szHttp, strlenW(szHttp))) {
1807 WCHAR *proxy_url = heap_alloc(strlenW(proxy)*sizeof(WCHAR) + sizeof(szHttp));
1808 if(!proxy_url) {
1809 heap_free(proxy);
1810 return FALSE;
1812 strcpyW(proxy_url, szHttp);
1813 strcatW(proxy_url, proxy);
1814 heap_free(proxy);
1815 proxy = proxy_url;
1818 UrlComponents.dwHostNameLength = 1;
1819 if(InternetCrackUrlW(proxy, 0, 0, &UrlComponents) && UrlComponents.dwHostNameLength) {
1820 if( !request->path )
1821 request->path = szNul;
1823 new_server = get_server(substr(UrlComponents.lpszHostName, UrlComponents.dwHostNameLength),
1824 UrlComponents.nPort, UrlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
1826 heap_free(proxy);
1827 if(!new_server)
1828 return FALSE;
1830 request->proxy = new_server;
1832 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server->name), new_server->port);
1833 return TRUE;
1836 static DWORD HTTP_ResolveName(http_request_t *request)
1838 server_t *server = request->proxy ? request->proxy : request->server;
1839 int addr_len;
1841 if(server->addr_len)
1842 return ERROR_SUCCESS;
1844 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1845 INTERNET_STATUS_RESOLVING_NAME,
1846 server->name,
1847 (strlenW(server->name)+1) * sizeof(WCHAR));
1849 addr_len = sizeof(server->addr);
1850 if (!GetAddress(server->name, server->port, (SOCKADDR*)&server->addr, &addr_len, server->addr_str))
1851 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1853 server->addr_len = addr_len;
1854 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1855 INTERNET_STATUS_NAME_RESOLVED,
1856 server->addr_str, strlen(server->addr_str)+1);
1858 TRACE("resolved %s to %s\n", debugstr_w(server->name), server->addr_str);
1859 return ERROR_SUCCESS;
1862 static WCHAR *compose_request_url(http_request_t *req)
1864 static const WCHAR http[] = { 'h','t','t','p',':','/','/',0 };
1865 static const WCHAR https[] = { 'h','t','t','p','s',':','/','/',0 };
1866 const WCHAR *host, *scheme;
1867 WCHAR *buf, *ptr;
1868 size_t len;
1870 host = req->server->canon_host_port;
1872 if (req->server->is_https)
1873 scheme = https;
1874 else
1875 scheme = http;
1877 len = strlenW(scheme) + strlenW(host) + (req->path[0] != '/' ? 1 : 0) + strlenW(req->path);
1878 ptr = buf = heap_alloc((len+1) * sizeof(WCHAR));
1879 if(buf) {
1880 strcpyW(ptr, scheme);
1881 ptr += strlenW(ptr);
1883 strcpyW(ptr, host);
1884 ptr += strlenW(ptr);
1886 if(req->path[0] != '/')
1887 *ptr++ = '/';
1889 strcpyW(ptr, req->path);
1890 ptr += strlenW(ptr);
1891 *ptr = 0;
1894 return buf;
1898 /***********************************************************************
1899 * HTTPREQ_Destroy (internal)
1901 * Deallocate request handle
1904 static void HTTPREQ_Destroy(object_header_t *hdr)
1906 http_request_t *request = (http_request_t*) hdr;
1907 DWORD i;
1909 TRACE("\n");
1911 if(request->hCacheFile)
1912 CloseHandle(request->hCacheFile);
1913 if(request->req_file)
1914 req_file_release(request->req_file);
1916 request->headers_section.DebugInfo->Spare[0] = 0;
1917 DeleteCriticalSection( &request->headers_section );
1918 request->read_section.DebugInfo->Spare[0] = 0;
1919 DeleteCriticalSection( &request->read_section );
1920 WININET_Release(&request->session->hdr);
1922 destroy_authinfo(request->authInfo);
1923 destroy_authinfo(request->proxyAuthInfo);
1925 if(request->server)
1926 server_release(request->server);
1927 if(request->proxy)
1928 server_release(request->proxy);
1930 heap_free(request->path);
1931 heap_free(request->verb);
1932 heap_free(request->version);
1933 heap_free(request->statusText);
1935 for (i = 0; i < request->nCustHeaders; i++)
1937 heap_free(request->custHeaders[i].lpszField);
1938 heap_free(request->custHeaders[i].lpszValue);
1940 destroy_data_stream(request->data_stream);
1941 heap_free(request->custHeaders);
1944 static void http_release_netconn(http_request_t *req, BOOL reuse)
1946 TRACE("%p %p %x\n",req, req->netconn, reuse);
1948 if(!is_valid_netconn(req->netconn))
1949 return;
1951 if(reuse && req->netconn->keep_alive) {
1952 BOOL run_collector;
1954 EnterCriticalSection(&connection_pool_cs);
1956 list_add_head(&req->netconn->server->conn_pool, &req->netconn->pool_entry);
1957 req->netconn->keep_until = GetTickCount64() + COLLECT_TIME;
1958 req->netconn = NULL;
1960 run_collector = !collector_running;
1961 collector_running = TRUE;
1963 LeaveCriticalSection(&connection_pool_cs);
1965 if(run_collector) {
1966 HANDLE thread = NULL;
1967 HMODULE module;
1969 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR*)WININET_hModule, &module);
1970 if(module)
1971 thread = CreateThread(NULL, 0, collect_connections_proc, NULL, 0, NULL);
1972 if(!thread) {
1973 EnterCriticalSection(&connection_pool_cs);
1974 collector_running = FALSE;
1975 LeaveCriticalSection(&connection_pool_cs);
1977 if(module)
1978 FreeLibrary(module);
1980 else
1981 CloseHandle(thread);
1983 return;
1986 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1987 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1989 close_netconn(req->netconn);
1991 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1992 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1995 static BOOL HTTP_KeepAlive(http_request_t *request)
1997 WCHAR szVersion[10];
1998 WCHAR szConnectionResponse[20];
1999 DWORD dwBufferSize = sizeof(szVersion);
2000 BOOL keepalive = FALSE;
2002 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
2003 * the connection is keep-alive by default */
2004 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_VERSION, szVersion, &dwBufferSize, NULL) == ERROR_SUCCESS
2005 && !strcmpiW(szVersion, g_szHttp1_1))
2007 keepalive = TRUE;
2010 dwBufferSize = sizeof(szConnectionResponse);
2011 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS
2012 || HTTP_HttpQueryInfoW(request, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS)
2014 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
2017 return keepalive;
2020 static void HTTPREQ_CloseConnection(object_header_t *hdr)
2022 http_request_t *req = (http_request_t*)hdr;
2024 http_release_netconn(req, drain_content(req, FALSE));
2027 static DWORD str_to_buffer(const WCHAR *str, void *buffer, DWORD *size, BOOL unicode)
2029 int len;
2030 if (unicode)
2032 WCHAR *buf = buffer;
2034 if (str) len = strlenW(str);
2035 else len = 0;
2036 if (*size < (len + 1) * sizeof(WCHAR))
2038 *size = (len + 1) * sizeof(WCHAR);
2039 return ERROR_INSUFFICIENT_BUFFER;
2041 if (str) strcpyW(buf, str);
2042 else buf[0] = 0;
2044 *size = len;
2045 return ERROR_SUCCESS;
2047 else
2049 char *buf = buffer;
2051 if (str) len = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
2052 else len = 1;
2053 if (*size < len)
2055 *size = len;
2056 return ERROR_INSUFFICIENT_BUFFER;
2058 if (str) WideCharToMultiByte(CP_ACP, 0, str, -1, buf, *size, NULL, NULL);
2059 else buf[0] = 0;
2061 *size = len - 1;
2062 return ERROR_SUCCESS;
2066 static DWORD HTTPREQ_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2068 http_request_t *req = (http_request_t*)hdr;
2070 switch(option) {
2071 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO:
2073 INTERNET_DIAGNOSTIC_SOCKET_INFO *info = buffer;
2075 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2077 if (*size < sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO))
2078 return ERROR_INSUFFICIENT_BUFFER;
2079 *size = sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO);
2080 /* FIXME: can't get a SOCKET from our connection since we don't use
2081 * winsock
2083 info->Socket = 0;
2084 /* FIXME: get source port from req->netConnection */
2085 info->SourcePort = 0;
2086 info->DestPort = req->server->port;
2087 info->Flags = 0;
2088 if (HTTP_KeepAlive(req))
2089 info->Flags |= IDSI_FLAG_KEEP_ALIVE;
2090 if (req->proxy)
2091 info->Flags |= IDSI_FLAG_PROXY;
2092 if (is_valid_netconn(req->netconn) && req->netconn->secure)
2093 info->Flags |= IDSI_FLAG_SECURE;
2095 return ERROR_SUCCESS;
2098 case 98:
2099 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2100 /* fall through */
2101 case INTERNET_OPTION_SECURITY_FLAGS:
2103 DWORD flags;
2105 if (*size < sizeof(ULONG))
2106 return ERROR_INSUFFICIENT_BUFFER;
2108 *size = sizeof(DWORD);
2109 flags = is_valid_netconn(req->netconn) ? req->netconn->security_flags : req->security_flags | req->server->security_flags;
2110 *(DWORD *)buffer = flags;
2112 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags);
2113 return ERROR_SUCCESS;
2116 case INTERNET_OPTION_HANDLE_TYPE:
2117 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2119 if (*size < sizeof(ULONG))
2120 return ERROR_INSUFFICIENT_BUFFER;
2122 *size = sizeof(DWORD);
2123 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
2124 return ERROR_SUCCESS;
2126 case INTERNET_OPTION_URL: {
2127 WCHAR *url;
2128 DWORD res;
2130 TRACE("INTERNET_OPTION_URL\n");
2132 url = compose_request_url(req);
2133 if(!url)
2134 return ERROR_OUTOFMEMORY;
2136 res = str_to_buffer(url, buffer, size, unicode);
2137 heap_free(url);
2138 return res;
2140 case INTERNET_OPTION_USER_AGENT:
2141 return str_to_buffer(req->session->appInfo->agent, buffer, size, unicode);
2142 case INTERNET_OPTION_USERNAME:
2143 return str_to_buffer(req->session->userName, buffer, size, unicode);
2144 case INTERNET_OPTION_PASSWORD:
2145 return str_to_buffer(req->session->password, buffer, size, unicode);
2146 case INTERNET_OPTION_PROXY_USERNAME:
2147 return str_to_buffer(req->session->appInfo->proxyUsername, buffer, size, unicode);
2148 case INTERNET_OPTION_PROXY_PASSWORD:
2149 return str_to_buffer(req->session->appInfo->proxyPassword, buffer, size, unicode);
2151 case INTERNET_OPTION_CACHE_TIMESTAMPS: {
2152 INTERNET_CACHE_ENTRY_INFOW *info;
2153 INTERNET_CACHE_TIMESTAMPS *ts = buffer;
2154 DWORD nbytes, error;
2155 BOOL ret;
2157 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2159 if(!req->req_file)
2160 return ERROR_FILE_NOT_FOUND;
2162 if (*size < sizeof(*ts))
2164 *size = sizeof(*ts);
2165 return ERROR_INSUFFICIENT_BUFFER;
2168 nbytes = 0;
2169 ret = GetUrlCacheEntryInfoW(req->req_file->url, NULL, &nbytes);
2170 error = GetLastError();
2171 if (!ret && error == ERROR_INSUFFICIENT_BUFFER)
2173 if (!(info = heap_alloc(nbytes)))
2174 return ERROR_OUTOFMEMORY;
2176 GetUrlCacheEntryInfoW(req->req_file->url, info, &nbytes);
2178 ts->ftExpires = info->ExpireTime;
2179 ts->ftLastModified = info->LastModifiedTime;
2181 heap_free(info);
2182 *size = sizeof(*ts);
2183 return ERROR_SUCCESS;
2185 return error;
2188 case INTERNET_OPTION_DATAFILE_NAME: {
2189 DWORD req_size;
2191 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2193 if(!req->req_file) {
2194 *size = 0;
2195 return ERROR_INTERNET_ITEM_NOT_FOUND;
2198 if(unicode) {
2199 req_size = (lstrlenW(req->req_file->file_name)+1) * sizeof(WCHAR);
2200 if(*size < req_size)
2201 return ERROR_INSUFFICIENT_BUFFER;
2203 *size = req_size;
2204 memcpy(buffer, req->req_file->file_name, *size);
2205 return ERROR_SUCCESS;
2206 }else {
2207 req_size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name, -1, NULL, 0, NULL, NULL);
2208 if (req_size > *size)
2209 return ERROR_INSUFFICIENT_BUFFER;
2211 *size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name,
2212 -1, buffer, *size, NULL, NULL);
2213 return ERROR_SUCCESS;
2217 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
2218 PCCERT_CONTEXT context;
2220 if(!req->netconn)
2221 return ERROR_INTERNET_INVALID_OPERATION;
2223 if(*size < sizeof(INTERNET_CERTIFICATE_INFOA)) {
2224 *size = sizeof(INTERNET_CERTIFICATE_INFOA);
2225 return ERROR_INSUFFICIENT_BUFFER;
2228 context = (PCCERT_CONTEXT)NETCON_GetCert(req->netconn);
2229 if(context) {
2230 INTERNET_CERTIFICATE_INFOA *info = (INTERNET_CERTIFICATE_INFOA*)buffer;
2231 DWORD len;
2233 memset(info, 0, sizeof(*info));
2234 info->ftExpiry = context->pCertInfo->NotAfter;
2235 info->ftStart = context->pCertInfo->NotBefore;
2236 len = CertNameToStrA(context->dwCertEncodingType,
2237 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2238 info->lpszSubjectInfo = LocalAlloc(0, len);
2239 if(info->lpszSubjectInfo)
2240 CertNameToStrA(context->dwCertEncodingType,
2241 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2242 info->lpszSubjectInfo, len);
2243 len = CertNameToStrA(context->dwCertEncodingType,
2244 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2245 info->lpszIssuerInfo = LocalAlloc(0, len);
2246 if(info->lpszIssuerInfo)
2247 CertNameToStrA(context->dwCertEncodingType,
2248 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2249 info->lpszIssuerInfo, len);
2250 info->dwKeySize = NETCON_GetCipherStrength(req->netconn);
2251 CertFreeCertificateContext(context);
2252 return ERROR_SUCCESS;
2254 return ERROR_NOT_SUPPORTED;
2256 case INTERNET_OPTION_CONNECT_TIMEOUT:
2257 if (*size < sizeof(DWORD))
2258 return ERROR_INSUFFICIENT_BUFFER;
2260 *size = sizeof(DWORD);
2261 *(DWORD *)buffer = req->connect_timeout;
2262 return ERROR_SUCCESS;
2263 case INTERNET_OPTION_REQUEST_FLAGS: {
2264 DWORD flags = 0;
2266 if (*size < sizeof(DWORD))
2267 return ERROR_INSUFFICIENT_BUFFER;
2269 /* FIXME: Add support for:
2270 * INTERNET_REQFLAG_FROM_CACHE
2271 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2274 if(req->proxy)
2275 flags |= INTERNET_REQFLAG_VIA_PROXY;
2276 if(!req->status_code)
2277 flags |= INTERNET_REQFLAG_NO_HEADERS;
2279 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags);
2281 *size = sizeof(DWORD);
2282 *(DWORD*)buffer = flags;
2283 return ERROR_SUCCESS;
2287 return INET_QueryOption(hdr, option, buffer, size, unicode);
2290 static DWORD HTTPREQ_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
2292 http_request_t *req = (http_request_t*)hdr;
2294 switch(option) {
2295 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2296 TRACE("Undocumented option 99\n");
2298 if (!buffer || size != sizeof(DWORD))
2299 return ERROR_INVALID_PARAMETER;
2300 if(*(DWORD*)buffer & ~SECURITY_SET_MASK)
2301 return ERROR_INTERNET_OPTION_NOT_SETTABLE;
2303 /* fall through */
2304 case INTERNET_OPTION_SECURITY_FLAGS:
2306 DWORD flags;
2308 if (!buffer || size != sizeof(DWORD))
2309 return ERROR_INVALID_PARAMETER;
2310 flags = *(DWORD *)buffer;
2311 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags);
2312 flags &= SECURITY_SET_MASK;
2313 req->security_flags |= flags;
2314 if(is_valid_netconn(req->netconn))
2315 req->netconn->security_flags |= flags;
2316 return ERROR_SUCCESS;
2318 case INTERNET_OPTION_CONNECT_TIMEOUT:
2319 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2320 req->connect_timeout = *(DWORD *)buffer;
2321 return ERROR_SUCCESS;
2323 case INTERNET_OPTION_SEND_TIMEOUT:
2324 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2325 req->send_timeout = *(DWORD *)buffer;
2326 return ERROR_SUCCESS;
2328 case INTERNET_OPTION_RECEIVE_TIMEOUT:
2329 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2330 req->receive_timeout = *(DWORD *)buffer;
2331 return ERROR_SUCCESS;
2333 case INTERNET_OPTION_USERNAME:
2334 heap_free(req->session->userName);
2335 if (!(req->session->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2336 return ERROR_SUCCESS;
2338 case INTERNET_OPTION_PASSWORD:
2339 heap_free(req->session->password);
2340 if (!(req->session->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2341 return ERROR_SUCCESS;
2343 case INTERNET_OPTION_PROXY_USERNAME:
2344 heap_free(req->session->appInfo->proxyUsername);
2345 if (!(req->session->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2346 return ERROR_SUCCESS;
2348 case INTERNET_OPTION_PROXY_PASSWORD:
2349 heap_free(req->session->appInfo->proxyPassword);
2350 if (!(req->session->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2351 return ERROR_SUCCESS;
2353 case INTERNET_OPTION_HTTP_DECODING:
2354 if(size != sizeof(BOOL))
2355 return ERROR_INVALID_PARAMETER;
2356 req->decoding = *(BOOL*)buffer;
2357 return ERROR_SUCCESS;
2360 return INET_SetOption(hdr, option, buffer, size);
2363 static void commit_cache_entry(http_request_t *req)
2365 WCHAR *header;
2366 DWORD header_len;
2367 BOOL res;
2369 TRACE("%p\n", req);
2371 CloseHandle(req->hCacheFile);
2372 req->hCacheFile = NULL;
2374 header = build_response_header(req, TRUE);
2375 header_len = (header ? strlenW(header) : 0);
2376 res = CommitUrlCacheEntryW(req->req_file->url, req->req_file->file_name, req->expires,
2377 req->last_modified, NORMAL_CACHE_ENTRY,
2378 header, header_len, NULL, 0);
2379 if(res)
2380 req->req_file->is_committed = TRUE;
2381 else
2382 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2383 heap_free(header);
2386 static void create_cache_entry(http_request_t *req)
2388 static const WCHAR no_cacheW[] = {'n','o','-','c','a','c','h','e',0};
2389 static const WCHAR no_storeW[] = {'n','o','-','s','t','o','r','e',0};
2391 WCHAR file_name[MAX_PATH+1];
2392 WCHAR *url;
2393 BOOL b = TRUE;
2395 /* FIXME: We should free previous cache file earlier */
2396 if(req->req_file) {
2397 req_file_release(req->req_file);
2398 req->req_file = NULL;
2400 if(req->hCacheFile) {
2401 CloseHandle(req->hCacheFile);
2402 req->hCacheFile = NULL;
2405 if(req->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE)
2406 b = FALSE;
2408 if(b) {
2409 int header_idx;
2411 EnterCriticalSection( &req->headers_section );
2413 header_idx = HTTP_GetCustomHeaderIndex(req, szCache_Control, 0, FALSE);
2414 if(header_idx != -1) {
2415 WCHAR *ptr;
2417 for(ptr=req->custHeaders[header_idx].lpszValue; *ptr; ) {
2418 WCHAR *end;
2420 while(*ptr==' ' || *ptr=='\t')
2421 ptr++;
2423 end = strchrW(ptr, ',');
2424 if(!end)
2425 end = ptr + strlenW(ptr);
2427 if(!strncmpiW(ptr, no_cacheW, sizeof(no_cacheW)/sizeof(*no_cacheW)-1)
2428 || !strncmpiW(ptr, no_storeW, sizeof(no_storeW)/sizeof(*no_storeW)-1)) {
2429 b = FALSE;
2430 break;
2433 ptr = end;
2434 if(*ptr == ',')
2435 ptr++;
2439 LeaveCriticalSection( &req->headers_section );
2442 if(!b) {
2443 if(!(req->hdr.dwFlags & INTERNET_FLAG_NEED_FILE))
2444 return;
2446 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2449 url = compose_request_url(req);
2450 if(!url) {
2451 WARN("Could not get URL\n");
2452 return;
2455 b = CreateUrlCacheEntryW(url, req->contentLength == ~0u ? 0 : req->contentLength, NULL, file_name, 0);
2456 if(!b) {
2457 WARN("Could not create cache entry: %08x\n", GetLastError());
2458 return;
2461 create_req_file(file_name, &req->req_file);
2462 req->req_file->url = url;
2464 req->hCacheFile = CreateFileW(file_name, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
2465 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2466 if(req->hCacheFile == INVALID_HANDLE_VALUE) {
2467 WARN("Could not create file: %u\n", GetLastError());
2468 req->hCacheFile = NULL;
2469 return;
2472 if(req->read_size) {
2473 DWORD written;
2475 b = WriteFile(req->hCacheFile, req->read_buf+req->read_pos, req->read_size, &written, NULL);
2476 if(!b)
2477 FIXME("WriteFile failed: %u\n", GetLastError());
2479 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2480 commit_cache_entry(req);
2484 /* read some more data into the read buffer (the read section must be held) */
2485 static DWORD read_more_data( http_request_t *req, int maxlen )
2487 DWORD res;
2488 int len;
2490 if (req->read_pos)
2492 /* move existing data to the start of the buffer */
2493 if(req->read_size)
2494 memmove( req->read_buf, req->read_buf + req->read_pos, req->read_size );
2495 req->read_pos = 0;
2498 if (maxlen == -1) maxlen = sizeof(req->read_buf);
2500 res = NETCON_recv( req->netconn, req->read_buf + req->read_size,
2501 maxlen - req->read_size, TRUE, &len );
2502 if(res == ERROR_SUCCESS)
2503 req->read_size += len;
2505 return res;
2508 /* remove some amount of data from the read buffer (the read section must be held) */
2509 static void remove_data( http_request_t *req, int count )
2511 if (!(req->read_size -= count)) req->read_pos = 0;
2512 else req->read_pos += count;
2515 static DWORD read_line( http_request_t *req, LPSTR buffer, DWORD *len )
2517 int count, bytes_read, pos = 0;
2518 DWORD res;
2520 EnterCriticalSection( &req->read_section );
2521 for (;;)
2523 BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
2525 if (eol)
2527 count = eol - (req->read_buf + req->read_pos);
2528 bytes_read = count + 1;
2530 else count = bytes_read = req->read_size;
2532 count = min( count, *len - pos );
2533 memcpy( buffer + pos, req->read_buf + req->read_pos, count );
2534 pos += count;
2535 remove_data( req, bytes_read );
2536 if (eol) break;
2538 if ((res = read_more_data( req, -1 )))
2540 WARN( "read failed %u\n", res );
2541 LeaveCriticalSection( &req->read_section );
2542 return res;
2544 if (!req->read_size)
2546 *len = 0;
2547 TRACE( "returning empty string\n" );
2548 LeaveCriticalSection( &req->read_section );
2549 return ERROR_SUCCESS;
2552 LeaveCriticalSection( &req->read_section );
2554 if (pos < *len)
2556 if (pos && buffer[pos - 1] == '\r') pos--;
2557 *len = pos + 1;
2559 buffer[*len - 1] = 0;
2560 TRACE( "returning %s\n", debugstr_a(buffer));
2561 return ERROR_SUCCESS;
2564 /* check if we have reached the end of the data to read (the read section must be held) */
2565 static BOOL end_of_read_data( http_request_t *req )
2567 return !req->read_size && req->data_stream->vtbl->end_of_data(req->data_stream, req);
2570 static DWORD read_http_stream(http_request_t *req, BYTE *buf, DWORD size, DWORD *read, blocking_mode_t blocking_mode)
2572 DWORD res;
2574 res = req->data_stream->vtbl->read(req->data_stream, req, buf, size, read, blocking_mode);
2575 assert(*read <= size);
2577 if(req->hCacheFile) {
2578 if(*read) {
2579 BOOL bres;
2580 DWORD written;
2582 bres = WriteFile(req->hCacheFile, buf, *read, &written, NULL);
2583 if(!bres)
2584 FIXME("WriteFile failed: %u\n", GetLastError());
2587 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2588 commit_cache_entry(req);
2591 return res;
2594 /* fetch some more data into the read buffer (the read section must be held) */
2595 static DWORD refill_read_buffer(http_request_t *req, blocking_mode_t blocking_mode, DWORD *read_bytes)
2597 DWORD res, read=0;
2599 if(req->read_size == sizeof(req->read_buf))
2600 return ERROR_SUCCESS;
2602 if(req->read_pos) {
2603 if(req->read_size)
2604 memmove(req->read_buf, req->read_buf+req->read_pos, req->read_size);
2605 req->read_pos = 0;
2608 res = read_http_stream(req, req->read_buf+req->read_size, sizeof(req->read_buf) - req->read_size,
2609 &read, blocking_mode);
2610 req->read_size += read;
2612 TRACE("read %u bytes, read_size %u\n", read, req->read_size);
2613 if(read_bytes)
2614 *read_bytes = read;
2615 return res;
2618 /* return the size of data available to be read immediately (the read section must be held) */
2619 static DWORD get_avail_data( http_request_t *req )
2621 DWORD avail = req->read_size;
2624 * Different Windows versions have different limits of returned data, but all
2625 * of them return no more than centrain amount. We use READ_BUFFER_SIZE as a limit.
2627 if(avail < READ_BUFFER_SIZE)
2628 avail += req->data_stream->vtbl->get_avail_data(req->data_stream, req);
2630 return min(avail, READ_BUFFER_SIZE);
2633 static DWORD netconn_get_avail_data(data_stream_t *stream, http_request_t *req)
2635 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2636 DWORD avail = 0;
2638 if(is_valid_netconn(req->netconn))
2639 NETCON_query_data_available(req->netconn, &avail);
2640 return netconn_stream->content_length == ~0u
2641 ? avail
2642 : min(avail, netconn_stream->content_length-netconn_stream->content_read);
2645 static BOOL netconn_end_of_data(data_stream_t *stream, http_request_t *req)
2647 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2648 return netconn_stream->content_read == netconn_stream->content_length || !is_valid_netconn(req->netconn);
2651 static DWORD netconn_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2652 DWORD *read, blocking_mode_t blocking_mode)
2654 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2655 DWORD res = ERROR_SUCCESS;
2656 int len = 0, ret = 0;
2658 size = min(size, netconn_stream->content_length-netconn_stream->content_read);
2660 if(size && is_valid_netconn(req->netconn)) {
2661 while((res = NETCON_recv(req->netconn, buf+ret, size-ret, blocking_mode != BLOCKING_DISALLOW, &len)) == ERROR_SUCCESS) {
2662 if(!len) {
2663 netconn_stream->content_length = netconn_stream->content_read;
2664 break;
2666 ret += len;
2667 netconn_stream->content_read += len;
2668 if(blocking_mode != BLOCKING_WAITALL || size == ret)
2669 break;
2672 if(ret || (blocking_mode == BLOCKING_DISALLOW && res == WSAEWOULDBLOCK))
2673 res = ERROR_SUCCESS;
2676 TRACE("read %u bytes\n", ret);
2677 *read = ret;
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), FALSE, &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 static char next_chunked_data_char(chunked_stream_t *stream)
2714 assert(stream->buf_size);
2716 stream->buf_size--;
2717 return stream->buf[stream->buf_pos++];
2720 static BOOL chunked_end_of_data(data_stream_t *stream, http_request_t *req)
2722 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2723 return chunked_stream->state == CHUNKED_STREAM_STATE_END_OF_STREAM;
2726 static DWORD chunked_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2727 DWORD *read, blocking_mode_t blocking_mode)
2729 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2730 DWORD ret_read = 0, res = ERROR_SUCCESS;
2731 BOOL continue_read = TRUE;
2732 int read_bytes;
2733 char ch;
2735 do {
2736 TRACE("state %d\n", chunked_stream->state);
2738 /* Ensure that we have data in the buffer for states that need it. */
2739 if(!chunked_stream->buf_size) {
2740 switch(chunked_stream->state) {
2741 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE:
2742 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE:
2743 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA:
2744 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END:
2745 chunked_stream->buf_pos = 0;
2746 res = NETCON_recv(req->netconn, chunked_stream->buf, sizeof(chunked_stream->buf), blocking_mode != BLOCKING_DISALLOW, &read_bytes);
2747 if(res == ERROR_SUCCESS && read_bytes) {
2748 chunked_stream->buf_size += read_bytes;
2749 }else if(res == WSAEWOULDBLOCK) {
2750 continue_read = FALSE;
2751 continue;
2752 }else {
2753 chunked_stream->state = CHUNKED_STREAM_STATE_END_OF_STREAM;
2755 break;
2756 default:
2757 break;
2761 switch(chunked_stream->state) {
2762 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE:
2763 ch = next_chunked_data_char(chunked_stream);
2765 if(ch >= '0' && ch <= '9') {
2766 chunked_stream->chunk_size = chunked_stream->chunk_size * 16 + ch - '0';
2767 }else if(ch >= 'a' && ch <= 'f') {
2768 chunked_stream->chunk_size = chunked_stream->chunk_size * 16 + ch - 'a' + 10;
2769 }else if (ch >= 'A' && ch <= 'F') {
2770 chunked_stream->chunk_size = chunked_stream->chunk_size * 16 + ch - 'A' + 10;
2771 }else if (ch == ';' || ch == '\r' || ch == '\n') {
2772 TRACE("reading %u byte chunk\n", chunked_stream->chunk_size);
2773 chunked_stream->buf_size++;
2774 chunked_stream->buf_pos--;
2775 if(req->contentLength == ~0u) req->contentLength = chunked_stream->chunk_size;
2776 else req->contentLength += chunked_stream->chunk_size;
2777 chunked_stream->state = CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE;
2779 break;
2781 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE:
2782 ch = next_chunked_data_char(chunked_stream);
2783 if(ch == '\n')
2784 chunked_stream->state = chunked_stream->chunk_size
2785 ? CHUNKED_STREAM_STATE_READING_CHUNK
2786 : CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END;
2787 else if(ch != '\r')
2788 WARN("unexpected char '%c'\n", ch);
2789 break;
2791 case CHUNKED_STREAM_STATE_READING_CHUNK:
2792 assert(chunked_stream->chunk_size);
2793 if(!size) {
2794 continue_read = FALSE;
2795 break;
2797 read_bytes = min(size, chunked_stream->chunk_size);
2799 if(chunked_stream->buf_size) {
2800 if(read_bytes > chunked_stream->buf_size)
2801 read_bytes = chunked_stream->buf_size;
2803 memcpy(buf+ret_read, chunked_stream->buf+chunked_stream->buf_pos, read_bytes);
2804 chunked_stream->buf_pos += read_bytes;
2805 chunked_stream->buf_size -= read_bytes;
2806 }else {
2807 res = NETCON_recv(req->netconn, (char*)buf+ret_read, read_bytes,
2808 blocking_mode != BLOCKING_DISALLOW, (int*)&read_bytes);
2809 if(res != ERROR_SUCCESS) {
2810 continue_read = FALSE;
2811 break;
2814 if(!read_bytes) {
2815 chunked_stream->state = CHUNKED_STREAM_STATE_END_OF_STREAM;
2816 continue;
2820 chunked_stream->chunk_size -= read_bytes;
2821 size -= read_bytes;
2822 ret_read += read_bytes;
2823 if(!chunked_stream->chunk_size)
2824 chunked_stream->state = CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA;
2825 if(blocking_mode == BLOCKING_ALLOW)
2826 blocking_mode = BLOCKING_DISALLOW;
2827 break;
2829 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA:
2830 ch = next_chunked_data_char(chunked_stream);
2831 if(ch == '\n')
2832 chunked_stream->state = CHUNKED_STREAM_STATE_READING_CHUNK_SIZE;
2833 else if(ch != '\r')
2834 WARN("unexpected char '%c'\n", ch);
2835 break;
2837 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END:
2838 ch = next_chunked_data_char(chunked_stream);
2839 if(ch == '\n')
2840 chunked_stream->state = CHUNKED_STREAM_STATE_END_OF_STREAM;
2841 else if(ch != '\r')
2842 WARN("unexpected char '%c'\n", ch);
2843 break;
2845 case CHUNKED_STREAM_STATE_END_OF_STREAM:
2846 continue_read = FALSE;
2847 break;
2849 } while(continue_read);
2851 if(ret_read)
2852 res = ERROR_SUCCESS;
2853 if(res != ERROR_SUCCESS && res != WSAEWOULDBLOCK)
2854 return res;
2856 TRACE("read %d bytes\n", ret_read);
2857 *read = ret_read;
2858 return ERROR_SUCCESS;
2861 static DWORD chunked_get_avail_data(data_stream_t *stream, http_request_t *req)
2863 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2864 DWORD avail = 0;
2866 if(chunked_stream->state != CHUNKED_STREAM_STATE_READING_CHUNK) {
2867 DWORD res, read;
2869 /* try to process to the next chunk */
2870 res = chunked_read(stream, req, NULL, 0, &read, BLOCKING_DISALLOW);
2871 if(res != ERROR_SUCCESS || chunked_stream->state != CHUNKED_STREAM_STATE_READING_CHUNK)
2872 return 0;
2875 if(is_valid_netconn(req->netconn) && chunked_stream->buf_size < chunked_stream->chunk_size)
2876 NETCON_query_data_available(req->netconn, &avail);
2878 return min(avail + chunked_stream->buf_size, chunked_stream->chunk_size);
2881 static BOOL chunked_drain_content(data_stream_t *stream, http_request_t *req)
2883 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2884 return chunked_stream->state == CHUNKED_STREAM_STATE_END_OF_STREAM;
2887 static void chunked_destroy(data_stream_t *stream)
2889 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2890 heap_free(chunked_stream);
2893 static const data_stream_vtbl_t chunked_stream_vtbl = {
2894 chunked_get_avail_data,
2895 chunked_end_of_data,
2896 chunked_read,
2897 chunked_drain_content,
2898 chunked_destroy
2901 /* set the request content length based on the headers */
2902 static DWORD set_content_length(http_request_t *request)
2904 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
2905 static const WCHAR headW[] = {'H','E','A','D',0};
2906 WCHAR encoding[20];
2907 DWORD size;
2909 if(request->status_code == HTTP_STATUS_NO_CONTENT || !strcmpW(request->verb, headW)) {
2910 request->contentLength = request->netconn_stream.content_length = 0;
2911 return ERROR_SUCCESS;
2914 size = sizeof(request->contentLength);
2915 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2916 &request->contentLength, &size, NULL) != ERROR_SUCCESS)
2917 request->contentLength = ~0u;
2918 request->netconn_stream.content_length = request->contentLength;
2919 request->netconn_stream.content_read = request->read_size;
2921 size = sizeof(encoding);
2922 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) == ERROR_SUCCESS &&
2923 !strcmpiW(encoding, szChunked))
2925 chunked_stream_t *chunked_stream;
2927 chunked_stream = heap_alloc(sizeof(*chunked_stream));
2928 if(!chunked_stream)
2929 return ERROR_OUTOFMEMORY;
2931 chunked_stream->data_stream.vtbl = &chunked_stream_vtbl;
2932 chunked_stream->buf_size = chunked_stream->buf_pos = 0;
2933 chunked_stream->chunk_size = 0;
2934 chunked_stream->state = CHUNKED_STREAM_STATE_READING_CHUNK_SIZE;
2936 if(request->read_size) {
2937 memcpy(chunked_stream->buf, request->read_buf+request->read_pos, request->read_size);
2938 chunked_stream->buf_size = request->read_size;
2939 request->read_size = request->read_pos = 0;
2942 request->data_stream = &chunked_stream->data_stream;
2943 request->contentLength = ~0u;
2946 if(request->decoding) {
2947 int encoding_idx;
2949 static const WCHAR deflateW[] = {'d','e','f','l','a','t','e',0};
2950 static const WCHAR gzipW[] = {'g','z','i','p',0};
2952 EnterCriticalSection( &request->headers_section );
2954 encoding_idx = HTTP_GetCustomHeaderIndex(request, szContent_Encoding, 0, FALSE);
2955 if(encoding_idx != -1) {
2956 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, gzipW)) {
2957 HTTP_DeleteCustomHeader(request, encoding_idx);
2958 LeaveCriticalSection( &request->headers_section );
2959 return init_gzip_stream(request, TRUE);
2961 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, deflateW)) {
2962 HTTP_DeleteCustomHeader(request, encoding_idx);
2963 LeaveCriticalSection( &request->headers_section );
2964 return init_gzip_stream(request, FALSE);
2968 LeaveCriticalSection( &request->headers_section );
2971 return ERROR_SUCCESS;
2974 static void send_request_complete(http_request_t *req, DWORD_PTR result, DWORD error)
2976 INTERNET_ASYNC_RESULT iar;
2978 iar.dwResult = result;
2979 iar.dwError = error;
2981 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2982 sizeof(INTERNET_ASYNC_RESULT));
2985 static void HTTP_ReceiveRequestData(http_request_t *req, BOOL first_notif, DWORD *ret_size)
2987 DWORD res, read = 0, avail = 0;
2988 blocking_mode_t mode;
2990 TRACE("%p\n", req);
2992 EnterCriticalSection( &req->read_section );
2994 mode = first_notif && req->read_size ? BLOCKING_DISALLOW : BLOCKING_ALLOW;
2995 res = refill_read_buffer(req, mode, &read);
2996 if(res == ERROR_SUCCESS)
2997 avail = get_avail_data(req);
2999 LeaveCriticalSection( &req->read_section );
3001 if(res != ERROR_SUCCESS || (mode != BLOCKING_DISALLOW && !read)) {
3002 WARN("res %u read %u, closing connection\n", res, read);
3003 http_release_netconn(req, FALSE);
3006 if(res != ERROR_SUCCESS) {
3007 send_request_complete(req, 0, res);
3008 return;
3011 if(ret_size)
3012 *ret_size = avail;
3013 if(first_notif)
3014 avail = 0;
3016 send_request_complete(req, req->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)req->hdr.hInternet : 1, avail);
3019 /* read data from the http connection (the read section must be held) */
3020 static DWORD HTTPREQ_Read(http_request_t *req, void *buffer, DWORD size, DWORD *read)
3022 DWORD current_read = 0, ret_read = 0;
3023 blocking_mode_t blocking_mode;
3024 DWORD res = ERROR_SUCCESS;
3026 blocking_mode = req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC ? BLOCKING_ALLOW : BLOCKING_WAITALL;
3028 EnterCriticalSection( &req->read_section );
3030 if(req->read_size) {
3031 ret_read = min(size, req->read_size);
3032 memcpy(buffer, req->read_buf+req->read_pos, ret_read);
3033 req->read_size -= ret_read;
3034 req->read_pos += ret_read;
3035 if(blocking_mode == BLOCKING_ALLOW)
3036 blocking_mode = BLOCKING_DISALLOW;
3039 if(ret_read < size) {
3040 res = read_http_stream(req, (BYTE*)buffer+ret_read, size-ret_read, &current_read, blocking_mode);
3041 ret_read += current_read;
3044 LeaveCriticalSection( &req->read_section );
3046 *read = ret_read;
3047 TRACE( "retrieved %u bytes (%u)\n", ret_read, req->contentLength );
3049 if(size && !ret_read)
3050 http_release_netconn(req, res == ERROR_SUCCESS);
3052 return res;
3055 static BOOL drain_content(http_request_t *req, BOOL blocking)
3057 BOOL ret;
3059 if(!is_valid_netconn(req->netconn) || req->contentLength == -1)
3060 return FALSE;
3062 if(!strcmpW(req->verb, szHEAD))
3063 return TRUE;
3065 if(!blocking)
3066 return req->data_stream->vtbl->drain_content(req->data_stream, req);
3068 EnterCriticalSection( &req->read_section );
3070 while(1) {
3071 DWORD bytes_read, res;
3072 BYTE buf[4096];
3074 res = HTTPREQ_Read(req, buf, sizeof(buf), &bytes_read);
3075 if(res != ERROR_SUCCESS) {
3076 ret = FALSE;
3077 break;
3079 if(!bytes_read) {
3080 ret = TRUE;
3081 break;
3085 LeaveCriticalSection( &req->read_section );
3086 return ret;
3089 typedef struct {
3090 task_header_t hdr;
3091 void *buf;
3092 DWORD size;
3093 DWORD *ret_read;
3094 } read_file_ex_task_t;
3096 static void AsyncReadFileExProc(task_header_t *hdr)
3098 read_file_ex_task_t *task = (read_file_ex_task_t*)hdr;
3099 http_request_t *req = (http_request_t*)task->hdr.hdr;
3100 DWORD res = ERROR_SUCCESS, read = 0, buffered = 0;
3102 TRACE("%p\n", req);
3104 if(task->ret_read)
3105 res = HTTPREQ_Read(req, task->buf, task->size, &read);
3106 if(res == ERROR_SUCCESS)
3107 res = refill_read_buffer(req, task->ret_read ? BLOCKING_DISALLOW : BLOCKING_ALLOW, &buffered);
3108 if (res == ERROR_SUCCESS)
3110 if(task->ret_read)
3111 *task->ret_read = read;
3112 read += buffered;
3113 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3114 &read, sizeof(read));
3117 send_request_complete(req, res == ERROR_SUCCESS, res);
3120 static DWORD HTTPREQ_ReadFileEx(object_header_t *hdr, void *buf, DWORD size, DWORD *ret_read,
3121 DWORD flags, DWORD_PTR context)
3124 http_request_t *req = (http_request_t*)hdr;
3125 DWORD res, read, cread, error = ERROR_SUCCESS;
3127 TRACE("(%p %p %u %x)\n", req, buf, size, flags);
3129 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3130 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3132 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3134 if (req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3136 read_file_ex_task_t *task;
3138 if (TryEnterCriticalSection( &req->read_section ))
3140 if (get_avail_data(req) || end_of_read_data(req))
3142 res = HTTPREQ_Read(req, buf, size, &read);
3143 LeaveCriticalSection( &req->read_section );
3144 goto done;
3146 LeaveCriticalSection( &req->read_section );
3149 task = alloc_async_task(&req->hdr, AsyncReadFileExProc, sizeof(*task));
3150 task->buf = buf;
3151 task->size = size;
3152 task->ret_read = (flags & IRF_NO_WAIT) ? NULL : ret_read;
3154 INTERNET_AsyncCall(&task->hdr);
3156 return ERROR_IO_PENDING;
3159 read = 0;
3161 EnterCriticalSection( &req->read_section );
3162 if(hdr->dwError == ERROR_SUCCESS)
3163 hdr->dwError = INTERNET_HANDLE_IN_USE;
3164 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3165 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3167 while(1) {
3168 res = HTTPREQ_Read(req, (char*)buf+read, size-read, &cread);
3169 if(res != ERROR_SUCCESS)
3170 break;
3172 read += cread;
3173 if(read == size || end_of_read_data(req))
3174 break;
3176 LeaveCriticalSection( &req->read_section );
3178 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3179 &cread, sizeof(cread));
3180 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
3181 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3183 EnterCriticalSection( &req->read_section );
3186 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3187 hdr->dwError = ERROR_SUCCESS;
3188 else
3189 error = hdr->dwError;
3191 LeaveCriticalSection( &req->read_section );
3193 done:
3194 *ret_read = read;
3195 if (res == ERROR_SUCCESS) {
3196 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3197 &read, sizeof(read));
3200 return res==ERROR_SUCCESS ? error : res;
3203 static DWORD HTTPREQ_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
3205 DWORD res;
3206 http_request_t *request = (http_request_t*)hdr;
3208 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3210 *written = 0;
3211 res = NETCON_send(request->netconn, buffer, size, 0, (LPINT)written);
3212 if (res == ERROR_SUCCESS)
3213 request->bytesWritten += *written;
3215 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
3216 return res;
3219 static DWORD HTTPREQ_ReadFile(object_header_t *hdr, void *buffer, DWORD size, DWORD *read)
3221 http_request_t *req = (http_request_t*)hdr;
3222 DWORD res;
3224 if (req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3226 read_file_ex_task_t *task;
3228 if (TryEnterCriticalSection( &req->read_section ))
3230 if (get_avail_data(req) || end_of_read_data(req))
3232 res = HTTPREQ_Read(req, buffer, size, read);
3233 LeaveCriticalSection( &req->read_section );
3234 return res;
3236 LeaveCriticalSection( &req->read_section );
3239 task = alloc_async_task(&req->hdr, AsyncReadFileExProc, sizeof(*task));
3240 task->buf = buffer;
3241 task->size = size;
3242 task->ret_read = read;
3244 *read = 0;
3245 INTERNET_AsyncCall(&task->hdr);
3247 return ERROR_IO_PENDING;
3250 EnterCriticalSection( &req->read_section );
3251 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3252 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3254 res = HTTPREQ_Read(req, buffer, size, read);
3255 if(res == ERROR_SUCCESS)
3256 res = hdr->dwError;
3257 LeaveCriticalSection( &req->read_section );
3259 return res;
3262 typedef struct {
3263 task_header_t hdr;
3264 DWORD *ret_size;
3265 } http_data_available_task_t;
3267 static void AsyncQueryDataAvailableProc(task_header_t *hdr)
3269 http_data_available_task_t *task = (http_data_available_task_t*)hdr;
3271 HTTP_ReceiveRequestData((http_request_t*)task->hdr.hdr, FALSE, task->ret_size);
3274 static DWORD HTTPREQ_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
3276 http_request_t *req = (http_request_t*)hdr;
3278 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
3280 if (req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3282 http_data_available_task_t *task;
3284 /* never wait, if we can't enter the section we queue an async request right away */
3285 if (TryEnterCriticalSection( &req->read_section ))
3287 refill_read_buffer(req, BLOCKING_DISALLOW, NULL);
3288 if ((*available = get_avail_data( req ))) goto done;
3289 if (end_of_read_data( req )) goto done;
3290 LeaveCriticalSection( &req->read_section );
3293 task = alloc_async_task(&req->hdr, AsyncQueryDataAvailableProc, sizeof(*task));
3294 task->ret_size = available;
3295 INTERNET_AsyncCall(&task->hdr);
3296 return ERROR_IO_PENDING;
3299 EnterCriticalSection( &req->read_section );
3301 if (!(*available = get_avail_data( req )) && !end_of_read_data( req ))
3303 refill_read_buffer( req, BLOCKING_ALLOW, NULL );
3304 *available = get_avail_data( req );
3307 done:
3308 LeaveCriticalSection( &req->read_section );
3310 TRACE( "returning %u\n", *available );
3311 return ERROR_SUCCESS;
3314 static DWORD HTTPREQ_LockRequestFile(object_header_t *hdr, req_file_t **ret)
3316 http_request_t *req = (http_request_t*)hdr;
3318 TRACE("(%p)\n", req);
3320 if(!req->req_file) {
3321 WARN("No cache file name available\n");
3322 return ERROR_FILE_NOT_FOUND;
3325 *ret = req_file_addref(req->req_file);
3326 return ERROR_SUCCESS;
3329 static const object_vtbl_t HTTPREQVtbl = {
3330 HTTPREQ_Destroy,
3331 HTTPREQ_CloseConnection,
3332 HTTPREQ_QueryOption,
3333 HTTPREQ_SetOption,
3334 HTTPREQ_ReadFile,
3335 HTTPREQ_ReadFileEx,
3336 HTTPREQ_WriteFile,
3337 HTTPREQ_QueryDataAvailable,
3338 NULL,
3339 HTTPREQ_LockRequestFile
3342 /***********************************************************************
3343 * HTTP_HttpOpenRequestW (internal)
3345 * Open a HTTP request handle
3347 * RETURNS
3348 * HINTERNET a HTTP request handle on success
3349 * NULL on failure
3352 static DWORD HTTP_HttpOpenRequestW(http_session_t *session,
3353 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3354 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3355 DWORD dwFlags, DWORD_PTR dwContext, HINTERNET *ret)
3357 appinfo_t *hIC = session->appInfo;
3358 http_request_t *request;
3359 DWORD port, len;
3361 TRACE("-->\n");
3363 request = alloc_object(&session->hdr, &HTTPREQVtbl, sizeof(http_request_t));
3364 if(!request)
3365 return ERROR_OUTOFMEMORY;
3367 request->hdr.htype = WH_HHTTPREQ;
3368 request->hdr.dwFlags = dwFlags;
3369 request->hdr.dwContext = dwContext;
3370 request->contentLength = ~0u;
3372 request->netconn_stream.data_stream.vtbl = &netconn_stream_vtbl;
3373 request->data_stream = &request->netconn_stream.data_stream;
3374 request->connect_timeout = session->connect_timeout;
3375 request->send_timeout = session->send_timeout;
3376 request->receive_timeout = session->receive_timeout;
3378 InitializeCriticalSection( &request->headers_section );
3379 request->headers_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.headers_section");
3381 InitializeCriticalSection( &request->read_section );
3382 request->read_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.read_section");
3384 WININET_AddRef( &session->hdr );
3385 request->session = session;
3386 list_add_head( &session->hdr.children, &request->hdr.entry );
3388 port = session->hostPort;
3389 if (port == INTERNET_INVALID_PORT_NUMBER)
3390 port = (session->hdr.dwFlags & INTERNET_FLAG_SECURE) ?
3391 INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;
3393 request->server = get_server(substrz(session->hostName), port, (dwFlags & INTERNET_FLAG_SECURE) != 0, TRUE);
3394 if(!request->server) {
3395 WININET_Release(&request->hdr);
3396 return ERROR_OUTOFMEMORY;
3399 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_CN_INVALID)
3400 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
3401 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_DATE_INVALID)
3402 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
3404 if (lpszObjectName && *lpszObjectName) {
3405 HRESULT rc;
3406 WCHAR dummy;
3408 len = 1;
3409 rc = UrlCanonicalizeW(lpszObjectName, &dummy, &len, URL_ESCAPE_SPACES_ONLY);
3410 if (rc != E_POINTER)
3411 len = strlenW(lpszObjectName)+1;
3412 request->path = heap_alloc(len*sizeof(WCHAR));
3413 rc = UrlCanonicalizeW(lpszObjectName, request->path, &len,
3414 URL_ESCAPE_SPACES_ONLY);
3415 if (rc != S_OK)
3417 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
3418 strcpyW(request->path,lpszObjectName);
3420 }else {
3421 static const WCHAR slashW[] = {'/',0};
3423 request->path = heap_strdupW(slashW);
3426 if (lpszReferrer && *lpszReferrer)
3427 HTTP_ProcessHeader(request, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3429 if (lpszAcceptTypes)
3431 int i;
3432 for (i = 0; lpszAcceptTypes[i]; i++)
3434 if (!*lpszAcceptTypes[i]) continue;
3435 HTTP_ProcessHeader(request, HTTP_ACCEPT, lpszAcceptTypes[i],
3436 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
3437 HTTP_ADDHDR_FLAG_REQ |
3438 (i == 0 ? (HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD) : 0));
3442 request->verb = heap_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
3443 request->version = heap_strdupW(lpszVersion && *lpszVersion ? lpszVersion : g_szHttp1_1);
3445 if (hIC->proxy && hIC->proxy[0] && !HTTP_ShouldBypassProxy(hIC, session->hostName))
3446 HTTP_DealWithProxy( hIC, session, request );
3448 INTERNET_SendCallback(&session->hdr, dwContext,
3449 INTERNET_STATUS_HANDLE_CREATED, &request->hdr.hInternet,
3450 sizeof(HINTERNET));
3452 TRACE("<-- (%p)\n", request);
3454 *ret = request->hdr.hInternet;
3455 return ERROR_SUCCESS;
3458 /***********************************************************************
3459 * HttpOpenRequestW (WININET.@)
3461 * Open a HTTP request handle
3463 * RETURNS
3464 * HINTERNET a HTTP request handle on success
3465 * NULL on failure
3468 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
3469 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3470 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3471 DWORD dwFlags, DWORD_PTR dwContext)
3473 http_session_t *session;
3474 HINTERNET handle = NULL;
3475 DWORD res;
3477 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
3478 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
3479 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
3480 dwFlags, dwContext);
3481 if(lpszAcceptTypes!=NULL)
3483 int i;
3484 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
3485 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
3488 session = (http_session_t*) get_handle_object( hHttpSession );
3489 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
3491 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3492 goto lend;
3496 * My tests seem to show that the windows version does not
3497 * become asynchronous until after this point. And anyhow
3498 * if this call was asynchronous then how would you get the
3499 * necessary HINTERNET pointer returned by this function.
3502 res = HTTP_HttpOpenRequestW(session, lpszVerb, lpszObjectName,
3503 lpszVersion, lpszReferrer, lpszAcceptTypes,
3504 dwFlags, dwContext, &handle);
3505 lend:
3506 if( session )
3507 WININET_Release( &session->hdr );
3508 TRACE("returning %p\n", handle);
3509 if(res != ERROR_SUCCESS)
3510 SetLastError(res);
3511 return handle;
3514 static const LPCWSTR header_lookup[] = {
3515 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
3516 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3517 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3518 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
3519 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3520 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3521 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3522 szAllow, /* HTTP_QUERY_ALLOW = 7 */
3523 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
3524 szDate, /* HTTP_QUERY_DATE = 9 */
3525 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
3526 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3527 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
3528 szURI, /* HTTP_QUERY_URI = 13 */
3529 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
3530 NULL, /* HTTP_QUERY_COST = 15 */
3531 NULL, /* HTTP_QUERY_LINK = 16 */
3532 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
3533 NULL, /* HTTP_QUERY_VERSION = 18 */
3534 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
3535 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
3536 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
3537 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3538 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
3539 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
3540 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3541 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3542 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3543 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
3544 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3545 NULL, /* HTTP_QUERY_FORWARDED = 30 */
3546 NULL, /* HTTP_QUERY_FROM = 31 */
3547 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3548 szLocation, /* HTTP_QUERY_LOCATION = 33 */
3549 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
3550 szReferer, /* HTTP_QUERY_REFERER = 35 */
3551 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
3552 szServer, /* HTTP_QUERY_SERVER = 37 */
3553 NULL, /* HTTP_TITLE = 38 */
3554 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
3555 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3556 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3557 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3558 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
3559 szCookie, /* HTTP_QUERY_COOKIE = 44 */
3560 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3561 NULL, /* HTTP_QUERY_REFRESH = 46 */
3562 szContent_Disposition, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3563 szAge, /* HTTP_QUERY_AGE = 48 */
3564 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3565 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
3566 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3567 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3568 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3569 szETag, /* HTTP_QUERY_ETAG = 54 */
3570 hostW, /* HTTP_QUERY_HOST = 55 */
3571 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
3572 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3573 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
3574 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3575 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3576 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3577 szRange, /* HTTP_QUERY_RANGE = 62 */
3578 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3579 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
3580 szVary, /* HTTP_QUERY_VARY = 65 */
3581 szVia, /* HTTP_QUERY_VIA = 66 */
3582 szWarning, /* HTTP_QUERY_WARNING = 67 */
3583 szExpect, /* HTTP_QUERY_EXPECT = 68 */
3584 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3585 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3588 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3590 /***********************************************************************
3591 * HTTP_HttpQueryInfoW (internal)
3593 static DWORD HTTP_HttpQueryInfoW(http_request_t *request, DWORD dwInfoLevel,
3594 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3596 LPHTTPHEADERW lphttpHdr = NULL;
3597 BOOL request_only = !!(dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS);
3598 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
3599 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
3600 INT index = -1;
3602 EnterCriticalSection( &request->headers_section );
3604 /* Find requested header structure */
3605 switch (level)
3607 case HTTP_QUERY_CUSTOM:
3608 if (!lpBuffer)
3610 LeaveCriticalSection( &request->headers_section );
3611 return ERROR_INVALID_PARAMETER;
3613 index = HTTP_GetCustomHeaderIndex(request, lpBuffer, requested_index, request_only);
3614 break;
3615 case HTTP_QUERY_RAW_HEADERS_CRLF:
3617 LPWSTR headers;
3618 DWORD len = 0;
3619 DWORD res = ERROR_INVALID_PARAMETER;
3621 if (request_only)
3622 headers = build_request_header(request, request->verb, request->path, request->version, TRUE);
3623 else
3624 headers = build_response_header(request, TRUE);
3625 if (!headers)
3627 LeaveCriticalSection( &request->headers_section );
3628 return ERROR_OUTOFMEMORY;
3631 len = strlenW(headers) * sizeof(WCHAR);
3632 if (len + sizeof(WCHAR) > *lpdwBufferLength)
3634 len += sizeof(WCHAR);
3635 res = ERROR_INSUFFICIENT_BUFFER;
3637 else if (lpBuffer)
3639 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3640 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
3641 res = ERROR_SUCCESS;
3643 *lpdwBufferLength = len;
3645 heap_free(headers);
3646 LeaveCriticalSection( &request->headers_section );
3647 return res;
3649 case HTTP_QUERY_RAW_HEADERS:
3651 LPWSTR headers;
3652 DWORD len;
3654 if (request_only)
3655 headers = build_request_header(request, request->verb, request->path, request->version, FALSE);
3656 else
3657 headers = build_response_header(request, FALSE);
3659 if (!headers)
3661 LeaveCriticalSection( &request->headers_section );
3662 return ERROR_OUTOFMEMORY;
3665 len = strlenW(headers) * sizeof(WCHAR);
3666 if (len > *lpdwBufferLength)
3668 *lpdwBufferLength = len;
3669 heap_free(headers);
3670 LeaveCriticalSection( &request->headers_section );
3671 return ERROR_INSUFFICIENT_BUFFER;
3674 if (lpBuffer)
3676 DWORD i;
3678 TRACE("returning data: %s\n", debugstr_wn(headers, len / sizeof(WCHAR)));
3680 for (i = 0; i < len / sizeof(WCHAR); i++)
3682 if (headers[i] == '\n')
3683 headers[i] = 0;
3685 memcpy(lpBuffer, headers, len);
3687 *lpdwBufferLength = len - sizeof(WCHAR);
3689 heap_free(headers);
3690 LeaveCriticalSection( &request->headers_section );
3691 return ERROR_SUCCESS;
3693 case HTTP_QUERY_STATUS_TEXT:
3694 if (request->statusText)
3696 DWORD len = strlenW(request->statusText);
3697 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3699 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3700 LeaveCriticalSection( &request->headers_section );
3701 return ERROR_INSUFFICIENT_BUFFER;
3703 if (lpBuffer)
3705 memcpy(lpBuffer, request->statusText, (len + 1) * sizeof(WCHAR));
3706 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3708 *lpdwBufferLength = len * sizeof(WCHAR);
3709 LeaveCriticalSection( &request->headers_section );
3710 return ERROR_SUCCESS;
3712 break;
3713 case HTTP_QUERY_VERSION:
3714 if (request->version)
3716 DWORD len = strlenW(request->version);
3717 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3719 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3720 LeaveCriticalSection( &request->headers_section );
3721 return ERROR_INSUFFICIENT_BUFFER;
3723 if (lpBuffer)
3725 memcpy(lpBuffer, request->version, (len + 1) * sizeof(WCHAR));
3726 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3728 *lpdwBufferLength = len * sizeof(WCHAR);
3729 LeaveCriticalSection( &request->headers_section );
3730 return ERROR_SUCCESS;
3732 break;
3733 case HTTP_QUERY_CONTENT_ENCODING:
3734 index = HTTP_GetCustomHeaderIndex(request, header_lookup[request->read_gzip ? HTTP_QUERY_CONTENT_TYPE : level],
3735 requested_index,request_only);
3736 break;
3737 case HTTP_QUERY_STATUS_CODE: {
3738 DWORD res = ERROR_SUCCESS;
3740 if(request_only)
3742 LeaveCriticalSection( &request->headers_section );
3743 return ERROR_HTTP_INVALID_QUERY_REQUEST;
3746 if(requested_index)
3747 break;
3749 if(dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) {
3750 if(*lpdwBufferLength >= sizeof(DWORD))
3751 *(DWORD*)lpBuffer = request->status_code;
3752 else
3753 res = ERROR_INSUFFICIENT_BUFFER;
3754 *lpdwBufferLength = sizeof(DWORD);
3755 }else {
3756 WCHAR buf[12];
3757 DWORD size;
3758 static const WCHAR formatW[] = {'%','u',0};
3760 size = sprintfW(buf, formatW, request->status_code) * sizeof(WCHAR);
3762 if(size <= *lpdwBufferLength) {
3763 memcpy(lpBuffer, buf, size+sizeof(WCHAR));
3764 }else {
3765 size += sizeof(WCHAR);
3766 res = ERROR_INSUFFICIENT_BUFFER;
3769 *lpdwBufferLength = size;
3771 LeaveCriticalSection( &request->headers_section );
3772 return res;
3774 default:
3775 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
3777 if (level < LAST_TABLE_HEADER && header_lookup[level])
3778 index = HTTP_GetCustomHeaderIndex(request, header_lookup[level],
3779 requested_index,request_only);
3782 if (index >= 0)
3783 lphttpHdr = &request->custHeaders[index];
3785 /* Ensure header satisfies requested attributes */
3786 if (!lphttpHdr ||
3787 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
3788 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
3790 LeaveCriticalSection( &request->headers_section );
3791 return ERROR_HTTP_HEADER_NOT_FOUND;
3794 /* coalesce value to requested type */
3795 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
3797 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
3798 TRACE(" returning number: %d\n", *(int *)lpBuffer);
3800 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
3802 time_t tmpTime;
3803 struct tm tmpTM;
3804 SYSTEMTIME *STHook;
3806 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
3808 tmpTM = *gmtime(&tmpTime);
3809 STHook = (SYSTEMTIME *)lpBuffer;
3810 STHook->wDay = tmpTM.tm_mday;
3811 STHook->wHour = tmpTM.tm_hour;
3812 STHook->wMilliseconds = 0;
3813 STHook->wMinute = tmpTM.tm_min;
3814 STHook->wDayOfWeek = tmpTM.tm_wday;
3815 STHook->wMonth = tmpTM.tm_mon + 1;
3816 STHook->wSecond = tmpTM.tm_sec;
3817 STHook->wYear = 1900+tmpTM.tm_year;
3819 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3820 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
3821 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
3823 else if (lphttpHdr->lpszValue)
3825 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
3827 if (len > *lpdwBufferLength)
3829 *lpdwBufferLength = len;
3830 LeaveCriticalSection( &request->headers_section );
3831 return ERROR_INSUFFICIENT_BUFFER;
3833 if (lpBuffer)
3835 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
3836 TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
3838 *lpdwBufferLength = len - sizeof(WCHAR);
3840 if (lpdwIndex) (*lpdwIndex)++;
3842 LeaveCriticalSection( &request->headers_section );
3843 return ERROR_SUCCESS;
3846 /***********************************************************************
3847 * HttpQueryInfoW (WININET.@)
3849 * Queries for information about an HTTP request
3851 * RETURNS
3852 * TRUE on success
3853 * FALSE on failure
3856 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3857 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3859 http_request_t *request;
3860 DWORD res;
3862 if (TRACE_ON(wininet)) {
3863 #define FE(x) { x, #x }
3864 static const wininet_flag_info query_flags[] = {
3865 FE(HTTP_QUERY_MIME_VERSION),
3866 FE(HTTP_QUERY_CONTENT_TYPE),
3867 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
3868 FE(HTTP_QUERY_CONTENT_ID),
3869 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
3870 FE(HTTP_QUERY_CONTENT_LENGTH),
3871 FE(HTTP_QUERY_CONTENT_LANGUAGE),
3872 FE(HTTP_QUERY_ALLOW),
3873 FE(HTTP_QUERY_PUBLIC),
3874 FE(HTTP_QUERY_DATE),
3875 FE(HTTP_QUERY_EXPIRES),
3876 FE(HTTP_QUERY_LAST_MODIFIED),
3877 FE(HTTP_QUERY_MESSAGE_ID),
3878 FE(HTTP_QUERY_URI),
3879 FE(HTTP_QUERY_DERIVED_FROM),
3880 FE(HTTP_QUERY_COST),
3881 FE(HTTP_QUERY_LINK),
3882 FE(HTTP_QUERY_PRAGMA),
3883 FE(HTTP_QUERY_VERSION),
3884 FE(HTTP_QUERY_STATUS_CODE),
3885 FE(HTTP_QUERY_STATUS_TEXT),
3886 FE(HTTP_QUERY_RAW_HEADERS),
3887 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
3888 FE(HTTP_QUERY_CONNECTION),
3889 FE(HTTP_QUERY_ACCEPT),
3890 FE(HTTP_QUERY_ACCEPT_CHARSET),
3891 FE(HTTP_QUERY_ACCEPT_ENCODING),
3892 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
3893 FE(HTTP_QUERY_AUTHORIZATION),
3894 FE(HTTP_QUERY_CONTENT_ENCODING),
3895 FE(HTTP_QUERY_FORWARDED),
3896 FE(HTTP_QUERY_FROM),
3897 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
3898 FE(HTTP_QUERY_LOCATION),
3899 FE(HTTP_QUERY_ORIG_URI),
3900 FE(HTTP_QUERY_REFERER),
3901 FE(HTTP_QUERY_RETRY_AFTER),
3902 FE(HTTP_QUERY_SERVER),
3903 FE(HTTP_QUERY_TITLE),
3904 FE(HTTP_QUERY_USER_AGENT),
3905 FE(HTTP_QUERY_WWW_AUTHENTICATE),
3906 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
3907 FE(HTTP_QUERY_ACCEPT_RANGES),
3908 FE(HTTP_QUERY_SET_COOKIE),
3909 FE(HTTP_QUERY_COOKIE),
3910 FE(HTTP_QUERY_REQUEST_METHOD),
3911 FE(HTTP_QUERY_REFRESH),
3912 FE(HTTP_QUERY_CONTENT_DISPOSITION),
3913 FE(HTTP_QUERY_AGE),
3914 FE(HTTP_QUERY_CACHE_CONTROL),
3915 FE(HTTP_QUERY_CONTENT_BASE),
3916 FE(HTTP_QUERY_CONTENT_LOCATION),
3917 FE(HTTP_QUERY_CONTENT_MD5),
3918 FE(HTTP_QUERY_CONTENT_RANGE),
3919 FE(HTTP_QUERY_ETAG),
3920 FE(HTTP_QUERY_HOST),
3921 FE(HTTP_QUERY_IF_MATCH),
3922 FE(HTTP_QUERY_IF_NONE_MATCH),
3923 FE(HTTP_QUERY_IF_RANGE),
3924 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
3925 FE(HTTP_QUERY_MAX_FORWARDS),
3926 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
3927 FE(HTTP_QUERY_RANGE),
3928 FE(HTTP_QUERY_TRANSFER_ENCODING),
3929 FE(HTTP_QUERY_UPGRADE),
3930 FE(HTTP_QUERY_VARY),
3931 FE(HTTP_QUERY_VIA),
3932 FE(HTTP_QUERY_WARNING),
3933 FE(HTTP_QUERY_CUSTOM)
3935 static const wininet_flag_info modifier_flags[] = {
3936 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
3937 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
3938 FE(HTTP_QUERY_FLAG_NUMBER),
3939 FE(HTTP_QUERY_FLAG_COALESCE)
3941 #undef FE
3942 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
3943 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
3944 DWORD i;
3946 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, info);
3947 TRACE(" Attribute:");
3948 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
3949 if (query_flags[i].val == info) {
3950 TRACE(" %s", query_flags[i].name);
3951 break;
3954 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
3955 TRACE(" Unknown (%08x)", info);
3958 TRACE(" Modifier:");
3959 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
3960 if (modifier_flags[i].val & info_mod) {
3961 TRACE(" %s", modifier_flags[i].name);
3962 info_mod &= ~ modifier_flags[i].val;
3966 if (info_mod) {
3967 TRACE(" Unknown (%08x)", info_mod);
3969 TRACE("\n");
3972 request = (http_request_t*) get_handle_object( hHttpRequest );
3973 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
3975 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3976 goto lend;
3979 if (lpBuffer == NULL)
3980 *lpdwBufferLength = 0;
3981 res = HTTP_HttpQueryInfoW( request, dwInfoLevel,
3982 lpBuffer, lpdwBufferLength, lpdwIndex);
3984 lend:
3985 if( request )
3986 WININET_Release( &request->hdr );
3988 TRACE("%u <--\n", res);
3989 if(res != ERROR_SUCCESS)
3990 SetLastError(res);
3991 return res == ERROR_SUCCESS;
3994 /***********************************************************************
3995 * HttpQueryInfoA (WININET.@)
3997 * Queries for information about an HTTP request
3999 * RETURNS
4000 * TRUE on success
4001 * FALSE on failure
4004 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
4005 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
4007 BOOL result;
4008 DWORD len;
4009 WCHAR* bufferW;
4011 TRACE("%p %x\n", hHttpRequest, dwInfoLevel);
4013 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
4014 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
4016 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
4017 lpdwBufferLength, lpdwIndex );
4020 if (lpBuffer)
4022 DWORD alloclen;
4023 len = (*lpdwBufferLength)*sizeof(WCHAR);
4024 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
4026 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
4027 if (alloclen < len)
4028 alloclen = len;
4030 else
4031 alloclen = len;
4032 bufferW = heap_alloc(alloclen);
4033 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
4034 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
4035 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
4036 } else
4038 bufferW = NULL;
4039 len = 0;
4042 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
4043 &len, lpdwIndex );
4044 if( result )
4046 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
4047 lpBuffer, *lpdwBufferLength, NULL, NULL );
4048 *lpdwBufferLength = len - 1;
4050 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
4052 else
4053 /* since the strings being returned from HttpQueryInfoW should be
4054 * only ASCII characters, it is reasonable to assume that all of
4055 * the Unicode characters can be reduced to a single byte */
4056 *lpdwBufferLength = len / sizeof(WCHAR);
4058 heap_free( bufferW );
4059 return result;
4062 static WCHAR *get_redirect_url(http_request_t *request)
4064 static WCHAR szHttp[] = {'h','t','t','p',0};
4065 static WCHAR szHttps[] = {'h','t','t','p','s',0};
4066 http_session_t *session = request->session;
4067 URL_COMPONENTSW urlComponents = { sizeof(urlComponents) };
4068 WCHAR *orig_url = NULL, *redirect_url = NULL, *combined_url = NULL;
4069 DWORD url_length = 0, res;
4070 BOOL b;
4072 url_length = 0;
4073 res = HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, redirect_url, &url_length, NULL);
4074 if(res == ERROR_INSUFFICIENT_BUFFER) {
4075 redirect_url = heap_alloc(url_length);
4076 res = HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, redirect_url, &url_length, NULL);
4078 if(res != ERROR_SUCCESS) {
4079 heap_free(redirect_url);
4080 return NULL;
4083 urlComponents.lpszScheme = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
4084 urlComponents.lpszHostName = request->server->name;
4085 urlComponents.nPort = request->server->port;
4086 urlComponents.lpszUserName = session->userName;
4087 urlComponents.lpszUrlPath = request->path;
4089 b = InternetCreateUrlW(&urlComponents, 0, NULL, &url_length);
4090 if(!b && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
4091 orig_url = heap_alloc(url_length);
4093 /* convert from bytes to characters */
4094 url_length = url_length / sizeof(WCHAR) - 1;
4095 b = InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length);
4098 if(b) {
4099 url_length = 0;
4100 b = InternetCombineUrlW(orig_url, redirect_url, NULL, &url_length, ICU_ENCODE_SPACES_ONLY);
4101 if(!b && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
4102 combined_url = heap_alloc(url_length * sizeof(WCHAR));
4103 b = InternetCombineUrlW(orig_url, redirect_url, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY);
4104 if(!b) {
4105 heap_free(combined_url);
4106 combined_url = NULL;
4111 heap_free(orig_url);
4112 heap_free(redirect_url);
4113 return combined_url;
4117 /***********************************************************************
4118 * HTTP_HandleRedirect (internal)
4120 static DWORD HTTP_HandleRedirect(http_request_t *request, LPCWSTR lpszUrl)
4122 http_session_t *session = request->session;
4123 WCHAR *path;
4125 if(lpszUrl[0]=='/')
4127 /* if it's an absolute path, keep the same session info */
4128 path = heap_strdupW(lpszUrl);
4130 else
4132 URL_COMPONENTSW urlComponents = { sizeof(urlComponents) };
4133 BOOL custom_port = FALSE;
4134 substr_t host;
4136 urlComponents.dwHostNameLength = 1;
4137 urlComponents.dwUserNameLength = 1;
4138 urlComponents.dwUrlPathLength = 1;
4139 if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
4140 return INTERNET_GetLastError();
4142 if(urlComponents.nScheme == INTERNET_SCHEME_HTTP) {
4143 if(request->hdr.dwFlags & INTERNET_FLAG_SECURE) {
4144 TRACE("redirect from secure page to non-secure page\n");
4145 /* FIXME: warn about from secure redirect to non-secure page */
4146 request->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
4149 custom_port = urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT;
4150 }else if(urlComponents.nScheme == INTERNET_SCHEME_HTTPS) {
4151 if(!(request->hdr.dwFlags & INTERNET_FLAG_SECURE)) {
4152 TRACE("redirect from non-secure page to secure page\n");
4153 /* FIXME: notify about redirect to secure page */
4154 request->hdr.dwFlags |= INTERNET_FLAG_SECURE;
4157 custom_port = urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT;
4160 heap_free(session->hostName);
4162 session->hostName = heap_strndupW(urlComponents.lpszHostName, urlComponents.dwHostNameLength);
4163 session->hostPort = urlComponents.nPort;
4165 heap_free(session->userName);
4166 session->userName = NULL;
4167 if (urlComponents.dwUserNameLength)
4168 session->userName = heap_strndupW(urlComponents.lpszUserName, urlComponents.dwUserNameLength);
4170 reset_data_stream(request);
4172 host = substr(urlComponents.lpszHostName, urlComponents.dwHostNameLength);
4174 if(host.len != strlenW(request->server->name) || strncmpiW(request->server->name, host.str, host.len)
4175 || request->server->port != urlComponents.nPort) {
4176 server_t *new_server;
4178 new_server = get_server(host, urlComponents.nPort, urlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
4179 server_release(request->server);
4180 request->server = new_server;
4183 if (custom_port)
4184 HTTP_ProcessHeader(request, hostW, request->server->host_port, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4185 else
4186 HTTP_ProcessHeader(request, hostW, request->server->name, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4188 path = heap_strndupW(urlComponents.lpszUrlPath, urlComponents.dwUrlPathLength);
4190 heap_free(request->path);
4191 request->path = NULL;
4192 if (*path)
4194 DWORD needed = 1;
4195 HRESULT rc;
4196 WCHAR dummy = 0;
4198 rc = UrlEscapeW(path, &dummy, &needed, URL_ESCAPE_SPACES_ONLY);
4199 if (rc != E_POINTER)
4200 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4201 request->path = heap_alloc(needed*sizeof(WCHAR));
4202 rc = UrlEscapeW(path, request->path, &needed,
4203 URL_ESCAPE_SPACES_ONLY);
4204 if (rc != S_OK)
4206 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4207 strcpyW(request->path, path);
4211 heap_free(path);
4213 /* Remove custom content-type/length headers on redirects. */
4214 remove_header(request, szContent_Type, TRUE);
4215 remove_header(request, szContent_Length, TRUE);
4217 return ERROR_SUCCESS;
4220 /***********************************************************************
4221 * HTTP_build_req (internal)
4223 * concatenate all the strings in the request together
4225 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
4227 LPCWSTR *t;
4228 LPWSTR str;
4230 for( t = list; *t ; t++ )
4231 len += strlenW( *t );
4232 len++;
4234 str = heap_alloc(len*sizeof(WCHAR));
4235 *str = 0;
4237 for( t = list; *t ; t++ )
4238 strcatW( str, *t );
4240 return str;
4243 static void HTTP_InsertCookies(http_request_t *request)
4245 WCHAR *cookies;
4246 DWORD res;
4248 res = get_cookie_header(request->server->name, request->path, &cookies);
4249 if(res != ERROR_SUCCESS || !cookies)
4250 return;
4252 HTTP_HttpAddRequestHeadersW(request, cookies, strlenW(cookies),
4253 HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
4254 heap_free(cookies);
4257 static WORD HTTP_ParseWkday(LPCWSTR day)
4259 static const WCHAR days[7][4] = {{ 's','u','n',0 },
4260 { 'm','o','n',0 },
4261 { 't','u','e',0 },
4262 { 'w','e','d',0 },
4263 { 't','h','u',0 },
4264 { 'f','r','i',0 },
4265 { 's','a','t',0 }};
4266 unsigned int i;
4267 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4268 if (!strcmpiW(day, days[i]))
4269 return i;
4271 /* Invalid */
4272 return 7;
4275 static WORD HTTP_ParseMonth(LPCWSTR month)
4277 static const WCHAR jan[] = { 'j','a','n',0 };
4278 static const WCHAR feb[] = { 'f','e','b',0 };
4279 static const WCHAR mar[] = { 'm','a','r',0 };
4280 static const WCHAR apr[] = { 'a','p','r',0 };
4281 static const WCHAR may[] = { 'm','a','y',0 };
4282 static const WCHAR jun[] = { 'j','u','n',0 };
4283 static const WCHAR jul[] = { 'j','u','l',0 };
4284 static const WCHAR aug[] = { 'a','u','g',0 };
4285 static const WCHAR sep[] = { 's','e','p',0 };
4286 static const WCHAR oct[] = { 'o','c','t',0 };
4287 static const WCHAR nov[] = { 'n','o','v',0 };
4288 static const WCHAR dec[] = { 'd','e','c',0 };
4290 if (!strcmpiW(month, jan)) return 1;
4291 if (!strcmpiW(month, feb)) return 2;
4292 if (!strcmpiW(month, mar)) return 3;
4293 if (!strcmpiW(month, apr)) return 4;
4294 if (!strcmpiW(month, may)) return 5;
4295 if (!strcmpiW(month, jun)) return 6;
4296 if (!strcmpiW(month, jul)) return 7;
4297 if (!strcmpiW(month, aug)) return 8;
4298 if (!strcmpiW(month, sep)) return 9;
4299 if (!strcmpiW(month, oct)) return 10;
4300 if (!strcmpiW(month, nov)) return 11;
4301 if (!strcmpiW(month, dec)) return 12;
4302 /* Invalid */
4303 return 0;
4306 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4307 * optionally preceded by whitespace.
4308 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4309 * st, and sets *str to the first character after the time format.
4311 static BOOL HTTP_ParseTime(SYSTEMTIME *st, LPCWSTR *str)
4313 LPCWSTR ptr = *str;
4314 WCHAR *nextPtr;
4315 unsigned long num;
4317 while (isspaceW(*ptr))
4318 ptr++;
4320 num = strtoulW(ptr, &nextPtr, 10);
4321 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4323 ERR("unexpected time format %s\n", debugstr_w(ptr));
4324 return FALSE;
4326 if (num > 23)
4328 ERR("unexpected hour in time format %s\n", debugstr_w(ptr));
4329 return FALSE;
4331 ptr = nextPtr + 1;
4332 st->wHour = (WORD)num;
4333 num = strtoulW(ptr, &nextPtr, 10);
4334 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4336 ERR("unexpected time format %s\n", debugstr_w(ptr));
4337 return FALSE;
4339 if (num > 59)
4341 ERR("unexpected minute in time format %s\n", debugstr_w(ptr));
4342 return FALSE;
4344 ptr = nextPtr + 1;
4345 st->wMinute = (WORD)num;
4346 num = strtoulW(ptr, &nextPtr, 10);
4347 if (!nextPtr || nextPtr <= ptr)
4349 ERR("unexpected time format %s\n", debugstr_w(ptr));
4350 return FALSE;
4352 if (num > 59)
4354 ERR("unexpected second in time format %s\n", debugstr_w(ptr));
4355 return FALSE;
4357 ptr = nextPtr + 1;
4358 *str = ptr;
4359 st->wSecond = (WORD)num;
4360 return TRUE;
4363 static BOOL HTTP_ParseDateAsAsctime(LPCWSTR value, FILETIME *ft)
4365 static const WCHAR gmt[]= { 'G','M','T',0 };
4366 WCHAR day[4], *dayPtr, month[4], *monthPtr, *nextPtr;
4367 LPCWSTR ptr;
4368 SYSTEMTIME st = { 0 };
4369 unsigned long num;
4371 for (ptr = value, dayPtr = day; *ptr && !isspaceW(*ptr) &&
4372 dayPtr - day < sizeof(day) / sizeof(day[0]) - 1; ptr++, dayPtr++)
4373 *dayPtr = *ptr;
4374 *dayPtr = 0;
4375 st.wDayOfWeek = HTTP_ParseWkday(day);
4376 if (st.wDayOfWeek >= 7)
4378 ERR("unexpected weekday %s\n", debugstr_w(day));
4379 return FALSE;
4382 while (isspaceW(*ptr))
4383 ptr++;
4385 for (monthPtr = month; !isspace(*ptr) &&
4386 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4387 monthPtr++, ptr++)
4388 *monthPtr = *ptr;
4389 *monthPtr = 0;
4390 st.wMonth = HTTP_ParseMonth(month);
4391 if (!st.wMonth || st.wMonth > 12)
4393 ERR("unexpected month %s\n", debugstr_w(month));
4394 return FALSE;
4397 while (isspaceW(*ptr))
4398 ptr++;
4400 num = strtoulW(ptr, &nextPtr, 10);
4401 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4403 ERR("unexpected day %s\n", debugstr_w(ptr));
4404 return FALSE;
4406 ptr = nextPtr;
4407 st.wDay = (WORD)num;
4409 while (isspaceW(*ptr))
4410 ptr++;
4412 if (!HTTP_ParseTime(&st, &ptr))
4413 return FALSE;
4415 while (isspaceW(*ptr))
4416 ptr++;
4418 num = strtoulW(ptr, &nextPtr, 10);
4419 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4421 ERR("unexpected year %s\n", debugstr_w(ptr));
4422 return FALSE;
4424 ptr = nextPtr;
4425 st.wYear = (WORD)num;
4427 while (isspaceW(*ptr))
4428 ptr++;
4430 /* asctime() doesn't report a timezone, but some web servers do, so accept
4431 * with or without GMT.
4433 if (*ptr && strcmpW(ptr, gmt))
4435 ERR("unexpected timezone %s\n", debugstr_w(ptr));
4436 return FALSE;
4438 return SystemTimeToFileTime(&st, ft);
4441 static BOOL HTTP_ParseRfc1123Date(LPCWSTR value, FILETIME *ft)
4443 static const WCHAR gmt[]= { 'G','M','T',0 };
4444 WCHAR *nextPtr, day[4], month[4], *monthPtr;
4445 LPCWSTR ptr;
4446 unsigned long num;
4447 SYSTEMTIME st = { 0 };
4449 ptr = strchrW(value, ',');
4450 if (!ptr)
4451 return FALSE;
4452 if (ptr - value != 3)
4454 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4455 return FALSE;
4457 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4458 day[3] = 0;
4459 st.wDayOfWeek = HTTP_ParseWkday(day);
4460 if (st.wDayOfWeek > 6)
4462 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4463 return FALSE;
4465 ptr++;
4467 while (isspaceW(*ptr))
4468 ptr++;
4470 num = strtoulW(ptr, &nextPtr, 10);
4471 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4473 WARN("unexpected day %s\n", debugstr_w(value));
4474 return FALSE;
4476 ptr = nextPtr;
4477 st.wDay = (WORD)num;
4479 while (isspaceW(*ptr))
4480 ptr++;
4482 for (monthPtr = month; !isspace(*ptr) &&
4483 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4484 monthPtr++, ptr++)
4485 *monthPtr = *ptr;
4486 *monthPtr = 0;
4487 st.wMonth = HTTP_ParseMonth(month);
4488 if (!st.wMonth || st.wMonth > 12)
4490 WARN("unexpected month %s\n", debugstr_w(month));
4491 return FALSE;
4494 while (isspaceW(*ptr))
4495 ptr++;
4497 num = strtoulW(ptr, &nextPtr, 10);
4498 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4500 ERR("unexpected year %s\n", debugstr_w(value));
4501 return FALSE;
4503 ptr = nextPtr;
4504 st.wYear = (WORD)num;
4506 if (!HTTP_ParseTime(&st, &ptr))
4507 return FALSE;
4509 while (isspaceW(*ptr))
4510 ptr++;
4512 if (strcmpW(ptr, gmt))
4514 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4515 return FALSE;
4517 return SystemTimeToFileTime(&st, ft);
4520 static WORD HTTP_ParseWeekday(LPCWSTR day)
4522 static const WCHAR days[7][10] = {{ 's','u','n','d','a','y',0 },
4523 { 'm','o','n','d','a','y',0 },
4524 { 't','u','e','s','d','a','y',0 },
4525 { 'w','e','d','n','e','s','d','a','y',0 },
4526 { 't','h','u','r','s','d','a','y',0 },
4527 { 'f','r','i','d','a','y',0 },
4528 { 's','a','t','u','r','d','a','y',0 }};
4529 unsigned int i;
4530 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4531 if (!strcmpiW(day, days[i]))
4532 return i;
4534 /* Invalid */
4535 return 7;
4538 static BOOL HTTP_ParseRfc850Date(LPCWSTR value, FILETIME *ft)
4540 static const WCHAR gmt[]= { 'G','M','T',0 };
4541 WCHAR *nextPtr, day[10], month[4], *monthPtr;
4542 LPCWSTR ptr;
4543 unsigned long num;
4544 SYSTEMTIME st = { 0 };
4546 ptr = strchrW(value, ',');
4547 if (!ptr)
4548 return FALSE;
4549 if (ptr - value == 3)
4551 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4552 day[3] = 0;
4553 st.wDayOfWeek = HTTP_ParseWkday(day);
4554 if (st.wDayOfWeek > 6)
4556 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4557 return FALSE;
4560 else if (ptr - value < sizeof(day) / sizeof(day[0]))
4562 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4563 day[ptr - value + 1] = 0;
4564 st.wDayOfWeek = HTTP_ParseWeekday(day);
4565 if (st.wDayOfWeek > 6)
4567 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4568 return FALSE;
4571 else
4573 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4574 return FALSE;
4576 ptr++;
4578 while (isspaceW(*ptr))
4579 ptr++;
4581 num = strtoulW(ptr, &nextPtr, 10);
4582 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4584 ERR("unexpected day %s\n", debugstr_w(value));
4585 return FALSE;
4587 ptr = nextPtr;
4588 st.wDay = (WORD)num;
4590 if (*ptr != '-')
4592 ERR("unexpected month format %s\n", debugstr_w(ptr));
4593 return FALSE;
4595 ptr++;
4597 for (monthPtr = month; *ptr != '-' &&
4598 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4599 monthPtr++, ptr++)
4600 *monthPtr = *ptr;
4601 *monthPtr = 0;
4602 st.wMonth = HTTP_ParseMonth(month);
4603 if (!st.wMonth || st.wMonth > 12)
4605 ERR("unexpected month %s\n", debugstr_w(month));
4606 return FALSE;
4609 if (*ptr != '-')
4611 ERR("unexpected year format %s\n", debugstr_w(ptr));
4612 return FALSE;
4614 ptr++;
4616 num = strtoulW(ptr, &nextPtr, 10);
4617 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4619 ERR("unexpected year %s\n", debugstr_w(value));
4620 return FALSE;
4622 ptr = nextPtr;
4623 st.wYear = (WORD)num;
4625 if (!HTTP_ParseTime(&st, &ptr))
4626 return FALSE;
4628 while (isspaceW(*ptr))
4629 ptr++;
4631 if (strcmpW(ptr, gmt))
4633 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4634 return FALSE;
4636 return SystemTimeToFileTime(&st, ft);
4639 static BOOL HTTP_ParseDate(LPCWSTR value, FILETIME *ft)
4641 static const WCHAR zero[] = { '0',0 };
4642 BOOL ret;
4644 if (!strcmpW(value, zero))
4646 ft->dwLowDateTime = ft->dwHighDateTime = 0;
4647 ret = TRUE;
4649 else if (strchrW(value, ','))
4651 ret = HTTP_ParseRfc1123Date(value, ft);
4652 if (!ret)
4654 ret = HTTP_ParseRfc850Date(value, ft);
4655 if (!ret)
4656 ERR("unexpected date format %s\n", debugstr_w(value));
4659 else
4661 ret = HTTP_ParseDateAsAsctime(value, ft);
4662 if (!ret)
4663 ERR("unexpected date format %s\n", debugstr_w(value));
4665 return ret;
4668 static void HTTP_ProcessExpires(http_request_t *request)
4670 BOOL expirationFound = FALSE;
4671 int headerIndex;
4673 EnterCriticalSection( &request->headers_section );
4675 /* Look for a Cache-Control header with a max-age directive, as it takes
4676 * precedence over the Expires header.
4678 headerIndex = HTTP_GetCustomHeaderIndex(request, szCache_Control, 0, FALSE);
4679 if (headerIndex != -1)
4681 LPHTTPHEADERW ccHeader = &request->custHeaders[headerIndex];
4682 LPWSTR ptr;
4684 for (ptr = ccHeader->lpszValue; ptr && *ptr; )
4686 LPWSTR comma = strchrW(ptr, ','), end, equal;
4688 if (comma)
4689 end = comma;
4690 else
4691 end = ptr + strlenW(ptr);
4692 for (equal = end - 1; equal > ptr && *equal != '='; equal--)
4694 if (*equal == '=')
4696 static const WCHAR max_age[] = {
4697 'm','a','x','-','a','g','e',0 };
4699 if (!strncmpiW(ptr, max_age, equal - ptr - 1))
4701 LPWSTR nextPtr;
4702 unsigned long age;
4704 age = strtoulW(equal + 1, &nextPtr, 10);
4705 if (nextPtr > equal + 1)
4707 LARGE_INTEGER ft;
4709 NtQuerySystemTime( &ft );
4710 /* Age is in seconds, FILETIME resolution is in
4711 * 100 nanosecond intervals.
4713 ft.QuadPart += age * (ULONGLONG)1000000;
4714 request->expires.dwLowDateTime = ft.u.LowPart;
4715 request->expires.dwHighDateTime = ft.u.HighPart;
4716 expirationFound = TRUE;
4720 if (comma)
4722 ptr = comma + 1;
4723 while (isspaceW(*ptr))
4724 ptr++;
4726 else
4727 ptr = NULL;
4730 if (!expirationFound)
4732 headerIndex = HTTP_GetCustomHeaderIndex(request, szExpires, 0, FALSE);
4733 if (headerIndex != -1)
4735 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4736 FILETIME ft;
4738 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4740 expirationFound = TRUE;
4741 request->expires = ft;
4745 if (!expirationFound)
4747 LARGE_INTEGER t;
4749 /* With no known age, default to 10 minutes until expiration. */
4750 NtQuerySystemTime( &t );
4751 t.QuadPart += 10 * 60 * (ULONGLONG)10000000;
4752 request->expires.dwLowDateTime = t.u.LowPart;
4753 request->expires.dwHighDateTime = t.u.HighPart;
4756 LeaveCriticalSection( &request->headers_section );
4759 static void HTTP_ProcessLastModified(http_request_t *request)
4761 int headerIndex;
4763 EnterCriticalSection( &request->headers_section );
4765 headerIndex = HTTP_GetCustomHeaderIndex(request, szLast_Modified, 0, FALSE);
4766 if (headerIndex != -1)
4768 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4769 FILETIME ft;
4771 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4772 request->last_modified = ft;
4775 LeaveCriticalSection( &request->headers_section );
4778 static void http_process_keep_alive(http_request_t *req)
4780 int index;
4782 EnterCriticalSection( &req->headers_section );
4784 if ((index = HTTP_GetCustomHeaderIndex(req, szConnection, 0, FALSE)) != -1)
4785 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4786 else if ((index = HTTP_GetCustomHeaderIndex(req, szProxy_Connection, 0, FALSE)) != -1)
4787 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4788 else
4789 req->netconn->keep_alive = !strcmpiW(req->version, g_szHttp1_1);
4791 LeaveCriticalSection( &req->headers_section );
4794 static DWORD open_http_connection(http_request_t *request, BOOL *reusing)
4796 const BOOL is_https = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) != 0;
4797 netconn_t *netconn = NULL;
4798 DWORD res;
4800 reset_data_stream(request);
4802 if (request->netconn)
4804 if (is_valid_netconn(request->netconn) && NETCON_is_alive(request->netconn))
4806 *reusing = TRUE;
4807 return ERROR_SUCCESS;
4809 else
4811 free_netconn(request->netconn);
4812 request->netconn = NULL;
4816 res = HTTP_ResolveName(request);
4817 if(res != ERROR_SUCCESS)
4818 return res;
4820 EnterCriticalSection(&connection_pool_cs);
4822 while(!list_empty(&request->server->conn_pool)) {
4823 netconn = LIST_ENTRY(list_head(&request->server->conn_pool), netconn_t, pool_entry);
4824 list_remove(&netconn->pool_entry);
4826 if(is_valid_netconn(netconn) && NETCON_is_alive(netconn))
4827 break;
4829 TRACE("connection %p closed during idle\n", netconn);
4830 free_netconn(netconn);
4831 netconn = NULL;
4834 LeaveCriticalSection(&connection_pool_cs);
4836 if(netconn) {
4837 TRACE("<-- reusing %p netconn\n", netconn);
4838 request->netconn = netconn;
4839 *reusing = TRUE;
4840 return ERROR_SUCCESS;
4843 TRACE("connecting to %s, proxy %s\n", debugstr_w(request->server->name),
4844 request->proxy ? debugstr_w(request->proxy->name) : "(null)");
4846 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4847 INTERNET_STATUS_CONNECTING_TO_SERVER,
4848 request->server->addr_str,
4849 strlen(request->server->addr_str)+1);
4851 res = create_netconn(is_https, request->proxy ? request->proxy : request->server, request->security_flags,
4852 (request->hdr.ErrorMask & INTERNET_ERROR_MASK_COMBINED_SEC_CERT) != 0,
4853 request->connect_timeout, &netconn);
4854 if(res != ERROR_SUCCESS) {
4855 ERR("create_netconn failed: %u\n", res);
4856 return res;
4859 request->netconn = netconn;
4861 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4862 INTERNET_STATUS_CONNECTED_TO_SERVER,
4863 request->server->addr_str, strlen(request->server->addr_str)+1);
4865 *reusing = FALSE;
4866 TRACE("Created connection to %s: %p\n", debugstr_w(request->server->name), netconn);
4867 return ERROR_SUCCESS;
4870 static char *build_ascii_request( const WCHAR *str, void *data, DWORD data_len, DWORD *out_len )
4872 int len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
4873 char *ret;
4875 if (!(ret = heap_alloc( len + data_len ))) return NULL;
4876 WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
4877 if (data_len) memcpy( ret + len - 1, data, data_len );
4878 *out_len = len + data_len - 1;
4879 ret[*out_len] = 0;
4880 return ret;
4883 static void set_content_length_header( http_request_t *request, DWORD len, DWORD flags )
4885 static const WCHAR fmtW[] =
4886 {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','u','\r','\n',0};
4887 WCHAR buf[sizeof(fmtW)/sizeof(fmtW[0]) + 10];
4889 sprintfW( buf, fmtW, len );
4890 HTTP_HttpAddRequestHeadersW( request, buf, ~0u, flags );
4893 /***********************************************************************
4894 * HTTP_HttpSendRequestW (internal)
4896 * Sends the specified request to the HTTP server
4898 * RETURNS
4899 * ERROR_SUCCESS on success
4900 * win32 error code on failure
4903 static DWORD HTTP_HttpSendRequestW(http_request_t *request, LPCWSTR lpszHeaders,
4904 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
4905 DWORD dwContentLength, BOOL bEndRequest)
4907 BOOL redirected = FALSE, secure_proxy_connect = FALSE, loop_next;
4908 LPWSTR requestString = NULL;
4909 INT responseLen, cnt;
4910 DWORD res;
4912 TRACE("--> %p\n", request);
4914 assert(request->hdr.htype == WH_HHTTPREQ);
4916 /* if the verb is NULL default to GET */
4917 if (!request->verb)
4918 request->verb = heap_strdupW(szGET);
4920 HTTP_ProcessHeader(request, hostW, request->server->canon_host_port,
4921 HTTP_ADDREQ_FLAG_ADD_IF_NEW | HTTP_ADDHDR_FLAG_REQ);
4923 if (dwContentLength || strcmpW(request->verb, szGET))
4925 set_content_length_header(request, dwContentLength, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4926 request->bytesToWrite = dwContentLength;
4928 if (request->session->appInfo->agent)
4930 WCHAR *agent_header;
4931 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4932 int len;
4934 len = strlenW(request->session->appInfo->agent) + strlenW(user_agent);
4935 agent_header = heap_alloc(len * sizeof(WCHAR));
4936 sprintfW(agent_header, user_agent, request->session->appInfo->agent);
4938 HTTP_HttpAddRequestHeadersW(request, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4939 heap_free(agent_header);
4941 if (request->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
4943 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4944 HTTP_HttpAddRequestHeadersW(request, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4946 if ((request->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && strcmpW(request->verb, szGET))
4948 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4949 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4950 HTTP_HttpAddRequestHeadersW(request, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4953 /* add the headers the caller supplied */
4954 if( lpszHeaders && dwHeaderLength )
4955 HTTP_HttpAddRequestHeadersW(request, lpszHeaders, dwHeaderLength, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
4959 DWORD len, data_len = dwOptionalLength;
4960 BOOL reusing_connection;
4961 char *ascii_req;
4963 loop_next = FALSE;
4965 if(redirected) {
4966 request->contentLength = ~0u;
4967 request->bytesToWrite = 0;
4970 if (TRACE_ON(wininet))
4972 HTTPHEADERW *host;
4974 EnterCriticalSection( &request->headers_section );
4975 host = HTTP_GetHeader( request, hostW );
4976 TRACE("Going to url %s %s\n", debugstr_w(host->lpszValue), debugstr_w(request->path));
4977 LeaveCriticalSection( &request->headers_section );
4980 HTTP_FixURL(request);
4981 if (request->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
4983 HTTP_ProcessHeader(request, szConnection, szKeepAlive,
4984 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD);
4986 HTTP_InsertAuthorization(request, request->authInfo, szAuthorization);
4987 HTTP_InsertAuthorization(request, request->proxyAuthInfo, szProxy_Authorization);
4989 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
4990 HTTP_InsertCookies(request);
4992 res = open_http_connection(request, &reusing_connection);
4993 if (res != ERROR_SUCCESS)
4994 break;
4996 if (!reusing_connection && (request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4998 if (request->proxy) secure_proxy_connect = TRUE;
4999 else
5001 res = NETCON_secure_connect(request->netconn, request->server);
5002 if (res != ERROR_SUCCESS)
5004 WARN("failed to upgrade to secure connection\n");
5005 http_release_netconn(request, FALSE);
5006 break;
5010 if (secure_proxy_connect)
5012 static const WCHAR connectW[] = {'C','O','N','N','E','C','T',0};
5013 const WCHAR *target = request->server->host_port;
5015 if (HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE) >= 0)
5016 set_content_length_header(request, 0, HTTP_ADDREQ_FLAG_REPLACE);
5018 requestString = build_request_header(request, connectW, target, g_szHttp1_1, TRUE);
5020 else if (request->proxy && !(request->hdr.dwFlags & INTERNET_FLAG_SECURE))
5022 WCHAR *url = build_proxy_path_url(request);
5023 requestString = build_request_header(request, request->verb, url, request->version, TRUE);
5024 heap_free(url);
5026 else
5028 if (request->proxy && HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE) >= 0)
5029 set_content_length_header(request, dwContentLength, HTTP_ADDREQ_FLAG_REPLACE);
5031 requestString = build_request_header(request, request->verb, request->path, request->version, TRUE);
5034 TRACE("Request header -> %s\n", debugstr_w(requestString) );
5036 /* send the request as ASCII, tack on the optional data */
5037 if (!lpOptional || redirected || secure_proxy_connect)
5038 data_len = 0;
5040 ascii_req = build_ascii_request( requestString, lpOptional, data_len, &len );
5041 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
5043 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5044 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
5046 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
5047 res = NETCON_send(request->netconn, ascii_req, len, 0, &cnt);
5048 heap_free( ascii_req );
5049 if(res != ERROR_SUCCESS) {
5050 TRACE("send failed: %u\n", res);
5051 if(!reusing_connection)
5052 break;
5053 http_release_netconn(request, FALSE);
5054 loop_next = TRUE;
5055 continue;
5058 request->bytesWritten = data_len;
5060 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5061 INTERNET_STATUS_REQUEST_SENT,
5062 &len, sizeof(DWORD));
5064 if (bEndRequest)
5066 DWORD dwBufferSize;
5068 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5069 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5071 if (HTTP_GetResponseHeaders(request, &responseLen))
5073 http_release_netconn(request, FALSE);
5074 res = ERROR_INTERNET_CONNECTION_ABORTED;
5075 goto lend;
5077 /* FIXME: We should know that connection is closed before sending
5078 * headers. Otherwise wrong callbacks are executed */
5079 if(!responseLen && reusing_connection) {
5080 TRACE("Connection closed by server, reconnecting\n");
5081 http_release_netconn(request, FALSE);
5082 loop_next = TRUE;
5083 continue;
5086 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5087 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
5088 sizeof(DWORD));
5090 http_process_keep_alive(request);
5091 HTTP_ProcessCookies(request);
5092 HTTP_ProcessExpires(request);
5093 HTTP_ProcessLastModified(request);
5095 res = set_content_length(request);
5096 if(res != ERROR_SUCCESS)
5097 goto lend;
5098 if(!request->contentLength)
5099 http_release_netconn(request, TRUE);
5101 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
5103 WCHAR *new_url;
5105 switch(request->status_code) {
5106 case HTTP_STATUS_REDIRECT:
5107 case HTTP_STATUS_MOVED:
5108 case HTTP_STATUS_REDIRECT_KEEP_VERB:
5109 case HTTP_STATUS_REDIRECT_METHOD:
5110 new_url = get_redirect_url(request);
5111 if(!new_url)
5112 break;
5114 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5115 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5117 heap_free(request->verb);
5118 request->verb = heap_strdupW(szGET);
5120 http_release_netconn(request, drain_content(request, FALSE));
5121 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5122 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5123 res = HTTP_HandleRedirect(request, new_url);
5124 heap_free(new_url);
5125 if (res == ERROR_SUCCESS) {
5126 heap_free(requestString);
5127 loop_next = TRUE;
5129 redirected = TRUE;
5132 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
5134 WCHAR szAuthValue[2048];
5135 dwBufferSize=2048;
5136 if (request->status_code == HTTP_STATUS_DENIED)
5138 WCHAR *host = heap_strdupW( request->server->canon_host_port );
5139 DWORD dwIndex = 0;
5140 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5142 if (HTTP_DoAuthorization(request, szAuthValue,
5143 &request->authInfo,
5144 request->session->userName,
5145 request->session->password, host))
5147 heap_free(requestString);
5148 if(!drain_content(request, TRUE)) {
5149 FIXME("Could not drain content\n");
5150 http_release_netconn(request, FALSE);
5152 loop_next = TRUE;
5153 break;
5156 heap_free( host );
5158 if(!loop_next) {
5159 TRACE("Cleaning wrong authorization data\n");
5160 destroy_authinfo(request->authInfo);
5161 request->authInfo = NULL;
5164 if (request->status_code == HTTP_STATUS_PROXY_AUTH_REQ)
5166 DWORD dwIndex = 0;
5167 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5169 if (HTTP_DoAuthorization(request, szAuthValue,
5170 &request->proxyAuthInfo,
5171 request->session->appInfo->proxyUsername,
5172 request->session->appInfo->proxyPassword,
5173 NULL))
5175 heap_free(requestString);
5176 if(!drain_content(request, TRUE)) {
5177 FIXME("Could not drain content\n");
5178 http_release_netconn(request, FALSE);
5180 loop_next = TRUE;
5181 break;
5185 if(!loop_next) {
5186 TRACE("Cleaning wrong proxy authorization data\n");
5187 destroy_authinfo(request->proxyAuthInfo);
5188 request->proxyAuthInfo = NULL;
5192 if (secure_proxy_connect && request->status_code == HTTP_STATUS_OK)
5194 res = NETCON_secure_connect(request->netconn, request->server);
5195 if (res != ERROR_SUCCESS)
5197 WARN("failed to upgrade to secure proxy connection\n");
5198 http_release_netconn( request, FALSE );
5199 break;
5201 remove_header(request, szProxy_Authorization, TRUE);
5202 destroy_authinfo(request->proxyAuthInfo);
5203 request->proxyAuthInfo = NULL;
5205 secure_proxy_connect = FALSE;
5206 loop_next = TRUE;
5209 else
5210 res = ERROR_SUCCESS;
5212 while (loop_next);
5214 lend:
5215 heap_free(requestString);
5217 /* TODO: send notification for P3P header */
5219 if(res == ERROR_SUCCESS)
5220 create_cache_entry(request);
5222 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5224 if (res == ERROR_SUCCESS) {
5225 if(bEndRequest && request->contentLength && request->bytesWritten == request->bytesToWrite)
5226 HTTP_ReceiveRequestData(request, TRUE, NULL);
5227 else
5228 send_request_complete(request,
5229 request->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)request->hdr.hInternet : 1, 0);
5230 }else {
5231 send_request_complete(request, 0, res);
5235 TRACE("<--\n");
5236 return res;
5239 typedef struct {
5240 task_header_t hdr;
5241 WCHAR *headers;
5242 DWORD headers_len;
5243 void *optional;
5244 DWORD optional_len;
5245 DWORD content_len;
5246 BOOL end_request;
5247 } send_request_task_t;
5249 /***********************************************************************
5251 * Helper functions for the HttpSendRequest(Ex) functions
5254 static void AsyncHttpSendRequestProc(task_header_t *hdr)
5256 send_request_task_t *task = (send_request_task_t*)hdr;
5257 http_request_t *request = (http_request_t*)task->hdr.hdr;
5259 TRACE("%p\n", request);
5261 HTTP_HttpSendRequestW(request, task->headers, task->headers_len, task->optional,
5262 task->optional_len, task->content_len, task->end_request);
5264 heap_free(task->headers);
5268 static DWORD HTTP_HttpEndRequestW(http_request_t *request, DWORD dwFlags, DWORD_PTR dwContext)
5270 INT responseLen;
5271 DWORD res = ERROR_SUCCESS;
5273 if(!is_valid_netconn(request->netconn)) {
5274 WARN("Not connected\n");
5275 send_request_complete(request, 0, ERROR_INTERNET_OPERATION_CANCELLED);
5276 return ERROR_INTERNET_OPERATION_CANCELLED;
5279 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5280 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5282 if (HTTP_GetResponseHeaders(request, &responseLen) || !responseLen)
5283 res = ERROR_HTTP_HEADER_NOT_FOUND;
5285 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5286 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
5288 /* process cookies here. Is this right? */
5289 http_process_keep_alive(request);
5290 HTTP_ProcessCookies(request);
5291 HTTP_ProcessExpires(request);
5292 HTTP_ProcessLastModified(request);
5294 if ((res = set_content_length(request)) == ERROR_SUCCESS) {
5295 if(!request->contentLength)
5296 http_release_netconn(request, TRUE);
5299 if (res == ERROR_SUCCESS && !(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
5301 switch(request->status_code) {
5302 case HTTP_STATUS_REDIRECT:
5303 case HTTP_STATUS_MOVED:
5304 case HTTP_STATUS_REDIRECT_METHOD:
5305 case HTTP_STATUS_REDIRECT_KEEP_VERB: {
5306 WCHAR *new_url;
5308 new_url = get_redirect_url(request);
5309 if(!new_url)
5310 break;
5312 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5313 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5315 heap_free(request->verb);
5316 request->verb = heap_strdupW(szGET);
5318 http_release_netconn(request, drain_content(request, FALSE));
5319 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
5320 new_url, (strlenW(new_url) + 1) * sizeof(WCHAR));
5321 res = HTTP_HandleRedirect(request, new_url);
5322 heap_free(new_url);
5323 if (res == ERROR_SUCCESS)
5324 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, TRUE);
5329 if(res == ERROR_SUCCESS)
5330 create_cache_entry(request);
5332 if (res == ERROR_SUCCESS && request->contentLength)
5333 HTTP_ReceiveRequestData(request, TRUE, NULL);
5334 else
5335 send_request_complete(request, res == ERROR_SUCCESS, res);
5337 return res;
5340 /***********************************************************************
5341 * HttpEndRequestA (WININET.@)
5343 * Ends an HTTP request that was started by HttpSendRequestEx
5345 * RETURNS
5346 * TRUE if successful
5347 * FALSE on failure
5350 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
5351 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5353 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5355 if (lpBuffersOut)
5357 SetLastError(ERROR_INVALID_PARAMETER);
5358 return FALSE;
5361 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
5364 typedef struct {
5365 task_header_t hdr;
5366 DWORD flags;
5367 DWORD context;
5368 } end_request_task_t;
5370 static void AsyncHttpEndRequestProc(task_header_t *hdr)
5372 end_request_task_t *task = (end_request_task_t*)hdr;
5373 http_request_t *req = (http_request_t*)task->hdr.hdr;
5375 TRACE("%p\n", req);
5377 HTTP_HttpEndRequestW(req, task->flags, task->context);
5380 /***********************************************************************
5381 * HttpEndRequestW (WININET.@)
5383 * Ends an HTTP request that was started by HttpSendRequestEx
5385 * RETURNS
5386 * TRUE if successful
5387 * FALSE on failure
5390 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
5391 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5393 http_request_t *request;
5394 DWORD res;
5396 TRACE("%p %p %x %lx -->\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5398 if (lpBuffersOut)
5400 SetLastError(ERROR_INVALID_PARAMETER);
5401 return FALSE;
5404 request = (http_request_t*) get_handle_object( hRequest );
5406 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5408 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
5409 if (request)
5410 WININET_Release( &request->hdr );
5411 return FALSE;
5413 request->hdr.dwFlags |= dwFlags;
5415 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5417 end_request_task_t *task;
5419 task = alloc_async_task(&request->hdr, AsyncHttpEndRequestProc, sizeof(*task));
5420 task->flags = dwFlags;
5421 task->context = dwContext;
5423 INTERNET_AsyncCall(&task->hdr);
5424 res = ERROR_IO_PENDING;
5426 else
5427 res = HTTP_HttpEndRequestW(request, dwFlags, dwContext);
5429 WININET_Release( &request->hdr );
5430 TRACE("%u <--\n", res);
5431 if(res != ERROR_SUCCESS)
5432 SetLastError(res);
5433 return res == ERROR_SUCCESS;
5436 /***********************************************************************
5437 * HttpSendRequestExA (WININET.@)
5439 * Sends the specified request to the HTTP server and allows chunked
5440 * transfers.
5442 * RETURNS
5443 * Success: TRUE
5444 * Failure: FALSE, call GetLastError() for more information.
5446 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
5447 LPINTERNET_BUFFERSA lpBuffersIn,
5448 LPINTERNET_BUFFERSA lpBuffersOut,
5449 DWORD dwFlags, DWORD_PTR dwContext)
5451 INTERNET_BUFFERSW BuffersInW;
5452 BOOL rc = FALSE;
5453 DWORD headerlen;
5454 LPWSTR header = NULL;
5456 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5457 lpBuffersOut, dwFlags, dwContext);
5459 if (lpBuffersIn)
5461 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
5462 if (lpBuffersIn->lpcszHeader)
5464 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
5465 lpBuffersIn->dwHeadersLength,0,0);
5466 header = heap_alloc(headerlen*sizeof(WCHAR));
5467 if (!(BuffersInW.lpcszHeader = header))
5469 SetLastError(ERROR_OUTOFMEMORY);
5470 return FALSE;
5472 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
5473 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5474 header, headerlen);
5476 else
5477 BuffersInW.lpcszHeader = NULL;
5478 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
5479 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
5480 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
5481 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
5482 BuffersInW.Next = NULL;
5485 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
5487 heap_free(header);
5488 return rc;
5491 /***********************************************************************
5492 * HttpSendRequestExW (WININET.@)
5494 * Sends the specified request to the HTTP server and allows chunked
5495 * transfers
5497 * RETURNS
5498 * Success: TRUE
5499 * Failure: FALSE, call GetLastError() for more information.
5501 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
5502 LPINTERNET_BUFFERSW lpBuffersIn,
5503 LPINTERNET_BUFFERSW lpBuffersOut,
5504 DWORD dwFlags, DWORD_PTR dwContext)
5506 http_request_t *request;
5507 http_session_t *session;
5508 appinfo_t *hIC;
5509 DWORD res;
5511 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5512 lpBuffersOut, dwFlags, dwContext);
5514 request = (http_request_t*) get_handle_object( hRequest );
5516 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5518 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5519 goto lend;
5522 session = request->session;
5523 assert(session->hdr.htype == WH_HHTTPSESSION);
5524 hIC = session->appInfo;
5525 assert(hIC->hdr.htype == WH_HINIT);
5527 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5529 send_request_task_t *task;
5531 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5532 if (lpBuffersIn)
5534 DWORD size = 0;
5536 if (lpBuffersIn->lpcszHeader)
5538 if (lpBuffersIn->dwHeadersLength == ~0u)
5539 size = (strlenW( lpBuffersIn->lpcszHeader ) + 1) * sizeof(WCHAR);
5540 else
5541 size = lpBuffersIn->dwHeadersLength * sizeof(WCHAR);
5543 task->headers = heap_alloc(size);
5544 memcpy(task->headers, lpBuffersIn->lpcszHeader, size);
5546 else task->headers = NULL;
5548 task->headers_len = size / sizeof(WCHAR);
5549 task->optional = lpBuffersIn->lpvBuffer;
5550 task->optional_len = lpBuffersIn->dwBufferLength;
5551 task->content_len = lpBuffersIn->dwBufferTotal;
5553 else
5555 task->headers = NULL;
5556 task->headers_len = 0;
5557 task->optional = NULL;
5558 task->optional_len = 0;
5559 task->content_len = 0;
5562 task->end_request = FALSE;
5564 INTERNET_AsyncCall(&task->hdr);
5565 res = ERROR_IO_PENDING;
5567 else
5569 if (lpBuffersIn)
5570 res = HTTP_HttpSendRequestW(request, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5571 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
5572 lpBuffersIn->dwBufferTotal, FALSE);
5573 else
5574 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, FALSE);
5577 lend:
5578 if ( request )
5579 WININET_Release( &request->hdr );
5581 TRACE("<---\n");
5582 SetLastError(res);
5583 return res == ERROR_SUCCESS;
5586 /***********************************************************************
5587 * HttpSendRequestW (WININET.@)
5589 * Sends the specified request to the HTTP server
5591 * RETURNS
5592 * TRUE on success
5593 * FALSE on failure
5596 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
5597 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5599 http_request_t *request;
5600 http_session_t *session = NULL;
5601 appinfo_t *hIC = NULL;
5602 DWORD res = ERROR_SUCCESS;
5604 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
5605 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
5607 request = (http_request_t*) get_handle_object( hHttpRequest );
5608 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5610 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5611 goto lend;
5614 session = request->session;
5615 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
5617 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5618 goto lend;
5621 hIC = session->appInfo;
5622 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
5624 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5625 goto lend;
5628 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5630 send_request_task_t *task;
5632 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5633 if (lpszHeaders)
5635 DWORD size;
5637 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
5638 else size = dwHeaderLength * sizeof(WCHAR);
5640 task->headers = heap_alloc(size);
5641 memcpy(task->headers, lpszHeaders, size);
5643 else
5644 task->headers = NULL;
5645 task->headers_len = dwHeaderLength;
5646 task->optional = lpOptional;
5647 task->optional_len = dwOptionalLength;
5648 task->content_len = dwOptionalLength;
5649 task->end_request = TRUE;
5651 INTERNET_AsyncCall(&task->hdr);
5652 res = ERROR_IO_PENDING;
5654 else
5656 res = HTTP_HttpSendRequestW(request, lpszHeaders,
5657 dwHeaderLength, lpOptional, dwOptionalLength,
5658 dwOptionalLength, TRUE);
5660 lend:
5661 if( request )
5662 WININET_Release( &request->hdr );
5664 SetLastError(res);
5665 return res == ERROR_SUCCESS;
5668 /***********************************************************************
5669 * HttpSendRequestA (WININET.@)
5671 * Sends the specified request to the HTTP server
5673 * RETURNS
5674 * TRUE on success
5675 * FALSE on failure
5678 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
5679 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5681 BOOL result;
5682 LPWSTR szHeaders=NULL;
5683 DWORD nLen=dwHeaderLength;
5684 if(lpszHeaders!=NULL)
5686 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
5687 szHeaders = heap_alloc(nLen*sizeof(WCHAR));
5688 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
5690 result = HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
5691 heap_free(szHeaders);
5692 return result;
5695 /***********************************************************************
5696 * HTTPSESSION_Destroy (internal)
5698 * Deallocate session handle
5701 static void HTTPSESSION_Destroy(object_header_t *hdr)
5703 http_session_t *session = (http_session_t*) hdr;
5705 TRACE("%p\n", session);
5707 WININET_Release(&session->appInfo->hdr);
5709 heap_free(session->hostName);
5710 heap_free(session->password);
5711 heap_free(session->userName);
5714 static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
5716 http_session_t *ses = (http_session_t *)hdr;
5718 switch(option) {
5719 case INTERNET_OPTION_HANDLE_TYPE:
5720 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5722 if (*size < sizeof(ULONG))
5723 return ERROR_INSUFFICIENT_BUFFER;
5725 *size = sizeof(DWORD);
5726 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
5727 return ERROR_SUCCESS;
5728 case INTERNET_OPTION_CONNECT_TIMEOUT:
5729 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5731 if (*size < sizeof(DWORD))
5732 return ERROR_INSUFFICIENT_BUFFER;
5734 *size = sizeof(DWORD);
5735 *(DWORD *)buffer = ses->connect_timeout;
5736 return ERROR_SUCCESS;
5738 case INTERNET_OPTION_SEND_TIMEOUT:
5739 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5741 if (*size < sizeof(DWORD))
5742 return ERROR_INSUFFICIENT_BUFFER;
5744 *size = sizeof(DWORD);
5745 *(DWORD *)buffer = ses->send_timeout;
5746 return ERROR_SUCCESS;
5748 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5749 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5751 if (*size < sizeof(DWORD))
5752 return ERROR_INSUFFICIENT_BUFFER;
5754 *size = sizeof(DWORD);
5755 *(DWORD *)buffer = ses->receive_timeout;
5756 return ERROR_SUCCESS;
5759 return INET_QueryOption(hdr, option, buffer, size, unicode);
5762 static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
5764 http_session_t *ses = (http_session_t*)hdr;
5766 switch(option) {
5767 case INTERNET_OPTION_USERNAME:
5769 heap_free(ses->userName);
5770 if (!(ses->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5771 return ERROR_SUCCESS;
5773 case INTERNET_OPTION_PASSWORD:
5775 heap_free(ses->password);
5776 if (!(ses->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5777 return ERROR_SUCCESS;
5779 case INTERNET_OPTION_PROXY_USERNAME:
5781 heap_free(ses->appInfo->proxyUsername);
5782 if (!(ses->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5783 return ERROR_SUCCESS;
5785 case INTERNET_OPTION_PROXY_PASSWORD:
5787 heap_free(ses->appInfo->proxyPassword);
5788 if (!(ses->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5789 return ERROR_SUCCESS;
5791 case INTERNET_OPTION_CONNECT_TIMEOUT:
5793 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5794 ses->connect_timeout = *(DWORD *)buffer;
5795 return ERROR_SUCCESS;
5797 case INTERNET_OPTION_SEND_TIMEOUT:
5799 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5800 ses->send_timeout = *(DWORD *)buffer;
5801 return ERROR_SUCCESS;
5803 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5805 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5806 ses->receive_timeout = *(DWORD *)buffer;
5807 return ERROR_SUCCESS;
5809 default: break;
5812 return INET_SetOption(hdr, option, buffer, size);
5815 static const object_vtbl_t HTTPSESSIONVtbl = {
5816 HTTPSESSION_Destroy,
5817 NULL,
5818 HTTPSESSION_QueryOption,
5819 HTTPSESSION_SetOption,
5820 NULL,
5821 NULL,
5822 NULL,
5823 NULL,
5824 NULL
5828 /***********************************************************************
5829 * HTTP_Connect (internal)
5831 * Create http session handle
5833 * RETURNS
5834 * HINTERNET a session handle on success
5835 * NULL on failure
5838 DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
5839 INTERNET_PORT serverPort, LPCWSTR lpszUserName,
5840 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
5841 DWORD dwInternalFlags, HINTERNET *ret)
5843 http_session_t *session = NULL;
5845 TRACE("-->\n");
5847 if (!lpszServerName || !lpszServerName[0])
5848 return ERROR_INVALID_PARAMETER;
5850 assert( hIC->hdr.htype == WH_HINIT );
5852 session = alloc_object(&hIC->hdr, &HTTPSESSIONVtbl, sizeof(http_session_t));
5853 if (!session)
5854 return ERROR_OUTOFMEMORY;
5857 * According to my tests. The name is not resolved until a request is sent
5860 session->hdr.htype = WH_HHTTPSESSION;
5861 session->hdr.dwFlags = dwFlags;
5862 session->hdr.dwContext = dwContext;
5863 session->hdr.dwInternalFlags |= dwInternalFlags;
5865 WININET_AddRef( &hIC->hdr );
5866 session->appInfo = hIC;
5867 list_add_head( &hIC->hdr.children, &session->hdr.entry );
5869 session->hostName = heap_strdupW(lpszServerName);
5870 if (lpszUserName && lpszUserName[0])
5871 session->userName = heap_strdupW(lpszUserName);
5872 if (lpszPassword && lpszPassword[0])
5873 session->password = heap_strdupW(lpszPassword);
5874 session->hostPort = serverPort;
5875 session->connect_timeout = hIC->connect_timeout;
5876 session->send_timeout = 0;
5877 session->receive_timeout = 0;
5879 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5880 if (!(session->hdr.dwInternalFlags & INET_OPENURL))
5882 INTERNET_SendCallback(&hIC->hdr, dwContext,
5883 INTERNET_STATUS_HANDLE_CREATED, &session->hdr.hInternet,
5884 sizeof(HINTERNET));
5888 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5889 * windows
5892 TRACE("%p --> %p\n", hIC, session);
5894 *ret = session->hdr.hInternet;
5895 return ERROR_SUCCESS;
5898 /***********************************************************************
5899 * HTTP_clear_response_headers (internal)
5901 * clear out any old response headers
5903 static void HTTP_clear_response_headers( http_request_t *request )
5905 DWORD i;
5907 EnterCriticalSection( &request->headers_section );
5909 for( i=0; i<request->nCustHeaders; i++)
5911 if( !request->custHeaders[i].lpszField )
5912 continue;
5913 if( !request->custHeaders[i].lpszValue )
5914 continue;
5915 if ( request->custHeaders[i].wFlags & HDR_ISREQUEST )
5916 continue;
5917 HTTP_DeleteCustomHeader( request, i );
5918 i--;
5921 LeaveCriticalSection( &request->headers_section );
5924 /***********************************************************************
5925 * HTTP_GetResponseHeaders (internal)
5927 * Read server response
5929 * RETURNS
5931 * TRUE on success
5932 * FALSE on error
5934 static DWORD HTTP_GetResponseHeaders(http_request_t *request, INT *len)
5936 INT cbreaks = 0;
5937 WCHAR buffer[MAX_REPLY_LEN];
5938 DWORD buflen = MAX_REPLY_LEN;
5939 INT rc = 0;
5940 char bufferA[MAX_REPLY_LEN];
5941 LPWSTR status_code = NULL, status_text = NULL;
5942 DWORD res = ERROR_HTTP_INVALID_SERVER_RESPONSE;
5943 BOOL codeHundred = FALSE;
5945 TRACE("-->\n");
5947 if(!is_valid_netconn(request->netconn))
5948 goto lend;
5950 /* clear old response headers (eg. from a redirect response) */
5951 HTTP_clear_response_headers( request );
5953 NETCON_set_timeout( request->netconn, FALSE, request->receive_timeout );
5954 do {
5956 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5958 buflen = MAX_REPLY_LEN;
5959 if ((res = read_line(request, bufferA, &buflen)))
5960 goto lend;
5962 if (!buflen) goto lend;
5964 rc += buflen;
5965 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5966 /* check is this a status code line? */
5967 if (!strncmpW(buffer, g_szHttp1_0, 4))
5969 /* split the version from the status code */
5970 status_code = strchrW( buffer, ' ' );
5971 if( !status_code )
5972 goto lend;
5973 *status_code++=0;
5975 /* split the status code from the status text */
5976 status_text = strchrW( status_code, ' ' );
5977 if( status_text )
5978 *status_text++=0;
5980 request->status_code = atoiW(status_code);
5982 TRACE("version [%s] status code [%s] status text [%s]\n",
5983 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
5985 codeHundred = request->status_code == HTTP_STATUS_CONTINUE;
5987 else if (!codeHundred)
5989 WARN("No status line at head of response (%s)\n", debugstr_w(buffer));
5991 heap_free(request->version);
5992 heap_free(request->statusText);
5994 request->status_code = HTTP_STATUS_OK;
5995 request->version = heap_strdupW(g_szHttp1_0);
5996 request->statusText = heap_strdupW(szOK);
5998 goto lend;
6000 } while (codeHundred);
6002 /* Add status code */
6003 HTTP_ProcessHeader(request, szStatus, status_code,
6004 HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD);
6006 heap_free(request->version);
6007 heap_free(request->statusText);
6009 request->version = heap_strdupW(buffer);
6010 request->statusText = heap_strdupW(status_text ? status_text : emptyW);
6012 /* Restore the spaces */
6013 *(status_code-1) = ' ';
6014 if (status_text)
6015 *(status_text-1) = ' ';
6017 /* Parse each response line */
6020 buflen = MAX_REPLY_LEN;
6021 if (!read_line(request, bufferA, &buflen) && buflen)
6023 LPWSTR * pFieldAndValue;
6025 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
6027 if (!bufferA[0]) break;
6028 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
6030 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
6031 if (pFieldAndValue)
6033 HTTP_ProcessHeader(request, pFieldAndValue[0], pFieldAndValue[1],
6034 HTTP_ADDREQ_FLAG_ADD );
6035 HTTP_FreeTokens(pFieldAndValue);
6038 else
6040 cbreaks++;
6041 if (cbreaks >= 2)
6042 break;
6044 }while(1);
6046 res = ERROR_SUCCESS;
6048 lend:
6050 *len = rc;
6051 TRACE("<--\n");
6052 return res;
6055 /***********************************************************************
6056 * HTTP_InterpretHttpHeader (internal)
6058 * Parse server response
6060 * RETURNS
6062 * Pointer to array of field, value, NULL on success.
6063 * NULL on error.
6065 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
6067 LPWSTR * pTokenPair;
6068 LPWSTR pszColon;
6069 INT len;
6071 pTokenPair = heap_alloc_zero(sizeof(*pTokenPair)*3);
6073 pszColon = strchrW(buffer, ':');
6074 /* must have two tokens */
6075 if (!pszColon)
6077 HTTP_FreeTokens(pTokenPair);
6078 if (buffer[0])
6079 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
6080 return NULL;
6083 pTokenPair[0] = heap_alloc((pszColon - buffer + 1) * sizeof(WCHAR));
6084 if (!pTokenPair[0])
6086 HTTP_FreeTokens(pTokenPair);
6087 return NULL;
6089 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
6090 pTokenPair[0][pszColon - buffer] = '\0';
6092 /* skip colon */
6093 pszColon++;
6094 len = strlenW(pszColon);
6095 pTokenPair[1] = heap_alloc((len + 1) * sizeof(WCHAR));
6096 if (!pTokenPair[1])
6098 HTTP_FreeTokens(pTokenPair);
6099 return NULL;
6101 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
6103 strip_spaces(pTokenPair[0]);
6104 strip_spaces(pTokenPair[1]);
6106 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
6107 return pTokenPair;
6110 /***********************************************************************
6111 * HTTP_ProcessHeader (internal)
6113 * Stuff header into header tables according to <dwModifier>
6117 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6119 static DWORD HTTP_ProcessHeader(http_request_t *request, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
6121 LPHTTPHEADERW lphttpHdr = NULL;
6122 INT index;
6123 BOOL request_only = !!(dwModifier & HTTP_ADDHDR_FLAG_REQ);
6124 DWORD res = ERROR_HTTP_INVALID_HEADER;
6126 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
6128 EnterCriticalSection( &request->headers_section );
6130 /* REPLACE wins out over ADD */
6131 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6132 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
6134 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
6135 index = -1;
6136 else
6137 index = HTTP_GetCustomHeaderIndex(request, field, 0, request_only);
6139 if (index >= 0)
6141 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
6143 LeaveCriticalSection( &request->headers_section );
6144 return ERROR_HTTP_INVALID_HEADER;
6146 lphttpHdr = &request->custHeaders[index];
6148 else if (value)
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;
6163 /* no value to delete */
6164 else
6166 LeaveCriticalSection( &request->headers_section );
6167 return ERROR_SUCCESS;
6170 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6171 lphttpHdr->wFlags |= HDR_ISREQUEST;
6172 else
6173 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
6175 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6177 HTTP_DeleteCustomHeader( request, index );
6179 if (value && value[0])
6181 HTTPHEADERW hdr;
6183 hdr.lpszField = (LPWSTR)field;
6184 hdr.lpszValue = (LPWSTR)value;
6185 hdr.wFlags = hdr.wCount = 0;
6187 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6188 hdr.wFlags |= HDR_ISREQUEST;
6190 res = HTTP_InsertCustomHeader(request, &hdr);
6191 LeaveCriticalSection( &request->headers_section );
6192 return res;
6195 LeaveCriticalSection( &request->headers_section );
6196 return ERROR_SUCCESS;
6198 else if (dwModifier & COALESCEFLAGS)
6200 LPWSTR lpsztmp;
6201 WCHAR ch = 0;
6202 INT len = 0;
6203 INT origlen = strlenW(lphttpHdr->lpszValue);
6204 INT valuelen = strlenW(value);
6206 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
6208 ch = ',';
6209 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6211 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6213 ch = ';';
6214 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6217 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
6219 lpsztmp = heap_realloc(lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
6220 if (lpsztmp)
6222 lphttpHdr->lpszValue = lpsztmp;
6223 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6224 if (ch > 0)
6226 lphttpHdr->lpszValue[origlen] = ch;
6227 origlen++;
6228 lphttpHdr->lpszValue[origlen] = ' ';
6229 origlen++;
6232 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
6233 lphttpHdr->lpszValue[len] = '\0';
6234 res = ERROR_SUCCESS;
6236 else
6238 WARN("heap_realloc (%d bytes) failed\n",len+1);
6239 res = ERROR_OUTOFMEMORY;
6242 TRACE("<-- %d\n", res);
6243 LeaveCriticalSection( &request->headers_section );
6244 return res;
6247 /***********************************************************************
6248 * HTTP_GetCustomHeaderIndex (internal)
6250 * Return index of custom header from header array
6251 * Headers section must be held
6253 static INT HTTP_GetCustomHeaderIndex(http_request_t *request, LPCWSTR lpszField,
6254 int requested_index, BOOL request_only)
6256 DWORD index;
6258 TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
6260 for (index = 0; index < request->nCustHeaders; index++)
6262 if (strcmpiW(request->custHeaders[index].lpszField, lpszField))
6263 continue;
6265 if (request_only && !(request->custHeaders[index].wFlags & HDR_ISREQUEST))
6266 continue;
6268 if (!request_only && (request->custHeaders[index].wFlags & HDR_ISREQUEST))
6269 continue;
6271 if (requested_index == 0)
6272 break;
6273 requested_index --;
6276 if (index >= request->nCustHeaders)
6277 index = -1;
6279 TRACE("Return: %d\n", index);
6280 return index;
6284 /***********************************************************************
6285 * HTTP_InsertCustomHeader (internal)
6287 * Insert header into array
6288 * Headers section must be held
6290 static DWORD HTTP_InsertCustomHeader(http_request_t *request, LPHTTPHEADERW lpHdr)
6292 INT count;
6293 LPHTTPHEADERW lph = NULL;
6295 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
6296 count = request->nCustHeaders + 1;
6297 if (count > 1)
6298 lph = heap_realloc_zero(request->custHeaders, sizeof(HTTPHEADERW) * count);
6299 else
6300 lph = heap_alloc_zero(sizeof(HTTPHEADERW) * count);
6302 if (!lph)
6303 return ERROR_OUTOFMEMORY;
6305 request->custHeaders = lph;
6306 request->custHeaders[count-1].lpszField = heap_strdupW(lpHdr->lpszField);
6307 request->custHeaders[count-1].lpszValue = heap_strdupW(lpHdr->lpszValue);
6308 request->custHeaders[count-1].wFlags = lpHdr->wFlags;
6309 request->custHeaders[count-1].wCount= lpHdr->wCount;
6310 request->nCustHeaders++;
6312 return ERROR_SUCCESS;
6316 /***********************************************************************
6317 * HTTP_DeleteCustomHeader (internal)
6319 * Delete header from array
6320 * If this function is called, the index may change.
6321 * Headers section must be held
6323 static BOOL HTTP_DeleteCustomHeader(http_request_t *request, DWORD index)
6325 if( request->nCustHeaders <= 0 )
6326 return FALSE;
6327 if( index >= request->nCustHeaders )
6328 return FALSE;
6329 request->nCustHeaders--;
6331 heap_free(request->custHeaders[index].lpszField);
6332 heap_free(request->custHeaders[index].lpszValue);
6334 memmove( &request->custHeaders[index], &request->custHeaders[index+1],
6335 (request->nCustHeaders - index)* sizeof(HTTPHEADERW) );
6336 memset( &request->custHeaders[request->nCustHeaders], 0, sizeof(HTTPHEADERW) );
6338 return TRUE;
6342 /***********************************************************************
6343 * IsHostInProxyBypassList (@)
6345 * Undocumented
6348 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
6350 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
6351 return FALSE;