Загрузка/загрузка FTP с CosmosC#

Место общения программистов C#
Ответить
Anonymous
 Загрузка/загрузка FTP с Cosmos

Сообщение Anonymous »

Я размещаю космос Nat OS IT Oracle VirtualBox и использую мостовой адаптер. Я пытаюсь загрузить/загрузить с/на мой FTP -сервер с помощью Filezilla, но, скорее всего, он не может завершить передачу данных. Я тоже выключил брандмауэры, но это не решило проблему. Filezilla записывает следующее, когда я пытаюсь загрузить /загрузить файл: < /p>

[*] Trace: ccontrolsocket :: sendnextcommand () < /li>
trace: cftplogonopdata :: send () в состоянии 0 < /li>
: connopdata :: send (). 192.168.0.45:21...
[*] Статус: Соединение установлено, ожидание приветственного сообщения ... < /li>
трассировка: cftpcontrolsocket :: onreceive () < /li>
Ответ: 220 Служба готова к новому пользователю. Cftplogonopdata :: parseresponse () в состоянии 1 < /li>
трасса: ccontrolsocket :: sendnextcommand () < /li>
trace: cftplogonopdata :: send () в состоянии 2 < /li>
команда: auth tls < /li> < /li>
. CftpControlSocket :: onReceive () < /li>
Ответ: 530 Вход неверно. < /Li>
трассировка: cftplogonopdata :: parseresponse () в состоянии 2 < /li>
trace: ccontrolsocket ::: sendnexmand () < />

Cftplogonopdata :: send () в состоянии 3 < /li>
Команда: Auth ssl < /li>
трассировка: cftpcontrolsocket :: onreceive () < /li>
Ответ: 530 rougin incorrect. Государство 3 < /li>
Статус: небезопасный сервер, он не поддерживает FTP над TLS. < /li>
Trace: CcontrolSocket :: sendnextCommand () < /li>
trace: cftplogonopdata :: send () в состоянии 5 < /li>
CFTPControlSocket :: setAsyncRequestReply < /li>
трасса: ccontrolsocket :: sendnextcommand () < /li>
trace: cftplogonopdata :: send () в состоянии 6 < /li>
Команда: пользовательский тестоер < /li> < /li>
Cftpcontrolsocket :: onreceive ()
[*] Ответ: 331 Имя пользователя ОК, нужен пароль. /> Trace: cftplogonopdata :: send () в состоянии 6 < /li>
Команда: Pass ********* < /li>
Trace: cftpcontrolsocket :: onreceive () < /li>
Ответ: 230 Пользователь, введенный в систему, продолжайте. Cftplogonopdata :: parseresponse () в состоянии 6 < /li>
трасса: ccontrolsocket :: sendnextcommand () < /li>
trace: cftplogonopdata :: send () в состоянии 7 < /li>
команда: syst < /li>
CftpControlSocket :: onReceive () < /li>
Ответ: 215 Cosmosos < /li>
трассировка: cftplogonopdata :: parserestonse () в состоянии 7 < /li>
trace: ccontrolsocket :: sendnextcommand () < /> < />

< /> Cftplogonopdata :: send () в состоянии 8 < /li>
Command: feat < /li>
Trace: cftpcontrolsocket :: onreceive () < /li>
Ответ: 500 Неизвестно. 8 < /li>
Статус: Сервер не поддерживает символы, не являющиеся символами. CControlSocket :: Resetoperation (0)
[*] Trace: cftplogonopdata :: reset (0) в состоянии 15
[*] trace: ccontrolsocket :: sendnextcommand () [*] trace: cftspletopData ::::). /> Статус: извлечение списка каталогов ... < /li>
трасса: cftpchangediropdata :: shend () в состоянии 0 < /li>
трасс: cftpchangediropdata :: send () в состоянии 1 < /li>
: pwd < /li>

