use std::collections::{BTreeSet, HashSet};
use std::fmt;
use std::str::FromStr;
use crate::dialplan::Destination;
use crate::digits::DigitString;
use crate::error::ParseError;
use crate::identity::{Imeisv, Imsi, Msisdn, Pei, Supi, Tac};
use crate::plmn::{Mcc, MncWidths, PlmnId};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Pseudonym([u8; 32]);
impl Pseudonym {
#[must_use]
pub const fn from_digest(digest: [u8; 32]) -> Self {
Self(digest)
}
#[must_use]
pub const fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
}
impl fmt::Display for Pseudonym {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for byte in &self.0 {
write!(f, "{byte:02x}")?;
}
Ok(())
}
}
impl FromStr for Pseudonym {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let err = || ParseError::withheld("Pseudonym", "64 lower-case hex characters");
let bytes = s.as_bytes();
if bytes.len() != 64 {
return Err(err());
}
let nibble = |b: u8| match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
_ => None,
};
let mut digest = [0u8; 32];
for (slot, pair) in digest.iter_mut().zip(bytes.as_chunks::<2>().0) {
*slot = (nibble(pair[0]).ok_or_else(err)? << 4) | nibble(pair[1]).ok_or_else(err)?;
}
Ok(Self(digest))
}
}
pub trait Pseudonymiser {
fn digest(&self, input: &[u8]) -> [u8; 32];
fn pseudonymise(&self, identity: &impl fmt::Display) -> Pseudonym {
Pseudonym::from_digest(self.digest(identity.to_string().as_bytes()))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Reduction {
CountryOnly,
NetworkOnly,
ModelOnly,
}
impl Reduction {
pub const ALL: &'static [Self] = &[Self::CountryOnly, Self::NetworkOnly, Self::ModelOnly];
pub const CODES: &'static [&'static str] = &["COUNTRY_ONLY", "NETWORK_ONLY", "MODEL_ONLY"];
#[must_use]
pub const fn applies_to_subscription(self) -> bool {
matches!(self, Self::CountryOnly | Self::NetworkOnly)
}
#[must_use]
pub const fn needs_assignment_table(self) -> bool {
matches!(self, Self::NetworkOnly)
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::CountryOnly => "COUNTRY_ONLY",
Self::NetworkOnly => "NETWORK_ONLY",
Self::ModelOnly => "MODEL_ONLY",
}
}
}
impl std::str::FromStr for Reduction {
type Err = crate::error::ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::ALL
.iter()
.find(|r| r.as_str().eq_ignore_ascii_case(s.trim()))
.copied()
.ok_or_else(|| crate::error::ParseError::one_of("Reduction", s, Self::CODES))
}
}
impl fmt::Display for Reduction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NumberPrefix {
digits: crate::digits::DigitString,
}
impl NumberPrefix {
#[must_use]
pub fn of(msisdn: Msisdn, keep: usize) -> Option<Self> {
if keep == 0 || keep >= msisdn.len() {
return None;
}
Some(Self {
digits: msisdn.digits().slice(0, keep),
})
}
#[must_use]
pub fn without_last(msisdn: Msisdn, hide: usize) -> Option<Self> {
let keep = msisdn.len().checked_sub(hide)?;
if hide == 0 {
return None;
}
Self::of(msisdn, keep)
}
#[must_use]
pub fn len(&self) -> usize {
self.digits.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
false
}
}
impl fmt::Display for NumberPrefix {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.digits.fmt(f)
}
}
impl FromStr for NumberPrefix {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let err = || ParseError::withheld("NumberPrefix", "1 to 14 decimal digits");
if s.is_empty() || s.len() >= Msisdn::MAX_DIGITS || !s.bytes().all(|b| b.is_ascii_digit()) {
return Err(err());
}
let digits = DigitString::parse(s, Msisdn::MAX_DIGITS - 1).ok_or_else(err)?;
Ok(Self { digits })
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Itemisation {
Full,
Shortened,
}
impl Itemisation {
pub const ALL: &'static [Self] = &[Self::Full, Self::Shortened];
pub const CODES: &'static [&'static str] = &["FULL", "SHORTENED"];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Full => "FULL",
Self::Shortened => "SHORTENED",
}
}
}
impl fmt::Display for Itemisation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for Itemisation {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::ALL
.iter()
.find(|i| i.as_str().eq_ignore_ascii_case(s.trim()))
.copied()
.ok_or_else(|| ParseError::one_of("Itemisation", s, Self::CODES))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ShortenedNumber {
visible: DigitString,
international: bool,
}
impl ShortenedNumber {
pub const HIDDEN: usize = 3;
fn of(digits: DigitString, international: bool) -> Self {
let keep = digits.len().saturating_sub(Self::HIDDEN);
Self {
visible: digits.prefix(keep),
international: international && keep > 0,
}
}
#[must_use]
pub const fn visible(&self) -> DigitString {
self.visible
}
}
impl fmt::Display for ShortenedNumber {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.international {
f.write_str("+")?;
}
write!(f, "{}xxx", self.visible)
}
}
impl FromStr for ShortenedNumber {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let err = || {
ParseError::withheld(
"ShortenedNumber",
"digits followed by xxx, such as +4930123xxx",
)
};
let t = s.trim();
let body = t.strip_suffix("xxx").ok_or_else(err)?;
let (international, body) = match body.strip_prefix('+') {
Some(rest) if !rest.is_empty() => (true, rest),
Some(_) => return Err(err()),
None => (false, body),
};
if body.starts_with(['-', ' ']) {
return Err(err());
}
let visible = DigitString::parse(body, Msisdn::MAX_DIGITS).ok_or_else(err)?;
if body.len() != visible.len() {
return Err(err());
}
Ok(Self {
visible,
international,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ItemisedDestination {
Full(Destination),
Shortened(ShortenedNumber),
Omitted,
}
pub trait ProtectedDestinations {
fn is_protected(&self, destination: &Destination) -> bool;
}
impl ProtectedDestinations for [Destination] {
fn is_protected(&self, destination: &Destination) -> bool {
self.contains(destination)
}
}
impl<const N: usize> ProtectedDestinations for [Destination; N] {
fn is_protected(&self, destination: &Destination) -> bool {
self.contains(destination)
}
}
impl ProtectedDestinations for Vec<Destination> {
fn is_protected(&self, destination: &Destination) -> bool {
self.contains(destination)
}
}
impl ProtectedDestinations for BTreeSet<Destination> {
fn is_protected(&self, destination: &Destination) -> bool {
self.contains(destination)
}
}
impl<S: std::hash::BuildHasher> ProtectedDestinations for HashSet<Destination, S> {
fn is_protected(&self, destination: &Destination) -> bool {
self.contains(destination)
}
}
#[must_use]
pub fn itemise_called(
destination: &Destination,
choice: Itemisation,
protected: &(impl ProtectedDestinations + ?Sized),
) -> ItemisedDestination {
if protected.is_protected(destination) {
return ItemisedDestination::Omitted;
}
match choice {
Itemisation::Full => ItemisedDestination::Full(*destination),
Itemisation::Shortened => ItemisedDestination::Shortened(ShortenedNumber::of(
destination.digits(),
destination.as_number().is_some(),
)),
}
}
#[must_use]
pub fn itemise_calling(calling: Msisdn) -> ShortenedNumber {
ShortenedNumber::of(calling.digits(), true)
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ReducedSubscriber {
pub supi: Pseudonym,
pub country: Option<Mcc>,
pub network: Option<PlmnId>,
}
impl ReducedSubscriber {
#[must_use]
pub fn of(supi: &Supi, pseudonymiser: &impl Pseudonymiser, widths: &impl MncWidths) -> Self {
let imsi = supi.as_imsi();
Self {
supi: pseudonymiser.pseudonymise(supi),
country: imsi.map(Imsi::mcc),
network: imsi.and_then(|i| i.plmn(widths)),
}
}
}
impl fmt::Display for ReducedSubscriber {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.supi)?;
if let Some(network) = self.network {
write!(f, " @{network}")?;
} else if let Some(country) = self.country {
write!(f, " @{country}")?;
}
Ok(())
}
}
#[must_use]
pub const fn reduce_to_country(imsi: Imsi) -> Mcc {
imsi.mcc()
}
#[must_use]
pub fn reduce_to_network(imsi: Imsi, widths: &impl MncWidths) -> Option<PlmnId> {
imsi.plmn(widths)
}
#[must_use]
pub fn reduce_equipment(pei: Pei) -> Tac {
pei.tac()
}
#[must_use]
pub fn software_version(pei: Pei) -> Option<crate::identity::SoftwareVersion> {
match pei {
Pei::Imeisv(sv) => Some(Imeisv::software_version(sv)),
Pei::Imei(_) => None,
}
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::{
Itemisation, NumberPrefix, Pseudonym, ReducedSubscriber, Reduction, ShortenedNumber,
};
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
impl Serialize for Pseudonym {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for Pseudonym {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct V;
impl Visitor<'_> for V {
type Value = Pseudonym;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("64 lower-case hex characters")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Pseudonym, E> {
v.parse().map_err(de::Error::custom)
}
}
deserializer.deserialize_str(V)
}
}
impl Serialize for Reduction {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for Reduction {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct V;
impl Visitor<'_> for V {
type Value = Reduction;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a reduction code such as \"COUNTRY_ONLY\"")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Reduction, E> {
Reduction::ALL
.iter()
.find(|r| r.as_str() == v)
.copied()
.ok_or_else(|| de::Error::custom(format!("unknown reduction {v:?}")))
}
}
deserializer.deserialize_str(V)
}
}
impl Serialize for Itemisation {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for Itemisation {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct V;
impl Visitor<'_> for V {
type Value = Itemisation;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("an itemisation code such as \"SHORTENED\"")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Itemisation, E> {
v.parse().map_err(de::Error::custom)
}
}
deserializer.deserialize_str(V)
}
}
impl Serialize for ShortenedNumber {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for ShortenedNumber {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct V;
impl Visitor<'_> for V {
type Value = ShortenedNumber;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a shortened number such as \"+4930123xxx\"")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<ShortenedNumber, E> {
v.parse().map_err(de::Error::custom)
}
}
deserializer.deserialize_str(V)
}
}
impl Serialize for NumberPrefix {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for NumberPrefix {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct V;
impl Visitor<'_> for V {
type Value = NumberPrefix;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a number prefix such as \"49170\"")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<NumberPrefix, E> {
v.parse().map_err(de::Error::custom)
}
}
deserializer.deserialize_str(V)
}
}
#[derive(Serialize, Deserialize)]
#[serde(rename = "ReducedSubscriber")]
struct Repr {
supi: Pseudonym,
#[serde(default, skip_serializing_if = "Option::is_none")]
country: Option<crate::plmn::Mcc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
network: Option<crate::plmn::PlmnId>,
}
impl Serialize for ReducedSubscriber {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
Repr {
supi: self.supi,
country: self.country,
network: self.network,
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ReducedSubscriber {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let r = Repr::deserialize(deserializer)?;
Ok(ReducedSubscriber {
supi: r.supi,
country: r.country,
network: r.network,
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::plmn::NorthAmericanRule;
struct TestKey(u8);
impl Pseudonymiser for TestKey {
fn digest(&self, input: &[u8]) -> [u8; 32] {
let mut out = [self.0; 32];
for (index, byte) in input.iter().enumerate() {
out[index % 32] ^= byte.rotate_left((index % 8) as u32);
}
out
}
}
#[test]
fn a_pseudonym_is_stable_per_identity_and_per_key() {
let supi: Supi = "imsi-262021234567890".parse().unwrap();
let other: Supi = "imsi-262021234567891".parse().unwrap();
let key = TestKey(1);
assert_eq!(key.pseudonymise(&supi), key.pseudonymise(&supi));
assert_ne!(key.pseudonymise(&supi), key.pseudonymise(&other));
assert_ne!(key.pseudonymise(&supi), TestKey(2).pseudonymise(&supi));
}
#[test]
fn spelling_does_not_change_a_pseudonym() {
let key = TestKey(1);
let imsi: Imsi = "262021234567890".parse().unwrap();
let spaced: Imsi = "262 021 234 567 890".parse().unwrap();
assert_eq!(key.pseudonymise(&imsi), key.pseudonymise(&spaced));
}
#[test]
fn a_pseudonym_renders_and_parses_as_hex() {
let key = TestKey(7);
let supi: Supi = "imsi-262021234567890".parse().unwrap();
let rendered = key.pseudonymise(&supi).to_string();
assert_eq!(rendered.len(), 64);
assert!(rendered.chars().all(|c| c.is_ascii_hexdigit()));
}
#[test]
fn a_reduction_discards_rather_than_obscures() {
let imsi: Imsi = "262021234567890".parse().unwrap();
let country = reduce_to_country(imsi);
assert_eq!(country.to_string(), "262");
let other: Imsi = "262029999999999".parse().unwrap();
assert_eq!(reduce_to_country(other), country);
}
#[test]
fn a_network_reduction_needs_the_same_table_as_everything_else() {
let imsi: Imsi = "262021234567890".parse().unwrap();
assert_eq!(
reduce_to_network(imsi, &NorthAmericanRule)
.unwrap()
.to_string(),
"262-02"
);
let unknown = |_: Mcc| None;
assert_eq!(
reduce_to_network(imsi, &unknown),
None,
"an unresolvable network is not guessed"
);
}
#[test]
fn equipment_reduces_to_a_model_from_either_form() {
let imei: Pei = "imei-490154203237518".parse().unwrap();
let imeisv: Pei = "imeisv-4901542032375120".parse().unwrap();
assert_eq!(reduce_equipment(imei).to_string(), "49015420");
assert_eq!(reduce_equipment(imei), reduce_equipment(imeisv));
assert_eq!(reduce_equipment(imei), reduce_equipment(imei));
}
#[test]
fn a_software_version_is_separable_from_the_device() {
let imeisv: Pei = "imeisv-4901542032375120".parse().unwrap();
assert_eq!(software_version(imeisv).unwrap().to_string(), "20");
let imei: Pei = "imei-490154203237518".parse().unwrap();
assert_eq!(software_version(imei), None, "an IMEI carries none");
}
#[test]
fn a_prefix_must_actually_be_shorter() {
let msisdn: Msisdn = "491701234567".parse().unwrap();
assert_eq!(NumberPrefix::of(msisdn, 2).unwrap().to_string(), "49");
assert_eq!(NumberPrefix::of(msisdn, 2).unwrap().len(), 2);
assert_eq!(NumberPrefix::of(msisdn, 0), None, "nothing is not a prefix");
assert_eq!(
NumberPrefix::of(msisdn, msisdn.len()),
None,
"the whole number is not a reduction"
);
assert_eq!(NumberPrefix::of(msisdn, 99), None);
}
#[test]
fn a_reduced_subscriber_keeps_the_dimensions_and_loses_the_identity() {
let supi: Supi = "imsi-262021234567890".parse().unwrap();
let reduced = ReducedSubscriber::of(&supi, &TestKey(1), &NorthAmericanRule);
assert_eq!(reduced.country, Some(Mcc::GERMANY));
assert_eq!(reduced.network.unwrap().to_string(), "262-02");
assert!(reduced.to_string().ends_with("@262-02"));
let other: Supi = "imsi-262029999999999".parse().unwrap();
let other = ReducedSubscriber::of(&other, &TestKey(1), &NorthAmericanRule);
assert_eq!(reduced.network, other.network);
assert_ne!(reduced.supi, other.supi);
}
#[test]
fn a_network_specific_identity_yields_no_dimensions() {
let supi: Supi = "nai-device-42@iot.example.org".parse().unwrap();
let reduced = ReducedSubscriber::of(&supi, &TestKey(1), &NorthAmericanRule);
assert_eq!(reduced.country, None);
assert_eq!(reduced.network, None);
assert_eq!(reduced.to_string(), reduced.supi.to_string());
}
#[test]
fn reduction_codes_round_trip() {
for reduction in Reduction::ALL {
assert_eq!(reduction.to_string(), reduction.as_str());
}
assert_eq!(Reduction::ALL.len(), 3);
}
}