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