pub struct Connection<R: ProtocolPacket, W: ProtocolPacket> {
pub reader: ReadConnection<R>,
pub writer: WriteConnection<W>,
}Expand description
A connection that can read and write packets.
§Examples
Join an offline-mode server and go through the handshake.
use azalea_protocol::{
connect::Connection,
packets::{
self, ClientIntention, PROTOCOL_VERSION,
handshake::ServerboundIntention,
login::{ClientboundLoginPacket, ServerboundHello, ServerboundKey},
},
resolve,
};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let resolved_address = resolve::resolve_address(&"localhost".try_into().unwrap()).await?;
let mut conn = Connection::new(&resolved_address).await?;
// handshake
conn.write(
Default::default(),
ServerboundIntention {
protocol_version: PROTOCOL_VERSION,
hostname: resolved_address.ip().to_string(),
port: resolved_address.port(),
intention: ClientIntention::Login,
},
)
.await?;
let mut conn = conn.login();
// login
conn.write(
Default::default(),
ServerboundHello {
name: "bot".to_owned(),
profile_id: uuid::Uuid::nil(),
},
)
.await?;
let (conn, game_profile) = loop {
let packet = conn.read(Default::default()).await?;
match packet {
ClientboundLoginPacket::Hello(p) => {
let e = azalea_crypto::encrypt(&p.public_key, &p.challenge).unwrap();
conn.write(
Default::default(),
ServerboundKey {
key_bytes: e.encrypted_public_key,
encrypted_challenge: e.encrypted_challenge,
},
)
.await?;
conn.set_encryption_key(e.secret_key);
}
ClientboundLoginPacket::LoginCompression(p) => {
conn.set_compression_threshold(p.compression_threshold);
}
ClientboundLoginPacket::LoginFinished(p) => {
break (conn.config(), p.game_profile);
}
ClientboundLoginPacket::LoginDisconnect(p) => {
eprintln!("login disconnect: {}", p.reason);
return Err("login disconnect".into());
}
ClientboundLoginPacket::CustomQuery(p) => {}
ClientboundLoginPacket::CookieRequest(p) => {
conn.write(
Default::default(),
packets::login::ServerboundCookieResponse {
key: p.key,
payload: None,
},
)
.await?;
}
}
};
Ok(())
}Fields§
§reader: ReadConnection<R>§writer: WriteConnection<W>Implementations§
Source§impl<R, W> Connection<R, W>
impl<R, W> Connection<R, W>
Sourcepub async fn read(&mut self, ctx: Ctx<'_>) -> Result<R, Box<ReadPacketError>>
pub async fn read(&mut self, ctx: Ctx<'_>) -> Result<R, Box<ReadPacketError>>
Read a packet from the other side of the connection.
Examples found in repository?
100async fn handle_connection(stream: TcpStream) -> eyre::Result<()> {
101 stream.set_nodelay(true)?;
102 let ip = stream.peer_addr()?;
103 let mut conn: Connection<ServerboundHandshakePacket, ClientboundHandshakePacket> =
104 Connection::wrap(stream);
105
106 // The first packet sent from a client is the intent packet.
107 // This specifies whether the client is pinging
108 // the server or is going to join the game.
109 let intent = match conn.read(Default::default()).await {
110 Ok(packet) => match packet {
111 ServerboundHandshakePacket::Intention(packet) => {
112 info!(
113 "New connection from {}, hostname {:?}:{}, version {}, {:?}",
114 ip.ip(),
115 packet.hostname,
116 packet.port,
117 packet.protocol_version,
118 packet.intention
119 );
120 packet
121 }
122 },
123 Err(e) => {
124 let e = e.into();
125 warn!("Error during intent: {e}");
126 return Err(e);
127 }
128 };
129
130 match intent.intention {
131 // If the client is pinging the proxy, reply with the information below.
132 ClientIntention::Status => {
133 let mut conn = conn.status();
134 loop {
135 match conn.read(Default::default()).await {
136 Ok(p) => match p {
137 ServerboundStatusPacket::StatusRequest(_) => {
138 conn.write(
139 Default::default(),
140 ClientboundStatusResponse {
141 description: PROXY_DESC.into(),
142 favicon: PROXY_FAVICON.clone(),
143 players: PROXY_PLAYERS.clone(),
144 version: PROXY_VERSION.clone(),
145 enforces_secure_chat: PROXY_SECURE_CHAT,
146 contact: None,
147 },
148 )
149 .await?;
150 }
151 ServerboundStatusPacket::PingRequest(p) => {
152 conn.write(
153 Default::default(),
154 ClientboundPongResponse { time: p.time },
155 )
156 .await?;
157 break;
158 }
159 },
160 Err(e) => match *e {
161 ReadPacketError::ConnectionClosed => {
162 break;
163 }
164 e => {
165 warn!("Error during status: {e}");
166 return Err(e.into());
167 }
168 },
169 }
170 }
171 }
172 // If the client intends to join the proxy, wait for them to send the
173 // `Hello` packet to log their username and uuid, then start proxying
174 // their connection.
175 ClientIntention::Login => {
176 let mut conn = conn.login();
177 loop {
178 match conn.read(Default::default()).await {
179 Ok(p) => {
180 if let ServerboundLoginPacket::Hello(hello) = p {
181 info!(
182 "Player \'{}\' from {} logging in with uuid: {}",
183 hello.name,
184 ip.ip(),
185 hello.profile_id.to_string()
186 );
187
188 tokio::spawn(proxy_conn(conn).map(|r| {
189 if let Err(e) = r {
190 error!("Failed to proxy: {e}");
191 }
192 }));
193
194 break;
195 }
196 }
197 Err(e) => match *e {
198 ReadPacketError::ConnectionClosed => {
199 break;
200 }
201 e => {
202 warn!("Error during login: {e}");
203 return Err(e.into());
204 }
205 },
206 }
207 }
208 }
209 ClientIntention::Transfer => {
210 warn!("Client attempted to join via transfer")
211 }
212 }
213
214 Ok(())
215}
216
217async fn proxy_conn(
218 mut client_conn: Connection<ServerboundLoginPacket, ClientboundLoginPacket>,
219) -> Result<(), Box<dyn Error>> {
220 // resolve TARGET_ADDR
221 let parsed_target_addr = ServerAddr::from_str(TARGET_ADDR).unwrap();
222 let resolved_target_addr = resolve_address(&parsed_target_addr).await?;
223
224 let mut server_conn = Connection::new(&resolved_target_addr).await?;
225
226 let account = if ACCOUNT.contains('@') {
227 Account::microsoft(ACCOUNT).await?
228 } else {
229 Account::offline(ACCOUNT)
230 };
231 println!("got account: {:?}", account);
232
233 server_conn
234 .write(
235 Default::default(),
236 ServerboundIntention {
237 protocol_version: PROTOCOL_VERSION,
238 hostname: parsed_target_addr.host,
239 port: parsed_target_addr.port,
240 intention: ClientIntention::Login,
241 },
242 )
243 .await?;
244 let mut server_conn = server_conn.login();
245
246 // login
247 server_conn
248 .write(
249 Default::default(),
250 ServerboundHello {
251 name: account.username().to_owned(),
252 profile_id: account.uuid(),
253 },
254 )
255 .await?;
256
257 let (server_conn, login_finished) = loop {
258 let packet = server_conn.read(Default::default()).await?;
259
260 println!("got packet: {:?}", packet);
261
262 match packet {
263 ClientboundLoginPacket::Hello(p) => {
264 debug!("Got encryption request");
265 let e = azalea_crypto::encrypt(&p.public_key, &p.challenge).unwrap();
266
267 if let Some(access_token) = account.access_token() {
268 // keep track of the number of times we tried
269 // authenticating so we can give up after too many
270 let mut attempts: usize = 1;
271
272 while let Err(e) = {
273 server_conn
274 .authenticate(&access_token, &account.uuid(), e.secret_key, &p, None)
275 .await
276 } {
277 if attempts >= 2 {
278 // if this is the second attempt and we failed
279 // both times, give up
280 return Err(e.into());
281 }
282 if matches!(
283 e,
284 ClientSessionServerError::InvalidSession
285 | ClientSessionServerError::ForbiddenOperation
286 ) {
287 // uh oh, we got an invalid session and have
288 // to reauthenticate now
289 account.refresh().await?;
290 } else {
291 return Err(e.into());
292 }
293 attempts += 1;
294 }
295 }
296
297 server_conn
298 .write(
299 Default::default(),
300 ServerboundKey {
301 key_bytes: e.encrypted_public_key,
302 encrypted_challenge: e.encrypted_challenge,
303 },
304 )
305 .await?;
306
307 server_conn.set_encryption_key(e.secret_key);
308 }
309 ClientboundLoginPacket::LoginCompression(p) => {
310 debug!("Got compression request {:?}", p.compression_threshold);
311 server_conn.set_compression_threshold(p.compression_threshold);
312 }
313 ClientboundLoginPacket::LoginFinished(p) => {
314 debug!(
315 "Got profile {:?}. handshake is finished and we're now switching to the configuration state",
316 p.game_profile
317 );
318 // server_conn.write(Default::default(),
319 // ServerboundLoginAcknowledged {}).await?;
320 break (server_conn.config(), p);
321 }
322 ClientboundLoginPacket::LoginDisconnect(p) => {
323 error!("Got disconnect {p:?}");
324 return Err("Disconnected".into());
325 }
326 ClientboundLoginPacket::CustomQuery(p) => {
327 debug!("Got custom query {:?}", p);
328 // replying to custom query is done in
329 // packet_handling::login::process_packet_events
330 }
331 ClientboundLoginPacket::CookieRequest(p) => {
332 debug!("Got cookie request {:?}", p);
333
334 server_conn
335 .write(
336 Default::default(),
337 packets::login::ServerboundCookieResponse {
338 key: p.key,
339 // cookies aren't implemented
340 payload: None,
341 },
342 )
343 .await?;
344 }
345 }
346 };
347
348 // give the client the login_finished
349 println!("got the login_finished: {:?}", login_finished);
350 client_conn
351 .write(Default::default(), login_finished)
352 .await?;
353 let client_conn = client_conn.config();
354
355 info!("started direct bridging");
356
357 // bridge packets
358 let listen_raw_reader = client_conn.reader.raw;
359 let listen_raw_writer = client_conn.writer.raw;
360
361 let target_raw_reader = server_conn.reader.raw;
362 let target_raw_writer = server_conn.writer.raw;
363
364 let packet_logs_txt = Arc::new(tokio::sync::Mutex::new(
365 File::create("combined.txt").await.unwrap(),
366 ));
367
368 let packet_logs_txt_clone = packet_logs_txt.clone();
369 let copy_listen_to_target = tokio::spawn(async move {
370 let mut listen_raw_reader = listen_raw_reader;
371 let mut target_raw_writer = target_raw_writer;
372
373 let packet_logs_txt = packet_logs_txt_clone;
374
375 let mut serverbound_parsed_txt = File::create("serverbound.txt").await.unwrap();
376
377 loop {
378 let packet = match listen_raw_reader.read().await {
379 Ok(p) => p,
380 Err(e) => {
381 error!("Error reading packet from listen: {e}");
382 return;
383 }
384 };
385
386 // decode as a game packet
387 let decoded_packet = azalea_protocol::read::deserialize_packet::<ServerboundGamePacket>(
388 Default::default(),
389 &mut Cursor::new(&packet),
390 );
391
392 if let Ok(decoded_packet) = decoded_packet {
393 let timestamp = chrono::Utc::now();
394 let _ = serverbound_parsed_txt
395 .write_all(format!("{timestamp} {:?}\n", decoded_packet).as_bytes())
396 .await;
397 let _ = packet_logs_txt
398 .lock()
399 .await
400 .write_all(format!("{timestamp} <- {:?}\n", decoded_packet).as_bytes())
401 .await;
402 }
403
404 match target_raw_writer.write(Default::default(), &packet).await {
405 Ok(_) => {}
406 Err(e) => {
407 error!("Error writing packet to target: {e}");
408 return;
409 }
410 }
411 }
412 });
413
414 // write to clientbound.txt in a separate task so it doesn't block receiving
415 // packets
416 let (clientbound_tx, mut clientbound_rx) = tokio::sync::mpsc::unbounded_channel::<Box<[u8]>>();
417 let copy_clientbound_to_file = tokio::spawn(async move {
418 let mut clientbound_parsed_txt = File::create("clientbound.txt").await.unwrap();
419
420 loop {
421 let Some(packet) = clientbound_rx.recv().await else {
422 return;
423 };
424
425 // decode as a game packet
426 let decoded_packet = azalea_protocol::read::deserialize_packet::<ClientboundGamePacket>(
427 Default::default(),
428 &mut Cursor::new(&packet),
429 );
430
431 if let Ok(decoded_packet) = decoded_packet {
432 let timestamp = chrono::Utc::now();
433 let _ = clientbound_parsed_txt
434 .write_all(format!("{timestamp} {decoded_packet:?}\n").as_bytes())
435 .await;
436 let _ = packet_logs_txt
437 .lock()
438 .await
439 .write_all(format!("{timestamp} -> {decoded_packet:?}\n").as_bytes())
440 .await;
441 }
442 }
443 });
444
445 let copy_remote_to_local = tokio::spawn(async move {
446 let mut target_raw_reader = target_raw_reader;
447 let mut listen_raw_writer = listen_raw_writer;
448
449 loop {
450 let packet = match target_raw_reader.read().await {
451 Ok(p) => p,
452 Err(e) => {
453 error!("Error reading packet from target: {e}");
454 return;
455 }
456 };
457
458 clientbound_tx.send(packet.clone()).unwrap();
459
460 match listen_raw_writer.write(Default::default(), &packet).await {
461 Ok(_) => {}
462 Err(e) => {
463 error!("Error writing packet to listen: {e}");
464 return;
465 }
466 }
467 }
468 });
469
470 tokio::try_join!(
471 copy_listen_to_target,
472 copy_remote_to_local,
473 copy_clientbound_to_file
474 )?;
475
476 Ok(())
477}More examples
69async fn handle_connection(stream: TcpStream) -> eyre::Result<()> {
70 stream.set_nodelay(true)?;
71 let ip = stream.peer_addr()?;
72 let mut conn: Connection<ServerboundHandshakePacket, ClientboundHandshakePacket> =
73 Connection::wrap(stream);
74
75 // The first packet sent from a client is the intent packet.
76 // This specifies whether the client is pinging
77 // the server or is going to join the game.
78 let intent = match conn.read(Default::default()).await {
79 Ok(packet) => match packet {
80 ServerboundHandshakePacket::Intention(packet) => {
81 info!(
82 "New connection from {}, hostname {:?}:{}, version {}, {:?}",
83 ip.ip(),
84 packet.hostname,
85 packet.port,
86 packet.protocol_version,
87 packet.intention
88 );
89 packet
90 }
91 },
92 Err(e) => {
93 let e = e.into();
94 warn!("Error during intent: {e}");
95 return Err(e);
96 }
97 };
98
99 match intent.intention {
100 // If the client is pinging the proxy,
101 // reply with the information below.
102 ClientIntention::Status => {
103 let mut conn = conn.status();
104 loop {
105 match conn.read(Default::default()).await {
106 Ok(p) => match p {
107 ServerboundStatusPacket::StatusRequest(_) => {
108 conn.write(
109 Default::default(),
110 ClientboundStatusResponse {
111 description: PROXY_DESC.into(),
112 favicon: PROXY_FAVICON.clone(),
113 players: PROXY_PLAYERS.clone(),
114 version: PROXY_VERSION.clone(),
115 enforces_secure_chat: PROXY_SECURE_CHAT,
116 contact: None,
117 },
118 )
119 .await?;
120 }
121 ServerboundStatusPacket::PingRequest(p) => {
122 conn.write(
123 Default::default(),
124 ClientboundPongResponse { time: p.time },
125 )
126 .await?;
127 break;
128 }
129 },
130 Err(e) => match *e {
131 ReadPacketError::ConnectionClosed => {
132 break;
133 }
134 e => {
135 warn!("Error during status: {e}");
136 return Err(e.into());
137 }
138 },
139 }
140 }
141 }
142 // If the client intends to join the proxy,
143 // wait for them to send the `Hello` packet to
144 // log their username and uuid, then forward the
145 // connection along to the proxy target.
146 ClientIntention::Login => {
147 let mut conn = conn.login();
148 loop {
149 match conn.read(Default::default()).await {
150 Ok(p) => {
151 if let ServerboundLoginPacket::Hello(hello) = p {
152 info!(
153 "Player \'{0}\' from {1} logging in with uuid: {2}",
154 hello.name,
155 ip.ip(),
156 hello.profile_id.to_string()
157 );
158
159 tokio::spawn(transfer(conn.unwrap()?, intent, hello).map(|r| {
160 if let Err(e) = r {
161 error!("Failed to proxy: {e}");
162 }
163 }));
164
165 break;
166 }
167 }
168 Err(e) => match *e {
169 ReadPacketError::ConnectionClosed => {
170 break;
171 }
172 e => {
173 warn!("Error during login: {e}");
174 return Err(e.into());
175 }
176 },
177 }
178 }
179 }
180 ClientIntention::Transfer => {
181 warn!("Client attempted to join via transfer")
182 }
183 }
184
185 Ok(())
186}Sourcepub fn try_read(
&mut self,
ctx: Ctx<'_>,
) -> Result<Option<R>, Box<ReadPacketError>>
pub fn try_read( &mut self, ctx: Ctx<'_>, ) -> Result<Option<R>, Box<ReadPacketError>>
Try to read a packet from the other side of the connection, or return Ok(None) if there’s no packet to read.
Sourcepub async fn write(
&mut self,
ctx: Ctx<'_>,
packet: impl Packet<W>,
) -> Result<()>
pub async fn write( &mut self, ctx: Ctx<'_>, packet: impl Packet<W>, ) -> Result<()>
Write a packet to the other side of the connection.
Examples found in repository?
100async fn handle_connection(stream: TcpStream) -> eyre::Result<()> {
101 stream.set_nodelay(true)?;
102 let ip = stream.peer_addr()?;
103 let mut conn: Connection<ServerboundHandshakePacket, ClientboundHandshakePacket> =
104 Connection::wrap(stream);
105
106 // The first packet sent from a client is the intent packet.
107 // This specifies whether the client is pinging
108 // the server or is going to join the game.
109 let intent = match conn.read(Default::default()).await {
110 Ok(packet) => match packet {
111 ServerboundHandshakePacket::Intention(packet) => {
112 info!(
113 "New connection from {}, hostname {:?}:{}, version {}, {:?}",
114 ip.ip(),
115 packet.hostname,
116 packet.port,
117 packet.protocol_version,
118 packet.intention
119 );
120 packet
121 }
122 },
123 Err(e) => {
124 let e = e.into();
125 warn!("Error during intent: {e}");
126 return Err(e);
127 }
128 };
129
130 match intent.intention {
131 // If the client is pinging the proxy, reply with the information below.
132 ClientIntention::Status => {
133 let mut conn = conn.status();
134 loop {
135 match conn.read(Default::default()).await {
136 Ok(p) => match p {
137 ServerboundStatusPacket::StatusRequest(_) => {
138 conn.write(
139 Default::default(),
140 ClientboundStatusResponse {
141 description: PROXY_DESC.into(),
142 favicon: PROXY_FAVICON.clone(),
143 players: PROXY_PLAYERS.clone(),
144 version: PROXY_VERSION.clone(),
145 enforces_secure_chat: PROXY_SECURE_CHAT,
146 contact: None,
147 },
148 )
149 .await?;
150 }
151 ServerboundStatusPacket::PingRequest(p) => {
152 conn.write(
153 Default::default(),
154 ClientboundPongResponse { time: p.time },
155 )
156 .await?;
157 break;
158 }
159 },
160 Err(e) => match *e {
161 ReadPacketError::ConnectionClosed => {
162 break;
163 }
164 e => {
165 warn!("Error during status: {e}");
166 return Err(e.into());
167 }
168 },
169 }
170 }
171 }
172 // If the client intends to join the proxy, wait for them to send the
173 // `Hello` packet to log their username and uuid, then start proxying
174 // their connection.
175 ClientIntention::Login => {
176 let mut conn = conn.login();
177 loop {
178 match conn.read(Default::default()).await {
179 Ok(p) => {
180 if let ServerboundLoginPacket::Hello(hello) = p {
181 info!(
182 "Player \'{}\' from {} logging in with uuid: {}",
183 hello.name,
184 ip.ip(),
185 hello.profile_id.to_string()
186 );
187
188 tokio::spawn(proxy_conn(conn).map(|r| {
189 if let Err(e) = r {
190 error!("Failed to proxy: {e}");
191 }
192 }));
193
194 break;
195 }
196 }
197 Err(e) => match *e {
198 ReadPacketError::ConnectionClosed => {
199 break;
200 }
201 e => {
202 warn!("Error during login: {e}");
203 return Err(e.into());
204 }
205 },
206 }
207 }
208 }
209 ClientIntention::Transfer => {
210 warn!("Client attempted to join via transfer")
211 }
212 }
213
214 Ok(())
215}
216
217async fn proxy_conn(
218 mut client_conn: Connection<ServerboundLoginPacket, ClientboundLoginPacket>,
219) -> Result<(), Box<dyn Error>> {
220 // resolve TARGET_ADDR
221 let parsed_target_addr = ServerAddr::from_str(TARGET_ADDR).unwrap();
222 let resolved_target_addr = resolve_address(&parsed_target_addr).await?;
223
224 let mut server_conn = Connection::new(&resolved_target_addr).await?;
225
226 let account = if ACCOUNT.contains('@') {
227 Account::microsoft(ACCOUNT).await?
228 } else {
229 Account::offline(ACCOUNT)
230 };
231 println!("got account: {:?}", account);
232
233 server_conn
234 .write(
235 Default::default(),
236 ServerboundIntention {
237 protocol_version: PROTOCOL_VERSION,
238 hostname: parsed_target_addr.host,
239 port: parsed_target_addr.port,
240 intention: ClientIntention::Login,
241 },
242 )
243 .await?;
244 let mut server_conn = server_conn.login();
245
246 // login
247 server_conn
248 .write(
249 Default::default(),
250 ServerboundHello {
251 name: account.username().to_owned(),
252 profile_id: account.uuid(),
253 },
254 )
255 .await?;
256
257 let (server_conn, login_finished) = loop {
258 let packet = server_conn.read(Default::default()).await?;
259
260 println!("got packet: {:?}", packet);
261
262 match packet {
263 ClientboundLoginPacket::Hello(p) => {
264 debug!("Got encryption request");
265 let e = azalea_crypto::encrypt(&p.public_key, &p.challenge).unwrap();
266
267 if let Some(access_token) = account.access_token() {
268 // keep track of the number of times we tried
269 // authenticating so we can give up after too many
270 let mut attempts: usize = 1;
271
272 while let Err(e) = {
273 server_conn
274 .authenticate(&access_token, &account.uuid(), e.secret_key, &p, None)
275 .await
276 } {
277 if attempts >= 2 {
278 // if this is the second attempt and we failed
279 // both times, give up
280 return Err(e.into());
281 }
282 if matches!(
283 e,
284 ClientSessionServerError::InvalidSession
285 | ClientSessionServerError::ForbiddenOperation
286 ) {
287 // uh oh, we got an invalid session and have
288 // to reauthenticate now
289 account.refresh().await?;
290 } else {
291 return Err(e.into());
292 }
293 attempts += 1;
294 }
295 }
296
297 server_conn
298 .write(
299 Default::default(),
300 ServerboundKey {
301 key_bytes: e.encrypted_public_key,
302 encrypted_challenge: e.encrypted_challenge,
303 },
304 )
305 .await?;
306
307 server_conn.set_encryption_key(e.secret_key);
308 }
309 ClientboundLoginPacket::LoginCompression(p) => {
310 debug!("Got compression request {:?}", p.compression_threshold);
311 server_conn.set_compression_threshold(p.compression_threshold);
312 }
313 ClientboundLoginPacket::LoginFinished(p) => {
314 debug!(
315 "Got profile {:?}. handshake is finished and we're now switching to the configuration state",
316 p.game_profile
317 );
318 // server_conn.write(Default::default(),
319 // ServerboundLoginAcknowledged {}).await?;
320 break (server_conn.config(), p);
321 }
322 ClientboundLoginPacket::LoginDisconnect(p) => {
323 error!("Got disconnect {p:?}");
324 return Err("Disconnected".into());
325 }
326 ClientboundLoginPacket::CustomQuery(p) => {
327 debug!("Got custom query {:?}", p);
328 // replying to custom query is done in
329 // packet_handling::login::process_packet_events
330 }
331 ClientboundLoginPacket::CookieRequest(p) => {
332 debug!("Got cookie request {:?}", p);
333
334 server_conn
335 .write(
336 Default::default(),
337 packets::login::ServerboundCookieResponse {
338 key: p.key,
339 // cookies aren't implemented
340 payload: None,
341 },
342 )
343 .await?;
344 }
345 }
346 };
347
348 // give the client the login_finished
349 println!("got the login_finished: {:?}", login_finished);
350 client_conn
351 .write(Default::default(), login_finished)
352 .await?;
353 let client_conn = client_conn.config();
354
355 info!("started direct bridging");
356
357 // bridge packets
358 let listen_raw_reader = client_conn.reader.raw;
359 let listen_raw_writer = client_conn.writer.raw;
360
361 let target_raw_reader = server_conn.reader.raw;
362 let target_raw_writer = server_conn.writer.raw;
363
364 let packet_logs_txt = Arc::new(tokio::sync::Mutex::new(
365 File::create("combined.txt").await.unwrap(),
366 ));
367
368 let packet_logs_txt_clone = packet_logs_txt.clone();
369 let copy_listen_to_target = tokio::spawn(async move {
370 let mut listen_raw_reader = listen_raw_reader;
371 let mut target_raw_writer = target_raw_writer;
372
373 let packet_logs_txt = packet_logs_txt_clone;
374
375 let mut serverbound_parsed_txt = File::create("serverbound.txt").await.unwrap();
376
377 loop {
378 let packet = match listen_raw_reader.read().await {
379 Ok(p) => p,
380 Err(e) => {
381 error!("Error reading packet from listen: {e}");
382 return;
383 }
384 };
385
386 // decode as a game packet
387 let decoded_packet = azalea_protocol::read::deserialize_packet::<ServerboundGamePacket>(
388 Default::default(),
389 &mut Cursor::new(&packet),
390 );
391
392 if let Ok(decoded_packet) = decoded_packet {
393 let timestamp = chrono::Utc::now();
394 let _ = serverbound_parsed_txt
395 .write_all(format!("{timestamp} {:?}\n", decoded_packet).as_bytes())
396 .await;
397 let _ = packet_logs_txt
398 .lock()
399 .await
400 .write_all(format!("{timestamp} <- {:?}\n", decoded_packet).as_bytes())
401 .await;
402 }
403
404 match target_raw_writer.write(Default::default(), &packet).await {
405 Ok(_) => {}
406 Err(e) => {
407 error!("Error writing packet to target: {e}");
408 return;
409 }
410 }
411 }
412 });
413
414 // write to clientbound.txt in a separate task so it doesn't block receiving
415 // packets
416 let (clientbound_tx, mut clientbound_rx) = tokio::sync::mpsc::unbounded_channel::<Box<[u8]>>();
417 let copy_clientbound_to_file = tokio::spawn(async move {
418 let mut clientbound_parsed_txt = File::create("clientbound.txt").await.unwrap();
419
420 loop {
421 let Some(packet) = clientbound_rx.recv().await else {
422 return;
423 };
424
425 // decode as a game packet
426 let decoded_packet = azalea_protocol::read::deserialize_packet::<ClientboundGamePacket>(
427 Default::default(),
428 &mut Cursor::new(&packet),
429 );
430
431 if let Ok(decoded_packet) = decoded_packet {
432 let timestamp = chrono::Utc::now();
433 let _ = clientbound_parsed_txt
434 .write_all(format!("{timestamp} {decoded_packet:?}\n").as_bytes())
435 .await;
436 let _ = packet_logs_txt
437 .lock()
438 .await
439 .write_all(format!("{timestamp} -> {decoded_packet:?}\n").as_bytes())
440 .await;
441 }
442 }
443 });
444
445 let copy_remote_to_local = tokio::spawn(async move {
446 let mut target_raw_reader = target_raw_reader;
447 let mut listen_raw_writer = listen_raw_writer;
448
449 loop {
450 let packet = match target_raw_reader.read().await {
451 Ok(p) => p,
452 Err(e) => {
453 error!("Error reading packet from target: {e}");
454 return;
455 }
456 };
457
458 clientbound_tx.send(packet.clone()).unwrap();
459
460 match listen_raw_writer.write(Default::default(), &packet).await {
461 Ok(_) => {}
462 Err(e) => {
463 error!("Error writing packet to listen: {e}");
464 return;
465 }
466 }
467 }
468 });
469
470 tokio::try_join!(
471 copy_listen_to_target,
472 copy_remote_to_local,
473 copy_clientbound_to_file
474 )?;
475
476 Ok(())
477}More examples
69async fn handle_connection(stream: TcpStream) -> eyre::Result<()> {
70 stream.set_nodelay(true)?;
71 let ip = stream.peer_addr()?;
72 let mut conn: Connection<ServerboundHandshakePacket, ClientboundHandshakePacket> =
73 Connection::wrap(stream);
74
75 // The first packet sent from a client is the intent packet.
76 // This specifies whether the client is pinging
77 // the server or is going to join the game.
78 let intent = match conn.read(Default::default()).await {
79 Ok(packet) => match packet {
80 ServerboundHandshakePacket::Intention(packet) => {
81 info!(
82 "New connection from {}, hostname {:?}:{}, version {}, {:?}",
83 ip.ip(),
84 packet.hostname,
85 packet.port,
86 packet.protocol_version,
87 packet.intention
88 );
89 packet
90 }
91 },
92 Err(e) => {
93 let e = e.into();
94 warn!("Error during intent: {e}");
95 return Err(e);
96 }
97 };
98
99 match intent.intention {
100 // If the client is pinging the proxy,
101 // reply with the information below.
102 ClientIntention::Status => {
103 let mut conn = conn.status();
104 loop {
105 match conn.read(Default::default()).await {
106 Ok(p) => match p {
107 ServerboundStatusPacket::StatusRequest(_) => {
108 conn.write(
109 Default::default(),
110 ClientboundStatusResponse {
111 description: PROXY_DESC.into(),
112 favicon: PROXY_FAVICON.clone(),
113 players: PROXY_PLAYERS.clone(),
114 version: PROXY_VERSION.clone(),
115 enforces_secure_chat: PROXY_SECURE_CHAT,
116 contact: None,
117 },
118 )
119 .await?;
120 }
121 ServerboundStatusPacket::PingRequest(p) => {
122 conn.write(
123 Default::default(),
124 ClientboundPongResponse { time: p.time },
125 )
126 .await?;
127 break;
128 }
129 },
130 Err(e) => match *e {
131 ReadPacketError::ConnectionClosed => {
132 break;
133 }
134 e => {
135 warn!("Error during status: {e}");
136 return Err(e.into());
137 }
138 },
139 }
140 }
141 }
142 // If the client intends to join the proxy,
143 // wait for them to send the `Hello` packet to
144 // log their username and uuid, then forward the
145 // connection along to the proxy target.
146 ClientIntention::Login => {
147 let mut conn = conn.login();
148 loop {
149 match conn.read(Default::default()).await {
150 Ok(p) => {
151 if let ServerboundLoginPacket::Hello(hello) = p {
152 info!(
153 "Player \'{0}\' from {1} logging in with uuid: {2}",
154 hello.name,
155 ip.ip(),
156 hello.profile_id.to_string()
157 );
158
159 tokio::spawn(transfer(conn.unwrap()?, intent, hello).map(|r| {
160 if let Err(e) = r {
161 error!("Failed to proxy: {e}");
162 }
163 }));
164
165 break;
166 }
167 }
168 Err(e) => match *e {
169 ReadPacketError::ConnectionClosed => {
170 break;
171 }
172 e => {
173 warn!("Error during login: {e}");
174 return Err(e.into());
175 }
176 },
177 }
178 }
179 }
180 ClientIntention::Transfer => {
181 warn!("Client attempted to join via transfer")
182 }
183 }
184
185 Ok(())
186}
187
188async fn transfer(
189 mut inbound: TcpStream,
190 intent: ServerboundIntention,
191 hello: ServerboundHello,
192) -> Result<(), Box<dyn Error>> {
193 let outbound = TcpStream::connect(PROXY_ADDR).await?;
194 let name = hello.name.clone();
195 outbound.set_nodelay(true)?;
196
197 // Repeat the intent and hello packet
198 // received earlier to the proxy target
199 let mut outbound_conn: Connection<ClientboundHandshakePacket, ServerboundHandshakePacket> =
200 Connection::wrap(outbound);
201 outbound_conn.write(Default::default(), intent).await?;
202
203 let mut outbound_conn = outbound_conn.login();
204 outbound_conn.write(Default::default(), hello).await?;
205
206 let mut outbound = outbound_conn.unwrap()?;
207
208 // Split the incoming and outgoing connections in
209 // halves and handle each pair on separate threads.
210 let (mut ri, mut wi) = inbound.split();
211 let (mut ro, mut wo) = outbound.split();
212
213 let client_to_server = async {
214 io::copy(&mut ri, &mut wo).await?;
215 wo.shutdown().await
216 };
217
218 let server_to_client = async {
219 io::copy(&mut ro, &mut wi).await?;
220 wi.shutdown().await
221 };
222
223 tokio::try_join!(client_to_server, server_to_client)?;
224 info!("Player \'{name}\' left the game");
225
226 Ok(())
227}Sourcepub async fn write_batch(&mut self, ctx: Ctx<'_>, packets: &[W]) -> Result<()>
pub async fn write_batch(&mut self, ctx: Ctx<'_>, packets: &[W]) -> Result<()>
Write a batch of packets to the other side of the connection.
Sourcepub fn into_split(self) -> (ReadConnection<R>, WriteConnection<W>)
pub fn into_split(self) -> (ReadConnection<R>, WriteConnection<W>)
Split the reader and writer into two objects.
This doesn’t allocate.
Sourcepub fn into_split_raw(self) -> (RawReadConnection, RawWriteConnection)
pub fn into_split_raw(self) -> (RawReadConnection, RawWriteConnection)
Split the reader and writer into the state-agnostic
RawReadConnection and RawWriteConnection types.
This is meant to help with some types of proxies.
Source§impl Connection<ClientboundHandshakePacket, ServerboundHandshakePacket>
impl Connection<ClientboundHandshakePacket, ServerboundHandshakePacket>
Sourcepub async fn new(address: &SocketAddr) -> Result<Self, ConnectionError>
pub async fn new(address: &SocketAddr) -> Result<Self, ConnectionError>
Create a new connection to the given address.
Examples found in repository?
217async fn proxy_conn(
218 mut client_conn: Connection<ServerboundLoginPacket, ClientboundLoginPacket>,
219) -> Result<(), Box<dyn Error>> {
220 // resolve TARGET_ADDR
221 let parsed_target_addr = ServerAddr::from_str(TARGET_ADDR).unwrap();
222 let resolved_target_addr = resolve_address(&parsed_target_addr).await?;
223
224 let mut server_conn = Connection::new(&resolved_target_addr).await?;
225
226 let account = if ACCOUNT.contains('@') {
227 Account::microsoft(ACCOUNT).await?
228 } else {
229 Account::offline(ACCOUNT)
230 };
231 println!("got account: {:?}", account);
232
233 server_conn
234 .write(
235 Default::default(),
236 ServerboundIntention {
237 protocol_version: PROTOCOL_VERSION,
238 hostname: parsed_target_addr.host,
239 port: parsed_target_addr.port,
240 intention: ClientIntention::Login,
241 },
242 )
243 .await?;
244 let mut server_conn = server_conn.login();
245
246 // login
247 server_conn
248 .write(
249 Default::default(),
250 ServerboundHello {
251 name: account.username().to_owned(),
252 profile_id: account.uuid(),
253 },
254 )
255 .await?;
256
257 let (server_conn, login_finished) = loop {
258 let packet = server_conn.read(Default::default()).await?;
259
260 println!("got packet: {:?}", packet);
261
262 match packet {
263 ClientboundLoginPacket::Hello(p) => {
264 debug!("Got encryption request");
265 let e = azalea_crypto::encrypt(&p.public_key, &p.challenge).unwrap();
266
267 if let Some(access_token) = account.access_token() {
268 // keep track of the number of times we tried
269 // authenticating so we can give up after too many
270 let mut attempts: usize = 1;
271
272 while let Err(e) = {
273 server_conn
274 .authenticate(&access_token, &account.uuid(), e.secret_key, &p, None)
275 .await
276 } {
277 if attempts >= 2 {
278 // if this is the second attempt and we failed
279 // both times, give up
280 return Err(e.into());
281 }
282 if matches!(
283 e,
284 ClientSessionServerError::InvalidSession
285 | ClientSessionServerError::ForbiddenOperation
286 ) {
287 // uh oh, we got an invalid session and have
288 // to reauthenticate now
289 account.refresh().await?;
290 } else {
291 return Err(e.into());
292 }
293 attempts += 1;
294 }
295 }
296
297 server_conn
298 .write(
299 Default::default(),
300 ServerboundKey {
301 key_bytes: e.encrypted_public_key,
302 encrypted_challenge: e.encrypted_challenge,
303 },
304 )
305 .await?;
306
307 server_conn.set_encryption_key(e.secret_key);
308 }
309 ClientboundLoginPacket::LoginCompression(p) => {
310 debug!("Got compression request {:?}", p.compression_threshold);
311 server_conn.set_compression_threshold(p.compression_threshold);
312 }
313 ClientboundLoginPacket::LoginFinished(p) => {
314 debug!(
315 "Got profile {:?}. handshake is finished and we're now switching to the configuration state",
316 p.game_profile
317 );
318 // server_conn.write(Default::default(),
319 // ServerboundLoginAcknowledged {}).await?;
320 break (server_conn.config(), p);
321 }
322 ClientboundLoginPacket::LoginDisconnect(p) => {
323 error!("Got disconnect {p:?}");
324 return Err("Disconnected".into());
325 }
326 ClientboundLoginPacket::CustomQuery(p) => {
327 debug!("Got custom query {:?}", p);
328 // replying to custom query is done in
329 // packet_handling::login::process_packet_events
330 }
331 ClientboundLoginPacket::CookieRequest(p) => {
332 debug!("Got cookie request {:?}", p);
333
334 server_conn
335 .write(
336 Default::default(),
337 packets::login::ServerboundCookieResponse {
338 key: p.key,
339 // cookies aren't implemented
340 payload: None,
341 },
342 )
343 .await?;
344 }
345 }
346 };
347
348 // give the client the login_finished
349 println!("got the login_finished: {:?}", login_finished);
350 client_conn
351 .write(Default::default(), login_finished)
352 .await?;
353 let client_conn = client_conn.config();
354
355 info!("started direct bridging");
356
357 // bridge packets
358 let listen_raw_reader = client_conn.reader.raw;
359 let listen_raw_writer = client_conn.writer.raw;
360
361 let target_raw_reader = server_conn.reader.raw;
362 let target_raw_writer = server_conn.writer.raw;
363
364 let packet_logs_txt = Arc::new(tokio::sync::Mutex::new(
365 File::create("combined.txt").await.unwrap(),
366 ));
367
368 let packet_logs_txt_clone = packet_logs_txt.clone();
369 let copy_listen_to_target = tokio::spawn(async move {
370 let mut listen_raw_reader = listen_raw_reader;
371 let mut target_raw_writer = target_raw_writer;
372
373 let packet_logs_txt = packet_logs_txt_clone;
374
375 let mut serverbound_parsed_txt = File::create("serverbound.txt").await.unwrap();
376
377 loop {
378 let packet = match listen_raw_reader.read().await {
379 Ok(p) => p,
380 Err(e) => {
381 error!("Error reading packet from listen: {e}");
382 return;
383 }
384 };
385
386 // decode as a game packet
387 let decoded_packet = azalea_protocol::read::deserialize_packet::<ServerboundGamePacket>(
388 Default::default(),
389 &mut Cursor::new(&packet),
390 );
391
392 if let Ok(decoded_packet) = decoded_packet {
393 let timestamp = chrono::Utc::now();
394 let _ = serverbound_parsed_txt
395 .write_all(format!("{timestamp} {:?}\n", decoded_packet).as_bytes())
396 .await;
397 let _ = packet_logs_txt
398 .lock()
399 .await
400 .write_all(format!("{timestamp} <- {:?}\n", decoded_packet).as_bytes())
401 .await;
402 }
403
404 match target_raw_writer.write(Default::default(), &packet).await {
405 Ok(_) => {}
406 Err(e) => {
407 error!("Error writing packet to target: {e}");
408 return;
409 }
410 }
411 }
412 });
413
414 // write to clientbound.txt in a separate task so it doesn't block receiving
415 // packets
416 let (clientbound_tx, mut clientbound_rx) = tokio::sync::mpsc::unbounded_channel::<Box<[u8]>>();
417 let copy_clientbound_to_file = tokio::spawn(async move {
418 let mut clientbound_parsed_txt = File::create("clientbound.txt").await.unwrap();
419
420 loop {
421 let Some(packet) = clientbound_rx.recv().await else {
422 return;
423 };
424
425 // decode as a game packet
426 let decoded_packet = azalea_protocol::read::deserialize_packet::<ClientboundGamePacket>(
427 Default::default(),
428 &mut Cursor::new(&packet),
429 );
430
431 if let Ok(decoded_packet) = decoded_packet {
432 let timestamp = chrono::Utc::now();
433 let _ = clientbound_parsed_txt
434 .write_all(format!("{timestamp} {decoded_packet:?}\n").as_bytes())
435 .await;
436 let _ = packet_logs_txt
437 .lock()
438 .await
439 .write_all(format!("{timestamp} -> {decoded_packet:?}\n").as_bytes())
440 .await;
441 }
442 }
443 });
444
445 let copy_remote_to_local = tokio::spawn(async move {
446 let mut target_raw_reader = target_raw_reader;
447 let mut listen_raw_writer = listen_raw_writer;
448
449 loop {
450 let packet = match target_raw_reader.read().await {
451 Ok(p) => p,
452 Err(e) => {
453 error!("Error reading packet from target: {e}");
454 return;
455 }
456 };
457
458 clientbound_tx.send(packet.clone()).unwrap();
459
460 match listen_raw_writer.write(Default::default(), &packet).await {
461 Ok(_) => {}
462 Err(e) => {
463 error!("Error writing packet to listen: {e}");
464 return;
465 }
466 }
467 }
468 });
469
470 tokio::try_join!(
471 copy_listen_to_target,
472 copy_remote_to_local,
473 copy_clientbound_to_file
474 )?;
475
476 Ok(())
477}Sourcepub async fn new_with_proxy(
address: &SocketAddr,
proxy: Proxy,
) -> Result<Self, ConnectionError>
pub async fn new_with_proxy( address: &SocketAddr, proxy: Proxy, ) -> Result<Self, ConnectionError>
Create a new connection to the given address and SOCKS5 proxy.
If you’re not using a proxy, use Self::new instead.
Sourcepub async fn new_from_stream(stream: TcpStream) -> Result<Self, ConnectionError>
pub async fn new_from_stream(stream: TcpStream) -> Result<Self, ConnectionError>
Create a new connection from an existing stream.
Useful if you want to set custom options on the stream. Otherwise, just
use Self::new.
Sourcepub fn login(self) -> Connection<ClientboundLoginPacket, ServerboundLoginPacket>
pub fn login(self) -> Connection<ClientboundLoginPacket, ServerboundLoginPacket>
Change our state from handshake to login.
This is the state that is used for logging in.
Examples found in repository?
188async fn transfer(
189 mut inbound: TcpStream,
190 intent: ServerboundIntention,
191 hello: ServerboundHello,
192) -> Result<(), Box<dyn Error>> {
193 let outbound = TcpStream::connect(PROXY_ADDR).await?;
194 let name = hello.name.clone();
195 outbound.set_nodelay(true)?;
196
197 // Repeat the intent and hello packet
198 // received earlier to the proxy target
199 let mut outbound_conn: Connection<ClientboundHandshakePacket, ServerboundHandshakePacket> =
200 Connection::wrap(outbound);
201 outbound_conn.write(Default::default(), intent).await?;
202
203 let mut outbound_conn = outbound_conn.login();
204 outbound_conn.write(Default::default(), hello).await?;
205
206 let mut outbound = outbound_conn.unwrap()?;
207
208 // Split the incoming and outgoing connections in
209 // halves and handle each pair on separate threads.
210 let (mut ri, mut wi) = inbound.split();
211 let (mut ro, mut wo) = outbound.split();
212
213 let client_to_server = async {
214 io::copy(&mut ri, &mut wo).await?;
215 wo.shutdown().await
216 };
217
218 let server_to_client = async {
219 io::copy(&mut ro, &mut wi).await?;
220 wi.shutdown().await
221 };
222
223 tokio::try_join!(client_to_server, server_to_client)?;
224 info!("Player \'{name}\' left the game");
225
226 Ok(())
227}More examples
217async fn proxy_conn(
218 mut client_conn: Connection<ServerboundLoginPacket, ClientboundLoginPacket>,
219) -> Result<(), Box<dyn Error>> {
220 // resolve TARGET_ADDR
221 let parsed_target_addr = ServerAddr::from_str(TARGET_ADDR).unwrap();
222 let resolved_target_addr = resolve_address(&parsed_target_addr).await?;
223
224 let mut server_conn = Connection::new(&resolved_target_addr).await?;
225
226 let account = if ACCOUNT.contains('@') {
227 Account::microsoft(ACCOUNT).await?
228 } else {
229 Account::offline(ACCOUNT)
230 };
231 println!("got account: {:?}", account);
232
233 server_conn
234 .write(
235 Default::default(),
236 ServerboundIntention {
237 protocol_version: PROTOCOL_VERSION,
238 hostname: parsed_target_addr.host,
239 port: parsed_target_addr.port,
240 intention: ClientIntention::Login,
241 },
242 )
243 .await?;
244 let mut server_conn = server_conn.login();
245
246 // login
247 server_conn
248 .write(
249 Default::default(),
250 ServerboundHello {
251 name: account.username().to_owned(),
252 profile_id: account.uuid(),
253 },
254 )
255 .await?;
256
257 let (server_conn, login_finished) = loop {
258 let packet = server_conn.read(Default::default()).await?;
259
260 println!("got packet: {:?}", packet);
261
262 match packet {
263 ClientboundLoginPacket::Hello(p) => {
264 debug!("Got encryption request");
265 let e = azalea_crypto::encrypt(&p.public_key, &p.challenge).unwrap();
266
267 if let Some(access_token) = account.access_token() {
268 // keep track of the number of times we tried
269 // authenticating so we can give up after too many
270 let mut attempts: usize = 1;
271
272 while let Err(e) = {
273 server_conn
274 .authenticate(&access_token, &account.uuid(), e.secret_key, &p, None)
275 .await
276 } {
277 if attempts >= 2 {
278 // if this is the second attempt and we failed
279 // both times, give up
280 return Err(e.into());
281 }
282 if matches!(
283 e,
284 ClientSessionServerError::InvalidSession
285 | ClientSessionServerError::ForbiddenOperation
286 ) {
287 // uh oh, we got an invalid session and have
288 // to reauthenticate now
289 account.refresh().await?;
290 } else {
291 return Err(e.into());
292 }
293 attempts += 1;
294 }
295 }
296
297 server_conn
298 .write(
299 Default::default(),
300 ServerboundKey {
301 key_bytes: e.encrypted_public_key,
302 encrypted_challenge: e.encrypted_challenge,
303 },
304 )
305 .await?;
306
307 server_conn.set_encryption_key(e.secret_key);
308 }
309 ClientboundLoginPacket::LoginCompression(p) => {
310 debug!("Got compression request {:?}", p.compression_threshold);
311 server_conn.set_compression_threshold(p.compression_threshold);
312 }
313 ClientboundLoginPacket::LoginFinished(p) => {
314 debug!(
315 "Got profile {:?}. handshake is finished and we're now switching to the configuration state",
316 p.game_profile
317 );
318 // server_conn.write(Default::default(),
319 // ServerboundLoginAcknowledged {}).await?;
320 break (server_conn.config(), p);
321 }
322 ClientboundLoginPacket::LoginDisconnect(p) => {
323 error!("Got disconnect {p:?}");
324 return Err("Disconnected".into());
325 }
326 ClientboundLoginPacket::CustomQuery(p) => {
327 debug!("Got custom query {:?}", p);
328 // replying to custom query is done in
329 // packet_handling::login::process_packet_events
330 }
331 ClientboundLoginPacket::CookieRequest(p) => {
332 debug!("Got cookie request {:?}", p);
333
334 server_conn
335 .write(
336 Default::default(),
337 packets::login::ServerboundCookieResponse {
338 key: p.key,
339 // cookies aren't implemented
340 payload: None,
341 },
342 )
343 .await?;
344 }
345 }
346 };
347
348 // give the client the login_finished
349 println!("got the login_finished: {:?}", login_finished);
350 client_conn
351 .write(Default::default(), login_finished)
352 .await?;
353 let client_conn = client_conn.config();
354
355 info!("started direct bridging");
356
357 // bridge packets
358 let listen_raw_reader = client_conn.reader.raw;
359 let listen_raw_writer = client_conn.writer.raw;
360
361 let target_raw_reader = server_conn.reader.raw;
362 let target_raw_writer = server_conn.writer.raw;
363
364 let packet_logs_txt = Arc::new(tokio::sync::Mutex::new(
365 File::create("combined.txt").await.unwrap(),
366 ));
367
368 let packet_logs_txt_clone = packet_logs_txt.clone();
369 let copy_listen_to_target = tokio::spawn(async move {
370 let mut listen_raw_reader = listen_raw_reader;
371 let mut target_raw_writer = target_raw_writer;
372
373 let packet_logs_txt = packet_logs_txt_clone;
374
375 let mut serverbound_parsed_txt = File::create("serverbound.txt").await.unwrap();
376
377 loop {
378 let packet = match listen_raw_reader.read().await {
379 Ok(p) => p,
380 Err(e) => {
381 error!("Error reading packet from listen: {e}");
382 return;
383 }
384 };
385
386 // decode as a game packet
387 let decoded_packet = azalea_protocol::read::deserialize_packet::<ServerboundGamePacket>(
388 Default::default(),
389 &mut Cursor::new(&packet),
390 );
391
392 if let Ok(decoded_packet) = decoded_packet {
393 let timestamp = chrono::Utc::now();
394 let _ = serverbound_parsed_txt
395 .write_all(format!("{timestamp} {:?}\n", decoded_packet).as_bytes())
396 .await;
397 let _ = packet_logs_txt
398 .lock()
399 .await
400 .write_all(format!("{timestamp} <- {:?}\n", decoded_packet).as_bytes())
401 .await;
402 }
403
404 match target_raw_writer.write(Default::default(), &packet).await {
405 Ok(_) => {}
406 Err(e) => {
407 error!("Error writing packet to target: {e}");
408 return;
409 }
410 }
411 }
412 });
413
414 // write to clientbound.txt in a separate task so it doesn't block receiving
415 // packets
416 let (clientbound_tx, mut clientbound_rx) = tokio::sync::mpsc::unbounded_channel::<Box<[u8]>>();
417 let copy_clientbound_to_file = tokio::spawn(async move {
418 let mut clientbound_parsed_txt = File::create("clientbound.txt").await.unwrap();
419
420 loop {
421 let Some(packet) = clientbound_rx.recv().await else {
422 return;
423 };
424
425 // decode as a game packet
426 let decoded_packet = azalea_protocol::read::deserialize_packet::<ClientboundGamePacket>(
427 Default::default(),
428 &mut Cursor::new(&packet),
429 );
430
431 if let Ok(decoded_packet) = decoded_packet {
432 let timestamp = chrono::Utc::now();
433 let _ = clientbound_parsed_txt
434 .write_all(format!("{timestamp} {decoded_packet:?}\n").as_bytes())
435 .await;
436 let _ = packet_logs_txt
437 .lock()
438 .await
439 .write_all(format!("{timestamp} -> {decoded_packet:?}\n").as_bytes())
440 .await;
441 }
442 }
443 });
444
445 let copy_remote_to_local = tokio::spawn(async move {
446 let mut target_raw_reader = target_raw_reader;
447 let mut listen_raw_writer = listen_raw_writer;
448
449 loop {
450 let packet = match target_raw_reader.read().await {
451 Ok(p) => p,
452 Err(e) => {
453 error!("Error reading packet from target: {e}");
454 return;
455 }
456 };
457
458 clientbound_tx.send(packet.clone()).unwrap();
459
460 match listen_raw_writer.write(Default::default(), &packet).await {
461 Ok(_) => {}
462 Err(e) => {
463 error!("Error writing packet to listen: {e}");
464 return;
465 }
466 }
467 }
468 });
469
470 tokio::try_join!(
471 copy_listen_to_target,
472 copy_remote_to_local,
473 copy_clientbound_to_file
474 )?;
475
476 Ok(())
477}Sourcepub fn status(
self,
) -> Connection<ClientboundStatusPacket, ServerboundStatusPacket>
pub fn status( self, ) -> Connection<ClientboundStatusPacket, ServerboundStatusPacket>
Change our state from handshake to status.
This is the state that is used for pinging the server.
Source§impl Connection<ClientboundLoginPacket, ServerboundLoginPacket>
impl Connection<ClientboundLoginPacket, ServerboundLoginPacket>
Sourcepub fn set_compression_threshold(&mut self, threshold: i32)
pub fn set_compression_threshold(&mut self, threshold: i32)
Set our compression threshold, i.e. the maximum size that a packet is allowed to be without getting compressed.
Setting it to 0 means every packet will be compressed. If you set it to less than 0 then compression is disabled.
Examples found in repository?
217async fn proxy_conn(
218 mut client_conn: Connection<ServerboundLoginPacket, ClientboundLoginPacket>,
219) -> Result<(), Box<dyn Error>> {
220 // resolve TARGET_ADDR
221 let parsed_target_addr = ServerAddr::from_str(TARGET_ADDR).unwrap();
222 let resolved_target_addr = resolve_address(&parsed_target_addr).await?;
223
224 let mut server_conn = Connection::new(&resolved_target_addr).await?;
225
226 let account = if ACCOUNT.contains('@') {
227 Account::microsoft(ACCOUNT).await?
228 } else {
229 Account::offline(ACCOUNT)
230 };
231 println!("got account: {:?}", account);
232
233 server_conn
234 .write(
235 Default::default(),
236 ServerboundIntention {
237 protocol_version: PROTOCOL_VERSION,
238 hostname: parsed_target_addr.host,
239 port: parsed_target_addr.port,
240 intention: ClientIntention::Login,
241 },
242 )
243 .await?;
244 let mut server_conn = server_conn.login();
245
246 // login
247 server_conn
248 .write(
249 Default::default(),
250 ServerboundHello {
251 name: account.username().to_owned(),
252 profile_id: account.uuid(),
253 },
254 )
255 .await?;
256
257 let (server_conn, login_finished) = loop {
258 let packet = server_conn.read(Default::default()).await?;
259
260 println!("got packet: {:?}", packet);
261
262 match packet {
263 ClientboundLoginPacket::Hello(p) => {
264 debug!("Got encryption request");
265 let e = azalea_crypto::encrypt(&p.public_key, &p.challenge).unwrap();
266
267 if let Some(access_token) = account.access_token() {
268 // keep track of the number of times we tried
269 // authenticating so we can give up after too many
270 let mut attempts: usize = 1;
271
272 while let Err(e) = {
273 server_conn
274 .authenticate(&access_token, &account.uuid(), e.secret_key, &p, None)
275 .await
276 } {
277 if attempts >= 2 {
278 // if this is the second attempt and we failed
279 // both times, give up
280 return Err(e.into());
281 }
282 if matches!(
283 e,
284 ClientSessionServerError::InvalidSession
285 | ClientSessionServerError::ForbiddenOperation
286 ) {
287 // uh oh, we got an invalid session and have
288 // to reauthenticate now
289 account.refresh().await?;
290 } else {
291 return Err(e.into());
292 }
293 attempts += 1;
294 }
295 }
296
297 server_conn
298 .write(
299 Default::default(),
300 ServerboundKey {
301 key_bytes: e.encrypted_public_key,
302 encrypted_challenge: e.encrypted_challenge,
303 },
304 )
305 .await?;
306
307 server_conn.set_encryption_key(e.secret_key);
308 }
309 ClientboundLoginPacket::LoginCompression(p) => {
310 debug!("Got compression request {:?}", p.compression_threshold);
311 server_conn.set_compression_threshold(p.compression_threshold);
312 }
313 ClientboundLoginPacket::LoginFinished(p) => {
314 debug!(
315 "Got profile {:?}. handshake is finished and we're now switching to the configuration state",
316 p.game_profile
317 );
318 // server_conn.write(Default::default(),
319 // ServerboundLoginAcknowledged {}).await?;
320 break (server_conn.config(), p);
321 }
322 ClientboundLoginPacket::LoginDisconnect(p) => {
323 error!("Got disconnect {p:?}");
324 return Err("Disconnected".into());
325 }
326 ClientboundLoginPacket::CustomQuery(p) => {
327 debug!("Got custom query {:?}", p);
328 // replying to custom query is done in
329 // packet_handling::login::process_packet_events
330 }
331 ClientboundLoginPacket::CookieRequest(p) => {
332 debug!("Got cookie request {:?}", p);
333
334 server_conn
335 .write(
336 Default::default(),
337 packets::login::ServerboundCookieResponse {
338 key: p.key,
339 // cookies aren't implemented
340 payload: None,
341 },
342 )
343 .await?;
344 }
345 }
346 };
347
348 // give the client the login_finished
349 println!("got the login_finished: {:?}", login_finished);
350 client_conn
351 .write(Default::default(), login_finished)
352 .await?;
353 let client_conn = client_conn.config();
354
355 info!("started direct bridging");
356
357 // bridge packets
358 let listen_raw_reader = client_conn.reader.raw;
359 let listen_raw_writer = client_conn.writer.raw;
360
361 let target_raw_reader = server_conn.reader.raw;
362 let target_raw_writer = server_conn.writer.raw;
363
364 let packet_logs_txt = Arc::new(tokio::sync::Mutex::new(
365 File::create("combined.txt").await.unwrap(),
366 ));
367
368 let packet_logs_txt_clone = packet_logs_txt.clone();
369 let copy_listen_to_target = tokio::spawn(async move {
370 let mut listen_raw_reader = listen_raw_reader;
371 let mut target_raw_writer = target_raw_writer;
372
373 let packet_logs_txt = packet_logs_txt_clone;
374
375 let mut serverbound_parsed_txt = File::create("serverbound.txt").await.unwrap();
376
377 loop {
378 let packet = match listen_raw_reader.read().await {
379 Ok(p) => p,
380 Err(e) => {
381 error!("Error reading packet from listen: {e}");
382 return;
383 }
384 };
385
386 // decode as a game packet
387 let decoded_packet = azalea_protocol::read::deserialize_packet::<ServerboundGamePacket>(
388 Default::default(),
389 &mut Cursor::new(&packet),
390 );
391
392 if let Ok(decoded_packet) = decoded_packet {
393 let timestamp = chrono::Utc::now();
394 let _ = serverbound_parsed_txt
395 .write_all(format!("{timestamp} {:?}\n", decoded_packet).as_bytes())
396 .await;
397 let _ = packet_logs_txt
398 .lock()
399 .await
400 .write_all(format!("{timestamp} <- {:?}\n", decoded_packet).as_bytes())
401 .await;
402 }
403
404 match target_raw_writer.write(Default::default(), &packet).await {
405 Ok(_) => {}
406 Err(e) => {
407 error!("Error writing packet to target: {e}");
408 return;
409 }
410 }
411 }
412 });
413
414 // write to clientbound.txt in a separate task so it doesn't block receiving
415 // packets
416 let (clientbound_tx, mut clientbound_rx) = tokio::sync::mpsc::unbounded_channel::<Box<[u8]>>();
417 let copy_clientbound_to_file = tokio::spawn(async move {
418 let mut clientbound_parsed_txt = File::create("clientbound.txt").await.unwrap();
419
420 loop {
421 let Some(packet) = clientbound_rx.recv().await else {
422 return;
423 };
424
425 // decode as a game packet
426 let decoded_packet = azalea_protocol::read::deserialize_packet::<ClientboundGamePacket>(
427 Default::default(),
428 &mut Cursor::new(&packet),
429 );
430
431 if let Ok(decoded_packet) = decoded_packet {
432 let timestamp = chrono::Utc::now();
433 let _ = clientbound_parsed_txt
434 .write_all(format!("{timestamp} {decoded_packet:?}\n").as_bytes())
435 .await;
436 let _ = packet_logs_txt
437 .lock()
438 .await
439 .write_all(format!("{timestamp} -> {decoded_packet:?}\n").as_bytes())
440 .await;
441 }
442 }
443 });
444
445 let copy_remote_to_local = tokio::spawn(async move {
446 let mut target_raw_reader = target_raw_reader;
447 let mut listen_raw_writer = listen_raw_writer;
448
449 loop {
450 let packet = match target_raw_reader.read().await {
451 Ok(p) => p,
452 Err(e) => {
453 error!("Error reading packet from target: {e}");
454 return;
455 }
456 };
457
458 clientbound_tx.send(packet.clone()).unwrap();
459
460 match listen_raw_writer.write(Default::default(), &packet).await {
461 Ok(_) => {}
462 Err(e) => {
463 error!("Error writing packet to listen: {e}");
464 return;
465 }
466 }
467 }
468 });
469
470 tokio::try_join!(
471 copy_listen_to_target,
472 copy_remote_to_local,
473 copy_clientbound_to_file
474 )?;
475
476 Ok(())
477}Sourcepub fn set_encryption_key(&mut self, key: [u8; 16])
pub fn set_encryption_key(&mut self, key: [u8; 16])
Set the encryption key that is used to encrypt and decrypt packets.
It’s the same for both reading and writing.
Examples found in repository?
217async fn proxy_conn(
218 mut client_conn: Connection<ServerboundLoginPacket, ClientboundLoginPacket>,
219) -> Result<(), Box<dyn Error>> {
220 // resolve TARGET_ADDR
221 let parsed_target_addr = ServerAddr::from_str(TARGET_ADDR).unwrap();
222 let resolved_target_addr = resolve_address(&parsed_target_addr).await?;
223
224 let mut server_conn = Connection::new(&resolved_target_addr).await?;
225
226 let account = if ACCOUNT.contains('@') {
227 Account::microsoft(ACCOUNT).await?
228 } else {
229 Account::offline(ACCOUNT)
230 };
231 println!("got account: {:?}", account);
232
233 server_conn
234 .write(
235 Default::default(),
236 ServerboundIntention {
237 protocol_version: PROTOCOL_VERSION,
238 hostname: parsed_target_addr.host,
239 port: parsed_target_addr.port,
240 intention: ClientIntention::Login,
241 },
242 )
243 .await?;
244 let mut server_conn = server_conn.login();
245
246 // login
247 server_conn
248 .write(
249 Default::default(),
250 ServerboundHello {
251 name: account.username().to_owned(),
252 profile_id: account.uuid(),
253 },
254 )
255 .await?;
256
257 let (server_conn, login_finished) = loop {
258 let packet = server_conn.read(Default::default()).await?;
259
260 println!("got packet: {:?}", packet);
261
262 match packet {
263 ClientboundLoginPacket::Hello(p) => {
264 debug!("Got encryption request");
265 let e = azalea_crypto::encrypt(&p.public_key, &p.challenge).unwrap();
266
267 if let Some(access_token) = account.access_token() {
268 // keep track of the number of times we tried
269 // authenticating so we can give up after too many
270 let mut attempts: usize = 1;
271
272 while let Err(e) = {
273 server_conn
274 .authenticate(&access_token, &account.uuid(), e.secret_key, &p, None)
275 .await
276 } {
277 if attempts >= 2 {
278 // if this is the second attempt and we failed
279 // both times, give up
280 return Err(e.into());
281 }
282 if matches!(
283 e,
284 ClientSessionServerError::InvalidSession
285 | ClientSessionServerError::ForbiddenOperation
286 ) {
287 // uh oh, we got an invalid session and have
288 // to reauthenticate now
289 account.refresh().await?;
290 } else {
291 return Err(e.into());
292 }
293 attempts += 1;
294 }
295 }
296
297 server_conn
298 .write(
299 Default::default(),
300 ServerboundKey {
301 key_bytes: e.encrypted_public_key,
302 encrypted_challenge: e.encrypted_challenge,
303 },
304 )
305 .await?;
306
307 server_conn.set_encryption_key(e.secret_key);
308 }
309 ClientboundLoginPacket::LoginCompression(p) => {
310 debug!("Got compression request {:?}", p.compression_threshold);
311 server_conn.set_compression_threshold(p.compression_threshold);
312 }
313 ClientboundLoginPacket::LoginFinished(p) => {
314 debug!(
315 "Got profile {:?}. handshake is finished and we're now switching to the configuration state",
316 p.game_profile
317 );
318 // server_conn.write(Default::default(),
319 // ServerboundLoginAcknowledged {}).await?;
320 break (server_conn.config(), p);
321 }
322 ClientboundLoginPacket::LoginDisconnect(p) => {
323 error!("Got disconnect {p:?}");
324 return Err("Disconnected".into());
325 }
326 ClientboundLoginPacket::CustomQuery(p) => {
327 debug!("Got custom query {:?}", p);
328 // replying to custom query is done in
329 // packet_handling::login::process_packet_events
330 }
331 ClientboundLoginPacket::CookieRequest(p) => {
332 debug!("Got cookie request {:?}", p);
333
334 server_conn
335 .write(
336 Default::default(),
337 packets::login::ServerboundCookieResponse {
338 key: p.key,
339 // cookies aren't implemented
340 payload: None,
341 },
342 )
343 .await?;
344 }
345 }
346 };
347
348 // give the client the login_finished
349 println!("got the login_finished: {:?}", login_finished);
350 client_conn
351 .write(Default::default(), login_finished)
352 .await?;
353 let client_conn = client_conn.config();
354
355 info!("started direct bridging");
356
357 // bridge packets
358 let listen_raw_reader = client_conn.reader.raw;
359 let listen_raw_writer = client_conn.writer.raw;
360
361 let target_raw_reader = server_conn.reader.raw;
362 let target_raw_writer = server_conn.writer.raw;
363
364 let packet_logs_txt = Arc::new(tokio::sync::Mutex::new(
365 File::create("combined.txt").await.unwrap(),
366 ));
367
368 let packet_logs_txt_clone = packet_logs_txt.clone();
369 let copy_listen_to_target = tokio::spawn(async move {
370 let mut listen_raw_reader = listen_raw_reader;
371 let mut target_raw_writer = target_raw_writer;
372
373 let packet_logs_txt = packet_logs_txt_clone;
374
375 let mut serverbound_parsed_txt = File::create("serverbound.txt").await.unwrap();
376
377 loop {
378 let packet = match listen_raw_reader.read().await {
379 Ok(p) => p,
380 Err(e) => {
381 error!("Error reading packet from listen: {e}");
382 return;
383 }
384 };
385
386 // decode as a game packet
387 let decoded_packet = azalea_protocol::read::deserialize_packet::<ServerboundGamePacket>(
388 Default::default(),
389 &mut Cursor::new(&packet),
390 );
391
392 if let Ok(decoded_packet) = decoded_packet {
393 let timestamp = chrono::Utc::now();
394 let _ = serverbound_parsed_txt
395 .write_all(format!("{timestamp} {:?}\n", decoded_packet).as_bytes())
396 .await;
397 let _ = packet_logs_txt
398 .lock()
399 .await
400 .write_all(format!("{timestamp} <- {:?}\n", decoded_packet).as_bytes())
401 .await;
402 }
403
404 match target_raw_writer.write(Default::default(), &packet).await {
405 Ok(_) => {}
406 Err(e) => {
407 error!("Error writing packet to target: {e}");
408 return;
409 }
410 }
411 }
412 });
413
414 // write to clientbound.txt in a separate task so it doesn't block receiving
415 // packets
416 let (clientbound_tx, mut clientbound_rx) = tokio::sync::mpsc::unbounded_channel::<Box<[u8]>>();
417 let copy_clientbound_to_file = tokio::spawn(async move {
418 let mut clientbound_parsed_txt = File::create("clientbound.txt").await.unwrap();
419
420 loop {
421 let Some(packet) = clientbound_rx.recv().await else {
422 return;
423 };
424
425 // decode as a game packet
426 let decoded_packet = azalea_protocol::read::deserialize_packet::<ClientboundGamePacket>(
427 Default::default(),
428 &mut Cursor::new(&packet),
429 );
430
431 if let Ok(decoded_packet) = decoded_packet {
432 let timestamp = chrono::Utc::now();
433 let _ = clientbound_parsed_txt
434 .write_all(format!("{timestamp} {decoded_packet:?}\n").as_bytes())
435 .await;
436 let _ = packet_logs_txt
437 .lock()
438 .await
439 .write_all(format!("{timestamp} -> {decoded_packet:?}\n").as_bytes())
440 .await;
441 }
442 }
443 });
444
445 let copy_remote_to_local = tokio::spawn(async move {
446 let mut target_raw_reader = target_raw_reader;
447 let mut listen_raw_writer = listen_raw_writer;
448
449 loop {
450 let packet = match target_raw_reader.read().await {
451 Ok(p) => p,
452 Err(e) => {
453 error!("Error reading packet from target: {e}");
454 return;
455 }
456 };
457
458 clientbound_tx.send(packet.clone()).unwrap();
459
460 match listen_raw_writer.write(Default::default(), &packet).await {
461 Ok(_) => {}
462 Err(e) => {
463 error!("Error writing packet to listen: {e}");
464 return;
465 }
466 }
467 }
468 });
469
470 tokio::try_join!(
471 copy_listen_to_target,
472 copy_remote_to_local,
473 copy_clientbound_to_file
474 )?;
475
476 Ok(())
477}Sourcepub fn config(
self,
) -> Connection<ClientboundConfigPacket, ServerboundConfigPacket>
pub fn config( self, ) -> Connection<ClientboundConfigPacket, ServerboundConfigPacket>
Change our state from login to configuration.
This is the state where the server sends us the registries and the resource pack.
Examples found in repository?
217async fn proxy_conn(
218 mut client_conn: Connection<ServerboundLoginPacket, ClientboundLoginPacket>,
219) -> Result<(), Box<dyn Error>> {
220 // resolve TARGET_ADDR
221 let parsed_target_addr = ServerAddr::from_str(TARGET_ADDR).unwrap();
222 let resolved_target_addr = resolve_address(&parsed_target_addr).await?;
223
224 let mut server_conn = Connection::new(&resolved_target_addr).await?;
225
226 let account = if ACCOUNT.contains('@') {
227 Account::microsoft(ACCOUNT).await?
228 } else {
229 Account::offline(ACCOUNT)
230 };
231 println!("got account: {:?}", account);
232
233 server_conn
234 .write(
235 Default::default(),
236 ServerboundIntention {
237 protocol_version: PROTOCOL_VERSION,
238 hostname: parsed_target_addr.host,
239 port: parsed_target_addr.port,
240 intention: ClientIntention::Login,
241 },
242 )
243 .await?;
244 let mut server_conn = server_conn.login();
245
246 // login
247 server_conn
248 .write(
249 Default::default(),
250 ServerboundHello {
251 name: account.username().to_owned(),
252 profile_id: account.uuid(),
253 },
254 )
255 .await?;
256
257 let (server_conn, login_finished) = loop {
258 let packet = server_conn.read(Default::default()).await?;
259
260 println!("got packet: {:?}", packet);
261
262 match packet {
263 ClientboundLoginPacket::Hello(p) => {
264 debug!("Got encryption request");
265 let e = azalea_crypto::encrypt(&p.public_key, &p.challenge).unwrap();
266
267 if let Some(access_token) = account.access_token() {
268 // keep track of the number of times we tried
269 // authenticating so we can give up after too many
270 let mut attempts: usize = 1;
271
272 while let Err(e) = {
273 server_conn
274 .authenticate(&access_token, &account.uuid(), e.secret_key, &p, None)
275 .await
276 } {
277 if attempts >= 2 {
278 // if this is the second attempt and we failed
279 // both times, give up
280 return Err(e.into());
281 }
282 if matches!(
283 e,
284 ClientSessionServerError::InvalidSession
285 | ClientSessionServerError::ForbiddenOperation
286 ) {
287 // uh oh, we got an invalid session and have
288 // to reauthenticate now
289 account.refresh().await?;
290 } else {
291 return Err(e.into());
292 }
293 attempts += 1;
294 }
295 }
296
297 server_conn
298 .write(
299 Default::default(),
300 ServerboundKey {
301 key_bytes: e.encrypted_public_key,
302 encrypted_challenge: e.encrypted_challenge,
303 },
304 )
305 .await?;
306
307 server_conn.set_encryption_key(e.secret_key);
308 }
309 ClientboundLoginPacket::LoginCompression(p) => {
310 debug!("Got compression request {:?}", p.compression_threshold);
311 server_conn.set_compression_threshold(p.compression_threshold);
312 }
313 ClientboundLoginPacket::LoginFinished(p) => {
314 debug!(
315 "Got profile {:?}. handshake is finished and we're now switching to the configuration state",
316 p.game_profile
317 );
318 // server_conn.write(Default::default(),
319 // ServerboundLoginAcknowledged {}).await?;
320 break (server_conn.config(), p);
321 }
322 ClientboundLoginPacket::LoginDisconnect(p) => {
323 error!("Got disconnect {p:?}");
324 return Err("Disconnected".into());
325 }
326 ClientboundLoginPacket::CustomQuery(p) => {
327 debug!("Got custom query {:?}", p);
328 // replying to custom query is done in
329 // packet_handling::login::process_packet_events
330 }
331 ClientboundLoginPacket::CookieRequest(p) => {
332 debug!("Got cookie request {:?}", p);
333
334 server_conn
335 .write(
336 Default::default(),
337 packets::login::ServerboundCookieResponse {
338 key: p.key,
339 // cookies aren't implemented
340 payload: None,
341 },
342 )
343 .await?;
344 }
345 }
346 };
347
348 // give the client the login_finished
349 println!("got the login_finished: {:?}", login_finished);
350 client_conn
351 .write(Default::default(), login_finished)
352 .await?;
353 let client_conn = client_conn.config();
354
355 info!("started direct bridging");
356
357 // bridge packets
358 let listen_raw_reader = client_conn.reader.raw;
359 let listen_raw_writer = client_conn.writer.raw;
360
361 let target_raw_reader = server_conn.reader.raw;
362 let target_raw_writer = server_conn.writer.raw;
363
364 let packet_logs_txt = Arc::new(tokio::sync::Mutex::new(
365 File::create("combined.txt").await.unwrap(),
366 ));
367
368 let packet_logs_txt_clone = packet_logs_txt.clone();
369 let copy_listen_to_target = tokio::spawn(async move {
370 let mut listen_raw_reader = listen_raw_reader;
371 let mut target_raw_writer = target_raw_writer;
372
373 let packet_logs_txt = packet_logs_txt_clone;
374
375 let mut serverbound_parsed_txt = File::create("serverbound.txt").await.unwrap();
376
377 loop {
378 let packet = match listen_raw_reader.read().await {
379 Ok(p) => p,
380 Err(e) => {
381 error!("Error reading packet from listen: {e}");
382 return;
383 }
384 };
385
386 // decode as a game packet
387 let decoded_packet = azalea_protocol::read::deserialize_packet::<ServerboundGamePacket>(
388 Default::default(),
389 &mut Cursor::new(&packet),
390 );
391
392 if let Ok(decoded_packet) = decoded_packet {
393 let timestamp = chrono::Utc::now();
394 let _ = serverbound_parsed_txt
395 .write_all(format!("{timestamp} {:?}\n", decoded_packet).as_bytes())
396 .await;
397 let _ = packet_logs_txt
398 .lock()
399 .await
400 .write_all(format!("{timestamp} <- {:?}\n", decoded_packet).as_bytes())
401 .await;
402 }
403
404 match target_raw_writer.write(Default::default(), &packet).await {
405 Ok(_) => {}
406 Err(e) => {
407 error!("Error writing packet to target: {e}");
408 return;
409 }
410 }
411 }
412 });
413
414 // write to clientbound.txt in a separate task so it doesn't block receiving
415 // packets
416 let (clientbound_tx, mut clientbound_rx) = tokio::sync::mpsc::unbounded_channel::<Box<[u8]>>();
417 let copy_clientbound_to_file = tokio::spawn(async move {
418 let mut clientbound_parsed_txt = File::create("clientbound.txt").await.unwrap();
419
420 loop {
421 let Some(packet) = clientbound_rx.recv().await else {
422 return;
423 };
424
425 // decode as a game packet
426 let decoded_packet = azalea_protocol::read::deserialize_packet::<ClientboundGamePacket>(
427 Default::default(),
428 &mut Cursor::new(&packet),
429 );
430
431 if let Ok(decoded_packet) = decoded_packet {
432 let timestamp = chrono::Utc::now();
433 let _ = clientbound_parsed_txt
434 .write_all(format!("{timestamp} {decoded_packet:?}\n").as_bytes())
435 .await;
436 let _ = packet_logs_txt
437 .lock()
438 .await
439 .write_all(format!("{timestamp} -> {decoded_packet:?}\n").as_bytes())
440 .await;
441 }
442 }
443 });
444
445 let copy_remote_to_local = tokio::spawn(async move {
446 let mut target_raw_reader = target_raw_reader;
447 let mut listen_raw_writer = listen_raw_writer;
448
449 loop {
450 let packet = match target_raw_reader.read().await {
451 Ok(p) => p,
452 Err(e) => {
453 error!("Error reading packet from target: {e}");
454 return;
455 }
456 };
457
458 clientbound_tx.send(packet.clone()).unwrap();
459
460 match listen_raw_writer.write(Default::default(), &packet).await {
461 Ok(_) => {}
462 Err(e) => {
463 error!("Error writing packet to listen: {e}");
464 return;
465 }
466 }
467 }
468 });
469
470 tokio::try_join!(
471 copy_listen_to_target,
472 copy_remote_to_local,
473 copy_clientbound_to_file
474 )?;
475
476 Ok(())
477}Sourcepub async fn authenticate(
&self,
access_token: &str,
uuid: &Uuid,
private_key: [u8; 16],
packet: &ClientboundHello,
sessionserver_proxy: Option<Proxy>,
) -> Result<(), ClientSessionServerError>
pub async fn authenticate( &self, access_token: &str, uuid: &Uuid, private_key: [u8; 16], packet: &ClientboundHello, sessionserver_proxy: Option<Proxy>, ) -> Result<(), ClientSessionServerError>
Authenticate with Minecraft’s servers, which is required to join online-mode servers.
This must happen when you get a ClientboundLoginPacket::Hello packet.
§Examples
use azalea_auth::AuthResult;
use azalea_protocol::{
connect::Connection,
packets::login::{ClientboundLoginPacket, ServerboundKey},
};
use uuid::Uuid;
let AuthResult {
access_token,
profile,
} = azalea_auth::auth("example@example.com", azalea_auth::AuthOpts::default())
.await
.expect("Couldn't authenticate");
let mut conn = Connection::new(&resolved_address).await?;
// transition to the login state, in a real program we would have done a handshake first
let mut conn = conn.login();
match conn.read(Default::default()).await? {
ClientboundLoginPacket::Hello(p) => {
// tell Mojang we're joining the server & enable encryption
let e = azalea_crypto::encrypt(&p.public_key, &p.challenge).unwrap();
conn.authenticate(&access_token, &profile.id, e.secret_key, &p, None)
.await?;
conn.write(
Default::default(),
ServerboundKey {
key_bytes: e.encrypted_public_key,
encrypted_challenge: e.encrypted_challenge,
},
)
.await?;
conn.set_encryption_key(e.secret_key);
}
_ => {}
}Examples found in repository?
217async fn proxy_conn(
218 mut client_conn: Connection<ServerboundLoginPacket, ClientboundLoginPacket>,
219) -> Result<(), Box<dyn Error>> {
220 // resolve TARGET_ADDR
221 let parsed_target_addr = ServerAddr::from_str(TARGET_ADDR).unwrap();
222 let resolved_target_addr = resolve_address(&parsed_target_addr).await?;
223
224 let mut server_conn = Connection::new(&resolved_target_addr).await?;
225
226 let account = if ACCOUNT.contains('@') {
227 Account::microsoft(ACCOUNT).await?
228 } else {
229 Account::offline(ACCOUNT)
230 };
231 println!("got account: {:?}", account);
232
233 server_conn
234 .write(
235 Default::default(),
236 ServerboundIntention {
237 protocol_version: PROTOCOL_VERSION,
238 hostname: parsed_target_addr.host,
239 port: parsed_target_addr.port,
240 intention: ClientIntention::Login,
241 },
242 )
243 .await?;
244 let mut server_conn = server_conn.login();
245
246 // login
247 server_conn
248 .write(
249 Default::default(),
250 ServerboundHello {
251 name: account.username().to_owned(),
252 profile_id: account.uuid(),
253 },
254 )
255 .await?;
256
257 let (server_conn, login_finished) = loop {
258 let packet = server_conn.read(Default::default()).await?;
259
260 println!("got packet: {:?}", packet);
261
262 match packet {
263 ClientboundLoginPacket::Hello(p) => {
264 debug!("Got encryption request");
265 let e = azalea_crypto::encrypt(&p.public_key, &p.challenge).unwrap();
266
267 if let Some(access_token) = account.access_token() {
268 // keep track of the number of times we tried
269 // authenticating so we can give up after too many
270 let mut attempts: usize = 1;
271
272 while let Err(e) = {
273 server_conn
274 .authenticate(&access_token, &account.uuid(), e.secret_key, &p, None)
275 .await
276 } {
277 if attempts >= 2 {
278 // if this is the second attempt and we failed
279 // both times, give up
280 return Err(e.into());
281 }
282 if matches!(
283 e,
284 ClientSessionServerError::InvalidSession
285 | ClientSessionServerError::ForbiddenOperation
286 ) {
287 // uh oh, we got an invalid session and have
288 // to reauthenticate now
289 account.refresh().await?;
290 } else {
291 return Err(e.into());
292 }
293 attempts += 1;
294 }
295 }
296
297 server_conn
298 .write(
299 Default::default(),
300 ServerboundKey {
301 key_bytes: e.encrypted_public_key,
302 encrypted_challenge: e.encrypted_challenge,
303 },
304 )
305 .await?;
306
307 server_conn.set_encryption_key(e.secret_key);
308 }
309 ClientboundLoginPacket::LoginCompression(p) => {
310 debug!("Got compression request {:?}", p.compression_threshold);
311 server_conn.set_compression_threshold(p.compression_threshold);
312 }
313 ClientboundLoginPacket::LoginFinished(p) => {
314 debug!(
315 "Got profile {:?}. handshake is finished and we're now switching to the configuration state",
316 p.game_profile
317 );
318 // server_conn.write(Default::default(),
319 // ServerboundLoginAcknowledged {}).await?;
320 break (server_conn.config(), p);
321 }
322 ClientboundLoginPacket::LoginDisconnect(p) => {
323 error!("Got disconnect {p:?}");
324 return Err("Disconnected".into());
325 }
326 ClientboundLoginPacket::CustomQuery(p) => {
327 debug!("Got custom query {:?}", p);
328 // replying to custom query is done in
329 // packet_handling::login::process_packet_events
330 }
331 ClientboundLoginPacket::CookieRequest(p) => {
332 debug!("Got cookie request {:?}", p);
333
334 server_conn
335 .write(
336 Default::default(),
337 packets::login::ServerboundCookieResponse {
338 key: p.key,
339 // cookies aren't implemented
340 payload: None,
341 },
342 )
343 .await?;
344 }
345 }
346 };
347
348 // give the client the login_finished
349 println!("got the login_finished: {:?}", login_finished);
350 client_conn
351 .write(Default::default(), login_finished)
352 .await?;
353 let client_conn = client_conn.config();
354
355 info!("started direct bridging");
356
357 // bridge packets
358 let listen_raw_reader = client_conn.reader.raw;
359 let listen_raw_writer = client_conn.writer.raw;
360
361 let target_raw_reader = server_conn.reader.raw;
362 let target_raw_writer = server_conn.writer.raw;
363
364 let packet_logs_txt = Arc::new(tokio::sync::Mutex::new(
365 File::create("combined.txt").await.unwrap(),
366 ));
367
368 let packet_logs_txt_clone = packet_logs_txt.clone();
369 let copy_listen_to_target = tokio::spawn(async move {
370 let mut listen_raw_reader = listen_raw_reader;
371 let mut target_raw_writer = target_raw_writer;
372
373 let packet_logs_txt = packet_logs_txt_clone;
374
375 let mut serverbound_parsed_txt = File::create("serverbound.txt").await.unwrap();
376
377 loop {
378 let packet = match listen_raw_reader.read().await {
379 Ok(p) => p,
380 Err(e) => {
381 error!("Error reading packet from listen: {e}");
382 return;
383 }
384 };
385
386 // decode as a game packet
387 let decoded_packet = azalea_protocol::read::deserialize_packet::<ServerboundGamePacket>(
388 Default::default(),
389 &mut Cursor::new(&packet),
390 );
391
392 if let Ok(decoded_packet) = decoded_packet {
393 let timestamp = chrono::Utc::now();
394 let _ = serverbound_parsed_txt
395 .write_all(format!("{timestamp} {:?}\n", decoded_packet).as_bytes())
396 .await;
397 let _ = packet_logs_txt
398 .lock()
399 .await
400 .write_all(format!("{timestamp} <- {:?}\n", decoded_packet).as_bytes())
401 .await;
402 }
403
404 match target_raw_writer.write(Default::default(), &packet).await {
405 Ok(_) => {}
406 Err(e) => {
407 error!("Error writing packet to target: {e}");
408 return;
409 }
410 }
411 }
412 });
413
414 // write to clientbound.txt in a separate task so it doesn't block receiving
415 // packets
416 let (clientbound_tx, mut clientbound_rx) = tokio::sync::mpsc::unbounded_channel::<Box<[u8]>>();
417 let copy_clientbound_to_file = tokio::spawn(async move {
418 let mut clientbound_parsed_txt = File::create("clientbound.txt").await.unwrap();
419
420 loop {
421 let Some(packet) = clientbound_rx.recv().await else {
422 return;
423 };
424
425 // decode as a game packet
426 let decoded_packet = azalea_protocol::read::deserialize_packet::<ClientboundGamePacket>(
427 Default::default(),
428 &mut Cursor::new(&packet),
429 );
430
431 if let Ok(decoded_packet) = decoded_packet {
432 let timestamp = chrono::Utc::now();
433 let _ = clientbound_parsed_txt
434 .write_all(format!("{timestamp} {decoded_packet:?}\n").as_bytes())
435 .await;
436 let _ = packet_logs_txt
437 .lock()
438 .await
439 .write_all(format!("{timestamp} -> {decoded_packet:?}\n").as_bytes())
440 .await;
441 }
442 }
443 });
444
445 let copy_remote_to_local = tokio::spawn(async move {
446 let mut target_raw_reader = target_raw_reader;
447 let mut listen_raw_writer = listen_raw_writer;
448
449 loop {
450 let packet = match target_raw_reader.read().await {
451 Ok(p) => p,
452 Err(e) => {
453 error!("Error reading packet from target: {e}");
454 return;
455 }
456 };
457
458 clientbound_tx.send(packet.clone()).unwrap();
459
460 match listen_raw_writer.write(Default::default(), &packet).await {
461 Ok(_) => {}
462 Err(e) => {
463 error!("Error writing packet to listen: {e}");
464 return;
465 }
466 }
467 }
468 });
469
470 tokio::try_join!(
471 copy_listen_to_target,
472 copy_remote_to_local,
473 copy_clientbound_to_file
474 )?;
475
476 Ok(())
477}Source§impl Connection<ServerboundHandshakePacket, ClientboundHandshakePacket>
impl Connection<ServerboundHandshakePacket, ClientboundHandshakePacket>
Sourcepub fn login(self) -> Connection<ServerboundLoginPacket, ClientboundLoginPacket>
pub fn login(self) -> Connection<ServerboundLoginPacket, ClientboundLoginPacket>
Change our state from handshake to login.
This is the state that is used while negotiating encryption and authenticating with Mojang.
Examples found in repository?
100async fn handle_connection(stream: TcpStream) -> eyre::Result<()> {
101 stream.set_nodelay(true)?;
102 let ip = stream.peer_addr()?;
103 let mut conn: Connection<ServerboundHandshakePacket, ClientboundHandshakePacket> =
104 Connection::wrap(stream);
105
106 // The first packet sent from a client is the intent packet.
107 // This specifies whether the client is pinging
108 // the server or is going to join the game.
109 let intent = match conn.read(Default::default()).await {
110 Ok(packet) => match packet {
111 ServerboundHandshakePacket::Intention(packet) => {
112 info!(
113 "New connection from {}, hostname {:?}:{}, version {}, {:?}",
114 ip.ip(),
115 packet.hostname,
116 packet.port,
117 packet.protocol_version,
118 packet.intention
119 );
120 packet
121 }
122 },
123 Err(e) => {
124 let e = e.into();
125 warn!("Error during intent: {e}");
126 return Err(e);
127 }
128 };
129
130 match intent.intention {
131 // If the client is pinging the proxy, reply with the information below.
132 ClientIntention::Status => {
133 let mut conn = conn.status();
134 loop {
135 match conn.read(Default::default()).await {
136 Ok(p) => match p {
137 ServerboundStatusPacket::StatusRequest(_) => {
138 conn.write(
139 Default::default(),
140 ClientboundStatusResponse {
141 description: PROXY_DESC.into(),
142 favicon: PROXY_FAVICON.clone(),
143 players: PROXY_PLAYERS.clone(),
144 version: PROXY_VERSION.clone(),
145 enforces_secure_chat: PROXY_SECURE_CHAT,
146 contact: None,
147 },
148 )
149 .await?;
150 }
151 ServerboundStatusPacket::PingRequest(p) => {
152 conn.write(
153 Default::default(),
154 ClientboundPongResponse { time: p.time },
155 )
156 .await?;
157 break;
158 }
159 },
160 Err(e) => match *e {
161 ReadPacketError::ConnectionClosed => {
162 break;
163 }
164 e => {
165 warn!("Error during status: {e}");
166 return Err(e.into());
167 }
168 },
169 }
170 }
171 }
172 // If the client intends to join the proxy, wait for them to send the
173 // `Hello` packet to log their username and uuid, then start proxying
174 // their connection.
175 ClientIntention::Login => {
176 let mut conn = conn.login();
177 loop {
178 match conn.read(Default::default()).await {
179 Ok(p) => {
180 if let ServerboundLoginPacket::Hello(hello) = p {
181 info!(
182 "Player \'{}\' from {} logging in with uuid: {}",
183 hello.name,
184 ip.ip(),
185 hello.profile_id.to_string()
186 );
187
188 tokio::spawn(proxy_conn(conn).map(|r| {
189 if let Err(e) = r {
190 error!("Failed to proxy: {e}");
191 }
192 }));
193
194 break;
195 }
196 }
197 Err(e) => match *e {
198 ReadPacketError::ConnectionClosed => {
199 break;
200 }
201 e => {
202 warn!("Error during login: {e}");
203 return Err(e.into());
204 }
205 },
206 }
207 }
208 }
209 ClientIntention::Transfer => {
210 warn!("Client attempted to join via transfer")
211 }
212 }
213
214 Ok(())
215}More examples
69async fn handle_connection(stream: TcpStream) -> eyre::Result<()> {
70 stream.set_nodelay(true)?;
71 let ip = stream.peer_addr()?;
72 let mut conn: Connection<ServerboundHandshakePacket, ClientboundHandshakePacket> =
73 Connection::wrap(stream);
74
75 // The first packet sent from a client is the intent packet.
76 // This specifies whether the client is pinging
77 // the server or is going to join the game.
78 let intent = match conn.read(Default::default()).await {
79 Ok(packet) => match packet {
80 ServerboundHandshakePacket::Intention(packet) => {
81 info!(
82 "New connection from {}, hostname {:?}:{}, version {}, {:?}",
83 ip.ip(),
84 packet.hostname,
85 packet.port,
86 packet.protocol_version,
87 packet.intention
88 );
89 packet
90 }
91 },
92 Err(e) => {
93 let e = e.into();
94 warn!("Error during intent: {e}");
95 return Err(e);
96 }
97 };
98
99 match intent.intention {
100 // If the client is pinging the proxy,
101 // reply with the information below.
102 ClientIntention::Status => {
103 let mut conn = conn.status();
104 loop {
105 match conn.read(Default::default()).await {
106 Ok(p) => match p {
107 ServerboundStatusPacket::StatusRequest(_) => {
108 conn.write(
109 Default::default(),
110 ClientboundStatusResponse {
111 description: PROXY_DESC.into(),
112 favicon: PROXY_FAVICON.clone(),
113 players: PROXY_PLAYERS.clone(),
114 version: PROXY_VERSION.clone(),
115 enforces_secure_chat: PROXY_SECURE_CHAT,
116 contact: None,
117 },
118 )
119 .await?;
120 }
121 ServerboundStatusPacket::PingRequest(p) => {
122 conn.write(
123 Default::default(),
124 ClientboundPongResponse { time: p.time },
125 )
126 .await?;
127 break;
128 }
129 },
130 Err(e) => match *e {
131 ReadPacketError::ConnectionClosed => {
132 break;
133 }
134 e => {
135 warn!("Error during status: {e}");
136 return Err(e.into());
137 }
138 },
139 }
140 }
141 }
142 // If the client intends to join the proxy,
143 // wait for them to send the `Hello` packet to
144 // log their username and uuid, then forward the
145 // connection along to the proxy target.
146 ClientIntention::Login => {
147 let mut conn = conn.login();
148 loop {
149 match conn.read(Default::default()).await {
150 Ok(p) => {
151 if let ServerboundLoginPacket::Hello(hello) = p {
152 info!(
153 "Player \'{0}\' from {1} logging in with uuid: {2}",
154 hello.name,
155 ip.ip(),
156 hello.profile_id.to_string()
157 );
158
159 tokio::spawn(transfer(conn.unwrap()?, intent, hello).map(|r| {
160 if let Err(e) = r {
161 error!("Failed to proxy: {e}");
162 }
163 }));
164
165 break;
166 }
167 }
168 Err(e) => match *e {
169 ReadPacketError::ConnectionClosed => {
170 break;
171 }
172 e => {
173 warn!("Error during login: {e}");
174 return Err(e.into());
175 }
176 },
177 }
178 }
179 }
180 ClientIntention::Transfer => {
181 warn!("Client attempted to join via transfer")
182 }
183 }
184
185 Ok(())
186}Sourcepub fn status(
self,
) -> Connection<ServerboundStatusPacket, ClientboundStatusPacket>
pub fn status( self, ) -> Connection<ServerboundStatusPacket, ClientboundStatusPacket>
Change our state from handshake to status.
This is the state that is used for pinging the server.
Examples found in repository?
100async fn handle_connection(stream: TcpStream) -> eyre::Result<()> {
101 stream.set_nodelay(true)?;
102 let ip = stream.peer_addr()?;
103 let mut conn: Connection<ServerboundHandshakePacket, ClientboundHandshakePacket> =
104 Connection::wrap(stream);
105
106 // The first packet sent from a client is the intent packet.
107 // This specifies whether the client is pinging
108 // the server or is going to join the game.
109 let intent = match conn.read(Default::default()).await {
110 Ok(packet) => match packet {
111 ServerboundHandshakePacket::Intention(packet) => {
112 info!(
113 "New connection from {}, hostname {:?}:{}, version {}, {:?}",
114 ip.ip(),
115 packet.hostname,
116 packet.port,
117 packet.protocol_version,
118 packet.intention
119 );
120 packet
121 }
122 },
123 Err(e) => {
124 let e = e.into();
125 warn!("Error during intent: {e}");
126 return Err(e);
127 }
128 };
129
130 match intent.intention {
131 // If the client is pinging the proxy, reply with the information below.
132 ClientIntention::Status => {
133 let mut conn = conn.status();
134 loop {
135 match conn.read(Default::default()).await {
136 Ok(p) => match p {
137 ServerboundStatusPacket::StatusRequest(_) => {
138 conn.write(
139 Default::default(),
140 ClientboundStatusResponse {
141 description: PROXY_DESC.into(),
142 favicon: PROXY_FAVICON.clone(),
143 players: PROXY_PLAYERS.clone(),
144 version: PROXY_VERSION.clone(),
145 enforces_secure_chat: PROXY_SECURE_CHAT,
146 contact: None,
147 },
148 )
149 .await?;
150 }
151 ServerboundStatusPacket::PingRequest(p) => {
152 conn.write(
153 Default::default(),
154 ClientboundPongResponse { time: p.time },
155 )
156 .await?;
157 break;
158 }
159 },
160 Err(e) => match *e {
161 ReadPacketError::ConnectionClosed => {
162 break;
163 }
164 e => {
165 warn!("Error during status: {e}");
166 return Err(e.into());
167 }
168 },
169 }
170 }
171 }
172 // If the client intends to join the proxy, wait for them to send the
173 // `Hello` packet to log their username and uuid, then start proxying
174 // their connection.
175 ClientIntention::Login => {
176 let mut conn = conn.login();
177 loop {
178 match conn.read(Default::default()).await {
179 Ok(p) => {
180 if let ServerboundLoginPacket::Hello(hello) = p {
181 info!(
182 "Player \'{}\' from {} logging in with uuid: {}",
183 hello.name,
184 ip.ip(),
185 hello.profile_id.to_string()
186 );
187
188 tokio::spawn(proxy_conn(conn).map(|r| {
189 if let Err(e) = r {
190 error!("Failed to proxy: {e}");
191 }
192 }));
193
194 break;
195 }
196 }
197 Err(e) => match *e {
198 ReadPacketError::ConnectionClosed => {
199 break;
200 }
201 e => {
202 warn!("Error during login: {e}");
203 return Err(e.into());
204 }
205 },
206 }
207 }
208 }
209 ClientIntention::Transfer => {
210 warn!("Client attempted to join via transfer")
211 }
212 }
213
214 Ok(())
215}More examples
69async fn handle_connection(stream: TcpStream) -> eyre::Result<()> {
70 stream.set_nodelay(true)?;
71 let ip = stream.peer_addr()?;
72 let mut conn: Connection<ServerboundHandshakePacket, ClientboundHandshakePacket> =
73 Connection::wrap(stream);
74
75 // The first packet sent from a client is the intent packet.
76 // This specifies whether the client is pinging
77 // the server or is going to join the game.
78 let intent = match conn.read(Default::default()).await {
79 Ok(packet) => match packet {
80 ServerboundHandshakePacket::Intention(packet) => {
81 info!(
82 "New connection from {}, hostname {:?}:{}, version {}, {:?}",
83 ip.ip(),
84 packet.hostname,
85 packet.port,
86 packet.protocol_version,
87 packet.intention
88 );
89 packet
90 }
91 },
92 Err(e) => {
93 let e = e.into();
94 warn!("Error during intent: {e}");
95 return Err(e);
96 }
97 };
98
99 match intent.intention {
100 // If the client is pinging the proxy,
101 // reply with the information below.
102 ClientIntention::Status => {
103 let mut conn = conn.status();
104 loop {
105 match conn.read(Default::default()).await {
106 Ok(p) => match p {
107 ServerboundStatusPacket::StatusRequest(_) => {
108 conn.write(
109 Default::default(),
110 ClientboundStatusResponse {
111 description: PROXY_DESC.into(),
112 favicon: PROXY_FAVICON.clone(),
113 players: PROXY_PLAYERS.clone(),
114 version: PROXY_VERSION.clone(),
115 enforces_secure_chat: PROXY_SECURE_CHAT,
116 contact: None,
117 },
118 )
119 .await?;
120 }
121 ServerboundStatusPacket::PingRequest(p) => {
122 conn.write(
123 Default::default(),
124 ClientboundPongResponse { time: p.time },
125 )
126 .await?;
127 break;
128 }
129 },
130 Err(e) => match *e {
131 ReadPacketError::ConnectionClosed => {
132 break;
133 }
134 e => {
135 warn!("Error during status: {e}");
136 return Err(e.into());
137 }
138 },
139 }
140 }
141 }
142 // If the client intends to join the proxy,
143 // wait for them to send the `Hello` packet to
144 // log their username and uuid, then forward the
145 // connection along to the proxy target.
146 ClientIntention::Login => {
147 let mut conn = conn.login();
148 loop {
149 match conn.read(Default::default()).await {
150 Ok(p) => {
151 if let ServerboundLoginPacket::Hello(hello) = p {
152 info!(
153 "Player \'{0}\' from {1} logging in with uuid: {2}",
154 hello.name,
155 ip.ip(),
156 hello.profile_id.to_string()
157 );
158
159 tokio::spawn(transfer(conn.unwrap()?, intent, hello).map(|r| {
160 if let Err(e) = r {
161 error!("Failed to proxy: {e}");
162 }
163 }));
164
165 break;
166 }
167 }
168 Err(e) => match *e {
169 ReadPacketError::ConnectionClosed => {
170 break;
171 }
172 e => {
173 warn!("Error during login: {e}");
174 return Err(e.into());
175 }
176 },
177 }
178 }
179 }
180 ClientIntention::Transfer => {
181 warn!("Client attempted to join via transfer")
182 }
183 }
184
185 Ok(())
186}Source§impl Connection<ServerboundLoginPacket, ClientboundLoginPacket>
impl Connection<ServerboundLoginPacket, ClientboundLoginPacket>
Sourcepub fn set_compression_threshold(&mut self, threshold: i32)
pub fn set_compression_threshold(&mut self, threshold: i32)
Set our compression threshold, i.e. the maximum size that a packet is allowed to be without getting compressed.
If you set it to less than 0 then compression gets disabled.
Sourcepub fn set_encryption_key(&mut self, key: [u8; 16])
pub fn set_encryption_key(&mut self, key: [u8; 16])
Set the encryption key that is used to encrypt and decrypt packets.
It’s the same for both reading and writing.
Sourcepub fn game(self) -> Connection<ServerboundGamePacket, ClientboundGamePacket>
pub fn game(self) -> Connection<ServerboundGamePacket, ClientboundGamePacket>
Change our state from login to game.
This is the state that’s used when the client is actually in the game.
Sourcepub async fn authenticate(
&self,
username: &str,
public_key: &[u8],
private_key: &[u8; 16],
ip: Option<&str>,
) -> Result<GameProfile, ServerSessionServerError>
pub async fn authenticate( &self, username: &str, public_key: &[u8], private_key: &[u8; 16], ip: Option<&str>, ) -> Result<GameProfile, ServerSessionServerError>
Verify connecting clients have authenticated with Minecraft’s servers.
This must happen after the client sends a ServerboundLoginPacket::Key
packet.
Sourcepub fn config(
self,
) -> Connection<ServerboundConfigPacket, ClientboundConfigPacket>
pub fn config( self, ) -> Connection<ServerboundConfigPacket, ClientboundConfigPacket>
Change our state back to configuration.
Examples found in repository?
217async fn proxy_conn(
218 mut client_conn: Connection<ServerboundLoginPacket, ClientboundLoginPacket>,
219) -> Result<(), Box<dyn Error>> {
220 // resolve TARGET_ADDR
221 let parsed_target_addr = ServerAddr::from_str(TARGET_ADDR).unwrap();
222 let resolved_target_addr = resolve_address(&parsed_target_addr).await?;
223
224 let mut server_conn = Connection::new(&resolved_target_addr).await?;
225
226 let account = if ACCOUNT.contains('@') {
227 Account::microsoft(ACCOUNT).await?
228 } else {
229 Account::offline(ACCOUNT)
230 };
231 println!("got account: {:?}", account);
232
233 server_conn
234 .write(
235 Default::default(),
236 ServerboundIntention {
237 protocol_version: PROTOCOL_VERSION,
238 hostname: parsed_target_addr.host,
239 port: parsed_target_addr.port,
240 intention: ClientIntention::Login,
241 },
242 )
243 .await?;
244 let mut server_conn = server_conn.login();
245
246 // login
247 server_conn
248 .write(
249 Default::default(),
250 ServerboundHello {
251 name: account.username().to_owned(),
252 profile_id: account.uuid(),
253 },
254 )
255 .await?;
256
257 let (server_conn, login_finished) = loop {
258 let packet = server_conn.read(Default::default()).await?;
259
260 println!("got packet: {:?}", packet);
261
262 match packet {
263 ClientboundLoginPacket::Hello(p) => {
264 debug!("Got encryption request");
265 let e = azalea_crypto::encrypt(&p.public_key, &p.challenge).unwrap();
266
267 if let Some(access_token) = account.access_token() {
268 // keep track of the number of times we tried
269 // authenticating so we can give up after too many
270 let mut attempts: usize = 1;
271
272 while let Err(e) = {
273 server_conn
274 .authenticate(&access_token, &account.uuid(), e.secret_key, &p, None)
275 .await
276 } {
277 if attempts >= 2 {
278 // if this is the second attempt and we failed
279 // both times, give up
280 return Err(e.into());
281 }
282 if matches!(
283 e,
284 ClientSessionServerError::InvalidSession
285 | ClientSessionServerError::ForbiddenOperation
286 ) {
287 // uh oh, we got an invalid session and have
288 // to reauthenticate now
289 account.refresh().await?;
290 } else {
291 return Err(e.into());
292 }
293 attempts += 1;
294 }
295 }
296
297 server_conn
298 .write(
299 Default::default(),
300 ServerboundKey {
301 key_bytes: e.encrypted_public_key,
302 encrypted_challenge: e.encrypted_challenge,
303 },
304 )
305 .await?;
306
307 server_conn.set_encryption_key(e.secret_key);
308 }
309 ClientboundLoginPacket::LoginCompression(p) => {
310 debug!("Got compression request {:?}", p.compression_threshold);
311 server_conn.set_compression_threshold(p.compression_threshold);
312 }
313 ClientboundLoginPacket::LoginFinished(p) => {
314 debug!(
315 "Got profile {:?}. handshake is finished and we're now switching to the configuration state",
316 p.game_profile
317 );
318 // server_conn.write(Default::default(),
319 // ServerboundLoginAcknowledged {}).await?;
320 break (server_conn.config(), p);
321 }
322 ClientboundLoginPacket::LoginDisconnect(p) => {
323 error!("Got disconnect {p:?}");
324 return Err("Disconnected".into());
325 }
326 ClientboundLoginPacket::CustomQuery(p) => {
327 debug!("Got custom query {:?}", p);
328 // replying to custom query is done in
329 // packet_handling::login::process_packet_events
330 }
331 ClientboundLoginPacket::CookieRequest(p) => {
332 debug!("Got cookie request {:?}", p);
333
334 server_conn
335 .write(
336 Default::default(),
337 packets::login::ServerboundCookieResponse {
338 key: p.key,
339 // cookies aren't implemented
340 payload: None,
341 },
342 )
343 .await?;
344 }
345 }
346 };
347
348 // give the client the login_finished
349 println!("got the login_finished: {:?}", login_finished);
350 client_conn
351 .write(Default::default(), login_finished)
352 .await?;
353 let client_conn = client_conn.config();
354
355 info!("started direct bridging");
356
357 // bridge packets
358 let listen_raw_reader = client_conn.reader.raw;
359 let listen_raw_writer = client_conn.writer.raw;
360
361 let target_raw_reader = server_conn.reader.raw;
362 let target_raw_writer = server_conn.writer.raw;
363
364 let packet_logs_txt = Arc::new(tokio::sync::Mutex::new(
365 File::create("combined.txt").await.unwrap(),
366 ));
367
368 let packet_logs_txt_clone = packet_logs_txt.clone();
369 let copy_listen_to_target = tokio::spawn(async move {
370 let mut listen_raw_reader = listen_raw_reader;
371 let mut target_raw_writer = target_raw_writer;
372
373 let packet_logs_txt = packet_logs_txt_clone;
374
375 let mut serverbound_parsed_txt = File::create("serverbound.txt").await.unwrap();
376
377 loop {
378 let packet = match listen_raw_reader.read().await {
379 Ok(p) => p,
380 Err(e) => {
381 error!("Error reading packet from listen: {e}");
382 return;
383 }
384 };
385
386 // decode as a game packet
387 let decoded_packet = azalea_protocol::read::deserialize_packet::<ServerboundGamePacket>(
388 Default::default(),
389 &mut Cursor::new(&packet),
390 );
391
392 if let Ok(decoded_packet) = decoded_packet {
393 let timestamp = chrono::Utc::now();
394 let _ = serverbound_parsed_txt
395 .write_all(format!("{timestamp} {:?}\n", decoded_packet).as_bytes())
396 .await;
397 let _ = packet_logs_txt
398 .lock()
399 .await
400 .write_all(format!("{timestamp} <- {:?}\n", decoded_packet).as_bytes())
401 .await;
402 }
403
404 match target_raw_writer.write(Default::default(), &packet).await {
405 Ok(_) => {}
406 Err(e) => {
407 error!("Error writing packet to target: {e}");
408 return;
409 }
410 }
411 }
412 });
413
414 // write to clientbound.txt in a separate task so it doesn't block receiving
415 // packets
416 let (clientbound_tx, mut clientbound_rx) = tokio::sync::mpsc::unbounded_channel::<Box<[u8]>>();
417 let copy_clientbound_to_file = tokio::spawn(async move {
418 let mut clientbound_parsed_txt = File::create("clientbound.txt").await.unwrap();
419
420 loop {
421 let Some(packet) = clientbound_rx.recv().await else {
422 return;
423 };
424
425 // decode as a game packet
426 let decoded_packet = azalea_protocol::read::deserialize_packet::<ClientboundGamePacket>(
427 Default::default(),
428 &mut Cursor::new(&packet),
429 );
430
431 if let Ok(decoded_packet) = decoded_packet {
432 let timestamp = chrono::Utc::now();
433 let _ = clientbound_parsed_txt
434 .write_all(format!("{timestamp} {decoded_packet:?}\n").as_bytes())
435 .await;
436 let _ = packet_logs_txt
437 .lock()
438 .await
439 .write_all(format!("{timestamp} -> {decoded_packet:?}\n").as_bytes())
440 .await;
441 }
442 }
443 });
444
445 let copy_remote_to_local = tokio::spawn(async move {
446 let mut target_raw_reader = target_raw_reader;
447 let mut listen_raw_writer = listen_raw_writer;
448
449 loop {
450 let packet = match target_raw_reader.read().await {
451 Ok(p) => p,
452 Err(e) => {
453 error!("Error reading packet from target: {e}");
454 return;
455 }
456 };
457
458 clientbound_tx.send(packet.clone()).unwrap();
459
460 match listen_raw_writer.write(Default::default(), &packet).await {
461 Ok(_) => {}
462 Err(e) => {
463 error!("Error writing packet to listen: {e}");
464 return;
465 }
466 }
467 }
468 });
469
470 tokio::try_join!(
471 copy_listen_to_target,
472 copy_remote_to_local,
473 copy_clientbound_to_file
474 )?;
475
476 Ok(())
477}Source§impl Connection<ServerboundConfigPacket, ClientboundConfigPacket>
impl Connection<ServerboundConfigPacket, ClientboundConfigPacket>
Sourcepub fn game(self) -> Connection<ServerboundGamePacket, ClientboundGamePacket>
pub fn game(self) -> Connection<ServerboundGamePacket, ClientboundGamePacket>
Change our state from configuration to game.
This is the state that’s used when the client is actually in the world.
Source§impl Connection<ClientboundConfigPacket, ServerboundConfigPacket>
impl Connection<ClientboundConfigPacket, ServerboundConfigPacket>
Sourcepub fn game(self) -> Connection<ClientboundGamePacket, ServerboundGamePacket>
pub fn game(self) -> Connection<ClientboundGamePacket, ServerboundGamePacket>
Change our state from configuration to game.
This is the state that’s used when the client is actually in the world.
Source§impl Connection<ClientboundGamePacket, ServerboundGamePacket>
impl Connection<ClientboundGamePacket, ServerboundGamePacket>
Sourcepub fn config(
self,
) -> Connection<ClientboundConfigPacket, ServerboundConfigPacket>
pub fn config( self, ) -> Connection<ClientboundConfigPacket, ServerboundConfigPacket>
Change our state back to configuration.
Source§impl Connection<ServerboundGamePacket, ClientboundGamePacket>
impl Connection<ServerboundGamePacket, ClientboundGamePacket>
Sourcepub fn config(
self,
) -> Connection<ServerboundConfigPacket, ClientboundConfigPacket>
pub fn config( self, ) -> Connection<ServerboundConfigPacket, ClientboundConfigPacket>
Change our state back to configuration.
Source§impl<R1, W1> Connection<R1, W1>
impl<R1, W1> Connection<R1, W1>
Sourcepub fn from<R2, W2>(connection: Connection<R1, W1>) -> Connection<R2, W2>
pub fn from<R2, W2>(connection: Connection<R1, W1>) -> Connection<R2, W2>
Creates a Connection of a type from a Connection of another type.
Useful for servers or custom packets.
Sourcepub fn wrap(stream: TcpStream) -> Connection<R1, W1>
pub fn wrap(stream: TcpStream) -> Connection<R1, W1>
Convert an existing TcpStream into a Connection. Useful for servers.
Examples found in repository?
100async fn handle_connection(stream: TcpStream) -> eyre::Result<()> {
101 stream.set_nodelay(true)?;
102 let ip = stream.peer_addr()?;
103 let mut conn: Connection<ServerboundHandshakePacket, ClientboundHandshakePacket> =
104 Connection::wrap(stream);
105
106 // The first packet sent from a client is the intent packet.
107 // This specifies whether the client is pinging
108 // the server or is going to join the game.
109 let intent = match conn.read(Default::default()).await {
110 Ok(packet) => match packet {
111 ServerboundHandshakePacket::Intention(packet) => {
112 info!(
113 "New connection from {}, hostname {:?}:{}, version {}, {:?}",
114 ip.ip(),
115 packet.hostname,
116 packet.port,
117 packet.protocol_version,
118 packet.intention
119 );
120 packet
121 }
122 },
123 Err(e) => {
124 let e = e.into();
125 warn!("Error during intent: {e}");
126 return Err(e);
127 }
128 };
129
130 match intent.intention {
131 // If the client is pinging the proxy, reply with the information below.
132 ClientIntention::Status => {
133 let mut conn = conn.status();
134 loop {
135 match conn.read(Default::default()).await {
136 Ok(p) => match p {
137 ServerboundStatusPacket::StatusRequest(_) => {
138 conn.write(
139 Default::default(),
140 ClientboundStatusResponse {
141 description: PROXY_DESC.into(),
142 favicon: PROXY_FAVICON.clone(),
143 players: PROXY_PLAYERS.clone(),
144 version: PROXY_VERSION.clone(),
145 enforces_secure_chat: PROXY_SECURE_CHAT,
146 contact: None,
147 },
148 )
149 .await?;
150 }
151 ServerboundStatusPacket::PingRequest(p) => {
152 conn.write(
153 Default::default(),
154 ClientboundPongResponse { time: p.time },
155 )
156 .await?;
157 break;
158 }
159 },
160 Err(e) => match *e {
161 ReadPacketError::ConnectionClosed => {
162 break;
163 }
164 e => {
165 warn!("Error during status: {e}");
166 return Err(e.into());
167 }
168 },
169 }
170 }
171 }
172 // If the client intends to join the proxy, wait for them to send the
173 // `Hello` packet to log their username and uuid, then start proxying
174 // their connection.
175 ClientIntention::Login => {
176 let mut conn = conn.login();
177 loop {
178 match conn.read(Default::default()).await {
179 Ok(p) => {
180 if let ServerboundLoginPacket::Hello(hello) = p {
181 info!(
182 "Player \'{}\' from {} logging in with uuid: {}",
183 hello.name,
184 ip.ip(),
185 hello.profile_id.to_string()
186 );
187
188 tokio::spawn(proxy_conn(conn).map(|r| {
189 if let Err(e) = r {
190 error!("Failed to proxy: {e}");
191 }
192 }));
193
194 break;
195 }
196 }
197 Err(e) => match *e {
198 ReadPacketError::ConnectionClosed => {
199 break;
200 }
201 e => {
202 warn!("Error during login: {e}");
203 return Err(e.into());
204 }
205 },
206 }
207 }
208 }
209 ClientIntention::Transfer => {
210 warn!("Client attempted to join via transfer")
211 }
212 }
213
214 Ok(())
215}More examples
69async fn handle_connection(stream: TcpStream) -> eyre::Result<()> {
70 stream.set_nodelay(true)?;
71 let ip = stream.peer_addr()?;
72 let mut conn: Connection<ServerboundHandshakePacket, ClientboundHandshakePacket> =
73 Connection::wrap(stream);
74
75 // The first packet sent from a client is the intent packet.
76 // This specifies whether the client is pinging
77 // the server or is going to join the game.
78 let intent = match conn.read(Default::default()).await {
79 Ok(packet) => match packet {
80 ServerboundHandshakePacket::Intention(packet) => {
81 info!(
82 "New connection from {}, hostname {:?}:{}, version {}, {:?}",
83 ip.ip(),
84 packet.hostname,
85 packet.port,
86 packet.protocol_version,
87 packet.intention
88 );
89 packet
90 }
91 },
92 Err(e) => {
93 let e = e.into();
94 warn!("Error during intent: {e}");
95 return Err(e);
96 }
97 };
98
99 match intent.intention {
100 // If the client is pinging the proxy,
101 // reply with the information below.
102 ClientIntention::Status => {
103 let mut conn = conn.status();
104 loop {
105 match conn.read(Default::default()).await {
106 Ok(p) => match p {
107 ServerboundStatusPacket::StatusRequest(_) => {
108 conn.write(
109 Default::default(),
110 ClientboundStatusResponse {
111 description: PROXY_DESC.into(),
112 favicon: PROXY_FAVICON.clone(),
113 players: PROXY_PLAYERS.clone(),
114 version: PROXY_VERSION.clone(),
115 enforces_secure_chat: PROXY_SECURE_CHAT,
116 contact: None,
117 },
118 )
119 .await?;
120 }
121 ServerboundStatusPacket::PingRequest(p) => {
122 conn.write(
123 Default::default(),
124 ClientboundPongResponse { time: p.time },
125 )
126 .await?;
127 break;
128 }
129 },
130 Err(e) => match *e {
131 ReadPacketError::ConnectionClosed => {
132 break;
133 }
134 e => {
135 warn!("Error during status: {e}");
136 return Err(e.into());
137 }
138 },
139 }
140 }
141 }
142 // If the client intends to join the proxy,
143 // wait for them to send the `Hello` packet to
144 // log their username and uuid, then forward the
145 // connection along to the proxy target.
146 ClientIntention::Login => {
147 let mut conn = conn.login();
148 loop {
149 match conn.read(Default::default()).await {
150 Ok(p) => {
151 if let ServerboundLoginPacket::Hello(hello) = p {
152 info!(
153 "Player \'{0}\' from {1} logging in with uuid: {2}",
154 hello.name,
155 ip.ip(),
156 hello.profile_id.to_string()
157 );
158
159 tokio::spawn(transfer(conn.unwrap()?, intent, hello).map(|r| {
160 if let Err(e) = r {
161 error!("Failed to proxy: {e}");
162 }
163 }));
164
165 break;
166 }
167 }
168 Err(e) => match *e {
169 ReadPacketError::ConnectionClosed => {
170 break;
171 }
172 e => {
173 warn!("Error during login: {e}");
174 return Err(e.into());
175 }
176 },
177 }
178 }
179 }
180 ClientIntention::Transfer => {
181 warn!("Client attempted to join via transfer")
182 }
183 }
184
185 Ok(())
186}
187
188async fn transfer(
189 mut inbound: TcpStream,
190 intent: ServerboundIntention,
191 hello: ServerboundHello,
192) -> Result<(), Box<dyn Error>> {
193 let outbound = TcpStream::connect(PROXY_ADDR).await?;
194 let name = hello.name.clone();
195 outbound.set_nodelay(true)?;
196
197 // Repeat the intent and hello packet
198 // received earlier to the proxy target
199 let mut outbound_conn: Connection<ClientboundHandshakePacket, ServerboundHandshakePacket> =
200 Connection::wrap(outbound);
201 outbound_conn.write(Default::default(), intent).await?;
202
203 let mut outbound_conn = outbound_conn.login();
204 outbound_conn.write(Default::default(), hello).await?;
205
206 let mut outbound = outbound_conn.unwrap()?;
207
208 // Split the incoming and outgoing connections in
209 // halves and handle each pair on separate threads.
210 let (mut ri, mut wi) = inbound.split();
211 let (mut ro, mut wo) = outbound.split();
212
213 let client_to_server = async {
214 io::copy(&mut ri, &mut wo).await?;
215 wo.shutdown().await
216 };
217
218 let server_to_client = async {
219 io::copy(&mut ro, &mut wi).await?;
220 wi.shutdown().await
221 };
222
223 tokio::try_join!(client_to_server, server_to_client)?;
224 info!("Player \'{name}\' left the game");
225
226 Ok(())
227}Sourcepub fn unwrap(self) -> Result<TcpStream, ReuniteError>
pub fn unwrap(self) -> Result<TcpStream, ReuniteError>
Convert from a Connection into a TcpStream. Useful for servers.
Examples found in repository?
69async fn handle_connection(stream: TcpStream) -> eyre::Result<()> {
70 stream.set_nodelay(true)?;
71 let ip = stream.peer_addr()?;
72 let mut conn: Connection<ServerboundHandshakePacket, ClientboundHandshakePacket> =
73 Connection::wrap(stream);
74
75 // The first packet sent from a client is the intent packet.
76 // This specifies whether the client is pinging
77 // the server or is going to join the game.
78 let intent = match conn.read(Default::default()).await {
79 Ok(packet) => match packet {
80 ServerboundHandshakePacket::Intention(packet) => {
81 info!(
82 "New connection from {}, hostname {:?}:{}, version {}, {:?}",
83 ip.ip(),
84 packet.hostname,
85 packet.port,
86 packet.protocol_version,
87 packet.intention
88 );
89 packet
90 }
91 },
92 Err(e) => {
93 let e = e.into();
94 warn!("Error during intent: {e}");
95 return Err(e);
96 }
97 };
98
99 match intent.intention {
100 // If the client is pinging the proxy,
101 // reply with the information below.
102 ClientIntention::Status => {
103 let mut conn = conn.status();
104 loop {
105 match conn.read(Default::default()).await {
106 Ok(p) => match p {
107 ServerboundStatusPacket::StatusRequest(_) => {
108 conn.write(
109 Default::default(),
110 ClientboundStatusResponse {
111 description: PROXY_DESC.into(),
112 favicon: PROXY_FAVICON.clone(),
113 players: PROXY_PLAYERS.clone(),
114 version: PROXY_VERSION.clone(),
115 enforces_secure_chat: PROXY_SECURE_CHAT,
116 contact: None,
117 },
118 )
119 .await?;
120 }
121 ServerboundStatusPacket::PingRequest(p) => {
122 conn.write(
123 Default::default(),
124 ClientboundPongResponse { time: p.time },
125 )
126 .await?;
127 break;
128 }
129 },
130 Err(e) => match *e {
131 ReadPacketError::ConnectionClosed => {
132 break;
133 }
134 e => {
135 warn!("Error during status: {e}");
136 return Err(e.into());
137 }
138 },
139 }
140 }
141 }
142 // If the client intends to join the proxy,
143 // wait for them to send the `Hello` packet to
144 // log their username and uuid, then forward the
145 // connection along to the proxy target.
146 ClientIntention::Login => {
147 let mut conn = conn.login();
148 loop {
149 match conn.read(Default::default()).await {
150 Ok(p) => {
151 if let ServerboundLoginPacket::Hello(hello) = p {
152 info!(
153 "Player \'{0}\' from {1} logging in with uuid: {2}",
154 hello.name,
155 ip.ip(),
156 hello.profile_id.to_string()
157 );
158
159 tokio::spawn(transfer(conn.unwrap()?, intent, hello).map(|r| {
160 if let Err(e) = r {
161 error!("Failed to proxy: {e}");
162 }
163 }));
164
165 break;
166 }
167 }
168 Err(e) => match *e {
169 ReadPacketError::ConnectionClosed => {
170 break;
171 }
172 e => {
173 warn!("Error during login: {e}");
174 return Err(e.into());
175 }
176 },
177 }
178 }
179 }
180 ClientIntention::Transfer => {
181 warn!("Client attempted to join via transfer")
182 }
183 }
184
185 Ok(())
186}
187
188async fn transfer(
189 mut inbound: TcpStream,
190 intent: ServerboundIntention,
191 hello: ServerboundHello,
192) -> Result<(), Box<dyn Error>> {
193 let outbound = TcpStream::connect(PROXY_ADDR).await?;
194 let name = hello.name.clone();
195 outbound.set_nodelay(true)?;
196
197 // Repeat the intent and hello packet
198 // received earlier to the proxy target
199 let mut outbound_conn: Connection<ClientboundHandshakePacket, ServerboundHandshakePacket> =
200 Connection::wrap(outbound);
201 outbound_conn.write(Default::default(), intent).await?;
202
203 let mut outbound_conn = outbound_conn.login();
204 outbound_conn.write(Default::default(), hello).await?;
205
206 let mut outbound = outbound_conn.unwrap()?;
207
208 // Split the incoming and outgoing connections in
209 // halves and handle each pair on separate threads.
210 let (mut ri, mut wi) = inbound.split();
211 let (mut ro, mut wo) = outbound.split();
212
213 let client_to_server = async {
214 io::copy(&mut ri, &mut wo).await?;
215 wo.shutdown().await
216 };
217
218 let server_to_client = async {
219 io::copy(&mut ro, &mut wi).await?;
220 wi.shutdown().await
221 };
222
223 tokio::try_join!(client_to_server, server_to_client)?;
224 info!("Player \'{name}\' left the game");
225
226 Ok(())
227}Auto Trait Implementations§
impl<R, W> Forget for Connection<R, W>
impl<R, W> Freeze for Connection<R, W>where
*const ArcInner<TcpStream> is !null: Freeze,
PhantomData<ArcInner<TcpStream>>: Freeze,
*const u8 is !null: Freeze,
PhantomData<u8>: Freeze,
[u8; 16]: Freeze,
PhantomData<R>: Freeze,
PhantomData<W>: Freeze,
impl<R, W> Move for Connection<R, W>
impl<R, W> RefUnwindSafe for Connection<R, W>where
Atomic<usize>: RefUnwindSafe,
PollEvented<TcpStream>: RefUnwindSafe,
[u8; 16]: RefUnwindSafe,
R: RefUnwindSafe,
W: RefUnwindSafe,
impl<R, W> Send for Connection<R, W>
impl<R, W> Sync for Connection<R, W>
impl<R, W> Unpin for Connection<R, W>
impl<R, W> UnsafeUnpin for Connection<R, W>where
*const ArcInner<TcpStream> is !null: UnsafeUnpin,
PhantomData<ArcInner<TcpStream>>: UnsafeUnpin,
*const u8 is !null: UnsafeUnpin,
PhantomData<u8>: UnsafeUnpin,
[u8; 16]: UnsafeUnpin,
PhantomData<R>: UnsafeUnpin,
PhantomData<W>: UnsafeUnpin,
impl<R, W> UnwindSafe for Connection<R, W>where
Arc<TcpStream>: UnwindSafe,
RawVecInner: UnwindSafe,
[u8; 16]: UnwindSafe,
R: UnwindSafe,
W: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
impl<T> ConditionalSend for Twhere
T: Send,
§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be
downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further
downcast into Rc<ConcreteType> where ConcreteType implements Trait.§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.§impl<T> DowncastSend for T
impl<T> DowncastSend for T
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<A, B> Interchangeable<A> for B
impl<A, B> Interchangeable<A> for B
fn interchangeable_into(self) -> A
fn interchangeable_from(other: A) -> B
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more