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