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