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