wininet: Fix buffer size query for HttpQueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF).
[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         {
1899             DWORD required;
1900             LPWININETAPPINFOW ai = (LPWININETAPPINFOW)lpwhh;
1901
1902             TRACE("INTERNET_OPTION_USER_AGENT\n");
1903
1904             if (lpwhh->htype != INTERNET_HANDLE_TYPE_INTERNET)
1905             {
1906                 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1907                 return FALSE;
1908             }
1909             if (bIsUnicode)
1910             {
1911                 required = (strlenW(ai->lpszAgent) + 1) * sizeof(WCHAR);
1912                 if (*lpdwBufferLength < required)
1913                     INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1914                 else if (lpBuffer)
1915                 {
1916                     strcpyW(lpBuffer, ai->lpszAgent);
1917                     bSuccess = TRUE;
1918                 }
1919             }
1920             else
1921             {
1922                 required = WideCharToMultiByte(CP_ACP, 0, ai->lpszAgent, -1, NULL, 0, NULL, NULL);
1923                 if (*lpdwBufferLength < required)
1924                     INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1925                 else if (lpBuffer)
1926                 {
1927                     WideCharToMultiByte(CP_ACP, 0, ai->lpszAgent, -1, lpBuffer, required, NULL, NULL);
1928                     bSuccess = TRUE;
1929                 }
1930             }
1931             *lpdwBufferLength = required;
1932             break;
1933         }
1934         case INTERNET_OPTION_HTTP_VERSION:
1935         {
1936             if (*lpdwBufferLength < sizeof(HTTP_VERSION_INFO))
1937                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1938             else
1939             {
1940                 /*
1941                  * Presently hardcoded to 1.1
1942                  */
1943                 ((HTTP_VERSION_INFO*)lpBuffer)->dwMajorVersion = 1;
1944                 ((HTTP_VERSION_INFO*)lpBuffer)->dwMinorVersion = 1;
1945                 bSuccess = TRUE;
1946             }
1947             *lpdwBufferLength = sizeof(HTTP_VERSION_INFO);
1948             break;
1949         }
1950        case INTERNET_OPTION_CONNECTED_STATE:
1951        {
1952             DWORD *pdwConnectedState = (DWORD *)lpBuffer;
1953             FIXME("INTERNET_OPTION_CONNECTED_STATE: semi-stub\n");
1954
1955             if (*lpdwBufferLength < sizeof(*pdwConnectedState))
1956                  INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1957             else
1958             {
1959                 *pdwConnectedState = INTERNET_STATE_CONNECTED;
1960                 bSuccess = TRUE;
1961             }
1962             *lpdwBufferLength = sizeof(*pdwConnectedState);
1963             break;
1964         }
1965         case INTERNET_OPTION_PROXY:
1966         {
1967             LPWININETAPPINFOW lpwai = (LPWININETAPPINFOW)lpwhh;
1968             WININETAPPINFOW wai;
1969
1970             if (lpwai == NULL)
1971             {
1972                 TRACE("Getting global proxy info\n");
1973                 memset(&wai, 0, sizeof(WININETAPPINFOW));
1974                 INTERNET_ConfigureProxy( &wai );
1975                 lpwai = &wai;
1976             }
1977
1978             if (bIsUnicode)
1979             {
1980                 INTERNET_PROXY_INFOW *pPI = (INTERNET_PROXY_INFOW *)lpBuffer;
1981                 DWORD proxyBytesRequired = 0, proxyBypassBytesRequired = 0;
1982
1983                 if (lpwai->lpszProxy)
1984                     proxyBytesRequired = (lstrlenW(lpwai->lpszProxy) + 1) *
1985                      sizeof(WCHAR);
1986                 if (lpwai->lpszProxyBypass)
1987                     proxyBypassBytesRequired =
1988                      (lstrlenW(lpwai->lpszProxyBypass) + 1) * sizeof(WCHAR);
1989                 if (*lpdwBufferLength < sizeof(INTERNET_PROXY_INFOW) +
1990                  proxyBytesRequired + proxyBypassBytesRequired)
1991                     INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1992                 else
1993                 {
1994                     LPWSTR proxy = (LPWSTR)((LPBYTE)lpBuffer +
1995                                             sizeof(INTERNET_PROXY_INFOW));
1996                     LPWSTR proxy_bypass = (LPWSTR)((LPBYTE)lpBuffer +
1997                                                    sizeof(INTERNET_PROXY_INFOW) +
1998                                                    proxyBytesRequired);
1999
2000                     pPI->dwAccessType = lpwai->dwAccessType;
2001                     pPI->lpszProxy = NULL;
2002                     pPI->lpszProxyBypass = NULL;
2003                     if (lpwai->lpszProxy)
2004                     {
2005                         lstrcpyW(proxy, lpwai->lpszProxy);
2006                         pPI->lpszProxy = proxy;
2007                     }
2008
2009                     if (lpwai->lpszProxyBypass)
2010                     {
2011                         lstrcpyW(proxy_bypass, lpwai->lpszProxyBypass);
2012                         pPI->lpszProxyBypass = proxy_bypass;
2013                     }
2014                     bSuccess = TRUE;
2015                 }
2016                 *lpdwBufferLength = sizeof(INTERNET_PROXY_INFOW) +
2017                  proxyBytesRequired + proxyBypassBytesRequired;
2018             }
2019             else
2020             {
2021                 INTERNET_PROXY_INFOA *pPI = (INTERNET_PROXY_INFOA *)lpBuffer;
2022                 DWORD proxyBytesRequired = 0, proxyBypassBytesRequired = 0;
2023
2024                 if (lpwai->lpszProxy)
2025                     proxyBytesRequired = WideCharToMultiByte(CP_ACP, 0,
2026                      lpwai->lpszProxy, -1, NULL, 0, NULL, NULL);
2027                 if (lpwai->lpszProxyBypass)
2028                     proxyBypassBytesRequired = WideCharToMultiByte(CP_ACP, 0,
2029                      lpwai->lpszProxyBypass, -1, NULL, 0, NULL, NULL);
2030                 if (*lpdwBufferLength < sizeof(INTERNET_PROXY_INFOA) +
2031                  proxyBytesRequired + proxyBypassBytesRequired)
2032                     INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2033                 else
2034                 {
2035                     LPSTR proxy = (LPSTR)((LPBYTE)lpBuffer +
2036                                           sizeof(INTERNET_PROXY_INFOA));
2037                     LPSTR proxy_bypass = (LPSTR)((LPBYTE)lpBuffer +
2038                                                  sizeof(INTERNET_PROXY_INFOA) +
2039                                                  proxyBytesRequired);
2040
2041                     pPI->dwAccessType = lpwai->dwAccessType;
2042                     pPI->lpszProxy = NULL;
2043                     pPI->lpszProxyBypass = NULL;
2044                     if (lpwai->lpszProxy)
2045                     {
2046                         WideCharToMultiByte(CP_ACP, 0, lpwai->lpszProxy, -1,
2047                                             proxy, proxyBytesRequired, NULL, NULL);
2048                         pPI->lpszProxy = proxy;
2049                     }
2050
2051                     if (lpwai->lpszProxyBypass)
2052                     {
2053                         WideCharToMultiByte(CP_ACP, 0, lpwai->lpszProxyBypass,
2054                                             -1, proxy_bypass, proxyBypassBytesRequired,
2055                                             NULL, NULL);
2056                         pPI->lpszProxyBypass = proxy_bypass;
2057                     }
2058                     bSuccess = TRUE;
2059                 }
2060                 *lpdwBufferLength = sizeof(INTERNET_PROXY_INFOA) +
2061                  proxyBytesRequired + proxyBypassBytesRequired;
2062             }
2063             break;
2064         }
2065         case INTERNET_OPTION_MAX_CONNS_PER_SERVER:
2066         {
2067             ULONG conn = 2;
2068             TRACE("INTERNET_OPTION_MAX_CONNS_PER_SERVER: %d\n", conn);
2069             if (*lpdwBufferLength < sizeof(ULONG))
2070                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2071             else
2072             {
2073                 memcpy(lpBuffer, &conn, sizeof(ULONG));
2074                 bSuccess = TRUE;
2075             }
2076             *lpdwBufferLength = sizeof(ULONG);
2077             break;
2078         }
2079         case INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER:
2080         {
2081             ULONG conn = 4;
2082             TRACE("INTERNET_OPTION_MAX_CONNS_1_0_SERVER: %d\n", conn);
2083             if (*lpdwBufferLength < sizeof(ULONG))
2084                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2085             else
2086             {
2087                 memcpy(lpBuffer, &conn, sizeof(ULONG));
2088                 bSuccess = TRUE;
2089             }
2090             *lpdwBufferLength = sizeof(ULONG);
2091             break;
2092         }
2093         case INTERNET_OPTION_SECURITY_FLAGS:
2094             FIXME("INTERNET_OPTION_SECURITY_FLAGS: Stub\n");
2095             bSuccess = TRUE;
2096             break;
2097
2098         case INTERNET_OPTION_VERSION:
2099         {
2100             TRACE("INTERNET_OPTION_VERSION\n");
2101             if (*lpdwBufferLength < sizeof(INTERNET_VERSION_INFO))
2102                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2103             else
2104             {
2105                 static const INTERNET_VERSION_INFO info = { 1, 2 };
2106                 memcpy(lpBuffer, &info, sizeof(info));
2107                 *lpdwBufferLength = sizeof(info);
2108                 bSuccess = TRUE;
2109             }
2110             break;
2111         }
2112         case INTERNET_OPTION_PER_CONNECTION_OPTION:
2113             FIXME("INTERNET_OPTION_PER_CONNECTION_OPTION stub\n");
2114             if (*lpdwBufferLength < sizeof(INTERNET_PER_CONN_OPTION_LISTW))
2115                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
2116             else
2117             {
2118                 INTERNET_PER_CONN_OPTION_LISTW *con = lpBuffer;
2119                 int x;
2120                 bSuccess = TRUE;
2121                 for (x = 0; x < con->dwOptionCount; ++x)
2122                 {
2123                     INTERNET_PER_CONN_OPTIONW *option = con->pOptions + x;
2124                     switch (option->dwOption)
2125                     {
2126                     case INTERNET_PER_CONN_FLAGS:
2127                         option->Value.dwValue = PROXY_TYPE_DIRECT;
2128                         break;
2129
2130                     case INTERNET_PER_CONN_PROXY_SERVER:
2131                     case INTERNET_PER_CONN_PROXY_BYPASS:
2132                     case INTERNET_PER_CONN_AUTOCONFIG_URL:
2133                     case INTERNET_PER_CONN_AUTODISCOVERY_FLAGS:
2134                     case INTERNET_PER_CONN_AUTOCONFIG_SECONDARY_URL:
2135                     case INTERNET_PER_CONN_AUTOCONFIG_RELOAD_DELAY_MINS:
2136                     case INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_TIME:
2137                     case INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_URL:
2138                         FIXME("Unhandled dwOption %d\n", option->dwOption);
2139                         option->Value.dwValue = 0;
2140                         bSuccess = FALSE;
2141                         break;
2142
2143                     default:
2144                         FIXME("Unknown dwOption %d\n", option->dwOption);
2145                         bSuccess = FALSE;
2146                         break;
2147                     }
2148                 }
2149                 if (!bSuccess)
2150                     INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2151             }
2152             break;
2153     case 66:
2154         FIXME("66\n");
2155         bSuccess = TRUE;
2156         break;
2157         default: {
2158             if(lpwhh) {
2159                 DWORD res;
2160
2161                 res = lpwhh->vtbl->QueryOption(lpwhh, dwOption, lpBuffer, lpdwBufferLength, bIsUnicode);
2162                 if(res == ERROR_SUCCESS)
2163                     bSuccess = TRUE;
2164                 else
2165                     SetLastError(res);
2166             }else {
2167                 FIXME("Stub! %d\n", dwOption);
2168                 break;
2169             }
2170         }
2171     }
2172     if (lpwhh)
2173         WININET_Release( lpwhh );
2174
2175     return bSuccess;
2176 }
2177
2178 /***********************************************************************
2179  *           InternetQueryOptionW (WININET.@)
2180  *
2181  * Queries an options on the specified handle
2182  *
2183  * RETURNS
2184  *    TRUE  on success
2185  *    FALSE on failure
2186  *
2187  */
2188 BOOL WINAPI InternetQueryOptionW(HINTERNET hInternet, DWORD dwOption,
2189                                  LPVOID lpBuffer, LPDWORD lpdwBufferLength)
2190 {
2191     return INET_QueryOptionHelper(TRUE, hInternet, dwOption, lpBuffer, lpdwBufferLength);
2192 }
2193
2194 /***********************************************************************
2195  *           InternetQueryOptionA (WININET.@)
2196  *
2197  * Queries an options on the specified handle
2198  *
2199  * RETURNS
2200  *    TRUE  on success
2201  *    FALSE on failure
2202  *
2203  */
2204 BOOL WINAPI InternetQueryOptionA(HINTERNET hInternet, DWORD dwOption,
2205                                  LPVOID lpBuffer, LPDWORD lpdwBufferLength)
2206 {
2207     return INET_QueryOptionHelper(FALSE, hInternet, dwOption, lpBuffer, lpdwBufferLength);
2208 }
2209
2210
2211 /***********************************************************************
2212  *           InternetSetOptionW (WININET.@)
2213  *
2214  * Sets an options on the specified handle
2215  *
2216  * RETURNS
2217  *    TRUE  on success
2218  *    FALSE on failure
2219  *
2220  */
2221 BOOL WINAPI InternetSetOptionW(HINTERNET hInternet, DWORD dwOption,
2222                            LPVOID lpBuffer, DWORD dwBufferLength)
2223 {
2224     LPWININETHANDLEHEADER lpwhh;
2225     BOOL ret = TRUE;
2226
2227     TRACE("(%p %d %p %d)\n", hInternet, dwOption, lpBuffer, dwBufferLength);
2228
2229     lpwhh = (LPWININETHANDLEHEADER) WININET_GetObject( hInternet );
2230     if(lpwhh && lpwhh->vtbl->SetOption) {
2231         DWORD res;
2232
2233         res = lpwhh->vtbl->SetOption(lpwhh, dwOption, lpBuffer, dwBufferLength);
2234         if(res != ERROR_INTERNET_INVALID_OPTION) {
2235             WININET_Release( lpwhh );
2236
2237             if(res != ERROR_SUCCESS)
2238                 SetLastError(res);
2239
2240             return res == ERROR_SUCCESS;
2241         }
2242     }
2243
2244     switch (dwOption)
2245     {
2246     case INTERNET_OPTION_CALLBACK:
2247       {
2248         INTERNET_STATUS_CALLBACK callback = *(INTERNET_STATUS_CALLBACK *)lpBuffer;
2249         ret = (set_status_callback(lpwhh, callback, TRUE) != INTERNET_INVALID_STATUS_CALLBACK);
2250         break;
2251       }
2252     case INTERNET_OPTION_HTTP_VERSION:
2253       {
2254         HTTP_VERSION_INFO* pVersion=(HTTP_VERSION_INFO*)lpBuffer;
2255         FIXME("Option INTERNET_OPTION_HTTP_VERSION(%d,%d): STUB\n",pVersion->dwMajorVersion,pVersion->dwMinorVersion);
2256       }
2257       break;
2258     case INTERNET_OPTION_ERROR_MASK:
2259       {
2260         unsigned long flags=*(unsigned long*)lpBuffer;
2261         FIXME("Option INTERNET_OPTION_ERROR_MASK(%ld): STUB\n",flags);
2262       }
2263       break;
2264     case INTERNET_OPTION_CODEPAGE:
2265       {
2266         unsigned long codepage=*(unsigned long*)lpBuffer;
2267         FIXME("Option INTERNET_OPTION_CODEPAGE (%ld): STUB\n",codepage);
2268       }
2269       break;
2270     case INTERNET_OPTION_REQUEST_PRIORITY:
2271       {
2272         unsigned long priority=*(unsigned long*)lpBuffer;
2273         FIXME("Option INTERNET_OPTION_REQUEST_PRIORITY (%ld): STUB\n",priority);
2274       }
2275       break;
2276     case INTERNET_OPTION_CONNECT_TIMEOUT:
2277       {
2278         unsigned long connecttimeout=*(unsigned long*)lpBuffer;
2279         FIXME("Option INTERNET_OPTION_CONNECT_TIMEOUT (%ld): STUB\n",connecttimeout);
2280       }
2281       break;
2282     case INTERNET_OPTION_DATA_RECEIVE_TIMEOUT:
2283       {
2284         unsigned long receivetimeout=*(unsigned long*)lpBuffer;
2285         FIXME("Option INTERNET_OPTION_DATA_RECEIVE_TIMEOUT (%ld): STUB\n",receivetimeout);
2286       }
2287       break;
2288     case INTERNET_OPTION_MAX_CONNS_PER_SERVER:
2289       {
2290         unsigned long conns=*(unsigned long*)lpBuffer;
2291         FIXME("Option INTERNET_OPTION_MAX_CONNS_PER_SERVER (%ld): STUB\n",conns);
2292       }
2293       break;
2294     case INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER:
2295       {
2296         unsigned long conns=*(unsigned long*)lpBuffer;
2297         FIXME("Option INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER (%ld): STUB\n",conns);
2298       }
2299       break;
2300     case INTERNET_OPTION_RESET_URLCACHE_SESSION:
2301         FIXME("Option INTERNET_OPTION_RESET_URLCACHE_SESSION: STUB\n");
2302         break;
2303     case INTERNET_OPTION_END_BROWSER_SESSION:
2304         FIXME("Option INTERNET_OPTION_END_BROWSER_SESSION: STUB\n");
2305         break;
2306     case INTERNET_OPTION_CONNECTED_STATE:
2307         FIXME("Option INTERNET_OPTION_CONNECTED_STATE: STUB\n");
2308         break;
2309     case INTERNET_OPTION_DISABLE_PASSPORT_AUTH:
2310         TRACE("Option INTERNET_OPTION_DISABLE_PASSPORT_AUTH: harmless stub, since not enabled\n");
2311         break;
2312     case INTERNET_OPTION_SEND_TIMEOUT:
2313     case INTERNET_OPTION_RECEIVE_TIMEOUT:
2314         FIXME("INTERNET_OPTION_SEND/RECEIVE_TIMEOUT\n");
2315         break;
2316     case INTERNET_OPTION_CONNECT_RETRIES:
2317         FIXME("Option INTERNET_OPTION_CONNECT_RETRIES: STUB\n");
2318         break;
2319     case INTERNET_OPTION_CONTEXT_VALUE:
2320          FIXME("Option INTERNET_OPTION_CONTEXT_VALUE; STUB\n");
2321          break;
2322     case INTERNET_OPTION_SECURITY_FLAGS:
2323          FIXME("Option INTERNET_OPTION_SECURITY_FLAGS; STUB\n");
2324          break;
2325     case 86:
2326         FIXME("86\n");
2327         break;
2328     default:
2329         FIXME("Option %d STUB\n",dwOption);
2330         INTERNET_SetLastError(ERROR_INTERNET_INVALID_OPTION);
2331         ret = FALSE;
2332         break;
2333     }
2334
2335     if(lpwhh)
2336         WININET_Release( lpwhh );
2337
2338     return ret;
2339 }
2340
2341
2342 /***********************************************************************
2343  *           InternetSetOptionA (WININET.@)
2344  *
2345  * Sets an options on the specified handle.
2346  *
2347  * RETURNS
2348  *    TRUE  on success
2349  *    FALSE on failure
2350  *
2351  */
2352 BOOL WINAPI InternetSetOptionA(HINTERNET hInternet, DWORD dwOption,
2353                            LPVOID lpBuffer, DWORD dwBufferLength)
2354 {
2355     LPVOID wbuffer;
2356     DWORD wlen;
2357     BOOL r;
2358
2359     switch( dwOption )
2360     {
2361     case INTERNET_OPTION_CALLBACK:
2362         {
2363         LPWININETHANDLEHEADER lpwh;
2364         INTERNET_STATUS_CALLBACK callback = *(INTERNET_STATUS_CALLBACK *)lpBuffer;
2365
2366         if (!(lpwh = WININET_GetObject(hInternet))) return FALSE;
2367         r = (set_status_callback(lpwh, callback, FALSE) != INTERNET_INVALID_STATUS_CALLBACK);
2368         WININET_Release(lpwh);
2369         return r;
2370         }
2371     case INTERNET_OPTION_PROXY:
2372         {
2373         LPINTERNET_PROXY_INFOA pi = (LPINTERNET_PROXY_INFOA) lpBuffer;
2374         LPINTERNET_PROXY_INFOW piw;
2375         DWORD proxlen, prbylen;
2376         LPWSTR prox, prby;
2377
2378         proxlen = MultiByteToWideChar( CP_ACP, 0, pi->lpszProxy, -1, NULL, 0);
2379         prbylen= MultiByteToWideChar( CP_ACP, 0, pi->lpszProxyBypass, -1, NULL, 0);
2380         wlen = sizeof(*piw) + proxlen + prbylen;
2381         wbuffer = HeapAlloc( GetProcessHeap(), 0, wlen*sizeof(WCHAR) );
2382         piw = (LPINTERNET_PROXY_INFOW) wbuffer;
2383         piw->dwAccessType = pi->dwAccessType;
2384         prox = (LPWSTR) &piw[1];
2385         prby = &prox[proxlen+1];
2386         MultiByteToWideChar( CP_ACP, 0, pi->lpszProxy, -1, prox, proxlen);
2387         MultiByteToWideChar( CP_ACP, 0, pi->lpszProxyBypass, -1, prby, prbylen);
2388         piw->lpszProxy = prox;
2389         piw->lpszProxyBypass = prby;
2390         }
2391         break;
2392     case INTERNET_OPTION_USER_AGENT:
2393     case INTERNET_OPTION_USERNAME:
2394     case INTERNET_OPTION_PASSWORD:
2395         wlen = MultiByteToWideChar( CP_ACP, 0, lpBuffer, dwBufferLength,
2396                                    NULL, 0 );
2397         wbuffer = HeapAlloc( GetProcessHeap(), 0, wlen*sizeof(WCHAR) );
2398         MultiByteToWideChar( CP_ACP, 0, lpBuffer, dwBufferLength,
2399                                    wbuffer, wlen );
2400         break;
2401     default:
2402         wbuffer = lpBuffer;
2403         wlen = dwBufferLength;
2404     }
2405
2406     r = InternetSetOptionW(hInternet,dwOption, wbuffer, wlen);
2407
2408     if( lpBuffer != wbuffer )
2409         HeapFree( GetProcessHeap(), 0, wbuffer );
2410
2411     return r;
2412 }
2413
2414
2415 /***********************************************************************
2416  *           InternetSetOptionExA (WININET.@)
2417  */
2418 BOOL WINAPI InternetSetOptionExA(HINTERNET hInternet, DWORD dwOption,
2419                            LPVOID lpBuffer, DWORD dwBufferLength, DWORD dwFlags)
2420 {
2421     FIXME("Flags %08x ignored\n", dwFlags);
2422     return InternetSetOptionA( hInternet, dwOption, lpBuffer, dwBufferLength );
2423 }
2424
2425 /***********************************************************************
2426  *           InternetSetOptionExW (WININET.@)
2427  */
2428 BOOL WINAPI InternetSetOptionExW(HINTERNET hInternet, DWORD dwOption,
2429                            LPVOID lpBuffer, DWORD dwBufferLength, DWORD dwFlags)
2430 {
2431     FIXME("Flags %08x ignored\n", dwFlags);
2432     if( dwFlags & ~ISO_VALID_FLAGS )
2433     {
2434         INTERNET_SetLastError( ERROR_INVALID_PARAMETER );
2435         return FALSE;
2436     }
2437     return InternetSetOptionW( hInternet, dwOption, lpBuffer, dwBufferLength );
2438 }
2439
2440 static const WCHAR WININET_wkday[7][4] =
2441     { { 'S','u','n', 0 }, { 'M','o','n', 0 }, { 'T','u','e', 0 }, { 'W','e','d', 0 },
2442       { 'T','h','u', 0 }, { 'F','r','i', 0 }, { 'S','a','t', 0 } };
2443 static const WCHAR WININET_month[12][4] =
2444     { { 'J','a','n', 0 }, { 'F','e','b', 0 }, { 'M','a','r', 0 }, { 'A','p','r', 0 },
2445       { 'M','a','y', 0 }, { 'J','u','n', 0 }, { 'J','u','l', 0 }, { 'A','u','g', 0 },
2446       { 'S','e','p', 0 }, { 'O','c','t', 0 }, { 'N','o','v', 0 }, { 'D','e','c', 0 } };
2447
2448 /***********************************************************************
2449  *           InternetTimeFromSystemTimeA (WININET.@)
2450  */
2451 BOOL WINAPI InternetTimeFromSystemTimeA( const SYSTEMTIME* time, DWORD format, LPSTR string, DWORD size )
2452 {
2453     BOOL ret;
2454     WCHAR stringW[INTERNET_RFC1123_BUFSIZE];
2455
2456     TRACE( "%p 0x%08x %p 0x%08x\n", time, format, string, size );
2457
2458     ret = InternetTimeFromSystemTimeW( time, format, stringW, sizeof(stringW) );
2459     if (ret) WideCharToMultiByte( CP_ACP, 0, stringW, -1, string, size, NULL, NULL );
2460
2461     return ret;
2462 }
2463
2464 /***********************************************************************
2465  *           InternetTimeFromSystemTimeW (WININET.@)
2466  */
2467 BOOL WINAPI InternetTimeFromSystemTimeW( const SYSTEMTIME* time, DWORD format, LPWSTR string, DWORD size )
2468 {
2469     static const WCHAR date[] =
2470         { '%','s',',',' ','%','0','2','d',' ','%','s',' ','%','4','d',' ','%','0',
2471           '2','d',':','%','0','2','d',':','%','0','2','d',' ','G','M','T', 0 };
2472
2473     TRACE( "%p 0x%08x %p 0x%08x\n", time, format, string, size );
2474
2475     if (!time || !string) return FALSE;
2476
2477     if (format != INTERNET_RFC1123_FORMAT || size < INTERNET_RFC1123_BUFSIZE * sizeof(WCHAR))
2478         return FALSE;
2479
2480     sprintfW( string, date,
2481               WININET_wkday[time->wDayOfWeek],
2482               time->wDay,
2483               WININET_month[time->wMonth - 1],
2484               time->wYear,
2485               time->wHour,
2486               time->wMinute,
2487               time->wSecond );
2488
2489     return TRUE;
2490 }
2491
2492 /***********************************************************************
2493  *           InternetTimeToSystemTimeA (WININET.@)
2494  */
2495 BOOL WINAPI InternetTimeToSystemTimeA( LPCSTR string, SYSTEMTIME* time, DWORD reserved )
2496 {
2497     BOOL ret = FALSE;
2498     WCHAR *stringW;
2499     int len;
2500
2501     TRACE( "%s %p 0x%08x\n", debugstr_a(string), time, reserved );
2502
2503     len = MultiByteToWideChar( CP_ACP, 0, string, -1, NULL, 0 );
2504     stringW = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
2505
2506     if (stringW)
2507     {
2508         MultiByteToWideChar( CP_ACP, 0, string, -1, stringW, len );
2509         ret = InternetTimeToSystemTimeW( stringW, time, reserved );
2510         HeapFree( GetProcessHeap(), 0, stringW );
2511     }
2512     return ret;
2513 }
2514
2515 /***********************************************************************
2516  *           InternetTimeToSystemTimeW (WININET.@)
2517  */
2518 BOOL WINAPI InternetTimeToSystemTimeW( LPCWSTR string, SYSTEMTIME* time, DWORD reserved )
2519 {
2520     unsigned int i;
2521     const WCHAR *s = string;
2522     WCHAR       *end;
2523
2524     TRACE( "%s %p 0x%08x\n", debugstr_w(string), time, reserved );
2525
2526     if (!string || !time) return FALSE;
2527
2528     /* Windows does this too */
2529     GetSystemTime( time );
2530
2531     /*  Convert an RFC1123 time such as 'Fri, 07 Jan 2005 12:06:35 GMT' into
2532      *  a SYSTEMTIME structure.
2533      */
2534
2535     while (*s && !isalphaW( *s )) s++;
2536     if (s[0] == '\0' || s[1] == '\0' || s[2] == '\0') return TRUE;
2537     time->wDayOfWeek = 7;
2538
2539     for (i = 0; i < 7; i++)
2540     {
2541         if (toupperW( WININET_wkday[i][0] ) == toupperW( s[0] ) &&
2542             toupperW( WININET_wkday[i][1] ) == toupperW( s[1] ) &&
2543             toupperW( WININET_wkday[i][2] ) == toupperW( s[2] ) )
2544         {
2545             time->wDayOfWeek = i;
2546             break;
2547         }
2548     }
2549
2550     if (time->wDayOfWeek > 6) return TRUE;
2551     while (*s && !isdigitW( *s )) s++;
2552     time->wDay = strtolW( s, &end, 10 );
2553     s = end;
2554
2555     while (*s && !isalphaW( *s )) s++;
2556     if (s[0] == '\0' || s[1] == '\0' || s[2] == '\0') return TRUE;
2557     time->wMonth = 0;
2558
2559     for (i = 0; i < 12; i++)
2560     {
2561         if (toupperW( WININET_month[i][0]) == toupperW( s[0] ) &&
2562             toupperW( WININET_month[i][1]) == toupperW( s[1] ) &&
2563             toupperW( WININET_month[i][2]) == toupperW( s[2] ) )
2564         {
2565             time->wMonth = i + 1;
2566             break;
2567         }
2568     }
2569     if (time->wMonth == 0) return TRUE;
2570
2571     while (*s && !isdigitW( *s )) s++;
2572     if (*s == '\0') return TRUE;
2573     time->wYear = strtolW( s, &end, 10 );
2574     s = end;
2575
2576     while (*s && !isdigitW( *s )) s++;
2577     if (*s == '\0') return TRUE;
2578     time->wHour = strtolW( s, &end, 10 );
2579     s = end;
2580
2581     while (*s && !isdigitW( *s )) s++;
2582     if (*s == '\0') return TRUE;
2583     time->wMinute = strtolW( s, &end, 10 );
2584     s = end;
2585
2586     while (*s && !isdigitW( *s )) s++;
2587     if (*s == '\0') return TRUE;
2588     time->wSecond = strtolW( s, &end, 10 );
2589     s = end;
2590
2591     time->wMilliseconds = 0;
2592     return TRUE;
2593 }
2594
2595 /***********************************************************************
2596  *      InternetCheckConnectionW (WININET.@)
2597  *
2598  * Pings a requested host to check internet connection
2599  *
2600  * RETURNS
2601  *   TRUE on success and FALSE on failure. If a failure then
2602  *   ERROR_NOT_CONNECTED is placed into GetLastError
2603  *
2604  */
2605 BOOL WINAPI InternetCheckConnectionW( LPCWSTR lpszUrl, DWORD dwFlags, DWORD dwReserved )
2606 {
2607 /*
2608  * this is a kludge which runs the resident ping program and reads the output.
2609  *
2610  * Anyone have a better idea?
2611  */
2612
2613   BOOL   rc = FALSE;
2614   static const CHAR ping[] = "ping -c 1 ";
2615   static const CHAR redirect[] = " >/dev/null 2>/dev/null";
2616   CHAR *command = NULL;
2617   WCHAR hostW[1024];
2618   DWORD len;
2619   INTERNET_PORT port;
2620   int status = -1;
2621
2622   FIXME("\n");
2623
2624   /*
2625    * Crack or set the Address
2626    */
2627   if (lpszUrl == NULL)
2628   {
2629      /*
2630       * According to the doc we are supposed to use the ip for the next
2631       * server in the WnInet internal server database. I have
2632       * no idea what that is or how to get it.
2633       *
2634       * So someone needs to implement this.
2635       */
2636      FIXME("Unimplemented with URL of NULL\n");
2637      return TRUE;
2638   }
2639   else
2640   {
2641      URL_COMPONENTSW components;
2642
2643      ZeroMemory(&components,sizeof(URL_COMPONENTSW));
2644      components.lpszHostName = (LPWSTR)&hostW;
2645      components.dwHostNameLength = 1024;
2646
2647      if (!InternetCrackUrlW(lpszUrl,0,0,&components))
2648        goto End;
2649
2650      TRACE("host name : %s\n",debugstr_w(components.lpszHostName));
2651      port = components.nPort;
2652      TRACE("port: %d\n", port);
2653   }
2654
2655   if (dwFlags & FLAG_ICC_FORCE_CONNECTION)
2656   {
2657       struct sockaddr_in sin;
2658       int fd;
2659
2660       if (!GetAddress(hostW, port, &sin))
2661           goto End;
2662       fd = socket(sin.sin_family, SOCK_STREAM, 0);
2663       if (fd != -1)
2664       {
2665           if (connect(fd, (struct sockaddr *)&sin, sizeof(sin)) == 0)
2666               rc = TRUE;
2667           close(fd);
2668       }
2669   }
2670   else
2671   {
2672       /*
2673        * Build our ping command
2674        */
2675       len = WideCharToMultiByte(CP_UNIXCP, 0, hostW, -1, NULL, 0, NULL, NULL);
2676       command = HeapAlloc( GetProcessHeap(), 0, strlen(ping)+len+strlen(redirect) );
2677       strcpy(command,ping);
2678       WideCharToMultiByte(CP_UNIXCP, 0, hostW, -1, command+strlen(ping), len, NULL, NULL);
2679       strcat(command,redirect);
2680
2681       TRACE("Ping command is : %s\n",command);
2682
2683       status = system(command);
2684
2685       TRACE("Ping returned a code of %i\n",status);
2686
2687       /* Ping return code of 0 indicates success */
2688       if (status == 0)
2689          rc = TRUE;
2690   }
2691
2692 End:
2693
2694   HeapFree( GetProcessHeap(), 0, command );
2695   if (rc == FALSE)
2696     INTERNET_SetLastError(ERROR_NOT_CONNECTED);
2697
2698   return rc;
2699 }
2700
2701
2702 /***********************************************************************
2703  *      InternetCheckConnectionA (WININET.@)
2704  *
2705  * Pings a requested host to check internet connection
2706  *
2707  * RETURNS
2708  *   TRUE on success and FALSE on failure. If a failure then
2709  *   ERROR_NOT_CONNECTED is placed into GetLastError
2710  *
2711  */
2712 BOOL WINAPI InternetCheckConnectionA(LPCSTR lpszUrl, DWORD dwFlags, DWORD dwReserved)
2713 {
2714     WCHAR *szUrl;
2715     INT len;
2716     BOOL rc;
2717
2718     len = MultiByteToWideChar(CP_ACP, 0, lpszUrl, -1, NULL, 0);
2719     if (!(szUrl = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR))))
2720         return FALSE;
2721     MultiByteToWideChar(CP_ACP, 0, lpszUrl, -1, szUrl, len);
2722     rc = InternetCheckConnectionW(szUrl, dwFlags, dwReserved);
2723     HeapFree(GetProcessHeap(), 0, szUrl);
2724     
2725     return rc;
2726 }
2727
2728
2729 /**********************************************************
2730  *      INTERNET_InternetOpenUrlW (internal)
2731  *
2732  * Opens an URL
2733  *
2734  * RETURNS
2735  *   handle of connection or NULL on failure
2736  */
2737 HINTERNET WINAPI INTERNET_InternetOpenUrlW(LPWININETAPPINFOW hIC, LPCWSTR lpszUrl,
2738     LPCWSTR lpszHeaders, DWORD dwHeadersLength, DWORD dwFlags, DWORD_PTR dwContext)
2739 {
2740     URL_COMPONENTSW urlComponents;
2741     WCHAR protocol[32], hostName[MAXHOSTNAME], userName[1024];
2742     WCHAR password[1024], path[2048], extra[1024];
2743     HINTERNET client = NULL, client1 = NULL;
2744     
2745     TRACE("(%p, %s, %s, %08x, %08x, %08lx)\n", hIC, debugstr_w(lpszUrl), debugstr_w(lpszHeaders),
2746           dwHeadersLength, dwFlags, dwContext);
2747     
2748     urlComponents.dwStructSize = sizeof(URL_COMPONENTSW);
2749     urlComponents.lpszScheme = protocol;
2750     urlComponents.dwSchemeLength = 32;
2751     urlComponents.lpszHostName = hostName;
2752     urlComponents.dwHostNameLength = MAXHOSTNAME;
2753     urlComponents.lpszUserName = userName;
2754     urlComponents.dwUserNameLength = 1024;
2755     urlComponents.lpszPassword = password;
2756     urlComponents.dwPasswordLength = 1024;
2757     urlComponents.lpszUrlPath = path;
2758     urlComponents.dwUrlPathLength = 2048;
2759     urlComponents.lpszExtraInfo = extra;
2760     urlComponents.dwExtraInfoLength = 1024;
2761     if(!InternetCrackUrlW(lpszUrl, strlenW(lpszUrl), 0, &urlComponents))
2762         return NULL;
2763     switch(urlComponents.nScheme) {
2764     case INTERNET_SCHEME_FTP:
2765         if(urlComponents.nPort == 0)
2766             urlComponents.nPort = INTERNET_DEFAULT_FTP_PORT;
2767         client = FTP_Connect(hIC, hostName, urlComponents.nPort,
2768                              userName, password, dwFlags, dwContext, INET_OPENURL);
2769         if(client == NULL)
2770             break;
2771         client1 = FtpOpenFileW(client, path, GENERIC_READ, dwFlags, dwContext);
2772         if(client1 == NULL) {
2773             InternetCloseHandle(client);
2774             break;
2775         }
2776         break;
2777         
2778     case INTERNET_SCHEME_HTTP:
2779     case INTERNET_SCHEME_HTTPS: {
2780         static const WCHAR szStars[] = { '*','/','*', 0 };
2781         LPCWSTR accept[2] = { szStars, NULL };
2782         if(urlComponents.nPort == 0) {
2783             if(urlComponents.nScheme == INTERNET_SCHEME_HTTP)
2784                 urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
2785             else
2786                 urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
2787         }
2788         /* FIXME: should use pointers, not handles, as handles are not thread-safe */
2789         client = HTTP_Connect(hIC, hostName, urlComponents.nPort,
2790                               userName, password, dwFlags, dwContext, INET_OPENURL);
2791         if(client == NULL)
2792             break;
2793
2794         if (urlComponents.dwExtraInfoLength) {
2795                 WCHAR *path_extra;
2796                 DWORD len = urlComponents.dwUrlPathLength + urlComponents.dwExtraInfoLength + 1;
2797
2798                 if (!(path_extra = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR))))
2799                 {
2800                         InternetCloseHandle(client);
2801                         break;
2802                 }
2803                 strcpyW(path_extra, urlComponents.lpszUrlPath);
2804                 strcatW(path_extra, urlComponents.lpszExtraInfo);
2805                 client1 = HttpOpenRequestW(client, NULL, path_extra, NULL, NULL, accept, dwFlags, dwContext);
2806                 HeapFree(GetProcessHeap(), 0, path_extra);
2807         }
2808         else
2809                 client1 = HttpOpenRequestW(client, NULL, path, NULL, NULL, accept, dwFlags, dwContext);
2810
2811         if(client1 == NULL) {
2812             InternetCloseHandle(client);
2813             break;
2814         }
2815         HttpAddRequestHeadersW(client1, lpszHeaders, dwHeadersLength, HTTP_ADDREQ_FLAG_ADD);
2816         if (!HttpSendRequestW(client1, NULL, 0, NULL, 0) &&
2817             GetLastError() != ERROR_IO_PENDING) {
2818             InternetCloseHandle(client1);
2819             client1 = NULL;
2820             break;
2821         }
2822     }
2823     case INTERNET_SCHEME_GOPHER:
2824         /* gopher doesn't seem to be implemented in wine, but it's supposed
2825          * to be supported by InternetOpenUrlA. */
2826     default:
2827         INTERNET_SetLastError(ERROR_INTERNET_UNRECOGNIZED_SCHEME);
2828         break;
2829     }
2830
2831     TRACE(" %p <--\n", client1);
2832     
2833     return client1;
2834 }
2835
2836 /**********************************************************
2837  *      InternetOpenUrlW (WININET.@)
2838  *
2839  * Opens an URL
2840  *
2841  * RETURNS
2842  *   handle of connection or NULL on failure
2843  */
2844 static void AsyncInternetOpenUrlProc(WORKREQUEST *workRequest)
2845 {
2846     struct WORKREQ_INTERNETOPENURLW const *req = &workRequest->u.InternetOpenUrlW;
2847     LPWININETAPPINFOW hIC = (LPWININETAPPINFOW) workRequest->hdr;
2848
2849     TRACE("%p\n", hIC);
2850
2851     INTERNET_InternetOpenUrlW(hIC, req->lpszUrl,
2852                               req->lpszHeaders, req->dwHeadersLength, req->dwFlags, req->dwContext);
2853     HeapFree(GetProcessHeap(), 0, req->lpszUrl);
2854     HeapFree(GetProcessHeap(), 0, req->lpszHeaders);
2855 }
2856
2857 HINTERNET WINAPI InternetOpenUrlW(HINTERNET hInternet, LPCWSTR lpszUrl,
2858     LPCWSTR lpszHeaders, DWORD dwHeadersLength, DWORD dwFlags, DWORD_PTR dwContext)
2859 {
2860     HINTERNET ret = NULL;
2861     LPWININETAPPINFOW hIC = NULL;
2862
2863     if (TRACE_ON(wininet)) {
2864         TRACE("(%p, %s, %s, %08x, %08x, %08lx)\n", hInternet, debugstr_w(lpszUrl), debugstr_w(lpszHeaders),
2865               dwHeadersLength, dwFlags, dwContext);
2866         TRACE("  flags :");
2867         dump_INTERNET_FLAGS(dwFlags);
2868     }
2869
2870     if (!lpszUrl)
2871     {
2872         INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2873         goto lend;
2874     }
2875
2876     hIC = (LPWININETAPPINFOW) WININET_GetObject( hInternet );
2877     if (NULL == hIC ||  hIC->hdr.htype != WH_HINIT) {
2878         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2879         goto lend;
2880     }
2881     
2882     if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC) {
2883         WORKREQUEST workRequest;
2884         struct WORKREQ_INTERNETOPENURLW *req;
2885
2886         workRequest.asyncproc = AsyncInternetOpenUrlProc;
2887         workRequest.hdr = WININET_AddRef( &hIC->hdr );
2888         req = &workRequest.u.InternetOpenUrlW;
2889         req->lpszUrl = WININET_strdupW(lpszUrl);
2890         if (lpszHeaders)
2891             req->lpszHeaders = WININET_strdupW(lpszHeaders);
2892         else
2893             req->lpszHeaders = 0;
2894         req->dwHeadersLength = dwHeadersLength;
2895         req->dwFlags = dwFlags;
2896         req->dwContext = dwContext;
2897         
2898         INTERNET_AsyncCall(&workRequest);
2899         /*
2900          * This is from windows.
2901          */
2902         INTERNET_SetLastError(ERROR_IO_PENDING);
2903     } else {
2904         ret = INTERNET_InternetOpenUrlW(hIC, lpszUrl, lpszHeaders, dwHeadersLength, dwFlags, dwContext);
2905     }
2906     
2907   lend:
2908     if( hIC )
2909         WININET_Release( &hIC->hdr );
2910     TRACE(" %p <--\n", ret);
2911     
2912     return ret;
2913 }
2914
2915 /**********************************************************
2916  *      InternetOpenUrlA (WININET.@)
2917  *
2918  * Opens an URL
2919  *
2920  * RETURNS
2921  *   handle of connection or NULL on failure
2922  */
2923 HINTERNET WINAPI InternetOpenUrlA(HINTERNET hInternet, LPCSTR lpszUrl,
2924     LPCSTR lpszHeaders, DWORD dwHeadersLength, DWORD dwFlags, DWORD_PTR dwContext)
2925 {
2926     HINTERNET rc = NULL;
2927
2928     INT lenUrl;
2929     INT lenHeaders = 0;
2930     LPWSTR szUrl = NULL;
2931     LPWSTR szHeaders = NULL;
2932
2933     TRACE("\n");
2934
2935     if(lpszUrl) {
2936         lenUrl = MultiByteToWideChar(CP_ACP, 0, lpszUrl, -1, NULL, 0 );
2937         szUrl = HeapAlloc(GetProcessHeap(), 0, lenUrl*sizeof(WCHAR));
2938         if(!szUrl)
2939             return NULL;
2940         MultiByteToWideChar(CP_ACP, 0, lpszUrl, -1, szUrl, lenUrl);
2941     }
2942
2943     if(lpszHeaders) {
2944         lenHeaders = MultiByteToWideChar(CP_ACP, 0, lpszHeaders, dwHeadersLength, NULL, 0 );
2945         szHeaders = HeapAlloc(GetProcessHeap(), 0, lenHeaders*sizeof(WCHAR));
2946         if(!szHeaders) {
2947             HeapFree(GetProcessHeap(), 0, szUrl);
2948             return NULL;
2949         }
2950         MultiByteToWideChar(CP_ACP, 0, lpszHeaders, dwHeadersLength, szHeaders, lenHeaders);
2951     }
2952     
2953     rc = InternetOpenUrlW(hInternet, szUrl, szHeaders,
2954         lenHeaders, dwFlags, dwContext);
2955
2956     HeapFree(GetProcessHeap(), 0, szUrl);
2957     HeapFree(GetProcessHeap(), 0, szHeaders);
2958
2959     return rc;
2960 }
2961
2962
2963 static LPWITHREADERROR INTERNET_AllocThreadError(void)
2964 {
2965     LPWITHREADERROR lpwite = HeapAlloc(GetProcessHeap(), 0, sizeof(*lpwite));
2966
2967     if (lpwite)
2968     {
2969         lpwite->dwError = 0;
2970         lpwite->response[0] = '\0';
2971     }
2972
2973     if (!TlsSetValue(g_dwTlsErrIndex, lpwite))
2974     {
2975         HeapFree(GetProcessHeap(), 0, lpwite);
2976         return NULL;
2977     }
2978
2979     return lpwite;
2980 }
2981
2982
2983 /***********************************************************************
2984  *           INTERNET_SetLastError (internal)
2985  *
2986  * Set last thread specific error
2987  *
2988  * RETURNS
2989  *
2990  */
2991 void INTERNET_SetLastError(DWORD dwError)
2992 {
2993     LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);
2994
2995     if (!lpwite)
2996         lpwite = INTERNET_AllocThreadError();
2997
2998     SetLastError(dwError);
2999     if(lpwite)
3000         lpwite->dwError = dwError;
3001 }
3002
3003
3004 /***********************************************************************
3005  *           INTERNET_GetLastError (internal)
3006  *
3007  * Get last thread specific error
3008  *
3009  * RETURNS
3010  *
3011  */
3012 DWORD INTERNET_GetLastError(void)
3013 {
3014     LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);
3015     if (!lpwite) return 0;
3016     /* TlsGetValue clears last error, so set it again here */
3017     SetLastError(lpwite->dwError);
3018     return lpwite->dwError;
3019 }
3020
3021
3022 /***********************************************************************
3023  *           INTERNET_WorkerThreadFunc (internal)
3024  *
3025  * Worker thread execution function
3026  *
3027  * RETURNS
3028  *
3029  */
3030 static DWORD CALLBACK INTERNET_WorkerThreadFunc(LPVOID lpvParam)
3031 {
3032     LPWORKREQUEST lpRequest = lpvParam;
3033     WORKREQUEST workRequest;
3034
3035     TRACE("\n");
3036
3037     workRequest = *lpRequest;
3038     HeapFree(GetProcessHeap(), 0, lpRequest);
3039
3040     workRequest.asyncproc(&workRequest);
3041
3042     WININET_Release( workRequest.hdr );
3043     return TRUE;
3044 }
3045
3046
3047 /***********************************************************************
3048  *           INTERNET_AsyncCall (internal)
3049  *
3050  * Retrieves work request from queue
3051  *
3052  * RETURNS
3053  *
3054  */
3055 BOOL INTERNET_AsyncCall(LPWORKREQUEST lpWorkRequest)
3056 {
3057     BOOL bSuccess;
3058     LPWORKREQUEST lpNewRequest;
3059
3060     TRACE("\n");
3061
3062     lpNewRequest = HeapAlloc(GetProcessHeap(), 0, sizeof(WORKREQUEST));
3063     if (!lpNewRequest)
3064         return FALSE;
3065
3066     *lpNewRequest = *lpWorkRequest;
3067
3068     bSuccess = QueueUserWorkItem(INTERNET_WorkerThreadFunc, lpNewRequest, WT_EXECUTELONGFUNCTION);
3069     if (!bSuccess)
3070     {
3071         HeapFree(GetProcessHeap(), 0, lpNewRequest);
3072         INTERNET_SetLastError(ERROR_INTERNET_ASYNC_THREAD_FAILED);
3073     }
3074
3075     return bSuccess;
3076 }
3077
3078
3079 /***********************************************************************
3080  *          INTERNET_GetResponseBuffer  (internal)
3081  *
3082  * RETURNS
3083  *
3084  */
3085 LPSTR INTERNET_GetResponseBuffer(void)
3086 {
3087     LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);
3088     if (!lpwite)
3089         lpwite = INTERNET_AllocThreadError();
3090     TRACE("\n");
3091     return lpwite->response;
3092 }
3093
3094 /***********************************************************************
3095  *           INTERNET_GetNextLine  (internal)
3096  *
3097  * Parse next line in directory string listing
3098  *
3099  * RETURNS
3100  *   Pointer to beginning of next line
3101  *   NULL on failure
3102  *
3103  */
3104
3105 LPSTR INTERNET_GetNextLine(INT nSocket, LPDWORD dwLen)
3106 {
3107     struct pollfd pfd;
3108     BOOL bSuccess = FALSE;
3109     INT nRecv = 0;
3110     LPSTR lpszBuffer = INTERNET_GetResponseBuffer();
3111
3112     TRACE("\n");
3113
3114     pfd.fd = nSocket;
3115     pfd.events = POLLIN;
3116
3117     while (nRecv < MAX_REPLY_LEN)
3118     {
3119         if (poll(&pfd,1, RESPONSE_TIMEOUT * 1000) > 0)
3120         {
3121             if (recv(nSocket, &lpszBuffer[nRecv], 1, 0) <= 0)
3122             {
3123                 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
3124                 goto lend;
3125             }
3126
3127             if (lpszBuffer[nRecv] == '\n')
3128             {
3129                 bSuccess = TRUE;
3130                 break;
3131             }
3132             if (lpszBuffer[nRecv] != '\r')
3133                 nRecv++;
3134         }
3135         else
3136         {
3137             INTERNET_SetLastError(ERROR_INTERNET_TIMEOUT);
3138             goto lend;
3139         }
3140     }
3141
3142 lend:
3143     if (bSuccess)
3144     {
3145         lpszBuffer[nRecv] = '\0';
3146         *dwLen = nRecv - 1;
3147         TRACE(":%d %s\n", nRecv, lpszBuffer);
3148         return lpszBuffer;
3149     }
3150     else
3151     {
3152         return NULL;
3153     }
3154 }
3155
3156 /**********************************************************
3157  *      InternetQueryDataAvailable (WININET.@)
3158  *
3159  * Determines how much data is available to be read.
3160  *
3161  * RETURNS
3162  *   TRUE on success, FALSE if an error occurred. If
3163  *   INTERNET_FLAG_ASYNC was specified in InternetOpen, and
3164  *   no data is presently available, FALSE is returned with
3165  *   the last error ERROR_IO_PENDING; a callback with status
3166  *   INTERNET_STATUS_REQUEST_COMPLETE will be sent when more
3167  *   data is available.
3168  */
3169 BOOL WINAPI InternetQueryDataAvailable( HINTERNET hFile,
3170                                 LPDWORD lpdwNumberOfBytesAvailble,
3171                                 DWORD dwFlags, DWORD_PTR dwContext)
3172 {
3173     WININETHANDLEHEADER *hdr;
3174     DWORD res;
3175
3176     TRACE("(%p %p %x %lx)\n", hFile, lpdwNumberOfBytesAvailble, dwFlags, dwContext);
3177
3178     hdr = WININET_GetObject( hFile );
3179     if (!hdr) {
3180         INTERNET_SetLastError(ERROR_INVALID_HANDLE);
3181         return FALSE;
3182     }
3183
3184     if(hdr->vtbl->QueryDataAvailable) {
3185         res = hdr->vtbl->QueryDataAvailable(hdr, lpdwNumberOfBytesAvailble, dwFlags, dwContext);
3186     }else {
3187         WARN("wrong handle\n");
3188         res = ERROR_INTERNET_INCORRECT_HANDLE_TYPE;
3189     }
3190
3191     WININET_Release(hdr);
3192
3193     if(res != ERROR_SUCCESS)
3194         SetLastError(res);
3195     return res == ERROR_SUCCESS;
3196 }
3197
3198
3199 /***********************************************************************
3200  *      InternetLockRequestFile (WININET.@)
3201  */
3202 BOOL WINAPI InternetLockRequestFile( HINTERNET hInternet, HANDLE
3203 *lphLockReqHandle)
3204 {
3205     FIXME("STUB\n");
3206     return FALSE;
3207 }
3208
3209 BOOL WINAPI InternetUnlockRequestFile( HANDLE hLockHandle)
3210 {
3211     FIXME("STUB\n");
3212     return FALSE;
3213 }
3214
3215
3216 /***********************************************************************
3217  *      InternetAutodial (WININET.@)
3218  *
3219  * On windows this function is supposed to dial the default internet
3220  * connection. We don't want to have Wine dial out to the internet so
3221  * we return TRUE by default. It might be nice to check if we are connected.
3222  *
3223  * RETURNS
3224  *   TRUE on success
3225  *   FALSE on failure
3226  *
3227  */
3228 BOOL WINAPI InternetAutodial(DWORD dwFlags, HWND hwndParent)
3229 {
3230     FIXME("STUB\n");
3231
3232     /* Tell that we are connected to the internet. */
3233     return TRUE;
3234 }
3235
3236 /***********************************************************************
3237  *      InternetAutodialHangup (WININET.@)
3238  *
3239  * Hangs up a connection made with InternetAutodial
3240  *
3241  * PARAM
3242  *    dwReserved
3243  * RETURNS
3244  *   TRUE on success
3245  *   FALSE on failure
3246  *
3247  */
3248 BOOL WINAPI InternetAutodialHangup(DWORD dwReserved)
3249 {
3250     FIXME("STUB\n");
3251
3252     /* we didn't dial, we don't disconnect */
3253     return TRUE;
3254 }
3255
3256 /***********************************************************************
3257  *      InternetCombineUrlA (WININET.@)
3258  *
3259  * Combine a base URL with a relative URL
3260  *
3261  * RETURNS
3262  *   TRUE on success
3263  *   FALSE on failure
3264  *
3265  */
3266
3267 BOOL WINAPI InternetCombineUrlA(LPCSTR lpszBaseUrl, LPCSTR lpszRelativeUrl,
3268                                 LPSTR lpszBuffer, LPDWORD lpdwBufferLength,
3269                                 DWORD dwFlags)
3270 {
3271     HRESULT hr=S_OK;
3272
3273     TRACE("(%s, %s, %p, %p, 0x%08x)\n", debugstr_a(lpszBaseUrl), debugstr_a(lpszRelativeUrl), lpszBuffer, lpdwBufferLength, dwFlags);
3274
3275     /* Flip this bit to correspond to URL_ESCAPE_UNSAFE */
3276     dwFlags ^= ICU_NO_ENCODE;
3277     hr=UrlCombineA(lpszBaseUrl,lpszRelativeUrl,lpszBuffer,lpdwBufferLength,dwFlags);
3278
3279     return (hr==S_OK);
3280 }
3281
3282 /***********************************************************************
3283  *      InternetCombineUrlW (WININET.@)
3284  *
3285  * Combine a base URL with a relative URL
3286  *
3287  * RETURNS
3288  *   TRUE on success
3289  *   FALSE on failure
3290  *
3291  */
3292
3293 BOOL WINAPI InternetCombineUrlW(LPCWSTR lpszBaseUrl, LPCWSTR lpszRelativeUrl,
3294                                 LPWSTR lpszBuffer, LPDWORD lpdwBufferLength,
3295                                 DWORD dwFlags)
3296 {
3297     HRESULT hr=S_OK;
3298
3299     TRACE("(%s, %s, %p, %p, 0x%08x)\n", debugstr_w(lpszBaseUrl), debugstr_w(lpszRelativeUrl), lpszBuffer, lpdwBufferLength, dwFlags);
3300
3301     /* Flip this bit to correspond to URL_ESCAPE_UNSAFE */
3302     dwFlags ^= ICU_NO_ENCODE;
3303     hr=UrlCombineW(lpszBaseUrl,lpszRelativeUrl,lpszBuffer,lpdwBufferLength,dwFlags);
3304
3305     return (hr==S_OK);
3306 }
3307
3308 /* max port num is 65535 => 5 digits */
3309 #define MAX_WORD_DIGITS 5
3310
3311 #define URL_GET_COMP_LENGTH(url, component) ((url)->dw##component##Length ? \
3312     (url)->dw##component##Length : strlenW((url)->lpsz##component))
3313 #define URL_GET_COMP_LENGTHA(url, component) ((url)->dw##component##Length ? \
3314     (url)->dw##component##Length : strlen((url)->lpsz##component))
3315
3316 static BOOL url_uses_default_port(INTERNET_SCHEME nScheme, INTERNET_PORT nPort)
3317 {
3318     if ((nScheme == INTERNET_SCHEME_HTTP) &&
3319         (nPort == INTERNET_DEFAULT_HTTP_PORT))
3320         return TRUE;
3321     if ((nScheme == INTERNET_SCHEME_HTTPS) &&
3322         (nPort == INTERNET_DEFAULT_HTTPS_PORT))
3323         return TRUE;
3324     if ((nScheme == INTERNET_SCHEME_FTP) &&
3325         (nPort == INTERNET_DEFAULT_FTP_PORT))
3326         return TRUE;
3327     if ((nScheme == INTERNET_SCHEME_GOPHER) &&
3328         (nPort == INTERNET_DEFAULT_GOPHER_PORT))
3329         return TRUE;
3330
3331     if (nPort == INTERNET_INVALID_PORT_NUMBER)
3332         return TRUE;
3333
3334     return FALSE;
3335 }
3336
3337 /* opaque urls do not fit into the standard url hierarchy and don't have
3338  * two following slashes */
3339 static inline BOOL scheme_is_opaque(INTERNET_SCHEME nScheme)
3340 {
3341     return (nScheme != INTERNET_SCHEME_FTP) &&
3342            (nScheme != INTERNET_SCHEME_GOPHER) &&
3343            (nScheme != INTERNET_SCHEME_HTTP) &&
3344            (nScheme != INTERNET_SCHEME_HTTPS) &&
3345            (nScheme != INTERNET_SCHEME_FILE);
3346 }
3347
3348 static LPCWSTR INTERNET_GetSchemeString(INTERNET_SCHEME scheme)
3349 {
3350     int index;
3351     if (scheme < INTERNET_SCHEME_FIRST)
3352         return NULL;
3353     index = scheme - INTERNET_SCHEME_FIRST;
3354     if (index >= sizeof(url_schemes)/sizeof(url_schemes[0]))
3355         return NULL;
3356     return (LPCWSTR)&url_schemes[index];
3357 }
3358
3359 /* we can calculate using ansi strings because we're just
3360  * calculating string length, not size
3361  */
3362 static BOOL calc_url_length(LPURL_COMPONENTSW lpUrlComponents,
3363                             LPDWORD lpdwUrlLength)
3364 {
3365     INTERNET_SCHEME nScheme;
3366
3367     *lpdwUrlLength = 0;
3368
3369     if (lpUrlComponents->lpszScheme)
3370     {
3371         DWORD dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, Scheme);
3372         *lpdwUrlLength += dwLen;
3373         nScheme = GetInternetSchemeW(lpUrlComponents->lpszScheme, dwLen);
3374     }
3375     else
3376     {
3377         LPCWSTR scheme;
3378
3379         nScheme = lpUrlComponents->nScheme;
3380
3381         if (nScheme == INTERNET_SCHEME_DEFAULT)
3382             nScheme = INTERNET_SCHEME_HTTP;
3383         scheme = INTERNET_GetSchemeString(nScheme);
3384         *lpdwUrlLength += strlenW(scheme);
3385     }
3386
3387     (*lpdwUrlLength)++; /* ':' */
3388     if (!scheme_is_opaque(nScheme) || lpUrlComponents->lpszHostName)
3389         *lpdwUrlLength += strlen("//");
3390
3391     if (lpUrlComponents->lpszUserName)
3392     {
3393         *lpdwUrlLength += URL_GET_COMP_LENGTH(lpUrlComponents, UserName);
3394         *lpdwUrlLength += strlen("@");
3395     }
3396     else
3397     {
3398         if (lpUrlComponents->lpszPassword)
3399         {
3400             INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3401             return FALSE;
3402         }
3403     }
3404
3405     if (lpUrlComponents->lpszPassword)
3406     {
3407         *lpdwUrlLength += strlen(":");
3408         *lpdwUrlLength += URL_GET_COMP_LENGTH(lpUrlComponents, Password);
3409     }
3410
3411     if (lpUrlComponents->lpszHostName)
3412     {
3413         *lpdwUrlLength += URL_GET_COMP_LENGTH(lpUrlComponents, HostName);
3414
3415         if (!url_uses_default_port(nScheme, lpUrlComponents->nPort))
3416         {
3417             char szPort[MAX_WORD_DIGITS+1];
3418
3419             sprintf(szPort, "%d", lpUrlComponents->nPort);
3420             *lpdwUrlLength += strlen(szPort);
3421             *lpdwUrlLength += strlen(":");
3422         }
3423
3424         if (lpUrlComponents->lpszUrlPath && *lpUrlComponents->lpszUrlPath != '/')
3425             (*lpdwUrlLength)++; /* '/' */
3426     }
3427
3428     if (lpUrlComponents->lpszUrlPath)
3429         *lpdwUrlLength += URL_GET_COMP_LENGTH(lpUrlComponents, UrlPath);
3430
3431     return TRUE;
3432 }
3433
3434 static void convert_urlcomp_atow(LPURL_COMPONENTSA lpUrlComponents, LPURL_COMPONENTSW urlCompW)
3435 {
3436     INT len;
3437
3438     ZeroMemory(urlCompW, sizeof(URL_COMPONENTSW));
3439
3440     urlCompW->dwStructSize = sizeof(URL_COMPONENTSW);
3441     urlCompW->dwSchemeLength = lpUrlComponents->dwSchemeLength;
3442     urlCompW->nScheme = lpUrlComponents->nScheme;
3443     urlCompW->dwHostNameLength = lpUrlComponents->dwHostNameLength;
3444     urlCompW->nPort = lpUrlComponents->nPort;
3445     urlCompW->dwUserNameLength = lpUrlComponents->dwUserNameLength;
3446     urlCompW->dwPasswordLength = lpUrlComponents->dwPasswordLength;
3447     urlCompW->dwUrlPathLength = lpUrlComponents->dwUrlPathLength;
3448     urlCompW->dwExtraInfoLength = lpUrlComponents->dwExtraInfoLength;
3449
3450     if (lpUrlComponents->lpszScheme)
3451     {
3452         len = URL_GET_COMP_LENGTHA(lpUrlComponents, Scheme) + 1;
3453         urlCompW->lpszScheme = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3454         MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszScheme,
3455                             -1, urlCompW->lpszScheme, len);
3456     }
3457
3458     if (lpUrlComponents->lpszHostName)
3459     {
3460         len = URL_GET_COMP_LENGTHA(lpUrlComponents, HostName) + 1;
3461         urlCompW->lpszHostName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3462         MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszHostName,
3463                             -1, urlCompW->lpszHostName, len);
3464     }
3465
3466     if (lpUrlComponents->lpszUserName)
3467     {
3468         len = URL_GET_COMP_LENGTHA(lpUrlComponents, UserName) + 1;
3469         urlCompW->lpszUserName = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3470         MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszUserName,
3471                             -1, urlCompW->lpszUserName, len);
3472     }
3473
3474     if (lpUrlComponents->lpszPassword)
3475     {
3476         len = URL_GET_COMP_LENGTHA(lpUrlComponents, Password) + 1;
3477         urlCompW->lpszPassword = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3478         MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszPassword,
3479                             -1, urlCompW->lpszPassword, len);
3480     }
3481
3482     if (lpUrlComponents->lpszUrlPath)
3483     {
3484         len = URL_GET_COMP_LENGTHA(lpUrlComponents, UrlPath) + 1;
3485         urlCompW->lpszUrlPath = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3486         MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszUrlPath,
3487                             -1, urlCompW->lpszUrlPath, len);
3488     }
3489
3490     if (lpUrlComponents->lpszExtraInfo)
3491     {
3492         len = URL_GET_COMP_LENGTHA(lpUrlComponents, ExtraInfo) + 1;
3493         urlCompW->lpszExtraInfo = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3494         MultiByteToWideChar(CP_ACP, 0, lpUrlComponents->lpszExtraInfo,
3495                             -1, urlCompW->lpszExtraInfo, len);
3496     }
3497 }
3498
3499 /***********************************************************************
3500  *      InternetCreateUrlA (WININET.@)
3501  *
3502  * See InternetCreateUrlW.
3503  */
3504 BOOL WINAPI InternetCreateUrlA(LPURL_COMPONENTSA lpUrlComponents, DWORD dwFlags,
3505                                LPSTR lpszUrl, LPDWORD lpdwUrlLength)
3506 {
3507     BOOL ret;
3508     LPWSTR urlW = NULL;
3509     URL_COMPONENTSW urlCompW;
3510
3511     TRACE("(%p,%d,%p,%p)\n", lpUrlComponents, dwFlags, lpszUrl, lpdwUrlLength);
3512
3513     if (!lpUrlComponents || lpUrlComponents->dwStructSize != sizeof(URL_COMPONENTSW) || !lpdwUrlLength)
3514     {
3515         INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3516         return FALSE;
3517     }
3518
3519     convert_urlcomp_atow(lpUrlComponents, &urlCompW);
3520
3521     if (lpszUrl)
3522         urlW = HeapAlloc(GetProcessHeap(), 0, *lpdwUrlLength * sizeof(WCHAR));
3523
3524     ret = InternetCreateUrlW(&urlCompW, dwFlags, urlW, lpdwUrlLength);
3525
3526     if (!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER))
3527         *lpdwUrlLength /= sizeof(WCHAR);
3528
3529     /* on success, lpdwUrlLength points to the size of urlW in WCHARS
3530     * minus one, so add one to leave room for NULL terminator
3531     */
3532     if (ret)
3533         WideCharToMultiByte(CP_ACP, 0, urlW, -1, lpszUrl, *lpdwUrlLength + 1, NULL, NULL);
3534
3535     HeapFree(GetProcessHeap(), 0, urlCompW.lpszScheme);
3536     HeapFree(GetProcessHeap(), 0, urlCompW.lpszHostName);
3537     HeapFree(GetProcessHeap(), 0, urlCompW.lpszUserName);
3538     HeapFree(GetProcessHeap(), 0, urlCompW.lpszPassword);
3539     HeapFree(GetProcessHeap(), 0, urlCompW.lpszUrlPath);
3540     HeapFree(GetProcessHeap(), 0, urlCompW.lpszExtraInfo);
3541     HeapFree(GetProcessHeap(), 0, urlW);
3542
3543     return ret;
3544 }
3545
3546 /***********************************************************************
3547  *      InternetCreateUrlW (WININET.@)
3548  *
3549  * Creates a URL from its component parts.
3550  *
3551  * PARAMS
3552  *  lpUrlComponents [I] URL Components.
3553  *  dwFlags         [I] Flags. See notes.
3554  *  lpszUrl         [I] Buffer in which to store the created URL.
3555  *  lpdwUrlLength   [I/O] On input, the length of the buffer pointed to by
3556  *                        lpszUrl in characters. On output, the number of bytes
3557  *                        required to store the URL including terminator.
3558  *
3559  * NOTES
3560  *
3561  * The dwFlags parameter can be zero or more of the following:
3562  *|ICU_ESCAPE - Generates escape sequences for unsafe characters in the path and extra info of the URL.
3563  *
3564  * RETURNS
3565  *   TRUE on success
3566  *   FALSE on failure
3567  *
3568  */
3569 BOOL WINAPI InternetCreateUrlW(LPURL_COMPONENTSW lpUrlComponents, DWORD dwFlags,
3570                                LPWSTR lpszUrl, LPDWORD lpdwUrlLength)
3571 {
3572     DWORD dwLen;
3573     INTERNET_SCHEME nScheme;
3574
3575     static const WCHAR slashSlashW[] = {'/','/'};
3576     static const WCHAR percentD[] = {'%','d',0};
3577
3578     TRACE("(%p,%d,%p,%p)\n", lpUrlComponents, dwFlags, lpszUrl, lpdwUrlLength);
3579
3580     if (!lpUrlComponents || lpUrlComponents->dwStructSize != sizeof(URL_COMPONENTSW) || !lpdwUrlLength)
3581     {
3582         INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
3583         return FALSE;
3584     }
3585
3586     if (!calc_url_length(lpUrlComponents, &dwLen))
3587         return FALSE;
3588
3589     if (!lpszUrl || *lpdwUrlLength < dwLen)
3590     {
3591         *lpdwUrlLength = (dwLen + 1) * sizeof(WCHAR);
3592         INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
3593         return FALSE;
3594     }
3595
3596     *lpdwUrlLength = dwLen;
3597     lpszUrl[0] = 0x00;
3598
3599     dwLen = 0;
3600
3601     if (lpUrlComponents->lpszScheme)
3602     {
3603         dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, Scheme);
3604         memcpy(lpszUrl, lpUrlComponents->lpszScheme, dwLen * sizeof(WCHAR));
3605         lpszUrl += dwLen;
3606
3607         nScheme = GetInternetSchemeW(lpUrlComponents->lpszScheme, dwLen);
3608     }
3609     else
3610     {
3611         LPCWSTR scheme;
3612         nScheme = lpUrlComponents->nScheme;
3613
3614         if (nScheme == INTERNET_SCHEME_DEFAULT)
3615             nScheme = INTERNET_SCHEME_HTTP;
3616
3617         scheme = INTERNET_GetSchemeString(nScheme);
3618         dwLen = strlenW(scheme);
3619         memcpy(lpszUrl, scheme, dwLen * sizeof(WCHAR));
3620         lpszUrl += dwLen;
3621     }
3622
3623     /* all schemes are followed by at least a colon */
3624     *lpszUrl = ':';
3625     lpszUrl++;
3626
3627     if (!scheme_is_opaque(nScheme) || lpUrlComponents->lpszHostName)
3628     {
3629         memcpy(lpszUrl, slashSlashW, sizeof(slashSlashW));
3630         lpszUrl += sizeof(slashSlashW)/sizeof(slashSlashW[0]);
3631     }
3632
3633     if (lpUrlComponents->lpszUserName)
3634     {
3635         dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, UserName);
3636         memcpy(lpszUrl, lpUrlComponents->lpszUserName, dwLen * sizeof(WCHAR));
3637         lpszUrl += dwLen;
3638
3639         if (lpUrlComponents->lpszPassword)
3640         {
3641             *lpszUrl = ':';
3642             lpszUrl++;
3643
3644             dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, Password);
3645             memcpy(lpszUrl, lpUrlComponents->lpszPassword, dwLen * sizeof(WCHAR));
3646             lpszUrl += dwLen;
3647         }
3648
3649         *lpszUrl = '@';
3650         lpszUrl++;
3651     }
3652
3653     if (lpUrlComponents->lpszHostName)
3654     {
3655         dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, HostName);
3656         memcpy(lpszUrl, lpUrlComponents->lpszHostName, dwLen * sizeof(WCHAR));
3657         lpszUrl += dwLen;
3658
3659         if (!url_uses_default_port(nScheme, lpUrlComponents->nPort))
3660         {
3661             WCHAR szPort[MAX_WORD_DIGITS+1];
3662
3663             sprintfW(szPort, percentD, lpUrlComponents->nPort);
3664             *lpszUrl = ':';
3665             lpszUrl++;
3666             dwLen = strlenW(szPort);
3667             memcpy(lpszUrl, szPort, dwLen * sizeof(WCHAR));
3668             lpszUrl += dwLen;
3669         }
3670
3671         /* add slash between hostname and path if necessary */
3672         if (lpUrlComponents->lpszUrlPath && *lpUrlComponents->lpszUrlPath != '/')
3673         {
3674             *lpszUrl = '/';
3675             lpszUrl++;
3676         }
3677     }
3678
3679
3680     if (lpUrlComponents->lpszUrlPath)
3681     {
3682         dwLen = URL_GET_COMP_LENGTH(lpUrlComponents, UrlPath);
3683         memcpy(lpszUrl, lpUrlComponents->lpszUrlPath, dwLen * sizeof(WCHAR));
3684         lpszUrl += dwLen;
3685     }
3686
3687     *lpszUrl = '\0';
3688
3689     return TRUE;
3690 }
3691
3692 /***********************************************************************
3693  *      InternetConfirmZoneCrossingA (WININET.@)
3694  *
3695  */
3696 DWORD WINAPI InternetConfirmZoneCrossingA( HWND hWnd, LPSTR szUrlPrev, LPSTR szUrlNew, BOOL bPost )
3697 {
3698     FIXME("(%p, %s, %s, %x) stub\n", hWnd, debugstr_a(szUrlPrev), debugstr_a(szUrlNew), bPost);
3699     return ERROR_SUCCESS;
3700 }
3701
3702 /***********************************************************************
3703  *      InternetConfirmZoneCrossingW (WININET.@)
3704  *
3705  */
3706 DWORD WINAPI InternetConfirmZoneCrossingW( HWND hWnd, LPWSTR szUrlPrev, LPWSTR szUrlNew, BOOL bPost )
3707 {
3708     FIXME("(%p, %s, %s, %x) stub\n", hWnd, debugstr_w(szUrlPrev), debugstr_w(szUrlNew), bPost);
3709     return ERROR_SUCCESS;
3710 }
3711
3712 DWORD WINAPI InternetDialA( HWND hwndParent, LPSTR lpszConnectoid, DWORD dwFlags,
3713                             DWORD_PTR* lpdwConnection, DWORD dwReserved )
3714 {
3715     FIXME("(%p, %p, 0x%08x, %p, 0x%08x) stub\n", hwndParent, lpszConnectoid, dwFlags,
3716           lpdwConnection, dwReserved);
3717     return ERROR_SUCCESS;
3718 }
3719
3720 DWORD WINAPI InternetDialW( HWND hwndParent, LPWSTR lpszConnectoid, DWORD dwFlags,
3721                             DWORD_PTR* lpdwConnection, DWORD dwReserved )
3722 {
3723     FIXME("(%p, %p, 0x%08x, %p, 0x%08x) stub\n", hwndParent, lpszConnectoid, dwFlags,
3724           lpdwConnection, dwReserved);
3725     return ERROR_SUCCESS;
3726 }
3727
3728 BOOL WINAPI InternetGoOnlineA( LPSTR lpszURL, HWND hwndParent, DWORD dwReserved )
3729 {
3730     FIXME("(%s, %p, 0x%08x) stub\n", debugstr_a(lpszURL), hwndParent, dwReserved);
3731     return TRUE;
3732 }
3733
3734 BOOL WINAPI InternetGoOnlineW( LPWSTR lpszURL, HWND hwndParent, DWORD dwReserved )
3735 {
3736     FIXME("(%s, %p, 0x%08x) stub\n", debugstr_w(lpszURL), hwndParent, dwReserved);
3737     return TRUE;
3738 }
3739
3740 DWORD WINAPI InternetHangUp( DWORD_PTR dwConnection, DWORD dwReserved )
3741 {
3742     FIXME("(0x%08lx, 0x%08x) stub\n", dwConnection, dwReserved);
3743     return ERROR_SUCCESS;
3744 }
3745
3746 BOOL WINAPI CreateMD5SSOHash( PWSTR pszChallengeInfo, PWSTR pwszRealm, PWSTR pwszTarget,
3747                               PBYTE pbHexHash )
3748 {
3749     FIXME("(%s, %s, %s, %p) stub\n", debugstr_w(pszChallengeInfo), debugstr_w(pwszRealm),
3750           debugstr_w(pwszTarget), pbHexHash);
3751     return FALSE;
3752 }
3753
3754 BOOL WINAPI ResumeSuspendedDownload( HINTERNET hInternet, DWORD dwError )
3755 {
3756     FIXME("(%p, 0x%08x) stub\n", hInternet, dwError);
3757     return FALSE;
3758 }
3759
3760 BOOL WINAPI InternetQueryFortezzaStatus(DWORD *a, DWORD_PTR b)
3761 {
3762     FIXME("(%p, %08lx) stub\n", a, b);
3763     return 0;
3764 }