Ver código fonte

Move crypto into fleck_core.

Kestrel 2 anos atrás
pai
commit
9586180a5a

+ 7 - 4
fleck/src/fleck_core.rs

@@ -1,12 +1,13 @@
 // pub(crate) mod lowlevel;
-// mod nodes;
-// pub mod vchannel;
+pub mod crypto;
+pub mod nodes;
 pub mod io;
 pub mod msg;
 pub mod peer;
 
 // pub use nodes::Node;
-// pub use nodes::Nodes;
+pub use nodes::NodeService;
+pub use msg::MessageService;
 
 pub mod channel_tags {
     pub struct SendPacketTag {}
@@ -20,7 +21,7 @@ pub enum SendOrder {
     Route,
     Sign,
     Encrypt,
-    Send,
+    Dispatch,
 }
 pub type SendPacketChannel = (channel_tags::SendPacketTag, msg::Message, SendOrder);
 
@@ -55,5 +56,7 @@ impl crate::service::Service for std::rc::Rc<CoreInitService> {
                 .trigger(|api| api.queue::<MajorTickChannel>(()))
                 .build(io);
         });
+
+        api.add_service::<nodes::NodeService>();
     }
 }

+ 15 - 28
fleck/src/crypto.rs → fleck/src/fleck_core/crypto.rs

@@ -14,7 +14,7 @@ pub struct TrustDB {}
 
 pub struct KeyExchangeInitiate {}
 
