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
use anyhow::Context;
use common::protocol::MessageOrderer;
use common::{ClientAction, ServerAction};
use rand::Rng;
use rustls::{Certificate, ClientConfig, ClientConnection, RootCertStore};
use std::io::{ErrorKind, Read};
use std::net::{TcpStream, UdpSocket};
use std::sync::Arc;
use std::time::{Duration, Instant};
const SERVER_DNS_NAME: &str = "localhost";
const SERVER_URL: &str = "127.0.0.1:7812";
const KEEPALIVE_INTERVAL: Duration =
Duration::from_millis(common::protocol::DISCONNECT_THRESHOLD.as_millis() as u64 / 2);
pub struct GameplaySocket {
socket: UdpSocket,
queue: MessageOrderer<ClientAction, ServerAction>,
peer_id: [u8; 16],
previous_received_datagram_time: Option<Instant>,
previous_sent_datagram_time: Option<Instant>,
pub debug_max_message_length: usize,
}
impl GameplaySocket {
pub fn new() -> anyhow::Result<GameplaySocket> {
let mut socket = None;
for _ in 0..100 {
let port = rand::thread_rng().gen_range(20_000..65000u16);
if let Ok(bound_socket) = UdpSocket::bind(("0.0.0.0", port)) {
socket = Some(bound_socket);
}
}
let socket = socket.ok_or_else(|| {
std::io::Error::new(ErrorKind::Other, "cannot bind the udp gameplay socket")
})?;
socket
.connect(SERVER_URL)
.context("Failed to connect? This is a bug.")?;
socket
.set_nonblocking(true)
.context("Could not make the UDP socket non-blocking.")?;
let LoginInfo {
peer_id,
encryption_key,
} = login()?;
Ok(GameplaySocket {
socket,
queue: MessageOrderer::new(encryption_key),
peer_id,
previous_received_datagram_time: None,
previous_sent_datagram_time: None,
debug_max_message_length: 0,
})
}
pub fn disconnected(&self) -> bool {
if let Some(t) = self.previous_received_datagram_time {
Instant::now() - t >= common::protocol::DISCONNECT_THRESHOLD
} else {
true
}
}
fn keepalive_needed(&self) -> bool {
if let Some(t) = self.previous_sent_datagram_time {
Instant::now() - t >= KEEPALIVE_INTERVAL
} else {
false
}
}
pub fn transport(&mut self) {
let mut buf = [0; 65536];
loop {
match self.socket.recv_from(&mut buf) {
Ok((n, peer_addr)) => {
self.debug_max_message_length = self.debug_max_message_length.max(n);
self.queue.transport_recv(peer_addr, &mut buf[..n]);
self.previous_received_datagram_time = Some(Instant::now());
}
Err(err) => {
if err.kind() != ErrorKind::TimedOut && err.kind() != ErrorKind::WouldBlock {
log::debug!("Error receiving UDP datagram: {err}");
}
break;
}
}
}
if self.keepalive_needed() {
self.queue.send(ClientAction::KeepAlive);
}
if let Some(mut datagram) = self.queue.transport_send(SERVER_URL) {
datagram.splice(0..0, self.peer_id);
if let Err(err) = self.socket.send_to(&datagram, SERVER_URL) {
log::debug!("Error sending UDP datagram: {err}");
} else {
self.previous_sent_datagram_time = Some(Instant::now());
}
}
}
pub fn send(&mut self, action: ClientAction) {
self.queue.send(action);
}
pub fn recv(&mut self) -> Option<ServerAction> {
self.queue.recv()
}
}
struct LoginInfo {
peer_id: [u8; 16],
encryption_key: [u8; 32],
}
fn login() -> anyhow::Result<LoginInfo> {
let mut tcp_stream =
TcpStream::connect(SERVER_URL).context("Could not connect to the login server.")?;
let mut root_store = RootCertStore::empty();
root_store.add(&Certificate(include_bytes!("../../certs/ca.crt").to_vec()))?;
let config = Arc::new(
ClientConfig::builder()
.with_safe_defaults()
.with_root_certificates(root_store)
.with_no_client_auth(),
);
let server_name = SERVER_DNS_NAME.try_into().unwrap();
let mut tls_conn = ClientConnection::new(config, server_name)
.context("Could not setup rustls ClientConnection for login server.")?;
tls_conn
.complete_io(&mut tcp_stream)
.context("Failed to establish TLS connection to the login server.")?;
let mut login_server_stream = rustls::Stream::new(&mut tls_conn, &mut tcp_stream);
let mut peer_id = [0u8; 16];
let mut encryption_key = [0u8; 32];
login_server_stream
.read_exact(&mut peer_id)
.context("Could not read peer id from login server.")?;
login_server_stream
.read_exact(&mut encryption_key)
.context("Could not read encryption key from login server.")?;
Ok(LoginInfo {
peer_id,
encryption_key,
})
}