Browse Source

cleanup

pbs
jake 4 years ago
parent
commit
317acad564
  1. 6
      src/common/interserver.rs
  2. 44
      src/common/mainloop/client.rs
  3. 31
      src/common/mainloop/interserver.rs
  4. 8
      src/common/mainloop/mod.rs
  5. 29
      src/login/character.rs

6
src/common/interserver.rs

@ -11,7 +11,6 @@ pub struct AuthToken(pub String);
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct Ship { pub struct Ship {
pub name: String, pub name: String,
//pub ip: String,
pub ip: Ipv4Addr, pub ip: Ipv4Addr,
pub port: u16, pub port: u16,
pub block_count: u32, pub block_count: u32,
@ -43,11 +42,6 @@ pub enum ShipMessage {
} }
#[async_trait::async_trait] #[async_trait::async_trait]
pub trait InterserverActor { pub trait InterserverActor {
type SendMessage: Serialize; type SendMessage: Serialize;

44
src/common/mainloop/client.rs

@ -1,11 +1,9 @@
use std::pin::Pin; use std::pin::Pin;
use futures::future::{Future, join_all};
use futures::future::Future;
use log::{trace, info, warn}; use log::{trace, info, warn};
use async_std::sync::{Arc, Mutex}; use async_std::sync::{Arc, Mutex};
use async_std::io::prelude::{ReadExt, WriteExt}; use async_std::io::prelude::{ReadExt, WriteExt};
use std::collections::HashMap; use std::collections::HashMap;
use serde::{Serialize, Deserialize};
use serde::de::DeserializeOwned;
use libpso::crypto::{PSOCipher, NullCipher, CipherError}; use libpso::crypto::{PSOCipher, NullCipher, CipherError};
use libpso::PacketParseError; use libpso::PacketParseError;
@ -268,46 +266,6 @@ where
}); });
} }
pub async fn simple_mainloop<STATE, S, R, E>(state: STATE, port: u16) where
STATE: ServerState<SendPacket=S, RecvPacket=R, PacketError=E> + Send + 'static,
S: SendServerPacket + std::fmt::Debug + Send + Sync + 'static,
R: RecvServerPacket + std::fmt::Debug + Send + Sync + 'static,
E: std::fmt::Debug + Send,
{
let listener = async_std::task::spawn(async move {
let listener = async_std::net::TcpListener::bind(&std::net::SocketAddr::from((std::net::Ipv4Addr::new(0,0,0,0), port))).await.unwrap();
let mut id = 1;
let (server_state_sender, server_state_receiver) = async_std::sync::channel(1024);
server_state_loop(state, server_state_receiver).await;
loop {
let (sock, addr) = listener.accept().await.unwrap();
let client_id = crate::common::serverstate::ClientId(id);
id += 1;
info!("new client {:?} {:?} {:?}", client_id, sock, addr);
let (client_sender, client_receiver) = async_std::sync::channel(64);
let socket = Arc::new(sock);
let cipher_in: Arc<Mutex<Box<dyn PSOCipher + Send>>> = Arc::new(Mutex::new(Box::new(NullCipher {})));
let cipher_out: Arc<Mutex<Box<dyn PSOCipher + Send>>> = Arc::new(Mutex::new(Box::new(NullCipher {})));
client_recv_loop(client_id, socket.clone(), cipher_in.clone(), server_state_sender.clone(), client_sender).await;
client_send_loop(client_id, socket.clone(), cipher_in.clone(), cipher_out.clone(), client_receiver).await;
}
});
listener.await
}
////////////////////////////////////////////////////////////
async fn state_client_loop<STATE, S, R, E>(state: Arc<Mutex<STATE>>, async fn state_client_loop<STATE, S, R, E>(state: Arc<Mutex<STATE>>,
server_state_receiver: async_std::sync::Receiver<ClientAction<ServerStateAction<S>, R>>) where server_state_receiver: async_std::sync::Receiver<ClientAction<ServerStateAction<S>, R>>) where
STATE: ServerState<SendPacket=S, RecvPacket=R, PacketError=E> + Send + 'static, STATE: ServerState<SendPacket=S, RecvPacket=R, PacketError=E> + Send + 'static,

31
src/common/mainloop/interserver.rs

