Files
arrayvec
async_attributes
async_channel
async_executor
async_global_executor
async_io
async_lock
async_mutex
async_process
async_rustbus
async_std
collections
fs
future
io
net
option
os
path
pin
result
rt
stream
string
sync
task
unit
vec
async_task
atomic_waker
bitflags
blocking
cache_padded
cfg_if
concurrent_queue
crossbeam_utils
ctor
derive_utils
event_listener
fastrand
find_crate
futures
futures_channel
futures_core
futures_enum
futures_executor
futures_io
futures_lite
futures_macro
futures_sink
futures_task
futures_util
async_await
future
io
lock
sink
stream
task
kv_log_macro
lazy_static
libc
log
memchr
nix
num_cpus
once_cell
parking
pin_project_lite
pin_utils
polling
proc_macro2
proc_macro_hack
proc_macro_nested
quote
rustable
rustbus
rustbus_derive
serde
signal_hook
signal_hook_registry
slab
socket2
syn
toml
unicode_xid
value_bag
void
waker_fn
xml
  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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! Various validation functions for e.g. ObjectPath constraints

use super::*;
use crate::message_builder::MessageType;
use crate::params;
use crate::signature;
use crate::wire::HeaderField;

#[derive(Debug, Eq, PartialEq)]
pub enum Error {
    InvalidSignature(signature::Error),
    InvalidObjectPath,
    InvalidBusname,
    InvalidErrorname,
    InvalidMembername,
    InvalidInterface,
    InvalidHeaderFields,
    StringContainsNullByte,
    InvalidUtf8,
    DuplicatedHeaderFields,
    ArrayElementTypesDiffer,
    DictKeyTypesDiffer,
    DictValueTypesDiffer,
}

type Result<T> = std::result::Result<T, Error>;

pub fn validate_object_path(op: &str) -> Result<()> {
    if op.is_empty() {
        return Err(Error::InvalidObjectPath);
    }
    if !op.starts_with('/') {
        return Err(Error::InvalidObjectPath);
    }
    if op.len() > 1 {
        let split = op.split('/').collect::<Vec<_>>();
        if split.len() < 2 {
            return Err(Error::InvalidObjectPath);
        }
        for element in &split[1..] {
            if element.is_empty() {
                return Err(Error::InvalidObjectPath);
            }
            let alphanum_or_underscore = element.chars().all(|c| c.is_alphanumeric() || c == '_');
            if !alphanum_or_underscore {
                return Err(Error::InvalidObjectPath);
            }
        }
    }
    Ok(())
}
pub fn validate_interface(int: &str) -> Result<()> {
    let split = int.split('.');
    let mut cnt = 0;
    for (i, element) in split.enumerate() {
        if element
            .chars()
            .next()
            .ok_or(Error::InvalidInterface)?
            .is_numeric()
        {
            return Err(Error::InvalidInterface);
        }
        let alphanum_or_underscore = element.chars().all(|c| c.is_alphanumeric() || c == '_');
        if !alphanum_or_underscore {
            return Err(Error::InvalidInterface);
        }
        cnt = i + 1;
    }
    if cnt >= 2 {
        Ok(())
    } else {
        Err(Error::InvalidInterface)
    }
}

#[inline]
pub fn validate_errorname(en: &str) -> Result<()> {
    validate_interface(en).map_err(|_| Error::InvalidErrorname)
}

pub fn validate_busname(bn: &str) -> Result<()> {
    let (unique, bus_name) = if let Some(unique_name) = bn.strip_prefix(':') {
        (true, unique_name)
    } else {
        (false, bn)
    };

    let split = bus_name.split('.');
    let mut cnt = 0;
    for (i, element) in split.enumerate() {
        if element
            .chars()
            .next()
            .ok_or(Error::InvalidBusname)?
            .is_numeric()
            && !unique
        {
            return Err(Error::InvalidBusname);
        }
        let alphanum_or_underscore_or_dash = element
            .chars()
            .all(|c| c.is_alphanumeric() || c == '_' || c == '-');
        if !alphanum_or_underscore_or_dash {
            return Err(Error::InvalidBusname);
        }
        cnt = i + 1;
    }
    if cnt >= 2 {
        Ok(())
    } else {
        Err(Error::InvalidBusname)
    }
}

