rust/hedgewars-server/src/server/network.rs
author alfadur
Mon, 15 Apr 2019 21:22:51 +0300
changeset 14803 92225a708bda
parent 14796 f5d43f007970
child 14807 b2beb784e4b5
permissions -rw-r--r--
add client timeouts
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
     1
extern crate slab;
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
     2
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
     3
use std::{
13415
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
     4
    collections::HashSet,
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
     5
    io,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
     6
    io::{Error, ErrorKind, Read, Write},
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
     7
    mem::{replace, swap},
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
     8
    net::{IpAddr, Ipv4Addr, SocketAddr},
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
     9
};
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
    10
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
    11
use log::*;
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
    12
use mio::{
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
    13
    net::{TcpListener, TcpStream},
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
    14
    Poll, PollOpt, Ready, Token,
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
    15
};
14803
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
    16
use mio_extras::timer;
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
    17
use netbuf;
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
    18
use slab::Slab;
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
    19
14780
65861ba8b4e8 move room saves to IO thread
alfadur
parents: 14779
diff changeset
    20
use super::{core::HWServer, coretypes::ClientId, handlers};
13666
09f4a30e50cc Rust 2018 conversion
alfadur
parents: 13524
diff changeset
    21
use crate::{
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
    22
    protocol::{messages::*, ProtocolDecoder},
13666
09f4a30e50cc Rust 2018 conversion
alfadur
parents: 13524
diff changeset
    23
    utils,
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
    24
};
14779
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
    25
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
    26
#[cfg(feature = "official-server")]
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
    27
use super::io::{IOThread, RequestId};
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
    28
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
    29
use crate::server::handlers::{IoResult, IoTask};
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    30
#[cfg(feature = "tls-connections")]
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    31
use openssl::{
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
    32
    error::ErrorStack,
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    33
    ssl::{
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
    34
        HandshakeError, MidHandshakeSslStream, Ssl, SslContext, SslContextBuilder, SslFiletype,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
    35
        SslMethod, SslOptions, SslStream, SslStreamBuilder, SslVerifyMode,
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    36
    },
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    37
};
14803
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
    38
use std::time::Duration;
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
    39
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
    40
const MAX_BYTES_PER_READ: usize = 2048;
14803
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
    41
const SEND_PING_TIMEOUT: Duration = Duration::from_secs(30);
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
    42
const DROP_CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
    43
13415
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
    44
#[derive(Hash, Eq, PartialEq, Copy, Clone)]
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
    45
pub enum NetworkClientState {
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
    46
    Idle,
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
    47
    NeedsWrite,
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
    48
    NeedsRead,
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
    49
    Closed,
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
    50
}
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
    51
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
    52
type NetworkResult<T> = io::Result<(T, NetworkClientState)>;
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
    53
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    54
#[cfg(not(feature = "tls-connections"))]
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    55
pub enum ClientSocket {
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
    56
    Plain(TcpStream),
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    57
}
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    58
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    59
#[cfg(feature = "tls-connections")]
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    60
pub enum ClientSocket {
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    61
    SslHandshake(Option<MidHandshakeSslStream<TcpStream>>),
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
    62
    SslStream(SslStream<TcpStream>),
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    63
}
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    64
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    65
impl ClientSocket {
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    66
    fn inner(&self) -> &TcpStream {
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    67
        #[cfg(not(feature = "tls-connections"))]
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    68
        match self {
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    69
            ClientSocket::Plain(stream) => stream,
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    70
        }
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    71
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    72
        #[cfg(feature = "tls-connections")]
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    73
        match self {
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    74
            ClientSocket::SslHandshake(Some(builder)) => builder.get_ref(),
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    75
            ClientSocket::SslHandshake(None) => unreachable!(),
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
    76
            ClientSocket::SslStream(ssl_stream) => ssl_stream.get_ref(),
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    77
        }
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    78
    }
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    79
}
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    80
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
    81
