1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
use std::collections::HashMap;
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::thread;
use std::thread::JoinHandle;

use crate::backend_connection::*;
use crate::error::ServerError;
use crate::group::{Group, GroupId, Message as GroupMessage};
use log::{error, info, warn};
use ws::{listen, CloseCode, Handler, Handshake, Message, Request, Response, Sender};

const PROTOCOL: &str = "tuesday";
// WebSocket connection handler for the server connection
pub struct Socket {
    ws: Sender,
    group: mpsc::Sender<GroupMessage>,
    groups: Arc<Mutex<HashMap<u32, Group>>>,
    ip: String,
    id: GroupId,
}

pub fn run(address: &str, port: &str) -> Result<JoinHandle<()>, ServerError> {
    let count = Arc::new(Mutex::new(HashMap::new()));
    let (sender, _) = mpsc::channel();
    let url = format!("{}:{}", address, port);
    thread::Builder::new()
        .name("server".to_owned())
        .spawn(move || {
            listen(url, |out| Socket {
                ws: out,
                group: sender.clone(),
                groups: count.clone(),
                ip: "No ip".to_owned(),
                id: 0,
            })
            .unwrap()
        })
        .map_err(ServerError::WebSocketCreation)
}

impl Handler for Socket {
    // called when the socket connection is created
    fn on_open(&mut self, handshake: Handshake) -> ws::Result<()> {
        if let Ok(Some(ip)) = handshake.remote_addr() {
            self.ip = ip;
        }
        Ok(())
    }

    fn on_message(&mut self, msg: Message) -> ws::Result<()> {
        info!("Socket got message '{}'. ", msg);

        self.group
            .send(GroupMessage::Data((self.ip.clone(), msg.into_data())))
            .unwrap_or_else(|err| {
                let err = format!("failed to deliver internal message {}", err);
                error!("{}", err);
                self.ws
                    .close_with_reason(CloseCode::Error, err)
                    .unwrap_or_else(|e| error!("failed to send message to client {}", e));
            });

        Ok(())
    }

    fn on_close(&mut self, _: CloseCode, _: &str) {
        if let Ok(mut guard) = self.groups.lock() {
            if let Some(group) = guard.get_mut(&self.id) {
                if group.remove_client(&self.ws).is_err() {
                    warn!("failed to remove Client from Game");
                }
                if group.clients.is_empty() {
                    //guard.remove(&self.id); // TODO
                }
            }
        }
    }

    // low-level handling of requests
    fn on_request(&mut self, req: &Request) -> ws::Result<Response> {
        let (res, token) = handshake(req);
        Ok(
            match token
                .and_then(|token| {
                    info!("received token: {}", token);
                    crate::backend_connection::verify_token(token)
                })
                .and_then(move |response| self.handle_token(response))
            {
                Ok(()) => res,
                Err(err) => fail_response(
                    res,
                    format!("Client {:?}: {:?}", req.client_addr(), err).as_str(),
                ),
            },
        )
    }
}

impl Socket {
    fn handle_token(&mut self, response: TokenResponse) -> Result<(), ServerError> {
        match self.groups.lock() {
            Ok(mut guard) => {
                self.id = response.group_id;
                if !guard.contains_key(&response.group_id) {
                    let group = Group::new(response)?;
                    self.group = group.sender.clone();
                    guard.insert(group.id(), group);
                }

                // panics if any thread panicked while using the mutex
                let group = &mut self.group;
                guard
                    .get_mut(&self.id)
                    .unwrap()
                    .add_client(self.ws.clone())
                    .map(|s| *group = s)
            }
            Err(e) => Err(ServerError::Group(format!(
                "cold not add client {:?}  to group {}: {}",
                self.ws, response.group_id, e
            ))),
        }
    }
}

fn handshake(req: &Request) -> (Response, Result<i32, ServerError>) {
    let mut res = Response::from_request(req).unwrap();
    if let Ok(protocols) = req.protocols() {
        if protocols.iter().any(|pro| pro.contains(PROTOCOL)) {
            res.set_protocol(PROTOCOL)
        } else {
            return (
                fail_response(
                    res,
                    format!("does not support the {} protocol", PROTOCOL).as_str(),
                ),
                Err(ServerError::InvalidProtocol),
            );
        }
        let token = protocols.iter().find(|pro| pro.starts_with("Token-"));
        match token {
            Some(token) => {
                let (_, token) = token.split_at(6);
                if let Ok(token) = token.parse::<i32>() {
                    (res, Ok(token))
                } else {
                    (
                        fail_response(res, "token is no valid i32"),
                        Err(ServerError::InvalidTokenFormat),
                    )
                }
            }
            None => (
                fail_response(res, "no token in protocols"),
                Err(ServerError::InvalidToken(
                    "No Token was passed as a Protocol in the Sec-WebSocket-Protocol Header"
                        .to_string(),
                )),
            ),
        }
    } else {
        (
            fail_response(res, "failed to retrieve protocols"),
            Err(ServerError::InvalidProtocol),
        )
    }
}

fn fail_response(mut res: Response, reason: &str) -> Response {
    res.set_status(400);
    res.set_reason(reason);
    warn!("{}", reason);
    res
}