diff options
Diffstat (limited to '')
| -rw-r--r-- | src/bin/quassel-client.rs | 14 | ||||
| -rw-r--r-- | src/client/mod.rs | 230 | ||||
| -rw-r--r-- | src/lib.rs | 1 | ||||
| -rw-r--r-- | src/protocol/message/handshake.rs | 215 | ||||
| -rw-r--r-- | src/protocol/message/handshake/types.rs | 49 | ||||
| -rw-r--r-- | src/protocol/message/login.rs | 1 | ||||
| -rw-r--r-- | src/protocol/message/mod.rs | 4 | ||||
| -rw-r--r-- | src/protocol/primitive/basic.rs | 282 | ||||
| -rw-r--r-- | src/protocol/primitive/bufferinfo.rs | 74 | ||||
| -rw-r--r-- | src/protocol/primitive/datetime.rs | 93 | ||||
| -rw-r--r-- | src/protocol/primitive/message.rs | 184 | ||||
| -rw-r--r-- | src/protocol/primitive/mod.rs | 64 | ||||
| -rw-r--r-- | src/protocol/primitive/signedint.rs | 62 | ||||
| -rw-r--r-- | src/protocol/primitive/string.rs | 91 | ||||
| -rw-r--r-- | src/protocol/primitive/stringlist.rs | 45 | ||||
| -rw-r--r-- | src/protocol/primitive/unsignedint.rs | 81 | ||||
| -rw-r--r-- | src/protocol/primitive/variant.rs | 337 | ||||
| -rw-r--r-- | src/protocol/primitive/variantlist.rs | 46 | ||||
| -rw-r--r-- | src/protocol/primitive/variantmap.rs | 63 | ||||
| -rw-r--r-- | src/tests/base_types.rs | 76 | ||||
| -rw-r--r-- | src/tests/handshake_types.rs | 80 | ||||
| -rw-r--r-- | src/tests/mod.rs | 1 | ||||
| -rw-r--r-- | src/tests/variant_types.rs | 73 |
23 files changed, 1392 insertions, 774 deletions
diff --git a/src/bin/quassel-client.rs b/src/bin/quassel-client.rs index ce450b6..9d25088 100644 --- a/src/bin/quassel-client.rs +++ b/src/bin/quassel-client.rs @@ -3,16 +3,22 @@ use failure::Error; extern crate libquassel; use libquassel::client; -#[macro_use] extern crate tokio; +extern crate pretty_env_logger; #[tokio::main] async fn main() -> Result<(), Error> { + pretty_env_logger::init(); - let mut client = client::Client::connect( - "localhost", +// let mut client = client::Client::<tokio::net::TcpStream>::connect( +// "cocaine.farm", +// 4242, +// true, +// ).await.unwrap(); + + let mut client = client::Client::<tokio_tls::TlsStream<tokio::net::TcpStream>>::connect_tls( + "cocaine.farm", 4242, - false, true, ).await.unwrap(); diff --git a/src/client/mod.rs b/src/client/mod.rs index 4ab0601..fbb5b35 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -2,10 +2,16 @@ use std::result::Result; use std::vec::Vec; +use tokio::io::{AsyncRead, AsyncWrite}; +use core::marker::Unpin; use tokio::net::TcpStream; use tokio::prelude::*; -use tokio_util::codec::{Framed}; +use native_tls::TlsConnector; + +use tokio_tls; +use tokio_tls::TlsStream; +use tokio_util::codec::Framed; use futures_util::stream::StreamExt; use futures::SinkExt; @@ -13,102 +19,204 @@ use crate::protocol::frame::QuasselCodec; use failure::Error; +use log::{trace, debug, info, error}; + +use crate::protocol::message::ConnAck; + extern crate log; -// use log::{info, warn, debug}; -pub struct Client { - stream: Framed<TcpStream, QuasselCodec>, +pub struct Client<T: AsyncRead + AsyncWrite + Unpin> { + stream: Framed<T, QuasselCodec>, pub tls: bool, pub compression: bool, + pub state: ClientState, +} + +pub enum ClientState { + Handshake, + Connected, } -impl Client { +impl <T: AsyncRead + AsyncWrite + Unpin> Client<T> { pub async fn run(&mut self) { - // TODO while endlessly loops over same stream element + use crate::protocol::primitive::StringList; + use crate::protocol::message::handshake::ClientInit; + use crate::protocol::message::handshake::HandshakeSerialize; + + info!(target: "init", "Setting Features"); + + let mut features = StringList::new(); + features.push("SynchronizedMarkerLine".to_string()); + features.push("Authenticators".to_string()); + features.push("ExtendedFeatures".to_string()); + let client_init = ClientInit { + client_version:String::from("Rust 0.0.0"), + client_date: String::from("1579009211"), + feature_list: features, + client_features: 0x00008000, + }; + + self.stream.send(client_init.serialize().unwrap()).await.unwrap(); + + // Start event loop while let Some(msg) = self.stream.next().await { - println!("bing"); let msg = msg.unwrap(); - handle_login_message(self, &msg).await.unwrap(); + match self.state { + ClientState::Handshake => handle_login_message(self, &msg).await.unwrap(), + ClientState::Connected => handle_message(self, &msg).await.unwrap(), + } }; - } + } - pub async fn connect(address: &'static str, port: u64, tls: bool, compression: bool) -> Result<Client, Error> { - use crate::protocol::primitive::deserialize::Deserialize; - use crate::protocol::message::ConnAck; - use crate::protocol::primitive::{StringList}; - use crate::protocol::message::ClientInit; - use crate::protocol::message::handshake::HandshakeSerialize; + pub async fn connect(address: &'static str, port: u64, compression: bool) -> Result<Client<TcpStream>, Error> { + let mut stream = TcpStream::connect(format!("{}:{}", address, port)).await?; - let mut s = TcpStream::connect(format!("{}:{}", address, port)).await?; + info!(target: "init", "Establishing Connection"); + let connack = init(&mut stream, false, compression).await?; - // Set Features - let mut init: Vec<u8> = vec![]; - let mut handshake: u32 = 0x42b33f00; - if tls { - handshake |= 0x01; - } - if compression { - handshake |= 0x02; - } - let mut proto: u32 = 0x00000002; - let fin: u32 = 0x80000000; - proto |= fin; - init.extend(handshake.to_be_bytes().iter()); - init.extend(proto.to_be_bytes().iter()); - s.write(&init).await?; + debug!(target: "init", "{:?}", connack); + let codec = QuasselCodec::builder() + .compression(compression) + .new_codec(); - let mut buf = [0; 4]; - s.read(&mut buf).await?; - let (_, val) = ConnAck::parse(&buf).unwrap(); - println!("Received: {:?}", val); + let framed_stream = Framed::new(stream, codec); + + info!(target: "init", "Established Connection"); + + return Ok(Client { + stream: framed_stream, + tls: false, + compression, + state: ClientState::Handshake, + }); + } + + pub async fn connect_tls(address: &'static str, port: u64, compression: bool) -> Result<Client<TlsStream<TcpStream>>, Error> { + let mut stream: TcpStream = TcpStream::connect(format!("{}:{}", address, port)).await?; + + info!(target: "init", "Establishing Connection"); + let connack = init(&mut stream, true, compression).await?; + + debug!(target: "init", "{:?}", connack); let codec = QuasselCodec::builder() .compression(compression) .new_codec(); - let stream = Framed::new(s, codec); - let mut client = Client { - stream: stream, - tls: tls, - compression: compression, - }; + let tls_connector = tokio_tls::TlsConnector::from(TlsConnector::builder().build().unwrap()); - let mut features = StringList::new(); - features.push("SynchronizedMarkerLine".to_string()); - features.push("Authenticators".to_string()); - features.push("ExtendedFeatures".to_string()); - let client_init = ClientInit { - client_version:String::from("Rust 0.0.0"), - client_date: String::from("1579009211"), - feature_list: features, - client_features: 0x00008000, - }; + let tls_stream = tls_connector.connect(address, stream).await?; - client.stream.send(client_init.serialize()?).await?; + let framed_stream = Framed::new(tls_stream, codec); - return Ok(client); + info!(target: "init", "Established Connection"); + + return Ok(Client { + stream: framed_stream, + tls: true, + compression, + state: ClientState::Handshake, + }); } + } -pub async fn handle_login_message(client: &mut Client, buf: &[u8]) -> Result<(), Error> { +pub async fn handle_login_message<T: AsyncRead + AsyncWrite + Unpin>(client: &mut Client<T>, buf: &[u8]) -> Result<(), Error> { use crate::protocol::message::ClientLogin; use crate::protocol::message::handshake::{HandshakeSerialize, HandshakeDeserialize, VariantMap}; - use crate::protocol::error::ProtocolError; use crate::util::get_msg_type; + trace!(target: "message", "Received bytes: {:x?}", buf); let (_, res) = VariantMap::parse(buf)?; - println!("res {:?}", res); + debug!(target: "init", "Received Messsage: {:#?}", res); let msgtype = get_msg_type(&res["MsgType"])?; match msgtype { "ClientInitAck" => { - let login = ClientLogin {user: "audron".to_string(), password: "audron".to_string()}; + info!(target: "init", "Initialization successfull"); + info!(target: "login", "Starting Login"); + let login = ClientLogin {user: "audron".to_string(), password: "***REMOVED***".to_string()}; client.stream.send(login.serialize()?).await?; }, - "ClientInitReject" => { println!("init failed: {:?}", res) }, - "ClientLoginAck" => { println!("login done: {:?}", res) }, - "ClientLoginReject" => { println!("login failed: {:?}", res)}, - _ => bail!(ProtocolError::WrongMsgType) + "ClientInitReject" => { + error!(target: "init", "Initialization failed: {:?}", res); + }, + "ClientLoginAck" => { + info!(target: "login", "Login successfull"); + }, + "SessionInit" => { + info!(target: "message", "Received SessionInit: {:#?}", res); + info!(target: "login", "Session Initialization finished. Switching to Connected state"); + client.state = ClientState::Connected; + } + "ClientLoginReject" => { + error!(target: "login", "Login failed: {:?}", res); + }, + _ => { + error!(target: "client", "Error: WrongMsgType: {:#?}", res); + } } return Ok(()); } + +pub async fn handle_message<T: AsyncRead + AsyncWrite + Unpin>(client: &mut Client<T>, buf: &[u8]) -> Result<(), Error> { + use crate::protocol::primitive::VariantList; + use crate::protocol::primitive::deserialize::Deserialize; + use crate::protocol::primitive::serialize::Serialize; + use crate::util::get_msg_type; + + trace!(target: "message", "Received bytes: {:x?}", buf); + let (_, res) = VariantList::parse(buf)?; + debug!(target: "init", "Received Messsage: {:#?}", res); + // let msgtype = get_msg_type(&res["MsgType"])?; + // match msgtype { + // _ => { + // error!(target: "client", "Error: WrongMsgType: {:#?}", res); + // } + // } + return Ok(()); +} + +// Send the initialization message to the stream +pub async fn init(stream: &mut TcpStream, tls: bool, compression: bool) -> Result<ConnAck, Error> { + use crate::protocol::primitive::deserialize::Deserialize; + + // Buffer for our initialization + let mut init: Vec<u8> = vec![]; + + // The handshake message + let mut handshake: u32 = 0x42b33f00; + + // If TLS is enabled set the TLS bit on the handshake + if tls { + info!(target: "init", "Enabled TLS"); + handshake |= 0x01; + } + + // If COMPRESSION is enabled set the COMPRESSION bit on the handshake + if compression { + info!(target: "init", "Enabled Compression"); + handshake |= 0x02; + } + + // Select Protocol 2: Datastream + let mut proto: u32 = 0x00000002; + + // Flag proto as the last protocol + let fin: u32 = 0x80000000; + proto |= fin; + + // Add handshake and protocol to our buffer + init.extend(handshake.to_be_bytes().iter()); + init.extend(proto.to_be_bytes().iter()); + + // Send Buffer + stream.write(&init).await?; + + // Read Response + let mut buf = [0; 4]; + stream.read(&mut buf).await?; + + let (_, connack) = ConnAck::parse(&buf)?; + Ok(connack) +} @@ -10,6 +10,5 @@ pub mod client; #[cfg(test)] pub mod tests; - #[macro_use] extern crate failure; diff --git a/src/protocol/message/handshake.rs b/src/protocol/message/handshake.rs index b38d03f..357d1a4 100644 --- a/src/protocol/message/handshake.rs +++ b/src/protocol/message/handshake.rs @@ -1,50 +1,67 @@ -use std::result::Result; use failure::Error; +use std::result::Result; use crate::protocol::error::ProtocolError; use crate::protocol::primitive::{String, StringList, Variant, VariantList}; use crate::util::get_msg_type; mod types; -pub use types::{VariantMap, HandshakeDeserialize, HandshakeSerialize, HandshakeQRead}; +pub use types::{HandshakeDeserialize, HandshakeSerialize, VariantMap}; use crate::match_variant; - #[derive(Debug)] pub struct ConnAck { flags: u8, extra: i16, - version: i8 + version: i8, } impl crate::protocol::primitive::deserialize::Deserialize for ConnAck { fn parse(b: &[u8]) -> Result<(usize, Self), Error> { let (flen, flags) = u8::parse(b)?; let (elen, extra) = i16::parse(&b[flen..])?; - let (vlen, version) = i8::parse(&b[(flen+elen)..])?; - - return Ok((flen+elen+vlen, Self {flags, extra, version})); + let (vlen, version) = i8::parse(&b[(flen + elen)..])?; + + return Ok(( + flen + elen + vlen, + Self { + flags, + extra, + version, + }, + )); } } - #[derive(Debug)] pub struct ClientInit { pub client_version: String, // Version of the client - pub client_date: String, // Build date of the client + pub client_date: String, // Build date of the client pub client_features: u32, - pub feature_list: StringList // List of supported extended features + pub feature_list: StringList, // List of supported extended features } impl HandshakeSerialize for ClientInit { fn serialize(&self) -> Result<Vec<u8>, Error> { let mut values: VariantMap = VariantMap::with_capacity(5); - values.insert("MsgType".to_string(), Variant::String("ClientInit".to_string())); - values.insert("ClientVersion".to_string(), Variant::String(self.client_version.clone())); - values.insert("ClientDate".to_string(), Variant::String(self.client_date.clone())); + values.insert( + "MsgType".to_string(), + Variant::String("ClientInit".to_string()), + ); + values.insert( + "ClientVersion".to_string(), + Variant::String(self.client_version.clone()), + ); + values.insert( + "ClientDate".to_string(), + Variant::String(self.client_date.clone()), + ); values.insert("Features".to_string(), Variant::u32(self.client_features)); - values.insert("FeatureList".to_string(), Variant::StringList(self.feature_list.clone())); + values.insert( + "FeatureList".to_string(), + Variant::StringList(self.feature_list.clone()), + ); return HandshakeSerialize::serialize(&values); } } @@ -56,12 +73,15 @@ impl HandshakeDeserialize for ClientInit { let msgtype = get_msg_type(&values["MsgType"])?; if msgtype == "ClientInit" { - return Ok((len, Self { - client_version: match_variant!(values, Variant::String, "ClientVersion"), - client_date: match_variant!(values, Variant::String, "ClientDate"), - feature_list: match_variant!(values, Variant::StringList, "FeatureList"), - client_features: match_variant!(values, Variant::u32, "Features") - })); + return Ok(( + len, + Self { + client_version: match_variant!(values, Variant::String, "ClientVersion"), + client_date: match_variant!(values, Variant::String, "ClientDate"), + feature_list: match_variant!(values, Variant::StringList, "FeatureList"), + client_features: match_variant!(values, Variant::u32, "Features"), + }, + )); } else { bail!(ProtocolError::WrongMsgType); } @@ -70,14 +90,20 @@ impl HandshakeDeserialize for ClientInit { #[derive(Debug)] pub struct ClientInitReject { - pub error_string: String + pub error_string: String, } impl HandshakeSerialize for ClientInitReject { fn serialize(&self) -> Result<Vec<u8>, Error> { let mut values: VariantMap = VariantMap::with_capacity(2); - values.insert("MsgType".to_string(), Variant::String("ClientInitReject".to_string())); - values.insert("ErrorString".to_string(), Variant::String(self.error_string.clone())); + values.insert( + "MsgType".to_string(), + Variant::String("ClientInitReject".to_string()), + ); + values.insert( + "ErrorString".to_string(), + Variant::String(self.error_string.clone()), + ); return HandshakeSerialize::serialize(&values); } } @@ -89,9 +115,12 @@ impl HandshakeDeserialize for ClientInitReject { let msgtype = get_msg_type(&values["MsgType"])?; if msgtype == "ClientInitReject" { - return Ok((len, Self { - error_string: match_variant!(values, Variant::String, "ErrorString") - })); + return Ok(( + len, + Self { + error_string: match_variant!(values, Variant::String, "ErrorString"), + }, + )); } else { bail!(ProtocolError::WrongMsgType); } @@ -100,22 +129,37 @@ impl HandshakeDeserialize for ClientInitReject { #[derive(Debug)] pub struct ClientInitAck { - pub core_features: u32, // Flags of supported legacy features - pub core_configured: bool, // If the core has already been configured + pub core_features: u32, // Flags of supported legacy features + pub core_configured: bool, // If the core has already been configured pub storage_backends: VariantList, // List of VariantMaps of info on available backends - pub authenticators: VariantList, // List of VariantMaps of info on available authenticators - pub feature_list: StringList, // List of supported extended features + pub authenticators: VariantList, // List of VariantMaps of info on available authenticators + pub feature_list: StringList, // List of supported extended features } impl HandshakeSerialize for ClientInitAck { fn serialize(&self) -> Result<Vec<u8>, Error> { let mut values: VariantMap = VariantMap::with_capacity(6); - values.insert("MsgType".to_string(), Variant::String("ClientInitAck".to_string())); + values.insert( + "MsgType".to_string(), + Variant::String("ClientInitAck".to_string()), + ); values.insert("CoreFeatures".to_string(), Variant::u32(self.core_features)); - values.insert("Configured".to_string(), Variant::bool(self.core_configured)); - values.insert("StorageBackends".to_string(), Variant::VariantList(self.storage_backends.clone())); - values.insert("Authenticators".to_string(), Variant::VariantList(self.authenticators.clone())); - values.insert("FeatureList".to_string(), Variant::StringList(self.feature_list.clone())); + values.insert( + "Configured".to_string(), + Variant::bool(self.core_configured), + ); + values.insert( + "StorageBackends".to_string(), + Variant::VariantList(self.storage_backends.clone()), + ); + values.insert( + "Authenticators".to_string(), + Variant::VariantList(self.authenticators.clone()), + ); + values.insert( + "FeatureList".to_string(), + Variant::StringList(self.feature_list.clone()), + ); return HandshakeSerialize::serialize(&values); } } @@ -127,13 +171,20 @@ impl HandshakeDeserialize for ClientInitAck { let msgtype = get_msg_type(&values["MsgType"])?; if msgtype == "ClientInitAck" { - return Ok((len, Self { - core_features: 0x00008000, - core_configured: match_variant!(values, Variant::bool, "Configured"), - storage_backends: match_variant!(values, Variant::VariantList, "StorageBackends"), - authenticators: match_variant!(values, Variant::VariantList, "Authenticators"), - feature_list: match_variant!(values, Variant::StringList, "FeatureList") - })); + return Ok(( + len, + Self { + core_features: 0x00008000, + core_configured: match_variant!(values, Variant::bool, "Configured"), + storage_backends: match_variant!( + values, + Variant::VariantList, + "StorageBackends" + ), + authenticators: match_variant!(values, Variant::VariantList, "Authenticators"), + feature_list: match_variant!(values, Variant::StringList, "FeatureList"), + }, + )); } else { bail!(ProtocolError::WrongMsgType); } @@ -143,15 +194,21 @@ impl HandshakeDeserialize for ClientInitAck { #[derive(Debug)] pub struct ClientLogin { pub user: String, - pub password: String + pub password: String, } impl HandshakeSerialize for ClientLogin { fn serialize(&self) -> Result<Vec<u8>, Error> { let mut values: VariantMap = VariantMap::new(); - values.insert("MsgType".to_string(), Variant::String("ClientLogin".to_string())); + values.insert( + "MsgType".to_string(), + Variant::String("ClientLogin".to_string()), + ); values.insert("User".to_string(), Variant::String(self.user.clone())); - values.insert("Password".to_string(), Variant::String(self.password.clone())); + values.insert( + "Password".to_string(), + Variant::String(self.password.clone()), + ); return HandshakeSerialize::serialize(&values); } } @@ -163,10 +220,13 @@ impl HandshakeDeserialize for ClientLogin { let msgtype = get_msg_type(&values["MsgType"])?; if msgtype == "ClientLogin" { - return Ok((len, Self { - user: match_variant!(values, Variant::String, "User"), - password: match_variant!(values, Variant::String, "Password") - })); + return Ok(( + len, + Self { + user: match_variant!(values, Variant::String, "User"), + password: match_variant!(values, Variant::String, "Password"), + }, + )); } else { bail!(ProtocolError::WrongMsgType); } @@ -179,7 +239,10 @@ pub struct ClientLoginAck; impl HandshakeSerialize for ClientLoginAck { fn serialize(&self) -> Result<Vec<u8>, Error> { let mut values: VariantMap = VariantMap::with_capacity(1); - values.insert("MsgType".to_string(), Variant::String("ClientLoginAck".to_string())); + values.insert( + "MsgType".to_string(), + Variant::String("ClientLoginAck".to_string()), + ); return HandshakeSerialize::serialize(&values); } } @@ -200,14 +263,20 @@ impl HandshakeDeserialize for ClientLoginAck { #[derive(Debug)] pub struct ClientLoginReject { - error: String + error: String, } impl HandshakeSerialize for ClientLoginReject { fn serialize(&self) -> Result<Vec<u8>, Error> { let mut values: VariantMap = VariantMap::with_capacity(1); - values.insert("MsgType".to_string(), Variant::String("ClientLoginReject".to_string())); - values.insert("ErrorString".to_string(), Variant::String(self.error.clone())); + values.insert( + "MsgType".to_string(), + Variant::String("ClientLoginReject".to_string()), + ); + values.insert( + "ErrorString".to_string(), + Variant::String(self.error.clone()), + ); return HandshakeSerialize::serialize(&values); } } @@ -219,7 +288,12 @@ impl HandshakeDeserialize for ClientLoginReject { let msgtype = get_msg_type(&values["MsgType"])?; if msgtype == "ClientLogin" { - return Ok((len, Self { error: match_variant!(values, Variant::String, "ErrorString")})); + return Ok(( + len, + Self { + error: match_variant!(values, Variant::String, "ErrorString"), + }, + )); } else { bail!(ProtocolError::WrongMsgType); } @@ -236,10 +310,22 @@ pub struct SessionInit { impl HandshakeSerialize for SessionInit { fn serialize(&self) -> Result<Vec<u8>, Error> { let mut values: VariantMap = VariantMap::with_capacity(1); - values.insert("MsgType".to_string(), Variant::String("SessionInit".to_string())); - values.insert("Identities".to_string(), Variant::VariantList(self.identities.clone())); - values.insert("BufferInfos".to_string(), Variant::VariantList(self.buffers.clone())); - values.insert("NetworkIds".to_string(), Variant::VariantList(self.network_ids.clone())); + values.insert( + "MsgType".to_string(), + Variant::String("SessionInit".to_string()), + ); + values.insert( + "Identities".to_string(), + Variant::VariantList(self.identities.clone()), + ); + values.insert( + "BufferInfos".to_string(), + Variant::VariantList(self.buffers.clone()), + ); + values.insert( + "NetworkIds".to_string(), + Variant::VariantList(self.network_ids.clone()), + ); return HandshakeSerialize::serialize(&values); } } @@ -251,11 +337,14 @@ impl HandshakeDeserialize for SessionInit { let msgtype = get_msg_type(&values["MsgType"])?; if msgtype == "ClientLogin" { - return Ok((len, Self { - identities: match_variant!(values, Variant::VariantList, "Identities"), - buffers: match_variant!(values, Variant::VariantList, "BufferInfos"), - network_ids: match_variant!(values, Variant::VariantList, "NetworkIds") - })); + return Ok(( + len, + Self { + identities: match_variant!(values, Variant::VariantList, "Identities"), + buffers: match_variant!(values, Variant::VariantList, "BufferInfos"), + network_ids: match_variant!(values, Variant::VariantList, "NetworkIds"), + }, + )); } else { bail!(ProtocolError::WrongMsgType); } diff --git a/src/protocol/message/handshake/types.rs b/src/protocol/message/handshake/types.rs index 0c70914..99864b9 100644 --- a/src/protocol/message/handshake/types.rs +++ b/src/protocol/message/handshake/types.rs @@ -1,28 +1,24 @@ -use std::io::Read; -use std::vec::Vec; -use std::result::Result; -use std::convert::TryInto; use std::collections::HashMap; +use std::convert::TryInto; +use std::result::Result; +use std::vec::Vec; use failure::Error; -use crate::util; -use crate::protocol::primitive::{String, Variant}; -use crate::protocol::primitive::serialize::Serialize; -use crate::protocol::primitive::deserialize::Deserialize; -use crate::protocol::primitive::qread::QRead; use crate::protocol::error::ProtocolError; +use crate::protocol::primitive::deserialize::Deserialize; +use crate::protocol::primitive::serialize::Serialize; +use crate::protocol::primitive::{String, Variant}; +use crate::util; pub trait HandshakeSerialize { fn serialize(&self) -> Result<Vec<u8>, Error>; } pub trait HandshakeDeserialize { - fn parse(b: &[u8]) -> Result<(usize, Self), Error> where Self: std::marker::Sized ; -} - -pub trait HandshakeQRead { - fn read<T: Read>(stream: &mut T, buf: &mut [u8]) -> Result<usize, Error>; + fn parse(b: &[u8]) -> Result<(usize, Self), Error> + where + Self: std::marker::Sized; } pub type VariantMap = HashMap<String, Variant>; @@ -61,33 +57,10 @@ impl HandshakeDeserialize for VariantMap { match name { Variant::String(x) => map.insert(x, value), Variant::StringUTF8(x) => map.insert(x, value), - _ => bail!(ProtocolError::WrongVariant) + _ => bail!(ProtocolError::WrongVariant), }; } return Ok((pos, map)); } } - -impl HandshakeQRead for VariantMap { - fn read<T: Read>(s: &mut T, b: &mut [u8]) -> Result<usize, Error> { - s.read(&mut b[0..4])?; - let (_, len) = i32::parse(&b[0..4])?; - - let mut pos = 4; - for _ in 0..(len / 2) { - pos += Variant::read(s, &mut b[pos..])?; - pos += Variant::read(s, &mut b[pos..])?; - } - -// let mut pos = 8; -// let len: usize = len as usize; -// loop { -// if pos >= len { break; } -// pos += Variant::read(s, &mut b[pos..])?; -// pos += Variant::read(s, &mut b[pos..])?; -// } - - return Ok(pos); - } -} diff --git a/src/protocol/message/login.rs b/src/protocol/message/login.rs new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/src/protocol/message/login.rs @@ -0,0 +1 @@ + diff --git a/src/protocol/message/mod.rs b/src/protocol/message/mod.rs index 3b6d1a8..f1d4750 100644 --- a/src/protocol/message/mod.rs +++ b/src/protocol/message/mod.rs @@ -1,3 +1,5 @@ pub mod handshake; - pub use handshake::*; + +pub mod login; +pub use login::*; diff --git a/src/protocol/primitive/basic.rs b/src/protocol/primitive/basic.rs deleted file mode 100644 index c9f462d..0000000 --- a/src/protocol/primitive/basic.rs +++ /dev/null @@ -1,282 +0,0 @@ -#[allow(dead_code)] -pub const VOID: u32 = 0x00000000; -pub const BOOL: u32 = 0x00000001; -pub const QCHAR: u32 = 0x00000007; - -pub const QVARIANT: u32 = 0x00000090; -pub const QVARIANTMAP: u32 = 0x00000008; -pub const QVARIANTLIST: u32 = 0x00000009; - -pub const QSTRING: u32 = 0x0000000a; -pub const QSTRINGLIST: u32 = 0x0000000b; -pub const QBYTEARRAY: u32 = 0x0000000c; - -pub const QTIME: u32 = 0x0000000f; -pub const QDATETIME: u32 = 0x00000010; -pub const USERTYPE: u32 = 0x0000007f; - - -// Basic types -pub const LONG: u32 = 0x00000081; // int64_t -pub const INT: u32 = 0x00000002; // int32_t -pub const SHORT: u32 = 0x00000082; // int16_t -pub const CHAR: u32 = 0x00000083; // int8_t - -pub const ULONG: u32 = 0x00000084; // uint64_t -pub const UINT: u32 = 0x00000003; // uint32_t -pub const USHORT: u32 = 0x00000085; // uint16_t -pub const UCHAR: u32 = 0x00000086; // uint8_t - -extern crate byteorder; -use std::io::Cursor; -use byteorder::{BigEndian, ReadBytesExt}; - -use std::vec::Vec; -use std::result::Result; -use std::convert::TryInto; - -use failure::Error; - -use crate::util; -use crate::protocol::error::ProtocolError; -use crate::protocol::primitive::{deserialize, serialize, qread}; - -impl deserialize::Deserialize for bool { - fn parse(b: &[u8]) -> Result<(usize, Self), Error> { - if b[0] == 0 { - return Ok((1, false)) - } else if b[0] == 1 { - return Ok((1, true)) - } else { - bail!(ProtocolError::BoolOutOfRange); - }; - } -} - -impl qread::QRead for bool { - fn read<T: std::io::Read>(s: &mut T, b: &mut [u8]) -> Result<usize, Error> { - Ok(s.read(&mut b[0..1])?) - } -} - -impl deserialize::Deserialize for u64 { - fn parse(b: &[u8]) -> Result<(usize, Self), Error> { - let mut rdr = Cursor::new(&b[0..8]); - return Ok((8, rdr.read_u64::<BigEndian>()?)); - } -} - -impl qread::QRead for u64 { - fn read<T: std::io::Read>(s: &mut T, b: &mut [u8]) -> Result<usize, Error> { - Ok(s.read(&mut b[0..8])?) - } -} - -impl deserialize::Deserialize for u32 { - fn parse(b: &[u8]) -> Result<(usize, Self), Error> { - let mut rdr = Cursor::new(&b[0..4]); - return Ok((4, rdr.read_u32::<BigEndian>()?)); - } -} - -impl qread::QRead for u32 { - fn read<T: std::io::Read>(s: &mut T, b: &mut [u8]) -> Result<usize, Error> { - Ok(s.read(&mut b[0..4])?) - } -} - -impl deserialize::Deserialize for u16 { - fn parse(b: &[u8]) -> Result<(usize, Self), Error> { - let mut rdr = Cursor::new(&b[0..2]); - return Ok((2, rdr.read_u16::<BigEndian>()?)); - } -} - -impl qread::QRead for u16 { - fn read<T: std::io::Read>(s: &mut T, b: &mut [u8]) -> Result<usize, Error> { - Ok(s.read(&mut b[0..2])?) - } -} - -impl deserialize::Deserialize for u8 { - fn parse(b: &[u8]) -> Result<(usize, Self), Error> { - return Ok((1, b[0])); - } -} - -impl qread::QRead for u8 { - fn read<T: std::io::Read>(s: &mut T, b: &mut [u8]) -> Result<usize, Error> { - Ok(s.read(&mut [b[0]])?) - } -} - -impl deserialize::Deserialize for i64 { - fn parse(b: &[u8]) -> Result<(usize, Self), Error> { - let mut rdr = Cursor::new(&b[0..8]); - return Ok((8, rdr.read_i64::<BigEndian>()?)); - } -} - -impl qread::QRead for i64 { - fn read<T: std::io::Read>(s: &mut T, b: &mut [u8]) -> Result<usize, Error> { - Ok(s.read(&mut b[0..8])?) - } -} - -impl deserialize::Deserialize for i32 { - fn parse(b: &[u8]) -> Result<(usize, Self), Error> { - let mut rdr = Cursor::new(&b[0..4]); - return Ok((4, rdr.read_i32::<BigEndian>()?)); - } -} - -impl qread::QRead for i32 { - fn read<T: std::io::Read>(s: &mut T, b: &mut [u8]) -> Result<usize, Error> { - Ok(s.read(&mut b[0..4])?) - } -} - -impl deserialize::Deserialize for i16 { - fn parse(b: &[u8]) -> Result<(usize, Self), Error> { - let mut rdr = Cursor::new(&b[0..2]); - return Ok((2, rdr.read_i16::<BigEndian>()?)); - } -} - -impl qread::QRead for i16 { - fn read<T: std::io::Read>(s: &mut T, b: &mut [u8]) -> Result<usize, Error> { - Ok(s.read(&mut b[0..2])?) - } -} - -impl deserialize::Deserialize for i8 { - fn parse(b: &[u8]) -> Result<(usize, Self), Error> { - return Ok((1, b[0].try_into()?)); - } -} - -impl qread::QRead for i8 { - fn read<T: std::io::Read>(s: &mut T, b: &mut [u8]) -> Result<usize, Error> { - return Ok(s.read(&mut [b[0]])?) - } -} - - - -pub type String = std::string::String; -impl serialize::Serialize for String { - fn serialize(&self) -> Result<Vec<u8>, Error> { - let mut res: Vec<u8> = Vec::new(); - - let utf16: Vec<u16> = self.encode_utf16().collect(); - for i in utf16 { - res.extend(i.to_be_bytes().iter()); - } - - util::prepend_byte_len(&mut res); - return Ok(res); - } -} - -impl serialize::SerializeUTF8 for String { - fn serialize_utf8(&self) -> Result<Vec<u8>, Error> { - let mut res: Vec<u8> = Vec::new(); - res.extend(self.clone().into_bytes()); - util::prepend_byte_len(&mut res); - return Ok(res); - } -} - -impl deserialize::Deserialize for String { - fn parse(b: &[u8]) -> Result<(usize, Self), Error> { - let (_, len) = i32::parse(&b[0..4])?; - - let ulen = len as usize; - let mut pos: usize = 4; - let mut chars: Vec<u16> = Vec::new(); - loop { - if pos >= (ulen + 4) { break; } - let (slen, uchar) = u16::parse(&b[pos..(pos+2)])?; - chars.push(uchar); - pos += slen; - } - - let res: String = String::from_utf16(&chars).unwrap(); - return Ok((pos, res)); - } -} - -impl deserialize::DeserializeUTF8 for String { - fn parse_utf8(b: &[u8]) -> Result<(usize, Self), Error> { - use crate::protocol::primitive::deserialize::Deserialize; - let (_, len) = i32::parse(&b[0..4])?; - - let ulen = len as usize; - - let res: String = String::from_utf8(b[4..(ulen+4)].to_vec())?; - return Ok((ulen + 4, res)); - } -} - -impl qread::QRead for String { - fn read<T: std::io::Read>(s: &mut T, b: &mut [u8]) -> Result<usize, Error> { - use crate::protocol::primitive::deserialize::Deserialize; - - s.read(&mut b[0..4])?; - let (_, len) = i32::parse(&b[0..4])?; - - let ulen = len as usize; - s.read(&mut b[4..(4+ulen)])?; - - return Ok(4 + ulen); - } -} - -pub type StringList = Vec<String>; -impl serialize::Serialize for StringList { - fn serialize(&self) -> Result<Vec<u8>, Error> { - let len: i32 = self.len().try_into()?; - let mut res: Vec<u8> = Vec::new(); - - res.extend(len.to_be_bytes().iter()); - for x in self { - res.extend(x.serialize()?); - } - - return Ok(res); - } -} - -impl deserialize::Deserialize for StringList { - fn parse(b: &[u8]) -> Result<(usize, Self), Error> { - let (_, len) = i32::parse(&b[0..4])?; - let mut res: StringList = StringList::new(); - - let mut pos = 4; - if len > 0 { - for _ in 0..len { - let (lpos, val) = String::parse(&b[pos..])?; - pos += lpos; - res.push(val); - } - } - - return Ok((pos, res)); - } -} - -impl qread::QRead for StringList { - fn read<T: std::io::Read>(s: &mut T, b: &mut [u8]) -> Result<usize, Error> { - use crate::protocol::primitive::deserialize::Deserialize; - - s.read(&mut b[0..4])?; - let (_, len) = i32::parse(&b[0..4])?; - - let mut pos: usize = 4; - for _ in 0..len { - pos += String::read(s, &mut b[pos..])?; - } - - return Ok(pos); - } -} diff --git a/src/protocol/primitive/bufferinfo.rs b/src/protocol/primitive/bufferinfo.rs new file mode 100644 index 0000000..4c69286 --- /dev/null +++ b/src/protocol/primitive/bufferinfo.rs @@ -0,0 +1,74 @@ +use std::vec::Vec; + +use failure::Error; + +use crate::protocol::primitive::deserialize::{Deserialize, DeserializeUTF8}; +use crate::protocol::primitive::serialize::{Serialize, SerializeUTF8}; +use crate::protocol::primitive::String; + +extern crate bytes; + +#[derive(Clone, Debug, std::cmp::PartialEq)] +pub struct BufferInfo { + pub id: i32, // a unique, sequential id for the buffer + pub network_id: i32, // NetworkId of the network the buffer belongs to + pub buffer_type: BufferType, + pub name: String, // BufferName as displayed to the user +} + +impl Serialize for BufferInfo { + fn serialize(&self) -> Result<Vec<u8>, Error> { + let mut values: Vec<u8> = Vec::new(); + + values.append(&mut i32::serialize(&self.id)?); + values.append(&mut i32::serialize(&self.network_id)?); + values.append(&mut i16::serialize(&(self.buffer_type as i16))?); + values.append(&mut vec![0, 0, 0, 0]); + values.append(&mut String::serialize_utf8(&self.name)?); + + Ok(values) + } +} + +impl Deserialize for BufferInfo { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + let (_, id) = i32::parse(&b[0..4])?; + let (_, network_id) = i32::parse(&b[4..8])?; + let (_, buffer_type) = i16::parse(&b[8..10])?; + + // There are 4 additional undocumted Bytes in the BufferInfo + // so we start at byte 14 + let (size, name) = String::parse_utf8(&b[14..])?; + + return Ok(( + 14 + size, + Self { + id, + network_id, + buffer_type: BufferType::from(buffer_type), + name, + }, + )); + } +} + +#[repr(i16)] +#[derive(Copy, Clone, Debug, std::cmp::PartialEq)] +pub enum BufferType { + Status = 0x01, + Channel = 0x02, + Query = 0x04, + Group = 0x08, +} + +impl From<i16> for BufferType { + fn from(value: i16) -> Self { + match value { + 0x01 => return Self::Status, + 0x02 => return Self::Channel, + 0x04 => return Self::Query, + 0x08 => return Self::Group, + _ => unimplemented!(), + } + } +} diff --git a/src/protocol/primitive/datetime.rs b/src/protocol/primitive/datetime.rs new file mode 100644 index 0000000..688a022 --- /dev/null +++ b/src/protocol/primitive/datetime.rs @@ -0,0 +1,93 @@ +use crate::protocol::primitive::deserialize::Deserialize; +use crate::protocol::primitive::serialize::Serialize; + +#[derive(Clone, Debug, std::cmp::PartialEq)] +pub struct DateTime { + julian_day: i32, // Day in Julian calendar, unknown if signed or unsigned + millis_of_day: i32, // Milliseconds since start of day + zone: u8, // Timezone of DateTime, 0x00 is local, 0x01 is UTC +} + +impl Serialize for DateTime { + fn serialize(&self) -> Result<Vec<std::primitive::u8>, failure::Error> { + let mut values: Vec<u8> = Vec::new(); + + values.append(&mut i32::serialize(&self.julian_day)?); + values.append(&mut i32::serialize(&self.millis_of_day)?); + values.append(&mut u8::serialize(&(self.zone))?); + + Ok(values) + } +} + +impl Deserialize for DateTime { + fn parse(b: &[std::primitive::u8]) -> Result<(std::primitive::usize, Self), failure::Error> + where + Self: Sized, + { + let (_, julian_day) = i32::parse(&b[0..4])?; + let (_, millis_of_day) = i32::parse(&b[4..8])?; + let (_, zone) = u8::parse(&b[8..9])?; + + return Ok(( + 9, + DateTime { + julian_day, + millis_of_day, + zone, + }, + )); + } +} + +#[derive(Clone, Debug, std::cmp::PartialEq)] +pub struct Date { + julian_day: i32, // Day in Julian calendar, unknown if signed or unsigned +} + +impl Serialize for Date { + fn serialize(&self) -> Result<Vec<std::primitive::u8>, failure::Error> { + let mut values: Vec<u8> = Vec::new(); + + values.append(&mut i32::serialize(&self.julian_day)?); + + Ok(values) + } +} + +impl Deserialize for Date { + fn parse(b: &[std::primitive::u8]) -> Result<(std::primitive::usize, Self), failure::Error> + where + Self: Sized, + { + let (_, julian_day) = i32::parse(&b[0..4])?; + + return Ok((9, Date { julian_day })); + } +} + +#[derive(Clone, Debug, std::cmp::PartialEq)] +pub struct Time { + millis_of_day: i32, // Milliseconds since start of day +} + +impl Serialize for Time { + fn serialize(&self) -> Result<Vec<std::primitive::u8>, failure::Error> { + let mut values: Vec<u8> = Vec::new(); + + values.append(&mut i32::serialize(&self.millis_of_day)?); + + Ok(values) + } +} + +impl Deserialize for Time { + fn parse(b: &[std::primitive::u8]) -> Result<(std::primitive::usize, Self), failure::Error> + where + Self: Sized, + { + let (_, millis_of_day) = i32::parse(&b[0..4])?; + + return Ok((4, Time { millis_of_day })); + } +} diff --git a/src/protocol/primitive/message.rs b/src/protocol/primitive/message.rs new file mode 100644 index 0000000..4ae895d --- /dev/null +++ b/src/protocol/primitive/message.rs @@ -0,0 +1,184 @@ +use std::vec::Vec; + +use failure::Error; + +use crate::protocol::primitive::deserialize::{Deserialize, DeserializeUTF8}; +use crate::protocol::primitive::serialize::{Serialize, SerializeUTF8}; + +use crate::protocol::primitive::BufferInfo; +use crate::protocol::primitive::String; + +extern crate bytes; + +#[derive(Clone, Debug, std::cmp::PartialEq)] +pub struct Message { + pub msg_id: i32, // The unique, sequential id for the message + pub timestamp: i64, // The timestamp of the message in UNIX time (32-bit, seconds, 64-bit if LONGMESSAGE feature enabled) + pub msg_type: MessageType, + pub flags: i8, + pub buffer: BufferInfo, // The buffer the message belongs to, usually everything but BufferId is set to NULL + pub sender: String, // The sender as nick!ident@host + pub sender_prefixes: Option<String>, // The prefix modes of the sender + pub real_name: Option<String>, // The realName of the sender + pub avatar_url: Option<String>, // The avatarUrl of the sender, if available + pub content: String, // The message content, already stripped from CTCP formatting, but containing mIRC format codes +} + +impl Serialize for Message { + fn serialize(&self) -> Result<Vec<u8>, Error> { + let mut values: Vec<u8> = Vec::new(); + + values.append(&mut i32::serialize(&self.msg_id)?); + + // TODO LONGMESSAGE feature + if false { + values.append(&mut i64::serialize(&self.timestamp)?); + } else { + values.append(&mut i32::serialize(&(self.timestamp as i32))?); + } + + values.append(&mut i32::serialize(&(self.msg_type as i32))?); + values.append(&mut i8::serialize(&(self.flags as i8))?); + values.append(&mut BufferInfo::serialize(&self.buffer)?); + values.append(&mut String::serialize_utf8(&self.sender)?); + + // TODO SenderPrefixes feature + if false { + if let Some(x) = &self.sender_prefixes { + values.append(&mut String::serialize_utf8(&x)?); + } + } + + // TODO RichMessages feature + if false { + if let Some(x) = &self.real_name { + values.append(&mut String::serialize_utf8(&x)?); + } + if let Some(x) = &self.avatar_url { + values.append(&mut String::serialize_utf8(&x)?); + } + } + + values.append(&mut String::serialize_utf8(&self.content)?); + + return Ok(values); + } +} + +impl Deserialize for Message { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + let mut pos = 0; + let (parsed, msg_id) = i32::parse(&b[pos..])?; + pos += parsed; + + // TODO LONGMESSAGES feature + let timestamp; + if false { + let (parsed, temp_timestamp) = i64::parse(&b[pos..])?; + pos += parsed; + timestamp = temp_timestamp; + } else { + let (parsed, temp_timestamp) = i32::parse(&b[pos..])?; + pos += parsed; + timestamp = temp_timestamp as i64; + } + + let (parsed, msg_type) = i32::parse(&b[pos..])?; + pos += parsed; + let (parsed, flags) = i8::parse(&b[pos..])?; + pos += parsed; + let (parsed, buffer) = BufferInfo::parse(&b[pos..])?; + pos += parsed; + let (parsed, sender) = String::parse_utf8(&b[pos..])?; + pos += parsed; + + // TODO SenderPrefixes feature + let mut sender_prefixes = None; + if false { + let (parsed, temp) = String::parse_utf8(&b[pos..])?; + sender_prefixes = Some(temp); + pos += parsed; + } + + // TODO SenderPrefixes feature + let mut real_name = None; + let mut avatar_url = None; + if false { + let (parsed, temp) = String::parse_utf8(&b[pos..])?; + real_name = Some(temp); + pos += parsed; + + let (parsed, temp) = String::parse_utf8(&b[pos..])?; + avatar_url = Some(temp); + pos += parsed; + } + + let (parsed, content) = String::parse_utf8(&b[pos..])?; + pos += parsed; + + return Ok(( + pos, + Self { + msg_id, + timestamp, + msg_type: MessageType::from(msg_type), + flags, + buffer, + sender, + sender_prefixes, + real_name, + avatar_url, + content, + }, + )); + } +} + +#[repr(i32)] +#[derive(Copy, Clone, Debug, std::cmp::PartialEq)] +pub enum MessageType { + Plain = 0x00000001, + Notice = 0x00000002, + Action = 0x00000004, + Nick = 0x00000008, + Mode = 0x00000010, + Join = 0x00000020, + Part = 0x00000040, + Quit = 0x00000080, + Kick = 0x00000100, + Kill = 0x00000200, + Server = 0x00000400, + Info = 0x00000800, + Error = 0x00001000, + DayChange = 0x00002000, + Topic = 0x00004000, + NetsplitJoin = 0x00008000, + NetsplitQuit = 0x00010000, + Invite = 0x00020000, +} + +impl From<i32> for MessageType { + fn from(val: i32) -> Self { + match val { + 0x00000001 => MessageType::Plain, + 0x00000002 => MessageType::Notice, + 0x00000004 => MessageType::Action, + 0x00000008 => MessageType::Nick, + 0x00000010 => MessageType::Mode, + 0x00000020 => MessageType::Join, + 0x00000040 => MessageType::Part, + 0x00000080 => MessageType::Quit, + 0x00000100 => MessageType::Kick, + 0x00000200 => MessageType::Kill, + 0x00000400 => MessageType::Server, + 0x00000800 => MessageType::Info, + 0x00001000 => MessageType::Error, + 0x00002000 => MessageType::DayChange, + 0x00004000 => MessageType::Topic, + 0x00008000 => MessageType::NetsplitJoin, + 0x00010000 => MessageType::NetsplitQuit, + 0x00020000 => MessageType::Invite, + _ => unimplemented!(), + } + } +} diff --git a/src/protocol/primitive/mod.rs b/src/protocol/primitive/mod.rs index fb843ad..5656d71 100644 --- a/src/protocol/primitive/mod.rs +++ b/src/protocol/primitive/mod.rs @@ -1,10 +1,53 @@ -#[allow(dead_code)] -pub mod basic; +pub mod bufferinfo; +pub mod datetime; +pub mod message; +pub mod signedint; +pub mod string; +pub mod stringlist; +pub mod unsignedint; pub mod variant; +pub mod variantlist; +pub mod variantmap; -pub use basic::*; +pub use bufferinfo::*; +pub use datetime::*; +pub use message::*; +pub use signedint::*; +pub use string::*; +pub use stringlist::*; +pub use unsignedint::*; pub use variant::*; +pub use variantlist::*; +pub use variantmap::*; +// Static Type Definitions +pub const VOID: u32 = 0x00000000; +pub const BOOL: u32 = 0x00000001; +pub const QCHAR: u32 = 0x00000007; + +pub const QVARIANT: u32 = 0x00000090; +pub const QVARIANTMAP: u32 = 0x00000008; +pub const QVARIANTLIST: u32 = 0x00000009; + +pub const QSTRING: u32 = 0x0000000a; +pub const QSTRINGLIST: u32 = 0x0000000b; +pub const QBYTEARRAY: u32 = 0x0000000c; + +pub const QDATE: u32 = 0x0000000e; +pub const QTIME: u32 = 0x0000000f; +pub const QDATETIME: u32 = 0x00000010; +pub const USERTYPE: u32 = 0x0000007f; + +// Basic types +pub const LONG: u32 = 0x00000081; // int64_t +pub const INT: u32 = 0x00000002; // int32_t +pub const SHORT: u32 = 0x00000082; // int16_t +pub const CHAR: u32 = 0x00000083; // int8_t + +pub const ULONG: u32 = 0x00000084; // uint64_t +pub const UINT: u32 = 0x00000003; // uint32_t +pub const USHORT: u32 = 0x00000085; // uint16_t +pub const UCHAR: u32 = 0x00000086; // uint8_t pub mod serialize { use failure::Error; @@ -19,16 +62,13 @@ pub mod serialize { pub mod deserialize { use failure::Error; pub trait Deserialize { - fn parse(b: &[u8]) -> Result<(usize, Self), Error> where Self: std::marker::Sized ; + fn parse(b: &[u8]) -> Result<(usize, Self), Error> + where + Self: std::marker::Sized; } pub trait DeserializeUTF8 { - fn parse_utf8(b: &[u8]) -> Result<(usize, Self), Error> where Self: std::marker::Sized ; - } -} - -pub mod qread { - use failure::Error; - pub trait QRead { - fn read<T: std::io::Read>(stream: &mut T, buf: &mut [u8]) -> Result<usize, Error>; + fn parse_utf8(b: &[u8]) -> Result<(usize, Self), Error> + where + Self: std::marker::Sized; } } diff --git a/src/protocol/primitive/signedint.rs b/src/protocol/primitive/signedint.rs new file mode 100644 index 0000000..67ffb9d --- /dev/null +++ b/src/protocol/primitive/signedint.rs @@ -0,0 +1,62 @@ +extern crate byteorder; +use byteorder::{BigEndian, ReadBytesExt}; +use std::io::Cursor; + +use std::convert::TryInto; +use std::result::Result; +use std::vec::Vec; + +use failure::Error; + +use crate::protocol::primitive::{deserialize, serialize}; + +impl serialize::Serialize for i64 { + fn serialize(&self) -> Result<Vec<u8>, Error> { + Ok(Vec::from(self.to_be_bytes())) + } +} + +impl deserialize::Deserialize for i64 { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + let mut rdr = Cursor::new(&b[0..8]); + return Ok((8, rdr.read_i64::<BigEndian>()?)); + } +} + +impl serialize::Serialize for i32 { + fn serialize(&self) -> Result<Vec<u8>, Error> { + Ok(Vec::from(self.to_be_bytes())) + } +} + +impl deserialize::Deserialize for i32 { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + let mut rdr = Cursor::new(&b[0..4]); + return Ok((4, rdr.read_i32::<BigEndian>()?)); + } +} + +impl serialize::Serialize for i16 { + fn serialize(&self) -> Result<Vec<u8>, Error> { + Ok(Vec::from(self.to_be_bytes())) + } +} + +impl deserialize::Deserialize for i16 { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + let mut rdr = Cursor::new(&b[0..2]); + return Ok((2, rdr.read_i16::<BigEndian>()?)); + } +} + +impl serialize::Serialize for i8 { + fn serialize(&self) -> Result<Vec<u8>, Error> { + Ok(Vec::from(self.to_be_bytes())) + } +} + +impl deserialize::Deserialize for i8 { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + return Ok((1, b[0].try_into()?)); + } +} diff --git a/src/protocol/primitive/string.rs b/src/protocol/primitive/string.rs new file mode 100644 index 0000000..470f018 --- /dev/null +++ b/src/protocol/primitive/string.rs @@ -0,0 +1,91 @@ +extern crate byteorder; + +use std::result::Result; +use std::vec::Vec; + +use failure::Error; + +use log::trace; + +use crate::protocol::primitive::{deserialize, serialize}; +use crate::util; + +pub type String = std::string::String; +impl serialize::Serialize for String { + fn serialize(&self) -> Result<Vec<u8>, Error> { + let mut res: Vec<u8> = Vec::new(); + + let utf16: Vec<u16> = self.encode_utf16().collect(); + for i in utf16 { + res.extend(i.to_be_bytes().iter()); + } + + util::prepend_byte_len(&mut res); + return Ok(res); + } +} + +impl serialize::SerializeUTF8 for String { + fn serialize_utf8(&self) -> Result<Vec<u8>, Error> { + let mut res: Vec<u8> = Vec::new(); + res.extend(self.clone().into_bytes()); + res.extend(vec![0x00]); + util::prepend_byte_len(&mut res); + return Ok(res); + } +} + +impl deserialize::Deserialize for String { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + // Parse Length + let (_, len) = i32::parse(&b[0..4])?; + trace!(target: "protocol::primitive::String", "Parsing with length: {:?}, from bytes: {:x?}", len, &b[0..4]); + + if len == -1 { + return Ok((4, "".to_string())); + } + + // length as usize + let ulen = len as usize; + let mut pos: usize = 4; + let mut chars: Vec<u16> = Vec::new(); + loop { + // if position is behind the length plus our 4 bytes of the length we already parsed + if pos >= (ulen + 4) { + break; + } + let (slen, uchar) = u16::parse(&b[pos..(pos + 2)])?; + chars.push(uchar); + pos += slen; + } + + let res: String = String::from_utf16(&chars).unwrap(); + return Ok((pos, res)); + } +} + +impl deserialize::DeserializeUTF8 for String { + fn parse_utf8(b: &[u8]) -> Result<(usize, Self), Error> { + use crate::protocol::primitive::deserialize::Deserialize; + let (_, len) = i32::parse(&b[0..4])?; + + trace!(target: "protocol::primitive::String", "Parsing with length: {:?}, from bytes: {:x?}", len, &b[0..4]); + + if len <= 0 { + return Ok((4, "".to_string())); + } + + let ulen = len as usize; + + let mut res: String = String::from_utf8(b[4..(ulen + 4)].to_vec())?; + + // If the last byte is zero remove it + // Receiving a string as bytearray will sometimes have + // the string null terminated + if res.chars().last().unwrap() == '\u{0}' { + let _ = res.pop(); + } + + return Ok((ulen + 4, res)); + } +} diff --git a/src/protocol/primitive/stringlist.rs b/src/protocol/primitive/stringlist.rs new file mode 100644 index 0000000..d2902f2 --- /dev/null +++ b/src/protocol/primitive/stringlist.rs @@ -0,0 +1,45 @@ +extern crate byteorder; + +use std::convert::TryInto; +use std::result::Result; +use std::vec::Vec; + +use failure::Error; + +use log::trace; + +use crate::protocol::primitive::{deserialize, serialize}; + +pub type StringList = Vec<String>; +impl serialize::Serialize for StringList { + fn serialize(&self) -> Result<Vec<u8>, Error> { + let len: i32 = self.len().try_into()?; + let mut res: Vec<u8> = Vec::new(); + + res.extend(len.to_be_bytes().iter()); + for x in self { + res.extend(x.serialize()?); + } + + return Ok(res); + } +} + +impl deserialize::Deserialize for StringList { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + let (_, len) = i32::parse(&b[0..4])?; + trace!(target: "protocol::primitive::StringList", "Parsing with length: {:?}, from bytes: {:x?}", len, &b[0..4]); + let mut res: StringList = StringList::new(); + + let mut pos = 4; + if len > 0 { + for _ in 0..len { + let (lpos, val) = String::parse(&b[pos..])?; + pos += lpos; + res.push(val); + } + } + + return Ok((pos, res)); + } +} diff --git a/src/protocol/primitive/unsignedint.rs b/src/protocol/primitive/unsignedint.rs new file mode 100644 index 0000000..5b42e3c --- /dev/null +++ b/src/protocol/primitive/unsignedint.rs @@ -0,0 +1,81 @@ +extern crate byteorder; +use byteorder::{BigEndian, ReadBytesExt}; +use std::io::Cursor; + +use std::result::Result; +use std::vec::Vec; + +use failure::Error; + +use crate::protocol::error::ProtocolError; +use crate::protocol::primitive::{deserialize, serialize}; + +impl serialize::Serialize for bool { + fn serialize(&self) -> Result<Vec<u8>, Error> { + Ok({ + let i = *self as i8; + Vec::from(i.to_be_bytes()) + }) + } +} +impl deserialize::Deserialize for bool { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + if b[0] == 0 { + return Ok((1, false)); + } else if b[0] == 1 { + return Ok((1, true)); + } else { + bail!(ProtocolError::BoolOutOfRange); + }; + } +} +impl serialize::Serialize for u64 { + fn serialize(&self) -> Result<Vec<u8>, Error> { + Ok(Vec::from(self.to_be_bytes())) + } +} + +impl deserialize::Deserialize for u64 { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + let mut rdr = Cursor::new(&b[0..8]); + return Ok((8, rdr.read_u64::<BigEndian>()?)); + } +} + +impl serialize::Serialize for u32 { + fn serialize(&self) -> Result<Vec<u8>, Error> { + Ok(Vec::from(self.to_be_bytes())) + } +} + +impl deserialize::Deserialize for u32 { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + let mut rdr = Cursor::new(&b[0..4]); + return Ok((4, rdr.read_u32::<BigEndian>()?)); + } +} + +impl serialize::Serialize for u16 { + fn serialize(&self) -> Result<Vec<u8>, Error> { + Ok(Vec::from(self.to_be_bytes())) + } +} + +impl deserialize::Deserialize for u16 { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + let mut rdr = Cursor::new(&b[0..2]); + return Ok((2, rdr.read_u16::<BigEndian>()?)); + } +} + +impl serialize::Serialize for u8 { + fn serialize(&self) -> Result<Vec<u8>, Error> { + Ok(Vec::from(self.to_be_bytes())) + } +} + +impl deserialize::Deserialize for u8 { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + return Ok((1, b[0])); + } +} diff --git a/src/protocol/primitive/variant.rs b/src/protocol/primitive/variant.rs index 1c90574..84150a8 100644 --- a/src/protocol/primitive/variant.rs +++ b/src/protocol/primitive/variant.rs @@ -1,130 +1,37 @@ -use std::io::Read; use std::vec::Vec; -use std::convert::TryInto; -use std::collections::HashMap; use failure::Error; -use crate::util; -use crate::protocol::primitive::serialize::{Serialize, SerializeUTF8}; -use crate::protocol::primitive::deserialize::{Deserialize, DeserializeUTF8}; -use crate::protocol::primitive::qread::QRead; -use crate::protocol::primitive::{String,StringList}; +use log::{error, trace}; + use crate::protocol::error::ProtocolError; use crate::protocol::primitive; +use crate::protocol::primitive::deserialize::{Deserialize, DeserializeUTF8}; +use crate::protocol::primitive::serialize::{Serialize, SerializeUTF8}; +use crate::protocol::primitive::{String, StringList}; -pub type VariantMap = HashMap<String, Variant>; - -impl Serialize for VariantMap { - fn serialize<'a>(&'a self) -> Result<Vec<u8>, Error> { - let mut res: Vec<u8> = Vec::new(); - - for (k, v) in self { - res.extend(k.serialize()?); - res.extend(v.serialize()?); - } - - let len: i32 = self.len().try_into()?; - util::insert_bytes(0, &mut res, &mut len.to_be_bytes()); - - return Ok(res); - } -} - -impl Deserialize for VariantMap { - fn parse(b: &[u8]) -> Result<(usize, Self), Error> { - let (_, len) = i32::parse(&b[0..4])?; - - let mut pos = 4; - let mut map = VariantMap::new(); - for _ in 0..len { - let (nlen, name) = String::parse(&b[(pos)..])?; - pos += nlen; - - let (vlen, value) = Variant::parse(&b[(pos)..])?; - pos += vlen; - - map.insert(name, value); - } - - return Ok((pos, map)); - } -} - -impl QRead for VariantMap { - fn read<T: Read>(s: &mut T, b: &mut [u8]) -> Result<usize, Error> { - s.read(&mut b[0..4])?; - - - let (_, len) = i32::parse(&b[0..4])?; - - let mut pos = 4; - for _ in 0..len { - pos += String::read(s, &mut b[pos..])?; - pos += Variant::read(s, &mut b[(pos+3..)])?; - } - - return Ok(pos); - } -} - -///////////////////////////////////////////////////////////////////////// -pub type VariantList = Vec<Variant>; - -impl Serialize for VariantList { - fn serialize(&self) -> Result<Vec<u8>, Error> { - let len: i32 = self.len().try_into()?; - let mut res: Vec<u8> = Vec::new(); - - res.extend(len.to_be_bytes().iter()); - for v in self { - res.extend(v.serialize()?.iter()); - } - - return Ok(res); - } -} - -impl Deserialize for VariantList { - fn parse(b: &[u8]) -> Result<(usize, Self), Error> { - let (_, len) = i32::parse(&b[0..4])?; - - let mut res: VariantList = VariantList::new(); - let mut pos: usize = 4; - for _ in 0..len { - let (vlen, val) = Variant::parse(&b[pos..])?; - res.push(val); - pos += vlen; - } - - return Ok((pos, res)); - } -} - -impl QRead for VariantList { - fn read<T: Read>(s: &mut T, b: &mut [u8]) -> Result<usize, Error> { - s.read(&mut b[0..4])?; - - let (_, len) = i32::parse(&b[0..4])?; - - let mut pos = 4; - for _ in 0..len { - pos += Variant::read(s, &mut b[(pos+3..)])?; - } +extern crate bytes; +use bytes::BytesMut; - return Ok(pos); - } -} +use crate::protocol::primitive::{ + BufferInfo, Date, DateTime, Message, Time, VariantList, VariantMap, +}; -///////////////////////////////////////////////////////////////////////// #[allow(non_camel_case_types, dead_code)] #[derive(Clone, Debug, std::cmp::PartialEq)] pub enum Variant { Unknown, + UserType(String, BytesMut), + BufferInfo(BufferInfo), + Message(Message), + Time(Time), + Date(Date), + DateTime(DateTime), VariantMap(VariantMap), VariantList(VariantList), String(String), StringUTF8(String), + ByteArray(String), StringList(StringList), bool(bool), u64(u64), @@ -144,82 +51,106 @@ impl Serialize for Variant { match self { Variant::Unknown => { - bail!(ProtocolError::UnknownVariant); - }, + bail!(ProtocolError::UnknownVariant); + } Variant::VariantMap(v) => { res.extend(primitive::QVARIANTMAP.to_be_bytes().iter()); res.extend(unknown.to_be_bytes().iter()); res.extend(v.serialize()?.iter()); - }, + } Variant::VariantList(v) => { res.extend(primitive::QVARIANTLIST.to_be_bytes().iter()); res.extend(unknown.to_be_bytes().iter()); res.extend(v.serialize()?.iter()); - }, + } Variant::String(v) => { res.extend(primitive::QSTRING.to_be_bytes().iter()); res.extend(unknown.to_be_bytes().iter()); res.extend(v.serialize()?.iter()); - }, + } Variant::StringUTF8(v) => { res.extend(primitive::QBYTEARRAY.to_be_bytes().iter()); res.extend(unknown.to_be_bytes().iter()); res.extend(v.serialize_utf8()?.iter()); - }, + } + Variant::ByteArray(v) => { + res.extend(primitive::QBYTEARRAY.to_be_bytes().iter()); + res.extend(unknown.to_be_bytes().iter()); + res.extend(v.serialize_utf8()?.iter()); + res.extend(vec![0x00]); + } Variant::StringList(v) => { res.extend(primitive::QSTRINGLIST.to_be_bytes().iter()); res.extend(unknown.to_be_bytes().iter()); res.extend(v.serialize()?.iter()); - }, + } Variant::bool(v) => { res.extend(primitive::BOOL.to_be_bytes().iter()); res.extend(unknown.to_be_bytes().iter()); let i = *v as i8; res.extend(i.to_be_bytes().iter()); - }, + } Variant::u64(v) => { res.extend(primitive::ULONG.to_be_bytes().iter()); res.extend(unknown.to_be_bytes().iter()); res.extend(v.to_be_bytes().iter()); - }, + } Variant::u32(v) => { res.extend(primitive::UINT.to_be_bytes().iter()); res.extend(unknown.to_be_bytes().iter()); res.extend(v.to_be_bytes().iter()); - }, + } Variant::u16(v) => { res.extend(primitive::USHORT.to_be_bytes().iter()); res.extend(unknown.to_be_bytes().iter()); res.extend(v.to_be_bytes().iter()); - }, + } Variant::u8(v) => { res.extend(primitive::UCHAR.to_be_bytes().iter()); res.extend(unknown.to_be_bytes().iter()); res.extend(v.to_be_bytes().iter()); - }, + } Variant::i64(v) => { res.extend(primitive::LONG.to_be_bytes().iter()); res.extend(unknown.to_be_bytes().iter()); res.extend(v.to_be_bytes().iter()); - }, + } Variant::i32(v) => { res.extend(primitive::INT.to_be_bytes().iter()); res.extend(unknown.to_be_bytes().iter()); res.extend(v.to_be_bytes().iter()); - }, + } Variant::i16(v) => { res.extend(primitive::SHORT.to_be_bytes().iter()); res.extend(unknown.to_be_bytes().iter()); res.extend(v.to_be_bytes().iter()); - }, + } Variant::i8(v) => { res.extend(primitive::CHAR.to_be_bytes().iter()); res.extend(unknown.to_be_bytes().iter()); res.extend(v.to_be_bytes().iter()); - }, + } + Variant::UserType(_, _) => unimplemented!(), + Variant::BufferInfo(_) => unimplemented!(), + Variant::Message(_) => unimplemented!(), + Variant::DateTime(v) => { + res.extend(primitive::QDATETIME.to_be_bytes().iter()); + res.extend(unknown.to_be_bytes().iter()); + res.append(&mut v.serialize()?); + } + Variant::Time(v) => { + res.extend(primitive::QTIME.to_be_bytes().iter()); + res.extend(unknown.to_be_bytes().iter()); + res.append(&mut v.serialize()?); + } + Variant::Date(v) => { + res.extend(primitive::QDATE.to_be_bytes().iter()); + res.extend(unknown.to_be_bytes().iter()); + res.append(&mut v.serialize()?); + } } - return Ok(res) + return Ok(res); } } @@ -234,96 +165,126 @@ impl Deserialize for Variant { let len = 5; match qtype { primitive::QVARIANTMAP => { + trace!(target: "protocol::primitive::Variant", "Parsing Variant: VariantMap"); let (vlen, value) = VariantMap::parse(&b[len..])?; - return Ok((len+vlen, Variant::VariantMap(value))); - }, + return Ok((len + vlen, Variant::VariantMap(value))); + } primitive::QVARIANTLIST => { + trace!(target: "protocol::primitive::Variant", "Parsing Variant: VariantList"); let (vlen, value) = VariantList::parse(&b[len..])?; - return Ok((len+vlen, Variant::VariantList(value))); - }, + return Ok((len + vlen, Variant::VariantList(value))); + } primitive::QSTRING => { + trace!(target: "protocol::primitive::Variant", "Parsing Variant: String"); let (vlen, value) = String::parse(&b[len..])?; - return Ok((len+vlen, Variant::String(value.clone()))); - }, + return Ok((len + vlen, Variant::String(value.clone()))); + } primitive::QBYTEARRAY => { + trace!(target: "protocol::primitive::Variant", "Parsing Variant: ByteArray"); let (vlen, value) = String::parse_utf8(&b[len..])?; - return Ok((len+vlen, Variant::StringUTF8(value.clone()))); - }, + return Ok((len + vlen, Variant::StringUTF8(value.clone()))); + } primitive::QSTRINGLIST => { + trace!(target: "protocol::primitive::Variant", "Parsing Variant: StringList"); let (vlen, value) = StringList::parse(&b[len..])?; - return Ok((len+vlen, Variant::StringList(value.clone()))); - }, + return Ok((len + vlen, Variant::StringList(value.clone()))); + } + primitive::QDATETIME => { + trace!(target: "protocol::primitive::Variant", "Parsing Variant: Date"); + let (vlen, value) = Date::parse(&b[len..])?; + return Ok((len + vlen, Variant::Date(value.clone()))); + } + primitive::QDATE => { + trace!(target: "protocol::primitive::Variant", "Parsing Variant: Date"); + let (vlen, value) = Date::parse(&b[len..])?; + return Ok((len + vlen, Variant::Date(value.clone()))); + } + primitive::QTIME => { + trace!(target: "protocol::primitive::Variant", "Parsing Variant: Time"); + let (vlen, value) = Time::parse(&b[len..])?; + return Ok((len + vlen, Variant::Time(value.clone()))); + } primitive::BOOL => { let (vlen, value) = bool::parse(&b[len..])?; - return Ok((len+vlen, Variant::bool(value))); - }, + return Ok((len + vlen, Variant::bool(value))); + } primitive::ULONG => { let (vlen, value) = u64::parse(&b[len..])?; - return Ok((len+vlen, Variant::u64(value))); - }, + return Ok((len + vlen, Variant::u64(value))); + } primitive::UINT => { let (vlen, value) = u32::parse(&b[len..])?; - return Ok((len+vlen, Variant::u32(value))); - }, + return Ok((len + vlen, Variant::u32(value))); + } primitive::USHORT => { let (vlen, value) = u16::parse(&b[len..])?; - return Ok((len+vlen, Variant::u16(value))); - }, + return Ok((len + vlen, Variant::u16(value))); + } primitive::UCHAR => { let (vlen, value) = u8::parse(&b[len..])?; - return Ok((len+vlen, Variant::u8(value))); - }, + return Ok((len + vlen, Variant::u8(value))); + } primitive::LONG => { let (vlen, value) = i64::parse(&b[len..])?; - return Ok((len+vlen, Variant::i64(value))); - }, + return Ok((len + vlen, Variant::i64(value))); + } primitive::INT => { let (vlen, value) = i32::parse(&b[len..])?; - return Ok((len+vlen, Variant::i32(value))); - }, + return Ok((len + vlen, Variant::i32(value))); + } primitive::SHORT => { let (vlen, value) = i16::parse(&b[len..])?; - return Ok((len+vlen, Variant::i16(value))); - }, + return Ok((len + vlen, Variant::i16(value))); + } primitive::CHAR => { let (vlen, value) = i8::parse(&b[len..])?; - return Ok((len+vlen, Variant::i8(value))); - }, - _ => { + return Ok((len + vlen, Variant::i8(value))); + } + primitive::USERTYPE => { + trace!(target: "protocol::primitive::Variant", "Parsing UserType"); + // Parse UserType name + let (user_type_len, user_type) = String::parse_utf8(&b[len..])?; + + trace!(target: "protocol::primitive::Variant", "Parsing UserType: {:?}", user_type); + + // Match Possible User Types to basic structures + match user_type.as_str() { + // As VariantMap + "IrcUser" | "IrcChannel" | "Identity" | "NetworkInfo" | "Network::Server" => { + trace!(target: "protocol::primitive::Variant", "UserType is VariantMap"); + let (vlen, value) = VariantMap::parse(&b[(len + user_type_len)..])?; + return Ok((len + user_type_len + vlen, Variant::VariantMap(value))); + } + // As i32 + "BufferId" | "IdentityId" | "NetworkId" | "MsgId" => { + trace!(target: "protocol::primitive::Variant", "UserType is i32"); + + let (vlen, value) = i32::parse(&b[(len + user_type_len)..])?; + return Ok((len + user_type_len + vlen, Variant::i32(value))); + } + // As i64 + "PeerPtr" => { + trace!(target: "protocol::primitive::Variant", "UserType is i64"); + let (vlen, value) = i64::parse(&b[(len + user_type_len)..])?; + return Ok((len + user_type_len + vlen, Variant::i64(value))); + } + "BufferInfo" => { + trace!(target: "protocol::primitive::Variant", "UserType is BufferInfo"); + let (vlen, value) = BufferInfo::parse(&b[(len + user_type_len)..])?; + return Ok((len + user_type_len + vlen, Variant::BufferInfo(value))); + } + "Message" => { + trace!(target: "protocol::primitive::Variant", "UserType is Message"); + let (vlen, value) = Message::parse(&b[(len + user_type_len)..])?; + return Ok((len + user_type_len + vlen, Variant::Message(value))); + } + _ => unimplemented!(), + } + } + err => { + error!(target: "parser", "UnknownVariant: {:x?}", err); bail!(ProtocolError::UnknownVariant); } } } } - -impl QRead for Variant { - fn read<T: Read>(s: &mut T, b: &mut [u8]) -> Result<usize, Error> { - - s.read(&mut b[0..4])?; - let (_, qtype) = i32::parse(&b[0..4])?; - let qtype = qtype as u32; - - s.read(&mut [b[4]])?; - - let mut len = 5; - match qtype { - primitive::QVARIANTMAP => len += VariantMap::read(s, &mut b[len..])?, - primitive::QVARIANTLIST => len += VariantList::read(s, &mut b[len..])?, - primitive::QSTRING => len += String::read(s, &mut b[len..])?, - primitive::QBYTEARRAY => len += String::read(s, &mut b[len..])?, - primitive::QSTRINGLIST => len += StringList::read(s, &mut b[len..])?, - primitive::BOOL => len += bool::read(s, &mut b[len..])?, - primitive::ULONG => len += u64::read(s, &mut b[len..])?, - primitive::UINT => len += u32::read(s, &mut b[len..])?, - primitive::USHORT => len += u16::read(s, &mut b[len..])?, - primitive::UCHAR => len += u8::read(s, &mut b[len..])?, - primitive::LONG => len += i64::read(s, &mut b[len..])?, - primitive::INT => len += i32::read(s, &mut b[len..])?, - primitive::SHORT => len += i16::read(s, &mut b[len..])?, - primitive::CHAR => len += i8::read(s, &mut b[len..])?, - _ => bail!(ProtocolError::UnknownVariant) - } - - return Ok(len); - } -} diff --git a/src/protocol/primitive/variantlist.rs b/src/protocol/primitive/variantlist.rs new file mode 100644 index 0000000..2481b32 --- /dev/null +++ b/src/protocol/primitive/variantlist.rs @@ -0,0 +1,46 @@ +use std::convert::TryInto; +use std::vec::Vec; + +use failure::Error; + +use log::trace; + +use crate::protocol::primitive::{deserialize::Deserialize, serialize::Serialize}; + +extern crate bytes; + +use crate::protocol::primitive::Variant; + +pub type VariantList = Vec<Variant>; + +impl Serialize for VariantList { + fn serialize(&self) -> Result<Vec<u8>, Error> { + let len: i32 = self.len().try_into()?; + let mut res: Vec<u8> = Vec::new(); + + res.extend(len.to_be_bytes().iter()); + for v in self { + res.extend(v.serialize()?.iter()); + } + + return Ok(res); + } +} + +impl Deserialize for VariantList { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + let (_, len) = i32::parse(&b[0..4])?; + trace!(target: "protocol::primitive::VariantList", "Parsing VariantList with {:?} elements", len); + + let mut res: VariantList = VariantList::new(); + let mut pos: usize = 4; + for i in 0..len { + trace!(target: "protocol::primitive::VariantList", "Parsing VariantList element: {:?}", i); + let (vlen, val) = Variant::parse(&b[pos..])?; + res.push(val); + pos += vlen; + } + + return Ok((pos, res)); + } +} diff --git a/src/protocol/primitive/variantmap.rs b/src/protocol/primitive/variantmap.rs new file mode 100644 index 0000000..22ca0f1 --- /dev/null +++ b/src/protocol/primitive/variantmap.rs @@ -0,0 +1,63 @@ +use std::collections::HashMap; +use std::{convert::TryInto, vec::Vec}; + +use failure::Error; + +use log::trace; + +use crate::protocol::error::ProtocolError; +use crate::protocol::primitive::deserialize::Deserialize; +use crate::protocol::primitive::serialize::Serialize; +use crate::protocol::primitive::String; + +use crate::protocol::primitive::Variant; +use crate::util; + +extern crate bytes; + +pub type VariantMap = HashMap<String, Variant>; + +impl Serialize for VariantMap { + fn serialize<'a>(&'a self) -> Result<Vec<u8>, Error> { + let mut res: Vec<u8> = Vec::new(); + + for (k, v) in self { + res.extend(k.serialize()?); + res.extend(v.serialize()?); + } + + let len: i32 = self.len().try_into()?; + util::insert_bytes(0, &mut res, &mut len.to_be_bytes()); + + return Ok(res); + } +} + +impl Deserialize for VariantMap { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + let (_, len) = i32::parse(&b[0..4])?; + trace!(target: "protocol::primitive::VariantMap", "Parsing VariantMap with {:?} elements", len); + + let mut pos: usize = 4; + let mut map = VariantMap::new(); + for _ in 0..len { + trace!(target: "protocol::primitive::VariantMap", "Parsing entry name"); + // let (nlen, name) = Variant::parse(&b[pos..])?; + let (nlen, name) = String::parse(&b[pos..])?; + pos += nlen; + + trace!(target: "protocol::primitive::VariantMap", "Parsing entry: {:?} with len {:?}", name, &b[(pos)..(pos + 4)]); + let (vlen, value) = Variant::parse(&b[(pos)..])?; + pos += vlen; + + // match name { + // Variant::String(x) => map.insert(x, value), + // Variant::StringUTF8(x) => map.insert(x, value), + // _ => bail!(ProtocolError::WrongVariant), + // }; + map.insert(name, value); + } + + return Ok((pos, map)); + } +} diff --git a/src/tests/base_types.rs b/src/tests/base_types.rs index 45f1fd3..4cc56ae 100644 --- a/src/tests/base_types.rs +++ b/src/tests/base_types.rs @@ -1,6 +1,5 @@ -use crate::protocol::primitive::serialize::{Serialize, SerializeUTF8}; use crate::protocol::primitive::deserialize::{Deserialize, DeserializeUTF8}; -use crate::protocol::primitive::qread::QRead; +use crate::protocol::primitive::serialize::{Serialize, SerializeUTF8}; use crate::protocol::primitive::*; @@ -8,34 +7,31 @@ use crate::protocol::primitive::*; pub fn serialize_string() { let test_string: String = String::from("Configured"); - assert_eq!(test_string.serialize().unwrap(), [0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, 100]); + assert_eq!( + test_string.serialize().unwrap(), + [ + 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, + 100 + ] + ); } #[test] pub fn serialize_string_utf8() { let test_string: String = String::from("Configured"); - assert_eq!(test_string.serialize_utf8().unwrap(), [0, 0, 0, 10, 67, 111, 110, 102, 105, 103, 117, 114, 101, 100]); -} - -#[test] -pub fn read_string() { - use std::io::Cursor; - - let test_bytes: Vec<u8> = vec![0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, 100, 0, 0, 0, 1]; - - let mut buf: Vec<u8> = [0; 24].to_vec(); - let len = String::read(&mut Cursor::new(&test_bytes), &mut buf).unwrap(); - - assert_eq!(len, 24); - - let result_bytes: Vec<u8> = vec![0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, 100]; - assert_eq!(buf, result_bytes); + assert_eq!( + test_string.serialize_utf8().unwrap(), + [0, 0, 0, 11, 67, 111, 110, 102, 105, 103, 117, 114, 101, 100, 0] + ); } #[test] pub fn deserialize_string() { - let test_bytes: &[u8] = &[0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, 100, 0, 0, 0, 1]; + let test_bytes: &[u8] = &[ + 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, 100, + 0, 0, 0, 1, + ]; let (len, res) = String::parse(test_bytes).unwrap(); assert_eq!(res, "Configured"); assert_eq!(len, 24); @@ -43,43 +39,45 @@ pub fn deserialize_string() { #[test] pub fn deserialize_string_utf8() { - let test_bytes: &[u8] = &[0, 0, 0, 10, 67, 111, 110, 102, 105, 103, 117, 114, 101, 100, 0, 0, 0, 1]; + let test_bytes: &[u8] = &[ + 0, 0, 0, 10, 67, 111, 110, 102, 105, 103, 117, 114, 101, 100, 0, 0, 0, 1, + ]; let (len, res) = String::parse_utf8(test_bytes).unwrap(); assert_eq!(len, 14); assert_eq!(res, "Configured"); } #[test] +pub fn deserialize_string_utf8_null_terminated() { + let test_bytes: &[u8] = &[ + 0, 0, 0, 11, 67, 111, 110, 102, 105, 103, 117, 114, 101, 100, 0, 0, 0, 0, 1, + ]; + let (len, res) = String::parse_utf8(test_bytes).unwrap(); + assert_eq!(len, 15); + assert_eq!(res, "Configured"); +} + +#[test] pub fn serialize_string_list() { let mut test_list = StringList::new(); test_list.push("Configured".to_string()); assert_eq!( test_list.serialize().unwrap(), - [0, 0, 0, 1, 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, 100] + [ + 0, 0, 0, 1, 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, + 0, 101, 0, 100 + ] ) } #[test] -pub fn read_string_list() { - use std::io::Cursor; - - let test_bytes: Vec<u8> = vec![0, 0, 0, 1, 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, 100, 0, 0, 0, 1]; - - let mut buf: Vec<u8> = [0; 28].to_vec(); - let len = StringList::read(&mut Cursor::new(&test_bytes), &mut buf).unwrap(); - - assert_eq!(len, 28); - - let result_bytes: Vec<u8> = vec![0, 0, 0, 1, 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, 100]; - assert_eq!(buf, result_bytes); -} - -#[test] pub fn deserialize_string_list() { - let test_bytes: &[u8] = &[0, 0, 0, 1, 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, 100, 0, 0, 0, 1]; + let test_bytes: &[u8] = &[ + 0, 0, 0, 1, 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, + 101, 0, 100, 0, 0, 0, 1, + ]; let mut test_list = StringList::new(); test_list.push("Configured".to_string()); - println!("aaaaa"); let (len, res) = StringList::parse(test_bytes).unwrap(); assert_eq!(len, 28); assert_eq!(test_list, res); diff --git a/src/tests/handshake_types.rs b/src/tests/handshake_types.rs index d9368b2..d18ec8a 100644 --- a/src/tests/handshake_types.rs +++ b/src/tests/handshake_types.rs @@ -1,71 +1,24 @@ -use crate::protocol::message::handshake::{VariantMap, HandshakeSerialize, HandshakeDeserialize, HandshakeQRead}; -use crate::protocol::primitive::{Variant}; +use crate::protocol::message::handshake::{HandshakeDeserialize, HandshakeSerialize, VariantMap}; +use crate::protocol::primitive::Variant; #[test] pub fn serialize_variantmap() { let mut test_variantmap = VariantMap::new(); test_variantmap.insert("Configured".to_string(), Variant::bool(true)); - let bytes = [0, 0, 0, 2, 0, 0, 0, 10, 0, - 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, 100, - 0, 0, 0, 1, 0, 1].to_vec(); - assert_eq!( - test_variantmap.serialize().unwrap(), - bytes - ); -} - -#[test] -pub fn read_variantmap() { - use std::io::Cursor; - - let test_bytes: Vec<u8> = vec![ - // len - 0, 0, 0, 4, // 4 - // var - 0, 0, 0, 10, 0, // 5 - // strlen, str - 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, 100, // 24 - // bool - 0, 0, 0, 1, 0, 1, // 6 - // var - 0, 0, 0, 10, 0, // 5 - // strlen, str - 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, 100, // 24 - // bool - 0, 0, 0, 1, 0, 1, //6 - // extra - 0, 0, 0, 1]; - - let mut buf: Vec<u8> = [0; 74].to_vec(); - let len = VariantMap::read(&mut Cursor::new(&test_bytes), &mut buf).unwrap(); - - assert_eq!(len, 74); - - let result_bytes: Vec<u8> = vec![ - // len - 0, 0, 0, 4, - // var - 0, 0, 0, 10, 0, - // strlen, str - 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, 100, - // bool - 0, 0, 0, 1, 0, 1, - // var - 0, 0, 0, 10, 0, - // strlen, str - 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, 100, - // bool - 0, 0, 0, 1, 0, 1]; - assert_eq!(buf, result_bytes); + let bytes = [ + 0, 0, 0, 2, 0, 0, 0, 10, 0, 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, + 117, 0, 114, 0, 101, 0, 100, 0, 0, 0, 1, 0, 1, + ] + .to_vec(); + assert_eq!(test_variantmap.serialize().unwrap(), bytes); } #[test] pub fn deserialize_variantmap() { - let test_bytes: &[u8] = &[0, 0, 0, 2, - 0, 0, 0, 10, 0, - 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, 100, - 0, 0, 0, 1, 0, 1, - 0, 0, 0, 1]; + let test_bytes: &[u8] = &[ + 0, 0, 0, 2, 0, 0, 0, 10, 0, 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, + 117, 0, 114, 0, 101, 0, 100, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, + ]; let mut test_variantmap = VariantMap::new(); test_variantmap.insert("Configured".to_string(), Variant::bool(true)); @@ -77,11 +30,10 @@ pub fn deserialize_variantmap() { #[test] pub fn deserialize_variantmap_utf8() { - let test_bytes: &[u8] = &[0, 0, 0, 2, - 0, 0, 0, 12, 0, - 0, 0, 0, 10, 67, 111, 110, 102, 105, 103, 117, 114, 101, 100, - 0, 0, 0, 1, 0, 1, - 0, 0, 0, 1]; + let test_bytes: &[u8] = &[ + 0, 0, 0, 2, 0, 0, 0, 12, 0, 0, 0, 0, 10, 67, 111, 110, 102, 105, 103, 117, 114, 101, 100, + 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, + ]; let mut test_variantmap = VariantMap::new(); test_variantmap.insert("Configured".to_string(), Variant::bool(true)); diff --git a/src/tests/mod.rs b/src/tests/mod.rs index 4b030c7..16fd124 100644 --- a/src/tests/mod.rs +++ b/src/tests/mod.rs @@ -3,6 +3,7 @@ pub mod base_types; #[allow(unused_imports)] #[allow(unused_macros)] #[allow(dead_code)] +#[cfg(feature = "framing")] pub mod frame; pub mod handshake_types; diff --git a/src/tests/variant_types.rs b/src/tests/variant_types.rs index 6c49506..0381f07 100644 --- a/src/tests/variant_types.rs +++ b/src/tests/variant_types.rs @@ -1,20 +1,16 @@ -use crate::protocol::primitive::serialize::Serialize; use crate::protocol::primitive::deserialize::Deserialize; +use crate::protocol::primitive::serialize::Serialize; -use crate::protocol::primitive::{Variant, VariantList, VariantMap}; +use crate::protocol::primitive::{ + BufferInfo, BufferType, Message, Variant, VariantList, VariantMap, +}; #[test] pub fn serialize_variant_bool() { let test_variant_true = Variant::bool(true); let test_variant_false = Variant::bool(false); - assert_eq!( - test_variant_true.serialize().unwrap(), - [0, 0, 0, 1, 0, 1] - ); - assert_eq!( - test_variant_false.serialize().unwrap(), - [0, 0, 0, 1, 0, 0] - ); + assert_eq!(test_variant_true.serialize().unwrap(), [0, 0, 0, 1, 0, 1]); + assert_eq!(test_variant_false.serialize().unwrap(), [0, 0, 0, 1, 0, 0]); } #[test] @@ -49,23 +45,58 @@ pub fn deserialize_variantlist() { pub fn serialize_variantmap() { let mut test_variantmap = VariantMap::new(); test_variantmap.insert("Configured".to_string(), Variant::bool(true)); - let bytes = [0, 0, 0, 1, - 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, 100, - 0, 0, 0, 1, 0, 1].to_vec(); - assert_eq!( - test_variantmap.serialize().unwrap(), - bytes - ); + let bytes = [ + 0, 0, 0, 1, 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, + 101, 0, 100, 0, 0, 0, 1, 0, 1, + ] + .to_vec(); + assert_eq!(test_variantmap.serialize().unwrap(), bytes); } #[test] pub fn deserialize_variantmap() { - let test_bytes: &[u8] = &[0, 0, 0, 1, - 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, 117, 0, 114, 0, 101, 0, 100, - 0, 0, 0, 1, 0, 1, 0, 0, 0, 1]; + let test_bytes: &[u8] = &[ + 0, 0, 0, 1, 0, 0, 0, 10, 0, 0, 0, 0, 20, 0, 67, 0, 111, 0, 110, 0, 102, 0, 105, 0, 103, 0, + 117, 0, 114, 0, 101, 0, 100, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, + ]; let (len, res) = VariantMap::parse(test_bytes).unwrap(); let mut test_variantmap = VariantMap::new(); test_variantmap.insert("Configured".to_string(), Variant::bool(true)); - assert_eq!(len, 34); + assert_eq!(len, 39); assert_eq!(res, test_variantmap); } + +#[test] +pub fn serialize_buffer_info() { + let test_buffer_info = BufferInfo { + id: 0, + network_id: 0, + buffer_type: BufferType::Status, + name: "test".to_string(), + }; + + let bytes = vec![ + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x5, + 0x74, 0x65, 0x73, 0x74, 0x0, + ]; + assert_eq!(test_buffer_info.serialize().unwrap(), bytes); +} + +#[test] +pub fn deserialize_buffer_info() { + let test_buffer_info = BufferInfo { + id: 0, + network_id: 0, + buffer_type: BufferType::Status, + name: "test".to_string(), + }; + + let bytes = vec![ + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x5, + 0x74, 0x65, 0x73, 0x74, 0x0, + ]; + let (len, res) = BufferInfo::parse(&bytes).unwrap(); + + assert_eq!(len, 23); + assert_eq!(res, test_buffer_info); +} |
