98 lines
3.1 KiB
C#
98 lines
3.1 KiB
C#
using DearFTP.Configurations;
|
|
using DearFTP.Connection.Commands;
|
|
using DearFTP.Utils;
|
|
using System;
|
|
using System.Net;
|
|
using System.Net.Security;
|
|
using System.Net.Sockets;
|
|
|
|
namespace DearFTP.Connection
|
|
{
|
|
class Session : IDisposable
|
|
{
|
|
public Configuration Configuration { get; }
|
|
public CommandsDispatcher CommandsDispatcher { get; }
|
|
public Logger Logger { get; }
|
|
public User User { get; set; }
|
|
public Share[] Shares { get; set; }
|
|
public Share[] WritablesShares { get; set; }
|
|
public NavigablePath NavigablePath { get; set; }
|
|
public FtpStream FtpStream { get; private set; }
|
|
public IDataConnection DataConnection { get; set; }
|
|
public int RestartPosition { get; set; }
|
|
public bool IsTlsProtected { get; private set; }
|
|
public string CurrentWorkingDirectory => NavigablePath.CurrentDirectory;
|
|
|
|
public IPAddress LocalIP => ((IPEndPoint)_client.Client.LocalEndPoint).Address;
|
|
public IPAddress RemoteIP => ((IPEndPoint)_client.Client.RemoteEndPoint).Address;
|
|
|
|
private readonly TcpClient _client;
|
|
private readonly NetworkStream _networkStream;
|
|
private SslStream _sslStream;
|
|
private bool _isRunning = true;
|
|
|
|
public Session(TcpClient client)
|
|
{
|
|
_client = client;
|
|
_networkStream = client.GetStream();
|
|
FtpStream = new FtpStream(_networkStream);
|
|
|
|
Configuration = FtpServer.Instance.Configuration;
|
|
CommandsDispatcher = FtpServer.Instance.CommandsDispatcher;
|
|
Logger = FtpServer.Instance.Logger;
|
|
DataConnection = Configuration.Server.ForceDataPort == 0 ? (IDataConnection)new DynamicDataConnection() : new StaticDataConnection();
|
|
RestartPosition = 0;
|
|
IsTlsProtected = false;
|
|
}
|
|
|
|
public void Start()
|
|
{
|
|
FtpStream.Send(ResponseCode.ServiceReady, Configuration.Server.MOTD);
|
|
|
|
while (_isRunning)
|
|
{
|
|
(string command, string argument) = FtpStream.Receive();
|
|
Log($"{command} {argument}");
|
|
|
|
CommandsDispatcher.Dispatch(this, command, argument);
|
|
}
|
|
}
|
|
|
|
public void Stop()
|
|
{
|
|
_isRunning = false;
|
|
|
|
Dispose();
|
|
}
|
|
|
|
public void Log(string message)
|
|
{
|
|
Logger.Log($"[{_client.Client.RemoteEndPoint}]: {message}");
|
|
}
|
|
|
|
public void LogError(string error, string description)
|
|
{
|
|
Logger.LogError(error, $"[{_client.Client.RemoteEndPoint}]: {description}");
|
|
}
|
|
|
|
public void ActivateTls()
|
|
{
|
|
_sslStream = new SslStream(_networkStream, true);
|
|
|
|
_sslStream.AuthenticateAsServer(Configuration.Tls.X509Certificate, false, true);
|
|
|
|
FtpStream = new FtpStream(_sslStream);
|
|
|
|
IsTlsProtected = true;
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_sslStream?.Close();
|
|
_networkStream.Close();
|
|
_client.Close();
|
|
DataConnection.Close();
|
|
}
|
|
}
|
|
}
|