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