server: Create the initial thread as a separate request.
[wine.git] / dlls / wininet / http.c
blobb7be9939a12e06726b8a1ffdef4b0109fe8786d6
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 == sizeof(localW)/sizeof(WCHAR)-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, sizeof(no_cacheW)/sizeof(*no_cacheW)-1)
2413 || !strncmpiW(ptr, no_storeW, sizeof(no_storeW)/sizeof(*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 #define LAST_TABLE_HEADER (sizeof(header_lookup)/sizeof(header_lookup[0]))
3518 /***********************************************************************
3519 * HTTP_HttpQueryInfoW (internal)
3521 static DWORD HTTP_HttpQueryInfoW(http_request_t *request, DWORD dwInfoLevel,
3522 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3524 LPHTTPHEADERW lphttpHdr = NULL;
3525 BOOL request_only = !!(dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS);
3526 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
3527 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
3528 INT index = -1;
3530 EnterCriticalSection( &request->headers_section );
3532 /* Find requested header structure */
3533 switch (level)
3535 case HTTP_QUERY_CUSTOM:
3536 if (!lpBuffer)
3538 LeaveCriticalSection( &request->headers_section );
3539 return ERROR_INVALID_PARAMETER;
3541 index = HTTP_GetCustomHeaderIndex(request, lpBuffer, requested_index, request_only);
3542 break;
3543 case HTTP_QUERY_RAW_HEADERS_CRLF:
3545 LPWSTR headers;
3546 DWORD len = 0;
3547 DWORD res = ERROR_INVALID_PARAMETER;
3549 if (request_only)
3550 headers = build_request_header(request, request->verb, request->path, request->version, TRUE);
3551 else
3552 headers = build_response_header(request, TRUE);
3553 if (!headers)
3555 LeaveCriticalSection( &request->headers_section );
3556 return ERROR_OUTOFMEMORY;
3559 len = strlenW(headers) * sizeof(WCHAR);
3560 if (len + sizeof(WCHAR) > *lpdwBufferLength)
3562 len += sizeof(WCHAR);
3563 res = ERROR_INSUFFICIENT_BUFFER;
3565 else if (lpBuffer)
3567 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3568 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
3569 res = ERROR_SUCCESS;
3571 *lpdwBufferLength = len;
3573 heap_free(headers);
3574 LeaveCriticalSection( &request->headers_section );
3575 return res;
3577 case HTTP_QUERY_RAW_HEADERS:
3579 LPWSTR headers;
3580 DWORD len;
3582 if (request_only)
3583 headers = build_request_header(request, request->verb, request->path, request->version, FALSE);
3584 else
3585 headers = build_response_header(request, FALSE);
3587 if (!headers)
3589 LeaveCriticalSection( &request->headers_section );
3590 return ERROR_OUTOFMEMORY;
3593 len = strlenW(headers) * sizeof(WCHAR);
3594 if (len > *lpdwBufferLength)
3596 *lpdwBufferLength = len;
3597 heap_free(headers);
3598 LeaveCriticalSection( &request->headers_section );
3599 return ERROR_INSUFFICIENT_BUFFER;
3602 if (lpBuffer)
3604 DWORD i;
3606 TRACE("returning data: %s\n", debugstr_wn(headers, len / sizeof(WCHAR)));
3608 for (i = 0; i < len / sizeof(WCHAR); i++)
3610 if (headers[i] == '\n')
3611 headers[i] = 0;
3613 memcpy(lpBuffer, headers, len);
3615 *lpdwBufferLength = len - sizeof(WCHAR);
3617 heap_free(headers);
3618 LeaveCriticalSection( &request->headers_section );
3619 return ERROR_SUCCESS;
3621 case HTTP_QUERY_STATUS_TEXT:
3622 if (request->statusText)
3624 DWORD len = strlenW(request->statusText);
3625 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3627 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3628 LeaveCriticalSection( &request->headers_section );
3629 return ERROR_INSUFFICIENT_BUFFER;
3631 if (lpBuffer)
3633 memcpy(lpBuffer, request->statusText, (len + 1) * sizeof(WCHAR));
3634 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3636 *lpdwBufferLength = len * sizeof(WCHAR);
3637 LeaveCriticalSection( &request->headers_section );
3638 return ERROR_SUCCESS;
3640 break;
3641 case HTTP_QUERY_VERSION:
3642 if (request->version)
3644 DWORD len = strlenW(request->version);
3645 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3647 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3648 LeaveCriticalSection( &request->headers_section );
3649 return ERROR_INSUFFICIENT_BUFFER;
3651 if (lpBuffer)
3653 memcpy(lpBuffer, request->version, (len + 1) * sizeof(WCHAR));
3654 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3656 *lpdwBufferLength = len * sizeof(WCHAR);
3657 LeaveCriticalSection( &request->headers_section );
3658 return ERROR_SUCCESS;
3660 break;
3661 case HTTP_QUERY_CONTENT_ENCODING:
3662 index = HTTP_GetCustomHeaderIndex(request, header_lookup[request->read_gzip ? HTTP_QUERY_CONTENT_TYPE : level],
3663 requested_index,request_only);
3664 break;
3665 case HTTP_QUERY_STATUS_CODE: {
3666 DWORD res = ERROR_SUCCESS;
3668 if(request_only)
3670 LeaveCriticalSection( &request->headers_section );
3671 return ERROR_HTTP_INVALID_QUERY_REQUEST;
3674 if(requested_index)
3675 break;
3677 if(dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) {
3678 if(*lpdwBufferLength >= sizeof(DWORD))
3679 *(DWORD*)lpBuffer = request->status_code;
3680 else
3681 res = ERROR_INSUFFICIENT_BUFFER;
3682 *lpdwBufferLength = sizeof(DWORD);
3683 }else {
3684 WCHAR buf[12];
3685 DWORD size;
3686 static const WCHAR formatW[] = {'%','u',0};
3688 size = sprintfW(buf, formatW, request->status_code) * sizeof(WCHAR);
3690 if(size <= *lpdwBufferLength) {
3691 memcpy(lpBuffer, buf, size+sizeof(WCHAR));
3692 }else {
3693 size += sizeof(WCHAR);
3694 res = ERROR_INSUFFICIENT_BUFFER;
3697 *lpdwBufferLength = size;
3699 LeaveCriticalSection( &request->headers_section );
3700 return res;
3702 default:
3703 assert (LAST_TABLE_HEADER == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
3705 if (level < LAST_TABLE_HEADER && header_lookup[level])
3706 index = HTTP_GetCustomHeaderIndex(request, header_lookup[level],
3707 requested_index,request_only);
3710 if (index >= 0)
3711 lphttpHdr = &request->custHeaders[index];
3713 /* Ensure header satisfies requested attributes */
3714 if (!lphttpHdr ||
3715 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
3716 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
3718 LeaveCriticalSection( &request->headers_section );
3719 return ERROR_HTTP_HEADER_NOT_FOUND;
3722 /* coalesce value to requested type */
3723 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
3725 *(int *)lpBuffer = atoiW(lphttpHdr->lpszValue);
3726 TRACE(" returning number: %d\n", *(int *)lpBuffer);
3728 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
3730 time_t tmpTime;
3731 struct tm tmpTM;
3732 SYSTEMTIME *STHook;
3734 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
3736 tmpTM = *gmtime(&tmpTime);
3737 STHook = (SYSTEMTIME *)lpBuffer;
3738 STHook->wDay = tmpTM.tm_mday;
3739 STHook->wHour = tmpTM.tm_hour;
3740 STHook->wMilliseconds = 0;
3741 STHook->wMinute = tmpTM.tm_min;
3742 STHook->wDayOfWeek = tmpTM.tm_wday;
3743 STHook->wMonth = tmpTM.tm_mon + 1;
3744 STHook->wSecond = tmpTM.tm_sec;
3745 STHook->wYear = 1900+tmpTM.tm_year;
3747 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3748 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
3749 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
3751 else if (lphttpHdr->lpszValue)
3753 DWORD len = (strlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
3755 if (len > *lpdwBufferLength)
3757 *lpdwBufferLength = len;
3758 LeaveCriticalSection( &request->headers_section );
3759 return ERROR_INSUFFICIENT_BUFFER;
3761 if (lpBuffer)
3763 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
3764 TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
3766 *lpdwBufferLength = len - sizeof(WCHAR);
3768 if (lpdwIndex) (*lpdwIndex)++;
3770 LeaveCriticalSection( &request->headers_section );
3771 return ERROR_SUCCESS;
3774 /***********************************************************************
3775 * HttpQueryInfoW (WININET.@)
3777 * Queries for information about an HTTP request
3779 * RETURNS
3780 * TRUE on success
3781 * FALSE on failure
3784 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3785 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3787 http_request_t *request;
3788 DWORD res;
3790 if (TRACE_ON(wininet)) {
3791 #define FE(x) { x, #x }
3792 static const wininet_flag_info query_flags[] = {
3793 FE(HTTP_QUERY_MIME_VERSION),
3794 FE(HTTP_QUERY_CONTENT_TYPE),
3795 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
3796 FE(HTTP_QUERY_CONTENT_ID),
3797 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
3798 FE(HTTP_QUERY_CONTENT_LENGTH),
3799 FE(HTTP_QUERY_CONTENT_LANGUAGE),
3800 FE(HTTP_QUERY_ALLOW),
3801 FE(HTTP_QUERY_PUBLIC),
3802 FE(HTTP_QUERY_DATE),
3803 FE(HTTP_QUERY_EXPIRES),
3804 FE(HTTP_QUERY_LAST_MODIFIED),
3805 FE(HTTP_QUERY_MESSAGE_ID),
3806 FE(HTTP_QUERY_URI),
3807 FE(HTTP_QUERY_DERIVED_FROM),
3808 FE(HTTP_QUERY_COST),
3809 FE(HTTP_QUERY_LINK),
3810 FE(HTTP_QUERY_PRAGMA),
3811 FE(HTTP_QUERY_VERSION),
3812 FE(HTTP_QUERY_STATUS_CODE),
3813 FE(HTTP_QUERY_STATUS_TEXT),
3814 FE(HTTP_QUERY_RAW_HEADERS),
3815 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
3816 FE(HTTP_QUERY_CONNECTION),
3817 FE(HTTP_QUERY_ACCEPT),
3818 FE(HTTP_QUERY_ACCEPT_CHARSET),
3819 FE(HTTP_QUERY_ACCEPT_ENCODING),
3820 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
3821 FE(HTTP_QUERY_AUTHORIZATION),
3822 FE(HTTP_QUERY_CONTENT_ENCODING),
3823 FE(HTTP_QUERY_FORWARDED),
3824 FE(HTTP_QUERY_FROM),
3825 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
3826 FE(HTTP_QUERY_LOCATION),
3827 FE(HTTP_QUERY_ORIG_URI),
3828 FE(HTTP_QUERY_REFERER),
3829 FE(HTTP_QUERY_RETRY_AFTER),
3830 FE(HTTP_QUERY_SERVER),
3831 FE(HTTP_QUERY_TITLE),
3832 FE(HTTP_QUERY_USER_AGENT),
3833 FE(HTTP_QUERY_WWW_AUTHENTICATE),
3834 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
3835 FE(HTTP_QUERY_ACCEPT_RANGES),
3836 FE(HTTP_QUERY_SET_COOKIE),
3837 FE(HTTP_QUERY_COOKIE),
3838 FE(HTTP_QUERY_REQUEST_METHOD),
3839 FE(HTTP_QUERY_REFRESH),
3840 FE(HTTP_QUERY_CONTENT_DISPOSITION),
3841 FE(HTTP_QUERY_AGE),
3842 FE(HTTP_QUERY_CACHE_CONTROL),
3843 FE(HTTP_QUERY_CONTENT_BASE),
3844 FE(HTTP_QUERY_CONTENT_LOCATION),
3845 FE(HTTP_QUERY_CONTENT_MD5),
3846 FE(HTTP_QUERY_CONTENT_RANGE),
3847 FE(HTTP_QUERY_ETAG),
3848 FE(HTTP_QUERY_HOST),
3849 FE(HTTP_QUERY_IF_MATCH),
3850 FE(HTTP_QUERY_IF_NONE_MATCH),
3851 FE(HTTP_QUERY_IF_RANGE),
3852 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
3853 FE(HTTP_QUERY_MAX_FORWARDS),
3854 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
3855 FE(HTTP_QUERY_RANGE),
3856 FE(HTTP_QUERY_TRANSFER_ENCODING),
3857 FE(HTTP_QUERY_UPGRADE),
3858 FE(HTTP_QUERY_VARY),
3859 FE(HTTP_QUERY_VIA),
3860 FE(HTTP_QUERY_WARNING),
3861 FE(HTTP_QUERY_CUSTOM)
3863 static const wininet_flag_info modifier_flags[] = {
3864 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
3865 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
3866 FE(HTTP_QUERY_FLAG_NUMBER),
3867 FE(HTTP_QUERY_FLAG_COALESCE)
3869 #undef FE
3870 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
3871 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
3872 DWORD i;
3874 TRACE("(%p, 0x%08x)--> %d\n", hHttpRequest, dwInfoLevel, info);
3875 TRACE(" Attribute:");
3876 for (i = 0; i < (sizeof(query_flags) / sizeof(query_flags[0])); i++) {
3877 if (query_flags[i].val == info) {
3878 TRACE(" %s", query_flags[i].name);
3879 break;
3882 if (i == (sizeof(query_flags) / sizeof(query_flags[0]))) {
3883 TRACE(" Unknown (%08x)", info);
3886 TRACE(" Modifier:");
3887 for (i = 0; i < (sizeof(modifier_flags) / sizeof(modifier_flags[0])); i++) {
3888 if (modifier_flags[i].val & info_mod) {
3889 TRACE(" %s", modifier_flags[i].name);
3890 info_mod &= ~ modifier_flags[i].val;
3894 if (info_mod) {
3895 TRACE(" Unknown (%08x)", info_mod);
3897 TRACE("\n");
3900 request = (http_request_t*) get_handle_object( hHttpRequest );
3901 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
3903 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3904 goto lend;
3907 if (lpBuffer == NULL)
3908 *lpdwBufferLength = 0;
3909 res = HTTP_HttpQueryInfoW( request, dwInfoLevel,
3910 lpBuffer, lpdwBufferLength, lpdwIndex);
3912 lend:
3913 if( request )
3914 WININET_Release( &request->hdr );
3916 TRACE("%u <--\n", res);
3917 if(res != ERROR_SUCCESS)
3918 SetLastError(res);
3919 return res == ERROR_SUCCESS;
3922 /***********************************************************************
3923 * HttpQueryInfoA (WININET.@)
3925 * Queries for information about an HTTP request
3927 * RETURNS
3928 * TRUE on success
3929 * FALSE on failure
3932 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3933 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3935 BOOL result;
3936 DWORD len;
3937 WCHAR* bufferW;
3939 TRACE("%p %x\n", hHttpRequest, dwInfoLevel);
3941 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
3942 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
3944 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
3945 lpdwBufferLength, lpdwIndex );
3948 if (lpBuffer)
3950 DWORD alloclen;
3951 len = (*lpdwBufferLength)*sizeof(WCHAR);
3952 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3954 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
3955 if (alloclen < len)
3956 alloclen = len;
3958 else
3959 alloclen = len;
3960 bufferW = heap_alloc(alloclen);
3961 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
3962 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
3963 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
3964 } else
3966 bufferW = NULL;
3967 len = 0;
3970 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
3971 &len, lpdwIndex );
3972 if( result )
3974 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
3975 lpBuffer, *lpdwBufferLength, NULL, NULL );
3976 *lpdwBufferLength = len - 1;
3978 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
3980 else
3981 /* since the strings being returned from HttpQueryInfoW should be
3982 * only ASCII characters, it is reasonable to assume that all of
3983 * the Unicode characters can be reduced to a single byte */
3984 *lpdwBufferLength = len / sizeof(WCHAR);
3986 heap_free( bufferW );
3987 return result;
3990 static WCHAR *get_redirect_url(http_request_t *request)
3992 static WCHAR szHttp[] = {'h','t','t','p',0};
3993 static WCHAR szHttps[] = {'h','t','t','p','s',0};
3994 http_session_t *session = request->session;
3995 URL_COMPONENTSW urlComponents = { sizeof(urlComponents) };
3996 WCHAR *orig_url = NULL, *redirect_url = NULL, *combined_url = NULL;
3997 DWORD url_length = 0, res;
3998 BOOL b;
4000 url_length = 0;
4001 res = HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, redirect_url, &url_length, NULL);
4002 if(res == ERROR_INSUFFICIENT_BUFFER) {
4003 redirect_url = heap_alloc(url_length);
4004 res = HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, redirect_url, &url_length, NULL);
4006 if(res != ERROR_SUCCESS) {
4007 heap_free(redirect_url);
4008 return NULL;
4011 urlComponents.dwSchemeLength = 1;
4012 b = InternetCrackUrlW(redirect_url, url_length / sizeof(WCHAR), 0, &urlComponents);
4013 if(b && urlComponents.dwSchemeLength &&
4014 urlComponents.nScheme != INTERNET_SCHEME_HTTP && urlComponents.nScheme != INTERNET_SCHEME_HTTPS) {
4015 TRACE("redirect to non-http URL\n");
4016 return NULL;
4019 urlComponents.lpszScheme = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
4020 urlComponents.dwSchemeLength = 0;
4021 urlComponents.lpszHostName = request->server->name;
4022 urlComponents.nPort = request->server->port;
4023 urlComponents.lpszUserName = session->userName;
4024 urlComponents.lpszUrlPath = request->path;
4026 b = InternetCreateUrlW(&urlComponents, 0, NULL, &url_length);
4027 if(!b && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
4028 orig_url = heap_alloc(url_length);
4030 /* convert from bytes to characters */
4031 url_length = url_length / sizeof(WCHAR) - 1;
4032 b = InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length);
4035 if(b) {
4036 url_length = 0;
4037 b = InternetCombineUrlW(orig_url, redirect_url, NULL, &url_length, ICU_ENCODE_SPACES_ONLY);
4038 if(!b && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
4039 combined_url = heap_alloc(url_length * sizeof(WCHAR));
4040 b = InternetCombineUrlW(orig_url, redirect_url, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY);
4041 if(!b) {
4042 heap_free(combined_url);
4043 combined_url = NULL;
4048 heap_free(orig_url);
4049 heap_free(redirect_url);
4050 return combined_url;
4054 /***********************************************************************
4055 * HTTP_HandleRedirect (internal)
4057 static DWORD HTTP_HandleRedirect(http_request_t *request, WCHAR *url)
4059 URL_COMPONENTSW urlComponents = { sizeof(urlComponents) };
4060 http_session_t *session = request->session;
4061 size_t url_len = strlenW(url);
4063 if(url[0] == '/')
4065 /* if it's an absolute path, keep the same session info */
4066 urlComponents.lpszUrlPath = url;
4067 urlComponents.dwUrlPathLength = url_len;
4069 else
4071 urlComponents.dwHostNameLength = 1;
4072 urlComponents.dwUserNameLength = 1;
4073 urlComponents.dwUrlPathLength = 1;
4074 if(!InternetCrackUrlW(url, url_len, 0, &urlComponents))
4075 return INTERNET_GetLastError();
4077 if(!urlComponents.dwHostNameLength)
4078 return ERROR_INTERNET_INVALID_URL;
4081 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
4082 url, (url_len + 1) * sizeof(WCHAR));
4084 if(urlComponents.dwHostNameLength) {
4085 BOOL custom_port = FALSE;
4086 substr_t host;
4088 if(urlComponents.nScheme == INTERNET_SCHEME_HTTP) {
4089 if(request->hdr.dwFlags & INTERNET_FLAG_SECURE) {
4090 TRACE("redirect from secure page to non-secure page\n");
4091 /* FIXME: warn about from secure redirect to non-secure page */
4092 request->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
4095 custom_port = urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT;
4096 }else if(urlComponents.nScheme == INTERNET_SCHEME_HTTPS) {
4097 if(!(request->hdr.dwFlags & INTERNET_FLAG_SECURE)) {
4098 TRACE("redirect from non-secure page to secure page\n");
4099 /* FIXME: notify about redirect to secure page */
4100 request->hdr.dwFlags |= INTERNET_FLAG_SECURE;
4103 custom_port = urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT;
4106 heap_free(session->hostName);
4108 session->hostName = heap_strndupW(urlComponents.lpszHostName, urlComponents.dwHostNameLength);
4109 session->hostPort = urlComponents.nPort;
4111 heap_free(session->userName);
4112 session->userName = NULL;
4113 if (urlComponents.dwUserNameLength)
4114 session->userName = heap_strndupW(urlComponents.lpszUserName, urlComponents.dwUserNameLength);
4116 reset_data_stream(request);
4118 host = substr(urlComponents.lpszHostName, urlComponents.dwHostNameLength);
4120 if(host.len != strlenW(request->server->name) || strncmpiW(request->server->name, host.str, host.len)
4121 || request->server->port != urlComponents.nPort) {
4122 server_t *new_server;
4124 new_server = get_server(host, urlComponents.nPort, urlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
4125 server_release(request->server);
4126 request->server = new_server;
4129 if (custom_port)
4130 HTTP_ProcessHeader(request, hostW, request->server->host_port, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4131 else
4132 HTTP_ProcessHeader(request, hostW, request->server->name, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4135 heap_free(request->path);
4136 request->path = NULL;
4137 if(urlComponents.dwUrlPathLength)
4139 DWORD needed = 1;
4140 HRESULT rc;
4141 WCHAR dummy = 0;
4142 WCHAR *path;
4144 path = heap_strndupW(urlComponents.lpszUrlPath, urlComponents.dwUrlPathLength);
4145 rc = UrlEscapeW(path, &dummy, &needed, URL_ESCAPE_SPACES_ONLY);
4146 if (rc != E_POINTER)
4147 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4148 request->path = heap_alloc(needed*sizeof(WCHAR));
4149 rc = UrlEscapeW(path, request->path, &needed,
4150 URL_ESCAPE_SPACES_ONLY);
4151 if (rc != S_OK)
4153 ERR("Unable to escape string!(%s) (%d)\n",debugstr_w(path),rc);
4154 strcpyW(request->path, path);
4156 heap_free(path);
4159 /* Remove custom content-type/length headers on redirects. */
4160 remove_header(request, szContent_Type, TRUE);
4161 remove_header(request, szContent_Length, TRUE);
4163 return ERROR_SUCCESS;
4166 /***********************************************************************
4167 * HTTP_build_req (internal)
4169 * concatenate all the strings in the request together
4171 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
4173 LPCWSTR *t;
4174 LPWSTR str;
4176 for( t = list; *t ; t++ )
4177 len += strlenW( *t );
4178 len++;
4180 str = heap_alloc(len*sizeof(WCHAR));
4181 *str = 0;
4183 for( t = list; *t ; t++ )
4184 strcatW( str, *t );
4186 return str;
4189 static void HTTP_InsertCookies(http_request_t *request)
4191 WCHAR *cookies;
4192 DWORD res;
4194 res = get_cookie_header(request->server->name, request->path, &cookies);
4195 if(res != ERROR_SUCCESS || !cookies)
4196 return;
4198 HTTP_HttpAddRequestHeadersW(request, cookies, strlenW(cookies),
4199 HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
4200 heap_free(cookies);
4203 static WORD HTTP_ParseWkday(LPCWSTR day)
4205 static const WCHAR days[7][4] = {{ 's','u','n',0 },
4206 { 'm','o','n',0 },
4207 { 't','u','e',0 },
4208 { 'w','e','d',0 },
4209 { 't','h','u',0 },
4210 { 'f','r','i',0 },
4211 { 's','a','t',0 }};
4212 unsigned int i;
4213 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4214 if (!strcmpiW(day, days[i]))
4215 return i;
4217 /* Invalid */
4218 return 7;
4221 static WORD HTTP_ParseMonth(LPCWSTR month)
4223 static const WCHAR jan[] = { 'j','a','n',0 };
4224 static const WCHAR feb[] = { 'f','e','b',0 };
4225 static const WCHAR mar[] = { 'm','a','r',0 };
4226 static const WCHAR apr[] = { 'a','p','r',0 };
4227 static const WCHAR may[] = { 'm','a','y',0 };
4228 static const WCHAR jun[] = { 'j','u','n',0 };
4229 static const WCHAR jul[] = { 'j','u','l',0 };
4230 static const WCHAR aug[] = { 'a','u','g',0 };
4231 static const WCHAR sep[] = { 's','e','p',0 };
4232 static const WCHAR oct[] = { 'o','c','t',0 };
4233 static const WCHAR nov[] = { 'n','o','v',0 };
4234 static const WCHAR dec[] = { 'd','e','c',0 };
4236 if (!strcmpiW(month, jan)) return 1;
4237 if (!strcmpiW(month, feb)) return 2;
4238 if (!strcmpiW(month, mar)) return 3;
4239 if (!strcmpiW(month, apr)) return 4;
4240 if (!strcmpiW(month, may)) return 5;
4241 if (!strcmpiW(month, jun)) return 6;
4242 if (!strcmpiW(month, jul)) return 7;
4243 if (!strcmpiW(month, aug)) return 8;
4244 if (!strcmpiW(month, sep)) return 9;
4245 if (!strcmpiW(month, oct)) return 10;
4246 if (!strcmpiW(month, nov)) return 11;
4247 if (!strcmpiW(month, dec)) return 12;
4248 /* Invalid */
4249 return 0;
4252 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4253 * optionally preceded by whitespace.
4254 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4255 * st, and sets *str to the first character after the time format.
4257 static BOOL HTTP_ParseTime(SYSTEMTIME *st, LPCWSTR *str)
4259 LPCWSTR ptr = *str;
4260 WCHAR *nextPtr;
4261 unsigned long num;
4263 while (isspaceW(*ptr))
4264 ptr++;
4266 num = strtoulW(ptr, &nextPtr, 10);
4267 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4269 ERR("unexpected time format %s\n", debugstr_w(ptr));
4270 return FALSE;
4272 if (num > 23)
4274 ERR("unexpected hour in time format %s\n", debugstr_w(ptr));
4275 return FALSE;
4277 ptr = nextPtr + 1;
4278 st->wHour = (WORD)num;
4279 num = strtoulW(ptr, &nextPtr, 10);
4280 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4282 ERR("unexpected time format %s\n", debugstr_w(ptr));
4283 return FALSE;
4285 if (num > 59)
4287 ERR("unexpected minute in time format %s\n", debugstr_w(ptr));
4288 return FALSE;
4290 ptr = nextPtr + 1;
4291 st->wMinute = (WORD)num;
4292 num = strtoulW(ptr, &nextPtr, 10);
4293 if (!nextPtr || nextPtr <= ptr)
4295 ERR("unexpected time format %s\n", debugstr_w(ptr));
4296 return FALSE;
4298 if (num > 59)
4300 ERR("unexpected second in time format %s\n", debugstr_w(ptr));
4301 return FALSE;
4303 ptr = nextPtr + 1;
4304 *str = ptr;
4305 st->wSecond = (WORD)num;
4306 return TRUE;
4309 static BOOL HTTP_ParseDateAsAsctime(LPCWSTR value, FILETIME *ft)
4311 static const WCHAR gmt[]= { 'G','M','T',0 };
4312 WCHAR day[4], *dayPtr, month[4], *monthPtr, *nextPtr;
4313 LPCWSTR ptr;
4314 SYSTEMTIME st = { 0 };
4315 unsigned long num;
4317 for (ptr = value, dayPtr = day; *ptr && !isspaceW(*ptr) &&
4318 dayPtr - day < sizeof(day) / sizeof(day[0]) - 1; ptr++, dayPtr++)
4319 *dayPtr = *ptr;
4320 *dayPtr = 0;
4321 st.wDayOfWeek = HTTP_ParseWkday(day);
4322 if (st.wDayOfWeek >= 7)
4324 ERR("unexpected weekday %s\n", debugstr_w(day));
4325 return FALSE;
4328 while (isspaceW(*ptr))
4329 ptr++;
4331 for (monthPtr = month; !isspaceW(*ptr) &&
4332 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4333 monthPtr++, ptr++)
4334 *monthPtr = *ptr;
4335 *monthPtr = 0;
4336 st.wMonth = HTTP_ParseMonth(month);
4337 if (!st.wMonth || st.wMonth > 12)
4339 ERR("unexpected month %s\n", debugstr_w(month));
4340 return FALSE;
4343 while (isspaceW(*ptr))
4344 ptr++;
4346 num = strtoulW(ptr, &nextPtr, 10);
4347 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4349 ERR("unexpected day %s\n", debugstr_w(ptr));
4350 return FALSE;
4352 ptr = nextPtr;
4353 st.wDay = (WORD)num;
4355 while (isspaceW(*ptr))
4356 ptr++;
4358 if (!HTTP_ParseTime(&st, &ptr))
4359 return FALSE;
4361 while (isspaceW(*ptr))
4362 ptr++;
4364 num = strtoulW(ptr, &nextPtr, 10);
4365 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4367 ERR("unexpected year %s\n", debugstr_w(ptr));
4368 return FALSE;
4370 ptr = nextPtr;
4371 st.wYear = (WORD)num;
4373 while (isspaceW(*ptr))
4374 ptr++;
4376 /* asctime() doesn't report a timezone, but some web servers do, so accept
4377 * with or without GMT.
4379 if (*ptr && strcmpW(ptr, gmt))
4381 ERR("unexpected timezone %s\n", debugstr_w(ptr));
4382 return FALSE;
4384 return SystemTimeToFileTime(&st, ft);
4387 static BOOL HTTP_ParseRfc1123Date(LPCWSTR value, FILETIME *ft)
4389 static const WCHAR gmt[]= { 'G','M','T',0 };
4390 WCHAR *nextPtr, day[4], month[4], *monthPtr;
4391 LPCWSTR ptr;
4392 unsigned long num;
4393 SYSTEMTIME st = { 0 };
4395 ptr = strchrW(value, ',');
4396 if (!ptr)
4397 return FALSE;
4398 if (ptr - value != 3)
4400 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4401 return FALSE;
4403 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4404 day[3] = 0;
4405 st.wDayOfWeek = HTTP_ParseWkday(day);
4406 if (st.wDayOfWeek > 6)
4408 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4409 return FALSE;
4411 ptr++;
4413 while (isspaceW(*ptr))
4414 ptr++;
4416 num = strtoulW(ptr, &nextPtr, 10);
4417 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4419 WARN("unexpected day %s\n", debugstr_w(value));
4420 return FALSE;
4422 ptr = nextPtr;
4423 st.wDay = (WORD)num;
4425 while (isspaceW(*ptr))
4426 ptr++;
4428 for (monthPtr = month; !isspaceW(*ptr) &&
4429 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4430 monthPtr++, ptr++)
4431 *monthPtr = *ptr;
4432 *monthPtr = 0;
4433 st.wMonth = HTTP_ParseMonth(month);
4434 if (!st.wMonth || st.wMonth > 12)
4436 WARN("unexpected month %s\n", debugstr_w(month));
4437 return FALSE;
4440 while (isspaceW(*ptr))
4441 ptr++;
4443 num = strtoulW(ptr, &nextPtr, 10);
4444 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4446 ERR("unexpected year %s\n", debugstr_w(value));
4447 return FALSE;
4449 ptr = nextPtr;
4450 st.wYear = (WORD)num;
4452 if (!HTTP_ParseTime(&st, &ptr))
4453 return FALSE;
4455 while (isspaceW(*ptr))
4456 ptr++;
4458 if (strcmpW(ptr, gmt))
4460 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4461 return FALSE;
4463 return SystemTimeToFileTime(&st, ft);
4466 static WORD HTTP_ParseWeekday(LPCWSTR day)
4468 static const WCHAR days[7][10] = {{ 's','u','n','d','a','y',0 },
4469 { 'm','o','n','d','a','y',0 },
4470 { 't','u','e','s','d','a','y',0 },
4471 { 'w','e','d','n','e','s','d','a','y',0 },
4472 { 't','h','u','r','s','d','a','y',0 },
4473 { 'f','r','i','d','a','y',0 },
4474 { 's','a','t','u','r','d','a','y',0 }};
4475 unsigned int i;
4476 for (i = 0; i < sizeof(days)/sizeof(*days); i++)
4477 if (!strcmpiW(day, days[i]))
4478 return i;
4480 /* Invalid */
4481 return 7;
4484 static BOOL HTTP_ParseRfc850Date(LPCWSTR value, FILETIME *ft)
4486 static const WCHAR gmt[]= { 'G','M','T',0 };
4487 WCHAR *nextPtr, day[10], month[4], *monthPtr;
4488 LPCWSTR ptr;
4489 unsigned long num;
4490 SYSTEMTIME st = { 0 };
4492 ptr = strchrW(value, ',');
4493 if (!ptr)
4494 return FALSE;
4495 if (ptr - value == 3)
4497 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4498 day[3] = 0;
4499 st.wDayOfWeek = HTTP_ParseWkday(day);
4500 if (st.wDayOfWeek > 6)
4502 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4503 return FALSE;
4506 else if (ptr - value < sizeof(day) / sizeof(day[0]))
4508 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4509 day[ptr - value + 1] = 0;
4510 st.wDayOfWeek = HTTP_ParseWeekday(day);
4511 if (st.wDayOfWeek > 6)
4513 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4514 return FALSE;
4517 else
4519 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4520 return FALSE;
4522 ptr++;
4524 while (isspaceW(*ptr))
4525 ptr++;
4527 num = strtoulW(ptr, &nextPtr, 10);
4528 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4530 ERR("unexpected day %s\n", debugstr_w(value));
4531 return FALSE;
4533 ptr = nextPtr;
4534 st.wDay = (WORD)num;
4536 if (*ptr != '-')
4538 ERR("unexpected month format %s\n", debugstr_w(ptr));
4539 return FALSE;
4541 ptr++;
4543 for (monthPtr = month; *ptr != '-' &&
4544 monthPtr - month < sizeof(month) / sizeof(month[0]) - 1;
4545 monthPtr++, ptr++)
4546 *monthPtr = *ptr;
4547 *monthPtr = 0;
4548 st.wMonth = HTTP_ParseMonth(month);
4549 if (!st.wMonth || st.wMonth > 12)
4551 ERR("unexpected month %s\n", debugstr_w(month));
4552 return FALSE;
4555 if (*ptr != '-')
4557 ERR("unexpected year format %s\n", debugstr_w(ptr));
4558 return FALSE;
4560 ptr++;
4562 num = strtoulW(ptr, &nextPtr, 10);
4563 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4565 ERR("unexpected year %s\n", debugstr_w(value));
4566 return FALSE;
4568 ptr = nextPtr;
4569 st.wYear = (WORD)num;
4571 if (!HTTP_ParseTime(&st, &ptr))
4572 return FALSE;
4574 while (isspaceW(*ptr))
4575 ptr++;
4577 if (strcmpW(ptr, gmt))
4579 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4580 return FALSE;
4582 return SystemTimeToFileTime(&st, ft);
4585 static BOOL HTTP_ParseDate(LPCWSTR value, FILETIME *ft)
4587 static const WCHAR zero[] = { '0',0 };
4588 BOOL ret;
4590 if (!strcmpW(value, zero))
4592 ft->dwLowDateTime = ft->dwHighDateTime = 0;
4593 ret = TRUE;
4595 else if (strchrW(value, ','))
4597 ret = HTTP_ParseRfc1123Date(value, ft);
4598 if (!ret)
4600 ret = HTTP_ParseRfc850Date(value, ft);
4601 if (!ret)
4602 ERR("unexpected date format %s\n", debugstr_w(value));
4605 else
4607 ret = HTTP_ParseDateAsAsctime(value, ft);
4608 if (!ret)
4609 ERR("unexpected date format %s\n", debugstr_w(value));
4611 return ret;
4614 static void HTTP_ProcessExpires(http_request_t *request)
4616 BOOL expirationFound = FALSE;
4617 int headerIndex;
4619 EnterCriticalSection( &request->headers_section );
4621 /* Look for a Cache-Control header with a max-age directive, as it takes
4622 * precedence over the Expires header.
4624 headerIndex = HTTP_GetCustomHeaderIndex(request, szCache_Control, 0, FALSE);
4625 if (headerIndex != -1)
4627 LPHTTPHEADERW ccHeader = &request->custHeaders[headerIndex];
4628 LPWSTR ptr;
4630 for (ptr = ccHeader->lpszValue; ptr && *ptr; )
4632 LPWSTR comma = strchrW(ptr, ','), end, equal;
4634 if (comma)
4635 end = comma;
4636 else
4637 end = ptr + strlenW(ptr);
4638 for (equal = end - 1; equal > ptr && *equal != '='; equal--)
4640 if (*equal == '=')
4642 static const WCHAR max_age[] = {
4643 'm','a','x','-','a','g','e',0 };
4645 if (!strncmpiW(ptr, max_age, equal - ptr - 1))
4647 LPWSTR nextPtr;
4648 unsigned long age;
4650 age = strtoulW(equal + 1, &nextPtr, 10);
4651 if (nextPtr > equal + 1)
4653 LARGE_INTEGER ft;
4655 NtQuerySystemTime( &ft );
4656 /* Age is in seconds, FILETIME resolution is in
4657 * 100 nanosecond intervals.
4659 ft.QuadPart += age * (ULONGLONG)1000000;
4660 request->expires.dwLowDateTime = ft.u.LowPart;
4661 request->expires.dwHighDateTime = ft.u.HighPart;
4662 expirationFound = TRUE;
4666 if (comma)
4668 ptr = comma + 1;
4669 while (isspaceW(*ptr))
4670 ptr++;
4672 else
4673 ptr = NULL;
4676 if (!expirationFound)
4678 headerIndex = HTTP_GetCustomHeaderIndex(request, szExpires, 0, FALSE);
4679 if (headerIndex != -1)
4681 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4682 FILETIME ft;
4684 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4686 expirationFound = TRUE;
4687 request->expires = ft;
4691 if (!expirationFound)
4693 LARGE_INTEGER t;
4695 /* With no known age, default to 10 minutes until expiration. */
4696 NtQuerySystemTime( &t );
4697 t.QuadPart += 10 * 60 * (ULONGLONG)10000000;
4698 request->expires.dwLowDateTime = t.u.LowPart;
4699 request->expires.dwHighDateTime = t.u.HighPart;
4702 LeaveCriticalSection( &request->headers_section );
4705 static void HTTP_ProcessLastModified(http_request_t *request)
4707 int headerIndex;
4709 EnterCriticalSection( &request->headers_section );
4711 headerIndex = HTTP_GetCustomHeaderIndex(request, szLast_Modified, 0, FALSE);
4712 if (headerIndex != -1)
4714 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4715 FILETIME ft;
4717 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4718 request->last_modified = ft;
4721 LeaveCriticalSection( &request->headers_section );
4724 static void http_process_keep_alive(http_request_t *req)
4726 int index;
4728 EnterCriticalSection( &req->headers_section );
4730 if ((index = HTTP_GetCustomHeaderIndex(req, szConnection, 0, FALSE)) != -1)
4731 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4732 else if ((index = HTTP_GetCustomHeaderIndex(req, szProxy_Connection, 0, FALSE)) != -1)
4733 req->netconn->keep_alive = !strcmpiW(req->custHeaders[index].lpszValue, szKeepAlive);
4734 else
4735 req->netconn->keep_alive = !strcmpiW(req->version, g_szHttp1_1);
4737 LeaveCriticalSection( &req->headers_section );
4740 static DWORD open_http_connection(http_request_t *request, BOOL *reusing)
4742 netconn_t *netconn = NULL;
4743 DWORD res;
4745 if (request->netconn)
4747 if (NETCON_is_alive(request->netconn) && drain_content(request, TRUE) == ERROR_SUCCESS)
4749 reset_data_stream(request);
4750 *reusing = TRUE;
4751 return ERROR_SUCCESS;
4754 TRACE("freeing netconn\n");
4755 free_netconn(request->netconn);
4756 request->netconn = NULL;
4759 reset_data_stream(request);
4761 res = HTTP_ResolveName(request);
4762 if(res != ERROR_SUCCESS)
4763 return res;
4765 EnterCriticalSection(&connection_pool_cs);
4767 while(!list_empty(&request->server->conn_pool)) {
4768 netconn = LIST_ENTRY(list_head(&request->server->conn_pool), netconn_t, pool_entry);
4769 list_remove(&netconn->pool_entry);
4771 if(is_valid_netconn(netconn) && NETCON_is_alive(netconn))
4772 break;
4774 TRACE("connection %p closed during idle\n", netconn);
4775 free_netconn(netconn);
4776 netconn = NULL;
4779 LeaveCriticalSection(&connection_pool_cs);
4781 if(netconn) {
4782 TRACE("<-- reusing %p netconn\n", netconn);
4783 request->netconn = netconn;
4784 *reusing = TRUE;
4785 return ERROR_SUCCESS;
4788 TRACE("connecting to %s, proxy %s\n", debugstr_w(request->server->name),
4789 request->proxy ? debugstr_w(request->proxy->name) : "(null)");
4791 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4792 INTERNET_STATUS_CONNECTING_TO_SERVER,
4793 request->server->addr_str,
4794 strlen(request->server->addr_str)+1);
4796 res = create_netconn(request->proxy ? request->proxy : request->server, request->security_flags,
4797 (request->hdr.ErrorMask & INTERNET_ERROR_MASK_COMBINED_SEC_CERT) != 0,
4798 request->connect_timeout, &netconn);
4799 if(res != ERROR_SUCCESS) {
4800 ERR("create_netconn failed: %u\n", res);
4801 return res;
4804 request->netconn = netconn;
4806 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4807 INTERNET_STATUS_CONNECTED_TO_SERVER,
4808 request->server->addr_str, strlen(request->server->addr_str)+1);
4810 *reusing = FALSE;
4811 TRACE("Created connection to %s: %p\n", debugstr_w(request->server->name), netconn);
4812 return ERROR_SUCCESS;
4815 static char *build_ascii_request( const WCHAR *str, void *data, DWORD data_len, DWORD *out_len )
4817 int len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
4818 char *ret;
4820 if (!(ret = heap_alloc( len + data_len ))) return NULL;
4821 WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
4822 if (data_len) memcpy( ret + len - 1, data, data_len );
4823 *out_len = len + data_len - 1;
4824 ret[*out_len] = 0;
4825 return ret;
4828 static void set_content_length_header( http_request_t *request, DWORD len, DWORD flags )
4830 static const WCHAR fmtW[] =
4831 {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','u','\r','\n',0};
4832 WCHAR buf[sizeof(fmtW)/sizeof(fmtW[0]) + 10];
4834 sprintfW( buf, fmtW, len );
4835 HTTP_HttpAddRequestHeadersW( request, buf, ~0u, flags );
4838 /***********************************************************************
4839 * HTTP_HttpSendRequestW (internal)
4841 * Sends the specified request to the HTTP server
4843 * RETURNS
4844 * ERROR_SUCCESS on success
4845 * win32 error code on failure
4848 static DWORD HTTP_HttpSendRequestW(http_request_t *request, LPCWSTR lpszHeaders,
4849 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
4850 DWORD dwContentLength, BOOL bEndRequest)
4852 BOOL redirected = FALSE, secure_proxy_connect = FALSE, loop_next;
4853 WCHAR *request_header = NULL;
4854 INT responseLen, cnt;
4855 DWORD res;
4857 TRACE("--> %p\n", request);
4859 assert(request->hdr.htype == WH_HHTTPREQ);
4861 /* if the verb is NULL default to GET */
4862 if (!request->verb)
4863 request->verb = heap_strdupW(szGET);
4865 HTTP_ProcessHeader(request, hostW, request->server->canon_host_port,
4866 HTTP_ADDREQ_FLAG_ADD_IF_NEW | HTTP_ADDHDR_FLAG_REQ);
4868 if (dwContentLength || strcmpW(request->verb, szGET))
4870 set_content_length_header(request, dwContentLength, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4871 request->bytesToWrite = dwContentLength;
4873 if (request->session->appInfo->agent)
4875 WCHAR *agent_header;
4876 static const WCHAR user_agent[] = {'U','s','e','r','-','A','g','e','n','t',':',' ','%','s','\r','\n',0};
4877 int len;
4879 len = strlenW(request->session->appInfo->agent) + strlenW(user_agent);
4880 agent_header = heap_alloc(len * sizeof(WCHAR));
4881 sprintfW(agent_header, user_agent, request->session->appInfo->agent);
4883 HTTP_HttpAddRequestHeadersW(request, agent_header, strlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4884 heap_free(agent_header);
4886 if (request->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
4888 static const WCHAR pragma_nocache[] = {'P','r','a','g','m','a',':',' ','n','o','-','c','a','c','h','e','\r','\n',0};
4889 HTTP_HttpAddRequestHeadersW(request, pragma_nocache, strlenW(pragma_nocache), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4891 if ((request->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && strcmpW(request->verb, szGET))
4893 static const WCHAR cache_control[] = {'C','a','c','h','e','-','C','o','n','t','r','o','l',':',
4894 ' ','n','o','-','c','a','c','h','e','\r','\n',0};
4895 HTTP_HttpAddRequestHeadersW(request, cache_control, strlenW(cache_control), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
4898 /* add the headers the caller supplied */
4899 if( lpszHeaders && dwHeaderLength )
4900 HTTP_HttpAddRequestHeadersW(request, lpszHeaders, dwHeaderLength, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REPLACE);
4904 DWORD len, data_len = dwOptionalLength;
4905 BOOL reusing_connection;
4906 char *ascii_req;
4908 loop_next = FALSE;
4910 if(redirected) {
4911 request->contentLength = ~0u;
4912 request->bytesToWrite = 0;
4915 if (TRACE_ON(wininet))
4917 HTTPHEADERW *host;
4919 EnterCriticalSection( &request->headers_section );
4920 host = HTTP_GetHeader( request, hostW );
4921 TRACE("Going to url %s %s\n", debugstr_w(host->lpszValue), debugstr_w(request->path));
4922 LeaveCriticalSection( &request->headers_section );
4925 HTTP_FixURL(request);
4926 if (request->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
4928 HTTP_ProcessHeader(request, szConnection, szKeepAlive,
4929 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD);
4931 HTTP_InsertAuthorization(request, request->authInfo, szAuthorization);
4932 HTTP_InsertAuthorization(request, request->proxyAuthInfo, szProxy_Authorization);
4934 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
4935 HTTP_InsertCookies(request);
4937 res = open_http_connection(request, &reusing_connection);
4938 if (res != ERROR_SUCCESS)
4939 break;
4941 if (!reusing_connection && (request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4943 if (request->proxy) secure_proxy_connect = TRUE;
4944 else
4946 res = NETCON_secure_connect(request->netconn, request->server);
4947 if (res != ERROR_SUCCESS)
4949 WARN("failed to upgrade to secure connection\n");
4950 http_release_netconn(request, FALSE);
4951 break;
4955 if (secure_proxy_connect)
4957 static const WCHAR connectW[] = {'C','O','N','N','E','C','T',0};
4958 const WCHAR *target = request->server->host_port;
4960 if (HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE) >= 0)
4961 set_content_length_header(request, 0, HTTP_ADDREQ_FLAG_REPLACE);
4963 request_header = build_request_header(request, connectW, target, g_szHttp1_1, TRUE);
4965 else if (request->proxy && !(request->hdr.dwFlags & INTERNET_FLAG_SECURE))
4967 WCHAR *url = build_proxy_path_url(request);
4968 request_header = build_request_header(request, request->verb, url, request->version, TRUE);
4969 heap_free(url);
4971 else
4973 if (request->proxy && HTTP_GetCustomHeaderIndex(request, szContent_Length, 0, TRUE) >= 0)
4974 set_content_length_header(request, dwContentLength, HTTP_ADDREQ_FLAG_REPLACE);
4976 request_header = build_request_header(request, request->verb, request->path, request->version, TRUE);
4979 TRACE("Request header -> %s\n", debugstr_w(request_header) );
4981 /* send the request as ASCII, tack on the optional data */
4982 if (!lpOptional || redirected || secure_proxy_connect)
4983 data_len = 0;
4985 ascii_req = build_ascii_request(request_header, lpOptional, data_len, &len);
4986 heap_free(request_header);
4987 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
4989 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4990 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
4992 NETCON_set_timeout( request->netconn, TRUE, request->send_timeout );
4993 res = NETCON_send(request->netconn, ascii_req, len, 0, &cnt);
4994 heap_free( ascii_req );
4995 if(res != ERROR_SUCCESS) {
4996 TRACE("send failed: %u\n", res);
4997 if(!reusing_connection)
4998 break;
4999 http_release_netconn(request, FALSE);
5000 loop_next = TRUE;
5001 continue;
5004 request->bytesWritten = data_len;
5006 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5007 INTERNET_STATUS_REQUEST_SENT,
5008 &len, sizeof(DWORD));
5010 if (bEndRequest)
5012 DWORD dwBufferSize;
5014 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5015 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5017 if (HTTP_GetResponseHeaders(request, &responseLen))
5019 http_release_netconn(request, FALSE);
5020 res = ERROR_INTERNET_CONNECTION_ABORTED;
5021 goto lend;
5023 /* FIXME: We should know that connection is closed before sending
5024 * headers. Otherwise wrong callbacks are executed */
5025 if(!responseLen && reusing_connection) {
5026 TRACE("Connection closed by server, reconnecting\n");
5027 http_release_netconn(request, FALSE);
5028 loop_next = TRUE;
5029 continue;
5032 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5033 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
5034 sizeof(DWORD));
5036 http_process_keep_alive(request);
5037 HTTP_ProcessCookies(request);
5038 HTTP_ProcessExpires(request);
5039 HTTP_ProcessLastModified(request);
5041 res = set_content_length(request);
5042 if(res != ERROR_SUCCESS)
5043 goto lend;
5044 if(!request->contentLength && !secure_proxy_connect)
5045 http_release_netconn(request, TRUE);
5047 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
5049 WCHAR *new_url;
5051 switch(request->status_code) {
5052 case HTTP_STATUS_REDIRECT:
5053 case HTTP_STATUS_MOVED:
5054 case HTTP_STATUS_REDIRECT_KEEP_VERB:
5055 case HTTP_STATUS_REDIRECT_METHOD:
5056 new_url = get_redirect_url(request);
5057 if(!new_url)
5058 break;
5060 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5061 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5063 heap_free(request->verb);
5064 request->verb = heap_strdupW(szGET);
5066 http_release_netconn(request, drain_content(request, FALSE) == ERROR_SUCCESS);
5067 res = HTTP_HandleRedirect(request, new_url);
5068 heap_free(new_url);
5069 if (res == ERROR_SUCCESS)
5070 loop_next = TRUE;
5071 redirected = TRUE;
5074 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
5076 WCHAR szAuthValue[2048];
5077 dwBufferSize=2048;
5078 if (request->status_code == HTTP_STATUS_DENIED)
5080 WCHAR *host = heap_strdupW( request->server->canon_host_port );
5081 DWORD dwIndex = 0;
5082 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5084 if (HTTP_DoAuthorization(request, szAuthValue,
5085 &request->authInfo,
5086 request->session->userName,
5087 request->session->password, host))
5089 if (drain_content(request, TRUE) != ERROR_SUCCESS)
5091 FIXME("Could not drain content\n");
5092 http_release_netconn(request, FALSE);
5094 loop_next = TRUE;
5095 break;
5098 heap_free( host );
5100 if(!loop_next) {
5101 TRACE("Cleaning wrong authorization data\n");
5102 destroy_authinfo(request->authInfo);
5103 request->authInfo = NULL;
5106 if (request->status_code == HTTP_STATUS_PROXY_AUTH_REQ)
5108 DWORD dwIndex = 0;
5109 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5111 if (HTTP_DoAuthorization(request, szAuthValue,
5112 &request->proxyAuthInfo,
5113 request->session->appInfo->proxyUsername,
5114 request->session->appInfo->proxyPassword,
5115 NULL))
5117 if (drain_content(request, TRUE) != ERROR_SUCCESS)
5119 FIXME("Could not drain content\n");
5120 http_release_netconn(request, FALSE);
5122 loop_next = TRUE;
5123 break;
5127 if(!loop_next) {
5128 TRACE("Cleaning wrong proxy authorization data\n");
5129 destroy_authinfo(request->proxyAuthInfo);
5130 request->proxyAuthInfo = NULL;
5134 if (secure_proxy_connect && request->status_code == HTTP_STATUS_OK)
5136 res = NETCON_secure_connect(request->netconn, request->server);
5137 if (res != ERROR_SUCCESS)
5139 WARN("failed to upgrade to secure proxy connection\n");
5140 http_release_netconn( request, FALSE );
5141 break;
5143 remove_header(request, szProxy_Authorization, TRUE);
5144 destroy_authinfo(request->proxyAuthInfo);
5145 request->proxyAuthInfo = NULL;
5146 request->contentLength = 0;
5147 request->netconn_stream.content_length = 0;
5149 secure_proxy_connect = FALSE;
5150 loop_next = TRUE;
5153 else
5154 res = ERROR_SUCCESS;
5156 while (loop_next);
5158 lend:
5159 /* TODO: send notification for P3P header */
5161 if(res == ERROR_SUCCESS)
5162 create_cache_entry(request);
5164 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5166 if (res == ERROR_SUCCESS) {
5167 if(bEndRequest && request->contentLength && request->bytesWritten == request->bytesToWrite)
5168 HTTP_ReceiveRequestData(request);
5169 else
5170 send_request_complete(request,
5171 request->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)request->hdr.hInternet : 1, 0);
5172 }else {
5173 send_request_complete(request, 0, res);
5177 TRACE("<--\n");
5178 return res;
5181 typedef struct {
5182 task_header_t hdr;
5183 WCHAR *headers;
5184 DWORD headers_len;
5185 void *optional;
5186 DWORD optional_len;
5187 DWORD content_len;
5188 BOOL end_request;
5189 } send_request_task_t;
5191 /***********************************************************************
5193 * Helper functions for the HttpSendRequest(Ex) functions
5196 static void AsyncHttpSendRequestProc(task_header_t *hdr)
5198 send_request_task_t *task = (send_request_task_t*)hdr;
5199 http_request_t *request = (http_request_t*)task->hdr.hdr;
5201 TRACE("%p\n", request);
5203 HTTP_HttpSendRequestW(request, task->headers, task->headers_len, task->optional,
5204 task->optional_len, task->content_len, task->end_request);
5206 heap_free(task->headers);
5210 static DWORD HTTP_HttpEndRequestW(http_request_t *request, DWORD dwFlags, DWORD_PTR dwContext)
5212 INT responseLen;
5213 DWORD res = ERROR_SUCCESS;
5215 if(!is_valid_netconn(request->netconn)) {
5216 WARN("Not connected\n");
5217 send_request_complete(request, 0, ERROR_INTERNET_OPERATION_CANCELLED);
5218 return ERROR_INTERNET_OPERATION_CANCELLED;
5221 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5222 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5224 if (HTTP_GetResponseHeaders(request, &responseLen) || !responseLen)
5225 res = ERROR_HTTP_HEADER_NOT_FOUND;
5227 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5228 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
5230 /* process cookies here. Is this right? */
5231 http_process_keep_alive(request);
5232 HTTP_ProcessCookies(request);
5233 HTTP_ProcessExpires(request);
5234 HTTP_ProcessLastModified(request);
5236 if ((res = set_content_length(request)) == ERROR_SUCCESS) {
5237 if(!request->contentLength)
5238 http_release_netconn(request, TRUE);
5241 if (res == ERROR_SUCCESS && !(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
5243 switch(request->status_code) {
5244 case HTTP_STATUS_REDIRECT:
5245 case HTTP_STATUS_MOVED:
5246 case HTTP_STATUS_REDIRECT_METHOD:
5247 case HTTP_STATUS_REDIRECT_KEEP_VERB: {
5248 WCHAR *new_url;
5250 new_url = get_redirect_url(request);
5251 if(!new_url)
5252 break;
5254 if (strcmpW(request->verb, szGET) && strcmpW(request->verb, szHEAD) &&
5255 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5257 heap_free(request->verb);
5258 request->verb = heap_strdupW(szGET);
5260 http_release_netconn(request, drain_content(request, FALSE) == ERROR_SUCCESS);
5261 res = HTTP_HandleRedirect(request, new_url);
5262 heap_free(new_url);
5263 if (res == ERROR_SUCCESS)
5264 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, TRUE);
5269 if(res == ERROR_SUCCESS)
5270 create_cache_entry(request);
5272 if (res == ERROR_SUCCESS && request->contentLength)
5273 HTTP_ReceiveRequestData(request);
5274 else
5275 send_request_complete(request, res == ERROR_SUCCESS, res);
5277 return res;
5280 /***********************************************************************
5281 * HttpEndRequestA (WININET.@)
5283 * Ends an HTTP request that was started by HttpSendRequestEx
5285 * RETURNS
5286 * TRUE if successful
5287 * FALSE on failure
5290 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
5291 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5293 TRACE("(%p, %p, %08x, %08lx)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5295 if (lpBuffersOut)
5297 SetLastError(ERROR_INVALID_PARAMETER);
5298 return FALSE;
5301 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
5304 typedef struct {
5305 task_header_t hdr;
5306 DWORD flags;
5307 DWORD context;
5308 } end_request_task_t;
5310 static void AsyncHttpEndRequestProc(task_header_t *hdr)
5312 end_request_task_t *task = (end_request_task_t*)hdr;
5313 http_request_t *req = (http_request_t*)task->hdr.hdr;
5315 TRACE("%p\n", req);
5317 HTTP_HttpEndRequestW(req, task->flags, task->context);
5320 /***********************************************************************
5321 * HttpEndRequestW (WININET.@)
5323 * Ends an HTTP request that was started by HttpSendRequestEx
5325 * RETURNS
5326 * TRUE if successful
5327 * FALSE on failure
5330 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
5331 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5333 http_request_t *request;
5334 DWORD res;
5336 TRACE("%p %p %x %lx -->\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5338 if (lpBuffersOut)
5340 SetLastError(ERROR_INVALID_PARAMETER);
5341 return FALSE;
5344 request = (http_request_t*) get_handle_object( hRequest );
5346 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5348 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
5349 if (request)
5350 WININET_Release( &request->hdr );
5351 return FALSE;
5353 request->hdr.dwFlags |= dwFlags;
5355 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5357 end_request_task_t *task;
5359 task = alloc_async_task(&request->hdr, AsyncHttpEndRequestProc, sizeof(*task));
5360 task->flags = dwFlags;
5361 task->context = dwContext;
5363 INTERNET_AsyncCall(&task->hdr);
5364 res = ERROR_IO_PENDING;
5366 else
5367 res = HTTP_HttpEndRequestW(request, dwFlags, dwContext);
5369 WININET_Release( &request->hdr );
5370 TRACE("%u <--\n", res);
5371 if(res != ERROR_SUCCESS)
5372 SetLastError(res);
5373 return res == ERROR_SUCCESS;
5376 /***********************************************************************
5377 * HttpSendRequestExA (WININET.@)
5379 * Sends the specified request to the HTTP server and allows chunked
5380 * transfers.
5382 * RETURNS
5383 * Success: TRUE
5384 * Failure: FALSE, call GetLastError() for more information.
5386 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
5387 LPINTERNET_BUFFERSA lpBuffersIn,
5388 LPINTERNET_BUFFERSA lpBuffersOut,
5389 DWORD dwFlags, DWORD_PTR dwContext)
5391 INTERNET_BUFFERSW BuffersInW;
5392 BOOL rc = FALSE;
5393 DWORD headerlen;
5394 LPWSTR header = NULL;
5396 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5397 lpBuffersOut, dwFlags, dwContext);
5399 if (lpBuffersIn)
5401 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
5402 if (lpBuffersIn->lpcszHeader)
5404 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
5405 lpBuffersIn->dwHeadersLength,0,0);
5406 header = heap_alloc(headerlen*sizeof(WCHAR));
5407 if (!(BuffersInW.lpcszHeader = header))
5409 SetLastError(ERROR_OUTOFMEMORY);
5410 return FALSE;
5412 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
5413 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5414 header, headerlen);
5416 else
5417 BuffersInW.lpcszHeader = NULL;
5418 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
5419 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
5420 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
5421 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
5422 BuffersInW.Next = NULL;
5425 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
5427 heap_free(header);
5428 return rc;
5431 /***********************************************************************
5432 * HttpSendRequestExW (WININET.@)
5434 * Sends the specified request to the HTTP server and allows chunked
5435 * transfers
5437 * RETURNS
5438 * Success: TRUE
5439 * Failure: FALSE, call GetLastError() for more information.
5441 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
5442 LPINTERNET_BUFFERSW lpBuffersIn,
5443 LPINTERNET_BUFFERSW lpBuffersOut,
5444 DWORD dwFlags, DWORD_PTR dwContext)
5446 http_request_t *request;
5447 http_session_t *session;
5448 appinfo_t *hIC;
5449 DWORD res;
5451 TRACE("(%p, %p, %p, %08x, %08lx)\n", hRequest, lpBuffersIn,
5452 lpBuffersOut, dwFlags, dwContext);
5454 request = (http_request_t*) get_handle_object( hRequest );
5456 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5458 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5459 goto lend;
5462 session = request->session;
5463 assert(session->hdr.htype == WH_HHTTPSESSION);
5464 hIC = session->appInfo;
5465 assert(hIC->hdr.htype == WH_HINIT);
5467 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5469 send_request_task_t *task;
5471 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5472 if (lpBuffersIn)
5474 DWORD size = 0;
5476 if (lpBuffersIn->lpcszHeader)
5478 if (lpBuffersIn->dwHeadersLength == ~0u)
5479 size = (strlenW( lpBuffersIn->lpcszHeader ) + 1) * sizeof(WCHAR);
5480 else
5481 size = lpBuffersIn->dwHeadersLength * sizeof(WCHAR);
5483 task->headers = heap_alloc(size);
5484 memcpy(task->headers, lpBuffersIn->lpcszHeader, size);
5486 else task->headers = NULL;
5488 task->headers_len = size / sizeof(WCHAR);
5489 task->optional = lpBuffersIn->lpvBuffer;
5490 task->optional_len = lpBuffersIn->dwBufferLength;
5491 task->content_len = lpBuffersIn->dwBufferTotal;
5493 else
5495 task->headers = NULL;
5496 task->headers_len = 0;
5497 task->optional = NULL;
5498 task->optional_len = 0;
5499 task->content_len = 0;
5502 task->end_request = FALSE;
5504 INTERNET_AsyncCall(&task->hdr);
5505 res = ERROR_IO_PENDING;
5507 else
5509 if (lpBuffersIn)
5510 res = HTTP_HttpSendRequestW(request, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5511 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
5512 lpBuffersIn->dwBufferTotal, FALSE);
5513 else
5514 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, FALSE);
5517 lend:
5518 if ( request )
5519 WININET_Release( &request->hdr );
5521 TRACE("<---\n");
5522 SetLastError(res);
5523 return res == ERROR_SUCCESS;
5526 /***********************************************************************
5527 * HttpSendRequestW (WININET.@)
5529 * Sends the specified request to the HTTP server
5531 * RETURNS
5532 * TRUE on success
5533 * FALSE on failure
5536 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
5537 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5539 http_request_t *request;
5540 http_session_t *session = NULL;
5541 appinfo_t *hIC = NULL;
5542 DWORD res = ERROR_SUCCESS;
5544 TRACE("%p, %s, %i, %p, %i)\n", hHttpRequest,
5545 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
5547 request = (http_request_t*) get_handle_object( hHttpRequest );
5548 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5550 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5551 goto lend;
5554 session = request->session;
5555 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
5557 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5558 goto lend;
5561 hIC = session->appInfo;
5562 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
5564 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5565 goto lend;
5568 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5570 send_request_task_t *task;
5572 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5573 if (lpszHeaders)
5575 DWORD size;
5577 if (dwHeaderLength == ~0u) size = (strlenW(lpszHeaders) + 1) * sizeof(WCHAR);
5578 else size = dwHeaderLength * sizeof(WCHAR);
5580 task->headers = heap_alloc(size);
5581 memcpy(task->headers, lpszHeaders, size);
5583 else
5584 task->headers = NULL;
5585 task->headers_len = dwHeaderLength;
5586 task->optional = lpOptional;
5587 task->optional_len = dwOptionalLength;
5588 task->content_len = dwOptionalLength;
5589 task->end_request = TRUE;
5591 INTERNET_AsyncCall(&task->hdr);
5592 res = ERROR_IO_PENDING;
5594 else
5596 res = HTTP_HttpSendRequestW(request, lpszHeaders,
5597 dwHeaderLength, lpOptional, dwOptionalLength,
5598 dwOptionalLength, TRUE);
5600 lend:
5601 if( request )
5602 WININET_Release( &request->hdr );
5604 SetLastError(res);
5605 return res == ERROR_SUCCESS;
5608 /***********************************************************************
5609 * HttpSendRequestA (WININET.@)
5611 * Sends the specified request to the HTTP server
5613 * RETURNS
5614 * TRUE on success
5615 * FALSE on failure
5618 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
5619 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5621 BOOL result;
5622 LPWSTR szHeaders=NULL;
5623 DWORD nLen=dwHeaderLength;
5624 if(lpszHeaders!=NULL)
5626 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
5627 szHeaders = heap_alloc(nLen*sizeof(WCHAR));
5628 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
5630 result = HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
5631 heap_free(szHeaders);
5632 return result;
5635 /***********************************************************************
5636 * HTTPSESSION_Destroy (internal)
5638 * Deallocate session handle
5641 static void HTTPSESSION_Destroy(object_header_t *hdr)
5643 http_session_t *session = (http_session_t*) hdr;
5645 TRACE("%p\n", session);
5647 WININET_Release(&session->appInfo->hdr);
5649 heap_free(session->hostName);
5650 heap_free(session->password);
5651 heap_free(session->userName);
5654 static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
5656 http_session_t *ses = (http_session_t *)hdr;
5658 switch(option) {
5659 case INTERNET_OPTION_HANDLE_TYPE:
5660 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5662 if (*size < sizeof(ULONG))
5663 return ERROR_INSUFFICIENT_BUFFER;
5665 *size = sizeof(DWORD);
5666 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
5667 return ERROR_SUCCESS;
5668 case INTERNET_OPTION_CONNECT_TIMEOUT:
5669 TRACE("INTERNET_OPTION_CONNECT_TIMEOUT\n");
5671 if (*size < sizeof(DWORD))
5672 return ERROR_INSUFFICIENT_BUFFER;
5674 *size = sizeof(DWORD);
5675 *(DWORD *)buffer = ses->connect_timeout;
5676 return ERROR_SUCCESS;
5678 case INTERNET_OPTION_SEND_TIMEOUT:
5679 TRACE("INTERNET_OPTION_SEND_TIMEOUT\n");
5681 if (*size < sizeof(DWORD))
5682 return ERROR_INSUFFICIENT_BUFFER;
5684 *size = sizeof(DWORD);
5685 *(DWORD *)buffer = ses->send_timeout;
5686 return ERROR_SUCCESS;
5688 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5689 TRACE("INTERNET_OPTION_RECEIVE_TIMEOUT\n");
5691 if (*size < sizeof(DWORD))
5692 return ERROR_INSUFFICIENT_BUFFER;
5694 *size = sizeof(DWORD);
5695 *(DWORD *)buffer = ses->receive_timeout;
5696 return ERROR_SUCCESS;
5699 return INET_QueryOption(hdr, option, buffer, size, unicode);
5702 static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
5704 http_session_t *ses = (http_session_t*)hdr;
5706 switch(option) {
5707 case INTERNET_OPTION_USERNAME:
5709 heap_free(ses->userName);
5710 if (!(ses->userName = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5711 return ERROR_SUCCESS;
5713 case INTERNET_OPTION_PASSWORD:
5715 heap_free(ses->password);
5716 if (!(ses->password = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5717 return ERROR_SUCCESS;
5719 case INTERNET_OPTION_PROXY_USERNAME:
5721 heap_free(ses->appInfo->proxyUsername);
5722 if (!(ses->appInfo->proxyUsername = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5723 return ERROR_SUCCESS;
5725 case INTERNET_OPTION_PROXY_PASSWORD:
5727 heap_free(ses->appInfo->proxyPassword);
5728 if (!(ses->appInfo->proxyPassword = heap_strdupW(buffer))) return ERROR_OUTOFMEMORY;
5729 return ERROR_SUCCESS;
5731 case INTERNET_OPTION_CONNECT_TIMEOUT:
5733 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5734 ses->connect_timeout = *(DWORD *)buffer;
5735 return ERROR_SUCCESS;
5737 case INTERNET_OPTION_SEND_TIMEOUT:
5739 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5740 ses->send_timeout = *(DWORD *)buffer;
5741 return ERROR_SUCCESS;
5743 case INTERNET_OPTION_RECEIVE_TIMEOUT:
5745 if (!buffer || size != sizeof(DWORD)) return ERROR_INVALID_PARAMETER;
5746 ses->receive_timeout = *(DWORD *)buffer;
5747 return ERROR_SUCCESS;
5749 default: break;
5752 return INET_SetOption(hdr, option, buffer, size);
5755 static const object_vtbl_t HTTPSESSIONVtbl = {
5756 HTTPSESSION_Destroy,
5757 NULL,
5758 HTTPSESSION_QueryOption,
5759 HTTPSESSION_SetOption,
5760 NULL,
5761 NULL,
5762 NULL,
5763 NULL
5767 /***********************************************************************
5768 * HTTP_Connect (internal)
5770 * Create http session handle
5772 * RETURNS
5773 * HINTERNET a session handle on success
5774 * NULL on failure
5777 DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
5778 INTERNET_PORT serverPort, LPCWSTR lpszUserName,
5779 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
5780 DWORD dwInternalFlags, HINTERNET *ret)
5782 http_session_t *session = NULL;
5784 TRACE("-->\n");
5786 if (!lpszServerName || !lpszServerName[0])
5787 return ERROR_INVALID_PARAMETER;
5789 assert( hIC->hdr.htype == WH_HINIT );
5791 session = alloc_object(&hIC->hdr, &HTTPSESSIONVtbl, sizeof(http_session_t));
5792 if (!session)
5793 return ERROR_OUTOFMEMORY;
5796 * According to my tests. The name is not resolved until a request is sent
5799 session->hdr.htype = WH_HHTTPSESSION;
5800 session->hdr.dwFlags = dwFlags;
5801 session->hdr.dwContext = dwContext;
5802 session->hdr.dwInternalFlags |= dwInternalFlags;
5804 WININET_AddRef( &hIC->hdr );
5805 session->appInfo = hIC;
5806 list_add_head( &hIC->hdr.children, &session->hdr.entry );
5808 session->hostName = heap_strdupW(lpszServerName);
5809 if (lpszUserName && lpszUserName[0])
5810 session->userName = heap_strdupW(lpszUserName);
5811 session->password = heap_strdupW(lpszPassword);
5812 session->hostPort = serverPort;
5813 session->connect_timeout = hIC->connect_timeout;
5814 session->send_timeout = 0;
5815 session->receive_timeout = 0;
5817 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5818 if (!(session->hdr.dwInternalFlags & INET_OPENURL))
5820 INTERNET_SendCallback(&hIC->hdr, dwContext,
5821 INTERNET_STATUS_HANDLE_CREATED, &session->hdr.hInternet,
5822 sizeof(HINTERNET));
5826 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5827 * windows
5830 TRACE("%p --> %p\n", hIC, session);
5832 *ret = session->hdr.hInternet;
5833 return ERROR_SUCCESS;
5836 /***********************************************************************
5837 * HTTP_clear_response_headers (internal)
5839 * clear out any old response headers
5841 static void HTTP_clear_response_headers( http_request_t *request )
5843 DWORD i;
5845 EnterCriticalSection( &request->headers_section );
5847 for( i=0; i<request->nCustHeaders; i++)
5849 if( !request->custHeaders[i].lpszField )
5850 continue;
5851 if( !request->custHeaders[i].lpszValue )
5852 continue;
5853 if ( request->custHeaders[i].wFlags & HDR_ISREQUEST )
5854 continue;
5855 HTTP_DeleteCustomHeader( request, i );
5856 i--;
5859 LeaveCriticalSection( &request->headers_section );
5862 /***********************************************************************
5863 * HTTP_GetResponseHeaders (internal)
5865 * Read server response
5867 * RETURNS
5869 * TRUE on success
5870 * FALSE on error
5872 static DWORD HTTP_GetResponseHeaders(http_request_t *request, INT *len)
5874 INT cbreaks = 0;
5875 WCHAR buffer[MAX_REPLY_LEN];
5876 DWORD buflen = MAX_REPLY_LEN;
5877 INT rc = 0;
5878 char bufferA[MAX_REPLY_LEN];
5879 LPWSTR status_code = NULL, status_text = NULL;
5880 DWORD res = ERROR_HTTP_INVALID_SERVER_RESPONSE;
5881 BOOL codeHundred = FALSE;
5883 TRACE("-->\n");
5885 if(!is_valid_netconn(request->netconn))
5886 goto lend;
5888 /* clear old response headers (eg. from a redirect response) */
5889 HTTP_clear_response_headers( request );
5891 NETCON_set_timeout( request->netconn, FALSE, request->receive_timeout );
5892 do {
5894 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
5896 buflen = MAX_REPLY_LEN;
5897 if ((res = read_line(request, bufferA, &buflen)))
5898 goto lend;
5900 if (!buflen) goto lend;
5902 rc += buflen;
5903 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5904 /* check is this a status code line? */
5905 if (!strncmpW(buffer, g_szHttp1_0, 4))
5907 /* split the version from the status code */
5908 status_code = strchrW( buffer, ' ' );
5909 if( !status_code )
5910 goto lend;
5911 *status_code++=0;
5913 /* split the status code from the status text */
5914 status_text = strchrW( status_code, ' ' );
5915 if( status_text )
5916 *status_text++=0;
5918 request->status_code = atoiW(status_code);
5920 TRACE("version [%s] status code [%s] status text [%s]\n",
5921 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
5923 codeHundred = request->status_code == HTTP_STATUS_CONTINUE;
5925 else if (!codeHundred)
5927 WARN("No status line at head of response (%s)\n", debugstr_w(buffer));
5929 heap_free(request->version);
5930 heap_free(request->statusText);
5932 request->status_code = HTTP_STATUS_OK;
5933 request->version = heap_strdupW(g_szHttp1_0);
5934 request->statusText = heap_strdupW(szOK);
5936 goto lend;
5938 } while (codeHundred);
5940 /* Add status code */
5941 HTTP_ProcessHeader(request, szStatus, status_code,
5942 HTTP_ADDHDR_FLAG_REPLACE | HTTP_ADDHDR_FLAG_ADD);
5944 heap_free(request->version);
5945 heap_free(request->statusText);
5947 request->version = heap_strdupW(buffer);
5948 request->statusText = heap_strdupW(status_text ? status_text : emptyW);
5950 /* Restore the spaces */
5951 *(status_code-1) = ' ';
5952 if (status_text)
5953 *(status_text-1) = ' ';
5955 /* Parse each response line */
5958 buflen = MAX_REPLY_LEN;
5959 if (!read_line(request, bufferA, &buflen) && buflen)
5961 LPWSTR * pFieldAndValue;
5963 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
5965 if (!bufferA[0]) break;
5966 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
5968 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
5969 if (pFieldAndValue)
5971 HTTP_ProcessHeader(request, pFieldAndValue[0], pFieldAndValue[1],
5972 HTTP_ADDREQ_FLAG_ADD );
5973 HTTP_FreeTokens(pFieldAndValue);
5976 else
5978 cbreaks++;
5979 if (cbreaks >= 2)
5980 break;
5982 }while(1);
5984 res = ERROR_SUCCESS;
5986 lend:
5988 *len = rc;
5989 TRACE("<--\n");
5990 return res;
5993 /***********************************************************************
5994 * HTTP_InterpretHttpHeader (internal)
5996 * Parse server response
5998 * RETURNS
6000 * Pointer to array of field, value, NULL on success.
6001 * NULL on error.
6003 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
6005 LPWSTR * pTokenPair;
6006 LPWSTR pszColon;
6007 INT len;
6009 pTokenPair = heap_alloc_zero(sizeof(*pTokenPair)*3);
6011 pszColon = strchrW(buffer, ':');
6012 /* must have two tokens */
6013 if (!pszColon)
6015 HTTP_FreeTokens(pTokenPair);
6016 if (buffer[0])
6017 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
6018 return NULL;
6021 pTokenPair[0] = heap_alloc((pszColon - buffer + 1) * sizeof(WCHAR));
6022 if (!pTokenPair[0])
6024 HTTP_FreeTokens(pTokenPair);
6025 return NULL;
6027 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
6028 pTokenPair[0][pszColon - buffer] = '\0';
6030 /* skip colon */
6031 pszColon++;
6032 len = strlenW(pszColon);
6033 pTokenPair[1] = heap_alloc((len + 1) * sizeof(WCHAR));
6034 if (!pTokenPair[1])
6036 HTTP_FreeTokens(pTokenPair);
6037 return NULL;
6039 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
6041 strip_spaces(pTokenPair[0]);
6042 strip_spaces(pTokenPair[1]);
6044 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
6045 return pTokenPair;
6048 /***********************************************************************
6049 * HTTP_ProcessHeader (internal)
6051 * Stuff header into header tables according to <dwModifier>
6055 #define COALESCEFLAGS (HTTP_ADDHDR_FLAG_COALESCE|HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA|HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6057 static DWORD HTTP_ProcessHeader(http_request_t *request, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
6059 LPHTTPHEADERW lphttpHdr = NULL;
6060 INT index;
6061 BOOL request_only = !!(dwModifier & HTTP_ADDHDR_FLAG_REQ);
6062 DWORD res = ERROR_HTTP_INVALID_HEADER;
6064 TRACE("--> %s: %s - 0x%08x\n", debugstr_w(field), debugstr_w(value), dwModifier);
6066 EnterCriticalSection( &request->headers_section );
6068 /* REPLACE wins out over ADD */
6069 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6070 dwModifier &= ~HTTP_ADDHDR_FLAG_ADD;
6072 if (dwModifier & HTTP_ADDHDR_FLAG_ADD)
6073 index = -1;
6074 else
6075 index = HTTP_GetCustomHeaderIndex(request, field, 0, request_only);
6077 if (index >= 0)
6079 if (dwModifier & HTTP_ADDHDR_FLAG_ADD_IF_NEW)
6081 LeaveCriticalSection( &request->headers_section );
6082 return ERROR_HTTP_INVALID_HEADER;
6084 lphttpHdr = &request->custHeaders[index];
6086 else if (value)
6088 HTTPHEADERW hdr;
6090 hdr.lpszField = (LPWSTR)field;
6091 hdr.lpszValue = (LPWSTR)value;
6092 hdr.wFlags = hdr.wCount = 0;
6094 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6095 hdr.wFlags |= HDR_ISREQUEST;
6097 res = HTTP_InsertCustomHeader(request, &hdr);
6098 LeaveCriticalSection( &request->headers_section );
6099 return res;
6101 /* no value to delete */
6102 else
6104 LeaveCriticalSection( &request->headers_section );
6105 return ERROR_SUCCESS;
6108 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6109 lphttpHdr->wFlags |= HDR_ISREQUEST;
6110 else
6111 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
6113 if (dwModifier & HTTP_ADDHDR_FLAG_REPLACE)
6115 HTTP_DeleteCustomHeader( request, index );
6117 if (value && value[0])
6119 HTTPHEADERW hdr;
6121 hdr.lpszField = (LPWSTR)field;
6122 hdr.lpszValue = (LPWSTR)value;
6123 hdr.wFlags = hdr.wCount = 0;
6125 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6126 hdr.wFlags |= HDR_ISREQUEST;
6128 res = HTTP_InsertCustomHeader(request, &hdr);
6129 LeaveCriticalSection( &request->headers_section );
6130 return res;
6133 LeaveCriticalSection( &request->headers_section );
6134 return ERROR_SUCCESS;
6136 else if (dwModifier & COALESCEFLAGS)
6138 LPWSTR lpsztmp;
6139 WCHAR ch = 0;
6140 INT len = 0;
6141 INT origlen = strlenW(lphttpHdr->lpszValue);
6142 INT valuelen = strlenW(value);
6144 if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_COMMA)
6146 ch = ',';
6147 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6149 else if (dwModifier & HTTP_ADDHDR_FLAG_COALESCE_WITH_SEMICOLON)
6151 ch = ';';
6152 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6155 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
6157 lpsztmp = heap_realloc(lphttpHdr->lpszValue, (len+1)*sizeof(WCHAR));
6158 if (lpsztmp)
6160 lphttpHdr->lpszValue = lpsztmp;
6161 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6162 if (ch > 0)
6164 lphttpHdr->lpszValue[origlen] = ch;
6165 origlen++;
6166 lphttpHdr->lpszValue[origlen] = ' ';
6167 origlen++;
6170 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
6171 lphttpHdr->lpszValue[len] = '\0';
6172 res = ERROR_SUCCESS;
6174 else
6176 WARN("heap_realloc (%d bytes) failed\n",len+1);
6177 res = ERROR_OUTOFMEMORY;
6180 TRACE("<-- %d\n", res);
6181 LeaveCriticalSection( &request->headers_section );
6182 return res;
6185 /***********************************************************************
6186 * HTTP_GetCustomHeaderIndex (internal)
6188 * Return index of custom header from header array
6189 * Headers section must be held
6191 static INT HTTP_GetCustomHeaderIndex(http_request_t *request, LPCWSTR lpszField,
6192 int requested_index, BOOL request_only)
6194 DWORD index;
6196 TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
6198 for (index = 0; index < request->nCustHeaders; index++)
6200 if (strcmpiW(request->custHeaders[index].lpszField, lpszField))
6201 continue;
6203 if (request_only && !(request->custHeaders[index].wFlags & HDR_ISREQUEST))
6204 continue;
6206 if (!request_only && (request->custHeaders[index].wFlags & HDR_ISREQUEST))
6207 continue;
6209 if (requested_index == 0)
6210 break;
6211 requested_index --;
6214 if (index >= request->nCustHeaders)
6215 index = -1;
6217 TRACE("Return: %d\n", index);
6218 return index;
6222 /***********************************************************************
6223 * HTTP_InsertCustomHeader (internal)
6225 * Insert header into array
6226 * Headers section must be held
6228 static DWORD HTTP_InsertCustomHeader(http_request_t *request, LPHTTPHEADERW lpHdr)
6230 INT count;
6231 LPHTTPHEADERW lph = NULL;
6233 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
6234 count = request->nCustHeaders + 1;
6235 if (count > 1)
6236 lph = heap_realloc_zero(request->custHeaders, sizeof(HTTPHEADERW) * count);
6237 else
6238 lph = heap_alloc_zero(sizeof(HTTPHEADERW) * count);
6240 if (!lph)
6241 return ERROR_OUTOFMEMORY;
6243 request->custHeaders = lph;
6244 request->custHeaders[count-1].lpszField = heap_strdupW(lpHdr->lpszField);
6245 request->custHeaders[count-1].lpszValue = heap_strdupW(lpHdr->lpszValue);
6246 request->custHeaders[count-1].wFlags = lpHdr->wFlags;
6247 request->custHeaders[count-1].wCount= lpHdr->wCount;
6248 request->nCustHeaders++;
6250 return ERROR_SUCCESS;
6254 /***********************************************************************
6255 * HTTP_DeleteCustomHeader (internal)
6257 * Delete header from array
6258 * If this function is called, the index may change.
6259 * Headers section must be held
6261 static BOOL HTTP_DeleteCustomHeader(http_request_t *request, DWORD index)
6263 if( request->nCustHeaders <= 0 )
6264 return FALSE;
6265 if( index >= request->nCustHeaders )
6266 return FALSE;
6267 request->nCustHeaders--;
6269 heap_free(request->custHeaders[index].lpszField);
6270 heap_free(request->custHeaders[index].lpszValue);
6272 memmove( &request->custHeaders[index], &request->custHeaders[index+1],
6273 (request->nCustHeaders - index)* sizeof(HTTPHEADERW) );
6274 memset( &request->custHeaders[request->nCustHeaders], 0, sizeof(HTTPHEADERW) );
6276 return TRUE;
6280 /***********************************************************************
6281 * IsHostInProxyBypassList (@)
6283 * Undocumented
6286 BOOL WINAPI IsHostInProxyBypassList(DWORD flags, LPCSTR szHost, DWORD length)
6288 FIXME("STUB: flags=%d host=%s length=%d\n",flags,szHost,length);
6289 return FALSE;