Skip to main content

c/
netdb_extra.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// Network database backends: /etc/services, /etc/protocols, /etc/networks,
5// /etc/ethers and /etc/hosts, plus getaddrinfo/getnameinfo.
6
7#[repr(C)]
8pub struct ServEnt {
9    pub s_name: *mut c_char,
10    pub s_aliases: *mut *mut c_char,
11    pub s_port: c_int,
12    pub s_proto: *mut c_char,
13}
14
15#[repr(C)]
16pub struct ProtoEnt {
17    pub p_name: *mut c_char,
18    pub p_aliases: *mut *mut c_char,
19    pub p_proto: c_int,
20}
21
22#[repr(C)]
23pub struct NetEnt {
24    pub n_name: *mut c_char,
25    pub n_aliases: *mut *mut c_char,
26    pub n_addrtype: c_int,
27    pub n_net: u32,
28}
29
30const NDB_ENOENT: c_int = 2;
31const NDB_ERANGE: c_int = 34;
32const NDB_ENOTTY: c_int = 25;
33
34const EAI_BADFLAGS_V: c_int = -1;
35const EAI_NONAME_V: c_int = -2;
36const EAI_AGAIN_V: c_int = -3;
37const EAI_FAIL_V: c_int = -4;
38const EAI_FAMILY_V: c_int = -6;
39const EAI_SOCKTYPE_V: c_int = -7;
40const EAI_SERVICE_V: c_int = -8;
41const EAI_MEMORY_V: c_int = -10;
42const EAI_SYSTEM_V: c_int = -11;
43const EAI_NODATA_V: c_int = -5;
44const EAI_OVERFLOW_V: c_int = -12;
45
46const AI_PASSIVE_V: c_int = 0x01;
47const AI_CANONNAME_V: c_int = 0x02;
48const AI_NUMERICHOST_V: c_int = 0x04;
49const AI_V4MAPPED_V: c_int = 0x08;
50const AI_ALL_V: c_int = 0x10;
51const AI_ADDRCONFIG_V: c_int = 0x20;
52const AI_NUMERICSERV_V: c_int = 0x400;
53
54const NI_NUMERICHOST_V: c_int = 0x01;
55const NI_NUMERICSERV_V: c_int = 0x02;
56const NI_NOFQDN_V: c_int = 0x04;
57const NI_NAMEREQD_V: c_int = 0x08;
58const NI_DGRAM_V: c_int = 0x10;
59const NI_NUMERICSCOPE_V: c_int = 0x100;
60
61unsafe fn nd_isspace(c: c_char) -> bool {
62    c == b' ' as c_char || c == b'\t' as c_char || c == b'\r' as c_char || c == b'\n' as c_char
63}
64
65unsafe fn nd_copy_line(src: *const c_char, dst: *mut c_char, cap: usize) -> bool {
66    let mut i = 0usize;
67    while i + 1 < cap {
68        let c = *src.add(i);
69        *dst.add(i) = c;
70        if c == 0 { return true; }
71        i += 1;
72    }
73    *dst.add(cap - 1) = 0;
74    true
75}
76
77/// Split a mutable line into whitespace-separated tokens, honouring '#'.
78unsafe fn nd_split(buf: *mut c_char, toks: *mut *mut c_char, maxtok: usize) -> usize {
79    let mut n = 0usize;
80    let mut p = buf;
81    loop {
82        while *p != 0 && nd_isspace(*p) { p = p.add(1); }
83        if *p == 0 || *p == b'#' as c_char { break; }
84        if n < maxtok {
85            *toks.add(n) = p;
86            n += 1;
87        }
88        while *p != 0 && !nd_isspace(*p) && *p != b'#' as c_char { p = p.add(1); }
89        if *p == 0 { break; }
90        if *p == b'#' as c_char { *p = 0; break; }
91        *p = 0;
92        p = p.add(1);
93    }
94    n
95}
96
97unsafe fn nd_tokens(line: *const c_char, buf: *mut c_char, cap: usize, toks: &mut [*mut c_char; 24]) -> usize {
98    if !nd_copy_line(line, buf, cap) { return 0; }
99    nd_split(buf, toks.as_mut_ptr(), toks.len())
100}
101
102// ------------------------------------------------------------------
103// /etc/services
104// ------------------------------------------------------------------
105
106static mut SERV_FILE: *mut FILE = core::ptr::null_mut();
107static mut SERV_ENT: ServEnt = ServEnt {
108    s_name: core::ptr::null_mut(),
109    s_aliases: core::ptr::null_mut(),
110    s_port: 0,
111    s_proto: core::ptr::null_mut(),
112};
113static mut SERV_BUF: [c_char; 1024] = [0; 1024];
114static mut SERV_ALIASES: [*mut c_char; 16] = [core::ptr::null_mut(); 16];
115
116unsafe fn serv_parse(line: *const c_char) -> bool {
117    let mut toks: [*mut c_char; 24] = [core::ptr::null_mut(); 24];
118    let n = nd_tokens(line, SERV_BUF.as_mut_ptr(), SERV_BUF.len(), &mut toks);
119    if n < 2 { return false; }
120    let mut p = toks[1];
121    let port = crate::strtoul(p, &mut p, 10);
122    if p == toks[1] || port > 65535 { return false; }
123    let mut proto: *mut c_char = b"tcp\0".as_ptr() as *mut c_char;
124    if *p == b'/' as c_char {
125        p = p.add(1);
126        if *p == 0 { return false; }
127        proto = p;
128    }
129    SERV_ENT.s_name = toks[0];
130    SERV_ENT.s_port = htons(port as u16) as c_int;
131    SERV_ENT.s_proto = proto;
132    let mut ai = 0usize;
133    for i in 2..n {
134        if ai + 1 >= SERV_ALIASES.len() { break; }
135        SERV_ALIASES[ai] = toks[i];
136        ai += 1;
137    }
138    SERV_ALIASES[ai] = core::ptr::null_mut();
139    SERV_ENT.s_aliases = SERV_ALIASES.as_mut_ptr();
140    true
141}
142
143unsafe fn serv_next(f: *mut FILE) -> bool {
144    let mut line = [0 as c_char; 1024];
145    while !crate::fgets(line.as_mut_ptr(), line.len() as c_int, f).is_null() {
146        if serv_parse(line.as_ptr()) { return true; }
147    }
148    false
149}
150
151#[no_mangle]
152pub unsafe extern "C" fn setservent(stayopen: c_int) {
153    endservent();
154    SERV_FILE = crate::fopen(b"/etc/services\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
155    let _ = stayopen;
156}
157
158#[no_mangle]
159pub unsafe extern "C" fn endservent() {
160    if !SERV_FILE.is_null() {
161        crate::fclose(SERV_FILE);
162        SERV_FILE = core::ptr::null_mut();
163    }
164}
165
166#[no_mangle]
167pub unsafe extern "C" fn getservent() -> *mut ServEnt {
168    if SERV_FILE.is_null() {
169        SERV_FILE = crate::fopen(b"/etc/services\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
170        if SERV_FILE.is_null() { return core::ptr::null_mut(); }
171    }
172    if serv_next(SERV_FILE) { &raw mut SERV_ENT } else { core::ptr::null_mut() }
173}
174
175unsafe fn serv_name_matches(name: *const c_char) -> bool {
176    if crate::strcmp(SERV_ENT.s_name as *const u8, name as *const u8) == 0 { return true; }
177    let mut i = 0usize;
178    while !(*SERV_ENT.s_aliases.add(i)).is_null() {
179        if crate::strcmp(*SERV_ENT.s_aliases.add(i) as *const u8, name as *const u8) == 0 {
180            return true;
181        }
182        i += 1;
183    }
184    false
185}
186
187unsafe fn serv_proto_matches(proto: *const c_char) -> bool {
188    proto.is_null() || crate::strcmp(SERV_ENT.s_proto as *const u8, proto as *const u8) == 0
189}
190
191unsafe fn serv_search(name: *const c_char, proto: *const c_char, port: c_int) -> bool {
192    let f = crate::fopen(b"/etc/services\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
193    if f.is_null() { return false; }
194    let mut found = false;
195    while serv_next(f) {
196        if !serv_proto_matches(proto) { continue; }
197        let hit = if name.is_null() {
198            SERV_ENT.s_port == port
199        } else {
200            serv_name_matches(name)
201        };
202        if hit { found = true; break; }
203    }
204    crate::fclose(f);
205    found
206}
207
208#[no_mangle]
209pub unsafe extern "C" fn getservbyname(name: *const c_char, proto: *const c_char) -> *mut ServEnt {
210    if name.is_null() { return core::ptr::null_mut(); }
211    if serv_search(name, proto, 0) { &raw mut SERV_ENT } else { core::ptr::null_mut() }
212}
213
214#[no_mangle]
215pub unsafe extern "C" fn getservbyport(port: c_int, proto: *const c_char) -> *mut ServEnt {
216    if serv_search(core::ptr::null(), proto, port) { &raw mut SERV_ENT } else { core::ptr::null_mut() }
217}
218
219unsafe fn serv_copy_out(se: *mut ServEnt, buf: *mut c_char, buflen: usize, res: *mut *mut ServEnt) -> c_int {
220    if res.is_null() || se.is_null() { return EINVAL; }
221    *res = core::ptr::null_mut();
222    let ptrsz = core::mem::size_of::<*mut c_char>();
223    let mut need = crate::strlen((*se).s_name) + 1 + crate::strlen((*se).s_proto) + 1;
224    let mut nalias = 0usize;
225    while !(*(*se).s_aliases.add(nalias)).is_null() {
226        need += crate::strlen(*(*se).s_aliases.add(nalias)) + 1;
227        nalias += 1;
228    }
229    let align = (ptrsz - (buf as usize & (ptrsz - 1))) & (ptrsz - 1);
230    need += align + (nalias + 1) * ptrsz;
231    if need > buflen { return NDB_ERANGE; }
232
233    let mut p = buf.add(align);
234    let aliases = p as *mut *mut c_char;
235    p = p.add((nalias + 1) * ptrsz);
236
237    let n = crate::strlen((*se).s_name);
238    core::ptr::copy_nonoverlapping((*se).s_name, p, n + 1);
239    (*se).s_name = p;
240    p = p.add(n + 1);
241
242    let n = crate::strlen((*se).s_proto);
243    core::ptr::copy_nonoverlapping((*se).s_proto, p, n + 1);
244    (*se).s_proto = p;
245    p = p.add(n + 1);
246
247    for j in 0..nalias {
248        let src = *(*se).s_aliases.add(j);
249        let n = crate::strlen(src);
250        core::ptr::copy_nonoverlapping(src, p, n + 1);
251        *aliases.add(j) = p;
252        p = p.add(n + 1);
253    }
254    *aliases.add(nalias) = core::ptr::null_mut();
255    (*se).s_aliases = aliases;
256    *res = se;
257    0
258}
259
260#[no_mangle]
261pub unsafe extern "C" fn getservbyname_r(
262    name: *const c_char,
263    proto: *const c_char,
264    se: *mut ServEnt,
265    buf: *mut c_char,
266    buflen: usize,
267    res: *mut *mut ServEnt,
268) -> c_int {
269    if res.is_null() || se.is_null() { return EINVAL; }
270    *res = core::ptr::null_mut();
271    let p = getservbyname(name, proto);
272    if p.is_null() { return NDB_ENOENT; }
273    (*se).s_name = (*p).s_name;
274    (*se).s_aliases = (*p).s_aliases;
275    (*se).s_port = (*p).s_port;
276    (*se).s_proto = (*p).s_proto;
277    serv_copy_out(se, buf, buflen, res)
278}
279
280#[no_mangle]
281pub unsafe extern "C" fn getservbyport_r(
282    port: c_int,
283    proto: *const c_char,
284    se: *mut ServEnt,
285    buf: *mut c_char,
286    buflen: usize,
287    res: *mut *mut ServEnt,
288) -> c_int {
289    if res.is_null() || se.is_null() { return EINVAL; }
290    *res = core::ptr::null_mut();
291    let p = getservbyport(port, proto);
292    if p.is_null() { return NDB_ENOENT; }
293    (*se).s_name = (*p).s_name;
294    (*se).s_aliases = (*p).s_aliases;
295    (*se).s_port = (*p).s_port;
296    (*se).s_proto = (*p).s_proto;
297    serv_copy_out(se, buf, buflen, res)
298}
299
300// ------------------------------------------------------------------
301// /etc/protocols (with a builtin fallback table)
302// ------------------------------------------------------------------
303
304static PROTO_TABLE: [(&[u8], c_int); 36] = [
305    (b"ip\0", 0), (b"icmp\0", 1), (b"igmp\0", 2), (b"ggp\0", 3),
306    (b"ipencap\0", 4), (b"st\0", 5), (b"tcp\0", 6), (b"egp\0", 8),
307    (b"pup\0", 12), (b"udp\0", 17), (b"hmp\0", 20), (b"xns-idp\0", 22),
308    (b"rdp\0", 27), (b"iso-tp4\0", 29), (b"xtp\0", 36), (b"ddp\0", 37),
309    (b"idpr-cmtp\0", 38), (b"ipv6\0", 41), (b"ipv6-route\0", 43),
310    (b"ipv6-frag\0", 44), (b"idrp\0", 45), (b"rsvp\0", 46), (b"gre\0", 47),
311    (b"esp\0", 50), (b"ah\0", 51), (b"skip\0", 57), (b"ipv6-icmp\0", 58),
312    (b"ipv6-nonxt\0", 59), (b"ipv6-opts\0", 60), (b"rspf\0", 73),
313    (b"vmtp\0", 81), (b"ospf\0", 89), (b"ipip\0", 94), (b"encap\0", 98),
314    (b"pim\0", 103), (b"raw\0", 255),
315];
316
317static mut PROTO_FILE: *mut FILE = core::ptr::null_mut();
318static mut PROTO_ENT: ProtoEnt = ProtoEnt {
319    p_name: core::ptr::null_mut(),
320    p_aliases: core::ptr::null_mut(),
321    p_proto: 0,
322};
323static mut PROTO_BUF: [c_char; 1024] = [0; 1024];
324static mut PROTO_ALIASES: [*mut c_char; 16] = [core::ptr::null_mut(); 16];
325static mut PROTO_IDX: usize = 0;
326
327unsafe fn proto_parse(line: *const c_char) -> bool {
328    let mut toks: [*mut c_char; 24] = [core::ptr::null_mut(); 24];
329    let n = nd_tokens(line, PROTO_BUF.as_mut_ptr(), PROTO_BUF.len(), &mut toks);
330    if n < 2 { return false; }
331    let num = crate::strtol(toks[1], core::ptr::null_mut(), 10);
332    if num < 0 || num > 255 { return false; }
333    PROTO_ENT.p_name = toks[0];
334    PROTO_ENT.p_proto = num as c_int;
335    let mut ai = 0usize;
336    for i in 2..n {
337        if ai + 1 >= PROTO_ALIASES.len() { break; }
338        PROTO_ALIASES[ai] = toks[i];
339        ai += 1;
340    }
341    PROTO_ALIASES[ai] = core::ptr::null_mut();
342    PROTO_ENT.p_aliases = PROTO_ALIASES.as_mut_ptr();
343    true
344}
345
346unsafe fn proto_from_table(i: usize) -> bool {
347    if i >= PROTO_TABLE.len() { return false; }
348    PROTO_ENT.p_name = PROTO_TABLE[i].0.as_ptr() as *mut c_char;
349    PROTO_ENT.p_proto = PROTO_TABLE[i].1;
350    PROTO_ALIASES[0] = core::ptr::null_mut();
351    PROTO_ENT.p_aliases = PROTO_ALIASES.as_mut_ptr();
352    true
353}
354
355unsafe fn proto_file() -> *mut FILE {
356    if PROTO_FILE.is_null() {
357        PROTO_FILE = crate::fopen(b"/etc/protocols\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
358    }
359    PROTO_FILE
360}
361
362#[no_mangle]
363pub unsafe extern "C" fn setprotoent(stayopen: c_int) {
364    endprotoent();
365    PROTO_IDX = 0;
366    PROTO_FILE = crate::fopen(b"/etc/protocols\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
367    let _ = stayopen;
368}
369
370#[no_mangle]
371pub unsafe extern "C" fn endprotoent() {
372    if !PROTO_FILE.is_null() {
373        crate::fclose(PROTO_FILE);
374        PROTO_FILE = core::ptr::null_mut();
375    }
376    PROTO_IDX = 0;
377}
378
379#[no_mangle]
380pub unsafe extern "C" fn getprotoent() -> *mut ProtoEnt {
381    if PROTO_FILE.is_null() {
382        let f = crate::fopen(b"/etc/protocols\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
383        if f.is_null() {
384            let ok = proto_from_table(PROTO_IDX);
385            PROTO_IDX += 1;
386            return if ok { &raw mut PROTO_ENT } else { core::ptr::null_mut() };
387        }
388        PROTO_FILE = f;
389    }
390    let mut line = [0 as c_char; 1024];
391    while !crate::fgets(line.as_mut_ptr(), line.len() as c_int, PROTO_FILE).is_null() {
392        if proto_parse(line.as_ptr()) { return &raw mut PROTO_ENT; }
393    }
394    core::ptr::null_mut()
395}
396
397unsafe fn proto_name_matches(name: *const c_char) -> bool {
398    if crate::strcmp(PROTO_ENT.p_name as *const u8, name as *const u8) == 0 { return true; }
399    let mut i = 0usize;
400    while !(*PROTO_ENT.p_aliases.add(i)).is_null() {
401        if crate::strcmp(*PROTO_ENT.p_aliases.add(i) as *const u8, name as *const u8) == 0 { return true; }
402        i += 1;
403    }
404    false
405}
406
407unsafe fn proto_scan(name: *const c_char, num: c_int, by_name: bool) -> bool {
408    let f = crate::fopen(b"/etc/protocols\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
409    if !f.is_null() {
410        let mut line = [0 as c_char; 1024];
411        while !crate::fgets(line.as_mut_ptr(), line.len() as c_int, f).is_null() {
412            if !proto_parse(line.as_ptr()) { continue; }
413            let hit = if by_name { proto_name_matches(name) } else { PROTO_ENT.p_proto == num };
414            if hit { crate::fclose(f); return true; }
415        }
416        crate::fclose(f);
417    }
418    for i in 0..PROTO_TABLE.len() {
419        proto_from_table(i);
420        let hit = if by_name { proto_name_matches(name) } else { PROTO_ENT.p_proto == num };
421        if hit { return true; }
422    }
423    false
424}
425
426#[no_mangle]
427pub unsafe extern "C" fn getprotobyname(name: *const c_char) -> *mut ProtoEnt {
428    if name.is_null() { return core::ptr::null_mut(); }
429    if proto_scan(name, 0, true) { &raw mut PROTO_ENT } else { core::ptr::null_mut() }
430}
431
432#[no_mangle]
433pub unsafe extern "C" fn getprotobynumber(num: c_int) -> *mut ProtoEnt {
434    if proto_scan(core::ptr::null(), num, false) { &raw mut PROTO_ENT } else { core::ptr::null_mut() }
435}
436
437// ------------------------------------------------------------------
438// /etc/networks
439// ------------------------------------------------------------------
440
441static mut NET_FILE: *mut FILE = core::ptr::null_mut();
442static mut NET_ENT: NetEnt = NetEnt {
443    n_name: core::ptr::null_mut(),
444    n_aliases: core::ptr::null_mut(),
445    n_addrtype: AF_INET,
446    n_net: 0,
447};
448static mut NET_BUF: [c_char; 1024] = [0; 1024];
449static mut NET_ALIASES: [*mut c_char; 16] = [core::ptr::null_mut(); 16];
450
451unsafe fn net_parse(line: *const c_char) -> bool {
452    let mut toks: [*mut c_char; 24] = [core::ptr::null_mut(); 24];
453    let n = nd_tokens(line, NET_BUF.as_mut_ptr(), NET_BUF.len(), &mut toks);
454    if n < 2 { return false; }
455    let net = inet_network(toks[1]);
456    if net == u32::MAX { return false; }
457    NET_ENT.n_name = toks[0];
458    NET_ENT.n_addrtype = AF_INET;
459    NET_ENT.n_net = net;
460    let mut ai = 0usize;
461    for i in 2..n {
462        if ai + 1 >= NET_ALIASES.len() { break; }
463        NET_ALIASES[ai] = toks[i];
464        ai += 1;
465    }
466    NET_ALIASES[ai] = core::ptr::null_mut();
467    NET_ENT.n_aliases = NET_ALIASES.as_mut_ptr();
468    true
469}
470
471unsafe fn net_next(f: *mut FILE) -> bool {
472    let mut line = [0 as c_char; 1024];
473    while !crate::fgets(line.as_mut_ptr(), line.len() as c_int, f).is_null() {
474        if net_parse(line.as_ptr()) { return true; }
475    }
476    false
477}
478
479#[no_mangle]
480pub unsafe extern "C" fn setnetent(stayopen: c_int) {
481    endnetent();
482    NET_FILE = crate::fopen(b"/etc/networks\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
483    let _ = stayopen;
484}
485
486#[no_mangle]
487pub unsafe extern "C" fn endnetent() {
488    if !NET_FILE.is_null() {
489        crate::fclose(NET_FILE);
490        NET_FILE = core::ptr::null_mut();
491    }
492}
493
494#[no_mangle]
495pub unsafe extern "C" fn getnetent() -> *mut NetEnt {
496    if NET_FILE.is_null() {
497        NET_FILE = crate::fopen(b"/etc/networks\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
498        if NET_FILE.is_null() { return core::ptr::null_mut(); }
499    }
500    if net_next(NET_FILE) { &raw mut NET_ENT } else { core::ptr::null_mut() }
501}
502
503unsafe fn net_name_matches(name: *const c_char) -> bool {
504    if crate::strcmp(NET_ENT.n_name as *const u8, name as *const u8) == 0 { return true; }
505    let mut i = 0usize;
506    while !(*NET_ENT.n_aliases.add(i)).is_null() {
507        if crate::strcmp(*NET_ENT.n_aliases.add(i) as *const u8, name as *const u8) == 0 { return true; }
508        i += 1;
509    }
510    false
511}
512
513#[no_mangle]
514pub unsafe extern "C" fn getnetbyname(name: *const c_char) -> *mut NetEnt {
515    if name.is_null() { return core::ptr::null_mut(); }
516    let f = crate::fopen(b"/etc/networks\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
517    if !f.is_null() {
518        while net_next(f) {
519            if net_name_matches(name) { crate::fclose(f); return &raw mut NET_ENT; }
520        }
521        crate::fclose(f);
522    }
523    // "loopback" / "default" are always available even without the file.
524    if crate::cstr_eq(name as *const u8, b"loopback") {
525        net_parse(b"loopback 127.0.0.0\0".as_ptr() as *const c_char);
526        return &raw mut NET_ENT;
527    }
528    if crate::cstr_eq(name as *const u8, b"default") {
529        net_parse(b"default 0.0.0.0\0".as_ptr() as *const c_char);
530        return &raw mut NET_ENT;
531    }
532    core::ptr::null_mut()
533}
534
535#[no_mangle]
536pub unsafe extern "C" fn getnetbyaddr(net: u32, type_: c_int) -> *mut NetEnt {
537    if type_ != AF_INET { return core::ptr::null_mut(); }
538    let f = crate::fopen(b"/etc/networks\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
539    if !f.is_null() {
540        while net_next(f) {
541            let shift = if NET_ENT.n_net < 0x80000000 { 24 }
542                else if NET_ENT.n_net < 0xc0000000 { 16 } else { 8 };
543            if (NET_ENT.n_net >> shift) == (net >> shift) { crate::fclose(f); return &raw mut NET_ENT; }
544        }
545        crate::fclose(f);
546    }
547    core::ptr::null_mut()
548}
549
550// ------------------------------------------------------------------
551// /etc/ethers
552// ------------------------------------------------------------------
553
554unsafe fn ether_line_cap(
555    line: *const c_char,
556    ea: *mut u8,
557    hostname: *mut c_char,
558    hostname_cap: usize,
559) -> c_int {
560    if line.is_null() || ea.is_null() || hostname.is_null() || hostname_cap == 0 { return -1; }
561    let mut buf = [0 as c_char; 512];
562    let mut toks: [*mut c_char; 24] = [core::ptr::null_mut(); 24];
563    let n = nd_tokens(line, buf.as_mut_ptr(), buf.len(), &mut toks);
564    if n < 2 { return -1; }
565    if ether_aton_r(toks[0], ea).is_null() { return -1; }
566    let mut i = 0usize;
567    while *toks[1].add(i) != 0 {
568        if i + 1 >= hostname_cap { return -1; }
569        *hostname.add(i) = *toks[1].add(i);
570        i += 1;
571    }
572    *hostname.add(i) = 0;
573    0
574}
575
576#[no_mangle]
577pub unsafe extern "C" fn ether_line(line: *const c_char, ea: *mut u8, hostname: *mut c_char) -> c_int {
578    // The historical ABI has no buffer length; a hostname is at most 255
579    // bytes in practice, so bound the copy to that.
580    ether_line_cap(line, ea, hostname, 256)
581}
582
583unsafe fn ether_scan(want_name: *const c_char, ea: *mut u8, hostname: *mut c_char) -> c_int {
584    let f = crate::fopen(b"/etc/ethers\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
585    if f.is_null() { return -1; }
586    let mut line = [0 as c_char; 512];
587    let mut found = -1;
588    while !crate::fgets(line.as_mut_ptr(), line.len() as c_int, f).is_null() {
589        let mut mac = [0u8; 6];
590        let mut host = [0 as c_char; 256];
591        if ether_line_cap(line.as_ptr(), mac.as_mut_ptr(), host.as_mut_ptr(), host.len()) != 0 {
592            continue;
593        }
594        if !want_name.is_null() {
595            if crate::strcmp(host.as_ptr() as *const u8, want_name as *const u8) != 0 { continue; }
596            core::ptr::copy_nonoverlapping(mac.as_ptr(), ea, 6);
597            found = 0;
598            break;
599        } else {
600            let mut same = true;
601            for i in 0..6 {
602                if mac[i] != *ea.add(i) { same = false; break; }
603            }
604            if !same { continue; }
605            let mut i = 0usize;
606            while host[i] != 0 && i + 1 < 256 {
607                *hostname.add(i) = host[i];
608                i += 1;
609            }
610            *hostname.add(i) = 0;
611            found = 0;
612            break;
613        }
614    }
615    crate::fclose(f);
616    found
617}
618
619#[no_mangle]
620pub unsafe extern "C" fn ether_hostton(hostname: *const c_char, ea: *mut u8) -> c_int {
621    if hostname.is_null() || ea.is_null() { return -1; }
622    ether_scan(hostname, ea, core::ptr::null_mut())
623}
624
625#[no_mangle]
626pub unsafe extern "C" fn ether_ntohost(hostname: *mut c_char, ea: *const u8) -> c_int {
627    if hostname.is_null() || ea.is_null() { return -1; }
628    ether_scan(core::ptr::null(), ea as *mut u8, hostname)
629}
630
631// ------------------------------------------------------------------
632// /etc/hosts iteration and reverse lookups
633// ------------------------------------------------------------------
634
635static mut HOSTS_FILE: *mut FILE = core::ptr::null_mut();
636static mut HOSTS_BUF: [c_char; 1024] = [0; 1024];
637static mut HOSTS_ADDR: [u8; 4] = [0; 4];
638static mut HOSTS_ADDR_PTRS: [*mut c_char; 2] = [core::ptr::null_mut(); 2];
639static mut HOSTS_ALIASES: [*mut c_char; 16] = [core::ptr::null_mut(); 16];
640
641unsafe fn hosts_parse(line: *const c_char) -> bool {
642    let mut toks: [*mut c_char; 24] = [core::ptr::null_mut(); 24];
643    let n = nd_tokens(line, HOSTS_BUF.as_mut_ptr(), HOSTS_BUF.len(), &mut toks);
644    if n < 2 { return false; }
645    if inet_pton(AF_INET, toks[0], HOSTS_ADDR.as_mut_ptr() as *mut c_void) != 1 { return false; }
646    HOST_ENT.h_name = toks[1];
647    HOST_ENT.h_addrtype = AF_INET;
648    HOST_ENT.h_length = 4;
649    HOST_ENT.h_addr_list = HOSTS_ADDR_PTRS.as_mut_ptr();
650    HOSTS_ADDR_PTRS[0] = HOSTS_ADDR.as_mut_ptr() as *mut c_char;
651    HOSTS_ADDR_PTRS[1] = core::ptr::null_mut();
652    let mut ai = 0usize;
653    for i in 2..n {
654        if ai + 1 >= HOSTS_ALIASES.len() { break; }
655        HOSTS_ALIASES[ai] = toks[i];
656        ai += 1;
657    }
658    HOSTS_ALIASES[ai] = core::ptr::null_mut();
659    HOST_ENT.h_aliases = HOSTS_ALIASES.as_mut_ptr();
660    true
661}
662
663#[no_mangle]
664pub unsafe extern "C" fn sethostent(_stayopen: c_int) {
665    endhostent();
666}
667
668#[no_mangle]
669pub unsafe extern "C" fn endhostent() {
670    if !HOSTS_FILE.is_null() {
671        crate::fclose(HOSTS_FILE);
672        HOSTS_FILE = core::ptr::null_mut();
673    }
674}
675
676#[no_mangle]
677pub unsafe extern "C" fn gethostent() -> *mut HostEnt {
678    if HOSTS_FILE.is_null() {
679        HOSTS_FILE = crate::fopen(b"/etc/hosts\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
680        if HOSTS_FILE.is_null() { return core::ptr::null_mut(); }
681    }
682    let mut line = [0 as c_char; 1024];
683    while !crate::fgets(line.as_mut_ptr(), line.len() as c_int, HOSTS_FILE).is_null() {
684        if hosts_parse(line.as_ptr()) { return &raw mut HOST_ENT; }
685    }
686    core::ptr::null_mut()
687}
688
689unsafe fn hosts_lookup_addr(addr: *const u8, family: c_int) -> bool {
690    let f = crate::fopen(b"/etc/hosts\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
691    if f.is_null() { return false; }
692    let mut line = [0 as c_char; 1024];
693    let mut found = false;
694    while !crate::fgets(line.as_mut_ptr(), line.len() as c_int, f).is_null() {
695        let mut toks: [*mut c_char; 24] = [core::ptr::null_mut(); 24];
696        let n = nd_tokens(line.as_ptr(), HOSTS_BUF.as_mut_ptr(), HOSTS_BUF.len(), &mut toks);
697        if n < 2 { continue; }
698        let mut tmp = [0u8; 16];
699        if inet_pton(AF_INET, toks[0], tmp.as_mut_ptr() as *mut c_void) == 1 {
700            if family != AF_INET { continue; }
701        } else if inet_pton(AF_INET6, toks[0], tmp.as_mut_ptr() as *mut c_void) == 1 {
702            if family != AF_INET6 { continue; }
703        } else {
704            continue;
705        }
706        let len = if family == AF_INET6 { 16 } else { 4 };
707        let mut same = true;
708        for i in 0..len {
709            if tmp[i] != *addr.add(i) { same = false; break; }
710        }
711        if !same { continue; }
712        let nl = crate::strlen(toks[1]);
713        if nl >= HOST_NAME.len() { continue; }
714        core::ptr::copy_nonoverlapping(toks[1], HOST_NAME.as_mut_ptr(), nl + 1);
715        found = true;
716        break;
717    }
718    crate::fclose(f);
719    found
720}
721
722unsafe fn hosts_lookup_name(name: *const c_char) -> bool {
723    let f = crate::fopen(b"/etc/hosts\0".as_ptr() as *const c_char, b"r\0".as_ptr() as *const c_char);
724    if f.is_null() { return false; }
725    let mut line = [0 as c_char; 1024];
726    let mut found = false;
727    while !crate::fgets(line.as_mut_ptr(), line.len() as c_int, f).is_null() {
728        if !hosts_parse(line.as_ptr()) { continue; }
729        let mut hit = crate::strcmp(HOST_ENT.h_name as *const u8, name as *const u8) == 0;
730        if !hit {
731            let mut i = 0usize;
732            while !(*HOST_ENT.h_aliases.add(i)).is_null() {
733                if crate::strcmp(*HOST_ENT.h_aliases.add(i) as *const u8, name as *const u8) == 0 {
734                    hit = true;
735                    break;
736                }
737                i += 1;
738            }
739        }
740        if hit { found = true; break; }
741    }
742    crate::fclose(f);
743    found
744}
745
746// ------------------------------------------------------------------
747// getnameinfo
748// ------------------------------------------------------------------
749
750unsafe fn nd_itoa(mut v: u32, out: *mut c_char) -> usize {
751    let mut digits = [0u8; 10];
752    let mut n = 0usize;
753    if v == 0 { digits[0] = 0; n = 1; }
754    while v > 0 { digits[n] = (v % 10) as u8; v /= 10; n += 1; }
755    let mut o = 0usize;
756    while n > 0 { n -= 1; *out.add(o) = (b'0' + digits[n]) as c_char; o += 1; }
757    *out.add(o) = 0;
758    o
759}
760
761unsafe fn nd_reverse6(addr: *const u8, out: *mut c_char, cap: usize) -> bool {
762    if cap < 74 { return false; }
763    let hex = b"0123456789abcdef";
764    let mut o = 0usize;
765    let mut i = 16isize;
766    while i > 0 {
767        i -= 1;
768        let b = *addr.add(i as usize);
769        *out.add(o) = hex[(b & 0xf) as usize] as c_char; o += 1;
770        *out.add(o) = b'.' as c_char; o += 1;
771        *out.add(o) = hex[(b >> 4) as usize] as c_char; o += 1;
772        *out.add(o) = b'.' as c_char; o += 1;
773    }
774    for &c in b"ip6.arpa\0" { *out.add(o) = c as c_char; o += 1; }
775    true
776}
777
778#[no_mangle]
779pub unsafe extern "C" fn getnameinfo(
780    sa: *const c_void,
781    salen: u32,
782    host: *mut c_char,
783    hostlen: u32,
784    serv: *mut c_char,
785    servlen: u32,
786    flags: c_int,
787) -> c_int {
788    name_lock();
789    let r = getnameinfo_locked(sa, salen, host, hostlen, serv, servlen, flags);
790    name_unlock();
791    r
792}
793
794unsafe fn getnameinfo_locked(
795    sa: *const c_void,
796    salen: u32,
797    host: *mut c_char,
798    hostlen: u32,
799    serv: *mut c_char,
800    servlen: u32,
801    flags: c_int,
802) -> c_int {
803    if sa.is_null() { return EAI_FAIL_V; }
804    let family = core::ptr::read_unaligned(sa as *const u16) as c_int;
805    let mut addr = [0u8; 16];
806    let mut scope: u32 = 0;
807    let port: u16;
808    match family {
809        AF_INET => {
810            if salen < 16 { return EAI_FAMILY_V; }
811            port = u16::from_be(core::ptr::read_unaligned((sa as *const u8).add(2) as *const u16));
812            core::ptr::copy_nonoverlapping((sa as *const u8).add(4), addr.as_mut_ptr(), 4);
813        }
814        AF_INET6 => {
815            if salen < 28 { return EAI_FAMILY_V; }
816            port = u16::from_be(core::ptr::read_unaligned((sa as *const u8).add(2) as *const u16));
817            core::ptr::copy_nonoverlapping((sa as *const u8).add(8), addr.as_mut_ptr(), 16);
818            scope = core::ptr::read_unaligned((sa as *const u8).add(24) as *const u32);
819        }
820        _ => return EAI_FAMILY_V,
821    }
822
823    if !host.is_null() && hostlen > 0 {
824        let mut buf = [0 as c_char; 300];
825        let mut have = false;
826        if flags & NI_NUMERICHOST_V == 0 {
827            have = hosts_lookup_addr(addr.as_ptr(), family);
828            if have {
829                let l = crate::strlen(HOST_NAME.as_ptr());
830                let l = core::cmp::min(l, buf.len() - 1);
831                core::ptr::copy_nonoverlapping(HOST_NAME.as_ptr(), buf.as_mut_ptr(), l);
832                buf[l] = 0;
833            }
834            if !have {
835                let mut ptr = [0 as c_char; 80];
836                let ok = if family == AF_INET {
837                    let a = addr;
838                    // d.c.b.a.in-addr.arpa
839                    let mut o = 0usize;
840                    let mut i = 4usize;
841                    while i > 0 {
842                        i -= 1;
843                        o += nd_itoa(a[i] as u32, ptr.as_mut_ptr().add(o));
844                        *ptr.as_mut_ptr().add(o) = b'.' as c_char;
845                        o += 1;
846                    }
847                    for &c in b"in-addr.arpa\0" { *ptr.as_mut_ptr().add(o) = c as c_char; o += 1; }
848                    true
849                } else {
850                    nd_reverse6(addr.as_ptr(), ptr.as_mut_ptr(), ptr.len())
851                };
852                if ok {
853                    let mut answer = [0u8; 512];
854                    let r = res_query(ptr.as_ptr() as *const c_char, 1, 12, answer.as_mut_ptr(), answer.len() as c_int);
855                    if r >= 12 {
856                        let len = r as usize;
857                        if let Some(msg) = InBuf::new(answer.as_ptr(), len) {
858                            let qd = msg.peek_u16_be(4).unwrap_or(0) as usize;
859                            let an = msg.peek_u16_be(6).unwrap_or(0) as usize;
860                            let mut p = 12usize;
861                            for _ in 0..qd {
862                                p = match dns_skip_name(&msg, p) {
863                                    Some(v) => v,
864                                    None => { p = len; break; }
865                                };
866                                p = match p.checked_add(4) {
867                                    Some(v) if v <= len => v,
868                                    _ => { p = len; break; }
869                                };
870                            }
871                            for _ in 0..an {
872                                p = match dns_skip_name(&msg, p) {
873                                    Some(v) => v,
874                                    None => break,
875                                };
876                                let typ = match msg.peek_u16_be(p) {
877                                    Some(v) => v,
878                                    None => break,
879                                };
880                                let rdlen = match msg.peek_u16_be(p + 8) {
881                                    Some(v) => v as usize,
882                                    None => break,
883                                };
884                                let rdata_off = match p.checked_add(10) {
885                                    Some(v) => v,
886                                    None => break,
887                                };
888                                let rdata_end = match rdata_off.checked_add(rdlen) {
889                                    Some(v) if v <= len => v,
890                                    _ => break,
891                                };
892                                if typ == 12 {
893                                    let mut dst = match OutBuf::new(buf.as_mut_ptr() as *mut u8, buf.len()) {
894                                        Some(v) => v,
895                                        None => break,
896                                    };
897                                    let max_steps = len / 2 + 1;
898                                    if dns_expand_name_at(&msg, rdata_off, &mut dst, max_steps, 16).is_some() {
899                                        let l = crate::strlen(buf.as_ptr());
900                                        have = l > 0;
901                                        break;
902                                    }
903                                }
904                                p = rdata_end;
905                            }
906                        }
907                    }
908                }
909            }
910        }
911        if !have {
912            if flags & NI_NAMEREQD_V != 0 { return EAI_NONAME_V; }
913            let aptr = if family == AF_INET { addr.as_ptr() as *const c_void } else { addr.as_ptr() as *const c_void };
914            if inet_ntop(family, aptr, buf.as_mut_ptr(), buf.len() as u32).is_null() {
915                return EAI_FAIL_V;
916            }
917            if scope != 0 && family == AF_INET6 {
918                let mut l = crate::strlen(buf.as_ptr());
919                *buf.as_mut_ptr().add(l) = b'%' as c_char;
920                l += 1;
921                let mut name = [0 as c_char; 32];
922                let have_name = flags & NI_NUMERICSCOPE_V == 0
923                    && if_indextoname(scope, name.as_mut_ptr()) != core::ptr::null_mut();
924                if have_name {
925                    let nl = crate::strlen(name.as_ptr());
926                    core::ptr::copy_nonoverlapping(name.as_ptr(), buf.as_mut_ptr().add(l), nl + 1);
927                } else {
928                    nd_itoa(scope, buf.as_mut_ptr().add(l));
929                }
930            }
931        }
932        if flags & NI_NOFQDN_V != 0 {
933            let mut i = 0usize;
934            while buf[i] != 0 {
935                if buf[i] == b'.' as c_char { buf[i] = 0; break; }
936                i += 1;
937            }
938        }
939        if crate::strlen(buf.as_ptr()) >= hostlen as usize { return EAI_OVERFLOW_V; }
940        let l = crate::strlen(buf.as_ptr());
941        core::ptr::copy_nonoverlapping(buf.as_ptr(), host, l + 1);
942    }
943
944    if !serv.is_null() && servlen > 0 {
945        let mut buf = [0 as c_char; 64];
946        let mut have = false;
947        if flags & NI_NUMERICSERV_V == 0 {
948            let proto = if flags & NI_DGRAM_V != 0 { b"udp\0" } else { b"tcp\0" };
949            let port_net = (port as u16).to_be() as c_int;
950            let se = getservbyport(port_net, proto.as_ptr() as *const c_char);
951            if !se.is_null() {
952                let l = crate::strlen((*se).s_name);
953                if l < buf.len() {
954                    core::ptr::copy_nonoverlapping((*se).s_name, buf.as_mut_ptr(), l + 1);
955                    have = true;
956                }
957            }
958        }
959        if !have {
960            nd_itoa(port as u32, buf.as_mut_ptr());
961        }
962        if crate::strlen(buf.as_ptr()) >= servlen as usize { return EAI_OVERFLOW_V; }
963        let l = crate::strlen(buf.as_ptr());
964        core::ptr::copy_nonoverlapping(buf.as_ptr(), serv, l + 1);
965    }
966    0
967}
968
969// ------------------------------------------------------------------
970// getaddrinfo
971// ------------------------------------------------------------------
972
973unsafe fn nd_make_addrinfo(
974    family: c_int,
975    socktype: c_int,
976    protocol: c_int,
977    addr: *const u8,
978    port: u16,
979    scope: u32,
980    flags: c_int,
981    canon: *const c_char,
982) -> *mut AddrInfo {
983    let addrlen: usize = if family == AF_INET6 { 28 } else { 16 };
984    let canonlen = if !canon.is_null() { crate::strlen(canon) + 1 } else { 0 };
985    let total = core::mem::size_of::<AddrInfo>() + addrlen + canonlen;
986    let p = crate::malloc(total) as *mut u8;
987    if p.is_null() { return core::ptr::null_mut(); }
988    core::ptr::write_bytes(p, 0, total);
989    let ai = p as *mut AddrInfo;
990    (*ai).ai_flags = flags;
991    (*ai).ai_family = family;
992    (*ai).ai_socktype = socktype;
993    (*ai).ai_protocol = protocol;
994    (*ai).ai_addrlen = addrlen as u32;
995    let sa = p.add(core::mem::size_of::<AddrInfo>());
996    (*ai).ai_addr = sa as *mut c_void;
997    if family == AF_INET6 {
998        *(sa as *mut u16) = AF_INET6 as u16;
999        *(sa.add(2) as *mut u16) = port.to_be();
1000        *(sa.add(24) as *mut u32) = scope;
1001        core::ptr::copy_nonoverlapping(addr, sa.add(8), 16);
1002    } else {
1003        *(sa as *mut u16) = AF_INET as u16;
1004        *(sa.add(2) as *mut u16) = port.to_be();
1005        core::ptr::copy_nonoverlapping(addr, sa.add(4), 4);
1006    }
1007    if canonlen > 0 {
1008        let c = sa.add(addrlen);
1009        core::ptr::copy_nonoverlapping(canon as *const u8, c, canonlen);
1010        (*ai).ai_canonname = c as *mut c_char;
1011    }
1012    ai
1013}
1014
1015unsafe fn nd_parse_service(service: *const c_char, socktype: c_int, protocol: c_int, port: *mut u16, proto_out: *mut c_int) -> bool {
1016    if service.is_null() { *port = 0; return true; }
1017    let mut end: *mut c_char = core::ptr::null_mut();
1018    let v = crate::strtoul(service, &mut end, 10);
1019    let numeric = !end.is_null() && *end == 0;
1020    if numeric {
1021        if v > 65535 { return false; }
1022        *port = v as u16;
1023        return true;
1024    }
1025    let proto_name: *const c_char = if protocol == 6 { b"tcp\0".as_ptr() as *const c_char }
1026        else if protocol == 17 { b"udp\0".as_ptr() as *const c_char }
1027        else if socktype == SOCK_STREAM { b"tcp\0".as_ptr() as *const c_char }
1028        else if socktype == SOCK_DGRAM { b"udp\0".as_ptr() as *const c_char }
1029        else { core::ptr::null() };
1030    let se = getservbyname(service, proto_name);
1031    if se.is_null() { return false; }
1032    *port = ntohs((*se).s_port as u16);
1033    *proto_out = if crate::cstr_eq((*se).s_proto as *const u8, b"udp") { 17 } else { 6 };
1034    true
1035}
1036
1037#[no_mangle]
1038pub unsafe extern "C" fn getaddrinfo(
1039    node: *const c_char,
1040    service: *const c_char,
1041    hints: *const AddrInfo,
1042    res: *mut *mut AddrInfo,
1043) -> c_int {
1044    name_lock();
1045    let r = getaddrinfo_locked(node, service, hints, res);
1046    name_unlock();
1047    r
1048}
1049
1050unsafe fn getaddrinfo_locked(
1051    node: *const c_char,
1052    service: *const c_char,
1053    hints: *const AddrInfo,
1054    res: *mut *mut AddrInfo,
1055) -> c_int {
1056    if res.is_null() { return EAI_FAIL_V; }
1057    *res = core::ptr::null_mut();
1058
1059    let mut family = 0;
1060    let mut socktype = 0;
1061    let mut protocol = 0;
1062    let mut flags = 0;
1063    if !hints.is_null() {
1064        family = (*hints).ai_family;
1065        socktype = (*hints).ai_socktype;
1066        protocol = (*hints).ai_protocol;
1067        flags = (*hints).ai_flags;
1068    }
1069    if family != 0 && family != AF_INET && family != AF_INET6 { return EAI_FAMILY_V; }
1070    if socktype != 0 && socktype != SOCK_STREAM && socktype != SOCK_DGRAM { return EAI_SOCKTYPE_V; }
1071
1072    // musl's AI_ADDRCONFIG: a family counts as configured when a UDP socket
1073    // can connect to its loopback address. Unsupported/unreachable families
1074    // are dropped (or turn into EAI_NODATA when explicitly requested).
1075    if flags & AI_ADDRCONFIG_V != 0 {
1076        #[repr(C)]
1077        struct Lo6 {
1078            family: u16,
1079            port: u16,
1080            flowinfo: u32,
1081            addr: [u8; 16],
1082            scope_id: u32,
1083        }
1084        let lo4 = SockAddrIn {
1085            sin_family: AF_INET as u16,
1086            sin_port: 65535u16.to_be(),
1087            sin_addr: 0x7f000001,
1088            sin_zero: [0; 8],
1089        };
1090        let mut v6addr = [0u8; 16];
1091        v6addr[15] = 1;
1092        let lo6 = Lo6 {
1093            family: AF_INET6 as u16,
1094            port: 65535u16.to_be(),
1095            flowinfo: 0,
1096            addr: v6addr,
1097            scope_id: 0,
1098        };
1099        let tf = [AF_INET, AF_INET6];
1100        let tas: [*const c_void; 2] = [
1101            &lo4 as *const SockAddrIn as *const c_void,
1102            &lo6 as *const Lo6 as *const c_void,
1103        ];
1104        let tls = [
1105            core::mem::size_of::<SockAddrIn>() as u32,
1106            core::mem::size_of::<Lo6>() as u32,
1107        ];
1108        let mut no_family = false;
1109        for i in 0..2 {
1110            if family == tf[1 - i] { continue; }
1111            let s = crate::socket(tf[i], SOCK_DGRAM, 0);
1112            if s >= 0 {
1113                let r = crate::connect(s, tas[i] as *const crate::sockaddr, tls[i]);
1114                let e = ERRNO!();
1115                crate::close(s);
1116                if r == 0 { continue; }
1117                match e {
1118                    99 | 97 | 113 | 100 | 101 => {} // EADDRNOTAVAIL/AF/UNREACH/NETDOWN/NETUNREACH
1119                    _ => return EAI_SYSTEM_V,
1120                }
1121            }
1122            if family == tf[i] { no_family = true; }
1123            family = tf[1 - i];
1124        }
1125        if no_family { return EAI_NODATA_V; }
1126    }
1127    if flags & AI_NUMERICSERV_V != 0 && !service.is_null() {
1128        let mut end: *mut c_char = core::ptr::null_mut();
1129        let _ = crate::strtoul(service, &mut end, 10);
1130        if end.is_null() || *end != 0 { return EAI_NONAME_V; }
1131    }
1132
1133    let mut port: u16 = 0;
1134    let mut proto_from_service = 0;
1135    if !nd_parse_service(service, socktype, protocol, &mut port, &mut proto_from_service) {
1136        return EAI_SERVICE_V;
1137    }
1138
1139    let mut addrs: [[u8; 16]; 8] = [[0; 16]; 8];
1140    let mut fams: [c_int; 8] = [0; 8];
1141    let mut scopes: [u32; 8] = [0; 8];
1142    let mut count = 0usize;
1143    let mut canon: [c_char; 256] = [0; 256];
1144
1145    if node.is_null() {
1146        if family == 0 || family == AF_INET6 {
1147            addrs[count] = [0; 16];
1148            if flags & AI_PASSIVE_V == 0 {
1149                addrs[count][15] = 1;
1150            }
1151            fams[count] = AF_INET6;
1152            count += 1;
1153        }
1154        if family == 0 || family == AF_INET {
1155            addrs[count] = [0; 16];
1156            if flags & AI_PASSIVE_V == 0 {
1157                addrs[count][0] = 127;
1158                addrs[count][3] = 1;
1159            }
1160            fams[count] = AF_INET;
1161            count += 1;
1162        }
1163    } else {
1164        let mut numeric = false;
1165        let mut tmp = [0u8; 16];
1166        if inet_pton(AF_INET, node, tmp.as_mut_ptr() as *mut c_void) == 1 {
1167            numeric = true;
1168            if family == 0 || family == AF_INET {
1169                addrs[count][..4].copy_from_slice(&tmp[..4]);
1170                fams[count] = AF_INET;
1171                count += 1;
1172            } else if family == AF_INET6 && flags & AI_V4MAPPED_V != 0 {
1173                // ::ffff:a.b.c.d
1174                addrs[count][10] = 0xff;
1175                addrs[count][11] = 0xff;
1176                addrs[count][12..16].copy_from_slice(&tmp[..4]);
1177                fams[count] = AF_INET6;
1178                count += 1;
1179            }
1180        }
1181        // RFC 4007 scope suffix: fe80::1%eth0 or fe80::1%3.
1182        let mut ip6: *const c_char = node;
1183        let mut ip6buf = [0 as c_char; 64];
1184        let mut scope_id: u32 = 0;
1185        let mut has_scope = false;
1186        let mut i = 0usize;
1187        while *node.add(i) != 0 {
1188            if *node.add(i) == b'%' as c_char {
1189                if i >= ip6buf.len() { return EAI_NONAME_V; }
1190                core::ptr::copy_nonoverlapping(node, ip6buf.as_mut_ptr(), i);
1191                ip6buf[i] = 0;
1192                ip6 = ip6buf.as_ptr();
1193                has_scope = true;
1194                break;
1195            }
1196            i += 1;
1197        }
1198        if !numeric {
1199            if inet_pton(AF_INET6, ip6, tmp.as_mut_ptr() as *mut c_void) == 1 {
1200                numeric = true;
1201                if family == 0 || family == AF_INET6 {
1202                    if has_scope {
1203                        let p = node.add(i + 1);
1204                        let mut end: *mut c_char = core::ptr::null_mut();
1205                        let v = crate::strtoul(p, &mut end, 10);
1206                        let linklocal = (tmp[0] == 0xfe && (tmp[1] & 0xc0) == 0x80)
1207                            || (tmp[0] == 0xff && (tmp[1] & 0x0f) == 0x02);
1208                        if end.is_null() || *end != 0 {
1209                            if !linklocal { return EAI_NONAME_V; }
1210                            let idx = crate::if_nametoindex(p);
1211                            if idx == 0 { return EAI_NONAME_V; }
1212                            scope_id = idx;
1213                        } else {
1214                            if v > u32::MAX as u64 { return EAI_NONAME_V; }
1215                            scope_id = v as u32;
1216                        }
1217                    }
1218                    addrs[count] = tmp;
1219                    fams[count] = AF_INET6;
1220                    scopes[count] = scope_id;
1221                    count += 1;
1222                }
1223            }
1224        }
1225        if flags & AI_NUMERICHOST_V != 0 && !numeric {
1226            return EAI_NONAME_V;
1227        }
1228        if !numeric {
1229            let mut got = false;
1230            // Prefer /etc/hosts, then DNS.
1231            if hosts_lookup_name(node) {
1232                let l = core::cmp::min(crate::strlen(HOST_ENT.h_name), canon.len() - 1);
1233                core::ptr::copy_nonoverlapping(HOST_ENT.h_name, canon.as_mut_ptr(), l);
1234                canon[l] = 0;
1235                if family == 0 || family == AF_INET {
1236                    core::ptr::copy_nonoverlapping(HOSTS_ADDR.as_ptr(), addrs[count].as_mut_ptr(), 4);
1237                    fams[count] = AF_INET;
1238                    count += 1;
1239                    got = true;
1240                }
1241                // gethostbyname2 may return more than the hosts entry; fall
1242                // through for the requested family only when needed.
1243                if family == AF_INET6 {
1244                    got = false;
1245                }
1246            }
1247            if !got {
1248                let order: [c_int; 2] = if family == AF_INET6 { [AF_INET6, AF_INET] } else { [AF_INET, AF_INET6] };
1249                for &f in &order {
1250                    if family != 0 && family != f { continue; }
1251                    let h = gethostbyname2(node, f);
1252                    if h.is_null() { continue; }
1253                    let n = core::cmp::min((*h).h_length as usize, 16);
1254                    core::ptr::copy_nonoverlapping((*h).h_addr_list.read() as *const u8, addrs[count].as_mut_ptr(), n);
1255                    fams[count] = f;
1256                    count += 1;
1257                    let hl = crate::strlen((*h).h_name);
1258                    let l = core::cmp::min(hl, canon.len() - 1);
1259                    core::ptr::copy_nonoverlapping((*h).h_name, canon.as_mut_ptr(), l);
1260                    canon[l] = 0;
1261                    got = true;
1262                    if family != 0 { break; }
1263                }
1264            }
1265            // AF_INET6 + AI_V4MAPPED: fall back to (or, with AI_ALL, also
1266            // append) the IPv4 address mapped into ::ffff:a.b.c.d.
1267            if family == AF_INET6
1268                && flags & AI_V4MAPPED_V != 0
1269                && (flags & AI_ALL_V != 0 || !got)
1270                && count < addrs.len()
1271            {
1272                let h = gethostbyname2(node, AF_INET);
1273                if !h.is_null() && (*h).h_length >= 4 {
1274                    addrs[count][10] = 0xff;
1275                    addrs[count][11] = 0xff;
1276                    core::ptr::copy_nonoverlapping(
1277                        (*h).h_addr_list.read() as *const u8,
1278                        addrs[count].as_mut_ptr().add(12),
1279                        4,
1280                    );
1281                    fams[count] = AF_INET6;
1282                    count += 1;
1283                    got = true;
1284                }
1285            }
1286            if !got {
1287                return if h_errno == TRY_AGAIN { EAI_AGAIN_V } else { EAI_NONAME_V };
1288            }
1289        }
1290    }
1291    if count == 0 { return EAI_NONAME_V; }
1292
1293    let canonptr: *const c_char = if flags & AI_CANONNAME_V != 0 && canon[0] != 0 {
1294        canon.as_ptr()
1295    } else if flags & AI_CANONNAME_V != 0 && !node.is_null() {
1296        node
1297    } else {
1298        core::ptr::null()
1299    };
1300
1301    let mut head: *mut AddrInfo = core::ptr::null_mut();
1302    let mut tail: *mut AddrInfo = core::ptr::null_mut();
1303    let mut emitted = 0usize;
1304    for i in 0..count {
1305        let types: [c_int; 2] = if socktype == 0 { [SOCK_STREAM, SOCK_DGRAM] } else { [socktype, socktype] };
1306        let ntypes = if socktype == 0 { 2 } else { 1 };
1307        for t in 0..ntypes {
1308            let st = types[t];
1309            if protocol != 0 {
1310                if (protocol == 6 && st != SOCK_STREAM) || (protocol == 17 && st != SOCK_DGRAM) { continue; }
1311            }
1312            if proto_from_service != 0 && protocol == 0 {
1313                if (proto_from_service == 6 && st != SOCK_STREAM) || (proto_from_service == 17 && st != SOCK_DGRAM) { continue; }
1314            }
1315            let proto = if protocol != 0 { protocol } else if st == SOCK_STREAM { 6 } else { 17 };
1316            let cp = if emitted == 0 { canonptr } else { core::ptr::null() };
1317            let ai = nd_make_addrinfo(fams[i], st, proto, addrs[i].as_ptr(), port, scopes[i], flags, cp);
1318            if ai.is_null() {
1319                freeaddrinfo(head);
1320                return EAI_MEMORY_V;
1321            }
1322            if head.is_null() { head = ai; } else { (*tail).ai_next = ai; }
1323            tail = ai;
1324            emitted += 1;
1325        }
1326    }
1327    if emitted == 0 { return EAI_SERVICE_V; }
1328    *res = head;
1329    0
1330}
1331
1332#[no_mangle]
1333pub unsafe extern "C" fn freeaddrinfo(mut ai: *mut AddrInfo) {
1334    while !ai.is_null() {
1335        let next = (*ai).ai_next;
1336        crate::free(ai as *mut c_void);
1337        ai = next;
1338    }
1339}
1340
1341#[no_mangle]
1342pub unsafe extern "C" fn gai_strerror(code: c_int) -> *const c_char {
1343    let s: &[u8] = match code {
1344        EAI_BADFLAGS_V => b"Bad flags\0",
1345        EAI_NONAME_V => b"Name not known\0",
1346        EAI_AGAIN_V => b"Try again\0",
1347        EAI_FAIL_V => b"Non-recoverable failure\0",
1348        -5 => b"No address data\0",
1349        EAI_FAMILY_V => b"Unsupported family\0",
1350        EAI_SOCKTYPE_V => b"Unsupported socket type\0",
1351        EAI_SERVICE_V => b"Unsupported service\0",
1352        -9 => b"Address family not supported\0",
1353        EAI_MEMORY_V => b"Out of memory\0",
1354        EAI_SYSTEM_V => b"System error\0",
1355        EAI_OVERFLOW_V => b"Overflow\0",
1356        _ => b"Unknown error\0",
1357    };
1358    s.as_ptr() as *const c_char
1359}
1360
1361// ------------------------------------------------------------------
1362// ttyname
1363// ------------------------------------------------------------------
1364
1365#[no_mangle]
1366pub unsafe extern "C" fn ttyname_r(fd: c_int, name: *mut c_char, size: usize) -> c_int {
1367    if name.is_null() || size == 0 { return EINVAL; }
1368    if crate::isatty(fd) != 1 { return NDB_ENOTTY; }
1369    let mut procname = [0 as c_char; 32];
1370    let mut o = 0usize;
1371    for &c in b"/proc/self/fd/" { procname[o] = c as c_char; o += 1; }
1372    o += nd_itoa(fd as u32, procname.as_mut_ptr().add(o));
1373    procname[o] = 0;
1374    let n = crate::readlink(procname.as_ptr(), name, size - 1);
1375    if n < 0 { return ERRNO!(); }
1376    if n as usize == size - 1 { return NDB_ERANGE; }
1377    *name.add(n as usize) = 0;
1378    0
1379}
1380
1381#[no_mangle]
1382pub unsafe extern "C" fn ttyname(fd: c_int) -> *mut c_char {
1383    static mut TTY_BUF: [c_char; 64] = [0; 64];
1384    if ttyname_r(fd, TTY_BUF.as_mut_ptr(), TTY_BUF.len()) != 0 {
1385        core::ptr::null_mut()
1386    } else {
1387        TTY_BUF.as_mut_ptr()
1388    }
1389}
1390
1391// ------------------------------------------------------------------
1392// Reentrant host lookups
1393// ------------------------------------------------------------------
1394
1395unsafe fn host_copy_out(
1396    h: *mut HostEnt,
1397    ret: *mut HostEnt,
1398    buf: *mut c_char,
1399    buflen: usize,
1400    result: *mut *mut HostEnt,
1401) -> c_int {
1402    if result.is_null() { return EINVAL; }
1403    *result = core::ptr::null_mut();
1404    let ptrsz = core::mem::size_of::<*mut c_char>();
1405    let mut need = crate::strlen((*h).h_name) + 1;
1406    let mut nalias = 0usize;
1407    if !(*h).h_aliases.is_null() {
1408        while !(*(*h).h_aliases.add(nalias)).is_null() {
1409            need += crate::strlen(*(*h).h_aliases.add(nalias)) + 1;
1410            nalias += 1;
1411        }
1412    }
1413    let alen = (*h).h_length as usize;
1414    let align = (ptrsz - (buf as usize & (ptrsz - 1))) & (ptrsz - 1);
1415    need += align + (nalias + 1) * ptrsz + alen + 2 * ptrsz;
1416    if need > buflen { return NDB_ERANGE; }
1417
1418    let mut p = buf.add(align);
1419    let aliases = p as *mut *mut c_char;
1420    p = p.add((nalias + 1) * ptrsz);
1421    let addr_list = p as *mut *mut c_char;
1422    p = p.add(2 * ptrsz);
1423
1424    let n = crate::strlen((*h).h_name);
1425    core::ptr::copy_nonoverlapping((*h).h_name, p, n + 1);
1426    (*ret).h_name = p;
1427    p = p.add(n + 1);
1428
1429    for i in 0..nalias {
1430        let src = *(*h).h_aliases.add(i);
1431        let n = crate::strlen(src);
1432        core::ptr::copy_nonoverlapping(src, p, n + 1);
1433        *aliases.add(i) = p;
1434        p = p.add(n + 1);
1435    }
1436    *aliases.add(nalias) = core::ptr::null_mut();
1437
1438    let src = *(*h).h_addr_list;
1439    core::ptr::copy_nonoverlapping(src, p, alen);
1440    *addr_list = p;
1441    *addr_list.add(1) = core::ptr::null_mut();
1442
1443    (*ret).h_aliases = aliases;
1444    (*ret).h_addrtype = (*h).h_addrtype;
1445    (*ret).h_length = (*h).h_length;
1446    (*ret).h_addr_list = addr_list;
1447    *result = ret;
1448    0
1449}
1450
1451#[no_mangle]
1452pub unsafe extern "C" fn gethostbyname_r(
1453    name: *const c_char,
1454    ret: *mut HostEnt,
1455    buf: *mut c_char,
1456    buflen: usize,
1457    result: *mut *mut HostEnt,
1458    errnop: *mut c_int,
1459) -> c_int {
1460    gethostbyname2_r(name, AF_INET, ret, buf, buflen, result, errnop)
1461}
1462
1463#[no_mangle]
1464pub unsafe extern "C" fn gethostbyname2_r(
1465    name: *const c_char,
1466    af: c_int,
1467    ret: *mut HostEnt,
1468    buf: *mut c_char,
1469    buflen: usize,
1470    result: *mut *mut HostEnt,
1471    errnop: *mut c_int,
1472) -> c_int {
1473    if result.is_null() { return EINVAL; }
1474    *result = core::ptr::null_mut();
1475    let h = gethostbyname2(name, af);
1476    if h.is_null() {
1477        if !errnop.is_null() { *errnop = if h_errno != 0 { h_errno } else { HOST_NOT_FOUND }; }
1478        return 0;
1479    }
1480    let r = host_copy_out(h, ret, buf, buflen, result);
1481    if r == NDB_ERANGE {
1482        if !errnop.is_null() { *errnop = NO_RECOVERY; }
1483        *result = core::ptr::null_mut();
1484    }
1485    r
1486}
1487
1488#[no_mangle]
1489pub unsafe extern "C" fn gethostbyaddr_r(
1490    addr: *const c_void,
1491    len: u32,
1492    type_: c_int,
1493    ret: *mut HostEnt,
1494    buf: *mut c_char,
1495    buflen: usize,
1496    result: *mut *mut HostEnt,
1497    errnop: *mut c_int,
1498) -> c_int {
1499    if result.is_null() { return EINVAL; }
1500    *result = core::ptr::null_mut();
1501    let h = gethostbyaddr(addr, len, type_);
1502    if h.is_null() {
1503        if !errnop.is_null() { *errnop = if h_errno != 0 { h_errno } else { HOST_NOT_FOUND }; }
1504        return 0;
1505    }
1506    let r = host_copy_out(h, ret, buf, buflen, result);
1507    if r == NDB_ERANGE {
1508        if !errnop.is_null() { *errnop = NO_RECOVERY; }
1509        *result = core::ptr::null_mut();
1510    }
1511    r
1512}
1513
1514
1515#[no_mangle]
1516pub unsafe extern "C" fn initgroups(user: *const c_char, group: u32) -> c_int {
1517    if user.is_null() { ERRNO!() = EINVAL; return -1; }
1518    let mut buf = [0u32; 256];
1519    let mut n: c_int = buf.len() as c_int;
1520    if getgrouplist(user, group, buf.as_mut_ptr(), &mut n) < 0 {
1521        if n <= 0 { return -1; }
1522        let p = crate::malloc(n as usize * core::mem::size_of::<u32>()) as *mut u32;
1523        if p.is_null() { return -1; }
1524        let mut n2 = n;
1525        let r = getgrouplist(user, group, p, &mut n2);
1526        let rr = if r < 0 { -1 } else { crate::setgroups(n2 as usize, p) };
1527        crate::free(p as *mut c_void);
1528        return rr;
1529    }
1530    crate::setgroups(n as usize, buf.as_ptr())
1531}