Skip to main content

php_std/
encoding.rs

1//! Encodings: URL encoding, `http_build_query`, base64, hex, HTML entities
2//! and quoted-printable.
3//!
4//! Ported from PHP 8.5.11 (`ext/standard/url.c`, `http.c`, `base64.c`,
5//! `string.c`, `html.c`, `quot_print.c`). Byte strings in, byte strings out;
6//! encoders whose output is always ASCII return `String`.
7//!
8//! | PHP | Rust |
9//! |---|---|
10//! | `urlencode`, `rawurlencode`, `urldecode`, `rawurldecode` | [`urlencode`], [`rawurlencode`], [`urldecode`], [`rawurldecode`] |
11//! | `http_build_query` | [`http_build_query`] with [`QueryEncoding`] |
12//! | `parse_str` | [`parse_str`] |
13//! | `base64_encode`, `base64_decode` | [`base64_encode`], [`base64_decode`] |
14//! | `bin2hex`, `hex2bin` | [`bin2hex`], [`hex2bin`] |
15//! | `htmlspecialchars`, `htmlentities` | [`htmlspecialchars`], [`htmlentities`] with [`HtmlFlags`] |
16//! | `quoted_printable_encode` | [`quoted_printable_encode`] |
17//!
18//! The HTML functions support PHP's default charset, UTF-8. Their entity
19//! tables (`encoding/html_tables.rs`) are generated by
20//! `data/html_entities.py` from php-src's `ext/standard/html_tables.h` and
21//! PHP's own `get_html_translation_table()` (`data/html_entities.php`).
22
23mod html_tables;
24
25use std::borrow::Cow;
26
27use serde_json::Value;
28
29use crate::number;
30use crate::string::hex_value;
31
32const HEX_UPPER: &[u8; 16] = b"0123456789ABCDEF";
33const HEX_LOWER: &[u8; 16] = b"0123456789abcdef";
34
35// ---------------------------------------------------------------------------
36// URL encoding
37// ---------------------------------------------------------------------------
38
39fn url_encode_into(out: &mut Vec<u8>, s: &[u8], raw: bool) {
40    for &c in s {
41        if !raw && c == b' ' {
42            out.push(b'+');
43        } else if c.is_ascii_alphanumeric() || c == b'-' || c == b'.' || c == b'_' || (raw && c == b'~') {
44            out.push(c);
45        } else {
46            out.extend_from_slice(&[b'%', HEX_UPPER[(c >> 4) as usize], HEX_UPPER[(c & 15) as usize]]);
47        }
48    }
49}
50
51/// PHP `urlencode`: `application/x-www-form-urlencoded` (RFC 1738):
52/// alphanumerics and `-_.` are kept, a space is `+`, every other byte
53/// (including `~`) is `%XX`.
54pub fn urlencode(s: &[u8]) -> String {
55    let mut out = Vec::with_capacity(s.len() * 3);
56    url_encode_into(&mut out, s, false);
57    String::from_utf8(out).unwrap_or_default()
58}
59
60/// PHP `rawurlencode` (RFC 3986): alphanumerics and `-_.~` are kept, every
61/// other byte is `%XX`.
62pub fn rawurlencode(s: &[u8]) -> String {
63    let mut out = Vec::with_capacity(s.len() * 3);
64    url_encode_into(&mut out, s, true);
65    String::from_utf8(out).unwrap_or_default()
66}
67
68fn url_decode(s: &[u8], plus: bool) -> Vec<u8> {
69    let mut out = Vec::with_capacity(s.len());
70    url_decode_into(&mut out, s, plus);
71    out
72}
73
74fn url_decode_into(out: &mut Vec<u8>, s: &[u8], plus: bool) {
75    let mut i = 0;
76    while i < s.len() {
77        let c = s[i];
78        if plus && c == b'+' {
79            out.push(b' ');
80        } else if c == b'%' && i + 2 < s.len() && s[i + 1].is_ascii_hexdigit() && s[i + 2].is_ascii_hexdigit() {
81            out.push(hex_value(s[i + 1]) * 16 + hex_value(s[i + 2]));
82            i += 2;
83        } else {
84            out.push(c);
85        }
86        i += 1;
87    }
88}
89
90/// [`urldecode`], appended to `out` instead of a new buffer.
91pub fn urldecode_into(out: &mut Vec<u8>, s: &[u8]) {
92    url_decode_into(out, s, true);
93}
94
95/// [`rawurldecode`], appended to `out` instead of a new buffer.
96pub fn rawurldecode_into(out: &mut Vec<u8>, s: &[u8]) {
97    url_decode_into(out, s, false);
98}
99
100/// PHP `urldecode`: `+` is a space and `%XX` a byte; a `%` not followed by
101/// two hex digits is kept.
102pub fn urldecode(s: &[u8]) -> Vec<u8> {
103    url_decode(s, true)
104}
105
106/// PHP `rawurldecode`: `%XX` is a byte (`+` stays `+`).
107pub fn rawurldecode(s: &[u8]) -> Vec<u8> {
108    url_decode(s, false)
109}
110
111// ---------------------------------------------------------------------------
112// http_build_query
113// ---------------------------------------------------------------------------
114
115/// `http_build_query()`'s `$encoding_type`.
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
117pub enum QueryEncoding {
118    /// `PHP_QUERY_RFC1738` (1, the default): spaces as `+` ([`urlencode`]).
119    #[default]
120    Rfc1738,
121    /// `PHP_QUERY_RFC3986` (2): spaces as `%20` ([`rawurlencode`]).
122    Rfc3986,
123}
124
125impl QueryEncoding {
126    /// PHP's value: 2 is RFC 3986, and every other integer RFC 1738 (PHP
127    /// does not validate it).
128    pub fn from_php(value: i64) -> Self {
129        if value == 2 { QueryEncoding::Rfc3986 } else { QueryEncoding::Rfc1738 }
130    }
131}
132
133/// Whether a PHP array key string is an integer key (`ZEND_HANDLE_NUMERIC_STR`):
134/// `-?[1-9][0-9]*` or `0`, within `i64`.
135pub fn is_integer_key(key: &str) -> bool {
136    let digits = key.strip_prefix('-').unwrap_or(key);
137    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
138        return false;
139    }
140    if digits.starts_with('0') && key.len() > 1 {
141        return false;
142    }
143    key.parse::<i64>().is_ok()
144}
145
146struct QueryBuilder<'a> {
147    out: Vec<u8>,
148    separator: &'a [u8],
149    raw: bool,
150}
151
152impl QueryBuilder<'_> {
153    fn scalar(&mut self, key: &str, value: &Value, prefix: Option<&[u8]>, numeric_prefix: Option<&[u8]>) {
154        if !self.out.is_empty() {
155            self.out.extend_from_slice(self.separator);
156        }
157        if let Some(p) = prefix {
158            self.out.extend_from_slice(p);
159        }
160        if is_integer_key(key) {
161            if let Some(np) = numeric_prefix {
162                self.out.extend_from_slice(np);
163            }
164            self.out.extend_from_slice(key.as_bytes());
165        } else {
166            url_encode_into(&mut self.out, key.as_bytes(), self.raw);
167        }
168        if prefix.is_some() {
169            self.out.extend_from_slice(b"%5D");
170        }
171        self.out.push(b'=');
172        match value {
173            Value::String(s) => url_encode_into(&mut self.out, s.as_bytes(), self.raw),
174            Value::Number(n) => match crate::value::json_number(n) {
175                crate::value::Number::Int(i) => self.out.extend_from_slice(i.to_string().as_bytes()),
176                crate::value::Number::Float(f) => {
177                    url_encode_into(&mut self.out, number::to_string(f).as_bytes(), self.raw)
178                }
179            },
180            Value::Bool(b) => self.out.push(if *b { b'1' } else { b'0' }),
181            _ => {}
182        }
183    }
184
185    fn hash(&mut self, data: &Value, prefix: Option<&[u8]>, numeric_prefix: Option<&[u8]>) {
186        let entries: Vec<(Cow<'_, str>, &Value)> = match data {
187            Value::Array(a) => a.iter().enumerate().map(|(i, v)| (Cow::Owned(i.to_string()), v)).collect(),
188            Value::Object(o) => o.iter().map(|(k, v)| (Cow::Borrowed(k.as_str()), v)).collect(),
189            _ => return,
190        };
191        for (key, value) in entries {
192            match value {
193                Value::Array(_) | Value::Object(_) => {
194                    let mut next = Vec::new();
195                    if is_integer_key(&key) {
196                        match (prefix, numeric_prefix) {
197                            (Some(p), Some(np)) => {
198                                next.extend_from_slice(p);
199                                next.extend_from_slice(np);
200                                next.extend_from_slice(key.as_bytes());
201                                next.extend_from_slice(b"%5D%5B");
202                            }
203                            (Some(p), None) => {
204                                next.extend_from_slice(p);
205                                next.extend_from_slice(key.as_bytes());
206                                next.extend_from_slice(b"%5D%5B");
207                            }
208                            (None, Some(np)) => {
209                                next.extend_from_slice(np);
210                                next.extend_from_slice(key.as_bytes());
211                                next.extend_from_slice(b"%5B");
212                            }
213                            (None, None) => {
214                                next.extend_from_slice(key.as_bytes());
215                                next.extend_from_slice(b"%5B");
216                            }
217                        }
218                    } else {
219                        let mut encoded = Vec::new();
220                        url_encode_into(&mut encoded, key.as_bytes(), self.raw);
221                        match prefix {
222                            Some(p) => {
223                                next.extend_from_slice(p);
224                                next.extend_from_slice(&encoded);
225                                next.extend_from_slice(b"%5D%5B");
226                            }
227                            None => {
228                                next.extend_from_slice(&encoded);
229                                next.extend_from_slice(b"%5B");
230                            }
231                        }
232                    }
233                    self.hash(value, Some(&next), None);
234                }
235                Value::Null => {}
236                _ => self.scalar(&key, value, prefix, numeric_prefix),
237            }
238        }
239    }
240}
241
242/// PHP `http_build_query($data, $numeric_prefix, $arg_separator, $encoding_type)`
243/// for data decoded from JSON (objects are PHP arrays; keys that are
244/// canonical integers are integer keys, which get `numeric_prefix` at the
245/// top level). Nested arrays become `a%5Bb%5D=...`; `null` values are
246/// skipped, booleans are `1`/`0`, floats use the `precision` setting.
247/// `arg_separator` `None` is PHP's `arg_separator.output` default, `&`.
248pub fn http_build_query(
249    data: &Value,
250    numeric_prefix: &[u8],
251    arg_separator: Option<&[u8]>,
252    encoding: QueryEncoding,
253) -> Vec<u8> {
254    let mut b = QueryBuilder {
255        out: Vec::new(),
256        separator: arg_separator.unwrap_or(b"&"),
257        raw: encoding == QueryEncoding::Rfc3986,
258    };
259    b.hash(data, None, Some(numeric_prefix));
260    b.out
261}
262
263// ---------------------------------------------------------------------------
264// base64 and hex
265// ---------------------------------------------------------------------------
266
267const BASE64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
268
269/// PHP `base64_encode`: standard alphabet with `=` padding.
270pub fn base64_encode(s: &[u8]) -> String {
271    let mut out = String::with_capacity(s.len().div_ceil(3) * 4);
272    for chunk in s.chunks(3) {
273        let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
274        out.push(BASE64[(b[0] >> 2) as usize] as char);
275        out.push(BASE64[(((b[0] & 0x03) << 4) | (b[1] >> 4)) as usize] as char);
276        out.push(if chunk.len() > 1 { BASE64[(((b[1] & 0x0f) << 2) | (b[2] >> 6)) as usize] as char } else { '=' });
277        out.push(if chunk.len() > 2 { BASE64[(b[2] & 0x3f) as usize] as char } else { '=' });
278    }
279    out
280}
281
282/// `base64_reverse_table`: a value, -1 for skipped white space, -2 otherwise.
283const fn base64_value(c: u8) -> i32 {
284    match c {
285        b'A'..=b'Z' => (c - b'A') as i32,
286        b'a'..=b'z' => (c - b'a') as i32 + 26,
287        b'0'..=b'9' => (c - b'0') as i32 + 52,
288        b'+' => 62,
289        b'/' => 63,
290        b'\t' | b'\n' | b'\r' | b' ' => -1,
291        _ => -2,
292    }
293}
294
295/// [`base64_value`] of every byte (negative: not in the alphabet).
296const BASE64_VALUES: [i8; 256] = {
297    let mut t = [-2i8; 256];
298    let mut c = 0;
299    while c < 256 {
300        t[c] = base64_value(c as u8) as i8;
301        c += 1;
302    }
303    t
304};
305
306/// PHP `base64_decode($string, $strict)`. Non-strict skips every byte that
307/// is not in the alphabet (and decodes data after `=` padding); strict skips
308/// only `\t \n \r` and spaces and fails (`None`, PHP's `false`) on anything
309/// else, on data after padding, on a lone final character or on bad padding.
310pub fn base64_decode(s: &[u8], strict: bool) -> Option<Vec<u8>> {
311    let mut out: Vec<u8> = Vec::with_capacity(s.len() / 4 * 3 + 3);
312    let put = |out: &mut Vec<u8>, j: usize, v: u8, or: bool| {
313        if j == out.len() {
314            out.push(0);
315        }
316        if or { out[j] |= v } else { out[j] = v }
317    };
318    // The bulk: whole groups of four alphabet characters from the start,
319    // three bytes each.
320    let mut k = 0;
321    while let Some(g) = s.get(k..k + 4) {
322        let v = |n: usize| BASE64_VALUES[g[n] as usize];
323        let (a, b, c, d) = (v(0), v(1), v(2), v(3));
324        if (a | b | c | d) < 0 {
325            break;
326        }
327        let (a, b, c, d) = (a as u8, b as u8, c as u8, d as u8);
328        out.extend_from_slice(&[a << 2 | b >> 4, b << 4 | c >> 2, c << 6 | d]);
329        k += 4;
330    }
331    let (mut i, mut padding, mut j) = (k, 0usize, out.len());
332    while k < s.len() {
333        // Four alphabet characters at a group boundary: three bytes at once.
334        if i.is_multiple_of(4) && (!strict || padding == 0) && k + 4 <= s.len() {
335            let v = |n: usize| BASE64_VALUES[s[k + n] as usize];
336            let (a, b, c, d) = (v(0), v(1), v(2), v(3));
337            if (a | b | c | d) >= 0 {
338                let (a, b, c, d) = (a as u8, b as u8, c as u8, d as u8);
339                out.extend_from_slice(&[a << 2 | b >> 4, b << 4 | c >> 2, c << 6 | d]);
340                j += 3;
341                i += 4;
342                k += 4;
343                continue;
344            }
345        }
346        let c = s[k];
347        k += 1;
348        if c == b'=' {
349            padding += 1;
350            continue;
351        }
352        let ch = base64_value(c);
353        if !strict {
354            if ch < 0 {
355                continue;
356            }
357        } else {
358            if ch == -1 {
359                continue;
360            }
361            if ch == -2 || padding > 0 {
362                return None;
363            }
364        }
365        let ch = ch as u8;
366        match i % 4 {
367            0 => put(&mut out, j, ch << 2, false),
368            1 => {
369                put(&mut out, j, ch >> 4, true);
370                j += 1;
371                put(&mut out, j, (ch & 0x0f) << 4, false);
372            }
373            2 => {
374                put(&mut out, j, ch >> 2, true);
375                j += 1;
376                put(&mut out, j, (ch & 0x03) << 6, false);
377            }
378            _ => {
379                put(&mut out, j, ch, true);
380                j += 1;
381            }
382        }
383        i += 1;
384    }
385    if strict && i % 4 == 1 {
386        return None;
387    }
388    if strict && padding > 0 && (padding > 2 || (i + padding) % 4 != 0) {
389        return None;
390    }
391    out.truncate(j);
392    Some(out)
393}
394
395/// PHP `bin2hex`: lowercase hexadecimal.
396pub fn bin2hex(s: &[u8]) -> String {
397    let mut out = String::with_capacity(s.len() * 2);
398    for &b in s {
399        out.push(HEX_LOWER[(b >> 4) as usize] as char);
400        out.push(HEX_LOWER[(b & 15) as usize] as char);
401    }
402    out
403}
404
405/// PHP `hex2bin`: `None` (PHP's `false`, with a warning) for an odd length
406/// or a non-hexadecimal character.
407pub fn hex2bin(s: &[u8]) -> Option<Vec<u8>> {
408    if !s.len().is_multiple_of(2) || !s.iter().all(u8::is_ascii_hexdigit) {
409        return None;
410    }
411    Some(s.chunks(2).map(|p| hex_value(p[0]) * 16 + hex_value(p[1])).collect())
412}
413
414// ---------------------------------------------------------------------------
415// Slashes and quoted-printable
416// ---------------------------------------------------------------------------
417
418/// PHP `quoted_printable_encode` (RFC 2045, lines of at most 76 bytes with
419/// PHP's look-ahead for multi-byte UTF-8 lead bytes).
420pub fn quoted_printable_encode(s: &[u8]) -> Vec<u8> {
421    const MAXL: u64 = 75;
422    let mut out = Vec::with_capacity(s.len() * 3);
423    let mut lp: u64 = 0;
424    let mut i = 0;
425    let at = |k: usize| s.get(k).copied().unwrap_or(0);
426    while i < s.len() {
427        let c = s[i];
428        i += 1;
429        let remaining = s.len() - i;
430        if c == b'\r' && at(i) == b'\n' && remaining > 0 {
431            out.extend_from_slice(b"\r\n");
432            i += 1;
433            lp = 0;
434        } else if c < 32 || c == 0x7f || c & 0x80 != 0 || c == b'=' || (c == b' ' && at(i) == b'\r') {
435            lp += 3;
436            if (lp > MAXL && c <= 0x7f)
437                || (c > 0x7f && c <= 0xdf && lp + 3 > MAXL)
438                || (c > 0xdf && c <= 0xef && lp + 6 > MAXL)
439                || (c > 0xef && c <= 0xf4 && lp + 9 > MAXL)
440            {
441                out.extend_from_slice(b"=\r\n");
442                lp = 3;
443            }
444            out.extend_from_slice(&[b'=', HEX_UPPER[(c >> 4) as usize], HEX_UPPER[(c & 15) as usize]]);
445        } else {
446            lp += 1;
447            if lp > MAXL {
448                out.extend_from_slice(b"=\r\n");
449                lp = 1;
450            }
451            out.push(c);
452        }
453    }
454    out
455}
456
457// ---------------------------------------------------------------------------
458// HTML entities
459// ---------------------------------------------------------------------------
460
461/// The document type of the `ENT_HTML401`/`ENT_XML1`/`ENT_XHTML`/`ENT_HTML5` flags.
462#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
463pub enum Doctype {
464    /// `ENT_HTML401` (0), the default.
465    #[default]
466    Html401,
467    /// `ENT_XML1` (16).
468    Xml1,
469    /// `ENT_XHTML` (32).
470    Xhtml,
471    /// `ENT_HTML5` (48).
472    Html5,
473}
474
475/// The `$flags` of the HTML functions, decoded from PHP's bit mask.
476#[derive(Debug, Clone, Copy, PartialEq, Eq)]
477pub struct HtmlFlags {
478    /// `ENT_HTML_QUOTE_SINGLE` (1): convert `'`.
479    pub single_quotes: bool,
480    /// `ENT_HTML_QUOTE_DOUBLE` (2, `ENT_COMPAT`): convert `"`.
481    pub double_quotes: bool,
482    /// `ENT_IGNORE` (4): drop invalid UTF-8 (wins over `substitute`).
483    pub ignore: bool,
484    /// `ENT_SUBSTITUTE` (8): replace invalid UTF-8 with U+FFFD. Without it
485    /// (and without `ignore`) invalid UTF-8 makes the result empty.
486    pub substitute: bool,
487    /// `ENT_DISALLOWED` (128): replace code points the doctype disallows.
488    pub disallowed: bool,
489    /// The document type (`ENT_HTML401`, `ENT_XML1`, `ENT_XHTML` or `ENT_HTML5`).
490    pub doctype: Doctype,
491}
492
493impl HtmlFlags {
494    /// PHP's default, `ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401`.
495    pub const DEFAULT: Self = Self::from_php(3 | 8);
496
497    /// The flags of PHP's integer `$flags` (other bits are ignored, as in PHP).
498    pub const fn from_php(flags: i64) -> Self {
499        HtmlFlags {
500            single_quotes: flags & 1 != 0,
501            double_quotes: flags & 2 != 0,
502            ignore: flags & 4 != 0,
503            substitute: flags & 8 != 0,
504            disallowed: flags & 128 != 0,
505            doctype: match flags & 48 {
506                0 => Doctype::Html401,
507                16 => Doctype::Xml1,
508                32 => Doctype::Xhtml,
509                _ => Doctype::Html5,
510            },
511        }
512    }
513}
514
515impl Default for HtmlFlags {
516    /// PHP's default flags, [`HtmlFlags::DEFAULT`].
517    fn default() -> Self {
518        Self::DEFAULT
519    }
520}
521
522/// `get_next_char` for UTF-8: a code point, or how many bytes an invalid
523/// sequence spans (PHP's "strategy 2" of UTR #36).
524fn next_utf8(s: &[u8], pos: usize) -> Result<(u32, usize), usize> {
525    let avail = s.len() - pos;
526    let c = s[pos];
527    let lead = |b: u8| b < 0x80 || (0xC2..=0xF4).contains(&b);
528    let trail = |b: u8| (0x80..=0xBF).contains(&b);
529    if c < 0x80 {
530        return Ok((c as u32, 1));
531    }
532    if c < 0xC2 {
533        return Err(1);
534    }
535    if c < 0xE0 {
536        if avail < 2 {
537            return Err(1);
538        }
539        if !trail(s[pos + 1]) {
540            return Err(if lead(s[pos + 1]) { 1 } else { 2 });
541        }
542        return Ok((((c as u32 & 0x1F) << 6) | (s[pos + 1] as u32 & 0x3F), 2));
543    }
544    if c < 0xF0 {
545        if avail < 3 || !trail(s[pos + 1]) || !trail(s[pos + 2]) {
546            return Err(if avail < 2 || lead(s[pos + 1]) {
547                1
548            } else if avail < 3 || lead(s[pos + 2]) {
549                2
550            } else {
551                3
552            });
553        }
554        let cp = ((c as u32 & 0x0F) << 12) | ((s[pos + 1] as u32 & 0x3F) << 6) | (s[pos + 2] as u32 & 0x3F);
555        if cp < 0x800 || (0xD800..=0xDFFF).contains(&cp) {
556            return Err(3);
557        }
558        return Ok((cp, 3));
559    }
560    if c < 0xF5 {
561        if avail < 4 || !trail(s[pos + 1]) || !trail(s[pos + 2]) || !trail(s[pos + 3]) {
562            return Err(if avail < 2 || lead(s[pos + 1]) {
563                1
564            } else if avail < 3 || lead(s[pos + 2]) {
565                2
566            } else if avail < 4 || lead(s[pos + 3]) {
567                3
568            } else {
569                4
570            });
571        }
572        let cp = ((c as u32 & 0x07) << 18)
573            | ((s[pos + 1] as u32 & 0x3F) << 12)
574            | ((s[pos + 2] as u32 & 0x3F) << 6)
575            | (s[pos + 3] as u32 & 0x3F);
576        if !(0x10000..=0x10FFFF).contains(&cp) {
577            return Err(4);
578        }
579        return Ok((cp, 4));
580    }
581    Err(1)
582}
583
584/// `unicode_cp_is_allowed`.
585fn cp_allowed(cp: u32, doctype: Doctype) -> bool {
586    match doctype {
587        Doctype::Html401 => {
588            (0x20..=0x7E).contains(&cp)
589                || cp == 0x0A
590                || cp == 0x09
591                || cp == 0x0D
592                || (0xA0..=0xD7FF).contains(&cp)
593                || (0xE000..=0x10FFFF).contains(&cp)
594        }
595        Doctype::Html5 => {
596            (0x20..=0x7E).contains(&cp)
597                || ((0x09..=0x0D).contains(&cp) && cp != 0x0B)
598                || (0xA0..=0xD7FF).contains(&cp)
599                || ((0xE000..=0x10FFFF).contains(&cp) && (cp & 0xFFFF) < 0xFFFE && !(0xFDD0..=0xFDEF).contains(&cp))
600        }
601        Doctype::Xhtml | Doctype::Xml1 => {
602            (0x20..=0xD7FF).contains(&cp)
603                || cp == 0x0A
604                || cp == 0x09
605                || cp == 0x0D
606                || ((0xE000..=0x10FFFF).contains(&cp) && cp != 0xFFFE && cp != 0xFFFF)
607        }
608    }
609}
610
611/// `numeric_entity_is_allowed`.
612fn numeric_allowed(cp: u32, doctype: Doctype) -> bool {
613    match doctype {
614        Doctype::Html401 => cp <= 0x10FFFF,
615        Doctype::Html5 => {
616            (0x20..=0x7E).contains(&cp)
617                || ((0x09..=0x0C).contains(&cp) && cp != 0x0B)
618                || ((0xA0..=0x10FFFF).contains(&cp) && (cp & 0xFFFF) < 0xFFFE && !(0xFDD0..=0xFDEF).contains(&cp))
619        }
620        Doctype::Xhtml | Doctype::Xml1 => cp_allowed(cp, doctype),
621    }
622}
623
624/// `process_numeric_entity` from `pos` (just after `&#`): the code point and
625/// the position of the closing `;`. Digits are read like C `strtol` (which
626/// also accepts a `0x` prefix in hexadecimal entities).
627fn numeric_entity(s: &[u8], pos: usize) -> Option<(u32, usize)> {
628    let at = |k: usize| s.get(k).copied().unwrap_or(0);
629    let mut p = pos;
630    let hex = at(p) == b'x' || at(p) == b'X';
631    if hex {
632        p += 1;
633    }
634    if (hex && !at(p).is_ascii_hexdigit()) || (!hex && !at(p).is_ascii_digit()) {
635        return None;
636    }
637    let base: u64 = if hex { 16 } else { 10 };
638    if hex && at(p) == b'0' && at(p + 1) | 32 == b'x' {
639        if at(p + 2).is_ascii_hexdigit() {
640            p += 2;
641        } else {
642            // strtol stops after the "0"
643            return if at(p + 1) == b';' { Some((0, p + 1)) } else { None };
644        }
645    }
646    let mut value: u64 = 0;
647    while at(p).is_ascii_hexdigit() && (hex || at(p).is_ascii_digit()) {
648        value = value.saturating_mul(base).saturating_add(hex_value(at(p)) as u64);
649        p += 1;
650    }
651    if at(p) != b';' || value > 0x10FFFF {
652        return None;
653    }
654    Some((value as u32, p))
655}
656
657/// `process_named_entity_html` from `pos` (just after `&`): the name's end
658/// (the `;`), for `[A-Za-z0-9]+;`.
659fn named_entity(s: &[u8], pos: usize) -> Option<usize> {
660    let mut p = pos;
661    while p < s.len() && s[p].is_ascii_alphanumeric() {
662        p += 1;
663    }
664    if p == pos || s.get(p) != Some(&b';') {
665        return None;
666    }
667    Some(p)
668}
669
670fn decode_table(doctype: Doctype) -> &'static [(&'static str, u32, u32)] {
671    match doctype {
672        Doctype::Html5 => html_tables::HTML5_DECODE,
673        _ => html_tables::HTML401_DECODE,
674    }
675}
676
677/// A named entity for decoding (`resolve_named_entity_html`): `all` selects
678/// the doctype's full table, else (and for XML 1.0) the basic entities.
679fn resolve_named(name: &[u8], all: bool, doctype: Doctype) -> Option<(u32, u32)> {
680    let basic = |apos: bool| -> Option<(u32, u32)> {
681        Some(match name {
682            b"quot" => (0x22, 0),
683            b"amp" => (0x26, 0),
684            b"lt" => (0x3C, 0),
685            b"gt" => (0x3E, 0),
686            b"apos" if apos => (0x27, 0),
687            b"#039" if !apos => (0x27, 0),
688            _ => return None,
689        })
690    };
691    if !all {
692        return basic(doctype != Doctype::Html401);
693    }
694    match doctype {
695        Doctype::Xml1 => basic(true),
696        _ => {
697            let table = decode_table(doctype);
698            table.binary_search_by(|(n, _, _)| n.as_bytes().cmp(name)).ok().map(|i| (table[i].1, table[i].2))
699        }
700    }
701}
702
703/// The basic entity of a character (`stage3_table_be_*`): XHTML, XML 1.0
704/// and HTML5 use `apos`, HTML 4.01 `#039`.
705fn basic_entity(c: u32, doctype: Doctype) -> Option<&'static str> {
706    match c {
707        0x22 => Some("quot"),
708        0x26 => Some("amp"),
709        0x27 => Some(if doctype == Doctype::Html401 { "#039" } else { "apos" }),
710        0x3C => Some("lt"),
711        0x3E => Some("gt"),
712        _ => None,
713    }
714}
715
716fn escape(s: &[u8], flags: HtmlFlags, double_encode: bool, all: bool) -> Vec<u8> {
717    let doctype = flags.doctype;
718    let all = all && doctype != Doctype::Xml1;
719    let mut out = Vec::with_capacity(s.len() + s.len() / 4 + 16);
720    let mut cursor = 0;
721    while cursor < s.len() {
722        let before = cursor;
723        let (c, len) = match next_utf8(s, cursor) {
724            Ok(v) => v,
725            Err(advance) => {
726                cursor += advance;
727                if flags.ignore {
728                    continue;
729                } else if flags.substitute {
730                    out.extend_from_slice("\u{FFFD}".as_bytes());
731                    continue;
732                }
733                return Vec::new();
734            }
735        };
736        cursor += len;
737        if c != u32::from(b'&') {
738            if (c == 0x27 && !flags.single_quotes) || (c == 0x22 && !flags.double_quotes) {
739                out.extend_from_slice(&s[before..cursor]);
740                continue;
741            }
742            let entity: Option<&str> = if all {
743                if doctype == Doctype::Html5 {
744                    let pair = html_tables::HTML5_ENCODE_PAIRS.iter().any(|&(a, _, _)| a == c);
745                    let mut found = None;
746                    if pair
747                        && cursor < s.len()
748                        && let Ok((next, next_len)) = next_utf8(s, cursor)
749                        && let Some(&(_, _, name)) =
750                            html_tables::HTML5_ENCODE_PAIRS.iter().find(|&&(a, b, _)| a == c && b == next)
751                    {
752                        found = Some(name);
753                        cursor += next_len;
754                    }
755                    found.or_else(|| lookup_encode(html_tables::HTML5_ENCODE, c))
756                } else {
757                    lookup_encode(html_tables::HTML401_ENCODE, c)
758                }
759            } else {
760                basic_entity(c, doctype)
761            };
762            match entity {
763                Some(name) => {
764                    out.push(b'&');
765                    out.extend_from_slice(name.as_bytes());
766                    out.push(b';');
767                }
768                None => {
769                    if flags.disallowed && !cp_allowed(c, doctype) {
770                        out.extend_from_slice("\u{FFFD}".as_bytes());
771                    } else {
772                        out.extend_from_slice(&s[before..cursor]);
773                    }
774                }
775            }
776            continue;
777        }
778        // '&'
779        if !double_encode {
780            let valid_end = if s.get(cursor) == Some(&b'#') {
781                numeric_entity(s, cursor + 1)
782                    .filter(|&(cp, _)| !flags.disallowed || numeric_allowed(cp, doctype))
783                    .map(|(_, e)| e)
784            } else {
785                named_entity(s, cursor).filter(|&end| {
786                    let name = &s[cursor..end];
787                    resolve_named(name, true, doctype).is_some() || (doctype == Doctype::Xhtml && name == b"apos")
788                })
789            };
790            if let Some(end) = valid_end {
791                out.push(b'&');
792                out.extend_from_slice(&s[cursor..end]);
793                out.push(b';');
794                cursor = end + 1;
795                continue;
796            }
797        }
798        out.extend_from_slice(b"&amp;");
799    }
800    out
801}
802
803fn lookup_encode(table: &[(u32, &'static str)], c: u32) -> Option<&'static str> {
804    table.binary_search_by_key(&c, |&(k, _)| k).ok().map(|i| table[i].1)
805}
806
807/// PHP `htmlspecialchars($string, $flags, 'UTF-8', $double_encode)`:
808/// escapes `& < >` and the quotes `flags` selects (`'` as `&#039;` in HTML
809/// 4.01, `&apos;` otherwise). With `double_encode` false, existing valid
810/// entities are kept. Invalid UTF-8 follows `ENT_IGNORE`/`ENT_SUBSTITUTE`,
811/// else the result is empty.
812pub fn htmlspecialchars(s: &[u8], flags: HtmlFlags, double_encode: bool) -> Vec<u8> {
813    escape(s, flags, double_encode, false)
814}
815
816/// PHP `htmlentities($string, $flags, 'UTF-8', $double_encode)`: like
817/// [`htmlspecialchars`] but every character with a named entity in the
818/// doctype's table is converted (HTML 4.01 and XHTML: 253 entities, HTML5:
819/// 1511 including two-character ones such as `fj`; XML 1.0: the basic ones).
820pub fn htmlentities(s: &[u8], flags: HtmlFlags, double_encode: bool) -> Vec<u8> {
821    escape(s, flags, double_encode, true)
822}
823
824// ---------------------------------------------------------------------------
825// parse_str and request variable registration (main/php_variables.c)
826// ---------------------------------------------------------------------------
827
828/// `max_input_vars`: variables registered per input, PHP's default.
829pub const MAX_INPUT_VARS: usize = 1000;
830
831/// `max_input_nesting_level`: bracket levels in a variable name, PHP's default.
832pub const MAX_INPUT_NESTING_LEVEL: usize = 64;
833
834/// `parse_str($string, $result)`: `php_default_treat_data(PARSE_STRING)`
835/// with the default `arg_separator.input` (`&`), `max_input_vars` and
836/// `max_input_nesting_level`. Also how Swoole fills `$request->get` and,
837/// for `application/x-www-form-urlencoded` bodies, `$request->post`.
838///
839/// The input is a C string to the engine: it ends at the first NUL byte.
840pub fn parse_str(input: &[u8]) -> crate::types::Array {
841    let input = c_str(input);
842    let mut array = crate::types::Array::new();
843    let mut count = 0usize;
844    for var in input.split(|&b| b == b'&').filter(|t| !t.is_empty()) {
845        count += 1;
846        if count > MAX_INPUT_VARS {
847            break;
848        }
849        let (name, value) = match var.iter().position(|&b| b == b'=') {
850            Some(eq) => (&var[..eq], urldecode(&var[eq + 1..])),
851            None => (var, Vec::new()),
852        };
853        let name = urldecode(name);
854        register_variable(&mut array, &name, crate::types::Value::Str(value.into()), false);
855    }
856    array
857}
858
859/// `php_register_variable_ex($name, $value, $array)`: registers one request
860/// variable the way PHP fills `$_GET`, `$_POST` and `$_COOKIE`. Leading
861/// spaces are dropped, `.` and ` ` in the base name become `_`, `name[a][]`
862/// builds nested arrays (at most [`MAX_INPUT_NESTING_LEVEL`] levels; deeper
863/// names drop the whole variable), and an unterminated `[` is kept as `_`.
864///
865/// `keep_existing` is the `$_COOKIE` rule: a top-level name that is already
866/// set is not overwritten.
867pub fn register_variable(
868    array: &mut crate::types::Array,
869    name: &[u8],
870    value: crate::types::Value,
871    keep_existing: bool,
872) {
873    use crate::types::{Array, ArrayKey as Key, Value};
874    let key_of = |b: &[u8]| Key::normalize(crate::types::Str::copy_from(b));
875
876    // The engine works on a NUL-terminated copy: everything from a NUL on is ignored.
877    let mut var: Vec<u8> = c_str(name).iter().copied().skip_while(|&b| b == b' ').collect();
878    let len_at = |buf: &[u8], from: usize| buf[from..].iter().position(|&b| b == 0).unwrap_or(buf.len() - from);
879    var.push(0);
880
881    let mut ip: Option<usize> = None;
882    let mut p = 0;
883    while var[p] != 0 {
884        match var[p] {
885            b' ' | b'.' => var[p] = b'_',
886            b'[' => {
887                ip = Some(p);
888                var[p] = 0;
889                break;
890            }
891            _ => {}
892        }
893        p += 1;
894    }
895    let var_len = p;
896    if var_len == 0 {
897        return;
898    }
899
900    // `index` is (start, len) into `var`, or None for `[]`.
901    let mut index: Option<(usize, usize)> = Some((0, var_len));
902    // Keys from the root to the array being filled.
903    let mut path: Vec<Key> = Vec::new();
904    let root_key = key_of(&var[..var_len]);
905
906    if let Some(mut ip) = ip {
907        let mut nest_level = 0;
908        loop {
909            nest_level += 1;
910            if nest_level > MAX_INPUT_NESTING_LEVEL {
911                array.remove(&root_key);
912                return;
913            }
914            ip += 1;
915            let mut index_s = Some(ip);
916            if var[ip] == b' ' {
917                ip += 1;
918            }
919            let new_idx_len;
920            if var[ip] == b']' {
921                index_s = None;
922                new_idx_len = 0;
923            } else {
924                match var[ip..].iter().position(|&b| b == b']' || b == 0).filter(|&o| var[ip + o] == b']') {
925                    Some(o) => {
926                        ip += o;
927                        var[ip] = 0;
928                        new_idx_len = len_at(&var, index_s.unwrap_or(ip));
929                    }
930                    None => {
931                        // Not an index: un-terminate the name and keep it as a plain variable.
932                        let s = index_s.unwrap_or(ip);
933                        var[s - 1] = b'_';
934                        let mut q = s;
935                        while var[q] != 0 {
936                            if matches!(var[q], b' ' | b'.' | b'[') {
937                                var[q] = b'_';
938                            }
939                            q += 1;
940                        }
941                        if let Some((start, _)) = index {
942                            index = Some((start, len_at(&var, start)));
943                        }
944                        break;
945                    }
946                }
947            }
948
949            // Descend into (or create) the array at `index`.
950            let table = table_at(array, &path);
951            let key = match index {
952                None => {
953                    let k = table.next_index().unwrap_or(0);
954                    if table.push(Value::Array(Array::new())).is_err() {
955                        return;
956                    }
957                    Key::Int(k)
958                }
959                Some((start, len)) => {
960                    let key = key_of(&var[start..start + len]);
961                    match table.get_mut(&key) {
962                        Some(Value::Array(_)) => {}
963                        Some(other) => *other = Value::Array(Array::new()),
964                        None => {
965                            table.set(key.clone(), Value::Array(Array::new()));
966                        }
967                    }
968                    key
969                }
970            };
971            path.push(key);
972            index = index_s.map(|s| (s, new_idx_len));
973
974            ip += 1;
975            if var[ip] == b'[' {
976                var[ip] = 0;
977            } else {
978                break;
979            }
980        }
981    }
982
983    let table = table_at(array, &path);
984    match index {
985        None => {
986            let _ = table.push(value);
987        }
988        Some((start, len)) => {
989            let key = key_of(&var[start..start + len]);
990            if keep_existing && path.is_empty() && table.get(&key).is_some() {
991                return;
992            }
993            table.set(key, value);
994        }
995    }
996}
997
998/// The nested array `path` leads to (every step is an array by construction).
999fn table_at<'a>(array: &'a mut crate::types::Array, path: &[crate::types::ArrayKey]) -> &'a mut crate::types::Array {
1000    let mut table = array;
1001    for key in path {
1002        match table.get_mut(key) {
1003            Some(crate::types::Value::Array(next)) => table = next,
1004            _ => unreachable!("register_variable path steps are arrays"),
1005        }
1006    }
1007    table
1008}
1009
1010/// The bytes before the first NUL (how the engine sees a C string).
1011fn c_str(s: &[u8]) -> &[u8] {
1012    match s.iter().position(|&b| b == 0) {
1013        Some(n) => &s[..n],
1014        None => s,
1015    }
1016}
1017
1018#[cfg(test)]
1019mod tests {
1020    use super::*;
1021    use serde_json::json;
1022
1023    #[test]
1024    fn url_like_php() {
1025        assert_eq!(urlencode(b"a b~c&"), "a+b%7Ec%26");
1026        assert_eq!(rawurlencode(b"a b~c&"), "a%20b~c%26");
1027        assert_eq!(urldecode(b"a+b%2"), b"a b%2");
1028    }
1029
1030    #[test]
1031    fn query_like_php() {
1032        let data = json!({"a": 1, "b": [1, {"c": "x y"}], "0": true, "n": null});
1033        assert_eq!(
1034            http_build_query(&data, b"p", None, QueryEncoding::Rfc1738),
1035            b"a=1&b%5B0%5D=1&b%5B1%5D%5Bc%5D=x+y&p0=1"
1036        );
1037    }
1038
1039    #[test]
1040    fn base64_like_php() {
1041        assert_eq!(base64_encode(b"ab"), "YWI=");
1042        assert_eq!(base64_decode(b"YW I=", true).unwrap(), b"ab");
1043        assert_eq!(base64_decode(b"YWI=x", true), None);
1044        assert_eq!(base64_decode(b"Y!WI", false).unwrap(), b"ab");
1045    }
1046
1047    #[test]
1048    fn html_like_php() {
1049        let f = HtmlFlags::DEFAULT;
1050        assert_eq!(
1051            htmlspecialchars(b"<a href='x'>&amp;</a>", f, true),
1052            b"&lt;a href=&#039;x&#039;&gt;&amp;amp;&lt;/a&gt;"
1053        );
1054        assert_eq!(htmlspecialchars(b"&amp; &bogus;", f, false), b"&amp; &amp;bogus;");
1055        assert_eq!(htmlentities("café".as_bytes(), f, true), b"caf&eacute;");
1056        assert_eq!(htmlspecialchars(b"a\xFFb", HtmlFlags::from_php(3), true), b"");
1057    }
1058}
1059
1060#[cfg(test)]
1061mod parse_str_tests {
1062    use super::parse_str;
1063    use crate::types::Value;
1064    use serde_json::json;
1065
1066    fn parsed(s: &str) -> serde_json::Value {
1067        Value::Array(parse_str(s.as_bytes())).to_json()
1068    }
1069
1070    #[test]
1071    fn parses_like_php() {
1072        assert_eq!(parsed("x=1&y[]=2&y[]=3&a.b=4"), json!({"x": "1", "y": ["2", "3"], "a_b": "4"}));
1073        assert_eq!(
1074            parsed("a[b=1&c[d][e=2&f]=3&g[ h]=4&i.j[k.l]=5&m[]=6&m[]=7&m[5]=8&m[]=9"),
1075            json!({"a_b": "1", "c": {"d": "2"}, "f]": "3", "g": {" h": "4"}, "i_j": {"k.l": "5"}, "m": {"0": "6", "1": "7", "5": "8", "6": "9"}})
1076        );
1077        assert_eq!(parsed("&&=x&+a=%41+"), json!({"a": "A "}));
1078    }
1079}