Cftpcontrolsocket :: onreceive ()
[*] Ответ: 257 "/" - это текущий каталог. /> Trace: CControlSocket :: Resetoperation (0) < /li>
Trace: cftpchangediropdata :: Reset (0) в состоянии 1 < /li>
trace: cftplistopdata :: subcommandResult (0) в состоянии 1 < /li>
CcontrolSocket :: sendnextCommand ()
[*] трассировка: cftplistopdata :: send () в состоянии 2
[*] trace: cftprawtransferopdata :: send () в состоянии 0
[*] trace: cftprawtransfepra /> Команда: тип i < /li>
trace: cftpControlSocket :: onReceive () < /li>
Ответ: 200 Команда CcontrolSocket :: sendnextCommand () < /li>
трассировка: cftprawtransforpdata :: send () в состоянии 2 < /li>
Команда: pasv < /li>
trace: cftpcontrolsocket :: onReceive () < /li> entrolsocket :: onReceive () entrolSocket: (192,168,0,45,243,131) < /li>
трассировка: cftprawtransferopdata :: parserestonse () в состоянии 2 < /li>
trace: ccontrolsocket :: sendextcommand () < /li>
В состоянии 4 < /li>
Trace: Trace: Suppling Data Connection Source IP для управления источником соединения
ip 192.168.0.151 < /li>
Команда: список < /li>
trace: ctransfersocket :: onconnect < /li>
trace: ctransfersocket :: onconnect < /li>
trace: Cftpcontrolsocket :: onreceive ()
[*] Ответ: 150 Здесь приходит список каталогов. /> trace: cftprawtransferopdata :: send () в состоянии 5 < /li>
trace: cftpcontrolsocket :: onreceive () < /li>
Ответ: 226 Отправить OK. 5 < /li>
trace: ccontrolsocket :: sendnextcommand () < /li>
trace: cftprawtransferopdata :: send () в состоянии 8 < /li>
trace: ctransfersocket :: transperend (1) < /li>
Cftpcontrolsocket :: transdend ()
[*] trace: cftpcontrolsocket :: resetoperation (0)
[*] trace: ccontrolsocket :: resetoperation (0)
[*] trace: cftprawtransferopdath /> Trace: cftplistopdata :: subcommandresult (0) в состоянии 3 < /li>
Trace: cftpControlSocket :: Resetoperation (0) < /li>
trace: ccontrolsocket :: resetoperation (0) < /li>
Cftplistopdata :: reset (0) в состоянии 3
[*] Статус: Список каталогов "/" Успешное
[*] трассировка: ccontrolsocket :: sendnextcommand ()
[*] trace: cftplogonopData :: send () in in in in in in in in in in in in in in in in in in in in State 0 Сервер: 192.168.0.45:21...
Ошибка: подключение времени после 20 секунд < /li>
трассировка: cftpcontrolsocket :: resetoperation (2114) < /li>
trace: ccontrolsocket :: re -re -reteperatore (2114) < /> < /> < /> < /> < /> < /> < /> < /> < /> Cftplogonopdata :: reset (2114) в состоянии 1 < /li>
Ошибка: не удалось подключиться к серверу < /li>
Состояние: отключено от сервера < /li>
< /ul>
Я имею следующие коды:
application.cs:
using CosmosTest.App.HttpServer;
using System;

namespace CosmosTest.App
{
internal class Application
{
private FTP2Server ftpServer;

public Application(Network network)
{
Console.WriteLine("Application: Constructor started.");

Console.WriteLine("Application: Initializing FtpServer...");
this.ftpServer = new FTP2Server();
this.ftpServer.Initialize();

Console.WriteLine("Application: FtpServer initialized and ready to poll.");
}
public void RunTasks()
{
if (this.ftpServer != null)
{
this.ftpServer.Poll();
}
}
}
}
< /code>
network.cs:
using Cosmos.System.Network.Config;
using Cosmos.System.Network.IPv4.UDP.DHCP;
using System;
using System.Threading;

