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