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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
use std::io::{Read, Write, Result as IoResult, ErrorKind};
use std::net::{SocketAddr, Shutdown};
use std::num::NonZeroUsize;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::time::{Duration};
use mio::{Token, Interest};
use mio::net::TcpStream as MioTcpStream;
use log::warn;
use crate::utilities::Timeout;
use crate::{TcpConnection, TcpManager, TcpError};
use crate::manager::TcpPollContext;
#[derive(Debug)]
pub struct TcpStream {
stream: MioTcpStream,
token: Token,
timeouts: (Option<Duration>, Option<Duration>),
manager: Rc<TcpManager>,
}
impl TcpStream {
pub fn from(manager: &Rc<TcpManager>, connection: TcpConnection) -> IoResult<Self> {
let mut stream = connection.stream();
let manager = manager.clone();
let token = Self::register(&manager.context(), &mut stream)?;
Ok(Self {
stream,
token,
timeouts: (None, None),
manager,
})
}
pub fn set_default_timeouts(&mut self, timeout_rd: Option<Duration>, timeout_wr: Option<Duration>) {
self.timeouts = (timeout_rd, timeout_wr);
}
pub fn peer_addr(&self) -> Option<SocketAddr> {
self.stream.peer_addr().ok()
}
pub fn local_addr(&self) -> Option<SocketAddr> {
self.stream.local_addr().ok()
}
pub fn shutdown(&self, how: Shutdown) -> IoResult<()> {
self.stream.shutdown(how)
}
fn register<T>(context: &T, stream: &mut MioTcpStream) -> IoResult<Token>
where
T: Deref<Target=TcpPollContext>
{
let token = context.token();
context.registry().register(stream, token, Interest::READABLE | Interest::WRITABLE)?;
Ok(token)
}
fn deregister<T>(context: &T, stream: &mut MioTcpStream)
where
T: Deref<Target=TcpPollContext>
{
if let Err(error) = context.registry().deregister(stream) {
warn!("Failed to de-register: {:?}", error);
}
}
pub fn connect(manager: &Rc<TcpManager>, addr: SocketAddr, timeout: Option<Duration>) -> Result<Self, TcpError> {
if manager.cancelled() {
return Err(TcpError::Cancelled);
}
let mut stream = MioTcpStream::connect(addr)?;
let manager = manager.clone();
let token = Self::init_connection(&manager, &mut stream, timeout)?;
Ok(Self {
stream,
token,
timeouts: (None, None),
manager,
})
}
fn init_connection(manager: &Rc<TcpManager>, stream: &mut MioTcpStream, timeout: Option<Duration>) -> Result<Token, TcpError> {
let mut context = manager.context_mut();
let token = Self::register(&context, stream)?;
match Self::await_connected(manager, &mut context, stream, token, timeout) {
Ok(_) => Ok(token),
Err(error) => {
Self::deregister(&context, stream);
Err(error)
},
}
}
fn await_connected<T>(manager: &Rc<TcpManager>, context: &mut T, stream: &mut MioTcpStream, token: Token, timeout: Option<Duration>) -> Result<(), TcpError>
where
T: DerefMut<Target=TcpPollContext>
{
let timeout = Timeout::start(timeout);
loop {
let remaining = timeout.remaining_time();
match context.poll(remaining) {
Ok(events) => {
for _event in events.iter().filter(|event| (event.token() == token)) {
match Self::event_conn(stream) {
Ok(true) => return Ok(()),
Ok(_) => (),
Err(error) => return Err(error.into()),
}
}
},
Err(error) => return Err(error.into()),
}
if manager.cancelled() {
return Err(TcpError::Cancelled);
}
if remaining.map(|time| time.is_zero()).unwrap_or(false) {
return Err(TcpError::TimedOut);
}
}
}
fn event_conn(stream: &mut MioTcpStream) -> IoResult<bool> {
loop {
if let Some(err) = stream.take_error()? {
return Err(err);
}
match stream.peer_addr() {
Ok(_addr) => return Ok(true),
Err(error) => match error.kind() {
ErrorKind::Interrupted => (),
ErrorKind::NotConnected => return Ok(false),
_ => return Err(error),
},
}
}
}
pub fn read_timeout(&mut self, buffer: &mut [u8], timeout: Option<Duration>) -> Result<usize, TcpError> {
if self.manager.cancelled() {
return Err(TcpError::Cancelled);
}
let timeout = Timeout::start(timeout);
match Self::event_read(&mut self.stream, buffer) {
Ok(Some(len)) => return Ok(len),
Ok(_) => (),
Err(error) => return Err(error.into()),
}
let mut context = self.manager.context_mut();
loop {
let remaining = timeout.remaining_time();
match context.poll(remaining) {
Ok(events) => {
for _event in events.iter().filter(|event| (event.token() == self.token) && event.is_readable()) {
match Self::event_read(&mut self.stream, buffer) {
Ok(Some(len)) => return Ok(len),
Ok(_) => (),
Err(error) => return Err(error.into()),
}
}
},
Err(error) => return Err(error.into()),
}
if self.manager.cancelled() {
return Err(TcpError::Cancelled);
}
if remaining.map(|time| time.is_zero()).unwrap_or(false) {
return Err(TcpError::TimedOut);
}
}
}
pub fn read_all_timeout<F>(&mut self, buffer: &mut Vec<u8>, timeout: Option<Duration>, chunk_size: Option<NonZeroUsize>, fn_complete: F) -> Result<(), TcpError>
where
F: Fn(&[u8]) -> bool,
{
let timeout = Timeout::start(timeout);
let chunk_size = chunk_size.map(NonZeroUsize::get).unwrap_or(4096);
let mut valid_length = buffer.len();
loop {
buffer.resize(compute_capacity(valid_length, chunk_size), 0);
let done = match self.read_timeout(&mut buffer[valid_length..], timeout.remaining_time()) {
Ok(0) => Some(Err(TcpError::Incomplete)),
Ok(count) => {
valid_length += count;
match fn_complete(&buffer[..valid_length]) {
true => Some(Ok(())),
false => None,
}
},
Err(error) => Some(Err(error)),
};
if let Some(result) = done {
buffer.truncate(valid_length);
return result;
}
}
}
fn event_read(stream: &mut MioTcpStream, buffer: &mut [u8]) -> IoResult<Option<usize>> {
loop {
match stream.read(buffer) {
Ok(count) => return Ok(Some(count)),
Err(error) => match error.kind() {
ErrorKind::Interrupted => (),
ErrorKind::WouldBlock => return Ok(None),
_ => return Err(error),
},
}
}
}
pub fn write_timeout(&mut self, buffer: &[u8], timeout: Option<Duration>) -> Result<usize, TcpError> {
if self.manager.cancelled() {
return Err(TcpError::Cancelled);
}
let timeout = Timeout::start(timeout);
match Self::event_write(&mut self.stream, buffer) {
Ok(Some(len)) => return Ok(len),
Ok(_) => (),
Err(error) => return Err(error.into()),
}
let mut context = self.manager.context_mut();
loop {
let remaining = timeout.remaining_time();
match context.poll(remaining) {
Ok(events) => {
for _event in events.iter().filter(|event| (event.token() == self.token) && event.is_writable()) {
match Self::event_write(&mut self.stream, buffer) {
Ok(Some(len)) => return Ok(len),
Ok(_) => (),
Err(error) => return Err(error.into()),
}
}
},
Err(error) => return Err(error.into()),
}
if self.manager.cancelled() {
return Err(TcpError::Cancelled);
}
if remaining.map(|time| time.is_zero()).unwrap_or(false) {
return Err(TcpError::TimedOut);
}
}
}
pub fn write_all_timeout(&mut self, mut buffer: &[u8], timeout: Option<Duration>) -> Result<(), TcpError> {
let timeout = Timeout::start(timeout);
loop {
match self.write_timeout(buffer, timeout.remaining_time()) {
Ok(0) => return Err(TcpError::Incomplete),
Ok(count) => {
buffer = &buffer[count..];
if buffer.is_empty() { return Ok(()); }
},
Err(error) => return Err(error),
};
}
}
fn event_write(stream: &mut MioTcpStream, buffer: &[u8]) -> IoResult<Option<usize>> {
loop {
match stream.write(buffer) {
Ok(count) => return Ok(Some(count)),
Err(error) => match error.kind() {
ErrorKind::Interrupted => (),
ErrorKind::WouldBlock => return Ok(None),
_ => return Err(error),
},
}
}
}
}
impl Read for TcpStream {
fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
into_io_result(self.read_timeout(buf, self.timeouts.0))
}
}
impl Write for TcpStream {
fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
into_io_result(self.write_timeout(buf, self.timeouts.1))
}
fn flush(&mut self) -> IoResult<()> {
self.stream.flush()
}
}
impl Drop for TcpStream {
fn drop(&mut self) {
let context = self.manager.context();
Self::deregister(&context, &mut self.stream);
}
}
fn into_io_result<T>(result: Result<T, TcpError>) -> IoResult<T> {
match result {
Ok(value) => Ok(value),
Err(error) => Err(error.into()),
}
}
fn compute_capacity(length: usize, chunk_size: usize) -> usize {
let padded_len = match length % chunk_size {
0 => length,
r => length.checked_add(chunk_size - r).expect("Numerical overflow!"),
};
padded_len.checked_add(chunk_size).expect("Numerical overflow!")
}