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