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