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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
|
use crate::database;
use crate::games::registry::get_game_registry;
use crate::games::traits::GameError;
use crate::tls::TlsStream;
use once_cell::sync::Lazy;
use rusqlite::Connection;
use std::io::{BufRead, BufReader, Write};
use std::net::TcpStream;
use std::sync::Mutex;
static DB_CONN: Lazy<Mutex<Connection>> = Lazy::new(|| {
let conn = Connection::open(std::env::var("SERVER_DB").unwrap_or_else(|_| "server.db".to_string())).unwrap();
database::init_db(&conn);
Mutex::new(conn)
});
#[allow(dead_code)]
pub fn handle_client(stream: TcpStream) {
let client_addr = stream.peer_addr().unwrap().to_string();
let mut user = "guest".to_string();
println!("[{} @ {}] Client connected", user, client_addr);
let reader_stream = stream.try_clone().unwrap();
let reader = BufReader::new(reader_stream);
let mut writer = stream;
for line in reader.lines() {
let line = line.unwrap();
println!("[{} @ {}] Received: {}", user, client_addr, line);
let response = process_message(&line, &mut user);
writeln!(writer, "{}", response).unwrap();
println!("[{} @ {}] Sent: {}", user, client_addr, response);
}
println!("[{} @ {}] Client disconnected", user, client_addr);
}
fn process_message(msg: &str, user: &mut String) -> String {
let parts: Vec<&str> = msg.splitn(5, ' ').collect();
match parts[0] {
"GAME_LIST" => {
let registry = get_game_registry();
let games: Vec<String> = registry.list_games();
if games.is_empty() {
"ERROR No games available".to_string()
} else {
let game_info: Vec<String> = games
.iter()
.filter_map(|gt| {
registry
.get_game(gt)
.map(|g| format!("{}:{}", gt, g.get_name()))
})
.collect();
format!("GAME_LIST {}", game_info.join(","))
}
}
"GAME_INFO" => {
if parts.len() != 2 {
"ERROR Invalid GAME_INFO format. Usage: GAME_INFO <game_type>".to_string()
} else {
let registry = get_game_registry();
match registry.get_game(parts[1]) {
Some(game) => format!(
"GAME_INFO {} {} {}",
parts[1],
game.get_name(),
game.get_description()
),
None => format!("ERROR Unknown game type: {}", parts[1]),
}
}
}
"PLAY_START" => {
if parts.len() != 3 {
"ERROR Invalid PLAY_START format. Usage: PLAY_START <game_type> <bet_amount>"
.to_string()
} else {
handle_play_start(user, parts[1], parts[2])
}
}
"REGISTER" => {
if parts.len() != 3 {
"ERROR Invalid REGISTER format".to_string()
} else {
let username = parts[1];
let hashed_password = parts[2];
let db = DB_CONN.lock().unwrap();
match database::add_user(&db, username, hashed_password) {
Ok(_) => format!("REGISTERED {}", username),
Err(_) => "ERROR User already exists".to_string(),
}
}
}
"AUTH" => {
if parts.len() != 3 {
"ERROR Invalid AUTH format".to_string()
} else {
let username = parts[1];
let sent_hash = parts[2];
let db = DB_CONN.lock().unwrap();
if let Some(stored_hash) = database::get_hashed_password(&db, username) {
if sent_hash == stored_hash {
*user = username.to_string();
format!("OK {}", username)
} else {
"ERROR Invalid credentials".to_string()
}
} else {
"ERROR User not found".to_string()
}
}
}
"PING" => "PONG".to_string(),
"INFO" => {
if *user == "guest" {
"ERROR Not logged in".to_string()
} else {
let db = DB_CONN.lock().unwrap();
if let (Some(id), Some(balance)) = (
database::get_account_id(&db, user),
database::get_balance(&db, user),
) {
format!("INFO {} {} {}", user, id, balance)
} else {
"ERROR Error retrieving user info".to_string()
}
}
}
_ => msg.to_string(),
}
}
fn handle_play_start(user: &str, game_type: &str, bet_amount_str: &str) -> String {
if user == "guest" {
return "ERROR Not logged in".to_string();
}
let bet_amount: u64 = match bet_amount_str.parse() {
Ok(amount) => amount,
Err(_) => return "ERROR Invalid bet amount".to_string(),
};
let db = DB_CONN.lock().unwrap();
let current_balance = match database::get_balance(&db, user) {
Some(balance) => balance as u64,
None => return "ERROR Could not retrieve balance".to_string(),
};
let registry = get_game_registry();
let game = match registry.get_game(game_type) {
Some(game) => game,
None => return format!("ERROR Unknown game type: {}", game_type),
};
if let Err(e) = game.validate_bet(bet_amount, current_balance) {
return match e {
GameError::InsufficientBalance => "ERROR Insufficient balance".to_string(),
GameError::InvalidBet => "ERROR Invalid bet amount".to_string(),
_ => "ERROR Bet validation failed".to_string(),
};
}
let game_state = game.prepare_state(user, bet_amount);
drop(db);
let db = DB_CONN.lock().unwrap();
if let Err(_) = db.execute(
"UPDATE users SET balance = balance - ?1 WHERE username = ?2",
(bet_amount as i64, user),
) {
return "ERROR Failed to deduct bet".to_string();
}
let new_state = match game.process_action(&game_state, "spin", &[]) {
Ok(state) => state,
Err(e) => {
let _ = db.execute(
"UPDATE users SET balance = balance + ?1 WHERE username = ?2",
(bet_amount as i64, user),
);
return format!("ERROR Failed to spin: {:?}", e);
}
};
let result = match game.calculate_result(&new_state) {
Ok(result) => result,
Err(e) => {
let _ = db.execute(
"UPDATE users SET balance = balance + ?1 WHERE username = ?2",
(bet_amount as i64, user),
);
return format!("ERROR Failed to calculate result: {:?}", e);
}
};
let total_return = result.bet_amount + result.winnings;
if let Err(_) = db.execute(
"UPDATE users SET balance = balance + ?1 WHERE username = ?2",
(total_return as i64, user),
) {
return "ERROR Failed to update balance".to_string();
}
let new_balance = match database::get_balance(&db, user) {
Some(balance) => balance,
None => return "ERROR Could not retrieve new balance".to_string(),
};
let reels = new_state.data.get("reels").cloned().unwrap_or_default();
let win_type = new_state.data.get("win_type").cloned().unwrap_or_default();
format!(
"GAME_RESULT {} {} {} {} {} {}",
result.session_id, result.winnings, result.bet_amount, new_balance, reels, win_type
)
}
pub fn handle_client_tls(mut stream: TlsStream) {
let client_addr = stream.peer_addr().unwrap().to_string();
let mut user = "guest".to_string();
println!("[{} @ {}] TLS Client connected", user, client_addr);
loop {
let mut line = String::new();
match stream.read_line(&mut line) {
Ok(0) => break,
Ok(_) => {}
Err(e) => {
eprintln!("Read error: {}", e);
break;
}
}
let line = line.trim();
if line.is_empty() {
continue;
}
println!("[{} @ {}] Received: {}", user, client_addr, line);
let response = process_message(line, &mut user);
if let Err(e) = stream.write_line(&response) {
eprintln!("Write error: {}", e);
break;
}
println!("[{} @ {}] Sent: {}", user, client_addr, response);
}
println!("[{} @ {}] TLS Client disconnected", user, client_addr);
}
|