namespace CosmosTest.App
{
internal class Network
{
internal Network()
{

}
internal bool Initialize()
{
int attempts = 0;
Console.Write("Network Initializing");
using (var xClient = new DHCPClient())
{
while (attempts < 5)
{
if (xClient.SendDiscoverPacket() >= 0)
{
Console.WriteLine(" done");
Console.WriteLine("IP-Address: " + NetworkConfiguration.CurrentAddress.ToString());
return true;
}
Thread.Sleep(1000);
Console.Write(".");
attempts++;
}
}
Console.WriteLine("failed");
return false;
}
}
}

< /code>
kernel.cs:
using CosmosTest.App;
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Sys = Cosmos.System;

namespace CosmosTest
{
public class Kernel : Sys.Kernel
{
private Network network = null!;
private Application application = null!;

protected override void BeforeRun()
{
Console.Clear();
Console.WriteLine("\r\n\r\n ________ ________ ________ \r\n|\\ ___ \\|\\ __ \\|\\ ____\\ \r\n\\ \\ \\\\ \\ \\ \\ \\|\\ \\ \\ \\___|_ \r\n \\ \\ \\\\ \\ \\ \\ __ \\ \\_____ \\ \r\n \\ \\ \\\\ \\ \\ \\ \\ \\ \\|____|\\ \\ \r\n \\ \\__\\\\ \\__\\ \\__\\ \\__\\____\\_\\ \\ \r\n \\|__| \\|__|\\|__|\\|__|\\_________\\\r\n \\|_________|\r\n\r\n");

network = new Network();
if (!network.Initialize())
{
Console.WriteLine("Press any key to restart");
Console.ReadKey();
Sys.Power.Reboot();
}

try
{
this.application = new Application(network);
}
catch (Exception ex)
{
Console.WriteLine("!!! HIBA AZ ALKALMAZAS LETREHOZASAKOR !!!");
Console.WriteLine(ex.ToString());
Console.WriteLine("A rendszer leallt.");
while (true) ;
}
}

protected override void Run()
{
try
{
this.application.RunTasks();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());

while (true) ;
}
}
}
}
< /code>
ftspserver.cs:
using Cosmos.System.FileSystem;
using Cosmos.System.FileSystem.VFS;
using System;
using FtpServer = CosmosFtpServer.FtpServer;

