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