Implemented SHCreateStdEnumFmtEtc.
[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("%x,%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 /***********************************************************************
945  *           InternetQueryOptionA (WININET.@)
946  *
947  * Queries an options on the specified handle
948  *
949  * RETURNS
950  *    TRUE  on success
951  *    FALSE on failure
952  *
953  */
954 BOOL WINAPI InternetQueryOptionA(HINTERNET hInternet, DWORD dwOption,
955         LPVOID lpBuffer, LPDWORD lpdwBufferLength)
956 {
957     LPWININETHANDLEHEADER lpwhh;
958     BOOL bSuccess = FALSE;
959
960     TRACE("0x%08lx\n", dwOption);
961
962     if (NULL == hInternet)
963     {
964         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
965         return FALSE;
966     }
967
968     lpwhh = (LPWININETHANDLEHEADER) hInternet;
969
970     switch (dwOption)
971     {
972         case INTERNET_OPTION_HANDLE_TYPE:
973         {
974             ULONG type = lpwhh->htype;
975             TRACE("INTERNET_OPTION_HANDLE_TYPE: %ld\n", type);
976
977             if (*lpdwBufferLength < sizeof(ULONG))
978                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
979             else
980             {
981                 memcpy(lpBuffer, &type, sizeof(ULONG));
982                     *lpdwBufferLength = sizeof(ULONG);
983                 bSuccess = TRUE;
984             }
985             break;
986         }
987
988         case INTERNET_OPTION_REQUEST_FLAGS:
989         {
990             ULONG flags = 4;
991             TRACE("INTERNET_OPTION_REQUEST_FLAGS: %ld\n", flags);
992             if (*lpdwBufferLength < sizeof(ULONG))
993                 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
994             else
995             {
996                 memcpy(lpBuffer, &flags, sizeof(ULONG));
997                     *lpdwBufferLength = sizeof(ULONG);
998                 bSuccess = TRUE;
999             }
1000             break;
1001         }
1002
1003         case INTERNET_OPTION_URL:
1004         case INTERNET_OPTION_DATAFILE_NAME:
1005         {
1006             ULONG type = lpwhh->htype;
1007             if (type == WH_HHTTPREQ)
1008             {
1009                 LPWININETHTTPREQA lpreq = hInternet;
1010                 char url[1023];
1011
1012                 sprintf(url,"http://%s%s",lpreq->lpszHostName,lpreq->lpszPath);
1013                 TRACE("INTERNET_OPTION_URL: %s\n",url);
1014                 if (*lpdwBufferLength < strlen(url)+1)
1015                     INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1016                 else
1017                 {
1018                     memcpy(lpBuffer, url, strlen(url)+1);
1019                         *lpdwBufferLength = strlen(url)+1;
1020                     bSuccess = TRUE;
1021                 }
1022             }
1023             break;
1024         }
1025        case INTERNET_OPTION_HTTP_VERSION:
1026        {
1027             /*
1028              * Presently hardcoded to 1.1
1029              */
1030             ((HTTP_VERSION_INFO*)lpBuffer)->dwMajorVersion = 1;
1031             ((HTTP_VERSION_INFO*)lpBuffer)->dwMinorVersion = 1;
1032             bSuccess = TRUE;
1033         break;
1034        }
1035
1036        default:
1037          FIXME("Stub! %ld \n",dwOption);
1038          break;
1039     }
1040
1041     return bSuccess;
1042 }
1043
1044
1045 /***********************************************************************
1046  *           InternetSetOptionW (WININET.@)
1047  *
1048  * Sets an options on the specified handle
1049  *
1050  * RETURNS
1051  *    TRUE  on success
1052  *    FALSE on failure
1053  *
1054  */
1055 BOOL WINAPI InternetSetOptionW(HINTERNET hInternet, DWORD dwOption,
1056                            LPVOID lpBuffer, DWORD dwBufferLength)
1057 {
1058     LPWININETHANDLEHEADER lpwhh;
1059     BOOL bSuccess = FALSE;
1060
1061     TRACE("0x%08lx\n", dwOption);
1062
1063     if (NULL == hInternet)
1064     {
1065         INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1066         return FALSE;
1067     }
1068
1069     lpwhh = (LPWININETHANDLEHEADER) hInternet;
1070
1071     switch (dwOption)
1072     {
1073     default:
1074         INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1075         FIXME("Stub!\n");
1076         break;
1077     }
1078
1079     return bSuccess;
1080 }
1081
1082
1083 /***********************************************************************
1084  *           InternetSetOptionA (WININET.@)
1085  *
1086  * Sets an options on the specified handle.
1087  *
1088  * RETURNS
1089  *    TRUE  on success
1090  *    FALSE on failure
1091  *
1092  */
1093 BOOL WINAPI InternetSetOptionA(HINTERNET hInternet, DWORD dwOption,
1094                            LPVOID lpBuffer, DWORD dwBufferLength)
1095 {
1096     /* FIXME!!! implement if lpBuffer is a string, dwBufferLength is
1097        in TCHARs */
1098     return InternetSetOptionW(hInternet,dwOption, lpBuffer,
1099                               dwBufferLength);
1100 }
1101
1102
1103 /***********************************************************************
1104  *           InternetGetCookieA (WININET.@)
1105  *
1106  * Retrieve cookie from the specified url
1107  *
1108  * RETURNS
1109  *    TRUE  on success
1110  *    FALSE on failure
1111  *
1112  */
1113 BOOL WINAPI InternetGetCookieA(LPCSTR lpszUrl, LPCSTR lpszCookieName,
1114                 LPSTR lpCookieData, LPDWORD lpdwSize)
1115 {
1116     FIXME("(%s,%s,%p), stub!\n",debugstr_a(lpszUrl),debugstr_a(lpszCookieName),
1117             lpCookieData
1118     );
1119     return FALSE;
1120 }
1121 /***********************************************************************
1122  *           InternetSetCookieA (WININET.@)
1123  *
1124  * Sets cookie for the specified url
1125  *
1126  * RETURNS
1127  *    TRUE  on success
1128  *    FALSE on failure
1129  *
1130  */
1131 BOOL WINAPI InternetSetCookieA(
1132         LPCSTR lpszUrl, LPCSTR lpszCookieName, LPCSTR lpCookieData
1133 ) {
1134     FIXME("(%s,%s,%s), stub!\n",debugstr_a(lpszUrl),debugstr_a(lpszCookieName),debugstr_a(lpCookieData));
1135     return FALSE;
1136 }
1137
1138 /***********************************************************************
1139  *           GetInternetScheme (internal)
1140  *
1141  * Get scheme of url
1142  *
1143  * RETURNS
1144  *    scheme on success
1145  *    INTERNET_SCHEME_UNKNOWN on failure
1146  *
1147  */
1148 INTERNET_SCHEME GetInternetScheme(LPCSTR lpszScheme, INT nMaxCmp)
1149 {
1150     TRACE("\n");
1151     if(lpszScheme==NULL)
1152         return INTERNET_SCHEME_UNKNOWN;
1153
1154     if (!strncasecmp("ftp", lpszScheme, nMaxCmp))
1155         return INTERNET_SCHEME_FTP;
1156     else if (!strncasecmp("gopher", lpszScheme, nMaxCmp))
1157         return INTERNET_SCHEME_GOPHER;
1158     else if (!strncasecmp("http", lpszScheme, nMaxCmp))
1159         return INTERNET_SCHEME_HTTP;
1160     else if (!strncasecmp("https", lpszScheme, nMaxCmp))
1161         return INTERNET_SCHEME_HTTPS;
1162     else if (!strncasecmp("file", lpszScheme, nMaxCmp))
1163         return INTERNET_SCHEME_FILE;
1164     else if (!strncasecmp("news", lpszScheme, nMaxCmp))
1165         return INTERNET_SCHEME_NEWS;
1166     else if (!strncasecmp("mailto", lpszScheme, nMaxCmp))
1167         return INTERNET_SCHEME_MAILTO;
1168     else
1169         return INTERNET_SCHEME_UNKNOWN;
1170 }
1171
1172 /***********************************************************************
1173  *      InternetCheckConnectionA (WININET.@)
1174  *
1175  * Pings a requested host to check internet connection
1176  *
1177  * RETURNS
1178  *
1179  *  TRUE on success and FALSE on failure. if a failures then
1180  *   ERROR_NOT_CONNECTED is places into GetLastError
1181  *
1182  */
1183 BOOL WINAPI InternetCheckConnectionA( LPCSTR lpszUrl, DWORD dwFlags, DWORD dwReserved )
1184 {
1185 /*
1186  * this is a kludge which runs the resident ping program and reads the output.
1187  *
1188  * Anyone have a better idea?
1189  */
1190
1191   BOOL   rc = FALSE;
1192   char command[1024];
1193   char host[1024];
1194   int status = -1;
1195
1196   FIXME("\n");
1197
1198   /*
1199    * Crack or set the Address
1200    */
1201   if (lpszUrl == NULL)
1202   {
1203      /*
1204       * According to the doc we are supost to use the ip for the next
1205       * server in the WnInet internal server database. I have
1206       * no idea what that is or how to get it.
1207       *
1208       * So someone needs to implement this.
1209       */
1210      FIXME("Unimplemented with URL of NULL\n");
1211      return TRUE;
1212   }
1213   else
1214   {
1215      URL_COMPONENTSA componets;
1216
1217      ZeroMemory(&componets,sizeof(URL_COMPONENTSA));
1218      componets.lpszHostName = (LPSTR)&host;
1219      componets.dwHostNameLength = 1024;
1220
1221      if (!InternetCrackUrlA(lpszUrl,0,0,&componets))
1222        goto End;
1223
1224      TRACE("host name : %s\n",componets.lpszHostName);
1225   }
1226
1227   /*
1228    * Build our ping command
1229    */
1230   strcpy(command,"ping -w 1 ");
1231   strcat(command,host);
1232   strcat(command," >/dev/null 2>/dev/null");
1233
1234   TRACE("Ping command is : %s\n",command);
1235
1236   status = system(command);
1237
1238   TRACE("Ping returned a code of %i \n",status);
1239
1240   /* Ping return code of 0 indicates success */
1241   if (status == 0)
1242      rc = TRUE;
1243
1244 End:
1245
1246   if (rc == FALSE)
1247     SetLastError(ERROR_NOT_CONNECTED);
1248
1249   return rc;
1250 }
1251
1252 /**********************************************************
1253  *      InternetOpenUrlA (WININET.@)
1254  *
1255  * Opens an URL
1256  *
1257  * RETURNS
1258  *   handle of connection or NULL on failure
1259  */
1260 HINTERNET WINAPI InternetOpenUrlA(HINTERNET hInternet, LPCSTR lpszUrl, LPCSTR lpszHeaders, DWORD dwHeadersLength, DWORD dwFlags, DWORD dwContext)
1261 {
1262   URL_COMPONENTSA urlComponents;
1263   char protocol[32], hostName[MAXHOSTNAME], userName[1024], password[1024], path[2048], extra[1024];
1264   HINTERNET client = NULL, client1 = NULL;
1265   urlComponents.dwStructSize = sizeof(URL_COMPONENTSA);
1266   urlComponents.lpszScheme = protocol;
1267   urlComponents.dwSchemeLength = 32;
1268   urlComponents.lpszHostName = hostName;
1269   urlComponents.dwHostNameLength = MAXHOSTNAME;
1270   urlComponents.lpszUserName = userName;
1271   urlComponents.dwUserNameLength = 1024;
1272   urlComponents.lpszPassword = password;
1273   urlComponents.dwPasswordLength = 1024;
1274   urlComponents.lpszUrlPath = path;
1275   urlComponents.dwUrlPathLength = 2048;
1276   urlComponents.lpszExtraInfo = extra;
1277   urlComponents.dwExtraInfoLength = 1024;
1278   if(!InternetCrackUrlA(lpszUrl, strlen(lpszUrl), 0, &urlComponents))
1279     return NULL;
1280   switch(urlComponents.nScheme) {
1281   case INTERNET_SCHEME_FTP:
1282     if(urlComponents.nPort == 0)
1283       urlComponents.nPort = INTERNET_DEFAULT_FTP_PORT;
1284     client = InternetConnectA(hInternet, hostName, urlComponents.nPort, userName, password, INTERNET_SERVICE_FTP, dwFlags, dwContext);
1285     return FtpOpenFileA(client, path, GENERIC_READ, dwFlags, dwContext);
1286     break;
1287   case INTERNET_SCHEME_HTTP:
1288   case INTERNET_SCHEME_HTTPS:
1289   {
1290     LPCSTR accept[2] = { "*/*", NULL };
1291     char *hostreq=(char*)malloc(strlen(hostName)+9);
1292     sprintf(hostreq, "Host: %s\r\n", hostName);
1293     if(urlComponents.nPort == 0) {
1294       if(urlComponents.nScheme == INTERNET_SCHEME_HTTP)
1295         urlComponents.nPort = INTERNET_DEFAULT_HTTP_PORT;
1296       else
1297         urlComponents.nPort = INTERNET_DEFAULT_HTTPS_PORT;
1298     }
1299     client = InternetConnectA(hInternet, hostName, urlComponents.nPort, userName, password, INTERNET_SERVICE_HTTP, dwFlags, dwContext);
1300     if(client == NULL)
1301       return NULL;
1302     client1 = HttpOpenRequestA(hInternet, NULL, path, NULL, NULL, accept, dwFlags, dwContext);
1303     if(client1 == NULL) {
1304       InternetCloseHandle(client);
1305       return NULL;
1306     }
1307     HttpAddRequestHeadersA(client1, lpszHeaders, dwHeadersLength, HTTP_ADDREQ_FLAG_ADD);
1308     HttpAddRequestHeadersA(client1, hostreq, -1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW);
1309     if(!HttpSendRequestA(client1, NULL, 0, NULL, 0)) {
1310       InternetCloseHandle(client1);
1311       InternetCloseHandle(client);
1312       return NULL;
1313     }
1314     return client1;
1315     break;
1316   }
1317   case INTERNET_SCHEME_GOPHER:
1318     /* gopher doesn't seem to be implemented in wine, but it's supposed
1319      * to be supported by InternetOpenUrlA. */
1320   default:
1321     return NULL;
1322   }
1323   if(client != NULL)
1324     InternetCloseHandle(client);
1325 }
1326
1327
1328 /***********************************************************************
1329  *           INTERNET_SetLastError (internal)
1330  *
1331  * Set last thread specific error
1332  *
1333  * RETURNS
1334  *
1335  */
1336 void INTERNET_SetLastError(DWORD dwError)
1337 {
1338     LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);
1339
1340     SetLastError(dwError);
1341     lpwite->dwError = dwError;
1342 }
1343
1344
1345 /***********************************************************************
1346  *           INTERNET_GetLastError (internal)
1347  *
1348  * Get last thread specific error
1349  *
1350  * RETURNS
1351  *
1352  */
1353 DWORD INTERNET_GetLastError()
1354 {
1355     LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);
1356     return lpwite->dwError;
1357 }
1358
1359
1360 /***********************************************************************
1361  *           INTERNET_WorkerThreadFunc (internal)
1362  *
1363  * Worker thread execution function
1364  *
1365  * RETURNS
1366  *
1367  */
1368 DWORD INTERNET_WorkerThreadFunc(LPVOID *lpvParam)
1369 {
1370     DWORD dwWaitRes;
1371
1372     while (1)
1373     {
1374         dwWaitRes = WaitForMultipleObjects(2, hEventArray, FALSE, MAX_IDLE_WORKER);
1375
1376         if (dwWaitRes == WAIT_OBJECT_0 + 1)
1377             INTERNET_ExecuteWork();
1378         else
1379             break;
1380
1381         InterlockedIncrement(&dwNumIdleThreads);
1382     }
1383
1384     InterlockedDecrement(&dwNumIdleThreads);
1385     InterlockedDecrement(&dwNumThreads);
1386     TRACE("Worker thread exiting\n");
1387     return TRUE;
1388 }
1389
1390
1391 /***********************************************************************
1392  *           INTERNET_InsertWorkRequest (internal)
1393  *
1394  * Insert work request into queue
1395  *
1396  * RETURNS
1397  *
1398  */
1399 BOOL INTERNET_InsertWorkRequest(LPWORKREQUEST lpWorkRequest)
1400 {
1401     BOOL bSuccess = FALSE;
1402     LPWORKREQUEST lpNewRequest;
1403
1404     TRACE("\n");
1405
1406     lpNewRequest = HeapAlloc(GetProcessHeap(), 0, sizeof(WORKREQUEST));
1407     if (lpNewRequest)
1408     {
1409         memcpy(lpNewRequest, lpWorkRequest, sizeof(WORKREQUEST));
1410         lpNewRequest->prev = NULL;
1411
1412         EnterCriticalSection(&csQueue);
1413
1414         lpNewRequest->next = lpWorkQueueTail;
1415         if (lpWorkQueueTail)
1416             lpWorkQueueTail->prev = lpNewRequest;
1417         lpWorkQueueTail = lpNewRequest;
1418         if (!lpHeadWorkQueue)
1419             lpHeadWorkQueue = lpWorkQueueTail;
1420
1421         LeaveCriticalSection(&csQueue);
1422
1423         bSuccess = TRUE;
1424     }
1425
1426     return bSuccess;
1427 }
1428
1429
1430 /***********************************************************************
1431  *           INTERNET_GetWorkRequest (internal)
1432  *
1433  * Retrieves work request from queue
1434  *
1435  * RETURNS
1436  *
1437  */
1438 BOOL INTERNET_GetWorkRequest(LPWORKREQUEST lpWorkRequest)
1439 {
1440     BOOL bSuccess = FALSE;
1441     LPWORKREQUEST lpRequest = NULL;
1442
1443     TRACE("\n");
1444
1445     EnterCriticalSection(&csQueue);
1446
1447     if (lpHeadWorkQueue)
1448     {
1449         lpRequest = lpHeadWorkQueue;
1450         lpHeadWorkQueue = lpHeadWorkQueue->prev;
1451         if (lpRequest == lpWorkQueueTail)
1452             lpWorkQueueTail = lpHeadWorkQueue;
1453     }
1454
1455     LeaveCriticalSection(&csQueue);
1456
1457     if (lpRequest)
1458     {
1459         memcpy(lpWorkRequest, lpRequest, sizeof(WORKREQUEST));
1460         HeapFree(GetProcessHeap(), 0, lpRequest);
1461         bSuccess = TRUE;
1462     }
1463
1464     return bSuccess;
1465 }
1466
1467
1468 /***********************************************************************
1469  *           INTERNET_AsyncCall (internal)
1470  *
1471  * Retrieves work request from queue
1472  *
1473  * RETURNS
1474  *
1475  */
1476 BOOL INTERNET_AsyncCall(LPWORKREQUEST lpWorkRequest)
1477 {
1478     HANDLE hThread;
1479     DWORD dwTID;
1480     BOOL bSuccess = FALSE;
1481
1482     TRACE("\n");
1483
1484     if (InterlockedDecrement(&dwNumIdleThreads) < 0)
1485     {
1486         InterlockedIncrement(&dwNumIdleThreads);
1487
1488         if (InterlockedIncrement(&dwNumThreads) > MAX_WORKER_THREADS ||
1489             !(hThread = CreateThread(NULL, 0,
1490             (LPTHREAD_START_ROUTINE)INTERNET_WorkerThreadFunc, NULL, 0, &dwTID)))
1491         {
1492             InterlockedDecrement(&dwNumThreads);
1493             INTERNET_SetLastError(ERROR_INTERNET_ASYNC_THREAD_FAILED);
1494             goto lerror;
1495         }
1496
1497         TRACE("Created new thread\n");
1498     }
1499
1500     bSuccess = TRUE;
1501     INTERNET_InsertWorkRequest(lpWorkRequest);
1502     SetEvent(hWorkEvent);
1503
1504 lerror:
1505
1506     return bSuccess;
1507 }
1508
1509
1510 /***********************************************************************
1511  *           INTERNET_ExecuteWork (internal)
1512  *
1513  * RETURNS
1514  *
1515  */
1516 VOID INTERNET_ExecuteWork()
1517 {
1518     WORKREQUEST workRequest;
1519
1520     TRACE("\n");
1521
1522     if (INTERNET_GetWorkRequest(&workRequest))
1523     {
1524         switch (workRequest.asyncall)
1525         {
1526             case FTPPUTFILEA:
1527                 FTP_FtpPutFileA((HINTERNET)workRequest.HFTPSESSION, (LPCSTR)workRequest.LPSZLOCALFILE,
1528                     (LPCSTR)workRequest.LPSZNEWREMOTEFILE, workRequest.DWFLAGS, workRequest.DWCONTEXT);
1529                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZLOCALFILE);
1530                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZNEWREMOTEFILE);
1531                 break;
1532
1533             case FTPSETCURRENTDIRECTORYA:
1534                 FTP_FtpSetCurrentDirectoryA((HINTERNET)workRequest.HFTPSESSION,
1535                         (LPCSTR)workRequest.LPSZDIRECTORY);
1536                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZDIRECTORY);
1537                 break;
1538
1539             case FTPCREATEDIRECTORYA:
1540                 FTP_FtpCreateDirectoryA((HINTERNET)workRequest.HFTPSESSION,
1541                         (LPCSTR)workRequest.LPSZDIRECTORY);
1542                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZDIRECTORY);
1543                 break;
1544
1545             case FTPFINDFIRSTFILEA:
1546                 FTP_FtpFindFirstFileA((HINTERNET)workRequest.HFTPSESSION,
1547                         (LPCSTR)workRequest.LPSZSEARCHFILE,
1548                    (LPWIN32_FIND_DATAA)workRequest.LPFINDFILEDATA, workRequest.DWFLAGS,
1549                    workRequest.DWCONTEXT);
1550                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZSEARCHFILE);
1551                 break;
1552
1553             case FTPGETCURRENTDIRECTORYA:
1554                 FTP_FtpGetCurrentDirectoryA((HINTERNET)workRequest.HFTPSESSION,
1555                         (LPSTR)workRequest.LPSZDIRECTORY, (LPDWORD)workRequest.LPDWDIRECTORY);
1556                 break;
1557
1558             case FTPOPENFILEA:
1559                  FTP_FtpOpenFileA((HINTERNET)workRequest.HFTPSESSION,
1560                     (LPCSTR)workRequest.LPSZFILENAME,
1561                     workRequest.FDWACCESS,
1562                     workRequest.DWFLAGS,
1563                     workRequest.DWCONTEXT);
1564                  HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZFILENAME);
1565                  break;
1566
1567             case FTPGETFILEA:
1568                 FTP_FtpGetFileA((HINTERNET)workRequest.HFTPSESSION,
1569                     (LPCSTR)workRequest.LPSZREMOTEFILE,
1570                     (LPCSTR)workRequest.LPSZNEWFILE,
1571                     (BOOL)workRequest.FFAILIFEXISTS,
1572                     workRequest.DWLOCALFLAGSATTRIBUTE,
1573                     workRequest.DWFLAGS,
1574                     workRequest.DWCONTEXT);
1575                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZREMOTEFILE);
1576                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZNEWFILE);
1577                 break;
1578
1579             case FTPDELETEFILEA:
1580                 FTP_FtpDeleteFileA((HINTERNET)workRequest.HFTPSESSION,
1581                         (LPCSTR)workRequest.LPSZFILENAME);
1582                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZFILENAME);
1583                 break;
1584
1585             case FTPREMOVEDIRECTORYA:
1586                 FTP_FtpRemoveDirectoryA((HINTERNET)workRequest.HFTPSESSION,
1587                         (LPCSTR)workRequest.LPSZDIRECTORY);
1588                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZDIRECTORY);
1589                 break;
1590
1591             case FTPRENAMEFILEA:
1592                 FTP_FtpRenameFileA((HINTERNET)workRequest.HFTPSESSION,
1593                         (LPCSTR)workRequest.LPSZSRCFILE,
1594                         (LPCSTR)workRequest.LPSZDESTFILE);
1595                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZSRCFILE);
1596                 HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZDESTFILE);
1597                 break;
1598
1599             case INTERNETFINDNEXTA:
1600                 INTERNET_FindNextFileA((HINTERNET)workRequest.HFTPSESSION,
1601                     (LPWIN32_FIND_DATAA)workRequest.LPFINDFILEDATA);
1602                 break;
1603
1604             case HTTPSENDREQUESTA:
1605                HTTP_HttpSendRequestA((HINTERNET)workRequest.HFTPSESSION,
1606                        (LPCSTR)workRequest.LPSZHEADER,
1607                        workRequest.DWHEADERLENGTH,
1608                        (LPVOID)workRequest.LPOPTIONAL,
1609                        workRequest.DWOPTIONALLENGTH);
1610                HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZHEADER);
1611                break;
1612
1613             case HTTPOPENREQUESTA:
1614                HTTP_HttpOpenRequestA((HINTERNET)workRequest.HFTPSESSION,
1615                        (LPCSTR)workRequest.LPSZVERB,
1616                        (LPCSTR)workRequest.LPSZOBJECTNAME,
1617                        (LPCSTR)workRequest.LPSZVERSION,
1618                        (LPCSTR)workRequest.LPSZREFERRER,
1619                        (LPCSTR*)workRequest.LPSZACCEPTTYPES,
1620                        workRequest.DWFLAGS,
1621                        workRequest.DWCONTEXT);
1622                HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZVERB);
1623                HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZOBJECTNAME);
1624                HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZVERSION);
1625                HeapFree(GetProcessHeap(), 0, (LPVOID)workRequest.LPSZREFERRER);
1626                 break;
1627
1628             case SENDCALLBACK:
1629                SendAsyncCallbackInt((LPWININETAPPINFOA)workRequest.param1,
1630                        (HINTERNET)workRequest.param2, workRequest.param3,
1631                         workRequest.param4, (LPVOID)workRequest.param5,
1632                         workRequest.param6);
1633                break;
1634         }
1635     }
1636 }
1637
1638
1639 /***********************************************************************
1640  *          INTERNET_GetResponseBuffer
1641  *
1642  * RETURNS
1643  *
1644  */
1645 LPSTR INTERNET_GetResponseBuffer()
1646 {
1647     LPWITHREADERROR lpwite = (LPWITHREADERROR)TlsGetValue(g_dwTlsErrIndex);
1648     TRACE("\n");
1649     return lpwite->response;
1650 }
1651
1652
1653 /***********************************************************************
1654  *           INTERNET_GetNextLine  (internal)
1655  *
1656  * Parse next line in directory string listing
1657  *
1658  * RETURNS
1659  *   Pointer to beginning of next line
1660  *   NULL on failure
1661  *
1662  */
1663
1664 LPSTR INTERNET_GetNextLine(INT nSocket, LPSTR lpszBuffer, LPDWORD dwBuffer)
1665 {
1666     struct timeval tv;
1667     fd_set infd;
1668     BOOL bSuccess = FALSE;
1669     INT nRecv = 0;
1670
1671     TRACE("\n");
1672
1673     FD_ZERO(&infd);
1674     FD_SET(nSocket, &infd);
1675     tv.tv_sec=RESPONSE_TIMEOUT;
1676     tv.tv_usec=0;
1677
1678     while (nRecv < *dwBuffer)
1679     {
1680         if (select(nSocket+1,&infd,NULL,NULL,&tv) > 0)
1681         {
1682             if (recv(nSocket, &lpszBuffer[nRecv], 1, 0) <= 0)
1683             {
1684                 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
1685                 goto lend;
1686             }
1687
1688             if (lpszBuffer[nRecv] == '\n')
1689             {
1690                 bSuccess = TRUE;
1691                 break;
1692             }
1693             if (lpszBuffer[nRecv] != '\r')
1694                 nRecv++;
1695         }
1696         else
1697         {
1698             INTERNET_SetLastError(ERROR_INTERNET_TIMEOUT);
1699             goto lend;
1700         }
1701     }
1702
1703 lend:
1704     if (bSuccess)
1705     {
1706         lpszBuffer[nRecv] = '\0';
1707         *dwBuffer = nRecv - 1;
1708         TRACE(":%d %s\n", nRecv, lpszBuffer);
1709         return lpszBuffer;
1710     }
1711     else
1712     {
1713         return NULL;
1714     }
1715 }
1716
1717 /***********************************************************************
1718  *
1719  */
1720 BOOL WINAPI InternetQueryDataAvailable( HINTERNET hFile,
1721                                 LPDWORD lpdwNumberOfBytesAvailble,
1722                                 DWORD dwFlags, DWORD dwConext)
1723 {
1724     LPWININETHTTPREQA lpwhr = (LPWININETHTTPREQA) hFile;
1725     INT retval = -1;
1726     int nSocket = -1;
1727
1728
1729     if (NULL == lpwhr)
1730     {
1731         SetLastError(ERROR_NO_MORE_FILES);
1732         return FALSE;
1733     }
1734
1735     TRACE("-->  %p %i %i\n",lpwhr,lpwhr->hdr.htype,lpwhr->nSocketFD);
1736
1737     switch (lpwhr->hdr.htype)
1738     {
1739         case WH_HHTTPREQ:
1740             nSocket = lpwhr->nSocketFD;
1741             break;
1742
1743         default:
1744             break;
1745     }
1746
1747     if (nSocket != -1)
1748     {
1749         char buffer[4048];
1750
1751         retval = recv(nSocket,buffer,4048,MSG_PEEK);
1752     }
1753     else
1754     {
1755         SetLastError(ERROR_NO_MORE_FILES);
1756     }
1757
1758     if (lpdwNumberOfBytesAvailble)
1759     {
1760         (*lpdwNumberOfBytesAvailble) = retval;
1761     }
1762
1763     TRACE("<-- %i\n",retval);
1764     return (retval+1);
1765 }
1766
1767
1768 /***********************************************************************
1769  *
1770  */
1771 BOOL WINAPI InternetLockRequestFile( HINTERNET hInternet, HANDLE
1772 *lphLockReqHandle)
1773 {
1774     FIXME("STUB\n");
1775     return FALSE;
1776 }
1777
1778 BOOL WINAPI InternetUnlockRequestFile( HANDLE hLockHandle)
1779 {
1780     FIXME("STUB\n");
1781     return FALSE;
1782 }
1783
1784
1785 /***********************************************************************
1786  *           InternetAutoDial
1787  *
1788  * On windows this function is supposed to dial the default internet
1789  * connection. We don't want to have Wine dial out to the internet so
1790  * we return TRUE by default. It might be nice to check if we are connected.
1791  *
1792  * RETURNS
1793  *   TRUE on success
1794  *   FALSE on failure
1795  *
1796  */
1797
1798 BOOL WINAPI InternetAutoDial(DWORD dwFlags, HWND hwndParent)
1799 {
1800     FIXME("STUB\n");
1801
1802     /* Tell that we are connected to the internet. */
1803     return TRUE;
1804 }