namespace CosmosTest
{
internal class FTP2Server
{
private CosmosVFS fs;
private FtpServer xServer;

internal FTP2Server()
{
Console.WriteLine("Initializing VFS...");
fs = new CosmosVFS();
VFSManager.RegisterVFS(fs);

try
{
if (!VFSManager.DirectoryExists("0:\\test_dir"))
{
VFSManager.CreateDirectory("0:\\test_dir");
Console.WriteLine("Created '0:\\test_dir' directory.");
}
}
catch (Exception e)
{
Console.WriteLine("VFS Error: " + e.Message);
}
}

internal void Initialize()
{
Console.WriteLine("FTP Server Initializing...");
this.xServer = new FtpServer(fs, "0:\\");
Console.WriteLine("FTP Initialized and ready.");
}

internal void Poll()
{
if (xServer != null)
{
xServer.Listen();
}
}
}
}
< /code>
ftpcommandmanager.cs:
using Cosmos.System.FileSystem;
using Cosmos.System.FileSystem.Listing;
using Cosmos.System.Network.Config;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace CosmosFtpServer
{
internal class FtpCommandManager
{
internal CosmosVFS FileSystem { get; set; }
internal string BaseDirectory { get; set; }
internal string CurrentDirectory { get; set; }

internal FtpCommandManager(CosmosVFS fs, string directory)
{
FileSystem = fs;
CurrentDirectory = directory;
BaseDirectory = directory;
}

internal void ProcessRequest(FtpClient ftpClient, FtpCommand command)
{
if (command.Command == "USER") { ProcessUser(ftpClient, command); }
else if (command.Command == "PASS") { ProcessPass(ftpClient, command); }
else
{
if (ftpClient.IsConnected())
{
switch (command.Command)
{
case "CWD": ProcessCwd(ftpClient, command); break;
case "SYST": ftpClient.SendReply(215, "CosmosOS"); break;
case "CDUP": ProcessCdup(ftpClient, command); break;
case "QUIT": ProcessQuit(ftpClient, command); break;
case "DELE": ProcessDele(ftpClient, command); break;
case "PWD": ProcessPwd(ftpClient, command); break;
case "PASV": ProcessPasv(ftpClient, command); break;
case "PORT": ProcessPort(ftpClient, command); break;
case "HELP": ftpClient.SendReply(200, "Help done."); break;
case "NOOP": ftpClient.SendReply(200, "Command okay."); break;
case "RETR": ProcessRetr(ftpClient, command); break;
case "STOR": ProcessStor(ftpClient, command); break;
case "RMD": ProcessRmd(ftpClient, command); break;
case "MKD": ProcessMkd(ftpClient, command); break;
case "LIST": ProcessList(ftpClient, command); break;
case "TYPE": ftpClient.SendReply(200, "Command okay."); break;
default: ftpClient.SendReply(500, "Unknown command."); break;
}
}
}
}

internal void ProcessUser(FtpClient ftpClient, FtpCommand command)
{
if (string.IsNullOrEmpty(command.Content)) { ftpClient.SendReply(501, "Syntax error in parameters or arguments."); return; }
if (command.Content == "anonymous") { ftpClient.Username = command.Content; ftpClient.Connected = true; ftpClient.LastGoodDirectory = BaseDirectory; ftpClient.SendReply(230, "User logged in, proceed."); }
else if (string.IsNullOrEmpty(ftpClient.Username)) { ftpClient.Username = command.Content; ftpClient.SendReply(331, "User name okay, need password."); }
else { ftpClient.SendReply(550, "Requested action not taken."); }
}

internal void ProcessPass(FtpClient ftpClient, FtpCommand command)
{
if (string.IsNullOrEmpty(command.Content)) { ftpClient.SendReply(501, "Syntax error in parameters or arguments."); return; }
if (ftpClient.Username == "anonymous") { ftpClient.SendReply(530, "Login incorrect."); }
else if (string.IsNullOrEmpty(ftpClient.Username)) { ftpClient.SendReply(332, "Need account for login."); }
else
{
ftpClient.Password = command.Content;
ftpClient.Connected = true;
ftpClient.LastGoodDirectory = BaseDirectory;
ftpClient.SendReply(230, "User logged in, proceed.");
}
}

internal void ProcessCwd(FtpClient ftpClient, FtpCommand command)
{
if (string.IsNullOrEmpty(command.Content)) { ftpClient.SendReply(501, "Syntax error in parameters or arguments."); return; }
try
{
string targetDir;
if (command.Content.StartsWith("/") || command.Content.StartsWith("\\"))
{
targetDir = Path.Combine(BaseDirectory, command.Content.TrimStart('/', '\\'));
}
else
{
targetDir = Path.Combine(ftpClient.LastGoodDirectory, command.Content);
}

if (Directory.Exists(targetDir))
{
ftpClient.LastGoodDirectory = targetDir;
ftpClient.SendReply(250, "Requested file action okay.");
}
else
{
ftpClient.SendReply(550, "Requested action not taken. Directory not found.");
}
}
catch { ftpClient.SendReply(550, "Requested action not taken."); }
}

internal void ProcessPwd(FtpClient ftpClient, FtpCommand command)
{
string current = ftpClient.LastGoodDirectory.Replace(BaseDirectory, "").Replace('\\', '/');
if (string.IsNullOrEmpty(current)) { current = "/"; }
ftpClient.SendReply(257, $"\"{current}\" is the current directory.");
}

internal void ProcessPasv(FtpClient ftpClient, FtpCommand command)
{
ushort port = Cosmos.System.Network.IPv4.TCP.Tcp.GetDynamicPort();
ftpClient.DataListener = new TcpListener(IPAddress.Any, port);
ftpClient.DataListener.Start();
var addressBytes = NetworkConfiguration.CurrentAddress.ToByteArray();
byte p1 = (byte)(port / 256);
byte p2 = (byte)(port % 256);
string pasvReplyMessage = string.Format("Entering Passive Mode ({0},{1},{2},{3},{4},{5})", addressBytes[0], addressBytes[1], addressBytes[2], addressBytes[3], p1, p2);
ftpClient.SendReply(227, pasvReplyMessage);
ftpClient.Mode = TransferMode.PASV;
}

internal void ProcessPort(FtpClient ftpClient, FtpCommand command)
{
string[] splitted = command.Content.Split(',');
byte[] array = new byte[] { (byte)int.Parse(splitted[0]), (byte)int.Parse(splitted[1]), (byte)int.Parse(splitted[2]), (byte)int.Parse(splitted[3]) };
IPAddress address = new IPAddress(array);
ftpClient.Data = new TcpClient();
ftpClient.Address = address;
ftpClient.Port = int.Parse(splitted[4]) * 256 + int.Parse(splitted[5]);
ftpClient.SendReply(200, "Entering Active Mode.");
ftpClient.Mode = TransferMode.ACTV;
}

internal void ProcessList(FtpClient ftpClient, FtpCommand command)
{
try
{
if (ftpClient.Mode == TransferMode.NONE) { ftpClient.SendReply(425, "Use PASV or PORT first."); return; }
if (ftpClient.Mode == TransferMode.PASV) { ftpClient.Data = ftpClient.DataListener.AcceptTcpClient(); }
else { ftpClient.Data.Connect(ftpClient.Address, ftpClient.Port); }

ftpClient.DataStream = ftpClient.Data.GetStream();
ftpClient.SendReply(150, "Here comes the directory listing.");
DoList(ftpClient, command);
}
catch (Exception e) { System.Console.WriteLine("LIST Error: " + e.ToString()); ftpClient.SendReply(425, "Can't open data connection."); }
finally { if (ftpClient.Mode == TransferMode.PASV) { ftpClient.DataListener.Stop(); } }
}

private void DoList(FtpClient ftpClient, FtpCommand command)
{
try
{
var directory_list = FileSystem.GetDirectoryListing(ftpClient.LastGoodDirectory);
var sb = new StringBuilder();
foreach (var directoryEntry in directory_list)
{
if (directoryEntry.mEntryType == DirectoryEntryTypeEnum.Directory) { sb.Append("d"); } else { sb.Append("-"); }
sb.Append("rwxrwxrwx 1 ftp ftp ");
sb.Append(directoryEntry.mSize.ToString().PadLeft(12));
sb.Append(" Jun 26 17:17 ");
sb.AppendLine(directoryEntry.mName);
}
ftpClient.DataStream.Write(Encoding.ASCII.GetBytes(sb.ToString()));
ftpClient.SendReply(226, "Directory send OK.");
}
catch (Exception e) { System.Console.WriteLine("DoList Error: " + e.ToString()); ftpClient.SendReply(550, "Error listing directory."); }
finally { ftpClient.Data?.Close(); }
}

internal void ProcessDele(FtpClient ftpClient, FtpCommand command) { /* ... változatlan ... */ }
internal void ProcessRmd(FtpClient ftpClient, FtpCommand command) { /* ... változatlan ... */ }
internal void ProcessMkd(FtpClient ftpClient, FtpCommand command) { /* ... változatlan ... */ }
internal void ProcessCdup(FtpClient ftpClient, FtpCommand command) { /* ... változatlan ... */ }
internal void ProcessQuit(FtpClient ftpClient, FtpCommand command) { /* ... változatlan ... */ }

internal void ProcessStor(FtpClient ftpClient, FtpCommand command)
{
if (string.IsNullOrEmpty(command.Content)) { ftpClient.SendReply(501, "Syntax error."); return; }
try
{
if (ftpClient.Mode == TransferMode.NONE) { ftpClient.SendReply(425, "Use PASV or PORT first."); return; }
if (ftpClient.Mode == TransferMode.PASV) { ftpClient.Data = ftpClient.DataListener.AcceptTcpClient(); }
else { ftpClient.Data.Connect(ftpClient.Address, ftpClient.Port); }

ftpClient.DataStream = ftpClient.Data.GetStream();
ftpClient.SendReply(150, "Opening data connection for file transfer.");
DoStor(ftpClient, command);
}
catch (Exception e) { System.Console.WriteLine("STOR Connection Error: " + e.Message); ftpClient.SendReply(425, "Can't open data connection."); }
finally { if (ftpClient.Mode == TransferMode.PASV) { ftpClient.DataListener.Stop(); } }
}

private void DoStor(FtpClient ftpClient, FtpCommand command)
{
try
{
string filePath = Path.Combine(ftpClient.LastGoodDirectory, command.Content);
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
byte[] buffer = new byte[8192];
int count;
while ((count = ftpClient.DataStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, count);
}
}
ftpClient.SendReply(226, "Transfer complete.");
}
catch (Exception e)
{
System.Console.WriteLine("STOR Write Error: " + e.Message);
ftpClient.SendReply(552, "Transfer aborted or other error.");
}
finally { ftpClient.Data?.Close(); }
}

internal void ProcessRetr(FtpClient ftpClient, FtpCommand command)
{
if (string.IsNullOrEmpty(command.Content)) { ftpClient.SendReply(501, "Syntax error."); return; }
try
{
string filePath = Path.Combine(ftpClient.LastGoodDirectory, command.Content);
if (!File.Exists(filePath)) { ftpClient.SendReply(550, "File not found."); return; }
if (ftpClient.Mode == TransferMode.NONE) { ftpClient.SendReply(425, "Use PASV or PORT first."); return; }
if (ftpClient.Mode == TransferMode.PASV) { ftpClient.Data = ftpClient.DataListener.AcceptTcpClient(); }
else { ftpClient.Data.Connect(ftpClient.Address, ftpClient.Port); }

ftpClient.DataStream = ftpClient.Data.GetStream();
ftpClient.SendReply(150, "Opening data connection for file transfer.");
DoRetr(ftpClient, filePath);
}
catch (Exception e) { System.Console.WriteLine("RETR Connection Error: " + e.Message); ftpClient.SendReply(425, "Can't open data connection."); }
finally { if (ftpClient.Mode == TransferMode.PASV) { ftpClient.DataListener.Stop(); } }
}

private void DoRetr(FtpClient ftpClient, string filePath)
{
try
{
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[8192];
int count;
while ((count = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
ftpClient.DataStream.Write(buffer, 0, count);
}
}
ftpClient.SendReply(226, "Transfer complete.");
}
catch (Exception e) { System.Console.WriteLine("RETR Read Error: " + e.Message); ftpClient.SendReply(550, "Error reading file."); }
finally { ftpClient.Data?.Close(); }
}
}
}
< /code>
ftpclient.cs:
/*
* PROJECT: Cosmos Operating System Development
* CONTENT: FTP Client
* PROGRAMMERS: Valentin Charbonnier
*/

