2 * WININET - Ftp implementation
4 * Copyright 1999 Corel Corporation
5 * Copyright 2004 Mike McCormack for CodeWeavers
6 * Copyright 2004 Kevin Koltzau
7 * Copyright 2007 Hans Leidekker
12 * Copyright 2000 Andreas Mohr
13 * Copyright 2002 Jaco Greeff
15 * This library is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU Lesser General Public
17 * License as published by the Free Software Foundation; either
18 * version 2.1 of the License, or (at your option) any later version.
20 * This library is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 * Lesser General Public License for more details.
25 * You should have received a copy of the GNU Lesser General Public
26 * License along with this library; if not, write to the Free Software
27 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
31 #include "wine/port.h"
33 #if defined(__MINGW32__) || defined (_MSC_VER)
42 #include <sys/types.h>
43 #ifdef HAVE_SYS_SOCKET_H
44 # include <sys/socket.h>
46 #ifdef HAVE_ARPA_INET_H
47 # include <arpa/inet.h>
52 #ifdef HAVE_SYS_IOCTL_H
53 # include <sys/ioctl.h>
69 #include "wine/debug.h"
72 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
74 typedef struct _ftp_session_t ftp_session_t;
79 ftp_session_t *lpFtpSession;
83 HANDLE cache_file_handle;
92 int pasvSocket; /* data socket connected by us in case of passive FTP */
93 ftp_file_t *download_in_progress;
94 struct sockaddr_in socketAddress;
95 struct sockaddr_in lstnSocketAddress;
97 INTERNET_PORT serverport;
107 SYSTEMTIME tmLastModified;
108 unsigned short permissions;
109 } FILEPROPERTIESW, *LPFILEPROPERTIESW;
114 ftp_session_t *lpFtpSession;
117 LPFILEPROPERTIESW lpafp;
118 } WININETFTPFINDNEXTW, *LPWININETFTPFINDNEXTW;
120 #define DATA_PACKET_SIZE 0x2000
121 #define szCRLF "\r\n"
122 #define MAX_BACKLOG 5
124 /* Testing shows that Windows only accepts dwFlags where the last
125 * 3 (yes 3) bits define FTP_TRANSFER_TYPE_UNKNOWN, FTP_TRANSFER_TYPE_ASCII or FTP_TRANSFER_TYPE_BINARY.
127 #define FTP_CONDITION_MASK 0x0007
130 /* FTP commands with arguments. */
146 /* FTP commands without arguments. */
155 static const CHAR *const szFtpCommands[] = {
178 static const CHAR szMonths[] = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";
179 static const WCHAR szNoAccount[] = {'n','o','a','c','c','o','u','n','t','\0'};
181 static BOOL FTP_SendCommand(INT nSocket, FTP_COMMAND ftpCmd, LPCWSTR lpszParam,
182 INTERNET_STATUS_CALLBACK lpfnStatusCB, object_header_t *hdr, DWORD_PTR dwContext);
183 static BOOL FTP_SendStore(ftp_session_t*, LPCWSTR lpszRemoteFile, DWORD dwType);
184 static BOOL FTP_GetDataSocket(ftp_session_t*, LPINT nDataSocket);
185 static BOOL FTP_SendData(ftp_session_t*, INT nDataSocket, HANDLE hFile);
186 static INT FTP_ReceiveResponse(ftp_session_t*, DWORD_PTR dwContext);
187 static BOOL FTP_SendRetrieve(ftp_session_t*, LPCWSTR lpszRemoteFile, DWORD dwType);
188 static BOOL FTP_RetrieveFileData(ftp_session_t*, INT nDataSocket, HANDLE hFile);
189 static BOOL FTP_InitListenSocket(ftp_session_t*);
190 static BOOL FTP_ConnectToHost(ftp_session_t*);
191 static BOOL FTP_SendPassword(ftp_session_t*);
192 static BOOL FTP_SendAccount(ftp_session_t*);
193 static BOOL FTP_SendType(ftp_session_t*, DWORD dwType);
194 static BOOL FTP_SendPort(ftp_session_t*);
195 static BOOL FTP_DoPassive(ftp_session_t*);
196 static BOOL FTP_SendPortOrPasv(ftp_session_t*);
197 static BOOL FTP_ParsePermission(LPCSTR lpszPermission, LPFILEPROPERTIESW lpfp);
198 static BOOL FTP_ParseNextFile(INT nSocket, LPCWSTR lpszSearchFile, LPFILEPROPERTIESW fileprop);
199 static BOOL FTP_ParseDirectory(ftp_session_t*, INT nSocket, LPCWSTR lpszSearchFile,
200 LPFILEPROPERTIESW *lpafp, LPDWORD dwfp);
201 static HINTERNET FTP_ReceiveFileList(ftp_session_t*, INT nSocket, LPCWSTR lpszSearchFile,
202 LPWIN32_FIND_DATAW lpFindFileData, DWORD_PTR dwContext);
203 static DWORD FTP_SetResponseError(DWORD dwResponse);
204 static BOOL FTP_ConvertFileProp(LPFILEPROPERTIESW lpafp, LPWIN32_FIND_DATAW lpFindFileData);
205 static BOOL FTP_FtpPutFileW(ftp_session_t*, LPCWSTR lpszLocalFile,
206 LPCWSTR lpszNewRemoteFile, DWORD dwFlags, DWORD_PTR dwContext);
207 static BOOL FTP_FtpSetCurrentDirectoryW(ftp_session_t*, LPCWSTR lpszDirectory);
208 static BOOL FTP_FtpCreateDirectoryW(ftp_session_t*, LPCWSTR lpszDirectory);
209 static HINTERNET FTP_FtpFindFirstFileW(ftp_session_t*,
210 LPCWSTR lpszSearchFile, LPWIN32_FIND_DATAW lpFindFileData, DWORD dwFlags, DWORD_PTR dwContext);
211 static BOOL FTP_FtpGetCurrentDirectoryW(ftp_session_t*, LPWSTR lpszCurrentDirectory,
212 LPDWORD lpdwCurrentDirectory);
213 static BOOL FTP_FtpRenameFileW(ftp_session_t*, LPCWSTR lpszSrc, LPCWSTR lpszDest);
214 static BOOL FTP_FtpRemoveDirectoryW(ftp_session_t*, LPCWSTR lpszDirectory);
215 static BOOL FTP_FtpDeleteFileW(ftp_session_t*, LPCWSTR lpszFileName);
216 static BOOL FTP_FtpGetFileW(ftp_session_t*, LPCWSTR lpszRemoteFile, LPCWSTR lpszNewFile,
217 BOOL fFailIfExists, DWORD dwLocalFlagsAttribute, DWORD dwInternetFlags,
218 DWORD_PTR dwContext);
220 /* A temporary helper until we get rid of INTERNET_GetLastError calls */
221 static BOOL res_to_le(DWORD res)
223 if(res != ERROR_SUCCESS)
224 INTERNET_SetLastError(res);
225 return res == ERROR_SUCCESS;
228 /***********************************************************************
229 * FtpPutFileA (WININET.@)
231 * Uploads a file to the FTP server
238 BOOL WINAPI FtpPutFileA(HINTERNET hConnect, LPCSTR lpszLocalFile,
239 LPCSTR lpszNewRemoteFile, DWORD dwFlags, DWORD_PTR dwContext)
241 LPWSTR lpwzLocalFile;
242 LPWSTR lpwzNewRemoteFile;
245 lpwzLocalFile = heap_strdupAtoW(lpszLocalFile);
246 lpwzNewRemoteFile = heap_strdupAtoW(lpszNewRemoteFile);
247 ret = FtpPutFileW(hConnect, lpwzLocalFile, lpwzNewRemoteFile,
249 heap_free(lpwzLocalFile);
250 heap_free(lpwzNewRemoteFile);
262 static void AsyncFtpPutFileProc(task_header_t *hdr)
264 put_file_task_t *task = (put_file_task_t*)hdr;
265 ftp_session_t *session = (ftp_session_t*)task->hdr.hdr;
267 TRACE("%p\n", session);
269 FTP_FtpPutFileW(session, task->local_file, task->remote_file,
270 task->flags, task->context);
272 heap_free(task->local_file);
273 heap_free(task->remote_file);
276 /***********************************************************************
277 * FtpPutFileW (WININET.@)
279 * Uploads a file to the FTP server
286 BOOL WINAPI FtpPutFileW(HINTERNET hConnect, LPCWSTR lpszLocalFile,
287 LPCWSTR lpszNewRemoteFile, DWORD dwFlags, DWORD_PTR dwContext)
289 ftp_session_t *lpwfs;
290 appinfo_t *hIC = NULL;
293 if (!lpszLocalFile || !lpszNewRemoteFile)
295 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
299 lpwfs = (ftp_session_t*) get_handle_object( hConnect );
302 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
306 if (WH_HFTPSESSION != lpwfs->hdr.htype)
308 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
312 if (lpwfs->download_in_progress != NULL)
314 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
318 if ((dwFlags & FTP_CONDITION_MASK) > FTP_TRANSFER_TYPE_BINARY)
320 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
324 hIC = lpwfs->lpAppInfo;
325 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
327 put_file_task_t *task = alloc_async_task(&lpwfs->hdr, AsyncFtpPutFileProc, sizeof(*task));
329 task->local_file = heap_strdupW(lpszLocalFile);
330 task->remote_file = heap_strdupW(lpszNewRemoteFile);
331 task->flags = dwFlags;
332 task->context = dwContext;
334 r = res_to_le(INTERNET_AsyncCall(&task->hdr));
338 r = FTP_FtpPutFileW(lpwfs, lpszLocalFile,
339 lpszNewRemoteFile, dwFlags, dwContext);
343 WININET_Release( &lpwfs->hdr );
348 /***********************************************************************
349 * FTP_FtpPutFileW (Internal)
351 * Uploads a file to the FTP server
358 static BOOL FTP_FtpPutFileW(ftp_session_t *lpwfs, LPCWSTR lpszLocalFile,
359 LPCWSTR lpszNewRemoteFile, DWORD dwFlags, DWORD_PTR dwContext)
362 BOOL bSuccess = FALSE;
363 appinfo_t *hIC = NULL;
366 TRACE(" lpszLocalFile(%s) lpszNewRemoteFile(%s)\n", debugstr_w(lpszLocalFile), debugstr_w(lpszNewRemoteFile));
368 /* Clear any error information */
369 INTERNET_SetLastError(0);
371 /* Open file to be uploaded */
372 if (INVALID_HANDLE_VALUE ==
373 (hFile = CreateFileW(lpszLocalFile, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0)))
374 /* Let CreateFile set the appropriate error */
377 hIC = lpwfs->lpAppInfo;
379 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
381 if (FTP_SendStore(lpwfs, lpszNewRemoteFile, dwFlags))
385 /* Get data socket to server */
386 if (FTP_GetDataSocket(lpwfs, &nDataSocket))
388 FTP_SendData(lpwfs, nDataSocket, hFile);
389 closesocket(nDataSocket);
390 nResCode = FTP_ReceiveResponse(lpwfs, dwContext);
396 FTP_SetResponseError(nResCode);
401 if (lpwfs->lstnSocket != -1)
403 closesocket(lpwfs->lstnSocket);
404 lpwfs->lstnSocket = -1;
407 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
409 INTERNET_ASYNC_RESULT iar;
411 iar.dwResult = (DWORD)bSuccess;
412 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
413 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
414 &iar, sizeof(INTERNET_ASYNC_RESULT));
423 /***********************************************************************
424 * FtpSetCurrentDirectoryA (WININET.@)
426 * Change the working directory on the FTP server
433 BOOL WINAPI FtpSetCurrentDirectoryA(HINTERNET hConnect, LPCSTR lpszDirectory)
435 LPWSTR lpwzDirectory;
438 lpwzDirectory = heap_strdupAtoW(lpszDirectory);
439 ret = FtpSetCurrentDirectoryW(hConnect, lpwzDirectory);
440 heap_free(lpwzDirectory);
445 static void AsyncFtpSetCurrentDirectoryProc(WORKREQUEST *workRequest)
447 struct WORKREQ_FTPSETCURRENTDIRECTORYW const *req = &workRequest->u.FtpSetCurrentDirectoryW;
448 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
450 TRACE("%p\n", lpwfs);
452 FTP_FtpSetCurrentDirectoryW(lpwfs, req->lpszDirectory);
453 heap_free(req->lpszDirectory);
456 /***********************************************************************
457 * FtpSetCurrentDirectoryW (WININET.@)
459 * Change the working directory on the FTP server
466 BOOL WINAPI FtpSetCurrentDirectoryW(HINTERNET hConnect, LPCWSTR lpszDirectory)
468 ftp_session_t *lpwfs = NULL;
469 appinfo_t *hIC = NULL;
474 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
478 lpwfs = (ftp_session_t*) get_handle_object( hConnect );
479 if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
481 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
485 if (lpwfs->download_in_progress != NULL)
487 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
491 TRACE("lpszDirectory(%s)\n", debugstr_w(lpszDirectory));
493 hIC = lpwfs->lpAppInfo;
494 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
497 struct WORKREQ_FTPSETCURRENTDIRECTORYW *req;
499 task = alloc_async_task(&lpwfs->hdr, AsyncFtpSetCurrentDirectoryProc, sizeof(*task));
500 req = &task->u.FtpSetCurrentDirectoryW;
501 req->lpszDirectory = heap_strdupW(lpszDirectory);
503 r = res_to_le(INTERNET_AsyncCall(task));
507 r = FTP_FtpSetCurrentDirectoryW(lpwfs, lpszDirectory);
512 WININET_Release( &lpwfs->hdr );
518 /***********************************************************************
519 * FTP_FtpSetCurrentDirectoryW (Internal)
521 * Change the working directory on the FTP server
528 static BOOL FTP_FtpSetCurrentDirectoryW(ftp_session_t *lpwfs, LPCWSTR lpszDirectory)
531 appinfo_t *hIC = NULL;
532 DWORD bSuccess = FALSE;
534 TRACE("lpszDirectory(%s)\n", debugstr_w(lpszDirectory));
536 /* Clear any error information */
537 INTERNET_SetLastError(0);
539 hIC = lpwfs->lpAppInfo;
540 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_CWD, lpszDirectory,
541 lpwfs->hdr.lpfnStatusCB, &lpwfs->hdr, lpwfs->hdr.dwContext))
544 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
551 FTP_SetResponseError(nResCode);
555 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
557 INTERNET_ASYNC_RESULT iar;
559 iar.dwResult = bSuccess;
560 iar.dwError = bSuccess ? ERROR_SUCCESS : ERROR_INTERNET_EXTENDED_ERROR;
561 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
562 &iar, sizeof(INTERNET_ASYNC_RESULT));
568 /***********************************************************************
569 * FtpCreateDirectoryA (WININET.@)
571 * Create new directory on the FTP server
578 BOOL WINAPI FtpCreateDirectoryA(HINTERNET hConnect, LPCSTR lpszDirectory)
580 LPWSTR lpwzDirectory;
583 lpwzDirectory = heap_strdupAtoW(lpszDirectory);
584 ret = FtpCreateDirectoryW(hConnect, lpwzDirectory);
585 heap_free(lpwzDirectory);
590 static void AsyncFtpCreateDirectoryProc(WORKREQUEST *workRequest)
592 struct WORKREQ_FTPCREATEDIRECTORYW const *req = &workRequest->u.FtpCreateDirectoryW;
593 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
595 TRACE(" %p\n", lpwfs);
597 FTP_FtpCreateDirectoryW(lpwfs, req->lpszDirectory);
598 heap_free(req->lpszDirectory);
601 /***********************************************************************
602 * FtpCreateDirectoryW (WININET.@)
604 * Create new directory on the FTP server
611 BOOL WINAPI FtpCreateDirectoryW(HINTERNET hConnect, LPCWSTR lpszDirectory)
613 ftp_session_t *lpwfs;
614 appinfo_t *hIC = NULL;
617 lpwfs = (ftp_session_t*) get_handle_object( hConnect );
620 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
624 if (WH_HFTPSESSION != lpwfs->hdr.htype)
626 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
630 if (lpwfs->download_in_progress != NULL)
632 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
638 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
642 hIC = lpwfs->lpAppInfo;
643 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
646 struct WORKREQ_FTPCREATEDIRECTORYW *req;
648 task = alloc_async_task(&lpwfs->hdr, AsyncFtpCreateDirectoryProc, sizeof(*task));
649 req = &task->u.FtpCreateDirectoryW;
650 req->lpszDirectory = heap_strdupW(lpszDirectory);
652 r = res_to_le(INTERNET_AsyncCall(task));
656 r = FTP_FtpCreateDirectoryW(lpwfs, lpszDirectory);
659 WININET_Release( &lpwfs->hdr );
665 /***********************************************************************
666 * FTP_FtpCreateDirectoryW (Internal)
668 * Create new directory on the FTP server
675 static BOOL FTP_FtpCreateDirectoryW(ftp_session_t *lpwfs, LPCWSTR lpszDirectory)
678 BOOL bSuccess = FALSE;
679 appinfo_t *hIC = NULL;
681 TRACE("lpszDirectory(%s)\n", debugstr_w(lpszDirectory));
683 /* Clear any error information */
684 INTERNET_SetLastError(0);
686 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_MKD, lpszDirectory, 0, 0, 0))
689 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
695 FTP_SetResponseError(nResCode);
699 hIC = lpwfs->lpAppInfo;
700 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
702 INTERNET_ASYNC_RESULT iar;
704 iar.dwResult = (DWORD)bSuccess;
705 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
706 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
707 &iar, sizeof(INTERNET_ASYNC_RESULT));
713 /***********************************************************************
714 * FtpFindFirstFileA (WININET.@)
716 * Search the specified directory
719 * HINTERNET on success
723 HINTERNET WINAPI FtpFindFirstFileA(HINTERNET hConnect,
724 LPCSTR lpszSearchFile, LPWIN32_FIND_DATAA lpFindFileData, DWORD dwFlags, DWORD_PTR dwContext)
726 LPWSTR lpwzSearchFile;
727 WIN32_FIND_DATAW wfd;
728 LPWIN32_FIND_DATAW lpFindFileDataW;
731 lpwzSearchFile = heap_strdupAtoW(lpszSearchFile);
732 lpFindFileDataW = lpFindFileData?&wfd:NULL;
733 ret = FtpFindFirstFileW(hConnect, lpwzSearchFile, lpFindFileDataW, dwFlags, dwContext);
734 heap_free(lpwzSearchFile);
736 if (ret && lpFindFileData)
737 WININET_find_data_WtoA(lpFindFileDataW, lpFindFileData);
743 static void AsyncFtpFindFirstFileProc(WORKREQUEST *workRequest)
745 struct WORKREQ_FTPFINDFIRSTFILEW const *req = &workRequest->u.FtpFindFirstFileW;
746 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
748 TRACE("%p\n", lpwfs);
750 FTP_FtpFindFirstFileW(lpwfs, req->lpszSearchFile,
751 req->lpFindFileData, req->dwFlags, req->dwContext);
752 heap_free(req->lpszSearchFile);
755 /***********************************************************************
756 * FtpFindFirstFileW (WININET.@)
758 * Search the specified directory
761 * HINTERNET on success
765 HINTERNET WINAPI FtpFindFirstFileW(HINTERNET hConnect,
766 LPCWSTR lpszSearchFile, LPWIN32_FIND_DATAW lpFindFileData, DWORD dwFlags, DWORD_PTR dwContext)
768 ftp_session_t *lpwfs;
769 appinfo_t *hIC = NULL;
772 lpwfs = (ftp_session_t*) get_handle_object( hConnect );
773 if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
775 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
779 if (lpwfs->download_in_progress != NULL)
781 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
785 hIC = lpwfs->lpAppInfo;
786 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
789 struct WORKREQ_FTPFINDFIRSTFILEW *req;
791 task = alloc_async_task(&lpwfs->hdr, AsyncFtpFindFirstFileProc, sizeof(*task));
792 req = &task->u.FtpFindFirstFileW;
793 req->lpszSearchFile = (lpszSearchFile == NULL) ? NULL : heap_strdupW(lpszSearchFile);
794 req->lpFindFileData = lpFindFileData;
795 req->dwFlags = dwFlags;
796 req->dwContext= dwContext;
798 INTERNET_AsyncCall(task);
803 r = FTP_FtpFindFirstFileW(lpwfs, lpszSearchFile, lpFindFileData,
808 WININET_Release( &lpwfs->hdr );
814 /***********************************************************************
815 * FTP_FtpFindFirstFileW (Internal)
817 * Search the specified directory
820 * HINTERNET on success
824 static HINTERNET FTP_FtpFindFirstFileW(ftp_session_t *lpwfs,
825 LPCWSTR lpszSearchFile, LPWIN32_FIND_DATAW lpFindFileData, DWORD dwFlags, DWORD_PTR dwContext)
828 appinfo_t *hIC = NULL;
829 HINTERNET hFindNext = NULL;
833 /* Clear any error information */
834 INTERNET_SetLastError(0);
836 if (!FTP_InitListenSocket(lpwfs))
839 if (!FTP_SendType(lpwfs, INTERNET_FLAG_TRANSFER_ASCII))
842 if (!FTP_SendPortOrPasv(lpwfs))
845 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_LIST, NULL,
846 lpwfs->hdr.lpfnStatusCB, &lpwfs->hdr, lpwfs->hdr.dwContext))
849 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
852 if (nResCode == 125 || nResCode == 150)
856 /* Get data socket to server */
857 if (FTP_GetDataSocket(lpwfs, &nDataSocket))
859 hFindNext = FTP_ReceiveFileList(lpwfs, nDataSocket, lpszSearchFile, lpFindFileData, dwContext);
860 closesocket(nDataSocket);
861 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
862 if (nResCode != 226 && nResCode != 250)
863 INTERNET_SetLastError(ERROR_NO_MORE_FILES);
867 FTP_SetResponseError(nResCode);
871 if (lpwfs->lstnSocket != -1)
873 closesocket(lpwfs->lstnSocket);
874 lpwfs->lstnSocket = -1;
877 hIC = lpwfs->lpAppInfo;
878 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
880 INTERNET_ASYNC_RESULT iar;
884 iar.dwResult = (DWORD_PTR)hFindNext;
885 iar.dwError = ERROR_SUCCESS;
886 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_HANDLE_CREATED,
887 &iar, sizeof(INTERNET_ASYNC_RESULT));
890 iar.dwResult = (DWORD_PTR)hFindNext;
891 iar.dwError = hFindNext ? ERROR_SUCCESS : INTERNET_GetLastError();
892 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
893 &iar, sizeof(INTERNET_ASYNC_RESULT));
900 /***********************************************************************
901 * FtpGetCurrentDirectoryA (WININET.@)
903 * Retrieves the current directory
910 BOOL WINAPI FtpGetCurrentDirectoryA(HINTERNET hFtpSession, LPSTR lpszCurrentDirectory,
911 LPDWORD lpdwCurrentDirectory)
917 if(lpdwCurrentDirectory) {
918 len = *lpdwCurrentDirectory;
919 if(lpszCurrentDirectory)
921 dir = heap_alloc(len * sizeof(WCHAR));
924 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
929 ret = FtpGetCurrentDirectoryW(hFtpSession, lpszCurrentDirectory?dir:NULL, lpdwCurrentDirectory?&len:NULL);
931 if (ret && lpszCurrentDirectory)
932 WideCharToMultiByte(CP_ACP, 0, dir, -1, lpszCurrentDirectory, len, NULL, NULL);
934 if (lpdwCurrentDirectory) *lpdwCurrentDirectory = len;
940 static void AsyncFtpGetCurrentDirectoryProc(WORKREQUEST *workRequest)
942 struct WORKREQ_FTPGETCURRENTDIRECTORYW const *req = &workRequest->u.FtpGetCurrentDirectoryW;
943 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
945 TRACE("%p\n", lpwfs);
947 FTP_FtpGetCurrentDirectoryW(lpwfs, req->lpszDirectory, req->lpdwDirectory);
950 /***********************************************************************
951 * FtpGetCurrentDirectoryW (WININET.@)
953 * Retrieves the current directory
960 BOOL WINAPI FtpGetCurrentDirectoryW(HINTERNET hFtpSession, LPWSTR lpszCurrentDirectory,
961 LPDWORD lpdwCurrentDirectory)
963 ftp_session_t *lpwfs;
964 appinfo_t *hIC = NULL;
967 TRACE("%p %p %p\n", hFtpSession, lpszCurrentDirectory, lpdwCurrentDirectory);
969 lpwfs = (ftp_session_t*) get_handle_object( hFtpSession );
972 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
976 if (WH_HFTPSESSION != lpwfs->hdr.htype)
978 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
982 if (!lpdwCurrentDirectory)
984 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
988 if (lpszCurrentDirectory == NULL)
990 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
994 if (lpwfs->download_in_progress != NULL)
996 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
1000 hIC = lpwfs->lpAppInfo;
1001 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1004 struct WORKREQ_FTPGETCURRENTDIRECTORYW *req;
1006 task = alloc_async_task(&lpwfs->hdr, AsyncFtpGetCurrentDirectoryProc, sizeof(*task));
1007 req = &task->u.FtpGetCurrentDirectoryW;
1008 req->lpszDirectory = lpszCurrentDirectory;
1009 req->lpdwDirectory = lpdwCurrentDirectory;
1011 r = res_to_le(INTERNET_AsyncCall(task));
1015 r = FTP_FtpGetCurrentDirectoryW(lpwfs, lpszCurrentDirectory,
1016 lpdwCurrentDirectory);
1021 WININET_Release( &lpwfs->hdr );
1027 /***********************************************************************
1028 * FTP_FtpGetCurrentDirectoryW (Internal)
1030 * Retrieves the current directory
1037 static BOOL FTP_FtpGetCurrentDirectoryW(ftp_session_t *lpwfs, LPWSTR lpszCurrentDirectory,
1038 LPDWORD lpdwCurrentDirectory)
1041 appinfo_t *hIC = NULL;
1042 DWORD bSuccess = FALSE;
1044 /* Clear any error information */
1045 INTERNET_SetLastError(0);
1047 hIC = lpwfs->lpAppInfo;
1048 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_PWD, NULL,
1049 lpwfs->hdr.lpfnStatusCB, &lpwfs->hdr, lpwfs->hdr.dwContext))
1052 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
1055 if (nResCode == 257) /* Extract directory name */
1057 DWORD firstpos, lastpos, len;
1058 LPWSTR lpszResponseBuffer = heap_strdupAtoW(INTERNET_GetResponseBuffer());
1060 for (firstpos = 0, lastpos = 0; lpszResponseBuffer[lastpos]; lastpos++)
1062 if ('"' == lpszResponseBuffer[lastpos])
1070 len = lastpos - firstpos;
1071 if (*lpdwCurrentDirectory >= len)
1073 memcpy(lpszCurrentDirectory, &lpszResponseBuffer[firstpos + 1], len * sizeof(WCHAR));
1074 lpszCurrentDirectory[len - 1] = 0;
1075 *lpdwCurrentDirectory = len;
1078 else INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1080 heap_free(lpszResponseBuffer);
1083 FTP_SetResponseError(nResCode);
1087 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1089 INTERNET_ASYNC_RESULT iar;
1091 iar.dwResult = bSuccess;
1092 iar.dwError = bSuccess ? ERROR_SUCCESS : ERROR_INTERNET_EXTENDED_ERROR;
1093 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1094 &iar, sizeof(INTERNET_ASYNC_RESULT));
1101 /***********************************************************************
1102 * FTPFILE_Destroy(internal)
1104 * Closes the file transfer handle. This also 'cleans' the data queue of
1105 * the 'transfer complete' message (this is a bit of a hack though :-/ )
1108 static void FTPFILE_Destroy(object_header_t *hdr)
1110 ftp_file_t *lpwh = (ftp_file_t*) hdr;
1111 ftp_session_t *lpwfs = lpwh->lpFtpSession;
1116 if (lpwh->cache_file_handle != INVALID_HANDLE_VALUE)
1117 CloseHandle(lpwh->cache_file_handle);
1119 heap_free(lpwh->cache_file);
1121 if (!lpwh->session_deleted)
1122 lpwfs->download_in_progress = NULL;
1124 if (lpwh->nDataSocket != -1)
1125 closesocket(lpwh->nDataSocket);
1127 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
1128 if (nResCode > 0 && nResCode != 226) WARN("server reports failed transfer\n");
1130 WININET_Release(&lpwh->lpFtpSession->hdr);
1133 static DWORD FTPFILE_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1136 case INTERNET_OPTION_HANDLE_TYPE:
1137 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
1139 if (*size < sizeof(ULONG))
1140 return ERROR_INSUFFICIENT_BUFFER;
1142 *size = sizeof(DWORD);
1143 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_FTP_FILE;
1144 return ERROR_SUCCESS;
1145 case INTERNET_OPTION_DATAFILE_NAME:
1148 ftp_file_t *file = (ftp_file_t *)hdr;
1150 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
1152 if (!file->cache_file)
1155 return ERROR_INTERNET_ITEM_NOT_FOUND;
1159 required = (lstrlenW(file->cache_file) + 1) * sizeof(WCHAR);
1160 if (*size < required)
1161 return ERROR_INSUFFICIENT_BUFFER;
1164 memcpy(buffer, file->cache_file, *size);
1165 return ERROR_SUCCESS;
1169 required = WideCharToMultiByte(CP_ACP, 0, file->cache_file, -1, NULL, 0, NULL, NULL);
1170 if (required > *size)
1171 return ERROR_INSUFFICIENT_BUFFER;
1173 *size = WideCharToMultiByte(CP_ACP, 0, file->cache_file, -1, buffer, *size, NULL, NULL);
1174 return ERROR_SUCCESS;
1178 return INET_QueryOption(hdr, option, buffer, size, unicode);
1181 static DWORD FTPFILE_ReadFile(object_header_t *hdr, void *buffer, DWORD size, DWORD *read)
1183 ftp_file_t *file = (ftp_file_t*)hdr;
1187 if (file->nDataSocket == -1)
1188 return ERROR_INTERNET_DISCONNECTED;
1190 /* FIXME: FTP should use NETCON_ stuff */
1191 res = recv(file->nDataSocket, buffer, size, MSG_WAITALL);
1192 *read = res>0 ? res : 0;
1194 error = res >= 0 ? ERROR_SUCCESS : INTERNET_ERROR_BASE; /* FIXME */
1195 if (error == ERROR_SUCCESS && file->cache_file)
1197 DWORD bytes_written;
1199 if (!WriteFile(file->cache_file_handle, buffer, *read, &bytes_written, NULL))
1200 WARN("WriteFile failed: %u\n", GetLastError());
1205 static DWORD FTPFILE_ReadFileEx(object_header_t *hdr, void *buf, DWORD size, DWORD *ret_size,
1206 DWORD flags, DWORD_PTR context)
1208 return FTPFILE_ReadFile(hdr, buf, size, ret_size);
1211 static DWORD FTPFILE_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
1213 ftp_file_t *lpwh = (ftp_file_t*) hdr;
1216 res = send(lpwh->nDataSocket, buffer, size, 0);
1218 *written = res>0 ? res : 0;
1219 return res >= 0 ? ERROR_SUCCESS : sock_get_error(errno);
1222 static void FTP_ReceiveRequestData(ftp_file_t *file, BOOL first_notif)
1224 INTERNET_ASYNC_RESULT iar;
1228 TRACE("%p\n", file);
1230 available = recv(file->nDataSocket, buffer, sizeof(buffer), MSG_PEEK);
1232 if(available != -1) {
1233 iar.dwResult = (DWORD_PTR)file->hdr.hInternet;
1234 iar.dwError = first_notif ? 0 : available;
1237 iar.dwError = INTERNET_GetLastError();
1240 INTERNET_SendCallback(&file->hdr, file->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1241 sizeof(INTERNET_ASYNC_RESULT));
1244 static void FTPFILE_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1246 ftp_file_t *file = (ftp_file_t*)workRequest->hdr;
1248 FTP_ReceiveRequestData(file, FALSE);
1251 static DWORD FTPFILE_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1253 ftp_file_t *file = (ftp_file_t*) hdr;
1254 int retval, unread = 0;
1256 TRACE("(%p %p %x %lx)\n", file, available, flags, ctx);
1259 retval = ioctlsocket(file->nDataSocket, FIONREAD, &unread);
1261 TRACE("%d bytes of queued, but unread data\n", unread);
1263 FIXME("FIONREAD not available\n");
1266 *available = unread;
1273 retval = recv(file->nDataSocket, &byte, 1, MSG_PEEK);
1275 task_header_t *task;
1277 task = alloc_async_task(&file->hdr, FTPFILE_AsyncQueryDataAvailableProc, sizeof(*task));
1278 INTERNET_AsyncCall(task);
1281 return ERROR_IO_PENDING;
1285 return ERROR_SUCCESS;
1289 static const object_vtbl_t FTPFILEVtbl = {
1292 FTPFILE_QueryOption,
1297 FTPFILE_QueryDataAvailable,
1301 /***********************************************************************
1302 * FTP_FtpOpenFileW (Internal)
1304 * Open a remote file for writing or reading
1307 * HINTERNET handle on success
1311 static HINTERNET FTP_FtpOpenFileW(ftp_session_t *lpwfs,
1312 LPCWSTR lpszFileName, DWORD fdwAccess, DWORD dwFlags,
1313 DWORD_PTR dwContext)
1316 BOOL bSuccess = FALSE;
1317 ftp_file_t *lpwh = NULL;
1318 appinfo_t *hIC = NULL;
1322 /* Clear any error information */
1323 INTERNET_SetLastError(0);
1325 if (GENERIC_READ == fdwAccess)
1327 /* Set up socket to retrieve data */
1328 bSuccess = FTP_SendRetrieve(lpwfs, lpszFileName, dwFlags);
1330 else if (GENERIC_WRITE == fdwAccess)
1332 /* Set up socket to send data */
1333 bSuccess = FTP_SendStore(lpwfs, lpszFileName, dwFlags);
1336 /* Get data socket to server */
1337 if (bSuccess && FTP_GetDataSocket(lpwfs, &nDataSocket))
1339 lpwh = alloc_object(&lpwfs->hdr, &FTPFILEVtbl, sizeof(ftp_file_t));
1340 lpwh->hdr.htype = WH_HFILE;
1341 lpwh->hdr.dwFlags = dwFlags;
1342 lpwh->hdr.dwContext = dwContext;
1343 lpwh->nDataSocket = nDataSocket;
1344 lpwh->cache_file = NULL;
1345 lpwh->cache_file_handle = INVALID_HANDLE_VALUE;
1346 lpwh->session_deleted = FALSE;
1348 WININET_AddRef( &lpwfs->hdr );
1349 lpwh->lpFtpSession = lpwfs;
1350 list_add_head( &lpwfs->hdr.children, &lpwh->hdr.entry );
1352 /* Indicate that a download is currently in progress */
1353 lpwfs->download_in_progress = lpwh;
1356 if (lpwfs->lstnSocket != -1)
1358 closesocket(lpwfs->lstnSocket);
1359 lpwfs->lstnSocket = -1;
1362 if (bSuccess && fdwAccess == GENERIC_READ)
1364 WCHAR filename[MAX_PATH + 1];
1368 memset(&uc, 0, sizeof(uc));
1369 uc.dwStructSize = sizeof(uc);
1370 uc.nScheme = INTERNET_SCHEME_FTP;
1371 uc.lpszHostName = lpwfs->servername;
1372 uc.nPort = lpwfs->serverport;
1373 uc.lpszUserName = lpwfs->lpszUserName;
1374 uc.lpszUrlPath = heap_strdupW(lpszFileName);
1376 if (!InternetCreateUrlW(&uc, 0, NULL, &len) && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
1378 WCHAR *url = heap_alloc(len * sizeof(WCHAR));
1380 if (url && InternetCreateUrlW(&uc, 0, url, &len) && CreateUrlCacheEntryW(url, 0, NULL, filename, 0))
1382 lpwh->cache_file = heap_strdupW(filename);
1383 lpwh->cache_file_handle = CreateFileW(filename, GENERIC_WRITE, FILE_SHARE_READ,
1384 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1385 if (lpwh->cache_file_handle == INVALID_HANDLE_VALUE)
1387 WARN("Could not create cache file: %u\n", GetLastError());
1388 heap_free(lpwh->cache_file);
1389 lpwh->cache_file = NULL;
1394 heap_free(uc.lpszUrlPath);
1397 hIC = lpwfs->lpAppInfo;
1398 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1400 INTERNET_ASYNC_RESULT iar;
1404 iar.dwResult = (DWORD_PTR)lpwh->hdr.hInternet;
1405 iar.dwError = ERROR_SUCCESS;
1406 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_HANDLE_CREATED,
1407 &iar, sizeof(INTERNET_ASYNC_RESULT));
1411 FTP_ReceiveRequestData(lpwh, TRUE);
1414 iar.dwError = INTERNET_GetLastError();
1415 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1416 &iar, sizeof(INTERNET_ASYNC_RESULT));
1423 return lpwh->hdr.hInternet;
1427 /***********************************************************************
1428 * FtpOpenFileA (WININET.@)
1430 * Open a remote file for writing or reading
1433 * HINTERNET handle on success
1437 HINTERNET WINAPI FtpOpenFileA(HINTERNET hFtpSession,
1438 LPCSTR lpszFileName, DWORD fdwAccess, DWORD dwFlags,
1439 DWORD_PTR dwContext)
1441 LPWSTR lpwzFileName;
1444 lpwzFileName = heap_strdupAtoW(lpszFileName);
1445 ret = FtpOpenFileW(hFtpSession, lpwzFileName, fdwAccess, dwFlags, dwContext);
1446 heap_free(lpwzFileName);
1451 static void AsyncFtpOpenFileProc(WORKREQUEST *workRequest)
1453 struct WORKREQ_FTPOPENFILEW const *req = &workRequest->u.FtpOpenFileW;
1454 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
1456 TRACE("%p\n", lpwfs);
1458 FTP_FtpOpenFileW(lpwfs, req->lpszFilename,
1459 req->dwAccess, req->dwFlags, req->dwContext);
1460 heap_free(req->lpszFilename);
1463 /***********************************************************************
1464 * FtpOpenFileW (WININET.@)
1466 * Open a remote file for writing or reading
1469 * HINTERNET handle on success
1473 HINTERNET WINAPI FtpOpenFileW(HINTERNET hFtpSession,
1474 LPCWSTR lpszFileName, DWORD fdwAccess, DWORD dwFlags,
1475 DWORD_PTR dwContext)
1477 ftp_session_t *lpwfs;
1478 appinfo_t *hIC = NULL;
1481 TRACE("(%p,%s,0x%08x,0x%08x,0x%08lx)\n", hFtpSession,
1482 debugstr_w(lpszFileName), fdwAccess, dwFlags, dwContext);
1484 lpwfs = (ftp_session_t*) get_handle_object( hFtpSession );
1487 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
1491 if (WH_HFTPSESSION != lpwfs->hdr.htype)
1493 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1497 if ((!lpszFileName) ||
1498 ((fdwAccess != GENERIC_READ) && (fdwAccess != GENERIC_WRITE)) ||
1499 ((dwFlags & FTP_CONDITION_MASK) > FTP_TRANSFER_TYPE_BINARY))
1501 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1505 if (lpwfs->download_in_progress != NULL)
1507 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
1511 hIC = lpwfs->lpAppInfo;
1512 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1515 struct WORKREQ_FTPOPENFILEW *req;
1517 task = alloc_async_task(&lpwfs->hdr, AsyncFtpOpenFileProc, sizeof(*task));
1518 req = &task->u.FtpOpenFileW;
1519 req->lpszFilename = heap_strdupW(lpszFileName);
1520 req->dwAccess = fdwAccess;
1521 req->dwFlags = dwFlags;
1522 req->dwContext = dwContext;
1524 INTERNET_AsyncCall(task);
1529 r = FTP_FtpOpenFileW(lpwfs, lpszFileName, fdwAccess, dwFlags, dwContext);
1533 WININET_Release( &lpwfs->hdr );
1539 /***********************************************************************
1540 * FtpGetFileA (WININET.@)
1542 * Retrieve file from the FTP server
1549 BOOL WINAPI FtpGetFileA(HINTERNET hInternet, LPCSTR lpszRemoteFile, LPCSTR lpszNewFile,
1550 BOOL fFailIfExists, DWORD dwLocalFlagsAttribute, DWORD dwInternetFlags,
1551 DWORD_PTR dwContext)
1553 LPWSTR lpwzRemoteFile;
1557 lpwzRemoteFile = heap_strdupAtoW(lpszRemoteFile);
1558 lpwzNewFile = heap_strdupAtoW(lpszNewFile);
1559 ret = FtpGetFileW(hInternet, lpwzRemoteFile, lpwzNewFile, fFailIfExists,
1560 dwLocalFlagsAttribute, dwInternetFlags, dwContext);
1561 heap_free(lpwzRemoteFile);
1562 heap_free(lpwzNewFile);
1567 static void AsyncFtpGetFileProc(WORKREQUEST *workRequest)
1569 struct WORKREQ_FTPGETFILEW const *req = &workRequest->u.FtpGetFileW;
1570 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
1572 TRACE("%p\n", lpwfs);
1574 FTP_FtpGetFileW(lpwfs, req->lpszRemoteFile,
1575 req->lpszNewFile, req->fFailIfExists,
1576 req->dwLocalFlagsAttribute, req->dwFlags, req->dwContext);
1577 heap_free(req->lpszRemoteFile);
1578 heap_free(req->lpszNewFile);
1582 /***********************************************************************
1583 * FtpGetFileW (WININET.@)
1585 * Retrieve file from the FTP server
1592 BOOL WINAPI FtpGetFileW(HINTERNET hInternet, LPCWSTR lpszRemoteFile, LPCWSTR lpszNewFile,
1593 BOOL fFailIfExists, DWORD dwLocalFlagsAttribute, DWORD dwInternetFlags,
1594 DWORD_PTR dwContext)
1596 ftp_session_t *lpwfs;
1597 appinfo_t *hIC = NULL;
1600 if (!lpszRemoteFile || !lpszNewFile)
1602 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1606 lpwfs = (ftp_session_t*) get_handle_object( hInternet );
1609 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
1613 if (WH_HFTPSESSION != lpwfs->hdr.htype)
1615 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1619 if ((dwInternetFlags & FTP_CONDITION_MASK) > FTP_TRANSFER_TYPE_BINARY)
1621 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1625 if (lpwfs->download_in_progress != NULL)
1627 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
1631 hIC = lpwfs->lpAppInfo;
1632 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1635 struct WORKREQ_FTPGETFILEW *req;
1637 task = alloc_async_task(&lpwfs->hdr, AsyncFtpGetFileProc, sizeof(*task));
1638 req = &task->u.FtpGetFileW;
1639 req->lpszRemoteFile = heap_strdupW(lpszRemoteFile);
1640 req->lpszNewFile = heap_strdupW(lpszNewFile);
1641 req->dwLocalFlagsAttribute = dwLocalFlagsAttribute;
1642 req->fFailIfExists = fFailIfExists;
1643 req->dwFlags = dwInternetFlags;
1644 req->dwContext = dwContext;
1646 r = res_to_le(INTERNET_AsyncCall(task));
1650 r = FTP_FtpGetFileW(lpwfs, lpszRemoteFile, lpszNewFile,
1651 fFailIfExists, dwLocalFlagsAttribute, dwInternetFlags, dwContext);
1655 WININET_Release( &lpwfs->hdr );
1661 /***********************************************************************
1662 * FTP_FtpGetFileW (Internal)
1664 * Retrieve file from the FTP server
1671 static BOOL FTP_FtpGetFileW(ftp_session_t *lpwfs, LPCWSTR lpszRemoteFile, LPCWSTR lpszNewFile,
1672 BOOL fFailIfExists, DWORD dwLocalFlagsAttribute, DWORD dwInternetFlags,
1673 DWORD_PTR dwContext)
1675 BOOL bSuccess = FALSE;
1677 appinfo_t *hIC = NULL;
1679 TRACE("lpszRemoteFile(%s) lpszNewFile(%s)\n", debugstr_w(lpszRemoteFile), debugstr_w(lpszNewFile));
1681 /* Clear any error information */
1682 INTERNET_SetLastError(0);
1684 /* Ensure we can write to lpszNewfile by opening it */
1685 hFile = CreateFileW(lpszNewFile, GENERIC_WRITE, 0, 0, fFailIfExists ?
1686 CREATE_NEW : CREATE_ALWAYS, dwLocalFlagsAttribute, 0);
1687 if (INVALID_HANDLE_VALUE == hFile)
1690 /* Set up socket to retrieve data */
1691 if (FTP_SendRetrieve(lpwfs, lpszRemoteFile, dwInternetFlags))
1695 /* Get data socket to server */
1696 if (FTP_GetDataSocket(lpwfs, &nDataSocket))
1701 FTP_RetrieveFileData(lpwfs, nDataSocket, hFile);
1702 closesocket(nDataSocket);
1704 nResCode = FTP_ReceiveResponse(lpwfs, dwContext);
1707 if (nResCode == 226)
1710 FTP_SetResponseError(nResCode);
1715 if (lpwfs->lstnSocket != -1)
1717 closesocket(lpwfs->lstnSocket);
1718 lpwfs->lstnSocket = -1;
1723 hIC = lpwfs->lpAppInfo;
1724 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1726 INTERNET_ASYNC_RESULT iar;
1728 iar.dwResult = (DWORD)bSuccess;
1729 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
1730 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1731 &iar, sizeof(INTERNET_ASYNC_RESULT));
1734 if (!bSuccess) DeleteFileW(lpszNewFile);
1738 /***********************************************************************
1739 * FtpGetFileSize (WININET.@)
1741 DWORD WINAPI FtpGetFileSize( HINTERNET hFile, LPDWORD lpdwFileSizeHigh )
1743 FIXME("(%p, %p)\n", hFile, lpdwFileSizeHigh);
1745 if (lpdwFileSizeHigh)
1746 *lpdwFileSizeHigh = 0;
1751 /***********************************************************************
1752 * FtpDeleteFileA (WININET.@)
1754 * Delete a file on the ftp server
1761 BOOL WINAPI FtpDeleteFileA(HINTERNET hFtpSession, LPCSTR lpszFileName)
1763 LPWSTR lpwzFileName;
1766 lpwzFileName = heap_strdupAtoW(lpszFileName);
1767 ret = FtpDeleteFileW(hFtpSession, lpwzFileName);
1768 heap_free(lpwzFileName);
1772 static void AsyncFtpDeleteFileProc(WORKREQUEST *workRequest)
1774 struct WORKREQ_FTPDELETEFILEW const *req = &workRequest->u.FtpDeleteFileW;
1775 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
1777 TRACE("%p\n", lpwfs);
1779 FTP_FtpDeleteFileW(lpwfs, req->lpszFilename);
1780 heap_free(req->lpszFilename);
1783 /***********************************************************************
1784 * FtpDeleteFileW (WININET.@)
1786 * Delete a file on the ftp server
1793 BOOL WINAPI FtpDeleteFileW(HINTERNET hFtpSession, LPCWSTR lpszFileName)
1795 ftp_session_t *lpwfs;
1796 appinfo_t *hIC = NULL;
1799 lpwfs = (ftp_session_t*) get_handle_object( hFtpSession );
1802 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
1806 if (WH_HFTPSESSION != lpwfs->hdr.htype)
1808 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1812 if (lpwfs->download_in_progress != NULL)
1814 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
1820 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1824 hIC = lpwfs->lpAppInfo;
1825 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1828 struct WORKREQ_FTPDELETEFILEW *req;
1830 task = alloc_async_task(&lpwfs->hdr, AsyncFtpDeleteFileProc, sizeof(*task));
1831 req = &task->u.FtpDeleteFileW;
1832 req->lpszFilename = heap_strdupW(lpszFileName);
1834 r = res_to_le(INTERNET_AsyncCall(task));
1838 r = FTP_FtpDeleteFileW(lpwfs, lpszFileName);
1842 WININET_Release( &lpwfs->hdr );
1847 /***********************************************************************
1848 * FTP_FtpDeleteFileW (Internal)
1850 * Delete a file on the ftp server
1857 BOOL FTP_FtpDeleteFileW(ftp_session_t *lpwfs, LPCWSTR lpszFileName)
1860 BOOL bSuccess = FALSE;
1861 appinfo_t *hIC = NULL;
1863 TRACE("%p\n", lpwfs);
1865 /* Clear any error information */
1866 INTERNET_SetLastError(0);
1868 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_DELE, lpszFileName, 0, 0, 0))
1871 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
1874 if (nResCode == 250)
1877 FTP_SetResponseError(nResCode);
1880 hIC = lpwfs->lpAppInfo;
1881 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1883 INTERNET_ASYNC_RESULT iar;
1885 iar.dwResult = (DWORD)bSuccess;
1886 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
1887 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1888 &iar, sizeof(INTERNET_ASYNC_RESULT));
1895 /***********************************************************************
1896 * FtpRemoveDirectoryA (WININET.@)
1898 * Remove a directory on the ftp server
1905 BOOL WINAPI FtpRemoveDirectoryA(HINTERNET hFtpSession, LPCSTR lpszDirectory)
1907 LPWSTR lpwzDirectory;
1910 lpwzDirectory = heap_strdupAtoW(lpszDirectory);
1911 ret = FtpRemoveDirectoryW(hFtpSession, lpwzDirectory);
1912 heap_free(lpwzDirectory);
1916 static void AsyncFtpRemoveDirectoryProc(WORKREQUEST *workRequest)
1918 struct WORKREQ_FTPREMOVEDIRECTORYW const *req = &workRequest->u.FtpRemoveDirectoryW;
1919 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
1921 TRACE("%p\n", lpwfs);
1923 FTP_FtpRemoveDirectoryW(lpwfs, req->lpszDirectory);
1924 heap_free(req->lpszDirectory);
1927 /***********************************************************************
1928 * FtpRemoveDirectoryW (WININET.@)
1930 * Remove a directory on the ftp server
1937 BOOL WINAPI FtpRemoveDirectoryW(HINTERNET hFtpSession, LPCWSTR lpszDirectory)
1939 ftp_session_t *lpwfs;
1940 appinfo_t *hIC = NULL;
1943 lpwfs = (ftp_session_t*) get_handle_object( hFtpSession );
1946 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
1950 if (WH_HFTPSESSION != lpwfs->hdr.htype)
1952 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1956 if (lpwfs->download_in_progress != NULL)
1958 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
1964 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1968 hIC = lpwfs->lpAppInfo;
1969 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1972 struct WORKREQ_FTPREMOVEDIRECTORYW *req;
1974 task = alloc_async_task(&lpwfs->hdr, AsyncFtpRemoveDirectoryProc, sizeof(*task));
1975 req = &task->u.FtpRemoveDirectoryW;
1976 req->lpszDirectory = heap_strdupW(lpszDirectory);
1978 r = res_to_le(INTERNET_AsyncCall(task));
1982 r = FTP_FtpRemoveDirectoryW(lpwfs, lpszDirectory);
1986 WININET_Release( &lpwfs->hdr );
1991 /***********************************************************************
1992 * FTP_FtpRemoveDirectoryW (Internal)
1994 * Remove a directory on the ftp server
2001 BOOL FTP_FtpRemoveDirectoryW(ftp_session_t *lpwfs, LPCWSTR lpszDirectory)
2004 BOOL bSuccess = FALSE;
2005 appinfo_t *hIC = NULL;
2009 /* Clear any error information */
2010 INTERNET_SetLastError(0);
2012 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_RMD, lpszDirectory, 0, 0, 0))
2015 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2018 if (nResCode == 250)
2021 FTP_SetResponseError(nResCode);
2025 hIC = lpwfs->lpAppInfo;
2026 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2028 INTERNET_ASYNC_RESULT iar;
2030 iar.dwResult = (DWORD)bSuccess;
2031 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
2032 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
2033 &iar, sizeof(INTERNET_ASYNC_RESULT));
2040 /***********************************************************************
2041 * FtpRenameFileA (WININET.@)
2043 * Rename a file on the ftp server
2050 BOOL WINAPI FtpRenameFileA(HINTERNET hFtpSession, LPCSTR lpszSrc, LPCSTR lpszDest)
2056 lpwzSrc = heap_strdupAtoW(lpszSrc);
2057 lpwzDest = heap_strdupAtoW(lpszDest);
2058 ret = FtpRenameFileW(hFtpSession, lpwzSrc, lpwzDest);
2060 heap_free(lpwzDest);
2064 static void AsyncFtpRenameFileProc(WORKREQUEST *workRequest)
2066 struct WORKREQ_FTPRENAMEFILEW const *req = &workRequest->u.FtpRenameFileW;
2067 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
2069 TRACE("%p\n", lpwfs);
2071 FTP_FtpRenameFileW(lpwfs, req->lpszSrcFile, req->lpszDestFile);
2072 heap_free(req->lpszSrcFile);
2073 heap_free(req->lpszDestFile);
2076 /***********************************************************************
2077 * FtpRenameFileW (WININET.@)
2079 * Rename a file on the ftp server
2086 BOOL WINAPI FtpRenameFileW(HINTERNET hFtpSession, LPCWSTR lpszSrc, LPCWSTR lpszDest)
2088 ftp_session_t *lpwfs;
2089 appinfo_t *hIC = NULL;
2092 lpwfs = (ftp_session_t*) get_handle_object( hFtpSession );
2095 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
2099 if (WH_HFTPSESSION != lpwfs->hdr.htype)
2101 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2105 if (lpwfs->download_in_progress != NULL)
2107 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
2111 if (!lpszSrc || !lpszDest)
2113 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2117 hIC = lpwfs->lpAppInfo;
2118 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2121 struct WORKREQ_FTPRENAMEFILEW *req;
2123 task = alloc_async_task(&lpwfs->hdr, AsyncFtpRenameFileProc, sizeof(*task));
2124 req = &task->u.FtpRenameFileW;
2125 req->lpszSrcFile = heap_strdupW(lpszSrc);
2126 req->lpszDestFile = heap_strdupW(lpszDest);
2128 r = res_to_le(INTERNET_AsyncCall(task));
2132 r = FTP_FtpRenameFileW(lpwfs, lpszSrc, lpszDest);
2136 WININET_Release( &lpwfs->hdr );
2141 /***********************************************************************
2142 * FTP_FtpRenameFileW (Internal)
2144 * Rename a file on the ftp server
2151 BOOL FTP_FtpRenameFileW(ftp_session_t *lpwfs, LPCWSTR lpszSrc, LPCWSTR lpszDest)
2154 BOOL bSuccess = FALSE;
2155 appinfo_t *hIC = NULL;
2159 /* Clear any error information */
2160 INTERNET_SetLastError(0);
2162 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_RNFR, lpszSrc, 0, 0, 0))
2165 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2166 if (nResCode == 350)
2168 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_RNTO, lpszDest, 0, 0, 0))
2171 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2174 if (nResCode == 250)
2177 FTP_SetResponseError(nResCode);
2180 hIC = lpwfs->lpAppInfo;
2181 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2183 INTERNET_ASYNC_RESULT iar;
2185 iar.dwResult = (DWORD)bSuccess;
2186 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
2187 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
2188 &iar, sizeof(INTERNET_ASYNC_RESULT));
2194 /***********************************************************************
2195 * FtpCommandA (WININET.@)
2197 BOOL WINAPI FtpCommandA( HINTERNET hConnect, BOOL fExpectResponse, DWORD dwFlags,
2198 LPCSTR lpszCommand, DWORD_PTR dwContext, HINTERNET* phFtpCommand )
2203 TRACE("%p %d 0x%08x %s 0x%08lx %p\n", hConnect, fExpectResponse, dwFlags,
2204 debugstr_a(lpszCommand), dwContext, phFtpCommand);
2206 if (fExpectResponse)
2208 FIXME("data connection not supported\n");
2212 if (!lpszCommand || !lpszCommand[0])
2214 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2218 if (!(cmdW = heap_strdupAtoW(lpszCommand)))
2220 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2224 r = FtpCommandW(hConnect, fExpectResponse, dwFlags, cmdW, dwContext, phFtpCommand);
2230 /***********************************************************************
2231 * FtpCommandW (WININET.@)
2233 BOOL WINAPI FtpCommandW( HINTERNET hConnect, BOOL fExpectResponse, DWORD dwFlags,
2234 LPCWSTR lpszCommand, DWORD_PTR dwContext, HINTERNET* phFtpCommand )
2237 ftp_session_t *lpwfs;
2239 DWORD len, nBytesSent= 0;
2240 INT nResCode, nRC = 0;
2242 TRACE("%p %d 0x%08x %s 0x%08lx %p\n", hConnect, fExpectResponse, dwFlags,
2243 debugstr_w(lpszCommand), dwContext, phFtpCommand);
2245 if (!lpszCommand || !lpszCommand[0])
2247 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2251 if (fExpectResponse)
2253 FIXME("data connection not supported\n");
2257 lpwfs = (ftp_session_t*) get_handle_object( hConnect );
2260 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
2264 if (WH_HFTPSESSION != lpwfs->hdr.htype)
2266 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2270 if (lpwfs->download_in_progress != NULL)
2272 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
2276 len = WideCharToMultiByte(CP_ACP, 0, lpszCommand, -1, NULL, 0, NULL, NULL) + strlen(szCRLF);
2277 if ((cmd = heap_alloc(len)))
2278 WideCharToMultiByte(CP_ACP, 0, lpszCommand, -1, cmd, len, NULL, NULL);
2281 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2285 strcat(cmd, szCRLF);
2288 TRACE("Sending (%s) len(%d)\n", cmd, len);
2289 while ((nBytesSent < len) && (nRC != -1))
2291 nRC = send(lpwfs->sndSocket, cmd + nBytesSent, len - nBytesSent, 0);
2295 TRACE("Sent %d bytes\n", nRC);
2301 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2302 if (nResCode > 0 && nResCode < 400)
2305 FTP_SetResponseError(nResCode);
2309 WININET_Release( &lpwfs->hdr );
2315 /***********************************************************************
2316 * FTPSESSION_Destroy (internal)
2318 * Deallocate session handle
2320 static void FTPSESSION_Destroy(object_header_t *hdr)
2322 ftp_session_t *lpwfs = (ftp_session_t*) hdr;
2326 WININET_Release(&lpwfs->lpAppInfo->hdr);
2328 heap_free(lpwfs->lpszPassword);
2329 heap_free(lpwfs->lpszUserName);
2330 heap_free(lpwfs->servername);
2333 static void FTPSESSION_CloseConnection(object_header_t *hdr)
2335 ftp_session_t *lpwfs = (ftp_session_t*) hdr;
2339 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext,
2340 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
2342 if (lpwfs->download_in_progress != NULL)
2343 lpwfs->download_in_progress->session_deleted = TRUE;
2345 if (lpwfs->sndSocket != -1)
2346 closesocket(lpwfs->sndSocket);
2348 if (lpwfs->lstnSocket != -1)
2349 closesocket(lpwfs->lstnSocket);
2351 if (lpwfs->pasvSocket != -1)
2352 closesocket(lpwfs->pasvSocket);
2354 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext,
2355 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
2358 static DWORD FTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2361 case INTERNET_OPTION_HANDLE_TYPE:
2362 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2364 if (*size < sizeof(ULONG))
2365 return ERROR_INSUFFICIENT_BUFFER;
2367 *size = sizeof(DWORD);
2368 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_FTP;
2369 return ERROR_SUCCESS;
2372 return INET_QueryOption(hdr, option, buffer, size, unicode);
2375 static const object_vtbl_t FTPSESSIONVtbl = {
2377 FTPSESSION_CloseConnection,
2378 FTPSESSION_QueryOption,
2388 /***********************************************************************
2389 * FTP_Connect (internal)
2391 * Connect to a ftp server
2394 * HINTERNET a session handle on success
2399 * Windows uses 'anonymous' as the username, when given a NULL username
2400 * and a NULL password. The password is first looked up in:
2402 * HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\EmailName
2404 * If this entry is not present it uses the current username as the password.
2408 HINTERNET FTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
2409 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
2410 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
2411 DWORD dwInternalFlags)
2413 static const WCHAR szKey[] = {'S','o','f','t','w','a','r','e','\\',
2414 'M','i','c','r','o','s','o','f','t','\\',
2415 'W','i','n','d','o','w','s','\\',
2416 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2417 'I','n','t','e','r','n','e','t',' ','S','e','t','t','i','n','g','s',0};
2418 static const WCHAR szValue[] = {'E','m','a','i','l','N','a','m','e',0};
2419 static const WCHAR szDefaultUsername[] = {'a','n','o','n','y','m','o','u','s','\0'};
2420 static const WCHAR szEmpty[] = {'\0'};
2421 struct sockaddr_in socketAddr;
2423 socklen_t sock_namelen;
2424 BOOL bSuccess = FALSE;
2425 ftp_session_t *lpwfs = NULL;
2426 char szaddr[INET_ADDRSTRLEN];
2428 TRACE("%p Server(%s) Port(%d) User(%s) Paswd(%s)\n",
2429 hIC, debugstr_w(lpszServerName),
2430 nServerPort, debugstr_w(lpszUserName), debugstr_w(lpszPassword));
2432 assert( hIC->hdr.htype == WH_HINIT );
2434 if ((!lpszUserName || !*lpszUserName) && lpszPassword && *lpszPassword)
2436 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2440 lpwfs = alloc_object(&hIC->hdr, &FTPSESSIONVtbl, sizeof(ftp_session_t));
2443 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2447 if (nServerPort == INTERNET_INVALID_PORT_NUMBER)
2448 lpwfs->serverport = INTERNET_DEFAULT_FTP_PORT;
2450 lpwfs->serverport = nServerPort;
2452 lpwfs->hdr.htype = WH_HFTPSESSION;
2453 lpwfs->hdr.dwFlags = dwFlags;
2454 lpwfs->hdr.dwContext = dwContext;
2455 lpwfs->hdr.dwInternalFlags |= dwInternalFlags;
2456 lpwfs->download_in_progress = NULL;
2457 lpwfs->sndSocket = -1;
2458 lpwfs->lstnSocket = -1;
2459 lpwfs->pasvSocket = -1;
2461 WININET_AddRef( &hIC->hdr );
2462 lpwfs->lpAppInfo = hIC;
2463 list_add_head( &hIC->hdr.children, &lpwfs->hdr.entry );
2465 if(hIC->proxy && hIC->accessType == INTERNET_OPEN_TYPE_PROXY) {
2466 if(strchrW(hIC->proxy, ' '))
2467 FIXME("Several proxies not implemented.\n");
2468 if(hIC->proxyBypass)
2469 FIXME("Proxy bypass is ignored.\n");
2471 if (!lpszUserName || !strlenW(lpszUserName)) {
2473 WCHAR szPassword[MAX_PATH];
2474 DWORD len = sizeof(szPassword);
2476 lpwfs->lpszUserName = heap_strdupW(szDefaultUsername);
2478 RegOpenKeyW(HKEY_CURRENT_USER, szKey, &key);
2479 if (RegQueryValueExW(key, szValue, NULL, NULL, (LPBYTE)szPassword, &len)) {
2480 /* Nothing in the registry, get the username and use that as the password */
2481 if (!GetUserNameW(szPassword, &len)) {
2482 /* Should never get here, but use an empty password as failsafe */
2483 strcpyW(szPassword, szEmpty);
2488 TRACE("Password used for anonymous ftp : (%s)\n", debugstr_w(szPassword));
2489 lpwfs->lpszPassword = heap_strdupW(szPassword);
2492 lpwfs->lpszUserName = heap_strdupW(lpszUserName);
2493 lpwfs->lpszPassword = heap_strdupW(lpszPassword ? lpszPassword : szEmpty);
2495 lpwfs->servername = heap_strdupW(lpszServerName);
2497 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
2498 if (!(lpwfs->hdr.dwInternalFlags & INET_OPENURL))
2500 INTERNET_ASYNC_RESULT iar;
2502 iar.dwResult = (DWORD_PTR)lpwfs->hdr.hInternet;
2503 iar.dwError = ERROR_SUCCESS;
2505 SendAsyncCallback(&hIC->hdr, dwContext,
2506 INTERNET_STATUS_HANDLE_CREATED, &iar,
2507 sizeof(INTERNET_ASYNC_RESULT));
2510 SendAsyncCallback(&hIC->hdr, dwContext, INTERNET_STATUS_RESOLVING_NAME,
2511 (LPWSTR) lpszServerName, (strlenW(lpszServerName)+1) * sizeof(WCHAR));
2513 sock_namelen = sizeof(socketAddr);
2514 if (!GetAddress(lpszServerName, lpwfs->serverport, (struct sockaddr *)&socketAddr, &sock_namelen))
2516 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
2520 if (socketAddr.sin_family != AF_INET)
2522 WARN("unsupported address family %d\n", socketAddr.sin_family);
2523 INTERNET_SetLastError(ERROR_INTERNET_CANNOT_CONNECT);
2527 inet_ntop(socketAddr.sin_family, &socketAddr.sin_addr, szaddr, sizeof(szaddr));
2528 SendAsyncCallback(&hIC->hdr, dwContext, INTERNET_STATUS_NAME_RESOLVED,
2529 szaddr, strlen(szaddr)+1);
2531 nsocket = socket(AF_INET,SOCK_STREAM,0);
2534 INTERNET_SetLastError(ERROR_INTERNET_CANNOT_CONNECT);
2538 SendAsyncCallback(&hIC->hdr, dwContext, INTERNET_STATUS_CONNECTING_TO_SERVER,
2539 szaddr, strlen(szaddr)+1);
2541 if (connect(nsocket, (struct sockaddr *)&socketAddr, sock_namelen) < 0)
2543 ERR("Unable to connect (%s)\n", strerror(errno));
2544 INTERNET_SetLastError(ERROR_INTERNET_CANNOT_CONNECT);
2545 closesocket(nsocket);
2549 TRACE("Connected to server\n");
2550 lpwfs->sndSocket = nsocket;
2551 SendAsyncCallback(&hIC->hdr, dwContext, INTERNET_STATUS_CONNECTED_TO_SERVER,
2552 szaddr, strlen(szaddr)+1);
2554 sock_namelen = sizeof(lpwfs->socketAddress);
2555 getsockname(nsocket, (struct sockaddr *) &lpwfs->socketAddress, &sock_namelen);
2557 if (FTP_ConnectToHost(lpwfs))
2559 TRACE("Successfully logged into server\n");
2568 WININET_Release( &lpwfs->hdr );
2572 return lpwfs->hdr.hInternet;
2576 /***********************************************************************
2577 * FTP_ConnectToHost (internal)
2579 * Connect to a ftp server
2586 static BOOL FTP_ConnectToHost(ftp_session_t *lpwfs)
2589 BOOL bSuccess = FALSE;
2592 FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2594 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_USER, lpwfs->lpszUserName, 0, 0, 0))
2597 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2600 /* Login successful... */
2601 if (nResCode == 230)
2603 /* User name okay, need password... */
2604 else if (nResCode == 331)
2605 bSuccess = FTP_SendPassword(lpwfs);
2606 /* Need account for login... */
2607 else if (nResCode == 332)
2608 bSuccess = FTP_SendAccount(lpwfs);
2610 FTP_SetResponseError(nResCode);
2613 TRACE("Returning %d\n", bSuccess);
2619 /***********************************************************************
2620 * FTP_SendCommandA (internal)
2622 * Send command to server
2629 static BOOL FTP_SendCommandA(INT nSocket, FTP_COMMAND ftpCmd, LPCSTR lpszParam,
2630 INTERNET_STATUS_CALLBACK lpfnStatusCB, object_header_t *hdr, DWORD_PTR dwContext)
2634 DWORD nBytesSent = 0;
2638 TRACE("%d: (%s) %d\n", ftpCmd, debugstr_a(lpszParam), nSocket);
2642 lpfnStatusCB(hdr->hInternet, dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
2645 dwParamLen = lpszParam?strlen(lpszParam)+1:0;
2646 len = dwParamLen + strlen(szFtpCommands[ftpCmd]) + strlen(szCRLF);
2647 if (NULL == (buf = heap_alloc(len+1)))
2649 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2652 sprintf(buf, "%s%s%s%s", szFtpCommands[ftpCmd], dwParamLen ? " " : "",
2653 dwParamLen ? lpszParam : "", szCRLF);
2655 TRACE("Sending (%s) len(%d)\n", buf, len);
2656 while((nBytesSent < len) && (nRC != -1))
2658 nRC = send(nSocket, buf+nBytesSent, len - nBytesSent, 0);
2665 lpfnStatusCB(hdr->hInternet, dwContext, INTERNET_STATUS_REQUEST_SENT,
2666 &nBytesSent, sizeof(DWORD));
2669 TRACE("Sent %d bytes\n", nBytesSent);
2673 /***********************************************************************
2674 * FTP_SendCommand (internal)
2676 * Send command to server
2683 static BOOL FTP_SendCommand(INT nSocket, FTP_COMMAND ftpCmd, LPCWSTR lpszParam,
2684 INTERNET_STATUS_CALLBACK lpfnStatusCB, object_header_t *hdr, DWORD_PTR dwContext)
2687 LPSTR lpszParamA = heap_strdupWtoA(lpszParam);
2688 ret = FTP_SendCommandA(nSocket, ftpCmd, lpszParamA, lpfnStatusCB, hdr, dwContext);
2689 heap_free(lpszParamA);
2693 /***********************************************************************
2694 * FTP_ReceiveResponse (internal)
2696 * Receive response from server
2699 * Reply code on success
2703 INT FTP_ReceiveResponse(ftp_session_t *lpwfs, DWORD_PTR dwContext)
2705 LPSTR lpszResponse = INTERNET_GetResponseBuffer();
2708 char firstprefix[5];
2709 BOOL multiline = FALSE;
2711 TRACE("socket(%d)\n", lpwfs->sndSocket);
2713 SendAsyncCallback(&lpwfs->hdr, dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
2717 if (!INTERNET_GetNextLine(lpwfs->sndSocket, &nRecv))
2724 if(lpszResponse[3] != '-')
2727 { /* Start of multiline response. Loop until we get "nnn " */
2729 memcpy(firstprefix, lpszResponse, 3);
2730 firstprefix[3] = ' ';
2731 firstprefix[4] = '\0';
2736 if(!memcmp(firstprefix, lpszResponse, 4))
2744 rc = atoi(lpszResponse);
2746 SendAsyncCallback(&lpwfs->hdr, dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
2747 &nRecv, sizeof(DWORD));
2751 TRACE("return %d\n", rc);
2756 /***********************************************************************
2757 * FTP_SendPassword (internal)
2759 * Send password to ftp server
2766 static BOOL FTP_SendPassword(ftp_session_t *lpwfs)
2769 BOOL bSuccess = FALSE;
2772 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_PASS, lpwfs->lpszPassword, 0, 0, 0))
2775 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2778 TRACE("Received reply code %d\n", nResCode);
2779 /* Login successful... */
2780 if (nResCode == 230)
2782 /* Command not implemented, superfluous at the server site... */
2783 /* Need account for login... */
2784 else if (nResCode == 332)
2785 bSuccess = FTP_SendAccount(lpwfs);
2787 FTP_SetResponseError(nResCode);
2791 TRACE("Returning %d\n", bSuccess);
2796 /***********************************************************************
2797 * FTP_SendAccount (internal)
2806 static BOOL FTP_SendAccount(ftp_session_t *lpwfs)
2809 BOOL bSuccess = FALSE;
2812 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_ACCT, szNoAccount, 0, 0, 0))
2815 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2819 FTP_SetResponseError(nResCode);
2826 /***********************************************************************
2827 * FTP_SendStore (internal)
2829 * Send request to upload file to ftp server
2836 static BOOL FTP_SendStore(ftp_session_t *lpwfs, LPCWSTR lpszRemoteFile, DWORD dwType)
2839 BOOL bSuccess = FALSE;
2842 if (!FTP_InitListenSocket(lpwfs))
2845 if (!FTP_SendType(lpwfs, dwType))
2848 if (!FTP_SendPortOrPasv(lpwfs))
2851 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_STOR, lpszRemoteFile, 0, 0, 0))
2853 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2856 if (nResCode == 150 || nResCode == 125)
2859 FTP_SetResponseError(nResCode);
2863 if (!bSuccess && lpwfs->lstnSocket != -1)
2865 closesocket(lpwfs->lstnSocket);
2866 lpwfs->lstnSocket = -1;
2873 /***********************************************************************
2874 * FTP_InitListenSocket (internal)
2876 * Create a socket to listen for server response
2883 static BOOL FTP_InitListenSocket(ftp_session_t *lpwfs)
2885 BOOL bSuccess = FALSE;
2886 socklen_t namelen = sizeof(lpwfs->lstnSocketAddress);
2890 lpwfs->lstnSocket = socket(PF_INET, SOCK_STREAM, 0);
2891 if (lpwfs->lstnSocket == -1)
2893 TRACE("Unable to create listening socket\n");
2897 /* We obtain our ip addr from the name of the command channel socket */
2898 lpwfs->lstnSocketAddress = lpwfs->socketAddress;
2900 /* and get the system to assign us a port */
2901 lpwfs->lstnSocketAddress.sin_port = htons(0);
2903 if (bind(lpwfs->lstnSocket,(struct sockaddr *) &lpwfs->lstnSocketAddress, sizeof(lpwfs->lstnSocketAddress)) == -1)
2905 TRACE("Unable to bind socket\n");
2909 if (listen(lpwfs->lstnSocket, MAX_BACKLOG) == -1)
2911 TRACE("listen failed\n");
2915 if (getsockname(lpwfs->lstnSocket, (struct sockaddr *) &lpwfs->lstnSocketAddress, &namelen) != -1)
2919 if (!bSuccess && lpwfs->lstnSocket != -1)
2921 closesocket(lpwfs->lstnSocket);
2922 lpwfs->lstnSocket = -1;
2929 /***********************************************************************
2930 * FTP_SendType (internal)
2932 * Tell server type of data being transferred
2938 * W98SE doesn't cache the type that's currently set
2939 * (i.e. it sends it always),
2940 * so we probably don't want to do that either.
2942 static BOOL FTP_SendType(ftp_session_t *lpwfs, DWORD dwType)
2945 WCHAR type[] = { 'I','\0' };
2946 BOOL bSuccess = FALSE;
2949 if (dwType & INTERNET_FLAG_TRANSFER_ASCII)
2952 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_TYPE, type, 0, 0, 0))
2955 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext)/100;
2961 FTP_SetResponseError(nResCode);
2969 #if 0 /* FIXME: should probably be used for FtpGetFileSize */
2970 /***********************************************************************
2971 * FTP_GetFileSize (internal)
2973 * Retrieves from the server the size of the given file
2980 static BOOL FTP_GetFileSize(ftp_session_t *lpwfs, LPCWSTR lpszRemoteFile, DWORD *dwSize)
2983 BOOL bSuccess = FALSE;
2987 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_SIZE, lpszRemoteFile, 0, 0, 0))
2990 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2993 if (nResCode == 213) {
2994 /* Now parses the output to get the actual file size */
2996 LPSTR lpszResponseBuffer = INTERNET_GetResponseBuffer();
2998 for (i = 0; (lpszResponseBuffer[i] != ' ') && (lpszResponseBuffer[i] != '\0'); i++) ;
2999 if (lpszResponseBuffer[i] == '\0') return FALSE;
3000 *dwSize = atol(&(lpszResponseBuffer[i + 1]));
3004 FTP_SetResponseError(nResCode);
3014 /***********************************************************************
3015 * FTP_SendPort (internal)
3017 * Tell server which port to use
3024 static BOOL FTP_SendPort(ftp_session_t *lpwfs)
3026 static const WCHAR szIPFormat[] = {'%','d',',','%','d',',','%','d',',','%','d',',','%','d',',','%','d','\0'};
3028 WCHAR szIPAddress[64];
3029 BOOL bSuccess = FALSE;
3032 sprintfW(szIPAddress, szIPFormat,
3033 lpwfs->lstnSocketAddress.sin_addr.s_addr&0x000000FF,
3034 (lpwfs->lstnSocketAddress.sin_addr.s_addr&0x0000FF00)>>8,
3035 (lpwfs->lstnSocketAddress.sin_addr.s_addr&0x00FF0000)>>16,
3036 (lpwfs->lstnSocketAddress.sin_addr.s_addr&0xFF000000)>>24,
3037 lpwfs->lstnSocketAddress.sin_port & 0xFF,
3038 (lpwfs->lstnSocketAddress.sin_port & 0xFF00)>>8);
3040 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_PORT, szIPAddress, 0, 0, 0))
3043 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
3046 if (nResCode == 200)
3049 FTP_SetResponseError(nResCode);
3057 /***********************************************************************
3058 * FTP_DoPassive (internal)
3060 * Tell server that we want to do passive transfers
3061 * and connect data socket
3068 static BOOL FTP_DoPassive(ftp_session_t *lpwfs)
3071 BOOL bSuccess = FALSE;
3074 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_PASV, NULL, 0, 0, 0))
3077 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
3080 if (nResCode == 227)
3082 LPSTR lpszResponseBuffer = INTERNET_GetResponseBuffer();
3086 char *pAddr, *pPort;
3088 struct sockaddr_in dataSocketAddress;
3090 p = lpszResponseBuffer+4; /* skip status code */
3091 while (*p != '\0' && (*p < '0' || *p > '9')) p++;
3095 ERR("no address found in response, aborting\n");
3099 if (sscanf(p, "%d,%d,%d,%d,%d,%d", &f[0], &f[1], &f[2], &f[3],
3102 ERR("unknown response address format '%s', aborting\n", p);
3105 for (i=0; i < 6; i++)
3108 dataSocketAddress = lpwfs->socketAddress;
3109 pAddr = (char *)&(dataSocketAddress.sin_addr.s_addr);
3110 pPort = (char *)&(dataSocketAddress.sin_port);
3118 nsocket = socket(AF_INET,SOCK_STREAM,0);
3122 if (connect(nsocket, (struct sockaddr *)&dataSocketAddress, sizeof(dataSocketAddress)))
3124 ERR("can't connect passive FTP data port.\n");
3125 closesocket(nsocket);
3128 lpwfs->pasvSocket = nsocket;
3132 FTP_SetResponseError(nResCode);
3140 static BOOL FTP_SendPortOrPasv(ftp_session_t *lpwfs)
3142 if (lpwfs->hdr.dwFlags & INTERNET_FLAG_PASSIVE)
3144 if (!FTP_DoPassive(lpwfs))
3149 if (!FTP_SendPort(lpwfs))
3156 /***********************************************************************
3157 * FTP_GetDataSocket (internal)
3159 * Either accepts an incoming data socket connection from the server
3160 * or just returns the already opened socket after a PASV command
3161 * in case of passive FTP.
3169 static BOOL FTP_GetDataSocket(ftp_session_t *lpwfs, LPINT nDataSocket)
3171 struct sockaddr_in saddr;
3172 socklen_t addrlen = sizeof(struct sockaddr);
3175 if (lpwfs->hdr.dwFlags & INTERNET_FLAG_PASSIVE)
3177 *nDataSocket = lpwfs->pasvSocket;
3178 lpwfs->pasvSocket = -1;
3182 *nDataSocket = accept(lpwfs->lstnSocket, (struct sockaddr *) &saddr, &addrlen);
3183 closesocket(lpwfs->lstnSocket);
3184 lpwfs->lstnSocket = -1;
3186 return *nDataSocket != -1;
3190 /***********************************************************************
3191 * FTP_SendData (internal)
3193 * Send data to the server
3200 static BOOL FTP_SendData(ftp_session_t *lpwfs, INT nDataSocket, HANDLE hFile)
3202 BY_HANDLE_FILE_INFORMATION fi;
3203 DWORD nBytesRead = 0;
3204 DWORD nBytesSent = 0;
3205 DWORD nTotalSent = 0;
3206 DWORD nBytesToSend, nLen;
3208 time_t s_long_time, e_long_time;
3213 lpszBuffer = heap_alloc_zero(sizeof(CHAR)*DATA_PACKET_SIZE);
3215 /* Get the size of the file. */
3216 GetFileInformationByHandle(hFile, &fi);
3221 nBytesToSend = nBytesRead - nBytesSent;
3223 if (nBytesToSend <= 0)
3225 /* Read data from file. */
3227 if (!ReadFile(hFile, lpszBuffer, DATA_PACKET_SIZE, &nBytesRead, 0))
3228 ERR("Failed reading from file\n");
3231 nBytesToSend = nBytesRead;
3236 nLen = DATA_PACKET_SIZE < nBytesToSend ?
3237 DATA_PACKET_SIZE : nBytesToSend;
3238 nRC = send(nDataSocket, lpszBuffer, nLen, 0);
3246 /* Do some computation to display the status. */
3248 nSeconds = e_long_time - s_long_time;
3249 if( nSeconds / 60 > 0 )
3251 TRACE( "%d bytes of %d bytes (%d%%) in %d min %d sec estimated remaining time %d sec\n",
3252 nTotalSent, fi.nFileSizeLow, nTotalSent*100/fi.nFileSizeLow, nSeconds / 60,
3253 nSeconds % 60, (fi.nFileSizeLow - nTotalSent) * nSeconds / nTotalSent );
3257 TRACE( "%d bytes of %d bytes (%d%%) in %d sec estimated remaining time %d sec\n",
3258 nTotalSent, fi.nFileSizeLow, nTotalSent*100/fi.nFileSizeLow, nSeconds,
3259 (fi.nFileSizeLow - nTotalSent) * nSeconds / nTotalSent);
3261 } while (nRC != -1);
3263 TRACE("file transfer complete!\n");
3265 heap_free(lpszBuffer);
3270 /***********************************************************************
3271 * FTP_SendRetrieve (internal)
3273 * Send request to retrieve a file
3276 * Number of bytes to be received on success
3280 static BOOL FTP_SendRetrieve(ftp_session_t *lpwfs, LPCWSTR lpszRemoteFile, DWORD dwType)
3286 if (!(ret = FTP_InitListenSocket(lpwfs)))
3289 if (!(ret = FTP_SendType(lpwfs, dwType)))
3292 if (!(ret = FTP_SendPortOrPasv(lpwfs)))
3295 if (!(ret = FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_RETR, lpszRemoteFile, 0, 0, 0)))
3298 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
3299 if ((nResCode != 125) && (nResCode != 150)) {
3300 /* That means that we got an error getting the file. */
3301 FTP_SetResponseError(nResCode);
3306 if (!ret && lpwfs->lstnSocket != -1)
3308 closesocket(lpwfs->lstnSocket);
3309 lpwfs->lstnSocket = -1;
3316 /***********************************************************************
3317 * FTP_RetrieveData (internal)
3319 * Retrieve data from server
3326 static BOOL FTP_RetrieveFileData(ftp_session_t *lpwfs, INT nDataSocket, HANDLE hFile)
3328 DWORD nBytesWritten;
3334 lpszBuffer = heap_alloc_zero(sizeof(CHAR)*DATA_PACKET_SIZE);
3335 if (NULL == lpszBuffer)
3337 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3343 nRC = recv(nDataSocket, lpszBuffer, DATA_PACKET_SIZE, 0);
3346 /* other side closed socket. */
3349 WriteFile(hFile, lpszBuffer, nRC, &nBytesWritten, NULL);
3353 TRACE("Data transfer complete\n");
3356 heap_free(lpszBuffer);
3360 /***********************************************************************
3361 * FTPFINDNEXT_Destroy (internal)
3363 * Deallocate session handle
3365 static void FTPFINDNEXT_Destroy(object_header_t *hdr)
3367 LPWININETFTPFINDNEXTW lpwfn = (LPWININETFTPFINDNEXTW) hdr;
3372 WININET_Release(&lpwfn->lpFtpSession->hdr);
3374 for (i = 0; i < lpwfn->size; i++)
3376 heap_free(lpwfn->lpafp[i].lpszName);
3378 heap_free(lpwfn->lpafp);
3381 static DWORD FTPFINDNEXT_FindNextFileProc(WININETFTPFINDNEXTW *find, LPVOID data)
3383 WIN32_FIND_DATAW *find_data = data;
3384 DWORD res = ERROR_SUCCESS;
3386 TRACE("index(%d) size(%d)\n", find->index, find->size);
3388 ZeroMemory(find_data, sizeof(WIN32_FIND_DATAW));
3390 if (find->index < find->size) {
3391 FTP_ConvertFileProp(&find->lpafp[find->index], find_data);
3394 TRACE("Name: %s\nSize: %d\n", debugstr_w(find_data->cFileName), find_data->nFileSizeLow);
3396 res = ERROR_NO_MORE_FILES;
3399 if (find->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3401 INTERNET_ASYNC_RESULT iar;
3403 iar.dwResult = (res == ERROR_SUCCESS);
3406 INTERNET_SendCallback(&find->hdr, find->hdr.dwContext,
3407 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3408 sizeof(INTERNET_ASYNC_RESULT));
3414 static void FTPFINDNEXT_AsyncFindNextFileProc(WORKREQUEST *workRequest)
3416 struct WORKREQ_FTPFINDNEXTW *req = &workRequest->u.FtpFindNextW;
3418 FTPFINDNEXT_FindNextFileProc((WININETFTPFINDNEXTW*)workRequest->hdr, req->lpFindFileData);
3421 static DWORD FTPFINDNEXT_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3424 case INTERNET_OPTION_HANDLE_TYPE:
3425 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
3427 if (*size < sizeof(ULONG))
3428 return ERROR_INSUFFICIENT_BUFFER;
3430 *size = sizeof(DWORD);
3431 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_FTP_FIND;
3432 return ERROR_SUCCESS;
3435 return INET_QueryOption(hdr, option, buffer, size, unicode);
3438 static DWORD FTPFINDNEXT_FindNextFileW(object_header_t *hdr, void *data)
3440 WININETFTPFINDNEXTW *find = (WININETFTPFINDNEXTW*)hdr;
3442 if (find->lpFtpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3445 struct WORKREQ_FTPFINDNEXTW *req;
3447 task = alloc_async_task(&find->hdr, FTPFINDNEXT_AsyncFindNextFileProc, sizeof(*task));
3448 req = &task->u.FtpFindNextW;
3449 req->lpFindFileData = data;
3451 INTERNET_AsyncCall(task);
3453 return ERROR_SUCCESS;
3456 return FTPFINDNEXT_FindNextFileProc(find, data);
3459 static const object_vtbl_t FTPFINDNEXTVtbl = {
3460 FTPFINDNEXT_Destroy,
3462 FTPFINDNEXT_QueryOption,
3468 FTPFINDNEXT_FindNextFileW
3471 /***********************************************************************
3472 * FTP_ReceiveFileList (internal)
3474 * Read file list from server
3477 * Handle to file list on success
3481 static HINTERNET FTP_ReceiveFileList(ftp_session_t *lpwfs, INT nSocket, LPCWSTR lpszSearchFile,
3482 LPWIN32_FIND_DATAW lpFindFileData, DWORD_PTR dwContext)
3485 LPFILEPROPERTIESW lpafp = NULL;
3486 LPWININETFTPFINDNEXTW lpwfn = NULL;
3488 TRACE("(%p,%d,%s,%p,%08lx)\n", lpwfs, nSocket, debugstr_w(lpszSearchFile), lpFindFileData, dwContext);
3490 if (FTP_ParseDirectory(lpwfs, nSocket, lpszSearchFile, &lpafp, &dwSize))
3493 FTP_ConvertFileProp(lpafp, lpFindFileData);
3495 lpwfn = alloc_object(&lpwfs->hdr, &FTPFINDNEXTVtbl, sizeof(WININETFTPFINDNEXTW));
3498 lpwfn->hdr.htype = WH_HFTPFINDNEXT;
3499 lpwfn->hdr.dwContext = dwContext;
3500 lpwfn->index = 1; /* Next index is 1 since we return index 0 */
3501 lpwfn->size = dwSize;
3502 lpwfn->lpafp = lpafp;
3504 WININET_AddRef( &lpwfs->hdr );
3505 lpwfn->lpFtpSession = lpwfs;
3506 list_add_head( &lpwfs->hdr.children, &lpwfn->hdr.entry );
3510 TRACE("Matched %d files\n", dwSize);
3511 return lpwfn ? lpwfn->hdr.hInternet : NULL;
3515 /***********************************************************************
3516 * FTP_ConvertFileProp (internal)
3518 * Converts FILEPROPERTIESW struct to WIN32_FIND_DATAA
3525 static BOOL FTP_ConvertFileProp(LPFILEPROPERTIESW lpafp, LPWIN32_FIND_DATAW lpFindFileData)
3527 BOOL bSuccess = FALSE;
3529 ZeroMemory(lpFindFileData, sizeof(WIN32_FIND_DATAW));
3533 SystemTimeToFileTime( &lpafp->tmLastModified, &lpFindFileData->ftLastAccessTime );
3534 lpFindFileData->ftLastWriteTime = lpFindFileData->ftLastAccessTime;
3535 lpFindFileData->ftCreationTime = lpFindFileData->ftLastAccessTime;
3537 /* Not all fields are filled in */
3538 lpFindFileData->nFileSizeHigh = 0; /* We do not handle files bigger than 0xFFFFFFFF bytes yet :-) */
3539 lpFindFileData->nFileSizeLow = lpafp->nSize;
3541 if (lpafp->bIsDirectory)
3542 lpFindFileData->dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
3544 if (lpafp->lpszName)
3545 lstrcpynW(lpFindFileData->cFileName, lpafp->lpszName, MAX_PATH);
3553 /***********************************************************************
3554 * FTP_ParseNextFile (internal)
3556 * Parse the next line in file listing
3562 static BOOL FTP_ParseNextFile(INT nSocket, LPCWSTR lpszSearchFile, LPFILEPROPERTIESW lpfp)
3564 static const char szSpace[] = " \t";
3572 lpfp->lpszName = NULL;
3574 if(!(pszLine = INTERNET_GetNextLine(nSocket, &nBufLen)))
3577 pszToken = strtok(pszLine, szSpace);
3579 * <Permissions> <NoLinks> <owner> <group> <size> <date> <time or year> <filename>
3582 * drwx--s--- 2 pcarrier ens 512 Sep 28 1995 pcarrier
3584 if(!isdigit(pszToken[0]) && 10 == strlen(pszToken)) {
3585 if(!FTP_ParsePermission(pszToken, lpfp))
3586 lpfp->bIsDirectory = FALSE;
3587 for(i=0; i<=3; i++) {
3588 if(!(pszToken = strtok(NULL, szSpace)))
3591 if(!pszToken) continue;
3592 if(lpfp->bIsDirectory) {
3593 TRACE("Is directory\n");
3597 TRACE("Size: %s\n", pszToken);
3598 lpfp->nSize = atol(pszToken);
3601 lpfp->tmLastModified.wSecond = 0;
3602 lpfp->tmLastModified.wMinute = 0;
3603 lpfp->tmLastModified.wHour = 0;
3604 lpfp->tmLastModified.wDay = 0;
3605 lpfp->tmLastModified.wMonth = 0;
3606 lpfp->tmLastModified.wYear = 0;
3608 /* Determine month */
3609 pszToken = strtok(NULL, szSpace);
3610 if(!pszToken) continue;
3611 if(strlen(pszToken) >= 3) {
3613 if((pszTmp = StrStrIA(szMonths, pszToken)))
3614 lpfp->tmLastModified.wMonth = ((pszTmp - szMonths) / 3)+1;
3617 pszToken = strtok(NULL, szSpace);
3618 if(!pszToken) continue;
3619 lpfp->tmLastModified.wDay = atoi(pszToken);
3620 /* Determine time or year */
3621 pszToken = strtok(NULL, szSpace);
3622 if(!pszToken) continue;
3623 if((pszTmp = strchr(pszToken, ':'))) {
3624 SYSTEMTIME curr_time;
3627 lpfp->tmLastModified.wMinute = atoi(pszTmp);
3628 lpfp->tmLastModified.wHour = atoi(pszToken);
3629 GetLocalTime( &curr_time );
3630 lpfp->tmLastModified.wYear = curr_time.wYear;
3633 lpfp->tmLastModified.wYear = atoi(pszToken);
3634 lpfp->tmLastModified.wHour = 12;
3636 TRACE("Mod time: %02d:%02d:%02d %04d/%02d/%02d\n",
3637 lpfp->tmLastModified.wHour, lpfp->tmLastModified.wMinute, lpfp->tmLastModified.wSecond,
3638 lpfp->tmLastModified.wYear, lpfp->tmLastModified.wMonth, lpfp->tmLastModified.wDay);
3640 pszToken = strtok(NULL, szSpace);
3641 if(!pszToken) continue;
3642 lpfp->lpszName = heap_strdupAtoW(pszToken);
3643 TRACE("File: %s\n", debugstr_w(lpfp->lpszName));
3645 /* NT way of parsing ... :
3647 07-13-03 08:55PM <DIR> sakpatch
3648 05-09-03 06:02PM 12656686 2003-04-21bgm_cmd_e.rgz
3650 else if(isdigit(pszToken[0]) && 8 == strlen(pszToken)) {
3651 int mon, mday, year, hour, min;
3652 lpfp->permissions = 0xFFFF; /* No idea, put full permission :-) */
3654 sscanf(pszToken, "%d-%d-%d", &mon, &mday, &year);
3655 lpfp->tmLastModified.wDay = mday;
3656 lpfp->tmLastModified.wMonth = mon;
3657 lpfp->tmLastModified.wYear = year;
3659 /* Hacky and bad Y2K protection :-) */
3660 if (lpfp->tmLastModified.wYear < 70) lpfp->tmLastModified.wYear += 2000;
3662 pszToken = strtok(NULL, szSpace);
3663 if(!pszToken) continue;
3664 sscanf(pszToken, "%d:%d", &hour, &min);
3665 lpfp->tmLastModified.wHour = hour;
3666 lpfp->tmLastModified.wMinute = min;
3667 if((pszToken[5] == 'P') && (pszToken[6] == 'M')) {
3668 lpfp->tmLastModified.wHour += 12;
3670 lpfp->tmLastModified.wSecond = 0;
3672 TRACE("Mod time: %02d:%02d:%02d %04d/%02d/%02d\n",
3673 lpfp->tmLastModified.wHour, lpfp->tmLastModified.wMinute, lpfp->tmLastModified.wSecond,
3674 lpfp->tmLastModified.wYear, lpfp->tmLastModified.wMonth, lpfp->tmLastModified.wDay);
3676 pszToken = strtok(NULL, szSpace);
3677 if(!pszToken) continue;
3678 if(!strcasecmp(pszToken, "<DIR>")) {
3679 lpfp->bIsDirectory = TRUE;
3681 TRACE("Is directory\n");
3684 lpfp->bIsDirectory = FALSE;
3685 lpfp->nSize = atol(pszToken);
3686 TRACE("Size: %d\n", lpfp->nSize);
3689 pszToken = strtok(NULL, szSpace);
3690 if(!pszToken) continue;
3691 lpfp->lpszName = heap_strdupAtoW(pszToken);
3692 TRACE("Name: %s\n", debugstr_w(lpfp->lpszName));
3694 /* EPLF format - http://cr.yp.to/ftp/list/eplf.html */
3695 else if(pszToken[0] == '+') {
3696 FIXME("EPLF Format not implemented\n");
3699 if(lpfp->lpszName) {
3700 if((lpszSearchFile == NULL) ||
3701 (PathMatchSpecW(lpfp->lpszName, lpszSearchFile))) {
3703 TRACE("Matched: %s\n", debugstr_w(lpfp->lpszName));
3706 heap_free(lpfp->lpszName);
3707 lpfp->lpszName = NULL;
3714 /***********************************************************************
3715 * FTP_ParseDirectory (internal)
3717 * Parse string of directory information
3723 static BOOL FTP_ParseDirectory(ftp_session_t *lpwfs, INT nSocket, LPCWSTR lpszSearchFile,
3724 LPFILEPROPERTIESW *lpafp, LPDWORD dwfp)
3726 BOOL bSuccess = TRUE;
3727 INT sizeFilePropArray = 500;/*20; */
3728 INT indexFilePropArray = -1;
3732 /* Allocate initial file properties array */
3733 *lpafp = heap_alloc_zero(sizeof(FILEPROPERTIESW)*(sizeFilePropArray));
3738 if (indexFilePropArray+1 >= sizeFilePropArray)
3740 LPFILEPROPERTIESW tmpafp;
3742 sizeFilePropArray *= 2;
3743 tmpafp = heap_realloc_zero(*lpafp, sizeof(FILEPROPERTIESW)*sizeFilePropArray);
3752 indexFilePropArray++;
3753 } while (FTP_ParseNextFile(nSocket, lpszSearchFile, &(*lpafp)[indexFilePropArray]));
3755 if (bSuccess && indexFilePropArray)
3757 if (indexFilePropArray < sizeFilePropArray - 1)
3759 LPFILEPROPERTIESW tmpafp;
3761 tmpafp = heap_realloc(*lpafp, sizeof(FILEPROPERTIESW)*indexFilePropArray);
3765 *dwfp = indexFilePropArray;
3770 INTERNET_SetLastError(ERROR_NO_MORE_FILES);
3778 /***********************************************************************
3779 * FTP_ParsePermission (internal)
3781 * Parse permission string of directory information
3788 static BOOL FTP_ParsePermission(LPCSTR lpszPermission, LPFILEPROPERTIESW lpfp)
3790 BOOL bSuccess = TRUE;
3791 unsigned short nPermission = 0;
3796 if ((*lpszPermission != 'd') && (*lpszPermission != '-') && (*lpszPermission != 'l'))
3802 lpfp->bIsDirectory = (*lpszPermission == 'd');
3808 nPermission |= (*(lpszPermission+1) == 'r' ? 1 : 0) << 8;
3811 nPermission |= (*(lpszPermission+2) == 'w' ? 1 : 0) << 7;
3814 nPermission |= (*(lpszPermission+3) == 'x' ? 1 : 0) << 6;
3817 nPermission |= (*(lpszPermission+4) == 'r' ? 1 : 0) << 5;
3820 nPermission |= (*(lpszPermission+5) == 'w' ? 1 : 0) << 4;
3823 nPermission |= (*(lpszPermission+6) == 'x' ? 1 : 0) << 3;
3826 nPermission |= (*(lpszPermission+7) == 'r' ? 1 : 0) << 2;
3829 nPermission |= (*(lpszPermission+8) == 'w' ? 1 : 0) << 1;
3832 nPermission |= (*(lpszPermission+9) == 'x' ? 1 : 0);
3836 }while (nPos <= nLast);
3838 lpfp->permissions = nPermission;
3843 /***********************************************************************
3844 * FTP_SetResponseError (internal)
3846 * Set the appropriate error code for a given response from the server
3851 static DWORD FTP_SetResponseError(DWORD dwResponse)
3857 case 425: /* Cannot open data connection. */
3858 dwCode = ERROR_INTERNET_CANNOT_CONNECT;
3861 case 426: /* Connection closed, transer aborted. */
3862 dwCode = ERROR_INTERNET_CONNECTION_ABORTED;
3865 case 530: /* Not logged in. Login incorrect. */
3866 dwCode = ERROR_INTERNET_LOGIN_FAILURE;
3869 case 421: /* Service not available - Server may be shutting down. */
3870 case 450: /* File action not taken. File may be busy. */
3871 case 451: /* Action aborted. Server error. */
3872 case 452: /* Action not taken. Insufficient storage space on server. */
3873 case 500: /* Syntax error. Command unrecognized. */
3874 case 501: /* Syntax error. Error in parameters or arguments. */
3875 case 502: /* Command not implemented. */
3876 case 503: /* Bad sequence of commands. */
3877 case 504: /* Command not implemented for that parameter. */
3878 case 532: /* Need account for storing files */
3879 case 550: /* File action not taken. File not found or no access. */
3880 case 551: /* Requested action aborted. Page type unknown */
3881 case 552: /* Action aborted. Exceeded storage allocation */
3882 case 553: /* Action not taken. File name not allowed. */
3885 dwCode = ERROR_INTERNET_EXTENDED_ERROR;
3889 INTERNET_SetLastError(dwCode);