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