Skip to main content

php_std/
net.rs

1//! Network helpers: `inet_pton`/`inet_ntop`.
2//!
3//! | PHP | Rust |
4//! |---|---|
5//! | `inet_pton($ip)` | [`inet_pton`] |
6//! | `inet_ntop($ip)` | [`inet_ntop`] |
7//!
8//! PHP's address functions call the C library; the dev image is Alpine, so
9//! these are ports of musl's `inet_pton`/`inet_ntop` (`src/network/`), whose
10//! IPv6 formatting differs from glibc's in which zero run it compresses.
11
12use std::fmt;
13
14/// PHP's `ValueError` for a string argument that must not contain NUL bytes
15/// (`Z_PARAM_PATH`): `"<function>(): Argument #1 ($ip) must not contain any
16/// null bytes"`.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct NulByteError {
19    function: &'static str,
20}
21
22impl NulByteError {
23    /// The PHP exception class this error corresponds to.
24    pub fn php_class(&self) -> &'static str {
25        "ValueError"
26    }
27}
28
29impl fmt::Display for NulByteError {
30    /// Writes PHP's `ValueError` message.
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        write!(f, "{}(): Argument #1 ($ip) must not contain any null bytes", self.function)
33    }
34}
35
36impl std::error::Error for NulByteError {}
37
38fn check_nul(function: &'static str, ip: &[u8]) -> Result<(), NulByteError> {
39    if ip.contains(&0) { Err(NulByteError { function }) } else { Ok(()) }
40}
41
42/// A packed address from [`inet_pton`].
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum PackedAddr {
45    /// A 4-byte IPv4 address.
46    V4([u8; 4]),
47    /// A 16-byte IPv6 address.
48    V6([u8; 16]),
49}
50
51impl PackedAddr {
52    /// The packed bytes, as PHP's binary string.
53    pub fn as_bytes(&self) -> &[u8] {
54        match self {
55            PackedAddr::V4(b) => b,
56            PackedAddr::V6(b) => b,
57        }
58    }
59}
60
61/// PHP `inet_pton($ip)`: IPv6 when the string contains `:`, IPv4 when it
62/// contains `.`, `None` (PHP's `false`) otherwise or when invalid.
63pub fn inet_pton(ip: &[u8]) -> Result<Option<PackedAddr>, NulByteError> {
64    check_nul("inet_pton", ip)?;
65    Ok(if ip.contains(&b':') {
66        pton6(ip).map(PackedAddr::V6)
67    } else if ip.contains(&b'.') {
68        pton4(ip).map(PackedAddr::V4)
69    } else {
70        None
71    })
72}
73
74/// PHP `inet_ntop($ip)`: a 4-byte (IPv4) or 16-byte (IPv6) packed address
75/// in text form; `None` (PHP's `false`) for any other length.
76pub fn inet_ntop(packed: &[u8]) -> Option<String> {
77    match packed.len() {
78        4 => Some(format!("{}.{}.{}.{}", packed[0], packed[1], packed[2], packed[3])),
79        16 => Some(ntop6(packed)),
80        _ => None,
81    }
82}
83
84/// musl `inet_pton(AF_INET)`. The input never contains NUL here.
85fn pton4(s: &[u8]) -> Option<[u8; 4]> {
86    let mut out = [0u8; 4];
87    let mut s = s;
88    for (i, slot) in out.iter_mut().enumerate() {
89        let mut v: u32 = 0;
90        let mut j = 0;
91        while j < 3 && j < s.len() && s[j].is_ascii_digit() {
92            v = 10 * v + u32::from(s[j] - b'0');
93            j += 1;
94        }
95        if j == 0 || (j > 1 && s[0] == b'0') || v > 255 {
96            return None;
97        }
98        *slot = v as u8;
99        if j == s.len() && i == 3 {
100            return Some(out);
101        }
102        if j >= s.len() || s[j] != b'.' {
103            return None;
104        }
105        s = &s[j + 1..];
106    }
107    None
108}
109
110fn hexval(c: u8) -> Option<u16> {
111    match c {
112        b'0'..=b'9' => Some(u16::from(c - b'0')),
113        b'a'..=b'f' => Some(u16::from(c - b'a' + 10)),
114        b'A'..=b'F' => Some(u16::from(c - b'A' + 10)),
115        _ => None,
116    }
117}
118
119/// musl `inet_pton(AF_INET6)`. Reading past the end yields NUL, as in C.
120fn pton6(input: &[u8]) -> Option<[u8; 16]> {
121    let at = |i: usize| input.get(i).copied().unwrap_or(0);
122    let mut ip = [0u16; 8];
123    let mut s = 0usize;
124    let mut brk: Option<usize> = None;
125    let mut need_v4 = false;
126
127    if at(s) == b':' {
128        s += 1;
129        if at(s) != b':' {
130            return None;
131        }
132    }
133
134    let mut i = 0usize;
135    loop {
136        if at(s) == b':' && brk.is_none() {
137            brk = Some(i);
138            ip[i & 7] = 0;
139            s += 1;
140            if at(s) == 0 {
141                break;
142            }
143            if i == 7 {
144                return None;
145            }
146            i += 1;
147            continue;
148        }
149        let mut v: u16 = 0;
150        let mut j = 0;
151        while j < 4 {
152            match hexval(at(s + j)) {
153                Some(d) => v = 16 * v + d,
154                None => break,
155            }
156            j += 1;
157        }
158        if j == 0 {
159            return None;
160        }
161        ip[i & 7] = v;
162        if at(s + j) == 0 && (brk.is_some() || i == 7) {
163            break;
164        }
165        if i == 7 {
166            return None;
167        }
168        if at(s + j) != b':' {
169            if at(s + j) != b'.' || (i < 6 && brk.is_none()) {
170                return None;
171            }
172            need_v4 = true;
173            i += 1;
174            ip[i & 7] = 0;
175            break;
176        }
177        s += j + 1;
178        i += 1;
179    }
180    if let Some(brk) = brk {
181        // memmove(ip+brk+7-i, ip+brk, 2*(i+1-brk)); zero the gap.
182        let count = i + 1 - brk;
183        let dst = brk + 7 - i;
184        let moved: Vec<u16> = ip[brk..brk + count].to_vec();
185        ip[dst..dst + count].copy_from_slice(&moved);
186        for slot in ip.iter_mut().skip(brk).take(7 - i) {
187            *slot = 0;
188        }
189    }
190    let mut out = [0u8; 16];
191    for (j, v) in ip.iter().enumerate() {
192        out[2 * j] = (v >> 8) as u8;
193        out[2 * j + 1] = *v as u8;
194    }
195    if need_v4 {
196        let v4 = pton4(&input[s..])?;
197        out[12..].copy_from_slice(&v4);
198    }
199    Some(out)
200}
201
202/// musl `inet_ntop(AF_INET6)`: prints every group, then replaces the longest
203/// `(^0|:)[:0]{2,}` run with `::` (a leading run needs one more character to
204/// lose to a later one).
205fn ntop6(a: &[u8]) -> String {
206    let w = |i: usize| (u32::from(a[2 * i]) << 8) | u32::from(a[2 * i + 1]);
207    let mut buf = if a[..12] != [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff] {
208        format!("{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}", w(0), w(1), w(2), w(3), w(4), w(5), w(6), w(7))
209    } else {
210        format!(
211            "{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{}.{}.{}.{}",
212            w(0),
213            w(1),
214            w(2),
215            w(3),
216            w(4),
217            w(5),
218            a[12],
219            a[13],
220            a[14],
221            a[15]
222        )
223    }
224    .into_bytes();
225    let (mut best, mut max) = (0usize, 2usize);
226    for i in 0..buf.len() {
227        if i != 0 && buf[i] != b':' {
228            continue;
229        }
230        let j = buf[i..].iter().take_while(|&&c| c == b':' || c == b'0').count();
231        if j > max + usize::from(best == 0) {
232            best = i;
233            max = j;
234        }
235    }
236    if max > 3 {
237        buf[best] = b':';
238        buf[best + 1] = b':';
239        buf.drain(best + 2..best + max);
240    }
241    String::from_utf8(buf).unwrap_or_default()
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247
248    #[test]
249    fn ipv6() {
250        let rt = |s: &str| inet_ntop(inet_pton(s.as_bytes()).unwrap().unwrap().as_bytes()).unwrap();
251        assert_eq!(rt("::1"), "::1");
252        assert_eq!(rt("0:0:1:0:0:1:0:0"), "::1:0:0:1:0:0");
253        assert_eq!(rt("1:0:0:0:1:0:0:0"), "1::1:0:0:0");
254        assert_eq!(rt("::1.2.3.4"), "::102:304");
255        assert_eq!(rt("::ffff:0:0"), "::ffff:0.0.0.0");
256        assert_eq!(rt("0:0:1::"), "0:0:1::");
257        assert_eq!(inet_pton(b"1:::2"), Ok(None));
258        assert_eq!(inet_ntop(b"abc"), None);
259    }
260}