13119
|
1 |
extern crate slab;
|
|
2 |
|
13414
|
3 |
use std::{
|
|
4 |
io, io::{Error, ErrorKind, Write},
|
|
5 |
net::{SocketAddr, IpAddr, Ipv4Addr},
|
13415
|
6 |
collections::HashSet,
|
|
7 |
mem::swap
|
13414
|
8 |
};
|
|
9 |
|
|
10 |
use mio::{
|
|
11 |
net::{TcpStream, TcpListener},
|
|
12 |
Poll, PollOpt, Ready, Token
|
|
13 |
};
|
|
14 |
use netbuf;
|
13119
|
15 |
use slab::Slab;
|
|
16 |
|
13414
|
17 |
use utils;
|
|
18 |
use protocol::{ProtocolDecoder, messages::*};
|
|
19 |
use super::{
|
13419
|
20 |
server::{HWServer},
|
13414
|
21 |
client::ClientId
|
|
22 |
};
|
|
23 |
|
|
24 |
const MAX_BYTES_PER_READ: usize = 2048;
|
13119
|
25 |
|
13415
|
26 |
#[derive(Hash, Eq, PartialEq, Copy, Clone)]
|
13414
|
27 |
pub enum NetworkClientState {
|
|
28 |
Idle,
|
|
29 |
NeedsWrite,
|
|
30 |
NeedsRead,
|
|
31 |
Closed,
|
|
32 |
}
|
|
33 |
|
|
34 |
type NetworkResult<T> = io::Result<(T, NetworkClientState)>;
|
13119
|
35 |
|
|
36 |
pub struct NetworkClient {
|
|
37 |
id: ClientId,
|
|
38 |
socket: TcpStream,
|
|
39 |
peer_addr: SocketAddr,
|
|
40 |
decoder: ProtocolDecoder,
|
13414
|
41 |
buf_out: netbuf::Buf
|
13119
|
42 |
}
|
|
43 |
|
|
44 |
impl NetworkClient {
|
|
45 |
pub fn new(id: ClientId, socket: TcpStream, peer_addr: SocketAddr) -> NetworkClient {
|
|
46 |
NetworkClient {
|
|
47 |
id, socket, peer_addr,
|
|
48 |
decoder: ProtocolDecoder::new(),
|
13414
|
49 |
buf_out: netbuf::Buf::new()
|
13119
|
50 |
}
|
|
51 |
}
|
|
52 |
|
13414
|
53 |
pub fn read_messages(&mut self) -> NetworkResult<Vec<HWProtocolMessage>> {
|
|
54 |
let mut bytes_read = 0;
|
|
55 |
let result = loop {
|
|
56 |
match self.decoder.read_from(&mut self.socket) {
|
|
57 |
Ok(bytes) => {
|
13416
|
58 |
debug!("Client {}: read {} bytes", self.id, bytes);
|
13414
|
59 |
bytes_read += bytes;
|
|
60 |
if bytes == 0 {
|
|
61 |
let result = if bytes_read == 0 {
|
|
62 |
info!("EOF for client {} ({})", self.id, self.peer_addr);
|
|
63 |
(Vec::new(), NetworkClientState::Closed)
|
|
64 |
} else {
|
|
65 |
(self.decoder.extract_messages(), NetworkClientState::NeedsRead)
|
|
66 |
};
|
|
67 |
break Ok(result);
|
|
68 |
}
|
|
69 |
else if bytes_read >= MAX_BYTES_PER_READ {
|
|
70 |
break Ok((self.decoder.extract_messages(), NetworkClientState::NeedsRead))
|
|
71 |
}
|
|
72 |
}
|
|
73 |
Err(ref error) if error.kind() == ErrorKind::WouldBlock => {
|
|
74 |
let messages = if bytes_read == 0 {
|
|
75 |
Vec::new()
|
|
76 |
} else {
|
|
77 |
self.decoder.extract_messages()
|
|
78 |
};
|
|
79 |
break Ok((messages, NetworkClientState::Idle));
|
|
80 |
}
|
|
81 |
Err(error) =>
|
|
82 |
break Err(error)
|
|
83 |
}
|
|
84 |
};
|
|
85 |
self.decoder.sweep();
|
|
86 |
result
|
|
87 |
}
|
|
88 |
|
|
89 |
pub fn flush(&mut self) -> NetworkResult<()> {
|
|
90 |
let result = loop {
|
|
91 |
match self.buf_out.write_to(&mut self.socket) {
|
|
92 |
Ok(bytes) if self.buf_out.is_empty() || bytes == 0 =>
|
|
93 |
break Ok(((), NetworkClientState::Idle)),
|
13415
|
94 |
Ok(_) => (),
|
13414
|
95 |
Err(ref error) if error.kind() == ErrorKind::Interrupted
|
|
96 |
|| error.kind() == ErrorKind::WouldBlock => {
|
|
97 |
break Ok(((), NetworkClientState::NeedsWrite));
|
|
98 |
},
|
|
99 |
Err(error) =>
|
|
100 |
break Err(error)
|
|
101 |
}
|
|
102 |
};
|
|
103 |
self.socket.flush()?;
|
|
104 |
result
|
|
105 |
}
|
|
106 |
|
13119
|
107 |
pub fn send_raw_msg(&mut self, msg: &[u8]) {
|
|
108 |
self.buf_out.write(msg).unwrap();
|
|
109 |
}
|
|
110 |
|
|
111 |
pub fn send_string(&mut self, msg: &String) {
|
|
112 |
self.send_raw_msg(&msg.as_bytes());
|
|
113 |
}
|
|
114 |
|
|
115 |
pub fn send_msg(&mut self, msg: HWServerMessage) {
|
|
116 |
self.send_string(&msg.to_raw_protocol());
|
|
117 |
}
|
|
118 |
}
|
|
119 |
|
|
120 |
pub struct NetworkLayer {
|
|
121 |
listener: TcpListener,
|
|
122 |
server: HWServer,
|
13414
|
123 |
clients: Slab<NetworkClient>,
|
13415
|
124 |
pending: HashSet<(ClientId, NetworkClientState)>,
|
|
125 |
pending_cache: Vec<(ClientId, NetworkClientState)>
|
13119
|
126 |
}
|
|
127 |
|
|
128 |
impl NetworkLayer {
|
|
129 |
pub fn new(listener: TcpListener, clients_limit: usize, rooms_limit: usize) -> NetworkLayer {
|
|
130 |
let server = HWServer::new(clients_limit, rooms_limit);
|
|
131 |
let clients = Slab::with_capacity(clients_limit);
|
13415
|
132 |
let pending = HashSet::with_capacity(2 * clients_limit);
|
|
133 |
let pending_cache = Vec::with_capacity(2 * clients_limit);
|
|
134 |
NetworkLayer {listener, server, clients, pending, pending_cache}
|
13119
|
135 |
}
|
|
136 |
|
|
137 |
pub fn register_server(&self, poll: &Poll) -> io::Result<()> {
|
|
138 |
poll.register(&self.listener, utils::SERVER, Ready::readable(),
|
|
139 |
PollOpt::edge())
|
|
140 |
}
|
|
141 |
|
|
142 |
fn deregister_client(&mut self, poll: &Poll, id: ClientId) {
|
|
143 |
let mut client_exists = false;
|
13414
|
144 |
if let Some(ref client) = self.clients.get(id) {
|
13119
|
145 |
poll.deregister(&client.socket)
|
|
146 |
.ok().expect("could not deregister socket");
|
|
147 |
info!("client {} ({}) removed", client.id, client.peer_addr);
|
|
148 |
client_exists = true;
|
|
149 |
}
|
|
150 |
if client_exists {
|
|
151 |
self.clients.remove(id);
|
|
152 |
}
|
|
153 |
}
|
|
154 |
|
|
155 |
fn register_client(&mut self, poll: &Poll, id: ClientId, client_socket: TcpStream, addr: SocketAddr) {
|
|
156 |
poll.register(&client_socket, Token(id),
|
|
157 |
Ready::readable() | Ready::writable(),
|
|
158 |
PollOpt::edge())
|
|
159 |
.ok().expect("could not register socket with event loop");
|
|
160 |
|
|
161 |
let entry = self.clients.vacant_entry();
|
|
162 |
let client = NetworkClient::new(id, client_socket, addr);
|
|
163 |
info!("client {} ({}) added", client.id, client.peer_addr);
|
|
164 |
entry.insert(client);
|
|
165 |
}
|
|
166 |
|
13414
|
167 |
fn flush_server_messages(&mut self) {
|
|
168 |
debug!("{} pending server messages", self.server.output.len());
|
13419
|
169 |
for (clients, message) in self.server.output.drain(..) {
|
|
170 |
debug!("Message {:?} to {:?}", message, clients);
|
|
171 |
let msg_string = message.to_raw_protocol();
|
|
172 |
for client_id in clients {
|
|
173 |
if let Some(client) = self.clients.get_mut(client_id) {
|
|
174 |
client.send_string(&msg_string);
|
|
175 |
self.pending.insert((client_id, NetworkClientState::NeedsWrite));
|
13414
|
176 |
}
|
|
177 |
}
|
|
178 |
}
|
|
179 |
}
|
|
180 |
|
13119
|
181 |
pub fn accept_client(&mut self, poll: &Poll) -> io::Result<()> {
|
|
182 |
let (client_socket, addr) = self.listener.accept()?;
|
|
183 |
info!("Connected: {}", addr);
|
|
184 |
|
|
185 |
let client_id = self.server.add_client();
|
|
186 |
self.register_client(poll, client_id, client_socket, addr);
|
|
187 |
self.flush_server_messages();
|
|
188 |
|
|
189 |
Ok(())
|
|
190 |
}
|
|
191 |
|
13414
|
192 |
fn operation_failed(&mut self, poll: &Poll, client_id: ClientId, error: Error, msg: &str) -> io::Result<()> {
|
|
193 |
let addr = if let Some(ref mut client) = self.clients.get_mut(client_id) {
|
|
194 |
client.peer_addr
|
|
195 |
} else {
|
|
196 |
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0)
|
|
197 |
};
|
|
198 |
debug!("{}({}): {}", msg, addr, error);
|
|
199 |
self.client_error(poll, client_id)
|
13119
|
200 |
}
|
|
201 |
|
|
202 |
pub fn client_readable(&mut self, poll: &Poll,
|
|
203 |
client_id: ClientId) -> io::Result<()> {
|
13414
|
204 |
let messages =
|
|
205 |
if let Some(ref mut client) = self.clients.get_mut(client_id) {
|
|
206 |
client.read_messages()
|
|
207 |
} else {
|
|
208 |
warn!("invalid readable client: {}", client_id);
|
|
209 |
Ok((Vec::new(), NetworkClientState::Idle))
|
13119
|
210 |
};
|
13414
|
211 |
|
|
212 |
match messages {
|
|
213 |
Ok((messages, state)) => {
|
|
214 |
for message in messages {
|
|
215 |
self.server.handle_msg(client_id, message);
|
|
216 |
}
|
|
217 |
match state {
|
13415
|
218 |
NetworkClientState::NeedsRead => {
|
|
219 |
self.pending.insert((client_id, state));
|
|
220 |
},
|
13414
|
221 |
NetworkClientState::Closed =>
|
|
222 |
self.client_error(&poll, client_id)?,
|
|
223 |
_ => {}
|
|
224 |
};
|
13119
|
225 |
}
|
13414
|
226 |
Err(e) => self.operation_failed(
|
|
227 |
poll, client_id, e,
|
|
228 |
"Error while reading from client socket")?
|
13119
|
229 |
}
|
|
230 |
|
13414
|
231 |
self.flush_server_messages();
|
|
232 |
|
13119
|
233 |
if !self.server.removed_clients.is_empty() {
|
13414
|
234 |
let ids: Vec<_> = self.server.removed_clients.drain(..).collect();
|
13119
|
235 |
for client_id in ids {
|
|
236 |
self.deregister_client(poll, client_id);
|
|
237 |
}
|
|
238 |
}
|
|
239 |
|
|
240 |
Ok(())
|
|
241 |
}
|
|
242 |
|
|
243 |
pub fn client_writable(&mut self, poll: &Poll,
|
|
244 |
client_id: ClientId) -> io::Result<()> {
|
13414
|
245 |
let result =
|
|
246 |
if let Some(ref mut client) = self.clients.get_mut(client_id) {
|
|
247 |
client.flush()
|
|
248 |
} else {
|
|
249 |
warn!("invalid writable client: {}", client_id);
|
|
250 |
Ok(((), NetworkClientState::Idle))
|
|
251 |
};
|
|
252 |
|
|
253 |
match result {
|
13415
|
254 |
Ok(((), state)) if state == NetworkClientState::NeedsWrite => {
|
|
255 |
self.pending.insert((client_id, state));
|
|
256 |
},
|
|
257 |
Ok(_) => {}
|
13414
|
258 |
Err(e) => self.operation_failed(
|
|
259 |
poll, client_id, e,
|
|
260 |
"Error while writing to client socket")?
|
13119
|
261 |
}
|
|
262 |
|
|
263 |
Ok(())
|
|
264 |
}
|
|
265 |
|
|
266 |
pub fn client_error(&mut self, poll: &Poll,
|
|
267 |
client_id: ClientId) -> io::Result<()> {
|
|
268 |
self.deregister_client(poll, client_id);
|
|
269 |
self.server.client_lost(client_id);
|
|
270 |
|
|
271 |
Ok(())
|
|
272 |
}
|
13414
|
273 |
|
|
274 |
pub fn has_pending_operations(&self) -> bool {
|
|
275 |
!self.pending.is_empty()
|
|
276 |
}
|
|
277 |
|
|
278 |
pub fn on_idle(&mut self, poll: &Poll) -> io::Result<()> {
|
13415
|
279 |
if self.has_pending_operations() {
|
|
280 |
let mut cache = Vec::new();
|
|
281 |
swap(&mut cache, &mut self.pending_cache);
|
|
282 |
cache.extend(self.pending.drain());
|
|
283 |
for (id, state) in cache.drain(..) {
|
|
284 |
match state {
|
|
285 |
NetworkClientState::NeedsRead =>
|
|
286 |
self.client_readable(poll, id)?,
|
|
287 |
NetworkClientState::NeedsWrite =>
|
|
288 |
self.client_writable(poll, id)?,
|
|
289 |
_ => {}
|
|
290 |
}
|
13414
|
291 |
}
|
13415
|
292 |
swap(&mut cache, &mut self.pending_cache);
|
13414
|
293 |
}
|
|
294 |
Ok(())
|
|
295 |
}
|
13119
|
296 |
}
|