Skip to main content

php_std/
glob.rs

1//! Shell glob matching: PHP's `fnmatch()`.
2//!
3//! PHP calls the C library's `fnmatch(3)`. The runtimes this port is held
4//! to run on Alpine Linux, so this is musl's implementation
5//! (`src/regex/fnmatch.c`) in the `C.UTF-8` locale PHP runs in there:
6//! characters are UTF-8 sequences, character classes are musl's Unicode
7//! tables ([`classes`]), an invalid sequence in the pattern matches nothing
8//! and one in the name only matches `?` or a negated bracket, as musl reads
9//! them.
10//!
11//! | PHP | Rust |
12//! |---|---|
13//! | `fnmatch($pattern, $filename)` (no flags) | [`fnmatch`] |
14
15mod classes;
16
17use crate::types::EngineError;
18
19/// `MAXPATHLEN` on Linux: longer arguments are refused.
20const MAXPATHLEN: usize = 4096;
21
22/// A pattern token (musl's `pat_next`).
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24enum Token {
25    End,
26    Unmatchable,
27    Bracket,
28    Question,
29    Star,
30    Char(i64),
31}
32
33/// musl's `mbtowc` on at most `n` bytes of `s`: the character and its
34/// length, or `None` for an invalid (or truncated) sequence.
35fn mbtowc(s: &[u8], n: usize) -> Option<(i64, usize)> {
36    let first = *s.first()?;
37    if first < 0x80 {
38        return Some((i64::from(first), 1));
39    }
40    let len = match first {
41        0xc2..=0xdf => 2,
42        0xe0..=0xef => 3,
43        0xf0..=0xf4 => 4,
44        _ => return None,
45    };
46    if n < len || s.len() < len {
47        return None;
48    }
49    let c = std::str::from_utf8(&s[..len]).ok()?.chars().next()?;
50    Some((i64::from(u32::from(c)), len))
51}
52
53/// musl's `str_next`: the next character of the name (0 at its end, -1 for
54/// an invalid byte) and how many bytes it spans.
55fn str_next(s: &[u8]) -> (i64, usize) {
56    match s.first() {
57        None => (0, 0),
58        Some(&b) if b < 0x80 => (i64::from(b), 1),
59        Some(_) => mbtowc(s, s.len()).unwrap_or((-1, 1)),
60    }
61}
62
63/// musl's `pat_next`: the next token of the pattern and how many bytes it
64/// spans.
65fn pat_next(pat: &[u8]) -> (Token, usize) {
66    let Some(&first) = pat.first() else { return (Token::End, 0) };
67    let m = pat.len();
68    let (at, esc) = if first == b'\\' && m > 1 {
69        (1, 1)
70    } else {
71        if first == b'[' {
72            let mut k = 1;
73            if k < m && (pat[k] == b'^' || pat[k] == b'!') {
74                k += 1;
75            }
76            if k < m && pat[k] == b']' {
77                k += 1;
78            }
79            while k < m && pat[k] != b']' {
80                if k + 1 < m && pat[k] == b'[' && matches!(pat[k + 1], b':' | b'.' | b'=') {
81                    let z = pat[k + 1];
82                    k += 2;
83                    if k < m {
84                        k += 1;
85                    }
86                    while k < m && (pat[k - 1] != z || pat[k] != b']') {
87                        k += 1;
88                    }
89                    if k == m {
90                        break;
91                    }
92                }
93                k += 1;
94            }
95            if k >= m {
96                return (Token::Char(i64::from(b'[')), 1);
97            }
98            return (Token::Bracket, k + 1);
99        }
100        match first {
101            b'*' => return (Token::Star, 1),
102            b'?' => return (Token::Question, 1),
103            _ => (0, 0),
104        }
105    };
106    let c = pat[at];
107    if c < 0x80 {
108        return (Token::Char(i64::from(c)), at + 1);
109    }
110    match mbtowc(&pat[at..], m - at) {
111        Some((wc, k)) => (Token::Char(wc), k + esc),
112        None => (Token::Unmatchable, 0),
113    }
114}
115
116/// Whether the class named `name` holds `k` (`iswctype(k, wctype(name))`).
117fn in_class(name: &[u8], k: i64) -> bool {
118    let Ok(k) = u32::try_from(k) else { return false };
119    let table = match name {
120        b"alnum" => classes::ALNUM,
121        b"alpha" => classes::ALPHA,
122        b"blank" => classes::BLANK,
123        b"cntrl" => classes::CNTRL,
124        b"digit" => classes::DIGIT,
125        b"graph" => classes::GRAPH,
126        b"lower" => classes::LOWER,
127        b"print" => classes::PRINT,
128        b"punct" => classes::PUNCT,
129        b"space" => classes::SPACE,
130        b"upper" => classes::UPPER,
131        b"xdigit" => classes::XDIGIT,
132        _ => return false,
133    };
134    table
135        .binary_search_by(|&(lo, hi)| {
136            if hi < k {
137                std::cmp::Ordering::Less
138            } else if lo > k {
139                std::cmp::Ordering::Greater
140            } else {
141                std::cmp::Ordering::Equal
142            }
143        })
144        .is_ok()
145}
146
147/// musl's `match_bracket`: whether the bracket expression at the start of
148/// `p` (known to be closed) matches `k`.
149fn match_bracket(p: &[u8], k: i64) -> bool {
150    let at = |i: usize| p.get(i).copied().unwrap_or(0);
151    let mut i = 1;
152    let mut inv = false;
153    if at(i) == b'^' || at(i) == b'!' {
154        inv = true;
155        i += 1;
156    }
157    if at(i) == b']' {
158        if k == i64::from(b']') {
159            return !inv;
160        }
161        i += 1;
162    } else if at(i) == b'-' {
163        if k == i64::from(b'-') {
164            return !inv;
165        }
166        i += 1;
167    }
168    let mut wc = i64::from(at(i - 1));
169    while at(i) != b']' {
170        if at(i) == b'-' && at(i + 1) != b']' {
171            let Some((wc2, l)) = mbtowc(&p[(i + 1).min(p.len())..], 4) else { return false };
172            if wc <= wc2 {
173                let span = (wc2 - wc) as u32;
174                if (k.wrapping_sub(wc) as u32) <= span {
175                    return !inv;
176                }
177            }
178            i += l;
179            continue;
180        }
181        if at(i) == b'[' && matches!(at(i + 1), b':' | b'.' | b'=') {
182            let start = i + 2;
183            let z = at(i + 1);
184            i += 3;
185            while at(i - 1) != z || at(i) != b']' {
186                i += 1;
187            }
188            let name = &p[start..i - 1];
189            if z == b':' && name.len() < 16 && in_class(name, k) {
190                return !inv;
191            }
192            i += 1;
193            continue;
194        }
195        if at(i) < 0x80 {
196            wc = i64::from(at(i));
197        } else {
198            let Some((c, l)) = mbtowc(&p[i..], 4) else { return false };
199            wc = c;
200            i += l - 1;
201        }
202        if wc == k {
203            return !inv;
204        }
205        i += 1;
206    }
207    inv
208}
209
210/// Whether a name character `k` matches the token at the start of `p`.
211fn token_matches(token: Token, p: &[u8], k: i64) -> bool {
212    match token {
213        Token::Bracket => match_bracket(p, k),
214        Token::Question => true,
215        Token::Char(c) => c == k,
216        _ => false,
217    }
218}
219
220/// musl's `fnmatch_internal` with no flags.
221fn matches(pat: &[u8], s: &[u8]) -> bool {
222    let (mut pat, mut s) = (pat, s);
223    // Characters up to the first star.
224    loop {
225        let (c, pinc) = pat_next(pat);
226        match c {
227            Token::Unmatchable => return false,
228            Token::Star => {
229                pat = &pat[1..];
230                break;
231            }
232            _ => {
233                let (k, sinc) = str_next(s);
234                if k <= 0 {
235                    return c == Token::End;
236                }
237                if !token_matches(c, pat, k) {
238                    return false;
239                }
240                s = &s[sinc..];
241                pat = &pat[pinc..];
242            }
243        }
244    }
245
246    // The last star, and how many characters the pattern needs after it.
247    let mut ptail = 0;
248    let mut tailcnt = 0usize;
249    let mut i = 0;
250    while i < pat.len() {
251        let (c, pinc) = pat_next(&pat[i..]);
252        match c {
253            Token::Unmatchable => return false,
254            Token::Star => {
255                tailcnt = 0;
256                ptail = i + 1;
257            }
258            _ => tailcnt += 1,
259        }
260        i += pinc;
261    }
262    if s.len() < tailcnt {
263        return false;
264    }
265
266    // Step back over the last `tailcnt` characters of the name.
267    let mut stail = s.len();
268    while stail > 0 && tailcnt > 0 {
269        if s[stail - 1] < 0x80 {
270            stail -= 1;
271        } else {
272            loop {
273                stail -= 1;
274                if !(s[stail].wrapping_sub(0x80) < 0x40 && stail > 0) {
275                    break;
276                }
277            }
278        }
279        tailcnt -= 1;
280    }
281    if tailcnt > 0 {
282        return false;
283    }
284
285    // The tails must match.
286    let mut p = ptail;
287    let mut j = stail;
288    loop {
289        let (c, pinc) = pat_next(&pat[p..]);
290        let token_at = p;
291        p += pinc;
292        let (k, sinc) = str_next(&s[j..]);
293        if k <= 0 {
294            if c != Token::End {
295                return false;
296            }
297            break;
298        }
299        j += sinc;
300        if !token_matches(c, &pat[token_at..], k) {
301            return false;
302        }
303    }
304
305    // The components between stars, leftmost first.
306    let endpat = ptail;
307    let endstr = stail;
308    let (mut pi, mut si) = (0usize, 0usize);
309    while pi < endpat {
310        let mut p = pi;
311        let mut sj = si;
312        let mut star = false;
313        loop {
314            let (c, pinc) = pat_next(&pat[p..endpat]);
315            let token_at = p;
316            p += pinc;
317            if c == Token::Star {
318                pi = p;
319                si = sj;
320                star = true;
321                break;
322            }
323            let (k, sinc) = str_next(&s[sj..endstr]);
324            if k == 0 {
325                return false;
326            }
327            if !token_matches(c, &pat[token_at..endpat], k) {
328                break;
329            }
330            sj += sinc;
331        }
332        if star {
333            continue;
334        }
335        let (k, sinc) = str_next(&s[si..endstr]);
336        if k > 0 {
337            si += sinc;
338        } else {
339            si += 1;
340            while si <= endstr && str_next(&s[si..endstr]).0 < 0 {
341                si += 1;
342            }
343        }
344    }
345    true
346}
347
348/// PHP `fnmatch($pattern, $filename)`: whether `filename` matches the shell
349/// glob `pattern` (`*`, `?`, `[...]` with `!`/`^`, ranges and `[:class:]`,
350/// `\` escapes; `*` crosses `/` and a leading `.` is not special).
351///
352/// A null byte in either argument is the `ValueError` PHP throws; an
353/// argument of 4096 bytes or more does not match (PHP warns).
354///
355/// ```
356/// use php_std::glob::fnmatch;
357///
358/// assert_eq!(fnmatch(b"v1.*", b"v1.2.0"), Ok(true));
359/// assert_eq!(fnmatch(b"v?.0.0", b"v10.0.0"), Ok(false));
360/// assert_eq!(fnmatch(b"[!a]*", b"beta"), Ok(true));
361/// ```
362pub fn fnmatch(pattern: &[u8], filename: &[u8]) -> Result<bool, EngineError> {
363    if pattern.contains(&0) {
364        return Err(EngineError::new(
365            "ValueError",
366            "fnmatch(): Argument #1 ($pattern) must not contain any null bytes",
367        ));
368    }
369    if filename.contains(&0) {
370        return Err(EngineError::new(
371            "ValueError",
372            "fnmatch(): Argument #2 ($filename) must not contain any null bytes",
373        ));
374    }
375    if filename.len() >= MAXPATHLEN || pattern.len() >= MAXPATHLEN {
376        return Ok(false);
377    }
378    Ok(matches(pattern, filename))
379}
380
381#[cfg(test)]
382mod tests {
383    use super::fnmatch;
384
385    #[test]
386    fn globs() {
387        let cases: &[(&[u8], &[u8], bool)] = &[
388            (b"*", b"", true),
389            (b"", b"", true),
390            (b"", b"a", false),
391            (b"a*b", b"ab", true),
392            (b"a*b*c", b"axxbyyc", true),
393            (b"a*b*c", b"axxbyy", false),
394            (b"v1.*", b"v1.0.0", true),
395            (b"v1.*", b"v2.0.0", false),
396            (b"[a-c]x", b"bx", true),
397            (b"[!a-c]x", b"bx", false),
398            (b"[]]", b"]", true),
399            (b"[", b"[", true),
400            (b"\\*", b"*", true),
401            (b"\\*", b"a", false),
402            (b"[[:digit:]]*", b"1abc", true),
403            (b"*.txt", b"dir/a.txt", true),
404            ("[[:alpha:]]".as_bytes(), "é".as_bytes(), true),
405            (b"[[:alpha:]]", b"\xe9", false),
406            (b"a", b"a\xff", true),
407            // musl: an invalid byte is no character, so ? does not match it
408            (b"?", b"\xff", false),
409            (b"a?", b"a\xff", false),
410            (b"*", b"\xff\xfe", true),
411        ];
412        for (p, s, want) in cases {
413            assert_eq!(fnmatch(p, s), Ok(*want), "{:?} {:?}", String::from_utf8_lossy(p), String::from_utf8_lossy(s));
414        }
415    }
416}