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
|
use std::error::Error;
use tokio::net::{TcpListener, TcpStream};
use tokio::io::AsyncWriteExt;
use crate::server::auto::cmd::property::{
create_property_update_command,
create_property_request_command
};
use tokio_util::codec::{BytesCodec, Decoder};
use tokio_stream::StreamExt;
use bytes::BytesMut;
use crate::server::cmd::text::{create_text_command_with_action, create_text_command};
use std::str::from_utf8;
use crate::server::cmd::buddy_list::create_buddy_list_notify_command;
use crate::server::auto::cmd::room::create_room_id_redirect_command;
use std::sync::Arc;
use tokio::sync::Mutex;
use crate::server::shared::Shared;
use crate::server::peer::Peer;
use std::net::SocketAddr;
use crate::server::auto::cmd::session::parse_session_initialization_command;
pub struct AutoServer;
impl AutoServer {
pub async fn new(addr: &'static str) -> Result<(), Box<dyn Error>> {
let listener = TcpListener::bind(addr).await?;
debug!("AutoServer now listening on {}", listener.local_addr().unwrap());
let state = Arc::new(Mutex::new(Shared::new()));
let mut counter = 0;
loop {
let (stream, address) = listener.accept().await?;
counter += 1;
let state = Arc::clone(&state);
tokio::spawn(async move {
if let Err(e) = AutoServer::handle(
state,
stream,
address,
counter
).await {
error!("an error occurred: {}", e);
}
});
}
}
pub async fn handle(
state: Arc<Mutex<Shared>>,
stream: TcpStream,
address: SocketAddr,
count: usize,
) -> Result<(), Box<dyn Error>> {
let bytes = BytesCodec::new().framed(stream);
let mut peer = Peer::new(state.clone(), bytes, count.to_string()).await?;
debug!("registered peer with address '{}' as '{}'", address, count);
let mut room_ids: Vec<String> = Vec::new();
let mut username: String = String::new();
// while let Some(msg) = peer.bytes.next().await {
// match msg {
// Ok(bytes) => match bytes.get(2).unwrap() {
// 10 => { // PROPREQ
// debug!("received property request command from client");
// peer.bytes.get_mut()
// .write_all(&create_property_update_command()).await?;
//
// debug!("sent property update command to client");
// }
// 6 => { // SESSINIT
// username = parse_session_initialization_command(bytes).username;
// debug!(
// "received session initialization command from client: {}",
// username
// );
// peer.bytes.get_mut()
// .write_all(&create_property_request_command()).await?;
// debug!("sent session initialization command to client");
// }
// 15 => { // PROPSET
// debug!("received property set command from client");
// peer.bytes.get_mut()
// .write_all(&create_text_command_with_action(
// "WORLDSMASTER", &std::env::var("WORLDSMASTER_GREETING")?
// )).await?;
// debug!("sent worldsmaster greeting to client");
// }
// 29 => { // BUDDYLISTUPDATE
// let received_buddy = from_utf8(
// bytes.get(4..bytes.get(0).unwrap().to_owned() as usize - 1).unwrap()
// ).unwrap();
// debug!(
// "received buddy list update command from client: {}",
// received_buddy
// );
// peer.bytes.get_mut()
// .write_all(&create_buddy_list_notify_command(received_buddy))
// .await?;
// debug!("sent buddy list notify command to client");
// }
// 20 => { // ROOMIDRQ
// let room_name = from_utf8(
// bytes.get(4..bytes.get(0).unwrap().to_owned() as usize).unwrap()
// ).unwrap();
// debug!("received room id request command from client: {}", room_name);
// let room_id;
// if !room_ids.contains(&room_name.to_string()) {
// room_ids.push(room_name.to_string());
// room_id = room_ids.iter()
// .position(|i| i == &room_name.to_string())
// .unwrap();
// trace!("inserted room '{}' as '{}'", room_name, room_id);
// } else {
// let position = room_ids.iter()
// .position(|i| i == &room_name.to_string())
// .unwrap();
// trace!("found room '{}' as '{}'", room_name, position);
// room_id = position;
// }
// trace!("room name: {}, room id: {}", room_name, room_id);
// trace!("{:?}", room_ids);
// peer.bytes.get_mut()
// .write_all(&create_room_id_redirect_command(room_name, room_id))
// .await?;
// debug!("sent redirect id command to client");
// }
// 14 => {
// let text = from_utf8(
// bytes.get(6..bytes.get(0).unwrap().to_owned() as usize).unwrap()
// ).unwrap();
// debug!("received text command from client: {}", text);
// let mut state = state.lock().await;
// state.broadcast(&create_text_command(&username, text)).await;
// debug!("broadcasted text command from client");
// }
// 7 => { // SESSEXIT
// debug!("received session exit command from client")
// }
// _ => (),
// }
// Err(err) => error!("stream closed with error: {:?}", err),
// }
// }
loop {
tokio::select! {
Some(msg) = peer.rx.recv() => {
// debug!("received bytes from peer: {:?}", &msg);
peer.bytes.get_mut().write_all(&msg).await?;
}
result = peer.bytes.next() => match result {
Some(Ok(msg)) => {
let msg: BytesMut = msg;
match msg.get(2).unwrap() {
10 => { // PROPREQ
debug!("received property request command from client");
peer.bytes.get_mut()
.write_all(&create_property_update_command()).await?;
debug!("sent property update command to client");
}
6 => { // SESSINIT
username = parse_session_initialization_command(msg).username;
debug!(
"received session initialization command from client: {}",
username
);
peer.bytes.get_mut()
.write_all(&create_property_request_command()).await?;
debug!("sent session initialization command to client");
}
15 => { // PROPSET
debug!("received property set command from client");
peer.bytes.get_mut()
.write_all(&create_text_command_with_action(
"WORLDSMASTER", &std::env::var("WORLDSMASTER_GREETING")?
)).await?;
debug!("sent worldsmaster greeting to client");
}
29 => { // BUDDYLISTUPDATE
let received_buddy = from_utf8(
msg.get(4..msg.get(0).unwrap().to_owned() as usize - 1).unwrap()
).unwrap();
debug!(
"received buddy list update command from client: {}",
received_buddy
);
peer.bytes.get_mut()
.write_all(&create_buddy_list_notify_command(received_buddy))
.await?;
debug!("sent buddy list notify command to client");
}
20 => { // ROOMIDRQ
let room_name = from_utf8(
msg.get(4..msg.get(0).unwrap().to_owned() as usize).unwrap()
).unwrap();
debug!("received room id request command from client: {}", room_name);
let room_id;
if !room_ids.contains(&room_name.to_string()) {
room_ids.push(room_name.to_string());
room_id = room_ids.iter()
.position(|i| i == &room_name.to_string())
.unwrap();
trace!("inserted room '{}' as '{}'", room_name, room_id);
} else {
let position = room_ids.iter()
.position(|i| i == &room_name.to_string())
.unwrap();
trace!("found room '{}' as '{}'", room_name, position);
room_id = position;
}
trace!("room name: {}, room id: {}", room_name, room_id);
trace!("{:?}", room_ids);
peer.bytes.get_mut()
.write_all(&create_room_id_redirect_command(room_name, room_id))
.await?;
debug!("sent redirect id command to client");
}
14 => {
let text = from_utf8(
msg.get(6..msg.get(0).unwrap().to_owned() as usize).unwrap()
).unwrap();
debug!("received text command from client: {}", text);
let mut state = state.lock().await;
state.broadcast(&create_text_command(&username, text)).await;
debug!("broadcasted text command from client");
}
7 => { // SESSEXIT
debug!("received session exit command from client")
}
_ => (),
}
}
Some(Err(e)) => {
error!("error while processing messages: {}", e); break;
}
None => break,
}
}
}
// De-register client
{
state.lock().await.peers.remove(&count.to_string());
debug!("removed peer: {}", count)
}
Ok(())
}
}
|