diff --git a/polariton_auth/src/handshake.rs b/polariton_auth/src/handshake.rs index 3078412..1eb8868 100644 --- a/polariton_auth/src/handshake.rs +++ b/polariton_auth/src/handshake.rs @@ -1,4 +1,4 @@ -use polariton::packet::{Packet, Message, StandardMessage, Data, Cryptographer}; +use polariton::packet::{Packet, Message, StandardMessage, Data}; use polariton::operation::{Typed, ParameterTable, OperationResponse}; #[derive(Debug)] @@ -153,7 +153,7 @@ impl , E> Handshake> { const AUTH_REQUEST_CODE: u8 = 230; const USER_ID_KEY: u8 = 225; const NICKNAME_KEY: u8 = 225; - pub fn authenticate<'a>(mut self, packet: &'a Packet, crypto: &dyn Cryptographer) -> Result, AuthError>> { + pub fn authenticate<'a>(mut self, packet: &'a Packet, serdes_ctx: &polariton::packet::SerdesContext<(), polariton::serdes::NoCustomSerdes>) -> Result, AuthError>> { if let Packet::Packet(packet) = &packet { if let Message::Standard(conn) = &packet.message { if let Data::OpReq(req) = &conn.data { @@ -172,8 +172,6 @@ impl , E> Handshake> { params_resp.insert(Self::USER_ID_KEY, user_id.to_owned()); params_resp.insert(Self::NICKNAME_KEY, user_id.to_owned()); } - let serdes_ctx = Default::default(); - let serdes_ctx = polariton::packet::SerdesContext::new(&serdes_ctx, crypto); return Ok(Packet::from_message( Message::Standard( StandardMessage { @@ -185,7 +183,7 @@ impl , E> Handshake> { params: params_resp.into(), }) }.encrypt(conn.is_encrypted()) - ), packet.header.channel, true, &serdes_ctx).unwrap()); + ), packet.header.channel, true, serdes_ctx).unwrap()); } } } diff --git a/rc_chat/src/main.rs b/rc_chat/src/main.rs index f36db46..900495a 100644 --- a/rc_chat/src/main.rs +++ b/rc_chat/src/main.rs @@ -1,5 +1,4 @@ mod cli; -mod state; use polariton_auth::Handshake; use tokio::net; @@ -44,11 +43,11 @@ async fn process_socket(mut socket: net::TcpStream, address: std::net::SocketAdd return; } }; - let sock_state = state::State::new(enc); - while let Ok(packet) = polariton_server::utils::receive_packet_async(&mut socket, &sock_state.serdes_ctx()).await { + let ctx = polariton::packet::SerdesContext::from_boxed(Default::default(), enc); + while let Ok(packet) = polariton_server::utils::receive_packet_async(&mut socket, &ctx).await { match packet { Packet::Ping(ping) => { - polariton_server::utils::handle_ping_async(ping, &mut socket, &sock_state.serdes_ctx()).await.unwrap_or_default(); + polariton_server::utils::handle_ping_async(ping, &mut socket, &ctx).await.unwrap_or_default(); }, Packet::Packet(packet) => log::warn!("Not handling packet {:?}", packet), } @@ -107,7 +106,7 @@ async fn do_connect_handshake( socket: &mut net::TcpStream, game_server_name: &str, game_server_url: &str, -) -> Option { +) -> Option> { let handshake = Handshake::new(APP_ID); // connect log::debug!("(connect) Handling first packet"); @@ -168,7 +167,7 @@ async fn do_connect_handshake( // pre-auth let handshake = handshake.with_auth(AuthImpl); let op_ctx = polariton::serdes::SerdesContext::default(); - let ctx = polariton::packet::SerdesContext::new(&op_ctx, &crypto); + let ctx = polariton::packet::SerdesContext::new(op_ctx, crypto); // authenticate log::debug!("(connect) Handling third packet"); let mut packet3 = match polariton_server::utils::receive_packet_async(socket, &ctx).await { @@ -188,7 +187,7 @@ async fn do_connect_handshake( } }; } - let to_send = match handshake.authenticate(&packet3, &crypto) { + let to_send = match handshake.authenticate(&packet3, &ctx) { Ok(x) => x, Err(h) => match h.extra { polariton_auth::AuthError::Validation(e) => { @@ -257,5 +256,5 @@ async fn do_connect_handshake( } } - Some(crypto) + Some(ctx.into_crypto()) } diff --git a/rc_chat/src/state.rs b/rc_chat/src/state.rs deleted file mode 100644 index 9d6664f..0000000 --- a/rc_chat/src/state.rs +++ /dev/null @@ -1,17 +0,0 @@ -const SERDES_SERDES_CTX_REF: &'static polariton::serdes::SerdesContext<(), polariton::serdes::NoCustomSerdes> = &polariton::serdes::SerdesContext::default_const(); - -pub struct State { - pub crypto: polariton_auth::CryptoImpl, -} - -impl State { - pub fn new(c: polariton_auth::CryptoImpl) -> Self { - Self { - crypto: c, - } - } - - pub fn serdes_ctx(&self) -> polariton::packet::SerdesContext<'_, (), polariton::serdes::NoCustomSerdes> { - polariton::packet::SerdesContext::new(SERDES_SERDES_CTX_REF, &self.crypto) - } -} diff --git a/rc_chat_room/src/main.rs b/rc_chat_room/src/main.rs index 4d18ac1..183c01c 100644 --- a/rc_chat_room/src/main.rs +++ b/rc_chat_room/src/main.rs @@ -18,7 +18,7 @@ async fn main() -> std::io::Result<()> { let args = cli::CliArgs::get(); log::debug!("Got cli args {:?}", args); - let server = std::sync::Arc::new(polariton_server::Server::new(operations::handler())); + let server = std::sync::Arc::new(polariton_server::Server::new(operations::handler(), polariton_server::events::EventsHandler::new())); let ip_addr: std::net::IpAddr = args.ip.parse().expect("Invalid IP address"); @@ -27,14 +27,16 @@ async fn main() -> std::io::Result<()> { if args.once { log::warn!("Handling first connection and then exiting"); let (socket, address) = listener.accept().await?; - process_socket(socket, address, server).await; - Ok(()) + process_socket(socket, address, server.clone()).await; } else { loop { let (socket, address) = listener.accept().await?; tokio::spawn(process_socket(socket, address, server.clone())); } } + server.join(); + server.join_async().await; + Ok(()) } async fn process_socket(mut socket: net::TcpStream, address: std::net::SocketAddr, server: std::sync::Arc>) { @@ -47,7 +49,8 @@ async fn process_socket(mut socket: net::TcpStream, address: std::net::SocketAdd } }; let user_state = state::UserState::new(); - server.handle_async(socket, user_state, enc, Default::default()).await; + let (socket_r, socket_w) = socket.into_split(); + let _packet_chann = server.handle_async(socket_r, socket_w, user_state, polariton::packet::SerdesContext::from_boxed(Default::default(), enc)).await; log::debug!("Goodbye connection from address {}", address); } @@ -100,7 +103,7 @@ impl polariton_auth::AuthProvider for AuthImpl { async fn do_connect_handshake( socket: &mut net::TcpStream, -) -> Option { +) -> Option> { let handshake = Handshake::new(APP_ID); // connect log::debug!("(connect) Handling first packet"); @@ -161,7 +164,7 @@ async fn do_connect_handshake( // pre-auth let handshake = handshake.with_auth(AuthImpl); let op_ctx = polariton::serdes::SerdesContext::default(); - let ctx = polariton::packet::SerdesContext::new(&op_ctx, &crypto); + let ctx = polariton::packet::SerdesContext::new(op_ctx, crypto); // authenticate log::debug!("(connect) Handling third packet"); let mut packet3 = match polariton_server::utils::receive_packet_async(socket, &ctx).await { @@ -181,7 +184,7 @@ async fn do_connect_handshake( } }; } - let to_send = match handshake.authenticate(&packet3, &crypto) { + let to_send = match handshake.authenticate(&packet3, &ctx) { Ok(x) => x, Err(h) => match h.extra { polariton_auth::AuthError::Validation(e) => { @@ -252,5 +255,5 @@ async fn do_connect_handshake( } } - Some(crypto) + Some(ctx.into_crypto()) } diff --git a/rc_services/src/main.rs b/rc_services/src/main.rs index 27812a4..cc43750 100644 --- a/rc_services/src/main.rs +++ b/rc_services/src/main.rs @@ -1,5 +1,4 @@ mod cli; -mod state; use polariton_auth::Handshake; use tokio::net; @@ -43,11 +42,11 @@ async fn process_socket(mut socket: net::TcpStream, address: std::net::SocketAdd return; } }; - let sock_state = state::State::new(enc); - while let Ok(packet) = polariton_server::utils::receive_packet_async(&mut socket, &sock_state.serdes_ctx()).await { + let ctx = polariton::packet::SerdesContext::from_boxed(Default::default(), enc); + while let Ok(packet) = polariton_server::utils::receive_packet_async(&mut socket, &ctx).await { match packet { Packet::Ping(ping) => { - polariton_server::utils::handle_ping_async(ping, &mut socket, &sock_state.serdes_ctx()).await.unwrap_or_default(); + polariton_server::utils::handle_ping_async(ping, &mut socket, &ctx).await.unwrap_or_default(); }, Packet::Packet(packet) => log::warn!("Not handling packet {:?}", packet), } @@ -106,7 +105,7 @@ async fn do_connect_handshake( socket: &mut net::TcpStream, game_server_url: &str, game_server_name: &str, -) -> Option { +) -> Option> { let handshake = Handshake::new(APP_ID); // connect log::debug!("(connect) Handling first packet"); @@ -167,7 +166,7 @@ async fn do_connect_handshake( // pre-auth let handshake = handshake.with_auth(AuthImpl); let op_ctx = polariton::serdes::SerdesContext::default(); - let ctx = polariton::packet::SerdesContext::new(&op_ctx, &crypto); + let ctx = polariton::packet::SerdesContext::new(op_ctx, crypto); // authenticate log::debug!("(connect) Handling third packet"); let mut packet3 = match polariton_server::utils::receive_packet_async(socket, &ctx).await { @@ -187,7 +186,7 @@ async fn do_connect_handshake( } }; } - let to_send = match handshake.authenticate(&packet3, &crypto) { + let to_send = match handshake.authenticate(&packet3, &ctx) { Ok(x) => x, Err(h) => match h.extra { polariton_auth::AuthError::Validation(e) => { @@ -271,5 +270,5 @@ async fn do_connect_handshake( } } - Some(crypto) + Some(ctx.into_crypto()) } diff --git a/rc_services/src/state.rs b/rc_services/src/state.rs deleted file mode 100644 index 9d6664f..0000000 --- a/rc_services/src/state.rs +++ /dev/null @@ -1,17 +0,0 @@ -const SERDES_SERDES_CTX_REF: &'static polariton::serdes::SerdesContext<(), polariton::serdes::NoCustomSerdes> = &polariton::serdes::SerdesContext::default_const(); - -pub struct State { - pub crypto: polariton_auth::CryptoImpl, -} - -impl State { - pub fn new(c: polariton_auth::CryptoImpl) -> Self { - Self { - crypto: c, - } - } - - pub fn serdes_ctx(&self) -> polariton::packet::SerdesContext<'_, (), polariton::serdes::NoCustomSerdes> { - polariton::packet::SerdesContext::new(SERDES_SERDES_CTX_REF, &self.crypto) - } -} diff --git a/rc_services_room/src/main.rs b/rc_services_room/src/main.rs index c3874f2..a2c0249 100644 --- a/rc_services_room/src/main.rs +++ b/rc_services_room/src/main.rs @@ -32,7 +32,7 @@ async fn main() -> std::io::Result<()> { users, }); - let server = std::sync::Arc::new(polariton_server::Server::new(operations::handler(&init_ctx))); + let server = std::sync::Arc::new(polariton_server::Server::new(operations::handler(&init_ctx), polariton_server::events::EventsHandler::new())); let ip_addr: std::net::IpAddr = args.ip.parse().expect("Invalid IP address"); @@ -41,14 +41,16 @@ async fn main() -> std::io::Result<()> { if args.once { log::warn!("Handling first connection and then exiting"); let (socket, address) = listener.accept().await?; - process_socket(socket, address, server, init_ctx).await; - Ok(()) + process_socket(socket, address, server.clone(), init_ctx).await; } else { loop { let (socket, address) = listener.accept().await?; tokio::spawn(process_socket(socket, address, server.clone(), init_ctx.clone())); } } + server.join(); + server.join_async().await; + Ok(()) } async fn process_socket(mut socket: net::TcpStream, address: std::net::SocketAddr, server: std::sync::Arc>, init_ctx: std::sync::Arc) { @@ -60,8 +62,10 @@ async fn process_socket(mut socket: net::TcpStream, address: std::net::SocketAdd return; } }; + let (socket_r, socket_w) = socket.into_split(); let user_state = std::sync::RwLock::new(state::UserState::<()>::new(init_ctx.users.clone())); - server.handle_async(socket, user_state, enc, Default::default()).await; + let ctx = polariton::packet::SerdesContext::from_boxed(Default::default(), enc); + server.handle_async(socket_r, socket_w, user_state, ctx).await; log::debug!("Goodbye connection from address {}", address); } @@ -114,7 +118,7 @@ impl polariton_auth::AuthProvider for AuthImpl { async fn do_connect_handshake( socket: &mut net::TcpStream, -) -> Option { +) -> Option> { let handshake = Handshake::new(APP_ID); // connect log::debug!("(connect) Handling first packet"); @@ -175,7 +179,7 @@ async fn do_connect_handshake( // pre-auth let handshake = handshake.with_auth(AuthImpl); let op_ctx = polariton::serdes::SerdesContext::default(); - let ctx = polariton::packet::SerdesContext::new(&op_ctx, &crypto); + let ctx = polariton::packet::SerdesContext::new(op_ctx, crypto); // authenticate log::debug!("(connect) Handling third packet"); let mut packet3 = match polariton_server::utils::receive_packet_async(socket, &ctx).await { @@ -195,7 +199,7 @@ async fn do_connect_handshake( } }; } - let to_send = match handshake.authenticate(&packet3, &crypto) { + let to_send = match handshake.authenticate(&packet3, &ctx) { Ok(x) => x, Err(h) => match h.extra { polariton_auth::AuthError::Validation(e) => { @@ -266,5 +270,5 @@ async fn do_connect_handshake( } } - Some(crypto) + Some(ctx.into_crypto()) } diff --git a/rc_singleplayer/src/main.rs b/rc_singleplayer/src/main.rs index ef6bfea..eff97b1 100644 --- a/rc_singleplayer/src/main.rs +++ b/rc_singleplayer/src/main.rs @@ -1,5 +1,4 @@ mod cli; -mod state; use polariton_auth::Handshake; use tokio::net; @@ -44,11 +43,11 @@ async fn process_socket(mut socket: net::TcpStream, address: std::net::SocketAdd return; } }; - let sock_state = state::State::new(enc); - while let Ok(packet) = polariton_server::utils::receive_packet_async(&mut socket, &sock_state.serdes_ctx()).await { + let ctx = polariton::packet::SerdesContext::from_boxed(Default::default(), enc); + while let Ok(packet) = polariton_server::utils::receive_packet_async(&mut socket, &ctx).await { match packet { Packet::Ping(ping) => { - polariton_server::utils::handle_ping_async(ping, &mut socket, &sock_state.serdes_ctx()).await.unwrap_or_default(); + polariton_server::utils::handle_ping_async(ping, &mut socket, &ctx).await.unwrap_or_default(); }, Packet::Packet(packet) => log::warn!("Not handling packet {:?}", packet), } @@ -107,7 +106,7 @@ async fn do_connect_handshake( socket: &mut net::TcpStream, game_server_name: &str, game_server_url: &str, -) -> Option { +) -> Option> { let handshake = Handshake::new(APP_ID); // connect log::debug!("(connect) Handling first packet"); @@ -168,7 +167,7 @@ async fn do_connect_handshake( // pre-auth let handshake = handshake.with_auth(AuthImpl); let op_ctx = polariton::serdes::SerdesContext::default(); - let ctx = polariton::packet::SerdesContext::new(&op_ctx, &crypto); + let ctx = polariton::packet::SerdesContext::new(op_ctx, crypto); // authenticate log::debug!("(connect) Handling third packet"); let mut packet3 = match polariton_server::utils::receive_packet_async(socket, &ctx).await { @@ -188,7 +187,7 @@ async fn do_connect_handshake( } }; } - let to_send = match handshake.authenticate(&packet3, &crypto) { + let to_send = match handshake.authenticate(&packet3, &ctx) { Ok(x) => x, Err(h) => match h.extra { polariton_auth::AuthError::Validation(e) => { @@ -259,5 +258,5 @@ async fn do_connect_handshake( } } - Some(crypto) + Some(ctx.into_crypto()) } diff --git a/rc_singleplayer/src/state.rs b/rc_singleplayer/src/state.rs deleted file mode 100644 index 9d6664f..0000000 --- a/rc_singleplayer/src/state.rs +++ /dev/null @@ -1,17 +0,0 @@ -const SERDES_SERDES_CTX_REF: &'static polariton::serdes::SerdesContext<(), polariton::serdes::NoCustomSerdes> = &polariton::serdes::SerdesContext::default_const(); - -pub struct State { - pub crypto: polariton_auth::CryptoImpl, -} - -impl State { - pub fn new(c: polariton_auth::CryptoImpl) -> Self { - Self { - crypto: c, - } - } - - pub fn serdes_ctx(&self) -> polariton::packet::SerdesContext<'_, (), polariton::serdes::NoCustomSerdes> { - polariton::packet::SerdesContext::new(SERDES_SERDES_CTX_REF, &self.crypto) - } -} diff --git a/rc_singleplayer_room/Cargo.toml b/rc_singleplayer_room/Cargo.toml index 3c2139a..6a8ad7f 100644 --- a/rc_singleplayer_room/Cargo.toml +++ b/rc_singleplayer_room/Cargo.toml @@ -6,7 +6,7 @@ edition = "2021" [dependencies] log.workspace = true env_logger.workspace = true -tokio = { version = "1.43", features = [ "net", "macros", "rt-multi-thread", "io-util" ] } +tokio = { version = "1.43", features = [ "net", "macros", "rt-multi-thread", "io-util", "time"] } clap.workspace = true polariton.workspace = true polariton_auth = { version = "*", path = "../polariton_auth" } diff --git a/rc_singleplayer_room/src/main.rs b/rc_singleplayer_room/src/main.rs index 9a0215d..c767f84 100644 --- a/rc_singleplayer_room/src/main.rs +++ b/rc_singleplayer_room/src/main.rs @@ -10,7 +10,7 @@ use tokio::net; use polariton::packet::{Data, Message, Packet, StandardMessage}; use polariton::operation::{OperationResponse, Typed}; -pub type UserTy = std::sync::RwLock; +pub type UserTy = state::UserState; #[tokio::main] async fn main() -> std::io::Result<()> { @@ -18,7 +18,7 @@ async fn main() -> std::io::Result<()> { let args = cli::CliArgs::get(); log::debug!("Got cli args {:?}", args); - let server = std::sync::Arc::new(polariton_server::Server::new(operations::handler())); + let server = std::sync::Arc::new(polariton_server::Server::new(operations::handler(), polariton_server::events::EventsHandler::new())); let ip_addr: std::net::IpAddr = args.ip.parse().expect("Invalid IP address"); @@ -27,14 +27,16 @@ async fn main() -> std::io::Result<()> { if args.once { log::warn!("Handling first connection and then exiting"); let (socket, address) = listener.accept().await?; - process_socket(socket, address, server).await; - Ok(()) + process_socket(socket, address, server.clone()).await; } else { loop { let (socket, address) = listener.accept().await?; tokio::spawn(process_socket(socket, address, server.clone())); } } + server.join(); + server.join_async().await; + Ok(()) } async fn process_socket(mut socket: net::TcpStream, address: std::net::SocketAddr, server: std::sync::Arc>) { @@ -46,8 +48,11 @@ async fn process_socket(mut socket: net::TcpStream, address: std::net::SocketAdd return; } }; - let user_state = state::UserState::new(); - server.handle_async(socket, user_state, enc, Default::default()).await; + let (socket_r, socket_w) = socket.into_split(); + let (chann_tx, chann_rx) = tokio::sync::mpsc::unbounded_channel(); + let user_state = state::UserState::new(chann_tx.clone()); + let ctx = polariton::packet::SerdesContext::from_boxed(Default::default(), enc); + server.handle_async_with_channel(socket_r, socket_w, user_state, ctx, chann_tx, chann_rx).await; log::debug!("Goodbye connection from address {}", address); } @@ -100,7 +105,7 @@ impl polariton_auth::AuthProvider for AuthImpl { async fn do_connect_handshake( socket: &mut net::TcpStream, -) -> Option { +) -> Option> { let handshake = Handshake::new(APP_ID); // connect log::debug!("(connect) Handling first packet"); @@ -161,7 +166,7 @@ async fn do_connect_handshake( // pre-auth let handshake = handshake.with_auth(AuthImpl); let op_ctx = polariton::serdes::SerdesContext::default(); - let ctx = polariton::packet::SerdesContext::new(&op_ctx, &crypto); + let ctx = polariton::packet::SerdesContext::new(op_ctx, crypto); // authenticate log::debug!("(connect) Handling third packet"); let mut packet3 = match polariton_server::utils::receive_packet_async(socket, &ctx).await { @@ -181,7 +186,7 @@ async fn do_connect_handshake( } }; } - let to_send = match handshake.authenticate(&packet3, &crypto) { + let to_send = match handshake.authenticate(&packet3, &ctx) { Ok(x) => x, Err(h) => match h.extra { polariton_auth::AuthError::Validation(e) => { @@ -252,5 +257,5 @@ async fn do_connect_handshake( } } - Some(crypto) + Some(ctx.into_crypto()) } diff --git a/rc_singleplayer_room/src/operations/load_ai_robots.rs b/rc_singleplayer_room/src/operations/load_ai_robots.rs index 88a7b93..6616433 100644 --- a/rc_singleplayer_room/src/operations/load_ai_robots.rs +++ b/rc_singleplayer_room/src/operations/load_ai_robots.rs @@ -1,5 +1,5 @@ use polariton_server::operations::SimpleFunc; -use polariton::operation::ParameterTable; +use polariton::operation::{ParameterTable, Typed}; use crate::data::player_data::*; @@ -785,7 +785,7 @@ const VALID_COLOUR: &[u8] = &[64, pub(super) fn tdm_machines_provider() -> SimpleFunc<1, crate::UserTy, impl (Fn(ParameterTable, &crate::UserTy) -> Result) + Sync + Sync> { SimpleFunc::new(|params, user: &crate::UserTy| { - let ulock = user.read().unwrap(); + let ulock = user.auth.read().unwrap(); let mut params = params.to_dict(); params.insert(PARAM_KEY, PlayerDatas { players: vec![ @@ -838,7 +838,7 @@ pub(super) fn tdm_machines_provider() -> SimpleFunc<1, crate::UserTy, impl (Fn(P robot_map: VALID_ROBOT.iter().map(|x| *x).collect(), team: 1, has_premium: false, - robot_uuid: "1_1".to_owned(), + robot_uuid: "12_12".to_owned(), cpu: 0, weapon_order: vec![20000200, 0, 0], colour_map: VALID_COLOUR.iter().map(|x| *x).collect(), @@ -850,6 +850,30 @@ pub(super) fn tdm_machines_provider() -> SimpleFunc<1, crate::UserTy, impl (Fn(P },*/ ] }.as_transmissible()); + let event_tx = user.event_tx.clone(); + tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_secs(10)).await; + log::debug!("Sending singleplayer events"); + let mut spawn_params = std::collections::HashMap::with_capacity(4); + spawn_params.insert(2 /* robot GUID */, Typed::Str("12_12".into())); + spawn_params.insert(3 /* machine model */, Typed::Bytes(VALID_ROBOT.iter().map(|x| *x).collect::>().into())); + spawn_params.insert(4 /* robot name */, Typed::Str("RE_robot_spawn_name0".into())); + spawn_params.insert(7 /* color model */, Typed::Bytes(VALID_COLOUR.iter().map(|x| *x).collect::>().into())); + event_tx.send(polariton_server::ToSend::Data { + data: polariton::packet::Data::Event(polariton::operation::Event { code: 3, params: spawn_params.into() }), + encrypt: true, + channel: 0, + reliable: true, + }).unwrap(); + let mut update_params = std::collections::HashMap::with_capacity(1); + update_params.insert(6 /* ??? */, Typed::Int(5)); + event_tx.send(polariton_server::ToSend::Data { + data: polariton::packet::Data::Event(polariton::operation::Event { code: 5, params: update_params.into() }), + encrypt: true, + channel: 0, + reliable: true, + }).unwrap(); + }); Ok(params.into()) }) } diff --git a/rc_singleplayer_room/src/operations/more_auth.rs b/rc_singleplayer_room/src/operations/more_auth.rs index c1fc5ee..27504f3 100644 --- a/rc_singleplayer_room/src/operations/more_auth.rs +++ b/rc_singleplayer_room/src/operations/more_auth.rs @@ -14,8 +14,8 @@ impl Operation for MoreLobbyAuth { fn handle(&self, params: polariton::operation::ParameterTable, _: &mut Self::State, user: &Self::User) -> polariton::operation::OperationResponse { let params_dict = params.to_dict(); if let Some(Typed::Str(auth_payload)) = params_dict.get(&Self::AUTH_PAYLOAD_KEY) { - let mut write_lock = user.write().unwrap(); - if write_lock.update_with_auth(&auth_payload.string) { + //let mut write_lock = user.write().unwrap(); + if user.update_with_auth(&auth_payload.string) { let mut resp_params = std::collections::HashMap::new(); resp_params.insert(Self::AUTH_PAYLOAD_KEY, polariton::operation::Typed::Byte(0)); return polariton::operation::OperationResponse { diff --git a/rc_singleplayer_room/src/state.rs b/rc_singleplayer_room/src/state.rs index bc39273..2d2c03e 100644 --- a/rc_singleplayer_room/src/state.rs +++ b/rc_singleplayer_room/src/state.rs @@ -1,27 +1,40 @@ use std::sync::RwLock; -#[derive(Default, Debug)] -pub struct UserState { +use tokio::sync::mpsc::UnboundedSender; +use polariton_server::ToSend; + +#[derive(Debug, Default)] +pub struct UserAuthInfo { pub uuid: String, pub token: String, pub refresh_token: String, } +#[derive(Debug)] +pub struct UserState { + pub auth: RwLock, + pub event_tx: UnboundedSender, +} + impl UserState { - pub fn update_with_auth(&mut self, auth_str: &str) -> bool { + pub fn update_with_auth(&self, auth_str: &str) -> bool { let splits: Vec<&str> = auth_str.split(';').collect(); if splits.len() != 3 { log::warn!("Invalid auth payload: {}", auth_str); false } else { - self.uuid = splits[0].to_owned(); - self.token = splits[1].to_owned(); - self.refresh_token = splits[2].to_owned(); + let mut lock = self.auth.write().unwrap(); + lock.uuid = splits[0].to_owned(); + lock.token = splits[1].to_owned(); + lock.refresh_token = splits[2].to_owned(); true } } - pub fn new() -> crate::UserTy { - RwLock::new(UserState::default()) + pub fn new(event_tx: UnboundedSender) -> crate::UserTy { + UserState { + auth: RwLock::new(Default::default()), + event_tx, + } } } diff --git a/rc_social/src/main.rs b/rc_social/src/main.rs index 84230fe..a93f52a 100644 --- a/rc_social/src/main.rs +++ b/rc_social/src/main.rs @@ -1,5 +1,4 @@ mod cli; -mod state; use polariton_auth::Handshake; use tokio::net; @@ -44,11 +43,11 @@ async fn process_socket(mut socket: net::TcpStream, address: std::net::SocketAdd return; } }; - let sock_state = state::State::new(enc); - while let Ok(packet) = polariton_server::utils::receive_packet_async(&mut socket, &sock_state.serdes_ctx()).await { + let ctx = polariton::packet::SerdesContext::from_boxed(Default::default(), enc); + while let Ok(packet) = polariton_server::utils::receive_packet_async(&mut socket, &ctx).await { match packet { Packet::Ping(ping) => { - polariton_server::utils::handle_ping_async(ping, &mut socket, &sock_state.serdes_ctx()).await.unwrap_or_default(); + polariton_server::utils::handle_ping_async(ping, &mut socket, &ctx).await.unwrap_or_default(); }, Packet::Packet(packet) => log::warn!("Not handling packet {:?}", packet), } @@ -107,7 +106,7 @@ async fn do_connect_handshake( socket: &mut net::TcpStream, game_server_name: &str, game_server_url: &str, -) -> Option { +) -> Option> { let handshake = Handshake::new(APP_ID); // connect log::debug!("(connect) Handling first packet"); @@ -168,7 +167,7 @@ async fn do_connect_handshake( // pre-auth let handshake = handshake.with_auth(AuthImpl); let op_ctx = polariton::serdes::SerdesContext::default(); - let ctx = polariton::packet::SerdesContext::new(&op_ctx, &crypto); + let ctx = polariton::packet::SerdesContext::new(op_ctx, crypto); // authenticate log::debug!("(connect) Handling third packet"); let mut packet3 = match polariton_server::utils::receive_packet_async(socket, &ctx).await { @@ -188,7 +187,7 @@ async fn do_connect_handshake( } }; } - let to_send = match handshake.authenticate(&packet3, &crypto) { + let to_send = match handshake.authenticate(&packet3, &ctx) { Ok(x) => x, Err(h) => match h.extra { polariton_auth::AuthError::Validation(e) => { @@ -257,5 +256,5 @@ async fn do_connect_handshake( } } - Some(crypto) + Some(ctx.into_crypto()) } diff --git a/rc_social/src/state.rs b/rc_social/src/state.rs deleted file mode 100644 index 9d6664f..0000000 --- a/rc_social/src/state.rs +++ /dev/null @@ -1,17 +0,0 @@ -const SERDES_SERDES_CTX_REF: &'static polariton::serdes::SerdesContext<(), polariton::serdes::NoCustomSerdes> = &polariton::serdes::SerdesContext::default_const(); - -pub struct State { - pub crypto: polariton_auth::CryptoImpl, -} - -impl State { - pub fn new(c: polariton_auth::CryptoImpl) -> Self { - Self { - crypto: c, - } - } - - pub fn serdes_ctx(&self) -> polariton::packet::SerdesContext<'_, (), polariton::serdes::NoCustomSerdes> { - polariton::packet::SerdesContext::new(SERDES_SERDES_CTX_REF, &self.crypto) - } -} diff --git a/rc_social_room/src/main.rs b/rc_social_room/src/main.rs index 3447fc0..1bc4e76 100644 --- a/rc_social_room/src/main.rs +++ b/rc_social_room/src/main.rs @@ -18,7 +18,7 @@ async fn main() -> std::io::Result<()> { let args = cli::CliArgs::get(); log::debug!("Got cli args {:?}", args); - let server = std::sync::Arc::new(polariton_server::Server::new(operations::handler())); + let server = std::sync::Arc::new(polariton_server::Server::new(operations::handler(), polariton_server::events::EventsHandler::new())); let ip_addr: std::net::IpAddr = args.ip.parse().expect("Invalid IP address"); @@ -27,14 +27,16 @@ async fn main() -> std::io::Result<()> { if args.once { log::warn!("Handling first connection and then exiting"); let (socket, address) = listener.accept().await?; - process_socket(socket, address, server).await; - Ok(()) + process_socket(socket, address, server.clone()).await; } else { loop { let (socket, address) = listener.accept().await?; tokio::spawn(process_socket(socket, address, server.clone())); } } + server.join(); + server.join_async().await; + Ok(()) } async fn process_socket(mut socket: net::TcpStream, address: std::net::SocketAddr, server: std::sync::Arc>) { @@ -46,9 +48,11 @@ async fn process_socket(mut socket: net::TcpStream, address: std::net::SocketAdd return; } }; + let (socket_r, socket_w) = socket.into_split(); let user_state = state::UserState::new(); let op_ctx = polariton::serdes::SerdesContext::::default_const(); - server.handle_async(socket, user_state, enc, op_ctx).await; + let ctx = polariton::packet::SerdesContext::from_boxed(op_ctx, enc); + server.handle_async(socket_r, socket_w, user_state, ctx).await; log::debug!("Goodbye connection from address {}", address); } @@ -101,7 +105,7 @@ impl polariton_auth::AuthProvider for AuthImpl { async fn do_connect_handshake( socket: &mut net::TcpStream, -) -> Option { +) -> Option> { let handshake = Handshake::new(APP_ID); // connect log::debug!("(connect) Handling first packet"); @@ -162,7 +166,7 @@ async fn do_connect_handshake( // pre-auth let handshake = handshake.with_auth(AuthImpl); let op_ctx = polariton::serdes::SerdesContext::default(); - let ctx = polariton::packet::SerdesContext::new(&op_ctx, &crypto); + let ctx = polariton::packet::SerdesContext::new(op_ctx, crypto); // authenticate log::debug!("(connect) Handling third packet"); let mut packet3 = match polariton_server::utils::receive_packet_async(socket, &ctx).await { @@ -182,7 +186,7 @@ async fn do_connect_handshake( } }; } - let to_send = match handshake.authenticate(&packet3, &crypto) { + let to_send = match handshake.authenticate(&packet3, &ctx) { Ok(x) => x, Err(h) => match h.extra { polariton_auth::AuthError::Validation(e) => { @@ -253,5 +257,5 @@ async fn do_connect_handshake( } } - Some(crypto) + Some(ctx.into_crypto()) }