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