Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

client_class: add split() #39

Merged
merged 1 commit into from
Sep 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions libs/client-classification/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ pub enum Expr {
Concat(Box<Expr>, Box<Expr>),
IfElse(Box<Expr>, Box<Expr>, Box<Expr>),
Hexstring(Box<Expr>, String),
Split(Box<Expr>, Box<Expr>, usize),
// prefix
Not(Box<Expr>),
// postfix
Expand Down Expand Up @@ -82,6 +83,8 @@ pub enum ParseErr {
IfElse(String),
#[error("'concat parse error with: {0}")]
Concat(String),
#[error("'split parse error with: {0}")]
Split(String),
#[error("expected option but found: {0}")]
Option(Expr),
#[error("bool parse error with: {0}")]
Expand Down Expand Up @@ -177,6 +180,23 @@ fn parse_expr(pairs: Pairs<Rule>, pratt: &PrattParser<Rule>) -> ParseResult<Expr
Box::new(parse_expr(b.into_inner(), pratt)?),
)
}
Rule::split => {
let mut inner = primary.into_inner();
let n = inner
.next_back()
.ok_or_else(|| ParseErr::Split(inner.to_string()))?;
let del = inner
.next_back()
.ok_or_else(|| ParseErr::Split(inner.to_string()))?;
let s = inner
.next_back()
.ok_or_else(|| ParseErr::Split(inner.to_string()))?;
Expr::Split(
Box::new(parse_expr(s.into_inner(), pratt)?),
Box::new(parse_expr(del.into_inner(), pratt)?),
n.as_str().parse()?,
)
}
Rule::hexstring => {
let mut inner = primary.into_inner();
let separator = parse_string(
Expand Down
34 changes: 19 additions & 15 deletions libs/client-classification/src/grammar.pest
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,6 @@ option = { "option[" ~ integer ~ "]" }
relay = { "relay4[" ~ integer ~ "]" }
member = { "member(" ~ string ~ ")" }

// builtin = _{
// builtin_bootp
// | builtin_known
// | builtin_unknown
// | builtin_all
// | builtin_drop
// | builtin_vendor
// }
// builtin_bootp = @{ "BOOTP" }
// builtin_known = @{ "KNOWN" }
// builtin_unknown = @{ "UNKNOWN" }
// builtin_all = @{ "ALL" }
// builtin_vendor = @{ "VENDOR_CLASS_" ~ ANY }

pkt = _{
pkt_mac
| pkt_hlen
Expand Down Expand Up @@ -77,6 +63,7 @@ end = _{


substring = { "substring(" ~ expr ~ "," ~ signed_int ~ "," ~ end ~ ")" }
split = { "split(" ~ expr ~ "," ~ expr ~ "," ~ integer ~ ")" }
concat = { "concat(" ~ expr ~ "," ~ expr ~ ")" }
hexstring = { "hexstring(" ~ expr ~ "," ~ string ~ ")" }
ifelse = { "ifelse(" ~ expr ~ "," ~ expr ~ "," ~ expr ~ ")" }
Expand All @@ -92,7 +79,24 @@ postfix = _{ to_hex | to_text | exists | sub_opt }
exists = { ".exists" }
sub_opt = { "." ~ option }

primary = _{ hex | ip | integer | string | boolean | option | relay | pkt | pkt_base | substring | concat | ifelse | hexstring | member | "(" ~ expr ~ ")" }
primary = _{ hex
| ip
| integer
| string
| boolean
| option
| relay
| pkt
| pkt_base
| substring
| concat
| split
| ifelse
| hexstring
| member
| "(" ~ expr ~ ")"
}

predicate = _{ SOI ~ expr ~ EOI }

WHITESPACE = _{ " " | "\t" | "\r" | "\n" }
85 changes: 85 additions & 0 deletions libs/client-classification/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,12 @@ pub fn eval(expr: &Expr, args: &Args) -> Result<Val, EvalErr> {
}
(a, _b) => return Err(EvalErr::ExpectedString(a)),
},
E::Split(lhs, del, n) => match (eval(lhs, args)?, eval(del, args)?) {
(Val::String(a), Val::String(del)) => split(a, &del, *n),
(Val::String(a), Val::Bytes(b)) => split(a, str::from_utf8(&b)?, *n),
// TODO: split() handling bytes?
(a, _b) => return Err(EvalErr::ExpectedString(a)),
},
E::IfElse(expr, a, b) => {
if is_bool(eval(expr, args)?)? {
eval(a, args)?
Expand All @@ -293,6 +299,16 @@ pub fn eval(expr: &Expr, args: &Args) -> Result<Val, EvalErr> {
})
}

// expects `n` to start at 1
fn split(a: String, del: &str, n: usize) -> Val {
Val::String(
a.split(del)
.nth(n - 1)
.map(ToString::to_string)
.unwrap_or(String::new()),
)
}

fn substring(s: &str, start: isize, j: Option<isize>) -> String {
match get_pos(s.len(), start, j) {
None => String::default(),
Expand Down Expand Up @@ -831,6 +847,75 @@ mod tests {
assert_eq!(substring("foobar", 0, Some(10)), "foobar");
}

#[test]
fn test_split() {
// from kea docs:
// split ('one.two..four', '.', 1) == 'one'
// split ('one.two..four', '.', 2) == 'two'
// split ('one.two..four', '.', 3) == ''
// split ('one.two..four', '.', 4) == 'four'
// split ('one.two..four', '.', 5) == ''
//
assert_eq!(
split("one.two..four".to_string(), ".", 1),
Val::String("one".to_string())
);
assert_eq!(
split("one.two..four".to_string(), ".", 2),
Val::String("two".to_string())
);
assert_eq!(
split("one.two..four".to_string(), ".", 3),
Val::String("".to_string())
);
assert_eq!(
split("one.two..four".to_string(), ".", 4),
Val::String("four".to_string())
);
assert_eq!(
split("one.two..four".to_string(), ".", 5),
Val::String("".to_string())
);
}

#[test]
fn test_split_expr() {
let args = Args {
chaddr: &hex::decode("DEADBEEF").unwrap(),
opts: HashMap::new(),
msg: &v4::Message::default(),
member: HashSet::new(),
pkt: PacketDetails::default(),
};

assert_eq!(
eval(
&ast::parse("split('one.two..four', '.', 1) == 'one'").unwrap(),
&args,
)
.unwrap(),
Val::Bool(true)
);

assert_eq!(
eval(
&ast::parse("split('one.two..four', '.', 2) == 'two'").unwrap(),
&args,
)
.unwrap(),
Val::Bool(true)
);

assert_eq!(
eval(
&ast::parse("split('one.two..four', '.', 3) == ''").unwrap(),
&args,
)
.unwrap(),
Val::Bool(true)
);
}

#[test]
fn test_concat() {
let args = Args {
Expand Down
Loading