ok() does not support '%S'. Store the Ansi version, convert to Unicode
[wine] / dlls / wininet / internet.c
1 /*
2  * Wininet
3  *
4  * Copyright 1999 Corel Corporation
5  * Copyright 2002 CodeWeavers Inc.
6  *
7  * Ulrich Czekalla
8  * Aric Stewart
9  *
10  * Copyright 2002 Jaco Greeff
11  *
12  * This library is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public
14  * License as published by the Free Software Foundation; either
15  * version 2.1 of the License, or (at your option) any later version.
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with this library; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25  */
26
27 #include "config.h"
28
29 #define MAXHOSTNAME 100 /* from http.c */
30
31 #include <string.h>
32 #include <stdio.h>
33 #include <sys/types.h>
34 #ifdef HAVE_SYS_SOCKET_H
35 # include <sys/socket.h>
36 #endif
37 #ifdef HAVE_SYS_TIME_H
38 # include <sys/time.h>
39 #endif
40 #include <stdlib.h>
41 #include <ctype.h>
42 #ifdef HAVE_UNISTD_H
43 # include <unistd.h>
44 #endif
45
46 #include "windef.h"
47 #include "winbase.h"
48 #include "winreg.h"
49 #include "wininet.h"
50 #include "winnls.h"
51 #include "wine/debug.h"
52 #include "winerror.h"
53 #define NO_SHLWAPI_STREAM
54 #include "shlwapi.h"
55
56 #include "wine/exception.h"
57 #include "excpt.h"
58
59 #include "internet.h"
60
61 #include "wine/unicode.h"
62
63 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
64
65 #define MAX_IDLE_WORKER 1000*60*1
66 #define MAX_WORKER_THREADS 10
67 #define RESPONSE_TIMEOUT        30
68
69 #define GET_HWININET_FROM_LPWININETFINDNEXT(lpwh) \
70 (LPWININETAPPINFOA)(((LPWININETFTPSESSIONA)(lpwh->hdr.lpwhparent))->hdr.lpwhparent)
71
72 /* filter for page-fault exceptions */
73 static WINE_EXCEPTION_FILTER(page_fault)
74 {
75     if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ||
76         GetExceptionCode() == EXCEPTION_PRIV_INSTRUCTION)
77         return EXCEPTION_EXECUTE_HANDLER;
78     return EXCEPTION_CONTINUE_SEARCH;
79 }
80
81 typedef struct
82 {
83     DWORD  dwError;
84     CHAR   response[MAX_REPLY_LEN];
85 } WITHREADERROR, *LPWITHREADERROR;
86
87 BOOL WINAPI INTERNET_FindNextFileA(HINTERNET hFind, LPVOID lpvFindData);
88 VOID INTERNET_ExecuteWork();
89
90 DWORD g_dwTlsErrIndex = TLS_OUT_OF_INDEXES;
91 DWORD dwNumThreads;
92 DWORD dwNumIdleThreads;
93 DWORD dwNumJobs;
94 HANDLE hEventArray[2];
95 #define hQuitEvent hEventArray[0]
96 #define hWorkEvent hEventArray[1]
97 CRITICAL_SECTION csQueue;
98 LPWORKREQUEST lpHeadWorkQueue;
99 LPWORKREQUEST lpWorkQueueTail;
100
101 /***********************************************************************
102  * DllMain [Internal] Initializes the internal 'WININET.DLL'.
103  *
104  * PARAMS
105  *     hinstDLL    [I] handle to the DLL's instance
106  *     fdwReason   [I]
107  *     lpvReserved [I] reserved, must be NULL
108  *
109  * RETURNS
110  *     Success: TRUE
111  *     Failure: FALSE
112  */
113
114 BOOL WINAPI DllMain (HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
115 {
116     TRACE("%p,%lx,%p\n", hinstDLL, fdwReason, lpvReserved);
117
118     switch (fdwReason) {
119         case DLL_PROCESS_ATTACH:
120
121             g_dwTlsErrIndex = TlsAlloc();
122
123             if (g_dwTlsErrIndex == TLS_OUT_OF_INDEXES)
124                 return FALSE;
125
126             hQuitEvent = CreateEventA(0, TRUE, FALSE, NULL);
127             hWorkEvent = CreateEventA(0, FALSE, FALSE, NULL);
128             InitializeCriticalSection(&csQueue);
129
130             dwNumThreads = 0;
131             dwNumIdleThreads = 0;
132             dwNumJobs = 0;
133
134         case DLL_THREAD_ATTACH:
135             {
136                 LPWITHREADERROR lpwite = HeapAlloc(GetProcessHeap(), 0, sizeof(WITHREADERROR));
137                 if (NULL == lpwite)
138                     return FALSE;
139
140                 TlsSetValue(g_dwTlsErrIndex, (LPVOID)lpwite);
141             }
142             break;
143
144         case DLL_THREAD_DETACH:
145             if (g_dwTlsErrIndex != TLS_OUT_OF_INDEXES)
146                         {
147                                 LPVOID lpwite = TlsGetValue(g_dwTlsErrIndex);
148                                 if (lpwite)
149                    HeapFree(GetProcessHeap(), 0, lpwite);
150                         }
151             break;
152
153         case DLL_PROCESS_DETACH:
154
155             if (g_dwTlsErrIndex != TLS_OUT_OF_INDEXES)
156             {
157                 HeapFree(GetProcessHeap(), 0, TlsGetValue(g_dwTlsErrIndex));
158                 TlsFree(g_dwTlsErrIndex);
159             }
160
161             SetEvent(hQuitEvent);
162
163             CloseHandle(hQuitEvent);
164             CloseHandle(hWorkEvent);
165             DeleteCriticalSection(&csQueue);
166             break;
167     }
168
169     return TRUE;
170 }
171
172
173 /***********************************************************************
174  *           InternetInitializeAutoProxyDll   (WININET.@)
175  *
176  * Setup the internal proxy
177  *
178  * PARAMETERS
179  *     dwReserved
180  *
181  * RETURNS
182  *     FALSE on failure
183  *
184  */
185 BOOL WINAPI InternetInitializeAutoProxyDll(DWORD dwReserved)
186 {
187     FIXME("STUB\n");
188     INTERNET_SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
189     return FALSE;
190 }
191
192
193 /***********************************************************************
194  *           InternetOpenA   (WININET.@)
195  *
196  * Per-application initialization of wininet
197  *
198  * RETURNS
199  *    HINTERNET on success
200  *    NULL on failure
201  *
202  */
203 HINTERNET WINAPI InternetOpenA(LPCSTR lpszAgent, DWORD dwAccessType,
204     LPCSTR lpszProxy, LPCSTR lpszProxyBypass, DWORD dwFlags)
205 {
206     LPWININETAPPINFOA lpwai = NULL;
207
208     TRACE("\n");
209
210     /* Clear any error information */
211     INTERNET_SetLastError(0);
212
213     lpwai = HeapAlloc(GetProcessHeap(), 0, sizeof(WININETAPPINFOA));
214     if (NULL == lpwai)
215         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
216     else
217     {
218         memset(lpwai, 0, sizeof(WININETAPPINFOA));
219         lpwai->hdr.htype = WH_HINIT;
220         lpwai->hdr.lpwhparent = NULL;
221         lpwai->hdr.dwFlags = dwFlags;
222         if (NULL != lpszAgent)
223         {
224             if ((lpwai->lpszAgent = HeapAlloc( GetProcessHeap(),0,strlen(lpszAgent)+1)))
225                 strcpy( lpwai->lpszAgent, lpszAgent );
226         }
227         if (NULL != lpszProxy)
228         {
229             if ((lpwai->lpszProxy = HeapAlloc( GetProcessHeap(), 0, strlen(lpszProxy)+1 )))
230                 strcpy( lpwai->lpszProxy, lpszProxy );
231         }
232         if (NULL != lpszProxyBypass)
233         {
234             if ((lpwai->lpszProxyBypass = HeapAlloc( GetProcessHeap(), 0, strlen(lpszProxyBypass)+1)))
235                 strcpy( lpwai->lpszProxyBypass, lpszProxyBypass );
236         }
237         lpwai->dwAccessType = dwAccessType;
238     }
239
240     return (HINTERNET)lpwai;
241 }
242
243
244 /***********************************************************************
245  *           InternetOpenW   (WININET.@)
246  *
247  * Per-application initialization of wininet
248  *
249  * RETURNS
250  *    HINTERNET on success
251  *    NULL on failure
252  *
253  */
254 HINTERNET WINAPI InternetOpenW(LPCWSTR lpszAgent, DWORD dwAccessType,
255     LPCWSTR lpszProxy, LPCWSTR lpszProxyBypass, DWORD dwFlags)
256 {
257     HINTERNET rc = (HINTERNET)NULL;
258     INT lenAgent = lstrlenW(lpszAgent)+1;
259     INT lenProxy = lstrlenW(lpszProxy)+1;
260     INT lenBypass = lstrlenW(lpszProxyBypass)+1;
261     CHAR *szAgent = (CHAR *)malloc(lenAgent*sizeof(CHAR));
262     CHAR *szProxy = (CHAR *)malloc(lenProxy*sizeof(CHAR));
263     CHAR *szBypass = (CHAR *)malloc(lenBypass*sizeof(CHAR));
264
265     if (!szAgent || !szProxy || !szBypass)
266     {
267         if (szAgent)
268             free(szAgent);
269         if (szProxy)
270             free(szProxy);
271         if (szBypass)
272             free(szBypass);
273         return (HINTERNET)NULL;
274     }
275
276     WideCharToMultiByte(CP_ACP, -1, lpszAgent, -1, szAgent, lenAgent,
277         NULL, NULL);
278     WideCharToMultiByte(CP_ACP, -1, lpszProxy, -1, szProxy, lenProxy,
279         NULL, NULL);
280     WideCharToMultiByte(CP_ACP, -1, lpszProxyBypass, -1, szBypass, lenBypass,
281         NULL, NULL);
282
283     rc = InternetOpenA(szAgent, dwAccessType, szProxy, szBypass, dwFlags);
284
285     free(szAgent);
286     free(szProxy);
287     free(szBypass);
288
289     return rc;
290 }
291
292 /***********************************************************************
293  *           InternetGetLastResponseInfoA (WININET.@)
294  *
295  * Return last wininet error description on the calling thread
296  *
297  * RETURNS
298  *    TRUE on success of writting to buffer
299  *    FALSE on failure
300  *
301  */
302 BOOL WINAPI InternetGetLastResponseInfoA(LPDWORD lpdwError,
303     LPSTR lpszBuffer, LPDWORD lpdwBufferLength)
304 {
305     LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);
306
307     TRACE("\n");
308
309     *lpdwError = lpwite->dwError;
310     if (lpwite->dwError)
311     {
312         strncpy(lpszBuffer, lpwite->response, *lpdwBufferLength);
313         *lpdwBufferLength = strlen(lpszBuffer);
314     }
315     else
316         *lpdwBufferLength = 0;
317
318     return TRUE;
319 }
320
321
322 /***********************************************************************
323  *           InternetGetConnectedState (WININET.@)
324  *
325  * Return connected state
326  *
327  * RETURNS
328  *    TRUE if connected
329  *    if lpdwStatus is not null, return the status (off line,
330  *    modem, lan...) in it.
331  *    FALSE if not connected
332  */
333 BOOL WINAPI InternetGetConnectedState(LPDWORD lpdwStatus, DWORD dwReserved)
334 {
335     if (lpdwStatus) {
336         FIXME("always returning LAN connection.\n");
337         *lpdwStatus = INTERNET_CONNECTION_LAN;
338     }
339     return TRUE;
340 }
341
342
343 /***********************************************************************
344  *           InternetConnectA (WININET.@)
345  *
346  * Open a ftp, gopher or http session
347  *
348  * RETURNS
349  *    HINTERNET a session handle on success
350  *    NULL on failure
351  *
352  */
353 HINTERNET WINAPI InternetConnectA(HINTERNET hInternet,
354     LPCSTR lpszServerName, INTERNET_PORT nServerPort,
355     LPCSTR lpszUserName, LPCSTR lpszPassword,
356     DWORD dwService, DWORD dwFlags, DWORD dwContext)
357 {
358     HINTERNET rc = (HINTERNET) NULL;
359
360     TRACE("ServerPort %i\n",nServerPort);
361
362     /* Clear any error information */
363     INTERNET_SetLastError(0);
364
365     switch (dwService)
366     {
367         case INTERNET_SERVICE_FTP:
368             rc = FTP_Connect(hInternet, lpszServerName, nServerPort,
369             lpszUserName, lpszPassword, dwFlags, dwContext);
370             break;
371
372         case INTERNET_SERVICE_HTTP:
373             rc = HTTP_Connect(hInternet, lpszServerName, nServerPort,
374             lpszUserName, lpszPassword, dwFlags, dwContext);
375             break;
376
377         case INTERNET_SERVICE_GOPHER:
378         default:
379             break;
380     }
381
382     return rc;
383 }
384
385
386 /***********************************************************************
387  *           InternetConnectW (WININET.@)
388  *
389  * Open a ftp, gopher or http session
390  *
391  * RETURNS
392  *    HINTERNET a session handle on success
393  *    NULL on failure
394  *
395  */
396 HINTERNET WINAPI InternetConnectW(HINTERNET hInternet,
397     LPCWSTR lpszServerName, INTERNET_PORT nServerPort,
398     LPCWSTR lpszUserName, LPCWSTR lpszPassword,
399     DWORD dwService, DWORD dwFlags, DWORD dwContext)
400 {
401     HINTERNET rc = (HINTERNET)NULL;
402     INT lenServer = lstrlenW(lpszServerName)+1;
403     INT lenUser = lstrlenW(lpszUserName)+1;
404     INT lenPass = lstrlenW(lpszPassword)+1;
405     CHAR *szServerName = (CHAR *)malloc(lenServer*sizeof(CHAR));
406     CHAR *szUserName = (CHAR *)malloc(lenUser*sizeof(CHAR));
407     CHAR *szPassword = (CHAR *)malloc(lenPass*sizeof(CHAR));
408
409     if (!szServerName || !szUserName || !szPassword)
410     {
411         if (szServerName)
412             free(szServerName);
413         if (szUserName)
414             free(szUserName);
415         if (szPassword)
416             free(szPassword);
417         return (HINTERNET)NULL;
418     }
419
420     WideCharToMultiByte(CP_ACP, -1, lpszServerName, -1, szServerName, lenServer,
421         NULL, NULL);
422     WideCharToMultiByte(CP_ACP, -1, lpszUserName, -1, szUserName, lenUser,
423         NULL, NULL);
424     WideCharToMultiByte(CP_ACP, -1, lpszPassword, -1, szPassword, lenPass,
425         NULL, NULL);
426
427     rc = InternetConnectA(hInternet, szServerName, nServerPort,
428         szUserName, szPassword, dwService, dwFlags, dwContext);
429
430     free(szServerName);
431     free(szUserName);
432     free(szPassword);
433     return rc;
434 }
435
436
437 /***********************************************************************
438  *           InternetFindNextFileA (WININET.@)
439  *
440  * Continues a file search from a previous call to FindFirstFile
441  *
442  * RETURNS
443  *    TRUE on success
444  *    FALSE on failure
445  *
446  */
447 BOOL WINAPI InternetFindNextFileA(HINTERNET hFind, LPVOID lpvFindData)
448 {
449     LPWININETAPPINFOA hIC = NULL;
450     LPWININETFINDNEXTA lpwh = (LPWININETFINDNEXTA) hFind;
451
452     TRACE("\n");
453
454     if (NULL == lpwh || lpwh->hdr.htype != WH_HFINDNEXT)
455     {
456         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
457         return FALSE;
458     }
459
460     hIC = GET_HWININET_FROM_LPWININETFINDNEXT(lpwh);
461     if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
462     {
463         WORKREQUEST workRequest;
464
465         workRequest.asyncall = INTERNETFINDNEXTA;
466         workRequest.HFTPSESSION = (DWORD)hFind;
467         workRequest.LPFINDFILEDATA = (DWORD)lpvFindData;
468
469         return INTERNET_AsyncCall(&workRequest);
470     }
471     else
472     {
473         return INTERNET_FindNextFileA(hFind, lpvFindData);
474     }
475 }
476
477 /***********************************************************************
478  *           INTERNET_FindNextFileA (Internal)
479  *
480  * Continues a file search from a previous call to FindFirstFile
481  *
482  * RETURNS
483  *    TRUE on success
484  *    FALSE on failure
485  *
486  */
487 BOOL WINAPI INTERNET_FindNextFileA(HINTERNET hFind, LPVOID lpvFindData)
488 {
489     BOOL bSuccess = TRUE;
490     LPWININETAPPINFOA hIC = NULL;
491     LPWIN32_FIND_DATAA lpFindFileData;
492     LPWININETFINDNEXTA lpwh = (LPWININETFINDNEXTA) hFind;
493
494     TRACE("\n");
495
496     if (NULL == lpwh || lpwh->hdr.htype != WH_HFINDNEXT)
497     {
498         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
499         return FALSE;
500     }
501
502     /* Clear any error information */
503     INTERNET_SetLastError(0);
504
505     if (lpwh->hdr.lpwhparent->htype != WH_HFTPSESSION)
506     {
507         FIXME("Only FTP find next supported\n");
508         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
509         return FALSE;
510     }
511
512     TRACE("index(%d) size(%ld)\n", lpwh->index, lpwh->size);
513
514     lpFindFileData = (LPWIN32_FIND_DATAA) lpvFindData;
515     ZeroMemory(lpFindFileData, sizeof(WIN32_FIND_DATAA));
516
517     if (lpwh->index >= lpwh->size)
518     {
519         INTERNET_SetLastError(ERROR_NO_MORE_FILES);
520         bSuccess = FALSE;
521         goto lend;
522     }
523
524     FTP_ConvertFileProp(&lpwh->lpafp[lpwh->index], lpFindFileData);
525     lpwh->index++;
526
527     TRACE("\nName: %s\nSize: %ld\n", lpFindFileData->cFileName, lpFindFileData->nFileSizeLow);
528
529 lend:
530
531     hIC = GET_HWININET_FROM_LPWININETFINDNEXT(lpwh);
532     if (hIC->lpfnStatusCB)
533     {
534         INTERNET_ASYNC_RESULT iar;
535
536         iar.dwResult = (DWORD)bSuccess;
537         iar.dwError = iar.dwError = bSuccess ? ERROR_SUCCESS :
538                                                INTERNET_GetLastError();
539
540         SendAsyncCallback(hIC, hFind, lpwh->hdr.dwContext,
541                       INTERNET_STATUS_REQUEST_COMPLETE, &iar,
542                        sizeof(INTERNET_ASYNC_RESULT));
543     }
544
545     return bSuccess;
546 }
547
548
549 /***********************************************************************
550  *           INTERNET_CloseHandle (internal)
551  *
552  * Close internet handle
553  *
554  * RETURNS
555  *    Void
556  *
557  */
558 VOID INTERNET_CloseHandle(LPWININETAPPINFOA lpwai)
559 {
560     TRACE("%p\n",lpwai);
561
562     SendAsyncCallback(lpwai, lpwai, lpwai->hdr.dwContext,
563                       INTERNET_STATUS_HANDLE_CLOSING, lpwai,
564                       sizeof(HINTERNET));
565
566     if (lpwai->lpszAgent)
567         HeapFree(GetProcessHeap(), 0, lpwai->lpszAgent);
568
569     if (lpwai->lpszProxy)
570         HeapFree(GetProcessHeap(), 0, lpwai->lpszProxy);
571
572     if (lpwai->lpszProxyBypass)
573         HeapFree(GetProcessHeap(), 0, lpwai->lpszProxyBypass);
574
575     HeapFree(GetProcessHeap(), 0, lpwai);
576 }
577
578
579 /***********************************************************************
580  *           InternetCloseHandle (WININET.@)
581  *
582  * Generic close handle function
583  *
584  * RETURNS
585  *    TRUE on success
586  *    FALSE on failure
587  *
588  */
589 BOOL WINAPI InternetCloseHandle(HINTERNET hInternet)
590 {
591     BOOL retval;
592     LPWININETHANDLEHEADER lpwh = (LPWININETHANDLEHEADER) hInternet;
593
594     TRACE("%p\n",hInternet);
595     if (NULL == lpwh)
596         return FALSE;
597
598     __TRY {
599         /* Clear any error information */
600         INTERNET_SetLastError(0);
601         retval = FALSE;
602
603         switch (lpwh->htype)
604         {
605             case WH_HINIT:
606                 INTERNET_CloseHandle((LPWININETAPPINFOA) lpwh);
607                 retval = TRUE;
608                 break;
609
610             case WH_HHTTPSESSION:
611                 HTTP_CloseHTTPSessionHandle((LPWININETHTTPSESSIONA) lpwh);
612                 retval = TRUE;
613                 break;
614
615             case WH_HHTTPREQ:
616                 HTTP_CloseHTTPRequestHandle((LPWININETHTTPREQA) lpwh);
617                 retval = TRUE;
618                 break;
619
620             case WH_HFTPSESSION:
621                 retval = FTP_CloseSessionHandle((LPWININETFTPSESSIONA) lpwh);
622                 break;
623
624             case WH_HFINDNEXT:
625                 retval = FTP_CloseFindNextHandle((LPWININETFINDNEXTA) lpwh);
626                 break;
627
628             default:
629                 break;
630         }
631     } __EXCEPT(page_fault) {
632         INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
633         return FALSE;
634     }
635     __ENDTRY
636
637     return retval;
638 }
639
640
641 /***********************************************************************
642  *           ConvertUrlComponentValue (Internal)
643  *
644  * Helper function for InternetCrackUrlA
645  *
646  */
647 void ConvertUrlComponentValue(LPSTR* lppszComponent, LPDWORD dwComponentLen,
648                               LPWSTR lpwszComponent, DWORD dwwComponentLen,
649                               LPCSTR lpszStart,
650                               LPCWSTR lpwszStart)
651 {
652     if (*dwComponentLen != 0)
653     {
654         int nASCIILength=WideCharToMultiByte(CP_ACP,0,lpwszComponent,dwwComponentLen,NULL,0,NULL,NULL);
655         if (*lppszComponent == NULL)
656         {
657             int nASCIIOffset=WideCharToMultiByte(CP_ACP,0,lpwszStart,lpwszComponent-lpwszStart,NULL,0,NULL,NULL);
658             *lppszComponent = (LPSTR)lpszStart+nASCIIOffset;
659             *dwComponentLen = nASCIILength;
660         }
661         else
662         {
663             INT ncpylen = min((*dwComponentLen)-1, nASCIILength);
664             WideCharToMultiByte(CP_ACP,0,lpwszComponent,dwwComponentLen,*lppszComponent,ncpylen+1,NULL,NULL);
665             (*lppszComponent)[ncpylen]=0;
666             *dwComponentLen = ncpylen;
667         }
668     }
669 }
670
671
672 /***********************************************************************
673  *           InternetCrackUrlA (WININET.@)
674  *
675  * Break up URL into its components
676  *
677  * TODO: Handle dwFlags
678  *
679  * RETURNS
680  *    TRUE on success
681  *    FALSE on failure
682  *
683  */
684 BOOL WINAPI InternetCrackUrlA(LPCSTR lpszUrl, DWORD dwUrlLength, DWORD dwFlags,
685     LPURL_COMPONENTSA lpUrlComponents)
686 {
687   DWORD nLength;
688   URL_COMPONENTSW UCW;
689   WCHAR* lpwszUrl;
690   if(dwUrlLength==0)
691       dwUrlLength=strlen(lpszUrl);
692   lpwszUrl=HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR)*(dwUrlLength+1));
693   memset(lpwszUrl,0,sizeof(WCHAR)*(dwUrlLength+1));
694   nLength=MultiByteToWideChar(CP_ACP,0,lpszUrl,dwUrlLength,lpwszUrl,dwUrlLength+1);
695   memset(&UCW,0,sizeof(UCW));
696   if(lpUrlComponents->dwHostNameLength!=0)
697       UCW.dwHostNameLength=1;
698   if(lpUrlComponents->dwUserNameLength!=0)
699       UCW.dwUserNameLength=1;
700   if(lpUrlComponents->dwPasswordLength!=0)
701       UCW.dwPasswordLength=1;
702   if(lpUrlComponents->dwUrlPathLength!=0)
703       UCW.dwUrlPathLength=1;
704   if(lpUrlComponents->dwSchemeLength!=0)
705       UCW.dwSchemeLength=1;
706   if(lpUrlComponents->dwExtraInfoLength!=0)
707       UCW.dwExtraInfoLength=1;
708   if(!InternetCrackUrlW(lpwszUrl,nLength,dwFlags,&UCW))
709   {
710       HeapFree(GetProcessHeap(), 0, lpwszUrl);
711       return FALSE;
712   }
713   ConvertUrlComponentValue(&lpUrlComponents->lpszHostName, &lpUrlComponents->dwHostNameLength,
714                            UCW.lpszHostName, UCW.dwHostNameLength,
715                            lpszUrl, lpwszUrl);
716   ConvertUrlComponentValue(&lpUrlComponents->lpszUserName, &lpUrlComponents->dwUserNameLength,
717                            UCW.lpszUserName, UCW.dwUserNameLength,
718                            lpszUrl, lpwszUrl);
719   ConvertUrlComponentValue(&lpUrlComponents->lpszPassword, &lpUrlComponents->dwPasswordLength,
720                            UCW.lpszPassword, UCW.dwPasswordLength,
721                            lpszUrl, lpwszUrl);
722   ConvertUrlComponentValue(&lpUrlComponents->lpszUrlPath, &lpUrlComponents->dwUrlPathLength,
723                            UCW.lpszUrlPath, UCW.dwUrlPathLength,
724                            lpszUrl, lpwszUrl);
725   ConvertUrlComponentValue(&lpUrlComponents->lpszScheme, &lpUrlComponents->dwSchemeLength,
726                            UCW.lpszScheme, UCW.dwSchemeLength,
727                            lpszUrl, lpwszUrl);
728   ConvertUrlComponentValue(&lpUrlComponents->lpszExtraInfo, &lpUrlComponents->dwExtraInfoLength,
729                            UCW.lpszExtraInfo, UCW.dwExtraInfoLength,
730                            lpszUrl, lpwszUrl);
731   lpUrlComponents->nScheme=UCW.nScheme;
732   lpUrlComponents->nPort=UCW.nPort;
733   HeapFree(GetProcessHeap(), 0, lpwszUrl);
734   
735   TRACE("%s: scheme(%s) host(%s) path(%s) extra(%s)\n", lpszUrl,
736           debugstr_an(lpUrlComponents->lpszScheme,lpUrlComponents->dwSchemeLength),
737           debugstr_an(lpUrlComponents->lpszHostName,lpUrlComponents->dwHostNameLength),
738           debugstr_an(lpUrlComponents->lpszUrlPath,lpUrlComponents->dwUrlPathLength),
739           debugstr_an(lpUrlComponents->lpszExtraInfo,lpUrlComponents->dwExtraInfoLength));
740
741   return TRUE;
742 }
743
744 /***********************************************************************
745  *           GetInternetSchemeW (internal)
746  *
747  * Get scheme of url
748  *
749  * RETURNS
750  *    scheme on success
751  *    INTERNET_SCHEME_UNKNOWN on failure
752  *
753  */
754 INTERNET_SCHEME GetInternetSchemeW(LPCWSTR lpszScheme, INT nMaxCmp)
755 {
756     INTERNET_SCHEME iScheme=INTERNET_SCHEME_UNKNOWN;
757     WCHAR lpszFtp[]={'f','t','p',0};
758     WCHAR lpszGopher[]={'g','o','p','h','e','r',0};
759     WCHAR lpszHttp[]={'h','t','t','p',0};
760     WCHAR lpszHttps[]={'h','t','t','p','s',0};
761     WCHAR lpszFile[]={'f','i','l','e',0};
762     WCHAR lpszNews[]={'n','e','w','s',0};
763     WCHAR lpszMailto[]={'m','a','i','l','t','o',0};
764     WCHAR lpszRes[]={'r','e','s',0};
765     WCHAR* tempBuffer=NULL;
766     TRACE("\n");
767     if(lpszScheme==NULL)
768         return INTERNET_SCHEME_UNKNOWN;
769
770     tempBuffer=malloc(nMaxCmp+1);
771     strncpyW(tempBuffer,lpszScheme,nMaxCmp);
772     tempBuffer[nMaxCmp]=0;
773     strlwrW(tempBuffer);
774     if (nMaxCmp==strlenW(lpszFtp) && !strncmpW(lpszFtp, tempBuffer, nMaxCmp))
775         iScheme=INTERNET_SCHEME_FTP;
776     else if (nMaxCmp==strlenW(lpszGopher) && !strncmpW(lpszGopher, tempBuffer, nMaxCmp))
777         iScheme=INTERNET_SCHEME_GOPHER;
778     else if (nMaxCmp==strlenW(lpszHttp) && !strncmpW(lpszHttp, tempBuffer, nMaxCmp))
779         iScheme=INTERNET_SCHEME_HTTP;
780     else if (nMaxCmp==strlenW(lpszHttps) && !strncmpW(lpszHttps, tempBuffer, nMaxCmp))
781         iScheme=INTERNET_SCHEME_HTTPS;
782     else if (nMaxCmp==strlenW(lpszFile) && !strncmpW(lpszFile, tempBuffer, nMaxCmp))
783         iScheme=INTERNET_SCHEME_FILE;
784     else if (nMaxCmp==strlenW(lpszNews) && !strncmpW(lpszNews, tempBuffer, nMaxCmp))
785         iScheme=INTERNET_SCHEME_NEWS;
786     else if (nMaxCmp==strlenW(lpszMailto) && !strncmpW(lpszMailto, tempBuffer, nMaxCmp))
787         iScheme=INTERNET_SCHEME_MAILTO;
788     else if (nMaxCmp==strlenW(lpszRes) && !strncmpW(lpszRes, tempBuffer, nMaxCmp))
789         iScheme=INTERNET_SCHEME_RES;
790     free(tempBuffer);
791     return iScheme;
792 }
793
794 /***********************************************************************
795  *           SetUrlComponentValueW (Internal)
796  *
797  * Helper function for InternetCrackUrlW
798  *
799  * RETURNS
800  *    TRUE on success
801  *    FALSE on failure
802  *
803  */
804 BOOL SetUrlComponentValueW(LPWSTR* lppszComponent, LPDWORD dwComponentLen, LPCWSTR lpszStart, INT len)
805 {
806     TRACE("%s (%d)\n", debugstr_wn(lpszStart,len), len);
807
808     if (*dwComponentLen != 0)
809     {
810         if (*lppszComponent == NULL)
811         {
812             *lppszComponent = (LPWSTR)lpszStart;
813             *dwComponentLen = len;
814         }
815         else
816         {
817             INT ncpylen = min((*dwComponentLen)-1, len);
818             strncpyW(*lppszComponent, lpszStart, ncpylen);
819             (*lppszComponent)[ncpylen] = '\0';
820             *dwComponentLen = ncpylen;
821         }
822     }
823
824     return TRUE;
825 }
826
827 /***********************************************************************
828  *           InternetCrackUrlW   (WININET.@)
829  */
830 BOOL WINAPI InternetCrackUrlW(LPCWSTR lpszUrl, DWORD dwUrlLength, DWORD dwFlags,
831                               LPURL_COMPONENTSW lpUC)
832 {
833   /*
834    * RFC 1808
835    * <protocol>:[//<net_loc>][/path][;<params>][?<query>][#<fragment>]
836    *
837    */
838     LPWSTR lpszParam    = NULL;
839     BOOL  bIsAbsolute = FALSE;
840     LPWSTR lpszap = (WCHAR*)lpszUrl;
841     LPWSTR lpszcp = NULL;
842     WCHAR lpszSeparators[3]={';','?',0};
843     WCHAR lpszSlash[2]={'/',0};
844     if(dwUrlLength==0)
845         dwUrlLength=strlenW(lpszUrl);
846
847     TRACE("\n");
848
849     /* Determine if the URI is absolute. */
850     while (*lpszap != '\0')
851     {
852         if (isalnumW(*lpszap))
853         {
854             lpszap++;
855             continue;
856         }
857         if ((*lpszap == ':') && (lpszap - lpszUrl >= 2))
858         {
859             bIsAbsolute = TRUE;
860             lpszcp = lpszap;
861         }
862         else
863         {
864             lpszcp = (LPWSTR)lpszUrl; /* Relative url */
865         }
866
867         break;
868     }
869
870     /* Parse <params> */
871     lpszParam = strpbrkW(lpszap, lpszSeparators);
872     if (lpszParam != NULL)
873     {
874         if (!SetUrlComponentValueW(&lpUC->lpszExtraInfo, &lpUC->dwExtraInfoLength,
875                                    lpszParam, dwUrlLength-(lpszParam-lpszUrl)))
876         {
877             return FALSE;
878         }
879     }
880
881     if (bIsAbsolute) /* Parse <protocol>:[//<net_loc>] */
882     {
883         LPWSTR lpszNetLoc;
884         WCHAR wszAbout[]={'a','b','o','u','t',':',0};
885
886         /* Get scheme first. */
887         lpUC->nScheme = GetInternetSchemeW(lpszUrl, lpszcp - lpszUrl);
888         if (!SetUrlComponentValueW(&lpUC->lpszScheme, &lpUC->dwSchemeLength,
889                                    lpszUrl, lpszcp - lpszUrl))
890             return FALSE;
891
892         /* Eat ':' in protocol. */
893         lpszcp++;
894
895         /* if the scheme is "about", there is no host */
896         if(strncmpW(wszAbout,lpszUrl, lpszcp - lpszUrl)==0)
897         {
898             SetUrlComponentValueW(&lpUC->lpszUserName, &lpUC->dwUserNameLength, NULL, 0);
899             SetUrlComponentValueW(&lpUC->lpszPassword, &lpUC->dwPasswordLength, NULL, 0);
900             SetUrlComponentValueW(&lpUC->lpszHostName, &lpUC->dwHostNameLength, NULL, 0);
901             lpUC->nPort = 0;
902         }
903         else
904         {
905             /* Skip over slashes. */
906             if (*lpszcp == '/')
907             {
908                 lpszcp++;
909                 if (*lpszcp == '/')
910                 {
911                     lpszcp++;
912                     if (*lpszcp == '/')
913                         lpszcp++;
914                 }
915             }
916
917             lpszNetLoc = strpbrkW(lpszcp, lpszSlash);
918             if (lpszParam)
919             {
920                 if (lpszNetLoc)
921                     lpszNetLoc = min(lpszNetLoc, lpszParam);
922                 else
923                     lpszNetLoc = lpszParam;
924             }
925             else if (!lpszNetLoc)
926                 lpszNetLoc = lpszcp + dwUrlLength-(lpszcp-lpszUrl);
927
928             /* Parse net-loc */
929             if (lpszNetLoc)
930             {
931                 LPWSTR lpszHost;
932                 LPWSTR lpszPort;
933
934                 /* [<user>[<:password>]@]<host>[:<port>] */
935                 /* First find the user and password if they exist */
936
937                 lpszHost = strchrW(lpszcp, '@');
938                 if (lpszHost == NULL || lpszHost > lpszNetLoc)
939                 {
940                     /* username and password not specified. */
941                     SetUrlComponentValueW(&lpUC->lpszUserName, &lpUC->dwUserNameLength, NULL, 0);
942                     SetUrlComponentValueW(&lpUC->lpszPassword, &lpUC->dwPasswordLength, NULL, 0);
943                 }
944                 else /* Parse out username and password */
945                 {
946                     LPWSTR lpszUser = lpszcp;
947                     LPWSTR lpszPasswd = lpszHost;
948
949                     while (lpszcp < lpszHost)
950                     {
951                         if (*lpszcp == ':')
952                             lpszPasswd = lpszcp;
953
954                         lpszcp++;
955                     }
956
957                     SetUrlComponentValueW(&lpUC->lpszUserName, &lpUC->dwUserNameLength,
958                                           lpszUser, lpszPasswd - lpszUser);
959
960                     if (lpszPasswd != lpszHost)
961                         lpszPasswd++;
962                     SetUrlComponentValueW(&lpUC->lpszPassword, &lpUC->dwPasswordLength,
963                                           lpszPasswd == lpszHost ? NULL : lpszPasswd,
964                                           lpszHost - lpszPasswd);
965
966                     lpszcp++; /* Advance to beginning of host */
967                 }
968
969                 /* Parse <host><:port> */
970
971                 lpszHost = lpszcp;
972                 lpszPort = lpszNetLoc;
973
974                 /* special case for res:// URLs: there is no port here, so the host is the
975                    entire string up to the first '/' */
976                 if(lpUC->nScheme==INTERNET_SCHEME_RES)
977                 {
978                     SetUrlComponentValueW(&lpUC->lpszHostName, &lpUC->dwHostNameLength,
979                                           lpszHost, lpszPort - lpszHost);
980                     lpUC->nPort = 0;
981                     lpszcp=lpszNetLoc;
982                 }
983                 else
984                 {
985                     while (lpszcp < lpszNetLoc)
986                     {
987                         if (*lpszcp == ':')
988                             lpszPort = lpszcp;
989
990                         lpszcp++;
991                     }
992
993                     /* If the scheme is "file" and the host is just one letter, it's not a host */
994                     if(lpUC->nScheme==INTERNET_SCHEME_FILE && (lpszPort-lpszHost)==1)
995                     {
996                         lpszcp=lpszHost;
997                         SetUrlComponentValueW(&lpUC->lpszHostName, &lpUC->dwHostNameLength,
998                                               NULL, 0);
999                         lpUC->nPort = 0;
1000                     }
1001                     else
1002                     {
1003                         SetUrlComponentValueW(&lpUC->lpszHostName, &lpUC->dwHostNameLength,
1004                                               lpszHost, lpszPort - lpszHost);
1005                         if (lpszPort != lpszNetLoc)
1006                             lpUC->nPort = atoiW(++lpszPort);
1007                         else
1008                             lpUC->nPort = 0;
1009                     }
1010                 }
1011             }
1012         }
1013     }
1014
1015     /* Here lpszcp points to:
1016      *
1017      * <protocol>:[//<net_loc>][/path][;<params>][?<query>][#<fragment>]
1018      *                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1019      */
1020     if (lpszcp != 0 && *lpszcp != '\0' && (!lpszParam || lpszcp < lpszParam))
1021     {
1022         INT len;
1023
1024         /* Only truncate the parameter list if it's already been saved
1025          * in lpUC->lpszExtraInfo.
1026          */
1027         if (lpszParam && lpUC->dwExtraInfoLength)
1028             len = lpszParam - lpszcp;
1029         else
1030         {
1031             /* Leave the parameter list in lpszUrlPath.  Strip off any trailing
1032              * newlines if necessary.
1033              */
1034             LPWSTR lpsznewline = strchrW(lpszcp, '\n');
1035             if (lpsznewline != NULL)
1036                 len = lpsznewline - lpszcp;
1037             else
1038                 len = dwUrlLength-(lpszcp-lpszUrl);
1039         }
1040
1041         if (!SetUrlComponentValueW(&lpUC->lpszUrlPath, &lpUC->dwUrlPathLength,
1042                                    lpszcp, len))
1043             return FALSE;
1044     }
1045     else
1046     {
1047         lpUC->dwUrlPathLength = 0;
1048     }
1049
1050     TRACE("%s: host(%s) path(%s) extra(%s)\n", debugstr_wn(lpszUrl,dwUrlLength),
1051              debugstr_wn(lpUC->lpszHostName,lpUC->dwHostNameLength),
1052              debugstr_wn(lpUC->lpszUrlPath,lpUC->dwUrlPathLength),
1053              debugstr_wn(lpUC->lpszExtraInfo,lpUC->dwExtraInfoLength));
1054
1055     return TRUE;
1056 }
1057
1058 /***********************************************************************
1059  *           InternetAttemptConnect (WININET.@)
1060  *
1061  * Attempt to make a connection to the internet
1062  *
1063  * RETURNS
1064  *    ERROR_SUCCESS on success
1065  *    Error value   on failure
1066  *
1067  */
1068 DWORD WINAPI InternetAttemptConnect(DWORD dwReserved)
1069 {
1070     FIXME("Stub\n");
1071     return ERROR_SUCCESS;
1072 }
1073
1074
1075 /***********************************************************************
1076  *           InternetCanonicalizeUrlA (WININET.@)
1077  *
1078  * Escape unsafe characters and spaces
1079  *
1080  * RETURNS
1081  *    TRUE on success
1082  *    FALSE on failure
1083  *
1084  */
1085 BOOL WINAPI InternetCanonicalizeUrlA(LPCSTR lpszUrl, LPSTR lpszBuffer,
1086         LPDWORD lpdwBufferLength, DWORD dwFlags)
1087 {
1088     HRESULT hr;
1089     TRACE("%s %p %p %08lx\n",debugstr_a(lpszUrl), lpszBuffer,
1090           lpdwBufferLength, dwFlags);
1091
1092     /* Flip this bit to correspond to URL_ESCAPE_UNSAFE */
1093     dwFlags ^= ICU_NO_ENCODE;
1094
1095     dwFlags |= 0x80000000; /* Don't know what this means */
1096
1097     hr = UrlCanonicalizeA(lpszUrl, lpszBuffer, lpdwBufferLength, dwFlags);
1098
1099     return (hr == S_OK) ? TRUE : FALSE;
1100 }
1101
1102 /***********************************************************************
1103  *           InternetCanonicalizeUrlW (WININET.@)
1104  *
1105  * Escape unsafe characters and spaces
1106  *
1107  * RETURNS
1108  *    TRUE on success
1109  *    FALSE on failure
1110  *
1111  */
1112 BOOL WINAPI InternetCanonicalizeUrlW(LPCWSTR lpszUrl, LPWSTR lpszBuffer,
1113     LPDWORD lpdwBufferLength, DWORD dwFlags)
1114 {
1115     HRESULT hr;
1116     TRACE("%s %p %p %08lx\n", debugstr_w(lpszUrl), lpszBuffer,
1117         lpdwBufferLength, dwFlags);
1118
1119     /* Flip this bit to correspond to URL_ESCAPE_UNSAFE */
1120     dwFlags ^= ICU_NO_ENCODE;
1121
1122     dwFlags |= 0x80000000; /* Don't know what this means */
1123
1124     hr = UrlCanonicalizeW(lpszUrl, lpszBuffer, lpdwBufferLength, dwFlags);
1125
1126     return (hr == S_OK) ? TRUE : FALSE;
1127 }
1128
1129
1130 /***********************************************************************
1131  *           InternetSetStatusCallback (WININET.@)
1132  *
1133  * Sets up a callback function which is called as progress is made
1134  * during an operation.
1135  *
1136  * RETURNS
1137  *    Previous callback or NULL         on success
1138  *    INTERNET_INVALID_STATUS_CALLBACK  on failure
1139  *
1140  */
1141 INTERNET_STATUS_CALLBACK WINAPI InternetSetStatusCallback(
1142         HINTERNET hInternet ,INTERNET_STATUS_CALLBACK lpfnIntCB)
1143 {
1144     INTERNET_STATUS_CALLBACK retVal;
1145     LPWININETAPPINFOA lpwai = (LPWININETAPPINFOA)hInternet;
1146
1147     TRACE("0x%08lx\n", (ULONG)hInternet);
1148     if (lpwai->hdr.htype != WH_HINIT)
1149         return INTERNET_INVALID_STATUS_CALLBACK;
1150
1151     retVal = lpwai->lpfnStatusCB;
1152     lpwai->lpfnStatusCB = lpfnIntCB;
1153
1154     return retVal;
1155 }
1156
1157
1158 /***********************************************************************
1159  *           InternetWriteFile (WININET.@)
1160  *
1161  * Write data to an open internet file
1162  *
1163  * RETURNS
1164  *    TRUE  on success
1165  *    FALSE on failure
1166  *
1167  */
1168 BOOL WINAPI InternetWriteFile(HINTERNET hFile, LPCVOID lpBuffer ,
1169         DWORD dwNumOfBytesToWrite, LPDWORD lpdwNumOfBytesWritten)
1170 {
1171     BOOL retval = FALSE;
1172     int nSocket = -1;
1173     LPWININETHANDLEHEADER lpwh = (LPWININETHANDLEHEADER) hFile;
1174
1175     TRACE("\n");
1176     if (NULL == lpwh)
1177         return FALSE;
1178
1179     switch (lpwh->htype)
1180     {
1181         case WH_HHTTPREQ:
1182             nSocket = ((LPWININETHTTPREQA)hFile)->nSocketFD;
1183             break;
1184
1185         case WH_HFILE:
1186             nSocket = ((LPWININETFILE)hFile)->nDataSocket;
1187             break;
1188
1189         default:
1190             break;
1191     }
1192
1193     if (nSocket != -1)
1194     {
1195         int res = send(nSocket, lpBuffer, dwNumOfBytesToWrite, 0);
1196         retval = (res >= 0);
1197         *lpdwNumOfBytesWritten = retval ? res : 0;
1198     }
1199
1200     return retval;
1201 }
1202
1203
1204 /***********************************************************************
1205  *           InternetReadFile (WININET.@)
1206  *
1207  * Read data from an open internet file
1208  *
1209  * RETURNS
1210  *    TRUE  on success
1211  *    FALSE on failure
1212  *
1213  */
1214 BOOL WINAPI InternetReadFile(HINTERNET hFile, LPVOID lpBuffer,
1215         DWORD dwNumOfBytesToRead, LPDWORD dwNumOfBytesRead)
1216 {
1217     BOOL retval = FALSE;
1218     int nSocket = -1;
1219     LPWININETHANDLEHEADER lpwh = (LPWININETHANDLEHEADER) hFile;
1220
1221     TRACE("\n");
1222
1223     if (NULL == lpwh)
1224         return FALSE;
1225
1226     switch (lpwh->htype)
1227     {
1228         case WH_HHTTPREQ:
1229             nSocket = ((LPWININETHTTPREQA)hFile)->nSocketFD;
1230             break;
1231
1232         case WH_HFILE:
1233             nSocket = ((LPWININETFILE)hFile)->nDataSocket;
1234             break;
1235
1236         default:
1237             break;
1238     }
1239
1240     if (nSocket != -1)
1241     {
1242         int res = recv(nSocket, lpBuffer, dwNumOfBytesToRead, 0);
1243         retval = (res >= 0);
1244         *dwNumOfBytesRead = retval ? res : 0;
1245     }
1246     return retval;
1247 }
1248
1249 /***********************************************************************
1250  *           InternetReadFileExA (WININET.@)
1251  *
1252  * Read data from an open internet file
1253  *
1254  * RETURNS
1255  *    TRUE  on success
1256  *    FALSE on failure
1257  *
1258  */
1259 BOOL WINAPI InternetReadFileExA(HINTERNET hFile, LPINTERNET_BUFFERSA lpBuffer,
1260         DWORD dwFlags, DWORD dwContext)
1261 {
1262   FIXME("stub\n");
1263   return FALSE;
1264 }
1265
1266 /***********************************************************************
1267  *           InternetReadFileExW (WININET.@)
1268  *
1269  * Read data from an open internet file
1270  *
1271  * RETURNS
1272  *    TRUE  on success
1273  *    FALSE on failure
1274  *
1275  */
1276 BOOL WINAPI InternetReadFileExW(HINTERNET hFile, LPINTERNET_BUFFERSW lpBuffer,
1277         DWORD dwFlags, DWORD dwContext)
1278 {
1279   FIXME("stub\n");
1280
1281   INTERNET_SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1282   return FALSE;
1283 }
1284
1285 /***********************************************************************
1286  *           INET_QueryOptionHelper (internal)
1287  */
1288 static BOOL INET_QueryOptionHelper(BOOL bIsUnicode, HINTERNET hInternet, DWORD dwOption,
1289                                    LPVOID lpBuffer, LPDWORD lpdwBufferLength)
1290 {
1291     LPWININETHANDLEHEADER lpwhh;
1292     BOOL bSuccess = FALSE;
1293
1294     TRACE("0x%08lx\n", dwOption);
1295
1296     if (NULL == hInternet)
1297     {
1298         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1299         return FALSE;
1300     }
1301
1302     lpwhh = (LPWININETHANDLEHEADER) hInternet;
1303
1304     switch (dwOption)
1305     {
1306         case INTERNET_OPTION_HANDLE_TYPE:
1307         {
1308             ULONG type = lpwhh->htype;
1309             TRACE("INTERNET_OPTION_HANDLE_TYPE: %ld\n", type);
1310
1311             if (*lpdwBufferLength < sizeof(ULONG))
1312                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1313             else
1314             {
1315                 memcpy(lpBuffer, &type, sizeof(ULONG));
1316                     *lpdwBufferLength = sizeof(ULONG);
1317                 bSuccess = TRUE;
1318             }
1319             break;
1320         }
1321
1322         case INTERNET_OPTION_REQUEST_FLAGS:
1323         {
1324             ULONG flags = 4;
1325             TRACE("INTERNET_OPTION_REQUEST_FLAGS: %ld\n", flags);
1326             if (*lpdwBufferLength < sizeof(ULONG))
1327                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1328             else
1329             {
1330                 memcpy(lpBuffer, &flags, sizeof(ULONG));
1331                     *lpdwBufferLength = sizeof(ULONG);
1332                 bSuccess = TRUE;
1333             }
1334             break;
1335         }
1336
1337         case INTERNET_OPTION_URL:
1338         case INTERNET_OPTION_DATAFILE_NAME:
1339         {
1340             ULONG type = lpwhh->htype;
1341             if (type == WH_HHTTPREQ)
1342             {
1343                 LPWININETHTTPREQA lpreq = hInternet;
1344                 char url[1023];
1345
1346                 sprintf(url,"http://%s%s",lpreq->lpszHostName,lpreq->lpszPath);
1347                 TRACE("INTERNET_OPTION_URL: %s\n",url);
1348                 if (*lpdwBufferLength < strlen(url)+1)
1349                     INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1350                 else
1351                 {
1352                     if(bIsUnicode)
1353                     {
1354                         *lpdwBufferLength=MultiByteToWideChar(CP_ACP,0,url,-1,lpBuffer,*lpdwBufferLength);
1355                     }
1356                     else
1357                     {
1358                         memcpy(lpBuffer, url, strlen(url)+1);
1359                         *lpdwBufferLength = strlen(url)+1;
1360                     }
1361                     bSuccess = TRUE;
1362                 }
1363             }
1364             break;
1365         }
1366        case INTERNET_OPTION_HTTP_VERSION:
1367        {
1368             /*
1369              * Presently hardcoded to 1.1
1370              */
1371             ((HTTP_VERSION_INFO*)lpBuffer)->dwMajorVersion = 1;
1372             ((HTTP_VERSION_INFO*)lpBuffer)->dwMinorVersion = 1;
1373             bSuccess = TRUE;
1374         break;
1375        }
1376
1377        default:
1378          FIXME("Stub! %ld \n",dwOption);
1379          break;
1380     }
1381
1382     return bSuccess;
1383 }
1384
1385 /***********************************************************************
1386  *           InternetQueryOptionW (WININET.@)
1387  *
1388  * Queries an options on the specified handle
1389  *
1390  * RETURNS
1391  *    TRUE  on success
1392  *    FALSE on failure
1393  *
1394  */
1395 BOOL WINAPI InternetQueryOptionW(HINTERNET hInternet, DWORD dwOption,
1396                                  LPVOID lpBuffer, LPDWORD lpdwBufferLength)
1397 {
1398     return INET_QueryOptionHelper(TRUE, hInternet, dwOption, lpBuffer, lpdwBufferLength);
1399 }
1400
1401 /***********************************************************************
1402  *           InternetQueryOptionA (WININET.@)
1403  *
1404  * Queries an options on the specified handle
1405  *
1406  * RETURNS
1407  *    TRUE  on success
1408  *    FALSE on failure
1409  *
1410  */
1411 BOOL WINAPI InternetQueryOptionA(HINTERNET hInternet, DWORD dwOption,
1412                                  LPVOID lpBuffer, LPDWORD lpdwBufferLength)
1413 {
1414     return INET_QueryOptionHelper(FALSE, hInternet, dwOption, lpBuffer, lpdwBufferLength);
1415 }
1416
1417
1418 /***********************************************************************
1419  *           InternetSetOptionW (WININET.@)
1420  *
1421  * Sets an options on the specified handle
1422  *
1423  * RETURNS
1424  *    TRUE  on success
1425  *    FALSE on failure
1426  *
1427  */
1428 BOOL WINAPI InternetSetOptionW(HINTERNET hInternet, DWORD dwOption,
1429                            LPVOID lpBuffer, DWORD dwBufferLength)
1430 {
1431     LPWININETHANDLEHEADER lpwhh;
1432
1433     TRACE("0x%08lx\n", dwOption);
1434
1435     if (NULL == hInternet)
1436     {
1437         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1438         return FALSE;
1439     }
1440
1441     lpwhh = (LPWININETHANDLEHEADER) hInternet;
1442
1443     switch (dwOption)
1444     {
1445     case INTERNET_OPTION_HTTP_VERSION:
1446       {
1447         HTTP_VERSION_INFO* pVersion=(HTTP_VERSION_INFO*)lpBuffer;
1448         FIXME("Option INTERNET_OPTION_HTTP_VERSION(%ld,%ld): STUB\n",pVersion->dwMajorVersion,pVersion->dwMinorVersion);
1449       }
1450       break;
1451     case INTERNET_OPTION_ERROR_MASK:
1452       {
1453         unsigned long flags=*(unsigned long*)lpBuffer;
1454         FIXME("Option INTERNET_OPTION_ERROR_MASK(%ld): STUB\n",flags);
1455       }
1456       break;
1457     case INTERNET_OPTION_CODEPAGE:
1458       {
1459         unsigned long codepage=*(unsigned long*)lpBuffer;
1460         FIXME("Option INTERNET_OPTION_CODEPAGE (%ld): STUB\n",codepage);
1461       }
1462       break;
1463     case INTERNET_OPTION_REQUEST_PRIORITY:
1464       {
1465         unsigned long priority=*(unsigned long*)lpBuffer;
1466         FIXME("Option INTERNET_OPTION_REQUEST_PRIORITY (%ld): STUB\n",priority);
1467       }
1468       break;
1469     default:
1470         FIXME("Option %ld STUB\n",dwOption);
1471         INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1472         return FALSE;
1473     }
1474
1475     return TRUE;
1476 }
1477
1478
1479 /***********************************************************************
1480  *           InternetSetOptionA (WININET.@)
1481  *
1482  * Sets an options on the specified handle.
1483  *
1484  * RETURNS
1485  *    TRUE  on success
1486  *    FALSE on failure
1487  *
1488  */
1489 BOOL WINAPI InternetSetOptionA(HINTERNET hInternet, DWORD dwOption,
1490                            LPVOID lpBuffer, DWORD dwBufferLength)
1491 {
1492     /* FIXME!!! implement if lpBuffer is a string, dwBufferLength is
1493        in TCHARs */
1494     return InternetSetOptionW(hInternet,dwOption, lpBuffer,
1495                               dwBufferLength);
1496 }
1497
1498
1499 /***********************************************************************
1500  *           InternetGetCookieA (WININET.@)
1501  *
1502  * Retrieve cookie from the specified url
1503  *
1504  * RETURNS
1505  *    TRUE  on success
1506  *    FALSE on failure
1507  *
1508  */
1509 BOOL WINAPI InternetGetCookieA(LPCSTR lpszUrl, LPCSTR lpszCookieName,
1510     LPSTR lpCookieData, LPDWORD lpdwSize)
1511 {
1512     FIXME("STUB\n");
1513     TRACE("(%s,%s,%p)\n", debugstr_a(lpszUrl),debugstr_a(lpszCookieName),
1514         lpCookieData);
1515     return FALSE;
1516 }
1517
1518
1519 /***********************************************************************
1520  *           InternetGetCookieW (WININET.@)
1521  *
1522  * Retrieve cookie from the specified url
1523  *
1524  * RETURNS
1525  *    TRUE  on success
1526  *    FALSE on failure
1527  *
1528  */
1529 BOOL WINAPI InternetGetCookieW(LPCSTR lpszUrl, LPCWSTR lpszCookieName,
1530     LPWSTR lpCookieData, LPDWORD lpdwSize)
1531 {
1532     FIXME("STUB\n");
1533     TRACE("(%s,%s,%p)\n", debugstr_a(lpszUrl), debugstr_w(lpszCookieName),
1534         lpCookieData);
1535     return FALSE;
1536 }
1537
1538
1539 /***********************************************************************
1540  *           InternetSetCookieA (WININET.@)
1541  *
1542  * Sets cookie for the specified url
1543  *
1544  * RETURNS
1545  *    TRUE  on success
1546  *    FALSE on failure
1547  *
1548  */
1549 BOOL WINAPI InternetSetCookieA(LPCSTR lpszUrl, LPCSTR lpszCookieName,
1550     LPCSTR lpCookieData)
1551 {
1552     FIXME("STUB\n");
1553     TRACE("(%s,%s,%s)\n", debugstr_a(lpszUrl),
1554         debugstr_a(lpszCookieName), debugstr_a(lpCookieData));
1555     return FALSE;
1556 }
1557
1558
1559 /***********************************************************************
1560  *           InternetSetCookieW (WININET.@)
1561  *
1562  * Sets cookie for the specified url
1563  *
1564  * RETURNS
1565  *    TRUE  on success
1566  *    FALSE on failure
1567  *
1568  */
1569 BOOL WINAPI InternetSetCookieW(LPCSTR lpszUrl, LPCWSTR lpszCookieName,
1570     LPCWSTR lpCookieData)
1571 {
1572     FIXME("STUB\n");
1573     TRACE("(%s,%s,%s)\n", debugstr_a(lpszUrl),
1574         debugstr_w(lpszCookieName), debugstr_w(lpCookieData));
1575     return FALSE;
1576 }
1577
1578
1579 /***********************************************************************
1580  *      InternetCheckConnectionA (WININET.@)
1581  *
1582  * Pings a requested host to check internet connection
1583  *
1584  * RETURNS
1585  *   TRUE on success and FALSE on failure. If a failure then
1586  *   ERROR_NOT_CONNECTED is placesd into GetLastError
1587  *
1588  */
1589 BOOL WINAPI InternetCheckConnectionA( LPCSTR lpszUrl, DWORD dwFlags, DWORD dwReserved )
1590 {
1591 /*
1592  * this is a kludge which runs the resident ping program and reads the output.
1593  *
1594  * Anyone have a better idea?
1595  */
1596
1597   BOOL   rc = FALSE;
1598   char command[1024];
1599   char host[1024];
1600   int status = -1;
1601
1602   FIXME("\n");
1603
1604   /*
1605    * Crack or set the Address
1606    */
1607   if (lpszUrl == NULL)
1608   {
1609      /*
1610       * According to the doc we are supost to use the ip for the next
1611       * server in the WnInet internal server database. I have
1612       * no idea what that is or how to get it.
1613       *
1614       * So someone needs to implement this.
1615       */
1616      FIXME("Unimplemented with URL of NULL\n");
1617      return TRUE;
1618   }
1619   else
1620   {
1621      URL_COMPONENTSA componets;
1622
1623      ZeroMemory(&componets,sizeof(URL_COMPONENTSA));
1624      componets.lpszHostName = (LPSTR)&host;
1625      componets.dwHostNameLength = 1024;
1626
1627      if (!InternetCrackUrlA(lpszUrl,0,0,&componets))
1628        goto End;
1629
1630      TRACE("host name : %s\n",componets.lpszHostName);
1631   }
1632
1633   /*
1634    * Build our ping command
1635    */
1636   strcpy(command,"ping -w 1 ");
1637   strcat(command,host);
1638   strcat(command," >/dev/null 2>/dev/null");
1639
1640   TRACE("Ping command is : %s\n",command);
1641
1642   status = system(command);
1643
1644   TRACE("Ping returned a code of %i \n",status);
1645
1646   /* Ping return code of 0 indicates success */
1647   if (status == 0)
1648      rc = TRUE;
1649
1650 End:
1651
1652   if (rc == FALSE)
1653     SetLastError(ERROR_NOT_CONNECTED);
1654
1655   return rc;
1656 }
1657
1658
1659 /***********************************************************************
1660  *      InternetCheckConnectionW (WININET.@)
1661  *
1662  * Pings a requested host to check internet connection
1663  *
1664  * RETURNS
1665  *   TRUE on success and FALSE on failure. If a failure then
1666  *   ERROR_NOT_CONNECTED is placed into GetLastError
1667  *
1668  */
1669 BOOL WINAPI InternetCheckConnectionW(LPCWSTR lpszUrl, DWORD dwFlags, DWORD dwReserved)
1670 {
1671     CHAR *szUrl;
1672     INT len;
1673     BOOL rc;
1674
1675     len = lstrlenW(lpszUrl)+1;
1676     if (!(szUrl = (CHAR *)malloc(len*sizeof(CHAR))))
1677         return FALSE;
1678     WideCharToMultiByte(CP_ACP, -1, lpszUrl, -1, szUrl, len, NULL, NULL);
1679     rc = InternetCheckConnectionA((LPCSTR)szUrl, dwFlags, dwReserved);
1680     free(szUrl);
1681     
1682     return rc;
1683 }
1684
1685
1686 /**********************************************************
1687  *      InternetOpenUrlA (WININET.@)
1688  *
1689  * Opens an URL
1690  *
1691  * RETURNS
1692  *   handle of connection or NULL on failure
1693  */
1694 HINTERNET WINAPI InternetOpenUrlA(HINTERNET hInternet, LPCSTR lpszUrl,
1695     LPCSTR lpszHeaders, DWORD dwHeadersLength, DWORD dwFlags, DWORD dwContext)
1696 {
1697   URL_COMPONENTSA urlComponents;
1698   char protocol[32], hostName[MAXHOSTNAME], userName[1024];
1699   char password[1024], path[2048], extra[1024];
1700   HINTERNET client = NULL, client1 = NULL;
1701   urlComponents.dwStructSize = sizeof(URL_COMPONENTSA);
1702   urlComponents.lpszScheme = protocol;
1703   urlComponents.dwSchemeLength = 32;
1704   urlComponents.lpszHostName = hostName;
1705   urlComponents.dwHostNameLength = MAXHOSTNAME;
1706   urlComponents.lpszUserName = userName;
1707   urlComponents.dwUserNameLength = 1024;
1708   urlComponents.lpszPassword = password;
1709   urlComponents.dwPasswordLength = 1024;
1710   urlComponents.lpszUrlPath = path;
1711   urlComponents.dwUrlPathLength = 2048;
1712   urlComponents.lpszExtraInfo = extra;
1713   urlComponents.dwExtraInfoLength = 1024;
1714   if(!InternetCrackUrlA(lpszUrl, strlen(lpszUrl), 0, &urlComponents))
1715     return NULL;
1716   switch(urlComponents.nScheme) {
1717   case INTERNET_SCHEME_FTP:
1718     if(urlComponents.nPort == 0)
1719       urlComponents.nPort = INTERNET_DEFAULT_FTP_PORT;
1720     client = InternetConnectA(hInternet, hostName, urlComponents.nPort,
1721         userName, password, INTERNET_SERVICE_FTP, dwFlags, dwContext);
1722     return FtpOpenFileA(client, path, GENERIC_READ, dwFlags, dwContext);
1723     break;
1724   case INTERNET_SCHEME_HTTP:
1725   case INTERNET_SCHEME_HTTPS:
1726   {
1727     LPCSTR accept[2] = { "*/*", NULL };
1728     char *hostreq=(char*)malloc(strlen(hostName)+9);
1729     sprintf(hostreq, "Host: %s\r\n", hostName);
1730     if(urlComponents.nPort == 0) {
1731       if(urlComponents.nScheme == INTERNET_SCHEME_HTTP)
1732         urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1733       else
1734         urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
1735     }
1736     client = InternetConnectA(hInternet, hostName, urlComponents.nPort, userName,
1737         password, INTERNET_SERVICE_HTTP, dwFlags, dwContext);
1738     if(client == NULL)
1739       return NULL;
1740     client1 = HttpOpenRequestA(hInternet, NULL, path, NULL, NULL, accept, dwFlags, dwContext);
1741     if(client1 == NULL) {
1742       InternetCloseHandle(client);
1743       return NULL;
1744     }
1745     HttpAddRequestHeadersA(client1, lpszHeaders, dwHeadersLength, HTTP_ADDREQ_FLAG_ADD);
1746     HttpAddRequestHeadersA(client1, hostreq, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
1747     if(!HttpSendRequestA(client1, NULL, 0, NULL, 0)) {
1748       InternetCloseHandle(client1);
1749       InternetCloseHandle(client);
1750       return NULL;
1751     }
1752     return client1;
1753     break;
1754   }
1755   case INTERNET_SCHEME_GOPHER:
1756     /* gopher doesn't seem to be implemented in wine, but it's supposed
1757      * to be supported by InternetOpenUrlA. */
1758   default:
1759     return NULL;
1760   }
1761   if(client != NULL)
1762     InternetCloseHandle(client);
1763 }
1764
1765
1766 /**********************************************************
1767  *      InternetOpenUrlW (WININET.@)
1768  *
1769  * Opens an URL
1770  *
1771  * RETURNS
1772  *   handle of connection or NULL on failure
1773  */
1774 HINTERNET WINAPI InternetOpenUrlW(HINTERNET hInternet, LPCWSTR lpszUrl,
1775     LPCWSTR lpszHeaders, DWORD dwHeadersLength, DWORD dwFlags, DWORD dwContext)
1776 {
1777     HINTERNET rc = (HINTERNET)NULL;
1778
1779     INT lenUrl = lstrlenW(lpszUrl)+1;
1780     INT lenHeaders = lstrlenW(lpszHeaders)+1;
1781     CHAR *szUrl = (CHAR *)malloc(lenUrl*sizeof(CHAR));
1782     CHAR *szHeaders = (CHAR *)malloc(lenHeaders*sizeof(CHAR));
1783
1784     if (!szUrl || !szHeaders)
1785     {
1786         if (szUrl)
1787             free(szUrl);
1788         if (szHeaders)
1789             free(szHeaders);
1790         return (HINTERNET)NULL;
1791     }
1792
1793     WideCharToMultiByte(CP_ACP, -1, lpszUrl, -1, szUrl, lenUrl,
1794         NULL, NULL);
1795     WideCharToMultiByte(CP_ACP, -1, lpszHeaders, -1, szHeaders, lenHeaders,
1796         NULL, NULL);
1797
1798     rc = InternetOpenUrlA(hInternet, szUrl, szHeaders,
1799         dwHeadersLength, dwFlags, dwContext);
1800
1801     free(szUrl);
1802     free(szHeaders);
1803
1804     return rc;
1805 }
1806
1807
1808 /***********************************************************************
1809  *           INTERNET_SetLastError (internal)
1810  *
1811  * Set last thread specific error
1812  *
1813  * RETURNS
1814  *
1815  */
1816 void INTERNET_SetLastError(DWORD dwError)
1817 {
1818     LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);
1819
1820     SetLastError(dwError);
1821     if(lpwite)
1822         lpwite->dwError = dwError;
1823 }
1824
1825
1826 /***********************************************************************
1827  *           INTERNET_GetLastError (internal)
1828  *
1829  * Get last thread specific error
1830  *
1831  * RETURNS
1832  *
1833  */
1834 DWORD INTERNET_GetLastError()
1835 {
1836     LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);
1837     return lpwite->dwError;
1838 }
1839
1840
1841 /***********************************************************************
1842  *           INTERNET_WorkerThreadFunc (internal)
1843  *
1844  * Worker thread execution function
1845  *
1846  * RETURNS
1847  *
1848  */
1849 DWORD INTERNET_WorkerThreadFunc(LPVOID *lpvParam)
1850 {
1851     DWORD dwWaitRes;
1852
1853     while (1)
1854     {
1855         if(dwNumJobs > 0) {
1856             INTERNET_ExecuteWork();
1857             continue;
1858         }
1859         dwWaitRes = WaitForMultipleObjects(2, hEventArray, FALSE, MAX_IDLE_WORKER);
1860
1861         if (dwWaitRes == WAIT_OBJECT_0 + 1)
1862             INTERNET_ExecuteWork();
1863         else
1864             break;
1865
1866         InterlockedIncrement(&dwNumIdleThreads);
1867     }
1868
1869     InterlockedDecrement(&dwNumIdleThreads);
1870     InterlockedDecrement(&dwNumThreads);
1871     TRACE("Worker thread exiting\n");
1872     return TRUE;
1873 }
1874
1875
1876 /***********************************************************************
1877  *           INTERNET_InsertWorkRequest (internal)
1878  *
1879  * Insert work request into queue
1880  *
1881  * RETURNS
1882  *
1883  */
1884 BOOL INTERNET_InsertWorkRequest(LPWORKREQUEST lpWorkRequest)
1885 {
1886     BOOL bSuccess = FALSE;
1887     LPWORKREQUEST lpNewRequest;
1888
1889     TRACE("\n");
1890
1891     lpNewRequest = HeapAlloc(GetProcessHeap(), 0, sizeof(WORKREQUEST));
1892     if (lpNewRequest)
1893     {
1894         memcpy(lpNewRequest, lpWorkRequest, sizeof(WORKREQUEST));
1895         lpNewRequest->prev = NULL;
1896
1897         EnterCriticalSection(&csQueue);
1898
1899         lpNewRequest->next = lpWorkQueueTail;
1900         if (lpWorkQueueTail)
1901             lpWorkQueueTail->prev = lpNewRequest;
1902         lpWorkQueueTail = lpNewRequest;
1903         if (!lpHeadWorkQueue)
1904             lpHeadWorkQueue = lpWorkQueueTail;
1905
1906         LeaveCriticalSection(&csQueue);
1907
1908         bSuccess = TRUE;
1909         InterlockedIncrement(&dwNumJobs);
1910     }
1911
1912     return bSuccess;
1913 }
1914
1915
1916 /***********************************************************************
1917  *           INTERNET_GetWorkRequest (internal)
1918  *
1919  * Retrieves work request from queue
1920  *
1921  * RETURNS
1922  *
1923  */
1924 BOOL INTERNET_GetWorkRequest(LPWORKREQUEST lpWorkRequest)
1925 {
1926     BOOL bSuccess = FALSE;
1927     LPWORKREQUEST lpRequest = NULL;
1928
1929     TRACE("\n");
1930
1931     EnterCriticalSection(&csQueue);
1932
1933     if (lpHeadWorkQueue)
1934     {
1935         lpRequest = lpHeadWorkQueue;
1936         lpHeadWorkQueue = lpHeadWorkQueue->prev;
1937         if (lpRequest == lpWorkQueueTail)
1938             lpWorkQueueTail = lpHeadWorkQueue;
1939     }
1940
1941     LeaveCriticalSection(&csQueue);
1942
1943     if (lpRequest)
1944     {
1945         memcpy(lpWorkRequest, lpRequest, sizeof(WORKREQUEST));
1946         HeapFree(GetProcessHeap(), 0, lpRequest);
1947         bSuccess = TRUE;
1948         InterlockedDecrement(&dwNumJobs);
1949     }
1950
1951     return bSuccess;
1952 }
1953
1954
1955 /***********************************************************************
1956  *           INTERNET_AsyncCall (internal)
1957  *
1958  * Retrieves work request from queue
1959  *
1960  * RETURNS
1961  *
1962  */
1963 BOOL INTERNET_AsyncCall(LPWORKREQUEST lpWorkRequest)
1964 {
1965     HANDLE hThread;
1966     DWORD dwTID;
1967     BOOL bSuccess = FALSE;
1968
1969     TRACE("\n");
1970
1971     if (InterlockedDecrement(&dwNumIdleThreads) < 0)
1972     {
1973         InterlockedIncrement(&dwNumIdleThreads);
1974
1975         if (InterlockedIncrement(&dwNumThreads) > MAX_WORKER_THREADS ||
1976             !(hThread = CreateThread(NULL, 0,
1977             (LPTHREAD_START_ROUTINE)INTERNET_WorkerThreadFunc, NULL, 0, &dwTID)))
1978         {
1979             InterlockedDecrement(&dwNumThreads);
1980             INTERNET_SetLastError(ERROR_INTERNET_ASYNC_THREAD_FAILED);
1981             goto lerror;
1982         }
1983
1984         TRACE("Created new thread\n");
1985     }
1986
1987     bSuccess = TRUE;
1988     INTERNET_InsertWorkRequest(lpWorkRequest);
1989     SetEvent(hWorkEvent);
1990
1991 lerror:
1992
1993     return bSuccess;
1994 }
1995
1996
1997 /***********************************************************************
1998  *           INTERNET_ExecuteWork (internal)
1999  *
2000  * RETURNS
2001  *
2002  */
2003 VOID INTERNET_ExecuteWork()
2004 {
2005     WORKREQUEST workRequest;
2006
2007     TRACE("\n");
2008
2009     if (INTERNET_GetWorkRequest(&workRequest))
2010     {
2011         TRACE("Got work %d\n", workRequest.asyncall);
2012         switch (workRequest.asyncall)
2013         {
2014             case FTPPUTFILEA:
2015                 FTP_FtpPutFileA((HINTERNET)workRequest.HFTPSESSION, (LPCSTR)workRequest.LPSZLOCALFILE,
2016                     (LPCSTR)workRequest.LPSZNEWREMOTEFILE, workRequest.DWFLAGS, workRequest.DWCONTEXT);
2017                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZLOCALFILE);
2018                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZNEWREMOTEFILE);
2019                 break;
2020
2021             case FTPSETCURRENTDIRECTORYA:
2022                 FTP_FtpSetCurrentDirectoryA((HINTERNET)workRequest.HFTPSESSION,
2023                         (LPCSTR)workRequest.LPSZDIRECTORY);
2024                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZDIRECTORY);
2025                 break;
2026
2027             case FTPCREATEDIRECTORYA:
2028                 FTP_FtpCreateDirectoryA((HINTERNET)workRequest.HFTPSESSION,
2029                         (LPCSTR)workRequest.LPSZDIRECTORY);
2030                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZDIRECTORY);
2031                 break;
2032
2033             case FTPFINDFIRSTFILEA:
2034                 FTP_FtpFindFirstFileA((HINTERNET)workRequest.HFTPSESSION,
2035                         (LPCSTR)workRequest.LPSZSEARCHFILE,
2036                    (LPWIN32_FIND_DATAA)workRequest.LPFINDFILEDATA, workRequest.DWFLAGS,
2037                    workRequest.DWCONTEXT);
2038                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZSEARCHFILE);
2039                 break;
2040
2041             case FTPGETCURRENTDIRECTORYA:
2042                 FTP_FtpGetCurrentDirectoryA((HINTERNET)workRequest.HFTPSESSION,
2043                         (LPSTR)workRequest.LPSZDIRECTORY, (LPDWORD)workRequest.LPDWDIRECTORY);
2044                 break;
2045
2046             case FTPOPENFILEA:
2047                  FTP_FtpOpenFileA((HINTERNET)workRequest.HFTPSESSION,
2048                     (LPCSTR)workRequest.LPSZFILENAME,
2049                     workRequest.FDWACCESS,
2050                     workRequest.DWFLAGS,
2051                     workRequest.DWCONTEXT);
2052                  HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZFILENAME);
2053                  break;
2054
2055             case FTPGETFILEA:
2056                 FTP_FtpGetFileA((HINTERNET)workRequest.HFTPSESSION,
2057                     (LPCSTR)workRequest.LPSZREMOTEFILE,
2058                     (LPCSTR)workRequest.LPSZNEWFILE,
2059                     (BOOL)workRequest.FFAILIFEXISTS,
2060                     workRequest.DWLOCALFLAGSATTRIBUTE,
2061                     workRequest.DWFLAGS,
2062                     workRequest.DWCONTEXT);
2063                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZREMOTEFILE);
2064                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZNEWFILE);
2065                 break;
2066
2067             case FTPDELETEFILEA:
2068                 FTP_FtpDeleteFileA((HINTERNET)workRequest.HFTPSESSION,
2069                         (LPCSTR)workRequest.LPSZFILENAME);
2070                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZFILENAME);
2071                 break;
2072
2073             case FTPREMOVEDIRECTORYA:
2074                 FTP_FtpRemoveDirectoryA((HINTERNET)workRequest.HFTPSESSION,
2075                         (LPCSTR)workRequest.LPSZDIRECTORY);
2076                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZDIRECTORY);
2077                 break;
2078
2079             case FTPRENAMEFILEA:
2080                 FTP_FtpRenameFileA((HINTERNET)workRequest.HFTPSESSION,
2081                         (LPCSTR)workRequest.LPSZSRCFILE,
2082                         (LPCSTR)workRequest.LPSZDESTFILE);
2083                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZSRCFILE);
2084                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZDESTFILE);
2085                 break;
2086
2087             case INTERNETFINDNEXTA:
2088                 INTERNET_FindNextFileA((HINTERNET)workRequest.HFTPSESSION,
2089                     (LPWIN32_FIND_DATAA)workRequest.LPFINDFILEDATA);
2090                 break;
2091
2092             case HTTPSENDREQUESTA:
2093                HTTP_HttpSendRequestA((HINTERNET)workRequest.HFTPSESSION,
2094                        (LPCSTR)workRequest.LPSZHEADER,
2095                        workRequest.DWHEADERLENGTH,
2096                        (LPVOID)workRequest.LPOPTIONAL,
2097                        workRequest.DWOPTIONALLENGTH);
2098                HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZHEADER);
2099                break;
2100
2101             case HTTPOPENREQUESTA:
2102                HTTP_HttpOpenRequestA((HINTERNET)workRequest.HFTPSESSION,
2103                        (LPCSTR)workRequest.LPSZVERB,
2104                        (LPCSTR)workRequest.LPSZOBJECTNAME,
2105                        (LPCSTR)workRequest.LPSZVERSION,
2106                        (LPCSTR)workRequest.LPSZREFERRER,
2107                        (LPCSTR*)workRequest.LPSZACCEPTTYPES,
2108                        workRequest.DWFLAGS,
2109                        workRequest.DWCONTEXT);
2110                HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZVERB);
2111                HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZOBJECTNAME);
2112                HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZVERSION);
2113                HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZREFERRER);
2114                 break;
2115
2116             case SENDCALLBACK:
2117                SendAsyncCallbackInt((LPWININETAPPINFOA)workRequest.param1,
2118                        (HINTERNET)workRequest.param2, workRequest.param3,
2119                         workRequest.param4, (LPVOID)workRequest.param5,
2120                         workRequest.param6);
2121                break;
2122         }
2123     }
2124 }
2125
2126
2127 /***********************************************************************
2128  *          INTERNET_GetResponseBuffer
2129  *
2130  * RETURNS
2131  *
2132  */
2133 LPSTR INTERNET_GetResponseBuffer()
2134 {
2135     LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);
2136     TRACE("\n");
2137     return lpwite->response;
2138 }
2139
2140
2141 /***********************************************************************
2142  *           INTERNET_GetNextLine  (internal)
2143  *
2144  * Parse next line in directory string listing
2145  *
2146  * RETURNS
2147  *   Pointer to beginning of next line
2148  *   NULL on failure
2149  *
2150  */
2151
2152 LPSTR INTERNET_GetNextLine(INT nSocket, LPSTR lpszBuffer, LPDWORD dwBuffer)
2153 {
2154     struct timeval tv;
2155     fd_set infd;
2156     BOOL bSuccess = FALSE;
2157     INT nRecv = 0;
2158
2159     TRACE("\n");
2160
2161     FD_ZERO(&infd);
2162     FD_SET(nSocket, &infd);
2163     tv.tv_sec=RESPONSE_TIMEOUT;
2164     tv.tv_usec=0;
2165
2166     while (nRecv < *dwBuffer)
2167     {
2168         if (select(nSocket+1,&infd,NULL,NULL,&tv) > 0)
2169         {
2170             if (recv(nSocket, &lpszBuffer[nRecv], 1, 0) <= 0)
2171             {
2172                 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
2173                 goto lend;
2174             }
2175
2176             if (lpszBuffer[nRecv] == '\n')
2177             {
2178                 bSuccess = TRUE;
2179                 break;
2180             }
2181             if (lpszBuffer[nRecv] != '\r')
2182                 nRecv++;
2183         }
2184         else
2185         {
2186             INTERNET_SetLastError(ERROR_INTERNET_TIMEOUT);
2187             goto lend;
2188         }
2189     }
2190
2191 lend:
2192     if (bSuccess)
2193     {
2194         lpszBuffer[nRecv] = '\0';
2195         *dwBuffer = nRecv - 1;
2196         TRACE(":%d %s\n", nRecv, lpszBuffer);
2197         return lpszBuffer;
2198     }
2199     else
2200     {
2201         return NULL;
2202     }
2203 }
2204
2205 /***********************************************************************
2206  *
2207  */
2208 BOOL WINAPI InternetQueryDataAvailable( HINTERNET hFile,
2209                                 LPDWORD lpdwNumberOfBytesAvailble,
2210                                 DWORD dwFlags, DWORD dwConext)
2211 {
2212     LPWININETHTTPREQA lpwhr = (LPWININETHTTPREQA) hFile;
2213     INT retval = -1;
2214     int nSocket = -1;
2215
2216
2217     if (NULL == lpwhr)
2218     {
2219         SetLastError(ERROR_NO_MORE_FILES);
2220         return FALSE;
2221     }
2222
2223     TRACE("-->  %p %i %i\n",lpwhr,lpwhr->hdr.htype,lpwhr->nSocketFD);
2224
2225     switch (lpwhr->hdr.htype)
2226     {
2227         case WH_HHTTPREQ:
2228             nSocket = lpwhr->nSocketFD;
2229             break;
2230
2231         default:
2232             break;
2233     }
2234
2235     if (nSocket != -1)
2236     {
2237         char buffer[4048];
2238
2239         retval = recv(nSocket,buffer,4048,MSG_PEEK);
2240     }
2241     else
2242     {
2243         SetLastError(ERROR_NO_MORE_FILES);
2244     }
2245
2246     if (lpdwNumberOfBytesAvailble)
2247     {
2248         (*lpdwNumberOfBytesAvailble) = retval;
2249     }
2250
2251     TRACE("<-- %i\n",retval);
2252     return (retval+1);
2253 }
2254
2255
2256 /***********************************************************************
2257  *
2258  */
2259 BOOL WINAPI InternetLockRequestFile( HINTERNET hInternet, HANDLE
2260 *lphLockReqHandle)
2261 {
2262     FIXME("STUB\n");
2263     return FALSE;
2264 }
2265
2266 BOOL WINAPI InternetUnlockRequestFile( HANDLE hLockHandle)
2267 {
2268     FIXME("STUB\n");
2269     return FALSE;
2270 }
2271
2272
2273 /***********************************************************************
2274  *           InternetAutoDial
2275  *
2276  * On windows this function is supposed to dial the default internet
2277  * connection. We don't want to have Wine dial out to the internet so
2278  * we return TRUE by default. It might be nice to check if we are connected.
2279  *
2280  * RETURNS
2281  *   TRUE on success
2282  *   FALSE on failure
2283  *
2284  */
2285 BOOL WINAPI InternetAutoDial(DWORD dwFlags, HWND hwndParent)
2286 {
2287     FIXME("STUB\n");
2288
2289     /* Tell that we are connected to the internet. */
2290     return TRUE;
2291 }
2292
2293 /***********************************************************************
2294  *           InternetAutoDialHangup
2295  *
2296  * Hangs up an connection made with InternetAutoDial
2297  *
2298  * PARAM
2299  *    dwReserved
2300  * RETURNS
2301  *   TRUE on success
2302  *   FALSE on failure
2303  *
2304  */
2305 BOOL WINAPI InternetAutodialHangup(DWORD dwReserved)
2306 {
2307     FIXME("STUB\n");
2308
2309     /* we didn't dial, we don't disconnect */
2310     return TRUE;
2311 }
2312
2313 /***********************************************************************
2314  *
2315  *         InternetCombineUrlA
2316  *
2317  * Combine a base URL with a relative URL
2318  *
2319  * RETURNS
2320  *   TRUE on success
2321  *   FALSE on failure
2322  *
2323  */
2324
2325 BOOL WINAPI InternetCombineUrlA(LPCSTR lpszBaseUrl, LPCSTR lpszRelativeUrl,
2326                                 LPSTR lpszBuffer, LPDWORD lpdwBufferLength,
2327                                 DWORD dwFlags)
2328 {
2329     HRESULT hr=S_OK;
2330     /* Flip this bit to correspond to URL_ESCAPE_UNSAFE */
2331     dwFlags ^= ICU_NO_ENCODE;
2332     hr=UrlCombineA(lpszBaseUrl,lpszRelativeUrl,lpszBuffer,lpdwBufferLength,dwFlags);
2333
2334     return (hr==S_OK);
2335 }
2336
2337 /***********************************************************************
2338  *
2339  *         InternetCombineUrlW
2340  *
2341  * Combine a base URL with a relative URL
2342  *
2343  * RETURNS
2344  *   TRUE on success
2345  *   FALSE on failure
2346  *
2347  */
2348
2349 BOOL WINAPI InternetCombineUrlW(LPCWSTR lpszBaseUrl, LPCWSTR lpszRelativeUrl,
2350                                 LPWSTR lpszBuffer, LPDWORD lpdwBufferLength,
2351                                 DWORD dwFlags)
2352 {
2353     HRESULT hr=S_OK;
2354     /* Flip this bit to correspond to URL_ESCAPE_UNSAFE */
2355     dwFlags ^= ICU_NO_ENCODE;
2356     hr=UrlCombineW(lpszBaseUrl,lpszRelativeUrl,lpszBuffer,lpdwBufferLength,dwFlags);
2357
2358     return (hr==S_OK);
2359 }