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