server.rs 16.9 KB
Newer Older
1
extern crate chrono;
2
use std::io::*;
3
use std::net::{SocketAddr, TcpListener, TcpStream};
4 5 6
use std::thread;
use std::sync::{Arc, Mutex, MutexGuard};
use std::collections::HashMap;
7
use self::chrono::Local;
8

Phuntsok Drak-pa's avatar
Phuntsok Drak-pa committed
9
// TODO: add server-side controls: display clients list, kick client, shutdown
10

11 12 13 14 15 16
///////////////////////////////////////////////////////////////////////////////
//                     Evolution implementation protocole                    //
///////////////////////////////////////////////////////////////////////////////

/*

17 18 19 20 21 22 23
0.1   [X]
1.1   [X]
1.2   [X]
1.3   [X]
1.4   [X]
1.5   [X]
1.6   [X]
24
1.7   [X]
25
1.8   [X]
26
1.9   [X]
27 28 29 30 31 32 33
2.1   [X]
2.2   [X]
3.1   [ ] // pas utile avec Rust
3.2   [X]
4.1.1 [X]
4.1.2 [X]
4.2.1 [X]
34
4.2.2 [X]
35 36 37 38

*/

///////////////////////////////////////////////////////////////////////////////
39
//                                   TYPES                                   //
40 41
///////////////////////////////////////////////////////////////////////////////

42 43 44 45
// Map for all connected clients containing their name and stream
type UserMapValue = (String, TcpStream);
type UserMap = HashMap<SocketAddr, UserMapValue>;

46 47 48 49
///////////////////////////////////////////////////////////////////////////////
//                                    CODE                                   //
///////////////////////////////////////////////////////////////////////////////

50
fn get_time() -> String {
51 52 53 54
    let date = Local::now();
    date.format("[%H:%M:%S]").to_string()
}

55 56 57 58 59 60
fn distribute_message(
    msg: &str,
    not_to: &SocketAddr,
    lock: &mut MutexGuard<UserMap>,
    everyone: bool,
) {
61 62 63 64 65 66 67
    let mut name = String::new();
    for (client, entry) in (*lock).iter() {
        if client == not_to {
            name = entry.0.clone();
            break;
        }
    }
68
    for (other_client, entry) in (*lock).iter() {
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
        let other_name = &entry.0;
        let other_stream = &entry.1;
        if everyone == false && other_client == not_to {
            continue;
        }
        match (|| -> Result<()> {
            let mut writer = BufWriter::new(other_stream);
            // test if message begins with "MSG " /////////////////////////
            if &msg[..4] == "MSG " {
                try!(writeln!(writer, "FROM {} {}", name, msg));
            } else {
                try!(writeln!(writer, "{}", msg));
            }
            ///////////////////////////////////////////////////////////////
            try!(writer.flush());
            return Ok(());
        })()
        {
            Ok(_) => {}
            Err(e) => {
                println!(
90 91 92 93 94
                    "{} Client {} <{}> disappeared during message distribution: {}",
                    get_time(),
                    other_client,
                    other_name,
                    e
95
                );
96 97
            }
        }
98 99 100
    }
}

101 102
fn send_clients_name(to: &SocketAddr, lock: &mut MutexGuard<UserMap>) {
    let mut clients = String::new();
103
    let mut num_client = 0usize;
104
    for (client, entry) in (*lock).iter() {
105
        num_client += 1;
106 107
        clients.push_str(&format!(
            "{}{} ",
108 109
            &entry.0.trim(),
            if client == to { "(you)" } else { "" }
110
        ));
111
    }
112
    let clients = clients.trim();
113 114 115 116
    for (client, entry) in (*lock).iter() {
        if client == to {
            let stream = &entry.1;
            let mut writer = BufWriter::new(stream);
117
            let mut req = String::from(format!("{}{} ", "LIST CLIENTS ", num_client));
118 119 120 121 122 123 124 125 126
            req.push_str(clients);
            println!(
                "{time} to {nick}@{addr} : {message}",
                time = get_time(),
                nick = &entry.0,
                addr = &entry.1.peer_addr().unwrap(),
                message = req
            );
            writeln!(writer, "{}", req).unwrap();
127 128 129 130 131 132
            writer.flush().unwrap();
            return;
        }
    }
}

133 134
fn disconnect_user(name: &str, client: &SocketAddr, lock: &mut MutexGuard<UserMap>) {
    (*lock).remove(&client);
135
    distribute_message(&format!("LOGOUT {}", name), client, lock, true);
136 137 138 139 140
}

