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>
49 #ifdef HAVE_SYS_IOCTL_H
50 # include <sys/ioctl.h>
66 #include "wine/debug.h"
69 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
71 typedef struct _ftp_session_t ftp_session_t;
76 ftp_session_t *lpFtpSession;
80 HANDLE cache_file_handle;
89 int pasvSocket; /* data socket connected by us in case of passive FTP */
90 ftp_file_t *download_in_progress;
91 struct sockaddr_in socketAddress;
92 struct sockaddr_in lstnSocketAddress;
94 INTERNET_PORT serverport;
104 SYSTEMTIME tmLastModified;
105 unsigned short permissions;
106 } FILEPROPERTIESW, *LPFILEPROPERTIESW;
111 ftp_session_t *lpFtpSession;
114 LPFILEPROPERTIESW lpafp;
115 } WININETFTPFINDNEXTW, *LPWININETFTPFINDNEXTW;
117 #define DATA_PACKET_SIZE 0x2000
118 #define szCRLF "\r\n"
119 #define MAX_BACKLOG 5
121 /* Testing shows that Windows only accepts dwFlags where the last
122 * 3 (yes 3) bits define FTP_TRANSFER_TYPE_UNKNOWN, FTP_TRANSFER_TYPE_ASCII or FTP_TRANSFER_TYPE_BINARY.
124 #define FTP_CONDITION_MASK 0x0007
127 /* FTP commands with arguments. */
143 /* FTP commands without arguments. */
152 static const CHAR *const szFtpCommands[] = {
175 static const CHAR szMonths[] = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";
176 static const WCHAR szNoAccount[] = {'n','o','a','c','c','o','u','n','t','\0'};
178 static BOOL FTP_SendCommand(INT nSocket, FTP_COMMAND ftpCmd, LPCWSTR lpszParam,
179 INTERNET_STATUS_CALLBACK lpfnStatusCB, object_header_t *hdr, DWORD_PTR dwContext);
180 static BOOL FTP_SendStore(ftp_session_t*, LPCWSTR lpszRemoteFile, DWORD dwType);
181 static BOOL FTP_GetDataSocket(ftp_session_t*, LPINT nDataSocket);
182 static BOOL FTP_SendData(ftp_session_t*, INT nDataSocket, HANDLE hFile);
183 static INT FTP_ReceiveResponse(ftp_session_t*, DWORD_PTR dwContext);
184 static BOOL FTP_SendRetrieve(ftp_session_t*, LPCWSTR lpszRemoteFile, DWORD dwType);
185 static BOOL FTP_RetrieveFileData(ftp_session_t*, INT nDataSocket, HANDLE hFile);
186 static BOOL FTP_InitListenSocket(ftp_session_t*);
187 static BOOL FTP_ConnectToHost(ftp_session_t*);
188 static BOOL FTP_SendPassword(ftp_session_t*);
189 static BOOL FTP_SendAccount(ftp_session_t*);
190 static BOOL FTP_SendType(ftp_session_t*, DWORD dwType);
191 static BOOL FTP_SendPort(ftp_session_t*);
192 static BOOL FTP_DoPassive(ftp_session_t*);
193 static BOOL FTP_SendPortOrPasv(ftp_session_t*);
194 static BOOL FTP_ParsePermission(LPCSTR lpszPermission, LPFILEPROPERTIESW lpfp);
195 static BOOL FTP_ParseNextFile(INT nSocket, LPCWSTR lpszSearchFile, LPFILEPROPERTIESW fileprop);
196 static BOOL FTP_ParseDirectory(ftp_session_t*, INT nSocket, LPCWSTR lpszSearchFile,
197 LPFILEPROPERTIESW *lpafp, LPDWORD dwfp);
198 static HINTERNET FTP_ReceiveFileList(ftp_session_t*, INT nSocket, LPCWSTR lpszSearchFile,
199 LPWIN32_FIND_DATAW lpFindFileData, DWORD_PTR dwContext);
200 static DWORD FTP_SetResponseError(DWORD dwResponse);
201 static BOOL FTP_ConvertFileProp(LPFILEPROPERTIESW lpafp, LPWIN32_FIND_DATAW lpFindFileData);
202 static BOOL FTP_FtpPutFileW(ftp_session_t*, LPCWSTR lpszLocalFile,
203 LPCWSTR lpszNewRemoteFile, DWORD dwFlags, DWORD_PTR dwContext);
204 static BOOL FTP_FtpSetCurrentDirectoryW(ftp_session_t*, LPCWSTR lpszDirectory);
205 static BOOL FTP_FtpCreateDirectoryW(ftp_session_t*, LPCWSTR lpszDirectory);
206 static HINTERNET FTP_FtpFindFirstFileW(ftp_session_t*,
207 LPCWSTR lpszSearchFile, LPWIN32_FIND_DATAW lpFindFileData, DWORD dwFlags, DWORD_PTR dwContext);
208 static BOOL FTP_FtpGetCurrentDirectoryW(ftp_session_t*, LPWSTR lpszCurrentDirectory,
209 LPDWORD lpdwCurrentDirectory);
210 static BOOL FTP_FtpRenameFileW(ftp_session_t*, LPCWSTR lpszSrc, LPCWSTR lpszDest);
211 static BOOL FTP_FtpRemoveDirectoryW(ftp_session_t*, LPCWSTR lpszDirectory);
212 static BOOL FTP_FtpDeleteFileW(ftp_session_t*, LPCWSTR lpszFileName);
213 static BOOL FTP_FtpGetFileW(ftp_session_t*, LPCWSTR lpszRemoteFile, LPCWSTR lpszNewFile,
214 BOOL fFailIfExists, DWORD dwLocalFlagsAttribute, DWORD dwInternetFlags,
215 DWORD_PTR dwContext);
218 /***********************************************************************
219 * FtpPutFileA (WININET.@)
221 * Uploads a file to the FTP server
228 BOOL WINAPI FtpPutFileA(HINTERNET hConnect, LPCSTR lpszLocalFile,
229 LPCSTR lpszNewRemoteFile, DWORD dwFlags, DWORD_PTR dwContext)
231 LPWSTR lpwzLocalFile;
232 LPWSTR lpwzNewRemoteFile;
235 lpwzLocalFile = heap_strdupAtoW(lpszLocalFile);
236 lpwzNewRemoteFile = heap_strdupAtoW(lpszNewRemoteFile);
237 ret = FtpPutFileW(hConnect, lpwzLocalFile, lpwzNewRemoteFile,
239 HeapFree(GetProcessHeap(), 0, lpwzLocalFile);
240 HeapFree(GetProcessHeap(), 0, lpwzNewRemoteFile);
244 static void AsyncFtpPutFileProc(WORKREQUEST *workRequest)
246 struct WORKREQ_FTPPUTFILEW const *req = &workRequest->u.FtpPutFileW;
247 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
249 TRACE("%p\n", lpwfs);
251 FTP_FtpPutFileW(lpwfs, req->lpszLocalFile,
252 req->lpszNewRemoteFile, req->dwFlags, req->dwContext);
254 HeapFree(GetProcessHeap(), 0, req->lpszLocalFile);
255 HeapFree(GetProcessHeap(), 0, req->lpszNewRemoteFile);
258 /***********************************************************************
259 * FtpPutFileW (WININET.@)
261 * Uploads a file to the FTP server
268 BOOL WINAPI FtpPutFileW(HINTERNET hConnect, LPCWSTR lpszLocalFile,
269 LPCWSTR lpszNewRemoteFile, DWORD dwFlags, DWORD_PTR dwContext)
271 ftp_session_t *lpwfs;
272 appinfo_t *hIC = NULL;
275 if (!lpszLocalFile || !lpszNewRemoteFile)
277 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
281 lpwfs = (ftp_session_t*) WININET_GetObject( hConnect );
284 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
288 if (WH_HFTPSESSION != lpwfs->hdr.htype)
290 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
294 if (lpwfs->download_in_progress != NULL)
296 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
300 if ((dwFlags & FTP_CONDITION_MASK) > FTP_TRANSFER_TYPE_BINARY)
302 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
306 hIC = lpwfs->lpAppInfo;
307 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
309 WORKREQUEST workRequest;
310 struct WORKREQ_FTPPUTFILEW *req = &workRequest.u.FtpPutFileW;
312 workRequest.asyncproc = AsyncFtpPutFileProc;
313 workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
314 req->lpszLocalFile = heap_strdupW(lpszLocalFile);
315 req->lpszNewRemoteFile = heap_strdupW(lpszNewRemoteFile);
316 req->dwFlags = dwFlags;
317 req->dwContext = dwContext;
319 r = INTERNET_AsyncCall(&workRequest);
323 r = FTP_FtpPutFileW(lpwfs, lpszLocalFile,
324 lpszNewRemoteFile, dwFlags, dwContext);
328 WININET_Release( &lpwfs->hdr );
333 /***********************************************************************
334 * FTP_FtpPutFileW (Internal)
336 * Uploads a file to the FTP server
343 static BOOL FTP_FtpPutFileW(ftp_session_t *lpwfs, LPCWSTR lpszLocalFile,
344 LPCWSTR lpszNewRemoteFile, DWORD dwFlags, DWORD_PTR dwContext)
347 BOOL bSuccess = FALSE;
348 appinfo_t *hIC = NULL;
351 TRACE(" lpszLocalFile(%s) lpszNewRemoteFile(%s)\n", debugstr_w(lpszLocalFile), debugstr_w(lpszNewRemoteFile));
353 /* Clear any error information */
354 INTERNET_SetLastError(0);
356 /* Open file to be uploaded */
357 if (INVALID_HANDLE_VALUE ==
358 (hFile = CreateFileW(lpszLocalFile, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0)))
359 /* Let CreateFile set the appropriate error */
362 hIC = lpwfs->lpAppInfo;
364 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
366 if (FTP_SendStore(lpwfs, lpszNewRemoteFile, dwFlags))
370 /* Get data socket to server */
371 if (FTP_GetDataSocket(lpwfs, &nDataSocket))
373 FTP_SendData(lpwfs, nDataSocket, hFile);
374 closesocket(nDataSocket);
375 nResCode = FTP_ReceiveResponse(lpwfs, dwContext);
381 FTP_SetResponseError(nResCode);
386 if (lpwfs->lstnSocket != -1)
388 closesocket(lpwfs->lstnSocket);
389 lpwfs->lstnSocket = -1;
392 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
394 INTERNET_ASYNC_RESULT iar;
396 iar.dwResult = (DWORD)bSuccess;
397 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
398 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
399 &iar, sizeof(INTERNET_ASYNC_RESULT));
408 /***********************************************************************
409 * FtpSetCurrentDirectoryA (WININET.@)
411 * Change the working directory on the FTP server
418 BOOL WINAPI FtpSetCurrentDirectoryA(HINTERNET hConnect, LPCSTR lpszDirectory)
420 LPWSTR lpwzDirectory;
423 lpwzDirectory = heap_strdupAtoW(lpszDirectory);
424 ret = FtpSetCurrentDirectoryW(hConnect, lpwzDirectory);
425 HeapFree(GetProcessHeap(), 0, lpwzDirectory);
430 static void AsyncFtpSetCurrentDirectoryProc(WORKREQUEST *workRequest)
432 struct WORKREQ_FTPSETCURRENTDIRECTORYW const *req = &workRequest->u.FtpSetCurrentDirectoryW;
433 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
435 TRACE("%p\n", lpwfs);
437 FTP_FtpSetCurrentDirectoryW(lpwfs, req->lpszDirectory);
438 HeapFree(GetProcessHeap(), 0, req->lpszDirectory);
441 /***********************************************************************
442 * FtpSetCurrentDirectoryW (WININET.@)
444 * Change the working directory on the FTP server
451 BOOL WINAPI FtpSetCurrentDirectoryW(HINTERNET hConnect, LPCWSTR lpszDirectory)
453 ftp_session_t *lpwfs = NULL;
454 appinfo_t *hIC = NULL;
459 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
463 lpwfs = (ftp_session_t*) WININET_GetObject( hConnect );
464 if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
466 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
470 if (lpwfs->download_in_progress != NULL)
472 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
476 TRACE("lpszDirectory(%s)\n", debugstr_w(lpszDirectory));
478 hIC = lpwfs->lpAppInfo;
479 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
481 WORKREQUEST workRequest;
482 struct WORKREQ_FTPSETCURRENTDIRECTORYW *req;
484 workRequest.asyncproc = AsyncFtpSetCurrentDirectoryProc;
485 workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
486 req = &workRequest.u.FtpSetCurrentDirectoryW;
487 req->lpszDirectory = heap_strdupW(lpszDirectory);
489 r = INTERNET_AsyncCall(&workRequest);
493 r = FTP_FtpSetCurrentDirectoryW(lpwfs, lpszDirectory);
498 WININET_Release( &lpwfs->hdr );
504 /***********************************************************************
505 * FTP_FtpSetCurrentDirectoryW (Internal)
507 * Change the working directory on the FTP server
514 static BOOL FTP_FtpSetCurrentDirectoryW(ftp_session_t *lpwfs, LPCWSTR lpszDirectory)
517 appinfo_t *hIC = NULL;
518 DWORD bSuccess = FALSE;
520 TRACE("lpszDirectory(%s)\n", debugstr_w(lpszDirectory));
522 /* Clear any error information */
523 INTERNET_SetLastError(0);
525 hIC = lpwfs->lpAppInfo;
526 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_CWD, lpszDirectory,
527 lpwfs->hdr.lpfnStatusCB, &lpwfs->hdr, lpwfs->hdr.dwContext))
530 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
537 FTP_SetResponseError(nResCode);
541 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
543 INTERNET_ASYNC_RESULT iar;
545 iar.dwResult = bSuccess;
546 iar.dwError = bSuccess ? ERROR_SUCCESS : ERROR_INTERNET_EXTENDED_ERROR;
547 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
548 &iar, sizeof(INTERNET_ASYNC_RESULT));
554 /***********************************************************************
555 * FtpCreateDirectoryA (WININET.@)
557 * Create new directory on the FTP server
564 BOOL WINAPI FtpCreateDirectoryA(HINTERNET hConnect, LPCSTR lpszDirectory)
566 LPWSTR lpwzDirectory;
569 lpwzDirectory = heap_strdupAtoW(lpszDirectory);
570 ret = FtpCreateDirectoryW(hConnect, lpwzDirectory);
571 HeapFree(GetProcessHeap(), 0, lpwzDirectory);
576 static void AsyncFtpCreateDirectoryProc(WORKREQUEST *workRequest)
578 struct WORKREQ_FTPCREATEDIRECTORYW const *req = &workRequest->u.FtpCreateDirectoryW;
579 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
581 TRACE(" %p\n", lpwfs);
583 FTP_FtpCreateDirectoryW(lpwfs, req->lpszDirectory);
584 HeapFree(GetProcessHeap(), 0, req->lpszDirectory);
587 /***********************************************************************
588 * FtpCreateDirectoryW (WININET.@)
590 * Create new directory on the FTP server
597 BOOL WINAPI FtpCreateDirectoryW(HINTERNET hConnect, LPCWSTR lpszDirectory)
599 ftp_session_t *lpwfs;
600 appinfo_t *hIC = NULL;
603 lpwfs = (ftp_session_t*) WININET_GetObject( hConnect );
606 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
610 if (WH_HFTPSESSION != lpwfs->hdr.htype)
612 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
616 if (lpwfs->download_in_progress != NULL)
618 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
624 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
628 hIC = lpwfs->lpAppInfo;
629 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
631 WORKREQUEST workRequest;
632 struct WORKREQ_FTPCREATEDIRECTORYW *req;
634 workRequest.asyncproc = AsyncFtpCreateDirectoryProc;
635 workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
636 req = &workRequest.u.FtpCreateDirectoryW;
637 req->lpszDirectory = heap_strdupW(lpszDirectory);
639 r = INTERNET_AsyncCall(&workRequest);
643 r = FTP_FtpCreateDirectoryW(lpwfs, lpszDirectory);
646 WININET_Release( &lpwfs->hdr );
652 /***********************************************************************
653 * FTP_FtpCreateDirectoryW (Internal)
655 * Create new directory on the FTP server
662 static BOOL FTP_FtpCreateDirectoryW(ftp_session_t *lpwfs, LPCWSTR lpszDirectory)
665 BOOL bSuccess = FALSE;
666 appinfo_t *hIC = NULL;
668 TRACE("lpszDirectory(%s)\n", debugstr_w(lpszDirectory));
670 /* Clear any error information */
671 INTERNET_SetLastError(0);
673 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_MKD, lpszDirectory, 0, 0, 0))
676 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
682 FTP_SetResponseError(nResCode);
686 hIC = lpwfs->lpAppInfo;
687 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
689 INTERNET_ASYNC_RESULT iar;
691 iar.dwResult = (DWORD)bSuccess;
692 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
693 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
694 &iar, sizeof(INTERNET_ASYNC_RESULT));
700 /***********************************************************************
701 * FtpFindFirstFileA (WININET.@)
703 * Search the specified directory
706 * HINTERNET on success
710 HINTERNET WINAPI FtpFindFirstFileA(HINTERNET hConnect,
711 LPCSTR lpszSearchFile, LPWIN32_FIND_DATAA lpFindFileData, DWORD dwFlags, DWORD_PTR dwContext)
713 LPWSTR lpwzSearchFile;
714 WIN32_FIND_DATAW wfd;
715 LPWIN32_FIND_DATAW lpFindFileDataW;
718 lpwzSearchFile = heap_strdupAtoW(lpszSearchFile);
719 lpFindFileDataW = lpFindFileData?&wfd:NULL;
720 ret = FtpFindFirstFileW(hConnect, lpwzSearchFile, lpFindFileDataW, dwFlags, dwContext);
721 HeapFree(GetProcessHeap(), 0, lpwzSearchFile);
723 if (ret && lpFindFileData)
724 WININET_find_data_WtoA(lpFindFileDataW, lpFindFileData);
730 static void AsyncFtpFindFirstFileProc(WORKREQUEST *workRequest)
732 struct WORKREQ_FTPFINDFIRSTFILEW const *req = &workRequest->u.FtpFindFirstFileW;
733 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
735 TRACE("%p\n", lpwfs);
737 FTP_FtpFindFirstFileW(lpwfs, req->lpszSearchFile,
738 req->lpFindFileData, req->dwFlags, req->dwContext);
739 HeapFree(GetProcessHeap(), 0, req->lpszSearchFile);
742 /***********************************************************************
743 * FtpFindFirstFileW (WININET.@)
745 * Search the specified directory
748 * HINTERNET on success
752 HINTERNET WINAPI FtpFindFirstFileW(HINTERNET hConnect,
753 LPCWSTR lpszSearchFile, LPWIN32_FIND_DATAW lpFindFileData, DWORD dwFlags, DWORD_PTR dwContext)
755 ftp_session_t *lpwfs;
756 appinfo_t *hIC = NULL;
759 lpwfs = (ftp_session_t*) WININET_GetObject( hConnect );
760 if (NULL == lpwfs || WH_HFTPSESSION != lpwfs->hdr.htype)
762 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
766 if (lpwfs->download_in_progress != NULL)
768 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
772 hIC = lpwfs->lpAppInfo;
773 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
775 WORKREQUEST workRequest;
776 struct WORKREQ_FTPFINDFIRSTFILEW *req;
778 workRequest.asyncproc = AsyncFtpFindFirstFileProc;
779 workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
780 req = &workRequest.u.FtpFindFirstFileW;
781 req->lpszSearchFile = (lpszSearchFile == NULL) ? NULL : heap_strdupW(lpszSearchFile);
782 req->lpFindFileData = lpFindFileData;
783 req->dwFlags = dwFlags;
784 req->dwContext= dwContext;
786 INTERNET_AsyncCall(&workRequest);
791 r = FTP_FtpFindFirstFileW(lpwfs, lpszSearchFile, lpFindFileData,
796 WININET_Release( &lpwfs->hdr );
802 /***********************************************************************
803 * FTP_FtpFindFirstFileW (Internal)
805 * Search the specified directory
808 * HINTERNET on success
812 static HINTERNET FTP_FtpFindFirstFileW(ftp_session_t *lpwfs,
813 LPCWSTR lpszSearchFile, LPWIN32_FIND_DATAW lpFindFileData, DWORD dwFlags, DWORD_PTR dwContext)
816 appinfo_t *hIC = NULL;
817 HINTERNET hFindNext = NULL;
821 /* Clear any error information */
822 INTERNET_SetLastError(0);
824 if (!FTP_InitListenSocket(lpwfs))
827 if (!FTP_SendType(lpwfs, INTERNET_FLAG_TRANSFER_ASCII))
830 if (!FTP_SendPortOrPasv(lpwfs))
833 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_LIST, NULL,
834 lpwfs->hdr.lpfnStatusCB, &lpwfs->hdr, lpwfs->hdr.dwContext))
837 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
840 if (nResCode == 125 || nResCode == 150)
844 /* Get data socket to server */
845 if (FTP_GetDataSocket(lpwfs, &nDataSocket))
847 hFindNext = FTP_ReceiveFileList(lpwfs, nDataSocket, lpszSearchFile, lpFindFileData, dwContext);
848 closesocket(nDataSocket);
849 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
850 if (nResCode != 226 && nResCode != 250)
851 INTERNET_SetLastError(ERROR_NO_MORE_FILES);
855 FTP_SetResponseError(nResCode);
859 if (lpwfs->lstnSocket != -1)
861 closesocket(lpwfs->lstnSocket);
862 lpwfs->lstnSocket = -1;
865 hIC = lpwfs->lpAppInfo;
866 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
868 INTERNET_ASYNC_RESULT iar;
872 iar.dwResult = (DWORD_PTR)hFindNext;
873 iar.dwError = ERROR_SUCCESS;
874 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_HANDLE_CREATED,
875 &iar, sizeof(INTERNET_ASYNC_RESULT));
878 iar.dwResult = (DWORD_PTR)hFindNext;
879 iar.dwError = hFindNext ? ERROR_SUCCESS : INTERNET_GetLastError();
880 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
881 &iar, sizeof(INTERNET_ASYNC_RESULT));
888 /***********************************************************************
889 * FtpGetCurrentDirectoryA (WININET.@)
891 * Retrieves the current directory
898 BOOL WINAPI FtpGetCurrentDirectoryA(HINTERNET hFtpSession, LPSTR lpszCurrentDirectory,
899 LPDWORD lpdwCurrentDirectory)
905 if(lpdwCurrentDirectory) {
906 len = *lpdwCurrentDirectory;
907 if(lpszCurrentDirectory)
909 dir = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
912 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
917 ret = FtpGetCurrentDirectoryW(hFtpSession, lpszCurrentDirectory?dir:NULL, lpdwCurrentDirectory?&len:NULL);
919 if (ret && lpszCurrentDirectory)
920 WideCharToMultiByte(CP_ACP, 0, dir, -1, lpszCurrentDirectory, len, NULL, NULL);
922 if (lpdwCurrentDirectory) *lpdwCurrentDirectory = len;
923 HeapFree(GetProcessHeap(), 0, dir);
928 static void AsyncFtpGetCurrentDirectoryProc(WORKREQUEST *workRequest)
930 struct WORKREQ_FTPGETCURRENTDIRECTORYW const *req = &workRequest->u.FtpGetCurrentDirectoryW;
931 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
933 TRACE("%p\n", lpwfs);
935 FTP_FtpGetCurrentDirectoryW(lpwfs, req->lpszDirectory, req->lpdwDirectory);
938 /***********************************************************************
939 * FtpGetCurrentDirectoryW (WININET.@)
941 * Retrieves the current directory
948 BOOL WINAPI FtpGetCurrentDirectoryW(HINTERNET hFtpSession, LPWSTR lpszCurrentDirectory,
949 LPDWORD lpdwCurrentDirectory)
951 ftp_session_t *lpwfs;
952 appinfo_t *hIC = NULL;
955 TRACE("%p %p %p\n", hFtpSession, lpszCurrentDirectory, lpdwCurrentDirectory);
957 lpwfs = (ftp_session_t*) WININET_GetObject( hFtpSession );
960 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
964 if (WH_HFTPSESSION != lpwfs->hdr.htype)
966 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
970 if (!lpdwCurrentDirectory)
972 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
976 if (lpszCurrentDirectory == NULL)
978 INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
982 if (lpwfs->download_in_progress != NULL)
984 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
988 hIC = lpwfs->lpAppInfo;
989 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
991 WORKREQUEST workRequest;
992 struct WORKREQ_FTPGETCURRENTDIRECTORYW *req;
994 workRequest.asyncproc = AsyncFtpGetCurrentDirectoryProc;
995 workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
996 req = &workRequest.u.FtpGetCurrentDirectoryW;
997 req->lpszDirectory = lpszCurrentDirectory;
998 req->lpdwDirectory = lpdwCurrentDirectory;
1000 r = INTERNET_AsyncCall(&workRequest);
1004 r = FTP_FtpGetCurrentDirectoryW(lpwfs, lpszCurrentDirectory,
1005 lpdwCurrentDirectory);
1010 WININET_Release( &lpwfs->hdr );
1016 /***********************************************************************
1017 * FTP_FtpGetCurrentDirectoryW (Internal)
1019 * Retrieves the current directory
1026 static BOOL FTP_FtpGetCurrentDirectoryW(ftp_session_t *lpwfs, LPWSTR lpszCurrentDirectory,
1027 LPDWORD lpdwCurrentDirectory)
1030 appinfo_t *hIC = NULL;
1031 DWORD bSuccess = FALSE;
1033 /* Clear any error information */
1034 INTERNET_SetLastError(0);
1036 hIC = lpwfs->lpAppInfo;
1037 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_PWD, NULL,
1038 lpwfs->hdr.lpfnStatusCB, &lpwfs->hdr, lpwfs->hdr.dwContext))
1041 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
1044 if (nResCode == 257) /* Extract directory name */
1046 DWORD firstpos, lastpos, len;
1047 LPWSTR lpszResponseBuffer = heap_strdupAtoW(INTERNET_GetResponseBuffer());
1049 for (firstpos = 0, lastpos = 0; lpszResponseBuffer[lastpos]; lastpos++)
1051 if ('"' == lpszResponseBuffer[lastpos])
1059 len = lastpos - firstpos;
1060 if (*lpdwCurrentDirectory >= len)
1062 memcpy(lpszCurrentDirectory, &lpszResponseBuffer[firstpos + 1], len * sizeof(WCHAR));
1063 lpszCurrentDirectory[len - 1] = 0;
1064 *lpdwCurrentDirectory = len;
1067 else INTERNET_SetLastError(ERROR_INSUFFICIENT_BUFFER);
1069 HeapFree(GetProcessHeap(), 0, lpszResponseBuffer);
1072 FTP_SetResponseError(nResCode);
1076 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1078 INTERNET_ASYNC_RESULT iar;
1080 iar.dwResult = bSuccess;
1081 iar.dwError = bSuccess ? ERROR_SUCCESS : ERROR_INTERNET_EXTENDED_ERROR;
1082 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1083 &iar, sizeof(INTERNET_ASYNC_RESULT));
1090 /***********************************************************************
1091 * FTPFILE_Destroy(internal)
1093 * Closes the file transfer handle. This also 'cleans' the data queue of
1094 * the 'transfer complete' message (this is a bit of a hack though :-/ )
1097 static void FTPFILE_Destroy(object_header_t *hdr)
1099 ftp_file_t *lpwh = (ftp_file_t*) hdr;
1100 ftp_session_t *lpwfs = lpwh->lpFtpSession;
1105 if (lpwh->cache_file_handle != INVALID_HANDLE_VALUE)
1106 CloseHandle(lpwh->cache_file_handle);
1108 HeapFree(GetProcessHeap(), 0, lpwh->cache_file);
1110 if (!lpwh->session_deleted)
1111 lpwfs->download_in_progress = NULL;
1113 if (lpwh->nDataSocket != -1)
1114 closesocket(lpwh->nDataSocket);
1116 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
1117 if (nResCode > 0 && nResCode != 226) WARN("server reports failed transfer\n");
1119 WININET_Release(&lpwh->lpFtpSession->hdr);
1121 HeapFree(GetProcessHeap(), 0, lpwh);
1124 static DWORD FTPFILE_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
1127 case INTERNET_OPTION_HANDLE_TYPE:
1128 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
1130 if (*size < sizeof(ULONG))
1131 return ERROR_INSUFFICIENT_BUFFER;
1133 *size = sizeof(DWORD);
1134 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_FTP_FILE;
1135 return ERROR_SUCCESS;
1136 case INTERNET_OPTION_DATAFILE_NAME:
1139 ftp_file_t *file = (ftp_file_t *)hdr;
1141 TRACE("INTERNET_OPTION_DATAFILE_NAME\n");
1143 if (!file->cache_file)
1146 return ERROR_INTERNET_ITEM_NOT_FOUND;
1150 required = (lstrlenW(file->cache_file) + 1) * sizeof(WCHAR);
1151 if (*size < required)
1152 return ERROR_INSUFFICIENT_BUFFER;
1155 memcpy(buffer, file->cache_file, *size);
1156 return ERROR_SUCCESS;
1160 required = WideCharToMultiByte(CP_ACP, 0, file->cache_file, -1, NULL, 0, NULL, NULL);
1161 if (required > *size)
1162 return ERROR_INSUFFICIENT_BUFFER;
1164 *size = WideCharToMultiByte(CP_ACP, 0, file->cache_file, -1, buffer, *size, NULL, NULL);
1165 return ERROR_SUCCESS;
1169 return INET_QueryOption(option, buffer, size, unicode);
1172 static DWORD FTPFILE_ReadFile(object_header_t *hdr, void *buffer, DWORD size, DWORD *read)
1174 ftp_file_t *file = (ftp_file_t*)hdr;
1178 if (file->nDataSocket == -1)
1179 return ERROR_INTERNET_DISCONNECTED;
1181 /* FIXME: FTP should use NETCON_ stuff */
1182 res = recv(file->nDataSocket, buffer, size, MSG_WAITALL);
1183 *read = res>0 ? res : 0;
1185 error = res >= 0 ? ERROR_SUCCESS : INTERNET_ERROR_BASE; /* FIXME */
1186 if (error == ERROR_SUCCESS && file->cache_file)
1188 DWORD bytes_written;
1190 if (!WriteFile(file->cache_file_handle, buffer, *read, &bytes_written, NULL))
1191 WARN("WriteFile failed: %u\n", GetLastError());
1196 static DWORD FTPFILE_ReadFileExA(object_header_t *hdr, INTERNET_BUFFERSA *buffers,
1197 DWORD flags, DWORD_PTR context)
1199 return FTPFILE_ReadFile(hdr, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength);
1202 static DWORD FTPFILE_ReadFileExW(object_header_t *hdr, INTERNET_BUFFERSW *buffers,
1203 DWORD flags, DWORD_PTR context)
1205 return FTPFILE_ReadFile(hdr, buffers->lpvBuffer, buffers->dwBufferLength, &buffers->dwBufferLength);
1208 static DWORD FTPFILE_WriteFile(object_header_t *hdr, const void *buffer, DWORD size, DWORD *written)
1210 ftp_file_t *lpwh = (ftp_file_t*) hdr;
1213 res = send(lpwh->nDataSocket, buffer, size, 0);
1215 *written = res>0 ? res : 0;
1216 return res >= 0 ? ERROR_SUCCESS : sock_get_error(errno);
1219 static void FTP_ReceiveRequestData(ftp_file_t *file, BOOL first_notif)
1221 INTERNET_ASYNC_RESULT iar;
1225 TRACE("%p\n", file);
1227 available = recv(file->nDataSocket, buffer, sizeof(buffer), MSG_PEEK);
1229 if(available != -1) {
1230 iar.dwResult = (DWORD_PTR)file->hdr.hInternet;
1231 iar.dwError = first_notif ? 0 : available;
1234 iar.dwError = INTERNET_GetLastError();
1237 INTERNET_SendCallback(&file->hdr, file->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE, &iar,
1238 sizeof(INTERNET_ASYNC_RESULT));
1241 static void FTPFILE_AsyncQueryDataAvailableProc(WORKREQUEST *workRequest)
1243 ftp_file_t *file = (ftp_file_t*)workRequest->hdr;
1245 FTP_ReceiveRequestData(file, FALSE);
1248 static DWORD FTPFILE_QueryDataAvailable(object_header_t *hdr, DWORD *available, DWORD flags, DWORD_PTR ctx)
1250 ftp_file_t *file = (ftp_file_t*) hdr;
1251 int retval, unread = 0;
1253 TRACE("(%p %p %x %lx)\n", file, available, flags, ctx);
1256 retval = ioctlsocket(file->nDataSocket, FIONREAD, &unread);
1258 TRACE("%d bytes of queued, but unread data\n", unread);
1260 FIXME("FIONREAD not available\n");
1263 *available = unread;
1270 retval = recv(file->nDataSocket, &byte, 1, MSG_PEEK);
1272 WORKREQUEST workRequest;
1275 workRequest.asyncproc = FTPFILE_AsyncQueryDataAvailableProc;
1276 workRequest.hdr = WININET_AddRef( &file->hdr );
1278 INTERNET_AsyncCall(&workRequest);
1280 return ERROR_IO_PENDING;
1284 return ERROR_SUCCESS;
1288 static const object_vtbl_t FTPFILEVtbl = {
1291 FTPFILE_QueryOption,
1294 FTPFILE_ReadFileExA,
1295 FTPFILE_ReadFileExW,
1297 FTPFILE_QueryDataAvailable,
1301 /***********************************************************************
1302 * FTP_FtpOpenFileW (Internal)
1304 * Open a remote file for writing or reading
1307 * HINTERNET handle on success
1311 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;
1319 HINTERNET handle = NULL;
1323 /* Clear any error information */
1324 INTERNET_SetLastError(0);
1326 if (GENERIC_READ == fdwAccess)
1328 /* Set up socket to retrieve data */
1329 bSuccess = FTP_SendRetrieve(lpwfs, lpszFileName, dwFlags);
1331 else if (GENERIC_WRITE == fdwAccess)
1333 /* Set up socket to send data */
1334 bSuccess = FTP_SendStore(lpwfs, lpszFileName, dwFlags);
1337 /* Get data socket to server */
1338 if (bSuccess && FTP_GetDataSocket(lpwfs, &nDataSocket))
1340 lpwh = HeapAlloc(GetProcessHeap(), 0, sizeof(ftp_file_t));
1341 lpwh->hdr.htype = WH_HFILE;
1342 lpwh->hdr.vtbl = &FTPFILEVtbl;
1343 lpwh->hdr.dwFlags = dwFlags;
1344 lpwh->hdr.dwContext = dwContext;
1345 lpwh->hdr.dwInternalFlags = 0;
1347 lpwh->hdr.lpfnStatusCB = lpwfs->hdr.lpfnStatusCB;
1348 lpwh->nDataSocket = nDataSocket;
1349 lpwh->cache_file = NULL;
1350 lpwh->cache_file_handle = INVALID_HANDLE_VALUE;
1351 lpwh->session_deleted = FALSE;
1353 WININET_AddRef( &lpwfs->hdr );
1354 lpwh->lpFtpSession = lpwfs;
1355 list_add_head( &lpwfs->hdr.children, &lpwh->hdr.entry );
1357 handle = WININET_AllocHandle( &lpwh->hdr );
1361 /* Indicate that a download is currently in progress */
1362 lpwfs->download_in_progress = lpwh;
1365 if (lpwfs->lstnSocket != -1)
1367 closesocket(lpwfs->lstnSocket);
1368 lpwfs->lstnSocket = -1;
1371 if (bSuccess && fdwAccess == GENERIC_READ)
1373 WCHAR filename[MAX_PATH + 1];
1377 memset(&uc, 0, sizeof(uc));
1378 uc.dwStructSize = sizeof(uc);
1379 uc.nScheme = INTERNET_SCHEME_FTP;
1380 uc.lpszHostName = lpwfs->servername;
1381 uc.nPort = lpwfs->serverport;
1382 uc.lpszUserName = lpwfs->lpszUserName;
1383 uc.lpszUrlPath = heap_strdupW(lpszFileName);
1385 if (!InternetCreateUrlW(&uc, 0, NULL, &len) && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
1387 WCHAR *url = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1389 if (url && InternetCreateUrlW(&uc, 0, url, &len) && CreateUrlCacheEntryW(url, 0, NULL, filename, 0))
1391 lpwh->cache_file = heap_strdupW(filename);
1392 lpwh->cache_file_handle = CreateFileW(filename, GENERIC_WRITE, FILE_SHARE_READ,
1393 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1394 if (lpwh->cache_file_handle == INVALID_HANDLE_VALUE)
1396 WARN("Could not create cache file: %u\n", GetLastError());
1397 HeapFree(GetProcessHeap(), 0, lpwh->cache_file);
1398 lpwh->cache_file = NULL;
1400 HeapFree(GetProcessHeap(), 0, url);
1403 HeapFree(GetProcessHeap(), 0, uc.lpszUrlPath);
1406 hIC = lpwfs->lpAppInfo;
1407 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1409 INTERNET_ASYNC_RESULT iar;
1413 iar.dwResult = (DWORD_PTR)handle;
1414 iar.dwError = ERROR_SUCCESS;
1415 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_HANDLE_CREATED,
1416 &iar, sizeof(INTERNET_ASYNC_RESULT));
1420 FTP_ReceiveRequestData(lpwh, TRUE);
1423 iar.dwError = INTERNET_GetLastError();
1424 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1425 &iar, sizeof(INTERNET_ASYNC_RESULT));
1431 WININET_Release( &lpwh->hdr );
1437 /***********************************************************************
1438 * FtpOpenFileA (WININET.@)
1440 * Open a remote file for writing or reading
1443 * HINTERNET handle on success
1447 HINTERNET WINAPI FtpOpenFileA(HINTERNET hFtpSession,
1448 LPCSTR lpszFileName, DWORD fdwAccess, DWORD dwFlags,
1449 DWORD_PTR dwContext)
1451 LPWSTR lpwzFileName;
1454 lpwzFileName = heap_strdupAtoW(lpszFileName);
1455 ret = FtpOpenFileW(hFtpSession, lpwzFileName, fdwAccess, dwFlags, dwContext);
1456 HeapFree(GetProcessHeap(), 0, lpwzFileName);
1461 static void AsyncFtpOpenFileProc(WORKREQUEST *workRequest)
1463 struct WORKREQ_FTPOPENFILEW const *req = &workRequest->u.FtpOpenFileW;
1464 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
1466 TRACE("%p\n", lpwfs);
1468 FTP_FtpOpenFileW(lpwfs, req->lpszFilename,
1469 req->dwAccess, req->dwFlags, req->dwContext);
1470 HeapFree(GetProcessHeap(), 0, req->lpszFilename);
1473 /***********************************************************************
1474 * FtpOpenFileW (WININET.@)
1476 * Open a remote file for writing or reading
1479 * HINTERNET handle on success
1483 HINTERNET WINAPI FtpOpenFileW(HINTERNET hFtpSession,
1484 LPCWSTR lpszFileName, DWORD fdwAccess, DWORD dwFlags,
1485 DWORD_PTR dwContext)
1487 ftp_session_t *lpwfs;
1488 appinfo_t *hIC = NULL;
1491 TRACE("(%p,%s,0x%08x,0x%08x,0x%08lx)\n", hFtpSession,
1492 debugstr_w(lpszFileName), fdwAccess, dwFlags, dwContext);
1494 lpwfs = (ftp_session_t*) WININET_GetObject( hFtpSession );
1497 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
1501 if (WH_HFTPSESSION != lpwfs->hdr.htype)
1503 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1507 if ((!lpszFileName) ||
1508 ((fdwAccess != GENERIC_READ) && (fdwAccess != GENERIC_WRITE)) ||
1509 ((dwFlags & FTP_CONDITION_MASK) > FTP_TRANSFER_TYPE_BINARY))
1511 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1515 if (lpwfs->download_in_progress != NULL)
1517 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
1521 hIC = lpwfs->lpAppInfo;
1522 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1524 WORKREQUEST workRequest;
1525 struct WORKREQ_FTPOPENFILEW *req;
1527 workRequest.asyncproc = AsyncFtpOpenFileProc;
1528 workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
1529 req = &workRequest.u.FtpOpenFileW;
1530 req->lpszFilename = heap_strdupW(lpszFileName);
1531 req->dwAccess = fdwAccess;
1532 req->dwFlags = dwFlags;
1533 req->dwContext = dwContext;
1535 INTERNET_AsyncCall(&workRequest);
1540 r = FTP_FtpOpenFileW(lpwfs, lpszFileName, fdwAccess, dwFlags, dwContext);
1544 WININET_Release( &lpwfs->hdr );
1550 /***********************************************************************
1551 * FtpGetFileA (WININET.@)
1553 * Retrieve file from the FTP server
1560 BOOL WINAPI FtpGetFileA(HINTERNET hInternet, LPCSTR lpszRemoteFile, LPCSTR lpszNewFile,
1561 BOOL fFailIfExists, DWORD dwLocalFlagsAttribute, DWORD dwInternetFlags,
1562 DWORD_PTR dwContext)
1564 LPWSTR lpwzRemoteFile;
1568 lpwzRemoteFile = heap_strdupAtoW(lpszRemoteFile);
1569 lpwzNewFile = heap_strdupAtoW(lpszNewFile);
1570 ret = FtpGetFileW(hInternet, lpwzRemoteFile, lpwzNewFile, fFailIfExists,
1571 dwLocalFlagsAttribute, dwInternetFlags, dwContext);
1572 HeapFree(GetProcessHeap(), 0, lpwzRemoteFile);
1573 HeapFree(GetProcessHeap(), 0, lpwzNewFile);
1578 static void AsyncFtpGetFileProc(WORKREQUEST *workRequest)
1580 struct WORKREQ_FTPGETFILEW const *req = &workRequest->u.FtpGetFileW;
1581 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
1583 TRACE("%p\n", lpwfs);
1585 FTP_FtpGetFileW(lpwfs, req->lpszRemoteFile,
1586 req->lpszNewFile, req->fFailIfExists,
1587 req->dwLocalFlagsAttribute, req->dwFlags, req->dwContext);
1588 HeapFree(GetProcessHeap(), 0, req->lpszRemoteFile);
1589 HeapFree(GetProcessHeap(), 0, req->lpszNewFile);
1593 /***********************************************************************
1594 * FtpGetFileW (WININET.@)
1596 * Retrieve file from the FTP server
1603 BOOL WINAPI FtpGetFileW(HINTERNET hInternet, LPCWSTR lpszRemoteFile, LPCWSTR lpszNewFile,
1604 BOOL fFailIfExists, DWORD dwLocalFlagsAttribute, DWORD dwInternetFlags,
1605 DWORD_PTR dwContext)
1607 ftp_session_t *lpwfs;
1608 appinfo_t *hIC = NULL;
1611 if (!lpszRemoteFile || !lpszNewFile)
1613 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1617 lpwfs = (ftp_session_t*) WININET_GetObject( hInternet );
1620 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
1624 if (WH_HFTPSESSION != lpwfs->hdr.htype)
1626 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1630 if ((dwInternetFlags & FTP_CONDITION_MASK) > FTP_TRANSFER_TYPE_BINARY)
1632 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1636 if (lpwfs->download_in_progress != NULL)
1638 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
1642 hIC = lpwfs->lpAppInfo;
1643 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1645 WORKREQUEST workRequest;
1646 struct WORKREQ_FTPGETFILEW *req;
1648 workRequest.asyncproc = AsyncFtpGetFileProc;
1649 workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
1650 req = &workRequest.u.FtpGetFileW;
1651 req->lpszRemoteFile = heap_strdupW(lpszRemoteFile);
1652 req->lpszNewFile = heap_strdupW(lpszNewFile);
1653 req->dwLocalFlagsAttribute = dwLocalFlagsAttribute;
1654 req->fFailIfExists = fFailIfExists;
1655 req->dwFlags = dwInternetFlags;
1656 req->dwContext = dwContext;
1658 r = INTERNET_AsyncCall(&workRequest);
1662 r = FTP_FtpGetFileW(lpwfs, lpszRemoteFile, lpszNewFile,
1663 fFailIfExists, dwLocalFlagsAttribute, dwInternetFlags, dwContext);
1667 WININET_Release( &lpwfs->hdr );
1673 /***********************************************************************
1674 * FTP_FtpGetFileW (Internal)
1676 * Retrieve file from the FTP server
1683 static BOOL FTP_FtpGetFileW(ftp_session_t *lpwfs, LPCWSTR lpszRemoteFile, LPCWSTR lpszNewFile,
1684 BOOL fFailIfExists, DWORD dwLocalFlagsAttribute, DWORD dwInternetFlags,
1685 DWORD_PTR dwContext)
1687 BOOL bSuccess = FALSE;
1689 appinfo_t *hIC = NULL;
1691 TRACE("lpszRemoteFile(%s) lpszNewFile(%s)\n", debugstr_w(lpszRemoteFile), debugstr_w(lpszNewFile));
1693 /* Clear any error information */
1694 INTERNET_SetLastError(0);
1696 /* Ensure we can write to lpszNewfile by opening it */
1697 hFile = CreateFileW(lpszNewFile, GENERIC_WRITE, 0, 0, fFailIfExists ?
1698 CREATE_NEW : CREATE_ALWAYS, dwLocalFlagsAttribute, 0);
1699 if (INVALID_HANDLE_VALUE == hFile)
1702 /* Set up socket to retrieve data */
1703 if (FTP_SendRetrieve(lpwfs, lpszRemoteFile, dwInternetFlags))
1707 /* Get data socket to server */
1708 if (FTP_GetDataSocket(lpwfs, &nDataSocket))
1713 FTP_RetrieveFileData(lpwfs, nDataSocket, hFile);
1714 closesocket(nDataSocket);
1716 nResCode = FTP_ReceiveResponse(lpwfs, dwContext);
1719 if (nResCode == 226)
1722 FTP_SetResponseError(nResCode);
1727 if (lpwfs->lstnSocket != -1)
1729 closesocket(lpwfs->lstnSocket);
1730 lpwfs->lstnSocket = -1;
1735 hIC = lpwfs->lpAppInfo;
1736 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1738 INTERNET_ASYNC_RESULT iar;
1740 iar.dwResult = (DWORD)bSuccess;
1741 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
1742 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1743 &iar, sizeof(INTERNET_ASYNC_RESULT));
1746 if (!bSuccess) DeleteFileW(lpszNewFile);
1750 /***********************************************************************
1751 * FtpGetFileSize (WININET.@)
1753 DWORD WINAPI FtpGetFileSize( HINTERNET hFile, LPDWORD lpdwFileSizeHigh )
1755 FIXME("(%p, %p)\n", hFile, lpdwFileSizeHigh);
1757 if (lpdwFileSizeHigh)
1758 *lpdwFileSizeHigh = 0;
1763 /***********************************************************************
1764 * FtpDeleteFileA (WININET.@)
1766 * Delete a file on the ftp server
1773 BOOL WINAPI FtpDeleteFileA(HINTERNET hFtpSession, LPCSTR lpszFileName)
1775 LPWSTR lpwzFileName;
1778 lpwzFileName = heap_strdupAtoW(lpszFileName);
1779 ret = FtpDeleteFileW(hFtpSession, lpwzFileName);
1780 HeapFree(GetProcessHeap(), 0, lpwzFileName);
1784 static void AsyncFtpDeleteFileProc(WORKREQUEST *workRequest)
1786 struct WORKREQ_FTPDELETEFILEW const *req = &workRequest->u.FtpDeleteFileW;
1787 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
1789 TRACE("%p\n", lpwfs);
1791 FTP_FtpDeleteFileW(lpwfs, req->lpszFilename);
1792 HeapFree(GetProcessHeap(), 0, req->lpszFilename);
1795 /***********************************************************************
1796 * FtpDeleteFileW (WININET.@)
1798 * Delete a file on the ftp server
1805 BOOL WINAPI FtpDeleteFileW(HINTERNET hFtpSession, LPCWSTR lpszFileName)
1807 ftp_session_t *lpwfs;
1808 appinfo_t *hIC = NULL;
1811 lpwfs = (ftp_session_t*) WININET_GetObject( hFtpSession );
1814 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
1818 if (WH_HFTPSESSION != lpwfs->hdr.htype)
1820 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1824 if (lpwfs->download_in_progress != NULL)
1826 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
1832 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1836 hIC = lpwfs->lpAppInfo;
1837 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1839 WORKREQUEST workRequest;
1840 struct WORKREQ_FTPDELETEFILEW *req;
1842 workRequest.asyncproc = AsyncFtpDeleteFileProc;
1843 workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
1844 req = &workRequest.u.FtpDeleteFileW;
1845 req->lpszFilename = heap_strdupW(lpszFileName);
1847 r = INTERNET_AsyncCall(&workRequest);
1851 r = FTP_FtpDeleteFileW(lpwfs, lpszFileName);
1855 WININET_Release( &lpwfs->hdr );
1860 /***********************************************************************
1861 * FTP_FtpDeleteFileW (Internal)
1863 * Delete a file on the ftp server
1870 BOOL FTP_FtpDeleteFileW(ftp_session_t *lpwfs, LPCWSTR lpszFileName)
1873 BOOL bSuccess = FALSE;
1874 appinfo_t *hIC = NULL;
1876 TRACE("%p\n", lpwfs);
1878 /* Clear any error information */
1879 INTERNET_SetLastError(0);
1881 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_DELE, lpszFileName, 0, 0, 0))
1884 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
1887 if (nResCode == 250)
1890 FTP_SetResponseError(nResCode);
1893 hIC = lpwfs->lpAppInfo;
1894 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1896 INTERNET_ASYNC_RESULT iar;
1898 iar.dwResult = (DWORD)bSuccess;
1899 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
1900 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
1901 &iar, sizeof(INTERNET_ASYNC_RESULT));
1908 /***********************************************************************
1909 * FtpRemoveDirectoryA (WININET.@)
1911 * Remove a directory on the ftp server
1918 BOOL WINAPI FtpRemoveDirectoryA(HINTERNET hFtpSession, LPCSTR lpszDirectory)
1920 LPWSTR lpwzDirectory;
1923 lpwzDirectory = heap_strdupAtoW(lpszDirectory);
1924 ret = FtpRemoveDirectoryW(hFtpSession, lpwzDirectory);
1925 HeapFree(GetProcessHeap(), 0, lpwzDirectory);
1929 static void AsyncFtpRemoveDirectoryProc(WORKREQUEST *workRequest)
1931 struct WORKREQ_FTPREMOVEDIRECTORYW const *req = &workRequest->u.FtpRemoveDirectoryW;
1932 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
1934 TRACE("%p\n", lpwfs);
1936 FTP_FtpRemoveDirectoryW(lpwfs, req->lpszDirectory);
1937 HeapFree(GetProcessHeap(), 0, req->lpszDirectory);
1940 /***********************************************************************
1941 * FtpRemoveDirectoryW (WININET.@)
1943 * Remove a directory on the ftp server
1950 BOOL WINAPI FtpRemoveDirectoryW(HINTERNET hFtpSession, LPCWSTR lpszDirectory)
1952 ftp_session_t *lpwfs;
1953 appinfo_t *hIC = NULL;
1956 lpwfs = (ftp_session_t*) WININET_GetObject( hFtpSession );
1959 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
1963 if (WH_HFTPSESSION != lpwfs->hdr.htype)
1965 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
1969 if (lpwfs->download_in_progress != NULL)
1971 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
1977 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
1981 hIC = lpwfs->lpAppInfo;
1982 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
1984 WORKREQUEST workRequest;
1985 struct WORKREQ_FTPREMOVEDIRECTORYW *req;
1987 workRequest.asyncproc = AsyncFtpRemoveDirectoryProc;
1988 workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
1989 req = &workRequest.u.FtpRemoveDirectoryW;
1990 req->lpszDirectory = heap_strdupW(lpszDirectory);
1992 r = INTERNET_AsyncCall(&workRequest);
1996 r = FTP_FtpRemoveDirectoryW(lpwfs, lpszDirectory);
2000 WININET_Release( &lpwfs->hdr );
2005 /***********************************************************************
2006 * FTP_FtpRemoveDirectoryW (Internal)
2008 * Remove a directory on the ftp server
2015 BOOL FTP_FtpRemoveDirectoryW(ftp_session_t *lpwfs, LPCWSTR lpszDirectory)
2018 BOOL bSuccess = FALSE;
2019 appinfo_t *hIC = NULL;
2023 /* Clear any error information */
2024 INTERNET_SetLastError(0);
2026 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_RMD, lpszDirectory, 0, 0, 0))
2029 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2032 if (nResCode == 250)
2035 FTP_SetResponseError(nResCode);
2039 hIC = lpwfs->lpAppInfo;
2040 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2042 INTERNET_ASYNC_RESULT iar;
2044 iar.dwResult = (DWORD)bSuccess;
2045 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
2046 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
2047 &iar, sizeof(INTERNET_ASYNC_RESULT));
2054 /***********************************************************************
2055 * FtpRenameFileA (WININET.@)
2057 * Rename a file on the ftp server
2064 BOOL WINAPI FtpRenameFileA(HINTERNET hFtpSession, LPCSTR lpszSrc, LPCSTR lpszDest)
2070 lpwzSrc = heap_strdupAtoW(lpszSrc);
2071 lpwzDest = heap_strdupAtoW(lpszDest);
2072 ret = FtpRenameFileW(hFtpSession, lpwzSrc, lpwzDest);
2073 HeapFree(GetProcessHeap(), 0, lpwzSrc);
2074 HeapFree(GetProcessHeap(), 0, lpwzDest);
2078 static void AsyncFtpRenameFileProc(WORKREQUEST *workRequest)
2080 struct WORKREQ_FTPRENAMEFILEW const *req = &workRequest->u.FtpRenameFileW;
2081 ftp_session_t *lpwfs = (ftp_session_t*) workRequest->hdr;
2083 TRACE("%p\n", lpwfs);
2085 FTP_FtpRenameFileW(lpwfs, req->lpszSrcFile, req->lpszDestFile);
2086 HeapFree(GetProcessHeap(), 0, req->lpszSrcFile);
2087 HeapFree(GetProcessHeap(), 0, req->lpszDestFile);
2090 /***********************************************************************
2091 * FtpRenameFileW (WININET.@)
2093 * Rename a file on the ftp server
2100 BOOL WINAPI FtpRenameFileW(HINTERNET hFtpSession, LPCWSTR lpszSrc, LPCWSTR lpszDest)
2102 ftp_session_t *lpwfs;
2103 appinfo_t *hIC = NULL;
2106 lpwfs = (ftp_session_t*) WININET_GetObject( hFtpSession );
2109 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
2113 if (WH_HFTPSESSION != lpwfs->hdr.htype)
2115 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2119 if (lpwfs->download_in_progress != NULL)
2121 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
2125 if (!lpszSrc || !lpszDest)
2127 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2131 hIC = lpwfs->lpAppInfo;
2132 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2134 WORKREQUEST workRequest;
2135 struct WORKREQ_FTPRENAMEFILEW *req;
2137 workRequest.asyncproc = AsyncFtpRenameFileProc;
2138 workRequest.hdr = WININET_AddRef( &lpwfs->hdr );
2139 req = &workRequest.u.FtpRenameFileW;
2140 req->lpszSrcFile = heap_strdupW(lpszSrc);
2141 req->lpszDestFile = heap_strdupW(lpszDest);
2143 r = INTERNET_AsyncCall(&workRequest);
2147 r = FTP_FtpRenameFileW(lpwfs, lpszSrc, lpszDest);
2151 WININET_Release( &lpwfs->hdr );
2156 /***********************************************************************
2157 * FTP_FtpRenameFileW (Internal)
2159 * Rename a file on the ftp server
2166 BOOL FTP_FtpRenameFileW(ftp_session_t *lpwfs, LPCWSTR lpszSrc, LPCWSTR lpszDest)
2169 BOOL bSuccess = FALSE;
2170 appinfo_t *hIC = NULL;
2174 /* Clear any error information */
2175 INTERNET_SetLastError(0);
2177 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_RNFR, lpszSrc, 0, 0, 0))
2180 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2181 if (nResCode == 350)
2183 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_RNTO, lpszDest, 0, 0, 0))
2186 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2189 if (nResCode == 250)
2192 FTP_SetResponseError(nResCode);
2195 hIC = lpwfs->lpAppInfo;
2196 if (hIC->hdr.dwFlags & INTERNET_FLAG_ASYNC)
2198 INTERNET_ASYNC_RESULT iar;
2200 iar.dwResult = (DWORD)bSuccess;
2201 iar.dwError = bSuccess ? ERROR_SUCCESS : INTERNET_GetLastError();
2202 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext, INTERNET_STATUS_REQUEST_COMPLETE,
2203 &iar, sizeof(INTERNET_ASYNC_RESULT));
2209 /***********************************************************************
2210 * FtpCommandA (WININET.@)
2212 BOOL WINAPI FtpCommandA( HINTERNET hConnect, BOOL fExpectResponse, DWORD dwFlags,
2213 LPCSTR lpszCommand, DWORD_PTR dwContext, HINTERNET* phFtpCommand )
2218 TRACE("%p %d 0x%08x %s 0x%08lx %p\n", hConnect, fExpectResponse, dwFlags,
2219 debugstr_a(lpszCommand), dwContext, phFtpCommand);
2221 if (fExpectResponse)
2223 FIXME("data connection not supported\n");
2227 if (!lpszCommand || !lpszCommand[0])
2229 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2233 if (!(cmdW = heap_strdupAtoW(lpszCommand)))
2235 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2239 r = FtpCommandW(hConnect, fExpectResponse, dwFlags, cmdW, dwContext, phFtpCommand);
2241 HeapFree(GetProcessHeap(), 0, cmdW);
2245 /***********************************************************************
2246 * FtpCommandW (WININET.@)
2248 BOOL WINAPI FtpCommandW( HINTERNET hConnect, BOOL fExpectResponse, DWORD dwFlags,
2249 LPCWSTR lpszCommand, DWORD_PTR dwContext, HINTERNET* phFtpCommand )
2252 ftp_session_t *lpwfs;
2254 DWORD len, nBytesSent= 0;
2255 INT nResCode, nRC = 0;
2257 TRACE("%p %d 0x%08x %s 0x%08lx %p\n", hConnect, fExpectResponse, dwFlags,
2258 debugstr_w(lpszCommand), dwContext, phFtpCommand);
2260 if (!lpszCommand || !lpszCommand[0])
2262 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2266 if (fExpectResponse)
2268 FIXME("data connection not supported\n");
2272 lpwfs = (ftp_session_t*) WININET_GetObject( hConnect );
2275 INTERNET_SetLastError(ERROR_INVALID_HANDLE);
2279 if (WH_HFTPSESSION != lpwfs->hdr.htype)
2281 INTERNET_SetLastError(ERROR_INTERNET_INCORRECT_HANDLE_TYPE);
2285 if (lpwfs->download_in_progress != NULL)
2287 INTERNET_SetLastError(ERROR_FTP_TRANSFER_IN_PROGRESS);
2291 len = WideCharToMultiByte(CP_ACP, 0, lpszCommand, -1, NULL, 0, NULL, NULL) + strlen(szCRLF);
2292 if ((cmd = HeapAlloc(GetProcessHeap(), 0, len )))
2293 WideCharToMultiByte(CP_ACP, 0, lpszCommand, -1, cmd, len, NULL, NULL);
2296 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2300 strcat(cmd, szCRLF);
2303 TRACE("Sending (%s) len(%d)\n", cmd, len);
2304 while ((nBytesSent < len) && (nRC != -1))
2306 nRC = send(lpwfs->sndSocket, cmd + nBytesSent, len - nBytesSent, 0);
2310 TRACE("Sent %d bytes\n", nRC);
2316 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2317 if (nResCode > 0 && nResCode < 400)
2320 FTP_SetResponseError(nResCode);
2324 WININET_Release( &lpwfs->hdr );
2325 HeapFree(GetProcessHeap(), 0, cmd);
2330 /***********************************************************************
2331 * FTPSESSION_Destroy (internal)
2333 * Deallocate session handle
2335 static void FTPSESSION_Destroy(object_header_t *hdr)
2337 ftp_session_t *lpwfs = (ftp_session_t*) hdr;
2341 WININET_Release(&lpwfs->lpAppInfo->hdr);
2343 HeapFree(GetProcessHeap(), 0, lpwfs->lpszPassword);
2344 HeapFree(GetProcessHeap(), 0, lpwfs->lpszUserName);
2345 HeapFree(GetProcessHeap(), 0, lpwfs->servername);
2346 HeapFree(GetProcessHeap(), 0, lpwfs);
2349 static void FTPSESSION_CloseConnection(object_header_t *hdr)
2351 ftp_session_t *lpwfs = (ftp_session_t*) hdr;
2355 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext,
2356 INTERNET_STATUS_CLOSING_CONNECTION, 0, 0);
2358 if (lpwfs->download_in_progress != NULL)
2359 lpwfs->download_in_progress->session_deleted = TRUE;
2361 if (lpwfs->sndSocket != -1)
2362 closesocket(lpwfs->sndSocket);
2364 if (lpwfs->lstnSocket != -1)
2365 closesocket(lpwfs->lstnSocket);
2367 if (lpwfs->pasvSocket != -1)
2368 closesocket(lpwfs->pasvSocket);
2370 SendAsyncCallback(&lpwfs->hdr, lpwfs->hdr.dwContext,
2371 INTERNET_STATUS_CONNECTION_CLOSED, 0, 0);
2374 static DWORD FTPSESSION_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
2377 case INTERNET_OPTION_HANDLE_TYPE:
2378 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
2380 if (*size < sizeof(ULONG))
2381 return ERROR_INSUFFICIENT_BUFFER;
2383 *size = sizeof(DWORD);
2384 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_CONNECT_FTP;
2385 return ERROR_SUCCESS;
2388 return INET_QueryOption(option, buffer, size, unicode);
2391 static const object_vtbl_t FTPSESSIONVtbl = {
2393 FTPSESSION_CloseConnection,
2394 FTPSESSION_QueryOption,
2404 /***********************************************************************
2405 * FTP_Connect (internal)
2407 * Connect to a ftp server
2410 * HINTERNET a session handle on success
2415 * Windows uses 'anonymous' as the username, when given a NULL username
2416 * and a NULL password. The password is first looked up in:
2418 * HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\EmailName
2420 * If this entry is not present it uses the current username as the password.
2424 HINTERNET FTP_Connect(appinfo_t *hIC, LPCWSTR lpszServerName,
2425 INTERNET_PORT nServerPort, LPCWSTR lpszUserName,
2426 LPCWSTR lpszPassword, DWORD dwFlags, DWORD_PTR dwContext,
2427 DWORD dwInternalFlags)
2429 static const WCHAR szKey[] = {'S','o','f','t','w','a','r','e','\\',
2430 'M','i','c','r','o','s','o','f','t','\\',
2431 'W','i','n','d','o','w','s','\\',
2432 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2433 'I','n','t','e','r','n','e','t',' ','S','e','t','t','i','n','g','s',0};
2434 static const WCHAR szValue[] = {'E','m','a','i','l','N','a','m','e',0};
2435 static const WCHAR szDefaultUsername[] = {'a','n','o','n','y','m','o','u','s','\0'};
2436 static const WCHAR szEmpty[] = {'\0'};
2437 struct sockaddr_in socketAddr;
2440 BOOL bSuccess = FALSE;
2441 ftp_session_t *lpwfs = NULL;
2442 HINTERNET handle = NULL;
2444 TRACE("%p Server(%s) Port(%d) User(%s) Paswd(%s)\n",
2445 hIC, debugstr_w(lpszServerName),
2446 nServerPort, debugstr_w(lpszUserName), debugstr_w(lpszPassword));
2448 assert( hIC->hdr.htype == WH_HINIT );
2450 if ((!lpszUserName || !*lpszUserName) && lpszPassword && *lpszPassword)
2452 INTERNET_SetLastError(ERROR_INVALID_PARAMETER);
2456 lpwfs = HeapAlloc(GetProcessHeap(), 0, sizeof(ftp_session_t));
2459 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2463 if (nServerPort == INTERNET_INVALID_PORT_NUMBER)
2464 lpwfs->serverport = INTERNET_DEFAULT_FTP_PORT;
2466 lpwfs->serverport = nServerPort;
2468 lpwfs->hdr.htype = WH_HFTPSESSION;
2469 lpwfs->hdr.vtbl = &FTPSESSIONVtbl;
2470 lpwfs->hdr.dwFlags = dwFlags;
2471 lpwfs->hdr.dwContext = dwContext;
2472 lpwfs->hdr.dwInternalFlags = dwInternalFlags;
2473 lpwfs->hdr.refs = 1;
2474 lpwfs->hdr.lpfnStatusCB = hIC->hdr.lpfnStatusCB;
2475 lpwfs->download_in_progress = NULL;
2476 lpwfs->sndSocket = -1;
2477 lpwfs->lstnSocket = -1;
2478 lpwfs->pasvSocket = -1;
2480 WININET_AddRef( &hIC->hdr );
2481 lpwfs->lpAppInfo = hIC;
2482 list_add_head( &hIC->hdr.children, &lpwfs->hdr.entry );
2484 handle = WININET_AllocHandle( &lpwfs->hdr );
2487 ERR("Failed to alloc handle\n");
2488 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2492 if(hIC->lpszProxy && hIC->dwAccessType == INTERNET_OPEN_TYPE_PROXY) {
2493 if(strchrW(hIC->lpszProxy, ' '))
2494 FIXME("Several proxies not implemented.\n");
2495 if(hIC->lpszProxyBypass)
2496 FIXME("Proxy bypass is ignored.\n");
2498 if (!lpszUserName || !strlenW(lpszUserName)) {
2500 WCHAR szPassword[MAX_PATH];
2501 DWORD len = sizeof(szPassword);
2503 lpwfs->lpszUserName = heap_strdupW(szDefaultUsername);
2505 RegOpenKeyW(HKEY_CURRENT_USER, szKey, &key);
2506 if (RegQueryValueExW(key, szValue, NULL, NULL, (LPBYTE)szPassword, &len)) {
2507 /* Nothing in the registry, get the username and use that as the password */
2508 if (!GetUserNameW(szPassword, &len)) {
2509 /* Should never get here, but use an empty password as failsafe */
2510 strcpyW(szPassword, szEmpty);
2515 TRACE("Password used for anonymous ftp : (%s)\n", debugstr_w(szPassword));
2516 lpwfs->lpszPassword = heap_strdupW(szPassword);
2519 lpwfs->lpszUserName = heap_strdupW(lpszUserName);
2520 lpwfs->lpszPassword = heap_strdupW(lpszPassword ? lpszPassword : szEmpty);
2522 lpwfs->servername = heap_strdupW(lpszServerName);
2524 /* Don't send a handle created callback if this handle was created with InternetOpenUrl */
2525 if (!(lpwfs->hdr.dwInternalFlags & INET_OPENURL))
2527 INTERNET_ASYNC_RESULT iar;
2529 iar.dwResult = (DWORD_PTR)handle;
2530 iar.dwError = ERROR_SUCCESS;
2532 SendAsyncCallback(&hIC->hdr, dwContext,
2533 INTERNET_STATUS_HANDLE_CREATED, &iar,
2534 sizeof(INTERNET_ASYNC_RESULT));
2537 SendAsyncCallback(&hIC->hdr, dwContext, INTERNET_STATUS_RESOLVING_NAME,
2538 (LPWSTR) lpszServerName, strlenW(lpszServerName));
2540 sock_namelen = sizeof(socketAddr);
2541 if (!GetAddress(lpszServerName, lpwfs->serverport, (struct sockaddr *)&socketAddr, &sock_namelen))
2543 INTERNET_SetLastError(ERROR_INTERNET_NAME_NOT_RESOLVED);
2547 SendAsyncCallback(&hIC->hdr, dwContext, INTERNET_STATUS_NAME_RESOLVED,
2548 (LPWSTR) lpszServerName, strlenW(lpszServerName));
2550 if (socketAddr.sin_family != AF_INET)
2552 WARN("unsupported address family %d\n", socketAddr.sin_family);
2553 INTERNET_SetLastError(ERROR_INTERNET_CANNOT_CONNECT);
2556 nsocket = socket(AF_INET,SOCK_STREAM,0);
2559 INTERNET_SetLastError(ERROR_INTERNET_CANNOT_CONNECT);
2563 SendAsyncCallback(&hIC->hdr, dwContext, INTERNET_STATUS_CONNECTING_TO_SERVER,
2564 &socketAddr, sock_namelen);
2566 if (connect(nsocket, (struct sockaddr *)&socketAddr, sock_namelen) < 0)
2568 ERR("Unable to connect (%s)\n", strerror(errno));
2569 INTERNET_SetLastError(ERROR_INTERNET_CANNOT_CONNECT);
2570 closesocket(nsocket);
2574 TRACE("Connected to server\n");
2575 lpwfs->sndSocket = nsocket;
2576 SendAsyncCallback(&hIC->hdr, dwContext, INTERNET_STATUS_CONNECTED_TO_SERVER,
2577 &socketAddr, sock_namelen);
2579 sock_namelen = sizeof(lpwfs->socketAddress);
2580 getsockname(nsocket, (struct sockaddr *) &lpwfs->socketAddress, &sock_namelen);
2582 if (FTP_ConnectToHost(lpwfs))
2584 TRACE("Successfully logged into server\n");
2590 if (lpwfs) WININET_Release( &lpwfs->hdr );
2592 if (!bSuccess && handle)
2594 WININET_FreeHandle( handle );
2602 /***********************************************************************
2603 * FTP_ConnectToHost (internal)
2605 * Connect to a ftp server
2612 static BOOL FTP_ConnectToHost(ftp_session_t *lpwfs)
2615 BOOL bSuccess = FALSE;
2618 FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2620 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_USER, lpwfs->lpszUserName, 0, 0, 0))
2623 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2626 /* Login successful... */
2627 if (nResCode == 230)
2629 /* User name okay, need password... */
2630 else if (nResCode == 331)
2631 bSuccess = FTP_SendPassword(lpwfs);
2632 /* Need account for login... */
2633 else if (nResCode == 332)
2634 bSuccess = FTP_SendAccount(lpwfs);
2636 FTP_SetResponseError(nResCode);
2639 TRACE("Returning %d\n", bSuccess);
2645 /***********************************************************************
2646 * FTP_SendCommandA (internal)
2648 * Send command to server
2655 static BOOL FTP_SendCommandA(INT nSocket, FTP_COMMAND ftpCmd, LPCSTR lpszParam,
2656 INTERNET_STATUS_CALLBACK lpfnStatusCB, object_header_t *hdr, DWORD_PTR dwContext)
2660 DWORD nBytesSent = 0;
2664 TRACE("%d: (%s) %d\n", ftpCmd, lpszParam, nSocket);
2668 lpfnStatusCB(hdr->hInternet, dwContext, INTERNET_STATUS_SENDING_REQUEST, NULL, 0);
2671 dwParamLen = lpszParam?strlen(lpszParam)+1:0;
2672 len = dwParamLen + strlen(szFtpCommands[ftpCmd]) + strlen(szCRLF);
2673 if (NULL == (buf = HeapAlloc(GetProcessHeap(), 0, len+1)))
2675 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
2678 sprintf(buf, "%s%s%s%s", szFtpCommands[ftpCmd], dwParamLen ? " " : "",
2679 dwParamLen ? lpszParam : "", szCRLF);
2681 TRACE("Sending (%s) len(%d)\n", buf, len);
2682 while((nBytesSent < len) && (nRC != -1))
2684 nRC = send(nSocket, buf+nBytesSent, len - nBytesSent, 0);
2688 HeapFree(GetProcessHeap(), 0, (LPVOID)buf);
2692 lpfnStatusCB(hdr->hInternet, dwContext, INTERNET_STATUS_REQUEST_SENT,
2693 &nBytesSent, sizeof(DWORD));
2696 TRACE("Sent %d bytes\n", nBytesSent);
2700 /***********************************************************************
2701 * FTP_SendCommand (internal)
2703 * Send command to server
2710 static BOOL FTP_SendCommand(INT nSocket, FTP_COMMAND ftpCmd, LPCWSTR lpszParam,
2711 INTERNET_STATUS_CALLBACK lpfnStatusCB, object_header_t *hdr, DWORD_PTR dwContext)
2714 LPSTR lpszParamA = heap_strdupWtoA(lpszParam);
2715 ret = FTP_SendCommandA(nSocket, ftpCmd, lpszParamA, lpfnStatusCB, hdr, dwContext);
2716 HeapFree(GetProcessHeap(), 0, lpszParamA);
2720 /***********************************************************************
2721 * FTP_ReceiveResponse (internal)
2723 * Receive response from server
2726 * Reply code on success
2730 INT FTP_ReceiveResponse(ftp_session_t *lpwfs, DWORD_PTR dwContext)
2732 LPSTR lpszResponse = INTERNET_GetResponseBuffer();
2735 char firstprefix[5];
2736 BOOL multiline = FALSE;
2738 TRACE("socket(%d)\n", lpwfs->sndSocket);
2740 SendAsyncCallback(&lpwfs->hdr, dwContext, INTERNET_STATUS_RECEIVING_RESPONSE, NULL, 0);
2744 if (!INTERNET_GetNextLine(lpwfs->sndSocket, &nRecv))
2751 if(lpszResponse[3] != '-')
2754 { /* Start of multiline response. Loop until we get "nnn " */
2756 memcpy(firstprefix, lpszResponse, 3);
2757 firstprefix[3] = ' ';
2758 firstprefix[4] = '\0';
2763 if(!memcmp(firstprefix, lpszResponse, 4))
2771 rc = atoi(lpszResponse);
2773 SendAsyncCallback(&lpwfs->hdr, dwContext, INTERNET_STATUS_RESPONSE_RECEIVED,
2774 &nRecv, sizeof(DWORD));
2778 TRACE("return %d\n", rc);
2783 /***********************************************************************
2784 * FTP_SendPassword (internal)
2786 * Send password to ftp server
2793 static BOOL FTP_SendPassword(ftp_session_t *lpwfs)
2796 BOOL bSuccess = FALSE;
2799 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_PASS, lpwfs->lpszPassword, 0, 0, 0))
2802 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2805 TRACE("Received reply code %d\n", nResCode);
2806 /* Login successful... */
2807 if (nResCode == 230)
2809 /* Command not implemented, superfluous at the server site... */
2810 /* Need account for login... */
2811 else if (nResCode == 332)
2812 bSuccess = FTP_SendAccount(lpwfs);
2814 FTP_SetResponseError(nResCode);
2818 TRACE("Returning %d\n", bSuccess);
2823 /***********************************************************************
2824 * FTP_SendAccount (internal)
2833 static BOOL FTP_SendAccount(ftp_session_t *lpwfs)
2836 BOOL bSuccess = FALSE;
2839 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_ACCT, szNoAccount, 0, 0, 0))
2842 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2846 FTP_SetResponseError(nResCode);
2853 /***********************************************************************
2854 * FTP_SendStore (internal)
2856 * Send request to upload file to ftp server
2863 static BOOL FTP_SendStore(ftp_session_t *lpwfs, LPCWSTR lpszRemoteFile, DWORD dwType)
2866 BOOL bSuccess = FALSE;
2869 if (!FTP_InitListenSocket(lpwfs))
2872 if (!FTP_SendType(lpwfs, dwType))
2875 if (!FTP_SendPortOrPasv(lpwfs))
2878 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_STOR, lpszRemoteFile, 0, 0, 0))
2880 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
2883 if (nResCode == 150 || nResCode == 125)
2886 FTP_SetResponseError(nResCode);
2890 if (!bSuccess && lpwfs->lstnSocket != -1)
2892 closesocket(lpwfs->lstnSocket);
2893 lpwfs->lstnSocket = -1;
2900 /***********************************************************************
2901 * FTP_InitListenSocket (internal)
2903 * Create a socket to listen for server response
2910 static BOOL FTP_InitListenSocket(ftp_session_t *lpwfs)
2912 BOOL bSuccess = FALSE;
2913 socklen_t namelen = sizeof(lpwfs->lstnSocketAddress);
2917 lpwfs->lstnSocket = socket(PF_INET, SOCK_STREAM, 0);
2918 if (lpwfs->lstnSocket == -1)
2920 TRACE("Unable to create listening socket\n");
2924 /* We obtain our ip addr from the name of the command channel socket */
2925 lpwfs->lstnSocketAddress = lpwfs->socketAddress;
2927 /* and get the system to assign us a port */
2928 lpwfs->lstnSocketAddress.sin_port = htons(0);
2930 if (bind(lpwfs->lstnSocket,(struct sockaddr *) &lpwfs->lstnSocketAddress, sizeof(lpwfs->lstnSocketAddress)) == -1)
2932 TRACE("Unable to bind socket\n");
2936 if (listen(lpwfs->lstnSocket, MAX_BACKLOG) == -1)
2938 TRACE("listen failed\n");
2942 if (getsockname(lpwfs->lstnSocket, (struct sockaddr *) &lpwfs->lstnSocketAddress, &namelen) != -1)
2946 if (!bSuccess && lpwfs->lstnSocket != -1)
2948 closesocket(lpwfs->lstnSocket);
2949 lpwfs->lstnSocket = -1;
2956 /***********************************************************************
2957 * FTP_SendType (internal)
2959 * Tell server type of data being transferred
2965 * W98SE doesn't cache the type that's currently set
2966 * (i.e. it sends it always),
2967 * so we probably don't want to do that either.
2969 static BOOL FTP_SendType(ftp_session_t *lpwfs, DWORD dwType)
2972 WCHAR type[] = { 'I','\0' };
2973 BOOL bSuccess = FALSE;
2976 if (dwType & INTERNET_FLAG_TRANSFER_ASCII)
2979 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_TYPE, type, 0, 0, 0))
2982 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext)/100;
2988 FTP_SetResponseError(nResCode);
2996 #if 0 /* FIXME: should probably be used for FtpGetFileSize */
2997 /***********************************************************************
2998 * FTP_GetFileSize (internal)
3000 * Retrieves from the server the size of the given file
3007 static BOOL FTP_GetFileSize(ftp_session_t *lpwfs, LPCWSTR lpszRemoteFile, DWORD *dwSize)
3010 BOOL bSuccess = FALSE;
3014 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_SIZE, lpszRemoteFile, 0, 0, 0))
3017 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
3020 if (nResCode == 213) {
3021 /* Now parses the output to get the actual file size */
3023 LPSTR lpszResponseBuffer = INTERNET_GetResponseBuffer();
3025 for (i = 0; (lpszResponseBuffer[i] != ' ') && (lpszResponseBuffer[i] != '\0'); i++) ;
3026 if (lpszResponseBuffer[i] == '\0') return FALSE;
3027 *dwSize = atol(&(lpszResponseBuffer[i + 1]));
3031 FTP_SetResponseError(nResCode);
3041 /***********************************************************************
3042 * FTP_SendPort (internal)
3044 * Tell server which port to use
3051 static BOOL FTP_SendPort(ftp_session_t *lpwfs)
3053 static const WCHAR szIPFormat[] = {'%','d',',','%','d',',','%','d',',','%','d',',','%','d',',','%','d','\0'};
3055 WCHAR szIPAddress[64];
3056 BOOL bSuccess = FALSE;
3059 sprintfW(szIPAddress, szIPFormat,
3060 lpwfs->lstnSocketAddress.sin_addr.s_addr&0x000000FF,
3061 (lpwfs->lstnSocketAddress.sin_addr.s_addr&0x0000FF00)>>8,
3062 (lpwfs->lstnSocketAddress.sin_addr.s_addr&0x00FF0000)>>16,
3063 (lpwfs->lstnSocketAddress.sin_addr.s_addr&0xFF000000)>>24,
3064 lpwfs->lstnSocketAddress.sin_port & 0xFF,
3065 (lpwfs->lstnSocketAddress.sin_port & 0xFF00)>>8);
3067 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_PORT, szIPAddress, 0, 0, 0))
3070 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
3073 if (nResCode == 200)
3076 FTP_SetResponseError(nResCode);
3084 /***********************************************************************
3085 * FTP_DoPassive (internal)
3087 * Tell server that we want to do passive transfers
3088 * and connect data socket
3095 static BOOL FTP_DoPassive(ftp_session_t *lpwfs)
3098 BOOL bSuccess = FALSE;
3101 if (!FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_PASV, NULL, 0, 0, 0))
3104 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
3107 if (nResCode == 227)
3109 LPSTR lpszResponseBuffer = INTERNET_GetResponseBuffer();
3113 char *pAddr, *pPort;
3115 struct sockaddr_in dataSocketAddress;
3117 p = lpszResponseBuffer+4; /* skip status code */
3118 while (*p != '\0' && (*p < '0' || *p > '9')) p++;
3122 ERR("no address found in response, aborting\n");
3126 if (sscanf(p, "%d,%d,%d,%d,%d,%d", &f[0], &f[1], &f[2], &f[3],
3129 ERR("unknown response address format '%s', aborting\n", p);
3132 for (i=0; i < 6; i++)
3135 dataSocketAddress = lpwfs->socketAddress;
3136 pAddr = (char *)&(dataSocketAddress.sin_addr.s_addr);
3137 pPort = (char *)&(dataSocketAddress.sin_port);
3145 nsocket = socket(AF_INET,SOCK_STREAM,0);
3149 if (connect(nsocket, (struct sockaddr *)&dataSocketAddress, sizeof(dataSocketAddress)))
3151 ERR("can't connect passive FTP data port.\n");
3152 closesocket(nsocket);
3155 lpwfs->pasvSocket = nsocket;
3159 FTP_SetResponseError(nResCode);
3167 static BOOL FTP_SendPortOrPasv(ftp_session_t *lpwfs)
3169 if (lpwfs->hdr.dwFlags & INTERNET_FLAG_PASSIVE)
3171 if (!FTP_DoPassive(lpwfs))
3176 if (!FTP_SendPort(lpwfs))
3183 /***********************************************************************
3184 * FTP_GetDataSocket (internal)
3186 * Either accepts an incoming data socket connection from the server
3187 * or just returns the already opened socket after a PASV command
3188 * in case of passive FTP.
3196 static BOOL FTP_GetDataSocket(ftp_session_t *lpwfs, LPINT nDataSocket)
3198 struct sockaddr_in saddr;
3199 socklen_t addrlen = sizeof(struct sockaddr);
3202 if (lpwfs->hdr.dwFlags & INTERNET_FLAG_PASSIVE)
3204 *nDataSocket = lpwfs->pasvSocket;
3205 lpwfs->pasvSocket = -1;
3209 *nDataSocket = accept(lpwfs->lstnSocket, (struct sockaddr *) &saddr, &addrlen);
3210 closesocket(lpwfs->lstnSocket);
3211 lpwfs->lstnSocket = -1;
3213 return *nDataSocket != -1;
3217 /***********************************************************************
3218 * FTP_SendData (internal)
3220 * Send data to the server
3227 static BOOL FTP_SendData(ftp_session_t *lpwfs, INT nDataSocket, HANDLE hFile)
3229 BY_HANDLE_FILE_INFORMATION fi;
3230 DWORD nBytesRead = 0;
3231 DWORD nBytesSent = 0;
3232 DWORD nTotalSent = 0;
3233 DWORD nBytesToSend, nLen;
3235 time_t s_long_time, e_long_time;
3240 lpszBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(CHAR)*DATA_PACKET_SIZE);
3242 /* Get the size of the file. */
3243 GetFileInformationByHandle(hFile, &fi);
3248 nBytesToSend = nBytesRead - nBytesSent;
3250 if (nBytesToSend <= 0)
3252 /* Read data from file. */
3254 if (!ReadFile(hFile, lpszBuffer, DATA_PACKET_SIZE, &nBytesRead, 0))
3255 ERR("Failed reading from file\n");
3258 nBytesToSend = nBytesRead;
3263 nLen = DATA_PACKET_SIZE < nBytesToSend ?
3264 DATA_PACKET_SIZE : nBytesToSend;
3265 nRC = send(nDataSocket, lpszBuffer, nLen, 0);
3273 /* Do some computation to display the status. */
3275 nSeconds = e_long_time - s_long_time;
3276 if( nSeconds / 60 > 0 )
3278 TRACE( "%d bytes of %d bytes (%d%%) in %d min %d sec estimated remaining time %d sec\n",
3279 nTotalSent, fi.nFileSizeLow, nTotalSent*100/fi.nFileSizeLow, nSeconds / 60,
3280 nSeconds % 60, (fi.nFileSizeLow - nTotalSent) * nSeconds / nTotalSent );
3284 TRACE( "%d bytes of %d bytes (%d%%) in %d sec estimated remaining time %d sec\n",
3285 nTotalSent, fi.nFileSizeLow, nTotalSent*100/fi.nFileSizeLow, nSeconds,
3286 (fi.nFileSizeLow - nTotalSent) * nSeconds / nTotalSent);
3288 } while (nRC != -1);
3290 TRACE("file transfer complete!\n");
3292 HeapFree(GetProcessHeap(), 0, lpszBuffer);
3298 /***********************************************************************
3299 * FTP_SendRetrieve (internal)
3301 * Send request to retrieve a file
3304 * Number of bytes to be received on success
3308 static BOOL FTP_SendRetrieve(ftp_session_t *lpwfs, LPCWSTR lpszRemoteFile, DWORD dwType)
3314 if (!(ret = FTP_InitListenSocket(lpwfs)))
3317 if (!(ret = FTP_SendType(lpwfs, dwType)))
3320 if (!(ret = FTP_SendPortOrPasv(lpwfs)))
3323 if (!(ret = FTP_SendCommand(lpwfs->sndSocket, FTP_CMD_RETR, lpszRemoteFile, 0, 0, 0)))
3326 nResCode = FTP_ReceiveResponse(lpwfs, lpwfs->hdr.dwContext);
3327 if ((nResCode != 125) && (nResCode != 150)) {
3328 /* That means that we got an error getting the file. */
3329 FTP_SetResponseError(nResCode);
3334 if (!ret && lpwfs->lstnSocket != -1)
3336 closesocket(lpwfs->lstnSocket);
3337 lpwfs->lstnSocket = -1;
3344 /***********************************************************************
3345 * FTP_RetrieveData (internal)
3347 * Retrieve data from server
3354 static BOOL FTP_RetrieveFileData(ftp_session_t *lpwfs, INT nDataSocket, HANDLE hFile)
3356 DWORD nBytesWritten;
3362 lpszBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(CHAR)*DATA_PACKET_SIZE);
3363 if (NULL == lpszBuffer)
3365 INTERNET_SetLastError(ERROR_OUTOFMEMORY);
3371 nRC = recv(nDataSocket, lpszBuffer, DATA_PACKET_SIZE, 0);
3374 /* other side closed socket. */
3377 WriteFile(hFile, lpszBuffer, nRC, &nBytesWritten, NULL);
3381 TRACE("Data transfer complete\n");
3384 HeapFree(GetProcessHeap(), 0, lpszBuffer);
3389 /***********************************************************************
3390 * FTPFINDNEXT_Destroy (internal)
3392 * Deallocate session handle
3394 static void FTPFINDNEXT_Destroy(object_header_t *hdr)
3396 LPWININETFTPFINDNEXTW lpwfn = (LPWININETFTPFINDNEXTW) hdr;
3401 WININET_Release(&lpwfn->lpFtpSession->hdr);
3403 for (i = 0; i < lpwfn->size; i++)
3405 HeapFree(GetProcessHeap(), 0, lpwfn->lpafp[i].lpszName);
3408 HeapFree(GetProcessHeap(), 0, lpwfn->lpafp);
3409 HeapFree(GetProcessHeap(), 0, lpwfn);
3412 static DWORD FTPFINDNEXT_FindNextFileProc(WININETFTPFINDNEXTW *find, LPVOID data)
3414 WIN32_FIND_DATAW *find_data = data;
3415 DWORD res = ERROR_SUCCESS;
3417 TRACE("index(%d) size(%d)\n", find->index, find->size);
3419 ZeroMemory(find_data, sizeof(WIN32_FIND_DATAW));
3421 if (find->index < find->size) {
3422 FTP_ConvertFileProp(&find->lpafp[find->index], find_data);
3425 TRACE("Name: %s\nSize: %d\n", debugstr_w(find_data->cFileName), find_data->nFileSizeLow);
3427 res = ERROR_NO_MORE_FILES;
3430 if (find->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3432 INTERNET_ASYNC_RESULT iar;
3434 iar.dwResult = (res == ERROR_SUCCESS);
3437 INTERNET_SendCallback(&find->hdr, find->hdr.dwContext,
3438 INTERNET_STATUS_REQUEST_COMPLETE, &iar,
3439 sizeof(INTERNET_ASYNC_RESULT));
3445 static void FTPFINDNEXT_AsyncFindNextFileProc(WORKREQUEST *workRequest)
3447 struct WORKREQ_FTPFINDNEXTW *req = &workRequest->u.FtpFindNextW;
3449 FTPFINDNEXT_FindNextFileProc((WININETFTPFINDNEXTW*)workRequest->hdr, req->lpFindFileData);
3452 static DWORD FTPFINDNEXT_QueryOption(object_header_t *hdr, DWORD option, void *buffer, DWORD *size, BOOL unicode)
3455 case INTERNET_OPTION_HANDLE_TYPE:
3456 TRACE("INTERNET_OPTION_HANDLE_TYPE\n");
3458 if (*size < sizeof(ULONG))
3459 return ERROR_INSUFFICIENT_BUFFER;
3461 *size = sizeof(DWORD);
3462 *(DWORD*)buffer = INTERNET_HANDLE_TYPE_FTP_FIND;
3463 return ERROR_SUCCESS;
3466 return INET_QueryOption(option, buffer, size, unicode);
3469 static DWORD FTPFINDNEXT_FindNextFileW(object_header_t *hdr, void *data)
3471 WININETFTPFINDNEXTW *find = (WININETFTPFINDNEXTW*)hdr;
3473 if (find->lpFtpSession->lpAppInfo->hdr.dwFlags & INTERNET_FLAG_ASYNC)
3475 WORKREQUEST workRequest;
3476 struct WORKREQ_FTPFINDNEXTW *req;
3478 workRequest.asyncproc = FTPFINDNEXT_AsyncFindNextFileProc;
3479 workRequest.hdr = WININET_AddRef( &find->hdr );
3480 req = &workRequest.u.FtpFindNextW;
3481 req->lpFindFileData = data;
3483 INTERNET_AsyncCall(&workRequest);
3485 return ERROR_SUCCESS;
3488 return FTPFINDNEXT_FindNextFileProc(find, data);
3491 static const object_vtbl_t FTPFINDNEXTVtbl = {
3492 FTPFINDNEXT_Destroy,
3494 FTPFINDNEXT_QueryOption,
3501 FTPFINDNEXT_FindNextFileW
3504 /***********************************************************************
3505 * FTP_ReceiveFileList (internal)
3507 * Read file list from server
3510 * Handle to file list on success
3514 static HINTERNET FTP_ReceiveFileList(ftp_session_t *lpwfs, INT nSocket, LPCWSTR lpszSearchFile,
3515 LPWIN32_FIND_DATAW lpFindFileData, DWORD_PTR dwContext)
3518 LPFILEPROPERTIESW lpafp = NULL;
3519 LPWININETFTPFINDNEXTW lpwfn = NULL;
3520 HINTERNET handle = 0;
3522 TRACE("(%p,%d,%s,%p,%08lx)\n", lpwfs, nSocket, debugstr_w(lpszSearchFile), lpFindFileData, dwContext);
3524 if (FTP_ParseDirectory(lpwfs, nSocket, lpszSearchFile, &lpafp, &dwSize))
3527 FTP_ConvertFileProp(lpafp, lpFindFileData);
3529 lpwfn = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WININETFTPFINDNEXTW));
3532 lpwfn->hdr.htype = WH_HFTPFINDNEXT;
3533 lpwfn->hdr.vtbl = &FTPFINDNEXTVtbl;
3534 lpwfn->hdr.dwContext = dwContext;
3535 lpwfn->hdr.refs = 1;
3536 lpwfn->hdr.lpfnStatusCB = lpwfs->hdr.lpfnStatusCB;
3537 lpwfn->index = 1; /* Next index is 1 since we return index 0 */
3538 lpwfn->size = dwSize;
3539 lpwfn->lpafp = lpafp;
3541 WININET_AddRef( &lpwfs->hdr );
3542 lpwfn->lpFtpSession = lpwfs;
3543 list_add_head( &lpwfs->hdr.children, &lpwfn->hdr.entry );
3545 handle = WININET_AllocHandle( &lpwfn->hdr );
3550 WININET_Release( &lpwfn->hdr );
3552 TRACE("Matched %d files\n", dwSize);
3557 /***********************************************************************
3558 * FTP_ConvertFileProp (internal)
3560 * Converts FILEPROPERTIESW struct to WIN32_FIND_DATAA
3567 static BOOL FTP_ConvertFileProp(LPFILEPROPERTIESW lpafp, LPWIN32_FIND_DATAW lpFindFileData)
3569 BOOL bSuccess = FALSE;
3571 ZeroMemory(lpFindFileData, sizeof(WIN32_FIND_DATAW));
3575 SystemTimeToFileTime( &lpafp->tmLastModified, &lpFindFileData->ftLastAccessTime );
3576 lpFindFileData->ftLastWriteTime = lpFindFileData->ftLastAccessTime;
3577 lpFindFileData->ftCreationTime = lpFindFileData->ftLastAccessTime;
3579 /* Not all fields are filled in */
3580 lpFindFileData->nFileSizeHigh = 0; /* We do not handle files bigger than 0xFFFFFFFF bytes yet :-) */
3581 lpFindFileData->nFileSizeLow = lpafp->nSize;
3583 if (lpafp->bIsDirectory)
3584 lpFindFileData->dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
3586 if (lpafp->lpszName)
3587 lstrcpynW(lpFindFileData->cFileName, lpafp->lpszName, MAX_PATH);
3595 /***********************************************************************
3596 * FTP_ParseNextFile (internal)
3598 * Parse the next line in file listing
3604 static BOOL FTP_ParseNextFile(INT nSocket, LPCWSTR lpszSearchFile, LPFILEPROPERTIESW lpfp)
3606 static const char szSpace[] = " \t";
3614 lpfp->lpszName = NULL;
3616 if(!(pszLine = INTERNET_GetNextLine(nSocket, &nBufLen)))
3619 pszToken = strtok(pszLine, szSpace);
3621 * <Permissions> <NoLinks> <owner> <group> <size> <date> <time or year> <filename>
3624 * drwx--s--- 2 pcarrier ens 512 Sep 28 1995 pcarrier
3626 if(!isdigit(pszToken[0]) && 10 == strlen(pszToken)) {
3627 if(!FTP_ParsePermission(pszToken, lpfp))
3628 lpfp->bIsDirectory = FALSE;
3629 for(i=0; i<=3; i++) {
3630 if(!(pszToken = strtok(NULL, szSpace)))
3633 if(!pszToken) continue;
3634 if(lpfp->bIsDirectory) {
3635 TRACE("Is directory\n");
3639 TRACE("Size: %s\n", pszToken);
3640 lpfp->nSize = atol(pszToken);
3643 lpfp->tmLastModified.wSecond = 0;
3644 lpfp->tmLastModified.wMinute = 0;
3645 lpfp->tmLastModified.wHour = 0;
3646 lpfp->tmLastModified.wDay = 0;
3647 lpfp->tmLastModified.wMonth = 0;
3648 lpfp->tmLastModified.wYear = 0;
3650 /* Determine month */
3651 pszToken = strtok(NULL, szSpace);
3652 if(!pszToken) continue;
3653 if(strlen(pszToken) >= 3) {
3655 if((pszTmp = StrStrIA(szMonths, pszToken)))
3656 lpfp->tmLastModified.wMonth = ((pszTmp - szMonths) / 3)+1;
3659 pszToken = strtok(NULL, szSpace);
3660 if(!pszToken) continue;
3661 lpfp->tmLastModified.wDay = atoi(pszToken);
3662 /* Determine time or year */
3663 pszToken = strtok(NULL, szSpace);
3664 if(!pszToken) continue;
3665 if((pszTmp = strchr(pszToken, ':'))) {
3666 SYSTEMTIME curr_time;
3669 lpfp->tmLastModified.wMinute = atoi(pszTmp);
3670 lpfp->tmLastModified.wHour = atoi(pszToken);
3671 GetLocalTime( &curr_time );
3672 lpfp->tmLastModified.wYear = curr_time.wYear;
3675 lpfp->tmLastModified.wYear = atoi(pszToken);
3676 lpfp->tmLastModified.wHour = 12;
3678 TRACE("Mod time: %02d:%02d:%02d %04d/%02d/%02d\n",
3679 lpfp->tmLastModified.wHour, lpfp->tmLastModified.wMinute, lpfp->tmLastModified.wSecond,
3680 lpfp->tmLastModified.wYear, lpfp->tmLastModified.wMonth, lpfp->tmLastModified.wDay);
3682 pszToken = strtok(NULL, szSpace);
3683 if(!pszToken) continue;
3684 lpfp->lpszName = heap_strdupAtoW(pszToken);
3685 TRACE("File: %s\n", debugstr_w(lpfp->lpszName));
3687 /* NT way of parsing ... :
3689 07-13-03 08:55PM <DIR> sakpatch
3690 05-09-03 06:02PM 12656686 2003-04-21bgm_cmd_e.rgz
3692 else if(isdigit(pszToken[0]) && 8 == strlen(pszToken)) {
3693 int mon, mday, year, hour, min;
3694 lpfp->permissions = 0xFFFF; /* No idea, put full permission :-) */
3696 sscanf(pszToken, "%d-%d-%d", &mon, &mday, &year);
3697 lpfp->tmLastModified.wDay = mday;
3698 lpfp->tmLastModified.wMonth = mon;
3699 lpfp->tmLastModified.wYear = year;
3701 /* Hacky and bad Y2K protection :-) */
3702 if (lpfp->tmLastModified.wYear < 70) lpfp->tmLastModified.wYear += 2000;
3704 pszToken = strtok(NULL, szSpace);
3705 if(!pszToken) continue;
3706 sscanf(pszToken, "%d:%d", &hour, &min);
3707 lpfp->tmLastModified.wHour = hour;
3708 lpfp->tmLastModified.wMinute = min;
3709 if((pszToken[5] == 'P') && (pszToken[6] == 'M')) {
3710 lpfp->tmLastModified.wHour += 12;
3712 lpfp->tmLastModified.wSecond = 0;
3714 TRACE("Mod time: %02d:%02d:%02d %04d/%02d/%02d\n",
3715 lpfp->tmLastModified.wHour, lpfp->tmLastModified.wMinute, lpfp->tmLastModified.wSecond,
3716 lpfp->tmLastModified.wYear, lpfp->tmLastModified.wMonth, lpfp->tmLastModified.wDay);
3718 pszToken = strtok(NULL, szSpace);
3719 if(!pszToken) continue;
3720 if(!strcasecmp(pszToken, "<DIR>")) {
3721 lpfp->bIsDirectory = TRUE;
3723 TRACE("Is directory\n");
3726 lpfp->bIsDirectory = FALSE;
3727 lpfp->nSize = atol(pszToken);
3728 TRACE("Size: %d\n", lpfp->nSize);
3731 pszToken = strtok(NULL, szSpace);
3732 if(!pszToken) continue;
3733 lpfp->lpszName = heap_strdupAtoW(pszToken);
3734 TRACE("Name: %s\n", debugstr_w(lpfp->lpszName));
3736 /* EPLF format - http://cr.yp.to/ftp/list/eplf.html */
3737 else if(pszToken[0] == '+') {
3738 FIXME("EPLF Format not implemented\n");
3741 if(lpfp->lpszName) {
3742 if((lpszSearchFile == NULL) ||
3743 (PathMatchSpecW(lpfp->lpszName, lpszSearchFile))) {
3745 TRACE("Matched: %s\n", debugstr_w(lpfp->lpszName));
3748 HeapFree(GetProcessHeap(), 0, lpfp->lpszName);
3749 lpfp->lpszName = NULL;
3756 /***********************************************************************
3757 * FTP_ParseDirectory (internal)
3759 * Parse string of directory information
3765 static BOOL FTP_ParseDirectory(ftp_session_t *lpwfs, INT nSocket, LPCWSTR lpszSearchFile,
3766 LPFILEPROPERTIESW *lpafp, LPDWORD dwfp)
3768 BOOL bSuccess = TRUE;
3769 INT sizeFilePropArray = 500;/*20; */
3770 INT indexFilePropArray = -1;
3774 /* Allocate initial file properties array */
3775 *lpafp = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(FILEPROPERTIESW)*(sizeFilePropArray));
3780 if (indexFilePropArray+1 >= sizeFilePropArray)
3782 LPFILEPROPERTIESW tmpafp;
3784 sizeFilePropArray *= 2;
3785 tmpafp = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *lpafp,
3786 sizeof(FILEPROPERTIESW)*sizeFilePropArray);
3795 indexFilePropArray++;
3796 } while (FTP_ParseNextFile(nSocket, lpszSearchFile, &(*lpafp)[indexFilePropArray]));
3798 if (bSuccess && indexFilePropArray)
3800 if (indexFilePropArray < sizeFilePropArray - 1)
3802 LPFILEPROPERTIESW tmpafp;
3804 tmpafp = HeapReAlloc(GetProcessHeap(), 0, *lpafp,
3805 sizeof(FILEPROPERTIESW)*indexFilePropArray);
3809 *dwfp = indexFilePropArray;
3813 HeapFree(GetProcessHeap(), 0, *lpafp);
3814 INTERNET_SetLastError(ERROR_NO_MORE_FILES);
3822 /***********************************************************************
3823 * FTP_ParsePermission (internal)
3825 * Parse permission string of directory information
3832 static BOOL FTP_ParsePermission(LPCSTR lpszPermission, LPFILEPROPERTIESW lpfp)
3834 BOOL bSuccess = TRUE;
3835 unsigned short nPermission = 0;
3840 if ((*lpszPermission != 'd') && (*lpszPermission != '-') && (*lpszPermission != 'l'))
3846 lpfp->bIsDirectory = (*lpszPermission == 'd');
3852 nPermission |= (*(lpszPermission+1) == 'r' ? 1 : 0) << 8;
3855 nPermission |= (*(lpszPermission+2) == 'w' ? 1 : 0) << 7;
3858 nPermission |= (*(lpszPermission+3) == 'x' ? 1 : 0) << 6;
3861 nPermission |= (*(lpszPermission+4) == 'r' ? 1 : 0) << 5;
3864 nPermission |= (*(lpszPermission+5) == 'w' ? 1 : 0) << 4;
3867 nPermission |= (*(lpszPermission+6) == 'x' ? 1 : 0) << 3;
3870 nPermission |= (*(lpszPermission+7) == 'r' ? 1 : 0) << 2;
3873 nPermission |= (*(lpszPermission+8) == 'w' ? 1 : 0) << 1;
3876 nPermission |= (*(lpszPermission+9) == 'x' ? 1 : 0);
3880 }while (nPos <= nLast);
3882 lpfp->permissions = nPermission;
3887 /***********************************************************************
3888 * FTP_SetResponseError (internal)
3890 * Set the appropriate error code for a given response from the server
3895 static DWORD FTP_SetResponseError(DWORD dwResponse)
3901 case 425: /* Cannot open data connection. */
3902 dwCode = ERROR_INTERNET_CANNOT_CONNECT;
3905 case 426: /* Connection closed, transer aborted. */
3906 dwCode = ERROR_INTERNET_CONNECTION_ABORTED;
3909 case 530: /* Not logged in. Login incorrect. */
3910 dwCode = ERROR_INTERNET_LOGIN_FAILURE;
3913 case 421: /* Service not available - Server may be shutting down. */
3914 case 450: /* File action not taken. File may be busy. */
3915 case 451: /* Action aborted. Server error. */
3916 case 452: /* Action not taken. Insufficient storage space on server. */
3917 case 500: /* Syntax error. Command unrecognized. */
3918 case 501: /* Syntax error. Error in parameters or arguments. */
3919 case 502: /* Command not implemented. */
3920 case 503: /* Bad sequence of commands. */
3921 case 504: /* Command not implemented for that parameter. */
3922 case 532: /* Need account for storing files */
3923 case 550: /* File action not taken. File not found or no access. */
3924 case 551: /* Requested action aborted. Page type unknown */
3925 case 552: /* Action aborted. Exceeded storage allocation */
3926 case 553: /* Action not taken. File name not allowed. */
3929 dwCode = ERROR_INTERNET_EXTENDED_ERROR;
3933 INTERNET_SetLastError(dwCode);