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