fn handle_client(stream: TcpStream, clients: Arc<Mutex<UserMap>>) {
    // Get client IP and port
    let client = stream.peer_addr().unwrap();
141
    println!("{} New connection from {}", get_time(), client);
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
    // Buffered reading and writing
    let mut reader = BufReader::new(&stream);
    let mut writer = BufWriter::new(&stream);

    // Write an entire line to the client
    // Can fail on IO errors, du to try! macro
    macro_rules! send {
        ($line:expr) => ({
            try!(writeln!(writer, "{}", $line));
            try!(writer.flush());
        })
    }

    // Read an entire line from the client
    // Can fail on IO errors or when EOF is reached
    macro_rules! receive {
        () => ({
            let mut line = String::new();
            match reader.read_line(&mut line) {
                Ok(len) => {
                    if len == 0 {
                        // Reader is at EOF.
                        return Err(Error::new(ErrorKind::Other, "unexpected EOF"));
                    }
                    line.pop();
                }
                Err(e) => {
                    return Err(e);
                }
            };
            line
        })
    }

177
    // Get user's name
178 179 180
    let name: String = match (|| loop {
        match receive!() {
            input => {
181 182 183 184 185 186
                println!(
                    "{time} Client {addr} : {message}",
                    time = get_time(),
                    addr = client,
                    message = input
                );
187 188 189 190 191 192 193 194 195 196 197 198
                let spliced_input: Vec<&str> = input.split_whitespace().collect();
                if spliced_input.len() != 4 && spliced_input.len() != 5
                    || spliced_input[0] != "PROT"
                {
                    return Err(Error::new(ErrorKind::Other, "BAD REQ"));
                }
                if spliced_input[1] != ::PROTOCOL {
                    return Err(Error::new(ErrorKind::Other, "BAD PROT"));
                }
                if spliced_input.len() == 5 {
                    if spliced_input[2] == "CONNECT" && spliced_input[3] == "USER" {
                        let username = String::from(spliced_input[4]);
199 200 201 202
                        let mut ascii_nick = true;
                        for c in username.chars() {
                            if !c.is_ascii() {
                                ascii_nick = false;
203 204 205 206 207 208
                                println!(
                                    "{time} to client {addr} : {message}",
                                    time = get_time(),
                                    addr = client,
                                    message = "NAME FAILURE"
                                );
209 210
                                send!("NAME FAILURE");
                                break;
211 212
                            }
                        }
213 214 215 216 217 218 219 220 221 222 223 224
                        if ascii_nick {
                            let mut used = false;
                            {
                                let lock = clients.lock().unwrap();
                                for (_, entry) in (*lock).iter() {
                                    if username == entry.0 {
                                        used = true;
                                        break;
                                    }
                                }
                            }
                            if used == false {
225 226 227 228 229 230
                                println!(
                                    "{time} to client {addr} : {message}",
                                    time = get_time(),
                                    addr = client,
                                    message = "NAME OK"
                                );
231 232 233
                                send!("NAME OK");
                                return Ok(username);
                            } else {
234 235 236 237 238 239
                                println!(
                                    "{time} to client {addr} : {message}",
                                    time = get_time(),
                                    addr = client,
                                    message = "NAME FAILURE"
                                );
240 241
                                send!("NAME FAILURE");
                            }
242
                        }
243 244
                    } else {
                        return Err(Error::new(ErrorKind::Other, "BAD REQ"));
245 246 247 248
                    }
                }

                loop {
249 250 251 252 253 254
                    println!(
                        "{time} to client {addr} : {message}",
                        time = get_time(),
                        addr = client,
                        message = "NAME REQ"
                    );
255 256 257
                    send!("NAME REQ");
                    match receive!() {
                        input => {
258 259 260 261 262 263
                            println!(
                                "{time} Client {addr} : {message}",
                                time = get_time(),
                                addr = client,
                                message = input
                            );
264 265 266 267 268
                            let spliced_input: Vec<&str> = input.split_whitespace().collect();
                            if spliced_input.len() != 2 || spliced_input[0] != "NAME" {
                                return Err(Error::new(ErrorKind::Other, "BAD REQ"));
                            }
                            let username = String::from(spliced_input[1]);
269 270 271 272
                            let mut ascii_nick = true;
                            for c in username.chars() {
                                if !c.is_ascii() {
                                    ascii_nick = false;
273 274 275 276 277 278
                                    println!(
                                        "{time} to client {addr} : {message}",
                                        time = get_time(),
                                        addr = client,
                                        message = "NAME FAILURE"
                                    );
279 280
                                    send!("NAME FAILURE");
                                    break;
281 282
                                }
                            }
283 284 285 286 287 288 289 290 291 292 293 294
                            if ascii_nick {
                                let mut used = false;
                                {
                                    let lock = clients.lock().unwrap();
                                    for (_, entry) in (*lock).iter() {
                                        if username == entry.0 {
                                            used = true;
                                            break;
                                        }
                                    }
                                }
                                if used == false {
295 296 297 298 299 300
                                    println!(
                                        "{time} to client {addr} : {message}",
                                        time = get_time(),
                                        addr = client,
                                        message = "NAME OK"
                                    );
301 302 303
                                    send!("NAME OK");
                                    return Ok(username);
                                } else {
304 305 306 307 308 309
                                    println!(
                                        "{time} to client {addr} : {message}",
                                        time = get_time(),
                                        addr = client,
                                        message = "NAME FAILURE"
                                    );
310 311
                                    send!("NAME FAILURE");
                                }
312 313 314 315 316 317
                            }
                        }
                    }
                }
            }
        }
318 319 320 321
    })()
    {
        Ok(name) => name,
        Err(e) => {
322
            println!(
323
                "{time} client {addr} encountered an error: {err}",
324 325 326
                time = get_time(),
                addr = client,
                err = e
327
            );
328 329
            writeln!(writer, "{}", e).unwrap();
            writer.flush().unwrap();
330
            return ();
331
        }
332 333 334 335 336 337
    };

    // Add user to global map. Lock will be released at the end of the scope
    {
        let mut lock = clients.lock().unwrap();
        (*lock).insert(client, (name.clone(), stream.try_clone().unwrap()));
338
        distribute_message(&format!("JOIN {}", name), &client, &mut lock, false);
339 340
    }

341 342 343
    writeln!(writer, "WELCOME").unwrap();
    writer.flush().unwrap();

344
    // Chat loop: Receive messages from users once connected
345 346 347
    match (|| loop {
        match receive!().as_str() {
            input => {
348 349 350 351 352 353 354 355 356 357
                println!(
                    "{time} {nick}@{addr}: {message}",
                    time = get_time(),
                    addr = client,
                    nick = name,
                    message = input
                );

                match input {
                    "BYE" => {
358
                        println!(
359
                            "{time} to {nick}@{addr} : {message}",
360 361
                            time = get_time(),
                            addr = client,
362 363
                            message = "BYE",
                            nick = name
364
                        );
365 366 367 368
                        send!("BYE");
                        return Ok(());
                    }

369 370
                    "PING" => {
                        println!(
371
                            "{time} to {nick}@{addr} : {message}",
372 373
                            time = get_time(),
                            addr = client,
374 375
                            message = "NAME FAILURE",
                            nick = name
376 377 378
                        );
                        send!("PONG");
                    }
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403

                    "REQ CLIENTS" => {
                        let mut lock = clients.lock().unwrap();
                        send_clients_name(&client, &mut lock);
                    }
                    input => {
                        let spliced_input: Vec<&str> = input.split_whitespace().collect();
                        match spliced_input[0] {
                            "MSG" => {
                                let mut message = String::new();
                                for i in 1..spliced_input.len() {
                                    message.push_str(spliced_input[i]);
                                }
                                {
                                    let mut lock = clients.lock().unwrap();
                                    distribute_message(
                                        &format!("{}", input),
                                        &client,
                                        &mut lock,
                                        true,
                                    );
                                }
                            }
                            _ => {
                                println!(
404
                                    "{time} to client {addr} : \"{message}\", cause : {inmessage}",
405
                                    time = get_time(),
406 407 408
                                    addr = client,
                                    message = "BAD REQ",
                                    inmessage = input
409 410 411 412 413
                                );
                                send!("BAD REQ");
                            }
                        }
                    }
414
                }
415 416 417 418
                // {
                //     let mut lock = clients.lock().unwrap();
                //     distribute_message(&format!("{}", input), &client, &mut lock, true);
                // }
419
            }
420
        }
421 422 423
    })()
    {
        Ok(_) => {
424
            println!("{} Client {} <{}> left", get_time(), client, name);
425 426 427
        }
        Err(e) => {
            println!(
428 429 430 431 432
                "{} Client {} <{}> disappeared during chat: {}",
                get_time(),
                client,
                name,
                e
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
            );
        }
    }

    // Remove user from global map
    {
        let mut lock = clients.lock().unwrap();
        disconnect_user(&name, &client, &mut lock);
    }
}

pub fn serveur(addr: String) {
    // Manage UserMap in a mutex
    let clients = Arc::new(Mutex::new(HashMap::new()));
    let serv_addr = addr.clone();

    // Start a TCP Listener
    let listener = match TcpListener::bind(serv_addr.as_str()) {
        Ok(listener) => listener,
        Err(e) => panic!("Could not read start TCP listener: {}", e),
    };

455 456 457 458 459
    println!(
        "{} Successfully started the server on {}",
        get_time(),
        serv_addr
    );
460 461 462

    for stream in listener.incoming() {
        match stream {
463 464 465 466 467
            Ok(stream) => {
                let clients = clients.clone();
                thread::spawn(move || {
                    //connection succeeded
                    handle_client(stream, clients)
468
                });
469
            }
470 471 472
            Err(e) => {
                writeln!(stderr(), "Connection failed: {}", e).unwrap();
            }
473 474
        }
    }
475 476 477

    // close the socket server
    drop(listener);
478
}