pub struct NetworkClient {
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
    82
    id: ClientId,
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
    83
    socket: ClientSocket,
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
    84
    peer_addr: SocketAddr,
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
    85
    decoder: ProtocolDecoder,
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
    86
    buf_out: netbuf::Buf,
14803
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
    87
    timeout: timer::Timeout,
13119
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
impl NetworkClient {
14803
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
    91
    pub fn new(
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
    92
        id: ClientId,
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
    93
        socket: ClientSocket,
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
    94
        peer_addr: SocketAddr,
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
    95
        timeout: timer::Timeout,
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
    96
    ) -> NetworkClient {
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
    97
        NetworkClient {
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
    98
            id,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
    99
            socket,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   100
            peer_addr,
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   101
            decoder: ProtocolDecoder::new(),
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   102
            buf_out: netbuf::Buf::new(),
14803
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   103
            timeout,
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   104
        }
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   105
    }
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   106
13802
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   107
    #[cfg(feature = "tls-connections")]
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   108
    fn handshake_impl(
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   109
        &mut self,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   110
        handshake: MidHandshakeSslStream<TcpStream>,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   111
    ) -> io::Result<NetworkClientState> {
13802
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   112
        match handshake.handshake() {
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   113
            Ok(stream) => {
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   114
                self.socket = ClientSocket::SslStream(stream);
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   115
                debug!(
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   116
                    "TLS handshake with {} ({}) completed",
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   117
                    self.id, self.peer_addr
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   118
                );
13802
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   119
                Ok(NetworkClientState::Idle)
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   120
            }
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   121
            Err(HandshakeError::WouldBlock(new_handshake)) => {
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   122
                self.socket = ClientSocket::SslHandshake(Some(new_handshake));
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   123
                Ok(NetworkClientState::Idle)
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   124
            }
13803
fea7c23d9c2c rescue the stream on handshake failure
alfadur
parents: 13802
diff changeset
   125
            Err(HandshakeError::Failure(new_handshake)) => {
fea7c23d9c2c rescue the stream on handshake failure
alfadur
parents: 13802
diff changeset
   126
                self.socket = ClientSocket::SslHandshake(Some(new_handshake));
13802
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   127
                debug!("TLS handshake with {} ({}) failed", self.id, self.peer_addr);
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   128
                Err(Error::new(ErrorKind::Other, "Connection failure"))
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   129
            }
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   130
            Err(HandshakeError::SetupFailure(_)) => unreachable!(),
13802
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   131
        }
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   132
    }
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   133
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   134
    fn read_impl<R: Read>(
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   135
        decoder: &mut ProtocolDecoder,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   136
        source: &mut R,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   137
        id: ClientId,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   138
        addr: &SocketAddr,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   139
    ) -> NetworkResult<Vec<HWProtocolMessage>> {
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   140
        let mut bytes_read = 0;
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   141
        let result = loop {
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   142
            match decoder.read_from(source) {
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   143
                Ok(bytes) => {
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   144
                    debug!("Client {}: read {} bytes", id, bytes);
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   145
                    bytes_read += bytes;
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   146
                    if bytes == 0 {
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   147
                        let result = if bytes_read == 0 {
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   148
                            info!("EOF for client {} ({})", id, addr);
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   149
                            (Vec::new(), NetworkClientState::Closed)
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   150
                        } else {
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   151
                            (decoder.extract_messages(), NetworkClientState::NeedsRead)
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   152
                        };
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   153
                        break Ok(result);
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   154
                    } else if bytes_read >= MAX_BYTES_PER_READ {
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   155
                        break Ok((decoder.extract_messages(), NetworkClientState::NeedsRead));
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   156
                    }
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   157
                }
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   158
                Err(ref error) if error.kind() == ErrorKind::WouldBlock => {
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   159
                    let messages = if bytes_read == 0 {
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   160
                        Vec::new()
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   161
                    } else {
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   162
                        decoder.extract_messages()
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   163
                    };
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   164
                    break Ok((messages, NetworkClientState::Idle));
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   165
                }
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   166
                Err(error) => break Err(error),
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   167
            }
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   168
        };
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   169
        result
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   170
    }
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   171
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   172
    pub fn read(&mut self) -> NetworkResult<Vec<HWProtocolMessage>> {
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   173
        #[cfg(not(feature = "tls-connections"))]
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   174
        match self.socket {
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   175
            ClientSocket::Plain(ref mut stream) => {
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   176
                NetworkClient::read_impl(&mut self.decoder, stream, self.id, &self.peer_addr)
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   177
            }
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   178
        }
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   179
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   180
        #[cfg(feature = "tls-connections")]
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   181
        match self.socket {
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   182
            ClientSocket::SslHandshake(ref mut handshake_opt) => {
13802
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   183
                let handshake = std::mem::replace(handshake_opt, None).unwrap();
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   184
                Ok((Vec::new(), self.handshake_impl(handshake)?))
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   185
            }
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   186
            ClientSocket::SslStream(ref mut stream) => {
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   187
                NetworkClient::read_impl(&mut self.decoder, stream, self.id, &self.peer_addr)
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   188
            }
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   189
        }
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   190
    }
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   191
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   192
    fn write_impl<W: Write>(buf_out: &mut netbuf::Buf, destination: &mut W) -> NetworkResult<()> {
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   193
        let result = loop {
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   194
            match buf_out.write_to(destination) {
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   195
                Ok(bytes) if buf_out.is_empty() || bytes == 0 => {
14671
455865ccd36c Server action refactoring part 2 of N
alfadur <mail@none>
parents: 14457
diff changeset
   196
                    break Ok(((), NetworkClientState::Idle));
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   197
                }
13415
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
   198
                Ok(_) => (),
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   199
                Err(ref error)
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   200
                    if error.kind() == ErrorKind::Interrupted
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   201
                        || error.kind() == ErrorKind::WouldBlock =>
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   202
                {
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   203
                    break Ok(((), NetworkClientState::NeedsWrite));
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   204
                }
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   205
                Err(error) => break Err(error),
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   206
            }
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   207
        };
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   208
        result
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   209
    }
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   210
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   211
    pub fn write(&mut self) -> NetworkResult<()> {
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   212
        let result = {
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   213
            #[cfg(not(feature = "tls-connections"))]
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   214
            match self.socket {
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   215
                ClientSocket::Plain(ref mut stream) => {
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   216
                    NetworkClient::write_impl(&mut self.buf_out, stream)
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   217
                }
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   218
            }
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   219
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   220
            #[cfg(feature = "tls-connections")]
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   221
            {
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   222
                match self.socket {
13802
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   223
                    ClientSocket::SslHandshake(ref mut handshake_opt) => {
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   224
                        let handshake = std::mem::replace(handshake_opt, None).unwrap();
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   225
                        Ok(((), self.handshake_impl(handshake)?))
24fe56d3c6a2 improve error handling for TLS handshake
alfadur
parents: 13799
diff changeset
   226
                    }
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   227
                    ClientSocket::SslStream(ref mut stream) => {
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   228
                        NetworkClient::write_impl(&mut self.buf_out, stream)
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   229
                    }
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   230
                }
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   231
            }
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   232
        };
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   233
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   234
        self.socket.inner().flush()?;
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   235
        result
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   236
    }
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   237
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   238
    pub fn send_raw_msg(&mut self, msg: &[u8]) {
13524
5359ff75da3a indulge clippy
alfadur
parents: 13478
diff changeset
   239
        self.buf_out.write_all(msg).unwrap();
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   240
    }
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   241
13524
5359ff75da3a indulge clippy
alfadur
parents: 13478
diff changeset
   242
    pub fn send_string(&mut self, msg: &str) {
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   243
        self.send_raw_msg(&msg.as_bytes());
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   244
    }
14803
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   245
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   246
    pub fn replace_timeout(&mut self, timeout: timer::Timeout) -> timer::Timeout {
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   247
        replace(&mut self.timeout, timeout)
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   248
    }
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   249
}
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   250
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   251
#[cfg(feature = "tls-connections")]
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   252
struct ServerSsl {
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   253
    context: SslContext,
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   254
}
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   255
14779
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   256
#[cfg(feature = "official-server")]
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   257
pub struct IoLayer {
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   258
    next_request_id: RequestId,
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   259
    request_queue: Vec<(RequestId, ClientId)>,
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   260
    io_thread: IOThread,
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   261
}
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   262
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   263
#[cfg(feature = "official-server")]
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   264
impl IoLayer {
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   265
    fn new() -> Self {
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   266
        Self {
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   267
            next_request_id: 0,
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   268
            request_queue: vec![],
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   269
            io_thread: IOThread::new(),
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   270
        }
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   271
    }
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   272
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   273
    fn send(&mut self, client_id: ClientId, task: IoTask) {
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   274
        let request_id = self.next_request_id;
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   275
        self.next_request_id += 1;
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   276
        self.request_queue.push((request_id, client_id));
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   277
        self.io_thread.send(request_id, task);
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   278
    }
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   279
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   280
    fn try_recv(&mut self) -> Option<(ClientId, IoResult)> {
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   281
        let (request_id, result) = self.io_thread.try_recv()?;
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   282
        if let Some(index) = self
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   283
            .request_queue
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   284
            .iter()
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   285
            .position(|(id, _)| *id == request_id)
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   286
        {
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   287
            let (_, client_id) = self.request_queue.swap_remove(index);
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   288
            Some((client_id, result))
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   289
        } else {
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   290
            None
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   291
        }
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   292
    }
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   293
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   294
    fn cancel(&mut self, client_id: ClientId) {
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   295
        let mut index = 0;
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   296
        while index < self.request_queue.len() {
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   297
            if self.request_queue[index].1 == client_id {
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   298
                self.request_queue.swap_remove(index);
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   299
            } else {
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   300
                index += 1;
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   301
            }
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   302
        }
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   303
    }
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   304
}
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   305
14803
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   306
enum TimeoutEvent {
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   307
    SendPing,
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   308
    DropClient,
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   309
}
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   310
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   311
struct TimerData(TimeoutEvent, ClientId);
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   312
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   313
pub struct NetworkLayer {
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   314
    listener: TcpListener,
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   315
    server: HWServer,
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   316
    clients: Slab<NetworkClient>,
13415
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
   317
    pending: HashSet<(ClientId, NetworkClientState)>,
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   318
    pending_cache: Vec<(ClientId, NetworkClientState)>,
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   319
    #[cfg(feature = "tls-connections")]
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   320
    ssl: ServerSsl,
14779
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   321
    #[cfg(feature = "official-server")]
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   322
    io: IoLayer,
14803
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   323
    timer: timer::Timer<TimerData>,
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   324
}
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   325
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   326
fn create_ping_timeout(timer: &mut timer::Timer<TimerData>, client_id: ClientId) -> timer::Timeout {
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   327
    timer.set_timeout(
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   328
        SEND_PING_TIMEOUT,
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   329
        TimerData(TimeoutEvent::SendPing, client_id),
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   330
    )
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   331
}
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   332
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   333
fn create_drop_timeout(timer: &mut timer::Timer<TimerData>, client_id: ClientId) -> timer::Timeout {
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   334
    timer.set_timeout(
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   335
        DROP_CLIENT_TIMEOUT,
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   336
        TimerData(TimeoutEvent::DropClient, client_id),
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   337
    )
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   338
}
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   339
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   340
impl NetworkLayer {
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   341
    pub fn new(listener: TcpListener, clients_limit: usize, rooms_limit: usize) -> NetworkLayer {
14780
65861ba8b4e8 move room saves to IO thread
alfadur
parents: 14779
diff changeset
   342
        let server = HWServer::new(clients_limit, rooms_limit);
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   343
        let clients = Slab::with_capacity(clients_limit);
13415
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
   344
        let pending = HashSet::with_capacity(2 * clients_limit);
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
   345
        let pending_cache = Vec::with_capacity(2 * clients_limit);
14803
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   346
        let timer = timer::Builder::default().build();
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   347
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   348
        NetworkLayer {
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   349
            listener,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   350
            server,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   351
            clients,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   352
            pending,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   353
            pending_cache,
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   354
            #[cfg(feature = "tls-connections")]
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   355
            ssl: NetworkLayer::create_ssl_context(),
14779
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   356
            #[cfg(feature = "official-server")]
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   357
            io: IoLayer::new(),
14803
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   358
            timer,
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   359
        }
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   360
    }
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   361
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   362
    #[cfg(feature = "tls-connections")]
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   363
    fn create_ssl_context() -> ServerSsl {
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   364
        let mut builder = SslContextBuilder::new(SslMethod::tls()).unwrap();
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   365
        builder.set_verify(SslVerifyMode::NONE);
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   366
        builder.set_read_ahead(true);
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   367
        builder
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   368
            .set_certificate_file("ssl/cert.pem", SslFiletype::PEM)
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   369
            .unwrap();
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   370
        builder
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   371
            .set_private_key_file("ssl/key.pem", SslFiletype::PEM)
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   372
            .unwrap();
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   373
        builder.set_options(SslOptions::NO_COMPRESSION);
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   374
        builder.set_cipher_list("DEFAULT:!LOW:!RC4:!EXP").unwrap();
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   375
        ServerSsl {
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   376
            context: builder.build(),
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   377
        }
13119
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
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   380
    pub fn register_server(&self, poll: &Poll) -> io::Result<()> {
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   381
        poll.register(
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   382
            &self.listener,
14779
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   383
            utils::SERVER_TOKEN,
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   384
            Ready::readable(),
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   385
            PollOpt::edge(),
14779
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   386
        )?;
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   387
14803
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   388
        poll.register(
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   389
            &self.timer,
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   390
            utils::TIMER_TOKEN,
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   391
            Ready::readable(),
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   392
            PollOpt::edge(),
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   393
        )?;
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   394
14779
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   395
        #[cfg(feature = "official-server")]
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   396
        self.io.io_thread.register_rx(poll, utils::IO_TOKEN)?;
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   397
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   398
        Ok(())
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   399
    }
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   400
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   401
    fn deregister_client(&mut self, poll: &Poll, id: ClientId) {
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   402
        let mut client_exists = false;
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   403
        if let Some(ref client) = self.clients.get(id) {
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   404
            poll.deregister(client.socket.inner())
13524
5359ff75da3a indulge clippy
alfadur
parents: 13478
diff changeset
   405
                .expect("could not deregister socket");
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   406
            info!("client {} ({}) removed", client.id, client.peer_addr);
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   407
            client_exists = true;
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
        if client_exists {
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   410
            self.clients.remove(id);
14779
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   411
            #[cfg(feature = "official-server")]
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   412
            self.io.cancel(id);
13119
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
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   416
    fn register_client(
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   417
        &mut self,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   418
        poll: &Poll,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   419
        client_socket: ClientSocket,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   420
        addr: SocketAddr,
14693
6a2e13e36b7f add server anteroom
alfadur <mail@none>
parents: 14673
diff changeset
   421
    ) -> ClientId {
6a2e13e36b7f add server anteroom
alfadur <mail@none>
parents: 14673
diff changeset
   422
        let entry = self.clients.vacant_entry();
6a2e13e36b7f add server anteroom
alfadur <mail@none>
parents: 14673
diff changeset
   423
        let client_id = entry.key();
6a2e13e36b7f add server anteroom
alfadur <mail@none>
parents: 14673
diff changeset
   424
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   425
        poll.register(
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   426
            client_socket.inner(),
14693
6a2e13e36b7f add server anteroom
alfadur <mail@none>
parents: 14673
diff changeset
   427
            Token(client_id),
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   428
            Ready::readable() | Ready::writable(),
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   429
            PollOpt::edge(),
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   430
        )
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   431
        .expect("could not register socket with event loop");
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   432
14803
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   433
        let client = NetworkClient::new(
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   434
            client_id,
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   435
            client_socket,
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   436
            addr,
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   437
            create_ping_timeout(&mut self.timer, client_id),
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   438
        );
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   439
        info!("client {} ({}) added", client.id, client.peer_addr);
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   440
        entry.insert(client);
14693
6a2e13e36b7f add server anteroom
alfadur <mail@none>
parents: 14673
diff changeset
   441
6a2e13e36b7f add server anteroom
alfadur <mail@none>
parents: 14673
diff changeset
   442
        client_id
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   443
    }
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   444
14779
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   445
    fn handle_response(&mut self, mut response: handlers::Response, poll: &Poll) {
14672
6e6632068a33 Server action refactoring part 3 of N
alfadur <mail@none>
parents: 14671
diff changeset
   446
        debug!("{} pending server messages", response.len());
6e6632068a33 Server action refactoring part 3 of N
alfadur <mail@none>
parents: 14671
diff changeset
   447
        let output = response.extract_messages(&mut self.server);
6e6632068a33 Server action refactoring part 3 of N
alfadur <mail@none>
parents: 14671
diff changeset
   448
        for (clients, message) in output {
13419
81e0ed105f5d implementation of team related messages
alfadur
parents: 13416
diff changeset
   449
            debug!("Message {:?} to {:?}", message, clients);
81e0ed105f5d implementation of team related messages
alfadur
parents: 13416
diff changeset
   450
            let msg_string = message.to_raw_protocol();
81e0ed105f5d implementation of team related messages
alfadur
parents: 13416
diff changeset
   451
            for client_id in clients {
81e0ed105f5d implementation of team related messages
alfadur
parents: 13416
diff changeset
   452
                if let Some(client) = self.clients.get_mut(client_id) {
81e0ed105f5d implementation of team related messages
alfadur
parents: 13416
diff changeset
   453
                    client.send_string(&msg_string);
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   454
                    self.pending
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   455
                        .insert((client_id, NetworkClientState::NeedsWrite));
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   456
                }
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   457
            }
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   458
        }
14696
8a45c90f4580 fix client removal
alfadur
parents: 14693
diff changeset
   459
8a45c90f4580 fix client removal
alfadur
parents: 14693
diff changeset
   460
        for client_id in response.extract_removed_clients() {
8a45c90f4580 fix client removal
alfadur
parents: 14693
diff changeset
   461
            self.deregister_client(poll, client_id);
8a45c90f4580 fix client removal
alfadur
parents: 14693
diff changeset
   462
        }
14779
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   463
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   464
        #[cfg(feature = "official-server")]
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   465
        {
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   466
            let client_id = response.client_id();
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   467
            for task in response.extract_io_tasks() {
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   468
                self.io.send(client_id, task);
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   469
            }
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   470
        }
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   471
    }
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   472
14803
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   473
    pub fn handle_timeout(&mut self, poll: &Poll) -> io::Result<()> {
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   474
        while let Some(TimerData(event, client_id)) = self.timer.poll() {
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   475
            match event {
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   476
                TimeoutEvent::SendPing => {
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   477
                    if let Some(ref mut client) = self.clients.get_mut(client_id) {
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   478
                        client.send_string(&HWServerMessage::Ping.to_raw_protocol());
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   479
                        client.write()?;
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   480
                        client.replace_timeout(create_drop_timeout(&mut self.timer, client_id));
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   481
                    }
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   482
                }
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   483
                TimeoutEvent::DropClient => {
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   484
                    self.operation_failed(
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   485
                        poll,
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   486
                        client_id,
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   487
                        &ErrorKind::TimedOut.into(),
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   488
                        "No ping response",
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   489
                    )?;
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   490
                }
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   491
            }
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   492
        }
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   493
        Ok(())
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   494
    }
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   495
14779
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   496
    #[cfg(feature = "official-server")]
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   497
    pub fn handle_io_result(&mut self) {
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   498
        if let Some((client_id, result)) = self.io.try_recv() {
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   499
            let mut response = handlers::Response::new(client_id);
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   500
            handlers::handle_io_result(&mut self.server, client_id, &mut response, result);
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   501
        }
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   502
    }
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   503
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   504
    fn create_client_socket(&self, socket: TcpStream) -> io::Result<ClientSocket> {
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   505
        #[cfg(not(feature = "tls-connections"))]
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   506
        {
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   507
            Ok(ClientSocket::Plain(socket))
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   508
        }
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   509
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   510
        #[cfg(feature = "tls-connections")]
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   511
        {
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   512
            let ssl = Ssl::new(&self.ssl.context).unwrap();
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   513
            let mut builder = SslStreamBuilder::new(ssl, socket);
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   514
            builder.set_accept_state();
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   515
            match builder.handshake() {
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   516
                Ok(stream) => Ok(ClientSocket::SslStream(stream)),
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   517
                Err(HandshakeError::WouldBlock(stream)) => {
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   518
                    Ok(ClientSocket::SslHandshake(Some(stream)))
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   519
                }
13799
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   520
                Err(e) => {
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   521
                    debug!("OpenSSL handshake failed: {}", e);
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   522
                    Err(Error::new(ErrorKind::Other, "Connection failure"))
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   523
                }
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   524
            }
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   525
        }
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   526
    }
c8fd12db6215 Add TLS support
alfadur
parents: 13666
diff changeset
   527
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   528
    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
   529
        let (client_socket, addr) = self.listener.accept()?;
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   530
        info!("Connected: {}", addr);
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   531
14693
6a2e13e36b7f add server anteroom
alfadur <mail@none>
parents: 14673
diff changeset
   532
        let client_id = self.register_client(poll, self.create_client_socket(client_socket)?, addr);
6a2e13e36b7f add server anteroom
alfadur <mail@none>
parents: 14673
diff changeset
   533
6a2e13e36b7f add server anteroom
alfadur <mail@none>
parents: 14673
diff changeset
   534
        let mut response = handlers::Response::new(client_id);
6a2e13e36b7f add server anteroom
alfadur <mail@none>
parents: 14673
diff changeset
   535
6a2e13e36b7f add server anteroom
alfadur <mail@none>
parents: 14673
diff changeset
   536
        handlers::handle_client_accept(&mut self.server, client_id, &mut response);
6a2e13e36b7f add server anteroom
alfadur <mail@none>
parents: 14673
diff changeset
   537
6a2e13e36b7f add server anteroom
alfadur <mail@none>
parents: 14673
diff changeset
   538
        if !response.is_empty() {
14779
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   539
            self.handle_response(response, poll);
14693
6a2e13e36b7f add server anteroom
alfadur <mail@none>
parents: 14673
diff changeset
   540
        }
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   541
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   542
        Ok(())
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   543
    }
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   544
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   545
    fn operation_failed(
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   546
        &mut self,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   547
        poll: &Poll,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   548
        client_id: ClientId,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   549
        error: &Error,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   550
        msg: &str,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   551
    ) -> io::Result<()> {
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   552
        let addr = if let Some(ref mut client) = self.clients.get_mut(client_id) {
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   553
            client.peer_addr
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   554
        } else {
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   555
            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0)
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   556
        };
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   557
        debug!("{}({}): {}", msg, addr, error);
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   558
        self.client_error(poll, client_id)
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   559
    }
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   560
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   561
    pub fn client_readable(&mut self, poll: &Poll, client_id: ClientId) -> io::Result<()> {
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   562
        let messages = if let Some(ref mut client) = self.clients.get_mut(client_id) {
14803
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   563
            let timeout = client.replace_timeout(create_ping_timeout(&mut self.timer, client_id));
92225a708bda add client timeouts
alfadur
parents: 14796
diff changeset
   564
            self.timer.cancel_timeout(&timeout);
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   565
            client.read()
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   566
        } else {
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   567
            warn!("invalid readable client: {}", client_id);
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   568
            Ok((Vec::new(), NetworkClientState::Idle))
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   569
        };
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   570
14671
455865ccd36c Server action refactoring part 2 of N
alfadur <mail@none>
parents: 14457
diff changeset
   571
        let mut response = handlers::Response::new(client_id);
455865ccd36c Server action refactoring part 2 of N
alfadur <mail@none>
parents: 14457
diff changeset
   572
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   573
        match messages {
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   574
            Ok((messages, state)) => {
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   575
                for message in messages {
14671
455865ccd36c Server action refactoring part 2 of N
alfadur <mail@none>
parents: 14457
diff changeset
   576
                    debug!("Handling message {:?} for client {}", message, client_id);
14796
f5d43f007970 start by actually handling client messages
alfadur
parents: 14795
diff changeset
   577
                    handlers::handle(&mut self.server, client_id, &mut response, message);
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   578
                }
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   579
                match state {
13415
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
   580
                    NetworkClientState::NeedsRead => {
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
   581
                        self.pending.insert((client_id, state));
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   582
                    }
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   583
                    NetworkClientState::Closed => self.client_error(&poll, client_id)?,
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   584
                    _ => {}
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   585
                };
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   586
            }
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   587
            Err(e) => self.operation_failed(
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   588
                poll,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   589
                client_id,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   590
                &e,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   591
                "Error while reading from client socket",
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   592
            )?,
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   593
        }
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   594
14672
6e6632068a33 Server action refactoring part 3 of N
alfadur <mail@none>
parents: 14671
diff changeset
   595
        if !response.is_empty() {
14779
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   596
            self.handle_response(response, poll);
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   597
        }
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   598
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   599
        Ok(())
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   600
    }
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   601
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   602
    pub fn client_writable(&mut self, poll: &Poll, client_id: ClientId) -> io::Result<()> {
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   603
        let result = if let Some(ref mut client) = self.clients.get_mut(client_id) {
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   604
            client.write()
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   605
        } else {
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   606
            warn!("invalid writable client: {}", client_id);
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   607
            Ok(((), NetworkClientState::Idle))
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   608
        };
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   609
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   610
        match result {
13415
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
   611
            Ok(((), state)) if state == NetworkClientState::NeedsWrite => {
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
   612
                self.pending.insert((client_id, state));
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   613
            }
13415
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
   614
            Ok(_) => {}
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   615
            Err(e) => {
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   616
                self.operation_failed(poll, client_id, &e, "Error while writing to client socket")?
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   617
            }
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   618
        }
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   619
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   620
        Ok(())
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   621
    }
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   622
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   623
    pub fn client_error(&mut self, poll: &Poll, client_id: ClientId) -> io::Result<()> {
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   624
        self.deregister_client(poll, client_id);
14673
08a8605bafaf Server action refactoring part 4 of N
alfadur <mail@none>
parents: 14672
diff changeset
   625
        let mut response = handlers::Response::new(client_id);
08a8605bafaf Server action refactoring part 4 of N
alfadur <mail@none>
parents: 14672
diff changeset
   626
        handlers::handle_client_loss(&mut self.server, client_id, &mut response);
14779
f43ab2bd76ae add a thread for internal server IO and implement account checking with it
alfadur
parents: 14697
diff changeset
   627
        self.handle_response(response, poll);
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   628
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   629
        Ok(())
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   630
    }
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   631
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   632
    pub fn has_pending_operations(&self) -> bool {
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   633
        !self.pending.is_empty()
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   634
    }
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   635
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   636
    pub fn on_idle(&mut self, poll: &Poll) -> io::Result<()> {
13415
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
   637
        if self.has_pending_operations() {
13478
d79795acaa73 Mostly implement voting
alfadur
parents: 13419
diff changeset
   638
            let mut cache = replace(&mut self.pending_cache, Vec::new());
13415
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
   639
            cache.extend(self.pending.drain());
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
   640
            for (id, state) in cache.drain(..) {
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
   641
                match state {
14457
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   642
                    NetworkClientState::NeedsRead => self.client_readable(poll, id)?,
98ef2913ec73 Apply rustfmt to all files
unc0rr
parents: 14415
diff changeset
   643
                    NetworkClientState::NeedsWrite => self.client_writable(poll, id)?,
13415
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
   644
                    _ => {}
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
   645
                }
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   646
            }
13415
0eedc17055a0 rework of prior
alfadur
parents: 13414
diff changeset
   647
            swap(&mut cache, &mut self.pending_cache);
13414
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   648
        }
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   649
        Ok(())
28b314ad566d handle edge polling properly
alfadur
parents: 13119
diff changeset
   650
    }
13119
1e39b8749072 separated the server logic from all the async io mess.
alfadur
parents:
diff changeset
   651
}