using System; using System.Net; using System.Net.Sockets; using System.Text; namespace AllocsFixes.NetConnections.Servers.Telnet { public class TelnetConnection : IConnection { private bool authenticated = false; private bool authEnabled; private TcpClient client; private NetworkStream stream; private int lineBufferLength = 0; private byte[] lineBuffer = new byte[200]; private EndPoint endpoint; public TelnetConnection (TcpClient client, bool authEnabled) { this.authEnabled = authEnabled; this.client = client; this.stream = client.GetStream (); this.endpoint = client.Client.RemoteEndPoint; } public EndPoint GetEndPoint () { return endpoint; } private void WriteByte (byte v) { if (!IsClosed () && stream.CanWrite) { stream.WriteByte (v); } } public void WriteLine (string s) { try { if (!IsClosed () && stream.CanWrite) { byte[] utfData = Encoding.UTF8.GetBytes (s); stream.Write (utfData, 0, utfData.Length); WriteByte (13); WriteByte (10); } } catch (Exception e) { Log.Out ("Error writing to client: " + e); } } public void Close () { if (client != null) client.Close (); client = null; } public bool IsClosed () { if (client != null && !client.Connected) { Log.Out ("Telnet connection interrupted: " + endpoint); } return (client == null) || (!client.Connected); } public bool IsAuthenticated () { return !authEnabled || authenticated; } public void SetAuthenticated () { authenticated = true; } public bool Read () { while (!IsClosed() && stream.CanRead && stream.DataAvailable) { int b = stream.ReadByte (); if (b == '\r' || b == '\n') { if (lineBufferLength > 0) { return true; } } else if (b >= 0) { lineBuffer [lineBufferLength] = (byte)b; lineBufferLength++; } } return false; } public string GetLine () { string res = Encoding.UTF8.GetString (lineBuffer, 0, lineBufferLength); lineBufferLength = 0; return res; } } }