1use super::arg_str;
18use crate::host::{with_host, JsObj};
19use fusevm::Value;
20use hickory_resolver::config::{NameServerConfig, ResolverConfig, GOOGLE};
21use hickory_resolver::lookup::Lookup;
22use hickory_resolver::net::runtime::TokioRuntimeProvider;
23use hickory_resolver::net::{DnsError, NetError};
24use hickory_resolver::proto::rr::{Name, RData, RecordType};
25use hickory_resolver::TokioResolver;
26use indexmap::IndexMap;
27use std::cell::RefCell;
28use std::net::{IpAddr, ToSocketAddrs};
29
30pub const METHODS: &[&str] = &[
31 "lookup",
33 "lookupService",
34 "resolve",
36 "resolve4",
37 "resolve6",
38 "resolveMx",
39 "resolveTxt",
40 "resolveCname",
41 "resolveNs",
42 "resolvePtr",
43 "resolveSrv",
44 "resolveSoa",
45 "resolveNaptr",
46 "resolveCaa",
47 "resolveTlsa",
48 "resolveAny",
49 "reverse",
50 "getServers",
52 "setServers",
53 "getDefaultResultOrder",
54 "setDefaultResultOrder",
55];
56
57pub const PROMISES_METHODS: &[&str] = &[
62 "lookup",
63 "lookupService",
64 "resolve",
65 "resolve4",
66 "resolve6",
67 "resolveMx",
68 "resolveTxt",
69 "resolveCname",
70 "resolveNs",
71 "resolvePtr",
72 "resolveSrv",
73 "resolveSoa",
74 "resolveNaptr",
75 "resolveCaa",
76 "resolveTlsa",
77 "resolveAny",
78 "reverse",
79 "getServers",
80 "setServers",
81 "getDefaultResultOrder",
82 "setDefaultResultOrder",
83];
84
85pub const RESOLVER_METHODS: &[&str] = &[
86 "getServers",
87 "setServers",
88 "resolve",
89 "resolve4",
90 "resolve6",
91 "resolveMx",
92 "resolveTxt",
93 "resolveCname",
94 "resolveNs",
95 "resolvePtr",
96 "resolveSrv",
97 "resolveSoa",
98 "resolveNaptr",
99 "resolveCaa",
100 "resolveTlsa",
101 "resolveAny",
102 "reverse",
103 "cancel",
104 "setLocalAddress",
105];
106
107pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
108 Some(match method {
109 "lookup" => lookup(args),
110 "lookupService" => lookup_service(args),
111 "resolve" => resolve_cb(args),
112 "resolve4" => cb_query(Query::A, args),
113 "resolve6" => cb_query(Query::Aaaa, args),
114 "resolveMx" => cb_query(Query::Mx, args),
115 "resolveTxt" => cb_query(Query::Txt, args),
116 "resolveCname" => cb_query(Query::Cname, args),
117 "resolveNs" => cb_query(Query::Ns, args),
118 "resolvePtr" => cb_query(Query::Ptr, args),
119 "resolveSrv" => cb_query(Query::Srv, args),
120 "resolveSoa" => cb_query(Query::Soa, args),
121 "resolveNaptr" => cb_query(Query::Naptr, args),
122 "resolveCaa" => cb_query(Query::Caa, args),
123 "resolveTlsa" => cb_query(Query::Tlsa, args),
124 "resolveAny" => cb_query(Query::Any, args),
125 "reverse" => cb_query(Query::Reverse, args),
126 "getServers" => get_servers(),
127 "setServers" => set_servers(args),
128 "getDefaultResultOrder" => Ok(get_default_result_order()),
129 "setDefaultResultOrder" => set_default_result_order(args),
130 "promiseLookup" => promise_lookup(args),
131 "promiseLookupService" => promise_lookup_service(args),
132 "promiseResolve" => resolve_promise(args),
133 "promiseResolve4" => promise_query(Query::A, args),
134 "promiseResolve6" => promise_query(Query::Aaaa, args),
135 "promiseResolveMx" => promise_query(Query::Mx, args),
136 "promiseResolveTxt" => promise_query(Query::Txt, args),
137 "promiseResolveCname" => promise_query(Query::Cname, args),
138 "promiseResolveNs" => promise_query(Query::Ns, args),
139 "promiseResolvePtr" => promise_query(Query::Ptr, args),
140 "promiseResolveSrv" => promise_query(Query::Srv, args),
141 "promiseResolveSoa" => promise_query(Query::Soa, args),
142 "promiseResolveNaptr" => promise_query(Query::Naptr, args),
143 "promiseResolveCaa" => promise_query(Query::Caa, args),
144 "promiseResolveTlsa" => promise_query(Query::Tlsa, args),
145 "promiseResolveAny" => promise_query(Query::Any, args),
146 "promiseReverse" => promise_query(Query::Reverse, args),
147 _ => return None,
148 })
149}
150
151struct DnsState {
154 servers: Option<Vec<String>>,
156 order: String,
158}
159
160thread_local! {
161 static STATE: RefCell<DnsState> =
162 RefCell::new(DnsState { servers: None, order: "verbatim".into() });
163}
164
165fn module_servers() -> Option<Vec<String>> {
166 STATE.with(|s| s.borrow().servers.clone())
167}
168
169pub fn constant(name: &str) -> Option<Value> {
173 match name {
174 "promises" => Some(with_host(|h| {
177 h.alloc(JsObj::Builtin("dns/promises".into()))
178 })),
179 "ADDRCONFIG" => Some(Value::Float(1024.0)),
180 "V4MAPPED" => Some(Value::Float(2048.0)),
181 "ALL" => Some(Value::Float(256.0)),
182 _ => code_constant(name).map(|c| with_host(|h| h.new_str(c))),
183 }
184}
185
186const CODE_CONSTANTS: &[(&str, &str)] = &[
188 ("NODATA", "ENODATA"),
189 ("FORMERR", "EFORMERR"),
190 ("SERVFAIL", "ESERVFAIL"),
191 ("NOTFOUND", "ENOTFOUND"),
192 ("NOTIMP", "ENOTIMP"),
193 ("REFUSED", "EREFUSED"),
194 ("BADQUERY", "EBADQUERY"),
195 ("BADNAME", "EBADNAME"),
196 ("BADFAMILY", "EBADFAMILY"),
197 ("BADRESP", "EBADRESP"),
198 ("CONNREFUSED", "ECONNREFUSED"),
199 ("TIMEOUT", "ETIMEOUT"),
200 ("EOF", "EOF"),
201 ("FILE", "EFILE"),
202 ("NOMEM", "ENOMEM"),
203 ("DESTRUCTION", "EDESTRUCTION"),
204 ("BADSTR", "EBADSTR"),
205 ("BADFLAGS", "EBADFLAGS"),
206 ("NONAME", "ENONAME"),
207 ("BADHINTS", "EBADHINTS"),
208 ("NOTINITIALIZED", "ENOTINITIALIZED"),
209 ("LOADIPHLPAPI", "ELOADIPHLPAPI"),
210 ("ADDRGETNETWORKPARAMS", "EADDRGETNETWORKPARAMS"),
211 ("CANCELLED", "ECANCELLED"),
212];
213
214fn code_constant(name: &str) -> Option<&'static str> {
215 CODE_CONSTANTS
216 .iter()
217 .find(|(k, _)| *k == name)
218 .map(|(_, v)| *v)
219}
220
221pub const VALUE_KEYS: &[&str] = &[
225 "ADDRCONFIG",
226 "ALL",
227 "V4MAPPED",
228 "NODATA",
229 "FORMERR",
230 "SERVFAIL",
231 "NOTFOUND",
232 "NOTIMP",
233 "REFUSED",
234 "BADQUERY",
235 "BADNAME",
236 "BADFAMILY",
237 "BADRESP",
238 "CONNREFUSED",
239 "TIMEOUT",
240 "EOF",
241 "FILE",
242 "NOMEM",
243 "DESTRUCTION",
244 "BADSTR",
245 "BADFLAGS",
246 "NONAME",
247 "BADHINTS",
248 "NOTINITIALIZED",
249 "LOADIPHLPAPI",
250 "ADDRGETNETWORKPARAMS",
251 "CANCELLED",
252 "promises",
253];
254
255#[cfg(test)]
256mod tests {
257 #[test]
258 fn value_keys_cover_every_constant() {
259 for (k, _) in super::CODE_CONSTANTS {
260 assert!(super::VALUE_KEYS.contains(k), "{k} missing from VALUE_KEYS");
261 }
262 assert_eq!(super::VALUE_KEYS.len(), super::CODE_CONSTANTS.len() + 4);
263 }
264}
265
266fn lookup(args: &[Value]) -> Result<Value, String> {
270 match args.first() {
273 None | Some(Value::Undef) => {}
274 Some(v) if with_host(|h| h.as_str(v)).is_some() => {}
275 Some(v) => {
276 return Err(crate::host::invalid_arg_type(
277 "hostname", "argument", "string", v,
278 ))
279 }
280 }
281 let hostname = arg_str(args, 0);
282 let want = opt_family(args);
283 let Some(cb) = args.last().cloned() else {
284 return Ok(Value::Undef);
285 };
286 match pick_addr(&hostname, want) {
287 Some(ip) => {
288 let family = if ip.is_ipv4() { 4.0 } else { 6.0 };
289 let (err, address) = with_host(|h| (h.null(), h.new_str(ip.to_string())));
290 crate::host::invoke(&cb, vec![err, address, Value::Float(family)], None)?;
291 }
292 None => {
293 let err = dns_error("ENOTFOUND", "getaddrinfo", &hostname);
294 crate::host::invoke(&cb, vec![err], None)?;
295 }
296 }
297 Ok(Value::Undef)
298}
299
300fn promise_lookup(args: &[Value]) -> Result<Value, String> {
302 let hostname = arg_str(args, 0);
303 let want = opt_family(args);
304 let p = with_host(|h| h.new_promise());
305 let id = with_host(|h| h.promise_id(&p)).unwrap_or(0);
306 match pick_addr(&hostname, want) {
307 Some(ip) => {
308 let family = if ip.is_ipv4() { 4.0 } else { 6.0 };
309 let obj = with_host(|h| {
310 let mut m = IndexMap::new();
311 m.insert("address".into(), h.new_str(ip.to_string()));
312 m.insert("family".into(), Value::Float(family));
313 h.new_object(m)
314 });
315 crate::host::resolve_promise_val(id, obj);
316 }
317 None => {
318 crate::host::reject_promise_val(id, dns_error("ENOTFOUND", "getaddrinfo", &hostname))
319 }
320 }
321 Ok(p)
322}
323
324fn pick_addr(hostname: &str, want: Option<u8>) -> Option<IpAddr> {
326 (hostname, 0u16)
327 .to_socket_addrs()
328 .ok()?
329 .map(|sa| sa.ip())
330 .find(|ip| match want {
331 Some(4) => ip.is_ipv4(),
332 Some(6) => ip.is_ipv6(),
333 _ => true,
334 })
335}
336
337fn opt_family(args: &[Value]) -> Option<u8> {
339 if args.len() < 3 {
340 return None;
341 }
342 with_host(|h| match h.get(&args[1]) {
343 Some(JsObj::Object(p)) => p.get("family").map(|f| h.to_number(f) as u8),
344 _ => {
345 let n = h.to_number(&args[1]);
346 (n.is_finite() && n > 0.0).then_some(n as u8)
347 }
348 })
349}
350
351fn lookup_service(args: &[Value]) -> Result<Value, String> {
355 let addr = arg_str(args, 0);
356 let port = super::arg_num(args, 1);
357 let Some(cb) = args.last().cloned() else {
358 return Ok(Value::Undef);
359 };
360 let servers = module_servers();
361 with_host(|h| h.incr_handle());
362 let tx = with_host(|h| h.io_sender());
363 std::thread::spawn(move || {
364 let result = run_lookup_service(&addr, port, servers.as_deref());
365 let label = addr;
366 let _ = tx.send(Box::new(move || {
367 with_host(|h| h.decr_handle());
368 let call_args = match result {
369 Ok((host, service)) => {
370 let (n, hv, sv) =
371 with_host(|h| (h.null(), h.new_str(host), h.new_str(service)));
372 vec![n, hv, sv]
373 }
374 Err(code) => vec![dns_error(&code, "getnameinfo", &label)],
375 };
376 if let Err(e) = crate::host::invoke(&cb, call_args, None) {
377 eprintln!("{e}");
378 }
379 Ok(())
380 }));
381 });
382 Ok(Value::Undef)
383}
384
385fn promise_lookup_service(args: &[Value]) -> Result<Value, String> {
387 let addr = arg_str(args, 0);
388 let port = super::arg_num(args, 1);
389 let servers = module_servers();
390 let p = with_host(|h| h.new_promise());
391 let id = with_host(|h| h.promise_id(&p)).unwrap_or(0);
392 with_host(|h| h.incr_handle());
393 let tx = with_host(|h| h.io_sender());
394 std::thread::spawn(move || {
395 let result = run_lookup_service(&addr, port, servers.as_deref());
396 let label = addr;
397 let _ = tx.send(Box::new(move || {
398 with_host(|h| h.decr_handle());
399 match result {
400 Ok((host, service)) => {
401 let obj = with_host(|h| {
402 let mut m = IndexMap::new();
403 m.insert("hostname".into(), h.new_str(host));
404 m.insert("service".into(), h.new_str(service));
405 h.new_object(m)
406 });
407 crate::host::resolve_promise_val(id, obj);
408 }
409 Err(code) => {
410 crate::host::reject_promise_val(id, dns_error(&code, "getnameinfo", &label))
411 }
412 }
413 Ok(())
414 }));
415 });
416 Ok(p)
417}
418
419fn run_lookup_service(
420 addr: &str,
421 port: f64,
422 servers: Option<&[String]>,
423) -> Result<(String, String), String> {
424 let ip: IpAddr = addr.parse().map_err(|_| "EINVAL".to_string())?;
425 let resolver = build_resolver(servers)?;
426 let lookup = resolver.run(resolver.r.reverse_lookup(ip))?;
427 let host = rdata(&lookup)
428 .find_map(|d| match d {
429 RData::PTR(p) => Some(name_str(p)),
430 _ => None,
431 })
432 .ok_or_else(|| "ENOTFOUND".to_string())?;
433 Ok((host, port_service(port as u16)))
434}
435
436fn port_service(port: u16) -> String {
439 let name = match port {
440 20 => "ftp-data",
441 21 => "ftp",
442 22 => "ssh",
443 23 => "telnet",
444 25 => "smtp",
445 53 => "domain",
446 67 => "bootps",
447 68 => "bootpc",
448 69 => "tftp",
449 79 => "finger",
450 80 => "http",
451 110 => "pop3",
452 111 => "sunrpc",
453 119 => "nntp",
454 123 => "ntp",
455 143 => "imap",
456 161 => "snmp",
457 194 => "irc",
458 389 => "ldap",
459 443 => "https",
460 445 => "microsoft-ds",
461 465 => "submissions",
462 514 => "shell",
463 515 => "printer",
464 587 => "submission",
465 631 => "ipp",
466 636 => "ldaps",
467 993 => "imaps",
468 995 => "pop3s",
469 1194 => "openvpn",
470 1433 => "ms-sql-s",
471 3306 => "mysql",
472 3389 => "ms-wbt-server",
473 5432 => "postgresql",
474 5060 => "sip",
475 5061 => "sips",
476 6379 => "redis",
477 8080 => "http-alt",
478 8443 => "https-alt",
479 _ => return port.to_string(),
480 };
481 name.to_string()
482}
483
484#[derive(Clone, Copy)]
487enum Query {
488 A,
489 Aaaa,
490 Mx,
491 Txt,
492 Cname,
493 Ns,
494 Ptr,
495 Srv,
496 Soa,
497 Naptr,
498 Caa,
499 Tlsa,
500 Any,
501 Reverse,
502}
503
504impl Query {
505 fn syscall(self) -> &'static str {
507 match self {
508 Query::A => "queryA",
509 Query::Aaaa => "queryAaaa",
510 Query::Mx => "queryMx",
511 Query::Txt => "queryTxt",
512 Query::Cname => "queryCname",
513 Query::Ns => "queryNs",
514 Query::Ptr => "queryPtr",
515 Query::Srv => "querySrv",
516 Query::Soa => "querySoa",
517 Query::Naptr => "queryNaptr",
518 Query::Caa => "queryCaa",
519 Query::Tlsa => "queryTlsa",
520 Query::Any => "queryAny",
521 Query::Reverse => "getHostByAddr",
522 }
523 }
524}
525
526fn query_of(rrtype: &str) -> Option<Query> {
527 Some(match rrtype {
528 "A" => Query::A,
529 "AAAA" => Query::Aaaa,
530 "MX" => Query::Mx,
531 "TXT" => Query::Txt,
532 "CNAME" => Query::Cname,
533 "NS" => Query::Ns,
534 "PTR" => Query::Ptr,
535 "SRV" => Query::Srv,
536 "SOA" => Query::Soa,
537 "NAPTR" => Query::Naptr,
538 "CAA" => Query::Caa,
539 "TLSA" => Query::Tlsa,
540 "ANY" => Query::Any,
541 _ => return None,
542 })
543}
544
545fn cb_query(q: Query, args: &[Value]) -> Result<Value, String> {
546 let name = arg_str(args, 0);
547 let Some(cb) = args.last().cloned() else {
548 return Ok(Value::Undef);
549 };
550 start_query(q, name, module_servers(), cb);
551 Ok(Value::Undef)
552}
553
554fn promise_query(q: Query, args: &[Value]) -> Result<Value, String> {
555 let name = arg_str(args, 0);
556 Ok(start_promise_query(q, name, module_servers()))
557}
558
559fn resolve_cb(args: &[Value]) -> Result<Value, String> {
561 let name = arg_str(args, 0);
562 let Some(cb) = args.last().cloned() else {
563 return Ok(Value::Undef);
564 };
565 let rrtype = if args.len() > 2 {
566 arg_str(args, 1)
567 } else {
568 "A".into()
569 };
570 let q = query_of(&rrtype).unwrap_or(Query::A);
571 start_query(q, name, module_servers(), cb);
572 Ok(Value::Undef)
573}
574
575fn resolve_promise(args: &[Value]) -> Result<Value, String> {
577 let name = arg_str(args, 0);
578 let rrtype = if args.len() > 1 {
579 arg_str(args, 1)
580 } else {
581 "A".into()
582 };
583 let q = query_of(&rrtype).unwrap_or(Query::A);
584 Ok(start_promise_query(q, name, module_servers()))
585}
586
587fn start_query(q: Query, name: String, servers: Option<Vec<String>>, cb: Value) {
590 with_host(|h| h.incr_handle());
591 let tx = with_host(|h| h.io_sender());
592 std::thread::spawn(move || {
593 let res = run_query(q, &name, servers.as_deref());
594 let label = name;
595 let _ = tx.send(Box::new(move || {
596 with_host(|h| h.decr_handle());
597 let call_args = match res {
598 Ok(data) => {
599 let val = dns_to_value(data);
600 let n = with_host(|h| h.null());
601 vec![n, val]
602 }
603 Err(code) => vec![dns_error(&code, q.syscall(), &label)],
604 };
605 if let Err(e) = crate::host::invoke(&cb, call_args, None) {
606 eprintln!("{e}");
607 }
608 Ok(())
609 }));
610 });
611}
612
613fn start_promise_query(q: Query, name: String, servers: Option<Vec<String>>) -> Value {
614 let p = with_host(|h| h.new_promise());
615 let id = with_host(|h| h.promise_id(&p)).unwrap_or(0);
616 with_host(|h| h.incr_handle());
617 let tx = with_host(|h| h.io_sender());
618 std::thread::spawn(move || {
619 let res = run_query(q, &name, servers.as_deref());
620 let label = name;
621 let _ = tx.send(Box::new(move || {
622 with_host(|h| h.decr_handle());
623 match res {
624 Ok(data) => crate::host::resolve_promise_val(id, dns_to_value(data)),
625 Err(code) => {
626 crate::host::reject_promise_val(id, dns_error(&code, q.syscall(), &label))
627 }
628 }
629 Ok(())
630 }));
631 });
632 p
633}
634
635fn run_or_promise(
637 q: Query,
638 name: String,
639 servers: Option<Vec<String>>,
640 cb: Option<Value>,
641 promises: bool,
642) -> Value {
643 if promises {
644 start_promise_query(q, name, servers)
645 } else if let Some(cb) = cb {
646 start_query(q, name, servers, cb);
647 Value::Undef
648 } else {
649 Value::Undef
650 }
651}
652
653enum DnsResult {
658 Strings(Vec<String>),
659 Mx(Vec<(u16, String)>),
660 Txt(Vec<Vec<String>>),
661 Srv(Vec<SrvRec>),
662 Soa(SoaRec),
663 Naptr(Vec<NaptrRec>),
664 Caa(Vec<CaaRec>),
665 Tlsa(Vec<TlsaRec>),
666 Any(Vec<AnyRec>),
667}
668
669struct SoaRec {
670 nsname: String,
671 hostmaster: String,
672 serial: u32,
673 refresh: i32,
674 retry: i32,
675 expire: i32,
676 minttl: u32,
677}
678
679struct SrvRec {
680 priority: u16,
681 weight: u16,
682 port: u16,
683 name: String,
684}
685
686struct NaptrRec {
687 flags: String,
688 service: String,
689 regexp: String,
690 replacement: String,
691 order: u16,
692 preference: u16,
693}
694
695struct CaaRec {
696 critical: u16,
697 tag: String,
698 value: String,
699}
700
701struct TlsaRec {
702 cert_usage: u8,
703 selector: u8,
704 matching: u8,
705 data: Vec<u8>,
706}
707
708enum AnyRec {
709 A(String, u32),
710 Aaaa(String, u32),
711 Cname(String),
712 Mx(u16, String),
713 Ns(String),
714 Ptr(String),
715 Txt(Vec<String>),
716 Srv(SrvRec),
717 Soa(SoaRec),
718 Naptr(NaptrRec),
719 Caa(CaaRec),
720}
721
722fn run_query(q: Query, name: &str, servers: Option<&[String]>) -> Result<DnsResult, String> {
723 let br = build_resolver(servers)?;
724 let r = &br.r;
725 match q {
726 Query::A => {
727 let l = br.run(r.ipv4_lookup(name))?;
728 Ok(DnsResult::Strings(
729 rdata(&l)
730 .filter_map(|d| match d {
731 RData::A(a) => Some(a.to_string()),
732 _ => None,
733 })
734 .collect(),
735 ))
736 }
737 Query::Aaaa => {
738 let l = br.run(r.ipv6_lookup(name))?;
739 Ok(DnsResult::Strings(
740 rdata(&l)
741 .filter_map(|d| match d {
742 RData::AAAA(a) => Some(a.to_string()),
743 _ => None,
744 })
745 .collect(),
746 ))
747 }
748 Query::Mx => {
749 let l = br.run(r.mx_lookup(name))?;
750 Ok(DnsResult::Mx(
751 rdata(&l)
752 .filter_map(|d| match d {
753 RData::MX(m) => Some((m.preference, name_str(&m.exchange))),
754 _ => None,
755 })
756 .collect(),
757 ))
758 }
759 Query::Txt => {
760 let l = br.run(r.txt_lookup(name))?;
761 let entries = rdata(&l)
762 .filter_map(|d| match d {
763 RData::TXT(t) => Some(txt_chunks(t)),
764 _ => None,
765 })
766 .collect();
767 Ok(DnsResult::Txt(entries))
768 }
769 Query::Cname => {
770 let l = br.run(r.lookup(name, RecordType::CNAME))?;
771 let names = rdata(&l)
772 .filter_map(|d| match d {
773 RData::CNAME(c) => Some(name_str(c)),
774 _ => None,
775 })
776 .collect();
777 Ok(DnsResult::Strings(names))
778 }
779 Query::Ns => {
780 let l = br.run(r.ns_lookup(name))?;
781 let names = rdata(&l)
782 .filter_map(|d| match d {
783 RData::NS(n) => Some(name_str(n)),
784 _ => None,
785 })
786 .collect();
787 Ok(DnsResult::Strings(names))
788 }
789 Query::Ptr => {
790 let l = br.run(r.lookup(name, RecordType::PTR))?;
791 let names = rdata(&l)
792 .filter_map(|d| match d {
793 RData::PTR(p) => Some(name_str(p)),
794 _ => None,
795 })
796 .collect();
797 Ok(DnsResult::Strings(names))
798 }
799 Query::Srv => {
800 let l = br.run(r.srv_lookup(name))?;
801 let recs = rdata(&l)
802 .filter_map(|d| match d {
803 RData::SRV(s) => Some(srv_rec(s)),
804 _ => None,
805 })
806 .collect();
807 Ok(DnsResult::Srv(recs))
808 }
809 Query::Soa => {
810 let l = br.run(r.soa_lookup(name))?;
811 let soa = rdata(&l)
812 .find_map(|d| match d {
813 RData::SOA(s) => Some(soa_rec(s)),
814 _ => None,
815 })
816 .ok_or_else(|| "ENODATA".to_string())?;
817 Ok(DnsResult::Soa(soa))
818 }
819 Query::Naptr => {
820 let l = br.run(r.lookup(name, RecordType::NAPTR))?;
821 let recs = rdata(&l)
822 .filter_map(|d| match d {
823 RData::NAPTR(n) => Some(naptr_rec(n)),
824 _ => None,
825 })
826 .collect();
827 Ok(DnsResult::Naptr(recs))
828 }
829 Query::Caa => {
830 let l = br.run(r.lookup(name, RecordType::CAA))?;
831 let recs = rdata(&l)
832 .filter_map(|d| match d {
833 RData::CAA(c) => Some(caa_rec(c)),
834 _ => None,
835 })
836 .collect();
837 Ok(DnsResult::Caa(recs))
838 }
839 Query::Tlsa => {
840 let l = br.run(r.tlsa_lookup(name))?;
841 let recs = rdata(&l)
842 .filter_map(|d| match d {
843 RData::TLSA(t) => Some(TlsaRec {
844 cert_usage: t.cert_usage.into(),
845 selector: t.selector.into(),
846 matching: t.matching.into(),
847 data: t.cert_data.clone(),
848 }),
849 _ => None,
850 })
851 .collect();
852 Ok(DnsResult::Tlsa(recs))
853 }
854 Query::Any => {
855 let l = br.run(r.lookup(name, RecordType::ANY))?;
856 let recs = l.answers().iter().filter_map(any_rec).collect();
857 Ok(DnsResult::Any(recs))
858 }
859 Query::Reverse => {
860 let ip: IpAddr = name.parse().map_err(|_| "EINVAL".to_string())?;
861 let l = br.run(r.reverse_lookup(ip))?;
862 let names = rdata(&l)
863 .filter_map(|d| match d {
864 RData::PTR(p) => Some(name_str(p)),
865 _ => None,
866 })
867 .collect();
868 Ok(DnsResult::Strings(names))
869 }
870 }
871}
872
873fn rdata(l: &Lookup) -> impl Iterator<Item = &RData> {
878 l.answers().iter().map(|rec| &rec.data)
879}
880
881fn name_str(n: &Name) -> String {
882 n.to_ascii().trim_end_matches('.').to_string()
883}
884
885fn txt_chunks(t: &hickory_resolver::proto::rr::rdata::TXT) -> Vec<String> {
886 t.txt_data
887 .iter()
888 .map(|b| String::from_utf8_lossy(b).into_owned())
889 .collect()
890}
891
892fn srv_rec(s: &hickory_resolver::proto::rr::rdata::SRV) -> SrvRec {
893 SrvRec {
894 priority: s.priority,
895 weight: s.weight,
896 port: s.port,
897 name: name_str(&s.target),
898 }
899}
900
901fn soa_rec(s: &hickory_resolver::proto::rr::rdata::SOA) -> SoaRec {
902 SoaRec {
903 nsname: name_str(&s.mname),
904 hostmaster: name_str(&s.rname),
905 serial: s.serial,
906 refresh: s.refresh,
907 retry: s.retry,
908 expire: s.expire,
909 minttl: s.minimum,
910 }
911}
912
913fn naptr_rec(n: &hickory_resolver::proto::rr::rdata::NAPTR) -> NaptrRec {
914 NaptrRec {
915 flags: String::from_utf8_lossy(&n.flags).into_owned(),
916 service: String::from_utf8_lossy(&n.services).into_owned(),
917 regexp: String::from_utf8_lossy(&n.regexp).into_owned(),
918 replacement: name_str(&n.replacement),
919 order: n.order,
920 preference: n.preference,
921 }
922}
923
924fn caa_rec(c: &hickory_resolver::proto::rr::rdata::CAA) -> CaaRec {
925 CaaRec {
926 critical: if c.issuer_critical { 128 } else { 0 },
927 tag: c.tag.clone(),
928 value: caa_value(c),
929 }
930}
931
932fn caa_value(c: &hickory_resolver::proto::rr::rdata::CAA) -> String {
935 let raw = || String::from_utf8_lossy(&c.value).into_owned();
936 match c.tag.to_ascii_lowercase().as_str() {
937 "issue" | "issuewild" => match c.value_as_issue() {
938 Ok((name, kvs)) => {
939 let mut s = name.as_ref().map(name_str).unwrap_or_default();
940 for kv in &kvs {
941 s.push_str("; ");
942 s.push_str(kv.key());
943 s.push('=');
944 s.push_str(kv.value());
945 }
946 s
947 }
948 Err(_) => raw(),
949 },
950 "iodef" => c
951 .value_as_iodef()
952 .map(|u| u.to_string())
953 .unwrap_or_else(|_| raw()),
954 _ => raw(),
955 }
956}
957
958fn any_rec(rec: &hickory_resolver::proto::rr::Record) -> Option<AnyRec> {
961 let ttl = rec.ttl;
962 Some(match &rec.data {
963 RData::A(a) => AnyRec::A(a.to_string(), ttl),
964 RData::AAAA(a) => AnyRec::Aaaa(a.to_string(), ttl),
965 RData::CNAME(c) => AnyRec::Cname(name_str(c)),
966 RData::MX(m) => AnyRec::Mx(m.preference, name_str(&m.exchange)),
967 RData::NS(n) => AnyRec::Ns(name_str(n)),
968 RData::PTR(p) => AnyRec::Ptr(name_str(p)),
969 RData::TXT(t) => AnyRec::Txt(txt_chunks(t)),
970 RData::SRV(s) => AnyRec::Srv(srv_rec(s)),
971 RData::SOA(s) => AnyRec::Soa(soa_rec(s)),
972 RData::NAPTR(n) => AnyRec::Naptr(naptr_rec(n)),
973 RData::CAA(c) => AnyRec::Caa(caa_rec(c)),
974 _ => return None,
975 })
976}
977
978fn dns_to_value(res: DnsResult) -> Value {
981 match res {
982 DnsResult::Strings(v) => with_host(|h| {
983 let items: Vec<Value> = v.into_iter().map(|s| h.new_str(s)).collect();
984 h.new_array(items)
985 }),
986 DnsResult::Mx(v) => with_host(|h| {
987 let items: Vec<Value> = v
988 .into_iter()
989 .map(|(pri, ex)| {
990 let mut m = IndexMap::new();
991 m.insert("exchange".into(), h.new_str(ex));
992 m.insert("priority".into(), Value::Float(pri as f64));
993 m.insert("type".into(), h.new_str("MX"));
994 h.new_object(m)
995 })
996 .collect();
997 h.new_array(items)
998 }),
999 DnsResult::Txt(v) => with_host(|h| {
1000 let items: Vec<Value> = v
1001 .into_iter()
1002 .map(|chunks| {
1003 let inner: Vec<Value> = chunks.into_iter().map(|s| h.new_str(s)).collect();
1004 h.new_array(inner)
1005 })
1006 .collect();
1007 h.new_array(items)
1008 }),
1009 DnsResult::Srv(v) => with_host(|h| {
1010 let items: Vec<Value> = v.iter().map(|s| srv_obj(h, s)).collect();
1011 h.new_array(items)
1012 }),
1013 DnsResult::Soa(s) => with_host(|h| soa_obj(h, &s)),
1014 DnsResult::Naptr(v) => with_host(|h| {
1015 let items: Vec<Value> = v.iter().map(|n| naptr_obj(h, n)).collect();
1016 h.new_array(items)
1017 }),
1018 DnsResult::Caa(v) => with_host(|h| {
1019 let items: Vec<Value> = v.iter().map(|c| caa_obj(h, c)).collect();
1020 h.new_array(items)
1021 }),
1022 DnsResult::Tlsa(v) => {
1023 let mut items = Vec::with_capacity(v.len());
1025 for t in v {
1026 let data = super::buffer::from_bytes(&t.data);
1027 let obj = with_host(|h| {
1028 let mut m = IndexMap::new();
1029 m.insert("certUsage".into(), Value::Float(t.cert_usage as f64));
1030 m.insert("selector".into(), Value::Float(t.selector as f64));
1031 m.insert("match".into(), Value::Float(t.matching as f64));
1032 m.insert("data".into(), data);
1033 h.new_object(m)
1034 });
1035 items.push(obj);
1036 }
1037 with_host(|h| h.new_array(items))
1038 }
1039 DnsResult::Any(v) => with_host(|h| {
1040 let items: Vec<Value> = v.into_iter().map(|rec| any_obj(h, rec)).collect();
1041 h.new_array(items)
1042 }),
1043 }
1044}
1045
1046fn srv_obj(h: &mut crate::host::JsHost, s: &SrvRec) -> Value {
1047 let mut m = IndexMap::new();
1048 m.insert("name".into(), h.new_str(s.name.clone()));
1049 m.insert("port".into(), Value::Float(s.port as f64));
1050 m.insert("priority".into(), Value::Float(s.priority as f64));
1051 m.insert("weight".into(), Value::Float(s.weight as f64));
1052 m.insert("type".into(), h.new_str("SRV"));
1053 h.new_object(m)
1054}
1055
1056fn soa_obj(h: &mut crate::host::JsHost, s: &SoaRec) -> Value {
1057 let mut m = IndexMap::new();
1058 m.insert("nsname".into(), h.new_str(s.nsname.clone()));
1059 m.insert("hostmaster".into(), h.new_str(s.hostmaster.clone()));
1060 m.insert("serial".into(), Value::Float(s.serial as f64));
1061 m.insert("refresh".into(), Value::Float(s.refresh as f64));
1062 m.insert("retry".into(), Value::Float(s.retry as f64));
1063 m.insert("expire".into(), Value::Float(s.expire as f64));
1064 m.insert("minttl".into(), Value::Float(s.minttl as f64));
1065 h.new_object(m)
1066}
1067
1068fn naptr_obj(h: &mut crate::host::JsHost, n: &NaptrRec) -> Value {
1069 let mut m = IndexMap::new();
1070 m.insert("flags".into(), h.new_str(n.flags.clone()));
1071 m.insert("service".into(), h.new_str(n.service.clone()));
1072 m.insert("regexp".into(), h.new_str(n.regexp.clone()));
1073 m.insert("replacement".into(), h.new_str(n.replacement.clone()));
1074 m.insert("order".into(), Value::Float(n.order as f64));
1075 m.insert("preference".into(), Value::Float(n.preference as f64));
1076 h.new_object(m)
1077}
1078
1079fn caa_obj(h: &mut crate::host::JsHost, c: &CaaRec) -> Value {
1080 let mut m = IndexMap::new();
1081 m.insert("critical".into(), Value::Float(c.critical as f64));
1082 m.insert("type".into(), h.new_str("CAA"));
1083 m.insert(c.tag.clone(), h.new_str(c.value.clone()));
1084 h.new_object(m)
1085}
1086
1087fn any_obj(h: &mut crate::host::JsHost, rec: AnyRec) -> Value {
1089 let mut m = IndexMap::new();
1090 match rec {
1091 AnyRec::A(addr, ttl) => {
1092 m.insert("type".into(), h.new_str("A"));
1093 m.insert("address".into(), h.new_str(addr));
1094 m.insert("ttl".into(), Value::Float(ttl as f64));
1095 }
1096 AnyRec::Aaaa(addr, ttl) => {
1097 m.insert("type".into(), h.new_str("AAAA"));
1098 m.insert("address".into(), h.new_str(addr));
1099 m.insert("ttl".into(), Value::Float(ttl as f64));
1100 }
1101 AnyRec::Cname(v) => {
1102 m.insert("type".into(), h.new_str("CNAME"));
1103 m.insert("value".into(), h.new_str(v));
1104 }
1105 AnyRec::Mx(pri, ex) => {
1106 m.insert("type".into(), h.new_str("MX"));
1107 m.insert("exchange".into(), h.new_str(ex));
1108 m.insert("priority".into(), Value::Float(pri as f64));
1109 }
1110 AnyRec::Ns(v) => {
1111 m.insert("type".into(), h.new_str("NS"));
1112 m.insert("value".into(), h.new_str(v));
1113 }
1114 AnyRec::Ptr(v) => {
1115 m.insert("type".into(), h.new_str("PTR"));
1116 m.insert("value".into(), h.new_str(v));
1117 }
1118 AnyRec::Txt(chunks) => {
1119 let entries: Vec<Value> = chunks.into_iter().map(|s| h.new_str(s)).collect();
1120 let arr = h.new_array(entries);
1121 m.insert("type".into(), h.new_str("TXT"));
1122 m.insert("entries".into(), arr);
1123 }
1124 AnyRec::Srv(s) => {
1125 m.insert("type".into(), h.new_str("SRV"));
1126 m.insert("priority".into(), Value::Float(s.priority as f64));
1127 m.insert("weight".into(), Value::Float(s.weight as f64));
1128 m.insert("port".into(), Value::Float(s.port as f64));
1129 m.insert("name".into(), h.new_str(s.name));
1130 }
1131 AnyRec::Soa(s) => return soa_with_type(h, &s),
1132 AnyRec::Naptr(n) => {
1133 m.insert("type".into(), h.new_str("NAPTR"));
1134 m.insert("flags".into(), h.new_str(n.flags));
1135 m.insert("service".into(), h.new_str(n.service));
1136 m.insert("regexp".into(), h.new_str(n.regexp));
1137 m.insert("replacement".into(), h.new_str(n.replacement));
1138 m.insert("order".into(), Value::Float(n.order as f64));
1139 m.insert("preference".into(), Value::Float(n.preference as f64));
1140 }
1141 AnyRec::Caa(c) => {
1142 m.insert("type".into(), h.new_str("CAA"));
1143 m.insert("critical".into(), Value::Float(c.critical as f64));
1144 m.insert(c.tag, h.new_str(c.value));
1145 }
1146 }
1147 h.new_object(m)
1148}
1149
1150fn soa_with_type(h: &mut crate::host::JsHost, s: &SoaRec) -> Value {
1151 let mut m = IndexMap::new();
1152 m.insert("type".into(), h.new_str("SOA"));
1153 m.insert("nsname".into(), h.new_str(s.nsname.clone()));
1154 m.insert("hostmaster".into(), h.new_str(s.hostmaster.clone()));
1155 m.insert("serial".into(), Value::Float(s.serial as f64));
1156 m.insert("refresh".into(), Value::Float(s.refresh as f64));
1157 m.insert("retry".into(), Value::Float(s.retry as f64));
1158 m.insert("expire".into(), Value::Float(s.expire as f64));
1159 m.insert("minttl".into(), Value::Float(s.minttl as f64));
1160 h.new_object(m)
1161}
1162
1163struct BlockingResolver {
1168 rt: tokio::runtime::Runtime,
1169 r: TokioResolver,
1170}
1171
1172impl BlockingResolver {
1173 fn run<T>(
1176 &self,
1177 fut: impl std::future::Future<Output = Result<T, NetError>>,
1178 ) -> Result<T, String> {
1179 self.rt.block_on(fut).map_err(|e| err_code(&e).to_string())
1180 }
1181}
1182
1183fn build_resolver(servers: Option<&[String]>) -> Result<BlockingResolver, String> {
1187 let rt = tokio::runtime::Builder::new_current_thread()
1188 .enable_all()
1189 .build()
1190 .map_err(|e| e.to_string())?;
1191 let provider = TokioRuntimeProvider::default;
1192 let r = {
1193 let _guard = rt.enter();
1195 let builder = match servers {
1196 Some(list) if !list.is_empty() => {
1197 let ns: Vec<NameServerConfig> = list
1198 .iter()
1199 .filter_map(|s| parse_ip(s))
1200 .map(NameServerConfig::udp_and_tcp)
1201 .collect();
1202 if ns.is_empty() {
1203 return Err("EBADFAMILY".into());
1204 }
1205 TokioResolver::builder_with_config(
1206 ResolverConfig::from_name_servers(ns),
1207 provider(),
1208 )
1209 }
1210 _ => TokioResolver::builder(provider()).unwrap_or_else(|_| {
1211 TokioResolver::builder_with_config(ResolverConfig::udp_and_tcp(&GOOGLE), provider())
1212 }),
1213 };
1214 builder.build().map_err(|e| e.to_string())?
1215 };
1216 Ok(BlockingResolver { rt, r })
1217}
1218
1219fn parse_ip(s: &str) -> Option<IpAddr> {
1221 s.parse::<IpAddr>()
1222 .ok()
1223 .or_else(|| s.parse::<std::net::SocketAddr>().ok().map(|sa| sa.ip()))
1224}
1225
1226fn system_servers() -> Vec<String> {
1228 match hickory_resolver::system_conf::read_system_conf() {
1229 Ok((cfg, _)) => {
1230 let mut out: Vec<String> = Vec::new();
1231 for ns in cfg.name_servers() {
1232 let ip = ns.ip.to_string();
1233 if !out.contains(&ip) {
1234 out.push(ip);
1235 }
1236 }
1237 out
1238 }
1239 Err(_) => Vec::new(),
1240 }
1241}
1242
1243fn err_code(e: &NetError) -> &'static str {
1245 match e {
1246 NetError::Dns(DnsError::NoRecordsFound(_)) if e.is_nx_domain() => "ENOTFOUND",
1247 NetError::Dns(DnsError::NoRecordsFound(_)) => "ENODATA",
1248 NetError::NoConnections => "ESERVFAIL",
1249 NetError::Timeout => "ETIMEOUT",
1250 _ => "ESERVFAIL",
1251 }
1252}
1253
1254fn dns_error(code: &str, syscall: &str, host: &str) -> Value {
1257 let msg = format!("Error: {syscall} {code} {host}");
1258 with_host(|h| {
1259 let e = crate::builtins::synth_error(h, &msg);
1260 let cv = h.new_str(code.to_string());
1261 let sv = h.new_str(syscall.to_string());
1262 let hv = h.new_str(host.to_string());
1263 if let Some(JsObj::Object(p)) = h.get_mut(&e) {
1264 p.insert("code".into(), cv);
1265 p.insert("syscall".into(), sv);
1266 p.insert("hostname".into(), hv);
1267 }
1268 e
1269 })
1270}
1271
1272fn get_servers() -> Result<Value, String> {
1275 let list = module_servers().unwrap_or_else(system_servers);
1276 Ok(with_host(|h| {
1277 let items: Vec<Value> = list.into_iter().map(|s| h.new_str(s)).collect();
1278 h.new_array(items)
1279 }))
1280}
1281
1282fn set_servers(args: &[Value]) -> Result<Value, String> {
1283 let list = servers_from_arg(args.first());
1284 STATE.with(|s| s.borrow_mut().servers = Some(list));
1285 Ok(Value::Undef)
1286}
1287
1288fn servers_from_arg(v: Option<&Value>) -> Vec<String> {
1289 with_host(|h| match v.and_then(|v| h.get(v)) {
1290 Some(JsObj::Array(items)) => items.iter().map(|x| h.str_of(x)).collect(),
1291 _ => Vec::new(),
1292 })
1293}
1294
1295fn get_default_result_order() -> Value {
1296 let order = STATE.with(|s| s.borrow().order.clone());
1297 with_host(|h| h.new_str(order))
1298}
1299
1300fn set_default_result_order(args: &[Value]) -> Result<Value, String> {
1301 let order = arg_str(args, 0);
1302 if order == "ipv4first" || order == "verbatim" || order == "ipv6first" {
1303 STATE.with(|s| s.borrow_mut().order = order);
1304 }
1305 Ok(Value::Undef)
1306}
1307
1308pub fn construct_resolver(_args: &[Value]) -> Value {
1312 make_resolver_obj(false)
1313}
1314
1315pub fn construct_resolver_promises(_args: &[Value]) -> Value {
1317 make_resolver_obj(true)
1318}
1319
1320fn make_resolver_obj(promises: bool) -> Value {
1321 let empty = with_host(|h| h.new_array(Vec::new()));
1322 let tag = with_host(|h| h.new_str("Resolver"));
1323 with_host(|h| {
1324 let mut m = IndexMap::new();
1325 m.insert("@@native".into(), tag);
1326 m.insert("@@servers".into(), empty);
1327 if promises {
1328 m.insert("@@promises".into(), Value::Bool(true));
1329 }
1330 h.new_object(m)
1331 })
1332}
1333
1334pub fn resolver_instance_call(
1336 recv: &Value,
1337 method: &str,
1338 args: Vec<Value>,
1339) -> Result<Value, String> {
1340 let promises = recv_promises(recv);
1341 let servers = recv_servers(recv);
1342
1343 match method {
1344 "getServers" => {
1345 let list = servers.clone().unwrap_or_else(system_servers);
1346 return Ok(with_host(|h| {
1347 let items: Vec<Value> = list.into_iter().map(|s| h.new_str(s)).collect();
1348 h.new_array(items)
1349 }));
1350 }
1351 "setServers" => {
1352 let list = servers_from_arg(args.first());
1353 set_recv_servers(recv, &list);
1354 return Ok(Value::Undef);
1355 }
1356 "cancel" | "setLocalAddress" => return Ok(Value::Undef),
1357 _ => {}
1358 }
1359
1360 if method == "resolve" {
1361 let name = super::arg_str(&args, 0);
1362 let has_rrtype = if promises {
1363 args.len() > 1
1364 } else {
1365 args.len() > 2
1366 };
1367 let rrtype = if has_rrtype {
1368 super::arg_str(&args, 1)
1369 } else {
1370 "A".to_string()
1371 };
1372 let q = query_of(&rrtype).unwrap_or(Query::A);
1373 let cb = if promises { None } else { args.last().cloned() };
1374 return Ok(run_or_promise(q, name, servers, cb, promises));
1375 }
1376
1377 if let Some(q) = query_for_method(method) {
1378 let name = super::arg_str(&args, 0);
1379 let cb = if promises { None } else { args.last().cloned() };
1380 return Ok(run_or_promise(q, name, servers, cb, promises));
1381 }
1382
1383 Err(format!("TypeError: resolver.{method} is not a function"))
1384}
1385
1386fn query_for_method(method: &str) -> Option<Query> {
1387 Some(match method {
1388 "resolve4" => Query::A,
1389 "resolve6" => Query::Aaaa,
1390 "resolveMx" => Query::Mx,
1391 "resolveTxt" => Query::Txt,
1392 "resolveCname" => Query::Cname,
1393 "resolveNs" => Query::Ns,
1394 "resolvePtr" => Query::Ptr,
1395 "resolveSrv" => Query::Srv,
1396 "resolveSoa" => Query::Soa,
1397 "resolveNaptr" => Query::Naptr,
1398 "resolveCaa" => Query::Caa,
1399 "resolveTlsa" => Query::Tlsa,
1400 "resolveAny" => Query::Any,
1401 "reverse" => Query::Reverse,
1402 _ => return None,
1403 })
1404}
1405
1406fn recv_promises(recv: &Value) -> bool {
1407 with_host(|h| {
1408 matches!(
1409 h.get(recv),
1410 Some(JsObj::Object(p)) if matches!(p.get("@@promises"), Some(Value::Bool(true)))
1411 )
1412 })
1413}
1414
1415fn recv_servers(recv: &Value) -> Option<Vec<String>> {
1416 with_host(|h| {
1417 let JsObj::Object(p) = h.get(recv)? else {
1418 return None;
1419 };
1420 let arr = p.get("@@servers")?;
1421 let JsObj::Array(items) = h.get(arr)? else {
1422 return None;
1423 };
1424 let list: Vec<String> = items.iter().map(|x| h.str_of(x)).collect();
1425 if list.is_empty() {
1426 None
1427 } else {
1428 Some(list)
1429 }
1430 })
1431}
1432
1433fn set_recv_servers(recv: &Value, list: &[String]) {
1434 let arr = with_host(|h| {
1435 let items: Vec<Value> = list.iter().map(|s| h.new_str(s.clone())).collect();
1436 h.new_array(items)
1437 });
1438 with_host(|h| {
1439 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
1440 p.insert("@@servers".into(), arr);
1441 }
1442 });
1443}