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