-impl crate::msg::MessageParams for KeyExchangeInitiate {
+impl fleck_core::msg::MessageParams for KeyExchangeInitiate {
     const NAME: &'static str = "KeyExchangeInitiate";
     const ENCRYPTED: bool = false;
 }
@@ -42,24 +42,15 @@ pub struct SymmetricKey {
 pub(crate) struct VerifyPacketSignature {}
 
 impl Service for std::rc::Rc<VerifyPacketSignature> {
-    fn register_channels(&self, eroot: &mut EventRoot) {
-        eroot
+    fn setup(&self, api: &crate::Fleck) {
+        api
             .channel::<fleck_core::ReceivePacketChannel>()
-            .subscribe(fleck_core::ReceiveOrder::Verify, self, VerifyPacketSignature::check);
+            .sub_opt(fleck_core::ReceiveOrder::Verify, self, VerifyPacketSignature::check);
     }
 }
 
 impl VerifyPacketSignature {
-    fn check(&self, api: &crate::Fleck, event : &mut FleckEvent<FleckPacket>) {
-        let packet = &event.data;
-        
-        let message: Option<crate::msg::Message> =
-            bincode::deserialize(packet.data.as_ref().unwrap()).ok();
-        if message.is_none() {
-            return;
-        }
-        let mut message = message.unwrap();
-
+    fn check(&self, api: &crate::Fleck, mut message: fleck_core::msg::Message) -> Option<fleck_core::msg::Message> {
         match message.crypto_header {
             PacketHeader::Signed(signature) => {
                 message.crypto_header = PacketHeader::NoCrypto;
@@ -75,6 +66,8 @@ impl VerifyPacketSignature {
             }
             _ => {},
         }
+
+        Some(message)
     }
 }
 
@@ -82,22 +75,16 @@ impl VerifyPacketSignature {
 pub(crate) struct SignPacket {}
 
 impl Service for std::rc::Rc<SignPacket> {
-    fn register_channels(&self, eroot: &mut EventRoot) {
-        eroot
+    fn setup(&self, api: &crate::Fleck) {
+        api
             .channel::<fleck_core::SendPacketChannel>()
-            .subscribe(fleck_core::SendOrder::Sign, self, SignPacket::sign);
+            .sub_ref(fleck_core::SendOrder::Sign, self, SignPacket::sign);
     }
 }
 
 impl SignPacket {
-    fn sign(&self, api: &crate::Fleck, packet: &mut FleckEvent<FleckPacket>) {
-        let msg = packet
-            .data
-            .msg
-            .as_mut()
-            .expect("packet got to signing stage without having a Msg?");
-
-        let params = msg
+    fn sign(&self, api: &crate::Fleck, message: &mut fleck_core::msg::Message) {
+        let params = message
             .saved_params
             .expect("packet got to signing stage without saved parameters?");
 
@@ -106,10 +93,10 @@ impl SignPacket {
             return;
         }
 
-        api.services().with_service(|ns: &fleck_core::Nodes| {
+        api.with_service(|ns: &fleck_core::NodeService| {
             let keypair = ns.self_node().keypair().unwrap();
-            let sign_data = bincode::serialize(msg).unwrap();
-            msg.crypto_header = PacketHeader::Signed(keypair.sign(&sign_data));
+            let sign_data = bincode::serialize(&message.content).unwrap();
+            message.crypto_header = PacketHeader::Signed(keypair.sign(&sign_data));
         });
     }
 }

+ 38 - 22
fleck/src/fleck_core/msg.rs

@@ -1,7 +1,7 @@
 use std::{
     any::Any,
     collections::HashMap,
-    hash::{Hash, Hasher},
+    hash::{Hash, Hasher}, cell::RefCell, rc::Rc,
 };
 
 use serde::{de::DeserializeOwned, Deserialize, Serialize};
@@ -40,11 +40,16 @@ fn message_type<M: MessageParams>() -> u16 {
 }
 
 #[derive(Serialize, Deserialize, Debug)]
-pub struct Message {
-    magic: u64,
+pub struct MessageContent {
     pub(crate) ty: u16,
-    // pub(crate) crypto_header: crate::crypto::PacketHeader,
     pub(crate) data: Vec<u8>,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct Message {
+    magic: u64,
+    pub(crate) crypto_header: fleck_core::crypto::PacketHeader,
+    pub(crate) content: MessageContent,
 
     #[serde(skip_serializing)]
     #[serde(skip_deserializing)]
@@ -63,9 +68,11 @@ impl Message {
     pub fn build<M: 'static + MessageParams + Serialize>(from: M) -> Self {
         Self {
             magic: MESSAGE_MAGIC,
-            ty: message_type::<M>(),
-            // crypto_header: Default::default(),
-            data: bincode::serialize(&from).expect("couldn't serialize message"),
+            crypto_header: Default::default(),
+            content: MessageContent {
+                ty: message_type::<M>(),
+                data: bincode::serialize(&from).expect("couldn't serialize message"),
+            },
             saved_params: Some(SavedMessageParams::save::<M>()),
             parsed: Some(Box::new(from)),
             peer: None,
@@ -73,7 +80,7 @@ impl Message {
     }
 
     pub fn is_type<M: MessageParams + DeserializeOwned>(&self) -> bool {
-        self.ty == message_type::<M>()
+        self.content.ty == message_type::<M>()
     }
 
     pub fn downcast<M: MessageParams + DeserializeOwned>(&self) -> Option<&M> {
@@ -81,33 +88,42 @@ impl Message {
     }
 }
 
+pub struct MessageChannelTag;
+pub type MessageChannel<M> = (MessageChannelTag, M);
+
 type Deserializer = dyn Fn(&[u8]) -> Option<Box<dyn std::any::Any>>;
 #[derive(Default)]
-pub struct MessageRegistry {
-    deser: HashMap<u16, Box<Deserializer>>,
+pub struct MessageService {
+    deser: RefCell<HashMap<u16, Box<Deserializer>>>,
 }
 
-impl MessageRegistry {
+impl Service for Rc<MessageService> {
+    fn setup(&self, api: &crate::Fleck) {
+        api.channel::<fleck_core::ReceivePacketChannel>().sub_opt(fleck_core::ReceiveOrder::Parse, self, MessageService::parse);
+    }
+}
+
+impl MessageService {
     pub fn add_message_type<MT: std::fmt::Debug + MessageParams + Serialize + DeserializeOwned>(
-        &mut self,
+        &self, api: &crate::Fleck
     ) {
         let derived_typeid = message_type::<MT>();
-        self.deser.insert(
+        self.deser.borrow_mut().insert(
             derived_typeid,
             Box::new(|data| Some(Box::new(bincode::deserialize::<MT>(data).ok()?))),
         );
+
+        api.create_channel::<MessageChannel<MT>>();
     }
 
-    pub(crate) fn deserialize(&self, message: &mut Message) -> Option<Box<dyn std::any::Any>> {
-        /*match message.crypto_header {
-            crate::crypto::PacketHeader::NoCrypto => {}
-            _ => {
-                log::error!("given packet with crypto still applied to deserialize!");
-                return None;
-            }
-        }*/
+    fn parse(&self, api: &crate::Fleck, mut msg: Message) -> Option<Message> {
+        // try deserializing
+        msg.parsed = Some(self.deserialize(&mut msg)?);
+        None
+    }
 
-        (self.deser.get(&message.ty)?)(&message.data)
+    fn deserialize(&self, message: &mut Message) -> Option<Box<dyn std::any::Any>> {
+        (self.deser.borrow().get(&message.content.ty)?)(&message.content.data)
     }
 }
 

+ 7 - 7
fleck/src/fleck_core/nodes.rs

@@ -4,7 +4,7 @@ use std::{rc::Rc, collections::{HashMap, HashSet}, cell::{RefCell, Ref}};
 
 use crate::prelude::*;
 
-use crate::crypto::{Keypair, PublicKey};
+use fleck_core::crypto::{Keypair, PublicKey};
 
 pub struct InnerRef<'l, T> {
     r: Ref<'l, Option<T>>
@@ -97,12 +97,12 @@ impl Node {
 pub struct RegTag {}
 pub type NodeRegistrationChannel = (RegTag, Rc<Node>);
 
-pub struct Nodes {
+pub struct NodeService {
     all_nodes: RefCell<Vec<Rc<Node>>>,
     self_node: Rc<Node>,
 }
 
-impl Default for Nodes {
+impl Default for NodeService {
     fn default() -> Self {
         let ret = Self {
             all_nodes: Default::default(),
@@ -115,7 +115,7 @@ impl Default for Nodes {
     }
 }
 
-impl Nodes {
+impl NodeService {
     pub fn self_node(&self) -> &Rc<Node> {
         &self.self_node
     }
@@ -135,8 +135,8 @@ impl Nodes {
     }
 }
 
-impl Service for Rc<Nodes> {
-    fn register_channels(&self, eroot: &mut EventRoot) {
-        eroot.create_channel::<NodeRegistrationChannel>();
+impl Service for Rc<NodeService> {
+    fn setup(&self, api: &crate::Fleck) {
+        api.create_channel::<NodeRegistrationChannel>();
     }
 }

+ 2 - 4
fleck/src/fleck_core/peer.rs

@@ -1,11 +1,9 @@
 //! Peer: someone we can communicate with directly
 
-use std::{cell::RefCell, collections::HashMap, rc::Rc};
+use std::rc::Rc;
 
 use crate::prelude::*;
 
-use super::msg::Message;
-
 pub(crate) enum PeerAddress {
     Stream,
     Udp(std::net::SocketAddr),
@@ -35,7 +33,7 @@ impl Service for std::rc::Rc<PeerService> {
     fn setup(&self, api: &crate::Fleck) {
         api.channel::<fleck_core::SendPacketChannel>()
             .as_ref()
-            .sub_opt(fleck_core::SendOrder::Send, self, PeerService::dispatch);
+            .sub_opt(fleck_core::SendOrder::Dispatch, self, PeerService::dispatch);
     }
 }
 

+ 0 - 50
fleck/src/fleck_core/vchannel.rs

@@ -1,50 +0,0 @@
-use std::{collections::HashSet, rc::Rc};
-
-use crate::prelude::*;
-
-pub struct VChannel {
-    
-}
-
-struct VChannelService<Tag: 'static> {
-    _ghost: std::marker::PhantomData<Tag>,
-}
-
-impl<Tag: 'static> Default for VChannelService<Tag> {
-    fn default() -> Self {
-        Self {
-            _ghost: Default::default(),
-        }
-    }
-}
-
-impl<Tag: 'static> Service for Rc<VChannelService<Tag>> {
-    fn register_channels(&self, eroot: &mut EventRoot) {
-        
-    }
-}
-
-#[derive(Default)]
-pub struct VChannelDispatch {
-    vchannels: HashSet<Rc<VChannel>>,
-}
-
-impl Service for std::rc::Rc<VChannelDispatch> {
-    fn register_channels(&self, eroot: &mut EventRoot) {
-        
-    }
-}
-
-impl VChannelDispatch {
-    pub fn link_udp_channel<SourceTag: 'static, SinkTag: 'static>(&self, api: &crate::Fleck) {
-        api.add_service::<VChannelService<(SourceTag, SinkTag)>>();
-    }
-
-    fn stream_receive(&self, api: &crate::Fleck, data: Vec<u8>) -> Option<Vec<u8>> {
-        None
-    }
-
-    fn udp_receive(&self, api: &crate::Fleck, data: (std::net::SocketAddr, Vec<u8>)) -> Option<(std::net::SocketAddr, Vec<u8>)> {
-        None
-    }
-}

+ 1 - 2
fleck/src/lib.rs

@@ -1,6 +1,5 @@
 use std::rc::Rc;
 
-// mod crypto;
 pub mod fleck_core;
 mod helper;
 pub mod service;
@@ -41,7 +40,7 @@ impl Fleck {
         // Actually sending packets
         // self.add_service::<fleck_core::lowlevel::SendPacket>();
         // Parsing incoming packets
-        self.add_service::<fleck_core::msg::ParsePacket>();
+        // self.add_service::<fleck_core::msg::ParsePacket>();
         // Signing packets
         // self.add_service::<crypto::SignPacket>();
     }

+ 0 - 5
fleck/src/service.rs

@@ -34,7 +34,6 @@ pub struct ServiceStack {
     service_map: RefCell<HashMap<TypeId, Box<dyn Service>>>,
 
     eroot: EventRoot,
-    message_registry: fleck_core::msg::MessageRegistry,
 }
 
 impl ServiceStack {
@@ -80,8 +79,4 @@ impl ServiceStack {
     pub fn event_root(&self) -> &EventRoot {
         &self.eroot
     }
-
-    pub fn message_registry(&self) -> &fleck_core::msg::MessageRegistry {
-        &self.message_registry
-    }
 }