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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
use std::collections::HashMap;
use tokio::sync::mpsc::channel;
use tokio::sync::Mutex;
use tokio::sync::mpsc::{Receiver, Sender};
use std::{net::SocketAddr, sync::Arc};
use tokio::net::UdpSocket;
use crate::{socket::*, raknet_log_debug, raknet_log_error};
use crate::packet::*;
use crate::utils::*;
use crate::error::{Result, RaknetError};
const SERVER_NAME : &str = "Rust Raknet Server";
const MAX_CONNECTION : u32 = 99999;
pub struct RaknetListener {
motd : String,
socket : Arc<UdpSocket>,
guid : u64,
listened : bool,
connection_receiver : Receiver<RaknetSocket>,
connection_sender : Sender<RaknetSocket>,
sessions : Arc<Mutex<HashMap<SocketAddr , (i64 ,Sender<Vec<u8>>)>>>
}
impl RaknetListener {
pub async fn bind(sockaddr : SocketAddr) -> Result<Self> {
let s = match UdpSocket::bind(sockaddr).await{
Ok(p) => p,
Err(_) => {
return Err(RaknetError::BindAdreesError);
},
};
let (connection_sender ,connection_receiver) = channel::<RaknetSocket>(10);
Ok(Self {
motd : String::new(),
socket : Arc::new(s),
guid : rand::random(),
listened : false,
connection_receiver,
connection_sender,
sessions : Arc::new(Mutex::new(HashMap::new())),
})
}
pub async fn from_std(s : std::net::UdpSocket) -> Result<Self>{
s.set_nonblocking(true).expect("set udpsocket nonblocking error");
let s = match UdpSocket::from_std(s){
Ok(p) => p,
Err(_) => {
return Err(RaknetError::SetRaknetRawSocketError);
},
};
let (connection_sender ,connection_receiver) = channel::<RaknetSocket>(10);
Ok(Self {
motd : String::new(),
socket : Arc::new(s),
guid : rand::random(),
listened : false,
connection_receiver,
connection_sender,
sessions : Arc::new(Mutex::new(HashMap::new())),
})
}
async fn start_session_collect(&self ,socket : &Arc<UdpSocket> , sessions : &Arc<Mutex<HashMap<SocketAddr , (i64 ,Sender<Vec<u8>>)>>> ,mut collect_receiver : Receiver<SocketAddr>) {
let sessions = sessions.clone();
let socket = socket.clone();
tokio::spawn(async move{
loop{
let addr = match collect_receiver.recv().await{
Some(p) => p,
None => {
raknet_log_debug!("session collecter closed");
break;
},
};
let mut sessions = sessions.lock().await;
if sessions.contains_key(&addr){
match socket.send_to(&[PacketID::Disconnect.to_u8()], addr).await{
Ok(_) => {},
Err(e) => {
raknet_log_error!("udp socket send_to error : {}" ,e);
},
};
sessions.remove(&addr);
raknet_log_debug!("collect socket : {}" , addr);
}
}
});
}
pub async fn listen(&mut self) {
if self.motd.is_empty(){
self.set_motd(SERVER_NAME , MAX_CONNECTION, "486" , "1.18.11", "Survival" , self.socket.local_addr().unwrap().port()).await;
}
let socket = self.socket.clone();
let guid = self.guid;
let sessions = self.sessions.clone();
let connection_sender = self.connection_sender.clone();
let motd = self.get_motd().await;
self.listened = true;
let (collect_sender ,collect_receiver) = channel::<SocketAddr>(10);
let collect_sender = Arc::new(Mutex::new(collect_sender));
self.start_session_collect(&socket ,&sessions , collect_receiver).await;
let local_addr = socket.local_addr().unwrap();
tokio::spawn(async move {
let mut buf= [0u8;2048];
raknet_log_debug!("start listen worker : {}" , local_addr );
loop{
let motd = motd.clone();
let (size , addr) = match socket.recv_from(&mut buf).await{
Ok(p) => p,
Err(e) => {
raknet_log_debug!("server recv_from error {}" , e);
break;
},
};
let cur_status = match PacketID::from(buf[0]){
Ok(p) => p,
Err(e) => {
raknet_log_debug!("parse packetid faild : {:?}" ,e );
continue;
},
};
match cur_status{
PacketID::UnconnectedPing1 => {
let _ping = match read_packet_ping(&buf[..size]).await{
Ok(p) => p,
Err(_) => continue,
};
let packet = crate::packet::PacketUnconnectedPong {
time: cur_timestamp_millis(),
guid,
magic: true,
motd
};
let pong = match write_packet_pong(&packet).await{
Ok(p) => p,
Err(_) => continue,
};
match socket.send_to(&pong, addr).await{
Ok(_) => {},
Err(e) => {
raknet_log_error!("udp socket send_to error : {}" ,e);
},
};
continue;
},
PacketID::UnconnectedPing2 => {
match read_packet_ping(&buf[..size]).await{
Ok(p) => p,
Err(_) => continue,
};
let packet = crate::packet::PacketUnconnectedPong {
time: cur_timestamp_millis(),
guid,
magic: true,
motd
};
let pong = match write_packet_pong(&packet).await{
Ok(p) => p,
Err(_) => continue,
};
match socket.send_to(&pong, addr).await{
Ok(_) => {},
Err(e) => {
raknet_log_error!("udp socket send_to error : {}" ,e);
},
};
continue;
},
PacketID::OpenConnectionRequest1 => {
let req = match read_packet_connection_open_request_1(&buf[..size]).await{
Ok(p) => p,
Err(_) => continue,
};
if req.protocol_version != RAKNET_PROTOCOL_VERSION{
let packet = crate::packet::IncompatibleProtocolVersion{
server_protocol: RAKNET_PROTOCOL_VERSION,
magic: true,
server_guid: guid,
};
let buf = write_packet_incompatible_protocol_version(&packet).await.unwrap();
match socket.send_to(&buf, addr).await{
Ok(_) => {},
Err(e) => {
raknet_log_error!("udp socket send_to error : {}" ,e);
},
};
continue;
}
let packet = crate::packet::OpenConnectionReply1 {
magic: true,
guid,
use_encryption: 0x00,
mtu_size: RAKNET_CLIENT_MTU,
};
let reply = match write_packet_connection_open_reply_1(&packet).await{
Ok(p) => p,
Err(_) => continue,
};
match socket.send_to(&reply, addr).await{
Ok(_) => {},
Err(e) => {
raknet_log_error!("udp socket send_to error : {}" ,e);
},
};
continue;
},
PacketID::OpenConnectionRequest2 => {
let req = match read_packet_connection_open_request_2(&buf[..size]).await{
Ok(p) => p,
Err(_) => continue,
};
let packet = crate::packet::OpenConnectionReply2 {
magic: true,
guid,
address: addr,
mtu: req.mtu,
encryption_enabled: 0x00,
};
let reply = match write_packet_connection_open_reply_2(&packet).await{
Ok(p) => p,
Err(_) => continue,
};
let mut sessions = sessions.lock().await;
if sessions.contains_key(&addr) {
let packet = write_packet_already_connected(&AlreadyConnected{
magic: true,
guid,
}).await.unwrap();
match socket.send_to(&packet, addr).await{
Ok(_) => {},
Err(e) => {
raknet_log_error!("udp socket send_to error : {}" ,e);
},
};
continue;
}
match socket.send_to(&reply, addr).await{
Ok(_) => {},
Err(e) => {
raknet_log_error!("udp socket send_to error : {}" ,e);
},
};
let (sender , receiver) = channel::<Vec<u8>>(10);
let s = RaknetSocket::from(&addr, &socket, receiver , req.mtu , collect_sender.clone());
raknet_log_debug!("accept connection : {}", addr);
sessions.insert(addr, (cur_timestamp_millis() ,sender));
let _ = connection_sender.send(s).await;
},
PacketID::Disconnect => {
let mut sessions = sessions.lock().await;
if sessions.contains_key(&addr){
sessions[&addr].1.send(buf[..size].to_vec()).await.unwrap();
sessions.remove(&addr);
}
}
_ => {
let mut sessions = sessions.lock().await;
if sessions.contains_key(&addr){
match sessions[&addr].1.send(buf[..size].to_vec()).await{
Ok(_) => {},
Err(_) => {
sessions.remove(&addr);
continue;
},
};
sessions.get_mut(&addr).unwrap().0 = cur_timestamp_millis();
}
},
}
}
raknet_log_debug!("listen worker closed");
});
}
pub async fn accept(&mut self) -> Result<RaknetSocket> {
if !self.listened{
Err(RaknetError::NotListen)
}else {
Ok(self.connection_receiver.recv().await.unwrap())
}
}
pub async fn set_motd(&mut self ,server_name : &str, max_connection : u32, mc_protocol_version : &str , mc_version : &str , game_type : &str ,port : u16 ) {
self.motd = format!("MCPE;{};{};{};0;{};{};Bedrock level;{};1;{};",server_name, mc_protocol_version , mc_version , max_connection , self.guid , game_type, port);
}
pub async fn get_motd(&self) -> String{
self.motd.clone()
}
pub fn local_addr(&self) -> Result<SocketAddr> {
Ok(self.socket.local_addr().unwrap())
}
}