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