mod literals;
#[cfg(test)]
mod tests;
use std::borrow::Cow;
use std::fmt;
use serde::Deserialize;
use thiserror::Error;
use crate::MatcherTier;
use crate::strmatch::{
BuildError, Captures, MAX_ALL_OF, ReplaceSyntax, Replacement, Signature, SignatureError,
SignatureScratch, SignatureSet, StrMatcher,
};
use literals::Required;
#[derive(Debug, Clone, Default, Deserialize)]
pub struct Rules {
#[serde(default)]
pub user_agent_parsers: Vec<UserAgentRule>,
#[serde(default)]
pub os_parsers: Vec<OsRule>,
#[serde(default)]
pub device_parsers: Vec<DeviceRule>,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct UserAgentRule {
pub regex: String,
pub family_replacement: Option<String>,
pub v1_replacement: Option<String>,
pub v2_replacement: Option<String>,
pub v3_replacement: Option<String>,
pub v4_replacement: Option<String>,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct OsRule {
pub regex: String,
pub os_replacement: Option<String>,
pub os_v1_replacement: Option<String>,
pub os_v2_replacement: Option<String>,
pub os_v3_replacement: Option<String>,
pub os_v4_replacement: Option<String>,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct DeviceRule {
pub regex: String,
pub regex_flag: Option<RegexFlag>,
pub device_replacement: Option<String>,
pub brand_replacement: Option<String>,
pub model_replacement: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub enum RegexFlag {
#[serde(rename = "i")]
IgnoreCase,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Domain {
UserAgent,
Os,
Device,
}
impl Domain {
pub const ALL: [Self; 3] = [Self::UserAgent, Self::Os, Self::Device];
const fn atom_len(self) -> usize {
match self {
Self::Device => 2,
Self::UserAgent | Self::Os => 3,
}
}
}
impl fmt::Display for Domain {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::UserAgent => "user agent",
Self::Os => "os",
Self::Device => "device",
})
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum UaError {
#[error("ua: {domain} rule {index}: {source}")]
Pattern {
domain: Domain,
index: usize,
#[source]
source: Box<BuildError>,
},
#[error("ua: user agent rule {index}: family_replacement names $1 and the regex has no group")]
MissingGroup {
index: usize,
},
#[error("ua: {domain} rules: {source}")]
Signatures {
domain: Domain,
#[source]
source: SignatureError,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UserAgent<'a> {
pub family: Cow<'a, str>,
pub major: Option<&'a str>,
pub minor: Option<&'a str>,
pub patch: Option<&'a str>,
pub patch_minor: Option<&'a str>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Os<'a> {
pub family: Cow<'a, str>,
pub major: Option<Cow<'a, str>>,
pub minor: Option<Cow<'a, str>>,
pub patch: Option<Cow<'a, str>>,
pub patch_minor: Option<Cow<'a, str>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Device<'a> {
pub family: Cow<'a, str>,
pub brand: Option<Cow<'a, str>>,
pub model: Option<Cow<'a, str>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Client<'a> {
pub user_agent: Option<UserAgent<'a>>,
pub os: Option<Os<'a>>,
pub device: Option<Device<'a>>,
}
#[derive(Debug, Clone)]
enum Field {
None,
Text(Box<str>),
Group(usize),
Family(Box<str>),
Template(Replacement),
}
fn has_group_ref(s: &str) -> bool {
s.as_bytes()
.windows(2)
.any(|w| w[0] == b'$' && w[1].is_ascii_digit())
}
fn templated(m: &StrMatcher, repl: Option<&str>, groups: usize, index: usize) -> Field {
match repl.filter(|s| !s.trim().is_empty()) {
Some(s) if has_group_ref(s) => Field::Template(m.replacement(s, ReplaceSyntax::Rust)),
Some(s) => Field::Text(s.into()),
None if groups >= index => Field::Group(index),
None => Field::None,
}
}
fn version(repl: Option<&str>, groups: usize, index: usize) -> Field {
match repl.filter(|s| !s.is_empty()) {
Some(s) => Field::Text(s.into()),
None if groups >= index => Field::Group(index),
None => Field::None,
}
}
#[derive(Debug)]
struct Rule {
matcher: StrMatcher,
fields: [Field; 5],
}
#[derive(Debug)]
struct Table {
rules: Vec<Rule>,
set: SignatureSet,
owner: Vec<u32>,
always: Vec<u32>,
}
struct Source<'r> {
regex: &'r str,
folded: bool,
repl: [Option<&'r str>; 5],
}
fn index_u32(i: usize, domain: Domain) -> Result<u32, UaError> {
u32::try_from(i).map_err(|_| UaError::Signatures {
domain,
source: SignatureError::TooMany {
max: u32::MAX as usize,
},
})
}
impl Table {
fn build<'r>(
domain: Domain,
sources: impl Iterator<Item = Source<'r>>,
) -> Result<Self, UaError> {
let mut rules = Vec::new();
let mut sigs = Vec::new();
let mut owner = Vec::new();
let mut always = Vec::new();
for (index, src) in sources.enumerate() {
let rule = index_u32(index, domain)?;
let pattern = literals::rewrite(src.regex);
let matcher = StrMatcher::builder()
.ascii_case_insensitive(src.folded)
.build(&pattern)
.map_err(|e| UaError::Pattern {
domain,
index,
source: Box::new(e),
})?;
let groups = matcher.group_len() - 1;
let fields = Self::fields(domain, &matcher, &src.repl, groups)
.ok_or(UaError::MissingGroup { index })?;
let required = regex_syntax::parse(&pattern).map_or(Required::Nothing, |hir| {
literals::required(&hir, domain.atom_len())
});
let mut push = |all_of: &[Vec<u8>], any_of: &[Vec<u8>]| -> Result<(), UaError> {
let mut all_of: Vec<&Vec<u8>> = all_of.iter().collect();
all_of.sort_by_key(|l| std::cmp::Reverse(l.len()));
all_of.truncate(MAX_ALL_OF);
let sig = Signature::builder()
.all_of(all_of)
.any_of(any_of)
.ascii_case_insensitive(src.folded)
.build()
.map_err(|source| UaError::Signatures { domain, source })?;
sigs.push(sig);
owner.push(rule);
Ok(())
};
match required {
Required::Nothing => always.push(rule),
Required::Clauses(clauses) => {
for c in &clauses {
push(c, &[])?;
}
}
Required::Flat { all_of, any_of } => push(&all_of, &any_of)?,
}
rules.push(Rule { matcher, fields });
}
let set =
SignatureSet::new(&sigs).map_err(|source| UaError::Signatures { domain, source })?;
Ok(Self {
rules,
set,
owner,
always,
})
}
fn fields(
domain: Domain,
m: &StrMatcher,
repl: &[Option<&str>; 5],
groups: usize,
) -> Option<[Field; 5]> {
Some(match domain {
Domain::UserAgent => {
let family = match repl[0] {
Some(s) if s.contains("$1") => {
if groups < 1 {
return None;
}
Field::Family(s.into())
}
Some(s) if !s.is_empty() => Field::Text(s.into()),
_ if groups >= 1 => Field::Group(1),
_ => Field::None,
};
[
family,
version(repl[1], groups, 2),
version(repl[2], groups, 3),
version(repl[3], groups, 4),
version(repl[4], groups, 5),
]
}
Domain::Os => [
templated(m, repl[0], groups, 1),
templated(m, repl[1], groups, 2),
templated(m, repl[2], groups, 3),
templated(m, repl[3], groups, 4),
templated(m, repl[4], groups, 5),
],
Domain::Device => [
templated(m, repl[0], groups, 1),
templated(m, repl[1], 0, 1),
templated(m, repl[2], groups, 1),
Field::None,
Field::None,
],
})
}
fn scratch(&self) -> TableScratch {
TableScratch {
sigs: self.set.scratch(),
candidates: Vec::with_capacity(self.rules.len().min(64)),
caps: self
.rules
.iter()
.map(|r| r.matcher.create_captures())
.collect(),
}
}
fn candidates(&self, hay: &[u8], s: &mut TableScratch) {
let out = &mut s.candidates;
out.clear();
self.set.for_each_match(hay, &mut s.sigs, |m| {
let rule = self.owner[m.index];
if out.last() != Some(&rule) {
out.push(rule);
}
});
if !self.always.is_empty() {
out.extend_from_slice(&self.always);
out.sort_unstable();
}
}
fn first(&self, hay: &[u8], s: &mut TableScratch) -> Option<usize> {
if s.caps.len() != self.rules.len() {
*s = self.scratch();
}
self.candidates(hay, s);
s.candidates
.iter()
.map(|&r| r as usize)
.find(|&r| self.rules[r].matcher.captures_into(hay, &mut s.caps[r]))
}
}
fn group<'a>(ua: &'a str, caps: &Captures, index: usize) -> Option<&'a str> {
caps.get(index)
.and_then(|m| ua.get(m.start..m.end))
.filter(|s| !s.is_empty())
}
fn resolve<'a>(
field: &'a Field,
ua: &'a str,
caps: &Captures,
buf: &mut Vec<u8>,
) -> Option<Cow<'a, str>> {
match field {
Field::None => None,
Field::Text(s) => Some(Cow::Borrowed(s)),
Field::Group(i) => group(ua, caps, *i).map(Cow::Borrowed),
Field::Family(t) => Some(Cow::Owned(
t.replace("$1", group(ua, caps, 1).unwrap_or("")),
)),
Field::Template(rep) => {
buf.clear();
caps.expand(ua.as_bytes(), rep, buf);
let text = String::from_utf8_lossy(buf);
let trimmed = text.trim();
(!trimmed.is_empty()).then(|| Cow::Owned(trimmed.to_owned()))
}
}
}
fn borrowed<'a>(field: &'a Field, ua: &'a str, caps: &Captures) -> Option<&'a str> {
match field {
Field::Text(s) => Some(s),
Field::Group(i) => group(ua, caps, *i),
Field::None | Field::Family(_) | Field::Template(_) => None,
}
}
#[derive(Debug, Clone)]
struct TableScratch {
sigs: SignatureScratch,
candidates: Vec<u32>,
caps: Vec<Captures>,
}
#[derive(Debug, Clone)]
pub struct UaScratch {
tables: [TableScratch; 3],
buf: Vec<u8>,
}
#[derive(Debug)]
pub struct UaParser {
tables: [Table; 3],
}
impl UaParser {
pub fn new(rules: &Rules) -> Result<Self, UaError> {
let user_agent = Table::build(
Domain::UserAgent,
rules.user_agent_parsers.iter().map(|r| Source {
regex: &r.regex,
folded: false,
repl: [
r.family_replacement.as_deref(),
r.v1_replacement.as_deref(),
r.v2_replacement.as_deref(),
r.v3_replacement.as_deref(),
r.v4_replacement.as_deref(),
],
}),
)?;
let os = Table::build(
Domain::Os,
rules.os_parsers.iter().map(|r| Source {
regex: &r.regex,
folded: false,
repl: [
r.os_replacement.as_deref(),
r.os_v1_replacement.as_deref(),
r.os_v2_replacement.as_deref(),
r.os_v3_replacement.as_deref(),
r.os_v4_replacement.as_deref(),
],
}),
)?;
let device = Table::build(
Domain::Device,
rules.device_parsers.iter().map(|r| Source {
regex: &r.regex,
folded: r.regex_flag == Some(RegexFlag::IgnoreCase),
repl: [
r.device_replacement.as_deref(),
r.brand_replacement.as_deref(),
r.model_replacement.as_deref(),
None,
None,
],
}),
)?;
Ok(Self {
tables: [user_agent, os, device],
})
}
#[must_use]
pub fn scratch(&self) -> UaScratch {
UaScratch {
tables: self.tables.each_ref().map(Table::scratch),
buf: Vec::new(),
}
}
#[must_use]
pub fn tier_counts(&self, domain: Domain) -> [usize; MatcherTier::ALL.len()] {
let mut counts = [0_usize; MatcherTier::ALL.len()];
for r in &self.table(domain).rules {
counts[r.matcher.tier().index()] += 1;
}
counts
}
const fn table(&self, domain: Domain) -> &Table {
match domain {
Domain::UserAgent => &self.tables[0],
Domain::Os => &self.tables[1],
Domain::Device => &self.tables[2],
}
}
fn lookup<'s>(
&self,
domain: Domain,
ua: &str,
scratch: &'s mut UaScratch,
) -> Option<(&[Field; 5], &'s Captures, &'s mut Vec<u8>)> {
let table = self.table(domain);
let s = &mut scratch.tables[domain as usize];
let rule = table.first(ua.as_bytes(), s)?;
Some((&table.rules[rule].fields, &s.caps[rule], &mut scratch.buf))
}
#[must_use]
pub fn user_agent<'a>(&'a self, ua: &'a str, scratch: &mut UaScratch) -> Option<UserAgent<'a>> {
let (f, caps, buf) = self.lookup(Domain::UserAgent, ua, scratch)?;
Some(UserAgent {
family: resolve(&f[0], ua, caps, buf).unwrap_or(Cow::Borrowed("")),
major: borrowed(&f[1], ua, caps),
minor: borrowed(&f[2], ua, caps),
patch: borrowed(&f[3], ua, caps),
patch_minor: borrowed(&f[4], ua, caps),
})
}
#[must_use]
pub fn os<'a>(&'a self, ua: &'a str, scratch: &mut UaScratch) -> Option<Os<'a>> {
let (f, caps, buf) = self.lookup(Domain::Os, ua, scratch)?;
Some(Os {
family: resolve(&f[0], ua, caps, buf).unwrap_or(Cow::Borrowed("")),
major: resolve(&f[1], ua, caps, buf),
minor: resolve(&f[2], ua, caps, buf),
patch: resolve(&f[3], ua, caps, buf),
patch_minor: resolve(&f[4], ua, caps, buf),
})
}
#[must_use]
pub fn device<'a>(&'a self, ua: &'a str, scratch: &mut UaScratch) -> Option<Device<'a>> {
let (f, caps, buf) = self.lookup(Domain::Device, ua, scratch)?;
Some(Device {
family: resolve(&f[0], ua, caps, buf).unwrap_or(Cow::Borrowed("")),
brand: resolve(&f[1], ua, caps, buf),
model: resolve(&f[2], ua, caps, buf),
})
}
#[must_use]
pub fn parse<'a>(&'a self, ua: &'a str, scratch: &mut UaScratch) -> Client<'a> {
Client {
user_agent: self.user_agent(ua, scratch),
os: self.os(ua, scratch),
device: self.device(ua, scratch),
}
}
}