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