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