Fixed warnings caused by conversion to -DSTRICT.
[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  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  */
24
25 #include "config.h"
26
27 #define MAXHOSTNAME 100 /* from http.c */
28
29 #include <string.h>
30 #include <stdio.h>
31 #include <sys/types.h>
32 #ifdef HAVE_SYS_SOCKET_H
33 # include <sys/socket.h>
34 #endif
35 #ifdef HAVE_SYS_TIME_H
36 # include <sys/time.h>
37 #endif
38 #include <stdlib.h>
39 #include <ctype.h>
40 #ifdef HAVE_UNISTD_H
41 # include <unistd.h>
42 #endif
43
44 #include "windef.h"
45 #include "winbase.h"
46 #include "winreg.h"
47 #include "wininet.h"
48 #include "wine/debug.h"
49 #include "winerror.h"
50 #define NO_SHLWAPI_STREAM
51 #include "shlwapi.h"
52
53 #include "wine/exception.h"
54 #include "msvcrt/excpt.h"
55
56 #include "internet.h"
57
58 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
59
60 #define MAX_IDLE_WORKER 1000*60*1
61 #define MAX_WORKER_THREADS 10
62 #define RESPONSE_TIMEOUT        30
63
64 #define GET_HWININET_FROM_LPWININETFINDNEXT(lpwh) \
65 (LPWININETAPPINFOA)(((LPWININETFTPSESSIONA)(lpwh->hdr.lpwhparent))->hdr.lpwhparent)
66
67 /* filter for page-fault exceptions */
68 static WINE_EXCEPTION_FILTER(page_fault)
69 {
70     if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ||
71         GetExceptionCode() == EXCEPTION_PRIV_INSTRUCTION)
72         return EXCEPTION_EXECUTE_HANDLER;
73     return EXCEPTION_CONTINUE_SEARCH;
74 }
75
76 typedef struct
77 {
78     DWORD  dwError;
79     CHAR   response[MAX_REPLY_LEN];
80 } WITHREADERROR, *LPWITHREADERROR;
81
82 INTERNET_SCHEME GetInternetScheme(LPCSTR lpszScheme, INT nMaxCmp);
83 BOOL WINAPI INTERNET_FindNextFileA(HINTERNET hFind, LPVOID lpvFindData);
84 VOID INTERNET_ExecuteWork();
85
86 DWORD g_dwTlsErrIndex = TLS_OUT_OF_INDEXES;
87 DWORD dwNumThreads;
88 DWORD dwNumIdleThreads;
89 HANDLE hEventArray[2];
90 #define hQuitEvent hEventArray[0]
91 #define hWorkEvent hEventArray[1]
92 CRITICAL_SECTION csQueue;
93 LPWORKREQUEST lpHeadWorkQueue;
94 LPWORKREQUEST lpWorkQueueTail;
95
96 /***********************************************************************
97  * WININET_LibMain [Internal] Initializes the internal 'WININET.DLL'.
98  *
99  * PARAMS
100  *     hinstDLL    [I] handle to the DLL's instance
101  *     fdwReason   [I]
102  *     lpvReserved [I] reserved, must be NULL
103  *
104  * RETURNS
105  *     Success: TRUE
106  *     Failure: FALSE
107  */
108
109 BOOL WINAPI
110 WININET_LibMain (HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
111 {
112     TRACE("%p,%lx,%p\n", hinstDLL, fdwReason, lpvReserved);
113
114     switch (fdwReason) {
115         case DLL_PROCESS_ATTACH:
116
117             g_dwTlsErrIndex = TlsAlloc();
118
119             if (g_dwTlsErrIndex == TLS_OUT_OF_INDEXES)
120                 return FALSE;
121
122             hQuitEvent = CreateEventA(0, TRUE, FALSE, NULL);
123             hWorkEvent = CreateEventA(0, FALSE, FALSE, NULL);
124             InitializeCriticalSection(&csQueue);
125
126             dwNumThreads = 0;
127             dwNumIdleThreads = 0;
128
129         case DLL_THREAD_ATTACH:
130             {
131                 LPWITHREADERROR lpwite = HeapAlloc(GetProcessHeap(), 0, sizeof(WITHREADERROR));
132                 if (NULL == lpwite)
133                     return FALSE;
134
135                 TlsSetValue(g_dwTlsErrIndex, (LPVOID)lpwite);
136             }
137             break;
138
139         case DLL_THREAD_DETACH:
140             if (g_dwTlsErrIndex != TLS_OUT_OF_INDEXES)
141                         {
142                                 LPVOID lpwite = TlsGetValue(g_dwTlsErrIndex);
143                                 if (lpwite)
144                    HeapFree(GetProcessHeap(), 0, lpwite);
145                         }
146             break;
147
148         case DLL_PROCESS_DETACH:
149
150             if (g_dwTlsErrIndex != TLS_OUT_OF_INDEXES)
151             {
152                 HeapFree(GetProcessHeap(), 0, TlsGetValue(g_dwTlsErrIndex));
153                 TlsFree(g_dwTlsErrIndex);
154             }
155
156             SetEvent(hQuitEvent);
157
158             CloseHandle(hQuitEvent);
159             CloseHandle(hWorkEvent);
160             DeleteCriticalSection(&csQueue);
161             break;
162     }
163
164     return TRUE;
165 }
166
167
168 /***********************************************************************
169  *           InternetOpenA   (WININET.@)
170  *
171  * Per-application initialization of wininet
172  *
173  * RETURNS
174  *    HINTERNET on success
175  *    NULL on failure
176  *
177  */
178 HINTERNET WINAPI InternetOpenA(LPCSTR lpszAgent,
179         DWORD dwAccessType, LPCSTR lpszProxy,
180         LPCSTR lpszProxyBypass, DWORD dwFlags)
181 {
182     LPWININETAPPINFOA lpwai = NULL;
183
184     TRACE("\n");
185
186     /* Clear any error information */
187     INTERNET_SetLastError(0);
188
189     lpwai = HeapAlloc(GetProcessHeap(), 0, sizeof(WININETAPPINFOA));
190     if (NULL == lpwai)
191         INTERNET_SetLastError(ERROR_OUTOFMEMORY);
192     else
193     {
194         memset(lpwai, 0, sizeof(WININETAPPINFOA));
195         lpwai->hdr.htype = WH_HINIT;
196         lpwai->hdr.lpwhparent = NULL;
197         lpwai->hdr.dwFlags = dwFlags;
198         if (NULL != lpszAgent)
199         {
200             if ((lpwai->lpszAgent = HeapAlloc( GetProcessHeap(),0,strlen(lpszAgent)+1)))
201                 strcpy( lpwai->lpszAgent, lpszAgent );
202         }
203         if (NULL != lpszProxy)
204         {
205             if ((lpwai->lpszProxy = HeapAlloc( GetProcessHeap(), 0, strlen(lpszProxy)+1 )))
206                 strcpy( lpwai->lpszProxy, lpszProxy );
207         }
208         if (NULL != lpszProxyBypass)
209         {
210             if ((lpwai->lpszProxyBypass = HeapAlloc( GetProcessHeap(), 0, strlen(lpszProxyBypass)+1)))
211                 strcpy( lpwai->lpszProxyBypass, lpszProxyBypass );
212         }
213         lpwai->dwAccessType = dwAccessType;
214     }
215
216     return (HINTERNET)lpwai;
217 }
218
219
220 /***********************************************************************
221  *           InternetGetLastResponseInfoA (WININET.@)
222  *
223  * Return last wininet error description on the calling thread
224  *
225  * RETURNS
226  *    TRUE on success of writting to buffer
227  *    FALSE on failure
228  *
229  */
230 BOOL WINAPI InternetGetLastResponseInfoA(LPDWORD lpdwError,
231     LPSTR lpszBuffer, LPDWORD lpdwBufferLength)
232 {
233     LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);
234
235     TRACE("\n");
236
237     *lpdwError = lpwite->dwError;
238     if (lpwite->dwError)
239     {
240         strncpy(lpszBuffer, lpwite->response, *lpdwBufferLength);
241         *lpdwBufferLength = strlen(lpszBuffer);
242     }
243     else
244         *lpdwBufferLength = 0;
245
246     return TRUE;
247 }
248
249
250 /***********************************************************************
251  *           InternetGetConnectedState (WININET.@)
252  *
253  * Return connected state
254  *
255  * RETURNS
256  *    TRUE if connected
257  *    if lpdwStatus is not null, return the status (off line,
258  *    modem, lan...) in it.
259  *    FALSE if not connected
260  */
261 BOOL WINAPI InternetGetConnectedState(LPDWORD lpdwStatus, DWORD dwReserved)
262 {
263     if (lpdwStatus) {
264         FIXME("always returning LAN connection.\n");
265         *lpdwStatus = INTERNET_CONNECTION_LAN;
266     }
267     return TRUE;
268 }
269
270
271 /***********************************************************************
272  *           InternetConnectA (WININET.@)
273  *
274  * Open a ftp, gopher or http session
275  *
276  * RETURNS
277  *    HINTERNET a session handle on success
278  *    NULL on failure
279  *
280  */
281 HINTERNET WINAPI InternetConnectA(HINTERNET hInternet,
282     LPCSTR lpszServerName, INTERNET_PORT nServerPort,
283     LPCSTR lpszUserName, LPCSTR lpszPassword,
284     DWORD dwService, DWORD dwFlags, DWORD dwContext)
285 {
286     HINTERNET rc = (HINTERNET) NULL;
287
288     TRACE("ServerPort %i\n",nServerPort);
289
290     /* Clear any error information */
291     INTERNET_SetLastError(0);
292
293     switch (dwService)
294     {
295         case INTERNET_SERVICE_FTP:
296             rc = FTP_Connect(hInternet, lpszServerName, nServerPort,
297             lpszUserName, lpszPassword, dwFlags, dwContext);
298             break;
299
300         case INTERNET_SERVICE_HTTP:
301             rc = HTTP_Connect(hInternet, lpszServerName, nServerPort,
302             lpszUserName, lpszPassword, dwFlags, dwContext);
303             break;
304
305         case INTERNET_SERVICE_GOPHER:
306         default:
307             break;
308     }
309
310     return rc;
311 }
312
313 /***********************************************************************
314  *           InternetFindNextFileA (WININET.@)
315  *
316  * Continues a file search from a previous call to FindFirstFile
317  *
318  * RETURNS
319  *    TRUE on success
320  *    FALSE on failure
321  *
322  */
323 BOOL WINAPI InternetFindNextFileA(HINTERNET hFind, LPVOID lpvFindData)
324 {
325     LPWININETAPPINFOA hIC = NULL;
326     LPWININETFINDNEXTA lpwh = (LPWININETFINDNEXTA) hFind;
327
328     TRACE("\n");
329
330     if (NULL == lpwh || lpwh->hdr.htype != WH_HFINDNEXT)
331     {
332         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
333         return FALSE;
334     }
335
336     hIC = GET_HWININET_FROM_LPWININETFINDNEXT(lpwh);
337     if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
338     {
339         WORKREQUEST workRequest;
340
341         workRequest.asyncall = INTERNETFINDNEXTA;
342         workRequest.HFTPSESSION = (DWORD)hFind;
343         workRequest.LPFINDFILEDATA = (DWORD)lpvFindData;
344
345         return INTERNET_AsyncCall(&workRequest);
346     }
347     else
348     {
349         return INTERNET_FindNextFileA(hFind, lpvFindData);
350     }
351 }
352
353 /***********************************************************************
354  *           INTERNET_FindNextFileA (Internal)
355  *
356  * Continues a file search from a previous call to FindFirstFile
357  *
358  * RETURNS
359  *    TRUE on success
360  *    FALSE on failure
361  *
362  */
363 BOOL WINAPI INTERNET_FindNextFileA(HINTERNET hFind, LPVOID lpvFindData)
364 {
365     BOOL bSuccess = TRUE;
366     LPWININETAPPINFOA hIC = NULL;
367     LPWIN32_FIND_DATAA lpFindFileData;
368     LPWININETFINDNEXTA lpwh = (LPWININETFINDNEXTA) hFind;
369
370     TRACE("\n");
371
372     if (NULL == lpwh || lpwh->hdr.htype != WH_HFINDNEXT)
373     {
374         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
375         return FALSE;
376     }
377
378     /* Clear any error information */
379     INTERNET_SetLastError(0);
380
381     if (lpwh->hdr.lpwhparent->htype != WH_HFTPSESSION)
382     {
383         FIXME("Only FTP find next supported\n");
384         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
385         return FALSE;
386     }
387
388     TRACE("index(%d) size(%ld)\n", lpwh->index, lpwh->size);
389
390     lpFindFileData = (LPWIN32_FIND_DATAA) lpvFindData;
391     ZeroMemory(lpFindFileData, sizeof(WIN32_FIND_DATAA));
392
393     if (lpwh->index >= lpwh->size)
394     {
395         INTERNET_SetLastError(ERROR_NO_MORE_FILES);
396         bSuccess = FALSE;
397         goto lend;
398     }
399
400     FTP_ConvertFileProp(&lpwh->lpafp[lpwh->index], lpFindFileData);
401     lpwh->index++;
402
403     TRACE("\nName: %s\nSize: %ld\n", lpFindFileData->cFileName, lpFindFileData->nFileSizeLow);
404
405 lend:
406
407     hIC = GET_HWININET_FROM_LPWININETFINDNEXT(lpwh);
408     if (hIC->lpfnStatusCB)
409     {
410         INTERNET_ASYNC_RESULT iar;
411
412         iar.dwResult = (DWORD)bSuccess;
413         iar.dwError = iar.dwError = bSuccess ? ERROR_SUCCESS :
414                                                INTERNET_GetLastError();
415
416         SendAsyncCallback(hIC, hFind, lpwh->hdr.dwContext,
417                       INTERNET_STATUS_REQUEST_COMPLETE, &iar,
418                        sizeof(INTERNET_ASYNC_RESULT));
419     }
420
421     return bSuccess;
422 }
423
424
425 /***********************************************************************
426  *           INTERNET_CloseHandle (internal)
427  *
428  * Close internet handle
429  *
430  * RETURNS
431  *    Void
432  *
433  */
434 VOID INTERNET_CloseHandle(LPWININETAPPINFOA lpwai)
435 {
436     TRACE("%p\n",lpwai);
437
438     SendAsyncCallback(lpwai, lpwai, lpwai->hdr.dwContext,
439                       INTERNET_STATUS_HANDLE_CLOSING, lpwai,
440                       sizeof(HINTERNET));
441
442     if (lpwai->lpszAgent)
443         HeapFree(GetProcessHeap(), 0, lpwai->lpszAgent);
444
445     if (lpwai->lpszProxy)
446         HeapFree(GetProcessHeap(), 0, lpwai->lpszProxy);
447
448     if (lpwai->lpszProxyBypass)
449         HeapFree(GetProcessHeap(), 0, lpwai->lpszProxyBypass);
450
451     HeapFree(GetProcessHeap(), 0, lpwai);
452 }
453
454
455 /***********************************************************************
456  *           InternetCloseHandle (WININET.@)
457  *
458  * Generic close handle function
459  *
460  * RETURNS
461  *    TRUE on success
462  *    FALSE on failure
463  *
464  */
465 BOOL WINAPI InternetCloseHandle(HINTERNET hInternet)
466 {
467     BOOL retval;
468     LPWININETHANDLEHEADER lpwh = (LPWININETHANDLEHEADER) hInternet;
469
470     TRACE("%p\n",hInternet);
471     if (NULL == lpwh)
472         return FALSE;
473
474     __TRY {
475         /* Clear any error information */
476         INTERNET_SetLastError(0);
477         retval = FALSE;
478
479         switch (lpwh->htype)
480         {
481             case WH_HINIT:
482                 INTERNET_CloseHandle((LPWININETAPPINFOA) lpwh);
483                 retval = TRUE;
484                 break;
485
486             case WH_HHTTPSESSION:
487                 HTTP_CloseHTTPSessionHandle((LPWININETHTTPSESSIONA) lpwh);
488                 retval = TRUE;
489                 break;
490
491             case WH_HHTTPREQ:
492                 HTTP_CloseHTTPRequestHandle((LPWININETHTTPREQA) lpwh);
493                 retval = TRUE;
494                 break;
495
496             case WH_HFTPSESSION:
497                 retval = FTP_CloseSessionHandle((LPWININETFTPSESSIONA) lpwh);
498                 break;
499
500             case WH_HFINDNEXT:
501                 retval = FTP_CloseFindNextHandle((LPWININETFINDNEXTA) lpwh);
502                 break;
503
504             default:
505                 break;
506         }
507     } __EXCEPT(page_fault) {
508         INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
509         return FALSE;
510     }
511     __ENDTRY
512
513     return retval;
514 }
515
516
517 /***********************************************************************
518  *           SetUrlComponentValue (Internal)
519  *
520  * Helper function for InternetCrackUrlA
521  *
522  * RETURNS
523  *    TRUE on success
524  *    FALSE on failure
525  *
526  */
527 BOOL SetUrlComponentValue(LPSTR* lppszComponent, LPDWORD dwComponentLen, LPCSTR lpszStart, INT len)
528 {
529     TRACE("%s (%d)\n", lpszStart, len);
530
531     if (*dwComponentLen != 0)
532     {
533         if (*lppszComponent == NULL)
534         {
535             *lppszComponent = (LPSTR)lpszStart;
536             *dwComponentLen = len;
537         }
538         else
539         {
540             INT ncpylen = min((*dwComponentLen)-1, len);
541             strncpy(*lppszComponent, lpszStart, ncpylen);
542             (*lppszComponent)[ncpylen] = '\0';
543             *dwComponentLen = ncpylen;
544         }
545     }
546
547     return TRUE;
548 }
549
550
551 /***********************************************************************
552  *           InternetCrackUrlA (WININET.@)
553  *
554  * Break up URL into its components
555  *
556  * TODO: Handle dwFlags
557  *
558  * RETURNS
559  *    TRUE on success
560  *    FALSE on failure
561  *
562  */
563 BOOL WINAPI InternetCrackUrlA(LPCSTR lpszUrl, DWORD dwUrlLength, DWORD dwFlags,
564                 LPURL_COMPONENTSA lpUrlComponents)
565 {
566   /*
567    * RFC 1808
568    * <protocol>:[//<net_loc>][/path][;<params>][?<query>][#<fragment>]
569    *
570    */
571     LPSTR lpszParam    = NULL;
572     BOOL  bIsAbsolute = FALSE;
573     LPSTR lpszap = (char*)lpszUrl;
574     LPSTR lpszcp = NULL;
575
576     TRACE("\n");
577
578     /* Determine if the URI is absolute. */
579     while (*lpszap != '\0')
580     {
581         if (isalnum(*lpszap))
582         {
583             lpszap++;
584             continue;
585         }
586         if ((*lpszap == ':') && (lpszap - lpszUrl >= 2))
587         {
588             bIsAbsolute = TRUE;
589             lpszcp = lpszap;
590         }
591         else
592         {
593             lpszcp = (LPSTR)lpszUrl; /* Relative url */
594         }
595
596         break;
597     }
598
599     /* Parse <params> */
600     lpszParam = strpbrk(lpszap, ";?");
601     if (lpszParam != NULL)
602     {
603         if (!SetUrlComponentValue(&lpUrlComponents->lpszExtraInfo,
604              &lpUrlComponents->dwExtraInfoLength, lpszParam+1, strlen(lpszParam+1)))
605         {
606             return FALSE;
607         }
608         }
609
610     if (bIsAbsolute) /* Parse <protocol>:[//<net_loc>] */
611         {
612         LPSTR lpszNetLoc;
613
614         /* Get scheme first. */
615         lpUrlComponents->nScheme = GetInternetScheme(lpszUrl, lpszcp - lpszUrl);
616         if (!SetUrlComponentValue(&lpUrlComponents->lpszScheme,
617                     &lpUrlComponents->dwSchemeLength, lpszUrl, lpszcp - lpszUrl))
618             return FALSE;
619
620         /* Eat ':' in protocol. */
621         lpszcp++;
622
623         /* Skip over slashes. */
624         if (*lpszcp == '/')
625         {
626             lpszcp++;
627             if (*lpszcp == '/')
628             {
629                 lpszcp++;
630                 if (*lpszcp == '/')
631                     lpszcp++;
632             }
633         }
634
635         lpszNetLoc = strpbrk(lpszcp, "/");
636         if (lpszParam)
637         {
638             if (lpszNetLoc)
639                lpszNetLoc = min(lpszNetLoc, lpszParam);
640         else
641                lpszNetLoc = lpszParam;
642         }
643         else if (!lpszNetLoc)
644             lpszNetLoc = lpszcp + strlen(lpszcp);
645
646         /* Parse net-loc */
647         if (lpszNetLoc)
648         {
649             LPSTR lpszHost;
650             LPSTR lpszPort;
651
652                 /* [<user>[<:password>]@]<host>[:<port>] */
653             /* First find the user and password if they exist */
654
655             lpszHost = strchr(lpszcp, '@');
656             if (lpszHost == NULL || lpszHost > lpszNetLoc)
657                 {
658                 /* username and password not specified. */
659                 SetUrlComponentValue(&lpUrlComponents->lpszUserName,
660                         &lpUrlComponents->dwUserNameLength, NULL, 0);
661                 SetUrlComponentValue(&lpUrlComponents->lpszPassword,
662                         &lpUrlComponents->dwPasswordLength, NULL, 0);
663                 }
664             else /* Parse out username and password */
665                 {
666                 LPSTR lpszUser = lpszcp;
667                 LPSTR lpszPasswd = lpszHost;
668
669                 while (lpszcp < lpszHost)
670                         {
671                    if (*lpszcp == ':')
672                        lpszPasswd = lpszcp;
673
674                    lpszcp++;
675                     }
676
677                 SetUrlComponentValue(&lpUrlComponents->lpszUserName,
678                         &lpUrlComponents->dwUserNameLength, lpszUser, lpszPasswd - lpszUser);
679
680                 if (lpszPasswd != lpszHost)
681                     lpszPasswd++;
682                 SetUrlComponentValue(&lpUrlComponents->lpszPassword,
683                         &lpUrlComponents->dwPasswordLength,
684                         lpszPasswd == lpszHost ? NULL : lpszPasswd,
685                         lpszHost - lpszPasswd);
686
687                 lpszcp++; /* Advance to beginning of host */
688                 }
689
690             /* Parse <host><:port> */
691
692             lpszHost = lpszcp;
693             lpszPort = lpszNetLoc;
694
695             while (lpszcp < lpszNetLoc)
696                     {
697                 if (*lpszcp == ':')
698                     lpszPort = lpszcp;
699
700                 lpszcp++;
701                 }
702
703             SetUrlComponentValue(&lpUrlComponents->lpszHostName,
704                &lpUrlComponents->dwHostNameLength, lpszHost, lpszPort - lpszHost);
705
706             if (lpszPort != lpszNetLoc)
707                 lpUrlComponents->nPort = atoi(++lpszPort);
708             else
709                 lpUrlComponents->nPort = 0;
710             }
711         }
712
713     /* Here lpszcp points to:
714      *
715      * <protocol>:[//<net_loc>][/path][;<params>][?<query>][#<fragment>]
716      *                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
717      */
718     if (lpszcp != 0 && *lpszcp != '\0' && (!lpszParam || lpszcp < lpszParam))
719     {
720         INT len;
721
722         /* Only truncate the parameter list if it's already been saved
723          * in lpUrlComponents->lpszExtraInfo.
724          */
725         if (lpszParam && lpUrlComponents->dwExtraInfoLength)
726             len = lpszParam - lpszcp;
727         else
728         {
729             /* Leave the parameter list in lpszUrlPath.  Strip off any trailing
730              * newlines if necessary.
731              */
732             LPSTR lpsznewline = strchr (lpszcp, '\n');
733             if (lpsznewline != NULL)
734                 len = lpsznewline - lpszcp;
735             else
736                 len = strlen(lpszcp);
737         }
738
739         if (!SetUrlComponentValue(&lpUrlComponents->lpszUrlPath,
740          &lpUrlComponents->dwUrlPathLength, lpszcp, len))
741          return FALSE;
742     }
743     else
744     {
745         lpUrlComponents->dwUrlPathLength = 0;
746     }
747
748     TRACE("%s: host(%s) path(%s) extra(%s)\n", lpszUrl, lpUrlComponents->lpszHostName,
749           lpUrlComponents->lpszUrlPath, lpUrlComponents->lpszExtraInfo);
750
751     return TRUE;
752 }
753
754
755 /***********************************************************************
756  *           GetUrlCacheEntryInfoA (WININET.@)
757  *
758  */
759 BOOL WINAPI GetUrlCacheEntryInfoA(LPCSTR lpszUrl,
760   LPINTERNET_CACHE_ENTRY_INFOA lpCacheEntry,
761   LPDWORD lpCacheEntrySize)
762 {
763     FIXME("stub\n");
764     return FALSE;
765 }
766
767 /***********************************************************************
768  *           CommitUrlCacheEntryA (WININET.@)
769  *
770  */
771 BOOL WINAPI CommitUrlCacheEntryA(LPCSTR lpszUrl, LPCSTR lpszLocalName,
772     FILETIME ExpireTime, FILETIME lastModified, DWORD cacheEntryType,
773     LPBYTE lpHeaderInfo, DWORD headerSize, LPCSTR fileExtension,
774     DWORD originalUrl)
775 {
776     FIXME("stub\n");
777     return FALSE;
778 }
779
780 /***********************************************************************
781  *           InternetAttemptConnect (WININET.@)
782  *
783  * Attempt to make a connection to the internet
784  *
785  * RETURNS
786  *    ERROR_SUCCESS on success
787  *    Error value   on failure
788  *
789  */
790 DWORD WINAPI InternetAttemptConnect(DWORD dwReserved)
791 {
792     FIXME("Stub\n");
793     return ERROR_SUCCESS;
794 }
795
796
797 /***********************************************************************
798  *           InternetCanonicalizeUrlA (WININET.@)
799  *
800  * Escape unsafe characters and spaces
801  *
802  * RETURNS
803  *    TRUE on success
804  *    FALSE on failure
805  *
806  */
807 BOOL WINAPI InternetCanonicalizeUrlA(LPCSTR lpszUrl, LPSTR lpszBuffer,
808         LPDWORD lpdwBufferLength, DWORD dwFlags)
809 {
810     HRESULT hr;
811     TRACE("%s %p %p %08lx\n",debugstr_a(lpszUrl), lpszBuffer,
812           lpdwBufferLength, dwFlags);
813
814     /* Flip this bit to correspond to URL_ESCAPE_UNSAFE */
815     dwFlags ^= ICU_NO_ENCODE;
816
817     dwFlags |= 0x80000000; /* Don't know what this means */
818
819     hr = UrlCanonicalizeA(lpszUrl, lpszBuffer, lpdwBufferLength, dwFlags);
820
821     return (hr == S_OK) ? TRUE : FALSE;
822 }
823
824 /***********************************************************************
825  *           InternetSetStatusCallback (WININET.@)
826  *
827  * Sets up a callback function which is called as progress is made
828  * during an operation.
829  *
830  * RETURNS
831  *    Previous callback or NULL         on success
832  *    INTERNET_INVALID_STATUS_CALLBACK  on failure
833  *
834  */
835 INTERNET_STATUS_CALLBACK WINAPI InternetSetStatusCallback(
836         HINTERNET hInternet ,INTERNET_STATUS_CALLBACK lpfnIntCB)
837 {
838     INTERNET_STATUS_CALLBACK retVal;
839     LPWININETAPPINFOA lpwai = (LPWININETAPPINFOA)hInternet;
840
841     TRACE("0x%08lx\n", (ULONG)hInternet);
842     if (lpwai->hdr.htype != WH_HINIT)
843         return INTERNET_INVALID_STATUS_CALLBACK;
844
845     retVal = lpwai->lpfnStatusCB;
846     lpwai->lpfnStatusCB = lpfnIntCB;
847
848     return retVal;
849 }
850
851
852 /***********************************************************************
853  *           InternetWriteFile (WININET.@)
854  *
855  * Write data to an open internet file
856  *
857  * RETURNS
858  *    TRUE  on success
859  *    FALSE on failure
860  *
861  */
862 BOOL WINAPI InternetWriteFile(HINTERNET hFile, LPCVOID lpBuffer ,
863         DWORD dwNumOfBytesToWrite, LPDWORD lpdwNumOfBytesWritten)
864 {
865     BOOL retval = FALSE;
866     int nSocket = -1;
867     LPWININETHANDLEHEADER lpwh = (LPWININETHANDLEHEADER) hFile;
868
869     TRACE("\n");
870     if (NULL == lpwh)
871         return FALSE;
872
873     switch (lpwh->htype)
874     {
875         case WH_HHTTPREQ:
876             nSocket = ((LPWININETHTTPREQA)hFile)->nSocketFD;
877             break;
878
879         case WH_HFILE:
880             nSocket = ((LPWININETFILE)hFile)->nDataSocket;
881             break;
882
883         default:
884             break;
885     }
886
887     if (nSocket != -1)
888     {
889         int res = send(nSocket, lpBuffer, dwNumOfBytesToWrite, 0);
890         retval = (res >= 0);
891         *lpdwNumOfBytesWritten = retval ? res : 0;
892     }
893
894     return retval;
895 }
896
897
898 /***********************************************************************
899  *           InternetReadFile (WININET.@)
900  *
901  * Read data from an open internet file
902  *
903  * RETURNS
904  *    TRUE  on success
905  *    FALSE on failure
906  *
907  */
908 BOOL WINAPI InternetReadFile(HINTERNET hFile, LPVOID lpBuffer,
909         DWORD dwNumOfBytesToRead, LPDWORD dwNumOfBytesRead)
910 {
911     BOOL retval = FALSE;
912     int nSocket = -1;
913     LPWININETHANDLEHEADER lpwh = (LPWININETHANDLEHEADER) hFile;
914
915     TRACE("\n");
916
917     if (NULL == lpwh)
918         return FALSE;
919
920     switch (lpwh->htype)
921     {
922         case WH_HHTTPREQ:
923             nSocket = ((LPWININETHTTPREQA)hFile)->nSocketFD;
924             break;
925
926         case WH_HFILE:
927             nSocket = ((LPWININETFILE)hFile)->nDataSocket;
928             break;
929
930         default:
931             break;
932     }
933
934     if (nSocket != -1)
935     {
936         int res = recv(nSocket, lpBuffer, dwNumOfBytesToRead, 0);
937         retval = (res >= 0);
938         *dwNumOfBytesRead = retval ? res : 0;
939     }
940     return retval;
941 }
942
943 /***********************************************************************
944  *           InternetReadFileExA (WININET.@)
945  *
946  * Read data from an open internet file
947  *
948  * RETURNS
949  *    TRUE  on success
950  *    FALSE on failure
951  *
952  */
953 BOOL WINAPI InternetReadFileExA(HINTERNET hFile, LPINTERNET_BUFFERSA lpBuffer,
954         DWORD dwFlags, DWORD dwContext)
955 {
956   FIXME("stub\n");
957   return FALSE;
958 }
959
960 /***********************************************************************
961  *           InternetReadFileExW (WININET.@)
962  *
963  * Read data from an open internet file
964  *
965  * RETURNS
966  *    TRUE  on success
967  *    FALSE on failure
968  *
969  */
970 BOOL WINAPI InternetReadFileExW(HINTERNET hFile, LPINTERNET_BUFFERSW lpBuffer,
971         DWORD dwFlags, DWORD dwContext)
972 {
973   FIXME("stub\n");
974
975   INTERNET_SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
976   return FALSE;
977 }
978
979 /***********************************************************************
980  *           InternetQueryOptionA (WININET.@)
981  *
982  * Queries an options on the specified handle
983  *
984  * RETURNS
985  *    TRUE  on success
986  *    FALSE on failure
987  *
988  */
989 BOOL WINAPI InternetQueryOptionA(HINTERNET hInternet, DWORD dwOption,
990         LPVOID lpBuffer, LPDWORD lpdwBufferLength)
991 {
992     LPWININETHANDLEHEADER lpwhh;
993     BOOL bSuccess = FALSE;
994
995     TRACE("0x%08lx\n", dwOption);
996
997     if (NULL == hInternet)
998     {
999         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1000         return FALSE;
1001     }
1002
1003     lpwhh = (LPWININETHANDLEHEADER) hInternet;
1004
1005     switch (dwOption)
1006     {
1007         case INTERNET_OPTION_HANDLE_TYPE:
1008         {
1009             ULONG type = lpwhh->htype;
1010             TRACE("INTERNET_OPTION_HANDLE_TYPE: %ld\n", type);
1011
1012             if (*lpdwBufferLength < sizeof(ULONG))
1013                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1014             else
1015             {
1016                 memcpy(lpBuffer, &type, sizeof(ULONG));
1017                     *lpdwBufferLength = sizeof(ULONG);
1018                 bSuccess = TRUE;
1019             }
1020             break;
1021         }
1022
1023         case INTERNET_OPTION_REQUEST_FLAGS:
1024         {
1025             ULONG flags = 4;
1026             TRACE("INTERNET_OPTION_REQUEST_FLAGS: %ld\n", flags);
1027             if (*lpdwBufferLength < sizeof(ULONG))
1028                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1029             else
1030             {
1031                 memcpy(lpBuffer, &flags, sizeof(ULONG));
1032                     *lpdwBufferLength = sizeof(ULONG);
1033                 bSuccess = TRUE;
1034             }
1035             break;
1036         }
1037
1038         case INTERNET_OPTION_URL:
1039         case INTERNET_OPTION_DATAFILE_NAME:
1040         {
1041             ULONG type = lpwhh->htype;
1042             if (type == WH_HHTTPREQ)
1043             {
1044                 LPWININETHTTPREQA lpreq = hInternet;
1045                 char url[1023];
1046
1047                 sprintf(url,"http://%s%s",lpreq->lpszHostName,lpreq->lpszPath);
1048                 TRACE("INTERNET_OPTION_URL: %s\n",url);
1049                 if (*lpdwBufferLength < strlen(url)+1)
1050                     INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1051                 else
1052                 {
1053                     memcpy(lpBuffer, url, strlen(url)+1);
1054                         *lpdwBufferLength = strlen(url)+1;
1055                     bSuccess = TRUE;
1056                 }
1057             }
1058             break;
1059         }
1060        case INTERNET_OPTION_HTTP_VERSION:
1061        {
1062             /*
1063              * Presently hardcoded to 1.1
1064              */
1065             ((HTTP_VERSION_INFO*)lpBuffer)->dwMajorVersion = 1;
1066             ((HTTP_VERSION_INFO*)lpBuffer)->dwMinorVersion = 1;
1067             bSuccess = TRUE;
1068         break;
1069        }
1070
1071        default:
1072          FIXME("Stub! %ld \n",dwOption);
1073          break;
1074     }
1075
1076     return bSuccess;
1077 }
1078
1079
1080 /***********************************************************************
1081  *           InternetSetOptionW (WININET.@)
1082  *
1083  * Sets an options on the specified handle
1084  *
1085  * RETURNS
1086  *    TRUE  on success
1087  *    FALSE on failure
1088  *
1089  */
1090 BOOL WINAPI InternetSetOptionW(HINTERNET hInternet, DWORD dwOption,
1091                            LPVOID lpBuffer, DWORD dwBufferLength)
1092 {
1093     LPWININETHANDLEHEADER lpwhh;
1094     BOOL bSuccess = FALSE;
1095
1096     TRACE("0x%08lx\n", dwOption);
1097
1098     if (NULL == hInternet)
1099     {
1100         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1101         return FALSE;
1102     }
1103
1104     lpwhh = (LPWININETHANDLEHEADER) hInternet;
1105
1106     switch (dwOption)
1107     {
1108     default:
1109         INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1110         FIXME("Stub!\n");
1111         break;
1112     }
1113
1114     return bSuccess;
1115 }
1116
1117
1118 /***********************************************************************
1119  *           InternetSetOptionA (WININET.@)
1120  *
1121  * Sets an options on the specified handle.
1122  *
1123  * RETURNS
1124  *    TRUE  on success
1125  *    FALSE on failure
1126  *
1127  */
1128 BOOL WINAPI InternetSetOptionA(HINTERNET hInternet, DWORD dwOption,
1129                            LPVOID lpBuffer, DWORD dwBufferLength)
1130 {
1131     /* FIXME!!! implement if lpBuffer is a string, dwBufferLength is
1132        in TCHARs */
1133     return InternetSetOptionW(hInternet,dwOption, lpBuffer,
1134                               dwBufferLength);
1135 }
1136
1137
1138 /***********************************************************************
1139  *           InternetGetCookieA (WININET.@)
1140  *
1141  * Retrieve cookie from the specified url
1142  *
1143  * RETURNS
1144  *    TRUE  on success
1145  *    FALSE on failure
1146  *
1147  */
1148 BOOL WINAPI InternetGetCookieA(LPCSTR lpszUrl, LPCSTR lpszCookieName,
1149                 LPSTR lpCookieData, LPDWORD lpdwSize)
1150 {
1151     FIXME("(%s,%s,%p), stub!\n",debugstr_a(lpszUrl),debugstr_a(lpszCookieName),
1152             lpCookieData
1153     );
1154     return FALSE;
1155 }
1156 /***********************************************************************
1157  *           InternetSetCookieA (WININET.@)
1158  *
1159  * Sets cookie for the specified url
1160  *
1161  * RETURNS
1162  *    TRUE  on success
1163  *    FALSE on failure
1164  *
1165  */
1166 BOOL WINAPI InternetSetCookieA(
1167         LPCSTR lpszUrl, LPCSTR lpszCookieName, LPCSTR lpCookieData
1168 ) {
1169     FIXME("(%s,%s,%s), stub!\n",debugstr_a(lpszUrl),debugstr_a(lpszCookieName),debugstr_a(lpCookieData));
1170     return FALSE;
1171 }
1172
1173 /***********************************************************************
1174  *           GetInternetScheme (internal)
1175  *
1176  * Get scheme of url
1177  *
1178  * RETURNS
1179  *    scheme on success
1180  *    INTERNET_SCHEME_UNKNOWN on failure
1181  *
1182  */
1183 INTERNET_SCHEME GetInternetScheme(LPCSTR lpszScheme, INT nMaxCmp)
1184 {
1185     TRACE("\n");
1186     if(lpszScheme==NULL)
1187         return INTERNET_SCHEME_UNKNOWN;
1188
1189     if (!strncasecmp("ftp", lpszScheme, nMaxCmp))
1190         return INTERNET_SCHEME_FTP;
1191     else if (!strncasecmp("gopher", lpszScheme, nMaxCmp))
1192         return INTERNET_SCHEME_GOPHER;
1193     else if (!strncasecmp("http", lpszScheme, nMaxCmp))
1194         return INTERNET_SCHEME_HTTP;
1195     else if (!strncasecmp("https", lpszScheme, nMaxCmp))
1196         return INTERNET_SCHEME_HTTPS;
1197     else if (!strncasecmp("file", lpszScheme, nMaxCmp))
1198         return INTERNET_SCHEME_FILE;
1199     else if (!strncasecmp("news", lpszScheme, nMaxCmp))
1200         return INTERNET_SCHEME_NEWS;
1201     else if (!strncasecmp("mailto", lpszScheme, nMaxCmp))
1202         return INTERNET_SCHEME_MAILTO;
1203     else
1204         return INTERNET_SCHEME_UNKNOWN;
1205 }
1206
1207 /***********************************************************************
1208  *      InternetCheckConnectionA (WININET.@)
1209  *
1210  * Pings a requested host to check internet connection
1211  *
1212  * RETURNS
1213  *
1214  *  TRUE on success and FALSE on failure. if a failures then
1215  *   ERROR_NOT_CONNECTED is places into GetLastError
1216  *
1217  */
1218 BOOL WINAPI InternetCheckConnectionA( LPCSTR lpszUrl, DWORD dwFlags, DWORD dwReserved )
1219 {
1220 /*
1221  * this is a kludge which runs the resident ping program and reads the output.
1222  *
1223  * Anyone have a better idea?
1224  */
1225
1226   BOOL   rc = FALSE;
1227   char command[1024];
1228   char host[1024];
1229   int status = -1;
1230
1231   FIXME("\n");
1232
1233   /*
1234    * Crack or set the Address
1235    */
1236   if (lpszUrl == NULL)
1237   {
1238      /*
1239       * According to the doc we are supost to use the ip for the next
1240       * server in the WnInet internal server database. I have
1241       * no idea what that is or how to get it.
1242       *
1243       * So someone needs to implement this.
1244       */
1245      FIXME("Unimplemented with URL of NULL\n");
1246      return TRUE;
1247   }
1248   else
1249   {
1250      URL_COMPONENTSA componets;
1251
1252      ZeroMemory(&componets,sizeof(URL_COMPONENTSA));
1253      componets.lpszHostName = (LPSTR)&host;
1254      componets.dwHostNameLength = 1024;
1255
1256      if (!InternetCrackUrlA(lpszUrl,0,0,&componets))
1257        goto End;
1258
1259      TRACE("host name : %s\n",componets.lpszHostName);
1260   }
1261
1262   /*
1263    * Build our ping command
1264    */
1265   strcpy(command,"ping -w 1 ");
1266   strcat(command,host);
1267   strcat(command," >/dev/null 2>/dev/null");
1268
1269   TRACE("Ping command is : %s\n",command);
1270
1271   status = system(command);
1272
1273   TRACE("Ping returned a code of %i \n",status);
1274
1275   /* Ping return code of 0 indicates success */
1276   if (status == 0)
1277      rc = TRUE;
1278
1279 End:
1280
1281   if (rc == FALSE)
1282     SetLastError(ERROR_NOT_CONNECTED);
1283
1284   return rc;
1285 }
1286
1287 /**********************************************************
1288  *      InternetOpenUrlA (WININET.@)
1289  *
1290  * Opens an URL
1291  *
1292  * RETURNS
1293  *   handle of connection or NULL on failure
1294  */
1295 HINTERNET WINAPI InternetOpenUrlA(HINTERNET hInternet, LPCSTR lpszUrl, LPCSTR lpszHeaders, DWORD dwHeadersLength, DWORD dwFlags, DWORD dwContext)
1296 {
1297   URL_COMPONENTSA urlComponents;
1298   char protocol[32], hostName[MAXHOSTNAME], userName[1024], password[1024], path[2048], extra[1024];
1299   HINTERNET client = NULL, client1 = NULL;
1300   urlComponents.dwStructSize = sizeof(URL_COMPONENTSA);
1301   urlComponents.lpszScheme = protocol;
1302   urlComponents.dwSchemeLength = 32;
1303   urlComponents.lpszHostName = hostName;
1304   urlComponents.dwHostNameLength = MAXHOSTNAME;
1305   urlComponents.lpszUserName = userName;
1306   urlComponents.dwUserNameLength = 1024;
1307   urlComponents.lpszPassword = password;
1308   urlComponents.dwPasswordLength = 1024;
1309   urlComponents.lpszUrlPath = path;
1310   urlComponents.dwUrlPathLength = 2048;
1311   urlComponents.lpszExtraInfo = extra;
1312   urlComponents.dwExtraInfoLength = 1024;
1313   if(!InternetCrackUrlA(lpszUrl, strlen(lpszUrl), 0, &urlComponents))
1314     return NULL;
1315   switch(urlComponents.nScheme) {
1316   case INTERNET_SCHEME_FTP:
1317     if(urlComponents.nPort == 0)
1318       urlComponents.nPort = INTERNET_DEFAULT_FTP_PORT;
1319     client = InternetConnectA(hInternet, hostName, urlComponents.nPort, userName, password, INTERNET_SERVICE_FTP, dwFlags, dwContext);
1320     return FtpOpenFileA(client, path, GENERIC_READ, dwFlags, dwContext);
1321     break;
1322   case INTERNET_SCHEME_HTTP:
1323   case INTERNET_SCHEME_HTTPS:
1324   {
1325     LPCSTR accept[2] = { "*/*", NULL };
1326     char *hostreq=(char*)malloc(strlen(hostName)+9);
1327     sprintf(hostreq, "Host: %s\r\n", hostName);
1328     if(urlComponents.nPort == 0) {
1329       if(urlComponents.nScheme == INTERNET_SCHEME_HTTP)
1330         urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1331       else
1332         urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
1333     }
1334     client = InternetConnectA(hInternet, hostName, urlComponents.nPort, userName, password, INTERNET_SERVICE_HTTP, dwFlags, dwContext);
1335     if(client == NULL)
1336       return NULL;
1337     client1 = HttpOpenRequestA(hInternet, NULL, path, NULL, NULL, accept, dwFlags, dwContext);
1338     if(client1 == NULL) {
1339       InternetCloseHandle(client);
1340       return NULL;
1341     }
1342     HttpAddRequestHeadersA(client1, lpszHeaders, dwHeadersLength, HTTP_ADDREQ_FLAG_ADD);
1343     HttpAddRequestHeadersA(client1, hostreq, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
1344     if(!HttpSendRequestA(client1, NULL, 0, NULL, 0)) {
1345       InternetCloseHandle(client1);
1346       InternetCloseHandle(client);
1347       return NULL;
1348     }
1349     return client1;
1350     break;
1351   }
1352   case INTERNET_SCHEME_GOPHER:
1353     /* gopher doesn't seem to be implemented in wine, but it's supposed
1354      * to be supported by InternetOpenUrlA. */
1355   default:
1356     return NULL;
1357   }
1358   if(client != NULL)
1359     InternetCloseHandle(client);
1360 }
1361
1362
1363 /***********************************************************************
1364  *           INTERNET_SetLastError (internal)
1365  *
1366  * Set last thread specific error
1367  *
1368  * RETURNS
1369  *
1370  */
1371 void INTERNET_SetLastError(DWORD dwError)
1372 {
1373     LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);
1374
1375     SetLastError(dwError);
1376     lpwite->dwError = dwError;
1377 }
1378
1379
1380 /***********************************************************************
1381  *           INTERNET_GetLastError (internal)
1382  *
1383  * Get last thread specific error
1384  *
1385  * RETURNS
1386  *
1387  */
1388 DWORD INTERNET_GetLastError()
1389 {
1390     LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);
1391     return lpwite->dwError;
1392 }
1393
1394
1395 /***********************************************************************
1396  *           INTERNET_WorkerThreadFunc (internal)
1397  *
1398  * Worker thread execution function
1399  *
1400  * RETURNS
1401  *
1402  */
1403 DWORD INTERNET_WorkerThreadFunc(LPVOID *lpvParam)
1404 {
1405     DWORD dwWaitRes;
1406
1407     while (1)
1408     {
1409         dwWaitRes = WaitForMultipleObjects(2, hEventArray, FALSE, MAX_IDLE_WORKER);
1410
1411         if (dwWaitRes == WAIT_OBJECT_0 + 1)
1412             INTERNET_ExecuteWork();
1413         else
1414             break;
1415
1416         InterlockedIncrement(&dwNumIdleThreads);
1417     }
1418
1419     InterlockedDecrement(&dwNumIdleThreads);
1420     InterlockedDecrement(&dwNumThreads);
1421     TRACE("Worker thread exiting\n");
1422     return TRUE;
1423 }
1424
1425
1426 /***********************************************************************
1427  *           INTERNET_InsertWorkRequest (internal)
1428  *
1429  * Insert work request into queue
1430  *
1431  * RETURNS
1432  *
1433  */
1434 BOOL INTERNET_InsertWorkRequest(LPWORKREQUEST lpWorkRequest)
1435 {
1436     BOOL bSuccess = FALSE;
1437     LPWORKREQUEST lpNewRequest;
1438
1439     TRACE("\n");
1440
1441     lpNewRequest = HeapAlloc(GetProcessHeap(), 0, sizeof(WORKREQUEST));
1442     if (lpNewRequest)
1443     {
1444         memcpy(lpNewRequest, lpWorkRequest, sizeof(WORKREQUEST));
1445         lpNewRequest->prev = NULL;
1446
1447         EnterCriticalSection(&csQueue);
1448
1449         lpNewRequest->next = lpWorkQueueTail;
1450         if (lpWorkQueueTail)
1451             lpWorkQueueTail->prev = lpNewRequest;
1452         lpWorkQueueTail = lpNewRequest;
1453         if (!lpHeadWorkQueue)
1454             lpHeadWorkQueue = lpWorkQueueTail;
1455
1456         LeaveCriticalSection(&csQueue);
1457
1458         bSuccess = TRUE;
1459     }
1460
1461     return bSuccess;
1462 }
1463
1464
1465 /***********************************************************************
1466  *           INTERNET_GetWorkRequest (internal)
1467  *
1468  * Retrieves work request from queue
1469  *
1470  * RETURNS
1471  *
1472  */
1473 BOOL INTERNET_GetWorkRequest(LPWORKREQUEST lpWorkRequest)
1474 {
1475     BOOL bSuccess = FALSE;
1476     LPWORKREQUEST lpRequest = NULL;
1477
1478     TRACE("\n");
1479
1480     EnterCriticalSection(&csQueue);
1481
1482     if (lpHeadWorkQueue)
1483     {
1484         lpRequest = lpHeadWorkQueue;
1485         lpHeadWorkQueue = lpHeadWorkQueue->prev;
1486         if (lpRequest == lpWorkQueueTail)
1487             lpWorkQueueTail = lpHeadWorkQueue;
1488     }
1489
1490     LeaveCriticalSection(&csQueue);
1491
1492     if (lpRequest)
1493     {
1494         memcpy(lpWorkRequest, lpRequest, sizeof(WORKREQUEST));
1495         HeapFree(GetProcessHeap(), 0, lpRequest);
1496         bSuccess = TRUE;
1497     }
1498
1499     return bSuccess;
1500 }
1501
1502
1503 /***********************************************************************
1504  *           INTERNET_AsyncCall (internal)
1505  *
1506  * Retrieves work request from queue
1507  *
1508  * RETURNS
1509  *
1510  */
1511 BOOL INTERNET_AsyncCall(LPWORKREQUEST lpWorkRequest)
1512 {
1513     HANDLE hThread;
1514     DWORD dwTID;
1515     BOOL bSuccess = FALSE;
1516
1517     TRACE("\n");
1518
1519     if (InterlockedDecrement(&dwNumIdleThreads) < 0)
1520     {
1521         InterlockedIncrement(&dwNumIdleThreads);
1522
1523         if (InterlockedIncrement(&dwNumThreads) > MAX_WORKER_THREADS ||
1524             !(hThread = CreateThread(NULL, 0,
1525             (LPTHREAD_START_ROUTINE)INTERNET_WorkerThreadFunc, NULL, 0, &dwTID)))
1526         {
1527             InterlockedDecrement(&dwNumThreads);
1528             INTERNET_SetLastError(ERROR_INTERNET_ASYNC_THREAD_FAILED);
1529             goto lerror;
1530         }
1531
1532         TRACE("Created new thread\n");
1533     }
1534
1535     bSuccess = TRUE;
1536     INTERNET_InsertWorkRequest(lpWorkRequest);
1537     SetEvent(hWorkEvent);
1538
1539 lerror:
1540
1541     return bSuccess;
1542 }
1543
1544
1545 /***********************************************************************
1546  *           INTERNET_ExecuteWork (internal)
1547  *
1548  * RETURNS
1549  *
1550  */
1551 VOID INTERNET_ExecuteWork()
1552 {
1553     WORKREQUEST workRequest;
1554
1555     TRACE("\n");
1556
1557     if (INTERNET_GetWorkRequest(&workRequest))
1558     {
1559         switch (workRequest.asyncall)
1560         {
1561             case FTPPUTFILEA:
1562                 FTP_FtpPutFileA((HINTERNET)workRequest.HFTPSESSION, (LPCSTR)workRequest.LPSZLOCALFILE,
1563                     (LPCSTR)workRequest.LPSZNEWREMOTEFILE, workRequest.DWFLAGS, workRequest.DWCONTEXT);
1564                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZLOCALFILE);
1565                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZNEWREMOTEFILE);
1566                 break;
1567
1568             case FTPSETCURRENTDIRECTORYA:
1569                 FTP_FtpSetCurrentDirectoryA((HINTERNET)workRequest.HFTPSESSION,
1570                         (LPCSTR)workRequest.LPSZDIRECTORY);
1571                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZDIRECTORY);
1572                 break;
1573
1574             case FTPCREATEDIRECTORYA:
1575                 FTP_FtpCreateDirectoryA((HINTERNET)workRequest.HFTPSESSION,
1576                         (LPCSTR)workRequest.LPSZDIRECTORY);
1577                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZDIRECTORY);
1578                 break;
1579
1580             case FTPFINDFIRSTFILEA:
1581                 FTP_FtpFindFirstFileA((HINTERNET)workRequest.HFTPSESSION,
1582                         (LPCSTR)workRequest.LPSZSEARCHFILE,
1583                    (LPWIN32_FIND_DATAA)workRequest.LPFINDFILEDATA, workRequest.DWFLAGS,
1584                    workRequest.DWCONTEXT);
1585                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZSEARCHFILE);
1586                 break;
1587
1588             case FTPGETCURRENTDIRECTORYA:
1589                 FTP_FtpGetCurrentDirectoryA((HINTERNET)workRequest.HFTPSESSION,
1590                         (LPSTR)workRequest.LPSZDIRECTORY, (LPDWORD)workRequest.LPDWDIRECTORY);
1591                 break;
1592
1593             case FTPOPENFILEA:
1594                  FTP_FtpOpenFileA((HINTERNET)workRequest.HFTPSESSION,
1595                     (LPCSTR)workRequest.LPSZFILENAME,
1596                     workRequest.FDWACCESS,
1597                     workRequest.DWFLAGS,
1598                     workRequest.DWCONTEXT);
1599                  HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZFILENAME);
1600                  break;
1601
1602             case FTPGETFILEA:
1603                 FTP_FtpGetFileA((HINTERNET)workRequest.HFTPSESSION,
1604                     (LPCSTR)workRequest.LPSZREMOTEFILE,
1605                     (LPCSTR)workRequest.LPSZNEWFILE,
1606                     (BOOL)workRequest.FFAILIFEXISTS,
1607                     workRequest.DWLOCALFLAGSATTRIBUTE,
1608                     workRequest.DWFLAGS,
1609                     workRequest.DWCONTEXT);
1610                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZREMOTEFILE);
1611                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZNEWFILE);
1612                 break;
1613
1614             case FTPDELETEFILEA:
1615                 FTP_FtpDeleteFileA((HINTERNET)workRequest.HFTPSESSION,
1616                         (LPCSTR)workRequest.LPSZFILENAME);
1617                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZFILENAME);
1618                 break;
1619
1620             case FTPREMOVEDIRECTORYA:
1621                 FTP_FtpRemoveDirectoryA((HINTERNET)workRequest.HFTPSESSION,
1622                         (LPCSTR)workRequest.LPSZDIRECTORY);
1623                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZDIRECTORY);
1624                 break;
1625
1626             case FTPRENAMEFILEA:
1627                 FTP_FtpRenameFileA((HINTERNET)workRequest.HFTPSESSION,
1628                         (LPCSTR)workRequest.LPSZSRCFILE,
1629                         (LPCSTR)workRequest.LPSZDESTFILE);
1630                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZSRCFILE);
1631                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZDESTFILE);
1632                 break;
1633
1634             case INTERNETFINDNEXTA:
1635                 INTERNET_FindNextFileA((HINTERNET)workRequest.HFTPSESSION,
1636                     (LPWIN32_FIND_DATAA)workRequest.LPFINDFILEDATA);
1637                 break;
1638
1639             case HTTPSENDREQUESTA:
1640                HTTP_HttpSendRequestA((HINTERNET)workRequest.HFTPSESSION,
1641                        (LPCSTR)workRequest.LPSZHEADER,
1642                        workRequest.DWHEADERLENGTH,
1643                        (LPVOID)workRequest.LPOPTIONAL,
1644                        workRequest.DWOPTIONALLENGTH);
1645                HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZHEADER);
1646                break;
1647
1648             case HTTPOPENREQUESTA:
1649                HTTP_HttpOpenRequestA((HINTERNET)workRequest.HFTPSESSION,
1650                        (LPCSTR)workRequest.LPSZVERB,
1651                        (LPCSTR)workRequest.LPSZOBJECTNAME,
1652                        (LPCSTR)workRequest.LPSZVERSION,
1653                        (LPCSTR)workRequest.LPSZREFERRER,
1654                        (LPCSTR*)workRequest.LPSZACCEPTTYPES,
1655                        workRequest.DWFLAGS,
1656                        workRequest.DWCONTEXT);
1657                HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZVERB);
1658                HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZOBJECTNAME);
1659                HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZVERSION);
1660                HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZREFERRER);
1661                 break;
1662
1663             case SENDCALLBACK:
1664                SendAsyncCallbackInt((LPWININETAPPINFOA)workRequest.param1,
1665                        (HINTERNET)workRequest.param2, workRequest.param3,
1666                         workRequest.param4, (LPVOID)workRequest.param5,
1667                         workRequest.param6);
1668                break;
1669         }
1670     }
1671 }
1672
1673
1674 /***********************************************************************
1675  *          INTERNET_GetResponseBuffer
1676  *
1677  * RETURNS
1678  *
1679  */
1680 LPSTR INTERNET_GetResponseBuffer()
1681 {
1682     LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);
1683     TRACE("\n");
1684     return lpwite->response;
1685 }
1686
1687
1688 /***********************************************************************
1689  *           INTERNET_GetNextLine  (internal)
1690  *
1691  * Parse next line in directory string listing
1692  *
1693  * RETURNS
1694  *   Pointer to beginning of next line
1695  *   NULL on failure
1696  *
1697  */
1698
1699 LPSTR INTERNET_GetNextLine(INT nSocket, LPSTR lpszBuffer, LPDWORD dwBuffer)
1700 {
1701     struct timeval tv;
1702     fd_set infd;
1703     BOOL bSuccess = FALSE;
1704     INT nRecv = 0;
1705
1706     TRACE("\n");
1707
1708     FD_ZERO(&infd);
1709     FD_SET(nSocket, &infd);
1710     tv.tv_sec=RESPONSE_TIMEOUT;
1711     tv.tv_usec=0;
1712
1713     while (nRecv < *dwBuffer)
1714     {
1715         if (select(nSocket+1,&infd,NULL,NULL,&tv) > 0)
1716         {
1717             if (recv(nSocket, &lpszBuffer[nRecv], 1, 0) <= 0)
1718             {
1719                 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
1720                 goto lend;
1721             }
1722
1723             if (lpszBuffer[nRecv] == '\n')
1724             {
1725                 bSuccess = TRUE;
1726                 break;
1727             }
1728             if (lpszBuffer[nRecv] != '\r')
1729                 nRecv++;
1730         }
1731         else
1732         {
1733             INTERNET_SetLastError(ERROR_INTERNET_TIMEOUT);
1734             goto lend;
1735         }
1736     }
1737
1738 lend:
1739     if (bSuccess)
1740     {
1741         lpszBuffer[nRecv] = '\0';
1742         *dwBuffer = nRecv - 1;
1743         TRACE(":%d %s\n", nRecv, lpszBuffer);
1744         return lpszBuffer;
1745     }
1746     else
1747     {
1748         return NULL;
1749     }
1750 }
1751
1752 /***********************************************************************
1753  *
1754  */
1755 BOOL WINAPI InternetQueryDataAvailable( HINTERNET hFile,
1756                                 LPDWORD lpdwNumberOfBytesAvailble,
1757                                 DWORD dwFlags, DWORD dwConext)
1758 {
1759     LPWININETHTTPREQA lpwhr = (LPWININETHTTPREQA) hFile;
1760     INT retval = -1;
1761     int nSocket = -1;
1762
1763
1764     if (NULL == lpwhr)
1765     {
1766         SetLastError(ERROR_NO_MORE_FILES);
1767         return FALSE;
1768     }
1769
1770     TRACE("-->  %p %i %i\n",lpwhr,lpwhr->hdr.htype,lpwhr->nSocketFD);
1771
1772     switch (lpwhr->hdr.htype)
1773     {
1774         case WH_HHTTPREQ:
1775             nSocket = lpwhr->nSocketFD;
1776             break;
1777
1778         default:
1779             break;
1780     }
1781
1782     if (nSocket != -1)
1783     {
1784         char buffer[4048];
1785
1786         retval = recv(nSocket,buffer,4048,MSG_PEEK);
1787     }
1788     else
1789     {
1790         SetLastError(ERROR_NO_MORE_FILES);
1791     }
1792
1793     if (lpdwNumberOfBytesAvailble)
1794     {
1795         (*lpdwNumberOfBytesAvailble) = retval;
1796     }
1797
1798     TRACE("<-- %i\n",retval);
1799     return (retval+1);
1800 }
1801
1802
1803 /***********************************************************************
1804  *
1805  */
1806 BOOL WINAPI InternetLockRequestFile( HINTERNET hInternet, HANDLE
1807 *lphLockReqHandle)
1808 {
1809     FIXME("STUB\n");
1810     return FALSE;
1811 }
1812
1813 BOOL WINAPI InternetUnlockRequestFile( HANDLE hLockHandle)
1814 {
1815     FIXME("STUB\n");
1816     return FALSE;
1817 }
1818
1819
1820 /***********************************************************************
1821  *           InternetAutoDial
1822  *
1823  * On windows this function is supposed to dial the default internet
1824  * connection. We don't want to have Wine dial out to the internet so
1825  * we return TRUE by default. It might be nice to check if we are connected.
1826  *
1827  * RETURNS
1828  *   TRUE on success
1829  *   FALSE on failure
1830  *
1831  */
1832
1833 BOOL WINAPI InternetAutoDial(DWORD dwFlags, HWND hwndParent)
1834 {
1835     FIXME("STUB\n");
1836
1837     /* Tell that we are connected to the internet. */
1838     return TRUE;
1839 }