Skip to main content

php_std/
filter.rs

1//! `filter_var()`: the validation filters (`FILTER_VALIDATE_INT`, `BOOL`,
2//! `FLOAT`, `REGEXP`, `URL`, `EMAIL`, `IP`, `MAC`, `DOMAIN`), the sanitizing
3//! filters (`FILTER_DEFAULT`/`FILTER_UNSAFE_RAW`, `FILTER_SANITIZE_*`) and
4//! `FILTER_CALLBACK`, with their flags and options, ported from `ext/filter`
5//! (`logical_filters.c`, `sanitizing_filters.c`, `callback_filter.c`,
6//! `filter.c`) of PHP 8.5.
7//!
8//! | PHP | Rust |
9//! |---|---|
10//! | `filter_var($value, $filter, $options)` | [`filter_var`] |
11//! | `filter_var($value, FILTER_CALLBACK, ['options' => $callable])` | [`filter_var_with`] |
12//!
13//! PHP values are [`Value`]s (strings are bytes). The third argument is
14//! either flags or an options array ([`Options`]), read the way
15//! `php_filter_call()` reads it: `"filter"`, `"flags"` and `"options"` keys,
16//! with `zval_get_long()`/`zval_get_double()` conversions of `min_range` and
17//! `max_range`, and the `"default"` option replacing a `false` (or, with
18//! `FILTER_NULL_ON_FAILURE`, `null`) result, even a valid `false` from
19//! `FILTER_VALIDATE_BOOL`.
20//!
21//! `FILTER_VALIDATE_REGEXP` runs its regular expression on [`crate::pcre`],
22//! through PHP's compiled-pattern cache like PHP does.
23//! `FILTER_VALIDATE_EMAIL` checks the language of PHP's fixed expressions
24//! directly (`filter/email.rs`), and runs the expression itself only for
25//! the addresses where PCRE2's backtracking limit could decide the result.
26//! `FILTER_VALIDATE_URL` parses with [`crate::url::parse_url`], or
27//! with [`crate::url::rfc3986`] for `"uri_parser_class" =>
28//! Uri\Rfc3986\Uri`.
29//!
30//! `FILTER_CALLBACK` calls a PHP callable; [`filter_var_with`] takes the
31//! [`Callables`] that stand for them: whether the `"options"` entry is
32//! callable (PHP throws `TypeError` when it is not), and calling it with the
33//! value converted to a string. [`filter_var`] knows no callable.
34//!
35//! Like PHP, filtering an array goes on after an element throws; the
36//! exception reported is the last one thrown (a failed validation does not
37//! throw while another exception is pending, and callables are not called).
38//!
39//! `FILTER_SANITIZE_FULL_SPECIAL_CHARS` encodes as `htmlentities()` with the
40//! default charset, which this port fixes at PHP's default, UTF-8
41//! (`default_charset`/`internal_encoding` are not consulted).
42//!
43//! Not supported (an [`Error`] with class `Unsupported`): the WHATWG URL
44//! parser (`Uri\WhatWg\Url`) for `FILTER_VALIDATE_URL`.
45
46use std::borrow::Cow;
47use std::fmt;
48
49pub use crate::pcre::Key;
50use crate::{number, pcre, url, value};
51
52mod email;
53pub(crate) mod sanitize;
54
55/// No flags, as PHP's `FILTER_FLAG_NONE`.
56pub const FILTER_FLAG_NONE: i64 = 0x0000;
57/// Requires an array and filters each element, as PHP's `FILTER_REQUIRE_ARRAY`.
58pub const FILTER_REQUIRE_ARRAY: i64 = 0x0100_0000;
59/// Requires a scalar value, as PHP's `FILTER_REQUIRE_SCALAR`.
60pub const FILTER_REQUIRE_SCALAR: i64 = 0x0200_0000;
61/// Wraps a scalar result in an array, as PHP's `FILTER_FORCE_ARRAY`.
62pub const FILTER_FORCE_ARRAY: i64 = 0x0400_0000;
63/// Returns `null` instead of `false` on failure, as PHP's `FILTER_NULL_ON_FAILURE`.
64pub const FILTER_NULL_ON_FAILURE: i64 = 0x0800_0000;
65/// Throws `Filter\FilterFailedException` on failure, as PHP's `FILTER_THROW_ON_FAILURE`.
66pub const FILTER_THROW_ON_FAILURE: i64 = 0x1000_0000;
67/// Accepts octal integers (`0` or `0o` prefix), as PHP's `FILTER_FLAG_ALLOW_OCTAL`.
68pub const FILTER_FLAG_ALLOW_OCTAL: i64 = 0x0001;
69/// Accepts hexadecimal integers (`0x` prefix), as PHP's `FILTER_FLAG_ALLOW_HEX`.
70pub const FILTER_FLAG_ALLOW_HEX: i64 = 0x0002;
71/// Strips bytes below 32, as PHP's `FILTER_FLAG_STRIP_LOW`.
72pub const FILTER_FLAG_STRIP_LOW: i64 = 0x0004;
73/// Strips bytes 127 and above, as PHP's `FILTER_FLAG_STRIP_HIGH`.
74pub const FILTER_FLAG_STRIP_HIGH: i64 = 0x0008;
75/// Encodes bytes below 32 as `&#N;`, as PHP's `FILTER_FLAG_ENCODE_LOW`.
76pub const FILTER_FLAG_ENCODE_LOW: i64 = 0x0010;
77/// Encodes bytes 127 and above as `&#N;`, as PHP's `FILTER_FLAG_ENCODE_HIGH`.
78pub const FILTER_FLAG_ENCODE_HIGH: i64 = 0x0020;
79/// Encodes `&` as `&`, as PHP's `FILTER_FLAG_ENCODE_AMP`.
80pub const FILTER_FLAG_ENCODE_AMP: i64 = 0x0040;
81/// Leaves `'` and `"` unencoded, as PHP's `FILTER_FLAG_NO_ENCODE_QUOTES`.
82pub const FILTER_FLAG_NO_ENCODE_QUOTES: i64 = 0x0080;
83/// Turns an empty string into `null`, as PHP's `FILTER_FLAG_EMPTY_STRING_NULL`.
84pub const FILTER_FLAG_EMPTY_STRING_NULL: i64 = 0x0100;
85/// Strips backticks, as PHP's `FILTER_FLAG_STRIP_BACKTICK`.
86pub const FILTER_FLAG_STRIP_BACKTICK: i64 = 0x0200;
87/// Keeps the decimal separator when sanitizing floats, as PHP's `FILTER_FLAG_ALLOW_FRACTION`.
88pub const FILTER_FLAG_ALLOW_FRACTION: i64 = 0x1000;
89/// Accepts or keeps thousand separators, as PHP's `FILTER_FLAG_ALLOW_THOUSAND`.
90pub const FILTER_FLAG_ALLOW_THOUSAND: i64 = 0x2000;
91/// Keeps `e` and `E` when sanitizing floats, as PHP's `FILTER_FLAG_ALLOW_SCIENTIFIC`.
92pub const FILTER_FLAG_ALLOW_SCIENTIFIC: i64 = 0x4000;
93/// Requires a path in a validated URL, as PHP's `FILTER_FLAG_PATH_REQUIRED`.
94pub const FILTER_FLAG_PATH_REQUIRED: i64 = 0x04_0000;
95/// Requires a query string in a validated URL, as PHP's `FILTER_FLAG_QUERY_REQUIRED`.
96pub const FILTER_FLAG_QUERY_REQUIRED: i64 = 0x08_0000;
97/// Accepts IPv4 addresses only, as PHP's `FILTER_FLAG_IPV4`.
98pub const FILTER_FLAG_IPV4: i64 = 0x0010_0000;
99/// Accepts IPv6 addresses only, as PHP's `FILTER_FLAG_IPV6`.
100pub const FILTER_FLAG_IPV6: i64 = 0x0020_0000;
101/// Rejects reserved IP ranges, as PHP's `FILTER_FLAG_NO_RES_RANGE`.
102pub const FILTER_FLAG_NO_RES_RANGE: i64 = 0x0040_0000;
103/// Rejects private IP ranges, as PHP's `FILTER_FLAG_NO_PRIV_RANGE`.
104pub const FILTER_FLAG_NO_PRIV_RANGE: i64 = 0x0080_0000;
105/// Accepts globally routable IP addresses only, as PHP's `FILTER_FLAG_GLOBAL_RANGE`.
106pub const FILTER_FLAG_GLOBAL_RANGE: i64 = 0x2000_0000;
107/// Requires a valid host name for `FILTER_VALIDATE_DOMAIN`, as PHP's `FILTER_FLAG_HOSTNAME`.
108pub const FILTER_FLAG_HOSTNAME: i64 = 0x0010_0000;
109/// Accepts Unicode in an email's local part, as PHP's `FILTER_FLAG_EMAIL_UNICODE`.
110pub const FILTER_FLAG_EMAIL_UNICODE: i64 = 0x0010_0000;
111
112/// Validates an integer, as PHP's `FILTER_VALIDATE_INT`.
113pub const FILTER_VALIDATE_INT: i64 = 0x0101;
114/// Validates a boolean (`"1"`, `"true"`, `"on"`, `"yes"` and their opposites), as PHP's `FILTER_VALIDATE_BOOL`.
115pub const FILTER_VALIDATE_BOOL: i64 = 0x0102;
116/// Validates a float, as PHP's `FILTER_VALIDATE_FLOAT`.
117pub const FILTER_VALIDATE_FLOAT: i64 = 0x0103;
118/// Validates against the `regexp` option, as PHP's `FILTER_VALIDATE_REGEXP`.
119pub const FILTER_VALIDATE_REGEXP: i64 = 0x0110;
120/// Validates a URL, as PHP's `FILTER_VALIDATE_URL`.
121pub const FILTER_VALIDATE_URL: i64 = 0x0111;
122/// Validates an email address, as PHP's `FILTER_VALIDATE_EMAIL`.
123pub const FILTER_VALIDATE_EMAIL: i64 = 0x0112;
124/// Validates an IPv4 or IPv6 address, as PHP's `FILTER_VALIDATE_IP`.
125pub const FILTER_VALIDATE_IP: i64 = 0x0113;
126/// Validates a MAC address, as PHP's `FILTER_VALIDATE_MAC`.
127pub const FILTER_VALIDATE_MAC: i64 = 0x0114;
128/// Validates a domain name, as PHP's `FILTER_VALIDATE_DOMAIN`.
129pub const FILTER_VALIDATE_DOMAIN: i64 = 0x0115;
130/// The default filter, which leaves the string as is, as PHP's `FILTER_DEFAULT`.
131pub const FILTER_DEFAULT: i64 = 0x0204;
132/// Leaves the string as is, optionally stripping or encoding bytes, as PHP's `FILTER_UNSAFE_RAW`.
133pub const FILTER_UNSAFE_RAW: i64 = 0x0204;
134/// PHP deprecates the constant (8.1), not the filter: the ID runs without
135/// a notice.
136pub const FILTER_SANITIZE_STRING: i64 = 0x0201;
137/// An alias of [`FILTER_SANITIZE_STRING`] (also a deprecated constant).
138pub const FILTER_SANITIZE_STRIPPED: i64 = 0x0201;
139/// URL-encodes the string, as PHP's `FILTER_SANITIZE_ENCODED`.
140pub const FILTER_SANITIZE_ENCODED: i64 = 0x0202;
141/// HTML-encodes `'"<>&` and bytes below 32, as PHP's `FILTER_SANITIZE_SPECIAL_CHARS`.
142pub const FILTER_SANITIZE_SPECIAL_CHARS: i64 = 0x0203;
143/// Removes the bytes an email address cannot hold, as PHP's `FILTER_SANITIZE_EMAIL`.
144pub const FILTER_SANITIZE_EMAIL: i64 = 0x0205;
145/// Removes the bytes a URL cannot hold, as PHP's `FILTER_SANITIZE_URL`.
146pub const FILTER_SANITIZE_URL: i64 = 0x0206;
147/// Keeps only digits and signs, as PHP's `FILTER_SANITIZE_NUMBER_INT`.
148pub const FILTER_SANITIZE_NUMBER_INT: i64 = 0x0207;
149/// Keeps only digits, signs and the allowed float characters, as PHP's `FILTER_SANITIZE_NUMBER_FLOAT`.
150pub const FILTER_SANITIZE_NUMBER_FLOAT: i64 = 0x0208;
151/// Encodes as `htmlentities()` with `ENT_QUOTES`, as PHP's `FILTER_SANITIZE_FULL_SPECIAL_CHARS`.
152pub const FILTER_SANITIZE_FULL_SPECIAL_CHARS: i64 = 0x020a;
153/// Escapes as `addslashes()`, as PHP's `FILTER_SANITIZE_ADD_SLASHES`.
154pub const FILTER_SANITIZE_ADD_SLASHES: i64 = 0x020b;
155/// Calls the callable in the `options` entry, as PHP's `FILTER_CALLBACK`.
156pub const FILTER_CALLBACK: i64 = 0x0400;
157
158/// A PHP value given to or returned by `filter_var()`.
159#[derive(Debug, Clone, PartialEq)]
160pub enum Value {
161    /// PHP `null`.
162    Null,
163    /// A PHP `bool`.
164    Bool(bool),
165    /// A PHP `int`.
166    Int(i64),
167    /// A PHP `float`.
168    Float(f64),
169    /// A PHP `string`, as bytes.
170    Str(Vec<u8>),
171    /// A PHP array, as its key-value pairs in order.
172    Array(Vec<(Key, Value)>),
173    /// A `stdClass` instance (no `__toString()`).
174    Object,
175}
176
177/// The third argument of `filter_var()`.
178#[derive(Debug, Clone, PartialEq)]
179pub enum Options {
180    /// A flags integer (`FILTER_FLAG_*` and `FILTER_*_ARRAY` bits).
181    Flags(i64),
182    /// `['filter' => ..., 'flags' => ..., 'options' => [...]]`
183    Array(Vec<(Key, Value)>),
184}
185
186/// An exception `filter_var()` throws (`ValueError`, `TypeError`,
187/// `Filter\FilterFailedException`), or `Unsupported` for what this port
188/// does not implement.
189#[derive(Debug, Clone, PartialEq, Eq)]
190pub struct Error {
191    class: &'static str,
192    message: Vec<u8>,
193}
194
195impl Error {
196    fn new(class: &'static str, message: impl Into<Vec<u8>>) -> Self {
197        Error { class, message: message.into() }
198    }
199
200    /// The PHP exception class.
201    pub fn php_class(&self) -> &'static str {
202        self.class
203    }
204
205    /// The message as bytes (it can quote the value).
206    pub fn message(&self) -> &[u8] {
207        &self.message
208    }
209}
210
211impl fmt::Display for Error {
212    /// Writes the message, lossily decoded as UTF-8.
213    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214        f.write_str(&String::from_utf8_lossy(&self.message))
215    }
216}
217
218impl std::error::Error for Error {}
219
220/// What `filter_var()` returned, and the warning it emitted, if any.
221#[derive(Debug, Clone, PartialEq)]
222pub struct Filtered {
223    /// The value `filter_var()` returned.
224    pub value: Value,
225    /// The PHP warning emitted, if any.
226    pub warning: Option<Vec<u8>>,
227}
228
229const FAILED: &str = "Filter\\FilterFailedException";
230
231fn lookup<'a>(array: &'a [(Key, Value)], key: &str) -> Option<&'a Value> {
232    array.iter().find(|(k, _)| matches!(k, Key::Str(s) if s.as_slice() == key.as_bytes())).map(|(_, v)| v)
233}
234
235/// `zval_get_long()`; a float that does not fit warns (PHP 8.5).
236fn get_long(v: &Value, warning: &mut Option<Vec<u8>>) -> i64 {
237    match v {
238        Value::Null | Value::Bool(false) => 0,
239        Value::Bool(true) => 1,
240        Value::Int(i) => *i,
241        Value::Float(f) => {
242            if !f.is_finite() || !(-TWO_POW_63..TWO_POW_63).contains(f) {
243                *warning = Some(
244                    format!("The float {} is not representable as an int, cast occurred", number::gcvt(*f, -1, 'E'))
245                        .into_bytes(),
246                );
247            }
248            dval_to_lval(*f)
249        }
250        Value::Str(s) => match numeric_prefix(s) {
251            None => 0,
252            Some(value::Number::Int(i)) => i,
253            Some(value::Number::Float(f)) => dval_to_lval_cap(f),
254        },
255        Value::Array(a) => i64::from(!a.is_empty()),
256        Value::Object => 1,
257    }
258}
259
260/// `zval_get_double()`.
261fn get_double(v: &Value) -> f64 {
262    match v {
263        Value::Null | Value::Bool(false) => 0.0,
264        Value::Bool(true) => 1.0,
265        Value::Int(i) => *i as f64,
266        Value::Float(f) => *f,
267        Value::Str(s) => strtod(s),
268        Value::Array(a) => f64::from(u8::from(!a.is_empty())),
269        Value::Object => 1.0,
270    }
271}
272
273/// `zend_dval_to_lval()`: modular for out-of-range values, 0 for non-finite.
274/// 2^63, the first double past `ZEND_LONG_MAX` (which rounds to it).
275const TWO_POW_63: f64 = 9_223_372_036_854_775_808.0;
276
277fn dval_to_lval(d: f64) -> i64 {
278    if !d.is_finite() {
279        return 0;
280    }
281    if (-TWO_POW_63..TWO_POW_63).contains(&d) {
282        return d as i64;
283    }
284    let two64 = 18_446_744_073_709_551_616.0_f64;
285    let mut dmod = d % two64;
286    if dmod < 0.0 {
287        // we're going to make this number positive; call ourselves recursively
288        // if the result is -zero, i.e. the number was a multiple of 2^64
289        dmod += two64;
290        if dmod >= two64 {
291            return 0;
292        }
293    }
294    if dmod > TWO_POW_63 {
295        dmod -= two64;
296    }
297    dmod as i64
298}
299
300/// `zend_dval_to_lval_cap()`: saturating.
301fn dval_to_lval_cap(d: f64) -> i64 {
302    if !d.is_finite() {
303        return 0;
304    }
305    if d >= TWO_POW_63 {
306        return i64::MAX;
307    }
308    if d < -TWO_POW_63 {
309        return i64::MIN;
310    }
311    d as i64
312}
313
314/// `is_numeric_string(..., allow_errors = true)`: leading whitespace, then
315/// the longest numeric prefix; `None` when there is none.
316fn numeric_prefix(s: &[u8]) -> Option<value::Number> {
317    let mut i = 0;
318    while i < s.len() && matches!(s[i], b' ' | b'\t' | b'\n' | b'\r' | 0x0b | 0x0c) {
319        i += 1;
320    }
321    let start = i;
322    if i < s.len() && (s[i] == b'+' || s[i] == b'-') {
323        i += 1;
324    }
325    let int_start = i;
326    while i < s.len() && s[i].is_ascii_digit() {
327        i += 1;
328    }
329    let int_digits = i - int_start;
330    let mut end = i;
331    let mut frac_digits = 0;
332    if i < s.len() && s[i] == b'.' {
333        let mut j = i + 1;
334        while j < s.len() && s[j].is_ascii_digit() {
335            j += 1;
336        }
337        frac_digits = j - i - 1;
338        if int_digits > 0 || frac_digits > 0 {
339            end = j;
340        }
341    }
342    if int_digits == 0 && frac_digits == 0 {
343        return None;
344    }
345    let mut k = end;
346    if k < s.len() && (s[k] == b'e' || s[k] == b'E') {
347        let mut j = k + 1;
348        if j < s.len() && (s[j] == b'+' || s[j] == b'-') {
349            j += 1;
350        }
351        let d = j;
352        while j < s.len() && s[j].is_ascii_digit() {
353            j += 1;
354        }
355        if j > d {
356            k = j;
357        }
358    }
359    let text = std::str::from_utf8(&s[start..k]).ok()?;
360    value::numeric_str(text)
361}
362
363/// `zend_strtod()` on the start of a string: leading whitespace, then the
364/// longest decimal prefix, or 0.
365fn strtod(s: &[u8]) -> f64 {
366    let mut i = 0;
367    while i < s.len() && matches!(s[i], b' ' | b'\t' | b'\n' | b'\r' | 0x0b | 0x0c) {
368        i += 1;
369    }
370    let s = &s[i..];
371    let mut i = 0;
372    if i < s.len() && (s[i] == b'+' || s[i] == b'-') {
373        i += 1;
374    }
375    let ds = i;
376    while i < s.len() && s[i].is_ascii_digit() {
377        i += 1;
378    }
379    let mut digits = i - ds;
380    if i < s.len() && s[i] == b'.' {
381        let mut j = i + 1;
382        while j < s.len() && s[j].is_ascii_digit() {
383            j += 1;
384        }
385        digits += j - i - 1;
386        if digits > 0 {
387            i = j;
388        }
389    }
390    if digits == 0 {
391        return 0.0;
392    }
393    if i < s.len() && (s[i] == b'e' || s[i] == b'E') {
394        let mut j = i + 1;
395        if j < s.len() && (s[j] == b'+' || s[j] == b'-') {
396            j += 1;
397        }
398        let d = j;
399        while j < s.len() && s[j].is_ascii_digit() {
400            j += 1;
401        }
402        if j > d {
403            i = j;
404        }
405    }
406    std::str::from_utf8(&s[..i]).ok().and_then(|t| t.parse::<f64>().ok()).unwrap_or(0.0)
407}
408
409/// `convert_to_string()` of a scalar; `NAN` warns (PHP 8.5). A string is
410/// borrowed, not copied.
411fn to_php_string<'v>(v: &'v Value, warning: &mut Option<Vec<u8>>) -> Cow<'v, [u8]> {
412    if let Value::Float(f) = v
413        && f.is_nan()
414    {
415        *warning = Some(b"unexpected NAN value was coerced to string".to_vec());
416    }
417    match v {
418        Value::Null | Value::Bool(false) | Value::Object => Cow::Borrowed(b""),
419        Value::Bool(true) => Cow::Borrowed(b"1"),
420        Value::Int(i) => Cow::Owned(i.to_string().into_bytes()),
421        Value::Float(f) => Cow::Owned(number::to_string(*f).into_bytes()),
422        Value::Str(s) => Cow::Borrowed(s),
423        Value::Array(_) => Cow::Borrowed(b"Array"),
424    }
425}
426
427/// `zend_zval_value_name()`.
428fn type_name(v: &Value) -> &'static str {
429    match v {
430        Value::Null => "null",
431        Value::Bool(true) => "true",
432        Value::Bool(false) => "false",
433        Value::Int(_) => "int",
434        Value::Float(_) => "float",
435        Value::Str(_) => "string",
436        Value::Array(_) => "array",
437        Value::Object => "stdClass",
438    }
439}
440
441/// The name of a filter in `filter_list[]`.
442fn filter_name(id: i64) -> &'static str {
443    match id {
444        FILTER_VALIDATE_INT => "int",
445        FILTER_VALIDATE_BOOL => "boolean",
446        FILTER_VALIDATE_FLOAT => "float",
447        FILTER_VALIDATE_REGEXP => "validate_regexp",
448        FILTER_VALIDATE_DOMAIN => "validate_domain",
449        FILTER_VALIDATE_URL => "validate_url",
450        FILTER_VALIDATE_EMAIL => "validate_email",
451        FILTER_VALIDATE_IP => "validate_ip",
452        FILTER_VALIDATE_MAC => "validate_mac",
453        FILTER_SANITIZE_STRING => "string",
454        FILTER_SANITIZE_ENCODED => "encoded",
455        FILTER_SANITIZE_SPECIAL_CHARS => "special_chars",
456        FILTER_SANITIZE_FULL_SPECIAL_CHARS => "full_special_chars",
457        FILTER_SANITIZE_EMAIL => "email",
458        FILTER_SANITIZE_URL => "url",
459        FILTER_SANITIZE_NUMBER_INT => "number_int",
460        FILTER_SANITIZE_NUMBER_FLOAT => "number_float",
461        FILTER_SANITIZE_ADD_SLASHES => "add_slashes",
462        FILTER_CALLBACK => "callback",
463        _ => "unsafe_raw",
464    }
465}
466
467/// Whether `filter_list[]` has the filter (`php_find_filter()` falls back
468/// to `FILTER_DEFAULT` otherwise).
469fn in_list(id: i64) -> bool {
470    matches!(id, 0x0101..=0x0103 | 0x0110..=0x0115 | 0x0201..=0x0208 | 0x020a | 0x020b | FILTER_CALLBACK)
471}
472
473/// `PHP_FILTER_ID_EXISTS()`.
474fn id_exists(id: i64) -> bool {
475    (0x0200..=0x020b).contains(&id) || (0x0100..=0x0115).contains(&id) || id == FILTER_CALLBACK
476}
477
478/// The outcome of one filter function.
479enum Outcome {
480    /// The filter accepted the value (possibly converting it).
481    Ok(Value),
482    /// `RETURN_VALIDATION_FAILED`.
483    Failed,
484}
485
486/// The PHP callables `FILTER_CALLBACK` can call, named by its `"options"`
487/// entry.
488pub trait Callables {
489    /// `zend_is_callable()`: whether the entry names a callable.
490    fn is_callable(&self, callable: &Value) -> bool;
491
492    /// Calls the callable with the value converted to a string and returns
493    /// its result.
494    fn call(&mut self, callable: &Value, value: &[u8]) -> Value;
495}
496
497/// No callable at all: `FILTER_CALLBACK` always throws `TypeError`.
498pub struct NoCallables;
499
500impl Callables for NoCallables {
501    /// Nothing is callable.
502    fn is_callable(&self, _callable: &Value) -> bool {
503        false
504    }
505
506    /// Never called; returns `null`.
507    fn call(&mut self, _callable: &Value, _value: &[u8]) -> Value {
508        Value::Null
509    }
510}
511
512/// `filter_var($value, $filter, $options)`, without callables (see
513/// [`filter_var_with`]).
514pub fn filter_var(value: &Value, filter: i64, options: &Options) -> Result<Filtered, Error> {
515    filter_var_with(value, filter, options, &mut NoCallables)
516}
517
518/// `filter_var($value, $filter, $options)` where `callables` resolves and
519/// calls the callable of `FILTER_CALLBACK` (the `"options"` entry).
520pub fn filter_var_with(
521    value: &Value,
522    filter: i64,
523    options: &Options,
524    callables: &mut dyn Callables,
525) -> Result<Filtered, Error> {
526    if !id_exists(filter) {
527        return Ok(Filtered {
528            value: Value::Bool(false),
529            warning: Some(format!("filter_var(): Unknown filter with ID {filter}").into_bytes()),
530        });
531    }
532    let mut warning = None;
533    let mut filter = filter;
534    let mut flags = FILTER_REQUIRE_SCALAR;
535    // `options`: the array of the filter's options, or FILTER_CALLBACK's
536    // callable.
537    let mut opts: Option<&Value> = None;
538    match options {
539        Options::Flags(f) => {
540            flags = *f;
541            if flags & (FILTER_REQUIRE_ARRAY | FILTER_FORCE_ARRAY) == 0 {
542                flags |= FILTER_REQUIRE_SCALAR;
543            }
544        }
545        Options::Array(args) => {
546            if let Some(f) = lookup(args, "filter") {
547                filter = get_long(f, &mut warning);
548            }
549            if let Some(o) = lookup(args, "options") {
550                if filter != FILTER_CALLBACK {
551                    if let Value::Array(_) = o {
552                        opts = Some(o);
553                    }
554                } else {
555                    opts = Some(o);
556                    flags = 0;
557                }
558            }
559            if let Some(f) = lookup(args, "flags") {
560                flags = get_long(f, &mut warning);
561                if flags & (FILTER_REQUIRE_ARRAY | FILTER_FORCE_ARRAY) == 0 {
562                    flags |= FILTER_REQUIRE_SCALAR;
563                }
564            }
565        }
566    }
567    if flags & FILTER_NULL_ON_FAILURE != 0 && flags & FILTER_THROW_ON_FAILURE != 0 {
568        return Err(Error::new(
569            "ValueError",
570            "filter_var(): Argument #3 ($options) cannot use both FILTER_NULL_ON_FAILURE and FILTER_THROW_ON_FAILURE",
571        ));
572    }
573    let failure = |flags: i64| if flags & FILTER_NULL_ON_FAILURE != 0 { Value::Null } else { Value::Bool(false) };
574    if let Value::Array(items) = value {
575        if flags & FILTER_REQUIRE_SCALAR != 0 {
576            if flags & FILTER_THROW_ON_FAILURE != 0 {
577                return Err(Error::new(FAILED, "filter validation failed: not a scalar value (got an array)"));
578            }
579            return Ok(Filtered { value: failure(flags), warning });
580        }
581        let mut thrown = None;
582        let out = filter_recursive(items, filter, flags, opts, callables, &mut thrown, &mut warning);
583        if let Some(e) = thrown {
584            return Err(e);
585        }
586        return Ok(Filtered { value: Value::Array(out), warning });
587    }
588    if flags & FILTER_REQUIRE_ARRAY != 0 {
589        if flags & FILTER_THROW_ON_FAILURE != 0 {
590            return Err(Error::new(
591                FAILED,
592                format!("filter validation failed: not an array (got {})", type_name(value)),
593            ));
594        }
595        return Ok(Filtered { value: failure(flags), warning });
596    }
597    let mut out = zval_filter(value, filter, flags, opts, callables, false, &mut warning)?.unwrap_or(Value::Null);
598    if flags & FILTER_FORCE_ARRAY != 0 {
599        out = Value::Array(vec![(Key::Int(0), out)]);
600    }
601    Ok(Filtered { value: out, warning })
602}
603
604/// `php_zval_filter_recursive()`. An element that throws does not stop the
605/// walk: `thrown` holds the exception pending, which a later one replaces.
606fn filter_recursive(
607    items: &[(Key, Value)],
608    filter: i64,
609    flags: i64,
610    opts: Option<&Value>,
611    callables: &mut dyn Callables,
612    thrown: &mut Option<Error>,
613    warning: &mut Option<Vec<u8>>,
614) -> Vec<(Key, Value)> {
615    let mut out = Vec::with_capacity(items.len());
616    for (k, v) in items {
617        let r = match v {
618            Value::Array(inner) => {
619                Value::Array(filter_recursive(inner, filter, flags, opts, callables, thrown, warning))
620            }
621            _ => match zval_filter(v, filter, flags, opts, callables, thrown.is_some(), warning) {
622                Ok(r) => r.unwrap_or(Value::Null),
623                Err(e) => {
624                    *thrown = Some(e);
625                    Value::Null
626                }
627            },
628        };
629        out.push((k.clone(), r));
630    }
631    out
632}
633
634/// `php_zval_filter()`. With an exception `pending`, a failed validation
635/// does not throw and a callable is not called; `Ok(None)` stands for the
636/// value they leave.
637fn zval_filter(
638    value: &Value,
639    filter: i64,
640    flags: i64,
641    options: Option<&Value>,
642    callables: &mut dyn Callables,
643    pending: bool,
644    warning: &mut Option<Vec<u8>>,
645) -> Result<Option<Value>, Error> {
646    let filter = if in_list(filter) { filter } else { FILTER_DEFAULT };
647    let opts = match options {
648        Some(Value::Array(a)) => Some(a.as_slice()),
649        _ => None,
650    };
651    let result = if let Value::Object = value {
652        if flags & FILTER_THROW_ON_FAILURE != 0 {
653            return Err(Error::new(
654                FAILED,
655                "filter validation failed: object of type stdClass has no __toString() method",
656            ));
657        }
658        if flags & FILTER_NULL_ON_FAILURE != 0 { Value::Null } else { Value::Bool(false) }
659    } else {
660        let s = to_php_string(value, warning);
661        let outcome = if filter == FILTER_CALLBACK {
662            // php_filter_callback(); zend_call_function() does not call
663            // while an exception is pending.
664            match options.filter(|o| callables.is_callable(o)) {
665                None => return Err(Error::new("TypeError", "filter_var(): Option must be a valid callback")),
666                Some(_) if pending => return Ok(None),
667                Some(o) => Outcome::Ok(callables.call(o, &s)),
668            }
669        } else {
670            run_filter(filter, &s, flags, opts, warning)?
671        };
672        match outcome {
673            Outcome::Ok(v) => v,
674            Outcome::Failed => {
675                if pending {
676                    // RETURN_VALIDATION_FAILED: nothing more to do.
677                    return Ok(None);
678                }
679                if flags & FILTER_THROW_ON_FAILURE != 0 {
680                    let shown = s.iter().position(|&b| b == 0).map_or(&s[..], |n| &s[..n]);
681                    let mut m = format!("filter validation failed: filter {} not satisfied by '", filter_name(filter))
682                        .into_bytes();
683                    m.extend_from_slice(shown);
684                    m.push(b'\'');
685                    return Err(Error::new(FAILED, m));
686                }
687                if flags & FILTER_NULL_ON_FAILURE != 0 { Value::Null } else { Value::Bool(false) }
688            }
689        }
690    };
691    // handle_default
692    if let Some(opts) = opts {
693        let replace =
694            if flags & FILTER_NULL_ON_FAILURE != 0 { result == Value::Null } else { result == Value::Bool(false) };
695        if replace && let Some(d) = lookup(opts, "default") {
696            return Ok(Some(d.clone()));
697        }
698    }
699    Ok(Some(result))
700}
701
702fn run_filter(
703    filter: i64,
704    s: &[u8],
705    flags: i64,
706    opts: Option<&[(Key, Value)]>,
707    warning: &mut Option<Vec<u8>>,
708) -> Result<Outcome, Error> {
709    let opt = |name: &str| opts.and_then(|o| lookup(o, name));
710    let str_opt = |name: &str| match opt(name) {
711        Some(Value::Str(v)) => Some(v.as_slice()),
712        _ => None,
713    };
714    match filter {
715        FILTER_VALIDATE_INT => {
716            let min = opt("min_range").map(|v| get_long(v, warning));
717            let max = opt("max_range").map(|v| get_long(v, warning));
718            Ok(validate_int(s, flags, min, max).map_or(Outcome::Failed, |v| Outcome::Ok(Value::Int(v))))
719        }
720        FILTER_VALIDATE_BOOL => Ok(match validate_bool(s) {
721            Some(b) => Outcome::Ok(Value::Bool(b)),
722            None => Outcome::Failed,
723        }),
724        FILTER_VALIDATE_FLOAT => {
725            let trimmed = trim(s);
726            if trimmed.is_empty() {
727                return Ok(Outcome::Failed);
728            }
729            let decimal = match str_opt("decimal") {
730                Some(d) if d.len() != 1 => {
731                    return Err(Error::new(
732                        "ValueError",
733                        "filter_var(): \"decimal\" option must be one character long",
734                    ));
735                }
736                Some(d) => d[0],
737                None => b'.',
738            };
739            let thousand: Vec<u8> = match str_opt("thousand") {
740                Some([]) => {
741                    return Err(Error::new("ValueError", "filter_var(): \"thousand\" option must not be empty"));
742                }
743                // A C string: strchr() stops at the first NUL.
744                Some(t) => t.iter().copied().take_while(|&b| b != 0).collect(),
745                None => b"',.".to_vec(),
746            };
747            let min = opt("min_range").map(get_double);
748            let max = opt("max_range").map(get_double);
749            Ok(validate_float(s, flags, decimal, &thousand, min, max)
750                .map_or(Outcome::Failed, |f| Outcome::Ok(Value::Float(f))))
751        }
752        FILTER_VALIDATE_REGEXP => {
753            let Some(re) = str_opt("regexp") else {
754                return Err(Error::new("ValueError", "filter_var(): \"regexp\" option is missing"));
755            };
756            let (matched, w) = pcre::engine_match("filter_var", re, s);
757            if w.is_some() {
758                *warning = w;
759            }
760            Ok(if matched == Some(true) { Outcome::Ok(Value::Str(s.to_vec())) } else { Outcome::Failed })
761        }
762        FILTER_VALIDATE_DOMAIN => Ok(if validate_domain(s, flags & FILTER_FLAG_HOSTNAME != 0) {
763            Outcome::Ok(Value::Str(s.to_vec()))
764        } else {
765            Outcome::Failed
766        }),
767        FILTER_VALIDATE_URL => {
768            let parser = match opts.and_then(|o| lookup(o, "uri_parser_class")) {
769                Some(Value::Str(p)) => Some(p.as_slice()),
770                _ => None,
771            };
772            validate_url(s, flags, parser)
773                .map(|ok| if ok { Outcome::Ok(Value::Str(s.to_vec())) } else { Outcome::Failed })
774        }
775        FILTER_VALIDATE_EMAIL => {
776            if s.len() > email::MAX_LENGTH {
777                return Ok(Outcome::Failed);
778            }
779            let unicode = flags & FILTER_FLAG_EMAIL_UNICODE != 0;
780            let valid = email::validate(s, unicode).unwrap_or_else(|| {
781                let re = if unicode { email::EMAIL_UNICODE } else { email::EMAIL };
782                let (matched, w) = pcre::engine_match("filter_var", re, s);
783                if w.is_some() {
784                    *warning = w;
785                }
786                matched == Some(true)
787            });
788            Ok(if valid { Outcome::Ok(Value::Str(s.to_vec())) } else { Outcome::Failed })
789        }
790        FILTER_VALIDATE_IP => {
791            Ok(if validate_ip(s, flags) { Outcome::Ok(Value::Str(s.to_vec())) } else { Outcome::Failed })
792        }
793        FILTER_VALIDATE_MAC => {
794            let sep = match str_opt("separator") {
795                Some(d) if d.len() != 1 => {
796                    return Err(Error::new(
797                        "ValueError",
798                        "filter_var(): \"separator\" option must be one character long",
799                    ));
800                }
801                Some(d) => Some(d[0]),
802                None => None,
803            };
804            Ok(if validate_mac(s, sep) { Outcome::Ok(Value::Str(s.to_vec())) } else { Outcome::Failed })
805        }
806        FILTER_SANITIZE_STRING => Ok(Outcome::Ok(sanitize::string(s, flags))),
807        FILTER_SANITIZE_ENCODED => Ok(Outcome::Ok(Value::Str(sanitize::encoded(s, flags)))),
808        FILTER_SANITIZE_SPECIAL_CHARS => Ok(Outcome::Ok(Value::Str(sanitize::special_chars(s, flags)))),
809        FILTER_SANITIZE_FULL_SPECIAL_CHARS => Ok(Outcome::Ok(Value::Str(sanitize::full_special_chars(s, flags)))),
810        FILTER_SANITIZE_EMAIL => Ok(Outcome::Ok(Value::Str(sanitize::email(s)))),
811        FILTER_SANITIZE_URL => Ok(Outcome::Ok(Value::Str(sanitize::url(s)))),
812        FILTER_SANITIZE_NUMBER_INT => Ok(Outcome::Ok(Value::Str(sanitize::number_int(s)))),
813        FILTER_SANITIZE_NUMBER_FLOAT => Ok(Outcome::Ok(Value::Str(sanitize::number_float(s, flags)))),
814        FILTER_SANITIZE_ADD_SLASHES => Ok(Outcome::Ok(Value::Str(sanitize::add_slashes(s)))),
815        _ => Ok(Outcome::Ok(sanitize::unsafe_raw(s, flags))),
816    }
817}
818
819/// `PHP_FILTER_TRIM_DEFAULT`: the range without leading and trailing
820/// `' '`, `\t`, `\r`, `\v`, `\n`.
821fn trim(s: &[u8]) -> &[u8] {
822    let ws = |b: u8| matches!(b, b' ' | b'\t' | b'\r' | 0x0b | b'\n');
823    let mut start = 0;
824    while start < s.len() && ws(s[start]) {
825        start += 1;
826    }
827    let mut end = s.len();
828    while end > start && ws(s[end - 1]) {
829        end -= 1;
830    }
831    &s[start..end]
832}
833
834/// `php_filter_parse_int()`.
835fn parse_int(s: &[u8]) -> Option<i64> {
836    let mut i = 0;
837    let at = |i: usize| s.get(i).copied().unwrap_or(0);
838    let mut negative = false;
839    match at(0) {
840        b'-' => {
841            negative = true;
842            i += 1;
843        }
844        b'+' => i += 1,
845        _ => {}
846    }
847    if at(i) == b'0' && i + 1 == s.len() {
848        return Some(0);
849    }
850    if !(i < s.len() && (b'1'..=b'9').contains(&s[i])) {
851        return None;
852    }
853    let mut value: i64 = i64::from(s[i] - b'0') * if negative { -1 } else { 1 };
854    i += 1;
855    if s.len() - i > 19 {
856        return None;
857    }
858    while i < s.len() {
859        let c = s[i];
860        if !c.is_ascii_digit() {
861            return None;
862        }
863        let digit = i64::from(c - b'0');
864        i += 1;
865        if !negative && value <= (i64::MAX - digit) / 10 {
866            value = value * 10 + digit;
867        } else if negative && value >= (i64::MIN + digit) / 10 {
868            value = value * 10 - digit;
869        } else {
870            return None;
871        }
872    }
873    Some(value)
874}
875
876/// `php_filter_parse_octal()`.
877fn parse_octal(s: &[u8]) -> Option<i64> {
878    let mut v: u64 = 0;
879    for &c in s {
880        if !(b'0'..=b'7').contains(&c) {
881            return None;
882        }
883        let n = u64::from(c - b'0');
884        if v > u64::MAX / 8 {
885            return None;
886        }
887        v *= 8;
888        if v > u64::MAX - n {
889            return None;
890        }
891        v += n;
892    }
893    Some(v as i64)
894}
895
896/// `php_filter_parse_hex()`.
897fn parse_hex(s: &[u8]) -> Option<i64> {
898    let mut v: u64 = 0;
899    for &c in s {
900        let n = match c {
901            b'0'..=b'9' => c - b'0',
902            b'a'..=b'f' => c - b'a' + 10,
903            b'A'..=b'F' => c - b'A' + 10,
904            _ => return None,
905        };
906        if v > u64::MAX / 16 {
907            return None;
908        }
909        v *= 16;
910        if v > u64::MAX - u64::from(n) {
911            return None;
912        }
913        v += u64::from(n);
914    }
915    Some(v as i64)
916}
917
918/// `php_filter_int()`.
919fn validate_int(s: &[u8], flags: i64, min: Option<i64>, max: Option<i64>) -> Option<i64> {
920    if s.is_empty() {
921        return None;
922    }
923    let p = trim(s);
924    if p.is_empty() {
925        return None;
926    }
927    let value = if p[0] == b'0' {
928        let rest = &p[1..];
929        if flags & FILTER_FLAG_ALLOW_HEX != 0 && matches!(rest.first(), Some(b'x' | b'X')) {
930            if rest.len() == 1 {
931                return None;
932            }
933            parse_hex(&rest[1..])
934        } else if flags & FILTER_FLAG_ALLOW_OCTAL != 0 {
935            let digits = if matches!(rest.first(), Some(b'o' | b'O')) {
936                if rest.len() == 1 {
937                    return None;
938                }
939                &rest[1..]
940            } else {
941                rest
942            };
943            parse_octal(digits)
944        } else if !rest.is_empty() {
945            None
946        } else {
947            Some(0)
948        }
949    } else {
950        parse_int(p)
951    }?;
952    if min.is_some_and(|m| value < m) || max.is_some_and(|m| value > m) {
953        return None;
954    }
955    Some(value)
956}
957
958/// `php_filter_boolean()`.
959fn validate_bool(s: &[u8]) -> Option<bool> {
960    let t = trim(s);
961    let eq = |w: &[u8]| t.eq_ignore_ascii_case(w);
962    match t.len() {
963        0 => Some(false),
964        1 => match t[0] {
965            b'1' => Some(true),
966            b'0' => Some(false),
967            _ => None,
968        },
969        2 if eq(b"on") => Some(true),
970        2 if eq(b"no") => Some(false),
971        3 if eq(b"yes") => Some(true),
972        3 if eq(b"off") => Some(false),
973        4 if eq(b"true") => Some(true),
974        5 if eq(b"false") => Some(false),
975        _ => None,
976    }
977}
978
979/// `php_filter_float()`. Reads past the trimmed range the way the C code
980/// does (the byte after it, or the terminating NUL).
981fn validate_float(s: &[u8], flags: i64, dec_sep: u8, tsd: &[u8], min: Option<f64>, max: Option<f64>) -> Option<f64> {
982    let ws = |b: u8| matches!(b, b' ' | b'\t' | b'\r' | 0x0b | b'\n');
983    let mut start = 0;
984    while start < s.len() && ws(s[start]) {
985        start += 1;
986    }
987    let mut end = s.len();
988    while end > start && ws(s[end - 1]) {
989        end -= 1;
990    }
991    let at = |i: usize| s.get(i).copied().unwrap_or(0);
992    let mut str = start;
993    let mut num: Vec<u8> = Vec::with_capacity(end - start);
994    if str < end && (s[str] == b'+' || s[str] == b'-') {
995        num.push(s[str]);
996        str += 1;
997    }
998    let mut first = true;
999    loop {
1000        let mut n = 0;
1001        while str < end && s[str].is_ascii_digit() {
1002            n += 1;
1003            num.push(s[str]);
1004            str += 1;
1005        }
1006        if str == end || at(str) == dec_sep || at(str) == b'e' || at(str) == b'E' {
1007            if !first && n != 3 {
1008                return None;
1009            }
1010            if at(str) == dec_sep {
1011                num.push(b'.');
1012                str += 1;
1013                while str < end && s[str].is_ascii_digit() {
1014                    num.push(s[str]);
1015                    str += 1;
1016                }
1017            }
1018            if at(str) == b'e' || at(str) == b'E' {
1019                num.push(at(str));
1020                str += 1;
1021                if str < end && (s[str] == b'+' || s[str] == b'-') {
1022                    num.push(s[str]);
1023                    str += 1;
1024                }
1025                while str < end && s[str].is_ascii_digit() {
1026                    num.push(s[str]);
1027                    str += 1;
1028                }
1029            }
1030            break;
1031        }
1032        // strchr() also finds the terminating NUL.
1033        let c = at(str);
1034        if flags & FILTER_FLAG_ALLOW_THOUSAND != 0 && (c == 0 || tsd.contains(&c)) {
1035            if if first { !(1..=3).contains(&n) } else { n != 3 } {
1036                return None;
1037            }
1038            first = false;
1039            str += 1;
1040        } else {
1041            return None;
1042        }
1043    }
1044    if str != end {
1045        return None;
1046    }
1047    let text = std::str::from_utf8(&num).ok()?;
1048    match value::numeric_str(text)? {
1049        value::Number::Int(l) => {
1050            let d = l as f64;
1051            if min.is_some_and(|m| d < m) || max.is_some_and(|m| d > m) {
1052                return None;
1053            }
1054            Some(d)
1055        }
1056        value::Number::Float(d) => {
1057            if (d == 0.0 && num.len() > 1 && num.iter().any(|b| (b'1'..=b'9').contains(b))) || !d.is_finite() {
1058                return None;
1059            }
1060            if min.is_some_and(|m| d < m) || max.is_some_and(|m| d > m) {
1061                return None;
1062            }
1063            Some(d)
1064        }
1065    }
1066}
1067
1068/// `php_filter_validate_domain_ex()`: whether a non-empty string passes
1069/// `filter_var($d, FILTER_VALIDATE_DOMAIN)`, with `FILTER_FLAG_HOSTNAME`
1070/// when `hostname` is set, without building the filter's result.
1071pub fn validate_domain(d: &[u8], hostname: bool) -> bool {
1072    let at = |i: usize| d.get(i).copied().unwrap_or(0);
1073    let alnum = |b: u8| b.is_ascii_alphanumeric();
1074    let mut l = d.len();
1075    let mut e = d.len();
1076    if l > 0 && d[l - 1] == b'.' {
1077        e -= 1;
1078        l -= 1;
1079    }
1080    if l > 253 {
1081        return false;
1082    }
1083    if at(0) == b'.' || (hostname && !alnum(at(0))) {
1084        return false;
1085    }
1086    let mut i: u32 = 1;
1087    let mut s = 0;
1088    while s < e {
1089        if d[s] == b'.' {
1090            if at(s + 1) == b'.' || (hostname && (!alnum(d[s - 1]) || !alnum(at(s + 1)))) {
1091                return false;
1092            }
1093            i = 1;
1094        } else {
1095            if i > 63 || (hostname && (d[s] != b'-' || at(s + 1) == 0) && !alnum(d[s])) {
1096                return false;
1097            }
1098            i += 1;
1099        }
1100        s += 1;
1101    }
1102    true
1103}
1104
1105/// `is_userinfo_valid()`.
1106fn is_userinfo_valid(s: &[u8]) -> bool {
1107    let mut p = 0;
1108    while p < s.len() {
1109        let c = s[p];
1110        if c.is_ascii_alphabetic() || c.is_ascii_digit() || b"-._~!$&'()*+,;=:".contains(&c) {
1111            p += 1;
1112        } else if c == b'%' && p + 3 <= s.len() && s[p + 1].is_ascii_digit() && s[p + 2].is_ascii_hexdigit() {
1113            p += 3;
1114        } else {
1115            return false;
1116        }
1117    }
1118    true
1119}
1120
1121/// Whether `php_filter_url()` (`FILTER_SANITIZE_URL`) keeps the byte.
1122fn is_url_byte(c: u8) -> bool {
1123    c.is_ascii_alphanumeric() || b"$-_.+!*'(),{}|\\^~[]`<>#%\";/?:@&=".contains(&c)
1124}
1125
1126/// `php_filter_validate_url()`: `filter_var($s, FILTER_VALIDATE_URL, $flags)` of a string,
1127/// without the copy of the string it returns; `Err` for an invalid `uri_parser_class`.
1128pub fn validate_url(s: &[u8], flags: i64, parser: Option<&[u8]>) -> Result<bool, Error> {
1129    // PHP sanitizes a copy and fails when that removed anything.
1130    if !s.iter().all(|&c| is_url_byte(c)) {
1131        return Ok(false);
1132    }
1133    /// The components, borrowed from the input.
1134    struct Parts<'a> {
1135        scheme: Option<Cow<'a, [u8]>>,
1136        user: Option<Cow<'a, [u8]>>,
1137        pass: Option<Cow<'a, [u8]>>,
1138        host: Option<Cow<'a, [u8]>>,
1139        path: Option<Cow<'a, [u8]>>,
1140        query: Option<Cow<'a, [u8]>>,
1141    }
1142    let php_parse_url = match parser {
1143        None | Some(b"parse_url") => true,
1144        Some(b"Uri\\Rfc3986\\Uri") => false,
1145        Some(b"Uri\\WhatWg\\Url") => return Err(Error::new("Unsupported", "the WHATWG URL parser")),
1146        Some(_) => return Err(Error::new("ValueError", "filter_var(): \"uri_parser_class\" option has invalid value")),
1147    };
1148    let parts = if php_parse_url {
1149        let Some(u) = url::parse_url(s) else { return Ok(false) };
1150        Parts { scheme: u.scheme(), user: u.user(), pass: u.pass(), host: u.host(), path: u.path(), query: u.query() }
1151    } else {
1152        let Some(u) = url::rfc3986::Uri::parse(s) else { return Ok(false) };
1153        Parts {
1154            scheme: u.raw_scheme(),
1155            user: u.raw_username(),
1156            pass: u.raw_password(),
1157            host: u.raw_host(),
1158            path: Some(u.raw_path()),
1159            query: u.raw_query(),
1160        }
1161    };
1162    if let Some(scheme) = &parts.scheme
1163        && (scheme.eq_ignore_ascii_case(b"http") || scheme.eq_ignore_ascii_case(b"https"))
1164    {
1165        let Some(host) = &parts.host else { return Ok(false) };
1166        if php_parse_url && !is_valid_ipv6_hostname(host) && !validate_domain(host, true) {
1167            return Ok(false);
1168        }
1169    }
1170    let Some(scheme) = &parts.scheme else { return Ok(false) };
1171    if parts.host.is_none() && !matches!(scheme.as_ref(), b"mailto" | b"news" | b"file") {
1172        return Ok(false);
1173    }
1174    if (flags & FILTER_FLAG_PATH_REQUIRED != 0 && parts.path.is_none())
1175        || (flags & FILTER_FLAG_QUERY_REQUIRED != 0 && parts.query.is_none())
1176    {
1177        return Ok(false);
1178    }
1179    if php_parse_url
1180        && (parts.user.as_ref().is_some_and(|u| !is_userinfo_valid(u))
1181            || parts.pass.as_ref().is_some_and(|p| !is_userinfo_valid(p)))
1182    {
1183        return Ok(false);
1184    }
1185    Ok(true)
1186}
1187
1188/// `php_filter_is_valid_ipv6_hostname()`.
1189fn is_valid_ipv6_hostname(s: &[u8]) -> bool {
1190    !s.is_empty() && s[0] == b'[' && s[s.len() - 1] == b']' && s.len() >= 2 && validate_ipv6(&s[1..s.len() - 1], None)
1191}
1192
1193/// `_php_filter_validate_ipv4()`.
1194fn validate_ipv4(s: &[u8], ip: &mut [i32; 4]) -> bool {
1195    let mut i = 0;
1196    let mut n = 0;
1197    while i < s.len() {
1198        if !s[i].is_ascii_digit() {
1199            return false;
1200        }
1201        let leading_zero = s[i] == b'0';
1202        let mut m = 1;
1203        let mut num = i32::from(s[i] - b'0');
1204        i += 1;
1205        while i < s.len() && s[i].is_ascii_digit() {
1206            num = num * 10 + i32::from(s[i] - b'0');
1207            i += 1;
1208            m += 1;
1209            if num > 255 || m > 3 {
1210                return false;
1211            }
1212        }
1213        if leading_zero && (num != 0 || m > 1) {
1214            return false;
1215        }
1216        ip[n] = num;
1217        n += 1;
1218        if n == 4 {
1219            return i == s.len();
1220        } else if i >= s.len() || s[i] != b'.' {
1221            return false;
1222        }
1223        i += 1;
1224    }
1225    false
1226}
1227
1228/// `_php_filter_validate_ipv6()`, filling `ip` like the C code when given.
1229fn validate_ipv6(s: &[u8], mut ip: Option<&mut [i32; 8]>) -> bool {
1230    if !s.contains(&b':') {
1231        return false;
1232    }
1233    let mut compressed_pos: i32 = -1;
1234    let mut blocks: i32 = 0;
1235    let mut ip4elm = [0i32; 4];
1236    let mut len = s.len();
1237    let mut ipv4_at = None;
1238    if let Some(dot) = s.iter().position(|&b| b == b'.') {
1239        let mut v = dot;
1240        while v > 0 && s[v - 1] != b':' {
1241            v -= 1;
1242        }
1243        if !validate_ipv4(&s[v..], &mut ip4elm) {
1244            return false;
1245        }
1246        len = v;
1247        if len < 2 {
1248            return false;
1249        }
1250        if s[v - 2] != b':' {
1251            len -= 1;
1252        }
1253        blocks = 2;
1254        ipv4_at = Some(v);
1255    }
1256    let end = len;
1257    let mut i = 0;
1258    let mut done = false;
1259    while i < end {
1260        if s[i] == b':' {
1261            i += 1;
1262            if i >= end {
1263                return false;
1264            }
1265            if s[i] == b':' {
1266                if compressed_pos >= 0 {
1267                    return false;
1268                }
1269                if let Some(ip) = ip.as_deref_mut()
1270                    && blocks < 8
1271                {
1272                    ip[blocks as usize] = -1;
1273                }
1274                compressed_pos = blocks;
1275                blocks += 1;
1276                i += 1;
1277                if i == end {
1278                    if blocks > 8 {
1279                        return false;
1280                    }
1281                    done = true;
1282                    break;
1283                }
1284            } else if i - 1 == 0 {
1285                return false;
1286            }
1287        }
1288        let mut num: u32 = 0;
1289        let mut n = 0;
1290        while i < end {
1291            let d = match s[i] {
1292                b'0'..=b'9' => u32::from(s[i] - b'0'),
1293                b'a'..=b'f' => u32::from(s[i] - b'a') + 10,
1294                b'A'..=b'F' => u32::from(s[i] - b'A') + 10,
1295                _ => break,
1296            };
1297            num = num.wrapping_mul(16).wrapping_add(d);
1298            n += 1;
1299            i += 1;
1300        }
1301        if let Some(ip) = ip.as_deref_mut()
1302            && blocks < 8
1303        {
1304            ip[blocks as usize] = num as i32;
1305        }
1306        if !(1..=4).contains(&n) {
1307            return false;
1308        }
1309        blocks += 1;
1310        if blocks > 8 {
1311            return false;
1312        }
1313    }
1314    let _ = done;
1315    if let Some(ip) = ip {
1316        if ipv4_at.is_some() {
1317            for x in ip.iter_mut().take(5) {
1318                *x = 0;
1319            }
1320            ip[5] = 0xffff;
1321            ip[6] = 256 * ip4elm[0] + ip4elm[1];
1322            ip[7] = 256 * ip4elm[2] + ip4elm[3];
1323        } else if compressed_pos >= 0 && blocks <= 8 {
1324            let offset = 8 - blocks;
1325            let mut k = 7;
1326            while k > compressed_pos + offset {
1327                ip[k as usize] = ip[(k - offset) as usize];
1328                k -= 1;
1329            }
1330            let mut k = compressed_pos + offset;
1331            while k >= compressed_pos {
1332                ip[k as usize] = 0;
1333                k -= 1;
1334            }
1335        }
1336    }
1337    (compressed_pos >= 0 && blocks <= 8) || blocks == 8
1338}
1339
1340/// `ipv4_get_status_flags()`: `(global, reserved, private)`, or `None`
1341/// for an address in no special block.
1342// One branch per block of PHP's table, in its order.
1343#[allow(clippy::if_same_then_else)]
1344fn ipv4_flags(ip: &[i32; 4]) -> Option<(bool, bool, bool)> {
1345    let r = |g, r, p| Some((g, r, p));
1346    if ip[0] == 0 {
1347        r(false, true, false)
1348    } else if ip[0] == 10 {
1349        r(false, false, true)
1350    } else if ip[0] == 100 && ip[1] >= 64 && ip[1] <= 127 {
1351        r(false, false, false)
1352    } else if ip[0] == 127 {
1353        r(false, true, false)
1354    } else if ip[0] == 169 && ip[1] == 254 {
1355        r(false, true, false)
1356    } else if ip[0] == 172 && ip[1] >= 16 && ip[1] <= 31 {
1357        r(false, false, true)
1358    } else if ip[0] == 192 && ip[1] == 0 && ip[2] == 0 {
1359        r(false, false, false)
1360    } else if ip[0] == 192 && ip[1] == 0 && ip[2] == 2 {
1361        r(false, false, false)
1362    } else if ip[0] == 192 && ip[1] == 88 && ip[2] == 99 {
1363        r(true, false, false)
1364    } else if ip[0] == 192 && ip[1] == 168 {
1365        r(false, false, true)
1366    } else if ip[0] == 198 && ip[1] >= 18 && ip[1] <= 19 {
1367        r(false, false, false)
1368    } else if ip[0] == 198 && ip[1] == 51 && ip[2] == 100 {
1369        r(false, false, false)
1370    } else if ip[0] == 203 && ip[1] == 0 && ip[2] == 113 {
1371        r(false, false, false)
1372    } else if ip[0] >= 240 && ip[1] <= 255 {
1373        r(false, true, false)
1374    } else if ip[0] == 255 && ip[1] == 255 && ip[2] == 255 && ip[3] == 255 {
1375        r(false, true, false)
1376    } else {
1377        None
1378    }
1379}
1380
1381/// `ipv6_get_status_flags()`.
1382// One branch per block of PHP's table, in its order.
1383#[allow(clippy::if_same_then_else)]
1384fn ipv6_flags(ip: &[i32; 8]) -> Option<(bool, bool, bool)> {
1385    let r = |g, r, p| Some((g, r, p));
1386    let zeros = |n: usize| ip[..n].iter().all(|&x| x == 0);
1387    if zeros(8) {
1388        r(false, true, false)
1389    } else if zeros(7) && ip[7] == 1 {
1390        r(false, true, false)
1391    } else if ip[0] == 0x0064 && ip[1] == 0xff9b {
1392        r(true, false, false)
1393    } else if zeros(5) && ip[5] == 0xffff {
1394        r(false, true, false)
1395    } else if ip[0] == 0x0100 && ip[1] == 0 && ip[2] == 0 && ip[3] == 0 {
1396        r(false, false, false)
1397    } else if ip[0] == 0x2001 && ip[1] == 0 {
1398        r(false, false, false)
1399    } else if ip[0] == 0x2001 && ip[1] <= 0x01ff {
1400        r(false, false, false)
1401    } else if ip[0] == 0x2001 && ip[1] == 0x0002 && ip[2] == 0 {
1402        r(false, false, false)
1403    } else if ip[0] == 0x2001 && ip[1] == 0x0db8 {
1404        r(false, false, false)
1405    } else if ip[0] == 0x2001 && ip[1] >= 0x0010 && ip[1] <= 0x001f {
1406        r(false, false, false)
1407    } else if ip[0] == 0x2002 {
1408        r(false, false, false)
1409    } else if ip[0] >= 0xfc00 && ip[0] <= 0xfdff {
1410        r(false, false, true)
1411    } else if ip[0] >= 0xfe80 && ip[0] <= 0xfebf {
1412        r(false, true, false)
1413    } else {
1414        None
1415    }
1416}
1417
1418/// `php_filter_validate_ip()`: whether `filter_var($s, FILTER_VALIDATE_IP, $flags)` of a
1419/// string succeeds, without the copy of the string it returns.
1420pub fn validate_ip(s: &[u8], flags: i64) -> bool {
1421    let v6 = if s.contains(&b':') {
1422        true
1423    } else if s.contains(&b'.') {
1424        false
1425    } else {
1426        return false;
1427    };
1428    let want4 = flags & FILTER_FLAG_IPV4 != 0;
1429    let want6 = flags & FILTER_FLAG_IPV6 != 0;
1430    if !(want4 && want6) && ((want4 && v6) || (want6 && !v6)) {
1431        return false;
1432    }
1433    let status = if v6 {
1434        let mut ip = [0i32; 8];
1435        if !validate_ipv6(s, Some(&mut ip)) {
1436            return false;
1437        }
1438        ipv6_flags(&ip)
1439    } else {
1440        let mut ip = [0i32; 4];
1441        if !validate_ipv4(s, &mut ip) {
1442            return false;
1443        }
1444        ipv4_flags(&ip)
1445    };
1446    let Some((global, reserved, private)) = status else { return true };
1447    if flags & FILTER_FLAG_GLOBAL_RANGE != 0 && !global {
1448        return false;
1449    }
1450    if flags & FILTER_FLAG_NO_PRIV_RANGE != 0 && private {
1451        return false;
1452    }
1453    if flags & FILTER_FLAG_NO_RES_RANGE != 0 && reserved {
1454        return false;
1455    }
1456    true
1457}
1458
1459/// `php_filter_validate_mac()`.
1460fn validate_mac(s: &[u8], expected: Option<u8>) -> bool {
1461    let (tokens, length, separator) = if s.len() == 14 {
1462        (3, 4, b'.')
1463    } else if s.len() == 17 && s[2] == b'-' {
1464        (6, 2, b'-')
1465    } else if s.len() == 17 && s[2] == b':' {
1466        (6, 2, b':')
1467    } else {
1468        return false;
1469    };
1470    if expected.is_some_and(|e| e != separator) {
1471        return false;
1472    }
1473    for i in 0..tokens {
1474        let offset = i * (length + 1);
1475        if i < tokens - 1 && s[offset + length] != separator {
1476            return false;
1477        }
1478        if parse_hex(&s[offset..offset + length]).is_none() {
1479            return false;
1480        }
1481    }
1482    true
1483}
1484
1485#[cfg(test)]
1486mod tests {
1487    use super::*;
1488
1489    fn fv(v: &str, filter: i64, flags: i64) -> Value {
1490        filter_var(&Value::Str(v.as_bytes().to_vec()), filter, &Options::Flags(flags)).unwrap().value
1491    }
1492
1493    #[test]
1494    fn validators() {
1495        assert_eq!(fv(" 42 ", FILTER_VALIDATE_INT, 0), Value::Int(42));
1496        assert_eq!(fv("0x1A", FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX), Value::Int(26));
1497        assert_eq!(fv("012", FILTER_VALIDATE_INT, 0), Value::Bool(false));
1498        assert_eq!(fv("yes", FILTER_VALIDATE_BOOL, 0), Value::Bool(true));
1499        assert_eq!(fv("maybe", FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE), Value::Null);
1500        assert_eq!(fv("1,000.5", FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND), Value::Float(1000.5));
1501        assert_eq!(fv("192.168.0.1", FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE), Value::Bool(false));
1502        assert_eq!(fv("::1", FILTER_VALIDATE_IP, 0), Value::Str(b"::1".to_vec()));
1503        assert_eq!(fv("http://example.com/x", FILTER_VALIDATE_URL, 0), Value::Str(b"http://example.com/x".to_vec()));
1504        assert_eq!(fv("http://exa_mple.com", FILTER_VALIDATE_URL, 0), Value::Bool(false));
1505        assert_eq!(fv("a@b.co", FILTER_VALIDATE_EMAIL, 0), Value::Str(b"a@b.co".to_vec()));
1506        assert_eq!(fv("a@b", FILTER_VALIDATE_EMAIL, 0), Value::Bool(false));
1507        assert_eq!(
1508            fv("ex-ample.com", FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME),
1509            Value::Str(b"ex-ample.com".to_vec())
1510        );
1511        assert_eq!(fv("01:23:45:67:89:ab", FILTER_VALIDATE_MAC, 0), Value::Str(b"01:23:45:67:89:ab".to_vec()));
1512    }
1513}