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
use std::error::Error as stdError;
use std::fmt::{Debug, Formatter, Display};
use crate::message::MatchRule;
use crate::{MessageType, Path};
use std::convert::TryFrom;
use crate::strings::{Interface, BusName, Member};
#[derive(Clone, Debug)]
pub enum Error {
UnknownType,
UnknownKey,
BadBoolean,
BadConversion(String),
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "Error while parsing MatchRule: ")?;
match self {
Error::UnknownType => {
write!(f, "Unsupported message type")
}
Error::UnknownKey => {
write!(f, "Unknown key used")
}
Error::BadBoolean => {
write!(f, "Got bad boolean value")
}
Error::BadConversion(err) => {
write!(f, "Error while converting: {}", err)
}
}
}
}
impl stdError for Error {}
pub type TokenRule<'a> = (&'a str, &'a str);
pub type TokenBuffer<'a> = Vec<TokenRule<'a>>;
#[derive(Clone, Debug)]
struct Tokenizer<'a> {
text: &'a str,
}
impl<'a> Tokenizer<'a> {
pub fn new(text: &'a str) -> Self {
Self {
text,
}
}
fn key(&self) -> (&'a str, &'a str) {
let index = self.text.find('=').unwrap_or_else(|| self.text.len());
((&self.text[..index]).trim(), &self.text[index + 1..])
}
fn value(&self) -> (&'a str, &'a str) {
let mut i = 0;
let mut quoted = false;
let mut escape = false;
for c in self.text.chars() {
match c {
'\'' if !escape => {
quoted = !quoted;
}
',' if !quoted => {
break;
}
'\\' if !quoted => {
escape = true;
i += 1;
continue;
}
_ => {}
}
escape = false;
i += 1;
}
let j = if self.text.len() == i { i } else { i + 1 };
((&self.text[..i]).trim(), &self.text[j..])
}
pub fn tokenize(&mut self) -> Result<TokenBuffer<'a>, Error> {
let mut rules = TokenBuffer::new();
while !self.text.is_empty() {
let (key, rest) = self.key();
self.text = rest;
let (value, rest) = self.value();
self.text = rest;
rules.push((key, value))
}
Ok(rules)
}
}
#[derive(Clone, Debug)]
pub struct Parser<'a> {
tokens: TokenBuffer<'a>,
}
impl<'a> Parser<'a> {
pub fn new(text: &'a str) -> Result<Self, Error> {
Ok(Self {
tokens: Tokenizer::new(text).tokenize()?
})
}
fn clean_string(&self, buf: &str) -> String {
let mut quoted = false;
let mut escape = false;
let mut outbuf = String::with_capacity(buf.len());
for c in buf.chars() {
match c {
'\'' if !escape => {
quoted = !quoted;
}
'\\' if !quoted => {
escape = true;
continue;
}
c if c.is_whitespace() && !quoted => {
continue;
}
c => {
outbuf.push(c);
}
}
}
outbuf
}
pub fn parse(&self) -> Result<MatchRule<'a>, Error> {
let mut match_rule = MatchRule::new();
for &(key, raw_value) in &self.tokens {
let value = self.clean_string(raw_value);
match key {
"type" => {
match_rule = match_rule.with_type(MessageType::try_from(value.as_str()).map_err(|_| Error::UnknownType)?);
Ok(())
}
"interface" => {
match_rule.interface = Some(Interface::new(value).map_err(Error::BadConversion)?);
Ok(())
}
"sender" => {
match_rule.sender = Some(BusName::new(value).map_err(Error::BadConversion)?);
Ok(())
}
"member" => {
match_rule.member = Some(Member::new(value).map_err(Error::BadConversion)?);
Ok(())
}
"path" => {
match_rule.path = Some(Path::new(value).map_err(Error::BadConversion)?);
Ok(())
}
"path_namespace" => {
match_rule.path = Some(Path::new(value).map_err(Error::BadConversion)?);
match_rule.path_is_namespace = true;
Ok(())
}
"eavesdrop" => {
match raw_value {
"'true'" | "true" => {
match_rule = match_rule.with_eavesdrop();
Ok(())
}
"'false'" | "false" => {
Ok(())
}
_ => {
Err(Error::BadBoolean)
}
}
}
_ => {
Err(Error::UnknownKey)
}
}?;
}
Ok(match_rule)
}
}
#[cfg(test)]
mod tests {
use crate::message::parser::Error;
use crate::message::MatchRule;
#[test]
fn test_tokenizer() -> Result<(), Error> {
let mr = MatchRule::parse(r"interface='org.freedesktop.Notifications',member='Notify'")?;
assert_eq!(mr.match_str(), "interface='org.freedesktop.Notifications',member='Notify'");
let mr = MatchRule::parse(r"interface='org.mpris.MediaPlayer2.Player' , path= /org/mpris/MediaPlayer2,member='Notify', eavesdrop ='true'")?;
assert_eq!(mr.match_str(), "path='/org/mpris/MediaPlayer2',interface='org.mpris.MediaPlayer2.Player',member='Notify',eavesdrop='true'");
Ok(())
}
#[test]
fn test_malformed() {
assert!(MatchRule::parse(r"interface='org.freedesktop.Notifications',member=").is_err());
}
#[test]
fn test_spurious_comma() {
assert!(MatchRule::parse(r"interface='org.freedesktop.Notifications',").is_ok());
}
}