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