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