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