using System.Net;
using System.Net.Sockets;
using System.Text;

namespace CosmosFtpServer
{
///
/// FtpClient class.
///
internal class FtpClient
{
///
/// Client IP Address.
///
internal IPAddress Address { get; set; }

///
/// Client TCP Port.
///
internal int Port { get; set; }

///
/// TCP Control Client. Used to send commands.
///
internal TcpClient Control { get; set; }

///
/// TCP Control Client. Used to send and receive commands.
///
internal NetworkStream ControlStream { get; set; }

///
/// TCP Data Transfer Client. Used to transfer data.
///
internal TcpClient Data { get; set; }

///
/// TCP Control Client. Used to send and receive commands.
///
internal NetworkStream DataStream { get; set; }

///
/// TCP Data Transfer Listener. Used in PASV mode.
///
internal TcpListener DataListener { get; set; }

///
/// FTP client data transfer mode.
///
internal TransferMode Mode { get; set; }

///
/// FTP client username.
///
internal string Username { get; set; }

///
/// FTP client password.
///
internal string Password { get; set; }

///
/// Is user connected.
///
internal bool Connected { get; set; }

///
/// Stores the last known good directory for the client.
///
internal string LastGoodDirectory { get; set; } //

Подробнее здесь: https://stackoverflow.com/questions/796 ... ith-cosmos
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»