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