public void Execute(FtpRequest request, FtpSession session) { if (request.Arguments == null || request.Arguments.Trim() == "") { session.Send("501 Missing User Name Argument"); return; } //record user name input session.SetData(UserDataKey, request.Arguments); session.Send("331 Send Password Command"); }
public void Execute(FtpRequest request, FtpSession session) { var inputUser = session.GetData(User.UserDataKey); var inputPass = request.Arguments; if (inputUser == null) { session.Send(SendUserFirst); return; } session.Authenticate(inputUser, inputPass); }
/* Download File */ public void Download(string localFile, string remoteFile) { try { /* Create an FTP Request */ FtpRequest = (FtpWebRequest)FtpWebRequest.Create(InterlocutorAddress + "/" + remoteFile); /* Log in to the FTP Server with the User Name and Password Provided */ FtpRequest.Credentials = new NetworkCredential(UserName, Password); LogInToInterlocutor(InterlocutorAddress); /* When in doubt, use these options */ FtpRequest.UseBinary = true; FtpRequest.UsePassive = true; FtpRequest.KeepAlive = true; /* Specify the Type of FTP Request */ FtpRequest.Method = WebRequestMethods.Ftp.DownloadFile; /* Establish Return Communication with the FTP Server */ FtpResponse = (FtpWebResponse)FtpRequest.GetResponse(); /* Get the FTP Server's Response Stream */ StartDownloadData(localFile, remoteFile, InterlocutorAddress); FtpStream = FtpResponse.GetResponseStream(); /* Open a File Stream to Write the Downloaded File */ FileStream localFileStream = new FileStream(localFile, FileMode.Create); /* Buffer for the Downloaded Data */ byte[] byteBuffer = new byte[BufferSize]; int bytesRead = FtpStream.Read(byteBuffer, 0, BufferSize); /* Download the File by Writing the Buffered Data Until the Transfer is Complete */ try { while (bytesRead > 0) { localFileStream.Write(byteBuffer, 0, bytesRead); bytesRead = FtpStream.Read(byteBuffer, 0, BufferSize); } } finally { /* Resource Cleanup */ localFileStream.Close(); EndDownloadData(localFile, remoteFile, InterlocutorAddress); } } finally { FtpStream.Close(); FtpResponse.Close(); FtpRequest = null; } }
/* Get the Size of a File */ public string GetFileSize(string fileName) { try { /* Create an FTP Request */ FtpRequest = (FtpWebRequest)FtpWebRequest.Create(InterlocutorAddress + "/" + fileName); /* Log in to the FTP Server with the User Name and Password Provided */ FtpRequest.Credentials = new NetworkCredential(UserName, Password); LogInToInterlocutor(InterlocutorAddress); /* When in doubt, use these options */ FtpRequest.UseBinary = true; FtpRequest.UsePassive = true; FtpRequest.KeepAlive = true; /* Specify the Type of FTP Request */ FtpRequest.Method = WebRequestMethods.Ftp.GetFileSize; /* Establish Return Communication with the FTP Server */ FtpResponse = (FtpWebResponse)FtpRequest.GetResponse(); /* Establish Return Communication with the FTP Server */ FtpStream = FtpResponse.GetResponseStream(); /* Get the FTP Server's Response Stream */ StreamReader ftpReader = new StreamReader(FtpStream); /* Store the Raw Response */ string fileInfo = null; /* Read the Full Response Stream */ try { while (ftpReader.Peek() != -1) { fileInfo = ftpReader.ReadToEnd(); } } finally { /* Resource Cleanup */ ftpReader.Close(); } /* Return File Size */ return(fileInfo); } finally { FtpStream.Close(); FtpResponse.Close(); FtpRequest = null; } }
/// <summary> /// Executes a request on the ftp server /// </summary> /// <typeparam name="T">Type of the expected response</typeparam> /// <param name="request">Request to execute</param> /// <returns></returns> public async Task <T> ExecuteAsync <T>(FtpRequest request) where T : FtpResponse { //if (!IsConnected) await ConnectAsync(); // TODO: Implement NotConnectedException if (!IsConnected) { throw new FtpException("Not Connected"); } System.Diagnostics.Debug.WriteLine("EXEC\t:" + (request.Command.StartsWith("PASS") ? "PASS <omitted>" : request.Command)); await WriteLineAsync(Encoding, request.Command); await FlushAsync(); return(await GetReplyAsync <T>()); }
/// <summary> Renombrar un archivo remoto. </summary> /// /// <param name="remotePathFile"> Path del archivo remoto a renombrar. </param> /// <param name="remoteFileNew"> Nuevo nombre del archivo remoto. </param> /// /// <returns></returns> /// public Char FtpRenameFile(string remotePathFile, string remoteFileNew) { Resultado = 'N'; try { if (String.IsNullOrEmpty(FTPHost) || string.IsNullOrEmpty(FTPUser) || FTPPwd == null) { UsrError = "KO - Faltan parámetros de conexión al Host Ftp"; UsrErrorC = -1; Resultado = 'N'; return(Resultado); } FtpRequest = (FtpWebRequest)FtpWebRequest.Create(FTPHost + "/" + remotePathFile); FtpRequest.Credentials = new NetworkCredential(FTPUser, FTPPwd); FtpRequest.Method = WebRequestMethods.Ftp.Rename; FtpRequest.RenameTo = remoteFileNew; // Canal de comunicación con el Host Ftp. FtpResponse = (FtpWebResponse)FtpRequest.GetResponse(); // Cerrar canales de comunicación Ftp. FtpRequest = null; FtpResponse.Close(); Resultado = 'S'; UsrError = "OK"; } catch (Exception ex) { // Error de programa. UsrErrorC = ex.HResult; UsrError = ex.Message; UsrErrorE = ex.StackTrace; Resultado = 'C'; } return(Resultado); }
/* List Directory Contents in Detail (Name, Size, Created, etc.) */ public string[] DirectoryListDetailed(string directory) { try { /* Create an FTP Request */ FtpRequest = (FtpWebRequest)FtpWebRequest.Create(InterlocutorAddress + "/" + directory); /* Log in to the FTP Server with the User Name and Password Provided */ FtpRequest.Credentials = new NetworkCredential(UserName, Password); LogInToInterlocutor(InterlocutorAddress); /* When in doubt, use these options */ FtpRequest.UseBinary = true; FtpRequest.UsePassive = true; FtpRequest.KeepAlive = true; /* Specify the Type of FTP Request */ FtpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; /* Establish Return Communication with the FTP Server */ FtpResponse = (FtpWebResponse)FtpRequest.GetResponse(); /* Establish Return Communication with the FTP Server */ FtpStream = FtpResponse.GetResponseStream(); /* Get the FTP Server's Response Stream */ StreamReader ftpReader = new StreamReader(FtpStream); /* Store the Raw Response */ string directoryRaw = null; /* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */ try { while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + "|"; } } finally { /* Resource Cleanup */ ftpReader.Close(); } /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */ return(directoryRaw.Split("|".ToCharArray())); } finally { FtpStream.Close(); FtpResponse.Close(); FtpRequest = null; } }
bool IFtpModule.HandleRequest(FtpRequest request, ClientData client, FtpHandler handler, Server server) { if (!client.Resources.TryGetResource <FtpData>(out var ftpData)) { client.Resources.SetResource(new FtpData()); } if (request.Command == FtpRequestCommands.STOR) { if (!ftpData.TransferDetails.ConnectionOpen) { handler.QueueFtpResponse(server, client, new FtpResponse { StatusCode = FtpResponseCodes.FileStatusOkay, Message = "Opening data connection" }); ftpData.OpenDataConnection(); } handler.QueueFtpResponse(server, client, this.StoreFile(request, ftpData)); ftpData.CloseDataConnection(); return(true); } else if (request.Command == FtpRequestCommands.DELE) { handler.QueueFtpResponse(server, client, this.RemoveFile(request, ftpData)); return(true); } else if (request.Command == FtpRequestCommands.RETR) { if (!ftpData.TransferDetails.ConnectionOpen) { handler.QueueFtpResponse(server, client, new FtpResponse { StatusCode = FtpResponseCodes.FileStatusOkay, Message = "Opening data connection" }); ftpData.OpenDataConnection(); } handler.QueueFtpResponse(server, client, this.RetrieveFile(request, ftpData)); ftpData.CloseDataConnection(); return(true); } return(false); }
/// <summary> /// Get as many details as it can about the target. /// </summary> /// <param name="target">If empty then will assume CWD has been used</param> /// <returns>May return null if nothing found</returns> public FileSystemFTPInfo GetFileDetails(string target) { List <FileSystemFTPInfo> foundValues; lock (commandLock) { // replace the windows style directory delimiter with a unix style delimiter target = NormaliseForFTP(target); Features featureToUse = ((SupportedFeatures & Features.MLST) == Features.MLST) ? Features.MLST : Features.LIST; if (featureToUse == Features.MLST) { happyCodes = FtpRequest.BuildResponseArray(FtpResponseCode.RequestedFileActionOkayAndCompleted, FtpResponseCode.SyntaxErrorInParametersOrArguments // Stop using exceptions to detect missing ); } else { happyCodes = FtpRequest.BuildResponseArray(FtpResponseCode.DataConnectionAlreadyOpenSoTransferStarting, FtpResponseCode.FileStatusOkaySoAboutToOpenDataConnection, FtpResponseCode.ClosingDataConnection, FtpResponseCode.RequestedFileActionOkayAndCompleted ); } FtpResponseCollection dirResults = (string.IsNullOrEmpty(target)) ? Feature((featureToUse != Features.MLST), featureToUse) : Feature((featureToUse != Features.MLST), featureToUse, true, target); if (featureToUse == Features.MLST) { foundValues = new MlstCollection(this, target, dirResults); } else { // Do it the harder way ?? FtpItemCollection results = new FtpItemCollection(target, dirResults.GetRawText(), ftpInstance.ItemParser); foundValues = FileSystemFTPInfo.ConvertFrom(results, this); } } return(foundValues.Count > 0 ? foundValues[0] : null); }
private FtpResponse RetrieveFile(FtpRequest request, FtpData ftpData) { var path = request.Arguments.Length > 0 ? Path.GetFullPath(ftpData.CurrentDirectory + request.Arguments.Aggregate((prev, next) => prev + " " + next)) : null; if (path != null) { using var fs = File.OpenRead(path); var buffer = new byte[256]; int bytesRead; while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) { ftpData.SendData(buffer, bytesRead); } } return(new FtpResponse { StatusCode = FtpResponseCodes.ClosingDataConnection, Message = "Transfer complete" }); }
//public bool ChangeDirectory(string path) //{ // if (path == null) // throw new ArgumentNullException("path"); // if (path.Length == 0) // throw new ArgumentException("must have a value", "path"); // // replace the windows style directory delimiter with a unix style delimiter // path = NormaliseForFTP( path ); // lock (commandLock) // { // FtpRequest request = new FtpRequest(FtpCmd.Cwd, ftpInstance.CharacterEncoding, path) // { // HappyCodes = // FtpRequest.BuildResponseArray( // FtpResponseCode.RequestedFileActionOkayAndCompleted, // FtpResponseCode.RequestedActionNotTakenFileUnavailable // ) // }; // CheckConnected(); // ftpInstance.SendRequest(request); // return ftpInstance.LastResponse.Code == FtpResponseCode.RequestedFileActionOkayAndCompleted; // } //} public List <FileSystemFTPInfo> GetDirList(string path) { List <FileSystemFTPInfo> foundValues; lock (commandLock) { // replace the windows style directory delimiter with a unix style delimiter path = NormaliseForFTP(path); Features featureToUse = ((SupportedFeatures & Features.MLSD) == Features.MLSD) ? Features.MLSD : Features.LIST; if (featureToUse == Features.MLSD) { happyCodes = FtpRequest.BuildResponseArray(FtpResponseCode.ClosingDataConnection, FtpResponseCode.RequestedFileActionOkayAndCompleted); } else { happyCodes = FtpRequest.BuildResponseArray(FtpResponseCode.DataConnectionAlreadyOpenSoTransferStarting, FtpResponseCode.FileStatusOkaySoAboutToOpenDataConnection, FtpResponseCode.ClosingDataConnection, FtpResponseCode.RequestedFileActionOkayAndCompleted); } FtpResponseCollection dirResults = (string.IsNullOrEmpty(path)) ? Feature((featureToUse != Features.MLSD), featureToUse) : Feature((featureToUse != Features.MLSD), featureToUse, true, path); if (featureToUse == Features.MLSD) { foundValues = new MlstCollection(this, path, dirResults); } else { // Do it the harder way ?? FtpItemCollection results = new FtpItemCollection(path, dirResults.GetRawText(), ftpInstance.ItemParser); foundValues = FileSystemFTPInfo.ConvertFrom(results, this); } } return(foundValues); }
private FtpResponse HandleTypeArguments(FtpRequest request, FtpData ftpData) { if (request.Arguments[0] == "I") { ftpData.TransferDetails.Type = TransferDetails.TransferType.BINARY; return(new FtpResponse { StatusCode = FtpResponseCodes.ActionCompleted, Message = "Set transfer encoding to binary" }); } else if (request.Arguments[0] == "A") { ftpData.TransferDetails.Type = TransferDetails.TransferType.ASCII; return(new FtpResponse { StatusCode = FtpResponseCodes.ActionCompleted, Message = "Set transfer encoding to ASCII" }); } else { return(new FtpResponse { StatusCode = FtpResponseCodes.CommandNotImplementedForParameter, Message = $"Command not implemented for parameter {request.Arguments[0]}" }); } }
private FtpResponse EnablePassiveMode(FtpRequest request, FtpData ftpData, ClientData client) { ftpData.TransferDetails.Socket?.Dispose(); ftpData.TransferDetails.Mode = TransferDetails.TransferMode.Passive; ftpData.TransferDetails.Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ftpData.TransferDetails.Socket.Bind(new IPEndPoint(IPAddress.Any, 0)); var address = ((IPEndPoint)client.Socket.LocalEndPoint).Address.GetAddressBytes(); var portBytes = BitConverter.GetBytes((short)ftpData.TransferDetails.LocalDataPort); if (BitConverter.IsLittleEndian) { Array.Reverse(portBytes); } ftpData.TransferDetails.Socket.Listen(10); return(new FtpResponse { StatusCode = FtpResponseCodes.EnterPassiveMode, Message = $"Entering Passive mode ({address[0]},{address[1]},{address[2]},{address[3]},{portBytes[0]},{portBytes[1]})" }); }
private FtpResponse CreateDirectory(FtpRequest request, FtpData ftpData) { var path = request.Arguments.Length > 0 ? Path.GetFullPath(ftpData.CurrentDirectory + "\\" + request.Arguments.Aggregate((prev, next) => prev + " " + next)) : null; if (path != null) { if (!path.IsSubPathOf(Path.GetFullPath(this.RootPath))) { return(new FtpResponse { StatusCode = FtpResponseCodes.RequestedFileActionNotTaken, Message = "Path not found!" }); } if (!Directory.Exists(path)) { Directory.CreateDirectory(path); return(new FtpResponse { StatusCode = FtpResponseCodes.RequestedFileActionOkay, Message = $"Created directory {request.Arguments[0]}!" }); } else { return(new FtpResponse { StatusCode = FtpResponseCodes.RequestedFileActionNotTaken, Message = $"Directory {request.Arguments[0]} already exists!" }); } } else { return(new FtpResponse { StatusCode = FtpResponseCodes.RequestedActionAborted, Message = $"No path argument provided!" }); } }
/// <summary> Descargar un fichero al servidor Ftp. </summary> /// /// <param name="remoteFile"> Nombre del fichero remoto. </param> /// <param name="localFile"> Nombre del fichero local. </param> /// <param name="crearFichero"> Sobreescribir destino si ya existe. </param> /// /// <returns> Resultado (S/N/C) </returns> /// public Char FtpDownloadFile(string remoteFile, string localFile, int crearFichero = (int)FileMode.Create) { FileStream localFileStream; byte[] byteBuffer; int bytesLeidos; Resultado = 'N'; try { if (String.IsNullOrEmpty(FTPHost) || string.IsNullOrEmpty(FTPUser) || FTPPwd == null) { UsrError = "KO - Faltan parámetros de conexión al Host Ftp"; UsrErrorC = -1; Resultado = 'N'; return(Resultado); } // Conexión con el Host Ftp. FtpRequest = (FtpWebRequest)FtpWebRequest.Create(FTPHost + "/" + remoteFile); FtpRequest.Credentials = new NetworkCredential(FTPUser, FTPPwd); FtpRequest.Method = WebRequestMethods.Ftp.DownloadFile; // Canal de comunicación con el Host Ftp. FtpResponse = (FtpWebResponse)FtpRequest.GetResponse(); // Retorno de comunicación con el Host Ftp. FtpFileStream = FtpResponse.GetResponseStream(); // Canal de comunicación con el fichero local. localFileStream = new FileStream(localFile, FileMode.Create); byteBuffer = new byte[_BYTE_BUFFER]; // Leer datos del fichero remoto y grabar en fichero local. bytesLeidos = FtpFileStream.Read(byteBuffer, 0, _BYTE_BUFFER); while (bytesLeidos > 0) { localFileStream.Write(byteBuffer, 0, _BYTE_BUFFER); bytesLeidos = FtpFileStream.Read(byteBuffer, 0, _BYTE_BUFFER); } // Cerrar canales de comunicación Ftp. localFileStream.Close(); FtpFileStream.Close(); FtpRequest = null; FtpResponse.Close(); Resultado = 'S'; UsrError = "OK"; } catch (Exception ex) { // Error de Ftp. UsrErrorC = ex.HResult; UsrError = ex.Message; UsrErrorE = ex.StackTrace; Resultado = 'C'; } return(Resultado); }
public void Execute(FtpRequest request, FtpSession session) { session.Send(NoopOK); }
/// <summary> /// Opens a data stream. /// </summary> /// <param name='request'>The command to execute that requires a data stream</param> /// <returns>The data stream.</returns> public async Task<StreamChannel> OpenDataStreamAsync(FtpRequest request) { StreamChannel stream = null; FtpDataConnectionType type = m_DataConnectionType; // The PORT and PASV commands do not work with IPv6 so // if either one of those types are set change them // to EPSV or EPRT appropriately. if (m_Stream.LocalEndPoint.Type == HostNameType.Ipv6) { switch (type) { case FtpDataConnectionType.PORT: type = FtpDataConnectionType.EPRT; Debug.WriteLine("Changed data connection type to EPRT because we are connected with IPv6."); break; case FtpDataConnectionType.PASV: case FtpDataConnectionType.PASVEX: type = FtpDataConnectionType.EPSV; Debug.WriteLine("Changed data connection type to EPSV because we are connected with IPv6."); break; } } switch (type) { case FtpDataConnectionType.AutoPassive: case FtpDataConnectionType.EPSV: case FtpDataConnectionType.PASV: case FtpDataConnectionType.PASVEX: stream = await m_Stream.OpenPassiveDataStreamAsync(type, request); break; case FtpDataConnectionType.AutoActive: case FtpDataConnectionType.EPRT: case FtpDataConnectionType.PORT: // TODO: break; } if (stream == null) { throw new InvalidOperationException("The specified data channel type is not implemented."); } return stream; }
public async Task <T> ExecuteInDuplexAsync <T>(FtpDataConnectionType connectionType, FtpRequest request) where T : FtpDuplexReponse { var response = Activator.CreateInstance <T>(); response.Request = request; if (!IsConnected) { throw new FtpException("Not Connected"); } var passiveChannel = await OpenPassiveDataStreamAsync(connectionType, request); string bufferResult; while ((bufferResult = await passiveChannel.ReadLineAsync(Encoding)) != null) { if (bufferResult.Length > 0) { response.MessageBody += bufferResult; System.Diagnostics.Debug.WriteLine(bufferResult); } } var finalResponse = await GetReplyAsync <FtpResponse>(); response.Code = finalResponse.Code; response.InfoMessages += finalResponse.Message; return(response); }
//------------------------------------------------------------------ // Métodos públicos de la clase. //------------------------------------------------------------------ /// <summary> /// /// </summary> /// <param name="remoteFile"> Nombre del fichero remoto. </param> /// /// <returns> Resultado (S/N/C) </returns> /// public Char FtpFileExists(string remoteFile) { // string fileInfo; Innecesario. Resultado = 'N'; try { if (String.IsNullOrEmpty(FTPHost) || string.IsNullOrEmpty(FTPUser) || FTPPwd == null) { UsrError = "KO - Faltan parámetros de conexión al Host Ftp"; UsrErrorC = -1; Resultado = 'N'; return(Resultado); } FtpRequest = (FtpWebRequest)FtpWebRequest.Create(FTPHost + "/" + remoteFile); FtpRequest.Credentials = new NetworkCredential(FTPUser, FTPPwd); FtpRequest.Method = WebRequestMethods.Ftp.GetDateTimestamp; // Canal de comunicación con el Host Ftp. FtpResponse = (FtpWebResponse)FtpRequest.GetResponse(); // Retorno de comunicación con el Host Ftp. FtpFileStream = FtpResponse.GetResponseStream(); // Canal de lectura del Host Ftp. - Innecesario. // FtpStreamReader = new StreamReader(FtpFileStream); // fileInfo = FtpStreamReader.ReadToEnd(); // Cerrar canales de comunicación Ftp. FtpFileStream.Close(); FtpRequest = null; FtpResponse.Close(); Resultado = 'S'; UsrError = "OK"; } catch (WebException ex) when(ex.Status.ToString() == "ProtocolError") { // Error de Ftp. UsrErrorC = ex.HResult; UsrError = ex.Message; UsrErrorE = ex.StackTrace; Resultado = 'N'; } catch (Exception ex) { // Error de programa. UsrErrorC = ex.HResult; UsrError = ex.Message; UsrErrorE = ex.StackTrace; Resultado = 'C'; } return(Resultado); }
public void Execute(FtpRequest request, FtpSession session) { session.Send(Responce_ClosingControl); session.Quit(); }
public async Task <FtpStreamChannel> OpenPassiveDataStreamAsync(FtpDataConnectionType connectionType, FtpRequest request) { FtpPassiveModeResponse reply; if (connectionType == FtpDataConnectionType.EPSV || connectionType == FtpDataConnectionType.AutoPassive) { if (!(reply = await SetExtendedPassiveMode()).Success) { // if we're connected with IPv4 and data channel type is AutoPassive then fallback to IPv4 if (reply.Type == FtpResponseType.PermanentNegativeCompletion && connectionType == FtpDataConnectionType.AutoPassive && LocalEndPoint.Type == HostNameType.Ipv4) { return(await OpenPassiveDataStreamAsync(FtpDataConnectionType.PASV, request)); } throw new FtpCommandException(reply); } } else { if (LocalEndPoint.Type != HostNameType.Ipv4) { throw new FtpException("Only IPv4 is supported by the PASV command. Use EPSV instead."); } if (!(reply = await SetPassiveMode()).Success) { throw new FtpCommandException(reply); } } var passiveConnection = new FtpStreamChannel(); await passiveConnection.ConnectAsync(reply.HostName, reply.ServiceName); // NOTE: Maybe it is better to just to open the passive channel, and execute the command else where.. if (!(await ExecuteAsync <FtpResponse>(request)).Success) { passiveConnection.Dispose(); throw new FtpCommandException(reply); } return(passiveConnection); }