pub fn validate_membername(mem: &str) -> Result<()> {
    if mem.is_empty() {
        return Err(Error::InvalidMembername);
    }

    let alphanum_or_underscore = mem.chars().all(|c| c.is_alphanumeric() || c == '_');
    if !alphanum_or_underscore {
        return Err(Error::InvalidMembername);
    }

    Ok(())
}

pub fn validate_signature(sig: &str) -> Result<()> {
    signature::Type::parse_description(sig).map_err(Error::InvalidSignature)?;
    Ok(())
}

pub fn validate_array<'a, 'e>(array: &[Param<'a, 'e>], sig: &signature::Type) -> Result<()> {
    if array.is_empty() {
        return Ok(());
    }
    for el in array {
        if !sig.eq(&el.sig()) {
            return Err(Error::ArrayElementTypesDiffer);
        }
    }
    Ok(())
}

pub fn validate_dict(
    dict: &params::DictMap,
    key_sig: signature::Base,
    val_sig: &signature::Type,
) -> Result<()> {
    if dict.is_empty() {
        return Ok(());
    }
    let key_sig = signature::Type::Base(key_sig);
    for el in dict.keys() {
        if !key_sig.eq(&el.sig()) {
            return Err(Error::DictKeyTypesDiffer);
        }
    }

    for el in dict.values() {
        if !val_sig.eq(&el.sig()) {
            return Err(Error::DictValueTypesDiffer);
        }
    }
    Ok(())
}

pub fn validate_header_fields(msg_type: MessageType, header_fields: &[HeaderField]) -> Result<()> {
    let mut have_path = false;
    let mut have_interface = false;
    let mut have_member = false;
    let mut have_errorname = false;
    let mut have_replyserial = false;
    let mut have_destination = false;
    let mut have_sender = false;
    let mut have_signature = false;
    let mut have_unixfds = false;

    for h in header_fields {
        match h {
            HeaderField::Destination(_) => {
                if have_destination {
                    return Err(Error::DuplicatedHeaderFields);
                }
                have_destination = true;
            }
            HeaderField::ErrorName(_) => {
                if have_errorname {
                    return Err(Error::DuplicatedHeaderFields);
                }
                have_errorname = true;
            }
            HeaderField::Interface(_) => {
                if have_interface {
                    return Err(Error::DuplicatedHeaderFields);
                }
                have_interface = true;
            }
            HeaderField::Member(_) => {
                if have_member {
                    return Err(Error::DuplicatedHeaderFields);
                }
                have_member = true;
            }
            HeaderField::Path(_) => {
                if have_path {
                    return Err(Error::DuplicatedHeaderFields);
                }
                have_path = true;
            }
            HeaderField::ReplySerial(_) => {
                if have_replyserial {
                    return Err(Error::DuplicatedHeaderFields);
                }
                have_replyserial = true;
            }
            HeaderField::Sender(_) => {
                if have_sender {
                    return Err(Error::DuplicatedHeaderFields);
                }
                have_sender = true;
            }
            HeaderField::Signature(_) => {
                if have_signature {
                    return Err(Error::DuplicatedHeaderFields);
                }
                have_signature = true;
            }
            HeaderField::UnixFds(_) => {
                if have_unixfds {
                    return Err(Error::DuplicatedHeaderFields);
                }
                have_unixfds = true;
            }
        }
    }

    let valid = match msg_type {
        MessageType::Invalid => false,
        MessageType::Call => have_path && have_member,
        MessageType::Signal => have_path && have_member && have_interface,
        MessageType::Reply => have_replyserial,
        MessageType::Error => have_errorname && have_replyserial,
    };
    if valid {
        Ok(())
    } else {
        Err(Error::InvalidHeaderFields)
    }
}

