1use crate::host::with_host;
8use fusevm::Value;
9use indexmap::IndexMap;
10
11pub const METHODS: &[&str] = &[
12 "platform",
13 "arch",
14 "type",
15 "release",
16 "hostname",
17 "homedir",
18 "tmpdir",
19 "endianness",
20 "cpus",
21 "totalmem",
22 "freemem",
23 "uptime",
24 "loadavg",
25 "userInfo",
26 "networkInterfaces",
27 "version",
28 "machine",
29 "availableParallelism",
30 "getPriority",
31 "setPriority",
32];
33
34pub fn constant(name: &str) -> Option<Value> {
36 match name {
37 "EOL" => Some(with_host(|h| h.new_str("\n"))),
38 "devNull" => Some(with_host(|h| h.new_str("/dev/null"))),
39 "constants" => {
45 let sig = super::constants::object(&super::constants::signals());
48 with_host(|h| h.seal_object(&sig, true));
50 let prio = super::constants::object(&super::constants::priority());
51 let errno = super::constants::object(&super::constants::errno());
52 let dlopen = super::constants::object(&super::constants::dlopen());
53 Some(with_host(|h| {
54 let mut m = indexmap::IndexMap::new();
55 m.insert("UV_UDP_REUSEADDR".to_string(), Value::Float(4.0));
56 m.insert("dlopen".to_string(), dlopen);
57 m.insert("errno".to_string(), errno);
58 m.insert("signals".to_string(), sig);
59 m.insert("priority".to_string(), prio);
60 h.new_object(m)
61 }))
62 }
63 _ => None,
64 }
65}
66
67pub fn platform() -> &'static str {
69 match std::env::consts::OS {
70 "macos" => "darwin",
71 "windows" => "win32",
72 other => other,
73 }
74}
75
76pub fn arch() -> &'static str {
78 match std::env::consts::ARCH {
79 "aarch64" => "arm64",
80 "x86_64" => "x64",
81 other => other,
82 }
83}
84
85pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
86 if let Some(m) = method.strip_prefix("@@toPrimitive:") {
88 return call(m, &[]);
89 }
90 let s = |v: &str| Ok(with_host(|h| h.new_str(v)));
91 Some(match method {
92 "platform" => s(platform()),
93 "arch" => s(arch()),
94 "machine" => s(std::env::consts::ARCH),
95 "type" => s(match std::env::consts::OS {
96 "macos" => "Darwin",
97 "linux" => "Linux",
98 "windows" => "Windows_NT",
99 other => other,
100 }),
101 "release" => s(""),
102 "version" => s(""),
103 "hostname" => s(&hostname()),
104 "homedir" => s(&dirs::home_dir()
105 .map(|p| p.to_string_lossy().into_owned())
106 .unwrap_or_default()),
107 "tmpdir" => s(std::env::temp_dir().to_string_lossy().trim_end_matches('/')),
108 "endianness" => s(if cfg!(target_endian = "big") {
109 "BE"
110 } else {
111 "LE"
112 }),
113 "totalmem" => Ok(Value::Float(phys_bytes(libc::_SC_PHYS_PAGES))),
117 "freemem" => Ok(Value::Float(free_bytes())),
118 "uptime" => Ok(Value::Float(uptime_secs())),
119 "cpus" => Ok(cpus()),
120 "loadavg" => {
122 let mut avg = [0f64; 3];
123 let n = unsafe { libc::getloadavg(avg.as_mut_ptr(), 3) };
125 let items: Vec<Value> = if n == 3 {
126 avg.iter().map(|v| Value::Float(*v)).collect()
127 } else {
128 vec![Value::Float(0.0); 3]
129 };
130 Ok(with_host(|h| h.new_array(items)))
131 }
132 "networkInterfaces" => Ok(network_interfaces()),
133 "userInfo" => user_info(args),
134 "availableParallelism" => {
136 let n = std::thread::available_parallelism()
137 .map(|n| n.get())
138 .unwrap_or(1);
139 Ok(Value::Float(n as f64))
140 }
141 "getPriority" => (|| -> Result<Value, String> {
143 let pid = match args.first() {
144 None | Some(Value::Undef) => 0,
145 Some(v) => {
146 super::validate_integer_in(v, "pid", -2_147_483_648.0, 2_147_483_647.0)? as i32
147 }
148 };
149 let prio = unsafe {
153 *errno_location() = 0;
154 libc::getpriority(libc::PRIO_PROCESS as _, pid as _)
155 };
156 if prio == -1 && std::io::Error::last_os_error().raw_os_error().unwrap_or(0) != 0 {
157 return Err(system_error(
158 "uv_os_getpriority",
159 std::io::Error::last_os_error(),
160 ));
161 }
162 Ok(Value::Float(prio as f64))
163 })(),
164 "setPriority" => (|| -> Result<Value, String> {
167 let (pid_v, prio_v) = if args.len() >= 2 {
169 (Some(args[0].clone()), args[1].clone())
170 } else {
171 (None, args.first().cloned().unwrap_or(Value::Undef))
172 };
173 let pid = match pid_v {
174 Some(v) => {
175 super::validate_integer_in(&v, "pid", -2_147_483_648.0, 2_147_483_647.0)? as i32
176 }
177 None => 0,
178 };
179 let prio = super::validate_integer_in(&prio_v, "priority", -20.0, 19.0)? as i32;
180 if unsafe { libc::setpriority(libc::PRIO_PROCESS as _, pid as _, prio as _) } != 0 {
182 return Err(system_error(
183 "uv_os_setpriority",
184 std::io::Error::last_os_error(),
185 ));
186 }
187 Ok(Value::Undef)
188 })(),
189 _ => return None,
190 })
191}
192
193fn hostname() -> String {
194 std::process::Command::new("hostname")
195 .output()
196 .ok()
197 .and_then(|o| String::from_utf8(o.stdout).ok())
198 .map(|s| s.trim().to_string())
199 .unwrap_or_default()
200}
201
202fn user_info(args: &[Value]) -> Result<Value, String> {
207 let as_buffer = match args.first() {
208 Some(o) if with_host(|h| h.type_of(o)) == "object" && !with_host(|h| h.is_null(o)) => {
209 let e = crate::builtins::get_property(o, "encoding")?;
210 with_host(|h| h.as_str(&e)).as_deref() == Some("buffer")
211 }
212 _ => false,
213 };
214 let uid = unsafe { libc::geteuid() };
217 let mut pw: libc::passwd = unsafe { std::mem::zeroed() };
218 let mut buf = vec![0 as libc::c_char; 16384];
219 let mut out: *mut libc::passwd = std::ptr::null_mut();
220 let rc = unsafe { libc::getpwuid_r(uid, &mut pw, buf.as_mut_ptr(), buf.len(), &mut out) };
221 if rc != 0 || out.is_null() {
222 let e = if rc != 0 {
223 std::io::Error::from_raw_os_error(rc)
224 } else {
225 std::io::Error::from_raw_os_error(libc::ENOENT)
226 };
227 return Err(system_error("uv_os_get_passwd", e));
228 }
229 let text = |p: *const libc::c_char| -> Vec<u8> {
230 if p.is_null() {
231 return Vec::new();
232 }
233 unsafe { std::ffi::CStr::from_ptr(p) }.to_bytes().to_vec()
234 };
235 let (name, dir, shell) = (text(pw.pw_name), text(pw.pw_dir), text(pw.pw_shell));
236 let field = |bytes: Vec<u8>| -> Value {
237 if as_buffer {
238 super::buffer::from_bytes(&bytes)
239 } else {
240 with_host(|h| h.new_str(String::from_utf8_lossy(&bytes).into_owned()))
241 }
242 };
243 let (name, dir, shell) = (field(name), field(dir), field(shell));
244 Ok(with_host(|h| {
245 let mut m = IndexMap::new();
246 m.insert("uid".into(), Value::Float(f64::from(pw.pw_uid)));
247 m.insert("gid".into(), Value::Float(f64::from(pw.pw_gid)));
248 m.insert("username".into(), name);
249 m.insert("homedir".into(), dir);
250 m.insert("shell".into(), shell);
251 h.new_object(m)
252 }))
253}
254
255#[cfg(target_os = "macos")]
257unsafe fn errno_location() -> *mut libc::c_int {
258 libc::__error()
259}
260#[cfg(not(target_os = "macos"))]
261unsafe fn errno_location() -> *mut libc::c_int {
262 libc::__errno_location()
263}
264
265fn system_error(syscall: &str, e: std::io::Error) -> String {
270 let code = super::fs::libuv_code(&e);
271 let (errno, reason) = super::util::errno_by_name(code).unwrap_or((libc::EIO, "i/o error"));
272 let msg = format!("A system error occurred: {syscall} returned {code} ({reason})");
273 let full = crate::host::coded_error("Error", "ERR_SYSTEM_ERROR", &msg);
274 with_host(|h| {
275 let err = crate::builtins::synth_error(h, &full);
276 let info = {
277 let mut m = IndexMap::new();
278 m.insert("errno".into(), Value::Float(-f64::from(errno)));
279 m.insert("code".into(), h.new_str(code));
280 m.insert("message".into(), h.new_str(reason));
281 m.insert("syscall".into(), h.new_str(syscall));
282 h.new_object(m)
283 };
284 let (name, stack, sys) = (
285 h.new_str("SystemError"),
286 h.new_str(format!("SystemError [ERR_SYSTEM_ERROR]: {msg}")),
287 h.new_str(syscall),
288 );
289 if let Some(crate::host::JsObj::Object(p)) = h.get_mut(&err) {
290 p.insert("info".into(), info);
291 p.insert("errno".into(), Value::Float(-f64::from(errno)));
292 p.insert("syscall".into(), sys);
293 p.insert("name".into(), name);
294 p.insert("stack".into(), stack);
295 }
296 h.hide_prop(&err, "name");
297 h.exc = Some(err);
298 });
299 full
300}
301
302fn phys_bytes(name: libc::c_int) -> f64 {
306 let pages = unsafe { libc::sysconf(name) };
308 let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
309 if pages <= 0 || page <= 0 {
310 return 0.0;
311 }
312 pages as f64 * page as f64
313}
314
315#[cfg(target_os = "linux")]
318fn free_bytes() -> f64 {
319 phys_bytes(libc::_SC_AVPHYS_PAGES)
320}
321
322#[cfg(target_os = "macos")]
323fn free_bytes() -> f64 {
324 let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
328 if page <= 0 {
329 return 0.0;
330 }
331 let free = sysctl_u32(c"vm.page_free_count").unwrap_or(0) as f64;
335 let spec = sysctl_u32(c"vm.page_speculative_count").unwrap_or(0) as f64;
336 (free + spec) * page as f64
337}
338
339#[cfg(not(any(target_os = "linux", target_os = "macos")))]
340fn free_bytes() -> f64 {
341 0.0
342}
343
344#[cfg(target_os = "linux")]
346fn uptime_secs() -> f64 {
347 std::fs::read_to_string("/proc/uptime")
348 .ok()
349 .and_then(|s| s.split_whitespace().next()?.parse::<f64>().ok())
350 .unwrap_or(0.0)
351}
352
353#[cfg(target_os = "macos")]
354fn uptime_secs() -> f64 {
355 let mut mib = [libc::CTL_KERN, libc::KERN_BOOTTIME];
356 let mut tv: libc::timeval = unsafe { std::mem::zeroed() };
357 let mut len = std::mem::size_of::<libc::timeval>();
358 let rc = unsafe {
360 libc::sysctl(
361 mib.as_mut_ptr(),
362 mib.len() as u32,
363 &mut tv as *mut _ as *mut libc::c_void,
364 &mut len,
365 std::ptr::null_mut(),
366 0,
367 )
368 };
369 if rc != 0 || tv.tv_sec == 0 {
370 return 0.0;
371 }
372 let now = std::time::SystemTime::now()
373 .duration_since(std::time::UNIX_EPOCH)
374 .map(|d| d.as_secs_f64())
375 .unwrap_or(0.0);
376 (now - tv.tv_sec as f64).max(0.0).floor()
377}
378
379#[cfg(not(any(target_os = "linux", target_os = "macos")))]
380fn uptime_secs() -> f64 {
381 0.0
382}
383
384fn cpus() -> Value {
390 let n = std::thread::available_parallelism()
391 .map(|n| n.get())
392 .unwrap_or(1);
393 let model = cpu_model();
394 let speed = cpu_speed_mhz();
395 with_host(|h| {
396 let items: Vec<Value> = (0..n)
397 .map(|_| {
398 let mut times = IndexMap::new();
399 for k in ["user", "nice", "sys", "idle", "irq"] {
404 times.insert(k.to_string(), Value::Float(0.0));
405 }
406 let times = h.new_object(times);
407 let mut m = IndexMap::new();
408 m.insert("model".into(), h.new_str(model.clone()));
409 m.insert("speed".into(), Value::Float(speed));
410 m.insert("times".into(), times);
411 h.new_object(m)
412 })
413 .collect();
414 h.new_array(items)
415 })
416}
417
418#[cfg(target_os = "macos")]
419fn cpu_model() -> String {
420 sysctl_string(c"machdep.cpu.brand_string").unwrap_or_else(|| "unknown".into())
421}
422
423#[cfg(target_os = "linux")]
424fn cpu_model() -> String {
425 std::fs::read_to_string("/proc/cpuinfo")
426 .ok()
427 .and_then(|s| {
428 s.lines()
429 .find(|l| l.starts_with("model name") || l.starts_with("Model"))
430 .and_then(|l| l.split_once(':'))
431 .map(|(_, v)| v.trim().to_string())
432 })
433 .unwrap_or_else(|| "unknown".into())
434}
435
436#[cfg(not(any(target_os = "linux", target_os = "macos")))]
437fn cpu_model() -> String {
438 "unknown".into()
439}
440
441#[cfg(target_os = "macos")]
442fn cpu_speed_mhz() -> f64 {
443 sysctl_u64(c"hw.cpufrequency").map_or(0.0, |hz| (hz / 1_000_000) as f64)
446}
447
448#[cfg(target_os = "linux")]
449fn cpu_speed_mhz() -> f64 {
450 std::fs::read_to_string("/proc/cpuinfo")
451 .ok()
452 .and_then(|s| {
453 s.lines()
454 .find(|l| l.starts_with("cpu MHz"))
455 .and_then(|l| l.split_once(':'))
456 .and_then(|(_, v)| v.trim().parse::<f64>().ok())
457 })
458 .map(|f| f.round())
459 .unwrap_or(0.0)
460}
461
462#[cfg(not(any(target_os = "linux", target_os = "macos")))]
463fn cpu_speed_mhz() -> f64 {
464 0.0
465}
466
467#[cfg(target_os = "macos")]
468fn sysctl_string(name: &std::ffi::CStr) -> Option<String> {
469 let mut len: usize = 0;
470 if unsafe {
472 libc::sysctlbyname(
473 name.as_ptr(),
474 std::ptr::null_mut(),
475 &mut len,
476 std::ptr::null_mut(),
477 0,
478 )
479 } != 0
480 || len == 0
481 {
482 return None;
483 }
484 let mut buf = vec![0u8; len];
485 if unsafe {
487 libc::sysctlbyname(
488 name.as_ptr(),
489 buf.as_mut_ptr() as *mut libc::c_void,
490 &mut len,
491 std::ptr::null_mut(),
492 0,
493 )
494 } != 0
495 {
496 return None;
497 }
498 buf.pop();
499 String::from_utf8(buf).ok()
500}
501
502#[cfg(target_os = "macos")]
503fn sysctl_u32(name: &std::ffi::CStr) -> Option<u32> {
504 let mut out: u32 = 0;
505 let mut len = std::mem::size_of::<u32>();
506 let rc = unsafe {
508 libc::sysctlbyname(
509 name.as_ptr(),
510 &mut out as *mut _ as *mut libc::c_void,
511 &mut len,
512 std::ptr::null_mut(),
513 0,
514 )
515 };
516 (rc == 0).then_some(out)
517}
518
519#[cfg(target_os = "macos")]
520fn sysctl_u64(name: &std::ffi::CStr) -> Option<u64> {
521 let mut out: u64 = 0;
522 let mut len = std::mem::size_of::<u64>();
523 let rc = unsafe {
525 libc::sysctlbyname(
526 name.as_ptr(),
527 &mut out as *mut _ as *mut libc::c_void,
528 &mut len,
529 std::ptr::null_mut(),
530 0,
531 )
532 };
533 (rc == 0).then_some(out)
534}
535
536fn network_interfaces() -> Value {
543 let mut head: *mut libc::ifaddrs = std::ptr::null_mut();
544 if unsafe { libc::getifaddrs(&mut head) } != 0 {
546 return with_host(|h| h.new_object(IndexMap::new()));
547 }
548 let mut macs: std::collections::HashMap<String, String> = std::collections::HashMap::new();
549 let mut addrs: Vec<(String, IfAddr)> = Vec::new();
550 let mut cur = head;
551 while !cur.is_null() {
552 let ifa = unsafe { &*cur };
554 cur = ifa.ifa_next;
555 if ifa.ifa_name.is_null() {
556 continue;
557 }
558 let name = unsafe { std::ffi::CStr::from_ptr(ifa.ifa_name) }
560 .to_string_lossy()
561 .into_owned();
562 if let Some(mac) = link_mac(ifa) {
563 macs.insert(name.clone(), mac);
564 continue;
565 }
566 if let Some(a) = ip_addr(ifa) {
567 addrs.push((name, a));
568 }
569 }
570 unsafe { libc::freeifaddrs(head) };
572 with_host(|h| {
573 let mut grouped: IndexMap<String, Vec<Value>> = IndexMap::new();
574 for (name, a) in addrs {
575 let mac = macs
576 .get(&name)
577 .cloned()
578 .unwrap_or_else(|| "00:00:00:00:00:00".into());
579 let mut m = IndexMap::new();
580 m.insert("address".into(), h.new_str(a.address.clone()));
581 m.insert("netmask".into(), h.new_str(a.netmask.clone()));
582 m.insert("family".into(), h.new_str(a.family.to_string()));
583 m.insert("mac".into(), h.new_str(mac));
584 m.insert("internal".into(), Value::Bool(a.internal));
585 m.insert(
586 "cidr".into(),
587 h.new_str(format!("{}/{}", a.address, a.prefix)),
588 );
589 grouped.entry(name).or_default().push(h.new_object(m));
590 }
591 let mut out = IndexMap::new();
592 for (name, list) in grouped {
593 let arr = h.new_array(list);
594 out.insert(name, arr);
595 }
596 h.new_object(out)
597 })
598}
599
600struct IfAddr {
601 address: String,
602 netmask: String,
603 family: &'static str,
604 internal: bool,
605 prefix: u32,
606}
607
608#[cfg(target_os = "macos")]
610fn link_mac(ifa: &libc::ifaddrs) -> Option<String> {
611 if ifa.ifa_addr.is_null() {
612 return None;
613 }
614 if unsafe { (*ifa.ifa_addr).sa_family } as i32 != libc::AF_LINK {
616 return None;
617 }
618 let dl = unsafe { &*(ifa.ifa_addr as *const libc::sockaddr_dl) };
620 let start = dl.sdl_nlen as usize;
621 let len = dl.sdl_alen as usize;
622 if len != 6 || start + len > dl.sdl_data.len() {
623 return None;
624 }
625 let b: Vec<String> = dl.sdl_data[start..start + len]
626 .iter()
627 .map(|c| format!("{:02x}", *c as u8))
628 .collect();
629 Some(b.join(":"))
630}
631
632#[cfg(target_os = "linux")]
633fn link_mac(ifa: &libc::ifaddrs) -> Option<String> {
634 if ifa.ifa_addr.is_null() {
635 return None;
636 }
637 if unsafe { (*ifa.ifa_addr).sa_family } as i32 != libc::AF_PACKET {
639 return None;
640 }
641 let ll = unsafe { &*(ifa.ifa_addr as *const libc::sockaddr_ll) };
643 let len = ll.sll_halen as usize;
644 if len != 6 {
645 return None;
646 }
647 let b: Vec<String> = ll.sll_addr[..len]
648 .iter()
649 .map(|c| format!("{c:02x}"))
650 .collect();
651 Some(b.join(":"))
652}
653
654#[cfg(not(any(target_os = "linux", target_os = "macos")))]
655fn link_mac(_ifa: &libc::ifaddrs) -> Option<String> {
656 None
657}
658
659fn ip_addr(ifa: &libc::ifaddrs) -> Option<IfAddr> {
661 if ifa.ifa_addr.is_null() {
662 return None;
663 }
664 let fam = unsafe { (*ifa.ifa_addr).sa_family } as i32;
666 let internal = ifa.ifa_flags & libc::IFF_LOOPBACK as u32 != 0;
667 if fam == libc::AF_INET {
668 let sin = unsafe { &*(ifa.ifa_addr as *const libc::sockaddr_in) };
670 let ip = std::net::Ipv4Addr::from(u32::from_be(sin.sin_addr.s_addr));
671 let mask = if ifa.ifa_netmask.is_null() {
672 std::net::Ipv4Addr::UNSPECIFIED
673 } else {
674 let m = unsafe { &*(ifa.ifa_netmask as *const libc::sockaddr_in) };
676 std::net::Ipv4Addr::from(u32::from_be(m.sin_addr.s_addr))
677 };
678 return Some(IfAddr {
679 address: ip.to_string(),
680 netmask: mask.to_string(),
681 family: "IPv4",
682 internal,
683 prefix: u32::from(mask).count_ones(),
684 });
685 }
686 if fam == libc::AF_INET6 {
687 let sin = unsafe { &*(ifa.ifa_addr as *const libc::sockaddr_in6) };
689 let ip = std::net::Ipv6Addr::from(sin.sin6_addr.s6_addr);
690 let mask = if ifa.ifa_netmask.is_null() {
691 std::net::Ipv6Addr::UNSPECIFIED
692 } else {
693 let m = unsafe { &*(ifa.ifa_netmask as *const libc::sockaddr_in6) };
695 std::net::Ipv6Addr::from(m.sin6_addr.s6_addr)
696 };
697 let prefix: u32 = mask.octets().iter().map(|b| b.count_ones()).sum();
698 return Some(IfAddr {
699 address: ip.to_string(),
700 netmask: mask.to_string(),
701 family: "IPv6",
702 internal,
703 prefix,
704 });
705 }
706 None
707}
708
709pub const TO_PRIMITIVE: &[&str] = &[
712 "arch",
713 "availableParallelism",
714 "endianness",
715 "freemem",
716 "homedir",
717 "hostname",
718 "platform",
719 "release",
720 "tmpdir",
721 "totalmem",
722 "type",
723 "uptime",
724 "version",
725 "machine",
726];