1use std::{
18 error::Error,
19 io::Cursor,
20 str::FromStr,
21 sync::{Arc, LazyLock},
22};
23
24use azalea_auth::{AuthOpts, sessionserver::ClientSessionServerError};
25use azalea_protocol::{
26 address::ServerAddr,
27 connect::Connection,
28 packets::{
29 self, ClientIntention, PROTOCOL_VERSION, VERSION_NAME,
30 game::{ClientboundGamePacket, ServerboundGamePacket},
31 handshake::{
32 ClientboundHandshakePacket, ServerboundHandshakePacket,
33 s_intention::ServerboundIntention,
34 },
35 login::{
36 ClientboundLoginPacket, ServerboundKey, ServerboundLoginPacket,
37 s_hello::ServerboundHello,
38 },
39 status::{
40 ServerboundStatusPacket,
41 c_pong_response::ClientboundPongResponse,
42 c_status_response::{ClientboundStatusResponse, Players, Version},
43 },
44 },
45 read::ReadPacketError,
46 resolver::resolve_address,
47};
48use futures::FutureExt;
49use parking_lot::Mutex;
50use tokio::{
51 fs::File,
52 io::AsyncWriteExt,
53 net::{TcpListener, TcpStream},
54};
55use tracing::{Level, debug, error, info, warn};
56use uuid::Uuid;
57
58const LISTEN_ADDR: &str = "127.0.0.1:25566";
60const TARGET_ADDR: &str = "localhost";
62const ACCOUNT: &str = "example@example.com";
65
66const PROXY_DESC: &str = "An Azalea Minecraft Proxy";
67static PROXY_FAVICON: LazyLock<Option<String>> = LazyLock::new(|| None);
69static PROXY_VERSION: LazyLock<Option<Version>> = LazyLock::new(|| {
70 Some(Version {
71 name: VERSION_NAME.to_string(),
72 protocol: PROTOCOL_VERSION,
73 })
74});
75const PROXY_PLAYERS: Option<Players> = Some(Players {
76 max: 1,
77 online: 0,
78 sample: Vec::new(),
79});
80const PROXY_SECURE_CHAT: Option<bool> = Some(false);
81
82#[tokio::main]
83async fn main() -> eyre::Result<()> {
84 tracing_subscriber::fmt()
85 .with_max_level(Level::DEBUG)
86 .init();
87
88 let listener = TcpListener::bind(LISTEN_ADDR).await?;
90
91 info!("Listening on {LISTEN_ADDR}, proxying to {TARGET_ADDR}");
92
93 loop {
94 let (stream, _) = listener.accept().await?;
96 tokio::spawn(handle_connection(stream));
97 }
98}
99
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 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 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 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 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 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 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 return Err(e.into());
281 }
282 if matches!(
283 e,
284 ClientSessionServerError::InvalidSession
285 | ClientSessionServerError::ForbiddenOperation
286 ) {
287 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 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 }
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 payload: None,
341 },
342 )
343 .await?;
344 }
345 }
346 };
347
348 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 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 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 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 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}
478
479#[derive(Debug)]
480enum Account {
481 Microsoft {
482 cache_key: String,
483 username: String,
484 uuid: Uuid,
485 access_token: Mutex<String>,
486 },
488 Offline {
489 username: String,
490 },
491}
492impl Account {
493 async fn microsoft(cache_key: &str) -> Result<Self, azalea_auth::AuthError> {
494 let minecraft_dir = minecraft_folder_path::minecraft_dir().unwrap_or_else(|| {
495 panic!(
496 "No {} environment variable found",
497 minecraft_folder_path::home_env_var()
498 )
499 });
500 let cache_file = minecraft_dir.join("azalea-auth.json");
501
502 let auth_result = azalea_auth::auth(
503 cache_key,
504 AuthOpts {
505 cache_file: Some(cache_file),
506 ..Default::default()
507 },
508 )
509 .await?;
510
511 Ok(Self::Microsoft {
512 cache_key: cache_key.to_owned(),
513 username: auth_result.profile.name,
514 uuid: auth_result.profile.id,
515 access_token: Mutex::new(auth_result.access_token),
516 })
518 }
519 fn offline(username: &str) -> Self {
520 Self::Offline {
521 username: username.to_owned(),
522 }
523 }
524
525 async fn refresh(&self) -> Result<(), azalea_auth::AuthError> {
526 match self {
527 Account::Microsoft {
528 cache_key,
529 access_token,
530 ..
531 } => {
532 let acc = Account::microsoft(cache_key).await?;
533 *access_token.lock() = acc.access_token().unwrap();
534 }
535 Account::Offline { .. } => {}
536 }
537
538 Ok(())
539 }
540
541 fn username(&self) -> &str {
542 match self {
543 Account::Microsoft { username, .. } => username,
544 Account::Offline { username } => username,
545 }
546 }
547 fn uuid(&self) -> Uuid {
548 match self {
549 Account::Microsoft { uuid, .. } => *uuid,
550 Account::Offline { username } => azalea_crypto::offline::generate_uuid(username),
551 }
552 }
553 fn access_token(&self) -> Option<String> {
554 match self {
555 Account::Microsoft { access_token, .. } => Some(access_token.lock().to_owned()),
556 Account::Offline { .. } => None,
557 }
558 }
559}