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