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