using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Threading; namespace AllocsFixes.NetConnections.Servers.Telnet { public class Telnet : IServer { private TcpListener listener = null; private bool authEnabled = false; private List connections = new List (); public Telnet () { try { if (!GamePrefs.GetBool (EnumGamePrefs.TelnetEnabled)) { return; } int port = GamePrefs.GetInt (EnumGamePrefs.TelnetPort); authEnabled = GamePrefs.GetString (EnumGamePrefs.TelnetPassword).Length != 0; if (authEnabled) listener = new TcpListener (IPAddress.Any, port); else listener = new TcpListener (IPAddress.Loopback, port); listener.Start (); listener.BeginAcceptTcpClient (new AsyncCallback (AcceptClient), null); NetTelnetServer.RegisterServer (this); Log.Out ("Started Telnet on " + port); } catch (Exception e) { Log.Out ("Error in Telnet.ctor: " + e); } } public void FailedLogins () { } private void AcceptClient (IAsyncResult asyncResult) { if (listener.Server.IsBound) { TelnetConnection c = new TelnetConnection (this, listener.EndAcceptTcpClient (asyncResult), authEnabled); connections.Add (c); listener.BeginAcceptTcpClient (new AsyncCallback (AcceptClient), null); } } public void Disconnect () { try { if (listener != null) { listener.Stop (); listener = null; } foreach (TelnetConnection c in connections) { c.Close (); } } catch (Exception e) { Log.Out ("Error in Telnet.Disconnect: " + e); } } private void RemoveClosedConnections () { try { List toRemove = new List (); foreach (TelnetConnection c in connections) { if (c.IsClosed ()) toRemove.Add (c); } foreach (TelnetConnection c in toRemove) { connections.Remove (c); } } catch (Exception e) { Log.Out ("Error in Telnet.RemoveClosedConnections: " + e); } } public void WriteToClient (string line) { if (line == null) { return; } RemoveClosedConnections (); foreach (TelnetConnection c in connections) { if (c.IsAuthenticated ()) c.WriteLine (line); } } public void WriteToClient_Single (string line, IConnection client) { if (line == null) { return; } RemoveClosedConnections (); foreach (TelnetConnection con in connections) { if (con == client) { if (con.IsAuthenticated ()) con.WriteLine (line); } } } } }