13124
|
1 |
extern crate slab;
|
|
2 |
|
13419
|
3 |
use std::{
|
13804
|
4 |
io, io::{Error, ErrorKind, Read, Write},
|
13419
|
5 |
net::{SocketAddr, IpAddr, Ipv4Addr},
|
13420
|
6 |
collections::HashSet,
|
13483
|
7 |
mem::{swap, replace}
|
13419
|
8 |
};
|
|
9 |
|
|
10 |
use mio::{
|
|
11 |
net::{TcpStream, TcpListener},
|
|
12 |
Poll, PollOpt, Ready, Token
|
|
13 |
};
|
|
14 |
use netbuf;
|
13124
|
15 |
use slab::Slab;
|
13810
|
16 |
use log::*;
|
13124
|
17 |
|
13671
|
18 |
use crate::{
|
|
19 |
utils,
|
|
20 |
protocol::{ProtocolDecoder, messages::*}
|
|
21 |
};
|
13419
|
22 |
use super::{
|
14379
|
23 |
core::{HWServer},
|
13483
|
24 |
coretypes::ClientId
|
13419
|
25 |
};
|
13804
|
26 |
#[cfg(feature = "tls-connections")]
|
|
27 |
use openssl::{
|
|
28 |
ssl::{
|
|
29 |
SslMethod, SslContext, Ssl, SslContextBuilder,
|
|
30 |
SslVerifyMode, SslFiletype, SslOptions,
|
|
31 |
SslStreamBuilder, HandshakeError, MidHandshakeSslStream, SslStream
|
|
32 |
},
|
|
33 |
error::ErrorStack
|
|
34 |
};
|
13419
|
35 |
|
|
36 |
const MAX_BYTES_PER_READ: usize = 2048;
|
13124
|
37 |
|
13420
|
38 |
#[derive(Hash, Eq, PartialEq, Copy, Clone)]
|
13419
|
39 |
pub enum NetworkClientState {
|
|
40 |
Idle,
|
|
41 |
NeedsWrite,
|
|
42 |
NeedsRead,
|
|
43 |
Closed,
|
|
44 |
}
|
|
45 |
|
|
46 |
type NetworkResult<T> = io::Result<(T, NetworkClientState)>;
|
13124
|
47 |
|
13804
|
48 |
#[cfg(not(feature = "tls-connections"))]
|
|
49 |
pub enum ClientSocket {
|
|
50 |
Plain(TcpStream)
|
|
51 |
}
|
|
52 |
|
|
53 |
#[cfg(feature = "tls-connections")]
|
|
54 |
pub enum ClientSocket {
|
|
55 |
SslHandshake(Option<MidHandshakeSslStream<TcpStream>>),
|
|
56 |
SslStream(SslStream<TcpStream>)
|
|
57 |
}
|
|
58 |
|
|
59 |
impl ClientSocket {
|
|
60 |
fn inner(&self) -> &TcpStream {
|
|
61 |
#[cfg(not(feature = "tls-connections"))]
|
|
62 |
match self {
|
|
63 |
ClientSocket::Plain(stream) => stream,
|
|
64 |
}
|
|
65 |
|
|
66 |
#[cfg(feature = "tls-connections")]
|
|
67 |
match self {
|
|
68 |
ClientSocket::SslHandshake(Some(builder)) => builder.get_ref(),
|
|
69 |
ClientSocket::SslHandshake(None) => unreachable!(),
|
|
70 |
ClientSocket::SslStream(ssl_stream) => ssl_stream.get_ref()
|
|
71 |
}
|
|
72 |
}
|
|
73 |
}
|
|
74 |
|
13124
|
75 |
pub struct NetworkClient {
|
|
76 |
id: ClientId,
|
13804
|
77 |
socket: ClientSocket,
|
13124
|
78 |
peer_addr: SocketAddr,
|
|
79 |
decoder: ProtocolDecoder,
|
13419
|
80 |
buf_out: netbuf::Buf
|
13124
|
81 |
}
|
|
82 |
|
|
83 |
impl NetworkClient {
|
13804
|
84 |
pub fn new(id: ClientId, socket: ClientSocket, peer_addr: SocketAddr) -> NetworkClient {
|
13124
|
85 |
NetworkClient {
|
|
86 |
id, socket, peer_addr,
|
|
87 |
decoder: ProtocolDecoder::new(),
|
13419
|
88 |
buf_out: netbuf::Buf::new()
|
13124
|
89 |
}
|
|
90 |
}
|
|
91 |
|
13807
|
92 |
#[cfg(feature = "tls-connections")]
|
|
93 |
fn handshake_impl(&mut self, handshake: MidHandshakeSslStream<TcpStream>) -> io::Result<NetworkClientState> {
|
|
94 |
match handshake.handshake() {
|
|
95 |
Ok(stream) => {
|
|
96 |
self.socket = ClientSocket::SslStream(stream);
|
|
97 |
debug!("TLS handshake with {} ({}) completed", self.id, self.peer_addr);
|
|
98 |
Ok(NetworkClientState::Idle)
|
|
99 |
}
|
|
100 |
Err(HandshakeError::WouldBlock(new_handshake)) => {
|
|
101 |
self.socket = ClientSocket::SslHandshake(Some(new_handshake));
|
|
102 |
Ok(NetworkClientState::Idle)
|
|
103 |
}
|
13808
|
104 |
Err(HandshakeError::Failure(new_handshake)) => {
|
|
105 |
self.socket = ClientSocket::SslHandshake(Some(new_handshake));
|
13807
|
106 |
debug!("TLS handshake with {} ({}) failed", self.id, self.peer_addr);
|
|
107 |
Err(Error::new(ErrorKind::Other, "Connection failure"))
|
|
108 |
}
|
|
109 |
Err(HandshakeError::SetupFailure(_)) => unreachable!()
|
|
110 |
}
|
|
111 |
}
|
|
112 |
|
13804
|
113 |
fn read_impl<R: Read>(decoder: &mut ProtocolDecoder, source: &mut R,
|
|
114 |
id: ClientId, addr: &SocketAddr) -> NetworkResult<Vec<HWProtocolMessage>> {
|
13419
|
115 |
let mut bytes_read = 0;
|
|
116 |
let result = loop {
|
13804
|
117 |
match decoder.read_from(source) {
|
13419
|
118 |
Ok(bytes) => {
|
13804
|
119 |
debug!("Client {}: read {} bytes", id, bytes);
|
13419
|
120 |
bytes_read += bytes;
|
|
121 |
if bytes == 0 {
|
|
122 |
let result = if bytes_read == 0 {
|
13804
|
123 |
info!("EOF for client {} ({})", id, addr);
|
13419
|
124 |
(Vec::new(), NetworkClientState::Closed)
|
|
125 |
} else {
|
13804
|
126 |
(decoder.extract_messages(), NetworkClientState::NeedsRead)
|
13419
|
127 |
};
|
|
128 |
break Ok(result);
|
|
129 |
}
|
|
130 |
else if bytes_read >= MAX_BYTES_PER_READ {
|
13804
|
131 |
break Ok((decoder.extract_messages(), NetworkClientState::NeedsRead))
|
13419
|
132 |
}
|
|
133 |
}
|
|
134 |
Err(ref error) if error.kind() == ErrorKind::WouldBlock => {
|
|
135 |
let messages = if bytes_read == 0 {
|
|
136 |
Vec::new()
|
|
137 |
} else {
|
13804
|
138 |
decoder.extract_messages()
|
13419
|
139 |
};
|
|
140 |
break Ok((messages, NetworkClientState::Idle));
|
|
141 |
}
|
|
142 |
Err(error) =>
|
|
143 |
break Err(error)
|
|
144 |
}
|
|
145 |
};
|
13804
|
146 |
decoder.sweep();
|
13419
|
147 |
result
|
|
148 |
}
|
|
149 |
|
13804
|
150 |
pub fn read(&mut self) -> NetworkResult<Vec<HWProtocolMessage>> {
|
|
151 |
#[cfg(not(feature = "tls-connections"))]
|
|
152 |
match self.socket {
|
|
153 |
ClientSocket::Plain(ref mut stream) =>
|
|
154 |
NetworkClient::read_impl(&mut self.decoder, stream, self.id, &self.peer_addr),
|
|
155 |
}
|
|
156 |
|
|
157 |
#[cfg(feature = "tls-connections")]
|
|
158 |
match self.socket {
|
|
159 |
ClientSocket::SslHandshake(ref mut handshake_opt) => {
|
13807
|
160 |
let handshake = std::mem::replace(handshake_opt, None).unwrap();
|
|
161 |
Ok((Vec::new(), self.handshake_impl(handshake)?))
|
13804
|
162 |
},
|
|
163 |
ClientSocket::SslStream(ref mut stream) =>
|
|
164 |
NetworkClient::read_impl(&mut self.decoder, stream, self.id, &self.peer_addr)
|
|
165 |
}
|
|
166 |
}
|
|
167 |
|
|
168 |
fn write_impl<W: Write>(buf_out: &mut netbuf::Buf, destination: &mut W) -> NetworkResult<()> {
|
13419
|
169 |
let result = loop {
|
13804
|
170 |
match buf_out.write_to(destination) {
|
|
171 |
Ok(bytes) if buf_out.is_empty() || bytes == 0 =>
|
13419
|
172 |
break Ok(((), NetworkClientState::Idle)),
|
13420
|
173 |
Ok(_) => (),
|
13419
|
174 |
Err(ref error) if error.kind() == ErrorKind::Interrupted
|
|
175 |
|| error.kind() == ErrorKind::WouldBlock => {
|
|
176 |
break Ok(((), NetworkClientState::NeedsWrite));
|
|
177 |
},
|
|
178 |
Err(error) =>
|
|
179 |
break Err(error)
|
|
180 |
}
|
|
181 |
};
|
13804
|
182 |
result
|
|
183 |
}
|
|
184 |
|
|
185 |
pub fn write(&mut self) -> NetworkResult<()> {
|
|
186 |
let result = {
|
|
187 |
#[cfg(not(feature = "tls-connections"))]
|
|
188 |
match self.socket {
|
|
189 |
ClientSocket::Plain(ref mut stream) =>
|
|
190 |
NetworkClient::write_impl(&mut self.buf_out, stream)
|
|
191 |
}
|
|
192 |
|
|
193 |
#[cfg(feature = "tls-connections")] {
|
|
194 |
match self.socket {
|
13807
|
195 |
ClientSocket::SslHandshake(ref mut handshake_opt) => {
|
|
196 |
let handshake = std::mem::replace(handshake_opt, None).unwrap();
|
|
197 |
Ok(((), self.handshake_impl(handshake)?))
|
|
198 |
}
|
13804
|
199 |
ClientSocket::SslStream(ref mut stream) =>
|
|
200 |
NetworkClient::write_impl(&mut self.buf_out, stream)
|
|
201 |
}
|
|
202 |
}
|
|
203 |
};
|
|
204 |
|
|
205 |
self.socket.inner().flush()?;
|
13419
|
206 |
result
|
|
207 |
}
|
|
208 |
|
13124
|
209 |
pub fn send_raw_msg(&mut self, msg: &[u8]) {
|
13529
|
210 |
self.buf_out.write_all(msg).unwrap();
|
13124
|
211 |
}
|
|
212 |
|
13529
|
213 |
pub fn send_string(&mut self, msg: &str) {
|
13124
|
214 |
self.send_raw_msg(&msg.as_bytes());
|
|
215 |
}
|
|
216 |
|
13529
|
217 |
pub fn send_msg(&mut self, msg: &HWServerMessage) {
|
13124
|
218 |
self.send_string(&msg.to_raw_protocol());
|
|
219 |
}
|
|
220 |
}
|
|
221 |
|
13804
|
222 |
#[cfg(feature = "tls-connections")]
|
|
223 |
struct ServerSsl {
|
|
224 |
context: SslContext
|
|
225 |
}
|
|
226 |
|
13124
|
227 |
pub struct NetworkLayer {
|
|
228 |
listener: TcpListener,
|
|
229 |
server: HWServer,
|
13419
|
230 |
clients: Slab<NetworkClient>,
|
13420
|
231 |
pending: HashSet<(ClientId, NetworkClientState)>,
|
13804
|
232 |
pending_cache: Vec<(ClientId, NetworkClientState)>,
|
|
233 |
#[cfg(feature = "tls-connections")]
|
|
234 |
ssl: ServerSsl
|
13124
|
235 |
}
|
|
236 |
|
|
237 |
impl NetworkLayer {
|
|
238 |
pub fn new(listener: TcpListener, clients_limit: usize, rooms_limit: usize) -> NetworkLayer {
|
|
239 |
let server = HWServer::new(clients_limit, rooms_limit);
|
|
240 |
let clients = Slab::with_capacity(clients_limit);
|
13420
|
241 |
let pending = HashSet::with_capacity(2 * clients_limit);
|
|
242 |
let pending_cache = Vec::with_capacity(2 * clients_limit);
|
13804
|
243 |
|
|
244 |
NetworkLayer {
|
|
245 |
listener, server, clients, pending, pending_cache,
|
|
246 |
#[cfg(feature = "tls-connections")]
|
|
247 |
ssl: NetworkLayer::create_ssl_context()
|
|
248 |
}
|
|
249 |
}
|
|
250 |
|
|
251 |
#[cfg(feature = "tls-connections")]
|
|
252 |
fn create_ssl_context() -> ServerSsl {
|
|
253 |
let mut builder = SslContextBuilder::new(SslMethod::tls()).unwrap();
|
|
254 |
builder.set_verify(SslVerifyMode::NONE);
|
|
255 |
builder.set_read_ahead(true);
|
|
256 |
builder.set_certificate_file("ssl/cert.pem", SslFiletype::PEM).unwrap();
|
|
257 |
builder.set_private_key_file("ssl/key.pem", SslFiletype::PEM).unwrap();
|
|
258 |
builder.set_options(SslOptions::NO_COMPRESSION);
|
|
259 |
builder.set_cipher_list("DEFAULT:!LOW:!RC4:!EXP").unwrap();
|
|
260 |
ServerSsl { context: builder.build() }
|
13124
|
261 |
}
|
|
262 |
|
|
263 |
pub fn register_server(&self, poll: &Poll) -> io::Result<()> {
|
|
264 |
poll.register(&self.listener, utils::SERVER, Ready::readable(),
|
|
265 |
PollOpt::edge())
|
|
266 |
}
|
|
267 |
|
|
268 |
fn deregister_client(&mut self, poll: &Poll, id: ClientId) {
|
|
269 |
let mut client_exists = false;
|
13419
|
270 |
if let Some(ref client) = self.clients.get(id) {
|
13804
|
271 |
poll.deregister(client.socket.inner())
|
13529
|
272 |
.expect("could not deregister socket");
|
13124
|
273 |
info!("client {} ({}) removed", client.id, client.peer_addr);
|
|
274 |
client_exists = true;
|
|
275 |
}
|
|
276 |
if client_exists {
|
|
277 |
self.clients.remove(id);
|
|
278 |
}
|
|
279 |
}
|
|
280 |
|
13804
|
281 |
fn register_client(&mut self, poll: &Poll, id: ClientId, client_socket: ClientSocket, addr: SocketAddr) {
|
|
282 |
poll.register(client_socket.inner(), Token(id),
|
13124
|
283 |
Ready::readable() | Ready::writable(),
|
|
284 |
PollOpt::edge())
|
13529
|
285 |
.expect("could not register socket with event loop");
|
13124
|
286 |
|
|
287 |
let entry = self.clients.vacant_entry();
|
|
288 |
let client = NetworkClient::new(id, client_socket, addr);
|
|
289 |
info!("client {} ({}) added", client.id, client.peer_addr);
|
|
290 |
entry.insert(client);
|
|
291 |
}
|
|
292 |
|
13419
|
293 |
fn flush_server_messages(&mut self) {
|
|
294 |
debug!("{} pending server messages", self.server.output.len());
|
13424
|
295 |
for (clients, message) in self.server.output.drain(..) {
|
|
296 |
debug!("Message {:?} to {:?}", message, clients);
|
|
297 |
let msg_string = message.to_raw_protocol();
|
|
298 |
for client_id in clients {
|
|
299 |
if let Some(client) = self.clients.get_mut(client_id) {
|
|
300 |
client.send_string(&msg_string);
|
|
301 |
self.pending.insert((client_id, NetworkClientState::NeedsWrite));
|
13419
|
302 |
}
|
|
303 |
}
|
|
304 |
}
|
|
305 |
}
|
|
306 |
|
13804
|
307 |
fn create_client_socket(&self, socket: TcpStream) -> io::Result<ClientSocket> {
|
|
308 |
#[cfg(not(feature = "tls-connections"))] {
|
|
309 |
Ok(ClientSocket::Plain(socket))
|
|
310 |
}
|
|
311 |
|
|
312 |
#[cfg(feature = "tls-connections")] {
|
|
313 |
let ssl = Ssl::new(&self.ssl.context).unwrap();
|
|
314 |
let mut builder = SslStreamBuilder::new(ssl, socket);
|
|
315 |
builder.set_accept_state();
|
|
316 |
match builder.handshake() {
|
|
317 |
Ok(stream) =>
|
|
318 |
Ok(ClientSocket::SslStream(stream)),
|
|
319 |
Err(HandshakeError::WouldBlock(stream)) =>
|
|
320 |
Ok(ClientSocket::SslHandshake(Some(stream))),
|
|
321 |
Err(e) => {
|
|
322 |
debug!("OpenSSL handshake failed: {}", e);
|
|
323 |
Err(Error::new(ErrorKind::Other, "Connection failure"))
|
|
324 |
}
|
|
325 |
}
|
|
326 |
}
|
|
327 |
}
|
|
328 |
|
13124
|
329 |
pub fn accept_client(&mut self, poll: &Poll) -> io::Result<()> {
|
|
330 |
let (client_socket, addr) = self.listener.accept()?;
|
|
331 |
info!("Connected: {}", addr);
|
|
332 |
|
|
333 |
let client_id = self.server.add_client();
|
13804
|
334 |
self.register_client(poll, client_id, self.create_client_socket(client_socket)?, addr);
|
13124
|
335 |
self.flush_server_messages();
|
|
336 |
|
|
337 |
Ok(())
|
|
338 |
}
|
|
339 |
|
13529
|
340 |
fn operation_failed(&mut self, poll: &Poll, client_id: ClientId, error: &Error, msg: &str) -> io::Result<()> {
|
13419
|
341 |
let addr = if let Some(ref mut client) = self.clients.get_mut(client_id) {
|
|
342 |
client.peer_addr
|
|
343 |
} else {
|
|
344 |
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0)
|
|
345 |
};
|
|
346 |
debug!("{}({}): {}", msg, addr, error);
|
|
347 |
self.client_error(poll, client_id)
|
13124
|
348 |
}
|
|
349 |
|
|
350 |
pub fn client_readable(&mut self, poll: &Poll,
|
|
351 |
client_id: ClientId) -> io::Result<()> {
|
13419
|
352 |
let messages =
|
|
353 |
if let Some(ref mut client) = self.clients.get_mut(client_id) {
|
13804
|
354 |
client.read()
|
13419
|
355 |
} else {
|
|
356 |
warn!("invalid readable client: {}", client_id);
|
|
357 |
Ok((Vec::new(), NetworkClientState::Idle))
|
13124
|
358 |
};
|
13419
|
359 |
|
|
360 |
match messages {
|
|
361 |
Ok((messages, state)) => {
|
|
362 |
for message in messages {
|
|
363 |
self.server.handle_msg(client_id, message);
|
|
364 |
}
|
|
365 |
match state {
|
13420
|
366 |
NetworkClientState::NeedsRead => {
|
|
367 |
self.pending.insert((client_id, state));
|
|
368 |
},
|
13419
|
369 |
NetworkClientState::Closed =>
|
|
370 |
self.client_error(&poll, client_id)?,
|
|
371 |
_ => {}
|
|
372 |
};
|
13124
|
373 |
}
|
13419
|
374 |
Err(e) => self.operation_failed(
|
13529
|
375 |
poll, client_id, &e,
|
13419
|
376 |
"Error while reading from client socket")?
|
13124
|
377 |
}
|
|
378 |
|
13419
|
379 |
self.flush_server_messages();
|
|
380 |
|
13124
|
381 |
if !self.server.removed_clients.is_empty() {
|
13419
|
382 |
let ids: Vec<_> = self.server.removed_clients.drain(..).collect();
|
13124
|
383 |
for client_id in ids {
|
|
384 |
self.deregister_client(poll, client_id);
|
|
385 |
}
|
|
386 |
}
|
|
387 |
|
|
388 |
Ok(())
|
|
389 |
}
|
|
390 |
|
|
391 |
pub fn client_writable(&mut self, poll: &Poll,
|
|
392 |
client_id: ClientId) -> io::Result<()> {
|
13419
|
393 |
let result =
|
|
394 |
if let Some(ref mut client) = self.clients.get_mut(client_id) {
|
13804
|
395 |
client.write()
|
13419
|
396 |
} else {
|
|
397 |
warn!("invalid writable client: {}", client_id);
|
|
398 |
Ok(((), NetworkClientState::Idle))
|
|
399 |
};
|
|
400 |
|
|
401 |
match result {
|
13420
|
402 |
Ok(((), state)) if state == NetworkClientState::NeedsWrite => {
|
|
403 |
self.pending.insert((client_id, state));
|
|
404 |
},
|
|
405 |
Ok(_) => {}
|
13419
|
406 |
Err(e) => self.operation_failed(
|
13529
|
407 |
poll, client_id, &e,
|
13419
|
408 |
"Error while writing to client socket")?
|
13124
|
409 |
}
|
|
410 |
|
|
411 |
Ok(())
|
|
412 |
}
|
|
413 |
|
|
414 |
pub fn client_error(&mut self, poll: &Poll,
|
|
415 |
client_id: ClientId) -> io::Result<()> {
|
|
416 |
self.deregister_client(poll, client_id);
|
|
417 |
self.server.client_lost(client_id);
|
|
418 |
|
|
419 |
Ok(())
|
|
420 |
}
|
13419
|
421 |
|
|
422 |
pub fn has_pending_operations(&self) -> bool {
|
|
423 |
!self.pending.is_empty()
|
|
424 |
}
|
|
425 |
|
|
426 |
pub fn on_idle(&mut self, poll: &Poll) -> io::Result<()> {
|
13420
|
427 |
if self.has_pending_operations() {
|
13483
|
428 |
let mut cache = replace(&mut self.pending_cache, Vec::new());
|
13420
|
429 |
cache.extend(self.pending.drain());
|
|
430 |
for (id, state) in cache.drain(..) {
|
|
431 |
match state {
|
|
432 |
NetworkClientState::NeedsRead =>
|
|
433 |
self.client_readable(poll, id)?,
|
|
434 |
NetworkClientState::NeedsWrite =>
|
|
435 |
self.client_writable(poll, id)?,
|
|
436 |
_ => {}
|
|
437 |
}
|
13419
|
438 |
}
|
13420
|
439 |
swap(&mut cache, &mut self.pending_cache);
|
13419
|
440 |
}
|
|
441 |
Ok(())
|
|
442 |
}
|
13124
|
443 |
}
|