@ -1,28 +1,24 @@
use std::time::Duration; use std::time::Duration;
use std::pin::Pin; use std::pin::Pin;
use futures::future::{Future, join_all, FutureExt};
use log::{trace, info, warn};
use futures::future::Future;
use log::{info, warn};
use async_std::sync::{Arc, Mutex}; use async_std::sync::{Arc, Mutex};
use async_std::io::prelude::{ReadExt, WriteExt}; use async_std::io::prelude::{ReadExt, WriteExt};
use std::collections::HashMap; use std::collections::HashMap;
use serde::{Serialize, Deserialize};
use serde::Serialize;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use crate::common::serverstate::{RecvServerPacket, SendServerPacket, ServerState, OnConnect};
use crate::common::interserver::{ServerId, InterserverActor, LoginMessage, ShipMessage};
use crate::common::mainloop::client::client_accept_mainloop;
pub use crate::common::mainloop::client::NetworkError;
use crate::common::interserver::{ServerId, InterserverActor};
use crate::patch::patch::PatchServerState;
use crate::login::character::CharacterServerState; use crate::login::character::CharacterServerState;
use crate::ship::ship::ShipServerState; use crate::ship::ship::ShipServerState;
use crate::entity::gateway::entitygateway::EntityGateway; use crate::entity::gateway::entitygateway::EntityGateway;
#[derive(Debug)] #[derive(Debug)]
enum MessageReceiverError { enum MessageReceiverError {
InvalidSize,
//InvalidSize,
InvalidPayload, InvalidPayload,
NetworkError(std::io::Error),
//NetworkError(std::io::Error),
Disconnected, Disconnected,
} }
@ -41,20 +37,16 @@ impl MessageReceiver {
let mut size_buf = [0u8; 4]; let mut size_buf = [0u8; 4];
self.socket.read_exact(&mut size_buf).await.map_err(|_| MessageReceiverError::Disconnected)?; self.socket.read_exact(&mut size_buf).await.map_err(|_| MessageReceiverError::Disconnected)?;
let size = u32::from_le_bytes(size_buf) as usize; let size = u32::from_le_bytes(size_buf) as usize;
info!("expected len: {:?}", size);
let mut payload = vec![0u8; size]; let mut payload = vec![0u8; size];
self.socket.read_exact(&mut payload).await.map_err(|err| MessageReceiverError::Disconnected)?; self.socket.read_exact(&mut payload).await.map_err(|err| MessageReceiverError::Disconnected)?;
let payload = String::from_utf8(payload).map_err(|_| MessageReceiverError::InvalidPayload)?; let payload = String::from_utf8(payload).map_err(|_| MessageReceiverError::InvalidPayload)?;
info!("payload: {:?}", payload);
let msg = serde_json::from_str(&payload).map_err(|_| MessageReceiverError::InvalidPayload)?; let msg = serde_json::from_str(&payload).map_err(|_| MessageReceiverError::InvalidPayload)?;
info!("msg: {:?}", msg);
Ok(msg) Ok(msg)
} }
} }
#[derive(Debug)] #[derive(Debug)]
enum InterserverInputAction<S, R> { enum InterserverInputAction<S, R> {
NewConnection(ServerId, async_std::sync::Sender<S>), NewConnection(ServerId, async_std::sync::Sender<S>),
@ -62,10 +54,6 @@ enum InterserverInputAction<S, R> {
Disconnect(ServerId), Disconnect(ServerId),
} }
/*struct LoginOutputAction {
Message
}*/
async fn interserver_state_loop<A, S, R>(state: Arc<Mutex<A>>, action_receiver: async_std::sync::Receiver<InterserverInputAction<S, R>>) async fn interserver_state_loop<A, S, R>(state: Arc<Mutex<A>>, action_receiver: async_std::sync::Receiver<InterserverInputAction<S, R>>)
where where
A: InterserverActor<SendMessage=S, RecvMessage=R, Error=()> + Send + 'static, A: InterserverActor<SendMessage=S, RecvMessage=R, Error=()> + Send + 'static,
@ -211,17 +199,12 @@ pub fn ship_connect_mainloop<EG: EntityGateway + 'static>(state: Arc<Mutex<ShipS
interserver_state_loop(state, server_state_receiver).await; interserver_state_loop(state, server_state_receiver).await;
loop { loop {
//let listener = async_std::net::TcpListener::bind(&std::net::SocketAddr::from((std::net::Ipv4Addr::new(0,0,0,0), port))).await.unwrap();
// TOOD: err check and loop with timeout
let socket = async_std::net::TcpStream::connect((ip, port)).await.unwrap(); let socket = async_std::net::TcpStream::connect((ip, port)).await.unwrap();
//let (socket, addr) = listener.accept().await.unwrap();
info!("ship connected to login: {:?}", socket);
id += 1; id += 1;
let server_id = crate::common::interserver::ServerId(id); let server_id = crate::common::interserver::ServerId(id);
let (client_sender, client_receiver) = async_std::sync::channel(64); let (client_sender, client_receiver) = async_std::sync::channel(64);
info!("ship connected to login: {:?}", socket);
login_recv_loop(server_id, socket.clone(), server_state_sender.clone(), client_sender).await; login_recv_loop(server_id, socket.clone(), server_state_sender.clone(), client_sender).await;
interserver_send_loop(server_id, socket.clone(), client_receiver).await; interserver_send_loop(server_id, socket.clone(), client_receiver).await;
loop { loop {

8
src/common/mainloop/mod.rs

@ -1,18 +1,10 @@
mod client; mod client;
mod interserver; mod interserver;
use std::time::Duration;
use std::pin::Pin; use std::pin::Pin;
use futures::future::{Future, join_all, FutureExt}; use futures::future::{Future, join_all, FutureExt};
use log::{trace, info, warn};
use async_std::sync::{Arc, Mutex}; use async_std::sync::{Arc, Mutex};
use async_std::io::prelude::{ReadExt, WriteExt};
use std::collections::HashMap;
use serde::{Serialize, Deserialize};
use serde::de::DeserializeOwned;
use crate::common::serverstate::{RecvServerPacket, SendServerPacket, ServerState, OnConnect};
use crate::common::interserver::{ServerId, InterserverActor, LoginMessage, ShipMessage};
use crate::common::mainloop::client::client_accept_mainloop; use crate::common::mainloop::client::client_accept_mainloop;
use crate::common::mainloop::interserver::{ship_connect_mainloop, login_listen_mainloop}; use crate::common::mainloop::interserver::{ship_connect_mainloop, login_listen_mainloop};
pub use crate::common::mainloop::client::NetworkError; pub use crate::common::mainloop::client::NetworkError;

29
src/login/character.rs

@ -1,8 +1,6 @@
#![allow(dead_code, unused_assignments)] #![allow(dead_code, unused_assignments)]
use std::io::Read; use std::io::Read;
use std::collections::{BTreeMap, HashMap}; use std::collections::{BTreeMap, HashMap};
use std::net::Ipv4Addr;
use std::str::FromStr;
use rand::Rng; use rand::Rng;
use crc::{crc32, Hasher32}; use crc::{crc32, Hasher32};
@ -165,24 +163,6 @@ impl ClientState {
} }
/*struct Ship {
flags: u32,
name: String,
ip: [u8; 4],
port: u16,
}*/
/*impl Ship {
fn new(name: &str, ip: [u8; 4], port: u16) -> Ship {
Ship {
flags: 0,
name: name.to_owned(),
ip: ip,
port: port,
}
}
}*/
pub struct CharacterServerState<EG: EntityGateway> { pub struct CharacterServerState<EG: EntityGateway> {
entity_gateway: EG, entity_gateway: EG,
param_header: ParamDataHeader, param_header: ParamDataHeader,
@ -194,8 +174,6 @@ pub struct CharacterServerState<EG: EntityGateway> {
async fn new_character<EG: EntityGateway>(entity_gateway: &mut EG, user: &UserAccountEntity, preview: &CharacterPreview) { async fn new_character<EG: EntityGateway>(entity_gateway: &mut EG, user: &UserAccountEntity, preview: &CharacterPreview) {
//let mut character = entity_gateway.new_character_by_user(&user);
//new_character_from_preview(&mut char, preview);
let mut character = new_character_from_preview(user, preview); let mut character = new_character_from_preview(user, preview);
match character.char_class { match character.char_class {
CharacterClass::FOmar | CharacterClass::FOmarl| CharacterClass::FOnewm | CharacterClass::FOnewearl => character.techs.set_tech(Technique::Foie, TechLevel(1)), CharacterClass::FOmar | CharacterClass::FOmarl| CharacterClass::FOnewm | CharacterClass::FOnewearl => character.techs.set_tech(Technique::Foie, TechLevel(1)),
@ -291,15 +269,10 @@ async fn new_character<EG: EntityGateway>(entity_gateway: &mut EG, user: &UserAc
} }
impl<EG: EntityGateway> CharacterServerState<EG> { impl<EG: EntityGateway> CharacterServerState<EG> {
pub fn new(entity_gateway: EG) -> CharacterServerState<EG> { pub fn new(entity_gateway: EG) -> CharacterServerState<EG> {
let (param_header, param_data) = generate_param_data("data/param/"); let (param_header, param_data) = generate_param_data("data/param/");
/*let ships = vec![Ship::new("Sona-Nyl", [127,0,0,1], 23423),
Ship::new("Dylath-Leen", [127,0,0,1], 23424),
Ship::new("Thalarion", [127,0,0,1], 23425),
];*/
CharacterServerState { CharacterServerState {
entity_gateway: entity_gateway, entity_gateway: entity_gateway,
param_header: param_header, param_header: param_header,
@ -581,7 +554,7 @@ impl<EG: EntityGateway> InterserverActor for CharacterServerState<EG> {
async fn action(&mut self, id: ServerId, msg: Self::RecvMessage) -> Result<Vec<(ServerId, Self::SendMessage)>, Self::Error> { async fn action(&mut self, id: ServerId, msg: Self::RecvMessage) -> Result<Vec<(ServerId, Self::SendMessage)>, Self::Error> {
match msg { match msg {
ShipMessage::Authenticate(auth_token) => {},
ShipMessage::Authenticate(_auth_token) => {},
ShipMessage::NewShip(new_ship) => { ShipMessage::NewShip(new_ship) => {
self.ships.insert(id, new_ship); self.ships.insert(id, new_ship);
}, },

Loading…
Cancel
Save