Skip to content

Commit

Permalink
feat(net): set user location on login
Browse files Browse the repository at this point in the history
  • Loading branch information
bigspeedfpv committed Nov 6, 2024
1 parent dce9ca3 commit 093d47f
Show file tree
Hide file tree
Showing 9 changed files with 246 additions and 39 deletions.
26 changes: 26 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ serde_json = "1.0.132"
sha2 = "0.10.8"
thiserror = "1.0.65"
tokio = { version = "1.41.0", features = ["full"] }
tokio-util = "0.7.12"
tracing = { version = "0.1.40", features = ["max_level_trace", "release_max_level_warn"] }
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
uuid = "1.11.0"
Expand Down
7 changes: 6 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,14 @@
* <https://www.gnu.org/licenses/>.
*/

use std::sync::Arc;
use std::{
sync::{Arc, LazyLock},
time::Duration,
};

use color_eyre::eyre::Result;
use server::Server;
use tokio_util::sync::CancellationToken;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};

#[macro_use]
Expand Down Expand Up @@ -80,6 +84,7 @@ async fn main() -> Result<()> {

// TODO: more graceful shutdown?
tokio::signal::ctrl_c().await?;
state.shutdown_token.cancel();

Ok(())
}
41 changes: 37 additions & 4 deletions src/net/player.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,19 @@ use tokio::{
sync::{Mutex, OwnedSemaphorePermit, RwLock},
time::{self, timeout},
};
use uuid::Uuid;

use crate::{
protocol::{
datatypes::{Bounded, VarInt},
packets::{
login::*,
play::{ConfirmTeleportS, Gamemode, LoginPlayC, SynchronisePositionC},
play::{
ConfirmTeleportS, Gamemode, LoginPlayC, PlayerInfoUpdateC, PlayerStatus,
SynchronisePositionC,
},
},
PacketState,
PacketState, Property,
},
CrawlState,
};
Expand All @@ -56,6 +60,7 @@ pub struct Player {
crawlstate: CrawlState,
packet_state: RwLock<PacketState>,

uuid: RwLock<Option<Uuid>>,
tp_state: Mutex<TeleportState>,
}

Expand All @@ -80,6 +85,7 @@ impl SharedPlayer {
id,
io: Mutex::new(NetIo::new(connection)),
_permit: permit,
uuid: RwLock::new(None),

crawlstate,
packet_state: RwLock::new(PacketState::Handshaking),
Expand Down Expand Up @@ -142,11 +148,16 @@ impl SharedPlayer {
let next_state = p.next_state;
drop(io);

let mut s = self.0.packet_state.write().await;
match next_state {
PacketState::Status => {
*s = PacketState::Status;
drop(s);
self.handle_status().await?;
}
PacketState::Login => {
*s = PacketState::Login;
drop(s);
self.login().await?;
}
s => unimplemented!("state {:#?} unimplemented after handshake", s),
Expand Down Expand Up @@ -208,6 +219,11 @@ impl SharedPlayer {
strict_error_handling: false,
};

{
let mut own_uuid = self.0.uuid.write().await;
*own_uuid = Some(uuid);
}

io.tx(&success).await?;
io.rx::<LoginAckS>().await?;

Expand Down Expand Up @@ -303,17 +319,29 @@ impl SharedPlayer {
Err(why)?;
}
Err(why) => {
warn!("Spawning player {} failed: {why}", self.0.id);
warn!("Spawning player {} timed out: {why}", self.0.id);
Err(why)?;
}
}

let player_add = PlayerInfoUpdateC {
players: &[PlayerStatus::for_player(self.uuid().await).add_player("AFK", &[])],
};
io.tx(&player_add).await?;

// FIXME: GROSS LOL?????? this should(?) change ownership of the player to the server
// thread but realistically who knows burhhhh
state.player_send.send(self.clone()).await?;

loop {
self.handle_packets().await?;
tokio::select! {
_ = self.handle_packets() => {
time::sleep(Duration::from_millis(50)).await;
}
_ = state.shutdown_token.cancelled() => {
return Ok(());
}
}
}
}

Expand All @@ -331,6 +359,11 @@ impl SharedPlayer {
},
}
}

async fn uuid(&self) -> Uuid {
let uuid = self.0.uuid.read().await;
uuid.expect("uuid() called on uninitialized player - only call this after login!")
}
}

#[derive(Debug, Error)]
Expand Down
24 changes: 23 additions & 1 deletion src/protocol/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,11 @@ pub mod packets {

pub mod play {
mod login;
mod status;
mod teleport;

pub use login::*;
pub use status::*;
pub use teleport::*;
}
}
Expand All @@ -60,7 +62,7 @@ mod encoder;
use std::{fmt::Debug, io::Write};

use color_eyre::eyre::{Context, Result};
use datatypes::VarInt;
use datatypes::{Bounded, VarInt};
pub use decoder::*;
pub use encoder::*;
use thiserror::Error;
Expand Down Expand Up @@ -127,3 +129,23 @@ pub trait ClientboundPacket: Packet + Encode + Debug {
}
}
impl<P> ClientboundPacket for P where P: Packet + Encode + Debug {}

#[derive(Debug)]
pub struct Property<'a> {
name: Bounded<&'a str, 32767>,
value: Bounded<&'a str, 32767>,
signature: Option<Bounded<&'a str, 32767>>,
}

impl Encode for Property<'_> {
fn encode(&self, mut w: impl std::io::Write) -> Result<()> {
let signed = self.signature.is_some();

self.name.encode(&mut w)?;
self.value.encode(&mut w)?;
signed.encode(&mut w)?;
self.signature.encode(&mut w)?;

Ok(())
}
}
24 changes: 2 additions & 22 deletions src/protocol/packets/login/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@
* <https://www.gnu.org/licenses/>.
*/


use color_eyre::eyre::Result;
use uuid::Uuid;

use crate::protocol::{
datatypes::{Bounded, Bytes, VarInt}, Decode, Encode, Packet,
datatypes::{Bounded, Bytes, VarInt},
Decode, Encode, Packet, Property,
};

#[derive(Debug)]
Expand Down Expand Up @@ -52,26 +52,6 @@ pub struct LoginSuccessC<'a> {
pub strict_error_handling: bool,
}

#[derive(Debug)]
pub struct Property<'a> {
name: Bounded<&'a str, 32767>,
value: Bounded<&'a str, 32767>,
signature: Option<Bounded<&'a str, 32767>>,
}

impl Encode for Property<'_> {
fn encode(&self, mut w: impl std::io::Write) -> Result<()> {
let signed = self.signature.is_some();

self.name.encode(&mut w)?;
self.value.encode(&mut w)?;
signed.encode(&mut w)?;
self.signature.encode(&mut w)?;

Ok(())
}
}

impl Packet for LoginSuccessC<'_> {
const ID: i32 = 0x02;
}
Expand Down
Loading

0 comments on commit 093d47f

Please sign in to comment.