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