Skip to main content

php_std/
url.rs

1//! `parse_url` and the PHP 8.5 URI extension (`Uri\Rfc3986\Uri`).
2//!
3//! | PHP | Rust |
4//! |---|---|
5//! | `parse_url($url)` | [`parse_url`] → [`Url`] |
6//! | `parse_url($url, PHP_URL_*)` | [`parse_url`] + [`Url::component`] ([`Component`]) |
7//! | `Uri\Rfc3986\Uri::parse($uri)` | [`rfc3986::Uri::parse`] |
8//!
9//! `Uri\WhatWg\Url` is not reimplemented: no Utopia library uses it.
10
11use std::borrow::Cow;
12use std::ops::Range;
13
14pub mod rfc3986;
15
16/// A URL split by PHP's `parse_url` (`php_url_parse_ex2` in
17/// `ext/standard/url.c`).
18///
19/// Components borrow from the input. PHP replaces ASCII control characters
20/// (`iscntrl`: `0x00`–`0x1F` and `0x7F`) in every component with `_`; the
21/// accessors do the same, allocating only when a component contains one.
22/// Components are byte strings because PHP strings are: when the input is
23/// valid UTF-8, so is every component (the parser only splits at ASCII
24/// bytes).
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct Url<'a> {
27    input: &'a [u8],
28    scheme: Option<Range<usize>>,
29    host: Option<Range<usize>>,
30    port: Option<u16>,
31    user: Option<Range<usize>>,
32    pass: Option<Range<usize>>,
33    path: Option<Range<usize>>,
34    query: Option<Range<usize>>,
35    fragment: Option<Range<usize>>,
36}
37
38/// A `PHP_URL_*` selector for `parse_url($url, $component)`.
39///
40/// PHP throws a `ValueError` for any other integer; the enum makes that
41/// unrepresentable (a recorded deviation).
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum Component {
44    /// `PHP_URL_SCHEME` (0)
45    Scheme,
46    /// `PHP_URL_HOST` (1)
47    Host,
48    /// `PHP_URL_PORT` (2)
49    Port,
50    /// `PHP_URL_USER` (3)
51    User,
52    /// `PHP_URL_PASS` (4)
53    Pass,
54    /// `PHP_URL_PATH` (5)
55    Path,
56    /// `PHP_URL_QUERY` (6)
57    Query,
58    /// `PHP_URL_FRAGMENT` (7)
59    Fragment,
60}
61
62impl Component {
63    /// The component for a `PHP_URL_*` constant value.
64    pub fn from_php(value: i64) -> Option<Self> {
65        Some(match value {
66            0 => Component::Scheme,
67            1 => Component::Host,
68            2 => Component::Port,
69            3 => Component::User,
70            4 => Component::Pass,
71            5 => Component::Path,
72            6 => Component::Query,
73            7 => Component::Fragment,
74            _ => return None,
75        })
76    }
77}
78
79/// The value `parse_url($url, $component)` returns for a component that is
80/// present: a string, or an integer for the port.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub enum ComponentValue<'a> {
83    /// A string component, as bytes.
84    Str(Cow<'a, [u8]>),
85    /// The port.
86    Port(u16),
87}
88
89/// PHP `parse_url($url)`: `None` where PHP returns `false` (a malformed URL,
90/// such as an invalid port or an empty host after `//`).
91pub fn parse_url(url: &[u8]) -> Option<Url<'_>> {
92    Parser { s: url, ret: Url::empty(url) }.run()
93}
94
95impl<'a> Url<'a> {
96    fn empty(input: &'a [u8]) -> Self {
97        Url {
98            input,
99            scheme: None,
100            host: None,
101            port: None,
102            user: None,
103            pass: None,
104            path: None,
105            query: None,
106            fragment: None,
107        }
108    }
109
110    fn part(&self, r: &Option<Range<usize>>) -> Option<Cow<'a, [u8]>> {
111        r.clone().map(|r| replace_controls(&self.input[r]))
112    }
113
114    /// `scheme`
115    pub fn scheme(&self) -> Option<Cow<'a, [u8]>> {
116        self.part(&self.scheme)
117    }
118
119    /// `host`
120    pub fn host(&self) -> Option<Cow<'a, [u8]>> {
121        self.part(&self.host)
122    }
123
124    /// `port`. PHP reports a port only when one was written (`:0` included).
125    pub fn port(&self) -> Option<u16> {
126        self.port
127    }
128
129    /// `user`
130    pub fn user(&self) -> Option<Cow<'a, [u8]>> {
131        self.part(&self.user)
132    }
133
134    /// `pass`
135    pub fn pass(&self) -> Option<Cow<'a, [u8]>> {
136        self.part(&self.pass)
137    }
138
139    /// `path`
140    pub fn path(&self) -> Option<Cow<'a, [u8]>> {
141        self.part(&self.path)
142    }
143
144    /// `query` (without `?`)
145    pub fn query(&self) -> Option<Cow<'a, [u8]>> {
146        self.part(&self.query)
147    }
148
149    /// `fragment` (without `#`)
150    pub fn fragment(&self) -> Option<Cow<'a, [u8]>> {
151        self.part(&self.fragment)
152    }
153
154    /// `parse_url($url, $component)` for a URL that parsed: `None` is PHP's
155    /// `null` (component absent).
156    pub fn component(&self, component: Component) -> Option<ComponentValue<'a>> {
157        let s = |v: Option<Cow<'a, [u8]>>| v.map(ComponentValue::Str);
158        match component {
159            Component::Scheme => s(self.scheme()),
160            Component::Host => s(self.host()),
161            Component::Port => self.port.map(ComponentValue::Port),
162            Component::User => s(self.user()),
163            Component::Pass => s(self.pass()),
164            Component::Path => s(self.path()),
165            Component::Query => s(self.query()),
166            Component::Fragment => s(self.fragment()),
167        }
168    }
169}
170
171/// `php_replace_controlchars`: `iscntrl()` bytes become `_`.
172fn replace_controls(bytes: &[u8]) -> Cow<'_, [u8]> {
173    if !bytes.iter().any(|&b| is_cntrl(b)) {
174        return Cow::Borrowed(bytes);
175    }
176    Cow::Owned(bytes.iter().map(|&b| if is_cntrl(b) { b'_' } else { b }).collect())
177}
178
179fn is_cntrl(b: u8) -> bool {
180    b < 0x20 || b == 0x7f
181}
182
183/// `isspace()` in the C locale.
184fn is_space(b: u8) -> bool {
185    matches!(b, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r')
186}
187
188/// `strtol(buf, &end, 10)` as used for ports: `None` when no digits were
189/// read (`end == buf`). `buf` is at most 5 bytes, so it cannot overflow.
190fn strtol(buf: &[u8]) -> Option<i64> {
191    let mut i = 0;
192    while i < buf.len() && is_space(buf[i]) {
193        i += 1;
194    }
195    let mut negative = false;
196    if i < buf.len() && (buf[i] == b'+' || buf[i] == b'-') {
197        negative = buf[i] == b'-';
198        i += 1;
199    }
200    let start = i;
201    let mut v: i64 = 0;
202    while i < buf.len() && buf[i].is_ascii_digit() {
203        v = v * 10 + i64::from(buf[i] - b'0');
204        i += 1;
205    }
206    if i == start {
207        return None;
208    }
209    Some(if negative { -v } else { v })
210}
211
212/// Where `php_url_parse_ex2` jumps to.
213enum Step {
214    ParsePort(usize),
215    ParseHost,
216    JustPath,
217}
218
219struct Parser<'a> {
220    s: &'a [u8],
221    ret: Url<'a>,
222}
223
224impl<'a> Parser<'a> {
225    /// `binary_strcspn(s, ue, chars)`: the first position in `from..` holding
226    /// any of `chars`, or the end.
227    fn cspn(&self, from: usize, chars: &[u8]) -> usize {
228        self.s[from..].iter().position(|b| chars.contains(b)).map_or(self.s.len(), |p| from + p)
229    }
230
231    fn run(mut self) -> Option<Url<'a>> {
232        let ue = self.s.len();
233        let mut s = 0;
234        let colon = self.s.iter().position(|&b| b == b':');
235
236        let step = match colon {
237            Some(e) if e != s => {
238                let invalid = self.s[s..e]
239                    .iter()
240                    .any(|&b| !(b.is_ascii_alphabetic() || b.is_ascii_digit() || b == b'+' || b == b'.' || b == b'-'));
241                if invalid {
242                    if e + 1 < ue && e < self.cspn(s, b"?#") {
243                        Step::ParsePort(e)
244                    } else if s + 1 < ue && self.s[s] == b'/' && self.s[s + 1] == b'/' {
245                        s += 2;
246                        Step::ParseHost
247                    } else {
248                        Step::JustPath
249                    }
250                } else if e + 1 == ue {
251                    // Only a scheme.
252                    self.ret.scheme = Some(s..e);
253                    return Some(self.ret);
254                } else if self.s[e + 1] != b'/' {
255                    // `mailto:` style, or `host:port`.
256                    let mut p = e + 1;
257                    while p < ue && self.s[p].is_ascii_digit() {
258                        p += 1;
259                    }
260                    if (p == ue || self.s[p] == b'/') && (p - e) < 7 {
261                        Step::ParsePort(e)
262                    } else {
263                        self.ret.scheme = Some(s..e);
264                        s = e + 1;
265                        Step::JustPath
266                    }
267                } else {
268                    self.ret.scheme = Some(s..e);
269                    if e + 2 < ue && self.s[e + 2] == b'/' {
270                        s = e + 3;
271                        if self.s[..e].eq_ignore_ascii_case(b"file") && e + 3 < ue && self.s[e + 3] == b'/' {
272                            // Windows drive letters: file:///c:/dir
273                            if e + 5 < ue && self.s[e + 5] == b':' {
274                                s = e + 4;
275                            }
276                            Step::JustPath
277                        } else {
278                            Step::ParseHost
279                        }
280                    } else {
281                        s = e + 1;
282                        Step::JustPath
283                    }
284                }
285            }
286            Some(e) => Step::ParsePort(e),
287            None if s + 1 < ue && self.s[s] == b'/' && self.s[s + 1] == b'/' => {
288                s += 2;
289                Step::ParseHost
290            }
291            None => Step::JustPath,
292        };
293
294        let step = match step {
295            Step::ParsePort(e) => {
296                let p = e + 1;
297                let mut pp = p;
298                while pp < ue && pp - p < 6 && self.s[pp].is_ascii_digit() {
299                    pp += 1;
300                }
301                if pp - p > 0 && pp - p < 6 && (pp == ue || self.s[pp] == b'/') {
302                    match strtol(&self.s[p..pp]) {
303                        Some(port @ 0..=65535) => {
304                            self.ret.port = Some(port as u16);
305                            if s + 1 < ue && self.s[s] == b'/' && self.s[s + 1] == b'/' {
306                                s += 2;
307                            }
308                            Step::ParseHost
309                        }
310                        _ => return None,
311                    }
312                } else if p == pp && pp == ue {
313                    return None;
314                } else if s + 1 < ue && self.s[s] == b'/' && self.s[s + 1] == b'/' {
315                    s += 2;
316                    Step::ParseHost
317                } else {
318                    Step::JustPath
319                }
320            }
321            other => other,
322        };
323
324        if let Step::ParseHost = step {
325            let e = self.cspn(s, b"/?#");
326            // User info.
327            if let Some(at) = self.s[s..e].iter().rposition(|&b| b == b'@').map(|p| s + p) {
328                match self.s[s..at].iter().position(|&b| b == b':').map(|p| s + p) {
329                    Some(pp) => {
330                        self.ret.user = Some(s..pp);
331                        self.ret.pass = Some(pp + 1..at);
332                    }
333                    None => self.ret.user = Some(s..at),
334                }
335                s = at + 1;
336            }
337            // Port, unless the host is an IPv6 literal.
338            let colon = if s < ue && self.s[s] == b'[' && self.s[e - 1] == b']' {
339                None
340            } else {
341                self.s[s..e].iter().rposition(|&b| b == b':').map(|p| s + p)
342            };
343            let host_end = match colon {
344                Some(p) => {
345                    // PHP tests the port value, not whether one was seen: an
346                    // earlier `:0` is parsed again here.
347                    if self.ret.port.is_none_or(|port| port == 0) {
348                        let digits = p + 1;
349                        if e - digits > 5 {
350                            return None;
351                        } else if e > digits {
352                            match strtol(&self.s[digits..e]) {
353                                Some(port @ 0..=65535) => self.ret.port = Some(port as u16),
354                                _ => return None,
355                            }
356                        }
357                    }
358                    p
359                }
360                None => e,
361            };
362            if host_end <= s {
363                return None;
364            }
365            self.ret.host = Some(s..host_end);
366            if e == ue {
367                return Some(self.ret);
368            }
369            s = e;
370        }
371
372        // just_path
373        let mut e = ue;
374        if let Some(hash) = self.s[s..e].iter().position(|&b| b == b'#').map(|p| s + p) {
375            self.ret.fragment = Some(hash + 1..e);
376            e = hash;
377        }
378        if let Some(q) = self.s[s..e].iter().position(|&b| b == b'?').map(|p| s + p) {
379            self.ret.query = Some(q + 1..e);
380            e = q;
381        }
382        if s < e || s == ue {
383            self.ret.path = Some(s..e);
384        }
385        Some(self.ret)
386    }
387}
388
389#[cfg(test)]
390mod tests {
391    use super::*;
392
393    fn parts(url: &str) -> Option<Vec<(&'static str, String)>> {
394        let u = parse_url(url.as_bytes())?;
395        let s = |v: Option<Cow<'_, [u8]>>| v.map(|v| String::from_utf8(v.into_owned()).unwrap());
396        let mut out = Vec::new();
397        for (k, v) in [
398            ("scheme", s(u.scheme())),
399            ("host", s(u.host())),
400            ("port", u.port().map(|p| p.to_string())),
401            ("user", s(u.user())),
402            ("pass", s(u.pass())),
403            ("path", s(u.path())),
404            ("query", s(u.query())),
405            ("fragment", s(u.fragment())),
406        ] {
407            if let Some(v) = v {
408                out.push((k, v));
409            }
410        }
411        Some(out)
412    }
413
414    #[test]
415    fn full_url() {
416        assert_eq!(
417            parts("https://u:p@example.com:8080/a/b?x=1#frag").unwrap(),
418            vec![
419                ("scheme", "https".into()),
420                ("host", "example.com".into()),
421                ("port", "8080".into()),
422                ("user", "u".into()),
423                ("pass", "p".into()),
424                ("path", "/a/b".into()),
425                ("query", "x=1".into()),
426                ("fragment", "frag".into()),
427            ]
428        );
429    }
430
431    #[test]
432    fn quirks() {
433        assert_eq!(parts("").unwrap(), vec![("path", "".into())]);
434        assert_eq!(parts("a.com:80").unwrap(), vec![("host", "a.com".into()), ("port", "80".into())]);
435        assert_eq!(parts("mailto:a@b.c").unwrap(), vec![("scheme", "mailto".into()), ("path", "a@b.c".into())]);
436        assert_eq!(parts("//example.com/x").unwrap(), vec![("host", "example.com".into()), ("path", "/x".into())]);
437        assert!(parts("http://").is_none());
438        assert!(parts("http://a:65536").is_none());
439        assert!(parts(":").is_none());
440        assert_eq!(parts("x?").unwrap(), vec![("path", "x".into()), ("query", "".into())]);
441        assert_eq!(parts("http://h/\x01").unwrap()[2], ("path", "/_".into()));
442    }
443}