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