1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
mod codec;
pub mod error;
use encoding::DecoderTrap;
use encoding::{all::GBK, Encoding};
use futures::stream::StreamExt;
use tokio::{
io::AsyncWriteExt,
net::TcpStream,
time::{self, Duration},
};
use tokio_util::codec::FramedRead;
use crate::codec::{Item, TelnetCodec};
use crate::error::TelnetError;
#[derive(Debug, Default)]
pub struct TelnetBuilder {
prompt: String,
username_prompt: String,
password_prompt: String,
connect_timeout: Duration,
timeout: Duration,
}
impl TelnetBuilder {
pub fn prompt(mut self, prompt: &str) -> TelnetBuilder {
self.prompt = prompt.to_string();
self
}
pub fn login_prompt(mut self, user_prompt: &str, pass_prompt: &str) -> TelnetBuilder {
self.username_prompt = user_prompt.to_string();
self.password_prompt = pass_prompt.to_string();
self
}
pub fn connect_timeout(mut self, connect_timeout: Duration) -> TelnetBuilder {
self.connect_timeout = connect_timeout;
self
}
pub fn timeout(mut self, timeout: Duration) -> TelnetBuilder {
self.timeout = timeout;
self
}
pub async fn connect(self, addr: &str) -> Result<Telnet, TelnetError> {
match time::timeout(self.connect_timeout, TcpStream::connect(addr)).await {
Ok(res) => Ok(Telnet {
content: vec![],
stream: res?,
timeout: self.timeout,
prompt: self.prompt,
username_prompt: self.username_prompt,
password_prompt: self.password_prompt,
}),
Err(_) => Err(TelnetError::Timeout(format!(
"Connect remote addr({})",
addr
))),
}
}
}
pub struct Telnet {
timeout: Duration,
content: Vec<u8>,
stream: TcpStream,
prompt: String,
username_prompt: String,
password_prompt: String,
}
impl Telnet {
pub fn builder() -> TelnetBuilder {
TelnetBuilder::default()
}
fn format_enter_str(s: &str) -> String {
if !s.ends_with('\n') {
format!("{}\n", s)
} else {
s.to_string()
}
}
pub async fn login(&mut self, username: &str, password: &str) -> Result<(), TelnetError> {
let user = Telnet::format_enter_str(username);
let pass = Telnet::format_enter_str(password);
let mut auth_failed = false;
let (read, mut write) = self.stream.split();
let mut telnet = FramedRead::new(read, TelnetCodec::default());
loop {
match time::timeout(self.timeout, telnet.next()).await {
Ok(res) => {
match res {
Some(res) => {
match res? {
Item::Do(i) | Item::Dont(i) => {
if i == 0x1f {
write
.write(&[
0xff, 0xfb, 0x1f, 0xff, 0xfa, 0x1f, 0x00, 0xfc,
0x00, 0x1b, 0xff, 0xf0,
])
.await?;
} else {
write.write(&[0xff, 0xfc, i]).await?;
}
}
Item::Will(i) | Item::Wont(i) => {
write.write(&[0xff, 0xfe, i]).await?;
}
Item::Line(content) => {
if content.ends_with(self.username_prompt.as_bytes()) {
if auth_failed {
return Err(TelnetError::AuthenticationFailed);
}
write.write(user.as_bytes()).await?;
} else if content.ends_with(self.password_prompt.as_bytes()) {
write.write(pass.as_bytes()).await?;
auth_failed = true;
} else if content.ends_with(self.prompt.as_bytes()) {
return Ok(());
}
}
item => return Err(TelnetError::UnknownIAC(format!("{:?}", item))),
}
}
None => return Err(TelnetError::NoMoreData),
};
}
Err(_) => return Err(TelnetError::Timeout("login".to_string())),
}
}
}
pub async fn execute(&mut self, cmd: &str) -> Result<String, TelnetError> {
let command = Telnet::format_enter_str(cmd);
let mut line_feed_cnt = command.lines().count() as isize;
let mut real_output = false;
let (read, mut write) = self.stream.split();
match time::timeout(self.timeout, write.write(command.as_bytes())).await {
Ok(res) => res?,
Err(_) => return Err(TelnetError::Timeout("write cmd".to_string())),
};
let mut telnet = FramedRead::new(read, TelnetCodec::default());
loop {
match time::timeout(self.timeout, telnet.next()).await {
Ok(res) => match res {
Some(item) => {
if let Item::Line(mut line) = item? {
if line.ends_with(self.prompt.as_bytes()) {
break;
}
if line.ends_with(&[10]) && line_feed_cnt > 0 {
line_feed_cnt -= 1;
if line_feed_cnt == 0 {
real_output = true;
continue;
}
}
if real_output {
self.content.append(&mut line);
}
}
}
None => return Err(TelnetError::NoMoreData),
},
Err(_) => return Err(TelnetError::Timeout("read next framed".to_string())),
}
}
let output = String::from_utf8(self.content.clone());
let result = match output {
Ok(s) => Ok(s),
Err(e) => match GBK.decode(&self.content, DecoderTrap::Strict) {
Ok(gbk_out) => Ok(gbk_out),
Err(_) => Err(TelnetError::ParseError(e)),
},
};
self.content.clear();
result
}
pub async fn normal_execute(&mut self, cmd: &str) -> Result<String, TelnetError> {
let command = Telnet::format_enter_str(cmd);
let (read, mut write) = self.stream.split();
match time::timeout(self.timeout, write.write(command.as_bytes())).await {
Ok(res) => res?,
Err(_) => return Err(TelnetError::Timeout("write cmd".to_string())),
};
let mut telnet = FramedRead::new(read, TelnetCodec::default());
loop {
match time::timeout(self.timeout, telnet.next()).await {
Ok(res) => match res {
Some(item) => {
if let Item::Line(mut line) = item? {
if line.ends_with(self.prompt.as_bytes()) {
break;
}
self.content.append(&mut line);
}
}
None => return Err(TelnetError::NoMoreData),
},
Err(_) => return Err(TelnetError::Timeout("read next framed".to_string())),
}
}
let output = String::from_utf8(self.content.clone());
let result = match output {
Ok(s) => Ok(s),
Err(e) => match GBK.decode(&self.content, DecoderTrap::Strict) {
Ok(gbk_out) => Ok(gbk_out),
Err(_) => Err(TelnetError::ParseError(e)),
},
};
self.content.clear();
result
}
}