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