forked from denoland/deno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.rs
629 lines (562 loc) · 15.9 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
use crate::sys_info;
use crate::worker::ExitCode;
use deno_core::op2;
use deno_core::v8;
use deno_core::OpState;
use deno_node::NODE_ENV_VAR_ALLOWLIST;
use deno_path_util::normalize_path;
use deno_permissions::PermissionsContainer;
use std::collections::HashMap;
use std::env;
deno_core::extension!(
deno_os,
ops = [
op_env,
op_exec_path,
op_exit,
op_delete_env,
op_get_env,
op_gid,
op_hostname,
op_loadavg,
op_network_interfaces,
op_os_release,
op_os_uptime,
op_set_env,
op_set_exit_code,
op_get_exit_code,
op_system_memory_info,
op_uid,
op_runtime_cpu_usage,
op_runtime_memory_usage,
],
options = {
exit_code: ExitCode,
},
state = |state, options| {
state.put::<ExitCode>(options.exit_code);
},
);
deno_core::extension!(
deno_os_worker,
ops = [
op_env,
op_exec_path,
op_exit,
op_delete_env,
op_get_env,
op_gid,
op_hostname,
op_loadavg,
op_network_interfaces,
op_os_release,
op_os_uptime,
op_set_env,
op_set_exit_code,
op_get_exit_code,
op_system_memory_info,
op_uid,
op_runtime_cpu_usage,
op_runtime_memory_usage,
],
middleware = |op| match op.name {
"op_exit" | "op_set_exit_code" | "op_get_exit_code" =>
op.with_implementation_from(&deno_core::op_void_sync()),
_ => op,
},
);
#[derive(Debug, thiserror::Error)]
pub enum OsError {
#[error(transparent)]
Permission(#[from] deno_permissions::PermissionCheckError),
#[error("File name or path {0:?} is not valid UTF-8")]
InvalidUtf8(std::ffi::OsString),
#[error("Key is an empty string.")]
EnvEmptyKey,
#[error("Key contains invalid characters: {0:?}")]
EnvInvalidKey(String),
#[error("Value contains invalid characters: {0:?}")]
EnvInvalidValue(String),
#[error(transparent)]
Var(#[from] env::VarError),
#[error("{0}")]
Io(#[from] std::io::Error),
}
#[op2(stack_trace)]
#[string]
fn op_exec_path(state: &mut OpState) -> Result<String, OsError> {
let current_exe = env::current_exe().unwrap();
state
.borrow_mut::<PermissionsContainer>()
.check_read_blind(¤t_exe, "exec_path", "Deno.execPath()")?;
// normalize path so it doesn't include '.' or '..' components
let path = normalize_path(current_exe);
path
.into_os_string()
.into_string()
.map_err(OsError::InvalidUtf8)
}
#[op2(fast, stack_trace)]
fn op_set_env(
state: &mut OpState,
#[string] key: &str,
#[string] value: &str,
) -> Result<(), OsError> {
state.borrow_mut::<PermissionsContainer>().check_env(key)?;
if key.is_empty() {
return Err(OsError::EnvEmptyKey);
}
if key.contains(&['=', '\0'] as &[char]) {
return Err(OsError::EnvInvalidKey(key.to_string()));
}
if value.contains('\0') {
return Err(OsError::EnvInvalidValue(value.to_string()));
}
env::set_var(key, value);
Ok(())
}
#[op2(stack_trace)]
#[serde]
fn op_env(
state: &mut OpState,
) -> Result<HashMap<String, String>, deno_core::error::AnyError> {
state.borrow_mut::<PermissionsContainer>().check_env_all()?;
Ok(env::vars().collect())
}
#[op2(stack_trace)]
#[string]
fn op_get_env(
state: &mut OpState,
#[string] key: String,
) -> Result<Option<String>, OsError> {
let skip_permission_check = NODE_ENV_VAR_ALLOWLIST.contains(&key);
if !skip_permission_check {
state.borrow_mut::<PermissionsContainer>().check_env(&key)?;
}
if key.is_empty() {
return Err(OsError::EnvEmptyKey);
}
if key.contains(&['=', '\0'] as &[char]) {
return Err(OsError::EnvInvalidKey(key.to_string()));
}
let r = match env::var(key) {
Err(env::VarError::NotPresent) => None,
v => Some(v?),
};
Ok(r)
}
#[op2(fast, stack_trace)]
fn op_delete_env(
state: &mut OpState,
#[string] key: String,
) -> Result<(), OsError> {
state.borrow_mut::<PermissionsContainer>().check_env(&key)?;
if key.is_empty() || key.contains(&['=', '\0'] as &[char]) {
return Err(OsError::EnvInvalidKey(key.to_string()));
}
env::remove_var(key);
Ok(())
}
#[op2(fast)]
fn op_set_exit_code(state: &mut OpState, #[smi] code: i32) {
state.borrow_mut::<ExitCode>().set(code);
}
#[op2(fast)]
#[smi]
fn op_get_exit_code(state: &mut OpState) -> i32 {
state.borrow_mut::<ExitCode>().get()
}
#[op2(fast)]
fn op_exit(state: &mut OpState) {
let code = state.borrow::<ExitCode>().get();
crate::exit(code)
}
#[op2(stack_trace)]
#[serde]
fn op_loadavg(
state: &mut OpState,
) -> Result<(f64, f64, f64), deno_core::error::AnyError> {
state
.borrow_mut::<PermissionsContainer>()
.check_sys("loadavg", "Deno.loadavg()")?;
Ok(sys_info::loadavg())
}
#[op2(stack_trace, stack_trace)]
#[string]
fn op_hostname(
state: &mut OpState,
) -> Result<String, deno_core::error::AnyError> {
state
.borrow_mut::<PermissionsContainer>()
.check_sys("hostname", "Deno.hostname()")?;
Ok(sys_info::hostname())
}
#[op2(stack_trace)]
#[string]
fn op_os_release(
state: &mut OpState,
) -> Result<String, deno_core::error::AnyError> {
state
.borrow_mut::<PermissionsContainer>()
.check_sys("osRelease", "Deno.osRelease()")?;
Ok(sys_info::os_release())
}
#[op2(stack_trace)]
#[serde]
fn op_network_interfaces(
state: &mut OpState,
) -> Result<Vec<NetworkInterface>, OsError> {
state
.borrow_mut::<PermissionsContainer>()
.check_sys("networkInterfaces", "Deno.networkInterfaces()")?;
Ok(netif::up()?.map(NetworkInterface::from).collect())
}
#[derive(serde::Serialize)]
struct NetworkInterface {
family: &'static str,
name: String,
address: String,
netmask: String,
scopeid: Option<u32>,
cidr: String,
mac: String,
}
impl From<netif::Interface> for NetworkInterface {
fn from(ifa: netif::Interface) -> Self {
let family = match ifa.address() {
std::net::IpAddr::V4(_) => "IPv4",
std::net::IpAddr::V6(_) => "IPv6",
};
let (address, range) = ifa.cidr();
let cidr = format!("{address:?}/{range}");
let name = ifa.name().to_owned();
let address = format!("{:?}", ifa.address());
let netmask = format!("{:?}", ifa.netmask());
let scopeid = ifa.scope_id();
let [b0, b1, b2, b3, b4, b5] = ifa.mac();
let mac = format!("{b0:02x}:{b1:02x}:{b2:02x}:{b3:02x}:{b4:02x}:{b5:02x}");
Self {
family,
name,
address,
netmask,
scopeid,
cidr,
mac,
}
}
}
#[op2(stack_trace)]
#[serde]
fn op_system_memory_info(
state: &mut OpState,
) -> Result<Option<sys_info::MemInfo>, deno_core::error::AnyError> {
state
.borrow_mut::<PermissionsContainer>()
.check_sys("systemMemoryInfo", "Deno.systemMemoryInfo()")?;
Ok(sys_info::mem_info())
}
#[cfg(not(windows))]
#[op2(stack_trace)]
#[smi]
fn op_gid(
state: &mut OpState,
) -> Result<Option<u32>, deno_core::error::AnyError> {
state
.borrow_mut::<PermissionsContainer>()
.check_sys("gid", "Deno.gid()")?;
// TODO(bartlomieju):
#[allow(clippy::undocumented_unsafe_blocks)]
unsafe {
Ok(Some(libc::getgid()))
}
}
#[cfg(windows)]
#[op2(stack_trace)]
#[smi]
fn op_gid(
state: &mut OpState,
) -> Result<Option<u32>, deno_core::error::AnyError> {
state
.borrow_mut::<PermissionsContainer>()
.check_sys("gid", "Deno.gid()")?;
Ok(None)
}
#[cfg(not(windows))]
#[op2(stack_trace)]
#[smi]
fn op_uid(
state: &mut OpState,
) -> Result<Option<u32>, deno_core::error::AnyError> {
state
.borrow_mut::<PermissionsContainer>()
.check_sys("uid", "Deno.uid()")?;
// TODO(bartlomieju):
#[allow(clippy::undocumented_unsafe_blocks)]
unsafe {
Ok(Some(libc::getuid()))
}
}
#[cfg(windows)]
#[op2(stack_trace)]
#[smi]
fn op_uid(
state: &mut OpState,
) -> Result<Option<u32>, deno_core::error::AnyError> {
state
.borrow_mut::<PermissionsContainer>()
.check_sys("uid", "Deno.uid()")?;
Ok(None)
}
#[op2]
#[serde]
fn op_runtime_cpu_usage() -> (usize, usize) {
let (sys, user) = get_cpu_usage();
(sys.as_micros() as usize, user.as_micros() as usize)
}
#[cfg(unix)]
fn get_cpu_usage() -> (std::time::Duration, std::time::Duration) {
let mut rusage = std::mem::MaybeUninit::uninit();
// Uses POSIX getrusage from libc
// to retrieve user and system times
// SAFETY: libc call
let ret = unsafe { libc::getrusage(libc::RUSAGE_SELF, rusage.as_mut_ptr()) };
if ret != 0 {
return Default::default();
}
// SAFETY: already checked the result
let rusage = unsafe { rusage.assume_init() };
let sys = std::time::Duration::from_micros(rusage.ru_stime.tv_usec as u64)
+ std::time::Duration::from_secs(rusage.ru_stime.tv_sec as u64);
let user = std::time::Duration::from_micros(rusage.ru_utime.tv_usec as u64)
+ std::time::Duration::from_secs(rusage.ru_utime.tv_sec as u64);
(sys, user)
}
#[cfg(windows)]
fn get_cpu_usage() -> (std::time::Duration, std::time::Duration) {
use winapi::shared::minwindef::FALSE;
use winapi::shared::minwindef::FILETIME;
use winapi::shared::minwindef::TRUE;
use winapi::um::minwinbase::SYSTEMTIME;
use winapi::um::processthreadsapi::GetCurrentProcess;
use winapi::um::processthreadsapi::GetProcessTimes;
use winapi::um::timezoneapi::FileTimeToSystemTime;
fn convert_system_time(system_time: SYSTEMTIME) -> std::time::Duration {
std::time::Duration::from_secs(
system_time.wHour as u64 * 3600
+ system_time.wMinute as u64 * 60
+ system_time.wSecond as u64,
) + std::time::Duration::from_millis(system_time.wMilliseconds as u64)
}
let mut creation_time = std::mem::MaybeUninit::<FILETIME>::uninit();
let mut exit_time = std::mem::MaybeUninit::<FILETIME>::uninit();
let mut kernel_time = std::mem::MaybeUninit::<FILETIME>::uninit();
let mut user_time = std::mem::MaybeUninit::<FILETIME>::uninit();
// SAFETY: winapi calls
let ret = unsafe {
GetProcessTimes(
GetCurrentProcess(),
creation_time.as_mut_ptr(),
exit_time.as_mut_ptr(),
kernel_time.as_mut_ptr(),
user_time.as_mut_ptr(),
)
};
if ret != TRUE {
return std::default::Default::default();
}
let mut kernel_system_time = std::mem::MaybeUninit::<SYSTEMTIME>::uninit();
let mut user_system_time = std::mem::MaybeUninit::<SYSTEMTIME>::uninit();
// SAFETY: convert to system time
unsafe {
let sys_ret = FileTimeToSystemTime(
kernel_time.assume_init_mut(),
kernel_system_time.as_mut_ptr(),
);
let user_ret = FileTimeToSystemTime(
user_time.assume_init_mut(),
user_system_time.as_mut_ptr(),
);
match (sys_ret, user_ret) {
(TRUE, TRUE) => (
convert_system_time(kernel_system_time.assume_init()),
convert_system_time(user_system_time.assume_init()),
),
(TRUE, FALSE) => (
convert_system_time(kernel_system_time.assume_init()),
Default::default(),
),
(FALSE, TRUE) => (
Default::default(),
convert_system_time(user_system_time.assume_init()),
),
(_, _) => Default::default(),
}
}
}
#[cfg(not(any(windows, unix)))]
fn get_cpu_usage() -> (std::time::Duration, std::time::Duration) {
Default::default()
}
#[op2]
#[serde]
fn op_runtime_memory_usage(
scope: &mut v8::HandleScope,
) -> (usize, usize, usize, usize) {
let mut s = v8::HeapStatistics::default();
scope.get_heap_statistics(&mut s);
let (rss, heap_total, heap_used, external) = (
rss(),
s.total_heap_size(),
s.used_heap_size(),
s.external_memory(),
);
(rss, heap_total, heap_used, external)
}
#[cfg(any(target_os = "android", target_os = "linux"))]
fn rss() -> usize {
// Inspired by https://github.com/Arc-blroth/memory-stats/blob/5364d0d09143de2a470d33161b2330914228fde9/src/linux.rs
// Extracts a positive integer from a string that
// may contain leading spaces and trailing chars.
// Returns the extracted number and the index of
// the next character in the string.
fn scan_int(string: &str) -> (usize, usize) {
let mut out = 0;
let mut idx = 0;
let mut chars = string.chars().peekable();
while let Some(' ') = chars.next_if_eq(&' ') {
idx += 1;
}
for n in chars {
idx += 1;
if n.is_ascii_digit() {
out *= 10;
out += n as usize - '0' as usize;
} else {
break;
}
}
(out, idx)
}
#[allow(clippy::disallowed_methods)]
let statm_content = if let Ok(c) = std::fs::read_to_string("/proc/self/statm")
{
c
} else {
return 0;
};
// statm returns the virtual size and rss, in
// multiples of the page size, as the first
// two columns of output.
// SAFETY: libc call
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
if page_size < 0 {
return 0;
}
let (_total_size_pages, idx) = scan_int(&statm_content);
let (total_rss_pages, _) = scan_int(&statm_content[idx..]);
total_rss_pages * page_size as usize
}
#[cfg(target_os = "macos")]
fn rss() -> usize {
// Inspired by https://github.com/Arc-blroth/memory-stats/blob/5364d0d09143de2a470d33161b2330914228fde9/src/darwin.rs
let mut task_info =
std::mem::MaybeUninit::<libc::mach_task_basic_info_data_t>::uninit();
let mut count = libc::MACH_TASK_BASIC_INFO_COUNT;
// SAFETY: libc calls
let r = unsafe {
libc::task_info(
libc::mach_task_self(),
libc::MACH_TASK_BASIC_INFO,
task_info.as_mut_ptr() as libc::task_info_t,
&mut count as *mut libc::mach_msg_type_number_t,
)
};
// According to libuv this should never fail
assert_eq!(r, libc::KERN_SUCCESS);
// SAFETY: we just asserted that it was success
let task_info = unsafe { task_info.assume_init() };
task_info.resident_size as usize
}
#[cfg(target_os = "openbsd")]
fn rss() -> usize {
// Uses OpenBSD's KERN_PROC_PID sysctl(2)
// to retrieve information about the current
// process, part of which is the RSS (p_vm_rssize)
// SAFETY: libc call (get PID of own process)
let pid = unsafe { libc::getpid() };
// SAFETY: libc call (get system page size)
let pagesize = unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as usize;
// KERN_PROC_PID returns a struct libc::kinfo_proc
let mut kinfoproc = std::mem::MaybeUninit::<libc::kinfo_proc>::uninit();
let mut size = std::mem::size_of_val(&kinfoproc) as libc::size_t;
let mut mib = [
libc::CTL_KERN,
libc::KERN_PROC,
libc::KERN_PROC_PID,
pid,
// mib is an array of integers, size is of type size_t
// conversion is safe, because the size of a libc::kinfo_proc
// structure will not exceed i32::MAX
size.try_into().unwrap(),
1,
];
// SAFETY: libc call, mib has been statically initialized,
// kinfoproc is a valid pointer to a libc::kinfo_proc struct
let res = unsafe {
libc::sysctl(
mib.as_mut_ptr(),
mib.len() as _,
kinfoproc.as_mut_ptr() as *mut libc::c_void,
&mut size,
std::ptr::null_mut(),
0,
)
};
if res == 0 {
// SAFETY: sysctl returns 0 on success and kinfoproc is initialized
// p_vm_rssize contains size in pages -> multiply with pagesize to
// get size in bytes.
pagesize * unsafe { (*kinfoproc.as_mut_ptr()).p_vm_rssize as usize }
} else {
0
}
}
#[cfg(windows)]
fn rss() -> usize {
use winapi::shared::minwindef::DWORD;
use winapi::shared::minwindef::FALSE;
use winapi::um::processthreadsapi::GetCurrentProcess;
use winapi::um::psapi::GetProcessMemoryInfo;
use winapi::um::psapi::PROCESS_MEMORY_COUNTERS;
// SAFETY: winapi calls
unsafe {
// this handle is a constant—no need to close it
let current_process = GetCurrentProcess();
let mut pmc: PROCESS_MEMORY_COUNTERS = std::mem::zeroed();
if GetProcessMemoryInfo(
current_process,
&mut pmc,
std::mem::size_of::<PROCESS_MEMORY_COUNTERS>() as DWORD,
) != FALSE
{
pmc.WorkingSetSize
} else {
0
}
}
}
fn os_uptime(state: &mut OpState) -> Result<u64, deno_core::error::AnyError> {
state
.borrow_mut::<PermissionsContainer>()
.check_sys("osUptime", "Deno.osUptime()")?;
Ok(sys_info::os_uptime())
}
#[op2(fast, stack_trace)]
#[number]
fn op_os_uptime(
state: &mut OpState,
) -> Result<u64, deno_core::error::AnyError> {
os_uptime(state)
}