summaryrefslogtreecommitdiffstats
path: root/src/client/connection.rs
blob: 497ed369fdae91f3bbfcfee1b12f3bbf057de8b7 (plain) (blame)
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
use std::io::{BufRead, BufReader, Write};
use std::net::TcpStream;
use std::sync::mpsc;
use std::thread;
use std::time::{Duration, Instant};
use rusqlite::Connection;
use bcrypt::hash_with_salt;
use crate::database;

const SALT: [u8; 16] = *b"fixedsalt1234567";

fn hash_password(password: &str) -> String {
    let result = hash_with_salt(password, 10, SALT).unwrap();
    result.to_string()
}

pub fn connect(addr: &str, conn: &Connection) -> Result<TcpStream, Box<dyn std::error::Error>> {
    let (tx, rx) = mpsc::channel();
    let addr_str = addr.to_string();
    thread::spawn(move || {
        match TcpStream::connect(&addr_str) {
            Ok(s) => tx.send(Ok(s)).unwrap(),
            Err(e) => tx.send(Err(e)).unwrap(),
        }
    });
    match rx.recv_timeout(Duration::from_secs(3)) {
        Ok(Ok(s)) => {
            let mut ping_writer = s.try_clone().unwrap();
            let mut ping_reader = BufReader::new(s.try_clone().unwrap());
            let start = Instant::now();
            writeln!(ping_writer, "PING").unwrap();
            let mut response = String::new();
            ping_reader.read_line(&mut response).unwrap();
            let elapsed = start.elapsed();
            println!("\n\rConnected to {} with ping delay: {:?}", addr, elapsed);
            
            // Check for credentials and auto-auth
            if let Some((username, password)) = database::get_credentials(conn, addr) {
                let hashed = hash_password(&password);
                let auth_msg = format!("AUTH {} {}", username, hashed);
                writeln!(ping_writer, "{}", auth_msg).unwrap();
                let mut auth_response = String::new();
                ping_reader.read_line(&mut auth_response).unwrap();
                if auth_response.trim().starts_with("OK") {
                    println!("Authenticated as {}", username);
                } else {
                    println!("Authentication failed: {}", auth_response.trim());
                    // Do not fail, allow manual login
                }
            }
            Ok(s)
        }
        Ok(Err(e)) => Err(Box::new(e)),
        Err(mpsc::RecvTimeoutError::Timeout) => Err("Connection timed out after 3 seconds".into()),
        Err(_) => Err("Connection attempt failed".into()),
    }
}