comctl32/tests: Avoid a structure initialization warning.
[wine.git] / dlls / wininet / http.c
blob4122067e4158f314c337317c0ef4363b50df892e
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 struct HttpAuthInfo
150 LPWSTR scheme;
151 CredHandle cred;
152 CtxtHandle ctx;
153 TimeStamp exp;
154 ULONG attr;
155 ULONG max_token;
156 void *auth_data;
157 unsigned int auth_data_len;
158 BOOL finished; /* finished authenticating */
162 typedef struct _basicAuthorizationData
164 struct list entry;
166 LPWSTR host;
167 LPWSTR realm;
168 LPSTR authorization;
169 UINT authorizationLen;
170 } basicAuthorizationData;
172 typedef struct _authorizationData
174 struct list entry;
176 LPWSTR host;
177 LPWSTR scheme;
178 LPWSTR domain;
179 UINT domain_len;
180 LPWSTR user;
181 UINT user_len;
182 LPWSTR password;
183 UINT password_len;
184 } authorizationData;
186 static struct list basicAuthorizationCache = LIST_INIT(basicAuthorizationCache);
187 static struct list authorizationCache = LIST_INIT(authorizationCache);
189 static CRITICAL_SECTION authcache_cs;
190 static CRITICAL_SECTION_DEBUG critsect_debug =
192 0, 0, &authcache_cs,
193 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
194 0, 0, { (DWORD_PTR)(__FILE__ ": authcache_cs") }
196 static CRITICAL_SECTION authcache_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
198 static DWORD HTTP_GetResponseHeaders(http_request_t *req, INT *len);
199 static DWORD HTTP_ProcessHeader(http_request_t *req, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
200 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
201 static DWORD HTTP_InsertCustomHeader(http_request_t *req, LPHTTPHEADERW lpHdr);
202 static INT HTTP_GetCustomHeaderIndex(http_request_t *req, LPCWSTR lpszField, INT index, BOOL Request);
203 static BOOL HTTP_DeleteCustomHeader(http_request_t *req, DWORD index);
204 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
205 static DWORD HTTP_HttpQueryInfoW(http_request_t*, DWORD, LPVOID, LPDWORD, LPDWORD);
206 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
207 static DWORD drain_content(http_request_t*,BOOL);
209 static CRITICAL_SECTION connection_pool_cs;
210 static CRITICAL_SECTION_DEBUG connection_pool_debug =
212 0, 0, &connection_pool_cs,
213 { &connection_pool_debug.ProcessLocksList, &connection_pool_debug.ProcessLocksList },
214 0, 0, { (DWORD_PTR)(__FILE__ ": connection_pool_cs") }
216 static CRITICAL_SECTION connection_pool_cs = { &connection_pool_debug, -1, 0, 0, 0, 0 };
218 static struct list connection_pool = LIST_INIT(connection_pool);
219 static BOOL collector_running;
221 void server_addref(server_t *server)
223 InterlockedIncrement(&server->ref);
226 void server_release(server_t *server)
228 if(InterlockedDecrement(&server->ref))
229 return;
231 list_remove(&server->entry);
233 if(server->cert_chain)
234 CertFreeCertificateChain(server->cert_chain);
235 heap_free(server->name);
236 heap_free(server->scheme_host_port);
237 heap_free(server);
240 static BOOL process_host_port(server_t *server)
242 BOOL default_port;
243 size_t name_len;
244 WCHAR *buf;
246 static const WCHAR httpW[] = {'h','t','t','p',0};
247 static const WCHAR httpsW[] = {'h','t','t','p','s',0};
248 static const WCHAR formatW[] = {'%','s',':','/','/','%','s',':','%','u',0};
250 name_len = strlenW(server->name);
251 buf = heap_alloc((name_len + 10 /* strlen("://:<port>") */)*sizeof(WCHAR) + sizeof(httpsW));
252 if(!buf)
253 return FALSE;
255 sprintfW(buf, formatW, server->is_https ? httpsW : httpW, server->name, server->port);
256 server->scheme_host_port = buf;
258 server->host_port = server->scheme_host_port + 7 /* strlen("http://") */;
259 if(server->is_https)
260 server->host_port++;
262 default_port = server->port == (server->is_https ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT);
263 server->canon_host_port = default_port ? server->name : server->host_port;
264 return TRUE;
267 server_t *get_server(substr_t name, INTERNET_PORT port, BOOL is_https, BOOL do_create)
269 server_t *iter, *server = NULL;
271 EnterCriticalSection(&connection_pool_cs);
273 LIST_FOR_EACH_ENTRY(iter, &connection_pool, server_t, entry) {
274 if(iter->port == port && name.len == strlenW(iter->name) && !strncmpiW(iter->name, name.str, name.len)
275 && iter->is_https == is_https) {
276 server = iter;
277 server_addref(server);
278 break;
282 if(!server && do_create) {
283 server = heap_alloc_zero(sizeof(*server));
284 if(server) {
285 server->ref = 2; /* list reference and return */
286 server->port = port;
287 server->is_https = is_https;
288 list_init(&server->conn_pool);
289 server->name = heap_strndupW(name.str, name.len);
290 if(server->name && process_host_port(server)) {
291 list_add_head(&connection_pool, &server->entry);
292 }else {
293 heap_free(server);
294 server = NULL;
299 LeaveCriticalSection(&connection_pool_cs);
301 return server;
304 BOOL collect_connections(collect_type_t collect_type)
306 netconn_t *netconn, *netconn_safe;
307 server_t *server, *server_safe;
308 BOOL remaining = FALSE;
309 DWORD64 now;
311 now = GetTickCount64();
313 LIST_FOR_EACH_ENTRY_SAFE(server, server_safe, &connection_pool, server_t, entry) {
314 LIST_FOR_EACH_ENTRY_SAFE(netconn, netconn_safe, &server->conn_pool, netconn_t, pool_entry) {
315 if(collect_type > COLLECT_TIMEOUT || netconn->keep_until < now) {
316 TRACE("freeing %p\n", netconn);
317 list_remove(&netconn->pool_entry);
318 free_netconn(netconn);
319 }else {
320 remaining = TRUE;
324 if(collect_type == COLLECT_CLEANUP) {
325 list_remove(&server->entry);
326 list_init(&server->entry);
327 server_release(server);
331 return remaining;
334 static DWORD WINAPI collect_connections_proc(void *arg)
336 BOOL remaining_conns;
338 do {
339 /* FIXME: Use more sophisticated method */
340 Sleep(5000);
342 EnterCriticalSection(&connection_pool_cs);
344 remaining_conns = collect_connections(COLLECT_TIMEOUT);
345 if(!remaining_conns)
346 collector_running = FALSE;
348 LeaveCriticalSection(&connection_pool_cs);
349 }while(remaining_conns);
351 FreeLibraryAndExitThread(WININET_hModule, 0);
354 /***********************************************************************
355 * HTTP_GetHeader (internal)
357 * Headers section must be held
359 static LPHTTPHEADERW HTTP_GetHeader(http_request_t *req, LPCWSTR head)
361 int HeaderIndex = 0;
362 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
363 if (HeaderIndex == -1)
364 return NULL;
365 else
366 return &req->custHeaders[HeaderIndex];
369 static WCHAR *get_host_header( http_request_t *req )
371 HTTPHEADERW *header;
372 WCHAR *ret = NULL;
374 EnterCriticalSection( &req->headers_section );
375 if ((header = HTTP_GetHeader( req, hostW ))) ret = heap_strdupW( header->lpszValue );
376 else ret = heap_strdupW( req->server->canon_host_port );
377 LeaveCriticalSection( &req->headers_section );
378 return ret;
381 struct data_stream_vtbl_t {
382 BOOL (*end_of_data)(data_stream_t*,http_request_t*);
383 DWORD (*read)(data_stream_t*,http_request_t*,BYTE*,DWORD,DWORD*,BOOL);
384 DWORD (*drain_content)(data_stream_t*,http_request_t*,BOOL);
385 void (*destroy)(data_stream_t*);
388 typedef struct {
389 data_stream_t data_stream;
391 BYTE buf[READ_BUFFER_SIZE];
392 DWORD buf_size;
393 DWORD buf_pos;
394 DWORD chunk_size;
396 enum {
397 CHUNKED_STREAM_STATE_READING_CHUNK_SIZE,
398 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE,
399 CHUNKED_STREAM_STATE_READING_CHUNK,
400 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA,
401 CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END,
402 CHUNKED_STREAM_STATE_END_OF_STREAM,
403 CHUNKED_STREAM_STATE_ERROR
404 } state;
405 } chunked_stream_t;
407 static inline void destroy_data_stream(data_stream_t *stream)
409 stream->vtbl->destroy(stream);
412 static void reset_data_stream(http_request_t *req)
414 destroy_data_stream(req->data_stream);
415 req->data_stream = &req->netconn_stream.data_stream;
416 req->read_pos = req->read_size = req->netconn_stream.content_read = 0;
417 req->read_gzip = FALSE;
420 static void remove_header( http_request_t *request, const WCHAR *str, BOOL from_request )
422 int index;
423 EnterCriticalSection( &request->headers_section );
424 index = HTTP_GetCustomHeaderIndex( request, str, 0, from_request );
425 if (index != -1) HTTP_DeleteCustomHeader( request, index );
426 LeaveCriticalSection( &request->headers_section );
429 #ifdef HAVE_ZLIB
431 typedef struct {
432 data_stream_t stream;
433 data_stream_t *parent_stream;
434 z_stream zstream;
435 BYTE buf[READ_BUFFER_SIZE];
436 DWORD buf_size;
437 DWORD buf_pos;
438 BOOL end_of_data;
439 } gzip_stream_t;
441 static BOOL gzip_end_of_data(data_stream_t *stream, http_request_t *req)
443 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
444 return gzip_stream->end_of_data
445 || (!gzip_stream->buf_size && gzip_stream->parent_stream->vtbl->end_of_data(gzip_stream->parent_stream, req));
448 static DWORD gzip_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
449 DWORD *read, BOOL allow_blocking)
451 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
452 z_stream *zstream = &gzip_stream->zstream;
453 DWORD current_read, ret_read = 0;
454 int zres;
455 DWORD res = ERROR_SUCCESS;
457 TRACE("(%d %x)\n", size, allow_blocking);
459 while(size && !gzip_stream->end_of_data) {
460 if(!gzip_stream->buf_size) {
461 if(gzip_stream->buf_pos) {
462 if(gzip_stream->buf_size)
463 memmove(gzip_stream->buf, gzip_stream->buf+gzip_stream->buf_pos, gzip_stream->buf_size);
464 gzip_stream->buf_pos = 0;
466 res = gzip_stream->parent_stream->vtbl->read(gzip_stream->parent_stream, req, gzip_stream->buf+gzip_stream->buf_size,
467 sizeof(gzip_stream->buf)-gzip_stream->buf_size, &current_read, allow_blocking);
468 if(res != ERROR_SUCCESS)
469 break;
471 gzip_stream->buf_size += current_read;
472 if(!current_read) {
473 WARN("unexpected end of data\n");
474 gzip_stream->end_of_data = TRUE;
475 break;
479 zstream->next_in = gzip_stream->buf+gzip_stream->buf_pos;
480 zstream->avail_in = gzip_stream->buf_size;
481 zstream->next_out = buf+ret_read;
482 zstream->avail_out = size;
483 zres = inflate(&gzip_stream->zstream, 0);
484 current_read = size - zstream->avail_out;
485 size -= current_read;
486 ret_read += current_read;
487 gzip_stream->buf_size -= zstream->next_in - (gzip_stream->buf+gzip_stream->buf_pos);
488 gzip_stream->buf_pos = zstream->next_in-gzip_stream->buf;
489 if(zres == Z_STREAM_END) {
490 TRACE("end of data\n");
491 gzip_stream->end_of_data = TRUE;
492 inflateEnd(zstream);
493 }else if(zres != Z_OK) {
494 WARN("inflate failed %d: %s\n", zres, debugstr_a(zstream->msg));
495 if(!ret_read)
496 res = ERROR_INTERNET_DECODING_FAILED;
497 break;
500 if(ret_read)
501 allow_blocking = FALSE;
504 TRACE("read %u bytes\n", ret_read);
505 if(ret_read)
506 res = ERROR_SUCCESS;
507 *read = ret_read;
508 return res;
511 static DWORD gzip_drain_content(data_stream_t *stream, http_request_t *req, BOOL allow_blocking)
513 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
514 return gzip_stream->parent_stream->vtbl->drain_content(gzip_stream->parent_stream, req, allow_blocking);
517 static void gzip_destroy(data_stream_t *stream)
519 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
521 destroy_data_stream(gzip_stream->parent_stream);
523 if(!gzip_stream->end_of_data)
524 inflateEnd(&gzip_stream->zstream);
525 heap_free(gzip_stream);
528 static const data_stream_vtbl_t gzip_stream_vtbl = {
529 gzip_end_of_data,
530 gzip_read,
531 gzip_drain_content,
532 gzip_destroy
535 static voidpf wininet_zalloc(voidpf opaque, uInt items, uInt size)
537 return heap_alloc(items*size);
540 static void wininet_zfree(voidpf opaque, voidpf address)
542 heap_free(address);
545 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
547 gzip_stream_t *gzip_stream;
548 int zres;
550 gzip_stream = heap_alloc_zero(sizeof(gzip_stream_t));
551 if(!gzip_stream)
552 return ERROR_OUTOFMEMORY;
554 gzip_stream->stream.vtbl = &gzip_stream_vtbl;
555 gzip_stream->zstream.zalloc = wininet_zalloc;
556 gzip_stream->zstream.zfree = wininet_zfree;
558 zres = inflateInit2(&gzip_stream->zstream, is_gzip ? 0x1f : -15);
559 if(zres != Z_OK) {
560 ERR("inflateInit failed: %d\n", zres);
561 heap_free(gzip_stream);
562 return ERROR_OUTOFMEMORY;
565 remove_header(req, szContent_Length, FALSE);
567 if(req->read_size) {
568 memcpy(gzip_stream->buf, req->read_buf+req->read_pos, req->read_size);
569 gzip_stream->buf_size = req->read_size;
570 req->read_pos = req->read_size = 0;
573 req->read_gzip = TRUE;
574 gzip_stream->parent_stream = req->data_stream;
575 req->data_stream = &gzip_stream->stream;
576 return ERROR_SUCCESS;
579 #else
581 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
583 ERR("gzip stream not supported, missing zlib.\n");
584 return ERROR_SUCCESS;
587 #endif
589 /***********************************************************************
590 * HTTP_FreeTokens (internal)
592 * Frees table of pointers.
594 static void HTTP_FreeTokens(LPWSTR * token_array)
596 int i;
597 for (i = 0; token_array[i]; i++) heap_free(token_array[i]);
598 heap_free(token_array);
601 static void HTTP_FixURL(http_request_t *request)
603 static const WCHAR szSlash[] = { '/',0 };
604 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/', 0 };
606 /* If we don't have a path we set it to root */
607 if (NULL == request->path)
608 request->path = heap_strdupW(szSlash);
609 else /* remove \r and \n*/
611 int nLen = strlenW(request->path);
612 while ((nLen >0 ) && ((request->path[nLen-1] == '\r')||(request->path[nLen-1] == '\n')))
614 nLen--;
615 request->path[nLen]='\0';
617 /* Replace '\' with '/' */
618 while (nLen>0) {
619 nLen--;
620 if (request->path[nLen] == '\\') request->path[nLen]='/';
624 if(CSTR_EQUAL != CompareStringW( LOCALE_INVARIANT, NORM_IGNORECASE,
625 request->path, strlenW(request->path), szHttp, strlenW(szHttp) )
626 && request->path[0] != '/') /* not an absolute path ?? --> fix it !! */
628 WCHAR *fixurl = heap_alloc((strlenW(request->path) + 2)*sizeof(WCHAR));
629 *fixurl = '/';
630 strcpyW(fixurl + 1, request->path);
631 heap_free( request->path );
632 request->path = fixurl;
636 static WCHAR* build_request_header(http_request_t *request, const WCHAR *verb,
637 const WCHAR *path, const WCHAR *version, BOOL use_cr)
639 static const WCHAR szSpace[] = {' ',0};
640 static const WCHAR szColon[] = {':',' ',0};
641 static const WCHAR szCr[] = {'\r',0};
642 static const WCHAR szLf[] = {'\n',0};
643 LPWSTR requestString;
644 DWORD len, n;
645 LPCWSTR *req;
646 UINT i;
648 EnterCriticalSection( &request->headers_section );
650 /* allocate space for an array of all the string pointers to be added */
651 len = request->nCustHeaders * 5 + 10;
652 if (!(req = heap_alloc( len * sizeof(const WCHAR *) )))
654 LeaveCriticalSection( &request->headers_section );
655 return NULL;
658 /* add the verb, path and HTTP version string */
659 n = 0;
660 req[n++] = verb;
661 req[n++] = szSpace;
662 req[n++] = path;
663 req[n++] = szSpace;
664 req[n++] = version;
665 if (use_cr)
666 req[n++] = szCr;
667 req[n++] = szLf;
669 /* Append custom request headers */
670 for (i = 0; i < request->nCustHeaders; i++)
672 if (request->custHeaders[i].wFlags & HDR_ISREQUEST)
674 req[n++] = request->custHeaders[i].lpszField;
675 req[n++] = szColon;
676 req[n++] = request->custHeaders[i].lpszValue;
677 if (use_cr)
678 req[n++] = szCr;
679 req[n++] = szLf;
681 TRACE("Adding custom header %s (%s)\n",
682 debugstr_w(request->custHeaders[i].lpszField),
683 debugstr_w(request->custHeaders[i].lpszValue));
686 if (use_cr)
687 req[n++] = szCr;
688 req[n++] = szLf;
689 req[n] = NULL;
691 requestString = HTTP_build_req( req, 4 );
692 heap_free( req );
693 LeaveCriticalSection( &request->headers_section );
694 return requestString;
697 static WCHAR* build_response_header(http_request_t *request, BOOL use_cr)
699 static const WCHAR colonW[] = { ':',' ',0 };
700 static const WCHAR crW[] = { '\r',0 };
701 static const WCHAR lfW[] = { '\n',0 };
702 static const WCHAR status_fmt[] = { ' ','%','u',' ',0 };
703 const WCHAR **req;
704 WCHAR *ret, buf[14];
705 DWORD i, n = 0;
707 EnterCriticalSection( &request->headers_section );
709 if (!(req = heap_alloc( (request->nCustHeaders * 5 + 8) * sizeof(WCHAR *) )))
711 LeaveCriticalSection( &request->headers_section );
712 return NULL;
715 if (request->status_code)
717 req[n++] = request->version;
718 sprintfW(buf, status_fmt, request->status_code);
719 req[n++] = buf;
720 req[n++] = request->statusText;
721 if (use_cr)
722 req[n++] = crW;
723 req[n++] = lfW;
726 for(i = 0; i < request->nCustHeaders; i++)
728 if(!(request->custHeaders[i].wFlags & HDR_ISREQUEST)
729 && strcmpW(request->custHeaders[i].lpszField, szStatus))
731 req[n++] = request->custHeaders[i].lpszField;
732 req[n++] = colonW;
733 req[n++] = request->custHeaders[i].lpszValue;
734 if(use_cr)
735 req[n++] = crW;
736 req[n++] = lfW;
738 TRACE("Adding custom header %s (%s)\n",
739 debugstr_w(request->custHeaders[i].lpszField),
740 debugstr_w(request->custHeaders[i].lpszValue));
743 if(use_cr)
744 req[n++] = crW;
745 req[n++] = lfW;
746 req[n] = NULL;
748 ret = HTTP_build_req(req, 0);
749 heap_free(req);
750 LeaveCriticalSection( &request->headers_section );
751 return ret;
754 static void HTTP_ProcessCookies( http_request_t *request )
756 int HeaderIndex;
757 int numCookies = 0;
758 LPHTTPHEADERW setCookieHeader;
760 if(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES)
761 return;
763 EnterCriticalSection( &request->headers_section );
765 while((HeaderIndex = HTTP_GetCustomHeaderIndex(request, szSet_Cookie, numCookies++, FALSE)) != -1)
767 const WCHAR *data;
768 substr_t name;
770 setCookieHeader = &request->custHeaders[HeaderIndex];
772 if (!setCookieHeader->lpszValue)
773 continue;
775 data = strchrW(setCookieHeader->lpszValue, '=');
776 if(!data)
777 continue;
779 name = substr(setCookieHeader->lpszValue, data - setCookieHeader->lpszValue);
780 data++;
781 set_cookie(substrz(request->server->name), substrz(request->path), name, substrz(data), INTERNET_COOKIE_HTTPONLY);
784 LeaveCriticalSection( &request->headers_section );
787 static void strip_spaces(LPWSTR start)
789 LPWSTR str = start;
790 LPWSTR end;
792 while (*str == ' ')
793 str++;
795 if (str != start)
796 memmove(start, str, sizeof(WCHAR) * (strlenW(str) + 1));
798 end = start + strlenW(start) - 1;
799 while (end >= start && *end == ' ')
801 *end = '\0';
802 end--;
806 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue, LPWSTR *pszRealm )
808 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
809 static const WCHAR szRealm[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
810 BOOL is_basic;
811 is_basic = !strncmpiW(pszAuthValue, szBasic, ARRAY_SIZE(szBasic)) &&
812 ((pszAuthValue[ARRAY_SIZE(szBasic)] == ' ') || !pszAuthValue[ARRAY_SIZE(szBasic)]);
813 if (is_basic && pszRealm)
815 LPCWSTR token;
816 LPCWSTR ptr = &pszAuthValue[ARRAY_SIZE(szBasic)];
817 LPCWSTR realm;
818 ptr++;
819 *pszRealm=NULL;
820 token = strchrW(ptr,'=');
821 if (!token)
822 return TRUE;
823 realm = ptr;
824 while (*realm == ' ')
825 realm++;
826 if(!strncmpiW(realm, szRealm, ARRAY_SIZE(szRealm)) &&
827 (realm[ARRAY_SIZE(szRealm)] == ' ' || realm[ARRAY_SIZE(szRealm)] == '='))
829 token++;
830 while (*token == ' ')
831 token++;
832 if (*token == '\0')
833 return TRUE;
834 *pszRealm = heap_strdupW(token);
835 strip_spaces(*pszRealm);
839 return is_basic;
842 static void destroy_authinfo( struct HttpAuthInfo *authinfo )
844 if (!authinfo) return;
846 if (SecIsValidHandle(&authinfo->ctx))
847 DeleteSecurityContext(&authinfo->ctx);
848 if (SecIsValidHandle(&authinfo->cred))
849 FreeCredentialsHandle(&authinfo->cred);
851 heap_free(authinfo->auth_data);
852 heap_free(authinfo->scheme);
853 heap_free(authinfo);
856 static UINT retrieve_cached_basic_authorization(const WCHAR *host, const WCHAR *realm, char **auth_data)
858 basicAuthorizationData *ad;
859 UINT rc = 0;
861 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host),debugstr_w(realm));
863 EnterCriticalSection(&authcache_cs);
864 LIST_FOR_EACH_ENTRY(ad, &basicAuthorizationCache, basicAuthorizationData, entry)
866 if (!strcmpiW(host, ad->host) && (!realm || !strcmpW(realm, ad->realm)))
868 TRACE("Authorization found in cache\n");
869 *auth_data = heap_alloc(ad->authorizationLen);
870 memcpy(*auth_data,ad->authorization,ad->authorizationLen);
871 rc = ad->authorizationLen;
872 break;
875 LeaveCriticalSection(&authcache_cs);
876 return rc;
879 static void cache_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR auth_data, UINT auth_data_len)
881 struct list *cursor;
882 basicAuthorizationData* ad = NULL;
884 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host),debugstr_w(realm),debugstr_an(auth_data,auth_data_len));
886 EnterCriticalSection(&authcache_cs);
887 LIST_FOR_EACH(cursor, &basicAuthorizationCache)
889 basicAuthorizationData *check = LIST_ENTRY(cursor,basicAuthorizationData,entry);
890 if (!strcmpiW(host,check->host) && !strcmpW(realm,check->realm))
892 ad = check;
893 break;
897 if (ad)
899 TRACE("Found match in cache, replacing\n");
900 heap_free(ad->authorization);
901 ad->authorization = heap_alloc(auth_data_len);
902 memcpy(ad->authorization, auth_data, auth_data_len);
903 ad->authorizationLen = auth_data_len;
905 else
907 ad = heap_alloc(sizeof(basicAuthorizationData));
908 ad->host = heap_strdupW(host);
909 ad->realm = heap_strdupW(realm);
910 ad->authorization = heap_alloc(auth_data_len);
911 memcpy(ad->authorization, auth_data, auth_data_len);
912 ad->authorizationLen = auth_data_len;
913 list_add_head(&basicAuthorizationCache,&ad->entry);
914 TRACE("authorization cached\n");
916 LeaveCriticalSection(&authcache_cs);
919 static BOOL retrieve_cached_authorization(LPWSTR host, LPWSTR scheme,
920 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
922 authorizationData *ad;
924 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
926 EnterCriticalSection(&authcache_cs);
927 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry) {
928 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
929 TRACE("Authorization found in cache\n");
931 nt_auth_identity->User = heap_strdupW(ad->user);
932 nt_auth_identity->Password = heap_strdupW(ad->password);
933 nt_auth_identity->Domain = heap_alloc(sizeof(WCHAR)*ad->domain_len);
934 if(!nt_auth_identity->User || !nt_auth_identity->Password ||
935 (!nt_auth_identity->Domain && ad->domain_len)) {
936 heap_free(nt_auth_identity->User);
937 heap_free(nt_auth_identity->Password);
938 heap_free(nt_auth_identity->Domain);
939 break;
942 nt_auth_identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
943 nt_auth_identity->UserLength = ad->user_len;
944 nt_auth_identity->PasswordLength = ad->password_len;
945 memcpy(nt_auth_identity->Domain, ad->domain, sizeof(WCHAR)*ad->domain_len);
946 nt_auth_identity->DomainLength = ad->domain_len;
947 LeaveCriticalSection(&authcache_cs);
948 return TRUE;
951 LeaveCriticalSection(&authcache_cs);
953 return FALSE;
956 static void cache_authorization(LPWSTR host, LPWSTR scheme,
957 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
959 authorizationData *ad;
960 BOOL found = FALSE;
962 TRACE("Caching authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
964 EnterCriticalSection(&authcache_cs);
965 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry)
966 if(!strcmpiW(host, ad->host) && !strcmpiW(scheme, ad->scheme)) {
967 found = TRUE;
968 break;
971 if(found) {
972 heap_free(ad->user);
973 heap_free(ad->password);
974 heap_free(ad->domain);
975 } else {
976 ad = heap_alloc(sizeof(authorizationData));
977 if(!ad) {
978 LeaveCriticalSection(&authcache_cs);
979 return;
982 ad->host = heap_strdupW(host);
983 ad->scheme = heap_strdupW(scheme);
984 list_add_head(&authorizationCache, &ad->entry);
987 ad->user = heap_strndupW(nt_auth_identity->User, nt_auth_identity->UserLength);
988 ad->password = heap_strndupW(nt_auth_identity->Password, nt_auth_identity->PasswordLength);
989 ad->domain = heap_strndupW(nt_auth_identity->Domain, nt_auth_identity->DomainLength);
990 ad->user_len = nt_auth_identity->UserLength;
991 ad->password_len = nt_auth_identity->PasswordLength;
992 ad->domain_len = nt_auth_identity->DomainLength;
994 if(!ad->host || !ad->scheme || !ad->user || !ad->password
995 || (nt_auth_identity->Domain && !ad->domain)) {
996 heap_free(ad->host);
997 heap_free(ad->scheme);
998 heap_free(ad->user);
999 heap_free(ad->password);
1000 heap_free(ad->domain);
1001 list_remove(&ad->entry);
1002 heap_free(ad);
1005 LeaveCriticalSection(&authcache_cs);
1008 static BOOL HTTP_DoAuthorization( http_request_t *request, LPCWSTR pszAuthValue,
1009 struct HttpAuthInfo **ppAuthInfo,
1010 LPWSTR domain_and_username, LPWSTR password,
1011 LPWSTR host )
1013 SECURITY_STATUS sec_status;
1014 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
1015 BOOL first = FALSE;
1016 LPWSTR szRealm = NULL;
1018 TRACE("%s\n", debugstr_w(pszAuthValue));
1020 if (!pAuthInfo)
1022 TimeStamp exp;
1024 first = TRUE;
1025 pAuthInfo = heap_alloc(sizeof(*pAuthInfo));
1026 if (!pAuthInfo)
1027 return FALSE;
1029 SecInvalidateHandle(&pAuthInfo->cred);
1030 SecInvalidateHandle(&pAuthInfo->ctx);
1031 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
1032 pAuthInfo->attr = 0;
1033 pAuthInfo->auth_data = NULL;
1034 pAuthInfo->auth_data_len = 0;
1035 pAuthInfo->finished = FALSE;
1037 if (is_basic_auth_value(pszAuthValue,NULL))
1039 static const WCHAR szBasic[] = {'B','a','s','i','c',0};
1040 pAuthInfo->scheme = heap_strdupW(szBasic);
1041 if (!pAuthInfo->scheme)
1043 heap_free(pAuthInfo);
1044 return FALSE;
1047 else
1049 PVOID pAuthData;
1050 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
1052 pAuthInfo->scheme = heap_strdupW(pszAuthValue);
1053 if (!pAuthInfo->scheme)
1055 heap_free(pAuthInfo);
1056 return FALSE;
1059 if (domain_and_username)
1061 WCHAR *user = strchrW(domain_and_username, '\\');
1062 WCHAR *domain = domain_and_username;
1064 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1066 pAuthData = &nt_auth_identity;
1068 if (user) user++;
1069 else
1071 user = domain_and_username;
1072 domain = NULL;
1075 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1076 nt_auth_identity.User = user;
1077 nt_auth_identity.UserLength = strlenW(nt_auth_identity.User);
1078 nt_auth_identity.Domain = domain;
1079 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
1080 nt_auth_identity.Password = password;
1081 nt_auth_identity.PasswordLength = strlenW(nt_auth_identity.Password);
1083 cache_authorization(host, pAuthInfo->scheme, &nt_auth_identity);
1085 else if(retrieve_cached_authorization(host, pAuthInfo->scheme, &nt_auth_identity))
1086 pAuthData = &nt_auth_identity;
1087 else
1088 /* use default credentials */
1089 pAuthData = NULL;
1091 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
1092 SECPKG_CRED_OUTBOUND, NULL,
1093 pAuthData, NULL,
1094 NULL, &pAuthInfo->cred,
1095 &exp);
1097 if(pAuthData && !domain_and_username) {
1098 heap_free(nt_auth_identity.User);
1099 heap_free(nt_auth_identity.Domain);
1100 heap_free(nt_auth_identity.Password);
1103 if (sec_status == SEC_E_OK)
1105 PSecPkgInfoW sec_pkg_info;
1106 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
1107 if (sec_status == SEC_E_OK)
1109 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
1110 FreeContextBuffer(sec_pkg_info);
1113 if (sec_status != SEC_E_OK)
1115 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08x\n",
1116 debugstr_w(pAuthInfo->scheme), sec_status);
1117 heap_free(pAuthInfo->scheme);
1118 heap_free(pAuthInfo);
1119 return FALSE;
1122 *ppAuthInfo = pAuthInfo;
1124 else if (pAuthInfo->finished)
1125 return FALSE;
1127 if ((strlenW(pszAuthValue) < strlenW(pAuthInfo->scheme)) ||
1128 strncmpiW(pszAuthValue, pAuthInfo->scheme, strlenW(pAuthInfo->scheme)))
1130 ERR("authentication scheme changed from %s to %s\n",
1131 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
1132 return FALSE;
1135 if (is_basic_auth_value(pszAuthValue,&szRealm))
1137 int userlen;
1138 int passlen;
1139 char *auth_data = NULL;
1140 UINT auth_data_len = 0;
1142 TRACE("basic authentication realm %s\n",debugstr_w(szRealm));
1144 if (!domain_and_username)
1146 if (host && szRealm)
1147 auth_data_len = retrieve_cached_basic_authorization(host, szRealm,&auth_data);
1148 if (auth_data_len == 0)
1150 heap_free(szRealm);
1151 return FALSE;
1154 else
1156 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
1157 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
1159 /* length includes a nul terminator, which will be re-used for the ':' */
1160 auth_data = heap_alloc(userlen + 1 + passlen);
1161 if (!auth_data)
1163 heap_free(szRealm);
1164 return FALSE;
1167 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
1168 auth_data[userlen] = ':';
1169 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
1170 auth_data_len = userlen + 1 + passlen;
1171 if (host && szRealm)
1172 cache_basic_authorization(host, szRealm, auth_data, auth_data_len);
1175 pAuthInfo->auth_data = auth_data;
1176 pAuthInfo->auth_data_len = auth_data_len;
1177 pAuthInfo->finished = TRUE;
1178 heap_free(szRealm);
1179 return TRUE;
1181 else
1183 LPCWSTR pszAuthData;
1184 SecBufferDesc out_desc, in_desc;
1185 SecBuffer out, in;
1186 unsigned char *buffer;
1187 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
1188 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
1190 in.BufferType = SECBUFFER_TOKEN;
1191 in.cbBuffer = 0;
1192 in.pvBuffer = NULL;
1194 in_desc.ulVersion = 0;
1195 in_desc.cBuffers = 1;
1196 in_desc.pBuffers = &in;
1198 pszAuthData = pszAuthValue + strlenW(pAuthInfo->scheme);
1199 if (*pszAuthData == ' ')
1201 pszAuthData++;
1202 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
1203 in.pvBuffer = heap_alloc(in.cbBuffer);
1204 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
1207 buffer = heap_alloc(pAuthInfo->max_token);
1209 out.BufferType = SECBUFFER_TOKEN;
1210 out.cbBuffer = pAuthInfo->max_token;
1211 out.pvBuffer = buffer;
1213 out_desc.ulVersion = 0;
1214 out_desc.cBuffers = 1;
1215 out_desc.pBuffers = &out;
1217 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
1218 first ? NULL : &pAuthInfo->ctx,
1219 first ? request->server->name : NULL,
1220 context_req, 0, SECURITY_NETWORK_DREP,
1221 in.pvBuffer ? &in_desc : NULL,
1222 0, &pAuthInfo->ctx, &out_desc,
1223 &pAuthInfo->attr, &pAuthInfo->exp);
1224 if (sec_status == SEC_E_OK)
1226 pAuthInfo->finished = TRUE;
1227 pAuthInfo->auth_data = out.pvBuffer;
1228 pAuthInfo->auth_data_len = out.cbBuffer;
1229 TRACE("sending last auth packet\n");
1231 else if (sec_status == SEC_I_CONTINUE_NEEDED)
1233 pAuthInfo->auth_data = out.pvBuffer;
1234 pAuthInfo->auth_data_len = out.cbBuffer;
1235 TRACE("sending next auth packet\n");
1237 else
1239 ERR("InitializeSecurityContextW returned error 0x%08x\n", sec_status);
1240 heap_free(out.pvBuffer);
1241 destroy_authinfo(pAuthInfo);
1242 *ppAuthInfo = NULL;
1243 return FALSE;
1247 return TRUE;
1250 /***********************************************************************
1251 * HTTP_HttpAddRequestHeadersW (internal)
1253 static DWORD HTTP_HttpAddRequestHeadersW(http_request_t *request,
1254 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1256 LPWSTR lpszStart;
1257 LPWSTR lpszEnd;
1258 LPWSTR buffer;
1259 DWORD len, res = ERROR_HTTP_INVALID_HEADER;
1261 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
1263 if( dwHeaderLength == ~0U )
1264 len = strlenW(lpszHeader);
1265 else
1266 len = dwHeaderLength;
1267 buffer = heap_alloc(sizeof(WCHAR)*(len+1));
1268 lstrcpynW( buffer, lpszHeader, len + 1);
1270 lpszStart = buffer;
1274 LPWSTR * pFieldAndValue;
1276 lpszEnd = lpszStart;
1278 while (*lpszEnd != '\0')
1280 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1281 break;
1282 lpszEnd++;
1285 if (*lpszStart == '\0')
1286 break;
1288 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1290 *lpszEnd = '\0';
1291 lpszEnd++; /* Jump over newline */
1293 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
1294 if (*lpszStart == '\0')
1296 /* Skip 0-length headers */
1297 lpszStart = lpszEnd;
1298 res = ERROR_SUCCESS;
1299 continue;
1301 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
1302 if (pFieldAndValue)
1304 res = HTTP_ProcessHeader(request, pFieldAndValue[0],
1305 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
1306 HTTP_FreeTokens(pFieldAndValue);
1309 lpszStart = lpszEnd;
1310 } while (res == ERROR_SUCCESS);
1312 heap_free(buffer);
1313 return res;
1316 /***********************************************************************
1317 * HttpAddRequestHeadersW (WININET.@)
1319 * Adds one or more HTTP header to the request handler
1321 * NOTE
1322 * On Windows if dwHeaderLength includes the trailing '\0', then
1323 * HttpAddRequestHeadersW() adds it too. However this results in an
1324 * invalid HTTP header which is rejected by some servers so we probably
1325 * don't need to match Windows on that point.
1327 * RETURNS
1328 * TRUE on success
1329 * FALSE on failure
1332 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
1333 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1335 http_request_t *request;
1336 DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
1338 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1340 if (!lpszHeader)
1341 return TRUE;
1343 request = (http_request_t*) get_handle_object( hHttpRequest );
1344 if (request && request->hdr.htype == WH_HHTTPREQ)
1345 res = HTTP_HttpAddRequestHeadersW( request, lpszHeader, dwHeaderLength, dwModifier );
1346 if( request )
1347 WININET_Release( &request->hdr );
1349 if(res != ERROR_SUCCESS)
1350 SetLastError(res);
1351 return res == ERROR_SUCCESS;
1354 /***********************************************************************
1355 * HttpAddRequestHeadersA (WININET.@)
1357 * Adds one or more HTTP header to the request handler
1359 * RETURNS
1360 * TRUE on success
1361 * FALSE on failure
1364 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
1365 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1367 WCHAR *headers = NULL;
1368 BOOL r;
1370 TRACE("%p, %s, %i, %i\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1372 if(lpszHeader)
1373 headers = heap_strndupAtoW(lpszHeader, dwHeaderLength, &dwHeaderLength);
1375 r = HttpAddRequestHeadersW(hHttpRequest, headers, dwHeaderLength, dwModifier);
1377 heap_free(headers);
1378 return r;
1381 static void free_accept_types( WCHAR **accept_types )
1383 WCHAR *ptr, **types = accept_types;
1385 if (!types) return;
1386 while ((ptr = *types))
1388 heap_free( ptr );
1389 types++;
1391 heap_free( accept_types );
1394 static WCHAR **convert_accept_types( const char **accept_types )
1396 unsigned int count;
1397 const char **types = accept_types;
1398 WCHAR **typesW;
1399 BOOL invalid_pointer = FALSE;
1401 if (!types) return NULL;
1402 count = 0;
1403 while (*types)
1405 __TRY
1407 /* find out how many there are */
1408 if (*types && **types)
1410 TRACE("accept type: %s\n", debugstr_a(*types));
1411 count++;
1414 __EXCEPT_PAGE_FAULT
1416 WARN("invalid accept type pointer\n");
1417 invalid_pointer = TRUE;
1419 __ENDTRY;
1420 types++;
1422 if (invalid_pointer) return NULL;
1423 if (!(typesW = heap_alloc( sizeof(WCHAR *) * (count + 1) ))) return NULL;
1424 count = 0;
1425 types = accept_types;
1426 while (*types)
1428 if (*types && **types) typesW[count++] = heap_strdupAtoW( *types );
1429 types++;
1431 typesW[count] = NULL;
1432 return typesW;
1435 /***********************************************************************
1436 * HttpOpenRequestA (WININET.@)
1438 * Open a HTTP request handle
1440 * RETURNS
1441 * HINTERNET a HTTP request handle on success
1442 * NULL on failure
1445 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
1446 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
1447 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
1448 DWORD dwFlags, DWORD_PTR dwContext)
1450 LPWSTR szVerb = NULL, szObjectName = NULL;
1451 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
1452 HINTERNET rc = NULL;
1454 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
1455 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
1456 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
1457 dwFlags, dwContext);
1459 if (lpszVerb)
1461 szVerb = heap_strdupAtoW(lpszVerb);
1462 if ( !szVerb )
1463 goto end;
1466 if (lpszObjectName)
1468 szObjectName = heap_strdupAtoW(lpszObjectName);
1469 if ( !szObjectName )
1470 goto end;
1473 if (lpszVersion)
1475 szVersion = heap_strdupAtoW(lpszVersion);
1476 if ( !szVersion )
1477 goto end;
1480 if (lpszReferrer)
1482 szReferrer = heap_strdupAtoW(lpszReferrer);
1483 if ( !szReferrer )
1484 goto end;
1487 szAcceptTypes = convert_accept_types( lpszAcceptTypes );
1488 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName, szVersion, szReferrer,
1489 (const WCHAR **)szAcceptTypes, dwFlags, dwContext);
1491 end:
1492 free_accept_types(szAcceptTypes);
1493 heap_free(szReferrer);
1494 heap_free(szVersion);
1495 heap_free(szObjectName);
1496 heap_free(szVerb);
1497 return rc;
1500 /***********************************************************************
1501 * HTTP_EncodeBase64
1503 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1505 UINT n = 0, x;
1506 static const CHAR HTTP_Base64Enc[] =
1507 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1509 while( len > 0 )
1511 /* first 6 bits, all from bin[0] */
1512 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1513 x = (bin[0] & 3) << 4;
1515 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1516 if( len == 1 )
1518 base64[n++] = HTTP_Base64Enc[x];
1519 base64[n++] = '=';
1520 base64[n++] = '=';
1521 break;
1523 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1524 x = ( bin[1] & 0x0f ) << 2;
1526 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1527 if( len == 2 )
1529 base64[n++] = HTTP_Base64Enc[x];
1530 base64[n++] = '=';
1531 break;
1533 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1535 /* last 6 bits, all from bin [2] */
1536 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1537 bin += 3;
1538 len -= 3;
1540 base64[n] = 0;
1541 return n;
1544 static const signed char HTTP_Base64Dec[] =
1546 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x00 */
1547 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x10 */
1548 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 0x20 */
1549 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, /* 0x30 */
1550 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 0x40 */
1551 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 0x50 */
1552 -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 0x60 */
1553 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 /* 0x70 */
1556 /***********************************************************************
1557 * HTTP_DecodeBase64
1559 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1561 unsigned int n = 0;
1563 while(*base64)
1565 signed char in[4];
1567 if (base64[0] >= ARRAY_SIZE(HTTP_Base64Dec) ||
1568 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1569 base64[1] >= ARRAY_SIZE(HTTP_Base64Dec) ||
1570 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1572 WARN("invalid base64: %s\n", debugstr_w(base64));
1573 return 0;
1575 if (bin)
1576 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1577 n++;
1579 if ((base64[2] == '=') && (base64[3] == '='))
1580 break;
1581 if (base64[2] > ARRAY_SIZE(HTTP_Base64Dec) ||
1582 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1584 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1585 return 0;
1587 if (bin)
1588 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1589 n++;
1591 if (base64[3] == '=')
1592 break;
1593 if (base64[3] > ARRAY_SIZE(HTTP_Base64Dec) ||
1594 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1596 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1597 return 0;
1599 if (bin)
1600 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1601 n++;
1603 base64 += 4;
1606 return n;
1609 static WCHAR *encode_auth_data( const WCHAR *scheme, const char *data, UINT data_len )
1611 WCHAR *ret;
1612 UINT len, scheme_len = strlenW( scheme );
1614 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1615 len = scheme_len + 1 + ((data_len + 2) * 4) / 3;
1616 if (!(ret = heap_alloc( (len + 1) * sizeof(WCHAR) ))) return NULL;
1617 memcpy( ret, scheme, scheme_len * sizeof(WCHAR) );
1618 ret[scheme_len] = ' ';
1619 HTTP_EncodeBase64( data, data_len, ret + scheme_len + 1 );
1620 return ret;
1624 /***********************************************************************
1625 * HTTP_InsertAuthorization
1627 * Insert or delete the authorization field in the request header.
1629 static BOOL HTTP_InsertAuthorization( http_request_t *request, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1631 static const WCHAR wszBasic[] = {'B','a','s','i','c',0};
1632 WCHAR *host, *authorization = NULL;
1634 if (pAuthInfo)
1636 if (pAuthInfo->auth_data_len)
1638 if (!(authorization = encode_auth_data(pAuthInfo->scheme, pAuthInfo->auth_data, pAuthInfo->auth_data_len)))
1639 return FALSE;
1641 /* clear the data as it isn't valid now that it has been sent to the
1642 * server, unless it's Basic authentication which doesn't do
1643 * connection tracking */
1644 if (strcmpiW(pAuthInfo->scheme, wszBasic))
1646 heap_free(pAuthInfo->auth_data);
1647 pAuthInfo->auth_data = NULL;
1648 pAuthInfo->auth_data_len = 0;
1652 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1654 HTTP_ProcessHeader(request, header, authorization,
1655 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
1656 heap_free(authorization);
1658 else if (!strcmpW(header, szAuthorization) && (host = get_host_header(request)))
1660 UINT data_len;
1661 char *data;
1663 if ((data_len = retrieve_cached_basic_authorization(host, NULL, &data)))
1665 TRACE("Found cached basic authorization for %s\n", debugstr_w(host));
1667 if (!(authorization = encode_auth_data(wszBasic, data, data_len)))
1669 heap_free(data);
1670 heap_free(host);
1671 return FALSE;
1674 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1676 HTTP_ProcessHeader(request, header, authorization,
1677 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD);
1678 heap_free(data);
1679 heap_free(authorization);
1681 heap_free(host);
1683 return TRUE;
1686 static WCHAR *build_proxy_path_url(http_request_t *req)
1688 DWORD size, len;
1689 WCHAR *url;
1691 len = strlenW(req->server->scheme_host_port);
1692 size = len + strlenW(req->path) + 1;
1693 if(*req->path != '/')
1694 size++;
1695 url = heap_alloc(size * sizeof(WCHAR));
1696 if(!url)
1697 return NULL;
1699 memcpy(url, req->server->scheme_host_port, len*sizeof(WCHAR));
1700 if(*req->path != '/')
1701 url[len++] = '/';
1703 strcpyW(url+len, req->path);
1705 TRACE("url=%s\n", debugstr_w(url));
1706 return url;
1709 static BOOL HTTP_DomainMatches(LPCWSTR server, substr_t domain)
1711 static const WCHAR localW[] = { '<','l','o','c','a','l','>',0 };
1712 const WCHAR *dot, *ptr;
1713 int len;
1715 if(domain.len == ARRAY_SIZE(localW)-1 && !strncmpiW(domain.str, localW, domain.len) && !strchrW(server, '.' ))
1716 return TRUE;
1718 if(domain.len && *domain.str != '*')
1719 return domain.len == strlenW(server) && !strncmpiW(server, domain.str, domain.len);
1721 if(domain.len < 2 || domain.str[1] != '.')
1722 return FALSE;
1724 /* For a hostname to match a wildcard, the last domain must match
1725 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1726 * hostname is www.foo.a.b, it matches, but a.b does not.
1728 dot = strchrW(server, '.');
1729 if(!dot)
1730 return FALSE;
1732 len = strlenW(dot + 1);
1733 if(len < domain.len - 2)
1734 return FALSE;
1736 /* The server's domain is longer than the wildcard, so it
1737 * could be a subdomain. Compare the last portion of the
1738 * server's domain.
1740 ptr = dot + 1 + len - domain.len + 2;
1741 if(!strncmpiW(ptr, domain.str+2, domain.len-2))
1742 /* This is only a match if the preceding character is
1743 * a '.', i.e. that it is a matching domain. E.g.
1744 * if domain is '*.b.c' and server is 'www.ab.c' they
1745 * do not match.
1747 return *(ptr - 1) == '.';
1749 return len == domain.len-2 && !strncmpiW(dot + 1, domain.str + 2, len);
1752 static BOOL HTTP_ShouldBypassProxy(appinfo_t *lpwai, LPCWSTR server)
1754 LPCWSTR ptr;
1755 BOOL ret = FALSE;
1757 if (!lpwai->proxyBypass) return FALSE;
1758 ptr = lpwai->proxyBypass;
1759 while(1) {
1760 LPCWSTR tmp = ptr;
1762 ptr = strchrW( ptr, ';' );
1763 if (!ptr)
1764 ptr = strchrW( tmp, ' ' );
1765 if (!ptr)
1766 ptr = tmp + strlenW(tmp);
1767 ret = HTTP_DomainMatches( server, substr(tmp, ptr-tmp) );
1768 if (ret || !*ptr)
1769 break;
1770 ptr++;
1772 return ret;
1775 /***********************************************************************
1776 * HTTP_DealWithProxy
1778 static BOOL HTTP_DealWithProxy(appinfo_t *hIC, http_session_t *session, http_request_t *request)
1780 static const WCHAR protoHttp[] = { 'h','t','t','p',0 };
1781 static const WCHAR szHttp[] = { 'h','t','t','p',':','/','/',0 };
1782 static WCHAR szNul[] = { 0 };
1783 URL_COMPONENTSW UrlComponents = { sizeof(UrlComponents) };
1784 server_t *new_server = NULL;
1785 WCHAR *proxy;
1787 proxy = INTERNET_FindProxyForProtocol(hIC->proxy, protoHttp);
1788 if(!proxy)
1789 return FALSE;
1790 if(CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1791 proxy, strlenW(szHttp), szHttp, strlenW(szHttp))) {
1792 WCHAR *proxy_url = heap_alloc(strlenW(proxy)*sizeof(WCHAR) + sizeof(szHttp));
1793 if(!proxy_url) {
1794 heap_free(proxy);
1795 return FALSE;
1797 strcpyW(proxy_url, szHttp);
1798 strcatW(proxy_url, proxy);
1799 heap_free(proxy);
1800 proxy = proxy_url;
1803 UrlComponents.dwHostNameLength = 1;
1804 if(InternetCrackUrlW(proxy, 0, 0, &UrlComponents) && UrlComponents.dwHostNameLength) {
1805 if( !request->path )
1806 request->path = szNul;
1808 new_server = get_server(substr(UrlComponents.lpszHostName, UrlComponents.dwHostNameLength),
1809 UrlComponents.nPort, UrlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
1811 heap_free(proxy);
1812 if(!new_server)
1813 return FALSE;
1815 request->proxy = new_server;
1817 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server->name), new_server->port);
1818 return TRUE;
1821 static DWORD HTTP_ResolveName(http_request_t *request)
1823 server_t *server = request->proxy ? request->proxy : request->server;
1824 int addr_len;
1826 if(server->addr_len)
1827 return ERROR_SUCCESS;
1829 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1830 INTERNET_STATUS_RESOLVING_NAME,
1831 server->name,
1832 (strlenW(server->name)+1) * sizeof(WCHAR));
1834 addr_len = sizeof(server->addr);
1835 if (!GetAddress(server->name, server->port, (SOCKADDR*)&server->addr, &addr_len, server->addr_str))
1836 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1838 server->addr_len = addr_len;
1839 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1840 INTERNET_STATUS_NAME_RESOLVED,
1841 server->addr_str, strlen(server->addr_str)+1);
1843 TRACE("resolved %s to %s\n", debugstr_w(server->name), server->addr_str);
1844 return ERROR_SUCCESS;
1847 static WCHAR *compose_request_url(http_request_t *req)
1849 static const WCHAR http[] = { 'h','t','t','p',':','/','/',0 };
1850 static const WCHAR https[] = { 'h','t','t','p','s',':','/','/',0 };
1851 const WCHAR *host, *scheme;
1852 WCHAR *buf, *ptr;
1853 size_t len;
1855 host = req->server->canon_host_port;
1857 if (req->server->is_https)
1858 scheme = https;
1859 else
1860 scheme = http;
1862 len = strlenW(scheme) + strlenW(host) + (req->path[0] != '/' ? 1 : 0) + strlenW(req->path);
1863 ptr = buf = heap_alloc((len+1) * sizeof(WCHAR));
1864 if(buf) {
1865 strcpyW(ptr, scheme);
1866 ptr += strlenW(ptr);
1868 strcpyW(ptr, host);
1869 ptr += strlenW(ptr);
1871 if(req->path[0] != '/')
1872 *ptr++ = '/';
1874 strcpyW(ptr, req->path);
1875 ptr += strlenW(ptr);
1876 *ptr = 0;
1879 return buf;
1883 /***********************************************************************
1884 * HTTPREQ_Destroy (internal)
1886 * Deallocate request handle
1889 static void HTTPREQ_Destroy(object_header_t *hdr)
1891 http_request_t *request = (http_request_t*) hdr;
1892 DWORD i;
1894 TRACE("\n");
1896 if(request->hCacheFile)
1897 CloseHandle(request->hCacheFile);
1898 if(request->req_file)
1899 req_file_release(request->req_file);
1901 request->headers_section.DebugInfo->Spare[0] = 0;
1902 DeleteCriticalSection( &request->headers_section );
1903 request->read_section.DebugInfo->Spare[0] = 0;
1904 DeleteCriticalSection( &request->read_section );
1905 WININET_Release(&request->session->hdr);
1907 destroy_authinfo(request->authInfo);
1908 destroy_authinfo(request->proxyAuthInfo);
1910 if(request->server)
1911 server_release(request->server);
1912 if(request->proxy)
1913 server_release(request->proxy);
1915 heap_free(request->path);
1916 heap_free(request->verb);
1917 heap_free(request->version);
1918 heap_free(request->statusText);
1920 for (i = 0; i < request->nCustHeaders; i++)
1922 heap_free(request->custHeaders[i].lpszField);
1923 heap_free(request->custHeaders[i].lpszValue);
1925 destroy_data_stream(request->data_stream);
1926 heap_free(request->custHeaders);
1929 static void http_release_netconn(http_request_t *req, BOOL reuse)
1931 TRACE("%p %p %x\n",req, req->netconn, reuse);
1933 if(!is_valid_netconn(req->netconn))
1934 return;
1936 if(reuse && req->netconn->keep_alive) {
1937 BOOL run_collector;
1939 EnterCriticalSection(&connection_pool_cs);
1941 list_add_head(&req->netconn->server->conn_pool, &req->netconn->pool_entry);
1942 req->netconn->keep_until = GetTickCount64() + COLLECT_TIME;
1943 req->netconn = NULL;
1945 run_collector = !collector_running;
1946 collector_running = TRUE;
1948 LeaveCriticalSection(&connection_pool_cs);
1950 if(run_collector) {
1951 HANDLE thread = NULL;
1952 HMODULE module;
1954 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR*)WININET_hModule, &module);
1955 if(module)
1956 thread = CreateThread(NULL, 0, collect_connections_proc, NULL, 0, NULL);
1957 if(!thread) {
1958 EnterCriticalSection(&connection_pool_cs);
1959 collector_running = FALSE;
1960 LeaveCriticalSection(&connection_pool_cs);
1962 if(module)
1963 FreeLibrary(module);
1965 else
1966 CloseHandle(thread);
1968 return;
1971 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1972 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1974 close_netconn(req->netconn);
1976 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1977 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1980 static BOOL HTTP_KeepAlive(http_request_t *request)
1982 WCHAR szVersion[10];
1983 WCHAR szConnectionResponse[20];
1984 DWORD dwBufferSize = sizeof(szVersion);
1985 BOOL keepalive = FALSE;
1987 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
1988 * the connection is keep-alive by default */
1989 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_VERSION, szVersion, &dwBufferSize, NULL) == ERROR_SUCCESS
1990 && !strcmpiW(szVersion, g_szHttp1_1))
1992 keepalive = TRUE;
1995 dwBufferSize = sizeof(szConnectionResponse);
1996 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS
1997 || HTTP_HttpQueryInfoW(request, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS)
1999 keepalive = !strcmpiW(szConnectionResponse, szKeepAlive);
2002 return keepalive;
2005 static void HTTPREQ_CloseConnection(object_header_t *hdr)
2007 http_request_t *req = (http_request_t*)hdr;
2009 http_release_netconn(req, drain_content(req, FALSE) == ERROR_SUCCESS);
2012 static DWORD str_to_buffer(const WCHAR *str, void *buffer, DWORD *size, BOOL unicode)
2014 int len;
2015 if (unicode)
2017 WCHAR *buf = buffer;
2019 if (str) len = strlenW(str);
2020 else len = 0;
2021 if (*size < (len + 1) * sizeof(WCHAR))
2023 *size = (len + 1) * sizeof(WCHAR);
2024 return ERROR_INSUFFICIENT_BUFFER;
2026 if (str) strcpyW(buf, str);
2027 else buf[0] = 0;
2029 *size = len;
2030 return ERROR_SUCCESS;
2032 else
2034 char *buf = buffer;
2036 if (str) len = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
2037 else len = 1;
2038 if (*size < len)
2040 *size = len;
2041 return ERROR_INSUFFICIENT_BUFFER;
2043 if (str) WideCharToMultiByte(CP_ACP, 0, str, -1, buf, *size, NULL, NULL);
2044 else buf[0] = 0;
2046 *size = len - 1;
2047 return ERROR_SUCCESS;
2051 static DWORD HTTPREQ_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2053 http_request_t *req = (http_request_t*)hdr;
2055 switch(option) {
2056 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO:
2058 INTERNET_DIAGNOSTIC_SOCKET_INFO *info = buffer;
2060 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2062 if (*size < sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO))
2063 return ERROR_INSUFFICIENT_BUFFER;
2064 *size = sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO);
2065 /* FIXME: can't get a SOCKET from our connection since we don't use
2066 * winsock
2068 info->Socket = 0;
2069 /* FIXME: get source port from req->netConnection */
2070 info->SourcePort = 0;
2071 info->DestPort = req->server->port;
2072 info->Flags = 0;
2073 if (HTTP_KeepAlive(req))
2074 info->Flags |= IDSI_FLAG_KEEP_ALIVE;
2075 if (req->proxy)
2076 info->Flags |= IDSI_FLAG_PROXY;
2077 if (is_valid_netconn(req->netconn) && req->netconn->secure)
2078 info->Flags |= IDSI_FLAG_SECURE;
2080 return ERROR_SUCCESS;
2083 case 98:
2084 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2085 /* fall through */
2086 case INTERNET_OPTION_SECURITY_FLAGS:
2088 DWORD flags;
2090 if (*size < sizeof(ULONG))
2091 return ERROR_INSUFFICIENT_BUFFER;
2093 *size = sizeof(DWORD);
2094 flags = is_valid_netconn(req->netconn) ? req->netconn->security_flags : req->security_flags | req->server->security_flags;
2095 *(DWORD *)buffer = flags;
2097 TRACE("INTERNET_OPTION_SECURITY_FLAGS %x\n", flags);
2098 return ERROR_SUCCESS;
2101 case INTERNET_OPTION_HANDLE_TYPE:
2102 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2104 if (*size < sizeof(ULONG))
2105 return ERROR_INSUFFICIENT_BUFFER;
2107 *size = sizeof(DWORD);
2108 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
2109 return ERROR_SUCCESS;
2111 case INTERNET_OPTION_URL: {
2112 WCHAR *url;
2113 DWORD res;
2115 TRACE("INTERNET_OPTION_URL\n");
2117 url = compose_request_url(req);
2118 if(!url)
2119 return ERROR_OUTOFMEMORY;
2121 res = str_to_buffer(url, buffer, size, unicode);
2122 heap_free(url);
2123 return res;
2125 case INTERNET_OPTION_USER_AGENT:
2126 return str_to_buffer(req->session->appInfo->agent, buffer, size, unicode);
2127 case INTERNET_OPTION_USERNAME:
2128 return str_to_buffer(req->session->userName, buffer, size, unicode);
2129 case INTERNET_OPTION_PASSWORD:
2130 return str_to_buffer(req->session->password, buffer, size, unicode);
2131 case INTERNET_OPTION_PROXY_USERNAME:
2132 return str_to_buffer(req->session->appInfo->proxyUsername, buffer, size, unicode);
2133 case INTERNET_OPTION_PROXY_PASSWORD:
2134 return str_to_buffer(req->session->appInfo->proxyPassword, buffer, size, unicode);
2136 case INTERNET_OPTION_CACHE_TIMESTAMPS: {
2137 INTERNET_CACHE_ENTRY_INFOW *info;
2138 INTERNET_CACHE_TIMESTAMPS *ts = buffer;
2139 DWORD nbytes, error;
2140 BOOL ret;
2142 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2144 if(!req->req_file)
2145 return ERROR_FILE_NOT_FOUND;
2147 if (*size < sizeof(*ts))
2149 *size = sizeof(*ts);
2150 return ERROR_INSUFFICIENT_BUFFER;
2153 nbytes = 0;
2154 ret = GetUrlCacheEntryInfoW(req->req_file->url, NULL, &nbytes);
2155 error = GetLastError();
2156 if (!ret && error == ERROR_INSUFFICIENT_BUFFER)
2158 if (!(info = heap_alloc(nbytes)))
2159 return ERROR_OUTOFMEMORY;
2161 GetUrlCacheEntryInfoW(req->req_file->url, info, &nbytes);
2163 ts->ftExpires = info->ExpireTime;
2164 ts->ftLastModified = info->LastModifiedTime;
2166 heap_free(info);
2167 *size = sizeof(*ts);
2168 return ERROR_SUCCESS;
2170 return error;
2173 case INTERNET_OPTION_DATAFILE_NAME: {
2174 DWORD req_size;
2176 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2178 if(!req->req_file) {
2179 *size = 0;
2180 return ERROR_INTERNET_ITEM_NOT_FOUND;
2183 if(unicode) {
2184 req_size = (lstrlenW(req->req_file->file_name)+1) * sizeof(WCHAR);
2185 if(*size < req_size)
2186 return ERROR_INSUFFICIENT_BUFFER;
2188 *size = req_size;
2189 memcpy(buffer, req->req_file->file_name, *size);
2190 return ERROR_SUCCESS;
2191 }else {
2192 req_size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name, -1, NULL, 0, NULL, NULL);
2193 if (req_size > *size)
2194 return ERROR_INSUFFICIENT_BUFFER;
2196 *size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name,
2197 -1, buffer, *size, NULL, NULL);
2198 return ERROR_SUCCESS;
2202 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
2203 PCCERT_CONTEXT context;
2205 if(!req->netconn)
2206 return ERROR_INTERNET_INVALID_OPERATION;
2208 if(*size < sizeof(INTERNET_CERTIFICATE_INFOA)) {
2209 *size = sizeof(INTERNET_CERTIFICATE_INFOA);
2210 return ERROR_INSUFFICIENT_BUFFER;
2213 context = (PCCERT_CONTEXT)NETCON_GetCert(req->netconn);
2214 if(context) {
2215 INTERNET_CERTIFICATE_INFOA *info = (INTERNET_CERTIFICATE_INFOA*)buffer;
2216 DWORD len;
2218 memset(info, 0, sizeof(*info));
2219 info->ftExpiry = context->pCertInfo->NotAfter;
2220 info->ftStart = context->pCertInfo->NotBefore;
2221 len = CertNameToStrA(context->dwCertEncodingType,
2222 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2223 info->lpszSubjectInfo = LocalAlloc(0, len);
2224 if(info->lpszSubjectInfo)
2225 CertNameToStrA(context->dwCertEncodingType,
2226 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2227 info->lpszSubjectInfo, len);
2228 len = CertNameToStrA(context->dwCertEncodingType,
2229 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2230 info->lpszIssuerInfo = LocalAlloc(0, len);
2231 if(info->lpszIssuerInfo)
2232 CertNameToStrA(context->dwCertEncodingType,
2233 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2234 info->lpszIssuerInfo, len);
2235 info->dwKeySize = NETCON_GetCipherStrength(req->netconn);
2236 CertFreeCertificateContext(context);
2237 return ERROR_SUCCESS;
2239 return ERROR_NOT_SUPPORTED;
2241 case INTERNET_OPTION_CONNECT_TIMEOUT:
2242 if (*size < sizeof(DWORD))
2243 return ERROR_INSUFFICIENT_BUFFER;
2245 *size = sizeof(DWORD);
2246 *(DWORD *)buffer = req->connect_timeout;
2247 return ERROR_SUCCESS;
2248 case INTERNET_OPTION_REQUEST_FLAGS: {
2249 DWORD flags = 0;
2251 if (*size < sizeof(DWORD))
2252 return ERROR_INSUFFICIENT_BUFFER;
2254 /* FIXME: Add support for:
2255 * INTERNET_REQFLAG_FROM_CACHE
2256 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2259 if(req->proxy)
2260 flags |= INTERNET_REQFLAG_VIA_PROXY;
2261 if(!req->status_code)
2262 flags |= INTERNET_REQFLAG_NO_HEADERS;
2264 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %x\n", flags);
2266 *size = sizeof(DWORD);
2267 *(DWORD*)buffer = flags;
2268 return ERROR_SUCCESS;
2272 return INET_QueryOption(hdr, option, buffer, size, unicode);
2275 static DWORD HTTPREQ_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
2277 http_request_t *req = (http_request_t*)hdr;
2279 switch(option) {
2280 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2281 TRACE("Undocumented option 99\n");
2283 if (!buffer || size != sizeof(DWORD))
2284 return ERROR_INVALID_PARAMETER;
2285 if(*(DWORD*)buffer & ~SECURITY_SET_MASK)
2286 return ERROR_INTERNET_OPTION_NOT_SETTABLE;
2288 /* fall through */
2289 case INTERNET_OPTION_SECURITY_FLAGS:
2291 DWORD flags;
2293 if (!buffer || size != sizeof(DWORD))
2294 return ERROR_INVALID_PARAMETER;
2295 flags = *(DWORD *)buffer;
2296 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08x\n", flags);
2297 flags &= SECURITY_SET_MASK;
2298 req->security_flags |= flags;
2299 if(is_valid_netconn(req->netconn))
2300 req->netconn->security_flags |= flags;
2301 return ERROR_SUCCESS;
2303 case INTERNET_OPTION_CONNECT_TIMEOUT:
2304 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2305 req->connect_timeout = *(DWORD *)buffer;
2306 return ERROR_SUCCESS;
2308 case INTERNET_OPTION_SEND_TIMEOUT:
2309 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2310 req->send_timeout = *(DWORD *)buffer;
2311 return ERROR_SUCCESS;
2313 case INTERNET_OPTION_RECEIVE_TIMEOUT:
2314 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
2315 req->receive_timeout = *(DWORD *)buffer;
2316 return ERROR_SUCCESS;
2318 case INTERNET_OPTION_USERNAME:
2319 heap_free(req->session->userName);
2320 if (!(req->session->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2321 return ERROR_SUCCESS;
2323 case INTERNET_OPTION_PASSWORD:
2324 heap_free(req->session->password);
2325 if (!(req->session->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2326 return ERROR_SUCCESS;
2328 case INTERNET_OPTION_PROXY_USERNAME:
2329 heap_free(req->session->appInfo->proxyUsername);
2330 if (!(req->session->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2331 return ERROR_SUCCESS;
2333 case INTERNET_OPTION_PROXY_PASSWORD:
2334 heap_free(req->session->appInfo->proxyPassword);
2335 if (!(req->session->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
2336 return ERROR_SUCCESS;
2338 case INTERNET_OPTION_HTTP_DECODING:
2339 if(size != sizeof(BOOL))
2340 return ERROR_INVALID_PARAMETER;
2341 req->decoding = *(BOOL*)buffer;
2342 return ERROR_SUCCESS;
2345 return INET_SetOption(hdr, option, buffer, size);
2348 static void commit_cache_entry(http_request_t *req)
2350 WCHAR *header;
2351 DWORD header_len;
2352 BOOL res;
2354 TRACE("%p\n", req);
2356 CloseHandle(req->hCacheFile);
2357 req->hCacheFile = NULL;
2359 header = build_response_header(req, TRUE);
2360 header_len = (header ? strlenW(header) : 0);
2361 res = CommitUrlCacheEntryW(req->req_file->url, req->req_file->file_name, req->expires,
2362 req->last_modified, NORMAL_CACHE_ENTRY,
2363 header, header_len, NULL, 0);
2364 if(res)
2365 req->req_file->is_committed = TRUE;
2366 else
2367 WARN("CommitUrlCacheEntry failed: %u\n", GetLastError());
2368 heap_free(header);
2371 static void create_cache_entry(http_request_t *req)
2373 static const WCHAR no_cacheW[] = {'n','o','-','c','a','c','h','e',0};
2374 static const WCHAR no_storeW[] = {'n','o','-','s','t','o','r','e',0};
2376 WCHAR file_name[MAX_PATH+1];
2377 WCHAR *url;
2378 BOOL b = TRUE;
2380 /* FIXME: We should free previous cache file earlier */
2381 if(req->req_file) {
2382 req_file_release(req->req_file);
2383 req->req_file = NULL;
2385 if(req->hCacheFile) {
2386 CloseHandle(req->hCacheFile);
2387 req->hCacheFile = NULL;
2390 if(req->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE)
2391 b = FALSE;
2393 if(b) {
2394 int header_idx;
2396 EnterCriticalSection( &req->headers_section );
2398 header_idx = HTTP_GetCustomHeaderIndex(req, szCache_Control, 0, FALSE);
2399 if(header_idx != -1) {
2400 WCHAR *ptr;
2402 for(ptr=req->custHeaders[header_idx].lpszValue; *ptr; ) {
2403 WCHAR *end;
2405 while(*ptr==' ' || *ptr=='\t')
2406 ptr++;
2408 end = strchrW(ptr, ',');
2409 if(!end)
2410 end = ptr + strlenW(ptr);
2412 if(!strncmpiW(ptr, no_cacheW, ARRAY_SIZE(no_cacheW)-1)
2413 || !strncmpiW(ptr, no_storeW, ARRAY_SIZE(no_storeW)-1)) {
2414 b = FALSE;
2415 break;
2418 ptr = end;
2419 if(*ptr == ',')
2420 ptr++;
2424 LeaveCriticalSection( &req->headers_section );
2427 if(!b) {
2428 if(!(req->hdr.dwFlags & INTERNET_FLAG_NEED_FILE))
2429 return;
2431 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2434 url = compose_request_url(req);
2435 if(!url) {
2436 WARN("Could not get URL\n");
2437 return;
2440 b = CreateUrlCacheEntryW(url, req->contentLength == ~0u ? 0 : req->contentLength, NULL, file_name, 0);
2441 if(!b) {
2442 WARN("Could not create cache entry: %08x\n", GetLastError());
2443 return;
2446 create_req_file(file_name, &req->req_file);
2447 req->req_file->url = url;
2449 req->hCacheFile = CreateFileW(file_name, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
2450 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2451 if(req->hCacheFile == INVALID_HANDLE_VALUE) {
2452 WARN("Could not create file: %u\n", GetLastError());
2453 req->hCacheFile = NULL;
2454 return;
2457 if(req->read_size) {
2458 DWORD written;
2460 b = WriteFile(req->hCacheFile, req->read_buf+req->read_pos, req->read_size, &written, NULL);
2461 if(!b)
2462 FIXME("WriteFile failed: %u\n", GetLastError());
2464 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2465 commit_cache_entry(req);
2469 /* read some more data into the read buffer (the read section must be held) */
2470 static DWORD read_more_data( http_request_t *req, int maxlen )
2472 DWORD res;
2473 int len;
2475 if (req->read_pos)
2477 /* move existing data to the start of the buffer */
2478 if(req->read_size)
2479 memmove( req->read_buf, req->read_buf + req->read_pos, req->read_size );
2480 req->read_pos = 0;
2483 if (maxlen == -1) maxlen = sizeof(req->read_buf);
2485 res = NETCON_recv( req->netconn, req->read_buf + req->read_size,
2486 maxlen - req->read_size, TRUE, &len );
2487 if(res == ERROR_SUCCESS)
2488 req->read_size += len;
2490 return res;
2493 /* remove some amount of data from the read buffer (the read section must be held) */
2494 static void remove_data( http_request_t *req, int count )
2496 if (!(req->read_size -= count)) req->read_pos = 0;
2497 else req->read_pos += count;
2500 static DWORD read_line( http_request_t *req, LPSTR buffer, DWORD *len )
2502 int count, bytes_read, pos = 0;
2503 DWORD res;
2505 EnterCriticalSection( &req->read_section );
2506 for (;;)
2508 BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
2510 if (eol)
2512 count = eol - (req->read_buf + req->read_pos);
2513 bytes_read = count + 1;
2515 else count = bytes_read = req->read_size;
2517 count = min( count, *len - pos );
2518 memcpy( buffer + pos, req->read_buf + req->read_pos, count );
2519 pos += count;
2520 remove_data( req, bytes_read );
2521 if (eol) break;
2523 if ((res = read_more_data( req, -1 )))
2525 WARN( "read failed %u\n", res );
2526 LeaveCriticalSection( &req->read_section );
2527 return res;
2529 if (!req->read_size)
2531 *len = 0;
2532 TRACE( "returning empty string\n" );
2533 LeaveCriticalSection( &req->read_section );
2534 return ERROR_SUCCESS;
2537 LeaveCriticalSection( &req->read_section );
2539 if (pos < *len)
2541 if (pos && buffer[pos - 1] == '\r') pos--;
2542 *len = pos + 1;
2544 buffer[*len - 1] = 0;
2545 TRACE( "returning %s\n", debugstr_a(buffer));
2546 return ERROR_SUCCESS;
2549 /* check if we have reached the end of the data to read (the read section must be held) */
2550 static BOOL end_of_read_data( http_request_t *req )
2552 return !req->read_size && req->data_stream->vtbl->end_of_data(req->data_stream, req);
2555 static DWORD read_http_stream(http_request_t *req, BYTE *buf, DWORD size, DWORD *read, BOOL allow_blocking)
2557 DWORD res;
2559 res = req->data_stream->vtbl->read(req->data_stream, req, buf, size, read, allow_blocking);
2560 if(res != ERROR_SUCCESS)
2561 *read = 0;
2562 assert(*read <= size);
2564 if(req->hCacheFile) {
2565 if(*read) {
2566 BOOL bres;
2567 DWORD written;
2569 bres = WriteFile(req->hCacheFile, buf, *read, &written, NULL);
2570 if(!bres)
2571 FIXME("WriteFile failed: %u\n", GetLastError());
2574 if((res == ERROR_SUCCESS && !*read) || req->data_stream->vtbl->end_of_data(req->data_stream, req))
2575 commit_cache_entry(req);
2578 return res;
2581 /* fetch some more data into the read buffer (the read section must be held) */
2582 static DWORD refill_read_buffer(http_request_t *req, BOOL allow_blocking, DWORD *read_bytes)
2584 DWORD res, read=0;
2586 if(req->read_size == sizeof(req->read_buf))
2587 return ERROR_SUCCESS;
2589 if(req->read_pos) {
2590 if(req->read_size)
2591 memmove(req->read_buf, req->read_buf+req->read_pos, req->read_size);
2592 req->read_pos = 0;
2595 res = read_http_stream(req, req->read_buf+req->read_size, sizeof(req->read_buf) - req->read_size,
2596 &read, allow_blocking);
2597 if(res != ERROR_SUCCESS)
2598 return res;
2600 req->read_size += read;
2602 TRACE("read %u bytes, read_size %u\n", read, req->read_size);
2603 if(read_bytes)
2604 *read_bytes = read;
2605 return res;
2608 static BOOL netconn_end_of_data(data_stream_t *stream, http_request_t *req)
2610 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2611 return netconn_stream->content_read == netconn_stream->content_length || !is_valid_netconn(req->netconn);
2614 static DWORD netconn_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2615 DWORD *read, BOOL allow_blocking)
2617 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2618 DWORD res = ERROR_SUCCESS;
2619 int ret = 0;
2621 size = min(size, netconn_stream->content_length-netconn_stream->content_read);
2623 if(size && is_valid_netconn(req->netconn)) {
2624 res = NETCON_recv(req->netconn, buf, size, allow_blocking, &ret);
2625 if(res == ERROR_SUCCESS) {
2626 if(!ret)
2627 netconn_stream->content_length = netconn_stream->content_read;
2628 netconn_stream->content_read += ret;
2632 TRACE("res %u read %u bytes\n", res, ret);
2633 *read = ret;
2634 return res;
2637 static DWORD netconn_drain_content(data_stream_t *stream, http_request_t *req, BOOL allow_blocking)
2639 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2640 BYTE buf[1024];
2641 int len, res;
2642 size_t size;
2644 if(netconn_stream->content_length == ~0u)
2645 return WSAEISCONN;
2647 while(netconn_stream->content_read < netconn_stream->content_length) {
2648 size = min(sizeof(buf), netconn_stream->content_length-netconn_stream->content_read);
2649 res = NETCON_recv(req->netconn, buf, size, allow_blocking, &len);
2650 if(res)
2651 return res;
2652 if(!len)
2653 return WSAECONNABORTED;
2655 netconn_stream->content_read += len;
2658 return ERROR_SUCCESS;
2661 static void netconn_destroy(data_stream_t *stream)
2665 static const data_stream_vtbl_t netconn_stream_vtbl = {
2666 netconn_end_of_data,
2667 netconn_read,
2668 netconn_drain_content,
2669 netconn_destroy
2672 static char next_chunked_data_char(chunked_stream_t *stream)
2674 assert(stream->buf_size);
2676 stream->buf_size--;
2677 return stream->buf[stream->buf_pos++];
2680 static BOOL chunked_end_of_data(data_stream_t *stream, http_request_t *req)
2682 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2683 switch(chunked_stream->state) {
2684 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END:
2685 case CHUNKED_STREAM_STATE_END_OF_STREAM:
2686 case CHUNKED_STREAM_STATE_ERROR:
2687 return TRUE;
2688 default:
2689 return FALSE;
2693 static DWORD chunked_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2694 DWORD *read, BOOL allow_blocking)
2696 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2697 DWORD ret_read = 0, res = ERROR_SUCCESS;
2698 BOOL continue_read = TRUE;
2699 int read_bytes;
2700 char ch;
2702 do {
2703 TRACE("state %d\n", chunked_stream->state);
2705 /* Ensure that we have data in the buffer for states that need it. */
2706 if(!chunked_stream->buf_size) {
2707 BOOL blocking_read = allow_blocking;
2709 switch(chunked_stream->state) {
2710 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END:
2711 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE:
2712 /* never allow blocking after 0 chunk size */
2713 if(!chunked_stream->chunk_size)
2714 blocking_read = FALSE;
2715 /* fall through */
2716 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE:
2717 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA:
2718 chunked_stream->buf_pos = 0;
2719 res = NETCON_recv(req->netconn, chunked_stream->buf, sizeof(chunked_stream->buf), blocking_read, &read_bytes);
2720 if(res == ERROR_SUCCESS && read_bytes) {
2721 chunked_stream->buf_size += read_bytes;
2722 }else if(res == WSAEWOULDBLOCK) {
2723 if(ret_read || allow_blocking)
2724 res = ERROR_SUCCESS;
2725 continue_read = FALSE;
2726 continue;
2727 }else {
2728 chunked_stream->state = CHUNKED_STREAM_STATE_ERROR;
2730 break;
2731 default:
2732 break;
2736 switch(chunked_stream->state) {
2737 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE:
2738 ch = next_chunked_data_char(chunked_stream);
2740 if(ch >= '0' && ch <= '9') {
2741 chunked_stream->chunk_size = chunked_stream->chunk_size * 16 + ch - '0';
2742 }else if(ch >= 'a' && ch <= 'f') {
2743 chunked_stream->chunk_size = chunked_stream->chunk_size * 16 + ch - 'a' + 10;
2744 }else if (ch >= 'A' && ch <= 'F') {
2745 chunked_stream->chunk_size = chunked_stream->chunk_size * 16 + ch - 'A' + 10;
2746 }else if (ch == ';' || ch == '\r' || ch == '\n') {
2747 TRACE("reading %u byte chunk\n", chunked_stream->chunk_size);
2748 chunked_stream->buf_size++;
2749 chunked_stream->buf_pos--;
2750 if(req->contentLength == ~0u) req->contentLength = chunked_stream->chunk_size;
2751 else req->contentLength += chunked_stream->chunk_size;
2752 chunked_stream->state = CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE;
2754 break;
2756 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE:
2757 ch = next_chunked_data_char(chunked_stream);
2758 if(ch == '\n')
2759 chunked_stream->state = chunked_stream->chunk_size
2760 ? CHUNKED_STREAM_STATE_READING_CHUNK
2761 : CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END;
2762 else if(ch != '\r')
2763 WARN("unexpected char '%c'\n", ch);
2764 break;
2766 case CHUNKED_STREAM_STATE_READING_CHUNK:
2767 assert(chunked_stream->chunk_size);
2768 if(!size) {
2769 continue_read = FALSE;
2770 break;
2772 read_bytes = min(size, chunked_stream->chunk_size);
2774 if(chunked_stream->buf_size) {
2775 if(read_bytes > chunked_stream->buf_size)
2776 read_bytes = chunked_stream->buf_size;
2778 memcpy(buf+ret_read, chunked_stream->buf+chunked_stream->buf_pos, read_bytes);
2779 chunked_stream->buf_pos += read_bytes;
2780 chunked_stream->buf_size -= read_bytes;
2781 }else {
2782 res = NETCON_recv(req->netconn, (char*)buf+ret_read, read_bytes,
2783 allow_blocking, (int*)&read_bytes);
2784 if(res != ERROR_SUCCESS) {
2785 continue_read = FALSE;
2786 break;
2789 if(!read_bytes) {
2790 chunked_stream->state = CHUNKED_STREAM_STATE_ERROR;
2791 continue;
2795 chunked_stream->chunk_size -= read_bytes;
2796 size -= read_bytes;
2797 ret_read += read_bytes;
2798 if(!chunked_stream->chunk_size)
2799 chunked_stream->state = CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA;
2800 allow_blocking = FALSE;
2801 break;
2803 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA:
2804 ch = next_chunked_data_char(chunked_stream);
2805 if(ch == '\n')
2806 chunked_stream->state = CHUNKED_STREAM_STATE_READING_CHUNK_SIZE;
2807 else if(ch != '\r')
2808 WARN("unexpected char '%c'\n", ch);
2809 break;
2811 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END:
2812 ch = next_chunked_data_char(chunked_stream);
2813 if(ch == '\n')
2814 chunked_stream->state = CHUNKED_STREAM_STATE_END_OF_STREAM;
2815 else if(ch != '\r')
2816 WARN("unexpected char '%c'\n", ch);
2817 break;
2819 case CHUNKED_STREAM_STATE_END_OF_STREAM:
2820 case CHUNKED_STREAM_STATE_ERROR:
2821 continue_read = FALSE;
2822 break;
2824 } while(continue_read);
2826 if(ret_read)
2827 res = ERROR_SUCCESS;
2828 if(res != ERROR_SUCCESS)
2829 return res;
2831 TRACE("read %d bytes\n", ret_read);
2832 *read = ret_read;
2833 return ERROR_SUCCESS;
2836 static DWORD chunked_drain_content(data_stream_t *stream, http_request_t *req, BOOL allow_blocking)
2838 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2839 BYTE buf[1024];
2840 DWORD size, res;
2842 while(chunked_stream->state != CHUNKED_STREAM_STATE_END_OF_STREAM
2843 && chunked_stream->state != CHUNKED_STREAM_STATE_ERROR) {
2844 res = chunked_read(stream, req, buf, sizeof(buf), &size, allow_blocking);
2845 if(res != ERROR_SUCCESS)
2846 return res;
2849 if(chunked_stream->state != CHUNKED_STREAM_STATE_END_OF_STREAM)
2850 return ERROR_NO_DATA;
2851 return ERROR_SUCCESS;
2854 static void chunked_destroy(data_stream_t *stream)
2856 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2857 heap_free(chunked_stream);
2860 static const data_stream_vtbl_t chunked_stream_vtbl = {
2861 chunked_end_of_data,
2862 chunked_read,
2863 chunked_drain_content,
2864 chunked_destroy
2867 /* set the request content length based on the headers */
2868 static DWORD set_content_length(http_request_t *request)
2870 static const WCHAR szChunked[] = {'c','h','u','n','k','e','d',0};
2871 static const WCHAR headW[] = {'H','E','A','D',0};
2872 WCHAR encoding[20];
2873 DWORD size;
2875 if(request->status_code == HTTP_STATUS_NO_CONTENT || !strcmpW(request->verb, headW)) {
2876 request->contentLength = request->netconn_stream.content_length = 0;
2877 return ERROR_SUCCESS;
2880 size = sizeof(request->contentLength);
2881 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH,
2882 &request->contentLength, &size, NULL) != ERROR_SUCCESS)
2883 request->contentLength = ~0u;
2884 request->netconn_stream.content_length = request->contentLength;
2885 request->netconn_stream.content_read = request->read_size;
2887 size = sizeof(encoding);
2888 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) == ERROR_SUCCESS &&
2889 !strcmpiW(encoding, szChunked))
2891 chunked_stream_t *chunked_stream;
2893 chunked_stream = heap_alloc(sizeof(*chunked_stream));
2894 if(!chunked_stream)
2895 return ERROR_OUTOFMEMORY;
2897 chunked_stream->data_stream.vtbl = &chunked_stream_vtbl;
2898 chunked_stream->buf_size = chunked_stream->buf_pos = 0;
2899 chunked_stream->chunk_size = 0;
2900 chunked_stream->state = CHUNKED_STREAM_STATE_READING_CHUNK_SIZE;
2902 if(request->read_size) {
2903 memcpy(chunked_stream->buf, request->read_buf+request->read_pos, request->read_size);
2904 chunked_stream->buf_size = request->read_size;
2905 request->read_size = request->read_pos = 0;
2908 request->data_stream = &chunked_stream->data_stream;
2909 request->contentLength = ~0u;
2912 if(request->decoding) {
2913 int encoding_idx;
2915 static const WCHAR deflateW[] = {'d','e','f','l','a','t','e',0};
2916 static const WCHAR gzipW[] = {'g','z','i','p',0};
2918 EnterCriticalSection( &request->headers_section );
2920 encoding_idx = HTTP_GetCustomHeaderIndex(request, szContent_Encoding, 0, FALSE);
2921 if(encoding_idx != -1) {
2922 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, gzipW)) {
2923 HTTP_DeleteCustomHeader(request, encoding_idx);
2924 LeaveCriticalSection( &request->headers_section );
2925 return init_gzip_stream(request, TRUE);
2927 if(!strcmpiW(request->custHeaders[encoding_idx].lpszValue, deflateW)) {
2928 HTTP_DeleteCustomHeader(request, encoding_idx);
2929 LeaveCriticalSection( &request->headers_section );
2930 return init_gzip_stream(request, FALSE);
2934 LeaveCriticalSection( &request->headers_section );
2937 return ERROR_SUCCESS;
2940 static void send_request_complete(http_request_t *req, DWORD_PTR result, DWORD error)
2942 INTERNET_ASYNC_RESULT iar;
2944 iar.dwResult = result;
2945 iar.dwError = error;
2947 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2948 sizeof(INTERNET_ASYNC_RESULT));
2951 static void HTTP_ReceiveRequestData(http_request_t *req)
2953 DWORD res, read = 0;
2955 TRACE("%p\n", req);
2957 EnterCriticalSection( &req->read_section );
2959 res = refill_read_buffer(req, FALSE, &read);
2960 if(res == ERROR_SUCCESS)
2961 read += req->read_size;
2963 LeaveCriticalSection( &req->read_section );
2965 if(res != WSAEWOULDBLOCK && (res != ERROR_SUCCESS || !read)) {
2966 WARN("res %u read %u, closing connection\n", res, read);
2967 http_release_netconn(req, FALSE);
2970 if(res != ERROR_SUCCESS && res != WSAEWOULDBLOCK) {
2971 send_request_complete(req, 0, res);
2972 return;
2975 send_request_complete(req, req->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)req->hdr.hInternet : 1, 0);
2978 /* read data from the http connection (the read section must be held) */
2979 static DWORD HTTPREQ_Read(http_request_t *req, void *buffer, DWORD size, DWORD *read, BOOL allow_blocking)
2981 DWORD current_read = 0, ret_read = 0;
2982 DWORD res = ERROR_SUCCESS;
2984 EnterCriticalSection( &req->read_section );
2986 if(req->read_size) {
2987 ret_read = min(size, req->read_size);
2988 memcpy(buffer, req->read_buf+req->read_pos, ret_read);
2989 req->read_size -= ret_read;
2990 req->read_pos += ret_read;
2991 allow_blocking = FALSE;
2994 if(ret_read < size) {
2995 res = read_http_stream(req, (BYTE*)buffer+ret_read, size-ret_read, &current_read, allow_blocking);
2996 if(res == ERROR_SUCCESS)
2997 ret_read += current_read;
2998 else if(res == WSAEWOULDBLOCK && ret_read)
2999 res = ERROR_SUCCESS;
3002 LeaveCriticalSection( &req->read_section );
3004 *read = ret_read;
3005 TRACE( "retrieved %u bytes (res %u)\n", ret_read, res );
3007 if(res != WSAEWOULDBLOCK) {
3008 if(res != ERROR_SUCCESS)
3009 http_release_netconn(req, FALSE);
3010 else if(!ret_read && drain_content(req, FALSE) == ERROR_SUCCESS)
3011 http_release_netconn(req, TRUE);
3014 return res;
3017 static DWORD drain_content(http_request_t *req, BOOL blocking)
3019 DWORD res;
3021 TRACE("%p\n", req->netconn);
3023 if(!is_valid_netconn(req->netconn))
3024 return ERROR_NO_DATA;
3026 if(!strcmpW(req->verb, szHEAD))
3027 return ERROR_SUCCESS;
3029 EnterCriticalSection( &req->read_section );
3030 res = req->data_stream->vtbl->drain_content(req->data_stream, req, blocking);
3031 LeaveCriticalSection( &req->read_section );
3032 return res;
3035 typedef struct {
3036 task_header_t hdr;
3037 void *buf;
3038 DWORD size;
3039 DWORD read_pos;
3040 DWORD *ret_read;
3041 } read_file_task_t;
3043 static void async_read_file_proc(task_header_t *hdr)
3045 read_file_task_t *task = (read_file_task_t*)hdr;
3046 http_request_t *req = (http_request_t*)task->hdr.hdr;
3047 DWORD res = ERROR_SUCCESS, read = task->read_pos, complete_arg = 0;
3049 TRACE("req %p buf %p size %u read_pos %u ret_read %p\n", req, task->buf, task->size, task->read_pos, task->ret_read);
3051 if(task->buf) {
3052 DWORD read_bytes;
3053 while (read < task->size) {
3054 res = HTTPREQ_Read(req, (char*)task->buf + read, task->size - read, &read_bytes, TRUE);
3055 if (res != ERROR_SUCCESS || !read_bytes)
3056 break;
3057 read += read_bytes;
3059 }else {
3060 EnterCriticalSection(&req->read_section);
3061 res = refill_read_buffer(req, TRUE, &read);
3062 LeaveCriticalSection(&req->read_section);
3064 if(task->ret_read)
3065 complete_arg = read; /* QueryDataAvailable reports read bytes in request complete notification */
3066 if(res != ERROR_SUCCESS || !read)
3067 http_release_netconn(req, drain_content(req, FALSE) == ERROR_SUCCESS);
3070 TRACE("res %u read %u\n", res, read);
3072 if(task->ret_read)
3073 *task->ret_read = read;
3075 /* FIXME: We should report bytes transferred before decoding content. */
3076 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED, &read, sizeof(read));
3078 if(res != ERROR_SUCCESS)
3079 complete_arg = res;
3080 send_request_complete(req, res == ERROR_SUCCESS, complete_arg);
3083 static DWORD async_read(http_request_t *req, void *buf, DWORD size, DWORD read_pos, DWORD *ret_read)
3085 read_file_task_t *task;
3087 task = alloc_async_task(&req->hdr, async_read_file_proc, sizeof(*task));
3088 if(!task)
3089 return ERROR_OUTOFMEMORY;
3091 task->buf = buf;
3092 task->size = size;
3093 task->read_pos = read_pos;
3094 task->ret_read = ret_read;
3096 INTERNET_AsyncCall(&task->hdr);
3097 return ERROR_IO_PENDING;
3100 static DWORD HTTPREQ_ReadFile(object_header_t *hdr, void *buf, DWORD size, DWORD *ret_read,
3101 DWORD flags, DWORD_PTR context)
3103 http_request_t *req = (http_request_t*)hdr;
3104 DWORD res = ERROR_SUCCESS, read = 0, cread, error = ERROR_SUCCESS;
3105 BOOL allow_blocking, notify_received = FALSE;
3107 TRACE("(%p %p %u %x)\n", req, buf, size, flags);
3109 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3110 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3112 allow_blocking = !(req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC);
3114 if(allow_blocking || TryEnterCriticalSection(&req->read_section)) {
3115 if(allow_blocking)
3116 EnterCriticalSection(&req->read_section);
3117 if(hdr->dwError == ERROR_SUCCESS)
3118 hdr->dwError = INTERNET_HANDLE_IN_USE;
3119 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3120 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3122 if(req->read_size) {
3123 read = min(size, req->read_size);
3124 memcpy(buf, req->read_buf + req->read_pos, read);
3125 req->read_size -= read;
3126 req->read_pos += read;
3129 if(read < size && (!read || !(flags & IRF_NO_WAIT)) && !end_of_read_data(req)) {
3130 LeaveCriticalSection(&req->read_section);
3131 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3132 EnterCriticalSection( &req->read_section );
3133 notify_received = TRUE;
3135 while(read < size) {
3136 res = HTTPREQ_Read(req, (char*)buf+read, size-read, &cread, allow_blocking);
3137 read += cread;
3138 if (res != ERROR_SUCCESS || !cread)
3139 break;
3143 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3144 hdr->dwError = ERROR_SUCCESS;
3145 else
3146 error = hdr->dwError;
3148 LeaveCriticalSection( &req->read_section );
3149 }else {
3150 res = WSAEWOULDBLOCK;
3153 if(res == WSAEWOULDBLOCK) {
3154 if(!(flags & IRF_NO_WAIT))
3155 return async_read(req, buf, size, read, ret_read);
3156 if(!read)
3157 return async_read(req, NULL, 0, 0, NULL);
3158 res = ERROR_SUCCESS;
3161 *ret_read = read;
3162 if (res != ERROR_SUCCESS)
3163 return res;
3165 if(notify_received)
3166 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3167 &read, sizeof(read));
3168 return error;
3171 static DWORD HTTPREQ_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
3173 DWORD res;
3174 http_request_t *request = (http_request_t*)hdr;
3176 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3178 *written = 0;
3179 res = NETCON_send(request->netconn, buffer, size, 0, (LPINT)written);
3180 if (res == ERROR_SUCCESS)
3181 request->bytesWritten += *written;
3183 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
3184 return res;
3187 static DWORD HTTPREQ_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
3189 http_request_t *req = (http_request_t*)hdr;
3190 DWORD res = ERROR_SUCCESS, avail = 0, error = ERROR_SUCCESS;
3191 BOOL allow_blocking, notify_received = FALSE;
3193 TRACE("(%p %p %x %lx)\n", req, available, flags, ctx);
3195 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3196 FIXME("these dwFlags aren't implemented: 0x%x\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3198 *available = 0;
3199 allow_blocking = !(req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC);
3201 if(allow_blocking || TryEnterCriticalSection(&req->read_section)) {
3202 if(allow_blocking)
3203 EnterCriticalSection(&req->read_section);
3204 if(hdr->dwError == ERROR_SUCCESS)
3205 hdr->dwError = INTERNET_HANDLE_IN_USE;
3206 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3207 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3209 avail = req->read_size;
3211 if(!avail && !end_of_read_data(req)) {
3212 LeaveCriticalSection(&req->read_section);
3213 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3214 EnterCriticalSection( &req->read_section );
3215 notify_received = TRUE;
3217 res = refill_read_buffer(req, allow_blocking, &avail);
3220 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3221 hdr->dwError = ERROR_SUCCESS;
3222 else
3223 error = hdr->dwError;
3225 LeaveCriticalSection( &req->read_section );
3226 }else {
3227 res = WSAEWOULDBLOCK;
3230 if(res == WSAEWOULDBLOCK)
3231 return async_read(req, NULL, 0, 0, available);
3233 if (res != ERROR_SUCCESS)
3234 return res;
3236 *available = avail;
3237 if(notify_received)
3238 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3239 &avail, sizeof(avail));
3240 return error;
3243 static DWORD HTTPREQ_LockRequestFile(object_header_t *hdr, req_file_t **ret)
3245 http_request_t *req = (http_request_t*)hdr;
3247 TRACE("(%p)\n", req);
3249 if(!req->req_file) {
3250 WARN("No cache file name available\n");
3251 return ERROR_FILE_NOT_FOUND;
3254 *ret = req_file_addref(req->req_file);
3255 return ERROR_SUCCESS;
3258 static const object_vtbl_t HTTPREQVtbl = {
3259 HTTPREQ_Destroy,
3260 HTTPREQ_CloseConnection,
3261 HTTPREQ_QueryOption,
3262 HTTPREQ_SetOption,
3263 HTTPREQ_ReadFile,
3264 HTTPREQ_WriteFile,
3265 HTTPREQ_QueryDataAvailable,
3266 NULL,
3267 HTTPREQ_LockRequestFile
3270 /***********************************************************************
3271 * HTTP_HttpOpenRequestW (internal)
3273 * Open a HTTP request handle
3275 * RETURNS
3276 * HINTERNET a HTTP request handle on success
3277 * NULL on failure
3280 static DWORD HTTP_HttpOpenRequestW(http_session_t *session,
3281 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3282 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3283 DWORD dwFlags, DWORD_PTR dwContext, HINTERNET *ret)
3285 appinfo_t *hIC = session->appInfo;
3286 http_request_t *request;
3287 DWORD port, len;
3289 TRACE("-->\n");
3291 request = alloc_object(&session->hdr, &HTTPREQVtbl, sizeof(http_request_t));
3292 if(!request)
3293 return ERROR_OUTOFMEMORY;
3295 request->hdr.htype = WH_HHTTPREQ;
3296 request->hdr.dwFlags = dwFlags;
3297 request->hdr.dwContext = dwContext;
3298 request->contentLength = ~0u;
3300 request->netconn_stream.data_stream.vtbl = &netconn_stream_vtbl;
3301 request->data_stream = &request->netconn_stream.data_stream;
3302 request->connect_timeout = session->connect_timeout;
3303 request->send_timeout = session->send_timeout;
3304 request->receive_timeout = session->receive_timeout;
3306 InitializeCriticalSection( &request->headers_section );
3307 request->headers_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.headers_section");
3309 InitializeCriticalSection( &request->read_section );
3310 request->read_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.read_section");
3312 WININET_AddRef( &session->hdr );
3313 request->session = session;
3314 list_add_head( &session->hdr.children, &request->hdr.entry );
3316 port = session->hostPort;
3317 if (port == INTERNET_INVALID_PORT_NUMBER)
3318 port = (session->hdr.dwFlags & INTERNET_FLAG_SECURE) ?
3319 INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;
3321 request->server = get_server(substrz(session->hostName), port, (dwFlags & INTERNET_FLAG_SECURE) != 0, TRUE);
3322 if(!request->server) {
3323 WININET_Release(&request->hdr);
3324 return ERROR_OUTOFMEMORY;
3327 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_CN_INVALID)
3328 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
3329 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_DATE_INVALID)
3330 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
3332 if (lpszObjectName && *lpszObjectName) {
3333 HRESULT rc;
3334 WCHAR dummy;
3336 len = 1;
3337 rc = UrlCanonicalizeW(lpszObjectName, &dummy, &len, URL_ESCAPE_SPACES_ONLY);
3338 if (rc != E_POINTER)
3339 len = strlenW(lpszObjectName)+1;
3340 request->path = heap_alloc(len*sizeof(WCHAR));
3341 rc = UrlCanonicalizeW(lpszObjectName, request->path, &len,
3342 URL_ESCAPE_SPACES_ONLY);
3343 if (rc != S_OK)
3345 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(lpszObjectName),rc);
3346 strcpyW(request->path,lpszObjectName);
3348 }else {
3349 static const WCHAR slashW[] = {'/',0};
3351 request->path = heap_strdupW(slashW);
3354 if (lpszReferrer && *lpszReferrer)
3355 HTTP_ProcessHeader(request, HTTP_REFERER, lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3357 if (lpszAcceptTypes)
3359 int i;
3360 for (i = 0; lpszAcceptTypes[i]; i++)
3362 if (!*lpszAcceptTypes[i]) continue;
3363 HTTP_ProcessHeader(request, HTTP_ACCEPT, lpszAcceptTypes[i],
3364 HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA |
3365 HTTP_ADDHDR_FLAG_REQ |
3366 (i == 0 ? (HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD) : 0));
3370 request->verb = heap_strdupW(lpszVerb && *lpszVerb ? lpszVerb : szGET);
3371 request->version = heap_strdupW(lpszVersion && *lpszVersion ? lpszVersion : g_szHttp1_1);
3373 if (hIC->proxy && hIC->proxy[0] && !HTTP_ShouldBypassProxy(hIC, session->hostName))
3374 HTTP_DealWithProxy( hIC, session, request );
3376 INTERNET_SendCallback(&session->hdr, dwContext,
3377 INTERNET_STATUS_HANDLE_CREATED, &request->hdr.hInternet,
3378 sizeof(HINTERNET));
3380 TRACE("<-- (%p)\n", request);
3382 *ret = request->hdr.hInternet;
3383 return ERROR_SUCCESS;
3386 /***********************************************************************
3387 * HttpOpenRequestW (WININET.@)
3389 * Open a HTTP request handle
3391 * RETURNS
3392 * HINTERNET a HTTP request handle on success
3393 * NULL on failure
3396 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
3397 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3398 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3399 DWORD dwFlags, DWORD_PTR dwContext)
3401 http_session_t *session;
3402 HINTERNET handle = NULL;
3403 DWORD res;
3405 TRACE("(%p, %s, %s, %s, %s, %p, %08x, %08lx)\n", hHttpSession,
3406 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
3407 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
3408 dwFlags, dwContext);
3409 if(lpszAcceptTypes!=NULL)
3411 int i;
3412 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
3413 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
3416 session = (http_session_t*) get_handle_object( hHttpSession );
3417 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
3419 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3420 goto lend;
3424 * My tests seem to show that the windows version does not
3425 * become asynchronous until after this point. And anyhow
3426 * if this call was asynchronous then how would you get the
3427 * necessary HINTERNET pointer returned by this function.
3430 res = HTTP_HttpOpenRequestW(session, lpszVerb, lpszObjectName,
3431 lpszVersion, lpszReferrer, lpszAcceptTypes,
3432 dwFlags, dwContext, &handle);
3433 lend:
3434 if( session )
3435 WININET_Release( &session->hdr );
3436 TRACE("returning %p\n", handle);
3437 if(res != ERROR_SUCCESS)
3438 SetLastError(res);
3439 return handle;
3442 static const LPCWSTR header_lookup[] = {
3443 szMime_Version, /* HTTP_QUERY_MIME_VERSION = 0 */
3444 szContent_Type, /* HTTP_QUERY_CONTENT_TYPE = 1 */
3445 szContent_Transfer_Encoding,/* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3446 szContent_ID, /* HTTP_QUERY_CONTENT_ID = 3 */
3447 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3448 szContent_Length, /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3449 szContent_Language, /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3450 szAllow, /* HTTP_QUERY_ALLOW = 7 */
3451 szPublic, /* HTTP_QUERY_PUBLIC = 8 */
3452 szDate, /* HTTP_QUERY_DATE = 9 */
3453 szExpires, /* HTTP_QUERY_EXPIRES = 10 */
3454 szLast_Modified, /* HTTP_QUERY_LAST_MODIFIED = 11 */
3455 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
3456 szURI, /* HTTP_QUERY_URI = 13 */
3457 szFrom, /* HTTP_QUERY_DERIVED_FROM = 14 */
3458 NULL, /* HTTP_QUERY_COST = 15 */
3459 NULL, /* HTTP_QUERY_LINK = 16 */
3460 szPragma, /* HTTP_QUERY_PRAGMA = 17 */
3461 NULL, /* HTTP_QUERY_VERSION = 18 */
3462 szStatus, /* HTTP_QUERY_STATUS_CODE = 19 */
3463 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
3464 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
3465 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3466 szConnection, /* HTTP_QUERY_CONNECTION = 23 */
3467 szAccept, /* HTTP_QUERY_ACCEPT = 24 */
3468 szAccept_Charset, /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3469 szAccept_Encoding, /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3470 szAccept_Language, /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3471 szAuthorization, /* HTTP_QUERY_AUTHORIZATION = 28 */
3472 szContent_Encoding, /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3473 NULL, /* HTTP_QUERY_FORWARDED = 30 */
3474 NULL, /* HTTP_QUERY_FROM = 31 */
3475 szIf_Modified_Since, /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3476 szLocation, /* HTTP_QUERY_LOCATION = 33 */
3477 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
3478 szReferer, /* HTTP_QUERY_REFERER = 35 */
3479 szRetry_After, /* HTTP_QUERY_RETRY_AFTER = 36 */
3480 szServer, /* HTTP_QUERY_SERVER = 37 */
3481 NULL, /* HTTP_TITLE = 38 */
3482 szUser_Agent, /* HTTP_QUERY_USER_AGENT = 39 */
3483 szWWW_Authenticate, /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3484 szProxy_Authenticate, /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3485 szAccept_Ranges, /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3486 szSet_Cookie, /* HTTP_QUERY_SET_COOKIE = 43 */
3487 szCookie, /* HTTP_QUERY_COOKIE = 44 */
3488 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3489 NULL, /* HTTP_QUERY_REFRESH = 46 */
3490 szContent_Disposition, /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3491 szAge, /* HTTP_QUERY_AGE = 48 */
3492 szCache_Control, /* HTTP_QUERY_CACHE_CONTROL = 49 */
3493 szContent_Base, /* HTTP_QUERY_CONTENT_BASE = 50 */
3494 szContent_Location, /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3495 szContent_MD5, /* HTTP_QUERY_CONTENT_MD5 = 52 */
3496 szContent_Range, /* HTTP_QUERY_CONTENT_RANGE = 53 */
3497 szETag, /* HTTP_QUERY_ETAG = 54 */
3498 hostW, /* HTTP_QUERY_HOST = 55 */
3499 szIf_Match, /* HTTP_QUERY_IF_MATCH = 56 */
3500 szIf_None_Match, /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3501 szIf_Range, /* HTTP_QUERY_IF_RANGE = 58 */
3502 szIf_Unmodified_Since, /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3503 szMax_Forwards, /* HTTP_QUERY_MAX_FORWARDS = 60 */
3504 szProxy_Authorization, /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3505 szRange, /* HTTP_QUERY_RANGE = 62 */
3506 szTransfer_Encoding, /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3507 szUpgrade, /* HTTP_QUERY_UPGRADE = 64 */
3508 szVary, /* HTTP_QUERY_VARY = 65 */
3509 szVia, /* HTTP_QUERY_VIA = 66 */
3510 szWarning, /* HTTP_QUERY_WARNING = 67 */
3511 szExpect, /* HTTP_QUERY_EXPECT = 68 */
3512 szProxy_Connection, /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3513 szUnless_Modified_Since, /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3516 /***********************************************************************
3517 * HTTP_HttpQueryInfoW (internal)
3519 static DWORD HTTP_HttpQueryInfoW(http_request_t *request, DWORD dwInfoLevel,
3520 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3522 LPHTTPHEADERW lphttpHdr = NULL;
3523 BOOL request_only = !!(dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS);
3524 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
3525 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
3526 INT index = -1;
3528 EnterCriticalSection( &request->headers_section );
3530 /* Find requested header structure */
3531 switch (level)
3533 case HTTP_QUERY_CUSTOM:
3534 if (!lpBuffer)
3536 LeaveCriticalSection( &request->headers_section );
3537 return ERROR_INVALID_PARAMETER;
3539 index = HTTP_GetCustomHeaderIndex(request, lpBuffer, requested_index, request_only);
3540 break;
3541 case HTTP_QUERY_RAW_HEADERS_CRLF:
3543 LPWSTR headers;
3544 DWORD len = 0;
3545 DWORD res = ERROR_INVALID_PARAMETER;
3547 if (request_only)
3548 headers = build_request_header(request, request->verb, request->path, request->version, TRUE);
3549 else
3550 headers = build_response_header(request, TRUE);
3551 if (!headers)
3553 LeaveCriticalSection( &request->headers_section );
3554 return ERROR_OUTOFMEMORY;
3557 len = strlenW(headers) * sizeof(WCHAR);
3558 if (len + sizeof(WCHAR) > *lpdwBufferLength)
3560 len += sizeof(WCHAR);
3561 res = ERROR_INSUFFICIENT_BUFFER;
3563 else if (lpBuffer)
3565 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3566 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
3567 res = ERROR_SUCCESS;
3569 *lpdwBufferLength = len;
3571 heap_free(headers);
3572 LeaveCriticalSection( &request->headers_section );
3573 return res;
3575 case HTTP_QUERY_RAW_HEADERS:
3577 LPWSTR headers;
3578 DWORD len;
3580 if (request_only)
3581 headers = build_request_header(request, request->verb, request->path, request->version, FALSE);
3582 else
3583 headers = build_response_header(request, FALSE);
3585 if (!headers)
3587 LeaveCriticalSection( &request->headers_section );
3588 return ERROR_OUTOFMEMORY;
3591 len = strlenW(headers) * sizeof(WCHAR);
3592 if (len > *lpdwBufferLength)
3594 *lpdwBufferLength = len;
3595 heap_free(headers);
3596 LeaveCriticalSection( &request->headers_section );
3597 return ERROR_INSUFFICIENT_BUFFER;
3600 if (lpBuffer)
3602 DWORD i;
3604 TRACE("returning data: %s\n", debugstr_wn(headers, len / sizeof(WCHAR)));
3606 for (i = 0; i < len / sizeof(WCHAR); i++)
3608 if (headers[i] == '\n')
3609 headers[i] = 0;
3611 memcpy(lpBuffer, headers, len);
3613 *lpdwBufferLength = len - sizeof(WCHAR);
3615 heap_free(headers);
3616 LeaveCriticalSection( &request->headers_section );
3617 return ERROR_SUCCESS;
3619 case HTTP_QUERY_STATUS_TEXT:
3620 if (request->statusText)
3622 DWORD len = strlenW(request->statusText);
3623 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3625 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3626 LeaveCriticalSection( &request->headers_section );
3627 return ERROR_INSUFFICIENT_BUFFER;
3629 if (lpBuffer)
3631 memcpy(lpBuffer, request->statusText, (len + 1) * sizeof(WCHAR));
3632 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3634 *lpdwBufferLength = len * sizeof(WCHAR);
3635 LeaveCriticalSection( &request->headers_section );
3636 return ERROR_SUCCESS;
3638 break;
3639 case HTTP_QUERY_VERSION:
3640 if (request->version)
3642 DWORD len = strlenW(request->version);
3643 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3645 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3646 LeaveCriticalSection( &request->headers_section );
3647 return ERROR_INSUFFICIENT_BUFFER;
3649 if (lpBuffer)
3651 memcpy(lpBuffer, request->version, (len + 1) * sizeof(WCHAR));
3652 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3654 *lpdwBufferLength = len * sizeof(WCHAR);
3655 LeaveCriticalSection( &request->headers_section );
3656 return ERROR_SUCCESS;
3658 break;
3659 case HTTP_QUERY_CONTENT_ENCODING:
3660 index = HTTP_GetCustomHeaderIndex(request, header_lookup[request->read_gzip ? HTTP_QUERY_CONTENT_TYPE : level],
3661 requested_index,request_only);
3662 break;
3663 case HTTP_QUERY_STATUS_CODE: {
3664 DWORD res = ERROR_SUCCESS;
3666 if(request_only)
3668 LeaveCriticalSection( &request->headers_section );
3669 return ERROR_HTTP_INVALID_QUERY_REQUEST;
3672 if(requested_index)
3673 break;
3675 if(dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) {
3676 if(*lpdwBufferLength >= sizeof(DWORD))
3677 *(DWORD*)lpBuffer = request->status_code;
3678 else
3679 res = ERROR_INSUFFICIENT_BUFFER;
3680 *lpdwBufferLength = sizeof(DWORD);
3681 }else {
3682 WCHAR buf[12];
3683 DWORD size;
3684 static const WCHAR formatW[] = {'%','u',0};
3686 size = sprintfW(buf, formatW, request->status_code) * sizeof(WCHAR);
3688 if(size <= *lpdwBufferLength) {
3689 memcpy(lpBuffer, buf, size+sizeof(WCHAR));
3690 }else {
3691 size += sizeof(WCHAR);
3692 res = ERROR_INSUFFICIENT_BUFFER;
3695 *lpdwBufferLength = size;
3697 LeaveCriticalSection( &request->headers_section );
3698 return res;
3700 default:
3701 assert (ARRAY_SIZE(header_lookup) == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
3703 if (level < ARRAY_SIZE(header_lookup) && header_lookup[level])
3704 index = HTTP_GetCustomHeaderIndex(request, header_lookup[level],
3705 requested_index,request_only);
3708 if (index >= 0)
3709 lphttpHdr = &request->custHeaders[index];
3711 /* Ensure header satisfies requested attributes */
3712 if (!lphttpHdr ||
3713 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
3714 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
3716 LeaveCriticalSection( &request->headers_section );
3717 return ERROR_HTTP_HEADER_NOT_FOUND;
3720 /* coalesce value to requested type */
3721 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
3723 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
3724 TRACE(" returning number: %d\n", *(int *)lpBuffer);
3726 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
3728 time_t tmpTime;
3729 struct tm tmpTM;
3730 SYSTEMTIME *STHook;
3732 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
3734 tmpTM = *gmtime(&tmpTime);
3735 STHook = (SYSTEMTIME *)lpBuffer;
3736 STHook->wDay = tmpTM.tm_mday;
3737 STHook->wHour = tmpTM.tm_hour;
3738 STHook->wMilliseconds = 0;
3739 STHook->wMinute = tmpTM.tm_min;
3740 STHook->wDayOfWeek = tmpTM.tm_wday;
3741 STHook->wMonth = tmpTM.tm_mon + 1;
3742 STHook->wSecond = tmpTM.tm_sec;
3743 STHook->wYear = 1900+tmpTM.tm_year;
3745 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3746 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
3747 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
3749 else if (lphttpHdr->lpszValue)
3751 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
3753 if (len > *lpdwBufferLength)
3755 *lpdwBufferLength = len;
3756 LeaveCriticalSection( &request->headers_section );
3757 return ERROR_INSUFFICIENT_BUFFER;
3759 if (lpBuffer)
3761 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
3762 TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
3764 *lpdwBufferLength = len - sizeof(WCHAR);
3766 if (lpdwIndex) (*lpdwIndex)++;
3768 LeaveCriticalSection( &request->headers_section );
3769 return ERROR_SUCCESS;
3772 /***********************************************************************
3773 * HttpQueryInfoW (WININET.@)
3775 * Queries for information about an HTTP request
3777 * RETURNS
3778 * TRUE on success
3779 * FALSE on failure
3782 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3783 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3785 http_request_t *request;
3786 DWORD res;
3788 if (TRACE_ON(wininet)) {
3789 #define FE(x) { x, #x }
3790 static const wininet_flag_info query_flags[] = {
3791 FE(HTTP_QUERY_MIME_VERSION),
3792 FE(HTTP_QUERY_CONTENT_TYPE),
3793 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
3794 FE(HTTP_QUERY_CONTENT_ID),
3795 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
3796 FE(HTTP_QUERY_CONTENT_LENGTH),
3797 FE(HTTP_QUERY_CONTENT_LANGUAGE),
3798 FE(HTTP_QUERY_ALLOW),
3799 FE(HTTP_QUERY_PUBLIC),
3800 FE(HTTP_QUERY_DATE),
3801 FE(HTTP_QUERY_EXPIRES),
3802 FE(HTTP_QUERY_LAST_MODIFIED),
3803 FE(HTTP_QUERY_MESSAGE_ID),
3804 FE(HTTP_QUERY_URI),
3805 FE(HTTP_QUERY_DERIVED_FROM),
3806 FE(HTTP_QUERY_COST),
3807 FE(HTTP_QUERY_LINK),
3808 FE(HTTP_QUERY_PRAGMA),
3809 FE(HTTP_QUERY_VERSION),
3810 FE(HTTP_QUERY_STATUS_CODE),
3811 FE(HTTP_QUERY_STATUS_TEXT),
3812 FE(HTTP_QUERY_RAW_HEADERS),
3813 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
3814 FE(HTTP_QUERY_CONNECTION),
3815 FE(HTTP_QUERY_ACCEPT),
3816 FE(HTTP_QUERY_ACCEPT_CHARSET),
3817 FE(HTTP_QUERY_ACCEPT_ENCODING),
3818 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
3819 FE(HTTP_QUERY_AUTHORIZATION),
3820 FE(HTTP_QUERY_CONTENT_ENCODING),
3821 FE(HTTP_QUERY_FORWARDED),
3822 FE(HTTP_QUERY_FROM),
3823 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
3824 FE(HTTP_QUERY_LOCATION),
3825 FE(HTTP_QUERY_ORIG_URI),
3826 FE(HTTP_QUERY_REFERER),
3827 FE(HTTP_QUERY_RETRY_AFTER),
3828 FE(HTTP_QUERY_SERVER),
3829 FE(HTTP_QUERY_TITLE),
3830 FE(HTTP_QUERY_USER_AGENT),
3831 FE(HTTP_QUERY_WWW_AUTHENTICATE),
3832 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
3833 FE(HTTP_QUERY_ACCEPT_RANGES),
3834 FE(HTTP_QUERY_SET_COOKIE),
3835 FE(HTTP_QUERY_COOKIE),
3836 FE(HTTP_QUERY_REQUEST_METHOD),
3837 FE(HTTP_QUERY_REFRESH),
3838 FE(HTTP_QUERY_CONTENT_DISPOSITION),
3839 FE(HTTP_QUERY_AGE),
3840 FE(HTTP_QUERY_CACHE_CONTROL),
3841 FE(HTTP_QUERY_CONTENT_BASE),
3842 FE(HTTP_QUERY_CONTENT_LOCATION),
3843 FE(HTTP_QUERY_CONTENT_MD5),
3844 FE(HTTP_QUERY_CONTENT_RANGE),
3845 FE(HTTP_QUERY_ETAG),
3846 FE(HTTP_QUERY_HOST),
3847 FE(HTTP_QUERY_IF_MATCH),
3848 FE(HTTP_QUERY_IF_NONE_MATCH),
3849 FE(HTTP_QUERY_IF_RANGE),
3850 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
3851 FE(HTTP_QUERY_MAX_FORWARDS),
3852 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
3853 FE(HTTP_QUERY_RANGE),
3854 FE(HTTP_QUERY_TRANSFER_ENCODING),
3855 FE(HTTP_QUERY_UPGRADE),
3856 FE(HTTP_QUERY_VARY),
3857 FE(HTTP_QUERY_VIA),
3858 FE(HTTP_QUERY_WARNING),
3859 FE(HTTP_QUERY_CUSTOM)
3861 static const wininet_flag_info modifier_flags[] = {
3862 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
3863 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
3864 FE(HTTP_QUERY_FLAG_NUMBER),
3865 FE(HTTP_QUERY_FLAG_COALESCE)
3867 #undef FE
3868 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
3869 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
3870 DWORD i;
3872 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, info);
3873 TRACE(" Attribute:");
3874 for (i = 0; i < ARRAY_SIZE(query_flags); i++) {
3875 if (query_flags[i].val == info) {
3876 TRACE(" %s", query_flags[i].name);
3877 break;
3880 if (i == ARRAY_SIZE(query_flags)) {
3881 TRACE(" Unknown (%08x)", info);
3884 TRACE(" Modifier:");
3885 for (i = 0; i < ARRAY_SIZE(modifier_flags); i++) {
3886 if (modifier_flags[i].val & info_mod) {
3887 TRACE(" %s", modifier_flags[i].name);
3888 info_mod &= ~ modifier_flags[i].val;
3892 if (info_mod) {
3893 TRACE(" Unknown (%08x)", info_mod);
3895 TRACE("\n");
3898 request = (http_request_t*) get_handle_object( hHttpRequest );
3899 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
3901 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3902 goto lend;
3905 if (lpBuffer == NULL)
3906 *lpdwBufferLength = 0;
3907 res = HTTP_HttpQueryInfoW( request, dwInfoLevel,
3908 lpBuffer, lpdwBufferLength, lpdwIndex);
3910 lend:
3911 if( request )
3912 WININET_Release( &request->hdr );
3914 TRACE("%u <--\n", res);
3915 if(res != ERROR_SUCCESS)
3916 SetLastError(res);
3917 return res == ERROR_SUCCESS;
3920 /***********************************************************************
3921 * HttpQueryInfoA (WININET.@)
3923 * Queries for information about an HTTP request
3925 * RETURNS
3926 * TRUE on success
3927 * FALSE on failure
3930 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3931 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3933 BOOL result;
3934 DWORD len;
3935 WCHAR* bufferW;
3937 TRACE("%p %x\n", hHttpRequest, dwInfoLevel);
3939 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
3940 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
3942 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
3943 lpdwBufferLength, lpdwIndex );
3946 if (lpBuffer)
3948 DWORD alloclen;
3949 len = (*lpdwBufferLength)*sizeof(WCHAR);
3950 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3952 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
3953 if (alloclen < len)
3954 alloclen = len;
3956 else
3957 alloclen = len;
3958 bufferW = heap_alloc(alloclen);
3959 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3960 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3961 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
3962 } else
3964 bufferW = NULL;
3965 len = 0;
3968 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
3969 &len, lpdwIndex );
3970 if( result )
3972 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
3973 lpBuffer, *lpdwBufferLength, NULL, NULL );
3974 *lpdwBufferLength = len - 1;
3976 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
3978 else
3979 /* since the strings being returned from HttpQueryInfoW should be
3980 * only ASCII characters, it is reasonable to assume that all of
3981 * the Unicode characters can be reduced to a single byte */
3982 *lpdwBufferLength = len / sizeof(WCHAR);
3984 heap_free( bufferW );
3985 return result;
3988 static WCHAR *get_redirect_url(http_request_t *request)
3990 static WCHAR szHttp[] = {'h','t','t','p',0};
3991 static WCHAR szHttps[] = {'h','t','t','p','s',0};
3992 http_session_t *session = request->session;
3993 URL_COMPONENTSW urlComponents = { sizeof(urlComponents) };
3994 WCHAR *orig_url = NULL, *redirect_url = NULL, *combined_url = NULL;
3995 DWORD url_length = 0, res;
3996 BOOL b;
3998 url_length = 0;
3999 res = HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, redirect_url, &url_length, NULL);
4000 if(res == ERROR_INSUFFICIENT_BUFFER) {
4001 redirect_url = heap_alloc(url_length);
4002 res = HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, redirect_url, &url_length, NULL);
4004 if(res != ERROR_SUCCESS) {
4005 heap_free(redirect_url);
4006 return NULL;
4009 urlComponents.dwSchemeLength = 1;
4010 b = InternetCrackUrlW(redirect_url, url_length / sizeof(WCHAR), 0, &urlComponents);
4011 if(b && urlComponents.dwSchemeLength &&
4012 urlComponents.nScheme != INTERNET_SCHEME_HTTP && urlComponents.nScheme != INTERNET_SCHEME_HTTPS) {
4013 TRACE("redirect to non-http URL\n");
4014 return NULL;
4017 urlComponents.lpszScheme = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
4018 urlComponents.dwSchemeLength = 0;
4019 urlComponents.lpszHostName = request->server->name;
4020 urlComponents.nPort = request->server->port;
4021 urlComponents.lpszUserName = session->userName;
4022 urlComponents.lpszUrlPath = request->path;
4024 b = InternetCreateUrlW(&urlComponents, 0, NULL, &url_length);
4025 if(!b && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
4026 orig_url = heap_alloc(url_length);
4028 /* convert from bytes to characters */
4029 url_length = url_length / sizeof(WCHAR) - 1;
4030 b = InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length);
4033 if(b) {
4034 url_length = 0;
4035 b = InternetCombineUrlW(orig_url, redirect_url, NULL, &url_length, ICU_ENCODE_SPACES_ONLY);
4036 if(!b && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
4037 combined_url = heap_alloc(url_length * sizeof(WCHAR));
4038 b = InternetCombineUrlW(orig_url, redirect_url, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY);
4039 if(!b) {
4040 heap_free(combined_url);
4041 combined_url = NULL;
4046 heap_free(orig_url);
4047 heap_free(redirect_url);
4048 return combined_url;
4052 /***********************************************************************
4053 * HTTP_HandleRedirect (internal)
4055 static DWORD HTTP_HandleRedirect(http_request_t *request, WCHAR *url)
4057 URL_COMPONENTSW urlComponents = { sizeof(urlComponents) };
4058 http_session_t *session = request->session;
4059 size_t url_len = strlenW(url);
4061 if(url[0] == '/')
4063 /* if it's an absolute path, keep the same session info */
4064 urlComponents.lpszUrlPath = url;
4065 urlComponents.dwUrlPathLength = url_len;
4067 else
4069 urlComponents.dwHostNameLength = 1;
4070 urlComponents.dwUserNameLength = 1;
4071 urlComponents.dwUrlPathLength = 1;
4072 if(!InternetCrackUrlW(url, url_len, 0, &urlComponents))
4073 return INTERNET_GetLastError();
4075 if(!urlComponents.dwHostNameLength)
4076 return ERROR_INTERNET_INVALID_URL;
4079 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
4080 url, (url_len + 1) * sizeof(WCHAR));
4082 if(urlComponents.dwHostNameLength) {
4083 BOOL custom_port = FALSE;
4084 substr_t host;
4086 if(urlComponents.nScheme == INTERNET_SCHEME_HTTP) {
4087 if(request->hdr.dwFlags & INTERNET_FLAG_SECURE) {
4088 TRACE("redirect from secure page to non-secure page\n");
4089 /* FIXME: warn about from secure redirect to non-secure page */
4090 request->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
4093 custom_port = urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT;
4094 }else if(urlComponents.nScheme == INTERNET_SCHEME_HTTPS) {
4095 if(!(request->hdr.dwFlags & INTERNET_FLAG_SECURE)) {
4096 TRACE("redirect from non-secure page to secure page\n");
4097 /* FIXME: notify about redirect to secure page */
4098 request->hdr.dwFlags |= INTERNET_FLAG_SECURE;
4101 custom_port = urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT;
4104 heap_free(session->hostName);
4106 session->hostName = heap_strndupW(urlComponents.lpszHostName, urlComponents.dwHostNameLength);
4107 session->hostPort = urlComponents.nPort;
4109 heap_free(session->userName);
4110 session->userName = NULL;
4111 if (urlComponents.dwUserNameLength)
4112 session->userName = heap_strndupW(urlComponents.lpszUserName, urlComponents.dwUserNameLength);
4114 reset_data_stream(request);
4116 host = substr(urlComponents.lpszHostName, urlComponents.dwHostNameLength);
4118 if(host.len != strlenW(request->server->name) || strncmpiW(request->server->name, host.str, host.len)
4119 || request->server->port != urlComponents.nPort) {
4120 server_t *new_server;
4122 new_server = get_server(host, urlComponents.nPort, urlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
4123 server_release(request->server);
4124 request->server = new_server;
4127 if (custom_port)
4128 HTTP_ProcessHeader(request, hostW, request->server->host_port, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4129 else
4130 HTTP_ProcessHeader(request, hostW, request->server->name, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4133 heap_free(request->path);
4134 request->path = NULL;
4135 if(urlComponents.dwUrlPathLength)
4137 DWORD needed = 1;
4138 HRESULT rc;
4139 WCHAR dummy = 0;
4140 WCHAR *path;
4142 path = heap_strndupW(urlComponents.lpszUrlPath, urlComponents.dwUrlPathLength);
4143 rc = UrlEscapeW(path, &dummy, &needed, URL_ESCAPE_SPACES_ONLY);
4144 if (rc != E_POINTER)
4145 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4146 request->path = heap_alloc(needed*sizeof(WCHAR));
4147 rc = UrlEscapeW(path, request->path, &needed,
4148 URL_ESCAPE_SPACES_ONLY);
4149 if (rc != S_OK)
4151 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4152 strcpyW(request->path, path);
4154 heap_free(path);
4157 /* Remove custom content-type/length headers on redirects. */
4158 remove_header(request, szContent_Type, TRUE);
4159 remove_header(request, szContent_Length, TRUE);
4161 return ERROR_SUCCESS;
4164 /***********************************************************************
4165 * HTTP_build_req (internal)
4167 * concatenate all the strings in the request together
4169 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
4171 LPCWSTR *t;
4172 LPWSTR str;
4174 for( t = list; *t ; t++ )
4175 len += strlenW( *t );
4176 len++;
4178 str = heap_alloc(len*sizeof(WCHAR));
4179 *str = 0;
4181 for( t = list; *t ; t++ )
4182 strcatW( str, *t );
4184 return str;
4187 static void HTTP_InsertCookies(http_request_t *request)
4189 WCHAR *cookies;
4190 DWORD res;
4192 res = get_cookie_header(request->server->name, request->path, &cookies);
4193 if(res != ERROR_SUCCESS || !cookies)
4194 return;
4196 HTTP_HttpAddRequestHeadersW(request, cookies, strlenW(cookies),
4197 HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
4198 heap_free(cookies);
4201 static WORD HTTP_ParseWkday(LPCWSTR day)
4203 static const WCHAR days[7][4] = {{ 's','u','n',0 },
4204 { 'm','o','n',0 },
4205 { 't','u','e',0 },
4206 { 'w','e','d',0 },
4207 { 't','h','u',0 },
4208 { 'f','r','i',0 },
4209 { 's','a','t',0 }};
4210 unsigned int i;
4211 for (i = 0; i < ARRAY_SIZE(days); i++)
4212 if (!strcmpiW(day, days[i]))
4213 return i;
4215 /* Invalid */
4216 return 7;
4219 static WORD HTTP_ParseMonth(LPCWSTR month)
4221 static const WCHAR jan[] = { 'j','a','n',0 };
4222 static const WCHAR feb[] = { 'f','e','b',0 };
4223 static const WCHAR mar[] = { 'm','a','r',0 };
4224 static const WCHAR apr[] = { 'a','p','r',0 };
4225 static const WCHAR may[] = { 'm','a','y',0 };
4226 static const WCHAR jun[] = { 'j','u','n',0 };
4227 static const WCHAR jul[] = { 'j','u','l',0 };
4228 static const WCHAR aug[] = { 'a','u','g',0 };
4229 static const WCHAR sep[] = { 's','e','p',0 };
4230 static const WCHAR oct[] = { 'o','c','t',0 };
4231 static const WCHAR nov[] = { 'n','o','v',0 };
4232 static const WCHAR dec[] = { 'd','e','c',0 };
4234 if (!strcmpiW(month, jan)) return 1;
4235 if (!strcmpiW(month, feb)) return 2;
4236 if (!strcmpiW(month, mar)) return 3;
4237 if (!strcmpiW(month, apr)) return 4;
4238 if (!strcmpiW(month, may)) return 5;
4239 if (!strcmpiW(month, jun)) return 6;
4240 if (!strcmpiW(month, jul)) return 7;
4241 if (!strcmpiW(month, aug)) return 8;
4242 if (!strcmpiW(month, sep)) return 9;
4243 if (!strcmpiW(month, oct)) return 10;
4244 if (!strcmpiW(month, nov)) return 11;
4245 if (!strcmpiW(month, dec)) return 12;
4246 /* Invalid */
4247 return 0;
4250 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4251 * optionally preceded by whitespace.
4252 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4253 * st, and sets *str to the first character after the time format.
4255 static BOOL HTTP_ParseTime(SYSTEMTIME *st, LPCWSTR *str)
4257 LPCWSTR ptr = *str;
4258 WCHAR *nextPtr;
4259 unsigned long num;
4261 while (isspaceW(*ptr))
4262 ptr++;
4264 num = strtoulW(ptr, &nextPtr, 10);
4265 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4267 ERR("unexpected time format %s\n", debugstr_w(ptr));
4268 return FALSE;
4270 if (num > 23)
4272 ERR("unexpected hour in time format %s\n", debugstr_w(ptr));
4273 return FALSE;
4275 ptr = nextPtr + 1;
4276 st->wHour = (WORD)num;
4277 num = strtoulW(ptr, &nextPtr, 10);
4278 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4280 ERR("unexpected time format %s\n", debugstr_w(ptr));
4281 return FALSE;
4283 if (num > 59)
4285 ERR("unexpected minute in time format %s\n", debugstr_w(ptr));
4286 return FALSE;
4288 ptr = nextPtr + 1;
4289 st->wMinute = (WORD)num;
4290 num = strtoulW(ptr, &nextPtr, 10);
4291 if (!nextPtr || nextPtr <= ptr)
4293 ERR("unexpected time format %s\n", debugstr_w(ptr));
4294 return FALSE;
4296 if (num > 59)
4298 ERR("unexpected second in time format %s\n", debugstr_w(ptr));
4299 return FALSE;
4301 ptr = nextPtr + 1;
4302 *str = ptr;
4303 st->wSecond = (WORD)num;
4304 return TRUE;
4307 static BOOL HTTP_ParseDateAsAsctime(LPCWSTR value, FILETIME *ft)
4309 static const WCHAR gmt[]= { 'G','M','T',0 };
4310 WCHAR day[4], *dayPtr, month[4], *monthPtr, *nextPtr;
4311 LPCWSTR ptr;
4312 SYSTEMTIME st = { 0 };
4313 unsigned long num;
4315 for (ptr = value, dayPtr = day; *ptr && !isspaceW(*ptr) &&
4316 dayPtr - day < ARRAY_SIZE(day) - 1; ptr++, dayPtr++)
4317 *dayPtr = *ptr;
4318 *dayPtr = 0;
4319 st.wDayOfWeek = HTTP_ParseWkday(day);
4320 if (st.wDayOfWeek >= 7)
4322 ERR("unexpected weekday %s\n", debugstr_w(day));
4323 return FALSE;
4326 while (isspaceW(*ptr))
4327 ptr++;
4329 for (monthPtr = month; !isspaceW(*ptr) && monthPtr - month < ARRAY_SIZE(month) - 1;
4330 monthPtr++, ptr++)
4331 *monthPtr = *ptr;
4332 *monthPtr = 0;
4333 st.wMonth = HTTP_ParseMonth(month);
4334 if (!st.wMonth || st.wMonth > 12)
4336 ERR("unexpected month %s\n", debugstr_w(month));
4337 return FALSE;
4340 while (isspaceW(*ptr))
4341 ptr++;
4343 num = strtoulW(ptr, &nextPtr, 10);
4344 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4346 ERR("unexpected day %s\n", debugstr_w(ptr));
4347 return FALSE;
4349 ptr = nextPtr;
4350 st.wDay = (WORD)num;
4352 while (isspaceW(*ptr))
4353 ptr++;
4355 if (!HTTP_ParseTime(&st, &ptr))
4356 return FALSE;
4358 while (isspaceW(*ptr))
4359 ptr++;
4361 num = strtoulW(ptr, &nextPtr, 10);
4362 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4364 ERR("unexpected year %s\n", debugstr_w(ptr));
4365 return FALSE;
4367 ptr = nextPtr;
4368 st.wYear = (WORD)num;
4370 while (isspaceW(*ptr))
4371 ptr++;
4373 /* asctime() doesn't report a timezone, but some web servers do, so accept
4374 * with or without GMT.
4376 if (*ptr && strcmpW(ptr, gmt))
4378 ERR("unexpected timezone %s\n", debugstr_w(ptr));
4379 return FALSE;
4381 return SystemTimeToFileTime(&st, ft);
4384 static BOOL HTTP_ParseRfc1123Date(LPCWSTR value, FILETIME *ft)
4386 static const WCHAR gmt[]= { 'G','M','T',0 };
4387 WCHAR *nextPtr, day[4], month[4], *monthPtr;
4388 LPCWSTR ptr;
4389 unsigned long num;
4390 SYSTEMTIME st = { 0 };
4392 ptr = strchrW(value, ',');
4393 if (!ptr)
4394 return FALSE;
4395 if (ptr - value != 3)
4397 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4398 return FALSE;
4400 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4401 day[3] = 0;
4402 st.wDayOfWeek = HTTP_ParseWkday(day);
4403 if (st.wDayOfWeek > 6)
4405 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4406 return FALSE;
4408 ptr++;
4410 while (isspaceW(*ptr))
4411 ptr++;
4413 num = strtoulW(ptr, &nextPtr, 10);
4414 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4416 WARN("unexpected day %s\n", debugstr_w(value));
4417 return FALSE;
4419 ptr = nextPtr;
4420 st.wDay = (WORD)num;
4422 while (isspaceW(*ptr))
4423 ptr++;
4425 for (monthPtr = month; !isspaceW(*ptr) && monthPtr - month < ARRAY_SIZE(month) - 1;
4426 monthPtr++, ptr++)
4427 *monthPtr = *ptr;
4428 *monthPtr = 0;
4429 st.wMonth = HTTP_ParseMonth(month);
4430 if (!st.wMonth || st.wMonth > 12)
4432 WARN("unexpected month %s\n", debugstr_w(month));
4433 return FALSE;
4436 while (isspaceW(*ptr))
4437 ptr++;
4439 num = strtoulW(ptr, &nextPtr, 10);
4440 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4442 ERR("unexpected year %s\n", debugstr_w(value));
4443 return FALSE;
4445 ptr = nextPtr;
4446 st.wYear = (WORD)num;
4448 if (!HTTP_ParseTime(&st, &ptr))
4449 return FALSE;
4451 while (isspaceW(*ptr))
4452 ptr++;
4454 if (strcmpW(ptr, gmt))
4456 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4457 return FALSE;
4459 return SystemTimeToFileTime(&st, ft);
4462 static WORD HTTP_ParseWeekday(LPCWSTR day)
4464 static const WCHAR days[7][10] = {{ 's','u','n','d','a','y',0 },
4465 { 'm','o','n','d','a','y',0 },
4466 { 't','u','e','s','d','a','y',0 },
4467 { 'w','e','d','n','e','s','d','a','y',0 },
4468 { 't','h','u','r','s','d','a','y',0 },
4469 { 'f','r','i','d','a','y',0 },
4470 { 's','a','t','u','r','d','a','y',0 }};
4471 unsigned int i;
4472 for (i = 0; i < ARRAY_SIZE(days); i++)
4473 if (!strcmpiW(day, days[i]))
4474 return i;
4476 /* Invalid */
4477 return 7;
4480 static BOOL HTTP_ParseRfc850Date(LPCWSTR value, FILETIME *ft)
4482 static const WCHAR gmt[]= { 'G','M','T',0 };
4483 WCHAR *nextPtr, day[10], month[4], *monthPtr;
4484 LPCWSTR ptr;
4485 unsigned long num;
4486 SYSTEMTIME st = { 0 };
4488 ptr = strchrW(value, ',');
4489 if (!ptr)
4490 return FALSE;
4491 if (ptr - value == 3)
4493 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4494 day[3] = 0;
4495 st.wDayOfWeek = HTTP_ParseWkday(day);
4496 if (st.wDayOfWeek > 6)
4498 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4499 return FALSE;
4502 else if (ptr - value < ARRAY_SIZE(day))
4504 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4505 day[ptr - value + 1] = 0;
4506 st.wDayOfWeek = HTTP_ParseWeekday(day);
4507 if (st.wDayOfWeek > 6)
4509 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4510 return FALSE;
4513 else
4515 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4516 return FALSE;
4518 ptr++;
4520 while (isspaceW(*ptr))
4521 ptr++;
4523 num = strtoulW(ptr, &nextPtr, 10);
4524 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4526 ERR("unexpected day %s\n", debugstr_w(value));
4527 return FALSE;
4529 ptr = nextPtr;
4530 st.wDay = (WORD)num;
4532 if (*ptr != '-')
4534 ERR("unexpected month format %s\n", debugstr_w(ptr));
4535 return FALSE;
4537 ptr++;
4539 for (monthPtr = month; *ptr != '-' && monthPtr - month < ARRAY_SIZE(month) - 1;
4540 monthPtr++, ptr++)
4541 *monthPtr = *ptr;
4542 *monthPtr = 0;
4543 st.wMonth = HTTP_ParseMonth(month);
4544 if (!st.wMonth || st.wMonth > 12)
4546 ERR("unexpected month %s\n", debugstr_w(month));
4547 return FALSE;
4550 if (*ptr != '-')
4552 ERR("unexpected year format %s\n", debugstr_w(ptr));
4553 return FALSE;
4555 ptr++;
4557 num = strtoulW(ptr, &nextPtr, 10);
4558 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4560 ERR("unexpected year %s\n", debugstr_w(value));
4561 return FALSE;
4563 ptr = nextPtr;
4564 st.wYear = (WORD)num;
4566 if (!HTTP_ParseTime(&st, &ptr))
4567 return FALSE;
4569 while (isspaceW(*ptr))
4570 ptr++;
4572 if (strcmpW(ptr, gmt))
4574 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4575 return FALSE;
4577 return SystemTimeToFileTime(&st, ft);
4580 static BOOL HTTP_ParseDate(LPCWSTR value, FILETIME *ft)
4582 static const WCHAR zero[] = { '0',0 };
4583 BOOL ret;
4585 if (!strcmpW(value, zero))
4587 ft->dwLowDateTime = ft->dwHighDateTime = 0;
4588 ret = TRUE;
4590 else if (strchrW(value, ','))
4592 ret = HTTP_ParseRfc1123Date(value, ft);
4593 if (!ret)
4595 ret = HTTP_ParseRfc850Date(value, ft);
4596 if (!ret)
4597 ERR("unexpected date format %s\n", debugstr_w(value));
4600 else
4602 ret = HTTP_ParseDateAsAsctime(value, ft);
4603 if (!ret)
4604 ERR("unexpected date format %s\n", debugstr_w(value));
4606 return ret;
4609 static void HTTP_ProcessExpires(http_request_t *request)
4611 BOOL expirationFound = FALSE;
4612 int headerIndex;
4614 EnterCriticalSection( &request->headers_section );
4616 /* Look for a Cache-Control header with a max-age directive, as it takes
4617 * precedence over the Expires header.
4619 headerIndex = HTTP_GetCustomHeaderIndex(request, szCache_Control, 0, FALSE);
4620 if (headerIndex != -1)
4622 LPHTTPHEADERW ccHeader = &request->custHeaders[headerIndex];
4623 LPWSTR ptr;
4625 for (ptr = ccHeader->lpszValue; ptr && *ptr; )
4627 LPWSTR comma = strchrW(ptr, ','), end, equal;
4629 if (comma)
4630 end = comma;
4631 else
4632 end = ptr + strlenW(ptr);
4633 for (equal = end - 1; equal > ptr && *equal != '='; equal--)
4635 if (*equal == '=')
4637 static const WCHAR max_age[] = {
4638 'm','a','x','-','a','g','e',0 };
4640 if (!strncmpiW(ptr, max_age, equal - ptr - 1))
4642 LPWSTR nextPtr;
4643 unsigned long age;
4645 age = strtoulW(equal + 1, &nextPtr, 10);
4646 if (nextPtr > equal + 1)
4648 LARGE_INTEGER ft;
4650 NtQuerySystemTime( &ft );
4651 /* Age is in seconds, FILETIME resolution is in
4652 * 100 nanosecond intervals.
4654 ft.QuadPart += age * (ULONGLONG)1000000;
4655 request->expires.dwLowDateTime = ft.u.LowPart;
4656 request->expires.dwHighDateTime = ft.u.HighPart;
4657 expirationFound = TRUE;
4661 if (comma)
4663 ptr = comma + 1;
4664 while (isspaceW(*ptr))
4665 ptr++;
4667 else
4668 ptr = NULL;
4671 if (!expirationFound)
4673 headerIndex = HTTP_GetCustomHeaderIndex(request, szExpires, 0, FALSE);
4674 if (headerIndex != -1)
4676 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4677 FILETIME ft;
4679 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4681 expirationFound = TRUE;
4682 request->expires = ft;
4686 if (!expirationFound)
4688 LARGE_INTEGER t;
4690 /* With no known age, default to 10 minutes until expiration. */
4691 NtQuerySystemTime( &t );
4692 t.QuadPart += 10 * 60 * (ULONGLONG)10000000;
4693 request->expires.dwLowDateTime = t.u.LowPart;
4694 request->expires.dwHighDateTime = t.u.HighPart;
4697 LeaveCriticalSection( &request->headers_section );
4700 static void HTTP_ProcessLastModified(http_request_t *request)
4702 int headerIndex;
4704 EnterCriticalSection( &request->headers_section );
4706 headerIndex = HTTP_GetCustomHeaderIndex(request, szLast_Modified, 0, FALSE);
4707 if (headerIndex != -1)
4709 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4710 FILETIME ft;
4712 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4713 request->last_modified = ft;
4716 LeaveCriticalSection( &request->headers_section );
4719 static void http_process_keep_alive(http_request_t *req)
4721 int index;
4723 EnterCriticalSection( &req->headers_section );
4725 if ((index = HTTP_GetCustomHeaderIndex(req, szConnection, 0, FALSE)) != -1)
4726 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4727 else if ((index = HTTP_GetCustomHeaderIndex(req, szProxy_Connection, 0, FALSE)) != -1)
4728 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4729 else
4730 req->netconn->keep_alive = !strcmpiW(req->version, g_szHttp1_1);
4732 LeaveCriticalSection( &req->headers_section );
4735 static DWORD open_http_connection(http_request_t *request, BOOL *reusing)
4737 netconn_t *netconn = NULL;
4738 DWORD res;
4740 if (request->netconn)
4742 if (NETCON_is_alive(request->netconn) && drain_content(request, TRUE) == ERROR_SUCCESS)
4744 reset_data_stream(request);
4745 *reusing = TRUE;
4746 return ERROR_SUCCESS;
4749 TRACE("freeing netconn\n");
4750 free_netconn(request->netconn);
4751 request->netconn = NULL;
4754 reset_data_stream(request);
4756 res = HTTP_ResolveName(request);
4757 if(res != ERROR_SUCCESS)
4758 return res;
4760 EnterCriticalSection(&connection_pool_cs);
4762 while(!list_empty(&request->server->conn_pool)) {
4763 netconn = LIST_ENTRY(list_head(&request->server->conn_pool), netconn_t, pool_entry);
4764 list_remove(&netconn->pool_entry);
4766 if(is_valid_netconn(netconn) && NETCON_is_alive(netconn))
4767 break;
4769 TRACE("connection %p closed during idle\n", netconn);
4770 free_netconn(netconn);
4771 netconn = NULL;
4774 LeaveCriticalSection(&connection_pool_cs);
4776 if(netconn) {
4777 TRACE("<-- reusing %p netconn\n", netconn);
4778 request->netconn = netconn;
4779 *reusing = TRUE;
4780 return ERROR_SUCCESS;
4783 TRACE("connecting to %s, proxy %s\n", debugstr_w(request->server->name),
4784 request->proxy ? debugstr_w(request->proxy->name) : "(null)");
4786 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4787 INTERNET_STATUS_CONNECTING_TO_SERVER,
4788 request->server->addr_str,
4789 strlen(request->server->addr_str)+1);
4791 res = create_netconn(request->proxy ? request->proxy : request->server, request->security_flags,
4792 (request->hdr.ErrorMask & INTERNET_ERROR_MASK_COMBINED_SEC_CERT) != 0,
4793 request->connect_timeout, &netconn);
4794 if(res != ERROR_SUCCESS) {
4795 ERR("create_netconn failed: %u\n", res);
4796 return res;
4799 request->netconn = netconn;
4801 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4802 INTERNET_STATUS_CONNECTED_TO_SERVER,
4803 request->server->addr_str, strlen(request->server->addr_str)+1);
4805 *reusing = FALSE;
4806 TRACE("Created connection to %s: %p\n", debugstr_w(request->server->name), netconn);
4807 return ERROR_SUCCESS;
4810 static char *build_ascii_request( const WCHAR *str, void *data, DWORD data_len, DWORD *out_len )
4812 int len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
4813 char *ret;
4815 if (!(ret = heap_alloc( len + data_len ))) return NULL;
4816 WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
4817 if (data_len) memcpy( ret + len - 1, data, data_len );
4818 *out_len = len + data_len - 1;
4819 ret[*out_len] = 0;
4820 return ret;
4823 static void set_content_length_header( http_request_t *request, DWORD len, DWORD flags )
4825 static const WCHAR fmtW[] =
4826 {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','u','\r','\n',0};
4827 WCHAR buf[ARRAY_SIZE(fmtW) + 10];
4829 sprintfW( buf, fmtW, len );
4830 HTTP_HttpAddRequestHeadersW( request, buf, ~0u, flags );
4833 /***********************************************************************
4834 * HTTP_HttpSendRequestW (internal)
4836 * Sends the specified request to the HTTP server
4838 * RETURNS
4839 * ERROR_SUCCESS on success
4840 * win32 error code on failure
4843 static DWORD HTTP_HttpSendRequestW(http_request_t *request, LPCWSTR lpszHeaders,
4844 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
4845 DWORD dwContentLength, BOOL bEndRequest)
4847 BOOL redirected = FALSE, secure_proxy_connect = FALSE, loop_next;
4848 WCHAR *request_header = NULL;
4849 INT responseLen, cnt;
4850 DWORD res;
4852 TRACE("--> %p\n", request);
4854 assert(request->hdr.htype == WH_HHTTPREQ);
4856 /* if the verb is NULL default to GET */
4857 if (!request->verb)
4858 request->verb = heap_strdupW(szGET);
4860 HTTP_ProcessHeader(request, hostW, request->server->canon_host_port,
4861 HTTP_ADDREQ_FLAG_ADD_IF_NEW | HTTP_ADDHDR_FLAG_REQ);
4863 if (dwContentLength || strcmpW(request->verb, szGET))
4865 set_content_length_header(request, dwContentLength, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4866 request->bytesToWrite = dwContentLength;
4868 if (request->session->appInfo->agent)
4870 WCHAR *agent_header;
4871 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4872 int len;
4874 len = strlenW(request->session->appInfo->agent) + strlenW(user_agent);
4875 agent_header = heap_alloc(len * sizeof(WCHAR));
4876 sprintfW(agent_header, user_agent, request->session->appInfo->agent);
4878 HTTP_HttpAddRequestHeadersW(request, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4879 heap_free(agent_header);
4881 if (request->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
4883 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4884 HTTP_HttpAddRequestHeadersW(request, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4886 if ((request->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && strcmpW(request->verb, szGET))
4888 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4889 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4890 HTTP_HttpAddRequestHeadersW(request, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4893 /* add the headers the caller supplied */
4894 if( lpszHeaders && dwHeaderLength )
4895 HTTP_HttpAddRequestHeadersW(request, lpszHeaders, dwHeaderLength, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
4899 DWORD len, data_len = dwOptionalLength;
4900 BOOL reusing_connection;
4901 char *ascii_req;
4903 loop_next = FALSE;
4905 if(redirected) {
4906 request->contentLength = ~0u;
4907 request->bytesToWrite = 0;
4910 if (TRACE_ON(wininet))
4912 HTTPHEADERW *host;
4914 EnterCriticalSection( &request->headers_section );
4915 host = HTTP_GetHeader( request, hostW );
4916 TRACE("Going to url %s %s\n", debugstr_w(host->lpszValue), debugstr_w(request->path));
4917 LeaveCriticalSection( &request->headers_section );
4920 HTTP_FixURL(request);
4921 if (request->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
4923 HTTP_ProcessHeader(request, szConnection, szKeepAlive,
4924 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD);
4926 HTTP_InsertAuthorization(request, request->authInfo, szAuthorization);
4927 HTTP_InsertAuthorization(request, request->proxyAuthInfo, szProxy_Authorization);
4929 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
4930 HTTP_InsertCookies(request);
4932 res = open_http_connection(request, &reusing_connection);
4933 if (res != ERROR_SUCCESS)
4934 break;
4936 if (!reusing_connection && (request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4938 if (request->proxy) secure_proxy_connect = TRUE;
4939 else
4941 res = NETCON_secure_connect(request->netconn, request->server);
4942 if (res != ERROR_SUCCESS)
4944 WARN("failed to upgrade to secure connection\n");
4945 http_release_netconn(request, FALSE);
4946 break;
4950 if (secure_proxy_connect)
4952 static const WCHAR connectW[] = {'C','O','N','N','E','C','T',0};
4953 const WCHAR *target = request->server->host_port;
4955 if (HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE) >= 0)
4956 set_content_length_header(request, 0, HTTP_ADDREQ_FLAG_REPLACE);
4958 request_header = build_request_header(request, connectW, target, g_szHttp1_1, TRUE);
4960 else if (request->proxy && !(request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4962 WCHAR *url = build_proxy_path_url(request);
4963 request_header = build_request_header(request, request->verb, url, request->version, TRUE);
4964 heap_free(url);
4966 else
4968 if (request->proxy && HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE) >= 0)
4969 set_content_length_header(request, dwContentLength, HTTP_ADDREQ_FLAG_REPLACE);
4971 request_header = build_request_header(request, request->verb, request->path, request->version, TRUE);
4974 TRACE("Request header -> %s\n", debugstr_w(request_header) );
4976 /* send the request as ASCII, tack on the optional data */
4977 if (!lpOptional || redirected || secure_proxy_connect)
4978 data_len = 0;
4980 ascii_req = build_ascii_request(request_header, lpOptional, data_len, &len);
4981 heap_free(request_header);
4982 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
4984 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4985 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
4987 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
4988 res = NETCON_send(request->netconn, ascii_req, len, 0, &cnt);
4989 heap_free( ascii_req );
4990 if(res != ERROR_SUCCESS) {
4991 TRACE("send failed: %u\n", res);
4992 if(!reusing_connection)
4993 break;
4994 http_release_netconn(request, FALSE);
4995 loop_next = TRUE;
4996 continue;
4999 request->bytesWritten = data_len;
5001 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5002 INTERNET_STATUS_REQUEST_SENT,
5003 &len, sizeof(DWORD));
5005 if (bEndRequest)
5007 DWORD dwBufferSize;
5009 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5010 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5012 if (HTTP_GetResponseHeaders(request, &responseLen))
5014 http_release_netconn(request, FALSE);
5015 res = ERROR_INTERNET_CONNECTION_ABORTED;
5016 goto lend;
5018 /* FIXME: We should know that connection is closed before sending
5019 * headers. Otherwise wrong callbacks are executed */
5020 if(!responseLen && reusing_connection) {
5021 TRACE("Connection closed by server, reconnecting\n");
5022 http_release_netconn(request, FALSE);
5023 loop_next = TRUE;
5024 continue;
5027 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5028 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
5029 sizeof(DWORD));
5031 http_process_keep_alive(request);
5032 HTTP_ProcessCookies(request);
5033 HTTP_ProcessExpires(request);
5034 HTTP_ProcessLastModified(request);
5036 res = set_content_length(request);
5037 if(res != ERROR_SUCCESS)
5038 goto lend;
5039 if(!request->contentLength && !secure_proxy_connect)
5040 http_release_netconn(request, TRUE);
5042 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
5044 WCHAR *new_url;
5046 switch(request->status_code) {
5047 case HTTP_STATUS_REDIRECT:
5048 case HTTP_STATUS_MOVED:
5049 case HTTP_STATUS_REDIRECT_KEEP_VERB:
5050 case HTTP_STATUS_REDIRECT_METHOD:
5051 new_url = get_redirect_url(request);
5052 if(!new_url)
5053 break;
5055 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5056 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5058 heap_free(request->verb);
5059 request->verb = heap_strdupW(szGET);
5061 http_release_netconn(request, drain_content(request, FALSE) == ERROR_SUCCESS);
5062 res = HTTP_HandleRedirect(request, new_url);
5063 heap_free(new_url);
5064 if (res == ERROR_SUCCESS)
5065 loop_next = TRUE;
5066 redirected = TRUE;
5069 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
5071 WCHAR szAuthValue[2048];
5072 dwBufferSize=2048;
5073 if (request->status_code == HTTP_STATUS_DENIED)
5075 WCHAR *host = heap_strdupW( request->server->canon_host_port );
5076 DWORD dwIndex = 0;
5077 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5079 if (HTTP_DoAuthorization(request, szAuthValue,
5080 &request->authInfo,
5081 request->session->userName,
5082 request->session->password, host))
5084 if (drain_content(request, TRUE) != ERROR_SUCCESS)
5086 FIXME("Could not drain content\n");
5087 http_release_netconn(request, FALSE);
5089 loop_next = TRUE;
5090 break;
5093 heap_free( host );
5095 if(!loop_next) {
5096 TRACE("Cleaning wrong authorization data\n");
5097 destroy_authinfo(request->authInfo);
5098 request->authInfo = NULL;
5101 if (request->status_code == HTTP_STATUS_PROXY_AUTH_REQ)
5103 DWORD dwIndex = 0;
5104 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5106 if (HTTP_DoAuthorization(request, szAuthValue,
5107 &request->proxyAuthInfo,
5108 request->session->appInfo->proxyUsername,
5109 request->session->appInfo->proxyPassword,
5110 NULL))
5112 if (drain_content(request, TRUE) != ERROR_SUCCESS)
5114 FIXME("Could not drain content\n");
5115 http_release_netconn(request, FALSE);
5117 loop_next = TRUE;
5118 break;
5122 if(!loop_next) {
5123 TRACE("Cleaning wrong proxy authorization data\n");
5124 destroy_authinfo(request->proxyAuthInfo);
5125 request->proxyAuthInfo = NULL;
5129 if (secure_proxy_connect && request->status_code == HTTP_STATUS_OK)
5131 res = NETCON_secure_connect(request->netconn, request->server);
5132 if (res != ERROR_SUCCESS)
5134 WARN("failed to upgrade to secure proxy connection\n");
5135 http_release_netconn( request, FALSE );
5136 break;
5138 remove_header(request, szProxy_Authorization, TRUE);
5139 destroy_authinfo(request->proxyAuthInfo);
5140 request->proxyAuthInfo = NULL;
5141 request->contentLength = 0;
5142 request->netconn_stream.content_length = 0;
5144 secure_proxy_connect = FALSE;
5145 loop_next = TRUE;
5148 else
5149 res = ERROR_SUCCESS;
5151 while (loop_next);
5153 lend:
5154 /* TODO: send notification for P3P header */
5156 if(res == ERROR_SUCCESS)
5157 create_cache_entry(request);
5159 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5161 if (res == ERROR_SUCCESS) {
5162 if(bEndRequest && request->contentLength && request->bytesWritten == request->bytesToWrite)
5163 HTTP_ReceiveRequestData(request);
5164 else
5165 send_request_complete(request,
5166 request->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)request->hdr.hInternet : 1, 0);
5167 }else {
5168 send_request_complete(request, 0, res);
5172 TRACE("<--\n");
5173 return res;
5176 typedef struct {
5177 task_header_t hdr;
5178 WCHAR *headers;
5179 DWORD headers_len;
5180 void *optional;
5181 DWORD optional_len;
5182 DWORD content_len;
5183 BOOL end_request;
5184 } send_request_task_t;
5186 /***********************************************************************
5188 * Helper functions for the HttpSendRequest(Ex) functions
5191 static void AsyncHttpSendRequestProc(task_header_t *hdr)
5193 send_request_task_t *task = (send_request_task_t*)hdr;
5194 http_request_t *request = (http_request_t*)task->hdr.hdr;
5196 TRACE("%p\n", request);
5198 HTTP_HttpSendRequestW(request, task->headers, task->headers_len, task->optional,
5199 task->optional_len, task->content_len, task->end_request);
5201 heap_free(task->headers);
5205 static DWORD HTTP_HttpEndRequestW(http_request_t *request, DWORD dwFlags, DWORD_PTR dwContext)
5207 INT responseLen;
5208 DWORD res = ERROR_SUCCESS;
5210 if(!is_valid_netconn(request->netconn)) {
5211 WARN("Not connected\n");
5212 send_request_complete(request, 0, ERROR_INTERNET_OPERATION_CANCELLED);
5213 return ERROR_INTERNET_OPERATION_CANCELLED;
5216 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5217 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5219 if (HTTP_GetResponseHeaders(request, &responseLen) || !responseLen)
5220 res = ERROR_HTTP_HEADER_NOT_FOUND;
5222 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5223 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
5225 /* process cookies here. Is this right? */
5226 http_process_keep_alive(request);
5227 HTTP_ProcessCookies(request);
5228 HTTP_ProcessExpires(request);
5229 HTTP_ProcessLastModified(request);
5231 if ((res = set_content_length(request)) == ERROR_SUCCESS) {
5232 if(!request->contentLength)
5233 http_release_netconn(request, TRUE);
5236 if (res == ERROR_SUCCESS && !(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
5238 switch(request->status_code) {
5239 case HTTP_STATUS_REDIRECT:
5240 case HTTP_STATUS_MOVED:
5241 case HTTP_STATUS_REDIRECT_METHOD:
5242 case HTTP_STATUS_REDIRECT_KEEP_VERB: {
5243 WCHAR *new_url;
5245 new_url = get_redirect_url(request);
5246 if(!new_url)
5247 break;
5249 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5250 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5252 heap_free(request->verb);
5253 request->verb = heap_strdupW(szGET);
5255 http_release_netconn(request, drain_content(request, FALSE) == ERROR_SUCCESS);
5256 res = HTTP_HandleRedirect(request, new_url);
5257 heap_free(new_url);
5258 if (res == ERROR_SUCCESS)
5259 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, TRUE);
5264 if(res == ERROR_SUCCESS)
5265 create_cache_entry(request);
5267 if (res == ERROR_SUCCESS && request->contentLength)
5268 HTTP_ReceiveRequestData(request);
5269 else
5270 send_request_complete(request, res == ERROR_SUCCESS, res);
5272 return res;
5275 /***********************************************************************
5276 * HttpEndRequestA (WININET.@)
5278 * Ends an HTTP request that was started by HttpSendRequestEx
5280 * RETURNS
5281 * TRUE if successful
5282 * FALSE on failure
5285 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
5286 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5288 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5290 if (lpBuffersOut)
5292 SetLastError(ERROR_INVALID_PARAMETER);
5293 return FALSE;
5296 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
5299 typedef struct {
5300 task_header_t hdr;
5301 DWORD flags;
5302 DWORD context;
5303 } end_request_task_t;
5305 static void AsyncHttpEndRequestProc(task_header_t *hdr)
5307 end_request_task_t *task = (end_request_task_t*)hdr;
5308 http_request_t *req = (http_request_t*)task->hdr.hdr;
5310 TRACE("%p\n", req);
5312 HTTP_HttpEndRequestW(req, task->flags, task->context);
5315 /***********************************************************************
5316 * HttpEndRequestW (WININET.@)
5318 * Ends an HTTP request that was started by HttpSendRequestEx
5320 * RETURNS
5321 * TRUE if successful
5322 * FALSE on failure
5325 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
5326 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5328 http_request_t *request;
5329 DWORD res;
5331 TRACE("%p %p %x %lx -->\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5333 if (lpBuffersOut)
5335 SetLastError(ERROR_INVALID_PARAMETER);
5336 return FALSE;
5339 request = (http_request_t*) get_handle_object( hRequest );
5341 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5343 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
5344 if (request)
5345 WININET_Release( &request->hdr );
5346 return FALSE;
5348 request->hdr.dwFlags |= dwFlags;
5350 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5352 end_request_task_t *task;
5354 task = alloc_async_task(&request->hdr, AsyncHttpEndRequestProc, sizeof(*task));
5355 task->flags = dwFlags;
5356 task->context = dwContext;
5358 INTERNET_AsyncCall(&task->hdr);
5359 res = ERROR_IO_PENDING;
5361 else
5362 res = HTTP_HttpEndRequestW(request, dwFlags, dwContext);
5364 WININET_Release( &request->hdr );
5365 TRACE("%u <--\n", res);
5366 if(res != ERROR_SUCCESS)
5367 SetLastError(res);
5368 return res == ERROR_SUCCESS;
5371 /***********************************************************************
5372 * HttpSendRequestExA (WININET.@)
5374 * Sends the specified request to the HTTP server and allows chunked
5375 * transfers.
5377 * RETURNS
5378 * Success: TRUE
5379 * Failure: FALSE, call GetLastError() for more information.
5381 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
5382 LPINTERNET_BUFFERSA lpBuffersIn,
5383 LPINTERNET_BUFFERSA lpBuffersOut,
5384 DWORD dwFlags, DWORD_PTR dwContext)
5386 INTERNET_BUFFERSW BuffersInW;
5387 BOOL rc = FALSE;
5388 DWORD headerlen;
5389 LPWSTR header = NULL;
5391 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5392 lpBuffersOut, dwFlags, dwContext);
5394 if (lpBuffersIn)
5396 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
5397 if (lpBuffersIn->lpcszHeader)
5399 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
5400 lpBuffersIn->dwHeadersLength,0,0);
5401 header = heap_alloc(headerlen*sizeof(WCHAR));
5402 if (!(BuffersInW.lpcszHeader = header))
5404 SetLastError(ERROR_OUTOFMEMORY);
5405 return FALSE;
5407 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
5408 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5409 header, headerlen);
5411 else
5412 BuffersInW.lpcszHeader = NULL;
5413 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
5414 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
5415 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
5416 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
5417 BuffersInW.Next = NULL;
5420 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
5422 heap_free(header);
5423 return rc;
5426 /***********************************************************************
5427 * HttpSendRequestExW (WININET.@)
5429 * Sends the specified request to the HTTP server and allows chunked
5430 * transfers
5432 * RETURNS
5433 * Success: TRUE
5434 * Failure: FALSE, call GetLastError() for more information.
5436 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
5437 LPINTERNET_BUFFERSW lpBuffersIn,
5438 LPINTERNET_BUFFERSW lpBuffersOut,
5439 DWORD dwFlags, DWORD_PTR dwContext)
5441 http_request_t *request;
5442 http_session_t *session;
5443 appinfo_t *hIC;
5444 DWORD res;
5446 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5447 lpBuffersOut, dwFlags, dwContext);
5449 request = (http_request_t*) get_handle_object( hRequest );
5451 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5453 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5454 goto lend;
5457 session = request->session;
5458 assert(session->hdr.htype == WH_HHTTPSESSION);
5459 hIC = session->appInfo;
5460 assert(hIC->hdr.htype == WH_HINIT);
5462 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5464 send_request_task_t *task;
5466 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5467 if (lpBuffersIn)
5469 DWORD size = 0;
5471 if (lpBuffersIn->lpcszHeader)
5473 if (lpBuffersIn->dwHeadersLength == ~0u)
5474 size = (strlenW( lpBuffersIn->lpcszHeader ) + 1) * sizeof(WCHAR);
5475 else
5476 size = lpBuffersIn->dwHeadersLength * sizeof(WCHAR);
5478 task->headers = heap_alloc(size);
5479 memcpy(task->headers, lpBuffersIn->lpcszHeader, size);
5481 else task->headers = NULL;
5483 task->headers_len = size / sizeof(WCHAR);
5484 task->optional = lpBuffersIn->lpvBuffer;
5485 task->optional_len = lpBuffersIn->dwBufferLength;
5486 task->content_len = lpBuffersIn->dwBufferTotal;
5488 else
5490 task->headers = NULL;
5491 task->headers_len = 0;
5492 task->optional = NULL;
5493 task->optional_len = 0;
5494 task->content_len = 0;
5497 task->end_request = FALSE;
5499 INTERNET_AsyncCall(&task->hdr);
5500 res = ERROR_IO_PENDING;
5502 else
5504 if (lpBuffersIn)
5505 res = HTTP_HttpSendRequestW(request, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5506 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
5507 lpBuffersIn->dwBufferTotal, FALSE);
5508 else
5509 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, FALSE);
5512 lend:
5513 if ( request )
5514 WININET_Release( &request->hdr );
5516 TRACE("<---\n");
5517 SetLastError(res);
5518 return res == ERROR_SUCCESS;
5521 /***********************************************************************
5522 * HttpSendRequestW (WININET.@)
5524 * Sends the specified request to the HTTP server
5526 * RETURNS
5527 * TRUE on success
5528 * FALSE on failure
5531 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
5532 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5534 http_request_t *request;
5535 http_session_t *session = NULL;
5536 appinfo_t *hIC = NULL;
5537 DWORD res = ERROR_SUCCESS;
5539 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
5540 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
5542 request = (http_request_t*) get_handle_object( hHttpRequest );
5543 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5545 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5546 goto lend;
5549 session = request->session;
5550 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
5552 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5553 goto lend;
5556 hIC = session->appInfo;
5557 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
5559 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5560 goto lend;
5563 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5565 send_request_task_t *task;
5567 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5568 if (lpszHeaders)
5570 DWORD size;
5572 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
5573 else size = dwHeaderLength * sizeof(WCHAR);
5575 task->headers = heap_alloc(size);
5576 memcpy(task->headers, lpszHeaders, size);
5578 else
5579 task->headers = NULL;
5580 task->headers_len = dwHeaderLength;
5581 task->optional = lpOptional;
5582 task->optional_len = dwOptionalLength;
5583 task->content_len = dwOptionalLength;
5584 task->end_request = TRUE;
5586 INTERNET_AsyncCall(&task->hdr);
5587 res = ERROR_IO_PENDING;
5589 else
5591 res = HTTP_HttpSendRequestW(request, lpszHeaders,
5592 dwHeaderLength, lpOptional, dwOptionalLength,
5593 dwOptionalLength, TRUE);
5595 lend:
5596 if( request )
5597 WININET_Release( &request->hdr );
5599 SetLastError(res);
5600 return res == ERROR_SUCCESS;
5603 /***********************************************************************
5604 * HttpSendRequestA (WININET.@)
5606 * Sends the specified request to the HTTP server
5608 * RETURNS
5609 * TRUE on success
5610 * FALSE on failure
5613 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
5614 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5616 BOOL result;
5617 LPWSTR szHeaders=NULL;
5618 DWORD nLen=dwHeaderLength;
5619 if(lpszHeaders!=NULL)
5621 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
5622 szHeaders = heap_alloc(nLen*sizeof(WCHAR));
5623 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
5625 result = HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
5626 heap_free(szHeaders);
5627 return result;
5630 /***********************************************************************
5631 * HTTPSESSION_Destroy (internal)
5633 * Deallocate session handle
5636 static void HTTPSESSION_Destroy(object_header_t *hdr)
5638 http_session_t *session = (http_session_t*) hdr;
5640 TRACE("%p\n", session);
5642 WININET_Release(&session->appInfo->hdr);
5644 heap_free(session->hostName);
5645 heap_free(session->password);
5646 heap_free(session->userName);
5649 static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
5651 http_session_t *ses = (http_session_t *)hdr;
5653 switch(option) {
5654 case INTERNET_OPTION_HANDLE_TYPE:
5655 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5657 if (*size < sizeof(ULONG))
5658 return ERROR_INSUFFICIENT_BUFFER;
5660 *size = sizeof(DWORD);
5661 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
5662 return ERROR_SUCCESS;
5663 case INTERNET_OPTION_CONNECT_TIMEOUT:
5664 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5666 if (*size < sizeof(DWORD))
5667 return ERROR_INSUFFICIENT_BUFFER;
5669 *size = sizeof(DWORD);
5670 *(DWORD *)buffer = ses->connect_timeout;
5671 return ERROR_SUCCESS;
5673 case INTERNET_OPTION_SEND_TIMEOUT:
5674 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5676 if (*size < sizeof(DWORD))
5677 return ERROR_INSUFFICIENT_BUFFER;
5679 *size = sizeof(DWORD);
5680 *(DWORD *)buffer = ses->send_timeout;
5681 return ERROR_SUCCESS;
5683 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5684 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5686 if (*size < sizeof(DWORD))
5687 return ERROR_INSUFFICIENT_BUFFER;
5689 *size = sizeof(DWORD);
5690 *(DWORD *)buffer = ses->receive_timeout;
5691 return ERROR_SUCCESS;
5694 return INET_QueryOption(hdr, option, buffer, size, unicode);
5697 static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
5699 http_session_t *ses = (http_session_t*)hdr;
5701 switch(option) {
5702 case INTERNET_OPTION_USERNAME:
5704 heap_free(ses->userName);
5705 if (!(ses->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5706 return ERROR_SUCCESS;
5708 case INTERNET_OPTION_PASSWORD:
5710 heap_free(ses->password);
5711 if (!(ses->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5712 return ERROR_SUCCESS;
5714 case INTERNET_OPTION_PROXY_USERNAME:
5716 heap_free(ses->appInfo->proxyUsername);
5717 if (!(ses->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5718 return ERROR_SUCCESS;
5720 case INTERNET_OPTION_PROXY_PASSWORD:
5722 heap_free(ses->appInfo->proxyPassword);
5723 if (!(ses->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5724 return ERROR_SUCCESS;
5726 case INTERNET_OPTION_CONNECT_TIMEOUT:
5728 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5729 ses->connect_timeout = *(DWORD *)buffer;
5730 return ERROR_SUCCESS;
5732 case INTERNET_OPTION_SEND_TIMEOUT:
5734 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5735 ses->send_timeout = *(DWORD *)buffer;
5736 return ERROR_SUCCESS;
5738 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5740 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5741 ses->receive_timeout = *(DWORD *)buffer;
5742 return ERROR_SUCCESS;
5744 default: break;
5747 return INET_SetOption(hdr, option, buffer, size);
5750 static const object_vtbl_t HTTPSESSIONVtbl = {
5751 HTTPSESSION_Destroy,
5752 NULL,
5753 HTTPSESSION_QueryOption,
5754 HTTPSESSION_SetOption,
5755 NULL,
5756 NULL,
5757 NULL,
5758 NULL
5762 /***********************************************************************
5763 * HTTP_Connect (internal)
5765 * Create http session handle
5767 * RETURNS
5768 * HINTERNET a session handle on success
5769 * NULL on failure
5772 DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
5773 INTERNET_PORT serverPort, LPCWSTR lpszUserName,
5774 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
5775 DWORD dwInternalFlags, HINTERNET *ret)
5777 http_session_t *session = NULL;
5779 TRACE("-->\n");
5781 if (!lpszServerName || !lpszServerName[0])
5782 return ERROR_INVALID_PARAMETER;
5784 assert( hIC->hdr.htype == WH_HINIT );
5786 session = alloc_object(&hIC->hdr, &HTTPSESSIONVtbl, sizeof(http_session_t));
5787 if (!session)
5788 return ERROR_OUTOFMEMORY;
5791 * According to my tests. The name is not resolved until a request is sent
5794 session->hdr.htype = WH_HHTTPSESSION;
5795 session->hdr.dwFlags = dwFlags;
5796 session->hdr.dwContext = dwContext;
5797 session->hdr.dwInternalFlags |= dwInternalFlags;
5799 WININET_AddRef( &hIC->hdr );
5800 session->appInfo = hIC;
5801 list_add_head( &hIC->hdr.children, &session->hdr.entry );
5803 session->hostName = heap_strdupW(lpszServerName);
5804 if (lpszUserName && lpszUserName[0])
5805 session->userName = heap_strdupW(lpszUserName);
5806 session->password = heap_strdupW(lpszPassword);
5807 session->hostPort = serverPort;
5808 session->connect_timeout = hIC->connect_timeout;
5809 session->send_timeout = 0;
5810 session->receive_timeout = 0;
5812 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5813 if (!(session->hdr.dwInternalFlags & INET_OPENURL))
5815 INTERNET_SendCallback(&hIC->hdr, dwContext,
5816 INTERNET_STATUS_HANDLE_CREATED, &session->hdr.hInternet,
5817 sizeof(HINTERNET));
5821 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5822 * windows
5825 TRACE("%p --> %p\n", hIC, session);
5827 *ret = session->hdr.hInternet;
5828 return ERROR_SUCCESS;
5831 /***********************************************************************
5832 * HTTP_clear_response_headers (internal)
5834 * clear out any old response headers
5836 static void HTTP_clear_response_headers( http_request_t *request )
5838 DWORD i;
5840 EnterCriticalSection( &request->headers_section );
5842 for( i=0; i<request->nCustHeaders; i++)
5844 if( !request->custHeaders[i].lpszField )
5845 continue;
5846 if( !request->custHeaders[i].lpszValue )
5847 continue;
5848 if ( request->custHeaders[i].wFlags & HDR_ISREQUEST )
5849 continue;
5850 HTTP_DeleteCustomHeader( request, i );
5851 i--;
5854 LeaveCriticalSection( &request->headers_section );
5857 /***********************************************************************
5858 * HTTP_GetResponseHeaders (internal)
5860 * Read server response
5862 * RETURNS
5864 * TRUE on success
5865 * FALSE on error
5867 static DWORD HTTP_GetResponseHeaders(http_request_t *request, INT *len)
5869 INT cbreaks = 0;
5870 WCHAR buffer[MAX_REPLY_LEN];
5871 DWORD buflen = MAX_REPLY_LEN;
5872 INT rc = 0;
5873 char bufferA[MAX_REPLY_LEN];
5874 LPWSTR status_code = NULL, status_text = NULL;
5875 DWORD res = ERROR_HTTP_INVALID_SERVER_RESPONSE;
5876 BOOL codeHundred = FALSE;
5878 TRACE("-->\n");
5880 if(!is_valid_netconn(request->netconn))
5881 goto lend;
5883 /* clear old response headers (eg. from a redirect response) */
5884 HTTP_clear_response_headers( request );
5886 NETCON_set_timeout( request->netconn, FALSE, request->receive_timeout );
5887 do {
5889 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5891 buflen = MAX_REPLY_LEN;
5892 if ((res = read_line(request, bufferA, &buflen)))
5893 goto lend;
5895 if (!buflen) goto lend;
5897 rc += buflen;
5898 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5899 /* check is this a status code line? */
5900 if (!strncmpW(buffer, g_szHttp1_0, 4))
5902 /* split the version from the status code */
5903 status_code = strchrW( buffer, ' ' );
5904 if( !status_code )
5905 goto lend;
5906 *status_code++=0;
5908 /* split the status code from the status text */
5909 status_text = strchrW( status_code, ' ' );
5910 if( status_text )
5911 *status_text++=0;
5913 request->status_code = atoiW(status_code);
5915 TRACE("version [%s] status code [%s] status text [%s]\n",
5916 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
5918 codeHundred = request->status_code == HTTP_STATUS_CONTINUE;
5920 else if (!codeHundred)
5922 WARN("No status line at head of response (%s)\n", debugstr_w(buffer));
5924 heap_free(request->version);
5925 heap_free(request->statusText);
5927 request->status_code = HTTP_STATUS_OK;
5928 request->version = heap_strdupW(g_szHttp1_0);
5929 request->statusText = heap_strdupW(szOK);
5931 goto lend;
5933 } while (codeHundred);
5935 /* Add status code */
5936 HTTP_ProcessHeader(request, szStatus, status_code,
5937 HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD);
5939 heap_free(request->version);
5940 heap_free(request->statusText);
5942 request->version = heap_strdupW(buffer);
5943 request->statusText = heap_strdupW(status_text ? status_text : emptyW);
5945 /* Restore the spaces */
5946 *(status_code-1) = ' ';
5947 if (status_text)
5948 *(status_text-1) = ' ';
5950 /* Parse each response line */
5953 buflen = MAX_REPLY_LEN;
5954 if (!read_line(request, bufferA, &buflen) && buflen)
5956 LPWSTR * pFieldAndValue;
5958 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
5960 if (!bufferA[0]) break;
5961 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5963 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
5964 if (pFieldAndValue)
5966 HTTP_ProcessHeader(request, pFieldAndValue[0], pFieldAndValue[1],
5967 HTTP_ADDREQ_FLAG_ADD );
5968 HTTP_FreeTokens(pFieldAndValue);
5971 else
5973 cbreaks++;
5974 if (cbreaks >= 2)
5975 break;
5977 }while(1);
5979 res = ERROR_SUCCESS;
5981 lend:
5983 *len = rc;
5984 TRACE("<--\n");
5985 return res;
5988 /***********************************************************************
5989 * HTTP_InterpretHttpHeader (internal)
5991 * Parse server response
5993 * RETURNS
5995 * Pointer to array of field, value, NULL on success.
5996 * NULL on error.
5998 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
6000 LPWSTR * pTokenPair;
6001 LPWSTR pszColon;
6002 INT len;
6004 pTokenPair = heap_alloc_zero(sizeof(*pTokenPair)*3);
6006 pszColon = strchrW(buffer, ':');
6007 /* must have two tokens */
6008 if (!pszColon)
6010 HTTP_FreeTokens(pTokenPair);
6011 if (buffer[0])
6012 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
6013 return NULL;
6016 pTokenPair[0] = heap_alloc((pszColon - buffer + 1) * sizeof(WCHAR));
6017 if (!pTokenPair[0])
6019 HTTP_FreeTokens(pTokenPair);
6020 return NULL;
6022 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
6023 pTokenPair[0][pszColon - buffer] = '\0';
6025 /* skip colon */
6026 pszColon++;
6027 len = strlenW(pszColon);
6028 pTokenPair[1] = heap_alloc((len + 1) * sizeof(WCHAR));
6029 if (!pTokenPair[1])
6031 HTTP_FreeTokens(pTokenPair);
6032 return NULL;
6034 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
6036 strip_spaces(pTokenPair[0]);
6037 strip_spaces(pTokenPair[1]);
6039 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
6040 return pTokenPair;
6043 /***********************************************************************
6044 * HTTP_ProcessHeader (internal)
6046 * Stuff header into header tables according to <dwModifier>
6050 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6052 static DWORD HTTP_ProcessHeader(http_request_t *request, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
6054 LPHTTPHEADERW lphttpHdr = NULL;
6055 INT index;
6056 BOOL request_only = !!(dwModifier & HTTP_ADDHDR_FLAG_REQ);
6057 DWORD res = ERROR_HTTP_INVALID_HEADER;
6059 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
6061 EnterCriticalSection( &request->headers_section );
6063 /* REPLACE wins out over ADD */
6064 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6065 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
6067 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
6068 index = -1;
6069 else
6070 index = HTTP_GetCustomHeaderIndex(request, field, 0, request_only);
6072 if (index >= 0)
6074 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
6076 LeaveCriticalSection( &request->headers_section );
6077 return ERROR_HTTP_INVALID_HEADER;
6079 lphttpHdr = &request->custHeaders[index];
6081 else if (value)
6083 HTTPHEADERW hdr;
6085 hdr.lpszField = (LPWSTR)field;
6086 hdr.lpszValue = (LPWSTR)value;
6087 hdr.wFlags = hdr.wCount = 0;
6089 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6090 hdr.wFlags |= HDR_ISREQUEST;
6092 res = HTTP_InsertCustomHeader(request, &hdr);
6093 LeaveCriticalSection( &request->headers_section );
6094 return res;
6096 /* no value to delete */
6097 else
6099 LeaveCriticalSection( &request->headers_section );
6100 return ERROR_SUCCESS;
6103 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6104 lphttpHdr->wFlags |= HDR_ISREQUEST;
6105 else
6106 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
6108 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6110 HTTP_DeleteCustomHeader( request, index );
6112 if (value && value[0])
6114 HTTPHEADERW hdr;
6116 hdr.lpszField = (LPWSTR)field;
6117 hdr.lpszValue = (LPWSTR)value;
6118 hdr.wFlags = hdr.wCount = 0;
6120 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6121 hdr.wFlags |= HDR_ISREQUEST;
6123 res = HTTP_InsertCustomHeader(request, &hdr);
6124 LeaveCriticalSection( &request->headers_section );
6125 return res;
6128 LeaveCriticalSection( &request->headers_section );
6129 return ERROR_SUCCESS;
6131 else if (dwModifier & COALESCEFLAGS)
6133 LPWSTR lpsztmp;
6134 WCHAR ch = 0;
6135 INT len = 0;
6136 INT origlen = strlenW(lphttpHdr->lpszValue);
6137 INT valuelen = strlenW(value);
6139 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
6141 ch = ',';
6142 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6144 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6146 ch = ';';
6147 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6150 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
6152 lpsztmp = heap_realloc(lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
6153 if (lpsztmp)
6155 lphttpHdr->lpszValue = lpsztmp;
6156 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6157 if (ch > 0)
6159 lphttpHdr->lpszValue[origlen] = ch;
6160 origlen++;
6161 lphttpHdr->lpszValue[origlen] = ' ';
6162 origlen++;
6165 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
6166 lphttpHdr->lpszValue[len] = '\0';
6167 res = ERROR_SUCCESS;
6169 else
6171 WARN("heap_realloc (%d bytes) failed\n",len+1);
6172 res = ERROR_OUTOFMEMORY;
6175 TRACE("<-- %d\n", res);
6176 LeaveCriticalSection( &request->headers_section );
6177 return res;
6180 /***********************************************************************
6181 * HTTP_GetCustomHeaderIndex (internal)
6183 * Return index of custom header from header array
6184 * Headers section must be held
6186 static INT HTTP_GetCustomHeaderIndex(http_request_t *request, LPCWSTR lpszField,
6187 int requested_index, BOOL request_only)
6189 DWORD index;
6191 TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
6193 for (index = 0; index < request->nCustHeaders; index++)
6195 if (strcmpiW(request->custHeaders[index].lpszField, lpszField))
6196 continue;
6198 if (request_only && !(request->custHeaders[index].wFlags & HDR_ISREQUEST))
6199 continue;
6201 if (!request_only && (request->custHeaders[index].wFlags & HDR_ISREQUEST))
6202 continue;
6204 if (requested_index == 0)
6205 break;
6206 requested_index --;
6209 if (index >= request->nCustHeaders)
6210 index = -1;
6212 TRACE("Return: %d\n", index);
6213 return index;
6217 /***********************************************************************
6218 * HTTP_InsertCustomHeader (internal)
6220 * Insert header into array
6221 * Headers section must be held
6223 static DWORD HTTP_InsertCustomHeader(http_request_t *request, LPHTTPHEADERW lpHdr)
6225 INT count;
6226 LPHTTPHEADERW lph = NULL;
6228 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
6229 count = request->nCustHeaders + 1;
6230 if (count > 1)
6231 lph = heap_realloc_zero(request->custHeaders, sizeof(HTTPHEADERW) * count);
6232 else
6233 lph = heap_alloc_zero(sizeof(HTTPHEADERW) * count);
6235 if (!lph)
6236 return ERROR_OUTOFMEMORY;
6238 request->custHeaders = lph;
6239 request->custHeaders[count-1].lpszField = heap_strdupW(lpHdr->lpszField);
6240 request->custHeaders[count-1].lpszValue = heap_strdupW(lpHdr->lpszValue);
6241 request->custHeaders[count-1].wFlags = lpHdr->wFlags;
6242 request->custHeaders[count-1].wCount= lpHdr->wCount;
6243 request->nCustHeaders++;
6245 return ERROR_SUCCESS;
6249 /***********************************************************************
6250 * HTTP_DeleteCustomHeader (internal)
6252 * Delete header from array
6253 * If this function is called, the index may change.
6254 * Headers section must be held
6256 static BOOL HTTP_DeleteCustomHeader(http_request_t *request, DWORD index)
6258 if( request->nCustHeaders <= 0 )
6259 return FALSE;
6260 if( index >= request->nCustHeaders )
6261 return FALSE;
6262 request->nCustHeaders--;
6264 heap_free(request->custHeaders[index].lpszField);
6265 heap_free(request->custHeaders[index].lpszValue);
6267 memmove( &request->custHeaders[index], &request->custHeaders[index+1],
6268 (request->nCustHeaders - index)* sizeof(HTTPHEADERW) );
6269 memset( &request->custHeaders[request->nCustHeaders], 0, sizeof(HTTPHEADERW) );
6271 return TRUE;
6275 /***********************************************************************
6276 * IsHostInProxyBypassList (@)
6278 * Undocumented
6281 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
6283 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
6284 return FALSE;