aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/client/mod.rs40
-rw-r--r--src/consts.rs0
-rw-r--r--src/error/mod.rs (renamed from src/protocol/error/mod.rs)0
-rw-r--r--src/frame/mod.rs (renamed from src/protocol/frame/mod.rs)44
-rw-r--r--src/lib.rs57
-rw-r--r--src/message/handshake.rs (renamed from src/protocol/message/handshake.rs)159
-rw-r--r--src/message/handshake/types.rs (renamed from src/protocol/message/handshake/types.rs)22
-rw-r--r--src/message/login.rs (renamed from src/protocol/message/login.rs)0
-rw-r--r--src/message/mod.rs (renamed from src/protocol/message/mod.rs)6
-rw-r--r--src/primitive/bufferinfo.rs (renamed from src/protocol/primitive/bufferinfo.rs)21
-rw-r--r--src/primitive/datetime.rs (renamed from src/protocol/primitive/datetime.rs)28
-rw-r--r--src/primitive/message.rs (renamed from src/protocol/primitive/message.rs)41
-rw-r--r--src/primitive/mod.rs70
-rw-r--r--src/primitive/signedint.rs (renamed from src/protocol/primitive/signedint.rs)18
-rw-r--r--src/primitive/string.rs (renamed from src/protocol/primitive/string.rs)21
-rw-r--r--src/primitive/stringlist.rs (renamed from src/protocol/primitive/stringlist.rs)12
-rw-r--r--src/primitive/unsignedint.rs (renamed from src/protocol/primitive/unsignedint.rs)24
-rw-r--r--src/primitive/variant.rs (renamed from src/protocol/primitive/variant.rs)80
-rw-r--r--src/primitive/variantlist.rs (renamed from src/protocol/primitive/variantlist.rs)11
-rw-r--r--src/primitive/variantmap.rs (renamed from src/protocol/primitive/variantmap.rs)23
-rw-r--r--src/protocol/mod.rs9
-rw-r--r--src/protocol/primitive/mod.rs74
-rw-r--r--src/tests/base_types.rs6
-rw-r--r--src/tests/frame.rs37
-rw-r--r--src/tests/handshake_types.rs4
-rw-r--r--src/tests/variant_types.rs14
-rw-r--r--src/util.rs49
27 files changed, 513 insertions, 357 deletions
diff --git a/src/client/mod.rs b/src/client/mod.rs
index fbb5b35..5c9699e 100644
--- a/src/client/mod.rs
+++ b/src/client/mod.rs
@@ -15,13 +15,13 @@ use tokio_util::codec::Framed;
use futures_util::stream::StreamExt;
use futures::SinkExt;
-use crate::protocol::frame::QuasselCodec;
+use crate::frame::QuasselCodec;
use failure::Error;
use log::{trace, debug, info, error};
-use crate::protocol::message::ConnAck;
+use crate::message::ConnAck;
extern crate log;
@@ -39,9 +39,9 @@ pub enum ClientState {
impl <T: AsyncRead + AsyncWrite + Unpin> Client<T> {
pub async fn run(&mut self) {
- use crate::protocol::primitive::StringList;
- use crate::protocol::message::handshake::ClientInit;
- use crate::protocol::message::handshake::HandshakeSerialize;
+ use crate::primitive::StringList;
+ use crate::message::ClientInit;
+ use crate::HandshakeSerialize;
info!(target: "init", "Setting Features");
@@ -49,6 +49,7 @@ impl <T: AsyncRead + AsyncWrite + Unpin> Client<T> {
features.push("SynchronizedMarkerLine".to_string());
features.push("Authenticators".to_string());
features.push("ExtendedFeatures".to_string());
+ features.push("BufferActivitySync".to_string());
let client_init = ClientInit {
client_version:String::from("Rust 0.0.0"),
client_date: String::from("1579009211"),
@@ -123,15 +124,16 @@ impl <T: AsyncRead + AsyncWrite + Unpin> Client<T> {
}
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::util::get_msg_type;
+ use crate::{HandshakeSerialize, HandshakeDeserialize};
+ use crate::message::ClientLogin;
+ use crate::primitive::{VariantMap, Variant};
trace!(target: "message", "Received bytes: {:x?}", buf);
let (_, res) = VariantMap::parse(buf)?;
debug!(target: "init", "Received Messsage: {:#?}", res);
- let msgtype = get_msg_type(&res["MsgType"])?;
- match msgtype {
+
+ let msgtype = match_variant!(&res["MsgType"], Variant::String);
+ match msgtype.as_str() {
"ClientInitAck" => {
info!(target: "init", "Initialization successfull");
info!(target: "login", "Starting Login");
@@ -145,7 +147,6 @@ pub async fn handle_login_message<T: AsyncRead + AsyncWrite + Unpin>(client: &mu
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;
}
@@ -156,30 +157,25 @@ pub async fn handle_login_message<T: AsyncRead + AsyncWrite + Unpin>(client: &mu
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;
+ use crate::primitive::VariantList;
+ use crate::Deserialize;
+ use crate::Serialize;
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;
+ use crate::Deserialize;
// Buffer for our initialization
let mut init: Vec<u8> = vec![];
diff --git a/src/consts.rs b/src/consts.rs
deleted file mode 100644
index e69de29..0000000
--- a/src/consts.rs
+++ /dev/null
diff --git a/src/protocol/error/mod.rs b/src/error/mod.rs
index 72a9e59..72a9e59 100644
--- a/src/protocol/error/mod.rs
+++ b/src/error/mod.rs
diff --git a/src/protocol/frame/mod.rs b/src/frame/mod.rs
index 8c5a8d3..709d3af 100644
--- a/src/protocol/frame/mod.rs
+++ b/src/frame/mod.rs
@@ -15,13 +15,15 @@ use flate2::Decompress;
use flate2::FlushCompress;
use flate2::FlushDecompress;
+/// Builder for the QuasselCodec
#[derive(Debug, Clone, Copy)]
pub struct Builder {
- // Maximum frame length
+ /// Enable or Disable Compression
compression: bool,
+ /// The level of Compression
compression_level: Compression,
- // Maximum frame length
+ /// Maximum length of the frame
max_frame_len: usize,
}
@@ -30,6 +32,7 @@ pub struct QuasselCodecError {
_priv: (),
}
+/// QuasselCodec provides the base layer of frameing and compression
#[derive(Debug)]
pub struct QuasselCodec {
builder: Builder,
@@ -45,7 +48,7 @@ enum DecodeState {
}
impl QuasselCodec {
- // Creates a new quassel codec with default values
+ /// Creates a new quassel codec with default values
pub fn new() -> Self {
Self {
builder: Builder::new(),
@@ -61,6 +64,7 @@ impl QuasselCodec {
Builder::new()
}
+ /// Gets the maximum frame length
pub fn max_frame_length(&self) -> usize {
self.builder.max_frame_len
}
@@ -73,6 +77,11 @@ impl QuasselCodec {
self.builder.compression_level
}
+ /// Gets the maximum frame length
+ pub fn set_max_frame_length(&mut self, val: usize) {
+ self.builder.max_frame_length(val);
+ }
+
pub fn set_compression(&mut self, val: bool) {
self.builder.compression(val);
}
@@ -213,9 +222,12 @@ impl Encoder for QuasselCodec {
if self.builder.compression {
let mut cbuf: Vec<u8> = vec![0; 4 + n];
+
let before_in = self.comp.total_in();
let before_out = self.comp.total_out();
+
self.comp.compress(buf, &mut cbuf, FlushCompress::Full)?;
+
let after_in = self.comp.total_in();
let after_out = self.comp.total_out();
@@ -238,14 +250,14 @@ impl Default for QuasselCodec {
// ===== impl Builder =====
impl Builder {
- /// Creates a new length delimited codec builder with default configuration
+ /// Creates a new codec builder with default configuration
/// values.
///
/// # Examples
///
/// ```
/// # use tokio::io::AsyncRead;
- /// use libquassel::protocol::frame::QuasselCodec;
+ /// use libquassel::frame::QuasselCodec;
///
/// # fn bind_read<T: AsyncRead>(io: T) {
/// QuasselCodec::builder()
@@ -261,11 +273,13 @@ impl Builder {
}
}
+ /// Enables or disables the compression
pub fn compression(&mut self, val: bool) -> &mut Self {
self.compression = val;
self
}
+ /// Sets the level of compression to
pub fn compression_level(&mut self, val: Compression) -> &mut Self {
self.compression_level = val;
self
@@ -274,7 +288,7 @@ impl Builder {
/// Sets the max frame length
///
/// This configuration option applies to both encoding and decoding. The
- /// default value is 8MB.
+ /// default value is 67MB.
///
/// When decoding, the length field read from the byte stream is checked
/// against this setting **before** any adjustments are applied. When
@@ -288,7 +302,7 @@ impl Builder {
///
/// ```
/// # use tokio::io::AsyncRead;
- /// use libquassel::protocol::frame::QuasselCodec;
+ /// use libquassel::frame::QuasselCodec;
///
/// # fn bind_read<T: AsyncRead>(io: T) {
/// QuasselCodec::builder()
@@ -302,12 +316,12 @@ impl Builder {
self
}
- /// Create a configured length delimited `QuasselCodec`
+ /// Create a configured `QuasselCodec`
///
/// # Examples
///
/// ```
- /// use libquassel::protocol::frame::QuasselCodec;
+ /// use libquassel::frame::QuasselCodec;
/// # pub fn main() {
/// QuasselCodec::builder()
/// .new_codec();
@@ -322,13 +336,13 @@ impl Builder {
}
}
- /// Create a configured length delimited `FramedRead`
+ /// Create a configured `FramedRead`
///
/// # Examples
///
/// ```
/// # use tokio::io::AsyncRead;
- /// use libquassel::protocol::frame::QuasselCodec;
+ /// use libquassel::frame::QuasselCodec;
///
/// # fn bind_read<T: AsyncRead>(io: T) {
/// QuasselCodec::builder()
@@ -343,13 +357,13 @@ impl Builder {
FramedRead::new(upstream, self.new_codec())
}
- /// Create a configured length delimited `FramedWrite`
+ /// Create a configured `FramedWrite`
///
/// # Examples
///
/// ```
/// # use tokio::io::AsyncWrite;
- /// # use libquassel::protocol::frame::QuasselCodec;
+ /// # use libquassel::frame::QuasselCodec;
/// # fn write_frame<T: AsyncWrite>(io: T) {
/// QuasselCodec::builder()
/// .new_write(io);
@@ -363,13 +377,13 @@ impl Builder {
FramedWrite::new(inner, self.new_codec())
}
- /// Create a configured length delimited `Framed`
+ /// Create a configured `Framed`
///
/// # Examples
///
/// ```
/// # use tokio::io::{AsyncRead, AsyncWrite};
- /// # use libquassel::protocol::frame::QuasselCodec;
+ /// # use libquassel::frame::QuasselCodec;
/// # fn write_frame<T: AsyncRead + AsyncWrite>(io: T) {
/// # let _ =
/// QuasselCodec::builder()
diff --git a/src/lib.rs b/src/lib.rs
index ed05773..215dcfc 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,8 +1,5 @@
-pub mod consts;
-pub mod protocol;
-
#[macro_use]
-pub mod util;
+mod util;
#[cfg(feature = "client")]
pub mod client;
@@ -12,3 +9,55 @@ pub mod tests;
#[macro_use]
extern crate failure;
+
+pub mod message;
+pub mod primitive;
+
+#[allow(dead_code)]
+pub mod error;
+
+#[allow(unused_variables, dead_code)]
+#[cfg(feature = "framing")]
+pub mod frame;
+
+use failure::Error;
+
+/// Serialization of types and structs to the quassel byteprotocol
+pub trait Serialize {
+ fn serialize(&self) -> Result<Vec<u8>, Error>;
+}
+
+/// Serialization of UTF-8 based Strings to the quassel byteprotocol
+pub trait SerializeUTF8 {
+ fn serialize_utf8(&self) -> Result<Vec<u8>, Error>;
+}
+
+/// Deserialization of types and structs to the quassel byteprotocol
+pub trait Deserialize {
+ fn parse(b: &[u8]) -> Result<(usize, Self), Error>
+ where
+ Self: std::marker::Sized;
+}
+
+/// Deserialization of UTF-8 based Strings to the quassel byteprotocol
+pub trait DeserializeUTF8 {
+ fn parse_utf8(b: &[u8]) -> Result<(usize, Self), Error>
+ where
+ Self: std::marker::Sized;
+}
+
+/// HandshakeSerialize implements the serialization needed during the handhake phase.
+///
+/// The protocol has some minor differences during this phase compared to the regular parsing.
+pub trait HandshakeSerialize {
+ fn serialize(&self) -> Result<Vec<u8>, Error>;
+}
+
+/// HandshakeDeserialize implements the deserialization needed during the handhake phase.
+///
+/// The protocol has some minor differences during this phase compared to the regular parsing.
+pub trait HandshakeDeserialize {
+ fn parse(b: &[u8]) -> Result<(usize, Self), Error>
+ where
+ Self: std::marker::Sized;
+}
diff --git a/src/protocol/message/handshake.rs b/src/message/handshake.rs
index 357d1a4..753488e 100644
--- a/src/protocol/message/handshake.rs
+++ b/src/message/handshake.rs
@@ -1,23 +1,56 @@
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;
-
+use crate::error::ProtocolError;
+use crate::primitive::{StringList, Variant, VariantList};
mod types;
-pub use types::{HandshakeDeserialize, HandshakeSerialize, VariantMap};
+use crate::primitive::VariantMap;
+use crate::{HandshakeDeserialize, HandshakeSerialize};
use crate::match_variant;
+/// Data received right after initializing the connection
+///
+/// ConnAck is serialized sequentially
#[derive(Debug)]
pub struct ConnAck {
+ /// The Flag 0x01 for TLS
+ /// and 0x02 for Deflate Compression
flags: u8,
+ /// Some extra protocol version specific data
+ /// So far unused
extra: i16,
+ /// The version of the protocol
+ /// 0x00000001 for the legacy protocol
+ /// 0x00000002 for the datastream protocol
+ ///
+ /// Only the datastream protocol is supported by this crate
version: i8,
}
-impl crate::protocol::primitive::deserialize::Deserialize for ConnAck {
+impl Default for ConnAck {
+ fn default() -> Self {
+ Self {
+ flags: 0x00,
+ extra: 0x00,
+ version: 0x00000002,
+ }
+ }
+}
+
+impl crate::Serialize for ConnAck {
+ fn serialize(&self) -> Result<Vec<std::primitive::u8>, Error> {
+ let mut bytes: Vec<u8> = Vec::new();
+
+ bytes.append(&mut self.flags.serialize()?);
+ bytes.append(&mut self.extra.serialize()?);
+ bytes.append(&mut self.version.serialize()?);
+
+ Ok(bytes)
+ }
+}
+
+impl crate::Deserialize for ConnAck {
fn parse(b: &[u8]) -> Result<(usize, Self), Error> {
let (flen, flags) = u8::parse(b)?;
let (elen, extra) = i16::parse(&b[flen..])?;
@@ -34,12 +67,44 @@ impl crate::protocol::primitive::deserialize::Deserialize for ConnAck {
}
}
+/// ClientInit is the Initial message send to the core after establishing a base layer comunication.
+///
+/// Features
+///
+/// | Flag | Name | Description |
+/// | ---- | ---- | ----------- |
+/// | 0x00000001 | SynchronizedMarkerLine | -- |
+/// | 0x00000002 | SaslAuthentication | -- |
+/// | 0x00000004 | SaslExternal | -- |
+/// | 0x00000008 | HideInactiveNetworks | -- |
+/// | 0x00000010 | PasswordChange | -- |
+/// | 0x00000020 | CapNegotiation | IRCv3 capability negotiation, account tracking |
+/// | 0x00000040 | VerifyServerSSL | IRC server SSL validation |
+/// | 0x00000080 | CustomRateLimits | IRC server custom message rate limits |
+/// | 0x00000100 | DccFileTransfer | Currently not supported |
+/// | 0x00000200 | AwayFormatTimestamp | Timestamp formatting in away (e.g. %%hh:mm%%) |
+/// | 0x00000400 | Authenticators | Support for exchangeable auth backends |
+/// | 0x00000800 | BufferActivitySync | Sync buffer activity status |
+/// | 0x00001000 | CoreSideHighlights | Core-Side highlight configuration and matching |
+/// | 0x00002000 | SenderPrefixes | Show prefixes for senders in backlog |
+/// | 0x00004000 | RemoteDisconnect | Supports RPC call disconnectFromCore to remotely disconnect a client |
+/// | 0x00008000 | ExtendedFeatures | Transmit features as list of strings |
+/// | -- | LongTime | Serialize message time as 64-bit |
+/// | -- | RichMessages | Real Name and Avatar URL in backlog |
+/// | -- | BacklogFilterType | Backlogmanager supports filtering backlog by messagetype |
+/// | -- | EcdsaCertfpKeys | ECDSA keys for CertFP in identities |
+/// | -- | LongMessageId | 64-bit IDs for messages |
+/// | -- | SyncedCoreInfo | CoreInfo dynamically updated using signals |
#[derive(Debug)]
pub struct ClientInit {
- pub client_version: String, // Version of the client
- pub client_date: String, // Build date of the client
+ /// Version of the client
+ pub client_version: String,
+ /// Build date of the client
+ pub client_date: String,
+ /// supported features as bitflags
pub client_features: u32,
- pub feature_list: StringList, // List of supported extended features
+ /// List of supported extended features
+ pub feature_list: StringList,
}
impl HandshakeSerialize for ClientInit {
@@ -70,16 +135,16 @@ impl HandshakeDeserialize for ClientInit {
fn parse(b: &[u8]) -> Result<(usize, Self), Error> {
let (len, values): (usize, VariantMap) = HandshakeDeserialize::parse(b)?;
- let msgtype = get_msg_type(&values["MsgType"])?;
+ let msgtype = match_variant!(&values["MsgType"], Variant::StringUTF8);
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"),
+ client_version: match_variant!(values["ClientVersion"], Variant::String),
+ client_date: match_variant!(values["ClientDate"], Variant::String),
+ feature_list: match_variant!(values["FeatureList"], Variant::StringList),
+ client_features: match_variant!(values["Features"], Variant::u32),
},
));
} else {
@@ -88,8 +153,10 @@ impl HandshakeDeserialize for ClientInit {
}
}
+/// ClientInitReject is received when the initialization fails
#[derive(Debug)]
pub struct ClientInitReject {
+ /// String with an error message of what went wrong
pub error_string: String,
}
@@ -112,13 +179,13 @@ impl HandshakeDeserialize for ClientInitReject {
fn parse(b: &[u8]) -> Result<(usize, Self), Error> {
let (len, values): (usize, VariantMap) = HandshakeDeserialize::parse(b)?;
- let msgtype = get_msg_type(&values["MsgType"])?;
+ let msgtype = match_variant!(&values["MsgType"], Variant::StringUTF8);
if msgtype == "ClientInitReject" {
return Ok((
len,
Self {
- error_string: match_variant!(values, Variant::String, "ErrorString"),
+ error_string: match_variant!(values["ErrorString"], Variant::String),
},
));
} else {
@@ -127,13 +194,19 @@ impl HandshakeDeserialize for ClientInitReject {
}
}
+/// ClientInitAck is received when the initialization was successfull
#[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 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
+ /// Flags of supported legacy features
+ pub core_features: u32,
+ /// If the core has already been configured
+ pub core_configured: bool,
+ /// List of VariantMaps of info on available backends
+ pub storage_backends: VariantList,
+ /// List of VariantMaps of info on available authenticators
+ pub authenticators: VariantList,
+ /// List of supported extended features
+ pub feature_list: StringList,
}
impl HandshakeSerialize for ClientInitAck {
@@ -168,21 +241,20 @@ impl HandshakeDeserialize for ClientInitAck {
fn parse(b: &[u8]) -> Result<(usize, Self), Error> {
let (len, values): (usize, VariantMap) = HandshakeDeserialize::parse(b)?;
- let msgtype = get_msg_type(&values["MsgType"])?;
+ let msgtype = match_variant!(&values["MsgType"], Variant::StringUTF8);
if msgtype == "ClientInitAck" {
return Ok((
len,
Self {
core_features: 0x00008000,
- core_configured: match_variant!(values, Variant::bool, "Configured"),
+ core_configured: match_variant!(values["Configured"], Variant::bool),
storage_backends: match_variant!(
- values,
- Variant::VariantList,
- "StorageBackends"
+ values["StorageBackends"],
+ Variant::VariantList
),
- authenticators: match_variant!(values, Variant::VariantList, "Authenticators"),
- feature_list: match_variant!(values, Variant::StringList, "FeatureList"),
+ authenticators: match_variant!(values["Authenticators"], Variant::VariantList),
+ feature_list: match_variant!(values["FeatureList"], Variant::StringList),
},
));
} else {
@@ -191,6 +263,8 @@ impl HandshakeDeserialize for ClientInitAck {
}
}
+/// Login to the core with user data
+/// username and password are transmitted in plain text
#[derive(Debug)]
pub struct ClientLogin {
pub user: String,
@@ -217,14 +291,14 @@ impl HandshakeDeserialize for ClientLogin {
fn parse(b: &[u8]) -> Result<(usize, Self), Error> {
let (len, values): (usize, VariantMap) = HandshakeDeserialize::parse(b)?;
- let msgtype = get_msg_type(&values["MsgType"])?;
+ let msgtype = match_variant!(&values["MsgType"], Variant::StringUTF8);
if msgtype == "ClientLogin" {
return Ok((
len,
Self {
- user: match_variant!(values, Variant::String, "User"),
- password: match_variant!(values, Variant::String, "Password"),
+ user: match_variant!(values["User"], Variant::String),
+ password: match_variant!(values["Password"], Variant::String),
},
));
} else {
@@ -233,6 +307,8 @@ impl HandshakeDeserialize for ClientLogin {
}
}
+/// ClientLoginAck is received after the client has successfully logged in
+/// it has no fields
#[derive(Debug)]
pub struct ClientLoginAck;
@@ -251,7 +327,7 @@ impl HandshakeDeserialize for ClientLoginAck {
fn parse(b: &[u8]) -> Result<(usize, Self), Error> {
let (len, values): (usize, VariantMap) = HandshakeDeserialize::parse(b)?;
- let msgtype = get_msg_type(&values["MsgType"])?;
+ let msgtype = match_variant!(&values["MsgType"], Variant::StringUTF8);
if msgtype == "ClientLogin" {
return Ok((len, Self {}));
@@ -261,6 +337,8 @@ impl HandshakeDeserialize for ClientLoginAck {
}
}
+/// ClientLoginReject is received after the client failed to login
+/// It contains an error message as String
#[derive(Debug)]
pub struct ClientLoginReject {
error: String,
@@ -285,13 +363,13 @@ impl HandshakeDeserialize for ClientLoginReject {
fn parse(b: &[u8]) -> Result<(usize, Self), Error> {
let (len, values): (usize, VariantMap) = HandshakeDeserialize::parse(b)?;
- let msgtype = get_msg_type(&values["MsgType"])?;
+ let msgtype = match_variant!(&values["MsgType"], Variant::StringUTF8);
if msgtype == "ClientLogin" {
return Ok((
len,
Self {
- error: match_variant!(values, Variant::String, "ErrorString"),
+ error: match_variant!(values["ErrorString"], Variant::String),
},
));
} else {
@@ -300,10 +378,15 @@ impl HandshakeDeserialize for ClientLoginReject {
}
}
+/// SessionInit is received along with ClientLoginAck to initialize that user Session
+// TODO Replace with proper types
#[derive(Debug)]
pub struct SessionInit {
+ /// List of all configured identities
identities: VariantList,
+ /// List of all existing buffers
buffers: VariantList,
+ /// Ids of all networks
network_ids: VariantList,
}
@@ -334,15 +417,15 @@ impl HandshakeDeserialize for SessionInit {
fn parse(b: &[u8]) -> Result<(usize, Self), Error> {
let (len, values): (usize, VariantMap) = HandshakeDeserialize::parse(b)?;
- let msgtype = get_msg_type(&values["MsgType"])?;
+ let msgtype = match_variant!(&values["MsgType"], Variant::StringUTF8);
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"),
+ identities: match_variant!(values["Identities"], Variant::VariantList),
+ buffers: match_variant!(values["BufferInfos"], Variant::VariantList),
+ network_ids: match_variant!(values["NetworkIds"], Variant::VariantList),
},
));
} else {
diff --git a/src/protocol/message/handshake/types.rs b/src/message/handshake/types.rs
index 99864b9..04e1dd0 100644
--- a/src/protocol/message/handshake/types.rs
+++ b/src/message/handshake/types.rs
@@ -1,27 +1,17 @@
-use std::collections::HashMap;
use std::convert::TryInto;
use std::result::Result;
use std::vec::Vec;
use failure::Error;
-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::error::ProtocolError;
+use crate::primitive::Variant;
+use crate::Deserialize;
+use crate::Serialize;
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 type VariantMap = HashMap<String, Variant>;
+use crate::primitive::VariantMap;
+use crate::{HandshakeDeserialize, HandshakeSerialize};
impl HandshakeSerialize for VariantMap {
fn serialize<'a>(&'a self) -> Result<Vec<u8>, Error> {
diff --git a/src/protocol/message/login.rs b/src/message/login.rs
index 8b13789..8b13789 100644
--- a/src/protocol/message/login.rs
+++ b/src/message/login.rs
diff --git a/src/protocol/message/mod.rs b/src/message/mod.rs
index f1d4750..b390e2f 100644
--- a/src/protocol/message/mod.rs
+++ b/src/message/mod.rs
@@ -1,5 +1,5 @@
-pub mod handshake;
-pub use handshake::*;
+mod handshake;
+mod login;
-pub mod login;
+pub use handshake::*;
pub use login::*;
diff --git a/src/protocol/primitive/bufferinfo.rs b/src/primitive/bufferinfo.rs
index 4c69286..9cbaa2d 100644
--- a/src/protocol/primitive/bufferinfo.rs
+++ b/src/primitive/bufferinfo.rs
@@ -2,18 +2,24 @@ 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;
+use crate::{Deserialize, DeserializeUTF8};
+use crate::{Serialize, SerializeUTF8};
extern crate bytes;
+/// The BufferInfo struct represents a BufferInfo as received in IRC
+///
+/// BufferInfo is, like all other struct based types, serialized sequentially.
#[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
+ /// a unique, sequential id for the buffer
+ pub id: i32,
+ /// NetworkId of the network the buffer belongs to
+ pub network_id: i32,
+ /// The Type of the Buffer
pub buffer_type: BufferType,
- pub name: String, // BufferName as displayed to the user
+ /// BufferName as displayed to the user
+ pub name: String,
}
impl Serialize for BufferInfo {
@@ -36,7 +42,7 @@ impl Deserialize for BufferInfo {
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
+ // There are 4 additional undocumented Bytes in the BufferInfo
// so we start at byte 14
let (size, name) = String::parse_utf8(&b[14..])?;
@@ -52,6 +58,7 @@ impl Deserialize for BufferInfo {
}
}
+/// The Type of the Buffer
#[repr(i16)]
#[derive(Copy, Clone, Debug, std::cmp::PartialEq)]
pub enum BufferType {
diff --git a/src/protocol/primitive/datetime.rs b/src/primitive/datetime.rs
index 688a022..e6946b9 100644
--- a/src/protocol/primitive/datetime.rs
+++ b/src/primitive/datetime.rs
@@ -1,11 +1,17 @@
-use crate::protocol::primitive::deserialize::Deserialize;
-use crate::protocol::primitive::serialize::Serialize;
+use crate::Deserialize;
+use crate::Serialize;
+/// The DateTime struct represents a DateTime as received in IRC
+///
+/// DateTime is, like all other struct based types, serialized sequentially.
#[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
+ /// Day in Julian calendar, unknown if signed or unsigned
+ julian_day: i32,
+ /// Milliseconds since start of day
+ millis_of_day: i32,
+ /// Timezone of DateTime, 0x00 is local, 0x01 is UTC
+ zone: u8,
}
impl Serialize for DateTime {
@@ -40,9 +46,13 @@ impl Deserialize for DateTime {
}
}
+/// The Date struct represents a Date as received in IRC
+///
+/// Date is, like all other struct based types, serialized sequentially.
#[derive(Clone, Debug, std::cmp::PartialEq)]
pub struct Date {
- julian_day: i32, // Day in Julian calendar, unknown if signed or unsigned
+ /// Day in Julian calendar, unknown if signed or unsigned
+ julian_day: i32,
}
impl Serialize for Date {
@@ -66,9 +76,13 @@ impl Deserialize for Date {
}
}
+/// The Time struct represents a Time as received in IRC
+///
+/// Time is, like all other struct based types, serialized sequentially.
#[derive(Clone, Debug, std::cmp::PartialEq)]
pub struct Time {
- millis_of_day: i32, // Milliseconds since start of day
+ /// Milliseconds since start of day
+ millis_of_day: i32,
}
impl Serialize for Time {
diff --git a/src/protocol/primitive/message.rs b/src/primitive/message.rs
index 4ae895d..64b132d 100644
--- a/src/protocol/primitive/message.rs
+++ b/src/primitive/message.rs
@@ -2,26 +2,41 @@ use std::vec::Vec;
use failure::Error;
-use crate::protocol::primitive::deserialize::{Deserialize, DeserializeUTF8};
-use crate::protocol::primitive::serialize::{Serialize, SerializeUTF8};
+use crate::{Deserialize, DeserializeUTF8};
+use crate::{Serialize, SerializeUTF8};
-use crate::protocol::primitive::BufferInfo;
-use crate::protocol::primitive::String;
+use crate::primitive::BufferInfo;
extern crate bytes;
+/// The Message struct represents a Message as received in IRC
+///
+/// Messages are, like all other struct based types, serialized sequentially.
#[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)
+ /// The unique, sequential id for the message
+ pub msg_id: i32,
+ /// The timestamp of the message in UNIX time (32-bit, seconds, 64-bit if LONGMESSAGE feature enabled)
+ pub timestamp: i64,
+ /// The message type as it's own type serialized as i32
pub msg_type: MessageType,
+ /// The flags
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
+ /// The buffer the message belongs to, usually everything but BufferId is set to NULL
+ pub buffer: BufferInfo,
+ /// The sender as nick!ident@host
+ pub sender: String,
+ /// The prefix modes of the sender.
+ /// Only Some when the SenderPrefix features is enabled
+ pub sender_prefixes: Option<String>,
+ /// The realName of the sender
+ /// Only Some when the RichMessage features is enabled
+ pub real_name: Option<String>,
+ /// The avatarUrl of the sender, if available
+ /// Only Some when the RichMessage features is enabled
+ pub avatar_url: Option<String>,
+ /// The message content, already stripped from CTCP formatting, but containing mIRC format codes
+ pub content: String,
}
impl Serialize for Message {
@@ -155,6 +170,7 @@ pub enum MessageType {
NetsplitJoin = 0x00008000,
NetsplitQuit = 0x00010000,
Invite = 0x00020000,
+ Markerline = 0x00040000,
}
impl From<i32> for MessageType {
@@ -178,6 +194,7 @@ impl From<i32> for MessageType {
0x00008000 => MessageType::NetsplitJoin,
0x00010000 => MessageType::NetsplitQuit,
0x00020000 => MessageType::Invite,
+ 0x00040000 => MessageType::Markerline,
_ => unimplemented!(),
}
}
diff --git a/src/primitive/mod.rs b/src/primitive/mod.rs
new file mode 100644
index 0000000..a3d2dcd
--- /dev/null
+++ b/src/primitive/mod.rs
@@ -0,0 +1,70 @@
+mod bufferinfo;
+mod datetime;
+mod message;
+mod signedint;
+mod string;
+mod stringlist;
+mod unsignedint;
+mod variant;
+mod variantlist;
+mod variantmap;
+
+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::*;
+
+/// Byte Representation of the type used in Variant to identify it
+pub const VOID: u32 = 0x00000000;
+/// Byte Representation of the type used in Variant to identify it
+pub const BOOL: u32 = 0x00000001;
+/// Byte Representation of the type used in Variant to identify it
+pub const QCHAR: u32 = 0x00000007;
+
+/// Byte Representation of the type used in Variant to identify it
+pub const QVARIANT: u32 = 0x00000090;
+/// Byte Representation of the type used in Variant to identify it
+pub const QVARIANTMAP: u32 = 0x00000008;
+/// Byte Representation of the type used in Variant to identify it
+pub const QVARIANTLIST: u32 = 0x00000009;
+
+/// Byte Representation of the type used in Variant to identify it
+pub const QSTRING: u32 = 0x0000000a;
+/// Byte Representation of the type used in Variant to identify it
+pub const QSTRINGLIST: u32 = 0x0000000b;
+/// Byte Representation of the type used in Variant to identify it
+pub const QBYTEARRAY: u32 = 0x0000000c;
+
+/// Byte Representation of the type used in Variant to identify it
+pub const QDATE: u32 = 0x0000000e;
+/// Byte Representation of the type used in Variant to identify it
+pub const QTIME: u32 = 0x0000000f;
+/// Byte Representation of the type used in Variant to identify it
+pub const QDATETIME: u32 = 0x00000010;
+/// Byte Representation of the type used in Variant to identify it
+pub const USERTYPE: u32 = 0x0000007f;
+
+// Basic types
+/// Byte Representation of the type used in Variant to identify it
+pub const LONG: u32 = 0x00000081; // int64_t
+/// Byte Representation of the type used in Variant to identify it
+pub const INT: u32 = 0x00000002; // int32_t
+/// Byte Representation of the type used in Variant to identify it
+pub const SHORT: u32 = 0x00000082; // int16_t
+/// Byte Representation of the type used in Variant to identify it
+pub const CHAR: u32 = 0x00000083; // int8_t
+
+/// Byte Representation of the type used in Variant to identify it
+pub const ULONG: u32 = 0x00000084; // uint64_t
+/// Byte Representation of the type used in Variant to identify it
+pub const UINT: u32 = 0x00000003; // uint32_t
+/// Byte Representation of the type used in Variant to identify it
+pub const USHORT: u32 = 0x00000085; // uint16_t
+/// Byte Representation of the type used in Variant to identify it
+pub const UCHAR: u32 = 0x00000086; // uint8_t
diff --git a/src/protocol/primitive/signedint.rs b/src/primitive/signedint.rs
index 67ffb9d..4c21a69 100644
--- a/src/protocol/primitive/signedint.rs
+++ b/src/primitive/signedint.rs
@@ -8,54 +8,54 @@ use std::vec::Vec;
use failure::Error;
-use crate::protocol::primitive::{deserialize, serialize};
+use crate::{Deserialize, Serialize};
-impl serialize::Serialize for i64 {
+impl Serialize for i64 {
fn serialize(&self) -> Result<Vec<u8>, Error> {
Ok(Vec::from(self.to_be_bytes()))
}
}
-impl deserialize::Deserialize for i64 {
+impl 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 {
+impl Serialize for i32 {
fn serialize(&self) -> Result<Vec<u8>, Error> {
Ok(Vec::from(self.to_be_bytes()))
}
}
-impl deserialize::Deserialize for i32 {
+impl 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 {
+impl Serialize for i16 {
fn serialize(&self) -> Result<Vec<u8>, Error> {
Ok(Vec::from(self.to_be_bytes()))
}
}
-impl deserialize::Deserialize for i16 {
+impl 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 {
+impl Serialize for i8 {
fn serialize(&self) -> Result<Vec<u8>, Error> {
Ok(Vec::from(self.to_be_bytes()))
}
}
-impl deserialize::Deserialize for i8 {
+impl 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/primitive/string.rs
index 470f018..86bcdec 100644
--- a/src/protocol/primitive/string.rs
+++ b/src/primitive/string.rs
@@ -7,11 +7,15 @@ use failure::Error;
use log::trace;
-use crate::protocol::primitive::{deserialize, serialize};
+use crate::{Deserialize, DeserializeUTF8, Serialize, SerializeUTF8};
use crate::util;
-pub type String = std::string::String;
-impl serialize::Serialize for String {
+/// We Shadow the String type here as we can only use impl on types in our own scope.
+///
+/// Strings are serialized as an i32 for the length in bytes, then the chars represented in UTF-16 in bytes.
+///
+/// Strings can only be serialized as UTF-8 null-terminated ByteArrays with (de)serialize_utf8().
+impl Serialize for String {
fn serialize(&self) -> Result<Vec<u8>, Error> {
let mut res: Vec<u8> = Vec::new();
@@ -25,7 +29,7 @@ impl serialize::Serialize for String {
}
}
-impl serialize::SerializeUTF8 for String {
+impl SerializeUTF8 for String {
fn serialize_utf8(&self) -> Result<Vec<u8>, Error> {
let mut res: Vec<u8> = Vec::new();
res.extend(self.clone().into_bytes());
@@ -35,11 +39,11 @@ impl serialize::SerializeUTF8 for String {
}
}
-impl deserialize::Deserialize for String {
+impl 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]);
+ trace!(target: "primitive::String", "Parsing with length: {:?}, from bytes: {:x?}", len, &b[0..4]);
if len == -1 {
return Ok((4, "".to_string()));
@@ -64,12 +68,11 @@ impl deserialize::Deserialize for String {
}
}
-impl deserialize::DeserializeUTF8 for String {
+impl 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]);
+ trace!(target: "primitive::String", "Parsing with length: {:?}, from bytes: {:x?}", len, &b[0..4]);
if len <= 0 {
return Ok((4, "".to_string()));
diff --git a/src/protocol/primitive/stringlist.rs b/src/primitive/stringlist.rs
index d2902f2..e5d1a44 100644
--- a/src/protocol/primitive/stringlist.rs
+++ b/src/primitive/stringlist.rs
@@ -8,10 +8,14 @@ use failure::Error;
use log::trace;
-use crate::protocol::primitive::{deserialize, serialize};
+use crate::{Deserialize, Serialize};
+/// StringList are represented as a Vec of Strings
+///
+/// StringLists are serialized as an i32 of the amount of elements and then each element as a String
pub type StringList = Vec<String>;
-impl serialize::Serialize for StringList {
+
+impl Serialize for StringList {
fn serialize(&self) -> Result<Vec<u8>, Error> {
let len: i32 = self.len().try_into()?;
let mut res: Vec<u8> = Vec::new();
@@ -25,10 +29,10 @@ impl serialize::Serialize for StringList {
}
}
-impl deserialize::Deserialize for StringList {
+impl 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]);
+ trace!(target: "primitive::StringList", "Parsing with length: {:?}, from bytes: {:x?}", len, &b[0..4]);
let mut res: StringList = StringList::new();
let mut pos = 4;
diff --git a/src/protocol/primitive/unsignedint.rs b/src/primitive/unsignedint.rs
index 5b42e3c..6e91e2a 100644
--- a/src/protocol/primitive/unsignedint.rs
+++ b/src/primitive/unsignedint.rs
@@ -7,10 +7,10 @@ use std::vec::Vec;
use failure::Error;
-use crate::protocol::error::ProtocolError;
-use crate::protocol::primitive::{deserialize, serialize};
+use crate::error::ProtocolError;
+use crate::{Deserialize, Serialize};
-impl serialize::Serialize for bool {
+impl Serialize for bool {
fn serialize(&self) -> Result<Vec<u8>, Error> {
Ok({
let i = *self as i8;
@@ -18,7 +18,7 @@ impl serialize::Serialize for bool {
})
}
}
-impl deserialize::Deserialize for bool {
+impl Deserialize for bool {
fn parse(b: &[u8]) -> Result<(usize, Self), Error> {
if b[0] == 0 {
return Ok((1, false));
@@ -29,52 +29,52 @@ impl deserialize::Deserialize for bool {
};
}
}
-impl serialize::Serialize for u64 {
+impl Serialize for u64 {
fn serialize(&self) -> Result<Vec<u8>, Error> {
Ok(Vec::from(self.to_be_bytes()))
}
}
-impl deserialize::Deserialize for u64 {
+impl 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 {
+impl Serialize for u32 {
fn serialize(&self) -> Result<Vec<u8>, Error> {
Ok(Vec::from(self.to_be_bytes()))
}
}
-impl deserialize::Deserialize for u32 {
+impl 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 {
+impl Serialize for u16 {
fn serialize(&self) -> Result<Vec<u8>, Error> {
Ok(Vec::from(self.to_be_bytes()))
}
}
-impl deserialize::Deserialize for u16 {
+impl 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 {
+impl Serialize for u8 {
fn serialize(&self) -> Result<Vec<u8>, Error> {
Ok(Vec::from(self.to_be_bytes()))
}
}
-impl deserialize::Deserialize for u8 {
+impl 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/primitive/variant.rs
index 84150a8..71ddc4a 100644
--- a/src/protocol/primitive/variant.rs
+++ b/src/primitive/variant.rs
@@ -4,24 +4,31 @@ use failure::Error;
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};
+use crate::error::ProtocolError;
+use crate::primitive;
+use crate::primitive::StringList;
+use crate::{Deserialize, DeserializeUTF8};
+use crate::{Serialize, SerializeUTF8};
extern crate bytes;
-use bytes::BytesMut;
-use crate::protocol::primitive::{
+use crate::primitive::{
BufferInfo, Date, DateTime, Message, Time, VariantList, VariantMap,
};
+/// Variant represents the possible types we can receive
+///
+/// Variant's are serizalized as the Type as a i32 and then the Type in it's own format
+///
+/// BufferInfo and Message are UserTypes
+/// but we represent them as a native Type here.
+///
+/// StringUTF8 is de-/serialized as a C ByteArray.
#[allow(non_camel_case_types, dead_code)]
#[derive(Clone, Debug, std::cmp::PartialEq)]
pub enum Variant {
Unknown,
- UserType(String, BytesMut),
+ UserType(String, Vec<u8>),
BufferInfo(BufferInfo),
Message(Message),
Time(Time),
@@ -31,7 +38,6 @@ pub enum Variant {
VariantList(VariantList),
String(String),
StringUTF8(String),
- ByteArray(String),
StringList(StringList),
bool(bool),
u64(u64),
@@ -73,12 +79,6 @@ impl Serialize for Variant {
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());
@@ -130,9 +130,22 @@ impl Serialize for Variant {
res.extend(unknown.to_be_bytes().iter());
res.extend(v.to_be_bytes().iter());
}
- Variant::UserType(_, _) => unimplemented!(),
- Variant::BufferInfo(_) => unimplemented!(),
- Variant::Message(_) => unimplemented!(),
+ Variant::UserType(name, bytes) => {
+ res.extend(primitive::USERTYPE.to_be_bytes().iter());
+ res.extend(unknown.to_be_bytes().iter());
+ res.append(&mut name.serialize_utf8()?);
+ res.extend(bytes);
+ }
+ Variant::BufferInfo(v) => {
+ let bytes = BufferInfo::serialize(v)?;
+ let user = Variant::UserType("BufferInfo".to_string(), bytes);
+ Variant::serialize(&user).unwrap();
+ }
+ Variant::Message(v) => {
+ let bytes = Message::serialize(v)?;
+ let user = Variant::UserType("Message".to_string(), bytes);
+ Variant::serialize(&user).unwrap();
+ }
Variant::DateTime(v) => {
res.extend(primitive::QDATETIME.to_be_bytes().iter());
res.extend(unknown.to_be_bytes().iter());
@@ -165,42 +178,42 @@ impl Deserialize for Variant {
let len = 5;
match qtype {
primitive::QVARIANTMAP => {
- trace!(target: "protocol::primitive::Variant", "Parsing Variant: VariantMap");
+ trace!(target: "primitive::Variant", "Parsing Variant: VariantMap");
let (vlen, value) = VariantMap::parse(&b[len..])?;
return Ok((len + vlen, Variant::VariantMap(value)));
}
primitive::QVARIANTLIST => {
- trace!(target: "protocol::primitive::Variant", "Parsing Variant: VariantList");
+ trace!(target: "primitive::Variant", "Parsing Variant: VariantList");
let (vlen, value) = VariantList::parse(&b[len..])?;
return Ok((len + vlen, Variant::VariantList(value)));
}
primitive::QSTRING => {
- trace!(target: "protocol::primitive::Variant", "Parsing Variant: String");
+ trace!(target: "primitive::Variant", "Parsing Variant: String");
let (vlen, value) = String::parse(&b[len..])?;
return Ok((len + vlen, Variant::String(value.clone())));
}
primitive::QBYTEARRAY => {
- trace!(target: "protocol::primitive::Variant", "Parsing Variant: ByteArray");
+ trace!(target: "primitive::Variant", "Parsing Variant: ByteArray");
let (vlen, value) = String::parse_utf8(&b[len..])?;
return Ok((len + vlen, Variant::StringUTF8(value.clone())));
}
primitive::QSTRINGLIST => {
- trace!(target: "protocol::primitive::Variant", "Parsing Variant: StringList");
+ trace!(target: "primitive::Variant", "Parsing Variant: StringList");
let (vlen, value) = StringList::parse(&b[len..])?;
return Ok((len + vlen, Variant::StringList(value.clone())));
}
primitive::QDATETIME => {
- trace!(target: "protocol::primitive::Variant", "Parsing Variant: Date");
+ trace!(target: "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");
+ trace!(target: "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");
+ trace!(target: "primitive::Variant", "Parsing Variant: Time");
let (vlen, value) = Time::parse(&b[len..])?;
return Ok((len + vlen, Variant::Time(value.clone())));
}
@@ -241,40 +254,41 @@ impl Deserialize for Variant {
return Ok((len + vlen, Variant::i8(value)));
}
primitive::USERTYPE => {
- trace!(target: "protocol::primitive::Variant", "Parsing UserType");
+ trace!(target: "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);
+ trace!(target: "primitive::Variant", "Parsing UserType: {:?}", user_type);
+ // TODO implement all these types
// 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");
+ trace!(target: "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");
+ trace!(target: "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");
+ trace!(target: "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");
+ trace!(target: "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");
+ trace!(target: "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)));
}
diff --git a/src/protocol/primitive/variantlist.rs b/src/primitive/variantlist.rs
index 2481b32..452b927 100644
--- a/src/protocol/primitive/variantlist.rs
+++ b/src/primitive/variantlist.rs
@@ -5,12 +5,15 @@ use failure::Error;
use log::trace;
-use crate::protocol::primitive::{deserialize::Deserialize, serialize::Serialize};
+use crate::{Deserialize, Serialize};
extern crate bytes;
-use crate::protocol::primitive::Variant;
+use crate::primitive::Variant;
+/// VariantLists are represented as a Vec of Variants.
+///
+/// They are serialized as the amount of entries as a i32 and then a Variant for each entry
pub type VariantList = Vec<Variant>;
impl Serialize for VariantList {
@@ -30,12 +33,12 @@ impl Serialize for VariantList {
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);
+ trace!(target: "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);
+ trace!(target: "primitive::VariantList", "Parsing VariantList element: {:?}", i);
let (vlen, val) = Variant::parse(&b[pos..])?;
res.push(val);
pos += vlen;
diff --git a/src/protocol/primitive/variantmap.rs b/src/primitive/variantmap.rs
index 22ca0f1..4f017f3 100644
--- a/src/protocol/primitive/variantmap.rs
+++ b/src/primitive/variantmap.rs
@@ -5,16 +5,17 @@ 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::Deserialize;
+use crate::Serialize;
-use crate::protocol::primitive::Variant;
+use crate::primitive::Variant;
use crate::util;
extern crate bytes;
+/// VariantMaps are represented as a HashMap with String as key and Variant as value
+///
+/// They are serialized as the amount of keys as an i32 then for each entry a String and a Variant.
pub type VariantMap = HashMap<String, Variant>;
impl Serialize for VariantMap {
@@ -36,25 +37,19 @@ impl Serialize for VariantMap {
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);
+ trace!(target: "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..])?;
+ trace!(target: "primitive::VariantMap", "Parsing entry name");
let (nlen, name) = String::parse(&b[pos..])?;
pos += nlen;
- trace!(target: "protocol::primitive::VariantMap", "Parsing entry: {:?} with len {:?}", name, &b[(pos)..(pos + 4)]);
+ trace!(target: "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);
}
diff --git a/src/protocol/mod.rs b/src/protocol/mod.rs
deleted file mode 100644
index 3630fab..0000000
--- a/src/protocol/mod.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-pub mod message;
-pub mod primitive;
-
-#[allow(dead_code)]
-pub mod error;
-
-#[allow(unused_variables, dead_code)]
-#[cfg(feature = "framing")]
-pub mod frame;
diff --git a/src/protocol/primitive/mod.rs b/src/protocol/primitive/mod.rs
deleted file mode 100644
index 5656d71..0000000
--- a/src/protocol/primitive/mod.rs
+++ /dev/null
@@ -1,74 +0,0 @@
-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 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;
- pub trait Serialize {
- fn serialize(&self) -> Result<Vec<u8>, Error>;
- }
- pub trait SerializeUTF8 {
- fn serialize_utf8(&self) -> Result<Vec<u8>, Error>;
- }
-}
-
-pub mod deserialize {
- use failure::Error;
- pub trait Deserialize {
- 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;
- }
-}
diff --git a/src/tests/base_types.rs b/src/tests/base_types.rs
index 4cc56ae..bbd2fc3 100644
--- a/src/tests/base_types.rs
+++ b/src/tests/base_types.rs
@@ -1,7 +1,7 @@
-use crate::protocol::primitive::deserialize::{Deserialize, DeserializeUTF8};
-use crate::protocol::primitive::serialize::{Serialize, SerializeUTF8};
+use crate::{Deserialize, DeserializeUTF8};
+use crate::{Serialize, SerializeUTF8};
-use crate::protocol::primitive::*;
+use crate::primitive::*;
#[test]
pub fn serialize_string() {
diff --git a/src/tests/frame.rs b/src/tests/frame.rs
index 0bc87ad..878379f 100644
--- a/src/tests/frame.rs
+++ b/src/tests/frame.rs
@@ -20,7 +20,7 @@ use flate2::Decompress;
use flate2::FlushCompress;
use flate2::FlushDecompress;
-use crate::protocol::frame::QuasselCodec;
+use crate::frame::QuasselCodec;
macro_rules! mock {
($($x:expr,)*) => {{
@@ -131,24 +131,23 @@ pub fn read_single_frame_compressed() {
assert_done!(io);
}
-// TODO shit doens't work for whatever reason
-// #[test]
-// pub fn read_multi_frame_compressed() {
-// let io = FramedRead::new(
-// mock! {
-// data(
-// b"\x78\x9c\x63\x60\x60\xe0\x4c\x4c\x4a\x4e\x49\x4d\x4b\xcf\xc8\x04\x00\x11\xec\x03\x97\x78\x9c\x63\x60\x60\x60\x36\x34\x32\x06\x00\x01\x3d\x00\x9a\x78\x9c\x63\x60\x60\xe0\xce\x48\xcd\xc9\xc9\x57\x28\xcf\x2f\xca\x49\x01\x00\x1a\x93\x04\x68",
-// ),
-// },
-// QuasselCodec::builder().compression(true).new_codec(),
-// );
-// pin_mut!(io);
-//
-// assert_next_eq!(io, b"abcdefghi");
-// assert_next_eq!(io, b"123");
-// assert_next_eq!(io, b"hello world");
-// assert_done!(io);
-// }
+#[test]
+pub fn read_multi_frame_compressed() {
+ let io = FramedRead::new(
+ mock! {
+ data(
+ b"\x78\x9c\x63\x60\x60\xe0\x4c\x4c\x4a\x4e\x49\x4d\x4b\xcf\xc8\x04\x00\x11\xec\x03\x97\x78\x9c\x63\x60\x60\x60\x36\x34\x32\x06\x00\x01\x3d\x00\x9a\x78\x9c\x63\x60\x60\xe0\xce\x48\xcd\xc9\xc9\x57\x28\xcf\x2f\xca\x49\x01\x00\x1a\x93\x04\x68",
+ ),
+ },
+ QuasselCodec::builder().compression(true).new_codec(),
+ );
+ pin_mut!(io);
+
+ assert_next_eq!(io, b"abcdefghi");
+ assert_next_eq!(io, b"123");
+ assert_next_eq!(io, b"hello world");
+ assert_done!(io);
+}
// ======================
// ===== Test utils =====
diff --git a/src/tests/handshake_types.rs b/src/tests/handshake_types.rs
index d18ec8a..1e789c1 100644
--- a/src/tests/handshake_types.rs
+++ b/src/tests/handshake_types.rs
@@ -1,5 +1,5 @@
-use crate::protocol::message::handshake::{HandshakeDeserialize, HandshakeSerialize, VariantMap};
-use crate::protocol::primitive::Variant;
+use crate::primitive::{Variant, VariantMap};
+use crate::{HandshakeDeserialize, HandshakeSerialize};
#[test]
pub fn serialize_variantmap() {
diff --git a/src/tests/variant_types.rs b/src/tests/variant_types.rs
index 0381f07..7ba4166 100644
--- a/src/tests/variant_types.rs
+++ b/src/tests/variant_types.rs
@@ -1,9 +1,7 @@
-use crate::protocol::primitive::deserialize::Deserialize;
-use crate::protocol::primitive::serialize::Serialize;
+use crate::Deserialize;
+use crate::Serialize;
-use crate::protocol::primitive::{
- BufferInfo, BufferType, Message, Variant, VariantList, VariantMap,
-};
+use crate::primitive::{BufferInfo, BufferType, Message, Variant, VariantList, VariantMap};
#[test]
pub fn serialize_variant_bool() {
@@ -56,13 +54,13 @@ pub fn serialize_variantmap() {
#[test]
pub fn deserialize_variantmap() {
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,
+ 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,
];
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, 39);
+ assert_eq!(len, 34);
assert_eq!(res, test_variantmap);
}
diff --git a/src/util.rs b/src/util.rs
index 33735f1..dd87f7f 100644
--- a/src/util.rs
+++ b/src/util.rs
@@ -1,38 +1,21 @@
-#[macro_export]
-macro_rules! parse_match {
- ( $matchee:expr, $pos:expr, $map:expr, $bytes:expr, $name:expr, $(($pattern:pat, $type:ty, $variant:expr)),* ) => {
- match $matchee {
- $(
- $pattern => {
- let value: $type;
-
- $pos = $pos + value.parse(&$bytes[($pos)..]);
- $map.insert($name, $variant(value));
- },
- )*
- };
- };
-}
-
+/// Match a VariantMaps field and return it's contents if successfull
+///
+/// # Example
+///
+/// ```
+/// use libquassel::primitive::{VariantMap, Variant};
+///
+/// let var = Variant::String("test string");
+/// let result = match_variant!(var, Variant::String);
+/// ```
#[macro_export]
macro_rules! match_variant {
- ( $values:expr, $x:path, $field:expr ) => {
- match &$values[$field] {
- $x(x) => { Ok(x.clone()) },
- _ => { Err("") }
- }.unwrap();
- }
-}
-
-use crate::protocol::primitive::{Variant};
-use crate::protocol::error::ProtocolError;
-use failure::Error;
-
-pub fn get_msg_type(val: &Variant) -> Result<&str, Error> {
- match val {
- Variant::String(x) => return Ok(x),
- Variant::StringUTF8(x) => return Ok(x),
- _ => bail!(ProtocolError::WrongVariant)
+ ( $values:expr, $x:path ) => {
+ match &$values {
+ $x(x) => Ok(x.clone()),
+ _ => Err(""),
+ }
+ .unwrap();
};
}