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