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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
#![deny(missing_docs)]
pub mod cmds;
pub mod comms;
pub mod copyover;
pub mod prelude;
pub mod states;
use comms::{Client, Comms, Server};
use db::utils::{gen_uid, UID};
use crate::prelude::{LinesCodecResult, GAME_ADDR, PROXY_ADDR};
use crate::states::ConnStates;
use db::cache_structures::socket::CacheSocket;
use db::cache_structures::Cachable;
use futures::future::try_join;
use futures::SinkExt;
use std::error::Error;
use std::sync::Arc;
use std::{env, str};
use tokio::fs::File;
use tokio::net::{TcpListener, TcpStream};
use tokio::prelude::*;
use tokio::stream::StreamExt;
use tokio::sync::Mutex;
pub async fn send<'a>(client: &'a mut Client, msg: &'a str) -> LinesCodecResult<()> {
client.lines.send(msg.into()).await?;
Ok(())
}
pub async fn get<'a>(client: &'a mut Client) -> Option<String> {
client.lines.next().await.map_or(None, |v| v.ok())
}
pub async fn display_welcome<'a>(client: &'a mut Client) -> LinesCodecResult<()> {
let mut file = File::open("resources/welcome.txt").await?;
let mut contents = String::new();
file.read_to_string(&mut contents).await?;
client.lines.send(contents).await?;
Ok(())
}
pub async fn client_cleanup(uid: UID, server: &Arc<Mutex<Server>>, cache: CacheSocket) {
let mut server = server.lock().await;
server.clients.remove(&uid);
if let Ok(_) = cache.destruct() {
println!("Remove client with uid: {}", uid);
} else {
println!("Unable to remove client: {} from redis.", uid);
}
}
pub async fn process(
server: Arc<Mutex<Server>>,
stream: TcpStream,
mut cache: CacheSocket,
) -> Result<(), Box<dyn Error>> {
let uid = cache.get_value::<UID>("uid").unwrap_or_else(|| {
println!("Error retrieving UID from redis, reassigning UID");
let new_uid = gen_uid();
if let Err(e) = cache.set_value("uid", new_uid) {
println!(
"{}\nUnable to set key/value pair in redis uid: {}",
e, new_uid
);
};
new_uid
});
let mut client = Client::new(uid, server.clone(), stream).await?;
client.state = ConnStates::AwaitingName;
display_welcome(&mut client).await?;
let mut game_loop = true;
while game_loop {
if client.state == ConnStates::Quit {
println!("Client is disconnecting");
game_loop = false;
}
if let Some(response) = get(&mut client).await {
let new_state = client.state.clone().execute(&mut client, response).await?;
client.state = new_state;
let state = format!("({:?})", client.state);
send(&mut client, &state).await?;
} else {
println!("Client dropped connection. Removing...");
game_loop = false;
}
}
client_cleanup(uid, &server, cache).await;
Ok(())
}
pub async fn transfer(mut inbound: TcpStream, game_addr: String) -> Result<(), Box<dyn Error>> {
let mut outbound = TcpStream::connect(&game_addr).await?;
let inbound_addr = inbound.peer_addr()?;
let outbound_addr = outbound.peer_addr()?;
let mut buf = [0; 1024];
let n = inbound.peek(&mut buf).await?;
println!(
"Proxing {} to {}, msg: {}",
inbound_addr,
outbound_addr,
str::from_utf8(&buf[0..n])?
);
let (mut ri, mut wi) = inbound.split();
let (mut ro, mut wo) = outbound.split();
let client_to_server = copyover::copy(&mut ri, &mut wo, &inbound_addr, &outbound_addr);
let server_to_client = copyover::copy(&mut ro, &mut wi, &outbound_addr, &inbound_addr);
try_join(client_to_server, server_to_client).await?;
Ok(())
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
env::set_var("RUST_LOG", "info, warn, error,test");
pretty_env_logger::init();
let clients = Arc::new(Mutex::new(Server::new()));
println!(
"TCP Client listening on {} proxying to {}",
PROXY_ADDR, GAME_ADDR
);
let mut listener = TcpListener::bind(&PROXY_ADDR).await?;
while let Ok((stream, addr)) = listener.accept().await {
let server = Arc::clone(&clients);
println!("New user! on {}", addr);
let addr = stream.peer_addr()?;
let mut cache_socket = CacheSocket::new();
cache_socket.set_address(&addr).dump()?;
tokio::spawn(async move {
if let Err(e) = process(server, stream, cache_socket).await {
println!("An error occured; error={:?}", e);
}
});
}
Ok(())
}