include/mscvpdb.h: Use flexible array members for the rest of structures.
[wine.git] / dlls / wininet / http.c
blobc0f1e13bfa858415c41e6c98934b97474bfc3005
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 <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <time.h>
34 #include <assert.h>
35 #include <errno.h>
36 #include <limits.h>
37 #include <zlib.h>
39 #include "windef.h"
40 #include "winbase.h"
41 #include "wininet.h"
42 #include "winerror.h"
43 #include "winternl.h"
44 #include "winsock2.h"
45 #include "ws2ipdef.h"
46 #define NO_SHLWAPI_STREAM
47 #define NO_SHLWAPI_REG
48 #define NO_SHLWAPI_GDI
49 #include "shlwapi.h"
50 #include "sspi.h"
51 #include "wincrypt.h"
52 #include "winuser.h"
54 #include "internet.h"
55 #include "resource.h"
56 #include "wine/debug.h"
57 #include "wine/exception.h"
59 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
61 #define HTTP_ADDHDR_FLAG_REQ 0x02000000
63 #define COLLECT_TIME 60000
65 struct HttpAuthInfo
67 LPWSTR scheme;
68 CredHandle cred;
69 CtxtHandle ctx;
70 TimeStamp exp;
71 ULONG attr;
72 ULONG max_token;
73 void *auth_data;
74 unsigned int auth_data_len;
75 BOOL finished; /* finished authenticating */
79 typedef struct _basicAuthorizationData
81 struct list entry;
83 LPWSTR host;
84 LPWSTR realm;
85 LPSTR authorization;
86 UINT authorizationLen;
87 } basicAuthorizationData;
89 typedef struct _authorizationData
91 struct list entry;
93 LPWSTR host;
94 LPWSTR scheme;
95 LPWSTR domain;
96 UINT domain_len;
97 LPWSTR user;
98 UINT user_len;
99 LPWSTR password;
100 UINT password_len;
101 } authorizationData;
103 static struct list basicAuthorizationCache = LIST_INIT(basicAuthorizationCache);
104 static struct list authorizationCache = LIST_INIT(authorizationCache);
106 static CRITICAL_SECTION authcache_cs;
107 static CRITICAL_SECTION_DEBUG critsect_debug =
109 0, 0, &authcache_cs,
110 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
111 0, 0, { (DWORD_PTR)(__FILE__ ": authcache_cs") }
113 static CRITICAL_SECTION authcache_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
115 static DWORD HTTP_GetResponseHeaders(http_request_t *req, INT *len);
116 static DWORD HTTP_ProcessHeader(http_request_t *req, LPCWSTR field, LPCWSTR value, DWORD dwModifier);
117 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer);
118 static DWORD HTTP_InsertCustomHeader(http_request_t *req, LPHTTPHEADERW lpHdr);
119 static INT HTTP_GetCustomHeaderIndex(http_request_t *req, LPCWSTR lpszField, INT index, BOOL Request);
120 static BOOL HTTP_DeleteCustomHeader(http_request_t *req, DWORD index);
121 static LPWSTR HTTP_build_req( LPCWSTR *list, int len );
122 static DWORD HTTP_HttpQueryInfoW(http_request_t*, DWORD, LPVOID, LPDWORD, LPDWORD);
123 static UINT HTTP_DecodeBase64(LPCWSTR base64, LPSTR bin);
124 static DWORD drain_content(http_request_t*,BOOL);
126 static CRITICAL_SECTION connection_pool_cs;
127 static CRITICAL_SECTION_DEBUG connection_pool_debug =
129 0, 0, &connection_pool_cs,
130 { &connection_pool_debug.ProcessLocksList, &connection_pool_debug.ProcessLocksList },
131 0, 0, { (DWORD_PTR)(__FILE__ ": connection_pool_cs") }
133 static CRITICAL_SECTION connection_pool_cs = { &connection_pool_debug, -1, 0, 0, 0, 0 };
135 static struct list connection_pool = LIST_INIT(connection_pool);
136 static BOOL collector_running;
138 void server_addref(server_t *server)
140 InterlockedIncrement(&server->ref);
143 void server_release(server_t *server)
145 if(InterlockedDecrement(&server->ref))
146 return;
148 list_remove(&server->entry);
150 if(server->cert_chain)
151 CertFreeCertificateChain(server->cert_chain);
152 free(server->name);
153 free(server->scheme_host_port);
154 free(server);
157 static BOOL process_host_port(server_t *server)
159 BOOL default_port;
160 size_t name_len, len;
161 WCHAR *buf;
163 name_len = lstrlenW(server->name);
164 len = name_len + 10 /* strlen("://:<port>") */ + ARRAY_SIZE(L"https");
165 buf = malloc(len * sizeof(WCHAR));
166 if(!buf)
167 return FALSE;
169 swprintf(buf, len, L"%s://%s:%u", server->is_https ? L"https" : L"http", server->name, server->port);
170 server->scheme_host_port = buf;
172 server->host_port = server->scheme_host_port + 7 /* strlen("http://") */;
173 if(server->is_https)
174 server->host_port++;
176 default_port = server->port == (server->is_https ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT);
177 server->canon_host_port = default_port ? server->name : server->host_port;
178 return TRUE;
181 server_t *get_server(substr_t name, INTERNET_PORT port, BOOL is_https, BOOL do_create)
183 server_t *iter, *server = NULL;
185 EnterCriticalSection(&connection_pool_cs);
187 LIST_FOR_EACH_ENTRY(iter, &connection_pool, server_t, entry) {
188 if(iter->port == port && name.len == lstrlenW(iter->name) && !wcsnicmp(iter->name, name.str, name.len)
189 && iter->is_https == is_https) {
190 server = iter;
191 server_addref(server);
192 break;
196 if(!server && do_create) {
197 server = calloc(1, sizeof(*server));
198 if(server) {
199 server->ref = 2; /* list reference and return */
200 server->port = port;
201 server->is_https = is_https;
202 list_init(&server->conn_pool);
203 server->name = strndupW(name.str, name.len);
204 if(server->name && process_host_port(server)) {
205 list_add_head(&connection_pool, &server->entry);
206 }else {
207 free(server);
208 server = NULL;
213 LeaveCriticalSection(&connection_pool_cs);
215 return server;
218 BOOL collect_connections(collect_type_t collect_type)
220 netconn_t *netconn, *netconn_safe;
221 server_t *server, *server_safe;
222 BOOL remaining = FALSE;
223 DWORD64 now;
225 now = GetTickCount64();
227 LIST_FOR_EACH_ENTRY_SAFE(server, server_safe, &connection_pool, server_t, entry) {
228 LIST_FOR_EACH_ENTRY_SAFE(netconn, netconn_safe, &server->conn_pool, netconn_t, pool_entry) {
229 if(collect_type > COLLECT_TIMEOUT || netconn->keep_until < now) {
230 TRACE("freeing %p\n", netconn);
231 list_remove(&netconn->pool_entry);
232 free_netconn(netconn);
233 }else {
234 remaining = TRUE;
238 if(collect_type == COLLECT_CLEANUP) {
239 list_remove(&server->entry);
240 list_init(&server->entry);
241 server_release(server);
245 return remaining;
248 static DWORD WINAPI collect_connections_proc(void *arg)
250 BOOL remaining_conns;
252 SetThreadDescription(GetCurrentThread(), L"wine_wininet_collect_connections");
253 do {
254 /* FIXME: Use more sophisticated method */
255 Sleep(5000);
257 EnterCriticalSection(&connection_pool_cs);
259 remaining_conns = collect_connections(COLLECT_TIMEOUT);
260 if(!remaining_conns)
261 collector_running = FALSE;
263 LeaveCriticalSection(&connection_pool_cs);
264 }while(remaining_conns);
266 FreeLibraryAndExitThread(WININET_hModule, 0);
269 /***********************************************************************
270 * HTTP_GetHeader (internal)
272 * Headers section must be held
274 static LPHTTPHEADERW HTTP_GetHeader(http_request_t *req, LPCWSTR head)
276 int HeaderIndex = 0;
277 HeaderIndex = HTTP_GetCustomHeaderIndex(req, head, 0, TRUE);
278 if (HeaderIndex == -1)
279 return NULL;
280 else
281 return &req->custHeaders[HeaderIndex];
284 static WCHAR *get_host_header( http_request_t *req )
286 HTTPHEADERW *header;
287 WCHAR *ret = NULL;
289 EnterCriticalSection( &req->headers_section );
290 if ((header = HTTP_GetHeader( req, L"Host" ))) ret = wcsdup( header->lpszValue );
291 else ret = wcsdup( req->server->canon_host_port );
292 LeaveCriticalSection( &req->headers_section );
293 return ret;
296 struct data_stream_vtbl_t {
297 BOOL (*end_of_data)(data_stream_t*,http_request_t*);
298 DWORD (*read)(data_stream_t*,http_request_t*,BYTE*,DWORD,DWORD*,BOOL);
299 DWORD (*drain_content)(data_stream_t*,http_request_t*,BOOL);
300 void (*destroy)(data_stream_t*);
303 typedef struct {
304 data_stream_t data_stream;
306 BYTE buf[READ_BUFFER_SIZE];
307 DWORD buf_size;
308 DWORD buf_pos;
309 DWORD chunk_size;
311 enum {
312 CHUNKED_STREAM_STATE_READING_CHUNK_SIZE,
313 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE,
314 CHUNKED_STREAM_STATE_READING_CHUNK,
315 CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA,
316 CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END,
317 CHUNKED_STREAM_STATE_END_OF_STREAM,
318 CHUNKED_STREAM_STATE_ERROR
319 } state;
320 } chunked_stream_t;
322 static inline void destroy_data_stream(data_stream_t *stream)
324 stream->vtbl->destroy(stream);
327 static void reset_data_stream(http_request_t *req)
329 destroy_data_stream(req->data_stream);
330 req->data_stream = &req->netconn_stream.data_stream;
331 req->read_pos = req->read_size = req->netconn_stream.content_read = 0;
332 req->content_pos = 0;
333 req->read_gzip = FALSE;
336 static void remove_header( http_request_t *request, const WCHAR *str, BOOL from_request )
338 int index;
339 EnterCriticalSection( &request->headers_section );
340 index = HTTP_GetCustomHeaderIndex( request, str, 0, from_request );
341 if (index != -1) HTTP_DeleteCustomHeader( request, index );
342 LeaveCriticalSection( &request->headers_section );
345 typedef struct {
346 data_stream_t stream;
347 data_stream_t *parent_stream;
348 z_stream zstream;
349 BYTE buf[READ_BUFFER_SIZE];
350 DWORD buf_size;
351 DWORD buf_pos;
352 BOOL end_of_data;
353 } gzip_stream_t;
355 static BOOL gzip_end_of_data(data_stream_t *stream, http_request_t *req)
357 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
358 return gzip_stream->end_of_data
359 || (!gzip_stream->buf_size && gzip_stream->parent_stream->vtbl->end_of_data(gzip_stream->parent_stream, req));
362 static DWORD gzip_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
363 DWORD *read, BOOL allow_blocking)
365 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
366 z_stream *zstream = &gzip_stream->zstream;
367 DWORD current_read, ret_read = 0;
368 int zres;
369 DWORD res = ERROR_SUCCESS;
371 TRACE("(%ld %x)\n", size, allow_blocking);
373 while(size && !gzip_stream->end_of_data) {
374 if(!gzip_stream->buf_size) {
375 if(gzip_stream->buf_pos) {
376 if(gzip_stream->buf_size)
377 memmove(gzip_stream->buf, gzip_stream->buf+gzip_stream->buf_pos, gzip_stream->buf_size);
378 gzip_stream->buf_pos = 0;
380 res = gzip_stream->parent_stream->vtbl->read(gzip_stream->parent_stream, req, gzip_stream->buf+gzip_stream->buf_size,
381 sizeof(gzip_stream->buf)-gzip_stream->buf_size, &current_read, allow_blocking);
382 if(res != ERROR_SUCCESS)
383 break;
385 gzip_stream->buf_size += current_read;
386 if(!current_read) {
387 WARN("unexpected end of data\n");
388 gzip_stream->end_of_data = TRUE;
389 break;
393 zstream->next_in = gzip_stream->buf+gzip_stream->buf_pos;
394 zstream->avail_in = gzip_stream->buf_size;
395 zstream->next_out = buf+ret_read;
396 zstream->avail_out = size;
397 zres = inflate(&gzip_stream->zstream, 0);
398 current_read = size - zstream->avail_out;
399 size -= current_read;
400 ret_read += current_read;
401 gzip_stream->buf_size -= zstream->next_in - (gzip_stream->buf+gzip_stream->buf_pos);
402 gzip_stream->buf_pos = zstream->next_in-gzip_stream->buf;
403 if(zres == Z_STREAM_END) {
404 TRACE("end of data\n");
405 gzip_stream->end_of_data = TRUE;
406 inflateEnd(zstream);
407 }else if(zres != Z_OK) {
408 WARN("inflate failed %d: %s\n", zres, debugstr_a(zstream->msg));
409 if(!ret_read)
410 res = ERROR_INTERNET_DECODING_FAILED;
411 break;
414 if(ret_read)
415 allow_blocking = FALSE;
418 TRACE("read %lu bytes\n", ret_read);
419 if(ret_read)
420 res = ERROR_SUCCESS;
421 *read = ret_read;
422 return res;
425 static DWORD gzip_drain_content(data_stream_t *stream, http_request_t *req, BOOL allow_blocking)
427 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
428 return gzip_stream->parent_stream->vtbl->drain_content(gzip_stream->parent_stream, req, allow_blocking);
431 static void gzip_destroy(data_stream_t *stream)
433 gzip_stream_t *gzip_stream = (gzip_stream_t*)stream;
435 destroy_data_stream(gzip_stream->parent_stream);
437 if(!gzip_stream->end_of_data)
438 inflateEnd(&gzip_stream->zstream);
439 free(gzip_stream);
442 static const data_stream_vtbl_t gzip_stream_vtbl = {
443 gzip_end_of_data,
444 gzip_read,
445 gzip_drain_content,
446 gzip_destroy
449 static voidpf wininet_zalloc(voidpf opaque, uInt items, uInt size)
451 return malloc(items * size);
454 static void wininet_zfree(voidpf opaque, voidpf address)
456 free(address);
459 static DWORD init_gzip_stream(http_request_t *req, BOOL is_gzip)
461 gzip_stream_t *gzip_stream;
462 int zres;
464 gzip_stream = calloc(1, sizeof(gzip_stream_t));
465 if(!gzip_stream)
466 return ERROR_OUTOFMEMORY;
468 gzip_stream->stream.vtbl = &gzip_stream_vtbl;
469 gzip_stream->zstream.zalloc = wininet_zalloc;
470 gzip_stream->zstream.zfree = wininet_zfree;
472 zres = inflateInit2(&gzip_stream->zstream, is_gzip ? 0x1f : -15);
473 if(zres != Z_OK) {
474 ERR("inflateInit failed: %d\n", zres);
475 free(gzip_stream);
476 return ERROR_OUTOFMEMORY;
479 remove_header(req, L"Content-Length", FALSE);
481 if(req->read_size) {
482 memcpy(gzip_stream->buf, req->read_buf+req->read_pos, req->read_size);
483 gzip_stream->buf_size = req->read_size;
484 req->read_pos = req->read_size = 0;
487 req->read_gzip = TRUE;
488 gzip_stream->parent_stream = req->data_stream;
489 req->data_stream = &gzip_stream->stream;
490 return ERROR_SUCCESS;
493 /***********************************************************************
494 * HTTP_FreeTokens (internal)
496 * Frees table of pointers.
498 static void HTTP_FreeTokens(LPWSTR * token_array)
500 int i;
501 for (i = 0; token_array[i]; i++) free(token_array[i]);
502 free(token_array);
505 static void HTTP_FixURL(http_request_t *request)
507 /* If we don't have a path we set it to root */
508 if (NULL == request->path)
509 request->path = wcsdup(L"/");
510 else /* remove \r and \n*/
512 int nLen = lstrlenW(request->path);
513 while ((nLen >0 ) && ((request->path[nLen-1] == '\r')||(request->path[nLen-1] == '\n')))
515 nLen--;
516 request->path[nLen]='\0';
518 /* Replace '\' with '/' */
519 while (nLen>0) {
520 nLen--;
521 if (request->path[nLen] == '\\') request->path[nLen]='/';
525 if(CSTR_EQUAL != CompareStringW( LOCALE_INVARIANT, NORM_IGNORECASE,
526 request->path, lstrlenW(request->path), L"http://", lstrlenW(L"http://") )
527 && request->path[0] != '/') /* not an absolute path ?? --> fix it !! */
529 WCHAR *fixurl = malloc((wcslen(request->path) + 2) * sizeof(WCHAR));
530 *fixurl = '/';
531 lstrcpyW(fixurl + 1, request->path);
532 free(request->path);
533 request->path = fixurl;
537 static WCHAR* build_request_header(http_request_t *request, const WCHAR *verb,
538 const WCHAR *path, const WCHAR *version, BOOL use_cr)
540 LPWSTR requestString;
541 DWORD len, n;
542 LPCWSTR *req;
543 UINT i;
545 EnterCriticalSection( &request->headers_section );
547 /* allocate space for an array of all the string pointers to be added */
548 len = request->nCustHeaders * 5 + 10;
549 if (!(req = malloc( len * sizeof(const WCHAR *) )))
551 LeaveCriticalSection( &request->headers_section );
552 return NULL;
555 /* add the verb, path and HTTP version string */
556 n = 0;
557 req[n++] = verb;
558 req[n++] = L" ";
559 req[n++] = path;
560 req[n++] = L" ";
561 req[n++] = version;
562 if (use_cr)
563 req[n++] = L"\r";
564 req[n++] = L"\n";
566 /* Append custom request headers */
567 for (i = 0; i < request->nCustHeaders; i++)
569 if (request->custHeaders[i].wFlags & HDR_ISREQUEST)
571 req[n++] = request->custHeaders[i].lpszField;
572 req[n++] = L": ";
573 req[n++] = request->custHeaders[i].lpszValue;
574 if (use_cr)
575 req[n++] = L"\r";
576 req[n++] = L"\n";
578 TRACE("Adding custom header %s (%s)\n",
579 debugstr_w(request->custHeaders[i].lpszField),
580 debugstr_w(request->custHeaders[i].lpszValue));
583 if (use_cr)
584 req[n++] = L"\r";
585 req[n++] = L"\n";
586 req[n] = NULL;
588 requestString = HTTP_build_req( req, 4 );
589 free( req );
590 LeaveCriticalSection( &request->headers_section );
591 return requestString;
594 static WCHAR* build_response_header(http_request_t *request, BOOL use_cr)
596 const WCHAR **req;
597 WCHAR *ret, buf[14];
598 DWORD i, n = 0;
600 EnterCriticalSection( &request->headers_section );
602 if (!(req = malloc((request->nCustHeaders * 5 + 8) * sizeof(WCHAR *))))
604 LeaveCriticalSection( &request->headers_section );
605 return NULL;
608 if (request->status_code)
610 req[n++] = request->version;
611 swprintf(buf, ARRAY_SIZE(buf), L" %u ", request->status_code);
612 req[n++] = buf;
613 req[n++] = request->statusText;
614 if (use_cr)
615 req[n++] = L"\r";
616 req[n++] = L"\n";
619 for(i = 0; i < request->nCustHeaders; i++)
621 if(!(request->custHeaders[i].wFlags & HDR_ISREQUEST)
622 && wcscmp(request->custHeaders[i].lpszField, L"Status"))
624 req[n++] = request->custHeaders[i].lpszField;
625 req[n++] = L": ";
626 req[n++] = request->custHeaders[i].lpszValue;
627 if(use_cr)
628 req[n++] = L"\r";
629 req[n++] = L"\n";
631 TRACE("Adding custom header %s (%s)\n",
632 debugstr_w(request->custHeaders[i].lpszField),
633 debugstr_w(request->custHeaders[i].lpszValue));
636 if(use_cr)
637 req[n++] = L"\r";
638 req[n++] = L"\n";
639 req[n] = NULL;
641 ret = HTTP_build_req(req, 0);
642 free(req);
643 LeaveCriticalSection( &request->headers_section );
644 return ret;
647 static void HTTP_ProcessCookies( http_request_t *request )
649 int HeaderIndex;
650 int numCookies = 0;
651 LPHTTPHEADERW setCookieHeader;
653 if(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES)
654 return;
656 EnterCriticalSection( &request->headers_section );
658 while((HeaderIndex = HTTP_GetCustomHeaderIndex(request, L"Set-Cookie", numCookies++, FALSE)) != -1)
660 const WCHAR *data;
661 substr_t name;
663 setCookieHeader = &request->custHeaders[HeaderIndex];
665 if (!setCookieHeader->lpszValue)
666 continue;
668 data = wcschr(setCookieHeader->lpszValue, '=');
669 if(!data)
670 continue;
672 name = substr(setCookieHeader->lpszValue, data - setCookieHeader->lpszValue);
673 data++;
674 set_cookie(substrz(request->server->name), substrz(request->path), name, substrz(data), INTERNET_COOKIE_HTTPONLY);
677 LeaveCriticalSection( &request->headers_section );
680 static void strip_spaces(LPWSTR start)
682 LPWSTR str = start;
683 LPWSTR end;
685 while (*str == ' ')
686 str++;
688 if (str != start)
689 memmove(start, str, sizeof(WCHAR) * (lstrlenW(str) + 1));
691 end = start + lstrlenW(start) - 1;
692 while (end >= start && *end == ' ')
694 *end = '\0';
695 end--;
699 static inline BOOL is_basic_auth_value( LPCWSTR pszAuthValue, LPWSTR *pszRealm )
701 static const WCHAR szBasic[] = {'B','a','s','i','c'}; /* Note: not nul-terminated */
702 static const WCHAR szRealm[] = {'r','e','a','l','m'}; /* Note: not nul-terminated */
703 BOOL is_basic;
704 is_basic = !wcsnicmp(pszAuthValue, szBasic, ARRAY_SIZE(szBasic)) &&
705 ((pszAuthValue[ARRAY_SIZE(szBasic)] == ' ') || !pszAuthValue[ARRAY_SIZE(szBasic)]);
706 if (is_basic && pszRealm)
708 LPCWSTR token;
709 LPCWSTR ptr = &pszAuthValue[ARRAY_SIZE(szBasic)];
710 LPCWSTR realm;
711 ptr++;
712 *pszRealm=NULL;
713 token = wcschr(ptr,'=');
714 if (!token)
715 return TRUE;
716 realm = ptr;
717 while (*realm == ' ')
718 realm++;
719 if(!wcsnicmp(realm, szRealm, ARRAY_SIZE(szRealm)) &&
720 (realm[ARRAY_SIZE(szRealm)] == ' ' || realm[ARRAY_SIZE(szRealm)] == '='))
722 token++;
723 while (*token == ' ')
724 token++;
725 if (*token == '\0')
726 return TRUE;
727 *pszRealm = wcsdup(token);
728 strip_spaces(*pszRealm);
732 return is_basic;
735 static void destroy_authinfo( struct HttpAuthInfo *authinfo )
737 if (!authinfo) return;
739 if (SecIsValidHandle(&authinfo->ctx))
740 DeleteSecurityContext(&authinfo->ctx);
741 if (SecIsValidHandle(&authinfo->cred))
742 FreeCredentialsHandle(&authinfo->cred);
744 free(authinfo->auth_data);
745 free(authinfo->scheme);
746 free(authinfo);
749 static UINT retrieve_cached_basic_authorization(http_request_t *req, const WCHAR *host, const WCHAR *realm, char **auth_data)
751 basicAuthorizationData *ad;
752 UINT rc = 0;
754 TRACE("Looking for authorization for %s:%s\n",debugstr_w(host),debugstr_w(realm));
756 EnterCriticalSection(&authcache_cs);
757 LIST_FOR_EACH_ENTRY(ad, &basicAuthorizationCache, basicAuthorizationData, entry)
759 if (!wcsicmp(host, ad->host) && (!realm || !wcscmp(realm, ad->realm)))
761 char *colon;
762 DWORD length;
764 TRACE("Authorization found in cache\n");
765 *auth_data = malloc(ad->authorizationLen);
766 memcpy(*auth_data,ad->authorization,ad->authorizationLen);
767 rc = ad->authorizationLen;
769 /* update session username and password to reflect current credentials */
770 colon = strchr(ad->authorization, ':');
771 length = colon - ad->authorization;
773 free(req->session->userName);
774 free(req->session->password);
776 req->session->userName = strndupAtoW(ad->authorization, length, &length);
777 length++;
778 req->session->password = strndupAtoW(&ad->authorization[length], ad->authorizationLen - length, &length);
779 break;
782 LeaveCriticalSection(&authcache_cs);
783 return rc;
786 static void cache_basic_authorization(LPWSTR host, LPWSTR realm, LPSTR auth_data, UINT auth_data_len)
788 struct list *cursor;
789 basicAuthorizationData* ad = NULL;
791 TRACE("caching authorization for %s:%s = %s\n",debugstr_w(host),debugstr_w(realm),debugstr_an(auth_data,auth_data_len));
793 EnterCriticalSection(&authcache_cs);
794 LIST_FOR_EACH(cursor, &basicAuthorizationCache)
796 basicAuthorizationData *check = LIST_ENTRY(cursor,basicAuthorizationData,entry);
797 if (!wcsicmp(host,check->host) && !wcscmp(realm,check->realm))
799 ad = check;
800 break;
804 if (ad)
806 TRACE("Found match in cache, replacing\n");
807 free(ad->authorization);
808 ad->authorization = malloc(auth_data_len);
809 memcpy(ad->authorization, auth_data, auth_data_len);
810 ad->authorizationLen = auth_data_len;
812 else
814 ad = malloc(sizeof(basicAuthorizationData));
815 ad->host = wcsdup(host);
816 ad->realm = wcsdup(realm);
817 ad->authorization = malloc(auth_data_len);
818 memcpy(ad->authorization, auth_data, auth_data_len);
819 ad->authorizationLen = auth_data_len;
820 list_add_head(&basicAuthorizationCache,&ad->entry);
821 TRACE("authorization cached\n");
823 LeaveCriticalSection(&authcache_cs);
826 static BOOL retrieve_cached_authorization(LPWSTR host, LPWSTR scheme,
827 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
829 authorizationData *ad;
831 TRACE("Looking for authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
833 EnterCriticalSection(&authcache_cs);
834 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry) {
835 if(!wcsicmp(host, ad->host) && !wcsicmp(scheme, ad->scheme)) {
836 TRACE("Authorization found in cache\n");
838 nt_auth_identity->User = wcsdup(ad->user);
839 nt_auth_identity->Password = wcsdup(ad->password);
840 nt_auth_identity->Domain = malloc(sizeof(WCHAR) * ad->domain_len);
841 if(!nt_auth_identity->User || !nt_auth_identity->Password ||
842 (!nt_auth_identity->Domain && ad->domain_len)) {
843 free(nt_auth_identity->User);
844 free(nt_auth_identity->Password);
845 free(nt_auth_identity->Domain);
846 break;
849 nt_auth_identity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
850 nt_auth_identity->UserLength = ad->user_len;
851 nt_auth_identity->PasswordLength = ad->password_len;
852 memcpy(nt_auth_identity->Domain, ad->domain, sizeof(WCHAR)*ad->domain_len);
853 nt_auth_identity->DomainLength = ad->domain_len;
854 LeaveCriticalSection(&authcache_cs);
855 return TRUE;
858 LeaveCriticalSection(&authcache_cs);
860 return FALSE;
863 static void cache_authorization(LPWSTR host, LPWSTR scheme,
864 SEC_WINNT_AUTH_IDENTITY_W *nt_auth_identity)
866 authorizationData *ad;
867 BOOL found = FALSE;
869 TRACE("Caching authorization for %s:%s\n", debugstr_w(host), debugstr_w(scheme));
871 EnterCriticalSection(&authcache_cs);
872 LIST_FOR_EACH_ENTRY(ad, &authorizationCache, authorizationData, entry)
873 if(!wcsicmp(host, ad->host) && !wcsicmp(scheme, ad->scheme)) {
874 found = TRUE;
875 break;
878 if(found) {
879 free(ad->user);
880 free(ad->password);
881 free(ad->domain);
882 } else {
883 ad = malloc(sizeof(authorizationData));
884 if(!ad) {
885 LeaveCriticalSection(&authcache_cs);
886 return;
889 ad->host = wcsdup(host);
890 ad->scheme = wcsdup(scheme);
891 list_add_head(&authorizationCache, &ad->entry);
894 ad->user = strndupW(nt_auth_identity->User, nt_auth_identity->UserLength);
895 ad->password = strndupW(nt_auth_identity->Password, nt_auth_identity->PasswordLength);
896 ad->domain = strndupW(nt_auth_identity->Domain, nt_auth_identity->DomainLength);
897 ad->user_len = nt_auth_identity->UserLength;
898 ad->password_len = nt_auth_identity->PasswordLength;
899 ad->domain_len = nt_auth_identity->DomainLength;
901 if(!ad->host || !ad->scheme || !ad->user || !ad->password
902 || (nt_auth_identity->Domain && !ad->domain)) {
903 free(ad->host);
904 free(ad->scheme);
905 free(ad->user);
906 free(ad->password);
907 free(ad->domain);
908 list_remove(&ad->entry);
909 free(ad);
912 LeaveCriticalSection(&authcache_cs);
915 void free_authorization_cache(void)
917 authorizationData *ad, *sa_safe;
918 basicAuthorizationData *basic, *basic_safe;
920 EnterCriticalSection(&authcache_cs);
922 LIST_FOR_EACH_ENTRY_SAFE(basic, basic_safe, &basicAuthorizationCache, basicAuthorizationData, entry)
924 free(basic->host);
925 free(basic->realm);
926 free(basic->authorization);
928 list_remove(&basic->entry);
929 free(basic);
932 LIST_FOR_EACH_ENTRY_SAFE(ad, sa_safe, &authorizationCache, authorizationData, entry)
934 free(ad->host);
935 free(ad->scheme);
936 free(ad->user);
937 free(ad->password);
938 free(ad->domain);
939 list_remove(&ad->entry);
940 free(ad);
943 LeaveCriticalSection(&authcache_cs);
946 static BOOL HTTP_DoAuthorization( http_request_t *request, LPCWSTR pszAuthValue,
947 struct HttpAuthInfo **ppAuthInfo,
948 LPWSTR domain_and_username, LPWSTR password,
949 LPWSTR host )
951 SECURITY_STATUS sec_status;
952 struct HttpAuthInfo *pAuthInfo = *ppAuthInfo;
953 BOOL first = FALSE;
954 LPWSTR szRealm = NULL;
956 TRACE("%s\n", debugstr_w(pszAuthValue));
958 if (!pAuthInfo)
960 TimeStamp exp;
962 first = TRUE;
963 pAuthInfo = malloc(sizeof(*pAuthInfo));
964 if (!pAuthInfo)
965 return FALSE;
967 SecInvalidateHandle(&pAuthInfo->cred);
968 SecInvalidateHandle(&pAuthInfo->ctx);
969 memset(&pAuthInfo->exp, 0, sizeof(pAuthInfo->exp));
970 pAuthInfo->attr = 0;
971 pAuthInfo->auth_data = NULL;
972 pAuthInfo->auth_data_len = 0;
973 pAuthInfo->finished = FALSE;
975 if (is_basic_auth_value(pszAuthValue,NULL))
977 pAuthInfo->scheme = wcsdup(L"Basic");
978 if (!pAuthInfo->scheme)
980 free(pAuthInfo);
981 return FALSE;
984 else
986 PVOID pAuthData;
987 SEC_WINNT_AUTH_IDENTITY_W nt_auth_identity;
989 pAuthInfo->scheme = wcsdup(pszAuthValue);
990 if (!pAuthInfo->scheme)
992 free(pAuthInfo);
993 return FALSE;
996 if (domain_and_username)
998 WCHAR *user = wcschr(domain_and_username, '\\');
999 WCHAR *domain = domain_and_username;
1001 /* FIXME: make sure scheme accepts SEC_WINNT_AUTH_IDENTITY before calling AcquireCredentialsHandle */
1003 pAuthData = &nt_auth_identity;
1005 if (user) user++;
1006 else
1008 user = domain_and_username;
1009 domain = NULL;
1012 nt_auth_identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
1013 nt_auth_identity.User = user;
1014 nt_auth_identity.UserLength = lstrlenW(nt_auth_identity.User);
1015 nt_auth_identity.Domain = domain;
1016 nt_auth_identity.DomainLength = domain ? user - domain - 1 : 0;
1017 nt_auth_identity.Password = password;
1018 nt_auth_identity.PasswordLength = lstrlenW(nt_auth_identity.Password);
1020 cache_authorization(host, pAuthInfo->scheme, &nt_auth_identity);
1022 else if(retrieve_cached_authorization(host, pAuthInfo->scheme, &nt_auth_identity))
1023 pAuthData = &nt_auth_identity;
1024 else
1025 /* use default credentials */
1026 pAuthData = NULL;
1028 sec_status = AcquireCredentialsHandleW(NULL, pAuthInfo->scheme,
1029 SECPKG_CRED_OUTBOUND, NULL,
1030 pAuthData, NULL,
1031 NULL, &pAuthInfo->cred,
1032 &exp);
1034 if(pAuthData && !domain_and_username) {
1035 free(nt_auth_identity.User);
1036 free(nt_auth_identity.Domain);
1037 free(nt_auth_identity.Password);
1040 if (sec_status == SEC_E_OK)
1042 PSecPkgInfoW sec_pkg_info;
1043 sec_status = QuerySecurityPackageInfoW(pAuthInfo->scheme, &sec_pkg_info);
1044 if (sec_status == SEC_E_OK)
1046 pAuthInfo->max_token = sec_pkg_info->cbMaxToken;
1047 FreeContextBuffer(sec_pkg_info);
1050 if (sec_status != SEC_E_OK)
1052 WARN("AcquireCredentialsHandleW for scheme %s failed with error 0x%08lx\n",
1053 debugstr_w(pAuthInfo->scheme), sec_status);
1054 free(pAuthInfo->scheme);
1055 free(pAuthInfo);
1056 return FALSE;
1059 *ppAuthInfo = pAuthInfo;
1061 else if (pAuthInfo->finished)
1062 return FALSE;
1064 if ((lstrlenW(pszAuthValue) < lstrlenW(pAuthInfo->scheme)) ||
1065 wcsnicmp(pszAuthValue, pAuthInfo->scheme, lstrlenW(pAuthInfo->scheme)))
1067 ERR("authentication scheme changed from %s to %s\n",
1068 debugstr_w(pAuthInfo->scheme), debugstr_w(pszAuthValue));
1069 return FALSE;
1072 if (is_basic_auth_value(pszAuthValue,&szRealm))
1074 int userlen;
1075 int passlen;
1076 char *auth_data = NULL;
1077 UINT auth_data_len = 0;
1079 TRACE("basic authentication realm %s\n",debugstr_w(szRealm));
1081 if (!domain_and_username)
1083 if (host && szRealm)
1084 auth_data_len = retrieve_cached_basic_authorization(request, host, szRealm,&auth_data);
1085 if (auth_data_len == 0)
1087 free(szRealm);
1088 return FALSE;
1091 else
1093 userlen = WideCharToMultiByte(CP_UTF8, 0, domain_and_username, lstrlenW(domain_and_username), NULL, 0, NULL, NULL);
1094 passlen = WideCharToMultiByte(CP_UTF8, 0, password, lstrlenW(password), NULL, 0, NULL, NULL);
1096 /* length includes a nul terminator, which will be re-used for the ':' */
1097 auth_data = malloc(userlen + 1 + passlen);
1098 if (!auth_data)
1100 free(szRealm);
1101 return FALSE;
1104 WideCharToMultiByte(CP_UTF8, 0, domain_and_username, -1, auth_data, userlen, NULL, NULL);
1105 auth_data[userlen] = ':';
1106 WideCharToMultiByte(CP_UTF8, 0, password, -1, &auth_data[userlen+1], passlen, NULL, NULL);
1107 auth_data_len = userlen + 1 + passlen;
1108 if (host && szRealm)
1109 cache_basic_authorization(host, szRealm, auth_data, auth_data_len);
1112 pAuthInfo->auth_data = auth_data;
1113 pAuthInfo->auth_data_len = auth_data_len;
1114 pAuthInfo->finished = TRUE;
1115 free(szRealm);
1116 return TRUE;
1118 else
1120 LPCWSTR pszAuthData;
1121 SecBufferDesc out_desc, in_desc;
1122 SecBuffer out, in;
1123 unsigned char *buffer;
1124 ULONG context_req = ISC_REQ_CONNECTION | ISC_REQ_USE_DCE_STYLE |
1125 ISC_REQ_MUTUAL_AUTH | ISC_REQ_DELEGATE;
1127 in.BufferType = SECBUFFER_TOKEN;
1128 in.cbBuffer = 0;
1129 in.pvBuffer = NULL;
1131 in_desc.ulVersion = 0;
1132 in_desc.cBuffers = 1;
1133 in_desc.pBuffers = &in;
1135 pszAuthData = pszAuthValue + lstrlenW(pAuthInfo->scheme);
1136 if (*pszAuthData == ' ')
1138 pszAuthData++;
1139 in.cbBuffer = HTTP_DecodeBase64(pszAuthData, NULL);
1140 in.pvBuffer = malloc(in.cbBuffer);
1141 HTTP_DecodeBase64(pszAuthData, in.pvBuffer);
1144 buffer = malloc(pAuthInfo->max_token);
1146 out.BufferType = SECBUFFER_TOKEN;
1147 out.cbBuffer = pAuthInfo->max_token;
1148 out.pvBuffer = buffer;
1150 out_desc.ulVersion = 0;
1151 out_desc.cBuffers = 1;
1152 out_desc.pBuffers = &out;
1154 sec_status = InitializeSecurityContextW(first ? &pAuthInfo->cred : NULL,
1155 first ? NULL : &pAuthInfo->ctx,
1156 first ? request->server->name : NULL,
1157 context_req, 0, SECURITY_NETWORK_DREP,
1158 in.pvBuffer ? &in_desc : NULL,
1159 0, &pAuthInfo->ctx, &out_desc,
1160 &pAuthInfo->attr, &pAuthInfo->exp);
1161 if (sec_status == SEC_E_OK)
1163 pAuthInfo->finished = TRUE;
1164 pAuthInfo->auth_data = out.pvBuffer;
1165 pAuthInfo->auth_data_len = out.cbBuffer;
1166 TRACE("sending last auth packet\n");
1168 else if (sec_status == SEC_I_CONTINUE_NEEDED)
1170 pAuthInfo->auth_data = out.pvBuffer;
1171 pAuthInfo->auth_data_len = out.cbBuffer;
1172 TRACE("sending next auth packet\n");
1174 else
1176 ERR("InitializeSecurityContextW returned error 0x%08lx\n", sec_status);
1177 free(out.pvBuffer);
1178 destroy_authinfo(pAuthInfo);
1179 *ppAuthInfo = NULL;
1180 return FALSE;
1184 return TRUE;
1187 /***********************************************************************
1188 * HTTP_HttpAddRequestHeadersW (internal)
1190 static DWORD HTTP_HttpAddRequestHeadersW(http_request_t *request,
1191 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1193 LPWSTR lpszStart;
1194 LPWSTR lpszEnd;
1195 LPWSTR buffer;
1196 DWORD len, res = ERROR_HTTP_INVALID_HEADER;
1198 TRACE("copying header: %s\n", debugstr_wn(lpszHeader, dwHeaderLength));
1200 if( dwHeaderLength == ~0U )
1201 len = lstrlenW(lpszHeader);
1202 else
1203 len = dwHeaderLength;
1204 buffer = malloc(sizeof(WCHAR) * (len + 1));
1205 lstrcpynW( buffer, lpszHeader, len + 1);
1207 lpszStart = buffer;
1211 LPWSTR * pFieldAndValue;
1213 lpszEnd = lpszStart;
1215 while (*lpszEnd != '\0')
1217 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1218 break;
1219 lpszEnd++;
1222 if (*lpszStart == '\0')
1223 break;
1225 if (*lpszEnd == '\r' || *lpszEnd == '\n')
1227 *lpszEnd = '\0';
1228 lpszEnd++; /* Jump over newline */
1230 TRACE("interpreting header %s\n", debugstr_w(lpszStart));
1231 if (*lpszStart == '\0')
1233 /* Skip 0-length headers */
1234 lpszStart = lpszEnd;
1235 res = ERROR_SUCCESS;
1236 continue;
1238 pFieldAndValue = HTTP_InterpretHttpHeader(lpszStart);
1239 if (pFieldAndValue)
1241 res = HTTP_ProcessHeader(request, pFieldAndValue[0],
1242 pFieldAndValue[1], dwModifier | HTTP_ADDHDR_FLAG_REQ);
1243 HTTP_FreeTokens(pFieldAndValue);
1246 lpszStart = lpszEnd;
1247 } while (res == ERROR_SUCCESS);
1249 free(buffer);
1250 return res;
1253 /***********************************************************************
1254 * HttpAddRequestHeadersW (WININET.@)
1256 * Adds one or more HTTP header to the request handler
1258 * NOTE
1259 * On Windows if dwHeaderLength includes the trailing '\0', then
1260 * HttpAddRequestHeadersW() adds it too. However this results in an
1261 * invalid HTTP header which is rejected by some servers so we probably
1262 * don't need to match Windows on that point.
1264 * RETURNS
1265 * TRUE on success
1266 * FALSE on failure
1269 BOOL WINAPI HttpAddRequestHeadersW(HINTERNET hHttpRequest,
1270 LPCWSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1272 http_request_t *request;
1273 DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
1275 TRACE("%p, %s, %lu, %08lx\n", hHttpRequest, debugstr_wn(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1277 if (!lpszHeader)
1278 return TRUE;
1280 request = (http_request_t*) get_handle_object( hHttpRequest );
1281 if (request && request->hdr.htype == WH_HHTTPREQ)
1282 res = HTTP_HttpAddRequestHeadersW( request, lpszHeader, dwHeaderLength, dwModifier );
1283 if( request )
1284 WININET_Release( &request->hdr );
1286 if(res != ERROR_SUCCESS)
1287 SetLastError(res);
1288 return res == ERROR_SUCCESS;
1291 /***********************************************************************
1292 * HttpAddRequestHeadersA (WININET.@)
1294 * Adds one or more HTTP header to the request handler
1296 * RETURNS
1297 * TRUE on success
1298 * FALSE on failure
1301 BOOL WINAPI HttpAddRequestHeadersA(HINTERNET hHttpRequest,
1302 LPCSTR lpszHeader, DWORD dwHeaderLength, DWORD dwModifier)
1304 WCHAR *headers = NULL;
1305 BOOL r;
1307 TRACE("%p, %s, %lu, %08lx\n", hHttpRequest, debugstr_an(lpszHeader, dwHeaderLength), dwHeaderLength, dwModifier);
1309 if(lpszHeader)
1310 headers = strndupAtoW(lpszHeader, dwHeaderLength, &dwHeaderLength);
1312 r = HttpAddRequestHeadersW(hHttpRequest, headers, dwHeaderLength, dwModifier);
1314 free(headers);
1315 return r;
1318 static void free_accept_types( WCHAR **accept_types )
1320 WCHAR *ptr, **types = accept_types;
1322 if (!types) return;
1323 while ((ptr = *types))
1325 free(ptr);
1326 types++;
1328 free(accept_types);
1331 static WCHAR **convert_accept_types( const char **accept_types )
1333 unsigned int count;
1334 const char **types = accept_types;
1335 WCHAR **typesW;
1336 BOOL invalid_pointer = FALSE;
1338 if (!types) return NULL;
1339 count = 0;
1340 while (*types)
1342 __TRY
1344 /* find out how many there are */
1345 if (*types && **types)
1347 TRACE("accept type: %s\n", debugstr_a(*types));
1348 count++;
1351 __EXCEPT_PAGE_FAULT
1353 WARN("invalid accept type pointer\n");
1354 invalid_pointer = TRUE;
1356 __ENDTRY;
1357 types++;
1359 if (invalid_pointer) return NULL;
1360 if (!(typesW = malloc(sizeof(WCHAR *) * (count + 1)))) return NULL;
1361 count = 0;
1362 types = accept_types;
1363 while (*types)
1365 if (*types && **types) typesW[count++] = strdupAtoW(*types);
1366 types++;
1368 typesW[count] = NULL;
1369 return typesW;
1372 /***********************************************************************
1373 * HttpOpenRequestA (WININET.@)
1375 * Open a HTTP request handle
1377 * RETURNS
1378 * HINTERNET a HTTP request handle on success
1379 * NULL on failure
1382 HINTERNET WINAPI HttpOpenRequestA(HINTERNET hHttpSession,
1383 LPCSTR lpszVerb, LPCSTR lpszObjectName, LPCSTR lpszVersion,
1384 LPCSTR lpszReferrer , LPCSTR *lpszAcceptTypes,
1385 DWORD dwFlags, DWORD_PTR dwContext)
1387 LPWSTR szVerb = NULL, szObjectName = NULL;
1388 LPWSTR szVersion = NULL, szReferrer = NULL, *szAcceptTypes = NULL;
1389 HINTERNET rc = NULL;
1391 TRACE("(%p, %s, %s, %s, %s, %p, %08lx, %08Ix)\n", hHttpSession,
1392 debugstr_a(lpszVerb), debugstr_a(lpszObjectName),
1393 debugstr_a(lpszVersion), debugstr_a(lpszReferrer), lpszAcceptTypes,
1394 dwFlags, dwContext);
1396 if (lpszVerb)
1398 szVerb = strdupAtoW(lpszVerb);
1399 if ( !szVerb )
1400 goto end;
1403 if (lpszObjectName)
1405 szObjectName = strdupAtoW(lpszObjectName);
1406 if ( !szObjectName )
1407 goto end;
1410 if (lpszVersion)
1412 szVersion = strdupAtoW(lpszVersion);
1413 if ( !szVersion )
1414 goto end;
1417 if (lpszReferrer)
1419 szReferrer = strdupAtoW(lpszReferrer);
1420 if ( !szReferrer )
1421 goto end;
1424 szAcceptTypes = convert_accept_types( lpszAcceptTypes );
1425 rc = HttpOpenRequestW(hHttpSession, szVerb, szObjectName, szVersion, szReferrer,
1426 (const WCHAR **)szAcceptTypes, dwFlags, dwContext);
1428 end:
1429 free_accept_types(szAcceptTypes);
1430 free(szReferrer);
1431 free(szVersion);
1432 free(szObjectName);
1433 free(szVerb);
1434 return rc;
1437 /***********************************************************************
1438 * HTTP_EncodeBase64
1440 static UINT HTTP_EncodeBase64( LPCSTR bin, unsigned int len, LPWSTR base64 )
1442 UINT n = 0, x;
1443 static const CHAR HTTP_Base64Enc[] =
1444 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1446 while( len > 0 )
1448 /* first 6 bits, all from bin[0] */
1449 base64[n++] = HTTP_Base64Enc[(bin[0] & 0xfc) >> 2];
1450 x = (bin[0] & 3) << 4;
1452 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
1453 if( len == 1 )
1455 base64[n++] = HTTP_Base64Enc[x];
1456 base64[n++] = '=';
1457 base64[n++] = '=';
1458 break;
1460 base64[n++] = HTTP_Base64Enc[ x | ( (bin[1]&0xf0) >> 4 ) ];
1461 x = ( bin[1] & 0x0f ) << 2;
1463 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
1464 if( len == 2 )
1466 base64[n++] = HTTP_Base64Enc[x];
1467 base64[n++] = '=';
1468 break;
1470 base64[n++] = HTTP_Base64Enc[ x | ( (bin[2]&0xc0 ) >> 6 ) ];
1472 /* last 6 bits, all from bin [2] */
1473 base64[n++] = HTTP_Base64Enc[ bin[2] & 0x3f ];
1474 bin += 3;
1475 len -= 3;
1477 base64[n] = 0;
1478 return n;
1481 static const signed char HTTP_Base64Dec[] =
1483 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x00 */
1484 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x10 */
1485 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 0x20 */
1486 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, /* 0x30 */
1487 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 0x40 */
1488 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 0x50 */
1489 -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 0x60 */
1490 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 /* 0x70 */
1493 /***********************************************************************
1494 * HTTP_DecodeBase64
1496 static UINT HTTP_DecodeBase64( LPCWSTR base64, LPSTR bin )
1498 unsigned int n = 0;
1500 while(*base64)
1502 signed char in[4];
1504 if (base64[0] >= ARRAY_SIZE(HTTP_Base64Dec) ||
1505 ((in[0] = HTTP_Base64Dec[base64[0]]) == -1) ||
1506 base64[1] >= ARRAY_SIZE(HTTP_Base64Dec) ||
1507 ((in[1] = HTTP_Base64Dec[base64[1]]) == -1))
1509 WARN("invalid base64: %s\n", debugstr_w(base64));
1510 return 0;
1512 if (bin)
1513 bin[n] = (unsigned char) (in[0] << 2 | in[1] >> 4);
1514 n++;
1516 if ((base64[2] == '=') && (base64[3] == '='))
1517 break;
1518 if (base64[2] > ARRAY_SIZE(HTTP_Base64Dec) ||
1519 ((in[2] = HTTP_Base64Dec[base64[2]]) == -1))
1521 WARN("invalid base64: %s\n", debugstr_w(&base64[2]));
1522 return 0;
1524 if (bin)
1525 bin[n] = (unsigned char) (in[1] << 4 | in[2] >> 2);
1526 n++;
1528 if (base64[3] == '=')
1529 break;
1530 if (base64[3] > ARRAY_SIZE(HTTP_Base64Dec) ||
1531 ((in[3] = HTTP_Base64Dec[base64[3]]) == -1))
1533 WARN("invalid base64: %s\n", debugstr_w(&base64[3]));
1534 return 0;
1536 if (bin)
1537 bin[n] = (unsigned char) (((in[2] << 6) & 0xc0) | in[3]);
1538 n++;
1540 base64 += 4;
1543 return n;
1546 static WCHAR *encode_auth_data( const WCHAR *scheme, const char *data, UINT data_len )
1548 WCHAR *ret;
1549 UINT len, scheme_len = lstrlenW( scheme );
1551 /* scheme + space + base64 encoded data (3/2/1 bytes data -> 4 bytes of characters) */
1552 len = scheme_len + 1 + ((data_len + 2) * 4) / 3;
1553 if (!(ret = malloc( (len + 1) * sizeof(WCHAR) ))) return NULL;
1554 memcpy( ret, scheme, scheme_len * sizeof(WCHAR) );
1555 ret[scheme_len] = ' ';
1556 HTTP_EncodeBase64( data, data_len, ret + scheme_len + 1 );
1557 return ret;
1561 /***********************************************************************
1562 * HTTP_InsertAuthorization
1564 * Insert or delete the authorization field in the request header.
1566 static BOOL HTTP_InsertAuthorization( http_request_t *request, struct HttpAuthInfo *pAuthInfo, LPCWSTR header )
1568 WCHAR *host, *authorization = NULL;
1570 if (pAuthInfo)
1572 if (pAuthInfo->auth_data_len)
1574 if (!(authorization = encode_auth_data(pAuthInfo->scheme, pAuthInfo->auth_data, pAuthInfo->auth_data_len)))
1575 return FALSE;
1577 /* clear the data as it isn't valid now that it has been sent to the
1578 * server, unless it's Basic authentication which doesn't do
1579 * connection tracking */
1580 if (wcsicmp(pAuthInfo->scheme, L"Basic"))
1582 free(pAuthInfo->auth_data);
1583 pAuthInfo->auth_data = NULL;
1584 pAuthInfo->auth_data_len = 0;
1588 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1590 HTTP_ProcessHeader(request, header, authorization,
1591 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
1592 free(authorization);
1594 else
1596 UINT data_len;
1597 char *data;
1599 /* Don't use cached credentials when a username or Authorization was specified */
1600 if ((request->session->userName && request->session->userName[0]) || wcscmp(header, L"Authorization"))
1601 return TRUE;
1603 if (!(host = get_host_header(request)))
1604 return TRUE;
1606 if ((data_len = retrieve_cached_basic_authorization(request, host, NULL, &data)))
1608 TRACE("Found cached basic authorization for %s\n", debugstr_w(host));
1610 if (!(authorization = encode_auth_data(L"Basic", data, data_len)))
1612 free(data);
1613 free(host);
1614 return FALSE;
1617 TRACE("Inserting authorization: %s\n", debugstr_w(authorization));
1619 HTTP_ProcessHeader(request, header, authorization,
1620 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
1621 free(data);
1622 free(authorization);
1624 free(host);
1626 return TRUE;
1629 static WCHAR *build_proxy_path_url(http_request_t *req)
1631 DWORD size, len;
1632 WCHAR *url;
1634 len = lstrlenW(req->server->scheme_host_port);
1635 size = len + lstrlenW(req->path) + 1;
1636 if(*req->path != '/')
1637 size++;
1638 url = malloc(size * sizeof(WCHAR));
1639 if(!url)
1640 return NULL;
1642 memcpy(url, req->server->scheme_host_port, len*sizeof(WCHAR));
1643 if(*req->path != '/')
1644 url[len++] = '/';
1646 lstrcpyW(url+len, req->path);
1648 TRACE("url=%s\n", debugstr_w(url));
1649 return url;
1652 static BOOL HTTP_DomainMatches(LPCWSTR server, substr_t domain)
1654 const WCHAR *dot, *ptr;
1655 int len;
1657 if(domain.len == ARRAY_SIZE(L"<local>")-1 && !wcsnicmp(domain.str, L"<local>", domain.len) && !wcschr(server, '.' ))
1658 return TRUE;
1660 if(domain.len && *domain.str != '*')
1661 return domain.len == lstrlenW(server) && !wcsnicmp(server, domain.str, domain.len);
1663 if(domain.len < 2 || domain.str[1] != '.')
1664 return FALSE;
1666 /* For a hostname to match a wildcard, the last domain must match
1667 * the wildcard exactly. E.g. if the wildcard is *.a.b, and the
1668 * hostname is www.foo.a.b, it matches, but a.b does not.
1670 dot = wcschr(server, '.');
1671 if(!dot)
1672 return FALSE;
1674 len = lstrlenW(dot + 1);
1675 if(len < domain.len - 2)
1676 return FALSE;
1678 /* The server's domain is longer than the wildcard, so it
1679 * could be a subdomain. Compare the last portion of the
1680 * server's domain.
1682 ptr = dot + 1 + len - domain.len + 2;
1683 if(!wcsnicmp(ptr, domain.str+2, domain.len-2))
1684 /* This is only a match if the preceding character is
1685 * a '.', i.e. that it is a matching domain. E.g.
1686 * if domain is '*.b.c' and server is 'www.ab.c' they
1687 * do not match.
1689 return *(ptr - 1) == '.';
1691 return len == domain.len-2 && !wcsnicmp(dot + 1, domain.str + 2, len);
1694 static BOOL HTTP_ShouldBypassProxy(appinfo_t *lpwai, LPCWSTR server)
1696 LPCWSTR ptr;
1697 BOOL ret = FALSE;
1699 if (!lpwai->proxyBypass) return FALSE;
1700 ptr = lpwai->proxyBypass;
1701 while(1) {
1702 LPCWSTR tmp = ptr;
1704 ptr = wcschr( ptr, ';' );
1705 if (!ptr)
1706 ptr = wcschr( tmp, ' ' );
1707 if (!ptr)
1708 ptr = tmp + lstrlenW(tmp);
1709 ret = HTTP_DomainMatches( server, substr(tmp, ptr-tmp) );
1710 if (ret || !*ptr)
1711 break;
1712 ptr++;
1714 return ret;
1717 /***********************************************************************
1718 * HTTP_DealWithProxy
1720 static BOOL HTTP_DealWithProxy(appinfo_t *hIC, http_session_t *session, http_request_t *request)
1722 static WCHAR szNul[] = L"";
1723 URL_COMPONENTSW UrlComponents = { sizeof(UrlComponents) };
1724 server_t *new_server = NULL;
1725 WCHAR *proxy;
1727 proxy = INTERNET_FindProxyForProtocol(hIC->proxy, L"http");
1728 if(!proxy)
1729 return FALSE;
1730 if(CSTR_EQUAL != CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1731 proxy, lstrlenW(L"http://"), L"http://", lstrlenW(L"http://"))) {
1732 WCHAR *proxy_url = malloc(wcslen(proxy) * sizeof(WCHAR) + sizeof(L"http://"));
1733 if(!proxy_url) {
1734 free(proxy);
1735 return FALSE;
1737 lstrcpyW(proxy_url, L"http://");
1738 lstrcatW(proxy_url, proxy);
1739 free(proxy);
1740 proxy = proxy_url;
1743 UrlComponents.dwHostNameLength = 1;
1744 if(InternetCrackUrlW(proxy, 0, 0, &UrlComponents) && UrlComponents.dwHostNameLength) {
1745 if( !request->path )
1746 request->path = szNul;
1748 new_server = get_server(substr(UrlComponents.lpszHostName, UrlComponents.dwHostNameLength),
1749 UrlComponents.nPort, UrlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
1751 free(proxy);
1752 if(!new_server)
1753 return FALSE;
1755 request->proxy = new_server;
1757 TRACE("proxy server=%s port=%d\n", debugstr_w(new_server->name), new_server->port);
1758 return TRUE;
1761 static DWORD HTTP_ResolveName(http_request_t *request)
1763 server_t *server = request->proxy ? request->proxy : request->server;
1764 int addr_len;
1766 if(server->addr_len)
1767 return ERROR_SUCCESS;
1769 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1770 INTERNET_STATUS_RESOLVING_NAME,
1771 server->name,
1772 (lstrlenW(server->name)+1) * sizeof(WCHAR));
1774 addr_len = sizeof(server->addr);
1775 if (!GetAddress(server->name, server->port, (SOCKADDR*)&server->addr, &addr_len, server->addr_str))
1776 return ERROR_INTERNET_NAME_NOT_RESOLVED;
1778 server->addr_len = addr_len;
1779 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
1780 INTERNET_STATUS_NAME_RESOLVED,
1781 server->addr_str, strlen(server->addr_str)+1);
1783 TRACE("resolved %s to %s\n", debugstr_w(server->name), server->addr_str);
1784 return ERROR_SUCCESS;
1787 static WCHAR *compose_request_url(http_request_t *req)
1789 const WCHAR *host, *scheme;
1790 WCHAR *buf, *ptr;
1791 size_t len;
1793 host = req->server->canon_host_port;
1795 if (req->server->is_https)
1796 scheme = L"https://";
1797 else
1798 scheme = L"http://";
1800 len = lstrlenW(scheme) + lstrlenW(host) + (req->path[0] != '/' ? 1 : 0) + lstrlenW(req->path);
1801 ptr = buf = malloc((len + 1) * sizeof(WCHAR));
1802 if(buf) {
1803 lstrcpyW(ptr, scheme);
1804 ptr += lstrlenW(ptr);
1806 lstrcpyW(ptr, host);
1807 ptr += lstrlenW(ptr);
1809 if(req->path[0] != '/')
1810 *ptr++ = '/';
1812 lstrcpyW(ptr, req->path);
1813 ptr += lstrlenW(ptr);
1814 *ptr = 0;
1817 return buf;
1821 /***********************************************************************
1822 * HTTPREQ_Destroy (internal)
1824 * Deallocate request handle
1827 static void HTTPREQ_Destroy(object_header_t *hdr)
1829 http_request_t *request = (http_request_t*) hdr;
1830 DWORD i;
1832 TRACE("\n");
1834 if(request->hCacheFile)
1835 CloseHandle(request->hCacheFile);
1836 if(request->req_file)
1837 req_file_release(request->req_file);
1839 request->headers_section.DebugInfo->Spare[0] = 0;
1840 DeleteCriticalSection( &request->headers_section );
1841 request->read_section.DebugInfo->Spare[0] = 0;
1842 DeleteCriticalSection( &request->read_section );
1843 WININET_Release(&request->session->hdr);
1845 destroy_authinfo(request->authInfo);
1846 destroy_authinfo(request->proxyAuthInfo);
1848 if(request->server)
1849 server_release(request->server);
1850 if(request->proxy)
1851 server_release(request->proxy);
1853 free(request->path);
1854 free(request->verb);
1855 free(request->version);
1856 free(request->statusText);
1858 for (i = 0; i < request->nCustHeaders; i++)
1860 free(request->custHeaders[i].lpszField);
1861 free(request->custHeaders[i].lpszValue);
1863 destroy_data_stream(request->data_stream);
1864 free(request->custHeaders);
1867 static void http_release_netconn(http_request_t *req, BOOL reuse)
1869 TRACE("%p %p %x\n",req, req->netconn, reuse);
1871 if(!is_valid_netconn(req->netconn))
1872 return;
1874 if(reuse && req->netconn->keep_alive) {
1875 BOOL run_collector;
1877 EnterCriticalSection(&connection_pool_cs);
1879 list_add_head(&req->netconn->server->conn_pool, &req->netconn->pool_entry);
1880 req->netconn->keep_until = GetTickCount64() + COLLECT_TIME;
1881 req->netconn = NULL;
1883 run_collector = !collector_running;
1884 collector_running = TRUE;
1886 LeaveCriticalSection(&connection_pool_cs);
1888 if(run_collector) {
1889 HANDLE thread = NULL;
1890 HMODULE module;
1892 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (const WCHAR*)WININET_hModule, &module);
1893 if(module)
1894 thread = CreateThread(NULL, 0, collect_connections_proc, NULL, 0, NULL);
1895 if(!thread) {
1896 EnterCriticalSection(&connection_pool_cs);
1897 collector_running = FALSE;
1898 LeaveCriticalSection(&connection_pool_cs);
1900 if(module)
1901 FreeLibrary(module);
1903 else
1904 CloseHandle(thread);
1906 return;
1909 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1910 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
1912 close_netconn(req->netconn);
1914 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext,
1915 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
1918 static BOOL HTTP_KeepAlive(http_request_t *request)
1920 WCHAR szVersion[10];
1921 WCHAR szConnectionResponse[20];
1922 DWORD dwBufferSize = sizeof(szVersion);
1923 BOOL keepalive = FALSE;
1925 /* as per RFC 2068, S8.1.2.1, if the client is HTTP/1.1 then assume that
1926 * the connection is keep-alive by default */
1927 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_VERSION, szVersion, &dwBufferSize, NULL) == ERROR_SUCCESS
1928 && !wcsicmp(szVersion, L"HTTP/1.1"))
1930 keepalive = TRUE;
1933 dwBufferSize = sizeof(szConnectionResponse);
1934 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_PROXY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS
1935 || HTTP_HttpQueryInfoW(request, HTTP_QUERY_CONNECTION, szConnectionResponse, &dwBufferSize, NULL) == ERROR_SUCCESS)
1937 keepalive = !wcsicmp(szConnectionResponse, L"Keep-Alive");
1940 return keepalive;
1943 static void HTTPREQ_CloseConnection(object_header_t *hdr)
1945 http_request_t *req = (http_request_t*)hdr;
1947 http_release_netconn(req, drain_content(req, FALSE) == ERROR_SUCCESS);
1950 static DWORD str_to_buffer(const WCHAR *str, void *buffer, DWORD *size, BOOL unicode)
1952 int len;
1953 if (unicode)
1955 WCHAR *buf = buffer;
1957 if (str) len = lstrlenW(str);
1958 else len = 0;
1959 if (*size < (len + 1) * sizeof(WCHAR))
1961 *size = (len + 1) * sizeof(WCHAR);
1962 return ERROR_INSUFFICIENT_BUFFER;
1964 if (str) lstrcpyW(buf, str);
1965 else buf[0] = 0;
1967 *size = len;
1968 return ERROR_SUCCESS;
1970 else
1972 char *buf = buffer;
1974 if (str) len = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
1975 else len = 1;
1976 if (*size < len)
1978 *size = len;
1979 return ERROR_INSUFFICIENT_BUFFER;
1981 if (str) WideCharToMultiByte(CP_ACP, 0, str, -1, buf, *size, NULL, NULL);
1982 else buf[0] = 0;
1984 *size = len - 1;
1985 return ERROR_SUCCESS;
1989 static DWORD get_security_cert_struct(http_request_t *req, INTERNET_CERTIFICATE_INFOA *info)
1991 PCCERT_CONTEXT context;
1992 DWORD len;
1994 context = (PCCERT_CONTEXT)NETCON_GetCert(req->netconn);
1995 if(!context)
1996 return ERROR_NOT_SUPPORTED;
1998 memset(info, 0, sizeof(*info));
1999 info->ftExpiry = context->pCertInfo->NotAfter;
2000 info->ftStart = context->pCertInfo->NotBefore;
2001 len = CertNameToStrA(context->dwCertEncodingType,
2002 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2003 info->lpszSubjectInfo = LocalAlloc(0, len);
2004 if(info->lpszSubjectInfo)
2005 CertNameToStrA(context->dwCertEncodingType,
2006 &context->pCertInfo->Subject, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2007 info->lpszSubjectInfo, len);
2008 len = CertNameToStrA(context->dwCertEncodingType,
2009 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2010 info->lpszIssuerInfo = LocalAlloc(0, len);
2011 if(info->lpszIssuerInfo)
2012 CertNameToStrA(context->dwCertEncodingType,
2013 &context->pCertInfo->Issuer, CERT_SIMPLE_NAME_STR|CERT_NAME_STR_CRLF_FLAG,
2014 info->lpszIssuerInfo, len);
2015 info->dwKeySize = NETCON_GetCipherStrength(req->netconn);
2017 CertFreeCertificateContext(context);
2018 return ERROR_SUCCESS;
2021 static DWORD HTTPREQ_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2023 http_request_t *req = (http_request_t*)hdr;
2025 switch(option) {
2026 case INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO:
2028 INTERNET_DIAGNOSTIC_SOCKET_INFO *info = buffer;
2030 FIXME("INTERNET_DIAGNOSTIC_SOCKET_INFO stub\n");
2032 if (*size < sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO))
2033 return ERROR_INSUFFICIENT_BUFFER;
2034 *size = sizeof(INTERNET_DIAGNOSTIC_SOCKET_INFO);
2035 /* FIXME: can't get a SOCKET from our connection since we don't use
2036 * winsock
2038 info->Socket = 0;
2039 /* FIXME: get source port from req->netConnection */
2040 info->SourcePort = 0;
2041 info->DestPort = req->server->port;
2042 info->Flags = 0;
2043 if (HTTP_KeepAlive(req))
2044 info->Flags |= IDSI_FLAG_KEEP_ALIVE;
2045 if (req->proxy)
2046 info->Flags |= IDSI_FLAG_PROXY;
2047 if (is_valid_netconn(req->netconn) && req->netconn->secure)
2048 info->Flags |= IDSI_FLAG_SECURE;
2050 return ERROR_SUCCESS;
2053 case 98:
2054 TRACE("Queried undocumented option 98, forwarding to INTERNET_OPTION_SECURITY_FLAGS\n");
2055 /* fall through */
2056 case INTERNET_OPTION_SECURITY_FLAGS:
2058 DWORD flags;
2060 if (*size < sizeof(ULONG))
2061 return ERROR_INSUFFICIENT_BUFFER;
2063 *size = sizeof(DWORD);
2064 flags = is_valid_netconn(req->netconn) ? req->netconn->security_flags : req->security_flags | req->server->security_flags;
2065 *(DWORD *)buffer = flags;
2067 TRACE("INTERNET_OPTION_SECURITY_FLAGS %lx\n", flags);
2068 return ERROR_SUCCESS;
2071 case INTERNET_OPTION_HANDLE_TYPE:
2072 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2074 if (*size < sizeof(ULONG))
2075 return ERROR_INSUFFICIENT_BUFFER;
2077 *size = sizeof(DWORD);
2078 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_HTTP_REQUEST;
2079 return ERROR_SUCCESS;
2081 case INTERNET_OPTION_URL: {
2082 WCHAR *url;
2083 DWORD res;
2085 TRACE("INTERNET_OPTION_URL\n");
2087 url = compose_request_url(req);
2088 if(!url)
2089 return ERROR_OUTOFMEMORY;
2091 res = str_to_buffer(url, buffer, size, unicode);
2092 free(url);
2093 return res;
2095 case INTERNET_OPTION_USER_AGENT:
2096 return str_to_buffer(req->session->appInfo->agent, buffer, size, unicode);
2097 case INTERNET_OPTION_USERNAME:
2098 return str_to_buffer(req->session->userName, buffer, size, unicode);
2099 case INTERNET_OPTION_PASSWORD:
2100 return str_to_buffer(req->session->password, buffer, size, unicode);
2101 case INTERNET_OPTION_PROXY_USERNAME:
2102 return str_to_buffer(req->session->appInfo->proxyUsername, buffer, size, unicode);
2103 case INTERNET_OPTION_PROXY_PASSWORD:
2104 return str_to_buffer(req->session->appInfo->proxyPassword, buffer, size, unicode);
2106 case INTERNET_OPTION_CACHE_TIMESTAMPS: {
2107 INTERNET_CACHE_ENTRY_INFOW *info;
2108 INTERNET_CACHE_TIMESTAMPS *ts = buffer;
2109 DWORD nbytes, error;
2110 BOOL ret;
2112 TRACE("INTERNET_OPTION_CACHE_TIMESTAMPS\n");
2114 if(!req->req_file)
2115 return ERROR_FILE_NOT_FOUND;
2117 if (*size < sizeof(*ts))
2119 *size = sizeof(*ts);
2120 return ERROR_INSUFFICIENT_BUFFER;
2123 nbytes = 0;
2124 ret = GetUrlCacheEntryInfoW(req->req_file->url, NULL, &nbytes);
2125 error = GetLastError();
2126 if (!ret && error == ERROR_INSUFFICIENT_BUFFER)
2128 if (!(info = malloc(nbytes)))
2129 return ERROR_OUTOFMEMORY;
2131 GetUrlCacheEntryInfoW(req->req_file->url, info, &nbytes);
2133 ts->ftExpires = info->ExpireTime;
2134 ts->ftLastModified = info->LastModifiedTime;
2136 free(info);
2137 *size = sizeof(*ts);
2138 return ERROR_SUCCESS;
2140 return error;
2143 case INTERNET_OPTION_DATAFILE_NAME: {
2144 DWORD req_size;
2146 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
2148 if(!req->req_file) {
2149 *size = 0;
2150 return ERROR_INTERNET_ITEM_NOT_FOUND;
2153 if(unicode) {
2154 req_size = (lstrlenW(req->req_file->file_name)+1) * sizeof(WCHAR);
2155 if(*size < req_size)
2156 return ERROR_INSUFFICIENT_BUFFER;
2158 *size = req_size;
2159 memcpy(buffer, req->req_file->file_name, *size);
2160 return ERROR_SUCCESS;
2161 }else {
2162 req_size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name, -1, NULL, 0, NULL, NULL);
2163 if (req_size > *size)
2164 return ERROR_INSUFFICIENT_BUFFER;
2166 *size = WideCharToMultiByte(CP_ACP, 0, req->req_file->file_name,
2167 -1, buffer, *size, NULL, NULL);
2168 return ERROR_SUCCESS;
2172 case INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: {
2173 if(!req->netconn)
2174 return ERROR_INTERNET_INVALID_OPERATION;
2176 if(*size < sizeof(INTERNET_CERTIFICATE_INFOA)) {
2177 *size = sizeof(INTERNET_CERTIFICATE_INFOA);
2178 return ERROR_INSUFFICIENT_BUFFER;
2181 return get_security_cert_struct(req, (INTERNET_CERTIFICATE_INFOA*)buffer);
2183 case INTERNET_OPTION_SECURITY_CERTIFICATE: {
2184 DWORD err;
2185 int needed;
2186 char subject[64];
2187 char issuer[64];
2188 char effective[64];
2189 char expiration[64];
2190 char protocol[64];
2191 char signature[64];
2192 char encryption[64];
2193 char privacy[64];
2194 char bits[16];
2195 char strength[16];
2196 char start_date[32];
2197 char start_time[32];
2198 char expiry_date[32];
2199 char expiry_time[32];
2200 SYSTEMTIME start, expiry;
2201 INTERNET_CERTIFICATE_INFOA info;
2203 if(!size)
2204 return ERROR_INVALID_PARAMETER;
2206 if(!req->netconn) {
2207 *size = 0;
2208 return ERROR_INTERNET_INVALID_OPERATION;
2211 if(!buffer) {
2212 *size = 1;
2213 return ERROR_INSUFFICIENT_BUFFER;
2216 if((err = get_security_cert_struct(req, &info)))
2217 return err;
2219 LoadStringA(WININET_hModule, IDS_CERT_SUBJECT, subject, sizeof(subject));
2220 LoadStringA(WININET_hModule, IDS_CERT_ISSUER, issuer, sizeof(issuer));
2221 LoadStringA(WININET_hModule, IDS_CERT_EFFECTIVE, effective, sizeof(effective));
2222 LoadStringA(WININET_hModule, IDS_CERT_EXPIRATION, expiration, sizeof(expiration));
2223 LoadStringA(WININET_hModule, IDS_CERT_PROTOCOL, protocol, sizeof(protocol));
2224 LoadStringA(WININET_hModule, IDS_CERT_SIGNATURE, signature, sizeof(signature));
2225 LoadStringA(WININET_hModule, IDS_CERT_ENCRYPTION, encryption, sizeof(encryption));
2226 LoadStringA(WININET_hModule, IDS_CERT_PRIVACY, privacy, sizeof(privacy));
2227 LoadStringA(WININET_hModule, info.dwKeySize >= 128 ? IDS_CERT_HIGH : IDS_CERT_LOW,
2228 strength, sizeof(strength));
2229 LoadStringA(WININET_hModule, IDS_CERT_BITS, bits, sizeof(bits));
2231 FileTimeToSystemTime(&info.ftStart, &start);
2232 FileTimeToSystemTime(&info.ftExpiry, &expiry);
2233 GetDateFormatA(LOCALE_USER_DEFAULT, 0, &start, NULL, start_date, sizeof(start_date));
2234 GetTimeFormatA(LOCALE_USER_DEFAULT, 0, &start, NULL, start_time, sizeof(start_time));
2235 GetDateFormatA(LOCALE_USER_DEFAULT, 0, &expiry, NULL, expiry_date, sizeof(expiry_date));
2236 GetTimeFormatA(LOCALE_USER_DEFAULT, 0, &expiry, NULL, expiry_time, sizeof(expiry_time));
2238 needed = _scprintf("%s:\r\n%s\r\n"
2239 "%s:\r\n%s\r\n"
2240 "%s:\t%s %s\r\n"
2241 "%s:\t%s %s\r\n"
2242 "%s:\t(null)\r\n"
2243 "%s:\t(null)\r\n"
2244 "%s:\t(null)\r\n"
2245 "%s:\t%s (%lu %s)",
2246 subject, info.lpszSubjectInfo,
2247 issuer, info.lpszIssuerInfo,
2248 effective, start_date, start_time,
2249 expiration, expiry_date, expiry_time,
2250 protocol, signature, encryption,
2251 privacy, strength, info.dwKeySize, bits);
2253 if(needed < *size) {
2254 err = ERROR_SUCCESS;
2255 *size = snprintf(buffer, *size,
2256 "%s:\r\n%s\r\n"
2257 "%s:\r\n%s\r\n"
2258 "%s:\t%s %s\r\n"
2259 "%s:\t%s %s\r\n"
2260 "%s:\t(null)\r\n"
2261 "%s:\t(null)\r\n"
2262 "%s:\t(null)\r\n"
2263 "%s:\t%s (%lu %s)",
2264 subject, info.lpszSubjectInfo,
2265 issuer, info.lpszIssuerInfo,
2266 effective, start_date, start_time,
2267 expiration, expiry_date, expiry_time,
2268 protocol, signature, encryption,
2269 privacy, strength, info.dwKeySize, bits);
2270 }else {
2271 err = ERROR_INSUFFICIENT_BUFFER;
2272 *size = 1;
2275 LocalFree(info.lpszSubjectInfo);
2276 LocalFree(info.lpszIssuerInfo);
2277 LocalFree(info.lpszProtocolName);
2278 LocalFree(info.lpszSignatureAlgName);
2279 LocalFree(info.lpszEncryptionAlgName);
2280 return err;
2282 case INTERNET_OPTION_CONNECT_TIMEOUT:
2283 if (*size < sizeof(ULONG))
2284 return ERROR_INSUFFICIENT_BUFFER;
2286 *size = sizeof(ULONG);
2287 *(ULONG *)buffer = hdr->connect_timeout;
2288 return ERROR_SUCCESS;
2289 case INTERNET_OPTION_REQUEST_FLAGS: {
2290 DWORD flags = 0;
2292 if (*size < sizeof(DWORD))
2293 return ERROR_INSUFFICIENT_BUFFER;
2295 /* FIXME: Add support for:
2296 * INTERNET_REQFLAG_FROM_CACHE
2297 * INTERNET_REQFLAG_CACHE_WRITE_DISABLED
2300 if(req->proxy)
2301 flags |= INTERNET_REQFLAG_VIA_PROXY;
2302 if(!req->status_code)
2303 flags |= INTERNET_REQFLAG_NO_HEADERS;
2305 TRACE("INTERNET_OPTION_REQUEST_FLAGS returning %lx\n", flags);
2307 *size = sizeof(DWORD);
2308 *(DWORD*)buffer = flags;
2309 return ERROR_SUCCESS;
2311 case INTERNET_OPTION_ERROR_MASK:
2312 TRACE("INTERNET_OPTION_ERROR_MASK\n");
2314 if (*size < sizeof(ULONG))
2315 return ERROR_INSUFFICIENT_BUFFER;
2317 *(ULONG*)buffer = hdr->ErrorMask;
2318 *size = sizeof(ULONG);
2319 return ERROR_SUCCESS;
2320 case INTERNET_OPTION_SERVER_CERT_CHAIN_CONTEXT:
2321 TRACE("INTERNET_OPTION_SERVER_CERT_CHAIN_CONTEXT\n");
2323 if (*size < sizeof(PCCERT_CHAIN_CONTEXT))
2324 return ERROR_INSUFFICIENT_BUFFER;
2326 if (!req->server->cert_chain)
2327 return ERROR_INTERNET_INCORRECT_HANDLE_STATE;
2329 *(PCCERT_CHAIN_CONTEXT *)buffer = CertDuplicateCertificateChain(req->server->cert_chain);
2330 *size = sizeof(PCCERT_CHAIN_CONTEXT);
2332 return ERROR_SUCCESS;
2335 return INET_QueryOption(hdr, option, buffer, size, unicode);
2338 static DWORD HTTPREQ_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
2340 http_request_t *req = (http_request_t*)hdr;
2342 switch(option) {
2343 case 99: /* Undocumented, seems to be INTERNET_OPTION_SECURITY_FLAGS with argument validation */
2344 TRACE("Undocumented option 99\n");
2346 if (!buffer || size != sizeof(DWORD))
2347 return ERROR_INVALID_PARAMETER;
2348 if(*(DWORD*)buffer & ~SECURITY_SET_MASK)
2349 return ERROR_INTERNET_OPTION_NOT_SETTABLE;
2351 /* fall through */
2352 case INTERNET_OPTION_SECURITY_FLAGS:
2354 DWORD flags;
2356 if (!buffer || size != sizeof(DWORD))
2357 return ERROR_INVALID_PARAMETER;
2358 flags = *(DWORD *)buffer;
2359 TRACE("INTERNET_OPTION_SECURITY_FLAGS %08lx\n", flags);
2360 flags &= SECURITY_SET_MASK;
2361 req->security_flags |= flags;
2362 if(is_valid_netconn(req->netconn))
2363 req->netconn->security_flags |= flags;
2364 return ERROR_SUCCESS;
2367 case INTERNET_OPTION_USERNAME:
2368 free(req->session->userName);
2369 if (!(req->session->userName = wcsdup(buffer))) return ERROR_OUTOFMEMORY;
2370 return ERROR_SUCCESS;
2372 case INTERNET_OPTION_PASSWORD:
2373 free(req->session->password);
2374 if (!(req->session->password = wcsdup(buffer))) return ERROR_OUTOFMEMORY;
2375 return ERROR_SUCCESS;
2377 case INTERNET_OPTION_PROXY_USERNAME:
2378 free(req->session->appInfo->proxyUsername);
2379 if (!(req->session->appInfo->proxyUsername = wcsdup(buffer))) return ERROR_OUTOFMEMORY;
2380 return ERROR_SUCCESS;
2382 case INTERNET_OPTION_PROXY_PASSWORD:
2383 free(req->session->appInfo->proxyPassword);
2384 if (!(req->session->appInfo->proxyPassword = wcsdup(buffer))) return ERROR_OUTOFMEMORY;
2385 return ERROR_SUCCESS;
2389 return INET_SetOption(hdr, option, buffer, size);
2392 static void commit_cache_entry(http_request_t *req)
2394 WCHAR *header;
2395 DWORD header_len;
2396 BOOL res;
2398 TRACE("%p\n", req);
2400 CloseHandle(req->hCacheFile);
2401 req->hCacheFile = NULL;
2403 header = build_response_header(req, TRUE);
2404 header_len = (header ? lstrlenW(header) : 0);
2405 res = CommitUrlCacheEntryW(req->req_file->url, req->req_file->file_name, req->expires,
2406 req->last_modified, NORMAL_CACHE_ENTRY,
2407 header, header_len, NULL, 0);
2408 if(res)
2409 req->req_file->is_committed = TRUE;
2410 else
2411 WARN("CommitUrlCacheEntry failed: %lu\n", GetLastError());
2412 free(header);
2415 static void create_cache_entry(http_request_t *req)
2417 WCHAR file_name[MAX_PATH+1];
2418 WCHAR *url;
2419 BOOL b = TRUE;
2421 /* FIXME: We should free previous cache file earlier */
2422 if(req->req_file) {
2423 req_file_release(req->req_file);
2424 req->req_file = NULL;
2426 if(req->hCacheFile) {
2427 CloseHandle(req->hCacheFile);
2428 req->hCacheFile = NULL;
2431 if(req->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE)
2432 b = FALSE;
2434 if(b) {
2435 int header_idx;
2437 EnterCriticalSection( &req->headers_section );
2439 header_idx = HTTP_GetCustomHeaderIndex(req, L"Cache-Control", 0, FALSE);
2440 if(header_idx != -1) {
2441 WCHAR *ptr;
2443 for(ptr=req->custHeaders[header_idx].lpszValue; *ptr; ) {
2444 WCHAR *end;
2446 while(*ptr==' ' || *ptr=='\t')
2447 ptr++;
2449 end = wcschr(ptr, ',');
2450 if(!end)
2451 end = ptr + lstrlenW(ptr);
2453 if(!wcsnicmp(ptr, L"no-cache", ARRAY_SIZE(L"no-cache")-1)
2454 || !wcsnicmp(ptr, L"no-store", ARRAY_SIZE(L"no-store")-1)) {
2455 b = FALSE;
2456 break;
2459 ptr = end;
2460 if(*ptr == ',')
2461 ptr++;
2465 LeaveCriticalSection( &req->headers_section );
2468 if(!b) {
2469 if(!(req->hdr.dwFlags & INTERNET_FLAG_NEED_FILE))
2470 return;
2472 FIXME("INTERNET_FLAG_NEED_FILE is not supported correctly\n");
2475 url = compose_request_url(req);
2476 if(!url) {
2477 WARN("Could not get URL\n");
2478 return;
2481 b = CreateUrlCacheEntryW(url, req->contentLength == ~0 ? 0 : req->contentLength, NULL, file_name, 0);
2482 if(!b) {
2483 WARN("Could not create cache entry: %08lx\n", GetLastError());
2484 return;
2487 create_req_file(file_name, &req->req_file);
2488 req->req_file->url = url;
2489 req->content_pos = 0;
2490 req->cache_size = 0;
2492 req->hCacheFile = CreateFileW(file_name, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
2493 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2494 if(req->hCacheFile == INVALID_HANDLE_VALUE) {
2495 WARN("Could not create file: %lu\n", GetLastError());
2496 req->hCacheFile = NULL;
2497 return;
2500 if(req->read_size) {
2501 DWORD written;
2503 b = WriteFile(req->hCacheFile, req->read_buf+req->read_pos, req->read_size, &written, NULL);
2504 if(b)
2505 req->cache_size += written;
2506 else
2507 FIXME("WriteFile failed: %lu\n", GetLastError());
2509 if(req->data_stream->vtbl->end_of_data(req->data_stream, req))
2510 commit_cache_entry(req);
2514 /* read some more data into the read buffer (the read section must be held) */
2515 static DWORD read_more_data( http_request_t *req, int maxlen )
2517 DWORD res;
2518 int len;
2520 if (req->read_pos)
2522 /* move existing data to the start of the buffer */
2523 if(req->read_size)
2524 memmove( req->read_buf, req->read_buf + req->read_pos, req->read_size );
2525 req->read_pos = 0;
2528 if (maxlen == -1) maxlen = sizeof(req->read_buf);
2530 res = NETCON_recv( req->netconn, req->read_buf + req->read_size,
2531 maxlen - req->read_size, TRUE, &len );
2532 if(res == ERROR_SUCCESS)
2533 req->read_size += len;
2535 return res;
2538 /* remove some amount of data from the read buffer (the read section must be held) */
2539 static void remove_data( http_request_t *req, int count )
2541 if (!(req->read_size -= count)) req->read_pos = 0;
2542 else req->read_pos += count;
2545 static DWORD read_line( http_request_t *req, LPSTR buffer, DWORD *len )
2547 int count, bytes_read, pos = 0;
2548 DWORD res;
2550 EnterCriticalSection( &req->read_section );
2551 for (;;)
2553 BYTE *eol = memchr( req->read_buf + req->read_pos, '\n', req->read_size );
2555 if (eol)
2557 count = eol - (req->read_buf + req->read_pos);
2558 bytes_read = count + 1;
2560 else count = bytes_read = req->read_size;
2562 count = min( count, *len - pos );
2563 memcpy( buffer + pos, req->read_buf + req->read_pos, count );
2564 pos += count;
2565 remove_data( req, bytes_read );
2566 if (eol) break;
2568 if ((res = read_more_data( req, -1 )))
2570 WARN( "read failed %lu\n", res );
2571 LeaveCriticalSection( &req->read_section );
2572 return res;
2574 if (!req->read_size)
2576 *len = 0;
2577 TRACE( "returning empty string\n" );
2578 LeaveCriticalSection( &req->read_section );
2579 return ERROR_SUCCESS;
2582 LeaveCriticalSection( &req->read_section );
2584 if (pos < *len)
2586 if (pos && buffer[pos - 1] == '\r') pos--;
2587 *len = pos + 1;
2589 buffer[*len - 1] = 0;
2590 TRACE( "returning %s\n", debugstr_a(buffer));
2591 return ERROR_SUCCESS;
2594 /* check if we have reached the end of the data to read (the read section must be held) */
2595 static BOOL end_of_read_data( http_request_t *req )
2597 return !req->read_size && req->data_stream->vtbl->end_of_data(req->data_stream, req);
2600 static DWORD read_http_stream(http_request_t *req, BYTE *buf, DWORD size, DWORD *read, BOOL allow_blocking)
2602 DWORD res;
2604 res = req->data_stream->vtbl->read(req->data_stream, req, buf, size, read, allow_blocking);
2605 if(res != ERROR_SUCCESS)
2606 *read = 0;
2607 assert(*read <= size);
2609 if(req->hCacheFile) {
2610 if(*read) {
2611 BOOL bres;
2612 DWORD written;
2614 bres = WriteFile(req->hCacheFile, buf, *read, &written, NULL);
2615 if(bres)
2616 req->cache_size += written;
2617 else
2618 FIXME("WriteFile failed: %lu\n", GetLastError());
2621 if((res == ERROR_SUCCESS && !*read) || req->data_stream->vtbl->end_of_data(req->data_stream, req))
2622 commit_cache_entry(req);
2625 return res;
2628 /* fetch some more data into the read buffer (the read section must be held) */
2629 static DWORD refill_read_buffer(http_request_t *req, BOOL allow_blocking, DWORD *read_bytes)
2631 DWORD res, read=0;
2633 if(req->read_size == sizeof(req->read_buf))
2634 return ERROR_SUCCESS;
2636 if(req->read_pos) {
2637 if(req->read_size)
2638 memmove(req->read_buf, req->read_buf+req->read_pos, req->read_size);
2639 req->read_pos = 0;
2642 res = read_http_stream(req, req->read_buf+req->read_size, sizeof(req->read_buf) - req->read_size,
2643 &read, allow_blocking);
2644 if(res != ERROR_SUCCESS)
2645 return res;
2647 req->read_size += read;
2649 TRACE("read %lu bytes, read_size %lu\n", read, req->read_size);
2650 if(read_bytes)
2651 *read_bytes = read;
2652 return res;
2655 static BOOL netconn_end_of_data(data_stream_t *stream, http_request_t *req)
2657 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2658 return netconn_stream->content_read == netconn_stream->content_length || !is_valid_netconn(req->netconn);
2661 static DWORD netconn_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2662 DWORD *read, BOOL allow_blocking)
2664 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2665 DWORD res = ERROR_SUCCESS;
2666 int ret = 0;
2668 size = min(size, netconn_stream->content_length-netconn_stream->content_read);
2670 if(size && is_valid_netconn(req->netconn)) {
2671 res = NETCON_recv(req->netconn, buf, size, allow_blocking, &ret);
2672 if(res == ERROR_SUCCESS) {
2673 if(!ret)
2674 netconn_stream->content_length = netconn_stream->content_read;
2675 netconn_stream->content_read += ret;
2679 TRACE("res %lu read %u bytes\n", res, ret);
2680 *read = ret;
2681 return res;
2684 static DWORD netconn_drain_content(data_stream_t *stream, http_request_t *req, BOOL allow_blocking)
2686 netconn_stream_t *netconn_stream = (netconn_stream_t*)stream;
2687 BYTE buf[1024];
2688 int len, res;
2689 size_t size;
2691 if(netconn_stream->content_length == ~0)
2692 return WSAEISCONN;
2694 while(netconn_stream->content_read < netconn_stream->content_length) {
2695 size = min(sizeof(buf), netconn_stream->content_length-netconn_stream->content_read);
2696 res = NETCON_recv(req->netconn, buf, size, allow_blocking, &len);
2697 if(res)
2698 return res;
2699 if(!len)
2700 return WSAECONNABORTED;
2702 netconn_stream->content_read += len;
2705 return ERROR_SUCCESS;
2708 static void netconn_destroy(data_stream_t *stream)
2712 static const data_stream_vtbl_t netconn_stream_vtbl = {
2713 netconn_end_of_data,
2714 netconn_read,
2715 netconn_drain_content,
2716 netconn_destroy
2719 static char next_chunked_data_char(chunked_stream_t *stream)
2721 assert(stream->buf_size);
2723 stream->buf_size--;
2724 return stream->buf[stream->buf_pos++];
2727 static BOOL chunked_end_of_data(data_stream_t *stream, http_request_t *req)
2729 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2730 switch(chunked_stream->state) {
2731 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END:
2732 case CHUNKED_STREAM_STATE_END_OF_STREAM:
2733 case CHUNKED_STREAM_STATE_ERROR:
2734 return TRUE;
2735 default:
2736 return FALSE;
2740 static DWORD chunked_read(data_stream_t *stream, http_request_t *req, BYTE *buf, DWORD size,
2741 DWORD *read, BOOL allow_blocking)
2743 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2744 DWORD ret_read = 0, res = ERROR_SUCCESS;
2745 BOOL continue_read = TRUE;
2746 int read_bytes;
2747 char ch;
2749 do {
2750 TRACE("state %d\n", chunked_stream->state);
2752 /* Ensure that we have data in the buffer for states that need it. */
2753 if(!chunked_stream->buf_size) {
2754 BOOL blocking_read = allow_blocking;
2756 switch(chunked_stream->state) {
2757 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END:
2758 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE:
2759 /* never allow blocking after 0 chunk size */
2760 if(!chunked_stream->chunk_size)
2761 blocking_read = FALSE;
2762 /* fall through */
2763 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE:
2764 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA:
2765 chunked_stream->buf_pos = 0;
2766 res = NETCON_recv(req->netconn, chunked_stream->buf, sizeof(chunked_stream->buf), blocking_read, &read_bytes);
2767 if(res == ERROR_SUCCESS && read_bytes) {
2768 chunked_stream->buf_size += read_bytes;
2769 }else if(res == WSAEWOULDBLOCK) {
2770 if(ret_read || allow_blocking)
2771 res = ERROR_SUCCESS;
2772 continue_read = FALSE;
2773 continue;
2774 }else {
2775 chunked_stream->state = CHUNKED_STREAM_STATE_ERROR;
2777 break;
2778 default:
2779 break;
2783 switch(chunked_stream->state) {
2784 case CHUNKED_STREAM_STATE_READING_CHUNK_SIZE:
2785 ch = next_chunked_data_char(chunked_stream);
2787 if(ch >= '0' && ch <= '9') {
2788 chunked_stream->chunk_size = chunked_stream->chunk_size * 16 + ch - '0';
2789 }else if(ch >= 'a' && ch <= 'f') {
2790 chunked_stream->chunk_size = chunked_stream->chunk_size * 16 + ch - 'a' + 10;
2791 }else if (ch >= 'A' && ch <= 'F') {
2792 chunked_stream->chunk_size = chunked_stream->chunk_size * 16 + ch - 'A' + 10;
2793 }else if (ch == ';' || ch == '\r' || ch == '\n') {
2794 TRACE("reading %lu byte chunk\n", chunked_stream->chunk_size);
2795 chunked_stream->buf_size++;
2796 chunked_stream->buf_pos--;
2797 if(req->contentLength == ~0) req->contentLength = chunked_stream->chunk_size;
2798 else req->contentLength += chunked_stream->chunk_size;
2799 chunked_stream->state = CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE;
2801 break;
2803 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_SIZE:
2804 ch = next_chunked_data_char(chunked_stream);
2805 if(ch == '\n')
2806 chunked_stream->state = chunked_stream->chunk_size
2807 ? CHUNKED_STREAM_STATE_READING_CHUNK
2808 : CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END;
2809 else if(ch != '\r')
2810 WARN("unexpected char '%c'\n", ch);
2811 break;
2813 case CHUNKED_STREAM_STATE_READING_CHUNK:
2814 assert(chunked_stream->chunk_size);
2815 if(!size) {
2816 continue_read = FALSE;
2817 break;
2819 read_bytes = min(size, chunked_stream->chunk_size);
2821 if(chunked_stream->buf_size) {
2822 if(read_bytes > chunked_stream->buf_size)
2823 read_bytes = chunked_stream->buf_size;
2825 memcpy(buf+ret_read, chunked_stream->buf+chunked_stream->buf_pos, read_bytes);
2826 chunked_stream->buf_pos += read_bytes;
2827 chunked_stream->buf_size -= read_bytes;
2828 }else {
2829 res = NETCON_recv(req->netconn, (char*)buf+ret_read, read_bytes,
2830 allow_blocking, (int*)&read_bytes);
2831 if(res != ERROR_SUCCESS) {
2832 continue_read = FALSE;
2833 break;
2836 if(!read_bytes) {
2837 chunked_stream->state = CHUNKED_STREAM_STATE_ERROR;
2838 continue;
2842 chunked_stream->chunk_size -= read_bytes;
2843 size -= read_bytes;
2844 ret_read += read_bytes;
2845 if(!chunked_stream->chunk_size)
2846 chunked_stream->state = CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA;
2847 allow_blocking = FALSE;
2848 break;
2850 case CHUNKED_STREAM_STATE_DISCARD_EOL_AFTER_DATA:
2851 ch = next_chunked_data_char(chunked_stream);
2852 if(ch == '\n')
2853 chunked_stream->state = CHUNKED_STREAM_STATE_READING_CHUNK_SIZE;
2854 else if(ch != '\r')
2855 WARN("unexpected char '%c'\n", ch);
2856 break;
2858 case CHUNKED_STREAM_STATE_DISCARD_EOL_AT_END:
2859 ch = next_chunked_data_char(chunked_stream);
2860 if(ch == '\n')
2861 chunked_stream->state = CHUNKED_STREAM_STATE_END_OF_STREAM;
2862 else if(ch != '\r')
2863 WARN("unexpected char '%c'\n", ch);
2864 break;
2866 case CHUNKED_STREAM_STATE_END_OF_STREAM:
2867 case CHUNKED_STREAM_STATE_ERROR:
2868 continue_read = FALSE;
2869 break;
2871 } while(continue_read);
2873 if(ret_read)
2874 res = ERROR_SUCCESS;
2875 if(res != ERROR_SUCCESS)
2876 return res;
2878 TRACE("read %ld bytes\n", ret_read);
2879 *read = ret_read;
2880 return ERROR_SUCCESS;
2883 static DWORD chunked_drain_content(data_stream_t *stream, http_request_t *req, BOOL allow_blocking)
2885 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2886 BYTE buf[1024];
2887 DWORD size, res;
2889 while(chunked_stream->state != CHUNKED_STREAM_STATE_END_OF_STREAM
2890 && chunked_stream->state != CHUNKED_STREAM_STATE_ERROR) {
2891 res = chunked_read(stream, req, buf, sizeof(buf), &size, allow_blocking);
2892 if(res != ERROR_SUCCESS)
2893 return res;
2896 if(chunked_stream->state != CHUNKED_STREAM_STATE_END_OF_STREAM)
2897 return ERROR_NO_DATA;
2898 return ERROR_SUCCESS;
2901 static void chunked_destroy(data_stream_t *stream)
2903 chunked_stream_t *chunked_stream = (chunked_stream_t*)stream;
2904 free(chunked_stream);
2907 static const data_stream_vtbl_t chunked_stream_vtbl = {
2908 chunked_end_of_data,
2909 chunked_read,
2910 chunked_drain_content,
2911 chunked_destroy
2914 /* set the request content length based on the headers */
2915 static DWORD set_content_length(http_request_t *request)
2917 WCHAR contentLength[32];
2918 WCHAR encoding[20];
2919 DWORD size;
2921 if(request->status_code == HTTP_STATUS_NO_CONTENT || request->status_code == HTTP_STATUS_NOT_MODIFIED ||
2922 !wcscmp(request->verb, L"HEAD"))
2924 if (HTTP_GetCustomHeaderIndex(request, L"Content-Length", 0, FALSE) == -1 ||
2925 !wcscmp(request->verb, L"HEAD"))
2926 request->read_size = 0;
2927 request->contentLength = request->netconn_stream.content_length = 0;
2928 return ERROR_SUCCESS;
2931 size = sizeof(contentLength);
2932 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_CONTENT_LENGTH,
2933 contentLength, &size, NULL) != ERROR_SUCCESS ||
2934 !StrToInt64ExW(contentLength, STIF_DEFAULT, (LONGLONG*)&request->contentLength)) {
2935 request->contentLength = ~0;
2938 request->netconn_stream.content_length = request->contentLength;
2939 request->netconn_stream.content_read = request->read_size;
2941 size = sizeof(encoding);
2942 if (HTTP_HttpQueryInfoW(request, HTTP_QUERY_TRANSFER_ENCODING, encoding, &size, NULL) == ERROR_SUCCESS &&
2943 !wcsicmp(encoding, L"chunked"))
2945 chunked_stream_t *chunked_stream;
2947 chunked_stream = malloc(sizeof(*chunked_stream));
2948 if(!chunked_stream)
2949 return ERROR_OUTOFMEMORY;
2951 chunked_stream->data_stream.vtbl = &chunked_stream_vtbl;
2952 chunked_stream->buf_size = chunked_stream->buf_pos = 0;
2953 chunked_stream->chunk_size = 0;
2954 chunked_stream->state = CHUNKED_STREAM_STATE_READING_CHUNK_SIZE;
2956 if(request->read_size) {
2957 memcpy(chunked_stream->buf, request->read_buf+request->read_pos, request->read_size);
2958 chunked_stream->buf_size = request->read_size;
2959 request->read_size = request->read_pos = 0;
2962 request->data_stream = &chunked_stream->data_stream;
2963 request->contentLength = ~0;
2966 if(request->hdr.decoding) {
2967 int encoding_idx;
2969 EnterCriticalSection( &request->headers_section );
2971 encoding_idx = HTTP_GetCustomHeaderIndex(request, L"Content-Encoding", 0, FALSE);
2972 if(encoding_idx != -1) {
2973 if(!wcsicmp(request->custHeaders[encoding_idx].lpszValue, L"gzip")) {
2974 HTTP_DeleteCustomHeader(request, encoding_idx);
2975 LeaveCriticalSection( &request->headers_section );
2976 return init_gzip_stream(request, TRUE);
2978 if(!wcsicmp(request->custHeaders[encoding_idx].lpszValue, L"deflate")) {
2979 HTTP_DeleteCustomHeader(request, encoding_idx);
2980 LeaveCriticalSection( &request->headers_section );
2981 return init_gzip_stream(request, FALSE);
2985 LeaveCriticalSection( &request->headers_section );
2988 return ERROR_SUCCESS;
2991 static void send_request_complete(http_request_t *req, DWORD_PTR result, DWORD error)
2993 INTERNET_ASYNC_RESULT iar;
2995 iar.dwResult = result;
2996 iar.dwError = error;
2998 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
2999 sizeof(INTERNET_ASYNC_RESULT));
3002 static void HTTP_ReceiveRequestData(http_request_t *req)
3004 DWORD res, read = 0;
3006 TRACE("%p\n", req);
3008 EnterCriticalSection( &req->read_section );
3010 res = refill_read_buffer(req, FALSE, &read);
3011 if(res == ERROR_SUCCESS)
3012 read += req->read_size;
3014 LeaveCriticalSection( &req->read_section );
3016 if(res != WSAEWOULDBLOCK && (res != ERROR_SUCCESS || !read)) {
3017 WARN("res %lu read %lu, closing connection\n", res, read);
3018 http_release_netconn(req, FALSE);
3021 if(res != ERROR_SUCCESS && res != WSAEWOULDBLOCK) {
3022 send_request_complete(req, 0, res);
3023 return;
3026 send_request_complete(req, req->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)req->hdr.hInternet : 1, 0);
3029 static DWORD read_req_file(http_request_t *req, BYTE *buffer, DWORD size, DWORD *read, BOOL allow_blocking)
3031 DWORD ret_read = 0, res;
3032 LARGE_INTEGER off;
3033 BYTE buf[1024];
3035 while (req->content_pos > req->cache_size) {
3036 res = read_http_stream(req, (BYTE*)buf, min(sizeof(buf), req->content_pos - req->cache_size),
3037 &ret_read, allow_blocking);
3038 if (res != ERROR_SUCCESS)
3039 return res;
3040 if (!ret_read) {
3041 *read = 0;
3042 return ERROR_SUCCESS;
3046 if (req->content_pos < req->cache_size) {
3047 off.QuadPart = req->content_pos;
3048 if (!SetFilePointerEx(req->req_file->file_handle, off, NULL, FILE_BEGIN))
3049 return GetLastError();
3050 if (!ReadFile(req->req_file->file_handle, buffer, size, &ret_read, NULL))
3051 return GetLastError();
3054 *read = ret_read;
3055 return ERROR_SUCCESS;
3058 /* read data from the http connection (the read section must be held) */
3059 static DWORD HTTPREQ_Read(http_request_t *req, void *buffer, DWORD size, DWORD *read, BOOL allow_blocking)
3061 DWORD current_read = 0, ret_read = 0;
3062 DWORD res = ERROR_SUCCESS;
3064 EnterCriticalSection( &req->read_section );
3066 if(req->read_size) {
3067 ret_read = min(size, req->read_size);
3068 memcpy(buffer, req->read_buf+req->read_pos, ret_read);
3069 req->read_size -= ret_read;
3070 req->read_pos += ret_read;
3071 req->content_pos += ret_read;
3072 allow_blocking = FALSE;
3075 if(ret_read < size) {
3076 res = read_http_stream(req, (BYTE*)buffer+ret_read, size-ret_read, &current_read, allow_blocking);
3077 if(res == ERROR_SUCCESS) {
3078 ret_read += current_read;
3079 req->content_pos += current_read;
3081 else if(res == WSAEWOULDBLOCK && ret_read)
3082 res = ERROR_SUCCESS;
3085 LeaveCriticalSection( &req->read_section );
3087 *read = ret_read;
3088 TRACE( "retrieved %lu bytes (res %lu)\n", ret_read, res );
3090 if(res != WSAEWOULDBLOCK) {
3091 if(res != ERROR_SUCCESS)
3092 http_release_netconn(req, FALSE);
3093 else if(!ret_read && drain_content(req, FALSE) == ERROR_SUCCESS)
3094 http_release_netconn(req, TRUE);
3097 return res;
3100 static DWORD drain_content(http_request_t *req, BOOL blocking)
3102 DWORD res;
3104 TRACE("%p\n", req->netconn);
3106 if(!is_valid_netconn(req->netconn))
3107 return ERROR_NO_DATA;
3109 if(!wcscmp(req->verb, L"HEAD"))
3110 return ERROR_SUCCESS;
3112 EnterCriticalSection( &req->read_section );
3113 res = req->data_stream->vtbl->drain_content(req->data_stream, req, blocking);
3114 LeaveCriticalSection( &req->read_section );
3115 return res;
3118 typedef struct {
3119 task_header_t hdr;
3120 void *buf;
3121 DWORD size;
3122 DWORD read_pos;
3123 DWORD *ret_read;
3124 } read_file_task_t;
3126 static void async_read_file_proc(task_header_t *hdr)
3128 read_file_task_t *task = (read_file_task_t*)hdr;
3129 http_request_t *req = (http_request_t*)task->hdr.hdr;
3130 DWORD res = ERROR_SUCCESS, read = task->read_pos, complete_arg = 0;
3132 TRACE("req %p buf %p size %lu read_pos %lu ret_read %p\n", req, task->buf, task->size, task->read_pos, task->ret_read);
3134 if(req->req_file && req->req_file->file_handle) {
3135 DWORD ret, ret_read;
3136 BYTE buf[1024];
3137 while (req->content_pos > req->cache_size) {
3138 ret = read_http_stream(req, (BYTE*)buf, min(sizeof(buf), req->content_pos - req->cache_size),
3139 &ret_read, TRUE);
3140 if(ret != ERROR_SUCCESS || !ret_read)
3141 break;
3145 if(task->buf) {
3146 DWORD read_bytes;
3147 while (read < task->size) {
3148 res = HTTPREQ_Read(req, (char*)task->buf + read, task->size - read, &read_bytes, TRUE);
3149 if (res != ERROR_SUCCESS || !read_bytes)
3150 break;
3151 read += read_bytes;
3153 }else {
3154 EnterCriticalSection(&req->read_section);
3155 res = refill_read_buffer(req, TRUE, &read);
3156 LeaveCriticalSection(&req->read_section);
3158 if(task->ret_read)
3159 complete_arg = read; /* QueryDataAvailable reports read bytes in request complete notification */
3160 if(res != ERROR_SUCCESS || !read)
3161 http_release_netconn(req, drain_content(req, FALSE) == ERROR_SUCCESS);
3164 TRACE("res %lu read %lu\n", res, read);
3166 if(task->ret_read)
3167 *task->ret_read = read;
3169 /* FIXME: We should report bytes transferred before decoding content. */
3170 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED, &read, sizeof(read));
3172 if(res != ERROR_SUCCESS)
3173 complete_arg = res;
3174 send_request_complete(req, res == ERROR_SUCCESS, complete_arg);
3177 static DWORD async_read(http_request_t *req, void *buf, DWORD size, DWORD read_pos, DWORD *ret_read)
3179 read_file_task_t *task;
3181 task = alloc_async_task(&req->hdr, async_read_file_proc, sizeof(*task));
3182 if(!task)
3183 return ERROR_OUTOFMEMORY;
3185 task->buf = buf;
3186 task->size = size;
3187 task->read_pos = read_pos;
3188 task->ret_read = ret_read;
3190 INTERNET_AsyncCall(&task->hdr);
3191 return ERROR_IO_PENDING;
3194 static DWORD HTTPREQ_SetFilePointer(object_header_t *hdr, LONG lDistanceToMove, DWORD dwMoveContext)
3196 http_request_t *req = (http_request_t*)hdr;
3197 DWORD res = INVALID_SET_FILE_POINTER, err = ERROR_SUCCESS;
3199 if(req->hdr.dwFlags & (INTERNET_FLAG_DONT_CACHE|INTERNET_FLAG_NO_CACHE_WRITE)) {
3200 SetLastError(ERROR_INTERNET_INVALID_OPERATION);
3201 return INVALID_SET_FILE_POINTER;
3204 EnterCriticalSection(&req->read_section);
3206 switch (dwMoveContext) {
3207 case FILE_BEGIN:
3208 res = lDistanceToMove;
3209 break;
3210 case FILE_CURRENT:
3211 if(req->content_pos && lDistanceToMove < 0) {
3212 err = ERROR_NEGATIVE_SEEK;
3213 break;
3215 res = req->content_pos + lDistanceToMove;
3216 break;
3217 case FILE_END:
3218 FIXME("dwMoveContext FILE_END not implemented\n");
3219 /* fallthrough */
3220 default:
3221 err = ERROR_INTERNET_INVALID_OPERATION;
3222 break;
3225 if(err == ERROR_SUCCESS) {
3226 req->content_pos = res;
3227 req->read_pos = req->read_size = 0;
3230 LeaveCriticalSection(&req->read_section);
3231 SetLastError(err);
3232 return res;
3235 static DWORD HTTPREQ_ReadFile(object_header_t *hdr, void *buf, DWORD size, DWORD *ret_read,
3236 DWORD flags, DWORD_PTR context)
3238 http_request_t *req = (http_request_t*)hdr;
3239 DWORD res = ERROR_SUCCESS, read = 0, cread, error = ERROR_SUCCESS;
3240 BOOL allow_blocking, notify_received = FALSE;
3242 TRACE("(%p %p %lu %lx)\n", req, buf, size, flags);
3244 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3245 FIXME("these dwFlags aren't implemented: 0x%lx\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3247 allow_blocking = !(req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC);
3249 if(allow_blocking || TryEnterCriticalSection(&req->read_section)) {
3250 if(allow_blocking)
3251 EnterCriticalSection(&req->read_section);
3252 if(hdr->dwError == ERROR_SUCCESS)
3253 hdr->dwError = INTERNET_HANDLE_IN_USE;
3254 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3255 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3257 if(req->read_size) {
3258 read = min(size, req->read_size);
3259 memcpy(buf, req->read_buf + req->read_pos, read);
3260 req->read_size -= read;
3261 req->read_pos += read;
3262 req->content_pos += read;
3265 if(read < size && req->req_file && req->req_file->file_handle) {
3266 res = read_req_file(req, (BYTE*)buf + read, size - read, &cread, allow_blocking);
3267 if(res == ERROR_SUCCESS) {
3268 read += cread;
3269 req->content_pos += cread;
3273 if(res == ERROR_SUCCESS && read < size && (!read || !(flags & IRF_NO_WAIT)) && !end_of_read_data(req)) {
3274 LeaveCriticalSection(&req->read_section);
3275 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3276 EnterCriticalSection( &req->read_section );
3277 notify_received = TRUE;
3279 while(read < size) {
3280 res = HTTPREQ_Read(req, (char*)buf+read, size-read, &cread, allow_blocking);
3281 read += cread;
3282 if (res != ERROR_SUCCESS || !cread)
3283 break;
3287 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3288 hdr->dwError = ERROR_SUCCESS;
3289 else
3290 error = hdr->dwError;
3292 LeaveCriticalSection( &req->read_section );
3293 }else {
3294 res = WSAEWOULDBLOCK;
3297 if(res == WSAEWOULDBLOCK) {
3298 if(!(flags & IRF_NO_WAIT))
3299 return async_read(req, buf, size, read, ret_read);
3300 if(!read)
3301 return async_read(req, NULL, 0, 0, NULL);
3302 res = ERROR_SUCCESS;
3305 *ret_read = read;
3306 if (res != ERROR_SUCCESS)
3307 return res;
3309 if(notify_received)
3310 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3311 &read, sizeof(read));
3312 return error;
3315 static DWORD HTTPREQ_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
3317 DWORD res;
3318 http_request_t *request = (http_request_t*)hdr;
3320 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
3322 *written = 0;
3323 res = NETCON_send(request->netconn, buffer, size, 0, (LPINT)written);
3324 if (res == ERROR_SUCCESS)
3325 request->bytesWritten += *written;
3327 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REQUEST_SENT, written, sizeof(DWORD));
3328 return res;
3331 static DWORD HTTPREQ_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
3333 http_request_t *req = (http_request_t*)hdr;
3334 DWORD res = ERROR_SUCCESS, avail = 0, error = ERROR_SUCCESS;
3335 BOOL allow_blocking, notify_received = FALSE;
3337 TRACE("(%p %p %lx %Ix)\n", req, available, flags, ctx);
3339 if (flags & ~(IRF_ASYNC|IRF_NO_WAIT))
3340 FIXME("these dwFlags aren't implemented: 0x%lx\n", flags & ~(IRF_ASYNC|IRF_NO_WAIT));
3342 *available = 0;
3343 allow_blocking = !(req->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC);
3345 if(allow_blocking || TryEnterCriticalSection(&req->read_section)) {
3346 if(allow_blocking)
3347 EnterCriticalSection(&req->read_section);
3348 if(hdr->dwError == ERROR_SUCCESS)
3349 hdr->dwError = INTERNET_HANDLE_IN_USE;
3350 else if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3351 hdr->dwError = ERROR_INTERNET_INTERNAL_ERROR;
3353 avail = req->read_size;
3354 if(req->cache_size > req->content_pos)
3355 avail = max(avail, req->cache_size - req->content_pos);
3357 if(!avail && !end_of_read_data(req)) {
3358 LeaveCriticalSection(&req->read_section);
3359 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
3360 EnterCriticalSection( &req->read_section );
3361 notify_received = TRUE;
3363 res = refill_read_buffer(req, allow_blocking, &avail);
3366 if(hdr->dwError == INTERNET_HANDLE_IN_USE)
3367 hdr->dwError = ERROR_SUCCESS;
3368 else
3369 error = hdr->dwError;
3371 LeaveCriticalSection( &req->read_section );
3372 }else {
3373 res = WSAEWOULDBLOCK;
3376 if(res == WSAEWOULDBLOCK)
3377 return async_read(req, NULL, 0, 0, available);
3379 if (res != ERROR_SUCCESS)
3380 return res;
3382 *available = avail;
3383 if(notify_received)
3384 INTERNET_SendCallback(&req->hdr, req->hdr.dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
3385 &avail, sizeof(avail));
3386 return error;
3389 static DWORD HTTPREQ_LockRequestFile(object_header_t *hdr, req_file_t **ret)
3391 http_request_t *req = (http_request_t*)hdr;
3393 TRACE("(%p)\n", req);
3395 if(!req->req_file) {
3396 WARN("No cache file name available\n");
3397 return ERROR_FILE_NOT_FOUND;
3400 *ret = req_file_addref(req->req_file);
3401 return ERROR_SUCCESS;
3404 static const object_vtbl_t HTTPREQVtbl = {
3405 HTTPREQ_Destroy,
3406 HTTPREQ_CloseConnection,
3407 HTTPREQ_QueryOption,
3408 HTTPREQ_SetOption,
3409 HTTPREQ_SetFilePointer,
3410 HTTPREQ_ReadFile,
3411 HTTPREQ_WriteFile,
3412 HTTPREQ_QueryDataAvailable,
3413 NULL,
3414 HTTPREQ_LockRequestFile
3417 /***********************************************************************
3418 * HTTP_HttpOpenRequestW (internal)
3420 * Open a HTTP request handle
3422 * RETURNS
3423 * HINTERNET a HTTP request handle on success
3424 * NULL on failure
3427 static DWORD HTTP_HttpOpenRequestW(http_session_t *session,
3428 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3429 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3430 DWORD dwFlags, DWORD_PTR dwContext, HINTERNET *ret)
3432 appinfo_t *hIC = session->appInfo;
3433 http_request_t *request;
3434 DWORD port, len;
3436 TRACE("-->\n");
3438 request = alloc_object(&session->hdr, &HTTPREQVtbl, sizeof(http_request_t));
3439 if(!request)
3440 return ERROR_OUTOFMEMORY;
3442 request->hdr.htype = WH_HHTTPREQ;
3443 request->hdr.dwFlags = dwFlags;
3444 request->hdr.dwContext = dwContext;
3445 request->hdr.decoding = session->hdr.decoding;
3446 request->contentLength = ~0;
3448 request->netconn_stream.data_stream.vtbl = &netconn_stream_vtbl;
3449 request->data_stream = &request->netconn_stream.data_stream;
3450 request->hdr.connect_timeout = session->hdr.connect_timeout;
3451 request->hdr.send_timeout = session->hdr.send_timeout;
3452 request->hdr.receive_timeout = session->hdr.receive_timeout;
3454 InitializeCriticalSectionEx( &request->headers_section, 0, RTL_CRITICAL_SECTION_FLAG_FORCE_DEBUG_INFO );
3455 request->headers_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.headers_section");
3457 InitializeCriticalSectionEx( &request->read_section, 0, RTL_CRITICAL_SECTION_FLAG_FORCE_DEBUG_INFO );
3458 request->read_section.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": http_request_t.read_section");
3460 WININET_AddRef( &session->hdr );
3461 request->session = session;
3462 list_add_head( &session->hdr.children, &request->hdr.entry );
3464 port = session->hostPort;
3465 if (port == INTERNET_INVALID_PORT_NUMBER)
3466 port = (session->hdr.dwFlags & INTERNET_FLAG_SECURE) ?
3467 INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;
3469 request->server = get_server(substrz(session->hostName), port, (dwFlags & INTERNET_FLAG_SECURE) != 0, TRUE);
3470 if(!request->server) {
3471 WININET_Release(&request->hdr);
3472 return ERROR_OUTOFMEMORY;
3475 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_CN_INVALID)
3476 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
3477 if (dwFlags & INTERNET_FLAG_IGNORE_CERT_DATE_INVALID)
3478 request->security_flags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
3480 if (lpszObjectName && *lpszObjectName) {
3481 HRESULT rc;
3482 WCHAR dummy;
3484 len = 1;
3485 rc = UrlCanonicalizeW(lpszObjectName, &dummy, &len, URL_ESCAPE_SPACES_ONLY);
3486 if (rc != E_POINTER)
3487 len = lstrlenW(lpszObjectName)+1;
3488 request->path = malloc(len * sizeof(WCHAR));
3489 rc = UrlCanonicalizeW(lpszObjectName, request->path, &len,
3490 URL_ESCAPE_SPACES_ONLY);
3491 if (rc != S_OK)
3493 ERR("Unable to escape string!(%s) (%ld)\n",debugstr_w(lpszObjectName),rc);
3494 lstrcpyW(request->path,lpszObjectName);
3496 }else {
3497 request->path = wcsdup(L"/");
3500 if (lpszReferrer && *lpszReferrer)
3501 HTTP_ProcessHeader(request, L"Referer", lpszReferrer, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDHDR_FLAG_REQ);
3503 if (lpszAcceptTypes)
3505 int i;
3506 for (i = 0; lpszAcceptTypes[i]; i++)
3508 if (!*lpszAcceptTypes[i]) continue;
3509 HTTP_ProcessHeader(request, L"Accept", lpszAcceptTypes[i],
3510 HTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA |
3511 HTTP_ADDHDR_FLAG_REQ |
3512 (i == 0 ? (HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD) : 0));
3516 request->verb = wcsdup(lpszVerb && *lpszVerb ? lpszVerb : L"GET");
3517 request->version = wcsdup(lpszVersion && *lpszVersion ? lpszVersion : L"HTTP/1.1");
3519 if (hIC->proxy && hIC->proxy[0] && !HTTP_ShouldBypassProxy(hIC, session->hostName))
3520 HTTP_DealWithProxy( hIC, session, request );
3522 INTERNET_SendCallback(&session->hdr, dwContext,
3523 INTERNET_STATUS_HANDLE_CREATED, &request->hdr.hInternet,
3524 sizeof(HINTERNET));
3526 TRACE("<-- (%p)\n", request);
3528 *ret = request->hdr.hInternet;
3529 return ERROR_SUCCESS;
3532 /***********************************************************************
3533 * HttpOpenRequestW (WININET.@)
3535 * Open a HTTP request handle
3537 * RETURNS
3538 * HINTERNET a HTTP request handle on success
3539 * NULL on failure
3542 HINTERNET WINAPI HttpOpenRequestW(HINTERNET hHttpSession,
3543 LPCWSTR lpszVerb, LPCWSTR lpszObjectName, LPCWSTR lpszVersion,
3544 LPCWSTR lpszReferrer , LPCWSTR *lpszAcceptTypes,
3545 DWORD dwFlags, DWORD_PTR dwContext)
3547 http_session_t *session;
3548 HINTERNET handle = NULL;
3549 DWORD res;
3551 TRACE("(%p, %s, %s, %s, %s, %p, %08lx, %08Ix)\n", hHttpSession,
3552 debugstr_w(lpszVerb), debugstr_w(lpszObjectName),
3553 debugstr_w(lpszVersion), debugstr_w(lpszReferrer), lpszAcceptTypes,
3554 dwFlags, dwContext);
3555 if(lpszAcceptTypes!=NULL)
3557 int i;
3558 for(i=0;lpszAcceptTypes[i]!=NULL;i++)
3559 TRACE("\taccept type: %s\n",debugstr_w(lpszAcceptTypes[i]));
3562 session = (http_session_t*) get_handle_object( hHttpSession );
3563 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
3565 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3566 goto lend;
3570 * My tests seem to show that the windows version does not
3571 * become asynchronous until after this point. And anyhow
3572 * if this call was asynchronous then how would you get the
3573 * necessary HINTERNET pointer returned by this function.
3576 res = HTTP_HttpOpenRequestW(session, lpszVerb, lpszObjectName,
3577 lpszVersion, lpszReferrer, lpszAcceptTypes,
3578 dwFlags, dwContext, &handle);
3579 lend:
3580 if( session )
3581 WININET_Release( &session->hdr );
3582 TRACE("returning %p\n", handle);
3583 if(res != ERROR_SUCCESS)
3584 SetLastError(res);
3585 return handle;
3588 static const LPCWSTR header_lookup[] = {
3589 L"Mime-Version", /* HTTP_QUERY_MIME_VERSION = 0 */
3590 L"Content-Type", /* HTTP_QUERY_CONTENT_TYPE = 1 */
3591 L"Content-Transfer-Encoding", /* HTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2 */
3592 L"Content-ID", /* HTTP_QUERY_CONTENT_ID = 3 */
3593 NULL, /* HTTP_QUERY_CONTENT_DESCRIPTION = 4 */
3594 L"Content-Length", /* HTTP_QUERY_CONTENT_LENGTH = 5 */
3595 L"Content-Language", /* HTTP_QUERY_CONTENT_LANGUAGE = 6 */
3596 L"Allow", /* HTTP_QUERY_ALLOW = 7 */
3597 L"Public", /* HTTP_QUERY_PUBLIC = 8 */
3598 L"Date", /* HTTP_QUERY_DATE = 9 */
3599 L"Expires", /* HTTP_QUERY_EXPIRES = 10 */
3600 L"Last-Modified", /* HTTP_QUERY_LAST_MODIFIED = 11 */
3601 NULL, /* HTTP_QUERY_MESSAGE_ID = 12 */
3602 L"URI", /* HTTP_QUERY_URI = 13 */
3603 L"From", /* HTTP_QUERY_DERIVED_FROM = 14 */
3604 NULL, /* HTTP_QUERY_COST = 15 */
3605 NULL, /* HTTP_QUERY_LINK = 16 */
3606 L"Pragma", /* HTTP_QUERY_PRAGMA = 17 */
3607 NULL, /* HTTP_QUERY_VERSION = 18 */
3608 L"Status", /* HTTP_QUERY_STATUS_CODE = 19 */
3609 NULL, /* HTTP_QUERY_STATUS_TEXT = 20 */
3610 NULL, /* HTTP_QUERY_RAW_HEADERS = 21 */
3611 NULL, /* HTTP_QUERY_RAW_HEADERS_CRLF = 22 */
3612 L"Connection", /* HTTP_QUERY_CONNECTION = 23 */
3613 L"Accept", /* HTTP_QUERY_ACCEPT = 24 */
3614 L"Accept-Charset", /* HTTP_QUERY_ACCEPT_CHARSET = 25 */
3615 L"Accept-Encoding", /* HTTP_QUERY_ACCEPT_ENCODING = 26 */
3616 L"Accept-Language", /* HTTP_QUERY_ACCEPT_LANGUAGE = 27 */
3617 L"Authorization", /* HTTP_QUERY_AUTHORIZATION = 28 */
3618 L"Content-Encoding", /* HTTP_QUERY_CONTENT_ENCODING = 29 */
3619 NULL, /* HTTP_QUERY_FORWARDED = 30 */
3620 NULL, /* HTTP_QUERY_FROM = 31 */
3621 L"If-Modified-Since", /* HTTP_QUERY_IF_MODIFIED_SINCE = 32 */
3622 L"Location", /* HTTP_QUERY_LOCATION = 33 */
3623 NULL, /* HTTP_QUERY_ORIG_URI = 34 */
3624 L"Referer", /* HTTP_QUERY_REFERER = 35 */
3625 L"Retry-After", /* HTTP_QUERY_RETRY_AFTER = 36 */
3626 L"Server", /* HTTP_QUERY_SERVER = 37 */
3627 NULL, /* HTTP_TITLE = 38 */
3628 L"User-Agent", /* HTTP_QUERY_USER_AGENT = 39 */
3629 L"WWW-Authenticate", /* HTTP_QUERY_WWW_AUTHENTICATE = 40 */
3630 L"Proxy-Authenticate", /* HTTP_QUERY_PROXY_AUTHENTICATE = 41 */
3631 L"Accept-Ranges", /* HTTP_QUERY_ACCEPT_RANGES = 42 */
3632 L"Set-Cookie", /* HTTP_QUERY_SET_COOKIE = 43 */
3633 L"Cookie", /* HTTP_QUERY_COOKIE = 44 */
3634 NULL, /* HTTP_QUERY_REQUEST_METHOD = 45 */
3635 NULL, /* HTTP_QUERY_REFRESH = 46 */
3636 L"Content-Disposition", /* HTTP_QUERY_CONTENT_DISPOSITION = 47 */
3637 L"Age", /* HTTP_QUERY_AGE = 48 */
3638 L"Cache-Control", /* HTTP_QUERY_CACHE_CONTROL = 49 */
3639 L"Content-Base", /* HTTP_QUERY_CONTENT_BASE = 50 */
3640 L"Content-Location", /* HTTP_QUERY_CONTENT_LOCATION = 51 */
3641 L"Content-MD5", /* HTTP_QUERY_CONTENT_MD5 = 52 */
3642 L"Content-Range", /* HTTP_QUERY_CONTENT_RANGE = 53 */
3643 L"ETag", /* HTTP_QUERY_ETAG = 54 */
3644 L"Host", /* HTTP_QUERY_HOST = 55 */
3645 L"If-Match", /* HTTP_QUERY_IF_MATCH = 56 */
3646 L"If-None-Match", /* HTTP_QUERY_IF_NONE_MATCH = 57 */
3647 L"If-Range", /* HTTP_QUERY_IF_RANGE = 58 */
3648 L"If-Unmodified-Since", /* HTTP_QUERY_IF_UNMODIFIED_SINCE = 59 */
3649 L"Max-Forwards", /* HTTP_QUERY_MAX_FORWARDS = 60 */
3650 L"Proxy-Authorization", /* HTTP_QUERY_PROXY_AUTHORIZATION = 61 */
3651 L"Range", /* HTTP_QUERY_RANGE = 62 */
3652 L"Transfer-Encoding", /* HTTP_QUERY_TRANSFER_ENCODING = 63 */
3653 L"Upgrade", /* HTTP_QUERY_UPGRADE = 64 */
3654 L"Vary", /* HTTP_QUERY_VARY = 65 */
3655 L"Via", /* HTTP_QUERY_VIA = 66 */
3656 L"Warning", /* HTTP_QUERY_WARNING = 67 */
3657 L"Expect", /* HTTP_QUERY_EXPECT = 68 */
3658 L"Proxy-Connection", /* HTTP_QUERY_PROXY_CONNECTION = 69 */
3659 L"Unless-Modified-Since", /* HTTP_QUERY_UNLESS_MODIFIED_SINCE = 70 */
3662 /***********************************************************************
3663 * HTTP_HttpQueryInfoW (internal)
3665 static DWORD HTTP_HttpQueryInfoW(http_request_t *request, DWORD dwInfoLevel,
3666 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3668 LPHTTPHEADERW lphttpHdr = NULL;
3669 BOOL request_only = !!(dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS);
3670 INT requested_index = lpdwIndex ? *lpdwIndex : 0;
3671 DWORD level = (dwInfoLevel & ~HTTP_QUERY_MODIFIER_FLAGS_MASK);
3672 INT index = -1;
3674 EnterCriticalSection( &request->headers_section );
3676 /* Find requested header structure */
3677 switch (level)
3679 case HTTP_QUERY_CUSTOM:
3680 if (!lpBuffer)
3682 LeaveCriticalSection( &request->headers_section );
3683 return ERROR_INVALID_PARAMETER;
3685 index = HTTP_GetCustomHeaderIndex(request, lpBuffer, requested_index, request_only);
3686 break;
3687 case HTTP_QUERY_RAW_HEADERS_CRLF:
3689 LPWSTR headers;
3690 DWORD len = 0;
3691 DWORD res = ERROR_INVALID_PARAMETER;
3693 if (request_only)
3694 headers = build_request_header(request, request->verb, request->path, request->version, TRUE);
3695 else
3696 headers = build_response_header(request, TRUE);
3697 if (!headers)
3699 LeaveCriticalSection( &request->headers_section );
3700 return ERROR_OUTOFMEMORY;
3703 len = lstrlenW(headers) * sizeof(WCHAR);
3704 if (len + sizeof(WCHAR) > *lpdwBufferLength)
3706 len += sizeof(WCHAR);
3707 res = ERROR_INSUFFICIENT_BUFFER;
3709 else if (lpBuffer)
3711 memcpy(lpBuffer, headers, len + sizeof(WCHAR));
3712 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len / sizeof(WCHAR)));
3713 res = ERROR_SUCCESS;
3715 *lpdwBufferLength = len;
3717 free(headers);
3718 LeaveCriticalSection( &request->headers_section );
3719 return res;
3721 case HTTP_QUERY_RAW_HEADERS:
3723 LPWSTR headers;
3724 DWORD len;
3726 if (request_only)
3727 headers = build_request_header(request, request->verb, request->path, request->version, FALSE);
3728 else
3729 headers = build_response_header(request, FALSE);
3731 if (!headers)
3733 LeaveCriticalSection( &request->headers_section );
3734 return ERROR_OUTOFMEMORY;
3737 len = lstrlenW(headers) * sizeof(WCHAR);
3738 if (len > *lpdwBufferLength)
3740 *lpdwBufferLength = len;
3741 free(headers);
3742 LeaveCriticalSection( &request->headers_section );
3743 return ERROR_INSUFFICIENT_BUFFER;
3746 if (lpBuffer)
3748 DWORD i;
3750 TRACE("returning data: %s\n", debugstr_wn(headers, len / sizeof(WCHAR)));
3752 for (i = 0; i < len / sizeof(WCHAR); i++)
3754 if (headers[i] == '\n')
3755 headers[i] = 0;
3757 memcpy(lpBuffer, headers, len);
3759 *lpdwBufferLength = len - sizeof(WCHAR);
3761 free(headers);
3762 LeaveCriticalSection( &request->headers_section );
3763 return ERROR_SUCCESS;
3765 case HTTP_QUERY_STATUS_TEXT:
3766 if (request->statusText)
3768 DWORD len = lstrlenW(request->statusText);
3769 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3771 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3772 LeaveCriticalSection( &request->headers_section );
3773 return ERROR_INSUFFICIENT_BUFFER;
3775 if (lpBuffer)
3777 memcpy(lpBuffer, request->statusText, (len + 1) * sizeof(WCHAR));
3778 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3780 *lpdwBufferLength = len * sizeof(WCHAR);
3781 LeaveCriticalSection( &request->headers_section );
3782 return ERROR_SUCCESS;
3784 break;
3785 case HTTP_QUERY_VERSION:
3786 if (request->version)
3788 DWORD len = lstrlenW(request->version);
3789 if (len + 1 > *lpdwBufferLength/sizeof(WCHAR))
3791 *lpdwBufferLength = (len + 1) * sizeof(WCHAR);
3792 LeaveCriticalSection( &request->headers_section );
3793 return ERROR_INSUFFICIENT_BUFFER;
3795 if (lpBuffer)
3797 memcpy(lpBuffer, request->version, (len + 1) * sizeof(WCHAR));
3798 TRACE("returning data: %s\n", debugstr_wn(lpBuffer, len));
3800 *lpdwBufferLength = len * sizeof(WCHAR);
3801 LeaveCriticalSection( &request->headers_section );
3802 return ERROR_SUCCESS;
3804 break;
3805 case HTTP_QUERY_CONTENT_ENCODING:
3806 index = HTTP_GetCustomHeaderIndex(request, header_lookup[request->read_gzip ? HTTP_QUERY_CONTENT_TYPE : level],
3807 requested_index,request_only);
3808 break;
3809 case HTTP_QUERY_STATUS_CODE: {
3810 DWORD res = ERROR_SUCCESS;
3812 if(request_only)
3814 LeaveCriticalSection( &request->headers_section );
3815 return ERROR_HTTP_INVALID_QUERY_REQUEST;
3818 if(requested_index)
3819 break;
3821 if(dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) {
3822 if(*lpdwBufferLength >= sizeof(DWORD))
3823 *(DWORD*)lpBuffer = request->status_code;
3824 else
3825 res = ERROR_INSUFFICIENT_BUFFER;
3826 *lpdwBufferLength = sizeof(DWORD);
3827 }else {
3828 WCHAR buf[12];
3829 DWORD size;
3831 size = swprintf(buf, ARRAY_SIZE(buf), L"%u", request->status_code) * sizeof(WCHAR);
3833 if(size <= *lpdwBufferLength) {
3834 memcpy(lpBuffer, buf, size+sizeof(WCHAR));
3835 }else {
3836 size += sizeof(WCHAR);
3837 res = ERROR_INSUFFICIENT_BUFFER;
3840 *lpdwBufferLength = size;
3842 LeaveCriticalSection( &request->headers_section );
3843 return res;
3845 default:
3846 assert (ARRAY_SIZE(header_lookup) == (HTTP_QUERY_UNLESS_MODIFIED_SINCE + 1));
3848 if (level < ARRAY_SIZE(header_lookup) && header_lookup[level])
3849 index = HTTP_GetCustomHeaderIndex(request, header_lookup[level],
3850 requested_index,request_only);
3853 if (index >= 0)
3854 lphttpHdr = &request->custHeaders[index];
3856 /* Ensure header satisfies requested attributes */
3857 if (!lphttpHdr ||
3858 ((dwInfoLevel & HTTP_QUERY_FLAG_REQUEST_HEADERS) &&
3859 (~lphttpHdr->wFlags & HDR_ISREQUEST)))
3861 LeaveCriticalSection( &request->headers_section );
3862 return ERROR_HTTP_HEADER_NOT_FOUND;
3865 /* coalesce value to requested type */
3866 if (dwInfoLevel & HTTP_QUERY_FLAG_NUMBER && lpBuffer)
3868 unsigned long value;
3870 if (*lpdwBufferLength != sizeof(DWORD))
3872 LeaveCriticalSection( &request->headers_section );
3873 return ERROR_HTTP_INVALID_HEADER;
3876 errno = 0;
3877 value = wcstoul( lphttpHdr->lpszValue, NULL, 10 );
3878 if (value > UINT_MAX || (value == ULONG_MAX && errno == ERANGE))
3880 LeaveCriticalSection( &request->headers_section );
3881 return ERROR_HTTP_INVALID_HEADER;
3884 *(DWORD *)lpBuffer = value;
3885 TRACE(" returning number: %lu\n", *(DWORD *)lpBuffer);
3887 else if (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME && lpBuffer)
3889 time_t tmpTime;
3890 struct tm tmpTM;
3891 SYSTEMTIME *STHook;
3893 tmpTime = ConvertTimeString(lphttpHdr->lpszValue);
3895 tmpTM = *gmtime(&tmpTime);
3896 STHook = (SYSTEMTIME *)lpBuffer;
3897 STHook->wDay = tmpTM.tm_mday;
3898 STHook->wHour = tmpTM.tm_hour;
3899 STHook->wMilliseconds = 0;
3900 STHook->wMinute = tmpTM.tm_min;
3901 STHook->wDayOfWeek = tmpTM.tm_wday;
3902 STHook->wMonth = tmpTM.tm_mon + 1;
3903 STHook->wSecond = tmpTM.tm_sec;
3904 STHook->wYear = 1900+tmpTM.tm_year;
3906 TRACE(" returning time: %04d/%02d/%02d - %d - %02d:%02d:%02d.%02d\n",
3907 STHook->wYear, STHook->wMonth, STHook->wDay, STHook->wDayOfWeek,
3908 STHook->wHour, STHook->wMinute, STHook->wSecond, STHook->wMilliseconds);
3910 else if (lphttpHdr->lpszValue)
3912 DWORD len = (lstrlenW(lphttpHdr->lpszValue) + 1) * sizeof(WCHAR);
3914 if (len > *lpdwBufferLength)
3916 *lpdwBufferLength = len;
3917 LeaveCriticalSection( &request->headers_section );
3918 return ERROR_INSUFFICIENT_BUFFER;
3920 if (lpBuffer)
3922 memcpy(lpBuffer, lphttpHdr->lpszValue, len);
3923 TRACE("! returning string: %s\n", debugstr_w(lpBuffer));
3925 *lpdwBufferLength = len - sizeof(WCHAR);
3927 if (lpdwIndex) (*lpdwIndex)++;
3929 LeaveCriticalSection( &request->headers_section );
3930 return ERROR_SUCCESS;
3933 /***********************************************************************
3934 * HttpQueryInfoW (WININET.@)
3936 * Queries for information about an HTTP request
3938 * RETURNS
3939 * TRUE on success
3940 * FALSE on failure
3943 BOOL WINAPI HttpQueryInfoW(HINTERNET hHttpRequest, DWORD dwInfoLevel,
3944 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
3946 http_request_t *request;
3947 DWORD res;
3949 if (TRACE_ON(wininet)) {
3950 #define FE(x) { x, #x }
3951 static const wininet_flag_info query_flags[] = {
3952 FE(HTTP_QUERY_MIME_VERSION),
3953 FE(HTTP_QUERY_CONTENT_TYPE),
3954 FE(HTTP_QUERY_CONTENT_TRANSFER_ENCODING),
3955 FE(HTTP_QUERY_CONTENT_ID),
3956 FE(HTTP_QUERY_CONTENT_DESCRIPTION),
3957 FE(HTTP_QUERY_CONTENT_LENGTH),
3958 FE(HTTP_QUERY_CONTENT_LANGUAGE),
3959 FE(HTTP_QUERY_ALLOW),
3960 FE(HTTP_QUERY_PUBLIC),
3961 FE(HTTP_QUERY_DATE),
3962 FE(HTTP_QUERY_EXPIRES),
3963 FE(HTTP_QUERY_LAST_MODIFIED),
3964 FE(HTTP_QUERY_MESSAGE_ID),
3965 FE(HTTP_QUERY_URI),
3966 FE(HTTP_QUERY_DERIVED_FROM),
3967 FE(HTTP_QUERY_COST),
3968 FE(HTTP_QUERY_LINK),
3969 FE(HTTP_QUERY_PRAGMA),
3970 FE(HTTP_QUERY_VERSION),
3971 FE(HTTP_QUERY_STATUS_CODE),
3972 FE(HTTP_QUERY_STATUS_TEXT),
3973 FE(HTTP_QUERY_RAW_HEADERS),
3974 FE(HTTP_QUERY_RAW_HEADERS_CRLF),
3975 FE(HTTP_QUERY_CONNECTION),
3976 FE(HTTP_QUERY_ACCEPT),
3977 FE(HTTP_QUERY_ACCEPT_CHARSET),
3978 FE(HTTP_QUERY_ACCEPT_ENCODING),
3979 FE(HTTP_QUERY_ACCEPT_LANGUAGE),
3980 FE(HTTP_QUERY_AUTHORIZATION),
3981 FE(HTTP_QUERY_CONTENT_ENCODING),
3982 FE(HTTP_QUERY_FORWARDED),
3983 FE(HTTP_QUERY_FROM),
3984 FE(HTTP_QUERY_IF_MODIFIED_SINCE),
3985 FE(HTTP_QUERY_LOCATION),
3986 FE(HTTP_QUERY_ORIG_URI),
3987 FE(HTTP_QUERY_REFERER),
3988 FE(HTTP_QUERY_RETRY_AFTER),
3989 FE(HTTP_QUERY_SERVER),
3990 FE(HTTP_QUERY_TITLE),
3991 FE(HTTP_QUERY_USER_AGENT),
3992 FE(HTTP_QUERY_WWW_AUTHENTICATE),
3993 FE(HTTP_QUERY_PROXY_AUTHENTICATE),
3994 FE(HTTP_QUERY_ACCEPT_RANGES),
3995 FE(HTTP_QUERY_SET_COOKIE),
3996 FE(HTTP_QUERY_COOKIE),
3997 FE(HTTP_QUERY_REQUEST_METHOD),
3998 FE(HTTP_QUERY_REFRESH),
3999 FE(HTTP_QUERY_CONTENT_DISPOSITION),
4000 FE(HTTP_QUERY_AGE),
4001 FE(HTTP_QUERY_CACHE_CONTROL),
4002 FE(HTTP_QUERY_CONTENT_BASE),
4003 FE(HTTP_QUERY_CONTENT_LOCATION),
4004 FE(HTTP_QUERY_CONTENT_MD5),
4005 FE(HTTP_QUERY_CONTENT_RANGE),
4006 FE(HTTP_QUERY_ETAG),
4007 FE(HTTP_QUERY_HOST),
4008 FE(HTTP_QUERY_IF_MATCH),
4009 FE(HTTP_QUERY_IF_NONE_MATCH),
4010 FE(HTTP_QUERY_IF_RANGE),
4011 FE(HTTP_QUERY_IF_UNMODIFIED_SINCE),
4012 FE(HTTP_QUERY_MAX_FORWARDS),
4013 FE(HTTP_QUERY_PROXY_AUTHORIZATION),
4014 FE(HTTP_QUERY_RANGE),
4015 FE(HTTP_QUERY_TRANSFER_ENCODING),
4016 FE(HTTP_QUERY_UPGRADE),
4017 FE(HTTP_QUERY_VARY),
4018 FE(HTTP_QUERY_VIA),
4019 FE(HTTP_QUERY_WARNING),
4020 FE(HTTP_QUERY_CUSTOM)
4022 static const wininet_flag_info modifier_flags[] = {
4023 FE(HTTP_QUERY_FLAG_REQUEST_HEADERS),
4024 FE(HTTP_QUERY_FLAG_SYSTEMTIME),
4025 FE(HTTP_QUERY_FLAG_NUMBER),
4026 FE(HTTP_QUERY_FLAG_COALESCE)
4028 #undef FE
4029 DWORD info_mod = dwInfoLevel & HTTP_QUERY_MODIFIER_FLAGS_MASK;
4030 DWORD info = dwInfoLevel & HTTP_QUERY_HEADER_MASK;
4031 DWORD i;
4033 TRACE("(%p, 0x%08lx)--> %ld\n", hHttpRequest, dwInfoLevel, info);
4034 TRACE(" Attribute:");
4035 for (i = 0; i < ARRAY_SIZE(query_flags); i++) {
4036 if (query_flags[i].val == info) {
4037 TRACE(" %s", query_flags[i].name);
4038 break;
4041 if (i == ARRAY_SIZE(query_flags)) {
4042 TRACE(" Unknown (%08lx)", info);
4045 TRACE(" Modifier:");
4046 for (i = 0; i < ARRAY_SIZE(modifier_flags); i++) {
4047 if (modifier_flags[i].val & info_mod) {
4048 TRACE(" %s", modifier_flags[i].name);
4049 info_mod &= ~ modifier_flags[i].val;
4053 if (info_mod) {
4054 TRACE(" Unknown (%08lx)", info_mod);
4056 TRACE("\n");
4059 request = (http_request_t*) get_handle_object( hHttpRequest );
4060 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
4062 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
4063 goto lend;
4066 if (lpBuffer == NULL)
4067 *lpdwBufferLength = 0;
4068 res = HTTP_HttpQueryInfoW( request, dwInfoLevel,
4069 lpBuffer, lpdwBufferLength, lpdwIndex);
4071 lend:
4072 if( request )
4073 WININET_Release( &request->hdr );
4075 TRACE("%lu <--\n", res);
4077 SetLastError(res);
4078 return res == ERROR_SUCCESS;
4081 /***********************************************************************
4082 * HttpQueryInfoA (WININET.@)
4084 * Queries for information about an HTTP request
4086 * RETURNS
4087 * TRUE on success
4088 * FALSE on failure
4091 BOOL WINAPI HttpQueryInfoA(HINTERNET hHttpRequest, DWORD dwInfoLevel,
4092 LPVOID lpBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex)
4094 BOOL result;
4095 DWORD len;
4096 WCHAR* bufferW;
4098 TRACE("%p %lx\n", hHttpRequest, dwInfoLevel);
4100 if((dwInfoLevel & HTTP_QUERY_FLAG_NUMBER) ||
4101 (dwInfoLevel & HTTP_QUERY_FLAG_SYSTEMTIME))
4103 return HttpQueryInfoW( hHttpRequest, dwInfoLevel, lpBuffer,
4104 lpdwBufferLength, lpdwIndex );
4107 if (lpBuffer)
4109 DWORD alloclen;
4110 len = (*lpdwBufferLength)*sizeof(WCHAR);
4111 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
4113 alloclen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, NULL, 0 ) * sizeof(WCHAR);
4114 if (alloclen < len)
4115 alloclen = len;
4117 else
4118 alloclen = len;
4119 bufferW = malloc( alloclen );
4120 /* buffer is in/out because of HTTP_QUERY_CUSTOM */
4121 if ((dwInfoLevel & HTTP_QUERY_HEADER_MASK) == HTTP_QUERY_CUSTOM)
4122 MultiByteToWideChar( CP_ACP, 0, lpBuffer, -1, bufferW, alloclen / sizeof(WCHAR) );
4123 } else
4125 bufferW = NULL;
4126 len = 0;
4129 result = HttpQueryInfoW( hHttpRequest, dwInfoLevel, bufferW,
4130 &len, lpdwIndex );
4131 if( result )
4133 len = WideCharToMultiByte( CP_ACP,0, bufferW, len / sizeof(WCHAR) + 1,
4134 lpBuffer, *lpdwBufferLength, NULL, NULL );
4135 *lpdwBufferLength = len - 1;
4137 TRACE("lpBuffer: %s\n", debugstr_a(lpBuffer));
4139 else
4140 /* since the strings being returned from HttpQueryInfoW should be
4141 * only ASCII characters, it is reasonable to assume that all of
4142 * the Unicode characters can be reduced to a single byte */
4143 *lpdwBufferLength = len / sizeof(WCHAR);
4145 free( bufferW );
4146 return result;
4149 static WCHAR *get_redirect_url(http_request_t *request)
4151 static WCHAR szHttp[] = L"http";
4152 static WCHAR szHttps[] = L"https";
4153 http_session_t *session = request->session;
4154 URL_COMPONENTSW urlComponents = { sizeof(urlComponents) };
4155 WCHAR *orig_url = NULL, *redirect_url = NULL, *combined_url = NULL;
4156 DWORD url_length = 0, res;
4157 BOOL b;
4159 url_length = 0;
4160 res = HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, redirect_url, &url_length, NULL);
4161 if(res == ERROR_INSUFFICIENT_BUFFER) {
4162 redirect_url = malloc(url_length);
4163 res = HTTP_HttpQueryInfoW(request, HTTP_QUERY_LOCATION, redirect_url, &url_length, NULL);
4165 if(res != ERROR_SUCCESS) {
4166 free(redirect_url);
4167 return NULL;
4170 urlComponents.dwSchemeLength = 1;
4171 b = InternetCrackUrlW(redirect_url, url_length / sizeof(WCHAR), 0, &urlComponents);
4172 if(b && urlComponents.dwSchemeLength &&
4173 urlComponents.nScheme != INTERNET_SCHEME_HTTP && urlComponents.nScheme != INTERNET_SCHEME_HTTPS) {
4174 TRACE("redirect to non-http URL\n");
4175 return NULL;
4178 urlComponents.lpszScheme = (request->hdr.dwFlags & INTERNET_FLAG_SECURE) ? szHttps : szHttp;
4179 urlComponents.dwSchemeLength = 0;
4180 urlComponents.lpszHostName = request->server->name;
4181 urlComponents.nPort = request->server->port;
4182 urlComponents.lpszUserName = session->userName;
4183 urlComponents.lpszUrlPath = request->path;
4185 b = InternetCreateUrlW(&urlComponents, 0, NULL, &url_length);
4186 if(!b && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
4187 orig_url = malloc(url_length);
4189 /* convert from bytes to characters */
4190 url_length = url_length / sizeof(WCHAR) - 1;
4191 b = InternetCreateUrlW(&urlComponents, 0, orig_url, &url_length);
4194 if(b) {
4195 url_length = 0;
4196 b = InternetCombineUrlW(orig_url, redirect_url, NULL, &url_length, ICU_ENCODE_SPACES_ONLY);
4197 if(!b && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
4198 combined_url = malloc(url_length * sizeof(WCHAR));
4199 b = InternetCombineUrlW(orig_url, redirect_url, combined_url, &url_length, ICU_ENCODE_SPACES_ONLY);
4200 if(!b) {
4201 free(combined_url);
4202 combined_url = NULL;
4207 free(orig_url);
4208 free(redirect_url);
4209 return combined_url;
4213 /***********************************************************************
4214 * HTTP_HandleRedirect (internal)
4216 static DWORD HTTP_HandleRedirect(http_request_t *request, WCHAR *url)
4218 URL_COMPONENTSW urlComponents = { sizeof(urlComponents) };
4219 http_session_t *session = request->session;
4220 size_t url_len = lstrlenW(url);
4222 if(url[0] == '/')
4224 /* if it's an absolute path, keep the same session info */
4225 urlComponents.lpszUrlPath = url;
4226 urlComponents.dwUrlPathLength = url_len;
4228 else
4230 urlComponents.dwHostNameLength = 1;
4231 urlComponents.dwUserNameLength = 1;
4232 urlComponents.dwUrlPathLength = 1;
4233 if(!InternetCrackUrlW(url, url_len, 0, &urlComponents))
4234 return INTERNET_GetLastError();
4236 if(!urlComponents.dwHostNameLength)
4237 return ERROR_INTERNET_INVALID_URL;
4240 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext, INTERNET_STATUS_REDIRECT,
4241 url, (url_len + 1) * sizeof(WCHAR));
4243 if(urlComponents.dwHostNameLength) {
4244 BOOL custom_port = FALSE;
4245 substr_t host;
4247 if(urlComponents.nScheme == INTERNET_SCHEME_HTTP) {
4248 if(request->hdr.dwFlags & INTERNET_FLAG_SECURE) {
4249 TRACE("redirect from secure page to non-secure page\n");
4250 /* FIXME: warn about from secure redirect to non-secure page */
4251 request->hdr.dwFlags &= ~INTERNET_FLAG_SECURE;
4254 custom_port = urlComponents.nPort != INTERNET_DEFAULT_HTTP_PORT;
4255 }else if(urlComponents.nScheme == INTERNET_SCHEME_HTTPS) {
4256 if(!(request->hdr.dwFlags & INTERNET_FLAG_SECURE)) {
4257 TRACE("redirect from non-secure page to secure page\n");
4258 /* FIXME: notify about redirect to secure page */
4259 request->hdr.dwFlags |= INTERNET_FLAG_SECURE;
4262 custom_port = urlComponents.nPort != INTERNET_DEFAULT_HTTPS_PORT;
4265 free(session->hostName);
4267 session->hostName = strndupW(urlComponents.lpszHostName, urlComponents.dwHostNameLength);
4268 session->hostPort = urlComponents.nPort;
4270 free(session->userName);
4271 session->userName = NULL;
4272 if (urlComponents.dwUserNameLength)
4273 session->userName = strndupW(urlComponents.lpszUserName, urlComponents.dwUserNameLength);
4275 reset_data_stream(request);
4277 host = substr(urlComponents.lpszHostName, urlComponents.dwHostNameLength);
4279 if(host.len != lstrlenW(request->server->name) || wcsnicmp(request->server->name, host.str, host.len)
4280 || request->server->port != urlComponents.nPort) {
4281 server_t *new_server;
4283 new_server = get_server(host, urlComponents.nPort, urlComponents.nScheme == INTERNET_SCHEME_HTTPS, TRUE);
4284 server_release(request->server);
4285 request->server = new_server;
4288 if (custom_port)
4289 HTTP_ProcessHeader(request, L"Host", request->server->host_port,
4290 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4291 else
4292 HTTP_ProcessHeader(request, L"Host", request->server->name,
4293 HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDHDR_FLAG_REQ);
4296 free(request->path);
4297 request->path = NULL;
4298 if(urlComponents.dwUrlPathLength)
4300 DWORD needed = 1;
4301 HRESULT rc;
4302 WCHAR dummy[] = L"";
4303 WCHAR *path;
4305 path = strndupW(urlComponents.lpszUrlPath, urlComponents.dwUrlPathLength);
4306 rc = UrlEscapeW(path, dummy, &needed, URL_ESCAPE_SPACES_ONLY);
4307 if (rc != E_POINTER)
4308 ERR("Unable to escape string!(%s) (%ld)\n",debugstr_w(path),rc);
4309 request->path = malloc(needed * sizeof(WCHAR));
4310 rc = UrlEscapeW(path, request->path, &needed,
4311 URL_ESCAPE_SPACES_ONLY);
4312 if (rc != S_OK)
4314 ERR("Unable to escape string!(%s) (%ld)\n",debugstr_w(path),rc);
4315 lstrcpyW(request->path, path);
4317 free(path);
4320 /* Remove custom content-type/length headers on redirects. */
4321 remove_header(request, L"Content-Type", TRUE);
4322 remove_header(request, L"Content-Length", TRUE);
4324 return ERROR_SUCCESS;
4327 /***********************************************************************
4328 * HTTP_build_req (internal)
4330 * concatenate all the strings in the request together
4332 static LPWSTR HTTP_build_req( LPCWSTR *list, int len )
4334 LPCWSTR *t;
4335 LPWSTR str;
4337 for( t = list; *t ; t++ )
4338 len += lstrlenW( *t );
4339 len++;
4341 str = malloc(len * sizeof(WCHAR));
4342 *str = 0;
4344 for( t = list; *t ; t++ )
4345 lstrcatW( str, *t );
4347 return str;
4350 static void HTTP_InsertCookies(http_request_t *request)
4352 WCHAR *cookies;
4353 DWORD res;
4355 res = get_cookie_header(request->server->name, request->path, &cookies);
4356 if(res != ERROR_SUCCESS || !cookies)
4357 return;
4359 HTTP_HttpAddRequestHeadersW(request, cookies, lstrlenW(cookies),
4360 HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
4361 free(cookies);
4364 static WORD HTTP_ParseWkday(LPCWSTR day)
4366 static const WCHAR days[7][4] = {L"sun",
4367 L"mon",
4368 L"tue",
4369 L"wed",
4370 L"thu",
4371 L"fri",
4372 L"sat"};
4373 unsigned int i;
4374 for (i = 0; i < ARRAY_SIZE(days); i++)
4375 if (!wcsicmp(day, days[i]))
4376 return i;
4378 /* Invalid */
4379 return 7;
4382 static WORD HTTP_ParseMonth(LPCWSTR month)
4384 if (!wcsicmp(month, L"jan")) return 1;
4385 if (!wcsicmp(month, L"feb")) return 2;
4386 if (!wcsicmp(month, L"mar")) return 3;
4387 if (!wcsicmp(month, L"apr")) return 4;
4388 if (!wcsicmp(month, L"may")) return 5;
4389 if (!wcsicmp(month, L"jun")) return 6;
4390 if (!wcsicmp(month, L"jul")) return 7;
4391 if (!wcsicmp(month, L"aug")) return 8;
4392 if (!wcsicmp(month, L"sep")) return 9;
4393 if (!wcsicmp(month, L"oct")) return 10;
4394 if (!wcsicmp(month, L"nov")) return 11;
4395 if (!wcsicmp(month, L"dec")) return 12;
4396 /* Invalid */
4397 return 0;
4400 /* Parses the string pointed to by *str, assumed to be a 24-hour time HH:MM:SS,
4401 * optionally preceded by whitespace.
4402 * Upon success, returns TRUE, sets the wHour, wMinute, and wSecond fields of
4403 * st, and sets *str to the first character after the time format.
4405 static BOOL HTTP_ParseTime(SYSTEMTIME *st, LPCWSTR *str)
4407 LPCWSTR ptr = *str;
4408 WCHAR *nextPtr;
4409 unsigned long num;
4411 while (iswspace(*ptr))
4412 ptr++;
4414 num = wcstoul(ptr, &nextPtr, 10);
4415 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4417 ERR("unexpected time format %s\n", debugstr_w(ptr));
4418 return FALSE;
4420 if (num > 23)
4422 ERR("unexpected hour in time format %s\n", debugstr_w(ptr));
4423 return FALSE;
4425 ptr = nextPtr + 1;
4426 st->wHour = (WORD)num;
4427 num = wcstoul(ptr, &nextPtr, 10);
4428 if (!nextPtr || nextPtr <= ptr || *nextPtr != ':')
4430 ERR("unexpected time format %s\n", debugstr_w(ptr));
4431 return FALSE;
4433 if (num > 59)
4435 ERR("unexpected minute in time format %s\n", debugstr_w(ptr));
4436 return FALSE;
4438 ptr = nextPtr + 1;
4439 st->wMinute = (WORD)num;
4440 num = wcstoul(ptr, &nextPtr, 10);
4441 if (!nextPtr || nextPtr <= ptr)
4443 ERR("unexpected time format %s\n", debugstr_w(ptr));
4444 return FALSE;
4446 if (num > 59)
4448 ERR("unexpected second in time format %s\n", debugstr_w(ptr));
4449 return FALSE;
4451 *str = nextPtr;
4452 st->wSecond = (WORD)num;
4453 return TRUE;
4456 static BOOL HTTP_ParseDateAsAsctime(LPCWSTR value, FILETIME *ft)
4458 WCHAR day[4], *dayPtr, month[4], *monthPtr, *nextPtr;
4459 LPCWSTR ptr;
4460 SYSTEMTIME st = { 0 };
4461 unsigned long num;
4463 for (ptr = value, dayPtr = day; *ptr && !iswspace(*ptr) &&
4464 dayPtr - day < ARRAY_SIZE(day) - 1; ptr++, dayPtr++)
4465 *dayPtr = *ptr;
4466 *dayPtr = 0;
4467 st.wDayOfWeek = HTTP_ParseWkday(day);
4468 if (st.wDayOfWeek >= 7)
4470 ERR("unexpected weekday %s\n", debugstr_w(day));
4471 return FALSE;
4474 while (iswspace(*ptr))
4475 ptr++;
4477 for (monthPtr = month; !iswspace(*ptr) && monthPtr - month < ARRAY_SIZE(month) - 1;
4478 monthPtr++, ptr++)
4479 *monthPtr = *ptr;
4480 *monthPtr = 0;
4481 st.wMonth = HTTP_ParseMonth(month);
4482 if (!st.wMonth || st.wMonth > 12)
4484 ERR("unexpected month %s\n", debugstr_w(month));
4485 return FALSE;
4488 while (iswspace(*ptr))
4489 ptr++;
4491 num = wcstoul(ptr, &nextPtr, 10);
4492 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4494 ERR("unexpected day %s\n", debugstr_w(ptr));
4495 return FALSE;
4497 ptr = nextPtr;
4498 st.wDay = (WORD)num;
4500 while (iswspace(*ptr))
4501 ptr++;
4503 if (!HTTP_ParseTime(&st, &ptr))
4504 return FALSE;
4506 while (iswspace(*ptr))
4507 ptr++;
4509 num = wcstoul(ptr, &nextPtr, 10);
4510 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4512 ERR("unexpected year %s\n", debugstr_w(ptr));
4513 return FALSE;
4515 ptr = nextPtr;
4516 st.wYear = (WORD)num;
4518 while (iswspace(*ptr))
4519 ptr++;
4521 /* asctime() doesn't report a timezone, but some web servers do, so accept
4522 * with or without GMT.
4524 if (*ptr && wcscmp(ptr, L"GMT"))
4526 ERR("unexpected timezone %s\n", debugstr_w(ptr));
4527 return FALSE;
4529 return SystemTimeToFileTime(&st, ft);
4532 static BOOL HTTP_ParseRfc1123Date(LPCWSTR value, FILETIME *ft)
4534 WCHAR *nextPtr, day[4], month[4], *monthPtr;
4535 LPCWSTR ptr;
4536 unsigned long num;
4537 SYSTEMTIME st = { 0 };
4539 ptr = wcschr(value, ',');
4540 if (!ptr)
4541 return FALSE;
4542 if (ptr - value != 3)
4544 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4545 return FALSE;
4547 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4548 day[3] = 0;
4549 st.wDayOfWeek = HTTP_ParseWkday(day);
4550 if (st.wDayOfWeek > 6)
4552 WARN("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4553 return FALSE;
4555 ptr++;
4557 while (iswspace(*ptr))
4558 ptr++;
4560 num = wcstoul(ptr, &nextPtr, 10);
4561 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4563 WARN("unexpected day %s\n", debugstr_w(value));
4564 return FALSE;
4566 ptr = nextPtr;
4567 st.wDay = (WORD)num;
4569 while (iswspace(*ptr))
4570 ptr++;
4572 for (monthPtr = month; !iswspace(*ptr) && monthPtr - month < ARRAY_SIZE(month) - 1;
4573 monthPtr++, ptr++)
4574 *monthPtr = *ptr;
4575 *monthPtr = 0;
4576 st.wMonth = HTTP_ParseMonth(month);
4577 if (!st.wMonth || st.wMonth > 12)
4579 WARN("unexpected month %s\n", debugstr_w(month));
4580 return FALSE;
4583 while (iswspace(*ptr))
4584 ptr++;
4586 num = wcstoul(ptr, &nextPtr, 10);
4587 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4589 ERR("unexpected year %s\n", debugstr_w(value));
4590 return FALSE;
4592 ptr = nextPtr;
4593 st.wYear = (WORD)num;
4595 if (!HTTP_ParseTime(&st, &ptr))
4596 return FALSE;
4598 while (iswspace(*ptr))
4599 ptr++;
4601 if (wcscmp(ptr, L"GMT"))
4603 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4604 return FALSE;
4606 return SystemTimeToFileTime(&st, ft);
4609 static WORD HTTP_ParseWeekday(LPCWSTR day)
4611 static const WCHAR days[7][10] = {L"sunday",
4612 L"monday",
4613 L"tuesday",
4614 L"wednesday",
4615 L"thursday",
4616 L"friday",
4617 L"saturday"};
4618 unsigned int i;
4619 for (i = 0; i < ARRAY_SIZE(days); i++)
4620 if (!wcsicmp(day, days[i]))
4621 return i;
4623 /* Invalid */
4624 return 7;
4627 static BOOL HTTP_ParseRfc850Date(LPCWSTR value, FILETIME *ft)
4629 WCHAR *nextPtr, day[10], month[4], *monthPtr;
4630 LPCWSTR ptr;
4631 unsigned long num;
4632 SYSTEMTIME st = { 0 };
4634 ptr = wcschr(value, ',');
4635 if (!ptr)
4636 return FALSE;
4637 if (ptr - value == 3)
4639 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4640 day[3] = 0;
4641 st.wDayOfWeek = HTTP_ParseWkday(day);
4642 if (st.wDayOfWeek > 6)
4644 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4645 return FALSE;
4648 else if (ptr - value < ARRAY_SIZE(day))
4650 memcpy(day, value, (ptr - value) * sizeof(WCHAR));
4651 day[ptr - value + 1] = 0;
4652 st.wDayOfWeek = HTTP_ParseWeekday(day);
4653 if (st.wDayOfWeek > 6)
4655 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4656 return FALSE;
4659 else
4661 ERR("unexpected weekday %s\n", debugstr_wn(value, ptr - value));
4662 return FALSE;
4664 ptr++;
4666 while (iswspace(*ptr))
4667 ptr++;
4669 num = wcstoul(ptr, &nextPtr, 10);
4670 if (!nextPtr || nextPtr <= ptr || !num || num > 31)
4672 ERR("unexpected day %s\n", debugstr_w(value));
4673 return FALSE;
4675 ptr = nextPtr;
4676 st.wDay = (WORD)num;
4678 if (*ptr != '-')
4680 ERR("unexpected month format %s\n", debugstr_w(ptr));
4681 return FALSE;
4683 ptr++;
4685 for (monthPtr = month; *ptr != '-' && monthPtr - month < ARRAY_SIZE(month) - 1;
4686 monthPtr++, ptr++)
4687 *monthPtr = *ptr;
4688 *monthPtr = 0;
4689 st.wMonth = HTTP_ParseMonth(month);
4690 if (!st.wMonth || st.wMonth > 12)
4692 ERR("unexpected month %s\n", debugstr_w(month));
4693 return FALSE;
4696 if (*ptr != '-')
4698 ERR("unexpected year format %s\n", debugstr_w(ptr));
4699 return FALSE;
4701 ptr++;
4703 num = wcstoul(ptr, &nextPtr, 10);
4704 if (!nextPtr || nextPtr <= ptr || num < 1601 || num > 30827)
4706 ERR("unexpected year %s\n", debugstr_w(value));
4707 return FALSE;
4709 ptr = nextPtr;
4710 st.wYear = (WORD)num;
4712 if (!HTTP_ParseTime(&st, &ptr))
4713 return FALSE;
4715 while (iswspace(*ptr))
4716 ptr++;
4718 if (wcscmp(ptr, L"GMT"))
4720 ERR("unexpected time zone %s\n", debugstr_w(ptr));
4721 return FALSE;
4723 return SystemTimeToFileTime(&st, ft);
4726 static BOOL HTTP_ParseDate(LPCWSTR value, FILETIME *ft)
4728 BOOL ret;
4730 if (!wcscmp(value, L"0"))
4732 ft->dwLowDateTime = ft->dwHighDateTime = 0;
4733 ret = TRUE;
4735 else if (wcschr(value, ','))
4737 ret = HTTP_ParseRfc1123Date(value, ft);
4738 if (!ret)
4740 ret = HTTP_ParseRfc850Date(value, ft);
4741 if (!ret)
4742 ERR("unexpected date format %s\n", debugstr_w(value));
4745 else
4747 ret = HTTP_ParseDateAsAsctime(value, ft);
4748 if (!ret)
4749 ERR("unexpected date format %s\n", debugstr_w(value));
4751 return ret;
4754 static void HTTP_ProcessExpires(http_request_t *request)
4756 BOOL expirationFound = FALSE;
4757 int headerIndex;
4759 EnterCriticalSection( &request->headers_section );
4761 /* Look for a Cache-Control header with a max-age directive, as it takes
4762 * precedence over the Expires header.
4764 headerIndex = HTTP_GetCustomHeaderIndex(request, L"Cache-Control", 0, FALSE);
4765 if (headerIndex != -1)
4767 LPHTTPHEADERW ccHeader = &request->custHeaders[headerIndex];
4768 LPWSTR ptr;
4770 for (ptr = ccHeader->lpszValue; ptr && *ptr; )
4772 LPWSTR comma = wcschr(ptr, ','), end, equal;
4774 if (comma)
4775 end = comma;
4776 else
4777 end = ptr + lstrlenW(ptr);
4778 for (equal = end - 1; equal > ptr && *equal != '='; equal--)
4780 if (*equal == '=')
4782 if (!wcsnicmp(ptr, L"max-age", equal - ptr - 1))
4784 LPWSTR nextPtr;
4785 unsigned long age;
4787 age = wcstoul(equal + 1, &nextPtr, 10);
4788 if (nextPtr > equal + 1)
4790 LARGE_INTEGER ft;
4792 NtQuerySystemTime( &ft );
4793 /* Age is in seconds, FILETIME resolution is in
4794 * 100 nanosecond intervals.
4796 ft.QuadPart += age * (ULONGLONG)1000000;
4797 request->expires.dwLowDateTime = ft.u.LowPart;
4798 request->expires.dwHighDateTime = ft.u.HighPart;
4799 expirationFound = TRUE;
4803 if (comma)
4805 ptr = comma + 1;
4806 while (iswspace(*ptr))
4807 ptr++;
4809 else
4810 ptr = NULL;
4813 if (!expirationFound)
4815 headerIndex = HTTP_GetCustomHeaderIndex(request, L"Expires", 0, FALSE);
4816 if (headerIndex != -1)
4818 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4819 FILETIME ft;
4821 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4823 expirationFound = TRUE;
4824 request->expires = ft;
4828 if (!expirationFound)
4830 LARGE_INTEGER t;
4832 /* With no known age, default to 10 minutes until expiration. */
4833 NtQuerySystemTime( &t );
4834 t.QuadPart += 10 * 60 * (ULONGLONG)10000000;
4835 request->expires.dwLowDateTime = t.u.LowPart;
4836 request->expires.dwHighDateTime = t.u.HighPart;
4839 LeaveCriticalSection( &request->headers_section );
4842 static void HTTP_ProcessLastModified(http_request_t *request)
4844 int headerIndex;
4846 EnterCriticalSection( &request->headers_section );
4848 headerIndex = HTTP_GetCustomHeaderIndex(request, L"Last-Modified", 0, FALSE);
4849 if (headerIndex != -1)
4851 LPHTTPHEADERW expiresHeader = &request->custHeaders[headerIndex];
4852 FILETIME ft;
4854 if (HTTP_ParseDate(expiresHeader->lpszValue, &ft))
4855 request->last_modified = ft;
4858 LeaveCriticalSection( &request->headers_section );
4861 static void http_process_keep_alive(http_request_t *req)
4863 int index;
4865 EnterCriticalSection( &req->headers_section );
4867 if ((index = HTTP_GetCustomHeaderIndex(req, L"Connection", 0, FALSE)) != -1)
4868 req->netconn->keep_alive = !wcsicmp(req->custHeaders[index].lpszValue, L"Keep-Alive");
4869 else if ((index = HTTP_GetCustomHeaderIndex(req, L"Proxy-Connection", 0, FALSE)) != -1)
4870 req->netconn->keep_alive = !wcsicmp(req->custHeaders[index].lpszValue, L"Keep-Alive");
4871 else
4872 req->netconn->keep_alive = !wcsicmp(req->version, L"HTTP/1.1");
4874 LeaveCriticalSection( &req->headers_section );
4877 static DWORD open_http_connection(http_request_t *request, BOOL *reusing)
4879 netconn_t *netconn = NULL;
4880 DWORD res;
4882 if (request->netconn)
4884 if (NETCON_is_alive(request->netconn) && drain_content(request, TRUE) == ERROR_SUCCESS)
4886 reset_data_stream(request);
4887 *reusing = TRUE;
4888 return ERROR_SUCCESS;
4891 TRACE("freeing netconn\n");
4892 free_netconn(request->netconn);
4893 request->netconn = NULL;
4896 reset_data_stream(request);
4898 res = HTTP_ResolveName(request);
4899 if(res != ERROR_SUCCESS)
4900 return res;
4902 EnterCriticalSection(&connection_pool_cs);
4904 while(!list_empty(&request->server->conn_pool)) {
4905 netconn = LIST_ENTRY(list_head(&request->server->conn_pool), netconn_t, pool_entry);
4906 list_remove(&netconn->pool_entry);
4908 if(is_valid_netconn(netconn) && NETCON_is_alive(netconn))
4909 break;
4911 TRACE("connection %p closed during idle\n", netconn);
4912 free_netconn(netconn);
4913 netconn = NULL;
4916 LeaveCriticalSection(&connection_pool_cs);
4918 if(netconn) {
4919 TRACE("<-- reusing %p netconn\n", netconn);
4920 request->netconn = netconn;
4921 *reusing = TRUE;
4922 return ERROR_SUCCESS;
4925 TRACE("connecting to %s, proxy %s\n", debugstr_w(request->server->name),
4926 request->proxy ? debugstr_w(request->proxy->name) : "(null)");
4928 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4929 INTERNET_STATUS_CONNECTING_TO_SERVER,
4930 request->server->addr_str,
4931 strlen(request->server->addr_str)+1);
4933 res = create_netconn(request->proxy ? request->proxy : request->server, request->security_flags,
4934 (request->hdr.ErrorMask & INTERNET_ERROR_MASK_COMBINED_SEC_CERT) != 0,
4935 request->hdr.connect_timeout, &netconn);
4936 if(res != ERROR_SUCCESS) {
4937 ERR("create_netconn failed: %lu\n", res);
4938 return res;
4941 request->netconn = netconn;
4943 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
4944 INTERNET_STATUS_CONNECTED_TO_SERVER,
4945 request->server->addr_str, strlen(request->server->addr_str)+1);
4947 *reusing = FALSE;
4948 TRACE("Created connection to %s: %p\n", debugstr_w(request->server->name), netconn);
4949 return ERROR_SUCCESS;
4952 static char *build_ascii_request( const WCHAR *str, void *data, DWORD data_len, DWORD *out_len )
4954 int len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL );
4955 char *ret;
4957 if (!(ret = malloc( len + data_len ))) return NULL;
4958 WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
4959 if (data_len) memcpy( ret + len - 1, data, data_len );
4960 *out_len = len + data_len - 1;
4961 ret[*out_len] = 0;
4962 return ret;
4965 static void set_content_length_header( http_request_t *request, DWORD len, DWORD flags )
4967 WCHAR buf[ARRAY_SIZE(L"Content-Length: %u\r\n") + 10];
4969 swprintf( buf, ARRAY_SIZE(buf), L"Content-Length: %u\r\n", len );
4970 HTTP_HttpAddRequestHeadersW( request, buf, ~0u, flags );
4973 /***********************************************************************
4974 * HTTP_HttpSendRequestW (internal)
4976 * Sends the specified request to the HTTP server
4978 * RETURNS
4979 * ERROR_SUCCESS on success
4980 * win32 error code on failure
4983 static DWORD HTTP_HttpSendRequestW(http_request_t *request, LPCWSTR lpszHeaders,
4984 DWORD dwHeaderLength, LPVOID lpOptional, DWORD dwOptionalLength,
4985 DWORD dwContentLength, BOOL bEndRequest)
4987 BOOL redirected = FALSE, secure_proxy_connect = FALSE, loop_next;
4988 WCHAR *request_header = NULL;
4989 INT responseLen, cnt;
4990 DWORD res;
4992 TRACE("--> %p\n", request);
4994 assert(request->hdr.htype == WH_HHTTPREQ);
4996 /* if the verb is NULL default to GET */
4997 if (!request->verb)
4998 request->verb = wcsdup(L"GET");
5000 HTTP_ProcessHeader(request, L"Host", request->server->canon_host_port,
5001 HTTP_ADDREQ_FLAG_ADD_IF_NEW | HTTP_ADDHDR_FLAG_REQ);
5003 if (dwContentLength || wcscmp(request->verb, L"GET"))
5005 set_content_length_header(request, dwContentLength, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
5006 request->bytesToWrite = dwContentLength;
5008 if (request->session->appInfo->agent)
5010 WCHAR *agent_header;
5011 int len;
5013 len = lstrlenW(request->session->appInfo->agent) + lstrlenW(L"User-Agent: %s\r\n");
5014 agent_header = malloc(len * sizeof(WCHAR));
5015 swprintf(agent_header, len, L"User-Agent: %s\r\n", request->session->appInfo->agent);
5017 HTTP_HttpAddRequestHeadersW(request, agent_header, lstrlenW(agent_header), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
5018 free(agent_header);
5020 if (request->hdr.dwFlags & INTERNET_FLAG_PRAGMA_NOCACHE)
5022 HTTP_HttpAddRequestHeadersW(request, L"Pragma: no-cache\r\n",
5023 lstrlenW(L"Pragma: no-cache\r\n"), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
5025 if ((request->hdr.dwFlags & INTERNET_FLAG_NO_CACHE_WRITE) && wcscmp(request->verb, L"GET"))
5027 HTTP_HttpAddRequestHeadersW(request, L"Cache-Control: no-cache\r\n",
5028 lstrlenW(L"Cache-Control: no-cache\r\n"), HTTP_ADDREQ_FLAG_ADD_IF_NEW);
5031 /* add the headers the caller supplied */
5032 if (lpszHeaders)
5034 if (dwHeaderLength == 0)
5035 dwHeaderLength = lstrlenW(lpszHeaders);
5037 HTTP_HttpAddRequestHeadersW(request, lpszHeaders, dwHeaderLength, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE);
5042 DWORD len, data_len = dwOptionalLength;
5043 BOOL reusing_connection;
5044 char *ascii_req;
5046 loop_next = FALSE;
5048 if(redirected) {
5049 request->contentLength = ~0;
5050 request->bytesToWrite = 0;
5053 if (TRACE_ON(wininet))
5055 HTTPHEADERW *host;
5057 EnterCriticalSection( &request->headers_section );
5058 host = HTTP_GetHeader(request, L"Host");
5059 TRACE("Going to url %s %s\n", debugstr_w(host->lpszValue), debugstr_w(request->path));
5060 LeaveCriticalSection( &request->headers_section );
5063 HTTP_FixURL(request);
5064 if (request->hdr.dwFlags & INTERNET_FLAG_KEEP_CONNECTION)
5066 HTTP_ProcessHeader(request, L"Connection", L"Keep-Alive",
5067 HTTP_ADDHDR_FLAG_REQ | HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
5069 HTTP_InsertAuthorization(request, request->authInfo, L"Authorization");
5070 HTTP_InsertAuthorization(request, request->proxyAuthInfo, L"Proxy-Authorization");
5072 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_COOKIES))
5073 HTTP_InsertCookies(request);
5075 res = open_http_connection(request, &reusing_connection);
5076 if (res != ERROR_SUCCESS)
5077 break;
5079 if (!reusing_connection && (request->hdr.dwFlags & INTERNET_FLAG_SECURE))
5081 if (request->proxy) secure_proxy_connect = TRUE;
5082 else
5084 res = NETCON_secure_connect(request->netconn, request->server);
5085 if (res != ERROR_SUCCESS)
5087 WARN("failed to upgrade to secure connection\n");
5088 http_release_netconn(request, FALSE);
5089 break;
5093 if (secure_proxy_connect)
5095 const WCHAR *target = request->server->host_port;
5097 if (HTTP_GetCustomHeaderIndex(request, L"Content-Length", 0, TRUE) >= 0)
5098 set_content_length_header(request, 0, HTTP_ADDREQ_FLAG_REPLACE);
5100 request_header = build_request_header(request, L"CONNECT", target, L"HTTP/1.1", TRUE);
5102 else if (request->proxy && !(request->hdr.dwFlags & INTERNET_FLAG_SECURE))
5104 WCHAR *url = build_proxy_path_url(request);
5105 request_header = build_request_header(request, request->verb, url, request->version, TRUE);
5106 free(url);
5108 else
5110 if (request->proxy && HTTP_GetCustomHeaderIndex(request, L"Content-Length", 0, TRUE) >= 0)
5111 set_content_length_header(request, dwContentLength, HTTP_ADDREQ_FLAG_REPLACE);
5113 request_header = build_request_header(request, request->verb, request->path, request->version, TRUE);
5116 TRACE("Request header -> %s\n", debugstr_w(request_header) );
5118 /* send the request as ASCII, tack on the optional data */
5119 if (!lpOptional || redirected || secure_proxy_connect)
5120 data_len = 0;
5122 ascii_req = build_ascii_request(request_header, lpOptional, data_len, &len);
5123 free(request_header);
5124 TRACE("full request -> %s\n", debugstr_a(ascii_req) );
5126 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5127 INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
5129 NETCON_set_timeout( request->netconn, TRUE, request->hdr.send_timeout );
5130 res = NETCON_send(request->netconn, ascii_req, len, 0, &cnt);
5131 free(ascii_req);
5132 if(res != ERROR_SUCCESS) {
5133 TRACE("send failed: %lu\n", res);
5134 if(!reusing_connection)
5135 break;
5136 http_release_netconn(request, FALSE);
5137 loop_next = TRUE;
5138 continue;
5141 request->bytesWritten = data_len;
5143 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5144 INTERNET_STATUS_REQUEST_SENT,
5145 &len, sizeof(DWORD));
5147 if (bEndRequest)
5149 DWORD dwBufferSize;
5151 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5152 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5154 if (HTTP_GetResponseHeaders(request, &responseLen))
5156 http_release_netconn(request, FALSE);
5157 res = ERROR_INTERNET_CONNECTION_ABORTED;
5158 goto lend;
5160 /* FIXME: We should know that connection is closed before sending
5161 * headers. Otherwise wrong callbacks are executed */
5162 if(!responseLen && reusing_connection) {
5163 TRACE("Connection closed by server, reconnecting\n");
5164 http_release_netconn(request, FALSE);
5165 loop_next = TRUE;
5166 continue;
5169 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5170 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen,
5171 sizeof(DWORD));
5173 http_process_keep_alive(request);
5174 HTTP_ProcessCookies(request);
5175 HTTP_ProcessExpires(request);
5176 HTTP_ProcessLastModified(request);
5178 res = set_content_length(request);
5179 if(res != ERROR_SUCCESS)
5180 goto lend;
5181 if(!request->contentLength && !secure_proxy_connect)
5182 http_release_netconn(request, TRUE);
5184 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT) && responseLen)
5186 WCHAR *new_url;
5188 switch(request->status_code) {
5189 case HTTP_STATUS_REDIRECT:
5190 case HTTP_STATUS_MOVED:
5191 case HTTP_STATUS_REDIRECT_KEEP_VERB:
5192 case HTTP_STATUS_REDIRECT_METHOD:
5193 new_url = get_redirect_url(request);
5194 if(!new_url)
5195 break;
5197 if (wcscmp(request->verb, L"GET") && wcscmp(request->verb, L"HEAD") &&
5198 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5200 free(request->verb);
5201 request->verb = wcsdup(L"GET");
5203 http_release_netconn(request, drain_content(request, FALSE) == ERROR_SUCCESS);
5204 res = HTTP_HandleRedirect(request, new_url);
5205 free(new_url);
5206 if (res == ERROR_SUCCESS)
5207 loop_next = TRUE;
5208 redirected = TRUE;
5211 if (!(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTH) && res == ERROR_SUCCESS)
5213 WCHAR szAuthValue[2048];
5214 dwBufferSize=2048;
5215 if (request->status_code == HTTP_STATUS_DENIED)
5217 WCHAR *host = wcsdup(request->server->canon_host_port);
5218 DWORD dwIndex = 0;
5219 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_WWW_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5221 if (HTTP_DoAuthorization(request, szAuthValue,
5222 &request->authInfo,
5223 request->session->userName,
5224 request->session->password, host))
5226 if (drain_content(request, TRUE) != ERROR_SUCCESS)
5228 FIXME("Could not drain content\n");
5229 http_release_netconn(request, FALSE);
5231 loop_next = TRUE;
5232 break;
5235 dwBufferSize = 2048;
5237 free(host);
5239 if(!loop_next) {
5240 TRACE("Cleaning wrong authorization data\n");
5241 destroy_authinfo(request->authInfo);
5242 request->authInfo = NULL;
5245 if (request->status_code == HTTP_STATUS_PROXY_AUTH_REQ)
5247 DWORD dwIndex = 0;
5248 while (HTTP_HttpQueryInfoW(request,HTTP_QUERY_PROXY_AUTHENTICATE,szAuthValue,&dwBufferSize,&dwIndex) == ERROR_SUCCESS)
5250 if (HTTP_DoAuthorization(request, szAuthValue,
5251 &request->proxyAuthInfo,
5252 request->session->appInfo->proxyUsername,
5253 request->session->appInfo->proxyPassword,
5254 NULL))
5256 if (drain_content(request, TRUE) != ERROR_SUCCESS)
5258 FIXME("Could not drain content\n");
5259 http_release_netconn(request, FALSE);
5261 loop_next = TRUE;
5262 break;
5265 dwBufferSize = 2048;
5268 if(!loop_next) {
5269 TRACE("Cleaning wrong proxy authorization data\n");
5270 destroy_authinfo(request->proxyAuthInfo);
5271 request->proxyAuthInfo = NULL;
5275 if (secure_proxy_connect && request->status_code == HTTP_STATUS_OK)
5277 res = NETCON_secure_connect(request->netconn, request->server);
5278 if (res != ERROR_SUCCESS)
5280 WARN("failed to upgrade to secure proxy connection\n");
5281 http_release_netconn( request, FALSE );
5282 break;
5284 remove_header(request, L"Proxy-Authorization", TRUE);
5285 destroy_authinfo(request->proxyAuthInfo);
5286 request->proxyAuthInfo = NULL;
5287 request->contentLength = 0;
5288 request->netconn_stream.content_length = 0;
5290 secure_proxy_connect = FALSE;
5291 loop_next = TRUE;
5294 else
5295 res = ERROR_SUCCESS;
5297 while (loop_next);
5299 lend:
5300 /* TODO: send notification for P3P header */
5302 if(res == ERROR_SUCCESS)
5303 create_cache_entry(request);
5305 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5307 if (res == ERROR_SUCCESS) {
5308 if(bEndRequest && request->contentLength && request->bytesWritten == request->bytesToWrite)
5309 HTTP_ReceiveRequestData(request);
5310 else
5311 send_request_complete(request,
5312 request->session->hdr.dwInternalFlags & INET_OPENURL ? (DWORD_PTR)request->hdr.hInternet : 1, 0);
5313 }else {
5314 send_request_complete(request, 0, res);
5318 TRACE("<--\n");
5319 return res;
5322 typedef struct {
5323 task_header_t hdr;
5324 WCHAR *headers;
5325 DWORD headers_len;
5326 void *optional;
5327 DWORD optional_len;
5328 DWORD content_len;
5329 BOOL end_request;
5330 } send_request_task_t;
5332 /***********************************************************************
5334 * Helper functions for the HttpSendRequest(Ex) functions
5337 static void AsyncHttpSendRequestProc(task_header_t *hdr)
5339 send_request_task_t *task = (send_request_task_t*)hdr;
5340 http_request_t *request = (http_request_t*)task->hdr.hdr;
5342 TRACE("%p\n", request);
5344 HTTP_HttpSendRequestW(request, task->headers, task->headers_len, task->optional,
5345 task->optional_len, task->content_len, task->end_request);
5347 free(task->headers);
5351 static DWORD HTTP_HttpEndRequestW(http_request_t *request, DWORD dwFlags, DWORD_PTR dwContext)
5353 INT responseLen;
5354 DWORD res = ERROR_SUCCESS;
5356 if(!is_valid_netconn(request->netconn)) {
5357 WARN("Not connected\n");
5358 send_request_complete(request, 0, ERROR_INTERNET_OPERATION_CANCELLED);
5359 return ERROR_INTERNET_OPERATION_CANCELLED;
5362 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5363 INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
5365 if (HTTP_GetResponseHeaders(request, &responseLen) || !responseLen)
5366 res = ERROR_HTTP_HEADER_NOT_FOUND;
5368 INTERNET_SendCallback(&request->hdr, request->hdr.dwContext,
5369 INTERNET_STATUS_RESPONSE_RECEIVED, &responseLen, sizeof(DWORD));
5371 /* process cookies here. Is this right? */
5372 http_process_keep_alive(request);
5373 HTTP_ProcessCookies(request);
5374 HTTP_ProcessExpires(request);
5375 HTTP_ProcessLastModified(request);
5377 if ((res = set_content_length(request)) == ERROR_SUCCESS) {
5378 if(!request->contentLength)
5379 http_release_netconn(request, TRUE);
5382 if (res == ERROR_SUCCESS && !(request->hdr.dwFlags & INTERNET_FLAG_NO_AUTO_REDIRECT))
5384 switch(request->status_code) {
5385 case HTTP_STATUS_REDIRECT:
5386 case HTTP_STATUS_MOVED:
5387 case HTTP_STATUS_REDIRECT_METHOD:
5388 case HTTP_STATUS_REDIRECT_KEEP_VERB: {
5389 WCHAR *new_url;
5391 new_url = get_redirect_url(request);
5392 if(!new_url)
5393 break;
5395 if (wcscmp(request->verb, L"GET") && wcscmp(request->verb, L"HEAD") &&
5396 request->status_code != HTTP_STATUS_REDIRECT_KEEP_VERB)
5398 free(request->verb);
5399 request->verb = wcsdup(L"GET");
5401 http_release_netconn(request, drain_content(request, FALSE) == ERROR_SUCCESS);
5402 res = HTTP_HandleRedirect(request, new_url);
5403 free(new_url);
5404 if (res == ERROR_SUCCESS)
5405 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, TRUE);
5410 if(res == ERROR_SUCCESS)
5411 create_cache_entry(request);
5413 if (res == ERROR_SUCCESS && request->contentLength)
5414 HTTP_ReceiveRequestData(request);
5415 else
5416 send_request_complete(request, res == ERROR_SUCCESS, res);
5418 return res;
5421 /***********************************************************************
5422 * HttpEndRequestA (WININET.@)
5424 * Ends an HTTP request that was started by HttpSendRequestEx
5426 * RETURNS
5427 * TRUE if successful
5428 * FALSE on failure
5431 BOOL WINAPI HttpEndRequestA(HINTERNET hRequest,
5432 LPINTERNET_BUFFERSA lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5434 TRACE("(%p, %p, %08lx, %08Ix)\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5436 if (lpBuffersOut)
5438 SetLastError(ERROR_INVALID_PARAMETER);
5439 return FALSE;
5442 return HttpEndRequestW(hRequest, NULL, dwFlags, dwContext);
5445 typedef struct {
5446 task_header_t hdr;
5447 DWORD flags;
5448 DWORD context;
5449 } end_request_task_t;
5451 static void AsyncHttpEndRequestProc(task_header_t *hdr)
5453 end_request_task_t *task = (end_request_task_t*)hdr;
5454 http_request_t *req = (http_request_t*)task->hdr.hdr;
5456 TRACE("%p\n", req);
5458 HTTP_HttpEndRequestW(req, task->flags, task->context);
5461 /***********************************************************************
5462 * HttpEndRequestW (WININET.@)
5464 * Ends an HTTP request that was started by HttpSendRequestEx
5466 * RETURNS
5467 * TRUE if successful
5468 * FALSE on failure
5471 BOOL WINAPI HttpEndRequestW(HINTERNET hRequest,
5472 LPINTERNET_BUFFERSW lpBuffersOut, DWORD dwFlags, DWORD_PTR dwContext)
5474 http_request_t *request;
5475 DWORD res;
5477 TRACE("%p %p %lx %Ix -->\n", hRequest, lpBuffersOut, dwFlags, dwContext);
5479 if (lpBuffersOut)
5481 SetLastError(ERROR_INVALID_PARAMETER);
5482 return FALSE;
5485 request = (http_request_t*) get_handle_object( hRequest );
5487 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5489 SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
5490 if (request)
5491 WININET_Release( &request->hdr );
5492 return FALSE;
5494 request->hdr.dwFlags |= dwFlags;
5496 if (request->session->appInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5498 end_request_task_t *task;
5500 task = alloc_async_task(&request->hdr, AsyncHttpEndRequestProc, sizeof(*task));
5501 task->flags = dwFlags;
5502 task->context = dwContext;
5504 INTERNET_AsyncCall(&task->hdr);
5505 res = ERROR_IO_PENDING;
5507 else
5508 res = HTTP_HttpEndRequestW(request, dwFlags, dwContext);
5510 WININET_Release( &request->hdr );
5511 TRACE("%lu <--\n", res);
5512 if(res != ERROR_SUCCESS)
5513 SetLastError(res);
5514 return res == ERROR_SUCCESS;
5517 /***********************************************************************
5518 * HttpSendRequestExA (WININET.@)
5520 * Sends the specified request to the HTTP server and allows chunked
5521 * transfers.
5523 * RETURNS
5524 * Success: TRUE
5525 * Failure: FALSE, call GetLastError() for more information.
5527 BOOL WINAPI HttpSendRequestExA(HINTERNET hRequest,
5528 LPINTERNET_BUFFERSA lpBuffersIn,
5529 LPINTERNET_BUFFERSA lpBuffersOut,
5530 DWORD dwFlags, DWORD_PTR dwContext)
5532 INTERNET_BUFFERSW BuffersInW;
5533 BOOL rc = FALSE;
5534 DWORD headerlen;
5535 LPWSTR header = NULL;
5537 TRACE("(%p, %p, %p, %08lx, %08Ix)\n", hRequest, lpBuffersIn,
5538 lpBuffersOut, dwFlags, dwContext);
5540 if (lpBuffersIn)
5542 BuffersInW.dwStructSize = sizeof(LPINTERNET_BUFFERSW);
5543 if (lpBuffersIn->lpcszHeader)
5545 if (lpBuffersIn->dwHeadersLength == 0 && *lpBuffersIn->lpcszHeader != '\0')
5547 SetLastError(ERROR_INVALID_PARAMETER);
5548 return FALSE;
5551 headerlen = MultiByteToWideChar(CP_ACP,0,lpBuffersIn->lpcszHeader,
5552 lpBuffersIn->dwHeadersLength,0,0);
5553 header = malloc(headerlen * sizeof(WCHAR));
5554 if (!(BuffersInW.lpcszHeader = header))
5556 SetLastError(ERROR_OUTOFMEMORY);
5557 return FALSE;
5559 BuffersInW.dwHeadersLength = MultiByteToWideChar(CP_ACP, 0,
5560 lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5561 header, headerlen);
5563 else
5564 BuffersInW.lpcszHeader = NULL;
5565 BuffersInW.dwHeadersTotal = lpBuffersIn->dwHeadersTotal;
5566 BuffersInW.lpvBuffer = lpBuffersIn->lpvBuffer;
5567 BuffersInW.dwBufferLength = lpBuffersIn->dwBufferLength;
5568 BuffersInW.dwBufferTotal = lpBuffersIn->dwBufferTotal;
5569 BuffersInW.Next = NULL;
5572 rc = HttpSendRequestExW(hRequest, lpBuffersIn ? &BuffersInW : NULL, NULL, dwFlags, dwContext);
5574 free(header);
5575 return rc;
5578 /***********************************************************************
5579 * HttpSendRequestExW (WININET.@)
5581 * Sends the specified request to the HTTP server and allows chunked
5582 * transfers
5584 * RETURNS
5585 * Success: TRUE
5586 * Failure: FALSE, call GetLastError() for more information.
5588 BOOL WINAPI HttpSendRequestExW(HINTERNET hRequest,
5589 LPINTERNET_BUFFERSW lpBuffersIn,
5590 LPINTERNET_BUFFERSW lpBuffersOut,
5591 DWORD dwFlags, DWORD_PTR dwContext)
5593 http_request_t *request;
5594 http_session_t *session;
5595 appinfo_t *hIC;
5596 DWORD res;
5598 TRACE("(%p, %p, %p, %08lx, %08Ix)\n", hRequest, lpBuffersIn,
5599 lpBuffersOut, dwFlags, dwContext);
5601 request = (http_request_t*) get_handle_object( hRequest );
5603 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5605 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5606 goto lend;
5609 session = request->session;
5610 assert(session->hdr.htype == WH_HHTTPSESSION);
5611 hIC = session->appInfo;
5612 assert(hIC->hdr.htype == WH_HINIT);
5614 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5616 send_request_task_t *task;
5618 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5619 if (lpBuffersIn)
5621 DWORD size = 0;
5623 if (lpBuffersIn->lpcszHeader)
5625 if (lpBuffersIn->dwHeadersLength == ~0u)
5626 size = (lstrlenW( lpBuffersIn->lpcszHeader ) + 1) * sizeof(WCHAR);
5627 else
5628 size = lpBuffersIn->dwHeadersLength * sizeof(WCHAR);
5630 task->headers = malloc(size);
5631 memcpy(task->headers, lpBuffersIn->lpcszHeader, size);
5633 else task->headers = NULL;
5635 task->headers_len = size / sizeof(WCHAR);
5636 task->optional = lpBuffersIn->lpvBuffer;
5637 task->optional_len = lpBuffersIn->dwBufferLength;
5638 task->content_len = lpBuffersIn->dwBufferTotal;
5640 else
5642 task->headers = NULL;
5643 task->headers_len = 0;
5644 task->optional = NULL;
5645 task->optional_len = 0;
5646 task->content_len = 0;
5649 task->end_request = FALSE;
5651 INTERNET_AsyncCall(&task->hdr);
5652 res = ERROR_IO_PENDING;
5654 else
5656 if (lpBuffersIn)
5657 res = HTTP_HttpSendRequestW(request, lpBuffersIn->lpcszHeader, lpBuffersIn->dwHeadersLength,
5658 lpBuffersIn->lpvBuffer, lpBuffersIn->dwBufferLength,
5659 lpBuffersIn->dwBufferTotal, FALSE);
5660 else
5661 res = HTTP_HttpSendRequestW(request, NULL, 0, NULL, 0, 0, FALSE);
5664 lend:
5665 if ( request )
5666 WININET_Release( &request->hdr );
5668 TRACE("<---\n");
5669 SetLastError(res);
5670 return res == ERROR_SUCCESS;
5673 /***********************************************************************
5674 * HttpSendRequestW (WININET.@)
5676 * Sends the specified request to the HTTP server
5678 * RETURNS
5679 * TRUE on success
5680 * FALSE on failure
5683 BOOL WINAPI HttpSendRequestW(HINTERNET hHttpRequest, LPCWSTR lpszHeaders,
5684 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5686 http_request_t *request;
5687 http_session_t *session = NULL;
5688 appinfo_t *hIC = NULL;
5689 DWORD res = ERROR_SUCCESS;
5691 TRACE("%p, %s, %li, %p, %li)\n", hHttpRequest,
5692 debugstr_wn(lpszHeaders, dwHeaderLength), dwHeaderLength, lpOptional, dwOptionalLength);
5694 request = (http_request_t*) get_handle_object( hHttpRequest );
5695 if (NULL == request || request->hdr.htype != WH_HHTTPREQ)
5697 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5698 goto lend;
5701 session = request->session;
5702 if (NULL == session || session->hdr.htype != WH_HHTTPSESSION)
5704 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5705 goto lend;
5708 hIC = session->appInfo;
5709 if (NULL == hIC || hIC->hdr.htype != WH_HINIT)
5711 res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
5712 goto lend;
5715 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
5717 send_request_task_t *task;
5719 task = alloc_async_task(&request->hdr, AsyncHttpSendRequestProc, sizeof(*task));
5720 if (lpszHeaders)
5722 DWORD size;
5724 if (dwHeaderLength == ~0u) size = (lstrlenW(lpszHeaders) + 1) * sizeof(WCHAR);
5725 else size = dwHeaderLength * sizeof(WCHAR);
5727 task->headers = malloc(size);
5728 memcpy(task->headers, lpszHeaders, size);
5730 else
5731 task->headers = NULL;
5732 task->headers_len = dwHeaderLength;
5733 task->optional = lpOptional;
5734 task->optional_len = dwOptionalLength;
5735 task->content_len = dwOptionalLength;
5736 task->end_request = TRUE;
5738 INTERNET_AsyncCall(&task->hdr);
5739 res = ERROR_IO_PENDING;
5741 else
5743 res = HTTP_HttpSendRequestW(request, lpszHeaders,
5744 dwHeaderLength, lpOptional, dwOptionalLength,
5745 dwOptionalLength, TRUE);
5747 lend:
5748 if( request )
5749 WININET_Release( &request->hdr );
5751 SetLastError(res);
5752 return res == ERROR_SUCCESS;
5755 /***********************************************************************
5756 * HttpSendRequestA (WININET.@)
5758 * Sends the specified request to the HTTP server
5760 * RETURNS
5761 * TRUE on success
5762 * FALSE on failure
5765 BOOL WINAPI HttpSendRequestA(HINTERNET hHttpRequest, LPCSTR lpszHeaders,
5766 DWORD dwHeaderLength, LPVOID lpOptional ,DWORD dwOptionalLength)
5768 BOOL result;
5769 LPWSTR szHeaders=NULL;
5770 DWORD nLen=dwHeaderLength;
5771 if(lpszHeaders!=NULL)
5773 if (dwHeaderLength == 0 && *lpszHeaders != '\0')
5775 SetLastError(ERROR_INVALID_PARAMETER);
5776 return FALSE;
5779 nLen=MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,NULL,0);
5780 szHeaders = malloc(nLen * sizeof(WCHAR));
5781 MultiByteToWideChar(CP_ACP,0,lpszHeaders,dwHeaderLength,szHeaders,nLen);
5783 result = HttpSendRequestW(hHttpRequest, szHeaders, nLen, lpOptional, dwOptionalLength);
5784 free(szHeaders);
5785 return result;
5788 /***********************************************************************
5789 * HTTPSESSION_Destroy (internal)
5791 * Deallocate session handle
5794 static void HTTPSESSION_Destroy(object_header_t *hdr)
5796 http_session_t *session = (http_session_t*) hdr;
5798 TRACE("%p\n", session);
5800 WININET_Release(&session->appInfo->hdr);
5802 free(session->hostName);
5803 free(session->password);
5804 free(session->userName);
5807 static DWORD HTTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
5810 switch(option) {
5811 case INTERNET_OPTION_HANDLE_TYPE:
5812 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
5814 if (*size < sizeof(ULONG))
5815 return ERROR_INSUFFICIENT_BUFFER;
5817 *size = sizeof(DWORD);
5818 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_HTTP;
5819 return ERROR_SUCCESS;
5822 return INET_QueryOption(hdr, option, buffer, size, unicode);
5825 static DWORD HTTPSESSION_SetOption(object_header_t *hdr, DWORD option, void *buffer, DWORD size)
5827 http_session_t *ses = (http_session_t*)hdr;
5829 switch(option) {
5830 case INTERNET_OPTION_USERNAME:
5832 free(ses->userName);
5833 if (!(ses->userName = wcsdup(buffer))) return ERROR_OUTOFMEMORY;
5834 return ERROR_SUCCESS;
5836 case INTERNET_OPTION_PASSWORD:
5838 free(ses->password);
5839 if (!(ses->password = wcsdup(buffer))) return ERROR_OUTOFMEMORY;
5840 return ERROR_SUCCESS;
5842 case INTERNET_OPTION_PROXY_USERNAME:
5844 free(ses->appInfo->proxyUsername);
5845 if (!(ses->appInfo->proxyUsername = wcsdup(buffer))) return ERROR_OUTOFMEMORY;
5846 return ERROR_SUCCESS;
5848 case INTERNET_OPTION_PROXY_PASSWORD:
5850 free(ses->appInfo->proxyPassword);
5851 if (!(ses->appInfo->proxyPassword = wcsdup(buffer))) return ERROR_OUTOFMEMORY;
5852 return ERROR_SUCCESS;
5854 default: break;
5857 return INET_SetOption(hdr, option, buffer, size);
5860 static const object_vtbl_t HTTPSESSIONVtbl = {
5861 HTTPSESSION_Destroy,
5862 NULL,
5863 HTTPSESSION_QueryOption,
5864 HTTPSESSION_SetOption,
5865 NULL,
5866 NULL,
5867 NULL,
5868 NULL,
5869 NULL
5873 /***********************************************************************
5874 * HTTP_Connect (internal)
5876 * Create http session handle
5878 * RETURNS
5879 * HINTERNET a session handle on success
5880 * NULL on failure
5883 DWORD HTTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
5884 INTERNET_PORT serverPort, LPCWSTR lpszUserName,
5885 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
5886 DWORD dwInternalFlags, HINTERNET *ret)
5888 http_session_t *session = NULL;
5890 TRACE("-->\n");
5892 if (!lpszServerName || !lpszServerName[0])
5893 return ERROR_INVALID_PARAMETER;
5895 assert( hIC->hdr.htype == WH_HINIT );
5897 session = alloc_object(&hIC->hdr, &HTTPSESSIONVtbl, sizeof(http_session_t));
5898 if (!session)
5899 return ERROR_OUTOFMEMORY;
5902 * According to my tests. The name is not resolved until a request is sent
5905 session->hdr.htype = WH_HHTTPSESSION;
5906 session->hdr.dwFlags = dwFlags;
5907 session->hdr.dwContext = dwContext;
5908 session->hdr.dwInternalFlags |= dwInternalFlags;
5909 session->hdr.decoding = hIC->hdr.decoding;
5911 WININET_AddRef( &hIC->hdr );
5912 session->appInfo = hIC;
5913 list_add_head( &hIC->hdr.children, &session->hdr.entry );
5915 session->hostName = wcsdup(lpszServerName);
5916 if (lpszUserName && lpszUserName[0])
5917 session->userName = wcsdup(lpszUserName);
5918 session->password = wcsdup(lpszPassword);
5919 session->hostPort = serverPort;
5920 session->hdr.connect_timeout = hIC->hdr.connect_timeout;
5921 session->hdr.send_timeout = hIC->hdr.send_timeout;
5922 session->hdr.receive_timeout = hIC->hdr.receive_timeout;
5924 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
5925 if (!(session->hdr.dwInternalFlags & INET_OPENURL))
5927 INTERNET_SendCallback(&hIC->hdr, dwContext,
5928 INTERNET_STATUS_HANDLE_CREATED, &session->hdr.hInternet,
5929 sizeof(HINTERNET));
5933 * an INTERNET_STATUS_REQUEST_COMPLETE is NOT sent here as per my tests on
5934 * windows
5937 TRACE("%p --> %p\n", hIC, session);
5939 *ret = session->hdr.hInternet;
5940 return ERROR_SUCCESS;
5943 /***********************************************************************
5944 * HTTP_clear_response_headers (internal)
5946 * clear out any old response headers
5948 static void HTTP_clear_response_headers( http_request_t *request )
5950 DWORD i;
5952 EnterCriticalSection( &request->headers_section );
5954 for( i=0; i<request->nCustHeaders; i++)
5956 if( !request->custHeaders[i].lpszField )
5957 continue;
5958 if( !request->custHeaders[i].lpszValue )
5959 continue;
5960 if ( request->custHeaders[i].wFlags & HDR_ISREQUEST )
5961 continue;
5962 HTTP_DeleteCustomHeader( request, i );
5963 i--;
5966 LeaveCriticalSection( &request->headers_section );
5969 /***********************************************************************
5970 * HTTP_GetResponseHeaders (internal)
5972 * Read server response
5974 * RETURNS
5976 * TRUE on success
5977 * FALSE on error
5979 static DWORD HTTP_GetResponseHeaders(http_request_t *request, INT *len)
5981 INT cbreaks = 0;
5982 WCHAR buffer[MAX_REPLY_LEN];
5983 DWORD buflen = MAX_REPLY_LEN;
5984 INT rc = 0;
5985 char bufferA[MAX_REPLY_LEN];
5986 LPWSTR status_code = NULL, status_text = NULL;
5987 DWORD res = ERROR_HTTP_INVALID_SERVER_RESPONSE;
5988 BOOL codeHundred = FALSE;
5990 TRACE("-->\n");
5992 if(!is_valid_netconn(request->netconn))
5993 goto lend;
5995 /* clear old response headers (eg. from a redirect response) */
5996 HTTP_clear_response_headers( request );
5998 NETCON_set_timeout( request->netconn, FALSE, request->hdr.receive_timeout );
5999 do {
6001 * We should first receive 'HTTP/1.x nnn OK' where nnn is the status code.
6003 buflen = MAX_REPLY_LEN;
6004 if ((res = read_line(request, bufferA, &buflen)))
6005 goto lend;
6007 if (!buflen) goto lend;
6009 rc += buflen;
6010 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
6011 /* check is this a status code line? */
6012 if (!wcsncmp(buffer, L"HTTP/1.0", 4))
6014 /* split the version from the status code */
6015 status_code = wcschr( buffer, ' ' );
6016 if( !status_code )
6017 goto lend;
6018 *status_code++=0;
6020 /* split the status code from the status text */
6021 status_text = wcschr( status_code, ' ' );
6022 if( status_text )
6023 *status_text++=0;
6025 request->status_code = wcstol(status_code, NULL, 10);
6027 TRACE("version [%s] status code [%s] status text [%s]\n",
6028 debugstr_w(buffer), debugstr_w(status_code), debugstr_w(status_text) );
6030 codeHundred = request->status_code == HTTP_STATUS_CONTINUE;
6032 else if (!codeHundred)
6034 WARN("No status line at head of response (%s)\n", debugstr_w(buffer));
6036 free(request->version);
6037 free(request->statusText);
6039 request->status_code = HTTP_STATUS_OK;
6040 request->version = wcsdup(L"HTTP/1.0");
6041 request->statusText = wcsdup(L"OK");
6043 goto lend;
6045 } while (codeHundred);
6047 /* Add status code */
6048 HTTP_ProcessHeader(request, L"Status", status_code,
6049 HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
6051 free(request->version);
6052 free(request->statusText);
6054 request->version = wcsdup(buffer);
6055 request->statusText = wcsdup(status_text ? status_text : L"");
6057 /* Restore the spaces */
6058 *(status_code-1) = ' ';
6059 if (status_text)
6060 *(status_text-1) = ' ';
6062 /* Parse each response line */
6065 buflen = MAX_REPLY_LEN;
6066 if (!read_line(request, bufferA, &buflen) && buflen)
6068 LPWSTR * pFieldAndValue;
6070 TRACE("got line %s, now interpreting\n", debugstr_a(bufferA));
6072 if (!bufferA[0]) break;
6073 MultiByteToWideChar( CP_ACP, 0, bufferA, buflen, buffer, MAX_REPLY_LEN );
6075 pFieldAndValue = HTTP_InterpretHttpHeader(buffer);
6076 if (pFieldAndValue)
6078 HTTP_ProcessHeader(request, pFieldAndValue[0], pFieldAndValue[1],
6079 HTTP_ADDREQ_FLAG_ADD );
6080 HTTP_FreeTokens(pFieldAndValue);
6083 else
6085 cbreaks++;
6086 if (cbreaks >= 2)
6087 break;
6089 }while(1);
6091 res = ERROR_SUCCESS;
6093 lend:
6095 *len = rc;
6096 TRACE("<--\n");
6097 return res;
6100 /***********************************************************************
6101 * HTTP_InterpretHttpHeader (internal)
6103 * Parse server response
6105 * RETURNS
6107 * Pointer to array of field, value, NULL on success.
6108 * NULL on error.
6110 static LPWSTR * HTTP_InterpretHttpHeader(LPCWSTR buffer)
6112 LPWSTR * pTokenPair;
6113 LPWSTR pszColon;
6114 INT len;
6116 pTokenPair = calloc(3, sizeof(*pTokenPair));
6118 pszColon = wcschr(buffer, ':');
6119 /* must have two tokens */
6120 if (!pszColon)
6122 HTTP_FreeTokens(pTokenPair);
6123 if (buffer[0])
6124 TRACE("No ':' in line: %s\n", debugstr_w(buffer));
6125 return NULL;
6128 pTokenPair[0] = malloc((pszColon - buffer + 1) * sizeof(WCHAR));
6129 if (!pTokenPair[0])
6131 HTTP_FreeTokens(pTokenPair);
6132 return NULL;
6134 memcpy(pTokenPair[0], buffer, (pszColon - buffer) * sizeof(WCHAR));
6135 pTokenPair[0][pszColon - buffer] = '\0';
6137 /* skip colon */
6138 pszColon++;
6139 len = lstrlenW(pszColon);
6140 pTokenPair[1] = malloc((len + 1) * sizeof(WCHAR));
6141 if (!pTokenPair[1])
6143 HTTP_FreeTokens(pTokenPair);
6144 return NULL;
6146 memcpy(pTokenPair[1], pszColon, (len + 1) * sizeof(WCHAR));
6148 strip_spaces(pTokenPair[0]);
6149 strip_spaces(pTokenPair[1]);
6151 TRACE("field(%s) Value(%s)\n", debugstr_w(pTokenPair[0]), debugstr_w(pTokenPair[1]));
6152 return pTokenPair;
6155 /***********************************************************************
6156 * HTTP_ProcessHeader (internal)
6158 * Stuff header into header tables according to <dwModifier>
6162 #define COALESCEFLAGS (HTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA|HTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON)
6164 static DWORD HTTP_ProcessHeader(http_request_t *request, LPCWSTR field, LPCWSTR value, DWORD dwModifier)
6166 LPHTTPHEADERW lphttpHdr = NULL;
6167 INT index;
6168 BOOL request_only = !!(dwModifier & HTTP_ADDHDR_FLAG_REQ);
6169 DWORD res = ERROR_HTTP_INVALID_HEADER;
6171 TRACE("--> %s: %s - 0x%08lx\n", debugstr_w(field), debugstr_w(value), dwModifier);
6173 EnterCriticalSection( &request->headers_section );
6175 /* REPLACE wins out over ADD */
6176 if (dwModifier & HTTP_ADDREQ_FLAG_REPLACE)
6177 dwModifier &= ~HTTP_ADDREQ_FLAG_ADD;
6179 if (dwModifier & HTTP_ADDREQ_FLAG_ADD)
6180 index = -1;
6181 else
6182 index = HTTP_GetCustomHeaderIndex(request, field, 0, request_only);
6184 if (index >= 0)
6186 if (dwModifier & HTTP_ADDREQ_FLAG_ADD_IF_NEW)
6188 LeaveCriticalSection( &request->headers_section );
6189 return ERROR_HTTP_INVALID_HEADER;
6191 lphttpHdr = &request->custHeaders[index];
6193 else if (value)
6195 HTTPHEADERW hdr;
6197 hdr.lpszField = (LPWSTR)field;
6198 hdr.lpszValue = (LPWSTR)value;
6199 hdr.wFlags = hdr.wCount = 0;
6201 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6202 hdr.wFlags |= HDR_ISREQUEST;
6204 res = HTTP_InsertCustomHeader(request, &hdr);
6205 LeaveCriticalSection( &request->headers_section );
6206 return res;
6208 /* no value to delete */
6209 else
6211 LeaveCriticalSection( &request->headers_section );
6212 return ERROR_SUCCESS;
6215 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6216 lphttpHdr->wFlags |= HDR_ISREQUEST;
6217 else
6218 lphttpHdr->wFlags &= ~HDR_ISREQUEST;
6220 if (dwModifier & HTTP_ADDREQ_FLAG_REPLACE)
6222 HTTP_DeleteCustomHeader( request, index );
6224 if (value && value[0])
6226 HTTPHEADERW hdr;
6228 hdr.lpszField = (LPWSTR)field;
6229 hdr.lpszValue = (LPWSTR)value;
6230 hdr.wFlags = hdr.wCount = 0;
6232 if (dwModifier & HTTP_ADDHDR_FLAG_REQ)
6233 hdr.wFlags |= HDR_ISREQUEST;
6235 res = HTTP_InsertCustomHeader(request, &hdr);
6236 LeaveCriticalSection( &request->headers_section );
6237 return res;
6240 LeaveCriticalSection( &request->headers_section );
6241 return ERROR_SUCCESS;
6243 else if (dwModifier & COALESCEFLAGS)
6245 LPWSTR lpsztmp;
6246 WCHAR ch = 0;
6247 INT len = 0;
6248 INT origlen = lstrlenW(lphttpHdr->lpszValue);
6249 INT valuelen = lstrlenW(value);
6251 if (dwModifier & HTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA)
6253 ch = ',';
6254 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6256 else if (dwModifier & HTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON)
6258 ch = ';';
6259 lphttpHdr->wFlags |= HDR_COMMADELIMITED;
6262 len = origlen + valuelen + ((ch > 0) ? 2 : 0);
6264 lpsztmp = realloc(lphttpHdr->lpszValue, (len + 1) * sizeof(WCHAR));
6265 if (lpsztmp)
6267 lphttpHdr->lpszValue = lpsztmp;
6268 /* FIXME: Increment lphttpHdr->wCount. Perhaps lpszValue should be an array */
6269 if (ch > 0)
6271 lphttpHdr->lpszValue[origlen] = ch;
6272 origlen++;
6273 lphttpHdr->lpszValue[origlen] = ' ';
6274 origlen++;
6277 memcpy(&lphttpHdr->lpszValue[origlen], value, valuelen*sizeof(WCHAR));
6278 lphttpHdr->lpszValue[len] = '\0';
6279 res = ERROR_SUCCESS;
6281 else
6283 WARN("realloc (%d bytes) failed\n",len+1);
6284 res = ERROR_OUTOFMEMORY;
6287 TRACE("<-- %ld\n", res);
6288 LeaveCriticalSection( &request->headers_section );
6289 return res;
6292 /***********************************************************************
6293 * HTTP_GetCustomHeaderIndex (internal)
6295 * Return index of custom header from header array
6296 * Headers section must be held
6298 static INT HTTP_GetCustomHeaderIndex(http_request_t *request, LPCWSTR lpszField,
6299 int requested_index, BOOL request_only)
6301 DWORD index;
6303 TRACE("%s, %d, %d\n", debugstr_w(lpszField), requested_index, request_only);
6305 for (index = 0; index < request->nCustHeaders; index++)
6307 if (wcsicmp(request->custHeaders[index].lpszField, lpszField))
6308 continue;
6310 if (request_only && !(request->custHeaders[index].wFlags & HDR_ISREQUEST))
6311 continue;
6313 if (!request_only && (request->custHeaders[index].wFlags & HDR_ISREQUEST))
6314 continue;
6316 if (requested_index == 0)
6317 break;
6318 requested_index --;
6321 if (index >= request->nCustHeaders)
6322 index = -1;
6324 TRACE("Return: %ld\n", index);
6325 return index;
6329 /***********************************************************************
6330 * HTTP_InsertCustomHeader (internal)
6332 * Insert header into array
6333 * Headers section must be held
6335 static DWORD HTTP_InsertCustomHeader(http_request_t *request, LPHTTPHEADERW lpHdr)
6337 INT count;
6338 LPHTTPHEADERW lph = NULL;
6340 TRACE("--> %s: %s\n", debugstr_w(lpHdr->lpszField), debugstr_w(lpHdr->lpszValue));
6341 count = request->nCustHeaders + 1;
6342 lph = realloc(request->custHeaders, sizeof(HTTPHEADERW) * count);
6344 if (!lph)
6345 return ERROR_OUTOFMEMORY;
6347 request->custHeaders = lph;
6348 request->custHeaders[count-1].lpszField = wcsdup(lpHdr->lpszField);
6349 request->custHeaders[count-1].lpszValue = wcsdup(lpHdr->lpszValue);
6350 request->custHeaders[count-1].wFlags = lpHdr->wFlags;
6351 request->custHeaders[count-1].wCount= lpHdr->wCount;
6352 request->nCustHeaders++;
6354 return ERROR_SUCCESS;
6358 /***********************************************************************
6359 * HTTP_DeleteCustomHeader (internal)
6361 * Delete header from array
6362 * If this function is called, the index may change.
6363 * Headers section must be held
6365 static BOOL HTTP_DeleteCustomHeader(http_request_t *request, DWORD index)
6367 if( request->nCustHeaders <= 0 )
6368 return FALSE;
6369 if( index >= request->nCustHeaders )
6370 return FALSE;
6371 request->nCustHeaders--;
6373 free(request->custHeaders[index].lpszField);
6374 free(request->custHeaders[index].lpszValue);
6376 memmove( &request->custHeaders[index], &request->custHeaders[index+1],
6377 (request->nCustHeaders - index)* sizeof(HTTPHEADERW) );
6378 memset( &request->custHeaders[request->nCustHeaders], 0, sizeof(HTTPHEADERW) );
6380 return TRUE;
6384 /***********************************************************************
6385 * IsHostInProxyBypassList (WININET.@)
6387 BOOL WINAPI IsHostInProxyBypassList(INTERNET_SCHEME scheme, LPCSTR szHost, DWORD length)
6389 FIXME("STUB: scheme=%d host=%s length=%ld\n", scheme, szHost, length);
6390 return FALSE;