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