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