use std::borrow::Cow;
use php_std::string::strtolower;
use php_std::url::Component as UrlComponent;
use crate::network::{self, IpType};
use crate::object::input::loose_str_eq;
use crate::object::{Error, Input, Type, Validator, Verdict, is_valid_via_validate, scalar};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Restriction {
pub hostname: String,
pub levels: Option<i64>,
pub prefix_deny_list: Vec<String>,
}
impl Restriction {
pub fn new(hostname: impl Into<String>, levels: Option<i64>, prefix_deny_list: Vec<String>) -> Self {
Self { hostname: hostname.into(), levels, prefix_deny_list }
}
fn allows(&self, domain: &[u8]) -> Result<bool, Error> {
if !domain.ends_with(self.hostname.as_bytes()) {
return Ok(true);
}
if let Some(levels) = self.levels {
let limit = levels.checked_add(1).ok_or_else(|| {
Error::Type("explode(): Argument #3 ($limit) must be of type int, float given".into())
})?;
if network::explode_count(domain, limit) != levels {
return Ok(false);
}
}
Ok(!self.prefix_deny_list.iter().any(|p| domain.starts_with(p.as_bytes())))
}
}
#[derive(Debug, Clone)]
pub struct Domain {
pub restrictions: Vec<Restriction>,
pub hostnames: bool,
pub allow_empty: bool,
}
impl Default for Domain {
fn default() -> Self {
Self { restrictions: Vec::new(), hostnames: true, allow_empty: false }
}
}
impl Validator for Domain {
fn description(&self) -> String {
network::DOMAIN_DESCRIPTION.to_owned()
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
if self.allow_empty && value.as_str() == Some(b"") {
return Ok(Verdict::VALID);
}
let Some(domain) = value.as_str().filter(|_| value.truthy()) else {
return Ok(Verdict::INVALID);
};
if !network::domain(domain, self.hostnames) {
return Ok(Verdict::INVALID);
}
for restriction in &self.restrictions {
if !restriction.allows(domain)? {
return Ok(Verdict::INVALID);
}
}
Ok(Verdict::VALID)
}
fn kind(&self) -> Type {
Type::String
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IpVersion {
#[default]
All,
V4,
V6,
}
impl IpVersion {
pub const fn as_str(self) -> &'static str {
match self {
IpVersion::All => "all",
IpVersion::V4 => "ipv4",
IpVersion::V6 => "ipv6",
}
}
pub fn from_php(value: &str) -> Result<Self, Error> {
match value {
"all" => Ok(IpVersion::All),
"ipv4" => Ok(IpVersion::V4),
"ipv6" => Ok(IpVersion::V6),
_ => Err(Error::Exception("Unsupported IP type".into())),
}
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Ip {
pub version: IpVersion,
}
impl Ip {
pub const fn new(version: IpVersion) -> Self {
Self { version }
}
}
impl Validator for Ip {
fn description(&self) -> String {
network::IP_DESCRIPTION.to_owned()
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
let kind = match self.version {
IpVersion::All => IpType::All,
IpVersion::V4 => IpType::V4,
IpVersion::V6 => IpType::V6,
};
Ok(Verdict::of(match value.as_str() {
Some(s) => network::ip_str(s, kind),
None => network::ip(&value.filter_value(), kind),
}))
}
fn kind(&self) -> Type {
Type::String
}
}
#[derive(Debug, Clone)]
pub struct Url {
pub allowed_schemes: Vec<String>,
pub allow_empty: bool,
pub allow_fragments: bool,
pub allow_private_use_schemes: bool,
pub https_or_loopback: bool,
}
impl Default for Url {
fn default() -> Self {
Self {
allowed_schemes: Vec::new(),
allow_empty: false,
allow_fragments: true,
allow_private_use_schemes: false,
https_or_loopback: false,
}
}
}
enum Component {
False,
Null,
Value(Vec<u8>),
}
impl Component {
fn of(url: &[u8], component: UrlComponent) -> Self {
match network::url_component(url, component) {
None => Component::False,
Some(None) => Component::Null,
Some(Some(value)) => Component::Value(value),
}
}
fn bytes(&self) -> &[u8] {
match self {
Component::Value(v) => v,
_ => b"",
}
}
}
impl Url {
fn scheme_allowed(&self, scheme: &Component) -> bool {
self.allowed_schemes.iter().any(|allowed| match scheme {
Component::False => allowed.is_empty() || allowed == "0",
Component::Null => allowed.is_empty(),
Component::Value(s) => loose_str_eq(s, allowed.as_bytes()),
})
}
}
impl Validator for Url {
fn description(&self) -> String {
let schemes = (!self.allowed_schemes.is_empty()).then(|| self.allowed_schemes.join(", "));
let mut description = Vec::new();
network::url_description(
schemes.as_deref().map(str::as_bytes),
self.allow_fragments,
self.https_or_loopback,
&mut description,
);
String::from_utf8_lossy(&description).into_owned()
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
if self.allow_empty && value.as_str() == Some(b"") {
return Ok(Verdict::VALID);
}
let private = self.allow_private_use_schemes && value.as_str().is_some_and(network::private_use_scheme);
let url = match value.as_str() {
Some(s) => network::url_str(&network::url_ascii(s)),
None => network::url(&value.filter_value()),
};
if !private && !url {
return Ok(Verdict::INVALID);
}
let transport = self.https_or_loopback && !private;
if self.allowed_schemes.is_empty() && self.allow_fragments && !transport {
return Ok(Verdict::VALID);
}
let url: Cow<'_, [u8]> = value.to_bytes()?;
let component = |component| Component::of(&url, component);
if !self.allowed_schemes.is_empty() && !self.scheme_allowed(&component(UrlComponent::Scheme)) {
return Ok(Verdict::INVALID);
}
if !self.allow_fragments && !matches!(component(UrlComponent::Fragment), Component::Null) {
return Ok(Verdict::INVALID);
}
if transport {
let scheme = component(UrlComponent::Scheme);
let scheme = strtolower(scheme.bytes());
if scheme.as_ref() == b"http" {
let host = component(UrlComponent::Host);
let host = strtolower(host.bytes());
if !network::LOOPBACK_HOSTS.contains(&host.as_ref()) {
return Ok(Verdict::INVALID);
}
} else if scheme.as_ref() != b"https" {
return Ok(Verdict::INVALID);
}
}
Ok(Verdict::VALID)
}
fn kind(&self) -> Type {
Type::String
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Port;
impl Validator for Port {
fn description(&self) -> String {
"Value must be a port between 1 and 65535, optionally prefixed by a host IP address (e.g. 127.0.0.1:80)"
.to_owned()
}
is_valid_via_validate!();
fn validate(&self, value: Input<'_>) -> Result<Verdict, Error> {
Ok(Verdict::of(scalar::port(value.scalar())))
}
fn kind(&self) -> Type {
Type::String
}
}