1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
use crate::value::{
    Bus, BusError, Error, ErrorError, Interface, InterfaceError, Member, MemberError, ObjectPath,
    Struct, Type, Value,
};
use std::convert::TryFrom;
use thiserror::Error as ThisError;

macro_rules! try_set_field {
    ($function:ident, $field:ident, $variant:ident, $multiple_error:ident, $error:ident $(,$convert:expr)?) => {
        fn $function(&mut self, v: Value) -> Result<(), FieldsError> {
            if self.$field.is_some() {
                return Err(FieldsError::$multiple_error(v));
            }

            match v {
                Value::$variant(o) => {
                    $(let o = $convert(o)?;)?
                    self.$field = Some(o);
                    Ok(())
                }
                v => Err(FieldsError::$error(v)),
            }
        }
    };
}

macro_rules! add_to_vec {
    ($vec:ident, $fields:ident, $field:ident, $number:literal, $variant:ident $(,$convert:ident)?) => {
        if let Some(v) = $fields.$field {
            $(let v = v.$convert();)?
            $vec.push(Value::Struct(Struct(vec![
                Value::Byte($number),
                Value::Variant(Box::new(Value::$variant(v))),
            ])));
        }
    };
}

#[derive(Debug, PartialEq, ThisError)]
pub enum FieldsError {
    #[error("Value is not a Struct: {0:?}")]
    Struct(Value),
    #[error("Struct does not contain exactly two values: {0}")]
    Length(usize),
    #[error("Second value is not a Variant: {0:?}")]
    Variant(Value),
    #[error("First value is not a Byte: {0:?}")]
    Byte(Value),
    #[error("Variant does not contain a ObjectPath: {0:?}")]
    Path(Value),
    #[error("Variant does not contain a String: {0:?}")]
    Interface(Value),
    #[error("String could not be converted to an Interface: {0}")]
    InterfaceError(#[from] InterfaceError),
    #[error("Variant does not contain a String: {0:?}")]
    Member(Value),
    #[error("String could not be converted to an Member: {0}")]
    MemberError(#[from] MemberError),
    #[error("Variant does not contain a String: {0:?}")]
    ErrorName(Value),
    #[error("String could not be converted to an ErrorName: {0}")]
    ErrorError(#[from] ErrorError),
    #[error("Variant does not contain a Uint32: {0:?}")]
    ReplySerial(Value),
    #[error("")]
    BusError(#[from] BusError),
    #[error("Variant does not contain a String: {0:?}")]
    Destination(Value),
    #[error("Variant does not contain a String: {0:?}")]
    Sender(Value),
    #[error("Variant does not contain a Signature: {0:?}")]
    Signature(Value),
    #[cfg(target_family = "unix")]
    #[error("Variant does not contain a Uint32: {0:?}")]
    UnixFDs(Value),
    #[error("The byte does not has a valid number: {0}")]
    InvalidNumber(u8),
    #[error("The path is defined mutlple times: {0:?}")]
    MultiplePath(Value),
    #[error("The interface is defined mutlple times: {0:?}")]
    MultipleInterface(Value),
    #[error("The member is defined mutlple times: {0:?}")]
    MultipleMember(Value),
    #[error("The error name is defined mutlple times: {0:?}")]
    MultipleErrorName(Value),
    #[error("The reply serial is defined mutlple times: {0:?}")]
    MultipleReplySerial(Value),
    #[error("The destination is defined mutlple times: {0:?}")]
    MultipleDestination(Value),
    #[error("The destination is defined mutlple times: {0:?}")]
    MultipleSender(Value),
    #[error("The signature is defined mutlple times: {0:?}")]
    MultipleSignature(Value),
    #[cfg(target_family = "unix")]
    #[error("The unix fds is defined mutlple times: {0:?}")]
    MultipleUnixFDs(Value),
}

/// An struct representing the [header fields].
///
/// [header fields]: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-header-fields
#[derive(Debug, Clone, PartialOrd, PartialEq, Ord, Eq, Default)]
pub struct Fields {
    pub path: Option<ObjectPath>,
    pub interface: Option<Interface>,
    pub member: Option<Member>,
    pub error_name: Option<Error>,
    pub reply_serial: Option<u32>,
    pub destination: Option<Bus>,
    pub sender: Option<Bus>,
    pub signature: Option<Vec<Type>>,
    #[cfg(target_family = "unix")]
    pub unix_fds: Option<u32>,
}

impl Fields {
    try_set_field!(try_set_path, path, ObjectPath, MultiplePath, Path);
    try_set_field!(
        try_set_interface,
        interface,
        String,
        MultipleInterface,
        Interface,
        Interface::try_from
    );
    try_set_field!(
        try_set_member,
        member,
        String,
        MultipleMember,
        Member,
        Member::try_from
    );
    try_set_field!(
        try_set_error_name,
        error_name,
        String,
        MultipleErrorName,
        ErrorName,
        Error::try_from
    );
    try_set_field!(
        try_set_reply_serial,
        reply_serial,
        Uint32,
        MultipleReplySerial,
        ReplySerial
    );
    try_set_field!(
        try_set_destination,
        destination,
        String,
        MultipleDestination,
        Destination,
        Bus::try_from
    );
    try_set_field!(
        try_set_sender,
        sender,
        String,
        MultipleSender,
        Sender,
        Bus::try_from
    );
    try_set_field!(
        try_set_signature,
        signature,
        Signature,
        MultipleSignature,
        Signature
    );
    #[cfg(target_family = "unix")]
    try_set_field!(try_set_unix_fds, unix_fds, Uint32, MultipleUnixFDs, UnixFDs);

    fn try_set_field(&mut self, b: u8, v: Value) -> Result<(), FieldsError> {
        match b {
            1 => self.try_set_path(v),
            2 => self.try_set_interface(v),
            3 => self.try_set_member(v),
            4 => self.try_set_error_name(v),
            5 => self.try_set_reply_serial(v),
            6 => self.try_set_destination(v),
            7 => self.try_set_sender(v),
            8 => self.try_set_signature(v),
            #[cfg(target_family = "unix")]
            9 => self.try_set_unix_fds(v),
            // Invalid number.
            b => Err(FieldsError::InvalidNumber(b)),
        }
    }
}

fn unwrap_value(value: Value) -> Result<(u8, Value), FieldsError> {
    // The outer `Value` has to be a struct.
    let mut values: Vec<Value> = match value {
        Value::Struct(struct_) => struct_.into(),
        v => return Err(FieldsError::Struct(v)),
    };
    // The length of the struct have to be 2
    let values_len = values.len();
    if values_len != 2 {
        return Err(FieldsError::Length(values_len));
    }
    // Check if the second is a Variant and unwrap the value.
    let v = match values.pop().unwrap() {
        Value::Variant(v) => *v,
        v => return Err(FieldsError::Variant(v)),
    };
    // Check if the first is a byte
    let b = match values.pop().unwrap() {
        Value::Byte(b) => b,
        v => return Err(FieldsError::Byte(v)),
    };

    Ok((b, v))
}

impl TryFrom<Vec<Value>> for Fields {
    type Error = FieldsError;

    fn try_from(values: Vec<Value>) -> Result<Self, Self::Error> {
        let mut fields = Fields::default();

        for value in values {
            let (b, v) = unwrap_value(value)?;
            fields.try_set_field(b, v)?;
        }

        Ok(fields)
    }
}

impl From<Fields> for Vec<Value> {
    fn from(fields: Fields) -> Self {
        let mut values = Vec::new();

        add_to_vec!(values, fields, path, 1, ObjectPath);
        add_to_vec!(values, fields, interface, 2, String, to_string);
        add_to_vec!(values, fields, member, 3, String, to_string);
        add_to_vec!(values, fields, error_name, 4, String, to_string);
        add_to_vec!(values, fields, reply_serial, 5, Uint32);
        add_to_vec!(values, fields, destination, 6, String, to_string);
        add_to_vec!(values, fields, sender, 7, String, to_string);
        add_to_vec!(values, fields, signature, 8, Signature);
        #[cfg(target_family = "unix")]
        add_to_vec!(values, fields, unix_fds, 9, Uint32);
        values
    }
}