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