// more specific tests for constraints on strings
#[test]
fn test_objectpath_constraints() {
    let no_beginning_slash = "da/di/du";
    assert_eq!(
        Err(Error::InvalidObjectPath),
        crate::params::validate_object_path(no_beginning_slash)
    );
    let empty_element = "/da//du";
    assert_eq!(
        Err(Error::InvalidObjectPath),
        crate::params::validate_object_path(empty_element)
    );
    let trailing_slash = "/da/di/du/";
    assert_eq!(
        Err(Error::InvalidObjectPath),
        crate::params::validate_object_path(trailing_slash)
    );
    let invalid_chars = "/da$$/di!!/du~~";
    assert_eq!(
        Err(Error::InvalidObjectPath),
        crate::params::validate_object_path(invalid_chars)
    );
    let trailing_slash_on_root = "/";
    assert_eq!(
        Ok(()),
        crate::params::validate_object_path(trailing_slash_on_root)
    );
}
#[test]
fn test_interface_constraints() {
    let invalid_chars = "/da$$/di!!/du~~";
    assert_eq!(
        Err(Error::InvalidInterface),
        crate::params::validate_interface(invalid_chars)
    );
    let leading_digits = "1leading.digits";
    assert_eq!(
        Err(Error::InvalidInterface),
        crate::params::validate_interface(leading_digits)
    );
    let too_short = "have_more_than_one_element";
    assert_eq!(
        Err(Error::InvalidInterface),
        crate::params::validate_interface(too_short)
    );
    let too_long = (0..256).fold(String::new(), |mut s, _| {
        s.push('b');
        s.push('.');
        s
    });
    assert_eq!(
        Err(Error::InvalidInterface),
        crate::params::validate_interface(&too_long)
    );
}
#[test]
fn test_busname_constraints() {
    let invalid_chars = "/da$$/di!!/du~~";
    assert_eq!(
        Err(Error::InvalidBusname),
        crate::params::validate_busname(invalid_chars)
    );
    let empty = "";
    assert_eq!(
        Err(Error::InvalidBusname),
        crate::params::validate_busname(empty)
    );
    let too_short = "have_more_than_one_element";
    assert_eq!(
        Err(Error::InvalidBusname),
        crate::params::validate_busname(too_short)
    );

    let too_long = (0..256).fold(String::new(), |mut s, _| {
        s.push('b');
        s.push('.');
        s
    });
    assert_eq!(
        Err(Error::InvalidBusname),
        crate::params::validate_busname(&too_long)
    );
}
#[test]
fn test_membername_constraints() {
    let invalid_chars = "/da$$/di!!/du~~";
    assert_eq!(
        Err(Error::InvalidMembername),
        crate::params::validate_membername(invalid_chars)
    );
    let dots = "Shouldnt.have.dots";
    assert_eq!(
        Err(Error::InvalidMembername),
        crate::params::validate_membername(dots)
    );
    let empty = "";
    assert_eq!(
        Err(Error::InvalidMembername),
        crate::params::validate_membername(empty)
    );

    let too_long = (0..256).fold(String::new(), |mut s, _| {
        s.push('b');
        s.push('.');
        s
    });
    assert_eq!(
        Err(Error::InvalidMembername),
        crate::params::validate_membername(&too_long)
    );
}
#[test]
fn test_signature_constraints() {
    let wrong_parans = "((i)";
    assert_eq!(
        Err(Error::InvalidSignature(
            crate::signature::Error::InvalidSignature
        )),
        crate::params::validate_signature(wrong_parans)
    );
    let wrong_parans = "(i))";
    assert_eq!(
        Err(Error::InvalidSignature(
            crate::signature::Error::InvalidSignature
        )),
        crate::params::validate_signature(wrong_parans)
    );
    let wrong_parans = "a{{i}";
    assert_eq!(
        Err(Error::InvalidSignature(
            crate::signature::Error::InvalidSignature
        )),
        crate::params::validate_signature(wrong_parans)
    );
    let wrong_parans = "a{i}}";
    assert_eq!(
        Err(Error::InvalidSignature(
            crate::signature::Error::InvalidSignature
        )),
        crate::params::validate_signature(wrong_parans)
    );
    let array_without_type = "(i)a";
    assert_eq!(
        Err(Error::InvalidSignature(
            crate::signature::Error::InvalidSignature
        )),
        crate::params::validate_signature(array_without_type)
    );
    let invalid_chars = "!!§$%&(i)a";
    assert_eq!(
        Err(Error::InvalidSignature(
            crate::signature::Error::InvalidSignature
        )),
        crate::params::validate_signature(invalid_chars)
    );

    let too_deep_nesting = "(((((((((((((((((((((((((((((((((y)))))))))))))))))))))))))))))))))";
    assert_eq!(
        Err(Error::InvalidSignature(
            crate::signature::Error::NestingTooDeep
        )),
        crate::params::validate_signature(too_deep_nesting)
    );

    let too_long = (0..256).fold(String::new(), |mut s, _| {
        s.push('b');
        s
    });
    assert_eq!(
        Err(Error::InvalidSignature(
            crate::signature::Error::SignatureTooLong
        )),
        crate::params::validate_signature(&too_long)
    );
}