strmbase: do not lock in BaseOutputPinImpl_GetDeliveryBuffer the MemInputPin will...
[wine] / dlls / wininet / internet.c
1 /*
2  * Wininet
3  *
4  * Copyright 1999 Corel Corporation
5  * Copyright 2002 CodeWeavers Inc.
6  * Copyright 2002 Jaco Greeff
7  * Copyright 2002 TransGaming Technologies Inc.
8  * Copyright 2004 Mike McCormack for CodeWeavers
9  *
10  * Ulrich Czekalla
11  * Aric Stewart
12  * David Hammerton
13  *
14  * This library is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with this library; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27  */
28
29 #include "config.h"
30 #include "wine/port.h"
31
32 #if defined(__MINGW32__) || defined (_MSC_VER)
33 #include <ws2tcpip.h>
34 #endif
35
36 #include <string.h>
37 #include <stdarg.h>
38 #include <stdio.h>
39 #include <sys/types.h>
40 #ifdef HAVE_SYS_SOCKET_H
41 # include <sys/socket.h>
42 #endif
43 #ifdef HAVE_POLL_H
44 #include <poll.h>
45 #endif
46 #ifdef HAVE_SYS_POLL_H
47 # include <sys/poll.h>
48 #endif
49 #ifdef HAVE_SYS_TIME_H
50 # include <sys/time.h>
51 #endif
52 #include <stdlib.h>
53 #include <ctype.h>
54 #ifdef HAVE_UNISTD_H
55 # include <unistd.h>
56 #endif
57 #include <assert.h>
58
59 #include "windef.h"
60 #include "winbase.h"
61 #include "winreg.h"
62 #include "winuser.h"
63 #include "wininet.h"
64 #include "winineti.h"
65 #include "winnls.h"
66 #include "wine/debug.h"
67 #include "winerror.h"
68 #define NO_SHLWAPI_STREAM
69 #include "shlwapi.h"
70
71 #include "wine/exception.h"
72
73 #include "internet.h"
74 #include "resource.h"
75
76 #include "wine/unicode.h"
77
78 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
79
80 #define RESPONSE_TIMEOUT        30
81
82 typedef struct
83 {
84     DWORD  dwError;
85     CHAR   response[MAX_REPLY_LEN];
86 } WITHREADERROR, *LPWITHREADERROR;
87
88 static DWORD g_dwTlsErrIndex = TLS_OUT_OF_INDEXES;
89 HMODULE WININET_hModule;
90
91 static CRITICAL_SECTION WININET_cs;
92 static CRITICAL_SECTION_DEBUG WININET_cs_debug = 
93 {
94     0, 0, &WININET_cs,
95     { &WININET_cs_debug.ProcessLocksList, &WININET_cs_debug.ProcessLocksList },
96       0, 0, { (DWORD_PTR)(__FILE__ ": WININET_cs") }
97 };
98 static CRITICAL_SECTION WININET_cs = { &WININET_cs_debug, -1, 0, 0, 0, 0 };
99
100 static object_header_t **handle_table;
101 static UINT_PTR next_handle;
102 static UINT_PTR handle_table_size;
103
104 typedef struct
105 {
106     DWORD  proxyEnabled;
107     LPWSTR proxy;
108     LPWSTR proxyBypass;
109 } proxyinfo_t;
110
111 static ULONG max_conns = 2, max_1_0_conns = 4;
112
113 static const WCHAR szInternetSettings[] =
114     { 'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\',
115       'W','i','n','d','o','w','s','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
116       'I','n','t','e','r','n','e','t',' ','S','e','t','t','i','n','g','s',0 };
117 static const WCHAR szProxyServer[] = { 'P','r','o','x','y','S','e','r','v','e','r', 0 };
118 static const WCHAR szProxyEnable[] = { 'P','r','o','x','y','E','n','a','b','l','e', 0 };
119
120 void *alloc_object(object_header_t *parent, const object_vtbl_t *vtbl, size_t size)
121 {
122     UINT_PTR handle = 0, num;
123     object_header_t *ret;
124     object_header_t **p;
125     BOOL res = TRUE;
126
127     ret = heap_alloc_zero(size);
128     if(!ret)
129         return NULL;
130
131     list_init(&ret->children);
132
133     EnterCriticalSection( &WININET_cs );
134
135     if(!handle_table_size) {
136         num = 16;
137         p = heap_alloc_zero(sizeof(handle_table[0]) * num);
138         if(p) {
139             handle_table = p;
140             handle_table_size = num;
141             next_handle = 1;
142         }else {
143             res = FALSE;
144         }
145     }else if(next_handle == handle_table_size) {
146         num = handle_table_size * 2;
147         p = heap_realloc_zero(handle_table, sizeof(handle_table[0]) * num);
148         if(p) {
149             handle_table = p;
150             handle_table_size = num;
151         }else {
152             res = FALSE;
153         }
154     }
155
156     if(res) {
157         handle = next_handle;
158         if(handle_table[handle])
159             ERR("handle isn't free but should be\n");
160         handle_table[handle] = ret;
161         ret->valid_handle = TRUE;
162
163         while(handle_table[next_handle] && next_handle < handle_table_size)
164             next_handle++;
165     }
166
167     LeaveCriticalSection( &WININET_cs );
168
169     if(!res) {
170         heap_free(ret);
171         return NULL;
172     }
173
174     ret->vtbl = vtbl;
175     ret->refs = 1;
176     ret->hInternet = (HINTERNET)handle;
177
178     if(parent) {
179         ret->lpfnStatusCB = parent->lpfnStatusCB;
180         ret->dwInternalFlags = parent->dwInternalFlags & INET_CALLBACKW;
181     }
182
183     return ret;
184 }
185
186 object_header_t *WININET_AddRef( object_header_t *info )
187 {
188     ULONG refs = InterlockedIncrement(&info->refs);
189     TRACE("%p -> refcount = %d\n", info, refs );
190     return info;
191 }
192
193 object_header_t *get_handle_object( HINTERNET hinternet )
194 {
195     object_header_t *info = NULL;
196     UINT_PTR handle = (UINT_PTR) hinternet;
197
198     EnterCriticalSection( &WININET_cs );
199
200     if(handle > 0 && handle < handle_table_size && handle_table[handle] && handle_table[handle]->valid_handle)
201         info = WININET_AddRef(handle_table[handle]);
202
203     LeaveCriticalSection( &WININET_cs );
204
205     TRACE("handle %ld -> %p\n", handle, info);
206
207     return info;
208 }
209
210 static void invalidate_handle(object_header_t *info)
211 {
212     object_header_t *child, *next;
213
214     if(!info->valid_handle)
215         return;
216     info->valid_handle = FALSE;
217
218     /* Free all children as native does */
219     LIST_FOR_EACH_ENTRY_SAFE( child, next, &info->children, object_header_t, entry )
220     {
221         TRACE("invalidating child handle %p for parent %p\n", child->hInternet, info);
222         invalidate_handle( child );
223     }
224
225     WININET_Release(info);
226 }
227
228 BOOL WININET_Release( object_header_t *info )
229 {
230     ULONG refs = InterlockedDecrement(&info->refs);
231     TRACE( "object %p refcount = %d\n", info, refs );
232     if( !refs )
233     {
234         invalidate_handle(info);
235         if ( info->vtbl->CloseConnection )
236         {
237             TRACE( "closing connection %p\n", info);
238             info->vtbl->CloseConnection( info );
239         }
240         /* Don't send a callback if this is a session handle created with InternetOpenUrl */
241         if ((info->htype != WH_HHTTPSESSION && info->htype != WH_HFTPSESSION)
242             || !(info->dwInternalFlags & INET_OPENURL))
243         {
244             INTERNET_SendCallback(info, info->dwContext,
245                                   INTERNET_STATUS_HANDLE_CLOSING, &info->hInternet,
246                                   sizeof(HINTERNET));
247         }
248         TRACE( "destroying object %p\n", info);
249         if ( info->htype != WH_HINIT )
250             list_remove( &info->entry );
251         info->vtbl->Destroy( info );
252
253         if(info->hInternet) {
254             UINT_PTR handle = (UINT_PTR)info->hInternet;
255
256             EnterCriticalSection( &WININET_cs );
257
258             handle_table[handle] = NULL;
259             if(next_handle > handle)
260                 next_handle = handle;
261
262             LeaveCriticalSection( &WININET_cs );
263         }
264
265         heap_free(info);
266     }
267     return TRUE;
268 }
269
270 /***********************************************************************
271  * DllMain [Internal] Initializes the internal 'WININET.DLL'.
272  *
273  * PARAMS
274  *     hinstDLL    [I] handle to the DLL's instance
275  *     fdwReason   [I]
276  *     lpvReserved [I] reserved, must be NULL
277  *
278  * RETURNS
279  *     Success: TRUE
280  *     Failure: FALSE
281  */
282
283 BOOL WINAPI DllMain (HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
284 {
285     TRACE("%p,%x,%p\n", hinstDLL, fdwReason, lpvReserved);
286
287     switch (fdwReason) {
288         case DLL_PROCESS_ATTACH:
289
290             g_dwTlsErrIndex = TlsAlloc();
291
292             if (g_dwTlsErrIndex == TLS_OUT_OF_INDEXES)
293                 return FALSE;
294
295             URLCacheContainers_CreateDefaults();
296
297             WININET_hModule = hinstDLL;
298             break;
299
300         case DLL_THREAD_ATTACH:
301             break;
302
303         case DLL_THREAD_DETACH:
304             if (g_dwTlsErrIndex != TLS_OUT_OF_INDEXES)
305             {
306                 heap_free(TlsGetValue(g_dwTlsErrIndex));
307             }
308             break;
309
310         case DLL_PROCESS_DETACH:
311             collect_connections(TRUE);
312             NETCON_unload();
313             URLCacheContainers_DeleteAll();
314
315             if (g_dwTlsErrIndex != TLS_OUT_OF_INDEXES)
316             {
317                 heap_free(TlsGetValue(g_dwTlsErrIndex));
318                 TlsFree(g_dwTlsErrIndex);
319             }
320             break;
321     }
322     return TRUE;
323 }
324
325 /***********************************************************************
326  *           INTERNET_SaveProxySettings
327  *
328  * Stores the proxy settings given by lpwai into the registry
329  *
330  * RETURNS
331  *     ERROR_SUCCESS if no error, or error code on fail
332  */
333 static LONG INTERNET_SaveProxySettings( proxyinfo_t *lpwpi )
334 {
335     HKEY key;
336     LONG ret;
337
338     if ((ret = RegOpenKeyW( HKEY_CURRENT_USER, szInternetSettings, &key )))
339         return ret;
340
341     if ((ret = RegSetValueExW( key, szProxyEnable, 0, REG_DWORD, (BYTE*)&lpwpi->proxyEnabled, sizeof(DWORD))))
342     {
343         RegCloseKey( key );
344         return ret;
345     }
346
347     if (lpwpi->proxy)
348     {
349         if ((ret = RegSetValueExW( key, szProxyServer, 0, REG_SZ, (BYTE*)lpwpi->proxy, sizeof(WCHAR) * (lstrlenW(lpwpi->proxy) + 1))))
350         {
351             RegCloseKey( key );
352             return ret;
353         }
354     }
355     else
356     {
357         if ((ret = RegDeleteValueW( key, szProxyServer )))
358         {
359             RegCloseKey( key );
360             return ret;
361         }
362     }
363
364     RegCloseKey(key);
365     return ERROR_SUCCESS;
366 }
367
368 /***********************************************************************
369  *           INTERNET_FindProxyForProtocol
370  *
371  * Searches the proxy string for a proxy of the given protocol.
372  * Returns the found proxy, or the default proxy if none of the given
373  * protocol is found.
374  *
375  * PARAMETERS
376  *     szProxy       [In]     proxy string to search
377  *     proto         [In]     protocol to search for, e.g. "http"
378  *     foundProxy    [Out]    found proxy
379  *     foundProxyLen [In/Out] length of foundProxy buffer, in WCHARs
380  *
381  * RETURNS
382  *     TRUE if a proxy is found, FALSE if not.  If foundProxy is too short,
383  *     *foundProxyLen is set to the required size in WCHARs, including the
384  *     NULL terminator, and the last error is set to ERROR_INSUFFICIENT_BUFFER.
385  */
386 BOOL INTERNET_FindProxyForProtocol(LPCWSTR szProxy, LPCWSTR proto, WCHAR *foundProxy, DWORD *foundProxyLen)
387 {
388     LPCWSTR ptr;
389     BOOL ret = FALSE;
390
391     TRACE("(%s, %s)\n", debugstr_w(szProxy), debugstr_w(proto));
392
393     /* First, look for the specified protocol (proto=scheme://host:port) */
394     for (ptr = szProxy; !ret && ptr && *ptr; )
395     {
396         LPCWSTR end, equal;
397
398         if (!(end = strchrW(ptr, ' ')))
399             end = ptr + strlenW(ptr);
400         if ((equal = strchrW(ptr, '=')) && equal < end &&
401              equal - ptr == strlenW(proto) &&
402              !strncmpiW(proto, ptr, strlenW(proto)))
403         {
404             if (end - equal > *foundProxyLen)
405             {
406                 WARN("buffer too short for %s\n",
407                      debugstr_wn(equal + 1, end - equal - 1));
408                 *foundProxyLen = end - equal;
409                 SetLastError(ERROR_INSUFFICIENT_BUFFER);
410             }
411             else
412             {
413                 memcpy(foundProxy, equal + 1, (end - equal) * sizeof(WCHAR));
414                 foundProxy[end - equal] = 0;
415                 ret = TRUE;
416             }
417         }
418         if (*end == ' ')
419             ptr = end + 1;
420         else
421             ptr = end;
422     }
423     if (!ret)
424     {
425         /* It wasn't found: look for no protocol */
426         for (ptr = szProxy; !ret && ptr && *ptr; )
427         {
428             LPCWSTR end, equal;
429
430             if (!(end = strchrW(ptr, ' ')))
431                 end = ptr + strlenW(ptr);
432             if (!(equal = strchrW(ptr, '=')))
433             {
434                 if (end - ptr + 1 > *foundProxyLen)
435                 {
436                     WARN("buffer too short for %s\n",
437                          debugstr_wn(ptr, end - ptr));
438                     *foundProxyLen = end - ptr + 1;
439                     SetLastError(ERROR_INSUFFICIENT_BUFFER);
440                 }
441                 else
442                 {
443                     memcpy(foundProxy, ptr, (end - ptr) * sizeof(WCHAR));
444                     foundProxy[end - ptr] = 0;
445                     ret = TRUE;
446                 }
447             }
448             if (*end == ' ')
449                 ptr = end + 1;
450             else
451                 ptr = end;
452         }
453     }
454     if (ret)
455         TRACE("found proxy for %s: %s\n", debugstr_w(proto),
456               debugstr_w(foundProxy));
457     return ret;
458 }
459
460 /***********************************************************************
461  *           InternetInitializeAutoProxyDll   (WININET.@)
462  *
463  * Setup the internal proxy
464  *
465  * PARAMETERS
466  *     dwReserved
467  *
468  * RETURNS
469  *     FALSE on failure
470  *
471  */
472 BOOL WINAPI InternetInitializeAutoProxyDll(DWORD dwReserved)
473 {
474     FIXME("STUB\n");
475     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
476     return FALSE;
477 }
478
479 /***********************************************************************
480  *           DetectAutoProxyUrl   (WININET.@)
481  *
482  * Auto detect the proxy url
483  *
484  * RETURNS
485  *     FALSE on failure
486  *
487  */
488 BOOL WINAPI DetectAutoProxyUrl(LPSTR lpszAutoProxyUrl,
489         DWORD dwAutoProxyUrlLength, DWORD dwDetectFlags)
490 {
491     FIXME("STUB\n");
492     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
493     return FALSE;
494 }
495
496 static void FreeProxyInfo( proxyinfo_t *lpwpi )
497 {
498     heap_free(lpwpi->proxy);
499     heap_free(lpwpi->proxyBypass);
500 }
501
502 static proxyinfo_t *global_proxy;
503
504 static void free_global_proxy( void )
505 {
506     EnterCriticalSection( &WININET_cs );
507     if (global_proxy)
508     {
509         FreeProxyInfo( global_proxy );
510         heap_free( global_proxy );
511     }
512     LeaveCriticalSection( &WININET_cs );
513 }
514
515 /***********************************************************************
516  *          INTERNET_LoadProxySettings
517  *
518  * Loads proxy information from process-wide global settings, the registry,
519  * or the environment into lpwpi.
520  *
521  * The caller should call FreeProxyInfo when done with lpwpi.
522  *
523  * FIXME:
524  * The proxy may be specified in the form 'http=proxy.my.org'
525  * Presumably that means there can be ftp=ftpproxy.my.org too.
526  */
527 static LONG INTERNET_LoadProxySettings( proxyinfo_t *lpwpi )
528 {
529     HKEY key;
530     DWORD type, len;
531     LPCSTR envproxy;
532     LONG ret;
533
534     EnterCriticalSection( &WININET_cs );
535     if (global_proxy)
536     {
537         lpwpi->proxyEnabled = global_proxy->proxyEnabled;
538         lpwpi->proxy = heap_strdupW( global_proxy->proxy );
539         lpwpi->proxyBypass = heap_strdupW( global_proxy->proxyBypass );
540     }
541     LeaveCriticalSection( &WININET_cs );
542
543     if ((ret = RegOpenKeyW( HKEY_CURRENT_USER, szInternetSettings, &key )))
544         return ret;
545
546     len = sizeof(DWORD);
547     if (RegQueryValueExW( key, szProxyEnable, NULL, &type, (BYTE *)&lpwpi->proxyEnabled, &len ) || type != REG_DWORD)
548     {
549         lpwpi->proxyEnabled = 0;
550         if((ret = RegSetValueExW( key, szProxyEnable, 0, REG_DWORD, (BYTE *)&lpwpi->proxyEnabled, sizeof(DWORD) )))
551         {
552             RegCloseKey( key );
553             return ret;
554         }
555     }
556
557     if (!(envproxy = getenv( "http_proxy" )) || lpwpi->proxyEnabled)
558     {
559         TRACE("Proxy is enabled.\n");
560
561         /* figure out how much memory the proxy setting takes */
562         if (!RegQueryValueExW( key, szProxyServer, NULL, &type, NULL, &len ) && len && (type == REG_SZ))
563         {
564             LPWSTR szProxy, p;
565             static const WCHAR szHttp[] = {'h','t','t','p','=',0};
566
567             if (!(szProxy = heap_alloc(len)))
568             {
569                 RegCloseKey( key );
570                 return ERROR_OUTOFMEMORY;
571             }
572             RegQueryValueExW( key, szProxyServer, NULL, &type, (BYTE*)szProxy, &len );
573
574             /* find the http proxy, and strip away everything else */
575             p = strstrW( szProxy, szHttp );
576             if (p)
577             {
578                 p += lstrlenW( szHttp );
579                 lstrcpyW( szProxy, p );
580             }
581             p = strchrW( szProxy, ' ' );
582             if (p) *p = 0;
583
584             lpwpi->proxy = szProxy;
585
586             TRACE("http proxy = %s\n", debugstr_w(lpwpi->proxy));
587         }
588         else
589         {
590             TRACE("No proxy server settings in registry.\n");
591             lpwpi->proxy = NULL;
592         }
593     }
594     else if (envproxy)
595     {
596         WCHAR *envproxyW;
597
598         len = MultiByteToWideChar( CP_UNIXCP, 0, envproxy, -1, NULL, 0 );
599         if (!(envproxyW = heap_alloc(len * sizeof(WCHAR))))
600             return ERROR_OUTOFMEMORY;
601         MultiByteToWideChar( CP_UNIXCP, 0, envproxy, -1, envproxyW, len );
602
603         lpwpi->proxyEnabled = 1;
604         lpwpi->proxy = envproxyW;
605
606         TRACE("http proxy (from environment) = %s\n", debugstr_w(lpwpi->proxy));
607     }
608     RegCloseKey( key );
609
610     lpwpi->proxyBypass = NULL;
611
612     return ERROR_SUCCESS;
613 }
614
615 /***********************************************************************
616  *           INTERNET_ConfigureProxy
617  */
618 static BOOL INTERNET_ConfigureProxy( appinfo_t *lpwai )
619 {
620     proxyinfo_t wpi;
621
622     if (INTERNET_LoadProxySettings( &wpi ))
623         return FALSE;
624
625     if (wpi.proxyEnabled)
626     {
627         WCHAR proxyurl[INTERNET_MAX_URL_LENGTH];
628         WCHAR username[INTERNET_MAX_USER_NAME_LENGTH];
629         WCHAR password[INTERNET_MAX_PASSWORD_LENGTH];
630         WCHAR hostname[INTERNET_MAX_HOST_NAME_LENGTH];
631         URL_COMPONENTSW UrlComponents;
632
633         UrlComponents.dwStructSize = sizeof UrlComponents;
634         UrlComponents.dwSchemeLength = 0;
635         UrlComponents.lpszHostName = hostname;
636         UrlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
637         UrlComponents.lpszUserName = username;
638         UrlComponents.dwUserNameLength = INTERNET_MAX_USER_NAME_LENGTH;
639         UrlComponents.lpszPassword = password;
640         UrlComponents.dwPasswordLength = INTERNET_MAX_PASSWORD_LENGTH;
641         UrlComponents.dwUrlPathLength = 0;
642         UrlComponents.dwExtraInfoLength = 0;
643
644         if(InternetCrackUrlW(wpi.proxy, 0, 0, &UrlComponents))
645         {
646             static const WCHAR szFormat[] = { 'h','t','t','p',':','/','/','%','s',':','%','u',0 };
647
648             if(UrlComponents.nPort == INTERNET_INVALID_PORT_NUMBER)
649                 UrlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
650             sprintfW(proxyurl, szFormat, hostname, UrlComponents.nPort);
651
652             lpwai->accessType = INTERNET_OPEN_TYPE_PROXY;
653             lpwai->proxy = heap_strdupW(proxyurl);
654             if (UrlComponents.dwUserNameLength)
655             {
656                 lpwai->proxyUsername = heap_strdupW(UrlComponents.lpszUserName);
657                 lpwai->proxyPassword = heap_strdupW(UrlComponents.lpszPassword);
658             }
659
660             TRACE("http proxy = %s\n", debugstr_w(lpwai->proxy));
661             return TRUE;
662         }
663         else
664         {
665             TRACE("Failed to parse proxy: %s\n", debugstr_w(wpi.proxy));
666             lpwai->proxy = NULL;
667         }
668     }
669
670     lpwai->accessType = INTERNET_OPEN_TYPE_DIRECT;
671     return FALSE;
672 }
673
674 /***********************************************************************
675  *           dump_INTERNET_FLAGS
676  *
677  * Helper function to TRACE the internet flags.
678  *
679  * RETURNS
680  *    None
681  *
682  */
683 static void dump_INTERNET_FLAGS(DWORD dwFlags) 
684 {
685 #define FE(x) { x, #x }
686     static const wininet_flag_info flag[] = {
687         FE(INTERNET_FLAG_RELOAD),
688         FE(INTERNET_FLAG_RAW_DATA),
689         FE(INTERNET_FLAG_EXISTING_CONNECT),
690         FE(INTERNET_FLAG_ASYNC),
691         FE(INTERNET_FLAG_PASSIVE),
692         FE(INTERNET_FLAG_NO_CACHE_WRITE),
693         FE(INTERNET_FLAG_MAKE_PERSISTENT),
694         FE(INTERNET_FLAG_FROM_CACHE),
695         FE(INTERNET_FLAG_SECURE),
696         FE(INTERNET_FLAG_KEEP_CONNECTION),
697         FE(INTERNET_FLAG_NO_AUTO_REDIRECT),
698         FE(INTERNET_FLAG_READ_PREFETCH),
699         FE(INTERNET_FLAG_NO_COOKIES),
700         FE(INTERNET_FLAG_NO_AUTH),
701         FE(INTERNET_FLAG_CACHE_IF_NET_FAIL),
702         FE(INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP),
703         FE(INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS),
704         FE(INTERNET_FLAG_IGNORE_CERT_DATE_INVALID),
705         FE(INTERNET_FLAG_IGNORE_CERT_CN_INVALID),
706         FE(INTERNET_FLAG_RESYNCHRONIZE),
707         FE(INTERNET_FLAG_HYPERLINK),
708         FE(INTERNET_FLAG_NO_UI),
709         FE(INTERNET_FLAG_PRAGMA_NOCACHE),
710         FE(INTERNET_FLAG_CACHE_ASYNC),
711         FE(INTERNET_FLAG_FORMS_SUBMIT),
712         FE(INTERNET_FLAG_NEED_FILE),
713         FE(INTERNET_FLAG_TRANSFER_ASCII),
714         FE(INTERNET_FLAG_TRANSFER_BINARY)
715     };
716 #undef FE
717     unsigned int i;
718
719     for (i = 0; i < (sizeof(flag) / sizeof(flag[0])); i++) {
720         if (flag[i].val & dwFlags) {
721             TRACE(" %s", flag[i].name);
722             dwFlags &= ~flag[i].val;
723         }
724     }   
725     if (dwFlags)
726         TRACE(" Unknown flags (%08x)\n", dwFlags);
727     else
728         TRACE("\n");
729 }
730
731 /***********************************************************************
732  *           INTERNET_CloseHandle (internal)
733  *
734  * Close internet handle
735  *
736  */
737 static VOID APPINFO_Destroy(object_header_t *hdr)
738 {
739     appinfo_t *lpwai = (appinfo_t*)hdr;
740
741     TRACE("%p\n",lpwai);
742
743     heap_free(lpwai->agent);
744     heap_free(lpwai->proxy);
745     heap_free(lpwai->proxyBypass);
746     heap_free(lpwai->proxyUsername);
747     heap_free(lpwai->proxyPassword);
748 }
749
750 static DWORD APPINFO_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
751 {
752     appinfo_t *ai = (appinfo_t*)hdr;
753
754     switch(option) {
755     case INTERNET_OPTION_HANDLE_TYPE:
756         TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
757
758         if (*size < sizeof(ULONG))
759             return ERROR_INSUFFICIENT_BUFFER;
760
761         *size = sizeof(DWORD);
762         *(DWORD*)buffer = INTERNET_HANDLE_TYPE_INTERNET;
763         return ERROR_SUCCESS;
764
765     case INTERNET_OPTION_USER_AGENT: {
766         DWORD bufsize;
767
768         TRACE("INTERNET_OPTION_USER_AGENT\n");
769
770         bufsize = *size;
771
772         if (unicode) {
773             DWORD len = ai->agent ? strlenW(ai->agent) : 0;
774
775             *size = (len + 1) * sizeof(WCHAR);
776             if(!buffer || bufsize < *size)
777                 return ERROR_INSUFFICIENT_BUFFER;
778
779             if (ai->agent)
780                 strcpyW(buffer, ai->agent);
781             else
782                 *(WCHAR *)buffer = 0;
783             /* If the buffer is copied, the returned length doesn't include
784              * the NULL terminator.
785              */
786             *size = len * sizeof(WCHAR);
787         }else {
788             if (ai->agent)
789                 *size = WideCharToMultiByte(CP_ACP, 0, ai->agent, -1, NULL, 0, NULL, NULL);
790             else
791                 *size = 1;
792             if(!buffer || bufsize < *size)
793                 return ERROR_INSUFFICIENT_BUFFER;
794
795             if (ai->agent)
796                 WideCharToMultiByte(CP_ACP, 0, ai->agent, -1, buffer, *size, NULL, NULL);
797             else
798                 *(char *)buffer = 0;
799             /* If the buffer is copied, the returned length doesn't include
800              * the NULL terminator.
801              */
802             *size -= 1;
803         }
804
805         return ERROR_SUCCESS;
806     }
807
808     case INTERNET_OPTION_PROXY:
809         if(!size) return ERROR_INVALID_PARAMETER;
810         if (unicode) {
811             INTERNET_PROXY_INFOW *pi = (INTERNET_PROXY_INFOW *)buffer;
812             DWORD proxyBytesRequired = 0, proxyBypassBytesRequired = 0;
813             LPWSTR proxy, proxy_bypass;
814
815             if (ai->proxy)
816                 proxyBytesRequired = (lstrlenW(ai->proxy) + 1) * sizeof(WCHAR);
817             if (ai->proxyBypass)
818                 proxyBypassBytesRequired = (lstrlenW(ai->proxyBypass) + 1) * sizeof(WCHAR);
819             if (*size < sizeof(INTERNET_PROXY_INFOW) + proxyBytesRequired + proxyBypassBytesRequired)
820             {
821                 *size = sizeof(INTERNET_PROXY_INFOW) + proxyBytesRequired + proxyBypassBytesRequired;
822                 return ERROR_INSUFFICIENT_BUFFER;
823             }
824             proxy = (LPWSTR)((LPBYTE)buffer + sizeof(INTERNET_PROXY_INFOW));
825             proxy_bypass = (LPWSTR)((LPBYTE)buffer + sizeof(INTERNET_PROXY_INFOW) + proxyBytesRequired);
826
827             pi->dwAccessType = ai->accessType;
828             pi->lpszProxy = NULL;
829             pi->lpszProxyBypass = NULL;
830             if (ai->proxy) {
831                 lstrcpyW(proxy, ai->proxy);
832                 pi->lpszProxy = proxy;
833             }
834
835             if (ai->proxyBypass) {
836                 lstrcpyW(proxy_bypass, ai->proxyBypass);
837                 pi->lpszProxyBypass = proxy_bypass;
838             }
839
840             *size = sizeof(INTERNET_PROXY_INFOW) + proxyBytesRequired + proxyBypassBytesRequired;
841             return ERROR_SUCCESS;
842         }else {
843             INTERNET_PROXY_INFOA *pi = (INTERNET_PROXY_INFOA *)buffer;
844             DWORD proxyBytesRequired = 0, proxyBypassBytesRequired = 0;
845             LPSTR proxy, proxy_bypass;
846
847             if (ai->proxy)
848                 proxyBytesRequired = WideCharToMultiByte(CP_ACP, 0, ai->proxy, -1, NULL, 0, NULL, NULL);
849             if (ai->proxyBypass)
850                 proxyBypassBytesRequired = WideCharToMultiByte(CP_ACP, 0, ai->proxyBypass, -1,
851                         NULL, 0, NULL, NULL);
852             if (*size < sizeof(INTERNET_PROXY_INFOA) + proxyBytesRequired + proxyBypassBytesRequired)
853             {
854                 *size = sizeof(INTERNET_PROXY_INFOA) + proxyBytesRequired + proxyBypassBytesRequired;
855                 return ERROR_INSUFFICIENT_BUFFER;
856             }
857             proxy = (LPSTR)((LPBYTE)buffer + sizeof(INTERNET_PROXY_INFOA));
858             proxy_bypass = (LPSTR)((LPBYTE)buffer + sizeof(INTERNET_PROXY_INFOA) + proxyBytesRequired);
859
860             pi->dwAccessType = ai->accessType;
861             pi->lpszProxy = NULL;
862             pi->lpszProxyBypass = NULL;
863             if (ai->proxy) {
864                 WideCharToMultiByte(CP_ACP, 0, ai->proxy, -1, proxy, proxyBytesRequired, NULL, NULL);
865                 pi->lpszProxy = proxy;
866             }
867
868             if (ai->proxyBypass) {
869                 WideCharToMultiByte(CP_ACP, 0, ai->proxyBypass, -1, proxy_bypass,
870                         proxyBypassBytesRequired, NULL, NULL);
871                 pi->lpszProxyBypass = proxy_bypass;
872             }
873
874             *size = sizeof(INTERNET_PROXY_INFOA) + proxyBytesRequired + proxyBypassBytesRequired;
875             return ERROR_SUCCESS;
876         }
877     }
878
879     return INET_QueryOption(hdr, option, buffer, size, unicode);
880 }
881
882 static const object_vtbl_t APPINFOVtbl = {
883     APPINFO_Destroy,
884     NULL,
885     APPINFO_QueryOption,
886     INET_SetOption,
887     NULL,
888     NULL,
889     NULL,
890     NULL,
891     NULL
892 };
893
894
895 /***********************************************************************
896  *           InternetOpenW   (WININET.@)
897  *
898  * Per-application initialization of wininet
899  *
900  * RETURNS
901  *    HINTERNET on success
902  *    NULL on failure
903  *
904  */
905 HINTERNET WINAPI InternetOpenW(LPCWSTR lpszAgent, DWORD dwAccessType,
906     LPCWSTR lpszProxy, LPCWSTR lpszProxyBypass, DWORD dwFlags)
907 {
908     appinfo_t *lpwai = NULL;
909
910     if (TRACE_ON(wininet)) {
911 #define FE(x) { x, #x }
912         static const wininet_flag_info access_type[] = {
913             FE(INTERNET_OPEN_TYPE_PRECONFIG),
914             FE(INTERNET_OPEN_TYPE_DIRECT),
915             FE(INTERNET_OPEN_TYPE_PROXY),
916             FE(INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY)
917         };
918 #undef FE
919         DWORD i;
920         const char *access_type_str = "Unknown";
921         
922         TRACE("(%s, %i, %s, %s, %i)\n", debugstr_w(lpszAgent), dwAccessType,
923               debugstr_w(lpszProxy), debugstr_w(lpszProxyBypass), dwFlags);
924         for (i = 0; i < (sizeof(access_type) / sizeof(access_type[0])); i++) {
925             if (access_type[i].val == dwAccessType) {
926                 access_type_str = access_type[i].name;
927                 break;
928             }
929         }
930         TRACE("  access type : %s\n", access_type_str);
931         TRACE("  flags       :");
932         dump_INTERNET_FLAGS(dwFlags);
933     }
934
935     /* Clear any error information */
936     INTERNET_SetLastError(0);
937
938     lpwai = alloc_object(NULL, &APPINFOVtbl, sizeof(appinfo_t));
939     if (!lpwai) {
940         SetLastError(ERROR_OUTOFMEMORY);
941         return NULL;
942     }
943
944     lpwai->hdr.htype = WH_HINIT;
945     lpwai->hdr.dwFlags = dwFlags;
946     lpwai->accessType = dwAccessType;
947     lpwai->proxyUsername = NULL;
948     lpwai->proxyPassword = NULL;
949
950     lpwai->agent = heap_strdupW(lpszAgent);
951     if(dwAccessType == INTERNET_OPEN_TYPE_PRECONFIG)
952         INTERNET_ConfigureProxy( lpwai );
953     else
954         lpwai->proxy = heap_strdupW(lpszProxy);
955     lpwai->proxyBypass = heap_strdupW(lpszProxyBypass);
956
957     TRACE("returning %p\n", lpwai);
958
959     return lpwai->hdr.hInternet;
960 }
961
962
963 /***********************************************************************
964  *           InternetOpenA   (WININET.@)
965  *
966  * Per-application initialization of wininet
967  *
968  * RETURNS
969  *    HINTERNET on success
970  *    NULL on failure
971  *
972  */
973 HINTERNET WINAPI InternetOpenA(LPCSTR lpszAgent, DWORD dwAccessType,
974     LPCSTR lpszProxy, LPCSTR lpszProxyBypass, DWORD dwFlags)
975 {
976     WCHAR *szAgent, *szProxy, *szBypass;
977     HINTERNET rc;
978
979     TRACE("(%s, 0x%08x, %s, %s, 0x%08x)\n", debugstr_a(lpszAgent),
980        dwAccessType, debugstr_a(lpszProxy), debugstr_a(lpszProxyBypass), dwFlags);
981
982     szAgent = heap_strdupAtoW(lpszAgent);
983     szProxy = heap_strdupAtoW(lpszProxy);
984     szBypass = heap_strdupAtoW(lpszProxyBypass);
985
986     rc = InternetOpenW(szAgent, dwAccessType, szProxy, szBypass, dwFlags);
987
988     heap_free(szAgent);
989     heap_free(szProxy);
990     heap_free(szBypass);
991     return rc;
992 }
993
994 /***********************************************************************
995  *           InternetGetLastResponseInfoA (WININET.@)
996  *
997  * Return last wininet error description on the calling thread
998  *
999  * RETURNS
1000  *    TRUE on success of writing to buffer
1001  *    FALSE on failure
1002  *
1003  */
1004 BOOL WINAPI InternetGetLastResponseInfoA(LPDWORD lpdwError,
1005     LPSTR lpszBuffer, LPDWORD lpdwBufferLength)
1006 {
1007     LPWITHREADERROR lpwite = TlsGetValue(g_dwTlsErrIndex);
1008
1009     TRACE("\n");
1010
1011     if (lpwite)
1012     {
1013         *lpdwError = lpwite->dwError;
1014         if (lpwite->dwError)
1015         {
1016             memcpy(lpszBuffer, lpwite->response, *lpdwBufferLength);
1017             *lpdwBufferLength = strlen(lpszBuffer);
1018         }
1019         else
1020             *lpdwBufferLength = 0;
1021     }
1022     else
1023     {
1024         *lpdwError = 0;
1025         *lpdwBufferLength = 0;
1026     }
1027
1028     return TRUE;
1029 }
1030
1031 /***********************************************************************
1032  *           InternetGetLastResponseInfoW (WININET.@)
1033  *
1034  * Return last wininet error description on the calling thread
1035  *
1036  * RETURNS
1037  *    TRUE on success of writing to buffer
1038  *    FALSE on failure
1039  *
1040  */
1041 BOOL WINAPI InternetGetLastResponseInfoW(LPDWORD lpdwError,
1042     LPWSTR lpszBuffer, LPDWORD lpdwBufferLength)
1043 {
1044     LPWITHREADERROR lpwite = TlsGetValue(g_dwTlsErrIndex);
1045
1046     TRACE("\n");
1047
1048     if (lpwite)
1049     {
1050         *lpdwError = lpwite->dwError;
1051         if (lpwite->dwError)
1052         {
1053             memcpy(lpszBuffer, lpwite->response, *lpdwBufferLength);
1054             *lpdwBufferLength = lstrlenW(lpszBuffer);
1055         }
1056         else
1057             *lpdwBufferLength = 0;
1058     }
1059     else
1060     {
1061         *lpdwError = 0;
1062         *lpdwBufferLength = 0;
1063     }
1064
1065     return TRUE;
1066 }
1067
1068 /***********************************************************************
1069  *           InternetGetConnectedState (WININET.@)
1070  *
1071  * Return connected state
1072  *
1073  * RETURNS
1074  *    TRUE if connected
1075  *    if lpdwStatus is not null, return the status (off line,
1076  *    modem, lan...) in it.
1077  *    FALSE if not connected
1078  */
1079 BOOL WINAPI InternetGetConnectedState(LPDWORD lpdwStatus, DWORD dwReserved)
1080 {
1081     TRACE("(%p, 0x%08x)\n", lpdwStatus, dwReserved);
1082
1083     if (lpdwStatus) {
1084         WARN("always returning LAN connection.\n");
1085         *lpdwStatus = INTERNET_CONNECTION_LAN;
1086     }
1087     return TRUE;
1088 }
1089
1090
1091 /***********************************************************************
1092  *           InternetGetConnectedStateExW (WININET.@)
1093  *
1094  * Return connected state
1095  *
1096  * PARAMS
1097  *
1098  * lpdwStatus         [O] Flags specifying the status of the internet connection.
1099  * lpszConnectionName [O] Pointer to buffer to receive the friendly name of the internet connection.
1100  * dwNameLen          [I] Size of the buffer, in characters.
1101  * dwReserved         [I] Reserved. Must be set to 0.
1102  *
1103  * RETURNS
1104  *    TRUE if connected
1105  *    if lpdwStatus is not null, return the status (off line,
1106  *    modem, lan...) in it.
1107  *    FALSE if not connected
1108  *
1109  * NOTES
1110  *   If the system has no available network connections, an empty string is
1111  *   stored in lpszConnectionName. If there is a LAN connection, a localized
1112  *   "LAN Connection" string is stored. Presumably, if only a dial-up
1113  *   connection is available then the name of the dial-up connection is
1114  *   returned. Why any application, other than the "Internet Settings" CPL,
1115  *   would want to use this function instead of the simpler InternetGetConnectedStateW
1116  *   function is beyond me.
1117  */
1118 BOOL WINAPI InternetGetConnectedStateExW(LPDWORD lpdwStatus, LPWSTR lpszConnectionName,
1119                                          DWORD dwNameLen, DWORD dwReserved)
1120 {
1121     TRACE("(%p, %p, %d, 0x%08x)\n", lpdwStatus, lpszConnectionName, dwNameLen, dwReserved);
1122
1123     /* Must be zero */
1124     if(dwReserved)
1125         return FALSE;
1126
1127     if (lpdwStatus) {
1128         WARN("always returning LAN connection.\n");
1129         *lpdwStatus = INTERNET_CONNECTION_LAN;
1130     }
1131     return LoadStringW(WININET_hModule, IDS_LANCONNECTION, lpszConnectionName, dwNameLen);
1132 }
1133
1134
1135 /***********************************************************************
1136  *           InternetGetConnectedStateExA (WININET.@)
1137  */
1138 BOOL WINAPI InternetGetConnectedStateExA(LPDWORD lpdwStatus, LPSTR lpszConnectionName,
1139                                          DWORD dwNameLen, DWORD dwReserved)
1140 {
1141     LPWSTR lpwszConnectionName = NULL;
1142     BOOL rc;
1143
1144     TRACE("(%p, %p, %d, 0x%08x)\n", lpdwStatus, lpszConnectionName, dwNameLen, dwReserved);
1145
1146     if (lpszConnectionName && dwNameLen > 0)
1147         lpwszConnectionName = heap_alloc(dwNameLen * sizeof(WCHAR));
1148
1149     rc = InternetGetConnectedStateExW(lpdwStatus,lpwszConnectionName, dwNameLen,
1150                                       dwReserved);
1151     if (rc && lpwszConnectionName)
1152     {
1153         WideCharToMultiByte(CP_ACP,0,lpwszConnectionName,-1,lpszConnectionName,
1154                             dwNameLen, NULL, NULL);
1155         heap_free(lpwszConnectionName);
1156     }
1157     return rc;
1158 }
1159
1160
1161 /***********************************************************************
1162  *           InternetConnectW (WININET.@)
1163  *
1164  * Open a ftp, gopher or http session
1165  *
1166  * RETURNS
1167  *    HINTERNET a session handle on success
1168  *    NULL on failure
1169  *
1170  */
1171 HINTERNET WINAPI InternetConnectW(HINTERNET hInternet,
1172     LPCWSTR lpszServerName, INTERNET_PORT nServerPort,
1173     LPCWSTR lpszUserName, LPCWSTR lpszPassword,
1174     DWORD dwService, DWORD dwFlags, DWORD_PTR dwContext)
1175 {
1176     appinfo_t *hIC;
1177     HINTERNET rc = NULL;
1178     DWORD res = ERROR_SUCCESS;
1179
1180     TRACE("(%p, %s, %i, %s, %s, %i, %i, %lx)\n", hInternet, debugstr_w(lpszServerName),
1181           nServerPort, debugstr_w(lpszUserName), debugstr_w(lpszPassword),
1182           dwService, dwFlags, dwContext);
1183
1184     if (!lpszServerName)
1185     {
1186         SetLastError(ERROR_INVALID_PARAMETER);
1187         return NULL;
1188     }
1189
1190     hIC = (appinfo_t*)get_handle_object( hInternet );
1191     if ( (hIC == NULL) || (hIC->hdr.htype != WH_HINIT) )
1192     {
1193         res = ERROR_INVALID_HANDLE;
1194         goto lend;
1195     }
1196
1197     switch (dwService)
1198     {
1199         case INTERNET_SERVICE_FTP:
1200             rc = FTP_Connect(hIC, lpszServerName, nServerPort,
1201             lpszUserName, lpszPassword, dwFlags, dwContext, 0);
1202             if(!rc)
1203                 res = INTERNET_GetLastError();
1204             break;
1205
1206         case INTERNET_SERVICE_HTTP:
1207             res = HTTP_Connect(hIC, lpszServerName, nServerPort,
1208                     lpszUserName, lpszPassword, dwFlags, dwContext, 0, &rc);
1209             break;
1210
1211         case INTERNET_SERVICE_GOPHER:
1212         default:
1213             break;
1214     }
1215 lend:
1216     if( hIC )
1217         WININET_Release( &hIC->hdr );
1218
1219     TRACE("returning %p\n", rc);
1220     SetLastError(res);
1221     return rc;
1222 }
1223
1224
1225 /***********************************************************************
1226  *           InternetConnectA (WININET.@)
1227  *
1228  * Open a ftp, gopher or http session
1229  *
1230  * RETURNS
1231  *    HINTERNET a session handle on success
1232  *    NULL on failure
1233  *
1234  */
1235 HINTERNET WINAPI InternetConnectA(HINTERNET hInternet,
1236     LPCSTR lpszServerName, INTERNET_PORT nServerPort,
1237     LPCSTR lpszUserName, LPCSTR lpszPassword,
1238     DWORD dwService, DWORD dwFlags, DWORD_PTR dwContext)
1239 {
1240     HINTERNET rc = NULL;
1241     LPWSTR szServerName;
1242     LPWSTR szUserName;
1243     LPWSTR szPassword;
1244
1245     szServerName = heap_strdupAtoW(lpszServerName);
1246     szUserName = heap_strdupAtoW(lpszUserName);
1247     szPassword = heap_strdupAtoW(lpszPassword);
1248
1249     rc = InternetConnectW(hInternet, szServerName, nServerPort,
1250         szUserName, szPassword, dwService, dwFlags, dwContext);
1251
1252     heap_free(szServerName);
1253     heap_free(szUserName);
1254     heap_free(szPassword);
1255     return rc;
1256 }
1257
1258
1259 /***********************************************************************
1260  *           InternetFindNextFileA (WININET.@)
1261  *
1262  * Continues a file search from a previous call to FindFirstFile
1263  *
1264  * RETURNS
1265  *    TRUE on success
1266  *    FALSE on failure
1267  *
1268  */
1269 BOOL WINAPI InternetFindNextFileA(HINTERNET hFind, LPVOID lpvFindData)
1270 {
1271     BOOL ret;
1272     WIN32_FIND_DATAW fd;
1273     
1274     ret = InternetFindNextFileW(hFind, lpvFindData?&fd:NULL);
1275     if(lpvFindData)
1276         WININET_find_data_WtoA(&fd, (LPWIN32_FIND_DATAA)lpvFindData);
1277     return ret;
1278 }
1279
1280 /***********************************************************************
1281  *           InternetFindNextFileW (WININET.@)
1282  *
1283  * Continues a file search from a previous call to FindFirstFile
1284  *
1285  * RETURNS
1286  *    TRUE on success
1287  *    FALSE on failure
1288  *
1289  */
1290 BOOL WINAPI InternetFindNextFileW(HINTERNET hFind, LPVOID lpvFindData)
1291 {
1292     object_header_t *hdr;
1293     DWORD res;
1294
1295     TRACE("\n");
1296
1297     hdr = get_handle_object(hFind);
1298     if(!hdr) {
1299         WARN("Invalid handle\n");
1300         SetLastError(ERROR_INVALID_HANDLE);
1301         return FALSE;
1302     }
1303
1304     if(hdr->vtbl->FindNextFileW) {
1305         res = hdr->vtbl->FindNextFileW(hdr, lpvFindData);
1306     }else {
1307         WARN("Handle doesn't support NextFile\n");
1308         res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
1309     }
1310
1311     WININET_Release(hdr);
1312
1313     if(res != ERROR_SUCCESS)
1314         SetLastError(res);
1315     return res == ERROR_SUCCESS;
1316 }
1317
1318 /***********************************************************************
1319  *           InternetCloseHandle (WININET.@)
1320  *
1321  * Generic close handle function
1322  *
1323  * RETURNS
1324  *    TRUE on success
1325  *    FALSE on failure
1326  *
1327  */
1328 BOOL WINAPI InternetCloseHandle(HINTERNET hInternet)
1329 {
1330     object_header_t *obj;
1331     
1332     TRACE("%p\n", hInternet);
1333
1334     obj = get_handle_object( hInternet );
1335     if (!obj) {
1336         SetLastError(ERROR_INVALID_HANDLE);
1337         return FALSE;
1338     }
1339
1340     invalidate_handle(obj);
1341     WININET_Release(obj);
1342
1343     return TRUE;
1344 }
1345
1346
1347 /***********************************************************************
1348  *           ConvertUrlComponentValue (Internal)
1349  *
1350  * Helper function for InternetCrackUrlA
1351  *
1352  */
1353 static void ConvertUrlComponentValue(LPSTR* lppszComponent, LPDWORD dwComponentLen,
1354                                      LPWSTR lpwszComponent, DWORD dwwComponentLen,
1355                                      LPCSTR lpszStart, LPCWSTR lpwszStart)
1356 {
1357     TRACE("%p %d %p %d %p %p\n", *lppszComponent, *dwComponentLen, lpwszComponent, dwwComponentLen, lpszStart, lpwszStart);
1358     if (*dwComponentLen != 0)
1359     {
1360         DWORD nASCIILength=WideCharToMultiByte(CP_ACP,0,lpwszComponent,dwwComponentLen,NULL,0,NULL,NULL);
1361         if (*lppszComponent == NULL)
1362         {
1363             if (lpwszComponent)
1364             {
1365                 int offset = WideCharToMultiByte(CP_ACP, 0, lpwszStart, lpwszComponent-lpwszStart, NULL, 0, NULL, NULL);
1366                 *lppszComponent = (LPSTR)lpszStart + offset;
1367             }
1368             else
1369                 *lppszComponent = NULL;
1370
1371             *dwComponentLen = nASCIILength;
1372         }
1373         else
1374         {
1375             DWORD ncpylen = min((*dwComponentLen)-1, nASCIILength);
1376             WideCharToMultiByte(CP_ACP,0,lpwszComponent,dwwComponentLen,*lppszComponent,ncpylen+1,NULL,NULL);
1377             (*lppszComponent)[ncpylen]=0;
1378             *dwComponentLen = ncpylen;
1379         }
1380     }
1381 }
1382
1383
1384 /***********************************************************************
1385  *           InternetCrackUrlA (WININET.@)
1386  *
1387  * See InternetCrackUrlW.
1388  */
1389 BOOL WINAPI InternetCrackUrlA(LPCSTR lpszUrl, DWORD dwUrlLength, DWORD dwFlags,
1390     LPURL_COMPONENTSA lpUrlComponents)
1391 {
1392   DWORD nLength;
1393   URL_COMPONENTSW UCW;
1394   BOOL ret = FALSE;
1395   WCHAR *lpwszUrl, *hostname = NULL, *username = NULL, *password = NULL, *path = NULL,
1396         *scheme = NULL, *extra = NULL;
1397
1398   TRACE("(%s %u %x %p)\n",
1399         lpszUrl ? debugstr_an(lpszUrl, dwUrlLength ? dwUrlLength : strlen(lpszUrl)) : "(null)",
1400         dwUrlLength, dwFlags, lpUrlComponents);
1401
1402   if (!lpszUrl || !*lpszUrl || !lpUrlComponents ||
1403           lpUrlComponents->dwStructSize != sizeof(URL_COMPONENTSA))
1404   {
1405       INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1406       return FALSE;
1407   }
1408
1409   if(dwUrlLength<=0)
1410       dwUrlLength=-1;
1411   nLength=MultiByteToWideChar(CP_ACP,0,lpszUrl,dwUrlLength,NULL,0);
1412
1413   /* if dwUrlLength=-1 then nLength includes null but length to 
1414        InternetCrackUrlW should not include it                  */
1415   if (dwUrlLength == -1) nLength--;
1416
1417   lpwszUrl = heap_alloc((nLength + 1) * sizeof(WCHAR));
1418   MultiByteToWideChar(CP_ACP,0,lpszUrl,dwUrlLength,lpwszUrl,nLength + 1);
1419   lpwszUrl[nLength] = '\0';
1420
1421   memset(&UCW,0,sizeof(UCW));
1422   UCW.dwStructSize = sizeof(URL_COMPONENTSW);
1423   if (lpUrlComponents->dwHostNameLength)
1424   {
1425     UCW.dwHostNameLength = lpUrlComponents->dwHostNameLength;
1426     if (lpUrlComponents->lpszHostName)
1427     {
1428       hostname = heap_alloc(UCW.dwHostNameLength * sizeof(WCHAR));
1429       UCW.lpszHostName = hostname;
1430     }
1431   }
1432   if (lpUrlComponents->dwUserNameLength)
1433   {
1434     UCW.dwUserNameLength = lpUrlComponents->dwUserNameLength;
1435     if (lpUrlComponents->lpszUserName)
1436     {
1437       username = heap_alloc(UCW.dwUserNameLength * sizeof(WCHAR));
1438       UCW.lpszUserName = username;
1439     }
1440   }
1441   if (lpUrlComponents->dwPasswordLength)
1442   {
1443     UCW.dwPasswordLength = lpUrlComponents->dwPasswordLength;
1444     if (lpUrlComponents->lpszPassword)
1445     {
1446       password = heap_alloc(UCW.dwPasswordLength * sizeof(WCHAR));
1447       UCW.lpszPassword = password;
1448     }
1449   }
1450   if (lpUrlComponents->dwUrlPathLength)
1451   {
1452     UCW.dwUrlPathLength = lpUrlComponents->dwUrlPathLength;
1453     if (lpUrlComponents->lpszUrlPath)
1454     {
1455       path = heap_alloc(UCW.dwUrlPathLength * sizeof(WCHAR));
1456       UCW.lpszUrlPath = path;
1457     }
1458   }
1459   if (lpUrlComponents->dwSchemeLength)
1460   {
1461     UCW.dwSchemeLength = lpUrlComponents->dwSchemeLength;
1462     if (lpUrlComponents->lpszScheme)
1463     {
1464       scheme = heap_alloc(UCW.dwSchemeLength * sizeof(WCHAR));
1465       UCW.lpszScheme = scheme;
1466     }
1467   }
1468   if (lpUrlComponents->dwExtraInfoLength)
1469   {
1470     UCW.dwExtraInfoLength = lpUrlComponents->dwExtraInfoLength;
1471     if (lpUrlComponents->lpszExtraInfo)
1472     {
1473       extra = heap_alloc(UCW.dwExtraInfoLength * sizeof(WCHAR));
1474       UCW.lpszExtraInfo = extra;
1475     }
1476   }
1477   if ((ret = InternetCrackUrlW(lpwszUrl, nLength, dwFlags, &UCW)))
1478   {
1479     ConvertUrlComponentValue(&lpUrlComponents->lpszHostName, &lpUrlComponents->dwHostNameLength,
1480                              UCW.lpszHostName, UCW.dwHostNameLength, lpszUrl, lpwszUrl);
1481     ConvertUrlComponentValue(&lpUrlComponents->lpszUserName, &lpUrlComponents->dwUserNameLength,
1482                              UCW.lpszUserName, UCW.dwUserNameLength, lpszUrl, lpwszUrl);
1483     ConvertUrlComponentValue(&lpUrlComponents->lpszPassword, &lpUrlComponents->dwPasswordLength,
1484                              UCW.lpszPassword, UCW.dwPasswordLength, lpszUrl, lpwszUrl);
1485     ConvertUrlComponentValue(&lpUrlComponents->lpszUrlPath, &lpUrlComponents->dwUrlPathLength,
1486                              UCW.lpszUrlPath, UCW.dwUrlPathLength, lpszUrl, lpwszUrl);
1487     ConvertUrlComponentValue(&lpUrlComponents->lpszScheme, &lpUrlComponents->dwSchemeLength,
1488                              UCW.lpszScheme, UCW.dwSchemeLength, lpszUrl, lpwszUrl);
1489     ConvertUrlComponentValue(&lpUrlComponents->lpszExtraInfo, &lpUrlComponents->dwExtraInfoLength,
1490                              UCW.lpszExtraInfo, UCW.dwExtraInfoLength, lpszUrl, lpwszUrl);
1491
1492     lpUrlComponents->nScheme = UCW.nScheme;
1493     lpUrlComponents->nPort = UCW.nPort;
1494
1495     TRACE("%s: scheme(%s) host(%s) path(%s) extra(%s)\n", debugstr_a(lpszUrl),
1496           debugstr_an(lpUrlComponents->lpszScheme, lpUrlComponents->dwSchemeLength),
1497           debugstr_an(lpUrlComponents->lpszHostName, lpUrlComponents->dwHostNameLength),
1498           debugstr_an(lpUrlComponents->lpszUrlPath, lpUrlComponents->dwUrlPathLength),
1499           debugstr_an(lpUrlComponents->lpszExtraInfo, lpUrlComponents->dwExtraInfoLength));
1500   }
1501   heap_free(lpwszUrl);
1502   heap_free(hostname);
1503   heap_free(username);
1504   heap_free(password);
1505   heap_free(path);
1506   heap_free(scheme);
1507   heap_free(extra);
1508   return ret;
1509 }
1510
1511 static const WCHAR url_schemes[][7] =
1512 {
1513     {'f','t','p',0},
1514     {'g','o','p','h','e','r',0},
1515     {'h','t','t','p',0},
1516     {'h','t','t','p','s',0},
1517     {'f','i','l','e',0},
1518     {'n','e','w','s',0},
1519     {'m','a','i','l','t','o',0},
1520     {'r','e','s',0},
1521 };
1522
1523 /***********************************************************************
1524  *           GetInternetSchemeW (internal)
1525  *
1526  * Get scheme of url
1527  *
1528  * RETURNS
1529  *    scheme on success
1530  *    INTERNET_SCHEME_UNKNOWN on failure
1531  *
1532  */
1533 static INTERNET_SCHEME GetInternetSchemeW(LPCWSTR lpszScheme, DWORD nMaxCmp)
1534 {
1535     int i;
1536
1537     TRACE("%s %d\n",debugstr_wn(lpszScheme, nMaxCmp), nMaxCmp);
1538
1539     if(lpszScheme==NULL)
1540         return INTERNET_SCHEME_UNKNOWN;
1541
1542     for (i = 0; i < sizeof(url_schemes)/sizeof(url_schemes[0]); i++)
1543         if (!strncmpW(lpszScheme, url_schemes[i], nMaxCmp))
1544             return INTERNET_SCHEME_FIRST + i;
1545
1546     return INTERNET_SCHEME_UNKNOWN;
1547 }
1548
1549 /***********************************************************************
1550  *           SetUrlComponentValueW (Internal)
1551  *
1552  * Helper function for InternetCrackUrlW
1553  *
1554  * PARAMS
1555  *     lppszComponent [O] Holds the returned string
1556  *     dwComponentLen [I] Holds the size of lppszComponent
1557  *                    [O] Holds the length of the string in lppszComponent without '\0'
1558  *     lpszStart      [I] Holds the string to copy from
1559  *     len            [I] Holds the length of lpszStart without '\0'
1560  *
1561  * RETURNS
1562  *    TRUE on success
1563  *    FALSE on failure
1564  *
1565  */
1566 static BOOL SetUrlComponentValueW(LPWSTR* lppszComponent, LPDWORD dwComponentLen, LPCWSTR lpszStart, DWORD len)
1567 {
1568     TRACE("%s (%d)\n", debugstr_wn(lpszStart,len), len);
1569
1570     if ( (*dwComponentLen == 0) && (*lppszComponent == NULL) )
1571         return FALSE;
1572
1573     if (*dwComponentLen != 0 || *lppszComponent == NULL)
1574     {
1575         if (*lppszComponent == NULL)
1576         {
1577             *lppszComponent = (LPWSTR)lpszStart;
1578             *dwComponentLen = len;
1579         }
1580         else
1581         {
1582             DWORD ncpylen = min((*dwComponentLen)-1, len);
1583             memcpy(*lppszComponent, lpszStart, ncpylen*sizeof(WCHAR));
1584             (*lppszComponent)[ncpylen] = '\0';
1585             *dwComponentLen = ncpylen;
1586         }
1587     }
1588
1589     return TRUE;
1590 }
1591
1592 /***********************************************************************
1593  *           InternetCrackUrlW   (WININET.@)
1594  *
1595  * Break up URL into its components
1596  *
1597  * RETURNS
1598  *    TRUE on success
1599  *    FALSE on failure
1600  */
1601 BOOL WINAPI InternetCrackUrlW(LPCWSTR lpszUrl_orig, DWORD dwUrlLength_orig, DWORD dwFlags,
1602                               LPURL_COMPONENTSW lpUC)
1603 {
1604   /*
1605    * RFC 1808
1606    * <protocol>:[//<net_loc>][/path][;<params>][?<query>][#<fragment>]
1607    *
1608    */
1609     LPCWSTR lpszParam    = NULL;
1610     BOOL  bIsAbsolute = FALSE;
1611     LPCWSTR lpszap, lpszUrl = lpszUrl_orig;
1612     LPCWSTR lpszcp = NULL;
1613     LPWSTR  lpszUrl_decode = NULL;
1614     DWORD dwUrlLength = dwUrlLength_orig;
1615
1616     TRACE("(%s %u %x %p)\n",
1617           lpszUrl ? debugstr_wn(lpszUrl, dwUrlLength ? dwUrlLength : strlenW(lpszUrl)) : "(null)",
1618           dwUrlLength, dwFlags, lpUC);
1619
1620     if (!lpszUrl_orig || !*lpszUrl_orig || !lpUC)
1621     {
1622         INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1623         return FALSE;
1624     }
1625     if (!dwUrlLength) dwUrlLength = strlenW(lpszUrl);
1626
1627     if (dwFlags & ICU_DECODE)
1628     {
1629         WCHAR *url_tmp;
1630         DWORD len = dwUrlLength + 1;
1631
1632         if (!(url_tmp = heap_alloc(len * sizeof(WCHAR))))
1633         {
1634             INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1635             return FALSE;
1636         }
1637         memcpy(url_tmp, lpszUrl_orig, dwUrlLength * sizeof(WCHAR));
1638         url_tmp[dwUrlLength] = 0;
1639         if (!(lpszUrl_decode = heap_alloc(len * sizeof(WCHAR))))
1640         {
1641             heap_free(url_tmp);
1642             INTERNET_SetLastError(ERROR_OUTOFMEMORY);
1643             return FALSE;
1644         }
1645         if (InternetCanonicalizeUrlW(url_tmp, lpszUrl_decode, &len, ICU_DECODE | ICU_NO_ENCODE))
1646         {
1647             dwUrlLength = len;
1648             lpszUrl = lpszUrl_decode;
1649         }
1650         heap_free(url_tmp);
1651     }
1652     lpszap = lpszUrl;
1653     
1654     /* Determine if the URI is absolute. */
1655     while (lpszap - lpszUrl < dwUrlLength)
1656     {
1657         if (isalnumW(*lpszap) || *lpszap == '+' || *lpszap == '.' || *lpszap == '-')
1658         {
1659             lpszap++;
1660             continue;
1661         }
1662         if ((*lpszap == ':') && (lpszap - lpszUrl >= 2))
1663         {
1664             bIsAbsolute = TRUE;
1665             lpszcp = lpszap;
1666         }
1667         else
1668         {
1669             lpszcp = lpszUrl; /* Relative url */
1670         }
1671
1672         break;
1673     }
1674
1675     lpUC->nScheme = INTERNET_SCHEME_UNKNOWN;
1676     lpUC->nPort = INTERNET_INVALID_PORT_NUMBER;
1677
1678     /* Parse <params> */
1679     lpszParam = memchrW(lpszap, ';', dwUrlLength - (lpszap - lpszUrl));
1680     if(!lpszParam)
1681         lpszParam = memchrW(lpszap, '?', dwUrlLength - (lpszap - lpszUrl));
1682     if(!lpszParam)
1683         lpszParam = memchrW(lpszap, '#', dwUrlLength - (lpszap - lpszUrl));
1684
1685     SetUrlComponentValueW(&lpUC->lpszExtraInfo, &lpUC->dwExtraInfoLength,
1686                           lpszParam, lpszParam ? dwUrlLength-(lpszParam-lpszUrl) : 0);
1687
1688     if (bIsAbsolute) /* Parse <protocol>:[//<net_loc>] */
1689     {
1690         LPCWSTR lpszNetLoc;
1691
1692         /* Get scheme first. */
1693         lpUC->nScheme = GetInternetSchemeW(lpszUrl, lpszcp - lpszUrl);
1694         SetUrlComponentValueW(&lpUC->lpszScheme, &lpUC->dwSchemeLength,
1695                                    lpszUrl, lpszcp - lpszUrl);
1696
1697         /* Eat ':' in protocol. */
1698         lpszcp++;
1699
1700         /* double slash indicates the net_loc portion is present */
1701         if ((lpszcp[0] == '/') && (lpszcp[1] == '/'))
1702         {
1703             lpszcp += 2;
1704
1705             lpszNetLoc = memchrW(lpszcp, '/', dwUrlLength - (lpszcp - lpszUrl));
1706             if (lpszParam)
1707             {
1708                 if (lpszNetLoc)
1709                     lpszNetLoc = min(lpszNetLoc, lpszParam);
1710                 else
1711                     lpszNetLoc = lpszParam;
1712             }
1713             else if (!lpszNetLoc)
1714                 lpszNetLoc = lpszcp + dwUrlLength-(lpszcp-lpszUrl);
1715
1716             /* Parse net-loc */
1717             if (lpszNetLoc)
1718             {
1719                 LPCWSTR lpszHost;
1720                 LPCWSTR lpszPort;
1721
1722                 /* [<user>[<:password>]@]<host>[:<port>] */
1723                 /* First find the user and password if they exist */
1724
1725                 lpszHost = memchrW(lpszcp, '@', dwUrlLength - (lpszcp - lpszUrl));
1726                 if (lpszHost == NULL || lpszHost > lpszNetLoc)
1727                 {
1728                     /* username and password not specified. */
1729                     SetUrlComponentValueW(&lpUC->lpszUserName, &lpUC->dwUserNameLength, NULL, 0);
1730                     SetUrlComponentValueW(&lpUC->lpszPassword, &lpUC->dwPasswordLength, NULL, 0);
1731                 }
1732                 else /* Parse out username and password */
1733                 {
1734                     LPCWSTR lpszUser = lpszcp;
1735                     LPCWSTR lpszPasswd = lpszHost;
1736
1737                     while (lpszcp < lpszHost)
1738                     {
1739                         if (*lpszcp == ':')
1740                             lpszPasswd = lpszcp;
1741
1742                         lpszcp++;
1743                     }
1744
1745                     SetUrlComponentValueW(&lpUC->lpszUserName, &lpUC->dwUserNameLength,
1746                                           lpszUser, lpszPasswd - lpszUser);
1747
1748                     if (lpszPasswd != lpszHost)
1749                         lpszPasswd++;
1750                     SetUrlComponentValueW(&lpUC->lpszPassword, &lpUC->dwPasswordLength,
1751                                           lpszPasswd == lpszHost ? NULL : lpszPasswd,
1752                                           lpszHost - lpszPasswd);
1753
1754                     lpszcp++; /* Advance to beginning of host */
1755                 }
1756
1757                 /* Parse <host><:port> */
1758
1759                 lpszHost = lpszcp;
1760                 lpszPort = lpszNetLoc;
1761
1762                 /* special case for res:// URLs: there is no port here, so the host is the
1763                    entire string up to the first '/' */
1764                 if(lpUC->nScheme==INTERNET_SCHEME_RES)
1765                 {
1766                     SetUrlComponentValueW(&lpUC->lpszHostName, &lpUC->dwHostNameLength,
1767                                           lpszHost, lpszPort - lpszHost);
1768                     lpszcp=lpszNetLoc;
1769                 }
1770                 else
1771                 {
1772                     while (lpszcp < lpszNetLoc)
1773                     {
1774                         if (*lpszcp == ':')
1775                             lpszPort = lpszcp;
1776
1777                         lpszcp++;
1778                     }
1779
1780                     /* If the scheme is "file" and the host is just one letter, it's not a host */
1781                     if(lpUC->nScheme==INTERNET_SCHEME_FILE && lpszPort <= lpszHost+1)
1782                     {
1783                         lpszcp=lpszHost;
1784                         SetUrlComponentValueW(&lpUC->lpszHostName, &lpUC->dwHostNameLength,
1785                                               NULL, 0);
1786                     }
1787                     else
1788                     {
1789                         SetUrlComponentValueW(&lpUC->lpszHostName, &lpUC->dwHostNameLength,
1790                                               lpszHost, lpszPort - lpszHost);
1791                         if (lpszPort != lpszNetLoc)
1792                             lpUC->nPort = atoiW(++lpszPort);
1793                         else switch (lpUC->nScheme)
1794                         {
1795                         case INTERNET_SCHEME_HTTP:
1796                             lpUC->nPort = INTERNET_DEFAULT_HTTP_PORT;
1797                             break;
1798                         case INTERNET_SCHEME_HTTPS:
1799                             lpUC->nPort = INTERNET_DEFAULT_HTTPS_PORT;
1800                             break;
1801                         case INTERNET_SCHEME_FTP:
1802                             lpUC->nPort = INTERNET_DEFAULT_FTP_PORT;
1803                             break;
1804                         case INTERNET_SCHEME_GOPHER:
1805                             lpUC->nPort = INTERNET_DEFAULT_GOPHER_PORT;
1806                             break;
1807                         default:
1808                             break;
1809                         }
1810                     }
1811                 }
1812             }
1813         }
1814         else
1815         {
1816             SetUrlComponentValueW(&lpUC->lpszUserName, &lpUC->dwUserNameLength, NULL, 0);
1817             SetUrlComponentValueW(&lpUC->lpszPassword, &lpUC->dwPasswordLength, NULL, 0);
1818             SetUrlComponentValueW(&lpUC->lpszHostName, &lpUC->dwHostNameLength, NULL, 0);
1819         }
1820     }
1821     else
1822     {
1823         SetUrlComponentValueW(&lpUC->lpszScheme, &lpUC->dwSchemeLength, NULL, 0);
1824         SetUrlComponentValueW(&lpUC->lpszUserName, &lpUC->dwUserNameLength, NULL, 0);
1825         SetUrlComponentValueW(&lpUC->lpszPassword, &lpUC->dwPasswordLength, NULL, 0);
1826         SetUrlComponentValueW(&lpUC->lpszHostName, &lpUC->dwHostNameLength, NULL, 0);
1827     }
1828
1829     /* Here lpszcp points to:
1830      *
1831      * <protocol>:[//<net_loc>][/path][;<params>][?<query>][#<fragment>]
1832      *                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1833      */
1834     if (lpszcp != 0 && lpszcp - lpszUrl < dwUrlLength && (!lpszParam || lpszcp <= lpszParam))
1835     {
1836         DWORD len;
1837
1838         /* Only truncate the parameter list if it's already been saved
1839          * in lpUC->lpszExtraInfo.
1840          */
1841         if (lpszParam && lpUC->dwExtraInfoLength && lpUC->lpszExtraInfo)
1842             len = lpszParam - lpszcp;
1843         else
1844         {
1845             /* Leave the parameter list in lpszUrlPath.  Strip off any trailing
1846              * newlines if necessary.
1847              */
1848             LPWSTR lpsznewline = memchrW(lpszcp, '\n', dwUrlLength - (lpszcp - lpszUrl));
1849             if (lpsznewline != NULL)
1850                 len = lpsznewline - lpszcp;
1851             else
1852                 len = dwUrlLength-(lpszcp-lpszUrl);
1853         }
1854         if (lpUC->dwUrlPathLength && lpUC->lpszUrlPath &&
1855                 lpUC->nScheme == INTERNET_SCHEME_FILE)
1856         {
1857             WCHAR tmppath[MAX_PATH];
1858             if (*lpszcp == '/')
1859             {
1860                 len = MAX_PATH;
1861                 PathCreateFromUrlW(lpszUrl_orig, tmppath, &len, 0);
1862             }
1863             else
1864             {
1865                 WCHAR *iter;
1866                 memcpy(tmppath, lpszcp, len * sizeof(WCHAR));
1867                 tmppath[len] = '\0';
1868
1869                 iter = tmppath;
1870                 while (*iter) {
1871                     if (*iter == '/')
1872                         *iter = '\\';
1873                     ++iter;
1874                 }
1875             }
1876             /* if ends in \. or \.. append a backslash */
1877             if (tmppath[len - 1] == '.' &&
1878                     (tmppath[len - 2] == '\\' ||
1879                      (tmppath[len - 2] == '.' && tmppath[len - 3] == '\\')))
1880             {
1881                 if (len < MAX_PATH - 1)
1882                 {
1883                     tmppath[len] = '\\';
1884                     tmppath[len+1] = '\0';
1885                     ++len;
1886                 }
1887             }
1888             SetUrlComponentValueW(&lpUC->lpszUrlPath, &lpUC->dwUrlPathLength,
1889                                        tmppath, len);
1890         }
1891         else
1892             SetUrlComponentValueW(&lpUC->lpszUrlPath, &lpUC->dwUrlPathLength,
1893                                        lpszcp, len);
1894     }
1895     else
1896     {
1897         if (lpUC->lpszUrlPath && (lpUC->dwUrlPathLength > 0))
1898             lpUC->lpszUrlPath[0] = 0;
1899         lpUC->dwUrlPathLength = 0;
1900     }
1901
1902     TRACE("%s: scheme(%s) host(%s) path(%s) extra(%s)\n", debugstr_wn(lpszUrl,dwUrlLength),
1903              debugstr_wn(lpUC->lpszScheme,lpUC->dwSchemeLength),
1904              debugstr_wn(lpUC->lpszHostName,lpUC->dwHostNameLength),
1905              debugstr_wn(lpUC->lpszUrlPath,lpUC->dwUrlPathLength),
1906              debugstr_wn(lpUC->lpszExtraInfo,lpUC->dwExtraInfoLength));
1907
1908     heap_free( lpszUrl_decode );
1909     return TRUE;
1910 }
1911
1912 /***********************************************************************
1913  *           InternetAttemptConnect (WININET.@)
1914  *
1915  * Attempt to make a connection to the internet
1916  *
1917  * RETURNS
1918  *    ERROR_SUCCESS on success
1919  *    Error value   on failure
1920  *
1921  */
1922 DWORD WINAPI InternetAttemptConnect(DWORD dwReserved)
1923 {
1924     FIXME("Stub\n");
1925     return ERROR_SUCCESS;
1926 }
1927
1928
1929 /***********************************************************************
1930  *           InternetCanonicalizeUrlA (WININET.@)
1931  *
1932  * Escape unsafe characters and spaces
1933  *
1934  * RETURNS
1935  *    TRUE on success
1936  *    FALSE on failure
1937  *
1938  */
1939 BOOL WINAPI InternetCanonicalizeUrlA(LPCSTR lpszUrl, LPSTR lpszBuffer,
1940         LPDWORD lpdwBufferLength, DWORD dwFlags)
1941 {
1942     HRESULT hr;
1943     DWORD dwURLFlags = URL_WININET_COMPATIBILITY | URL_ESCAPE_UNSAFE;
1944
1945     TRACE("(%s, %p, %p, 0x%08x) bufferlength: %d\n", debugstr_a(lpszUrl), lpszBuffer,
1946         lpdwBufferLength, dwFlags, lpdwBufferLength ? *lpdwBufferLength : -1);
1947
1948     if(dwFlags & ICU_DECODE)
1949     {
1950         dwURLFlags |= URL_UNESCAPE;
1951         dwFlags &= ~ICU_DECODE;
1952     }
1953
1954     if(dwFlags & ICU_ESCAPE)
1955     {
1956         dwURLFlags |= URL_UNESCAPE;
1957         dwFlags &= ~ICU_ESCAPE;
1958     }
1959
1960     if(dwFlags & ICU_BROWSER_MODE)
1961     {
1962         dwURLFlags |= URL_BROWSER_MODE;
1963         dwFlags &= ~ICU_BROWSER_MODE;
1964     }
1965
1966     if(dwFlags & ICU_NO_ENCODE)
1967     {
1968         /* Flip this bit to correspond to URL_ESCAPE_UNSAFE */
1969         dwURLFlags ^= URL_ESCAPE_UNSAFE;
1970         dwFlags &= ~ICU_NO_ENCODE;
1971     }
1972
1973     if (dwFlags) FIXME("Unhandled flags 0x%08x\n", dwFlags);
1974
1975     hr = UrlCanonicalizeA(lpszUrl, lpszBuffer, lpdwBufferLength, dwURLFlags);
1976     if (hr == E_POINTER) SetLastError(ERROR_INSUFFICIENT_BUFFER);
1977     if (hr == E_INVALIDARG) SetLastError(ERROR_INVALID_PARAMETER);
1978
1979     return (hr == S_OK) ? TRUE : FALSE;
1980 }
1981
1982 /***********************************************************************
1983  *           InternetCanonicalizeUrlW (WININET.@)
1984  *
1985  * Escape unsafe characters and spaces
1986  *
1987  * RETURNS
1988  *    TRUE on success
1989  *    FALSE on failure
1990  *
1991  */
1992 BOOL WINAPI InternetCanonicalizeUrlW(LPCWSTR lpszUrl, LPWSTR lpszBuffer,
1993     LPDWORD lpdwBufferLength, DWORD dwFlags)
1994 {
1995     HRESULT hr;
1996     DWORD dwURLFlags = URL_WININET_COMPATIBILITY | URL_ESCAPE_UNSAFE;
1997
1998     TRACE("(%s, %p, %p, 0x%08x) bufferlength: %d\n", debugstr_w(lpszUrl), lpszBuffer,
1999           lpdwBufferLength, dwFlags, lpdwBufferLength ? *lpdwBufferLength : -1);
2000
2001     if(dwFlags & ICU_DECODE)
2002     {
2003         dwURLFlags |= URL_UNESCAPE;
2004         dwFlags &= ~ICU_DECODE;
2005     }
2006
2007     if(dwFlags & ICU_ESCAPE)
2008     {
2009         dwURLFlags |= URL_UNESCAPE;
2010         dwFlags &= ~ICU_ESCAPE;
2011     }
2012
2013     if(dwFlags & ICU_BROWSER_MODE)
2014     {
2015         dwURLFlags |= URL_BROWSER_MODE;
2016         dwFlags &= ~ICU_BROWSER_MODE;
2017     }
2018
2019     if(dwFlags & ICU_NO_ENCODE)
2020     {
2021         /* Flip this bit to correspond to URL_ESCAPE_UNSAFE */
2022         dwURLFlags ^= URL_ESCAPE_UNSAFE;
2023         dwFlags &= ~ICU_NO_ENCODE;
2024     }
2025
2026     if (dwFlags) FIXME("Unhandled flags 0x%08x\n", dwFlags);
2027
2028     hr = UrlCanonicalizeW(lpszUrl, lpszBuffer, lpdwBufferLength, dwURLFlags);
2029     if (hr == E_POINTER) SetLastError(ERROR_INSUFFICIENT_BUFFER);
2030     if (hr == E_INVALIDARG) SetLastError(ERROR_INVALID_PARAMETER);
2031
2032     return (hr == S_OK) ? TRUE : FALSE;
2033 }
2034
2035 /* #################################################### */
2036
2037 static INTERNET_STATUS_CALLBACK set_status_callback(
2038     object_header_t *lpwh, INTERNET_STATUS_CALLBACK callback, BOOL unicode)
2039 {
2040     INTERNET_STATUS_CALLBACK ret;
2041
2042     if (unicode) lpwh->dwInternalFlags |= INET_CALLBACKW;
2043     else lpwh->dwInternalFlags &= ~INET_CALLBACKW;
2044
2045     ret = lpwh->lpfnStatusCB;
2046     lpwh->lpfnStatusCB = callback;
2047
2048     return ret;
2049 }
2050
2051 /***********************************************************************
2052  *           InternetSetStatusCallbackA (WININET.@)
2053  *
2054  * Sets up a callback function which is called as progress is made
2055  * during an operation.
2056  *
2057  * RETURNS
2058  *    Previous callback or NULL         on success
2059  *    INTERNET_INVALID_STATUS_CALLBACK  on failure
2060  *
2061  */
2062 INTERNET_STATUS_CALLBACK WINAPI InternetSetStatusCallbackA(
2063         HINTERNET hInternet ,INTERNET_STATUS_CALLBACK lpfnIntCB)
2064 {
2065     INTERNET_STATUS_CALLBACK retVal;
2066     object_header_t *lpwh;
2067
2068     TRACE("%p\n", hInternet);
2069
2070     if (!(lpwh = get_handle_object(hInternet)))
2071         return INTERNET_INVALID_STATUS_CALLBACK;
2072
2073     retVal = set_status_callback(lpwh, lpfnIntCB, FALSE);
2074
2075     WININET_Release( lpwh );
2076     return retVal;
2077 }
2078
2079 /***********************************************************************
2080  *           InternetSetStatusCallbackW (WININET.@)
2081  *
2082  * Sets up a callback function which is called as progress is made
2083  * during an operation.
2084  *
2085  * RETURNS
2086  *    Previous callback or NULL         on success
2087  *    INTERNET_INVALID_STATUS_CALLBACK  on failure
2088  *
2089  */
2090 INTERNET_STATUS_CALLBACK WINAPI InternetSetStatusCallbackW(
2091         HINTERNET hInternet ,INTERNET_STATUS_CALLBACK lpfnIntCB)
2092 {
2093     INTERNET_STATUS_CALLBACK retVal;
2094     object_header_t *lpwh;
2095
2096     TRACE("%p\n", hInternet);
2097
2098     if (!(lpwh = get_handle_object(hInternet)))
2099         return INTERNET_INVALID_STATUS_CALLBACK;
2100
2101     retVal = set_status_callback(lpwh, lpfnIntCB, TRUE);
2102
2103     WININET_Release( lpwh );
2104     return retVal;
2105 }
2106
2107 /***********************************************************************
2108  *           InternetSetFilePointer (WININET.@)
2109  */
2110 DWORD WINAPI InternetSetFilePointer(HINTERNET hFile, LONG lDistanceToMove,
2111     PVOID pReserved, DWORD dwMoveContext, DWORD_PTR dwContext)
2112 {
2113     FIXME("(%p %d %p %d %lx): stub\n", hFile, lDistanceToMove, pReserved, dwMoveContext, dwContext);
2114     return FALSE;
2115 }
2116
2117 /***********************************************************************
2118  *           InternetWriteFile (WININET.@)
2119  *
2120  * Write data to an open internet file
2121  *
2122  * RETURNS
2123  *    TRUE  on success
2124  *    FALSE on failure
2125  *
2126  */
2127 BOOL WINAPI InternetWriteFile(HINTERNET hFile, LPCVOID lpBuffer,
2128         DWORD dwNumOfBytesToWrite, LPDWORD lpdwNumOfBytesWritten)
2129 {
2130     object_header_t *lpwh;
2131     BOOL res;
2132
2133     TRACE("(%p %p %d %p)\n", hFile, lpBuffer, dwNumOfBytesToWrite, lpdwNumOfBytesWritten);
2134
2135     lpwh = get_handle_object( hFile );
2136     if (!lpwh) {
2137         WARN("Invalid handle\n");
2138         SetLastError(ERROR_INVALID_HANDLE);
2139         return FALSE;
2140     }
2141
2142     if(lpwh->vtbl->WriteFile) {
2143         res = lpwh->vtbl->WriteFile(lpwh, lpBuffer, dwNumOfBytesToWrite, lpdwNumOfBytesWritten);
2144     }else {
2145         WARN("No Writefile method.\n");
2146         res = ERROR_INVALID_HANDLE;
2147     }
2148
2149     WININET_Release( lpwh );
2150
2151     if(res != ERROR_SUCCESS)
2152         SetLastError(res);
2153     return res == ERROR_SUCCESS;
2154 }
2155
2156
2157 /***********************************************************************
2158  *           InternetReadFile (WININET.@)
2159  *
2160  * Read data from an open internet file
2161  *
2162  * RETURNS
2163  *    TRUE  on success
2164  *    FALSE on failure
2165  *
2166  */
2167 BOOL WINAPI InternetReadFile(HINTERNET hFile, LPVOID lpBuffer,
2168         DWORD dwNumOfBytesToRead, LPDWORD pdwNumOfBytesRead)
2169 {
2170     object_header_t *hdr;
2171     DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
2172
2173     TRACE("%p %p %d %p\n", hFile, lpBuffer, dwNumOfBytesToRead, pdwNumOfBytesRead);
2174
2175     hdr = get_handle_object(hFile);
2176     if (!hdr) {
2177         INTERNET_SetLastError(ERROR_INVALID_HANDLE);
2178         return FALSE;
2179     }
2180
2181     if(hdr->vtbl->ReadFile)
2182         res = hdr->vtbl->ReadFile(hdr, lpBuffer, dwNumOfBytesToRead, pdwNumOfBytesRead);
2183
2184     WININET_Release(hdr);
2185
2186     TRACE("-- %s (%u) (bytes read: %d)\n", res == ERROR_SUCCESS ? "TRUE": "FALSE", res,
2187           pdwNumOfBytesRead ? *pdwNumOfBytesRead : -1);
2188
2189     if(res != ERROR_SUCCESS)
2190         SetLastError(res);
2191     return res == ERROR_SUCCESS;
2192 }
2193
2194 /***********************************************************************
2195  *           InternetReadFileExA (WININET.@)
2196  *
2197  * Read data from an open internet file
2198  *
2199  * PARAMS
2200  *  hFile         [I] Handle returned by InternetOpenUrl or HttpOpenRequest.
2201  *  lpBuffersOut  [I/O] Buffer.
2202  *  dwFlags       [I] Flags. See notes.
2203  *  dwContext     [I] Context for callbacks.
2204  *
2205  * RETURNS
2206  *    TRUE  on success
2207  *    FALSE on failure
2208  *
2209  * NOTES
2210  *  The parameter dwFlags include zero or more of the following flags:
2211  *|IRF_ASYNC - Makes the call asynchronous.
2212  *|IRF_SYNC - Makes the call synchronous.
2213  *|IRF_USE_CONTEXT - Forces dwContext to be used.
2214  *|IRF_NO_WAIT - Don't block if the data is not available, just return what is available.
2215  *
2216  * However, in testing IRF_USE_CONTEXT seems to have no effect - dwContext isn't used.
2217  *
2218  * SEE
2219  *  InternetOpenUrlA(), HttpOpenRequestA()
2220  */
2221 BOOL WINAPI InternetReadFileExA(HINTERNET hFile, LPINTERNET_BUFFERSA lpBuffersOut,
2222         DWORD dwFlags, DWORD_PTR dwContext)
2223 {
2224     object_header_t *hdr;
2225     DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
2226
2227     TRACE("(%p %p 0x%x 0x%lx)\n", hFile, lpBuffersOut, dwFlags, dwContext);
2228
2229     hdr = get_handle_object(hFile);
2230     if (!hdr) {
2231         INTERNET_SetLastError(ERROR_INVALID_HANDLE);
2232         return FALSE;
2233     }
2234
2235     if(hdr->vtbl->ReadFileExA)
2236         res = hdr->vtbl->ReadFileExA(hdr, lpBuffersOut, dwFlags, dwContext);
2237
2238     WININET_Release(hdr);
2239
2240     TRACE("-- %s (%u, bytes read: %d)\n", res == ERROR_SUCCESS ? "TRUE": "FALSE",
2241           res, lpBuffersOut->dwBufferLength);
2242
2243     if(res != ERROR_SUCCESS)
2244         SetLastError(res);
2245     return res == ERROR_SUCCESS;
2246 }
2247
2248 /***********************************************************************
2249  *           InternetReadFileExW (WININET.@)
2250  * SEE
2251  *  InternetReadFileExA()
2252  */
2253 BOOL WINAPI InternetReadFileExW(HINTERNET hFile, LPINTERNET_BUFFERSW lpBuffer,
2254         DWORD dwFlags, DWORD_PTR dwContext)
2255 {
2256     object_header_t *hdr;
2257     DWORD res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
2258
2259     TRACE("(%p %p 0x%x 0x%lx)\n", hFile, lpBuffer, dwFlags, dwContext);
2260
2261     hdr = get_handle_object(hFile);
2262     if (!hdr) {
2263         INTERNET_SetLastError(ERROR_INVALID_HANDLE);
2264         return FALSE;
2265     }
2266
2267     if(hdr->vtbl->ReadFileExW)
2268         res = hdr->vtbl->ReadFileExW(hdr, lpBuffer, dwFlags, dwContext);
2269
2270     WININET_Release(hdr);
2271
2272     TRACE("-- %s (%u, bytes read: %d)\n", res == ERROR_SUCCESS ? "TRUE": "FALSE",
2273           res, lpBuffer->dwBufferLength);
2274
2275     if(res != ERROR_SUCCESS)
2276         SetLastError(res);
2277     return res == ERROR_SUCCESS;
2278 }
2279
2280 static DWORD query_global_option(DWORD option, void *buffer, DWORD *size, BOOL unicode)
2281 {
2282     /* FIXME: This function currently handles more options than it should. Options requiring
2283      * proper handles should be moved to proper functions */
2284     switch(option) {
2285     case INTERNET_OPTION_REQUEST_FLAGS:
2286         TRACE("INTERNET_OPTION_REQUEST_FLAGS\n");
2287
2288         if (*size < sizeof(ULONG))
2289             return ERROR_INSUFFICIENT_BUFFER;
2290
2291         *(ULONG*)buffer = 4;
2292         *size = sizeof(ULONG);
2293
2294         return ERROR_SUCCESS;
2295
2296     case INTERNET_OPTION_HTTP_VERSION:
2297         if (*size < sizeof(HTTP_VERSION_INFO))
2298             return ERROR_INSUFFICIENT_BUFFER;
2299
2300         /*
2301          * Presently hardcoded to 1.1
2302          */
2303         ((HTTP_VERSION_INFO*)buffer)->dwMajorVersion = 1;
2304         ((HTTP_VERSION_INFO*)buffer)->dwMinorVersion = 1;
2305         *size = sizeof(HTTP_VERSION_INFO);
2306
2307         return ERROR_SUCCESS;
2308
2309     case INTERNET_OPTION_CONNECTED_STATE:
2310         FIXME("INTERNET_OPTION_CONNECTED_STATE: semi-stub\n");
2311
2312         if (*size < sizeof(ULONG))
2313             return ERROR_INSUFFICIENT_BUFFER;
2314
2315         *(ULONG*)buffer = INTERNET_STATE_CONNECTED;
2316         *size = sizeof(ULONG);
2317
2318         return ERROR_SUCCESS;
2319
2320     case INTERNET_OPTION_PROXY: {
2321         appinfo_t ai;
2322         BOOL ret;
2323
2324         TRACE("Getting global proxy info\n");
2325         memset(&ai, 0, sizeof(appinfo_t));
2326         INTERNET_ConfigureProxy(&ai);
2327
2328         ret = APPINFO_QueryOption(&ai.hdr, INTERNET_OPTION_PROXY, buffer, size, unicode); /* FIXME */
2329         APPINFO_Destroy(&ai.hdr);
2330         return ret;
2331     }
2332
2333     case INTERNET_OPTION_MAX_CONNS_PER_SERVER:
2334         TRACE("INTERNET_OPTION_MAX_CONNS_PER_SERVER\n");
2335
2336         if (*size < sizeof(ULONG))
2337             return ERROR_INSUFFICIENT_BUFFER;
2338
2339         *(ULONG*)buffer = max_conns;
2340         *size = sizeof(ULONG);
2341
2342         return ERROR_SUCCESS;
2343
2344     case INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER:
2345             TRACE("INTERNET_OPTION_MAX_CONNS_1_0_SERVER\n");
2346
2347             if (*size < sizeof(ULONG))
2348                 return ERROR_INSUFFICIENT_BUFFER;
2349
2350             *(ULONG*)buffer = max_1_0_conns;
2351             *size = sizeof(ULONG);
2352
2353             return ERROR_SUCCESS;
2354
2355     case INTERNET_OPTION_SECURITY_FLAGS:
2356         FIXME("INTERNET_OPTION_SECURITY_FLAGS: Stub\n");
2357         return ERROR_SUCCESS;
2358
2359     case INTERNET_OPTION_VERSION: {
2360         static const INTERNET_VERSION_INFO info = { 1, 2 };
2361
2362         TRACE("INTERNET_OPTION_VERSION\n");
2363
2364         if (*size < sizeof(INTERNET_VERSION_INFO))
2365             return ERROR_INSUFFICIENT_BUFFER;
2366
2367         memcpy(buffer, &info, sizeof(info));
2368         *size = sizeof(info);
2369
2370         return ERROR_SUCCESS;
2371     }
2372
2373     case INTERNET_OPTION_PER_CONNECTION_OPTION: {
2374         INTERNET_PER_CONN_OPTION_LISTW *con = buffer;
2375         INTERNET_PER_CONN_OPTION_LISTA *conA = buffer;
2376         DWORD res = ERROR_SUCCESS, i;
2377         proxyinfo_t pi;
2378         LONG ret;
2379
2380         TRACE("Getting global proxy info\n");
2381         if((ret = INTERNET_LoadProxySettings(&pi)))
2382             return ret;
2383
2384         FIXME("INTERNET_OPTION_PER_CONNECTION_OPTION stub\n");
2385
2386         if (*size < sizeof(INTERNET_PER_CONN_OPTION_LISTW)) {
2387             FreeProxyInfo(&pi);
2388             return ERROR_INSUFFICIENT_BUFFER;
2389         }
2390
2391         for (i = 0; i < con->dwOptionCount; i++) {
2392             INTERNET_PER_CONN_OPTIONW *optionW = con->pOptions + i;
2393             INTERNET_PER_CONN_OPTIONA *optionA = conA->pOptions + i;
2394
2395             switch (optionW->dwOption) {
2396             case INTERNET_PER_CONN_FLAGS:
2397                 if(pi.proxyEnabled)
2398                     optionW->Value.dwValue = PROXY_TYPE_PROXY;
2399                 else
2400                     optionW->Value.dwValue = PROXY_TYPE_DIRECT;
2401                 break;
2402
2403             case INTERNET_PER_CONN_PROXY_SERVER:
2404                 if (unicode)
2405                     optionW->Value.pszValue = heap_strdupW(pi.proxy);
2406                 else
2407                     optionA->Value.pszValue = heap_strdupWtoA(pi.proxy);
2408                 break;
2409
2410             case INTERNET_PER_CONN_PROXY_BYPASS:
2411                 if (unicode)
2412                     optionW->Value.pszValue = heap_strdupW(pi.proxyBypass);
2413                 else
2414                     optionA->Value.pszValue = heap_strdupWtoA(pi.proxyBypass);
2415                 break;
2416
2417             case INTERNET_PER_CONN_AUTOCONFIG_URL:
2418             case INTERNET_PER_CONN_AUTODISCOVERY_FLAGS:
2419             case INTERNET_PER_CONN_AUTOCONFIG_SECONDARY_URL:
2420             case INTERNET_PER_CONN_AUTOCONFIG_RELOAD_DELAY_MINS:
2421             case INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_TIME:
2422             case INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_URL:
2423                 FIXME("Unhandled dwOption %d\n", optionW->dwOption);
2424                 memset(&optionW->Value, 0, sizeof(optionW->Value));
2425                 break;
2426
2427             default:
2428                 FIXME("Unknown dwOption %d\n", optionW->dwOption);
2429                 res = ERROR_INVALID_PARAMETER;
2430                 break;
2431             }
2432         }
2433         FreeProxyInfo(&pi);
2434
2435         return res;
2436     }
2437     case INTERNET_OPTION_USER_AGENT:
2438         return ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
2439     case INTERNET_OPTION_POLICY:
2440         return ERROR_INVALID_PARAMETER;
2441     }
2442
2443     FIXME("Stub for %d\n", option);
2444     return ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
2445 }
2446
2447 DWORD INET_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2448 {
2449     switch(option) {
2450     case INTERNET_OPTION_CONTEXT_VALUE:
2451         if (!size)
2452             return ERROR_INVALID_PARAMETER;
2453
2454         if (*size < sizeof(DWORD_PTR)) {
2455             *size = sizeof(DWORD_PTR);
2456             return ERROR_INSUFFICIENT_BUFFER;
2457         }
2458         if (!buffer)
2459             return ERROR_INVALID_PARAMETER;
2460
2461         *(DWORD_PTR *)buffer = hdr->dwContext;
2462         *size = sizeof(DWORD_PTR);
2463         return ERROR_SUCCESS;
2464
2465     case INTERNET_OPTION_MAX_CONNS_PER_SERVER:
2466     case INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER:
2467         WARN("Called on global option %u\n", option);
2468         return ERROR_INTERNET_INVALID_OPERATION;
2469     }
2470
2471     /* FIXME: we shouldn't call it here */
2472     return query_global_option(option, buffer, size, unicode);
2473 }
2474
2475 /***********************************************************************
2476  *           InternetQueryOptionW (WININET.@)
2477  *
2478  * Queries an options on the specified handle
2479  *
2480  * RETURNS
2481  *    TRUE  on success
2482  *    FALSE on failure
2483  *
2484  */
2485 BOOL WINAPI InternetQueryOptionW(HINTERNET hInternet, DWORD dwOption,
2486                                  LPVOID lpBuffer, LPDWORD lpdwBufferLength)
2487 {
2488     object_header_t *hdr;
2489     DWORD res = ERROR_INVALID_HANDLE;
2490
2491     TRACE("%p %d %p %p\n", hInternet, dwOption, lpBuffer, lpdwBufferLength);
2492
2493     if(hInternet) {
2494         hdr = get_handle_object(hInternet);
2495         if (hdr) {
2496             res = hdr->vtbl->QueryOption(hdr, dwOption, lpBuffer, lpdwBufferLength, TRUE);
2497             WININET_Release(hdr);
2498         }
2499     }else {
2500         res = query_global_option(dwOption, lpBuffer, lpdwBufferLength, TRUE);
2501     }
2502
2503     if(res != ERROR_SUCCESS)
2504         SetLastError(res);
2505     return res == ERROR_SUCCESS;
2506 }
2507
2508 /***********************************************************************
2509  *           InternetQueryOptionA (WININET.@)
2510  *
2511  * Queries an options on the specified handle
2512  *
2513  * RETURNS
2514  *    TRUE  on success
2515  *    FALSE on failure
2516  *
2517  */
2518 BOOL WINAPI InternetQueryOptionA(HINTERNET hInternet, DWORD dwOption,
2519                                  LPVOID lpBuffer, LPDWORD lpdwBufferLength)
2520 {
2521     object_header_t *hdr;
2522     DWORD res = ERROR_INVALID_HANDLE;
2523
2524     TRACE("%p %d %p %p\n", hInternet, dwOption, lpBuffer, lpdwBufferLength);
2525
2526     if(hInternet) {
2527         hdr = get_handle_object(hInternet);
2528         if (hdr) {
2529             res = hdr->vtbl->QueryOption(hdr, dwOption, lpBuffer, lpdwBufferLength, FALSE);
2530             WININET_Release(hdr);
2531         }
2532     }else {
2533         res = query_global_option(dwOption, lpBuffer, lpdwBufferLength, FALSE);
2534     }
2535
2536     if(res != ERROR_SUCCESS)
2537         SetLastError(res);
2538     return res == ERROR_SUCCESS;
2539 }
2540
2541 DWORD INET_SetOption(object_header_t *hdr, DWORD option, void *buf, DWORD size)
2542 {
2543     switch(option) {
2544     case INTERNET_OPTION_CALLBACK:
2545         WARN("Not settable option %u\n", option);
2546         return ERROR_INTERNET_OPTION_NOT_SETTABLE;
2547     case INTERNET_OPTION_MAX_CONNS_PER_SERVER:
2548     case INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER:
2549         WARN("Called on global option %u\n", option);
2550         return ERROR_INTERNET_INVALID_OPERATION;
2551     }
2552
2553     return ERROR_INTERNET_INVALID_OPTION;
2554 }
2555
2556 static DWORD set_global_option(DWORD option, void *buf, DWORD size)
2557 {
2558     switch(option) {
2559     case INTERNET_OPTION_CALLBACK:
2560         WARN("Not global option %u\n", option);
2561         return ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
2562
2563     case INTERNET_OPTION_MAX_CONNS_PER_SERVER:
2564         TRACE("INTERNET_OPTION_MAX_CONNS_PER_SERVER\n");
2565
2566         if(size != sizeof(max_conns))
2567             return ERROR_INTERNET_BAD_OPTION_LENGTH;
2568         if(!*(ULONG*)buf)
2569             return ERROR_BAD_ARGUMENTS;
2570
2571         max_conns = *(ULONG*)buf;
2572         return ERROR_SUCCESS;
2573
2574     case INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER:
2575         TRACE("INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER\n");
2576
2577         if(size != sizeof(max_1_0_conns))
2578             return ERROR_INTERNET_BAD_OPTION_LENGTH;
2579         if(!*(ULONG*)buf)
2580             return ERROR_BAD_ARGUMENTS;
2581
2582         max_1_0_conns = *(ULONG*)buf;
2583         return ERROR_SUCCESS;
2584     }
2585
2586     return ERROR_INTERNET_INVALID_OPTION;
2587 }
2588
2589 /***********************************************************************
2590  *           InternetSetOptionW (WININET.@)
2591  *
2592  * Sets an options on the specified handle
2593  *
2594  * RETURNS
2595  *    TRUE  on success
2596  *    FALSE on failure
2597  *
2598  */
2599 BOOL WINAPI InternetSetOptionW(HINTERNET hInternet, DWORD dwOption,
2600                            LPVOID lpBuffer, DWORD dwBufferLength)
2601 {
2602     object_header_t *lpwhh;
2603     BOOL ret = TRUE;
2604     DWORD res;
2605
2606     TRACE("(%p %d %p %d)\n", hInternet, dwOption, lpBuffer, dwBufferLength);
2607
2608     lpwhh = (object_header_t*) get_handle_object( hInternet );
2609     if(lpwhh)
2610         res = lpwhh->vtbl->SetOption(lpwhh, dwOption, lpBuffer, dwBufferLength);
2611     else
2612         res = set_global_option(dwOption, lpBuffer, dwBufferLength);
2613
2614     if(res != ERROR_INTERNET_INVALID_OPTION) {
2615         if(lpwhh)
2616             WININET_Release(lpwhh);
2617
2618         if(res != ERROR_SUCCESS)
2619             SetLastError(res);
2620
2621         return res == ERROR_SUCCESS;
2622     }
2623
2624     switch (dwOption)
2625     {
2626     case INTERNET_OPTION_HTTP_VERSION:
2627       {
2628         HTTP_VERSION_INFO* pVersion=(HTTP_VERSION_INFO*)lpBuffer;
2629         FIXME("Option INTERNET_OPTION_HTTP_VERSION(%d,%d): STUB\n",pVersion->dwMajorVersion,pVersion->dwMinorVersion);
2630       }
2631       break;
2632     case INTERNET_OPTION_ERROR_MASK:
2633       {
2634         if(!lpwhh) {
2635             SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2636             return FALSE;
2637         } else if(*(ULONG*)lpBuffer & (~(INTERNET_ERROR_MASK_INSERT_CDROM|
2638                         INTERNET_ERROR_MASK_COMBINED_SEC_CERT|
2639                         INTERNET_ERROR_MASK_LOGIN_FAILURE_DISPLAY_ENTITY_BODY))) {
2640             SetLastError(ERROR_INVALID_PARAMETER);
2641             ret = FALSE;
2642         } else if(dwBufferLength != sizeof(ULONG)) {
2643             SetLastError(ERROR_INTERNET_BAD_OPTION_LENGTH);
2644             ret = FALSE;
2645         } else
2646             lpwhh->ErrorMask = *(ULONG*)lpBuffer;
2647       }
2648       break;
2649     case INTERNET_OPTION_PROXY:
2650     {
2651         INTERNET_PROXY_INFOW *info = lpBuffer;
2652
2653         if (!lpBuffer || dwBufferLength < sizeof(INTERNET_PROXY_INFOW))
2654         {
2655             SetLastError(ERROR_INVALID_PARAMETER);
2656             return FALSE;
2657         }
2658         if (!hInternet)
2659         {
2660             EnterCriticalSection( &WININET_cs );
2661             free_global_proxy();
2662             global_proxy = heap_alloc( sizeof(proxyinfo_t) );
2663             if (global_proxy)
2664             {
2665                 if (info->dwAccessType == INTERNET_OPEN_TYPE_PROXY)
2666                 {
2667                     global_proxy->proxyEnabled = 1;
2668                     global_proxy->proxy = heap_strdupW( info->lpszProxy );
2669                     global_proxy->proxyBypass = heap_strdupW( info->lpszProxyBypass );
2670                 }
2671                 else
2672                 {
2673                     global_proxy->proxyEnabled = 0;
2674                     global_proxy->proxy = global_proxy->proxyBypass = NULL;
2675                 }
2676             }
2677             LeaveCriticalSection( &WININET_cs );
2678         }
2679         else
2680         {
2681             /* In general, each type of object should handle
2682              * INTERNET_OPTION_PROXY directly.  This FIXME ensures it doesn't
2683              * get silently dropped.
2684              */
2685             FIXME("INTERNET_OPTION_PROXY unimplemented\n");
2686             SetLastError(ERROR_INTERNET_INVALID_OPTION);
2687             ret = FALSE;
2688         }
2689         break;
2690     }
2691     case INTERNET_OPTION_CODEPAGE:
2692       {
2693         ULONG codepage = *(ULONG *)lpBuffer;
2694         FIXME("Option INTERNET_OPTION_CODEPAGE (%d): STUB\n", codepage);
2695       }
2696       break;
2697     case INTERNET_OPTION_REQUEST_PRIORITY:
2698       {
2699         ULONG priority = *(ULONG *)lpBuffer;
2700         FIXME("Option INTERNET_OPTION_REQUEST_PRIORITY (%d): STUB\n", priority);
2701       }
2702       break;
2703     case INTERNET_OPTION_CONNECT_TIMEOUT:
2704       {
2705         ULONG connecttimeout = *(ULONG *)lpBuffer;
2706         FIXME("Option INTERNET_OPTION_CONNECT_TIMEOUT (%d): STUB\n", connecttimeout);
2707       }
2708       break;
2709     case INTERNET_OPTION_DATA_RECEIVE_TIMEOUT:
2710       {
2711         ULONG receivetimeout = *(ULONG *)lpBuffer;
2712         FIXME("Option INTERNET_OPTION_DATA_RECEIVE_TIMEOUT (%d): STUB\n", receivetimeout);
2713       }
2714       break;
2715     case INTERNET_OPTION_RESET_URLCACHE_SESSION:
2716         FIXME("Option INTERNET_OPTION_RESET_URLCACHE_SESSION: STUB\n");
2717         break;
2718     case INTERNET_OPTION_END_BROWSER_SESSION:
2719         FIXME("Option INTERNET_OPTION_END_BROWSER_SESSION: STUB\n");
2720         break;
2721     case INTERNET_OPTION_CONNECTED_STATE:
2722         FIXME("Option INTERNET_OPTION_CONNECTED_STATE: STUB\n");
2723         break;
2724     case INTERNET_OPTION_DISABLE_PASSPORT_AUTH:
2725         TRACE("Option INTERNET_OPTION_DISABLE_PASSPORT_AUTH: harmless stub, since not enabled\n");
2726         break;
2727     case INTERNET_OPTION_SEND_TIMEOUT:
2728     case INTERNET_OPTION_RECEIVE_TIMEOUT:
2729     case INTERNET_OPTION_DATA_SEND_TIMEOUT:
2730     {
2731         ULONG timeout = *(ULONG *)lpBuffer;
2732         FIXME("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT/DATA_SEND_TIMEOUT %d\n", timeout);
2733         break;
2734     }
2735     case INTERNET_OPTION_CONNECT_RETRIES:
2736     {
2737         ULONG retries = *(ULONG *)lpBuffer;
2738         FIXME("INTERNET_OPTION_CONNECT_RETRIES %d\n", retries);
2739         break;
2740     }
2741     case INTERNET_OPTION_CONTEXT_VALUE:
2742     {
2743         if (!lpwhh)
2744         {
2745             SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2746             return FALSE;
2747         }
2748         if (!lpBuffer || dwBufferLength != sizeof(DWORD_PTR))
2749         {
2750             SetLastError(ERROR_INVALID_PARAMETER);
2751             ret = FALSE;
2752         }
2753         else
2754             lpwhh->dwContext = *(DWORD_PTR *)lpBuffer;
2755         break;
2756     }
2757     case INTERNET_OPTION_SECURITY_FLAGS:
2758          FIXME("Option INTERNET_OPTION_SECURITY_FLAGS; STUB\n");
2759          break;
2760     case INTERNET_OPTION_DISABLE_AUTODIAL:
2761          FIXME("Option INTERNET_OPTION_DISABLE_AUTODIAL; STUB\n");
2762          break;
2763     case INTERNET_OPTION_HTTP_DECODING:
2764         FIXME("INTERNET_OPTION_HTTP_DECODING; STUB\n");
2765         SetLastError(ERROR_INTERNET_INVALID_OPTION);
2766         ret = FALSE;
2767         break;
2768     case INTERNET_OPTION_COOKIES_3RD_PARTY:
2769         FIXME("INTERNET_OPTION_COOKIES_3RD_PARTY; STUB\n");
2770         SetLastError(ERROR_INTERNET_INVALID_OPTION);
2771         ret = FALSE;
2772         break;
2773     case INTERNET_OPTION_SEND_UTF8_SERVERNAME_TO_PROXY:
2774         FIXME("INTERNET_OPTION_SEND_UTF8_SERVERNAME_TO_PROXY; STUB\n");
2775         SetLastError(ERROR_INTERNET_INVALID_OPTION);
2776         ret = FALSE;
2777         break;
2778     case INTERNET_OPTION_CODEPAGE_PATH:
2779         FIXME("INTERNET_OPTION_CODEPAGE_PATH; STUB\n");
2780         SetLastError(ERROR_INTERNET_INVALID_OPTION);
2781         ret = FALSE;
2782         break;
2783     case INTERNET_OPTION_CODEPAGE_EXTRA:
2784         FIXME("INTERNET_OPTION_CODEPAGE_EXTRA; STUB\n");
2785         SetLastError(ERROR_INTERNET_INVALID_OPTION);
2786         ret = FALSE;
2787         break;
2788     case INTERNET_OPTION_IDN:
2789         FIXME("INTERNET_OPTION_IDN; STUB\n");
2790         SetLastError(ERROR_INTERNET_INVALID_OPTION);
2791         ret = FALSE;
2792         break;
2793     case INTERNET_OPTION_POLICY:
2794         SetLastError(ERROR_INVALID_PARAMETER);
2795         ret = FALSE;
2796         break;
2797     case INTERNET_OPTION_PER_CONNECTION_OPTION: {
2798         INTERNET_PER_CONN_OPTION_LISTW *con = lpBuffer;
2799         LONG res;
2800         int i;
2801         proxyinfo_t pi;
2802
2803         INTERNET_LoadProxySettings(&pi);
2804
2805         for (i = 0; i < con->dwOptionCount; i++) {
2806             INTERNET_PER_CONN_OPTIONW *option = con->pOptions + i;
2807
2808             switch (option->dwOption) {
2809             case INTERNET_PER_CONN_PROXY_SERVER:
2810                 heap_free(pi.proxy);
2811                 pi.proxy = heap_strdupW(option->Value.pszValue);
2812                 break;
2813
2814             case INTERNET_PER_CONN_FLAGS:
2815                 if(option->Value.dwValue & PROXY_TYPE_PROXY)
2816                     pi.proxyEnabled = 1;
2817                 else
2818                 {
2819                     if(option->Value.dwValue != PROXY_TYPE_DIRECT)
2820                         FIXME("Unhandled flags: 0x%x\n", option->Value.dwValue);
2821                     pi.proxyEnabled = 0;
2822                 }
2823                 break;
2824
2825             case INTERNET_PER_CONN_AUTOCONFIG_URL:
2826             case INTERNET_PER_CONN_AUTODISCOVERY_FLAGS:
2827             case INTERNET_PER_CONN_AUTOCONFIG_SECONDARY_URL:
2828             case INTERNET_PER_CONN_AUTOCONFIG_RELOAD_DELAY_MINS:
2829             case INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_TIME:
2830             case INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_URL:
2831             case INTERNET_PER_CONN_PROXY_BYPASS:
2832                 FIXME("Unhandled dwOption %d\n", option->dwOption);
2833                 break;
2834
2835             default:
2836                 FIXME("Unknown dwOption %d\n", option->dwOption);
2837                 SetLastError(ERROR_INVALID_PARAMETER);
2838                 break;
2839             }
2840         }
2841
2842         if ((res = INTERNET_SaveProxySettings(&pi)))
2843             SetLastError(res);
2844
2845         FreeProxyInfo(&pi);
2846
2847         ret = (res == ERROR_SUCCESS);
2848         break;
2849         }
2850     default:
2851         FIXME("Option %d STUB\n",dwOption);
2852         SetLastError(ERROR_INTERNET_INVALID_OPTION);
2853         ret = FALSE;
2854         break;
2855     }
2856
2857     if(lpwhh)
2858         WININET_Release( lpwhh );
2859
2860     return ret;
2861 }
2862
2863
2864 /***********************************************************************
2865  *           InternetSetOptionA (WININET.@)
2866  *
2867  * Sets an options on the specified handle.
2868  *
2869  * RETURNS
2870  *    TRUE  on success
2871  *    FALSE on failure
2872  *
2873  */
2874 BOOL WINAPI InternetSetOptionA(HINTERNET hInternet, DWORD dwOption,
2875                            LPVOID lpBuffer, DWORD dwBufferLength)
2876 {
2877     LPVOID wbuffer;
2878     DWORD wlen;
2879     BOOL r;
2880
2881     switch( dwOption )
2882     {
2883     case INTERNET_OPTION_PROXY:
2884         {
2885         LPINTERNET_PROXY_INFOA pi = (LPINTERNET_PROXY_INFOA) lpBuffer;
2886         LPINTERNET_PROXY_INFOW piw;
2887         DWORD proxlen, prbylen;
2888         LPWSTR prox, prby;
2889
2890         proxlen = MultiByteToWideChar( CP_ACP, 0, pi->lpszProxy, -1, NULL, 0);
2891         prbylen= MultiByteToWideChar( CP_ACP, 0, pi->lpszProxyBypass, -1, NULL, 0);
2892         wlen = sizeof(*piw) + proxlen + prbylen;
2893         wbuffer = heap_alloc(wlen*sizeof(WCHAR) );
2894         piw = (LPINTERNET_PROXY_INFOW) wbuffer;
2895         piw->dwAccessType = pi->dwAccessType;
2896         prox = (LPWSTR) &piw[1];
2897         prby = &prox[proxlen+1];
2898         MultiByteToWideChar( CP_ACP, 0, pi->lpszProxy, -1, prox, proxlen);
2899         MultiByteToWideChar( CP_ACP, 0, pi->lpszProxyBypass, -1, prby, prbylen);
2900         piw->lpszProxy = prox;
2901         piw->lpszProxyBypass = prby;
2902         }
2903         break;
2904     case INTERNET_OPTION_USER_AGENT:
2905     case INTERNET_OPTION_USERNAME:
2906     case INTERNET_OPTION_PASSWORD:
2907         wlen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, dwBufferLength,
2908                                    NULL, 0 );
2909         wbuffer = heap_alloc(wlen*sizeof(WCHAR) );
2910         MultiByteToWideChar( CP_ACP, 0, lpBuffer, dwBufferLength,
2911                                    wbuffer, wlen );
2912         break;
2913     case INTERNET_OPTION_PER_CONNECTION_OPTION: {
2914         int i;
2915         INTERNET_PER_CONN_OPTION_LISTW *listW;
2916         INTERNET_PER_CONN_OPTION_LISTA *listA = lpBuffer;
2917         wlen = sizeof(INTERNET_PER_CONN_OPTION_LISTW);
2918         wbuffer = heap_alloc(wlen);
2919         listW = wbuffer;
2920
2921         listW->dwSize = sizeof(INTERNET_PER_CONN_OPTION_LISTW);
2922         if (listA->pszConnection)
2923         {
2924             wlen = MultiByteToWideChar( CP_ACP, 0, listA->pszConnection, -1, NULL, 0 );
2925             listW->pszConnection = heap_alloc(wlen*sizeof(WCHAR));
2926             MultiByteToWideChar( CP_ACP, 0, listA->pszConnection, -1, listW->pszConnection, wlen );
2927         }
2928         else
2929             listW->pszConnection = NULL;
2930         listW->dwOptionCount = listA->dwOptionCount;
2931         listW->dwOptionError = listA->dwOptionError;
2932         listW->pOptions = heap_alloc(sizeof(INTERNET_PER_CONN_OPTIONW) * listA->dwOptionCount);
2933
2934         for (i = 0; i < listA->dwOptionCount; ++i) {
2935             INTERNET_PER_CONN_OPTIONA *optA = listA->pOptions + i;
2936             INTERNET_PER_CONN_OPTIONW *optW = listW->pOptions + i;
2937
2938             optW->dwOption = optA->dwOption;
2939
2940             switch (optA->dwOption) {
2941             case INTERNET_PER_CONN_AUTOCONFIG_URL:
2942             case INTERNET_PER_CONN_PROXY_BYPASS:
2943             case INTERNET_PER_CONN_PROXY_SERVER:
2944             case INTERNET_PER_CONN_AUTOCONFIG_SECONDARY_URL:
2945             case INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_URL:
2946                 if (optA->Value.pszValue)
2947                 {
2948                     wlen = MultiByteToWideChar( CP_ACP, 0, optA->Value.pszValue, -1, NULL, 0 );
2949                     optW->Value.pszValue = heap_alloc(wlen*sizeof(WCHAR));
2950                     MultiByteToWideChar( CP_ACP, 0, optA->Value.pszValue, -1, optW->Value.pszValue, wlen );
2951                 }
2952                 else
2953                     optW->Value.pszValue = NULL;
2954                 break;
2955             case INTERNET_PER_CONN_AUTODISCOVERY_FLAGS:
2956             case INTERNET_PER_CONN_FLAGS:
2957             case INTERNET_PER_CONN_AUTOCONFIG_RELOAD_DELAY_MINS:
2958                 optW->Value.dwValue = optA->Value.dwValue;
2959                 break;
2960             case INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_TIME:
2961                 optW->Value.ftValue = optA->Value.ftValue;
2962                 break;
2963             default:
2964                 WARN("Unknown PER_CONN dwOption: %d, guessing at conversion to Wide\n", optA->dwOption);
2965                 optW->Value.dwValue = optA->Value.dwValue;
2966                 break;
2967             }
2968         }
2969         }
2970         break;
2971     default:
2972         wbuffer = lpBuffer;
2973         wlen = dwBufferLength;
2974     }
2975
2976     r = InternetSetOptionW(hInternet,dwOption, wbuffer, wlen);
2977
2978     if( lpBuffer != wbuffer )
2979     {
2980         if (dwOption == INTERNET_OPTION_PER_CONNECTION_OPTION)
2981         {
2982             INTERNET_PER_CONN_OPTION_LISTW *list = wbuffer;
2983             int i;
2984             for (i = 0; i < list->dwOptionCount; ++i) {
2985                 INTERNET_PER_CONN_OPTIONW *opt = list->pOptions + i;
2986                 switch (opt->dwOption) {
2987                 case INTERNET_PER_CONN_AUTOCONFIG_URL:
2988                 case INTERNET_PER_CONN_PROXY_BYPASS:
2989                 case INTERNET_PER_CONN_PROXY_SERVER:
2990                 case INTERNET_PER_CONN_AUTOCONFIG_SECONDARY_URL:
2991                 case INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_URL:
2992                     heap_free( opt->Value.pszValue );
2993                     break;
2994                 default:
2995                     break;
2996                 }
2997             }
2998             heap_free( list->pOptions );
2999         }
3000         heap_free( wbuffer );
3001     }
3002
3003     return r;
3004 }
3005
3006
3007 /***********************************************************************
3008  *           InternetSetOptionExA (WININET.@)
3009  */
3010 BOOL WINAPI InternetSetOptionExA(HINTERNET hInternet, DWORD dwOption,
3011                            LPVOID lpBuffer, DWORD dwBufferLength, DWORD dwFlags)
3012 {
3013     FIXME("Flags %08x ignored\n", dwFlags);
3014     return InternetSetOptionA( hInternet, dwOption, lpBuffer, dwBufferLength );
3015 }
3016
3017 /***********************************************************************
3018  *           InternetSetOptionExW (WININET.@)
3019  */
3020 BOOL WINAPI InternetSetOptionExW(HINTERNET hInternet, DWORD dwOption,
3021                            LPVOID lpBuffer, DWORD dwBufferLength, DWORD dwFlags)
3022 {
3023     FIXME("Flags %08x ignored\n", dwFlags);
3024     if( dwFlags & ~ISO_VALID_FLAGS )
3025     {
3026         SetLastError( ERROR_INVALID_PARAMETER );
3027         return FALSE;
3028     }
3029     return InternetSetOptionW( hInternet, dwOption, lpBuffer, dwBufferLength );
3030 }
3031
3032 static const WCHAR WININET_wkday[7][4] =
3033     { { 'S','u','n', 0 }, { 'M','o','n', 0 }, { 'T','u','e', 0 }, { 'W','e','d', 0 },
3034       { 'T','h','u', 0 }, { 'F','r','i', 0 }, { 'S','a','t', 0 } };
3035 static const WCHAR WININET_month[12][4] =
3036     { { 'J','a','n', 0 }, { 'F','e','b', 0 }, { 'M','a','r', 0 }, { 'A','p','r', 0 },
3037       { 'M','a','y', 0 }, { 'J','u','n', 0 }, { 'J','u','l', 0 }, { 'A','u','g', 0 },
3038       { 'S','e','p', 0 }, { 'O','c','t', 0 }, { 'N','o','v', 0 }, { 'D','e','c', 0 } };
3039
3040 /***********************************************************************
3041  *           InternetTimeFromSystemTimeA (WININET.@)
3042  */
3043 BOOL WINAPI InternetTimeFromSystemTimeA( const SYSTEMTIME* time, DWORD format, LPSTR string, DWORD size )
3044 {
3045     BOOL ret;
3046     WCHAR stringW[INTERNET_RFC1123_BUFSIZE];
3047
3048     TRACE( "%p 0x%08x %p 0x%08x\n", time, format, string, size );
3049
3050     if (!time || !string || format != INTERNET_RFC1123_FORMAT)
3051     {
3052         SetLastError(ERROR_INVALID_PARAMETER);
3053         return FALSE;
3054     }
3055
3056     if (size < INTERNET_RFC1123_BUFSIZE * sizeof(*string))
3057     {
3058         SetLastError(ERROR_INSUFFICIENT_BUFFER);
3059         return FALSE;
3060     }
3061
3062     ret = InternetTimeFromSystemTimeW( time, format, stringW, sizeof(stringW) );
3063     if (ret) WideCharToMultiByte( CP_ACP, 0, stringW, -1, string, size, NULL, NULL );
3064
3065     return ret;
3066 }
3067
3068 /***********************************************************************
3069  *           InternetTimeFromSystemTimeW (WININET.@)
3070  */
3071 BOOL WINAPI InternetTimeFromSystemTimeW( const SYSTEMTIME* time, DWORD format, LPWSTR string, DWORD size )
3072 {
3073     static const WCHAR date[] =
3074         { '%','s',',',' ','%','0','2','d',' ','%','s',' ','%','4','d',' ','%','0',
3075           '2','d',':','%','0','2','d',':','%','0','2','d',' ','G','M','T', 0 };
3076
3077     TRACE( "%p 0x%08x %p 0x%08x\n", time, format, string, size );
3078
3079     if (!time || !string || format != INTERNET_RFC1123_FORMAT)
3080     {
3081         SetLastError(ERROR_INVALID_PARAMETER);
3082         return FALSE;
3083     }
3084
3085     if (size < INTERNET_RFC1123_BUFSIZE * sizeof(*string))
3086     {
3087         SetLastError(ERROR_INSUFFICIENT_BUFFER);
3088         return FALSE;
3089     }
3090
3091     sprintfW( string, date,
3092               WININET_wkday[time->wDayOfWeek],
3093               time->wDay,
3094               WININET_month[time->wMonth - 1],
3095               time->wYear,
3096               time->wHour,
3097               time->wMinute,
3098               time->wSecond );
3099
3100     return TRUE;
3101 }
3102
3103 /***********************************************************************
3104  *           InternetTimeToSystemTimeA (WININET.@)
3105  */
3106 BOOL WINAPI InternetTimeToSystemTimeA( LPCSTR string, SYSTEMTIME* time, DWORD reserved )
3107 {
3108     BOOL ret = FALSE;
3109     WCHAR *stringW;
3110
3111     TRACE( "%s %p 0x%08x\n", debugstr_a(string), time, reserved );
3112
3113     stringW = heap_strdupAtoW(string);
3114     if (stringW)
3115     {
3116         ret = InternetTimeToSystemTimeW( stringW, time, reserved );
3117         heap_free( stringW );
3118     }
3119     return ret;
3120 }
3121
3122 /***********************************************************************
3123  *           InternetTimeToSystemTimeW (WININET.@)
3124  */
3125 BOOL WINAPI InternetTimeToSystemTimeW( LPCWSTR string, SYSTEMTIME* time, DWORD reserved )
3126 {
3127     unsigned int i;
3128     const WCHAR *s = string;
3129     WCHAR       *end;
3130
3131     TRACE( "%s %p 0x%08x\n", debugstr_w(string), time, reserved );
3132
3133     if (!string || !time) return FALSE;
3134
3135     /* Windows does this too */
3136     GetSystemTime( time );
3137
3138     /*  Convert an RFC1123 time such as 'Fri, 07 Jan 2005 12:06:35 GMT' into
3139      *  a SYSTEMTIME structure.
3140      */
3141
3142     while (*s && !isalphaW( *s )) s++;
3143     if (s[0] == '\0' || s[1] == '\0' || s[2] == '\0') return TRUE;
3144     time->wDayOfWeek = 7;
3145
3146     for (i = 0; i < 7; i++)
3147     {
3148         if (toupperW( WININET_wkday[i][0] ) == toupperW( s[0] ) &&
3149             toupperW( WININET_wkday[i][1] ) == toupperW( s[1] ) &&
3150             toupperW( WININET_wkday[i][2] ) == toupperW( s[2] ) )
3151         {
3152             time->wDayOfWeek = i;
3153             break;
3154         }
3155     }
3156
3157     if (time->wDayOfWeek > 6) return TRUE;
3158     while (*s && !isdigitW( *s )) s++;
3159     time->wDay = strtolW( s, &end, 10 );
3160     s = end;
3161
3162     while (*s && !isalphaW( *s )) s++;
3163     if (s[0] == '\0' || s[1] == '\0' || s[2] == '\0') return TRUE;
3164     time->wMonth = 0;
3165
3166     for (i = 0; i < 12; i++)
3167     {
3168         if (toupperW( WININET_month[i][0]) == toupperW( s[0] ) &&
3169             toupperW( WININET_month[i][1]) == toupperW( s[1] ) &&
3170             toupperW( WININET_month[i][2]) == toupperW( s[2] ) )
3171         {
3172             time->wMonth = i + 1;
3173             break;
3174         }
3175     }
3176     if (time->wMonth == 0) return TRUE;
3177
3178     while (*s && !isdigitW( *s )) s++;
3179     if (*s == '\0') return TRUE;
3180     time->wYear = strtolW( s, &end, 10 );
3181     s = end;
3182
3183     while (*s && !isdigitW( *s )) s++;
3184     if (*s == '\0') return TRUE;
3185     time->wHour = strtolW( s, &end, 10 );
3186     s = end;
3187
3188     while (*s && !isdigitW( *s )) s++;
3189     if (*s == '\0') return TRUE;
3190     time->wMinute = strtolW( s, &end, 10 );
3191     s = end;
3192
3193     while (*s && !isdigitW( *s )) s++;
3194     if (*s == '\0') return TRUE;
3195     time->wSecond = strtolW( s, &end, 10 );
3196     s = end;
3197
3198     time->wMilliseconds = 0;
3199     return TRUE;
3200 }
3201
3202 /***********************************************************************
3203  *      InternetCheckConnectionW (WININET.@)
3204  *
3205  * Pings a requested host to check internet connection
3206  *
3207  * RETURNS
3208  *   TRUE on success and FALSE on failure. If a failure then
3209  *   ERROR_NOT_CONNECTED is placed into GetLastError
3210  *
3211  */
3212 BOOL WINAPI InternetCheckConnectionW( LPCWSTR lpszUrl, DWORD dwFlags, DWORD dwReserved )
3213 {
3214 /*
3215  * this is a kludge which runs the resident ping program and reads the output.
3216  *
3217  * Anyone have a better idea?
3218  */
3219
3220   BOOL   rc = FALSE;
3221   static const CHAR ping[] = "ping -c 1 ";
3222   static const CHAR redirect[] = " >/dev/null 2>/dev/null";
3223   CHAR *command = NULL;
3224   WCHAR hostW[INTERNET_MAX_HOST_NAME_LENGTH];
3225   DWORD len;
3226   INTERNET_PORT port;
3227   int status = -1;
3228
3229   FIXME("\n");
3230
3231   /*
3232    * Crack or set the Address
3233    */
3234   if (lpszUrl == NULL)
3235   {
3236      /*
3237       * According to the doc we are supposed to use the ip for the next
3238       * server in the WnInet internal server database. I have
3239       * no idea what that is or how to get it.
3240       *
3241       * So someone needs to implement this.
3242       */
3243      FIXME("Unimplemented with URL of NULL\n");
3244      return TRUE;
3245   }
3246   else
3247   {
3248      URL_COMPONENTSW components;
3249
3250      ZeroMemory(&components,sizeof(URL_COMPONENTSW));
3251      components.lpszHostName = (LPWSTR)hostW;
3252      components.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
3253
3254      if (!InternetCrackUrlW(lpszUrl,0,0,&components))
3255        goto End;
3256
3257      TRACE("host name : %s\n",debugstr_w(components.lpszHostName));
3258      port = components.nPort;
3259      TRACE("port: %d\n", port);
3260   }
3261
3262   if (dwFlags & FLAG_ICC_FORCE_CONNECTION)
3263   {
3264       struct sockaddr_storage saddr;
3265       socklen_t sa_len = sizeof(saddr);
3266       int fd;
3267
3268       if (!GetAddress(hostW, port, (struct sockaddr *)&saddr, &sa_len))
3269           goto End;
3270       fd = socket(saddr.ss_family, SOCK_STREAM, 0);
3271       if (fd != -1)
3272       {
3273           if (connect(fd, (struct sockaddr *)&saddr, sa_len) == 0)
3274               rc = TRUE;
3275           close(fd);
3276       }
3277   }
3278   else
3279   {
3280       /*
3281        * Build our ping command
3282        */
3283       len = WideCharToMultiByte(CP_UNIXCP, 0, hostW, -1, NULL, 0, NULL, NULL);
3284       command = heap_alloc(strlen(ping)+len+strlen(redirect));
3285       strcpy(command,ping);
3286       WideCharToMultiByte(CP_UNIXCP, 0, hostW, -1, command+strlen(ping), len, NULL, NULL);
3287       strcat(command,redirect);
3288
3289       TRACE("Ping command is : %s\n",command);
3290
3291       status = system(command);
3292
3293       TRACE("Ping returned a code of %i\n",status);
3294
3295       /* Ping return code of 0 indicates success */
3296       if (status == 0)
3297          rc = TRUE;
3298   }
3299
3300 End:
3301   heap_free( command );
3302   if (rc == FALSE)
3303     INTERNET_SetLastError(ERROR_NOT_CONNECTED);
3304
3305   return rc;
3306 }
3307
3308
3309 /***********************************************************************
3310  *      InternetCheckConnectionA (WININET.@)
3311  *
3312  * Pings a requested host to check internet connection
3313  *
3314  * RETURNS
3315  *   TRUE on success and FALSE on failure. If a failure then
3316  *   ERROR_NOT_CONNECTED is placed into GetLastError
3317  *
3318  */
3319 BOOL WINAPI InternetCheckConnectionA(LPCSTR lpszUrl, DWORD dwFlags, DWORD dwReserved)
3320 {
3321     WCHAR *url = NULL;
3322     BOOL rc;
3323
3324     if(lpszUrl) {
3325         url = heap_strdupAtoW(lpszUrl);
3326         if(!url)
3327             return FALSE;
3328     }
3329
3330     rc = InternetCheckConnectionW(url, dwFlags, dwReserved);
3331
3332     heap_free(url);
3333     return rc;
3334 }
3335
3336
3337 /**********************************************************
3338  *      INTERNET_InternetOpenUrlW (internal)
3339  *
3340  * Opens an URL
3341  *
3342  * RETURNS
3343  *   handle of connection or NULL on failure
3344  */
3345 static HINTERNET INTERNET_InternetOpenUrlW(appinfo_t *hIC, LPCWSTR lpszUrl,
3346     LPCWSTR lpszHeaders, DWORD dwHeadersLength, DWORD dwFlags, DWORD_PTR dwContext)
3347 {
3348     URL_COMPONENTSW urlComponents;
3349     WCHAR protocol[INTERNET_MAX_SCHEME_LENGTH];
3350     WCHAR hostName[INTERNET_MAX_HOST_NAME_LENGTH];
3351     WCHAR userName[INTERNET_MAX_USER_NAME_LENGTH];
3352     WCHAR password[INTERNET_MAX_PASSWORD_LENGTH];
3353     WCHAR path[INTERNET_MAX_PATH_LENGTH];
3354     WCHAR extra[1024];
3355     HINTERNET client = NULL, client1 = NULL;
3356     DWORD res;
3357     
3358     TRACE("(%p, %s, %s, %08x, %08x, %08lx)\n", hIC, debugstr_w(lpszUrl), debugstr_w(lpszHeaders),
3359           dwHeadersLength, dwFlags, dwContext);
3360     
3361     urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
3362     urlComponents.lpszScheme = protocol;
3363     urlComponents.dwSchemeLength = INTERNET_MAX_SCHEME_LENGTH;
3364     urlComponents.lpszHostName = hostName;
3365     urlComponents.dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
3366     urlComponents.lpszUserName = userName;
3367     urlComponents.dwUserNameLength = INTERNET_MAX_USER_NAME_LENGTH;
3368     urlComponents.lpszPassword = password;
3369     urlComponents.dwPasswordLength = INTERNET_MAX_PASSWORD_LENGTH;
3370     urlComponents.lpszUrlPath = path;
3371     urlComponents.dwUrlPathLength = INTERNET_MAX_PATH_LENGTH;
3372     urlComponents.lpszExtraInfo = extra;
3373     urlComponents.dwExtraInfoLength = 1024;
3374     if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
3375         return NULL;
3376     switch(urlComponents.nScheme) {
3377     case INTERNET_SCHEME_FTP:
3378         if(urlComponents.nPort == 0)
3379             urlComponents.nPort = INTERNET_DEFAULT_FTP_PORT;
3380         client = FTP_Connect(hIC, hostName, urlComponents.nPort,
3381                              userName, password, dwFlags, dwContext, INET_OPENURL);
3382         if(client == NULL)
3383             break;
3384         client1 = FtpOpenFileW(client, path, GENERIC_READ, dwFlags, dwContext);
3385         if(client1 == NULL) {
3386             InternetCloseHandle(client);
3387             break;
3388         }
3389         break;
3390         
3391     case INTERNET_SCHEME_HTTP:
3392     case INTERNET_SCHEME_HTTPS: {
3393         static const WCHAR szStars[] = { '*','/','*', 0 };
3394         LPCWSTR accept[2] = { szStars, NULL };
3395         if(urlComponents.nPort == 0) {
3396             if(urlComponents.nScheme == INTERNET_SCHEME_HTTP)
3397                 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
3398             else
3399                 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
3400         }
3401         if (urlComponents.nScheme == INTERNET_SCHEME_HTTPS) dwFlags |= INTERNET_FLAG_SECURE;
3402
3403         /* FIXME: should use pointers, not handles, as handles are not thread-safe */
3404         res = HTTP_Connect(hIC, hostName, urlComponents.nPort,
3405                            userName, password, dwFlags, dwContext, INET_OPENURL, &client);
3406         if(res != ERROR_SUCCESS) {
3407             INTERNET_SetLastError(res);
3408             break;
3409         }
3410
3411         if (urlComponents.dwExtraInfoLength) {
3412                 WCHAR *path_extra;
3413                 DWORD len = urlComponents.dwUrlPathLength + urlComponents.dwExtraInfoLength + 1;
3414
3415                 if (!(path_extra = heap_alloc(len * sizeof(WCHAR))))
3416                 {
3417                         InternetCloseHandle(client);
3418                         break;
3419                 }
3420                 strcpyW(path_extra, urlComponents.lpszUrlPath);
3421                 strcatW(path_extra, urlComponents.lpszExtraInfo);
3422                 client1 = HttpOpenRequestW(client, NULL, path_extra, NULL, NULL, accept, dwFlags, dwContext);
3423                 heap_free(path_extra);
3424         }
3425         else
3426                 client1 = HttpOpenRequestW(client, NULL, path, NULL, NULL, accept, dwFlags, dwContext);
3427
3428         if(client1 == NULL) {
3429             InternetCloseHandle(client);
3430             break;
3431         }
3432         HttpAddRequestHeadersW(client1, lpszHeaders, dwHeadersLength, HTTP_ADDREQ_FLAG_ADD);
3433         if (!HttpSendRequestW(client1, NULL, 0, NULL, 0) &&
3434             GetLastError() != ERROR_IO_PENDING) {
3435             InternetCloseHandle(client1);
3436             client1 = NULL;
3437             break;
3438         }
3439     }
3440     case INTERNET_SCHEME_GOPHER:
3441         /* gopher doesn't seem to be implemented in wine, but it's supposed
3442          * to be supported by InternetOpenUrlA. */
3443     default:
3444         SetLastError(ERROR_INTERNET_UNRECOGNIZED_SCHEME);
3445         break;
3446     }
3447
3448     TRACE(" %p <--\n", client1);
3449     
3450     return client1;
3451 }
3452
3453 /**********************************************************
3454  *      InternetOpenUrlW (WININET.@)
3455  *
3456  * Opens an URL
3457  *
3458  * RETURNS
3459  *   handle of connection or NULL on failure
3460  */
3461 static void AsyncInternetOpenUrlProc(WORKREQUEST *workRequest)
3462 {
3463     struct WORKREQ_INTERNETOPENURLW const *req = &workRequest->u.InternetOpenUrlW;
3464     appinfo_t *hIC = (appinfo_t*) workRequest->hdr;
3465
3466     TRACE("%p\n", hIC);
3467
3468     INTERNET_InternetOpenUrlW(hIC, req->lpszUrl,
3469                               req->lpszHeaders, req->dwHeadersLength, req->dwFlags, req->dwContext);
3470     heap_free(req->lpszUrl);
3471     heap_free(req->lpszHeaders);
3472 }
3473
3474 HINTERNET WINAPI InternetOpenUrlW(HINTERNET hInternet, LPCWSTR lpszUrl,
3475     LPCWSTR lpszHeaders, DWORD dwHeadersLength, DWORD dwFlags, DWORD_PTR dwContext)
3476 {
3477     HINTERNET ret = NULL;
3478     appinfo_t *hIC = NULL;
3479
3480     if (TRACE_ON(wininet)) {
3481         TRACE("(%p, %s, %s, %08x, %08x, %08lx)\n", hInternet, debugstr_w(lpszUrl), debugstr_w(lpszHeaders),
3482               dwHeadersLength, dwFlags, dwContext);
3483         TRACE("  flags :");
3484         dump_INTERNET_FLAGS(dwFlags);
3485     }
3486
3487     if (!lpszUrl)
3488     {
3489         SetLastError(ERROR_INVALID_PARAMETER);
3490         goto lend;
3491     }
3492
3493     hIC = (appinfo_t*)get_handle_object( hInternet );
3494     if (NULL == hIC ||  hIC->hdr.htype != WH_HINIT) {
3495         SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
3496         goto lend;
3497     }
3498     
3499     if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC) {
3500         WORKREQUEST workRequest;
3501         struct WORKREQ_INTERNETOPENURLW *req;
3502
3503         workRequest.asyncproc = AsyncInternetOpenUrlProc;
3504         workRequest.hdr = WININET_AddRef( &hIC->hdr );
3505         req = &workRequest.u.InternetOpenUrlW;
3506         req->lpszUrl = heap_strdupW(lpszUrl);
3507         req->lpszHeaders = heap_strdupW(lpszHeaders);
3508         req->dwHeadersLength = dwHeadersLength;
3509         req->dwFlags = dwFlags;
3510         req->dwContext = dwContext;
3511         
3512         INTERNET_AsyncCall(&workRequest);
3513         /*
3514          * This is from windows.
3515          */
3516         SetLastError(ERROR_IO_PENDING);
3517     } else {
3518         ret = INTERNET_InternetOpenUrlW(hIC, lpszUrl, lpszHeaders, dwHeadersLength, dwFlags, dwContext);
3519     }
3520     
3521   lend:
3522     if( hIC )
3523         WININET_Release( &hIC->hdr );
3524     TRACE(" %p <--\n", ret);
3525     
3526     return ret;
3527 }
3528
3529 /**********************************************************
3530  *      InternetOpenUrlA (WININET.@)
3531  *
3532  * Opens an URL
3533  *
3534  * RETURNS
3535  *   handle of connection or NULL on failure
3536  */
3537 HINTERNET WINAPI InternetOpenUrlA(HINTERNET hInternet, LPCSTR lpszUrl,
3538     LPCSTR lpszHeaders, DWORD dwHeadersLength, DWORD dwFlags, DWORD_PTR dwContext)
3539 {
3540     HINTERNET rc = NULL;
3541     DWORD lenHeaders = 0;
3542     LPWSTR szUrl = NULL;
3543     LPWSTR szHeaders = NULL;
3544
3545     TRACE("\n");
3546
3547     if(lpszUrl) {
3548         szUrl = heap_strdupAtoW(lpszUrl);
3549         if(!szUrl)
3550             return NULL;
3551     }
3552
3553     if(lpszHeaders) {
3554         lenHeaders = MultiByteToWideChar(CP_ACP, 0, lpszHeaders, dwHeadersLength, NULL, 0 );
3555         szHeaders = heap_alloc(lenHeaders*sizeof(WCHAR));
3556         if(!szHeaders) {
3557             heap_free(szUrl);
3558             return NULL;
3559         }
3560         MultiByteToWideChar(CP_ACP, 0, lpszHeaders, dwHeadersLength, szHeaders, lenHeaders);
3561     }
3562     
3563     rc = InternetOpenUrlW(hInternet, szUrl, szHeaders,
3564         lenHeaders, dwFlags, dwContext);
3565
3566     heap_free(szUrl);
3567     heap_free(szHeaders);
3568     return rc;
3569 }
3570
3571
3572 static LPWITHREADERROR INTERNET_AllocThreadError(void)
3573 {
3574     LPWITHREADERROR lpwite = heap_alloc(sizeof(*lpwite));
3575
3576     if (lpwite)
3577     {
3578         lpwite->dwError = 0;
3579         lpwite->response[0] = '\0';
3580     }
3581
3582     if (!TlsSetValue(g_dwTlsErrIndex, lpwite))
3583     {
3584         heap_free(lpwite);
3585         return NULL;
3586     }
3587     return lpwite;
3588 }
3589
3590
3591 /***********************************************************************
3592  *           INTERNET_SetLastError (internal)
3593  *
3594  * Set last thread specific error
3595  *
3596  * RETURNS
3597  *
3598  */
3599 void INTERNET_SetLastError(DWORD dwError)
3600 {
3601     LPWITHREADERROR lpwite = TlsGetValue(g_dwTlsErrIndex);
3602
3603     if (!lpwite)
3604         lpwite = INTERNET_AllocThreadError();
3605
3606     SetLastError(dwError);
3607     if(lpwite)
3608         lpwite->dwError = dwError;
3609 }
3610
3611
3612 /***********************************************************************
3613  *           INTERNET_GetLastError (internal)
3614  *
3615  * Get last thread specific error
3616  *
3617  * RETURNS
3618  *
3619  */
3620 DWORD INTERNET_GetLastError(void)
3621 {
3622     LPWITHREADERROR lpwite = TlsGetValue(g_dwTlsErrIndex);
3623     if (!lpwite) return 0;
3624     /* TlsGetValue clears last error, so set it again here */
3625     SetLastError(lpwite->dwError);
3626     return lpwite->dwError;
3627 }
3628
3629
3630 /***********************************************************************
3631  *           INTERNET_WorkerThreadFunc (internal)
3632  *
3633  * Worker thread execution function
3634  *
3635  * RETURNS
3636  *
3637  */
3638 static DWORD CALLBACK INTERNET_WorkerThreadFunc(LPVOID lpvParam)
3639 {
3640     LPWORKREQUEST lpRequest = lpvParam;
3641     WORKREQUEST workRequest;
3642
3643     TRACE("\n");
3644
3645     workRequest = *lpRequest;
3646     heap_free(lpRequest);
3647
3648     workRequest.asyncproc(&workRequest);
3649     WININET_Release( workRequest.hdr );
3650
3651     if (g_dwTlsErrIndex != TLS_OUT_OF_INDEXES)
3652     {
3653         heap_free(TlsGetValue(g_dwTlsErrIndex));
3654         TlsSetValue(g_dwTlsErrIndex, NULL);
3655     }
3656     return TRUE;
3657 }
3658
3659
3660 /***********************************************************************
3661  *           INTERNET_AsyncCall (internal)
3662  *
3663  * Retrieves work request from queue
3664  *
3665  * RETURNS
3666  *
3667  */
3668 DWORD INTERNET_AsyncCall(LPWORKREQUEST lpWorkRequest)
3669 {
3670     BOOL bSuccess;
3671     LPWORKREQUEST lpNewRequest;
3672
3673     TRACE("\n");
3674
3675     lpNewRequest = heap_alloc(sizeof(WORKREQUEST));
3676     if (!lpNewRequest)
3677         return ERROR_OUTOFMEMORY;
3678
3679     *lpNewRequest = *lpWorkRequest;
3680
3681     bSuccess = QueueUserWorkItem(INTERNET_WorkerThreadFunc, lpNewRequest, WT_EXECUTELONGFUNCTION);
3682     if (!bSuccess)
3683     {
3684         heap_free(lpNewRequest);
3685         return ERROR_INTERNET_ASYNC_THREAD_FAILED;
3686     }
3687     return ERROR_SUCCESS;
3688 }
3689
3690
3691 /***********************************************************************
3692  *          INTERNET_GetResponseBuffer  (internal)
3693  *
3694  * RETURNS
3695  *
3696  */
3697 LPSTR INTERNET_GetResponseBuffer(void)
3698 {
3699     LPWITHREADERROR lpwite = TlsGetValue(g_dwTlsErrIndex);
3700     if (!lpwite)
3701         lpwite = INTERNET_AllocThreadError();
3702     TRACE("\n");
3703     return lpwite->response;
3704 }
3705
3706 /***********************************************************************
3707  *           INTERNET_GetNextLine  (internal)
3708  *
3709  * Parse next line in directory string listing
3710  *
3711  * RETURNS
3712  *   Pointer to beginning of next line
3713  *   NULL on failure
3714  *
3715  */
3716
3717 LPSTR INTERNET_GetNextLine(INT nSocket, LPDWORD dwLen)
3718 {
3719     struct pollfd pfd;
3720     BOOL bSuccess = FALSE;
3721     INT nRecv = 0;
3722     LPSTR lpszBuffer = INTERNET_GetResponseBuffer();
3723
3724     TRACE("\n");
3725
3726     pfd.fd = nSocket;
3727     pfd.events = POLLIN;
3728
3729     while (nRecv < MAX_REPLY_LEN)
3730     {
3731         if (poll(&pfd,1, RESPONSE_TIMEOUT * 1000) > 0)
3732         {
3733             if (recv(nSocket, &lpszBuffer[nRecv], 1, 0) <= 0)
3734             {
3735                 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
3736                 goto lend;
3737             }
3738
3739             if (lpszBuffer[nRecv] == '\n')
3740             {
3741                 bSuccess = TRUE;
3742                 break;
3743             }
3744             if (lpszBuffer[nRecv] != '\r')
3745                 nRecv++;
3746         }
3747         else
3748         {
3749             INTERNET_SetLastError(ERROR_INTERNET_TIMEOUT);
3750             goto lend;
3751         }
3752     }
3753
3754 lend:
3755     if (bSuccess)
3756     {
3757         lpszBuffer[nRecv] = '\0';
3758         *dwLen = nRecv - 1;
3759         TRACE(":%d %s\n", nRecv, lpszBuffer);
3760         return lpszBuffer;
3761     }
3762     else
3763     {
3764         return NULL;
3765     }
3766 }
3767
3768 /**********************************************************
3769  *      InternetQueryDataAvailable (WININET.@)
3770  *
3771  * Determines how much data is available to be read.
3772  *
3773  * RETURNS
3774  *   TRUE on success, FALSE if an error occurred. If
3775  *   INTERNET_FLAG_ASYNC was specified in InternetOpen, and
3776  *   no data is presently available, FALSE is returned with
3777  *   the last error ERROR_IO_PENDING; a callback with status
3778  *   INTERNET_STATUS_REQUEST_COMPLETE will be sent when more
3779  *   data is available.
3780  */
3781 BOOL WINAPI InternetQueryDataAvailable( HINTERNET hFile,
3782                                 LPDWORD lpdwNumberOfBytesAvailble,
3783                                 DWORD dwFlags, DWORD_PTR dwContext)
3784 {
3785     object_header_t *hdr;
3786     DWORD res;
3787
3788     TRACE("(%p %p %x %lx)\n", hFile, lpdwNumberOfBytesAvailble, dwFlags, dwContext);
3789
3790     hdr = get_handle_object( hFile );
3791     if (!hdr) {
3792         SetLastError(ERROR_INVALID_HANDLE);
3793         return FALSE;
3794     }
3795
3796     if(hdr->vtbl->QueryDataAvailable) {
3797         res = hdr->vtbl->QueryDataAvailable(hdr, lpdwNumberOfBytesAvailble, dwFlags, dwContext);
3798     }else {
3799         WARN("wrong handle\n");
3800         res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3801     }
3802
3803     WININET_Release(hdr);
3804
3805     if(res != ERROR_SUCCESS)
3806         SetLastError(res);
3807     return res == ERROR_SUCCESS;
3808 }
3809
3810
3811 /***********************************************************************
3812  *      InternetLockRequestFile (WININET.@)
3813  */
3814 BOOL WINAPI InternetLockRequestFile( HINTERNET hInternet, HANDLE
3815 *lphLockReqHandle)
3816 {
3817     FIXME("STUB\n");
3818     return FALSE;
3819 }
3820
3821 BOOL WINAPI InternetUnlockRequestFile( HANDLE hLockHandle)
3822 {
3823     FIXME("STUB\n");
3824     return FALSE;
3825 }
3826
3827
3828 /***********************************************************************
3829  *      InternetAutodial (WININET.@)
3830  *
3831  * On windows this function is supposed to dial the default internet
3832  * connection. We don't want to have Wine dial out to the internet so
3833  * we return TRUE by default. It might be nice to check if we are connected.
3834  *
3835  * RETURNS
3836  *   TRUE on success
3837  *   FALSE on failure
3838  *
3839  */
3840 BOOL WINAPI InternetAutodial(DWORD dwFlags, HWND hwndParent)
3841 {
3842     FIXME("STUB\n");
3843
3844     /* Tell that we are connected to the internet. */
3845     return TRUE;
3846 }
3847
3848 /***********************************************************************
3849  *      InternetAutodialHangup (WININET.@)
3850  *
3851  * Hangs up a connection made with InternetAutodial
3852  *
3853  * PARAM
3854  *    dwReserved
3855  * RETURNS
3856  *   TRUE on success
3857  *   FALSE on failure
3858  *
3859  */
3860 BOOL WINAPI InternetAutodialHangup(DWORD dwReserved)
3861 {
3862     FIXME("STUB\n");
3863
3864     /* we didn't dial, we don't disconnect */
3865     return TRUE;
3866 }
3867
3868 /***********************************************************************
3869  *      InternetCombineUrlA (WININET.@)
3870  *
3871  * Combine a base URL with a relative URL
3872  *
3873  * RETURNS
3874  *   TRUE on success
3875  *   FALSE on failure
3876  *
3877  */
3878
3879 BOOL WINAPI InternetCombineUrlA(LPCSTR lpszBaseUrl, LPCSTR lpszRelativeUrl,
3880                                 LPSTR lpszBuffer, LPDWORD lpdwBufferLength,
3881                                 DWORD dwFlags)
3882 {
3883     HRESULT hr=S_OK;
3884
3885     TRACE("(%s, %s, %p, %p, 0x%08x)\n", debugstr_a(lpszBaseUrl), debugstr_a(lpszRelativeUrl), lpszBuffer, lpdwBufferLength, dwFlags);
3886
3887     /* Flip this bit to correspond to URL_ESCAPE_UNSAFE */
3888     dwFlags ^= ICU_NO_ENCODE;
3889     hr=UrlCombineA(lpszBaseUrl,lpszRelativeUrl,lpszBuffer,lpdwBufferLength,dwFlags);
3890
3891     return (hr==S_OK);
3892 }
3893
3894 /***********************************************************************
3895  *      InternetCombineUrlW (WININET.@)
3896  *
3897  * Combine a base URL with a relative URL
3898  *
3899  * RETURNS
3900  *   TRUE on success
3901  *   FALSE on failure
3902  *
3903  */
3904
3905 BOOL WINAPI InternetCombineUrlW(LPCWSTR lpszBaseUrl, LPCWSTR lpszRelativeUrl,
3906                                 LPWSTR lpszBuffer, LPDWORD lpdwBufferLength,
3907                                 DWORD dwFlags)
3908 {
3909     HRESULT hr=S_OK;
3910
3911     TRACE("(%s, %s, %p, %p, 0x%08x)\n", debugstr_w(lpszBaseUrl), debugstr_w(lpszRelativeUrl), lpszBuffer, lpdwBufferLength, dwFlags);
3912
3913     /* Flip this bit to correspond to URL_ESCAPE_UNSAFE */
3914     dwFlags ^= ICU_NO_ENCODE;
3915     hr=UrlCombineW(lpszBaseUrl,lpszRelativeUrl,lpszBuffer,lpdwBufferLength,dwFlags);
3916
3917     return (hr==S_OK);
3918 }
3919
3920 /* max port num is 65535 => 5 digits */
3921 #define MAX_WORD_DIGITS 5
3922
3923 #define URL_GET_COMP_LENGTH(url, component) ((url)->dw##component##Length ? \
3924     (url)->dw##component##Length : strlenW((url)->lpsz##component))
3925 #define URL_GET_COMP_LENGTHA(url, component) ((url)->dw##component##Length ? \
3926     (url)->dw##component##Length : strlen((url)->lpsz##component))
3927
3928 static BOOL url_uses_default_port(INTERNET_SCHEME nScheme, INTERNET_PORT nPort)
3929 {
3930     if ((nScheme == INTERNET_SCHEME_HTTP) &&
3931         (nPort == INTERNET_DEFAULT_HTTP_PORT))
3932         return TRUE;
3933     if ((nScheme == INTERNET_SCHEME_HTTPS) &&
3934         (nPort == INTERNET_DEFAULT_HTTPS_PORT))
3935         return TRUE;
3936     if ((nScheme == INTERNET_SCHEME_FTP) &&
3937         (nPort == INTERNET_DEFAULT_FTP_PORT))
3938         return TRUE;
3939     if ((nScheme == INTERNET_SCHEME_GOPHER) &&
3940         (nPort == INTERNET_DEFAULT_GOPHER_PORT))
3941         return TRUE;
3942
3943     if (nPort == INTERNET_INVALID_PORT_NUMBER)
3944         return TRUE;
3945
3946     return FALSE;
3947 }
3948
3949 /* opaque urls do not fit into the standard url hierarchy and don't have
3950  * two following slashes */
3951 static inline BOOL scheme_is_opaque(INTERNET_SCHEME nScheme)
3952 {
3953     return (nScheme != INTERNET_SCHEME_FTP) &&
3954            (nScheme != INTERNET_SCHEME_GOPHER) &&
3955            (nScheme != INTERNET_SCHEME_HTTP) &&
3956            (nScheme != INTERNET_SCHEME_HTTPS) &&
3957            (nScheme != INTERNET_SCHEME_FILE);
3958 }
3959
3960 static LPCWSTR INTERNET_GetSchemeString(INTERNET_SCHEME scheme)
3961 {
3962     int index;
3963     if (scheme < INTERNET_SCHEME_FIRST)
3964         return NULL;
3965     index = scheme - INTERNET_SCHEME_FIRST;
3966     if (index >= sizeof(url_schemes)/sizeof(url_schemes[0]))
3967         return NULL;
3968     return (LPCWSTR)url_schemes[index];
3969 }
3970
3971 /* we can calculate using ansi strings because we're just
3972  * calculating string length, not size
3973  */
3974 static BOOL calc_url_length(LPURL_COMPONENTSW lpUrlComponents,
3975                             LPDWORD lpdwUrlLength)
3976 {
3977     INTERNET_SCHEME nScheme;
3978
3979     *lpdwUrlLength = 0;
3980
3981     if (lpUrlComponents->lpszScheme)
3982     {
3983         DWORD dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, Scheme);
3984         *lpdwUrlLength += dwLen;
3985         nScheme = GetInternetSchemeW(lpUrlComponents->lpszScheme, dwLen);
3986     }
3987     else
3988     {
3989         LPCWSTR scheme;
3990
3991         nScheme = lpUrlComponents->nScheme;
3992
3993         if (nScheme == INTERNET_SCHEME_DEFAULT)
3994             nScheme = INTERNET_SCHEME_HTTP;
3995         scheme = INTERNET_GetSchemeString(nScheme);
3996         *lpdwUrlLength += strlenW(scheme);
3997     }
3998
3999     (*lpdwUrlLength)++; /* ':' */
4000     if (!scheme_is_opaque(nScheme) || lpUrlComponents->lpszHostName)
4001         *lpdwUrlLength += strlen("//");
4002
4003     if (lpUrlComponents->lpszUserName)
4004     {
4005         *lpdwUrlLength += URL_GET_COMP_LENGTH(lpUrlComponents, UserName);
4006         *lpdwUrlLength += strlen("@");
4007     }
4008     else
4009     {
4010         if (lpUrlComponents->lpszPassword)
4011         {
4012             INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
4013             return FALSE;
4014         }
4015     }
4016
4017     if (lpUrlComponents->lpszPassword)
4018     {
4019         *lpdwUrlLength += strlen(":");
4020         *lpdwUrlLength += URL_GET_COMP_LENGTH(lpUrlComponents, Password);
4021     }
4022
4023     if (lpUrlComponents->lpszHostName)
4024     {
4025         *lpdwUrlLength += URL_GET_COMP_LENGTH(lpUrlComponents, HostName);
4026
4027         if (!url_uses_default_port(nScheme, lpUrlComponents->nPort))
4028         {
4029             char szPort[MAX_WORD_DIGITS+1];
4030
4031             sprintf(szPort, "%d", lpUrlComponents->nPort);
4032             *lpdwUrlLength += strlen(szPort);
4033             *lpdwUrlLength += strlen(":");
4034         }
4035
4036         if (lpUrlComponents->lpszUrlPath && *lpUrlComponents->lpszUrlPath != '/')
4037             (*lpdwUrlLength)++; /* '/' */
4038     }
4039
4040     if (lpUrlComponents->lpszUrlPath)
4041         *lpdwUrlLength += URL_GET_COMP_LENGTH(lpUrlComponents, UrlPath);
4042
4043     if (lpUrlComponents->lpszExtraInfo)
4044         *lpdwUrlLength += URL_GET_COMP_LENGTH(lpUrlComponents, ExtraInfo);
4045
4046     return TRUE;
4047 }
4048
4049 static void convert_urlcomp_atow(LPURL_COMPONENTSA lpUrlComponents, LPURL_COMPONENTSW urlCompW)
4050 {
4051     INT len;
4052
4053     ZeroMemory(urlCompW, sizeof(URL_COMPONENTSW));
4054
4055     urlCompW->dwStructSize = sizeof(URL_COMPONENTSW);
4056     urlCompW->dwSchemeLength = lpUrlComponents->dwSchemeLength;
4057     urlCompW->nScheme = lpUrlComponents->nScheme;
4058     urlCompW->dwHostNameLength = lpUrlComponents->dwHostNameLength;
4059     urlCompW->nPort = lpUrlComponents->nPort;
4060     urlCompW->dwUserNameLength = lpUrlComponents->dwUserNameLength;
4061     urlCompW->dwPasswordLength = lpUrlComponents->dwPasswordLength;
4062     urlCompW->dwUrlPathLength = lpUrlComponents->dwUrlPathLength;
4063     urlCompW->dwExtraInfoLength = lpUrlComponents->dwExtraInfoLength;
4064
4065     if (lpUrlComponents->lpszScheme)
4066     {
4067         len = URL_GET_COMP_LENGTHA(lpUrlComponents, Scheme) + 1;
4068         urlCompW->lpszScheme = heap_alloc(len * sizeof(WCHAR));
4069         MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszScheme,
4070                             -1, urlCompW->lpszScheme, len);
4071     }
4072
4073     if (lpUrlComponents->lpszHostName)
4074     {
4075         len = URL_GET_COMP_LENGTHA(lpUrlComponents, HostName) + 1;
4076         urlCompW->lpszHostName = heap_alloc(len * sizeof(WCHAR));
4077         MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszHostName,
4078                             -1, urlCompW->lpszHostName, len);
4079     }
4080
4081     if (lpUrlComponents->lpszUserName)
4082     {
4083         len = URL_GET_COMP_LENGTHA(lpUrlComponents, UserName) + 1;
4084         urlCompW->lpszUserName = heap_alloc(len * sizeof(WCHAR));
4085         MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszUserName,
4086                             -1, urlCompW->lpszUserName, len);
4087     }
4088
4089     if (lpUrlComponents->lpszPassword)
4090     {
4091         len = URL_GET_COMP_LENGTHA(lpUrlComponents, Password) + 1;
4092         urlCompW->lpszPassword = heap_alloc(len * sizeof(WCHAR));
4093         MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszPassword,
4094                             -1, urlCompW->lpszPassword, len);
4095     }
4096
4097     if (lpUrlComponents->lpszUrlPath)
4098     {
4099         len = URL_GET_COMP_LENGTHA(lpUrlComponents, UrlPath) + 1;
4100         urlCompW->lpszUrlPath = heap_alloc(len * sizeof(WCHAR));
4101         MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszUrlPath,
4102                             -1, urlCompW->lpszUrlPath, len);
4103     }
4104
4105     if (lpUrlComponents->lpszExtraInfo)
4106     {
4107         len = URL_GET_COMP_LENGTHA(lpUrlComponents, ExtraInfo) + 1;
4108         urlCompW->lpszExtraInfo = heap_alloc(len * sizeof(WCHAR));
4109         MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszExtraInfo,
4110                             -1, urlCompW->lpszExtraInfo, len);
4111     }
4112 }
4113
4114 /***********************************************************************
4115  *      InternetCreateUrlA (WININET.@)
4116  *
4117  * See InternetCreateUrlW.
4118  */
4119 BOOL WINAPI InternetCreateUrlA(LPURL_COMPONENTSA lpUrlComponents, DWORD dwFlags,
4120                                LPSTR lpszUrl, LPDWORD lpdwUrlLength)
4121 {
4122     BOOL ret;
4123     LPWSTR urlW = NULL;
4124     URL_COMPONENTSW urlCompW;
4125
4126     TRACE("(%p,%d,%p,%p)\n", lpUrlComponents, dwFlags, lpszUrl, lpdwUrlLength);
4127
4128     if (!lpUrlComponents || lpUrlComponents->dwStructSize != sizeof(URL_COMPONENTSW) || !lpdwUrlLength)
4129     {
4130         SetLastError(ERROR_INVALID_PARAMETER);
4131         return FALSE;
4132     }
4133
4134     convert_urlcomp_atow(lpUrlComponents, &urlCompW);
4135
4136     if (lpszUrl)
4137         urlW = heap_alloc(*lpdwUrlLength * sizeof(WCHAR));
4138
4139     ret = InternetCreateUrlW(&urlCompW, dwFlags, urlW, lpdwUrlLength);
4140
4141     if (!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER))
4142         *lpdwUrlLength /= sizeof(WCHAR);
4143
4144     /* on success, lpdwUrlLength points to the size of urlW in WCHARS
4145     * minus one, so add one to leave room for NULL terminator
4146     */
4147     if (ret)
4148         WideCharToMultiByte(CP_ACP, 0, urlW, -1, lpszUrl, *lpdwUrlLength + 1, NULL, NULL);
4149
4150     heap_free(urlCompW.lpszScheme);
4151     heap_free(urlCompW.lpszHostName);
4152     heap_free(urlCompW.lpszUserName);
4153     heap_free(urlCompW.lpszPassword);
4154     heap_free(urlCompW.lpszUrlPath);
4155     heap_free(urlCompW.lpszExtraInfo);
4156     heap_free(urlW);
4157     return ret;
4158 }
4159
4160 /***********************************************************************
4161  *      InternetCreateUrlW (WININET.@)
4162  *
4163  * Creates a URL from its component parts.
4164  *
4165  * PARAMS
4166  *  lpUrlComponents [I] URL Components.
4167  *  dwFlags         [I] Flags. See notes.
4168  *  lpszUrl         [I] Buffer in which to store the created URL.
4169  *  lpdwUrlLength   [I/O] On input, the length of the buffer pointed to by
4170  *                        lpszUrl in characters. On output, the number of bytes
4171  *                        required to store the URL including terminator.
4172  *
4173  * NOTES
4174  *
4175  * The dwFlags parameter can be zero or more of the following:
4176  *|ICU_ESCAPE - Generates escape sequences for unsafe characters in the path and extra info of the URL.
4177  *
4178  * RETURNS
4179  *   TRUE on success
4180  *   FALSE on failure
4181  *
4182  */
4183 BOOL WINAPI InternetCreateUrlW(LPURL_COMPONENTSW lpUrlComponents, DWORD dwFlags,
4184                                LPWSTR lpszUrl, LPDWORD lpdwUrlLength)
4185 {
4186     DWORD dwLen;
4187     INTERNET_SCHEME nScheme;
4188
4189     static const WCHAR slashSlashW[] = {'/','/'};
4190     static const WCHAR fmtW[] = {'%','u',0};
4191
4192     TRACE("(%p,%d,%p,%p)\n", lpUrlComponents, dwFlags, lpszUrl, lpdwUrlLength);
4193
4194     if (!lpUrlComponents || lpUrlComponents->dwStructSize != sizeof(URL_COMPONENTSW) || !lpdwUrlLength)
4195     {
4196         INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
4197         return FALSE;
4198     }
4199
4200     if (!calc_url_length(lpUrlComponents, &dwLen))
4201         return FALSE;
4202
4203     if (!lpszUrl || *lpdwUrlLength < dwLen)
4204     {
4205         *lpdwUrlLength = (dwLen + 1) * sizeof(WCHAR);
4206         INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
4207         return FALSE;
4208     }
4209
4210     *lpdwUrlLength = dwLen;
4211     lpszUrl[0] = 0x00;
4212
4213     dwLen = 0;
4214
4215     if (lpUrlComponents->lpszScheme)
4216     {
4217         dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, Scheme);
4218         memcpy(lpszUrl, lpUrlComponents->lpszScheme, dwLen * sizeof(WCHAR));
4219         lpszUrl += dwLen;
4220
4221         nScheme = GetInternetSchemeW(lpUrlComponents->lpszScheme, dwLen);
4222     }
4223     else
4224     {
4225         LPCWSTR scheme;
4226         nScheme = lpUrlComponents->nScheme;
4227
4228         if (nScheme == INTERNET_SCHEME_DEFAULT)
4229             nScheme = INTERNET_SCHEME_HTTP;
4230
4231         scheme = INTERNET_GetSchemeString(nScheme);
4232         dwLen = strlenW(scheme);
4233         memcpy(lpszUrl, scheme, dwLen * sizeof(WCHAR));
4234         lpszUrl += dwLen;
4235     }
4236
4237     /* all schemes are followed by at least a colon */
4238     *lpszUrl = ':';
4239     lpszUrl++;
4240
4241     if (!scheme_is_opaque(nScheme) || lpUrlComponents->lpszHostName)
4242     {
4243         memcpy(lpszUrl, slashSlashW, sizeof(slashSlashW));
4244         lpszUrl += sizeof(slashSlashW)/sizeof(slashSlashW[0]);
4245     }
4246
4247     if (lpUrlComponents->lpszUserName)
4248     {
4249         dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, UserName);
4250         memcpy(lpszUrl, lpUrlComponents->lpszUserName, dwLen * sizeof(WCHAR));
4251         lpszUrl += dwLen;
4252
4253         if (lpUrlComponents->lpszPassword)
4254         {
4255             *lpszUrl = ':';
4256             lpszUrl++;
4257
4258             dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, Password);
4259             memcpy(lpszUrl, lpUrlComponents->lpszPassword, dwLen * sizeof(WCHAR));
4260             lpszUrl += dwLen;
4261         }
4262
4263         *lpszUrl = '@';
4264         lpszUrl++;
4265     }
4266
4267     if (lpUrlComponents->lpszHostName)
4268     {
4269         dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, HostName);
4270         memcpy(lpszUrl, lpUrlComponents->lpszHostName, dwLen * sizeof(WCHAR));
4271         lpszUrl += dwLen;
4272
4273         if (!url_uses_default_port(nScheme, lpUrlComponents->nPort))
4274         {
4275             WCHAR szPort[MAX_WORD_DIGITS+1];
4276
4277             sprintfW(szPort, fmtW, lpUrlComponents->nPort);
4278             *lpszUrl = ':';
4279             lpszUrl++;
4280             dwLen = strlenW(szPort);
4281             memcpy(lpszUrl, szPort, dwLen * sizeof(WCHAR));
4282             lpszUrl += dwLen;
4283         }
4284
4285         /* add slash between hostname and path if necessary */
4286         if (lpUrlComponents->lpszUrlPath && *lpUrlComponents->lpszUrlPath != '/')
4287         {
4288             *lpszUrl = '/';
4289             lpszUrl++;
4290         }
4291     }
4292
4293     if (lpUrlComponents->lpszUrlPath)
4294     {
4295         dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, UrlPath);
4296         memcpy(lpszUrl, lpUrlComponents->lpszUrlPath, dwLen * sizeof(WCHAR));
4297         lpszUrl += dwLen;
4298     }
4299
4300     if (lpUrlComponents->lpszExtraInfo)
4301     {
4302         dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, ExtraInfo);
4303         memcpy(lpszUrl, lpUrlComponents->lpszExtraInfo, dwLen * sizeof(WCHAR));
4304         lpszUrl += dwLen;
4305     }
4306
4307     *lpszUrl = '\0';
4308
4309     return TRUE;
4310 }
4311
4312 /***********************************************************************
4313  *      InternetConfirmZoneCrossingA (WININET.@)
4314  *
4315  */
4316 DWORD WINAPI InternetConfirmZoneCrossingA( HWND hWnd, LPSTR szUrlPrev, LPSTR szUrlNew, BOOL bPost )
4317 {
4318     FIXME("(%p, %s, %s, %x) stub\n", hWnd, debugstr_a(szUrlPrev), debugstr_a(szUrlNew), bPost);
4319     return ERROR_SUCCESS;
4320 }
4321
4322 /***********************************************************************
4323  *      InternetConfirmZoneCrossingW (WININET.@)
4324  *
4325  */
4326 DWORD WINAPI InternetConfirmZoneCrossingW( HWND hWnd, LPWSTR szUrlPrev, LPWSTR szUrlNew, BOOL bPost )
4327 {
4328     FIXME("(%p, %s, %s, %x) stub\n", hWnd, debugstr_w(szUrlPrev), debugstr_w(szUrlNew), bPost);
4329     return ERROR_SUCCESS;
4330 }
4331
4332 static DWORD zone_preference = 3;
4333
4334 /***********************************************************************
4335  *      PrivacySetZonePreferenceW (WININET.@)
4336  */
4337 DWORD WINAPI PrivacySetZonePreferenceW( DWORD zone, DWORD type, DWORD template, LPCWSTR preference )
4338 {
4339     FIXME( "%x %x %x %s: stub\n", zone, type, template, debugstr_w(preference) );
4340
4341     zone_preference = template;
4342     return 0;
4343 }
4344
4345 /***********************************************************************
4346  *      PrivacyGetZonePreferenceW (WININET.@)
4347  */
4348 DWORD WINAPI PrivacyGetZonePreferenceW( DWORD zone, DWORD type, LPDWORD template,
4349                                         LPWSTR preference, LPDWORD length )
4350 {
4351     FIXME( "%x %x %p %p %p: stub\n", zone, type, template, preference, length );
4352
4353     if (template) *template = zone_preference;
4354     return 0;
4355 }
4356
4357 DWORD WINAPI InternetDialA( HWND hwndParent, LPSTR lpszConnectoid, DWORD dwFlags,
4358                             DWORD_PTR* lpdwConnection, DWORD dwReserved )
4359 {
4360     FIXME("(%p, %p, 0x%08x, %p, 0x%08x) stub\n", hwndParent, lpszConnectoid, dwFlags,
4361           lpdwConnection, dwReserved);
4362     return ERROR_SUCCESS;
4363 }
4364
4365 DWORD WINAPI InternetDialW( HWND hwndParent, LPWSTR lpszConnectoid, DWORD dwFlags,
4366                             DWORD_PTR* lpdwConnection, DWORD dwReserved )
4367 {
4368     FIXME("(%p, %p, 0x%08x, %p, 0x%08x) stub\n", hwndParent, lpszConnectoid, dwFlags,
4369           lpdwConnection, dwReserved);
4370     return ERROR_SUCCESS;
4371 }
4372
4373 BOOL WINAPI InternetGoOnlineA( LPSTR lpszURL, HWND hwndParent, DWORD dwReserved )
4374 {
4375     FIXME("(%s, %p, 0x%08x) stub\n", debugstr_a(lpszURL), hwndParent, dwReserved);
4376     return TRUE;
4377 }
4378
4379 BOOL WINAPI InternetGoOnlineW( LPWSTR lpszURL, HWND hwndParent, DWORD dwReserved )
4380 {
4381     FIXME("(%s, %p, 0x%08x) stub\n", debugstr_w(lpszURL), hwndParent, dwReserved);
4382     return TRUE;
4383 }
4384
4385 DWORD WINAPI InternetHangUp( DWORD_PTR dwConnection, DWORD dwReserved )
4386 {
4387     FIXME("(0x%08lx, 0x%08x) stub\n", dwConnection, dwReserved);
4388     return ERROR_SUCCESS;
4389 }
4390
4391 BOOL WINAPI CreateMD5SSOHash( PWSTR pszChallengeInfo, PWSTR pwszRealm, PWSTR pwszTarget,
4392                               PBYTE pbHexHash )
4393 {
4394     FIXME("(%s, %s, %s, %p) stub\n", debugstr_w(pszChallengeInfo), debugstr_w(pwszRealm),
4395           debugstr_w(pwszTarget), pbHexHash);
4396     return FALSE;
4397 }
4398
4399 BOOL WINAPI ResumeSuspendedDownload( HINTERNET hInternet, DWORD dwError )
4400 {
4401     FIXME("(%p, 0x%08x) stub\n", hInternet, dwError);
4402     return FALSE;
4403 }
4404
4405 BOOL WINAPI InternetQueryFortezzaStatus(DWORD *a, DWORD_PTR b)
4406 {
4407     FIXME("(%p, %08lx) stub\n", a, b);
4408     return 0;
4409 }
4410
4411 DWORD WINAPI ShowClientAuthCerts(HWND parent)
4412 {
4413     FIXME("%p: stub\n", parent);
4414     return 0;
4415 }