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