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(13);
|
---|
42 | WriteByte (10);
|
---|
43 | }
|
---|
44 | } catch (Exception e) {
|
---|
45 | Log.Out("Error writing to client: " + e);
|
---|
46 | }
|
---|
47 | }
|
---|
48 |
|
---|
49 | public void Close ()
|
---|
50 | {
|
---|
51 | if (client != null)
|
---|
52 | client.Close ();
|
---|
53 | client = null;
|
---|
54 | }
|
---|
55 |
|
---|
56 | public bool IsClosed ()
|
---|
57 | {
|
---|
58 | if (client != null && !client.Connected) {
|
---|
59 | Log.Out ("Telnet connection interrupted: " + endpoint);
|
---|
60 | }
|
---|
61 | return (client == null) || (!client.Connected);
|
---|
62 | }
|
---|
63 |
|
---|
64 | public bool IsAuthenticated ()
|
---|
65 | {
|
---|
66 | return !authEnabled || authenticated;
|
---|
67 | }
|
---|
68 |
|
---|
69 | public void SetAuthenticated ()
|
---|
70 | {
|
---|
71 | authenticated = true;
|
---|
72 | }
|
---|
73 |
|
---|
74 | public bool Read ()
|
---|
75 | {
|
---|
76 | while (!IsClosed() && stream.CanRead && stream.DataAvailable) {
|
---|
77 | int b = stream.ReadByte ();
|
---|
78 | if (b == '\r' || b == '\n') {
|
---|
79 | if (lineBuffer.Length > 0)
|
---|
80 | return true;
|
---|
81 | } else {
|
---|
82 | lineBuffer += (char)b;
|
---|
83 | }
|
---|
84 | }
|
---|
85 | return false;
|
---|
86 | }
|
---|
87 |
|
---|
88 | public string GetLine ()
|
---|
89 | {
|
---|
90 | string res = lineBuffer;
|
---|
91 | lineBuffer = string.Empty;
|
---|
92 | return res;
|
---|
93 | }
|
---|
94 | }
|
---|