1 | using System;
|
---|
2 | using System.Net;
|
---|
3 | using System.Net.Sockets;
|
---|
4 |
|
---|
5 | public class AllocsTelnetConnection
|
---|
6 | {
|
---|
7 | private bool authenticated = false;
|
---|
8 | private bool authEnabled;
|
---|
9 | private TcpClient client;
|
---|
10 | private NetworkStream stream;
|
---|
11 | private string lineBuffer = string.Empty;
|
---|
12 | private EndPoint endpoint;
|
---|
13 |
|
---|
14 | public AllocsTelnetConnection (TcpClient client, bool authEnabled)
|
---|
15 | {
|
---|
16 | this.authEnabled = authEnabled;
|
---|
17 | this.client = client;
|
---|
18 | this.stream = client.GetStream ();
|
---|
19 | this.endpoint = client.Client.RemoteEndPoint;
|
---|
20 | }
|
---|
21 |
|
---|
22 | public EndPoint GetEndPoint ()
|
---|
23 | {
|
---|
24 | return endpoint;
|
---|
25 | }
|
---|
26 |
|
---|
27 | private void WriteByte (byte v)
|
---|
28 | {
|
---|
29 | if (!IsClosed () && stream.CanWrite) {
|
---|
30 | stream.WriteByte (v);
|
---|
31 | }
|
---|
32 | }
|
---|
33 |
|
---|
34 | public void WriteLine (string s)
|
---|
35 | {
|
---|
36 | try {
|
---|
37 | if (!IsClosed () && stream.CanWrite) {
|
---|
38 | for (int i = 0; i < s.Length; i++) {
|
---|
39 | WriteByte ((byte)s [i]);
|
---|
40 | }
|
---|
41 | WriteByte (10);
|
---|
42 | }
|
---|
43 | } catch (Exception e) {
|
---|
44 | Log.Out("Error writing to client: " + e);
|
---|
45 | }
|
---|
46 | }
|
---|
47 |
|
---|
48 | public void Close ()
|
---|
49 | {
|
---|
50 | if (client != null)
|
---|
51 | client.Close ();
|
---|
52 | client = null;
|
---|
53 | }
|
---|
54 |
|
---|
55 | public bool IsClosed ()
|
---|
56 | {
|
---|
57 | if (client != null && !client.Connected) {
|
---|
58 | Log.Out ("Telnet connection interrupted: " + endpoint);
|
---|
59 | }
|
---|
60 | return (client == null) || (!client.Connected);
|
---|
61 | }
|
---|
62 |
|
---|
63 | public bool IsAuthenticated ()
|
---|
64 | {
|
---|
65 | return !authEnabled || authenticated;
|
---|
66 | }
|
---|
67 |
|
---|
68 | public void SetAuthenticated ()
|
---|
69 | {
|
---|
70 | authenticated = true;
|
---|
71 | }
|
---|
72 |
|
---|
73 | public bool Read ()
|
---|
74 | {
|
---|
75 | while (!IsClosed() && stream.CanRead && stream.DataAvailable) {
|
---|
76 | int b = stream.ReadByte ();
|
---|
77 | if (b == '\r' || b == '\n') {
|
---|
78 | if (lineBuffer.Length > 0)
|
---|
79 | return true;
|
---|
80 | } else {
|
---|
81 | lineBuffer += (char)b;
|
---|
82 | }
|
---|
83 | }
|
---|
84 | return false;
|
---|
85 | }
|
---|
86 |
|
---|
87 | public string GetLine ()
|
---|
88 | {
|
---|
89 | string res = lineBuffer;
|
---|
90 | lineBuffer = string.Empty;
|
---|
91 | return res;
|
---|
92 | }
|
---|
93 | }
|
---|