utopia_validators/
network.rs1use std::borrow::Cow;
8
9use php_std::filter::{
10 self, FILTER_FLAG_IPV4, FILTER_FLAG_IPV6, FILTER_VALIDATE_IP, FILTER_VALIDATE_URL, Options, Value,
11};
12use php_std::url::rfc3986::Uri;
13use php_std::url::{Component, ComponentValue, parse_url};
14
15use crate::chars;
16
17fn passes(value: &Value, filter: i64, flags: i64) -> bool {
19 filter::filter_var(value, filter, &Options::Flags(flags))
20 .is_ok_and(|filtered| !matches!(filtered.value, Value::Bool(false)))
21}
22
23fn truthy(value: &Value, filter: i64, flags: i64) -> bool {
26 filter::filter_var(value, filter, &Options::Flags(flags)).is_ok_and(|filtered| match filtered.value {
27 Value::Bool(b) => b,
28 Value::Str(s) => !(s.is_empty() || s == b"0"),
29 Value::Null => false,
30 Value::Int(i) => i != 0,
31 Value::Float(f) => f != 0.0,
32 Value::Array(a) => !a.is_empty(),
33 Value::Object => true,
34 })
35}
36
37pub const HOSTNAME_DESCRIPTION: &str = "Value must be a valid hostname without path, port and protocol.";
41
42pub fn hostname(value: &[u8]) -> bool {
45 !(value.is_empty() || value == b"0") && chars(value) <= 253 && !value.contains(&b'/') && !value.contains(&b':')
46}
47
48pub fn hostname_allowed(value: &[u8], allowed: &[u8]) -> bool {
51 value == allowed || allowed == b"*" || allowed.strip_prefix(b"*").is_some_and(|suffix| value.ends_with(suffix))
52}
53
54pub const DOMAIN_DESCRIPTION: &str = "Value must be a valid domain";
58
59pub fn domain(value: &[u8], hostnames: bool) -> bool {
62 filter::validate_domain(value, hostnames) && !value.ends_with(b".") && !value.ends_with(b"-")
64}
65
66pub fn explode_count(value: &[u8], limit: i64) -> i64 {
68 php_std::string::explode(b".", value, limit).map_or(0, |parts| i64::try_from(parts.len()).unwrap_or(i64::MAX))
69}
70
71pub const IP_DESCRIPTION: &str = "Value must be a valid IP address";
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum IpType {
79 All,
80 V4,
81 V6,
82}
83
84impl IpType {
85 pub fn from_name(name: &[u8]) -> Option<Self> {
88 match name {
89 b"all" => Some(IpType::All),
90 b"ipv4" => Some(IpType::V4),
91 b"ipv6" => Some(IpType::V6),
92 _ => None,
93 }
94 }
95}
96
97pub fn ip(value: &Value, kind: IpType) -> bool {
99 truthy(value, FILTER_VALIDATE_IP, kind.flags())
100}
101
102pub fn ip_str(value: &[u8], kind: IpType) -> bool {
105 filter::validate_ip(value, kind.flags())
106}
107
108impl IpType {
109 fn flags(self) -> i64 {
111 match self {
112 IpType::All => 0,
113 IpType::V4 => FILTER_FLAG_IPV4,
114 IpType::V6 => FILTER_FLAG_IPV6,
115 }
116 }
117}
118
119pub fn url_description(
125 schemes: Option<&[u8]>,
126 allow_fragments: bool,
127 https_or_loopback: bool,
128 description: &mut Vec<u8>,
129) {
130 let transport: &[u8] = if https_or_loopback { b" restricted to https or http on a loopback host" } else { b"" };
131 if let Some(schemes) = schemes {
132 description.extend_from_slice(b"Value must be a valid URL with following schemes (");
133 description.extend_from_slice(schemes);
134 description.push(b')');
135 if !allow_fragments {
136 description.extend_from_slice(b" and without a fragment component");
137 }
138 } else if !allow_fragments {
139 description.extend_from_slice(b"Value must be a valid URL without a fragment component");
140 } else {
141 description.extend_from_slice(b"Value must be a valid URL");
142 }
143 description.extend_from_slice(transport);
144}
145
146pub fn url_ascii(value: &[u8]) -> Cow<'_, [u8]> {
148 if value.is_ascii() {
149 return Cow::Borrowed(value);
150 }
151 let mut ascii = Vec::with_capacity(value.len() * 3);
152 for &byte in value {
153 if byte > 127 {
154 const HEX: &[u8; 16] = b"0123456789ABCDEF";
155 ascii.extend_from_slice(&[b'%', HEX[usize::from(byte >> 4)], HEX[usize::from(byte & 15)]]);
156 } else {
157 ascii.push(byte);
158 }
159 }
160 Cow::Owned(ascii)
161}
162
163pub fn url(value: &Value) -> bool {
165 passes(value, FILTER_VALIDATE_URL, 0)
166}
167
168pub fn url_str(value: &[u8]) -> bool {
170 filter::validate_url(value, 0, None).unwrap_or(false)
171}
172
173pub fn private_use_scheme(value: &[u8]) -> bool {
176 Uri::parse(value)
177 .is_some_and(|uri| uri.scheme().is_some_and(|scheme| scheme.contains(&b'.')) && uri.host().is_none())
178}
179
180pub fn url_component(value: &[u8], component: Component) -> Option<Option<Vec<u8>>> {
183 let url = parse_url(value)?;
184 Some(url.component(component).map(|found| match found {
185 ComponentValue::Str(s) => s.into_owned(),
186 ComponentValue::Port(port) => port.to_string().into_bytes(),
187 }))
188}
189
190pub const LOOPBACK_HOSTS: [&[u8]; 3] = [b"localhost", b"127.0.0.1", b"[::1]"];
192
193pub const HOST_DESCRIPTION_PREFIX: &str = "URL host must be one of: ";
197
198pub fn host_description(whitelist: &[u8], description: &mut Vec<u8>) {
200 description.extend_from_slice(HOST_DESCRIPTION_PREFIX.as_bytes());
201 description.extend_from_slice(whitelist);
202}
203
204pub const PHONE_DESCRIPTION: &str = "Phone number must start with a '+' and contain between 7 and 15 digits.";
208
209fn e164_digits(value: &[u8]) -> bool {
212 let digits = value.strip_suffix(b"\n").unwrap_or(value);
213 matches!(digits.first(), Some(b'1'..=b'9'))
214 && (7..=15).contains(&digits.len())
215 && digits.iter().all(u8::is_ascii_digit)
216}
217
218pub fn phone(value: &[u8]) -> bool {
220 value.strip_prefix(b"+").is_some_and(e164_digits)
221}
222
223pub fn phone_normalize(value: &[u8]) -> Vec<u8> {
226 let value = php_std::encoding::rawurldecode(value);
227 if value.strip_prefix(b" ").is_some_and(e164_digits) {
228 let mut normalized = b"+".to_vec();
229 normalized.extend_from_slice(&value[1..]);
230 return normalized;
231 }
232 if !value.is_empty() && !value.starts_with(b"+") && e164_digits(&value) {
233 let mut normalized = b"+".to_vec();
234 normalized.extend_from_slice(&value);
235 return normalized;
236 }
237 value
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243
244 #[test]
245 fn phone_pattern_matches_pcre() {
246 assert!(phone(b"+1234567"));
247 assert!(phone(b"+1234567\n"));
248 assert!(!phone(b"+1234567\n\n"));
249 assert!(!phone(b"+0234567"));
250 assert!(!phone(b"+123456"));
251 assert!(phone(b"+123456789012345"));
252 assert!(!phone(b"+1234567890123456"));
253 assert_eq!(phone_normalize(b"%2B1234567"), b"+1234567");
254 assert_eq!(phone_normalize(b" 1234567"), b"+1234567");
255 assert_eq!(phone_normalize(b" 1234567\n"), b"+1234567\n");
256 assert_eq!(phone_normalize(b"1234567"), b"+1234567");
257 assert_eq!(phone_normalize(b"0234567"), b"0234567");
258 }
259
260 #[test]
261 fn hostname_shape_and_wildcards() {
262 assert!(hostname(b"a.b"));
263 assert!(!hostname(b"0"));
264 assert!(!hostname(b"a/b"));
265 assert!(!hostname(b"a:1"));
266 assert!(hostname_allowed(b"x.a.com", b"*.a.com"));
267 assert!(!hostname_allowed(b"a.com", b"*.a.com"));
268 assert!(hostname_allowed(b"anything", b"*"));
269 }
270
271 #[test]
272 fn url_ascii_encodes_high_bytes() {
273 assert_eq!(&*url_ascii("https://e.com/č".as_bytes()), b"https://e.com/%C4%8D");
274 }
275}