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