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