repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/build.rs
ext/node/build.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::env; fn main() { println!("cargo:rustc-env=TARGET={}", env::var("TARGET").unwrap()); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/vm.rs
ext/node/ops/vm.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::rc::Rc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::time::Duration; use deno_core::JsBuffer; use deno_core::op2; use deno_core::serde_v8; use deno_core::v8; use deno_core::v8::MapFnTo; use crate::create_host_defined_options; pub const PRIVATE_SYMBOL_NAME: v8::OneByteConst = v8::String::create_external_onebyte_const(b"node:contextify:context"); /// An unbounded script that can be run in a context. pub struct ContextifyScript { script: v8::TracedReference<v8::UnboundScript>, } // SAFETY: we're sure this can be GCed unsafe impl v8::cppgc::GarbageCollected for ContextifyScript { fn trace(&self, visitor: &mut v8::cppgc::Visitor) { visitor.trace(&self.script); } fn get_name(&self) -> &'static std::ffi::CStr { c"ContextifyScript" } } impl ContextifyScript { #[allow(clippy::too_many_arguments)] fn create<'s>( scope: &mut v8::PinScope<'s, '_>, source: v8::Local<'s, v8::String>, filename: v8::Local<'s, v8::Value>, line_offset: i32, column_offset: i32, cached_data: Option<JsBuffer>, produce_cached_data: bool, parsing_context: Option<v8::Local<'s, v8::Object>>, ) -> Option<CompileResult<'s>> { let context = if let Some(parsing_context) = parsing_context { let Some(context) = ContextifyContext::from_sandbox_obj(scope, parsing_context) else { let message = v8::String::new_external_onebyte_static( scope, b"Invalid sandbox object", ) .unwrap(); let exception = v8::Exception::type_error(scope, message); scope.throw_exception(exception); return None; }; context.context(scope) } else { scope.get_current_context() }; let scope = &mut v8::ContextScope::new(scope, context); let host_defined_options = create_host_defined_options(scope); let origin = v8::ScriptOrigin::new( scope, filename, line_offset, column_offset, true, -1, None, false, false, false, Some(host_defined_options), ); let mut source = if let Some(cached_data) = cached_data { let cached_data = v8::script_compiler::CachedData::new(&cached_data); v8::script_compiler::Source::new_with_cached_data( source, Some(&origin), cached_data, ) } else { v8::script_compiler::Source::new(source, Some(&origin)) }; let options = if source.get_cached_data().is_some() { v8::script_compiler::CompileOptions::ConsumeCodeCache } else { v8::script_compiler::CompileOptions::NoCompileOptions }; v8::tc_scope!(scope, scope); let Some(unbound_script) = v8::script_compiler::compile_unbound_script( scope, &mut source, options, v8::script_compiler::NoCacheReason::NoReason, ) else { if !scope.has_terminated() { scope.rethrow(); } return None; }; let cached_data = if produce_cached_data { unbound_script.create_code_cache() } else { None }; let script = v8::TracedReference::new(scope, unbound_script); let this = deno_core::cppgc::make_cppgc_object(scope, Self { script }); Some(CompileResult { value: serde_v8::Value { v8_value: this.into(), }, cached_data: cached_data.as_ref().map(|c| { let backing_store = v8::ArrayBuffer::new_backing_store_from_vec(c.to_vec()); v8::ArrayBuffer::with_backing_store(scope, &backing_store.make_shared()) .into() }), cached_data_rejected: source .get_cached_data() .map(|c| c.rejected()) .unwrap_or(false), cached_data_produced: cached_data.is_some(), }) } fn run_in_context<'s>( &self, scope: &mut v8::PinScope<'s, '_>, sandbox: Option<v8::Local<'s, v8::Object>>, timeout: i64, display_errors: bool, break_on_sigint: bool, ) -> Option<v8::Local<'s, v8::Value>> { let (context, microtask_queue) = if let Some(sandbox) = sandbox { let Some(context) = ContextifyContext::from_sandbox_obj(scope, sandbox) else { let message = v8::String::new_external_onebyte_static( scope, b"Invalid sandbox object", ) .unwrap(); let exception = v8::Exception::type_error(scope, message); scope.throw_exception(exception); return None; }; (context.context(scope), context.microtask_queue()) } else { (scope.get_current_context(), None) }; self.eval_machine( scope, context, timeout, display_errors, break_on_sigint, microtask_queue, ) } pub fn eval_machine<'s, 'i>( &self, scope: &mut v8::PinScope<'s, 'i>, context: v8::Local<'s, v8::Context>, timeout: i64, _display_errors: bool, _break_on_sigint: bool, microtask_queue: Option<&v8::MicrotaskQueue>, ) -> Option<v8::Local<'s, v8::Value>> { let context_scope = &mut v8::ContextScope::new(scope, context); let scope_storage = std::pin::pin!(v8::EscapableHandleScope::new(context_scope)); let scope = &mut scope_storage.init(); v8::tc_scope!(scope, scope); let unbound_script = self.script.get(scope).unwrap(); let script = unbound_script.bind_to_current_context(scope); let handle = scope.thread_safe_handle(); let mut run = || { let r = script.run(scope); if r.is_some() && let Some(mtask_queue) = microtask_queue { mtask_queue.perform_checkpoint(scope); } r }; #[allow(clippy::disallowed_types)] let timed_out = std::sync::Arc::new(AtomicBool::new(false)); let result = if timeout != -1 { let timed_out = timed_out.clone(); let (tx, rx) = std::sync::mpsc::channel(); deno_core::unsync::spawn_blocking(move || { if rx .recv_timeout(Duration::from_millis(timeout as _)) .is_err() { timed_out.store(true, Ordering::Relaxed); handle.terminate_execution(); } }); let r = run(); let _ = tx.send(()); r } else { run() }; if timed_out.load(Ordering::Relaxed) { if scope.has_terminated() { scope.cancel_terminate_execution(); } let message = v8::String::new( scope, &format!("Script execution timed out after {timeout}ms"), ) .unwrap(); let exception = v8::Exception::error(scope, message); let code_str = v8::String::new_external_onebyte_static(scope, b"code").unwrap(); let code = v8::String::new_external_onebyte_static( scope, b"ERR_SCRIPT_EXECUTION_TIMEOUT", ) .unwrap(); exception .cast::<v8::Object>() .set(scope, code_str.into(), code.into()); scope.throw_exception(exception); } if scope.has_caught() { // If there was an exception thrown during script execution, re-throw it. if !scope.has_terminated() { scope.rethrow(); } return None; } Some(scope.escape(result?)) } } pub struct ContextifyContext { microtask_queue: *mut v8::MicrotaskQueue, context: v8::TracedReference<v8::Context>, sandbox: v8::TracedReference<v8::Object>, } // SAFETY: we're sure this can be GCed unsafe impl deno_core::GarbageCollected for ContextifyContext { fn trace(&self, visitor: &mut v8::cppgc::Visitor) { visitor.trace(&self.context); visitor.trace(&self.sandbox); } fn get_name(&self) -> &'static std::ffi::CStr { c"ContextifyContext" } } impl Drop for ContextifyContext { fn drop(&mut self) { if !self.microtask_queue.is_null() { // SAFETY: If this isn't null, it is a valid MicrotaskQueue. unsafe { std::ptr::drop_in_place(self.microtask_queue); } } } } struct AllowCodeGenWasm(bool); extern "C" fn allow_wasm_code_gen( context: v8::Local<v8::Context>, _source: v8::Local<v8::String>, ) -> bool { match context.get_slot::<AllowCodeGenWasm>() { Some(b) => b.0, None => true, } } impl ContextifyContext { pub fn attach( scope: &mut v8::PinScope<'_, '_>, sandbox_obj: v8::Local<v8::Object>, _name: String, _origin: String, allow_code_gen_strings: bool, allow_code_gen_wasm: bool, own_microtask_queue: bool, ) { let main_context = scope.get_current_context(); let tmp = init_global_template(scope, ContextInitMode::UseSnapshot); let microtask_queue = if own_microtask_queue { v8::MicrotaskQueue::new(scope, v8::MicrotasksPolicy::Explicit).into_raw() } else { std::ptr::null_mut() }; let context = create_v8_context( scope, tmp, ContextInitMode::UseSnapshot, microtask_queue, ); let context_state = main_context.get_aligned_pointer_from_embedder_data( deno_core::CONTEXT_STATE_SLOT_INDEX, ); let module_map = main_context .get_aligned_pointer_from_embedder_data(deno_core::MODULE_MAP_SLOT_INDEX); context.set_security_token(main_context.get_security_token(scope)); // SAFETY: set embedder data from the creation context unsafe { context.set_aligned_pointer_in_embedder_data( deno_core::CONTEXT_STATE_SLOT_INDEX, context_state, ); context.set_aligned_pointer_in_embedder_data( deno_core::MODULE_MAP_SLOT_INDEX, module_map, ); } scope.set_allow_wasm_code_generation_callback(allow_wasm_code_gen); context.set_allow_generation_from_strings(allow_code_gen_strings); context.set_slot(Rc::new(AllowCodeGenWasm(allow_code_gen_wasm))); let wrapper = { let context = v8::TracedReference::new(scope, context); let sandbox = v8::TracedReference::new(scope, sandbox_obj); deno_core::cppgc::make_cppgc_object( scope, Self { context, sandbox, microtask_queue, }, ) }; let ptr = deno_core::cppgc::try_unwrap_cppgc_object::<Self>(scope, wrapper.into()); // SAFETY: We are storing a pointer to the ContextifyContext // in the embedder data of the v8::Context. The contextified wrapper // lives longer than the execution context, so this should be safe. unsafe { context.set_aligned_pointer_in_embedder_data( 3, &*ptr.unwrap() as *const ContextifyContext as _, ); } let private_str = v8::String::new_from_onebyte_const(scope, &PRIVATE_SYMBOL_NAME); let private_symbol = v8::Private::for_api(scope, private_str); sandbox_obj.set_private(scope, private_symbol, wrapper.into()); } pub fn from_sandbox_obj<'a>( scope: &mut v8::PinScope<'a, '_>, sandbox_obj: v8::Local<v8::Object>, ) -> Option<&'a Self> { let private_str = v8::String::new_from_onebyte_const(scope, &PRIVATE_SYMBOL_NAME); let private_symbol = v8::Private::for_api(scope, private_str); sandbox_obj .get_private(scope, private_symbol) .and_then(|wrapper| { deno_core::cppgc::try_unwrap_cppgc_object::<Self>(scope, wrapper) // SAFETY: the lifetime of the scope does not actually bind to // the lifetime of this reference at all, but the object we read // it from does, so it will be alive at least that long. .map(|r| unsafe { &*(&*r as *const _) }) }) } pub fn is_contextify_context( scope: &mut v8::PinScope<'_, '_>, object: v8::Local<v8::Object>, ) -> bool { Self::from_sandbox_obj(scope, object).is_some() } pub fn context<'a>( &self, scope: &mut v8::PinScope<'a, '_>, ) -> v8::Local<'a, v8::Context> { self.context.get(scope).unwrap() } fn global_proxy<'s>( &self, scope: &mut v8::PinScope<'s, '_>, ) -> v8::Local<'s, v8::Object> { let ctx = self.context(scope); ctx.global(scope) } fn sandbox<'a>( &self, scope: &mut v8::PinScope<'a, '_>, ) -> Option<v8::Local<'a, v8::Object>> { self.sandbox.get(scope) } fn microtask_queue(&self) -> Option<&v8::MicrotaskQueue> { if self.microtask_queue.is_null() { None } else { // SAFETY: If this isn't null, it is a valid MicrotaskQueue. Some(unsafe { &*self.microtask_queue }) } } fn get<'a, 'c>( scope: &mut v8::PinScope<'a, '_>, object: v8::Local<'a, v8::Object>, ) -> Option<&'c ContextifyContext> { let context = object.get_creation_context(scope)?; let context_ptr = context.get_aligned_pointer_from_embedder_data(3); if context_ptr.is_null() { return None; } // SAFETY: We are storing a pointer to the ContextifyContext // in the embedder data of the v8::Context during creation. Some(unsafe { &*(context_ptr as *const ContextifyContext) }) } } pub const VM_CONTEXT_INDEX: usize = 0; #[derive(PartialEq)] pub enum ContextInitMode { ForSnapshot, UseSnapshot, } pub fn create_v8_context<'a>( scope: &mut v8::PinScope<'a, '_, ()>, object_template: v8::Local<v8::ObjectTemplate>, mode: ContextInitMode, microtask_queue: *mut v8::MicrotaskQueue, ) -> v8::Local<'a, v8::Context> { let scope = std::pin::pin!(v8::EscapableHandleScope::new(scope)); let scope = &mut scope.init(); let context = if mode == ContextInitMode::UseSnapshot { v8::Context::from_snapshot( scope, VM_CONTEXT_INDEX, v8::ContextOptions { microtask_queue: Some(microtask_queue), ..Default::default() }, ) .unwrap() } else { let ctx = v8::Context::new( scope, v8::ContextOptions { global_template: Some(object_template), microtask_queue: Some(microtask_queue), ..Default::default() }, ); // SAFETY: ContextifyContexts will update this to a pointer to the native object unsafe { ctx.set_aligned_pointer_in_embedder_data(1, std::ptr::null_mut()); ctx.set_aligned_pointer_in_embedder_data(2, std::ptr::null_mut()); ctx.set_aligned_pointer_in_embedder_data(3, std::ptr::null_mut()); ctx.clear_all_slots(); }; ctx }; scope.escape(context) } #[derive(Debug, Clone)] struct SlotContextifyGlobalTemplate(v8::Global<v8::ObjectTemplate>); #[allow(clippy::unnecessary_unwrap)] pub fn init_global_template<'a>( scope: &mut v8::PinScope<'a, '_, ()>, mode: ContextInitMode, ) -> v8::Local<'a, v8::ObjectTemplate> { let maybe_object_template_slot = scope.get_slot::<SlotContextifyGlobalTemplate>(); if maybe_object_template_slot.is_none() { let global_object_template = init_global_template_inner(scope); if mode == ContextInitMode::UseSnapshot { let contextify_global_template_slot = SlotContextifyGlobalTemplate( v8::Global::new(scope, global_object_template), ); scope.set_slot(contextify_global_template_slot); } global_object_template } else { let object_template_slot = maybe_object_template_slot .expect("ContextifyGlobalTemplate slot should be already populated.") .clone(); v8::Local::new(scope, object_template_slot.0) } } // Using thread_local! to get around compiler bug. // // See NOTE in ext/node/global.rs#L12 thread_local! { pub static QUERY_MAP_FN: v8::NamedPropertyQueryCallback = property_query.map_fn_to(); pub static GETTER_MAP_FN: v8::NamedPropertyGetterCallback = property_getter.map_fn_to(); pub static SETTER_MAP_FN: v8::NamedPropertySetterCallback = property_setter.map_fn_to(); pub static DELETER_MAP_FN: v8::NamedPropertyDeleterCallback = property_deleter.map_fn_to(); pub static ENUMERATOR_MAP_FN: v8::NamedPropertyEnumeratorCallback = property_enumerator.map_fn_to(); pub static DEFINER_MAP_FN: v8::NamedPropertyDefinerCallback = property_definer.map_fn_to(); pub static DESCRIPTOR_MAP_FN: v8::NamedPropertyDescriptorCallback = property_descriptor.map_fn_to(); } thread_local! { pub static INDEXED_GETTER_MAP_FN: v8::IndexedPropertyGetterCallback = indexed_property_getter.map_fn_to(); pub static INDEXED_SETTER_MAP_FN: v8::IndexedPropertySetterCallback = indexed_property_setter.map_fn_to(); pub static INDEXED_DELETER_MAP_FN: v8::IndexedPropertyDeleterCallback = indexed_property_deleter.map_fn_to(); pub static INDEXED_DEFINER_MAP_FN: v8::IndexedPropertyDefinerCallback = indexed_property_definer.map_fn_to(); pub static INDEXED_DESCRIPTOR_MAP_FN: v8::IndexedPropertyDescriptorCallback = indexed_property_descriptor.map_fn_to(); pub static INDEXED_ENUMERATOR_MAP_FN: v8::IndexedPropertyEnumeratorCallback = indexed_property_enumerator.map_fn_to(); pub static INDEXED_QUERY_MAP_FN: v8::IndexedPropertyQueryCallback = indexed_property_query.map_fn_to(); } pub fn init_global_template_inner<'a, 'b, 'i>( scope: &'b mut v8::PinScope<'a, 'i, ()>, ) -> v8::Local<'a, v8::ObjectTemplate> { let scope = std::pin::pin!(v8::EscapableHandleScope::new(scope)); let scope = &mut scope.init(); let global_object_template = v8::ObjectTemplate::new(scope); global_object_template.set_internal_field_count(3); let named_property_handler_config = { let mut config = v8::NamedPropertyHandlerConfiguration::new() .flags(v8::PropertyHandlerFlags::HAS_NO_SIDE_EFFECT); config = GETTER_MAP_FN.with(|getter| config.getter_raw(*getter)); config = SETTER_MAP_FN.with(|setter| config.setter_raw(*setter)); config = QUERY_MAP_FN.with(|query| config.query_raw(*query)); config = DELETER_MAP_FN.with(|deleter| config.deleter_raw(*deleter)); config = ENUMERATOR_MAP_FN.with(|enumerator| config.enumerator_raw(*enumerator)); config = DEFINER_MAP_FN.with(|definer| config.definer_raw(*definer)); config = DESCRIPTOR_MAP_FN.with(|descriptor| config.descriptor_raw(*descriptor)); config }; let indexed_property_handler_config = { let mut config = v8::IndexedPropertyHandlerConfiguration::new() .flags(v8::PropertyHandlerFlags::HAS_NO_SIDE_EFFECT); config = INDEXED_GETTER_MAP_FN.with(|getter| config.getter_raw(*getter)); config = INDEXED_SETTER_MAP_FN.with(|setter| config.setter_raw(*setter)); config = INDEXED_QUERY_MAP_FN.with(|query| config.query_raw(*query)); config = INDEXED_DELETER_MAP_FN.with(|deleter| config.deleter_raw(*deleter)); config = INDEXED_ENUMERATOR_MAP_FN .with(|enumerator| config.enumerator_raw(*enumerator)); config = INDEXED_DEFINER_MAP_FN.with(|definer| config.definer_raw(*definer)); config = INDEXED_DESCRIPTOR_MAP_FN .with(|descriptor| config.descriptor_raw(*descriptor)); config }; global_object_template .set_named_property_handler(named_property_handler_config); global_object_template .set_indexed_property_handler(indexed_property_handler_config); scope.escape(global_object_template) } fn property_query<'s>( scope: &mut v8::PinScope<'s, '_>, property: v8::Local<'s, v8::Name>, args: v8::PropertyCallbackArguments<'s>, mut rv: v8::ReturnValue<v8::Integer>, ) -> v8::Intercepted { let Some(ctx) = ContextifyContext::get(scope, args.this()) else { return v8::Intercepted::No; }; let context = ctx.context(scope); let scope = &mut v8::ContextScope::new(scope, context); let Some(sandbox) = ctx.sandbox(scope) else { return v8::Intercepted::No; }; match sandbox.has_real_named_property(scope, property) { None => v8::Intercepted::No, Some(true) => { let Some(attr) = sandbox.get_real_named_property_attributes(scope, property) else { return v8::Intercepted::No; }; rv.set_uint32(attr.as_u32()); v8::Intercepted::Yes } Some(false) => { match ctx .global_proxy(scope) .has_real_named_property(scope, property) { None => v8::Intercepted::No, Some(true) => { let Some(attr) = ctx .global_proxy(scope) .get_real_named_property_attributes(scope, property) else { return v8::Intercepted::No; }; rv.set_uint32(attr.as_u32()); v8::Intercepted::Yes } Some(false) => v8::Intercepted::No, } } } } fn property_getter<'s>( scope: &mut v8::PinScope<'s, '_>, key: v8::Local<'s, v8::Name>, args: v8::PropertyCallbackArguments<'s>, mut ret: v8::ReturnValue, ) -> v8::Intercepted { let Some(ctx) = ContextifyContext::get(scope, args.this()) else { return v8::Intercepted::No; }; let Some(sandbox) = ctx.sandbox(scope) else { return v8::Intercepted::No; }; v8::tc_scope!(tc_scope, scope); let maybe_rv = sandbox.get_real_named_property(tc_scope, key).or_else(|| { ctx .global_proxy(tc_scope) .get_real_named_property(tc_scope, key) }); if let Some(mut rv) = maybe_rv { if tc_scope.has_caught() && !tc_scope.has_terminated() { tc_scope.rethrow(); } if rv == sandbox { rv = ctx.global_proxy(tc_scope).into(); } ret.set(rv); return v8::Intercepted::Yes; } v8::Intercepted::No } fn property_setter<'s>( scope: &mut v8::PinScope<'s, '_>, key: v8::Local<'s, v8::Name>, value: v8::Local<'s, v8::Value>, args: v8::PropertyCallbackArguments<'s>, _rv: v8::ReturnValue<()>, ) -> v8::Intercepted { let Some(ctx) = ContextifyContext::get(scope, args.this()) else { return v8::Intercepted::No; }; let (attributes, is_declared_on_global_proxy) = match ctx .global_proxy(scope) .get_real_named_property_attributes(scope, key) { Some(attr) => (attr, true), None => (v8::PropertyAttribute::NONE, false), }; let mut read_only = attributes.is_read_only(); let Some(sandbox) = ctx.sandbox(scope) else { return v8::Intercepted::No; }; let (attributes, is_declared_on_sandbox) = match sandbox.get_real_named_property_attributes(scope, key) { Some(attr) => (attr, true), None => (v8::PropertyAttribute::NONE, false), }; read_only |= attributes.is_read_only(); if read_only { return v8::Intercepted::No; } // true for x = 5 // false for this.x = 5 // false for Object.defineProperty(this, 'foo', ...) // false for vmResult.x = 5 where vmResult = vm.runInContext(); let is_contextual_store = ctx.global_proxy(scope) != args.this(); // Indicator to not return before setting (undeclared) function declarations // on the sandbox in strict mode, i.e. args.ShouldThrowOnError() = true. // True for 'function f() {}', 'this.f = function() {}', // 'var f = function()'. // In effect only for 'function f() {}' because // var f = function(), is_declared = true // this.f = function() {}, is_contextual_store = false. let is_function = value.is_function(); let is_declared = is_declared_on_global_proxy || is_declared_on_sandbox; if !is_declared && args.should_throw_on_error() && is_contextual_store && !is_function { return v8::Intercepted::No; } if !is_declared && key.is_symbol() { return v8::Intercepted::No; }; if sandbox.set(scope, key.into(), value).is_none() { return v8::Intercepted::No; } if is_declared_on_sandbox && let Some(desc) = sandbox.get_own_property_descriptor(scope, key) && !desc.is_undefined() { let desc_obj: v8::Local<v8::Object> = desc.try_into().unwrap(); // We have to specify the return value for any contextual or get/set // property let get_key = v8::String::new_external_onebyte_static(scope, b"get").unwrap(); let set_key = v8::String::new_external_onebyte_static(scope, b"set").unwrap(); if desc_obj .has_own_property(scope, get_key.into()) .unwrap_or(false) || desc_obj .has_own_property(scope, set_key.into()) .unwrap_or(false) { return v8::Intercepted::Yes; } } v8::Intercepted::No } fn property_descriptor<'s>( scope: &mut v8::PinScope<'s, '_>, key: v8::Local<'s, v8::Name>, args: v8::PropertyCallbackArguments<'s>, mut rv: v8::ReturnValue, ) -> v8::Intercepted { let Some(ctx) = ContextifyContext::get(scope, args.this()) else { return v8::Intercepted::No; }; let context = ctx.context(scope); let Some(sandbox) = ctx.sandbox(scope) else { return v8::Intercepted::No; }; let scope = &mut v8::ContextScope::new(scope, context); if sandbox.has_own_property(scope, key).unwrap_or(false) && let Some(desc) = sandbox.get_own_property_descriptor(scope, key) { rv.set(desc); return v8::Intercepted::Yes; } v8::Intercepted::No } fn property_definer<'s>( scope: &mut v8::PinScope<'s, '_>, key: v8::Local<'s, v8::Name>, desc: &v8::PropertyDescriptor, args: v8::PropertyCallbackArguments<'s>, _: v8::ReturnValue<()>, ) -> v8::Intercepted { let Some(ctx) = ContextifyContext::get(scope, args.this()) else { return v8::Intercepted::No; }; let context = ctx.context(scope); let scope = &mut v8::ContextScope::new(scope, context); let (attributes, is_declared) = match ctx .global_proxy(scope) .get_real_named_property_attributes(scope, key) { Some(attr) => (attr, true), None => (v8::PropertyAttribute::NONE, false), }; let read_only = attributes.is_read_only(); let dont_delete = attributes.is_dont_delete(); // If the property is set on the global as read_only, don't change it on // the global or sandbox. if is_declared && read_only && dont_delete { return v8::Intercepted::No; } let Some(sandbox) = ctx.sandbox(scope) else { return v8::Intercepted::No; }; let define_prop_on_sandbox = |scope: &mut v8::PinScope<'_, '_>, desc_for_sandbox: &mut v8::PropertyDescriptor| { if desc.has_enumerable() { desc_for_sandbox.set_enumerable(desc.enumerable()); } if desc.has_configurable() { desc_for_sandbox.set_configurable(desc.configurable()); } sandbox.define_property(scope, key, desc_for_sandbox); }; if desc.has_get() || desc.has_set() { let mut desc_for_sandbox = v8::PropertyDescriptor::new_from_get_set( if desc.has_get() { desc.get() } else { v8::undefined(scope).into() }, if desc.has_set() { desc.set() } else { v8::undefined(scope).into() }, ); define_prop_on_sandbox(scope, &mut desc_for_sandbox); } else { let value = if desc.has_value() { desc.value() } else { v8::undefined(scope).into() }; if desc.has_writable() { let mut desc_for_sandbox = v8::PropertyDescriptor::new_from_value_writable(value, desc.writable()); define_prop_on_sandbox(scope, &mut desc_for_sandbox); } else { let mut desc_for_sandbox = v8::PropertyDescriptor::new_from_value(value); define_prop_on_sandbox(scope, &mut desc_for_sandbox); } } v8::Intercepted::Yes } fn property_deleter<'s>( scope: &mut v8::PinScope<'s, '_>, key: v8::Local<'s, v8::Name>, args: v8::PropertyCallbackArguments<'s>, mut rv: v8::ReturnValue<v8::Boolean>, ) -> v8::Intercepted { let Some(ctx) = ContextifyContext::get(scope, args.this()) else { return v8::Intercepted::No; }; let context = ctx.context(scope); let Some(sandbox) = ctx.sandbox(scope) else { return v8::Intercepted::No; }; let context_scope = &mut v8::ContextScope::new(scope, context); if sandbox.delete(context_scope, key.into()).unwrap_or(false) { return v8::Intercepted::No; } rv.set_bool(false); v8::Intercepted::Yes } fn property_enumerator<'s>( scope: &mut v8::PinScope<'s, '_>, args: v8::PropertyCallbackArguments<'s>, mut rv: v8::ReturnValue<v8::Array>, ) { let Some(ctx) = ContextifyContext::get(scope, args.this()) else { return; }; let context = ctx.context(scope); let Some(sandbox) = ctx.sandbox(scope) else { return; }; let context_scope = &mut v8::ContextScope::new(scope, context); let Some(properties) = sandbox .get_property_names(context_scope, v8::GetPropertyNamesArgs::default()) else { return; }; rv.set(properties); } fn indexed_property_enumerator<'s>( scope: &mut v8::PinScope<'s, '_>, args: v8::PropertyCallbackArguments<'s>, mut rv: v8::ReturnValue<v8::Array>, ) { let Some(ctx) = ContextifyContext::get(scope, args.this()) else { return; }; let context = ctx.context(scope); let scope = &mut v8::ContextScope::new(scope, context); let Some(sandbox) = ctx.sandbox(scope) else { return; }; // By default, GetPropertyNames returns string and number property names, and // doesn't convert the numbers to strings. let Some(properties) = sandbox.get_property_names(scope, v8::GetPropertyNamesArgs::default()) else { return; }; let Ok(properties_vec) = serde_v8::from_v8::<Vec<serde_v8::Value>>(scope, properties.into()) else { return; }; let mut indices = vec![]; for prop in properties_vec { if prop.v8_value.is_number() { indices.push(prop.v8_value); } } rv.set(v8::Array::new_with_elements(scope, &indices)); } fn uint32_to_name<'s>( scope: &mut v8::PinScope<'s, '_>, index: u32, ) -> v8::Local<'s, v8::Name> { let int = v8::Integer::new_from_unsigned(scope, index); let u32 = v8::Local::<v8::Uint32>::try_from(int).unwrap(); u32.to_string(scope).unwrap().into() } fn indexed_property_query<'s>( scope: &mut v8::PinScope<'s, '_>, index: u32, args: v8::PropertyCallbackArguments<'s>, rv: v8::ReturnValue<v8::Integer>, ) -> v8::Intercepted { let name = uint32_to_name(scope, index); property_query(scope, name, args, rv) } fn indexed_property_getter<'s>( scope: &mut v8::PinScope<'s, '_>, index: u32, args: v8::PropertyCallbackArguments<'s>, rv: v8::ReturnValue, ) -> v8::Intercepted { let key = uint32_to_name(scope, index); property_getter(scope, key, args, rv) } fn indexed_property_setter<'s>( scope: &mut v8::PinScope<'s, '_>, index: u32, value: v8::Local<'s, v8::Value>, args: v8::PropertyCallbackArguments<'s>, rv: v8::ReturnValue<()>, ) -> v8::Intercepted { let key = uint32_to_name(scope, index); property_setter(scope, key, value, args, rv) } fn indexed_property_descriptor<'s>( scope: &mut v8::PinScope<'s, '_>, index: u32, args: v8::PropertyCallbackArguments<'s>, rv: v8::ReturnValue, ) -> v8::Intercepted { let key = uint32_to_name(scope, index); property_descriptor(scope, key, args, rv) } fn indexed_property_definer<'s>( scope: &mut v8::PinScope<'s, '_>, index: u32, descriptor: &v8::PropertyDescriptor, args: v8::PropertyCallbackArguments<'s>, rv: v8::ReturnValue<()>, ) -> v8::Intercepted { let key = uint32_to_name(scope, index); property_definer(scope, key, descriptor, args, rv) } fn indexed_property_deleter<'s>( scope: &mut v8::PinScope<'s, '_>, index: u32, args: v8::PropertyCallbackArguments<'s>, mut rv: v8::ReturnValue<v8::Boolean>, ) -> v8::Intercepted { let Some(ctx) = ContextifyContext::get(scope, args.this()) else { return v8::Intercepted::No; }; let context = ctx.context(scope); let Some(sandbox) = ctx.sandbox(scope) else { return v8::Intercepted::No; }; let context_scope = &mut v8::ContextScope::new(scope, context); if !sandbox.delete_index(context_scope, index).unwrap_or(false) { return v8::Intercepted::No; } // Delete failed on the sandbox, intercept and do not delete on // the global object. rv.set_bool(false); v8::Intercepted::No } #[allow(clippy::too_many_arguments)] #[op2] #[serde] pub fn op_vm_create_script<'a>( scope: &mut v8::PinScope<'a, '_>, source: v8::Local<'a, v8::String>, filename: v8::Local<'a, v8::Value>, line_offset: i32, column_offset: i32, #[buffer] cached_data: Option<JsBuffer>, produce_cached_data: bool, parsing_context: Option<v8::Local<'a, v8::Object>>, ) -> Option<CompileResult<'a>> { ContextifyScript::create( scope, source, filename, line_offset, column_offset, cached_data, produce_cached_data, parsing_context, ) } #[op2(reentrant)] pub fn op_vm_script_run_in_context<'a>( scope: &mut v8::PinScope<'a, '_>, #[cppgc] script: &ContextifyScript, sandbox: Option<v8::Local<'a, v8::Object>>, #[serde] timeout: i64, display_errors: bool, break_on_sigint: bool, ) -> Option<v8::Local<'a, v8::Value>> { script.run_in_context( scope, sandbox, timeout, display_errors, break_on_sigint, ) } #[op2(fast)] pub fn op_vm_create_context( scope: &mut v8::PinScope<'_, '_>, sandbox_obj: v8::Local<v8::Object>, #[string] name: String, #[string] origin: String, allow_code_gen_strings: bool, allow_code_gen_wasm: bool, own_microtask_queue: bool, ) { // Don't allow contextifying a sandbox multiple times. assert!(!ContextifyContext::is_contextify_context( scope,
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
true
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/blocklist.rs
ext/node/ops/blocklist.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::RefCell; use std::collections::HashSet; use std::net::IpAddr; use std::net::Ipv4Addr; use std::net::Ipv6Addr; use std::net::SocketAddr; use deno_core::OpState; use deno_core::op2; use ipnetwork::IpNetwork; use ipnetwork::Ipv4Network; use ipnetwork::Ipv6Network; use serde::Serialize; pub struct BlockListResource { blocklist: RefCell<BlockList>, } // SAFETY: we're sure this can be GCed unsafe impl deno_core::GarbageCollected for BlockListResource { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"BlockListResource" } } #[derive(Serialize)] struct SocketAddressSerialization(String, String); #[derive(Debug, thiserror::Error, deno_error::JsError)] #[class(generic)] pub enum BlocklistError { #[error("{0}")] AddrParse(#[from] std::net::AddrParseError), #[error("{0}")] IpNetwork(#[from] ipnetwork::IpNetworkError), #[error("Invalid address")] InvalidAddress, #[error("IP version mismatch between start and end addresses")] IpVersionMismatch, } #[op2(fast)] pub fn op_socket_address_parse( state: &mut OpState, #[string] addr: &str, #[smi] port: u16, #[string] family: &str, ) -> Result<bool, BlocklistError> { let ip = addr.parse::<IpAddr>()?; let parsed: SocketAddr = SocketAddr::new(ip, port); let parsed_ip_str = parsed.ip().to_string(); let family_correct = family.eq_ignore_ascii_case("ipv4") && parsed.is_ipv4() || family.eq_ignore_ascii_case("ipv6") && parsed.is_ipv6(); if family_correct { let family_is_lowercase = family[..3].chars().all(char::is_lowercase); if family_is_lowercase && parsed_ip_str == addr { Ok(true) } else { state.put::<SocketAddressSerialization>(SocketAddressSerialization( parsed_ip_str, family.to_lowercase(), )); Ok(false) } } else { Err(BlocklistError::InvalidAddress) } } #[op2] #[serde] pub fn op_socket_address_get_serialization( state: &mut OpState, ) -> SocketAddressSerialization { state.take::<SocketAddressSerialization>() } #[op2] #[cppgc] pub fn op_blocklist_new() -> BlockListResource { let blocklist = BlockList::new(); BlockListResource { blocklist: RefCell::new(blocklist), } } #[op2(fast)] pub fn op_blocklist_add_address( #[cppgc] wrap: &BlockListResource, #[string] addr: &str, ) -> Result<(), BlocklistError> { wrap.blocklist.borrow_mut().add_address(addr) } #[op2(fast)] pub fn op_blocklist_add_range( #[cppgc] wrap: &BlockListResource, #[string] start: &str, #[string] end: &str, ) -> Result<bool, BlocklistError> { wrap.blocklist.borrow_mut().add_range(start, end) } #[op2(fast)] pub fn op_blocklist_add_subnet( #[cppgc] wrap: &BlockListResource, #[string] addr: &str, #[smi] prefix: u8, ) -> Result<(), BlocklistError> { wrap.blocklist.borrow_mut().add_subnet(addr, prefix) } #[op2(fast)] pub fn op_blocklist_check( #[cppgc] wrap: &BlockListResource, #[string] addr: &str, #[string] r#type: &str, ) -> Result<bool, BlocklistError> { wrap.blocklist.borrow().check(addr, r#type) } struct BlockList { rules: HashSet<IpNetwork>, } impl BlockList { pub fn new() -> Self { BlockList { rules: HashSet::new(), } } fn map_addr_add_network( &mut self, addr: IpAddr, prefix: Option<u8>, ) -> Result<(), BlocklistError> { match addr { IpAddr::V4(addr) => { let ipv4_prefix = prefix.unwrap_or(32); self .rules .insert(IpNetwork::V4(Ipv4Network::new(addr, ipv4_prefix)?)); let ipv6_mapped = addr.to_ipv6_mapped(); let ipv6_prefix = 96 + ipv4_prefix; // IPv4-mapped IPv6 address prefix starts at 96 self .rules .insert(IpNetwork::V6(Ipv6Network::new(ipv6_mapped, ipv6_prefix)?)); } IpAddr::V6(addr) => { if let Some(ipv4_mapped) = addr.to_ipv4_mapped() { let ipv4_prefix = prefix.map(|v| v.clamp(96, 128) - 96).unwrap_or(32); self .rules .insert(IpNetwork::V4(Ipv4Network::new(ipv4_mapped, ipv4_prefix)?)); } let ipv6_prefix = prefix.unwrap_or(128); self .rules .insert(IpNetwork::V6(Ipv6Network::new(addr, ipv6_prefix)?)); } }; Ok(()) } pub fn add_address(&mut self, address: &str) -> Result<(), BlocklistError> { let ip: IpAddr = address.parse()?; self.map_addr_add_network(ip, None)?; Ok(()) } pub fn add_range( &mut self, start: &str, end: &str, ) -> Result<bool, BlocklistError> { let start_ip: IpAddr = start.parse()?; let end_ip: IpAddr = end.parse()?; match (start_ip, end_ip) { (IpAddr::V4(start), IpAddr::V4(end)) => { let start_u32: u32 = start.into(); let end_u32: u32 = end.into(); if end_u32 < start_u32 { // Indicates invalid range. return Ok(false); } for ip in start_u32..=end_u32 { let addr: Ipv4Addr = ip.into(); self.map_addr_add_network(IpAddr::V4(addr), None)?; } } (IpAddr::V6(start), IpAddr::V6(end)) => { let start_u128: u128 = start.into(); let end_u128: u128 = end.into(); if end_u128 < start_u128 { // Indicates invalid range. return Ok(false); } for ip in start_u128..=end_u128 { let addr: Ipv6Addr = ip.into(); self.map_addr_add_network(IpAddr::V6(addr), None)?; } } _ => return Err(BlocklistError::IpVersionMismatch), } Ok(true) } pub fn add_subnet( &mut self, addr: &str, prefix: u8, ) -> Result<(), BlocklistError> { let ip: IpAddr = addr.parse()?; self.map_addr_add_network(ip, Some(prefix))?; Ok(()) } pub fn check( &self, addr: &str, r#type: &str, ) -> Result<bool, BlocklistError> { let addr: IpAddr = addr.parse()?; let family = r#type.to_lowercase(); if family == "ipv4" && addr.is_ipv4() || family == "ipv6" && addr.is_ipv6() { Ok(self.rules.iter().any(|net| net.contains(addr))) } else { Err(BlocklistError::InvalidAddress) } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_add_address() { // Single IPv4 address let mut block_list = BlockList::new(); block_list.add_address("192.168.0.1").unwrap(); assert!(block_list.check("192.168.0.1", "ipv4").unwrap()); assert!(block_list.check("::ffff:c0a8:1", "ipv6").unwrap()); // Single IPv6 address let mut block_list = BlockList::new(); block_list.add_address("2001:db8::1").unwrap(); assert!(block_list.check("2001:db8::1", "ipv6").unwrap()); assert!(!block_list.check("192.168.0.1", "ipv4").unwrap()); } #[test] fn test_add_range() { // IPv4 range let mut block_list = BlockList::new(); block_list.add_range("192.168.0.1", "192.168.0.3").unwrap(); assert!(block_list.check("192.168.0.1", "ipv4").unwrap()); assert!(block_list.check("192.168.0.2", "ipv4").unwrap()); assert!(block_list.check("192.168.0.3", "ipv4").unwrap()); assert!(block_list.check("::ffff:c0a8:1", "ipv6").unwrap()); // IPv6 range let mut block_list = BlockList::new(); block_list.add_range("2001:db8::1", "2001:db8::3").unwrap(); assert!(block_list.check("2001:db8::1", "ipv6").unwrap()); assert!(block_list.check("2001:db8::2", "ipv6").unwrap()); assert!(block_list.check("2001:db8::3", "ipv6").unwrap()); assert!(!block_list.check("192.168.0.1", "ipv4").unwrap()); } #[test] fn test_add_subnet() { // IPv4 subnet let mut block_list = BlockList::new(); block_list.add_subnet("192.168.0.0", 24).unwrap(); assert!(block_list.check("192.168.0.1", "ipv4").unwrap()); assert!(block_list.check("192.168.0.255", "ipv4").unwrap()); assert!(block_list.check("::ffff:c0a8:0", "ipv6").unwrap()); // IPv6 subnet let mut block_list = BlockList::new(); block_list.add_subnet("2001:db8::", 64).unwrap(); block_list.add_subnet("::ffff:127.0.0.1", 128).unwrap(); assert!(block_list.check("2001:db8::1", "ipv6").unwrap()); assert!(block_list.check("2001:db8::ffff", "ipv6").unwrap()); assert!(!block_list.check("192.168.0.1", "ipv4").unwrap()); // Check host addresses of IPv4 mapped IPv6 address let mut block_list = BlockList::new(); block_list.add_subnet("1.1.1.0", 30).unwrap(); assert!(block_list.check("::ffff:1.1.1.1", "ipv6").unwrap()); assert!(!block_list.check("::ffff:1.1.1.4", "ipv6").unwrap()); } #[test] fn test_check() { // Check IPv4 presence let mut block_list = BlockList::new(); block_list.add_address("192.168.0.1").unwrap(); assert!(block_list.check("192.168.0.1", "ipv4").unwrap()); // Check IPv6 presence let mut block_list = BlockList::new(); block_list.add_address("2001:db8::1").unwrap(); assert!(block_list.check("2001:db8::1", "ipv6").unwrap()); // Check IPv4 not present let block_list = BlockList::new(); assert!(!block_list.check("192.168.0.1", "ipv4").unwrap()); // Check IPv6 not present let block_list = BlockList::new(); assert!(!block_list.check("2001:db8::1", "ipv6").unwrap()); // Check invalid IP version let block_list = BlockList::new(); assert!(block_list.check("192.168.0.1", "ipv6").is_err()); // Check invalid type let mut block_list = BlockList::new(); block_list.add_address("192.168.0.1").unwrap(); assert!(block_list.check("192.168.0.1", "invalid_type").is_err()); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/tls.rs
ext/node/ops/tls.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::collections::VecDeque; use std::future::Future; use std::io::Error; use std::io::ErrorKind; use std::num::NonZeroUsize; use std::pin::Pin; use std::rc::Rc; use std::sync::Arc; use std::sync::Mutex; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::task::Context; use std::task::Poll; use base64::Engine; use bytes::Bytes; use deno_core::AsyncRefCell; use deno_core::AsyncResult; use deno_core::OpState; use deno_core::RcRef; use deno_core::Resource; use deno_core::ResourceId; use deno_core::op2; use deno_net::DefaultTlsOptions; use deno_net::UnsafelyIgnoreCertificateErrors; use deno_net::ops::NetError; use deno_net::ops::TlsHandshakeInfo; use deno_net::ops_tls::TlsStreamResource; use deno_tls::SocketUse; use deno_tls::TlsClientConfigOptions; use deno_tls::TlsKeys; use deno_tls::TlsKeysHolder; use deno_tls::create_client_config; use deno_tls::rustls::ClientConnection; use deno_tls::rustls::pki_types::ServerName; use rustls_tokio_stream::TlsStream; use rustls_tokio_stream::TlsStreamRead; use rustls_tokio_stream::TlsStreamWrite; use rustls_tokio_stream::UnderlyingStream; use serde::Deserialize; use webpki_root_certs; use super::crypto::x509::Certificate; use super::crypto::x509::CertificateObject; #[op2] #[serde] pub fn op_get_root_certificates() -> Vec<String> { webpki_root_certs::TLS_SERVER_ROOT_CERTS .iter() .map(|cert| { let b64 = base64::engine::general_purpose::STANDARD.encode(cert); let pem_lines = b64 .chars() .collect::<Vec<char>>() // Node uses 72 characters per line, so we need to follow node even though // it's not spec compliant https://datatracker.ietf.org/doc/html/rfc7468#section-2 .chunks(72) .map(|c| c.iter().collect::<String>()) .collect::<Vec<String>>() .join("\n"); let pem = format!( "-----BEGIN CERTIFICATE-----\n{pem_lines}\n-----END CERTIFICATE-----\n", ); pem }) .collect::<Vec<String>>() } #[op2] #[serde] pub fn op_tls_peer_certificate( state: &mut OpState, #[smi] rid: ResourceId, detailed: bool, ) -> Option<CertificateObject> { let resource = state.resource_table.get::<TlsStreamResource>(rid).ok()?; let certs = resource.peer_certificates()?; if certs.is_empty() { return None; } // For Node.js compatibility, return the peer certificate (first in chain) let cert_der = &certs[0]; let cert = Certificate::from_der(cert_der.as_ref()).ok()?; cert.to_object(detailed).ok() } #[op2] #[string] pub fn op_tls_canonicalize_ipv4_address( #[string] hostname: String, ) -> Option<String> { let ip = hostname.parse::<std::net::IpAddr>().ok()?; let canonical_ip = match ip { std::net::IpAddr::V4(ipv4) => ipv4.to_string(), std::net::IpAddr::V6(ipv6) => ipv6.to_string(), }; Some(canonical_ip) } struct ReadableFuture<'a> { socket: &'a JSStreamSocket, } impl<'a> Future for ReadableFuture<'a> { type Output = std::io::Result<()>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { self.socket.poll_read_ready(cx) } } struct WritableFuture<'a> { socket: &'a JSStreamSocket, } impl<'a> Future for WritableFuture<'a> { type Output = std::io::Result<()>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { self.socket.poll_write_ready(cx) } } #[derive(Debug)] pub struct JSStreamSocket { readable: Arc<Mutex<tokio::sync::mpsc::Receiver<Bytes>>>, writable: tokio::sync::mpsc::Sender<Bytes>, read_buffer: Arc<Mutex<VecDeque<Bytes>>>, closed: AtomicBool, } impl JSStreamSocket { pub fn new( readable: tokio::sync::mpsc::Receiver<Bytes>, writable: tokio::sync::mpsc::Sender<Bytes>, ) -> Self { Self { readable: Arc::new(Mutex::new(readable)), writable, read_buffer: Arc::new(Mutex::new(VecDeque::new())), closed: AtomicBool::new(false), } } } impl UnderlyingStream for JSStreamSocket { type StdType = (); fn poll_read_ready( &self, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<std::io::Result<()>> { // Check if we have buffered data if let Ok(buffer) = self.read_buffer.lock() && !buffer.is_empty() { return Poll::Ready(Ok(())); } if self.closed.load(Ordering::Relaxed) { return Poll::Ready(Err(Error::new( ErrorKind::UnexpectedEof, "Stream closed", ))); } // Try to poll for data without consuming it if let Ok(mut receiver) = self.readable.lock() { match receiver.poll_recv(cx) { Poll::Ready(Some(data)) => { // Store the data in buffer for try_read if let Ok(mut buffer) = self.read_buffer.lock() { buffer.push_back(data); } Poll::Ready(Ok(())) } Poll::Ready(None) => { // Channel closed self.closed.store(true, Ordering::Relaxed); Poll::Ready(Err(Error::new( ErrorKind::UnexpectedEof, "Channel closed", ))) } Poll::Pending => Poll::Pending, } } else { panic!("Failed to acquire lock") } } fn poll_write_ready( &self, _cx: &mut std::task::Context<'_>, ) -> std::task::Poll<std::io::Result<()>> { if self.closed.load(Ordering::Relaxed) { return Poll::Ready(Err(Error::new( ErrorKind::BrokenPipe, "Stream closed", ))); } // For bounded sender, check if channel is ready if self.writable.is_closed() { self.closed.store(true, Ordering::Relaxed); Poll::Ready(Err(Error::new(ErrorKind::BrokenPipe, "Channel closed"))) } else { Poll::Ready(Ok(())) } } fn try_read(&self, buf: &mut [u8]) -> std::io::Result<usize> { if self.closed.load(Ordering::Relaxed) { return Err(Error::new(ErrorKind::UnexpectedEof, "Stream closed")); } // Check if we have buffered data first if let Ok(mut buffer) = self.read_buffer.lock() && let Some(data) = buffer.pop_front() { let len = std::cmp::min(buf.len(), data.len()); buf[..len].copy_from_slice(&data[..len]); // If there's leftover data, put it back in the buffer if data.len() > len { buffer.push_front(data.slice(len..)); } return Ok(len); } // Try to read from channel non-blocking if let Ok(mut receiver) = self.readable.lock() { match receiver.try_recv() { Ok(data) => { let len = std::cmp::min(buf.len(), data.len()); buf[..len].copy_from_slice(&data[..len]); // If there's leftover data, store it in buffer if data.len() > len && let Ok(mut buffer) = self.read_buffer.lock() { buffer.push_front(data.slice(len..)); } Ok(len) } Err(tokio::sync::mpsc::error::TryRecvError::Empty) => { Err(Error::new(ErrorKind::WouldBlock, "No data available")) } Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => { self.closed.store(true, Ordering::Relaxed); Err(Error::new(ErrorKind::UnexpectedEof, "Channel closed")) } } } else { Err(Error::other("Failed to acquire lock")) } } fn try_write(&self, buf: &[u8]) -> std::io::Result<usize> { if self.closed.load(Ordering::Relaxed) { return Err(Error::new(ErrorKind::BrokenPipe, "Stream closed")); } if self.writable.is_closed() { self.closed.store(true, Ordering::Relaxed); return Err(Error::new(ErrorKind::BrokenPipe, "Channel closed")); } let data = Bytes::copy_from_slice(buf); match self.writable.try_send(data) { Ok(()) => Ok(buf.len()), Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => { Err(Error::new(ErrorKind::WouldBlock, "Channel full")) } Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => { self.closed.store(true, Ordering::Relaxed); Err(Error::new(ErrorKind::BrokenPipe, "Channel closed")) } } } fn readable(&self) -> impl Future<Output = std::io::Result<()>> + Send { ReadableFuture { socket: self } } fn writable(&self) -> impl Future<Output = std::io::Result<()>> + Send { WritableFuture { socket: self } } fn shutdown(&self, _: std::net::Shutdown) -> std::io::Result<()> { self.closed.store(true, Ordering::Relaxed); Ok(()) } fn into_std(self) -> Option<std::io::Result<Self::StdType>> { None } } struct JSDuplexResource { readable: Arc<Mutex<tokio::sync::mpsc::Receiver<Bytes>>>, writable: tokio::sync::mpsc::Sender<Bytes>, read_buffer: Arc<Mutex<VecDeque<Bytes>>>, } impl JSDuplexResource { pub fn new( readable: tokio::sync::mpsc::Receiver<Bytes>, writable: tokio::sync::mpsc::Sender<Bytes>, ) -> Self { Self { readable: Arc::new(Mutex::new(readable)), writable, read_buffer: Arc::new(Mutex::new(VecDeque::new())), } } #[allow(clippy::await_holding_lock)] pub async fn read( self: Rc<Self>, data: &mut [u8], ) -> Result<usize, std::io::Error> { // First check if we have buffered data from previous partial read if let Ok(mut buffer) = self.read_buffer.lock() && let Some(buffered_data) = buffer.pop_front() { let len = std::cmp::min(data.len(), buffered_data.len()); data[..len].copy_from_slice(&buffered_data[..len]); // If there's remaining data, put it back in buffer if buffered_data.len() > len { buffer.push_front(buffered_data.slice(len..)); } return Ok(len); } // No buffered data, receive new data from channel let bytes = { let mut receiver = self .readable .lock() .map_err(|_| Error::other("Failed to acquire lock"))?; receiver.recv().await }; match bytes { Some(bytes) => { let len = std::cmp::min(data.len(), bytes.len()); data[..len].copy_from_slice(&bytes[..len]); // If there's remaining data, buffer it for next read if bytes.len() > len && let Ok(mut buffer) = self.read_buffer.lock() { buffer.push_back(bytes.slice(len..)); } Ok(len) } None => { // Channel closed Ok(0) } } } pub async fn write( self: Rc<Self>, data: &[u8], ) -> Result<usize, std::io::Error> { let bytes = Bytes::copy_from_slice(data); self .writable .send(bytes) .await .map_err(|_| Error::new(ErrorKind::BrokenPipe, "Channel closed"))?; Ok(data.len()) } } impl Resource for JSDuplexResource { deno_core::impl_readable_byob!(); deno_core::impl_writable!(); fn name(&self) -> Cow<'_, str> { "JSDuplexResource".into() } } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct StartJSTlsArgs { ca_certs: Vec<String>, hostname: String, alpn_protocols: Option<Vec<String>>, reject_unauthorized: Option<bool>, } #[derive(Debug)] pub struct JSStreamTlsResource { rd: AsyncRefCell<TlsStreamRead<JSStreamSocket>>, wr: AsyncRefCell<TlsStreamWrite<JSStreamSocket>>, } impl JSStreamTlsResource { pub fn new( (rd, wr): ( TlsStreamRead<JSStreamSocket>, TlsStreamWrite<JSStreamSocket>, ), ) -> Self { Self { rd: AsyncRefCell::new(rd), wr: AsyncRefCell::new(wr), } } pub async fn handshake( self: &Rc<Self>, ) -> Result<TlsHandshakeInfo, std::io::Error> { let mut wr = RcRef::map(self, |r| &r.wr).borrow_mut().await; let handshake = wr.handshake().await?; let alpn_protocol = handshake.alpn.map(|alpn| alpn.into()); let peer_certificates = handshake.peer_certificates.clone(); let tls_info = TlsHandshakeInfo { alpn_protocol, peer_certificates, }; Ok(tls_info) } pub async fn read( self: Rc<Self>, data: &mut [u8], ) -> Result<usize, std::io::Error> { use tokio::io::AsyncReadExt; let mut rd = RcRef::map(&self, |r| &r.rd).borrow_mut().await; rd.read(data).await } pub async fn write( self: Rc<Self>, data: &[u8], ) -> Result<usize, std::io::Error> { use tokio::io::AsyncWriteExt; let mut wr = RcRef::map(&self, |r| &r.wr).borrow_mut().await; let nwritten = wr.write(data).await?; wr.flush().await?; Ok(nwritten) } } impl Resource for JSStreamTlsResource { deno_core::impl_readable_byob!(); deno_core::impl_writable!(); fn name(&self) -> Cow<'_, str> { "JSStreamTlsResource".into() } } #[op2] pub fn op_node_tls_start( state: Rc<RefCell<OpState>>, #[serde] args: StartJSTlsArgs, #[buffer] output: &mut [u32], ) -> Result<(), NetError> { let reject_unauthorized = args.reject_unauthorized.unwrap_or(true); let hostname = match &*args.hostname { "" => "localhost".to_string(), n => n.to_string(), }; assert_eq!(output.len(), 2); let ca_certs = args .ca_certs .into_iter() .map(|s| s.into_bytes()) .collect::<Vec<_>>(); let hostname_dns = ServerName::try_from(hostname.to_string()) .map_err(|_| NetError::InvalidHostname(hostname))?; // --unsafely-ignore-certificate-errors overrides the `rejectUnauthorized` option. let unsafely_ignore_certificate_errors = if reject_unauthorized { state .borrow() .try_borrow::<UnsafelyIgnoreCertificateErrors>() .and_then(|it| it.0.clone()) } else { Some(Vec::new()) }; let root_cert_store = state .borrow() .borrow::<DefaultTlsOptions>() .root_cert_store() .map_err(NetError::RootCertStore)?; let (network_to_tls_tx, network_to_tls_rx) = tokio::sync::mpsc::channel::<Bytes>(10); let (tls_to_network_tx, tls_to_network_rx) = tokio::sync::mpsc::channel::<Bytes>(10); let js_stream = JSStreamSocket::new(network_to_tls_rx, tls_to_network_tx); let tls_null = TlsKeysHolder::from(TlsKeys::Null); let mut tls_config = create_client_config(TlsClientConfigOptions { root_cert_store, ca_certs, unsafely_ignore_certificate_errors, unsafely_disable_hostname_verification: false, cert_chain_and_key: tls_null.take(), socket_use: SocketUse::GeneralSsl, })?; if let Some(alpn_protocols) = args.alpn_protocols { tls_config.alpn_protocols = alpn_protocols.into_iter().map(|s| s.into_bytes()).collect(); } let tls_config = Arc::new(tls_config); let tls_stream = TlsStream::new_client_side( js_stream, ClientConnection::new(tls_config, hostname_dns)?, NonZeroUsize::new(65536), ); let tls_resource = JSStreamTlsResource::new(tls_stream.into_split()); let user_duplex = JSDuplexResource::new(tls_to_network_rx, network_to_tls_tx); let (tls_rid, duplex_rid) = { let mut state = state.borrow_mut(); let tls_rid = state.resource_table.add(tls_resource); let duplex_rid = state.resource_table.add(user_duplex); (tls_rid, duplex_rid) }; output[0] = tls_rid; output[1] = duplex_rid; Ok(()) } #[op2(async)] #[serde] pub async fn op_node_tls_handshake( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<TlsHandshakeInfo, NetError> { let resource = state .borrow() .resource_table .get::<JSStreamTlsResource>(rid) .map_err(|_| NetError::ListenerClosed)?; resource.handshake().await.map_err(Into::into) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/handle_wrap.rs
ext/node/ops/handle_wrap.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::Cell; use std::cell::RefCell; use std::rc::Rc; use deno_core::GarbageCollected; use deno_core::OpState; use deno_core::ResourceId; use deno_core::error::ResourceError; use deno_core::op2; use deno_core::v8; pub struct AsyncId(i64); impl Default for AsyncId { // `kAsyncIdCounter` should start at `1` because that'll be the id the execution // context during bootstrap. fn default() -> Self { Self(1) } } impl AsyncId { // Increment the internal id counter and return the value. fn next(&mut self) -> i64 { self.0 += 1; self.0 } } fn next_async_id(state: &mut OpState) -> i64 { state.borrow_mut::<AsyncId>().next() } #[op2(fast)] pub fn op_node_new_async_id(state: &mut OpState) -> f64 { next_async_id(state) as f64 } pub struct AsyncWrap { provider: i32, async_id: i64, } // SAFETY: we're sure this can be GCed unsafe impl GarbageCollected for AsyncWrap { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"AsyncWrap" } } impl AsyncWrap { pub(crate) fn create(state: &mut OpState, provider: i32) -> Self { let async_id = next_async_id(state); Self { provider, async_id } } } #[op2(base)] impl AsyncWrap { #[getter] fn provider(&self) -> i32 { self.provider } #[fast] fn get_async_id(&self) -> f64 { self.async_id as f64 } #[fast] fn get_provider_type(&self) -> i32 { self.provider } } #[derive(Copy, Clone, PartialEq, Eq, Default)] enum State { #[default] Initialized, Closing, Closed, } pub struct HandleWrap { handle: Option<ResourceId>, state: Rc<Cell<State>>, } // SAFETY: we're sure this can be GCed unsafe impl GarbageCollected for HandleWrap { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"HandleWrap" } } impl HandleWrap { pub(crate) fn create(handle: Option<ResourceId>) -> Self { Self { handle, state: Rc::new(Cell::new(State::Initialized)), } } fn is_alive(&self) -> bool { self.state.get() != State::Closed } } static ON_CLOSE_STR: deno_core::FastStaticString = deno_core::ascii_str!("_onClose"); #[op2(inherit = AsyncWrap)] impl HandleWrap { #[constructor] #[cppgc] fn new( state: &mut OpState, #[smi] provider: i32, #[smi] handle: Option<ResourceId>, ) -> (AsyncWrap, HandleWrap) { ( AsyncWrap::create(state, provider), HandleWrap::create(handle), ) } // Ported from Node.js // // https://github.com/nodejs/node/blob/038d82980ab26cd79abe4409adc2fecad94d7c93/src/handle_wrap.cc#L65-L85 #[reentrant] fn close( &self, op_state: Rc<RefCell<OpState>>, #[this] this: v8::Global<v8::Object>, scope: &mut v8::PinScope<'_, '_>, #[global] cb: Option<v8::Global<v8::Function>>, ) -> Result<(), ResourceError> { if self.state.get() != State::Initialized { return Ok(()); } let state = self.state.clone(); // This effectively mimicks Node's OnClose callback. // // https://github.com/nodejs/node/blob/038d82980ab26cd79abe4409adc2fecad94d7c93/src/handle_wrap.cc#L135-L157 let on_close = move |scope: &mut v8::PinScope<'_, '_>| { assert!(state.get() == State::Closing); state.set(State::Closed); // Workaround for https://github.com/denoland/deno/pull/24656 // // We need to delay 'cb' at least 2 ticks to avoid "close" event happening before "error" // event in net.Socket. // // This is a temporary solution. We should support async close like `uv_close`. if let Some(cb) = cb { let recv = v8::undefined(scope); cb.open(scope).call(scope, recv.into(), &[]); } }; uv_close(scope, op_state, this, on_close); self.state.set(State::Closing); Ok(()) } // Ported from Node.js // // https://github.com/nodejs/node/blob/038d82980ab26cd79abe4409adc2fecad94d7c93/src/handle_wrap.cc#L58-L62 #[fast] fn has_ref(&self, state: &mut OpState) -> bool { if let Some(handle) = self.handle { return state.has_ref(handle); } true } // Ported from Node.js // // https://github.com/nodejs/node/blob/038d82980ab26cd79abe4409adc2fecad94d7c93/src/handle_wrap.cc#L40-L46 #[fast] #[rename("ref")] fn ref_method(&self, state: &mut OpState) { if self.is_alive() && let Some(handle) = self.handle { state.uv_ref(handle); } } // Ported from Node.js // // https://github.com/nodejs/node/blob/038d82980ab26cd79abe4409adc2fecad94d7c93/src/handle_wrap.cc#L49-L55 #[fast] fn unref(&self, state: &mut OpState) { if self.is_alive() && let Some(handle) = self.handle { state.uv_unref(handle); } } } fn uv_close<F>( scope: &mut v8::PinScope<'_, '_>, op_state: Rc<RefCell<OpState>>, this: v8::Global<v8::Object>, on_close: F, ) where F: FnOnce(&mut v8::PinScope<'_, '_>) + 'static, { // Call _onClose() on the JS handles. Not needed for Rust handles. let this = v8::Local::new(scope, this); let on_close_str = ON_CLOSE_STR.v8_string(scope).unwrap(); let onclose = this.get(scope, on_close_str.into()); if let Some(onclose) = onclose { let fn_: v8::Local<v8::Function> = onclose.try_into().unwrap(); fn_.call(scope, this.into(), &[]); } op_state .borrow() .borrow::<deno_core::V8TaskSpawner>() .spawn(on_close); } #[cfg(test)] mod tests { use std::future::poll_fn; use std::task::Poll; use deno_core::JsRuntime; use deno_core::RuntimeOptions; async fn js_test(source_code: &'static str) { deno_core::extension!( test_ext, objects = [super::AsyncWrap, super::HandleWrap,], state = |state| { state.put::<super::AsyncId>(super::AsyncId::default()); } ); let mut runtime = JsRuntime::new(RuntimeOptions { extensions: vec![test_ext::init()], ..Default::default() }); poll_fn(move |cx| { runtime .execute_script("file://handle_wrap_test.js", source_code) .unwrap(); let result = runtime.poll_event_loop(cx, Default::default()); assert!(matches!(result, Poll::Ready(Ok(())))); Poll::Ready(()) }) .await; } #[tokio::test] async fn test_handle_wrap() { js_test( r#" const { HandleWrap } = Deno.core.ops; let called = false; class MyHandleWrap extends HandleWrap { constructor() { super(0, null); } _onClose() { called = true; } } const handleWrap = new MyHandleWrap(); handleWrap.close(); if (!called) { throw new Error("HandleWrap._onClose was not called"); } "#, ) .await; } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/process.rs
ext/node/ops/process.rs
// Copyright 2018-2025 the Deno authors. MIT license. use deno_core::OpState; use deno_core::op2; use deno_core::v8; use deno_permissions::PermissionCheckError; use deno_permissions::PermissionsContainer; #[cfg(unix)] use nix::unistd::Gid; #[cfg(unix)] use nix::unistd::Group; #[cfg(unix)] use nix::unistd::Uid; #[cfg(unix)] use nix::unistd::User; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum ProcessError { #[class(inherit)] #[error(transparent)] Permission( #[from] #[inherit] PermissionCheckError, ), #[class(generic)] #[error("{0} identifier does not exist: {1}")] #[property("code" = "ERR_UNKNOWN_CREDENTIAL")] UnknownCredential(String, String), #[class(inherit)] #[error(transparent)] Io(#[from] std::io::Error), #[class(generic)] #[error("Operation not supported on this platform")] NotSupported, #[class(type)] #[error("Invalid {0} parameter")] InvalidParam(String), } #[cfg(unix)] impl From<nix::Error> for ProcessError { fn from(err: nix::Error) -> Self { ProcessError::Io(std::io::Error::from_raw_os_error(err as i32)) } } #[cfg(unix)] fn kill(pid: i32, sig: i32) -> i32 { // SAFETY: FFI call to libc if unsafe { libc::kill(pid, sig) } < 0 { std::io::Error::last_os_error().raw_os_error().unwrap() } else { 0 } } #[cfg(not(unix))] fn kill(pid: i32, _sig: i32) -> i32 { match deno_subprocess_windows::process_kill(pid, _sig) { Ok(_) => 0, Err(e) => e.as_uv_error(), } } #[op2(fast, stack_trace)] pub fn op_node_process_kill( state: &mut OpState, #[smi] pid: i32, #[smi] sig: i32, ) -> Result<i32, deno_permissions::PermissionCheckError> { state .borrow_mut::<PermissionsContainer>() .check_run_all("process.kill")?; Ok(kill(pid, sig)) } #[op2(fast)] pub fn op_process_abort() { std::process::abort(); } #[cfg(not(any(target_os = "android", target_os = "windows")))] enum Id { Number(u32), Name(String), } #[cfg(not(any(target_os = "android", target_os = "windows")))] fn get_group_id(name: &str) -> Result<Gid, ProcessError> { let group = Group::from_name(name)?; if let Some(group) = group { Ok(group.gid) } else { Err(ProcessError::UnknownCredential( "Group".to_string(), name.to_string(), )) } } #[cfg(not(any(target_os = "android", target_os = "windows")))] fn serialize_id<'a>( scope: &mut v8::PinScope<'a, '_>, value: v8::Local<'a, v8::Value>, ) -> Result<Id, ProcessError> { if value.is_number() { let num = value.uint32_value(scope).unwrap(); return Ok(Id::Number(num)); } if value.is_string() { let name = value.to_string(scope).unwrap(); return Ok(Id::Name(name.to_rust_string_lossy(scope))); } Err(ProcessError::InvalidParam("id".to_string())) } #[cfg(not(any(target_os = "android", target_os = "windows")))] #[op2(fast, stack_trace)] pub fn op_node_process_setegid<'a>( scope: &mut v8::PinScope<'a, '_>, state: &mut OpState, id: v8::Local<'a, v8::Value>, ) -> Result<(), ProcessError> { { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_sys("setegid", "node:process.setegid")?; } let gid = match serialize_id(scope, id)? { Id::Number(number) => Gid::from_raw(number), Id::Name(name) => get_group_id(&name)?, }; nix::unistd::setegid(gid)?; Ok(()) } #[cfg(any(target_os = "android", target_os = "windows"))] #[op2(fast, stack_trace)] pub fn op_node_process_setegid( _scope: &mut v8::PinScope<'_, '_>, _state: &mut OpState, _id: v8::Local<'_, v8::Value>, ) -> Result<(), ProcessError> { Err(ProcessError::NotSupported) } #[cfg(not(any(target_os = "android", target_os = "windows")))] fn get_user_id(name: &str) -> Result<Uid, ProcessError> { let user = User::from_name(name)?; if let Some(user) = user { Ok(user.uid) } else { Err(ProcessError::UnknownCredential( "User".to_string(), name.to_string(), )) } } #[cfg(not(any(target_os = "android", target_os = "windows")))] #[op2(fast, stack_trace)] pub fn op_node_process_seteuid<'a>( scope: &mut v8::PinScope<'a, '_>, state: &mut OpState, id: v8::Local<'a, v8::Value>, ) -> Result<(), ProcessError> { { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_sys("seteuid", "node:process.seteuid")?; } let uid = match serialize_id(scope, id)? { Id::Number(number) => Uid::from_raw(number), Id::Name(name) => get_user_id(&name)?, }; nix::unistd::seteuid(uid)?; Ok(()) } #[cfg(any(target_os = "android", target_os = "windows"))] #[op2(fast, stack_trace)] pub fn op_node_process_seteuid( _scope: &mut v8::PinScope<'_, '_>, _state: &mut OpState, _id: v8::Local<'_, v8::Value>, ) -> Result<(), ProcessError> { Err(ProcessError::NotSupported) } #[cfg(not(any(target_os = "android", target_os = "windows")))] #[op2(fast, stack_trace)] pub fn op_node_process_setgid<'a>( scope: &mut v8::PinScope<'a, '_>, state: &mut OpState, id: v8::Local<'a, v8::Value>, ) -> Result<(), ProcessError> { { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_sys("setgid", "node:process.setgid")?; } let gid = match serialize_id(scope, id)? { Id::Number(number) => Gid::from_raw(number), Id::Name(name) => get_group_id(&name)?, }; nix::unistd::setgid(gid)?; Ok(()) } #[cfg(any(target_os = "android", target_os = "windows"))] #[op2(fast, stack_trace)] pub fn op_node_process_setgid( _scope: &mut v8::PinScope<'_, '_>, _state: &mut OpState, _id: v8::Local<'_, v8::Value>, ) -> Result<(), ProcessError> { Err(ProcessError::NotSupported) } #[cfg(not(any(target_os = "android", target_os = "windows")))] #[op2(fast, stack_trace)] pub fn op_node_process_setuid<'a>( scope: &mut v8::PinScope<'a, '_>, state: &mut OpState, id: v8::Local<'a, v8::Value>, ) -> Result<(), ProcessError> { { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_sys("setuid", "node:process.setuid")?; } let uid = match serialize_id(scope, id)? { Id::Number(number) => Uid::from_raw(number), Id::Name(name) => get_user_id(&name)?, }; nix::unistd::setuid(uid)?; Ok(()) } #[cfg(any(target_os = "android", target_os = "windows"))] #[op2(fast, stack_trace)] pub fn op_node_process_setuid( _scope: &mut v8::PinScope<'_, '_>, _state: &mut OpState, _id: v8::Local<'_, v8::Value>, ) -> Result<(), ProcessError> { Err(ProcessError::NotSupported) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/http.rs
ext/node/ops/http.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::cmp::min; use std::fmt::Debug; use std::future::Future; use std::pin::Pin; use std::rc::Rc; use std::task::Context; use std::task::Poll; use bytes::Bytes; use deno_core::AsyncRefCell; use deno_core::AsyncResult; use deno_core::BufView; use deno_core::ByteString; use deno_core::CancelFuture; use deno_core::CancelHandle; use deno_core::CancelTryFuture; use deno_core::Canceled; use deno_core::OpState; use deno_core::RcRef; use deno_core::Resource; use deno_core::ResourceId; use deno_core::error::ResourceError; use deno_core::futures::FutureExt; use deno_core::futures::Stream; use deno_core::futures::StreamExt; use deno_core::futures::channel::mpsc; use deno_core::futures::channel::oneshot; use deno_core::futures::stream::Peekable; use deno_core::op2; use deno_core::serde::Serialize; use deno_core::url::Url; use deno_error::JsError; use deno_error::JsErrorBox; use deno_fetch::FetchCancelHandle; use deno_fetch::FetchReturn; use deno_fetch::ResBody; use deno_net::io::TcpStreamResource; use deno_net::ops_tls::TlsStreamResource; use deno_net::raw::NetworkStream; use deno_net::raw::NetworkStreamAddress; use deno_net::raw::NetworkStreamReadHalf; use deno_net::raw::NetworkStreamWriteHalf; use deno_net::raw::take_network_stream_resource; use deno_permissions::PermissionCheckError; use deno_permissions::PermissionsContainer; use http::Method; use http::header::AUTHORIZATION; use http::header::CONTENT_LENGTH; use http::header::HeaderMap; use http::header::HeaderName; use http::header::HeaderValue; use http_body_util::BodyExt; use hyper::body::Frame; use hyper::body::Incoming; use hyper_util::rt::TokioIo; use tokio::io::AsyncReadExt; use tokio::io::AsyncWriteExt; #[derive(Default, Serialize)] #[serde(rename_all = "camelCase")] pub struct NodeHttpResponse { pub status: u16, pub status_text: String, pub headers: Vec<(ByteString, ByteString)>, pub url: String, pub response_rid: ResourceId, pub content_length: Option<u64>, pub error: Option<String>, } type CancelableResponseResult = Result<Result<http::Response<Incoming>, hyper::Error>, Canceled>; #[derive(Serialize, Debug)] #[serde(rename_all = "camelCase")] struct InformationalResponse { status: u16, status_text: String, headers: Vec<(ByteString, ByteString)>, version_major: u16, version_minor: u16, } pub struct NodeHttpClientResponse { response: Pin<Box<dyn Future<Output = CancelableResponseResult>>>, url: String, informational_rx: RefCell<Option<mpsc::Receiver<InformationalResponse>>>, socket_rx: RefCell<Option<oneshot::Receiver<NetworkStream>>>, } impl Debug for NodeHttpClientResponse { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("NodeHttpClientResponse") .field("url", &self.url) .finish() } } impl deno_core::Resource for NodeHttpClientResponse { fn name(&self) -> Cow<'_, str> { "nodeHttpClientResponse".into() } } #[derive(Debug, thiserror::Error, JsError)] pub enum ConnError { #[class(inherit)] #[error(transparent)] Resource(ResourceError), #[class(inherit)] #[error(transparent)] Permission(#[from] PermissionCheckError), #[class(type)] #[error("Invalid URL {0}")] InvalidUrl(Url), #[class(type)] #[error("Invalid Path {0}")] InvalidPath(String), #[class(type)] #[error(transparent)] InvalidHeaderName(#[from] http::header::InvalidHeaderName), #[class(type)] #[error(transparent)] InvalidHeaderValue(#[from] http::header::InvalidHeaderValue), #[class(inherit)] #[error(transparent)] Url(#[from] url::ParseError), #[class(type)] #[error(transparent)] Method(#[from] http::method::InvalidMethod), #[class(inherit)] #[error(transparent)] Io(#[from] std::io::Error), #[class("Busy")] #[error("TLS stream is currently in use")] TlsStreamBusy, #[class("Busy")] #[error("TCP stream is currently in use")] TcpStreamBusy, #[class(generic)] #[error(transparent)] ReuniteTcp(#[from] tokio::net::tcp::ReuniteError), #[cfg(unix)] #[class(generic)] #[error(transparent)] ReuniteUnix(#[from] tokio::net::unix::ReuniteError), #[class(inherit)] #[error(transparent)] Canceled(#[from] deno_core::Canceled), #[class("Http")] #[error(transparent)] Hyper(#[from] hyper::Error), } #[op2(async, stack_trace)] #[serde] // This is triggering a known false positive for explicit drop(state) calls. // See https://rust-lang.github.io/rust-clippy/master/index.html#await_holding_refcell_ref #[allow(clippy::await_holding_refcell_ref)] pub async fn op_node_http_request_with_conn( state: Rc<RefCell<OpState>>, #[serde] method: ByteString, #[string] url: String, #[string] request_path: Option<String>, #[serde] headers: Vec<(ByteString, ByteString)>, #[smi] body: Option<ResourceId>, #[smi] conn_rid: ResourceId, ) -> Result<FetchReturn, ConnError> { // Check if this is an upgrade request (e.g., WebSocket) let is_upgrade_request = headers.iter().any(|(name, value)| { name.eq_ignore_ascii_case(b"connection") && value .to_ascii_lowercase() .split(|&b| b == b',') .any(|part| part.trim_ascii() == b"upgrade") }); let stream = take_network_stream_resource( &mut state.borrow_mut().resource_table, conn_rid, ) .map_err(|_| ConnError::Resource(ResourceError::BadResourceId))?; let io = TokioIo::new(stream); let (mut sender, conn) = hyper::client::conn::http1::handshake(io).await?; // Create a channel to return the socket after the HTTP response is complete. // This enables keepAlive connection reuse // For upgrade requests, we use with_upgrades() which doesn't return the socket. let (socket_tx, socket_rx) = oneshot::channel(); if is_upgrade_request { tokio::task::spawn(async move { let _ = conn.with_upgrades().await; drop(socket_tx); }); } else { tokio::task::spawn(async move { if let Ok(parts) = conn.without_shutdown().await { let _ = socket_tx.send(parts.io.into_inner()); } }); } // Create the request. let method = Method::from_bytes(&method)?; let mut url_parsed = Url::parse(&url)?; let maybe_authority = deno_fetch::extract_authority(&mut url_parsed); { let mut state_ = state.borrow_mut(); let permissions = state_.borrow_mut::<PermissionsContainer>(); permissions.check_net_url(&url_parsed, "ClientRequest")?; } let mut header_map = HeaderMap::new(); for (key, value) in headers { let name = HeaderName::from_bytes(&key)?; let v = HeaderValue::from_bytes(&value)?; header_map.append(name, v); } let (body, con_len) = if let Some(body) = body { ( BodyExt::boxed(NodeHttpResourceToBodyAdapter::new( state .borrow_mut() .resource_table .take_any(body) .map_err(ConnError::Resource)?, )), None, ) } else { // POST and PUT requests should always have a 0 length content-length, // if there is no body. https://fetch.spec.whatwg.org/#http-network-or-cache-fetch let len = if matches!(method, Method::POST | Method::PUT) { Some(0) } else { None }; ( http_body_util::Empty::new() .map_err(|never| match never {}) .boxed(), len, ) }; let mut request = http::Request::new(body); *request.method_mut() = method.clone(); let path = url_parsed.path(); let query = url_parsed.query(); if let Some(request_path) = request_path { *request.uri_mut() = request_path .parse() .map_err(|_| ConnError::InvalidPath(request_path.clone()))?; } else { *request.uri_mut() = query .map(|q| format!("{}?{}", path, q)) .unwrap_or_else(|| path.to_string()) .parse() .map_err(|_| ConnError::InvalidUrl(url_parsed.clone()))?; } *request.headers_mut() = header_map; if let Some((username, password)) = maybe_authority { request.headers_mut().insert( AUTHORIZATION, deno_fetch::basic_auth(&username, password.as_deref()), ); } if let Some(len) = con_len { request.headers_mut().insert(CONTENT_LENGTH, len.into()); } let (tx, informational_rx) = mpsc::channel(1); hyper::ext::on_informational(&mut request, move |res| { let mut tx = tx.clone(); let _ = tx.try_send(InformationalResponse { status: res.status().as_u16(), status_text: res.status().canonical_reason().unwrap_or("").to_string(), headers: res .headers() .iter() .map(|(k, v)| (k.as_str().into(), v.as_bytes().into())) .collect(), version_major: match res.version() { hyper::Version::HTTP_09 => 0, hyper::Version::HTTP_10 => 1, hyper::Version::HTTP_11 => 1, hyper::Version::HTTP_2 => 2, hyper::Version::HTTP_3 => 3, _ => unreachable!(), }, version_minor: match res.version() { hyper::Version::HTTP_09 => 9, hyper::Version::HTTP_10 => 0, hyper::Version::HTTP_11 => 1, hyper::Version::HTTP_2 => 0, hyper::Version::HTTP_3 => 0, _ => unreachable!(), }, }); }); let cancel_handle = CancelHandle::new_rc(); let cancel_handle_ = cancel_handle.clone(); let fut = async move { sender.send_request(request).or_cancel(cancel_handle_).await }; let rid = state .borrow_mut() .resource_table .add(NodeHttpClientResponse { response: Box::pin(fut), url: url.clone(), informational_rx: RefCell::new(Some(informational_rx)), socket_rx: RefCell::new(Some(socket_rx)), }); let cancel_handle_rid = state .borrow_mut() .resource_table .add(FetchCancelHandle(cancel_handle)); Ok(FetchReturn { request_rid: rid, cancel_handle_rid: Some(cancel_handle_rid), }) } #[op2(async)] #[serde] pub async fn op_node_http_await_information( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Option<InformationalResponse> { let Ok(resource) = state .borrow_mut() .resource_table .get::<NodeHttpClientResponse>(rid) else { return None; }; let mut rx = resource.informational_rx.borrow_mut().take()?; drop(resource); rx.next().await } #[op2(async)] #[serde] pub async fn op_node_http_await_response( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<NodeHttpResponse, ConnError> { let resource = state .borrow_mut() .resource_table .take::<NodeHttpClientResponse>(rid) .map_err(ConnError::Resource)?; let resource = Rc::try_unwrap(resource).map_err(|_| { ConnError::Resource(ResourceError::Other( "NodeHttpClientResponse".to_string(), )) })?; // Extract the socket receiver before awaiting the response. let socket_rx = resource.socket_rx.borrow_mut().take(); let res = resource.response.await??; let status = res.status(); let mut res_headers = Vec::new(); for (key, val) in res.headers().iter() { res_headers.push((key.as_str().into(), val.as_bytes().into())); } let content_length = hyper::body::Body::size_hint(res.body()).exact(); let (parts, body) = res.into_parts(); let body = body.map_err(|e| JsErrorBox::new("Http", e.to_string())); let body = body.boxed(); let res = http::Response::from_parts(parts, body); let response_rid = state .borrow_mut() .resource_table .add(NodeHttpResponseResource::new( res, content_length, socket_rx, )); Ok(NodeHttpResponse { status: status.as_u16(), status_text: status.canonical_reason().unwrap_or("").to_string(), headers: res_headers, url: resource.url, response_rid, content_length, error: None, }) } /// Returns the socket after the HTTP response body has been fully consumed. /// This enables keepAlive connection reuse for the Node.js HTTP Agent. /// Returns the new resource ID for the socket, or None if the connection /// cannot be reused (e.g., connection error or already retrieved). #[op2(async)] #[smi] pub async fn op_node_http_response_reclaim_conn( state: Rc<RefCell<OpState>>, #[smi] response_rid: ResourceId, ) -> Result<Option<ResourceId>, ConnError> { let resource = state .borrow() .resource_table .get::<NodeHttpResponseResource>(response_rid) .map_err(ConnError::Resource)?; // Take the socket receiver - only one caller can retrieve the socket. let socket_rx = resource.socket_rx.borrow_mut().take(); drop(resource); let Some(rx) = socket_rx else { // Socket was already retrieved or never available. return Ok(None); }; // Wait for the socket to be returned from the connection task. let stream = match rx.await { Ok(stream) => stream, Err(_) => { // Sender was dropped - connection had an error. return Ok(None); } }; // Create a new resource from the returned socket. let rid = match stream { NetworkStream::Tcp(tcp_stream) => state .borrow_mut() .resource_table .add(TcpStreamResource::new(tcp_stream.into_split())), NetworkStream::Tls(tls_stream) => state .borrow_mut() .resource_table .add(TlsStreamResource::new_tcp(tls_stream.into_split())), #[cfg(unix)] NetworkStream::Unix(_) => { // Unix sockets are not commonly used for HTTP keepAlive. return Ok(None); } #[cfg(any( target_os = "android", target_os = "linux", target_os = "macos" ))] NetworkStream::Vsock(_) => { return Ok(None); } NetworkStream::Tunnel(_) => { return Ok(None); } }; Ok(Some(rid)) } #[op2(async)] #[serde] pub async fn op_node_http_fetch_response_upgrade( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<(ResourceId, Option<(String, u16, String, u16)>), ConnError> { let raw_response = state .borrow_mut() .resource_table .take::<NodeHttpResponseResource>(rid) .map_err(ConnError::Resource)?; let raw_response = Rc::try_unwrap(raw_response) .expect("Someone is holding onto NodeHttpFetchResponseResource"); let mut res = raw_response.take(); let upgraded = hyper::upgrade::on(&mut res).await?; let parts = upgraded.downcast::<TokioIo<NetworkStream>>().unwrap(); let stream = parts.io.into_inner(); let info = match (stream.local_address(), stream.peer_address()) { ( Ok(NetworkStreamAddress::Ip(local)), Ok(NetworkStreamAddress::Ip(peer)), ) => Some(( local.ip().to_string(), local.port(), peer.ip().to_string(), peer.port(), )), _ => None, }; Ok(( state .borrow_mut() .resource_table .add(UpgradeStream::new(stream, parts.read_buf)), info, )) } struct UpgradeStream { read: AsyncRefCell<(NetworkStreamReadHalf, Bytes)>, write: AsyncRefCell<NetworkStreamWriteHalf>, cancel_handle: CancelHandle, } impl UpgradeStream { pub fn new(stream: NetworkStream, bytes: Bytes) -> Self { let (read, write) = stream.into_split(); Self { read: AsyncRefCell::new((read, bytes)), write: AsyncRefCell::new(write), cancel_handle: CancelHandle::new(), } } async fn read( self: Rc<Self>, buf: &mut [u8], ) -> Result<usize, std::io::Error> { let cancel_handle = RcRef::map(self.clone(), |this| &this.cancel_handle); async { let read = RcRef::map(self, |this| &this.read); let mut read = read.borrow_mut().await; if !read.1.is_empty() { let n = read.1.len().min(buf.len()); buf[0..n].copy_from_slice(&read.1.split_to(n)); Ok(n) } else { Pin::new(&mut read.0).read(buf).await } } .try_or_cancel(cancel_handle) .await } async fn write(self: Rc<Self>, buf: &[u8]) -> Result<usize, std::io::Error> { let cancel_handle = RcRef::map(self.clone(), |this| &this.cancel_handle); async { let write = RcRef::map(self, |this| &this.write); let mut write = write.borrow_mut().await; Pin::new(&mut *write).write(buf).await } .try_or_cancel(cancel_handle) .await } } impl Resource for UpgradeStream { fn name(&self) -> Cow<'_, str> { "fetchUpgradedStream".into() } deno_core::impl_readable_byob!(); deno_core::impl_writable!(); fn close(self: Rc<Self>) { self.cancel_handle.cancel(); } } type BytesStream = Pin<Box<dyn Stream<Item = Result<bytes::Bytes, std::io::Error>> + Unpin>>; pub enum NodeHttpFetchResponseReader { Start(http::Response<ResBody>), BodyReader(Peekable<BytesStream>), } impl Default for NodeHttpFetchResponseReader { fn default() -> Self { let stream: BytesStream = Box::pin(deno_core::futures::stream::empty()); Self::BodyReader(stream.peekable()) } } #[derive(Debug)] pub struct NodeHttpResponseResource { pub response_reader: AsyncRefCell<NodeHttpFetchResponseReader>, pub cancel: CancelHandle, pub size: Option<u64>, socket_rx: RefCell<Option<oneshot::Receiver<NetworkStream>>>, } impl NodeHttpResponseResource { pub fn new( response: http::Response<ResBody>, size: Option<u64>, socket_rx: Option<oneshot::Receiver<NetworkStream>>, ) -> Self { Self { response_reader: AsyncRefCell::new(NodeHttpFetchResponseReader::Start( response, )), cancel: CancelHandle::default(), size, socket_rx: RefCell::new(socket_rx), } } pub fn take(self) -> http::Response<ResBody> { let reader = self.response_reader.into_inner(); match reader { NodeHttpFetchResponseReader::Start(resp) => resp, _ => unreachable!(), } } } impl Resource for NodeHttpResponseResource { fn name(&self) -> Cow<'_, str> { "fetchResponse".into() } fn read(self: Rc<Self>, limit: usize) -> AsyncResult<BufView> { Box::pin(async move { let mut reader = RcRef::map(&self, |r| &r.response_reader).borrow_mut().await; let body = loop { match &mut *reader { NodeHttpFetchResponseReader::BodyReader(reader) => break reader, NodeHttpFetchResponseReader::Start(_) => {} } match std::mem::take(&mut *reader) { NodeHttpFetchResponseReader::Start(resp) => { let stream: BytesStream = Box::pin( resp .into_body() .into_data_stream() .map(|r| r.map_err(std::io::Error::other)), ); *reader = NodeHttpFetchResponseReader::BodyReader(stream.peekable()); } NodeHttpFetchResponseReader::BodyReader(_) => unreachable!(), } }; let fut = async move { let mut reader = Pin::new(body); loop { match reader.as_mut().peek_mut().await { Some(Ok(chunk)) if !chunk.is_empty() => { let len = min(limit, chunk.len()); let chunk = chunk.split_to(len); break Ok(chunk.into()); } // This unwrap is safe because `peek_mut()` returned `Some`, and thus // currently has a peeked value that can be synchronously returned // from `next()`. // // The future returned from `next()` is always ready, so we can // safely call `await` on it without creating a race condition. Some(_) => match reader.as_mut().next().await.unwrap() { Ok(chunk) => assert!(chunk.is_empty()), Err(err) => break Err(JsErrorBox::type_error(err.to_string())), }, None => break Ok(BufView::empty()), } } }; let cancel_handle = RcRef::map(self, |r| &r.cancel); fut.try_or_cancel(cancel_handle).await }) } fn size_hint(&self) -> (u64, Option<u64>) { (self.size.unwrap_or(0), self.size) } fn close(self: Rc<Self>) { self.cancel.cancel() } } #[allow(clippy::type_complexity)] pub struct NodeHttpResourceToBodyAdapter( Rc<dyn Resource>, Option<Pin<Box<dyn Future<Output = Result<BufView, JsErrorBox>>>>>, ); impl NodeHttpResourceToBodyAdapter { pub fn new(resource: Rc<dyn Resource>) -> Self { let future = resource.clone().read(64 * 1024); Self(resource, Some(future)) } } // SAFETY: we only use this on a single-threaded executor unsafe impl Send for NodeHttpResourceToBodyAdapter {} // SAFETY: we only use this on a single-threaded executor unsafe impl Sync for NodeHttpResourceToBodyAdapter {} impl Stream for NodeHttpResourceToBodyAdapter { type Item = Result<Bytes, JsErrorBox>; fn poll_next( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Self::Item>> { let this = self.get_mut(); match this.1.take() { Some(mut fut) => match fut.poll_unpin(cx) { Poll::Pending => { this.1 = Some(fut); Poll::Pending } Poll::Ready(res) => match res { Ok(buf) if buf.is_empty() => Poll::Ready(None), Ok(buf) => { let bytes: Bytes = buf.to_vec().into(); this.1 = Some(this.0.clone().read(64 * 1024)); Poll::Ready(Some(Ok(bytes))) } Err(err) => Poll::Ready(Some(Err(err))), }, }, _ => Poll::Ready(None), } } } impl hyper::body::Body for NodeHttpResourceToBodyAdapter { type Data = Bytes; type Error = JsErrorBox; fn poll_frame( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> { match self.poll_next(cx) { Poll::Ready(Some(res)) => Poll::Ready(Some(res.map(Frame::data))), Poll::Ready(None) => Poll::Ready(None), Poll::Pending => Poll::Pending, } } } impl Drop for NodeHttpResourceToBodyAdapter { fn drop(&mut self) { self.0.clone().close() } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/idna.rs
ext/node/ops/idna.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use deno_core::op2; // map_domain, to_ascii and to_unicode are based on the punycode implementation in node.js // https://github.com/nodejs/node/blob/73025c4dec042e344eeea7912ed39f7b7c4a3991/lib/punycode.js const PUNY_PREFIX: &str = "xn--"; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum IdnaError { #[class(range)] #[error("Invalid input")] InvalidInput, #[class(generic)] #[error("Input would take more than 63 characters to encode")] InputTooLong, #[class(range)] #[error("Illegal input >= 0x80 (not a basic code point)")] IllegalInput, } deno_error::js_error_wrapper!(idna::Errors, JsIdnaErrors, "Error"); /// map a domain by mapping each label with the given function fn map_domain( domain: &str, f: impl Fn(&str) -> Result<Cow<'_, str>, IdnaError>, ) -> Result<String, IdnaError> { let mut result = String::with_capacity(domain.len()); let mut domain = domain; // if it's an email, leave the local part as is let mut parts = domain.split('@'); if let (Some(local), Some(remaining)) = (parts.next(), parts.next()) { result.push_str(local); result.push('@'); domain = remaining; } // split into labels and map each one for (i, label) in domain.split('.').enumerate() { if i > 0 { result.push('.'); } result.push_str(&f(label)?); } Ok(result) } /// Maps a unicode domain to ascii by punycode encoding each label /// /// Note this is not IDNA2003 or IDNA2008 compliant, rather it matches node.js's punycode implementation fn to_ascii(input: &str) -> Result<String, IdnaError> { if input.is_ascii() { return Ok(input.into()); } let mut result = String::with_capacity(input.len()); // at least as long as input let rest = map_domain(input, |label| { if label.is_ascii() { Ok(label.into()) } else { idna::punycode::encode_str(label) .map(|encoded| [PUNY_PREFIX, &encoded].join("").into()) // add the prefix .ok_or(IdnaError::InputTooLong) // only error possible per the docs } })?; result.push_str(&rest); Ok(result) } /// Maps an ascii domain to unicode by punycode decoding each label /// /// Note this is not IDNA2003 or IDNA2008 compliant, rather it matches node.js's punycode implementation fn to_unicode(input: &str) -> Result<String, IdnaError> { map_domain(input, |s| { if let Some(puny) = s.strip_prefix(PUNY_PREFIX) { // it's a punycode encoded label Ok( idna::punycode::decode_to_string(&puny.to_lowercase()) .ok_or(IdnaError::InvalidInput)? .into(), ) } else { Ok(s.into()) } }) } /// Converts a domain to unicode with behavior that is /// compatible with the `punycode` module in node.js #[op2] #[string] pub fn op_node_idna_punycode_to_ascii( #[string] domain: String, ) -> Result<String, IdnaError> { to_ascii(&domain) } /// Converts a domain to ASCII with behavior that is /// compatible with the `punycode` module in node.js #[op2] #[string] pub fn op_node_idna_punycode_to_unicode( #[string] domain: String, ) -> Result<String, IdnaError> { to_unicode(&domain) } /// Converts a domain to ASCII as per the IDNA spec /// (specifically UTS #46) /// /// Returns an empty string if the domain is invalid, matching Node.js behavior #[op2] #[string] pub fn op_node_idna_domain_to_ascii(#[string] domain: String) -> String { idna::domain_to_ascii(&domain).unwrap_or_default() } /// Converts a domain to Unicode as per the IDNA spec /// (specifically UTS #46) #[op2] #[string] pub fn op_node_idna_domain_to_unicode(#[string] domain: String) -> String { idna::domain_to_unicode(&domain).0 } #[op2] #[string] pub fn op_node_idna_punycode_decode( #[string] domain: String, ) -> Result<String, IdnaError> { if domain.is_empty() { return Ok(domain); } // all code points before the last delimiter must be basic // see https://github.com/nodejs/node/blob/73025c4dec042e344eeea7912ed39f7b7c4a3991/lib/punycode.js#L215-L227 let last_dash = domain.len() - 1 - domain .bytes() .rev() .position(|b| b == b'-') .unwrap_or(domain.len() - 1); if !domain[..last_dash].is_ascii() { return Err(IdnaError::IllegalInput); } idna::punycode::decode_to_string(&domain).ok_or(IdnaError::InvalidInput) } #[op2] #[string] pub fn op_node_idna_punycode_encode(#[string] domain: String) -> String { idna::punycode::encode_str(&domain).unwrap_or_default() }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/fs.rs
ext/node/ops/fs.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::path::Path; use std::path::PathBuf; use std::rc::Rc; use deno_core::OpState; use deno_core::ResourceId; use deno_core::op2; use deno_core::unsync::spawn_blocking; use deno_fs::FileSystemRc; use deno_fs::OpenOptions; use deno_io::fs::FileResource; use deno_permissions::CheckedPath; use deno_permissions::OpenAccessKind; use deno_permissions::PermissionsContainer; use serde::Serialize; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum FsError { #[class(inherit)] #[error(transparent)] Permission(#[from] deno_permissions::PermissionCheckError), #[class(inherit)] #[error("{0}")] Io( #[from] #[inherit] std::io::Error, ), #[cfg(windows)] #[class(generic)] #[error("Path has no root.")] PathHasNoRoot, #[cfg(not(any(unix, windows)))] #[class(generic)] #[error("Unsupported platform.")] UnsupportedPlatform, #[class(inherit)] #[error(transparent)] Fs( #[from] #[inherit] deno_io::fs::FsError, ), } #[op2(fast, stack_trace)] pub fn op_node_fs_exists_sync( state: &mut OpState, #[string] path: &str, ) -> Result<bool, deno_permissions::PermissionCheckError> { let path = state.borrow_mut::<PermissionsContainer>().check_open( Cow::Borrowed(Path::new(path)), OpenAccessKind::ReadNoFollow, Some("node:fs.existsSync()"), )?; let fs = state.borrow::<FileSystemRc>(); Ok(fs.exists_sync(&path)) } #[op2(async, stack_trace)] pub async fn op_node_fs_exists( state: Rc<RefCell<OpState>>, #[string] path: String, ) -> Result<bool, FsError> { let (fs, path) = { let mut state = state.borrow_mut(); let path = state.borrow_mut::<PermissionsContainer>().check_open( Cow::Owned(PathBuf::from(path)), OpenAccessKind::ReadNoFollow, Some("node:fs.exists()"), )?; (state.borrow::<FileSystemRc>().clone(), path) }; Ok(fs.exists_async(path.into_owned()).await?) } fn get_open_options(flags: i32, mode: Option<u32>) -> OpenOptions { let mut options = OpenOptions::from(flags); options.mode = mode; options } fn open_options_to_access_kind(open_options: &OpenOptions) -> OpenAccessKind { let read = open_options.read; let write = open_options.write || open_options.append; match (read, write) { (true, true) => OpenAccessKind::ReadWrite, (false, true) => OpenAccessKind::Write, (true, false) | (false, false) => OpenAccessKind::Read, } } #[op2(fast, stack_trace)] #[smi] pub fn op_node_open_sync( state: &mut OpState, #[string] path: &str, #[smi] flags: i32, #[smi] mode: u32, ) -> Result<ResourceId, FsError> { let path = Path::new(path); let options = get_open_options(flags, Some(mode)); let fs = state.borrow::<FileSystemRc>().clone(); let path = state.borrow_mut::<PermissionsContainer>().check_open( Cow::Borrowed(path), open_options_to_access_kind(&options), Some("node:fs.openSync"), )?; let file = fs.open_sync(&path, options)?; let rid = state .resource_table .add(FileResource::new(file, "fsFile".to_string())); Ok(rid) } #[op2(async, stack_trace)] #[smi] pub async fn op_node_open( state: Rc<RefCell<OpState>>, #[string] path: String, #[smi] flags: i32, #[smi] mode: u32, ) -> Result<ResourceId, FsError> { let path = PathBuf::from(path); let options = get_open_options(flags, Some(mode)); let (fs, path) = { let mut state = state.borrow_mut(); ( state.borrow::<FileSystemRc>().clone(), state.borrow_mut::<PermissionsContainer>().check_open( Cow::Owned(path), open_options_to_access_kind(&options), Some("node:fs.open"), )?, ) }; let file = fs.open_async(path.as_owned(), options).await?; let rid = state .borrow_mut() .resource_table .add(FileResource::new(file, "fsFile".to_string())); Ok(rid) } #[derive(Debug, Serialize)] pub struct StatFs { #[serde(rename = "type")] pub typ: u64, pub bsize: u64, pub blocks: u64, pub bfree: u64, pub bavail: u64, pub files: u64, pub ffree: u64, } #[op2(stack_trace)] #[serde] pub fn op_node_statfs_sync( state: &mut OpState, #[string] path: &str, bigint: bool, ) -> Result<StatFs, FsError> { let path = state.borrow_mut::<PermissionsContainer>().check_open( Cow::Borrowed(Path::new(path)), OpenAccessKind::ReadNoFollow, Some("node:fs.statfsSync"), )?; state .borrow_mut::<PermissionsContainer>() .check_sys("statfs", "node:fs.statfsSync")?; statfs(path, bigint) } #[op2(async, stack_trace)] #[serde] pub async fn op_node_statfs( state: Rc<RefCell<OpState>>, #[string] path: String, bigint: bool, ) -> Result<StatFs, FsError> { let path = { let mut state = state.borrow_mut(); let path = state.borrow_mut::<PermissionsContainer>().check_open( Cow::Owned(PathBuf::from(path)), OpenAccessKind::ReadNoFollow, Some("node:fs.statfs"), )?; state .borrow_mut::<PermissionsContainer>() .check_sys("statfs", "node:fs.statfs")?; path }; match spawn_blocking(move || statfs(path, bigint)).await { Ok(result) => result, Err(err) => Err(FsError::Io(err.into())), } } fn statfs(path: CheckedPath, bigint: bool) -> Result<StatFs, FsError> { #[cfg(unix)] { use std::os::unix::ffi::OsStrExt; let path = path.as_os_str(); let mut cpath = path.as_bytes().to_vec(); cpath.push(0); if bigint { #[cfg(not(any( target_os = "macos", target_os = "freebsd", target_os = "openbsd" )))] // SAFETY: `cpath` is NUL-terminated and result is pointer to valid statfs memory. let (code, result) = unsafe { let mut result: libc::statfs64 = std::mem::zeroed(); (libc::statfs64(cpath.as_ptr() as _, &mut result), result) }; #[cfg(any( target_os = "macos", target_os = "freebsd", target_os = "openbsd" ))] // SAFETY: `cpath` is NUL-terminated and result is pointer to valid statfs memory. let (code, result) = unsafe { let mut result: libc::statfs = std::mem::zeroed(); (libc::statfs(cpath.as_ptr() as _, &mut result), result) }; if code == -1 { return Err(std::io::Error::last_os_error().into()); } Ok(StatFs { #[cfg(not(target_os = "openbsd"))] typ: result.f_type as _, #[cfg(target_os = "openbsd")] typ: 0 as _, bsize: result.f_bsize as _, blocks: result.f_blocks as _, bfree: result.f_bfree as _, bavail: result.f_bavail as _, files: result.f_files as _, ffree: result.f_ffree as _, }) } else { // SAFETY: `cpath` is NUL-terminated and result is pointer to valid statfs memory. let (code, result) = unsafe { let mut result: libc::statfs = std::mem::zeroed(); (libc::statfs(cpath.as_ptr() as _, &mut result), result) }; if code == -1 { return Err(std::io::Error::last_os_error().into()); } Ok(StatFs { #[cfg(not(target_os = "openbsd"))] typ: result.f_type as _, #[cfg(target_os = "openbsd")] typ: 0 as _, bsize: result.f_bsize as _, blocks: result.f_blocks as _, bfree: result.f_bfree as _, bavail: result.f_bavail as _, files: result.f_files as _, ffree: result.f_ffree as _, }) } } #[cfg(windows)] { use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceW; let _ = bigint; // Using a vfs here doesn't make sense, it won't align with the windows API // call below. #[allow(clippy::disallowed_methods)] let path = path.canonicalize()?; let root = path.ancestors().last().ok_or(FsError::PathHasNoRoot)?; let mut root = OsStr::new(root).encode_wide().collect::<Vec<_>>(); root.push(0); let mut sectors_per_cluster = 0; let mut bytes_per_sector = 0; let mut available_clusters = 0; let mut total_clusters = 0; let mut code = 0; let mut retries = 0; // We retry here because libuv does: https://github.com/libuv/libuv/blob/fa6745b4f26470dae5ee4fcbb1ee082f780277e0/src/win/fs.c#L2705 while code == 0 && retries < 2 { // SAFETY: Normal GetDiskFreeSpaceW usage. code = unsafe { GetDiskFreeSpaceW( root.as_ptr(), &mut sectors_per_cluster, &mut bytes_per_sector, &mut available_clusters, &mut total_clusters, ) }; retries += 1; } if code == 0 { return Err(std::io::Error::last_os_error().into()); } Ok(StatFs { typ: 0, bsize: (bytes_per_sector * sectors_per_cluster) as _, blocks: total_clusters as _, bfree: available_clusters as _, bavail: available_clusters as _, files: 0, ffree: 0, }) } #[cfg(not(any(unix, windows)))] { let _ = path; let _ = bigint; Err(FsError::UnsupportedPlatform) } } #[op2(fast, stack_trace)] pub fn op_node_lutimes_sync( state: &mut OpState, #[string] path: &str, #[number] atime_secs: i64, #[smi] atime_nanos: u32, #[number] mtime_secs: i64, #[smi] mtime_nanos: u32, ) -> Result<(), FsError> { let path = state.borrow_mut::<PermissionsContainer>().check_open( Cow::Borrowed(Path::new(path)), OpenAccessKind::WriteNoFollow, Some("node:fs.lutimes"), )?; let fs = state.borrow::<FileSystemRc>(); fs.lutime_sync(&path, atime_secs, atime_nanos, mtime_secs, mtime_nanos)?; Ok(()) } #[op2(async, stack_trace)] pub async fn op_node_lutimes( state: Rc<RefCell<OpState>>, #[string] path: String, #[number] atime_secs: i64, #[smi] atime_nanos: u32, #[number] mtime_secs: i64, #[smi] mtime_nanos: u32, ) -> Result<(), FsError> { let (fs, path) = { let mut state = state.borrow_mut(); let path = state.borrow_mut::<PermissionsContainer>().check_open( Cow::Owned(PathBuf::from(path)), OpenAccessKind::WriteNoFollow, Some("node:fs.lutimesSync"), )?; (state.borrow::<FileSystemRc>().clone(), path) }; fs.lutime_async( path.into_owned(), atime_secs, atime_nanos, mtime_secs, mtime_nanos, ) .await?; Ok(()) } #[op2(stack_trace)] pub fn op_node_lchown_sync( state: &mut OpState, #[string] path: &str, uid: Option<u32>, gid: Option<u32>, ) -> Result<(), FsError> { let path = state.borrow_mut::<PermissionsContainer>().check_open( Cow::Borrowed(Path::new(path)), OpenAccessKind::WriteNoFollow, Some("node:fs.lchownSync"), )?; let fs = state.borrow::<FileSystemRc>(); fs.lchown_sync(&path, uid, gid)?; Ok(()) } #[op2(async, stack_trace)] pub async fn op_node_lchown( state: Rc<RefCell<OpState>>, #[string] path: String, uid: Option<u32>, gid: Option<u32>, ) -> Result<(), FsError> { let (fs, path) = { let mut state = state.borrow_mut(); let path = state.borrow_mut::<PermissionsContainer>().check_open( Cow::Owned(PathBuf::from(path)), OpenAccessKind::WriteNoFollow, Some("node:fs.lchown"), )?; (state.borrow::<FileSystemRc>().clone(), path) }; fs.lchown_async(path.into_owned(), uid, gid).await?; Ok(()) } #[op2(fast, stack_trace)] pub fn op_node_lchmod_sync( state: &mut OpState, #[string] path: &str, #[smi] mode: u32, ) -> Result<(), FsError> { let path = state.borrow_mut::<PermissionsContainer>().check_open( Cow::Borrowed(Path::new(path)), OpenAccessKind::WriteNoFollow, Some("node:fs.lchmodSync"), )?; let fs = state.borrow::<FileSystemRc>(); fs.lchmod_sync(&path, mode)?; Ok(()) } #[op2(async, stack_trace)] pub async fn op_node_lchmod( state: Rc<RefCell<OpState>>, #[string] path: String, #[smi] mode: u32, ) -> Result<(), FsError> { let (fs, path) = { let mut state = state.borrow_mut(); let path = state.borrow_mut::<PermissionsContainer>().check_open( Cow::Owned(PathBuf::from(path)), OpenAccessKind::WriteNoFollow, Some("node:fs.lchmod"), )?; (state.borrow::<FileSystemRc>().clone(), path) }; fs.lchmod_async(path.into_owned(), mode).await?; Ok(()) } #[op2(stack_trace)] #[string] pub fn op_node_mkdtemp_sync( state: &mut OpState, #[string] path: &str, ) -> Result<String, FsError> { // https://github.com/nodejs/node/blob/2ea31e53c61463727c002c2d862615081940f355/deps/uv/src/unix/os390-syscalls.c#L409 for _ in 0..libc::TMP_MAX { let path = temp_path_append_suffix(path); let checked_path = state.borrow_mut::<PermissionsContainer>().check_open( Cow::Borrowed(Path::new(&path)), OpenAccessKind::WriteNoFollow, Some("node:fs.mkdtempSync()"), )?; let fs = state.borrow::<FileSystemRc>(); match fs.mkdir_sync(&checked_path, false, Some(0o700)) { Ok(()) => return Ok(path), Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => { continue; } Err(err) => return Err(FsError::Fs(err)), } } Err(FsError::Io(std::io::Error::new( std::io::ErrorKind::AlreadyExists, "too many temp dirs exist", ))) } #[op2(async, stack_trace)] #[string] pub async fn op_node_mkdtemp( state: Rc<RefCell<OpState>>, #[string] path: String, ) -> Result<String, FsError> { // https://github.com/nodejs/node/blob/2ea31e53c61463727c002c2d862615081940f355/deps/uv/src/unix/os390-syscalls.c#L409 for _ in 0..libc::TMP_MAX { let path = temp_path_append_suffix(&path); let (fs, checked_path) = { let mut state = state.borrow_mut(); let checked_path = state.borrow_mut::<PermissionsContainer>().check_open( Cow::Owned(PathBuf::from(path.clone())), OpenAccessKind::WriteNoFollow, Some("node:fs.mkdtemp()"), )?; (state.borrow::<FileSystemRc>().clone(), checked_path) }; match fs .mkdir_async(checked_path.into_owned(), false, Some(0o700)) .await { Ok(()) => return Ok(path), Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => { continue; } Err(err) => return Err(FsError::Fs(err)), } } Err(FsError::Io(std::io::Error::new( std::io::ErrorKind::AlreadyExists, "too many temp dirs exist", ))) } fn temp_path_append_suffix(prefix: &str) -> String { use rand::Rng; use rand::distributions::Alphanumeric; use rand::rngs::OsRng; let suffix: String = (0..6).map(|_| OsRng.sample(Alphanumeric) as char).collect(); format!("{}{}", prefix, suffix) } /// Create a file resource from a raw file descriptor. /// This is used for wrapping PTYs and other non-socket file descriptors /// that can't be wrapped as Unix streams. #[cfg(unix)] #[op2(fast)] #[smi] pub fn op_node_file_from_fd( state: &mut OpState, fd: i32, ) -> Result<ResourceId, FsError> { use std::fs::File as StdFile; use std::os::unix::io::FromRawFd; if fd < 0 { return Err(FsError::Io(std::io::Error::new( std::io::ErrorKind::InvalidInput, "Invalid file descriptor", ))); } // SAFETY: The caller is responsible for passing a valid fd that they own. // The fd will be owned by the created File from this point on. let std_file = unsafe { StdFile::from_raw_fd(fd) }; let file = Rc::new(deno_io::StdFileResourceInner::file(std_file, None)); let rid = state .resource_table .add(FileResource::new(file, "pipe".to_string())); Ok(rid) } #[cfg(not(unix))] #[op2(fast)] #[smi] pub fn op_node_file_from_fd( _state: &mut OpState, _fd: i32, ) -> Result<ResourceId, FsError> { Err(FsError::Io(std::io::Error::new( std::io::ErrorKind::Unsupported, "op_node_file_from_fd is not supported on this platform", ))) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/perf_hooks.rs
ext/node/ops/perf_hooks.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::Cell; use std::cell::RefCell; use deno_core::GarbageCollected; use deno_core::op2; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum PerfHooksError { #[class(generic)] #[error(transparent)] TokioEld(#[from] tokio_eld::Error), } pub struct EldHistogram { eld: RefCell<tokio_eld::EldHistogram<u64>>, started: Cell<bool>, } // SAFETY: we're sure this can be GCed unsafe impl GarbageCollected for EldHistogram { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"EldHistogram" } } #[op2] impl EldHistogram { // Creates an interval EldHistogram object that samples and reports the event // loop delay over time. // // The delays will be reported in nanoseconds. #[constructor] #[cppgc] pub fn new(#[smi] resolution: u32) -> Result<EldHistogram, PerfHooksError> { Ok(EldHistogram { eld: RefCell::new(tokio_eld::EldHistogram::new(resolution as usize)?), started: Cell::new(false), }) } // Disables the update interval timer. // // Returns true if the timer was stopped, false if it was already stopped. #[fast] fn enable(&self) -> bool { if self.started.get() { return false; } self.eld.borrow().start(); self.started.set(true); true } // Enables the update interval timer. // // Returns true if the timer was started, false if it was already started. #[fast] fn disable(&self) -> bool { if !self.started.get() { return false; } self.eld.borrow().stop(); self.started.set(false); true } #[fast] fn reset(&self) { self.eld.borrow_mut().reset(); } // Returns the value at the given percentile. // // `percentile` ∈ (0, 100] #[fast] #[number] fn percentile(&self, percentile: f64) -> u64 { self.eld.borrow().value_at_percentile(percentile) } // Returns the value at the given percentile as a bigint. #[fast] #[bigint] fn percentile_big_int(&self, percentile: f64) -> u64 { self.eld.borrow().value_at_percentile(percentile) } // The number of samples recorded by the histogram. #[getter] #[number] fn count(&self) -> u64 { self.eld.borrow().len() } // The number of samples recorded by the histogram as a bigint. #[getter] #[bigint] fn count_big_int(&self) -> u64 { self.eld.borrow().len() } // The maximum recorded event loop delay. #[getter] #[number] fn max(&self) -> u64 { self.eld.borrow().max() } // The maximum recorded event loop delay as a bigint. #[getter] #[bigint] fn max_big_int(&self) -> u64 { self.eld.borrow().max() } // The mean of the recorded event loop delays. #[getter] fn mean(&self) -> f64 { self.eld.borrow().mean() } // The minimum recorded event loop delay. #[getter] #[number] fn min(&self) -> u64 { self.eld.borrow().min() } // The minimum recorded event loop delay as a bigint. #[getter] #[bigint] fn min_big_int(&self) -> u64 { self.eld.borrow().min() } // The standard deviation of the recorded event loop delays. #[getter] fn stddev(&self) -> f64 { self.eld.borrow().stdev() } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/v8.rs
ext/node/ops/v8.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ptr::NonNull; use deno_core::FastString; use deno_core::GarbageCollected; use deno_core::ToJsBuffer; use deno_core::op2; use deno_core::v8; use deno_error::JsErrorBox; use v8::ValueDeserializerHelper; use v8::ValueSerializerHelper; #[op2(fast)] pub fn op_v8_cached_data_version_tag() -> u32 { v8::script_compiler::cached_data_version_tag() } #[op2(fast)] pub fn op_v8_get_heap_statistics( scope: &mut v8::PinScope<'_, '_>, #[buffer] buffer: &mut [f64], ) { let stats = scope.get_heap_statistics(); buffer[0] = stats.total_heap_size() as f64; buffer[1] = stats.total_heap_size_executable() as f64; buffer[2] = stats.total_physical_size() as f64; buffer[3] = stats.total_available_size() as f64; buffer[4] = stats.used_heap_size() as f64; buffer[5] = stats.heap_size_limit() as f64; buffer[6] = stats.malloced_memory() as f64; buffer[7] = stats.peak_malloced_memory() as f64; buffer[8] = if stats.does_zap_garbage() { 1.0 } else { 0.0 }; buffer[9] = stats.number_of_native_contexts() as f64; buffer[10] = stats.number_of_detached_contexts() as f64; buffer[11] = stats.total_global_handles_size() as f64; buffer[12] = stats.used_global_handles_size() as f64; buffer[13] = stats.external_memory() as f64; } pub struct Serializer<'a> { inner: v8::ValueSerializer<'a>, } pub struct SerializerDelegate { obj: v8::Global<v8::Object>, } // SAFETY: we're sure this can be GCed unsafe impl v8::cppgc::GarbageCollected for Serializer<'_> { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"Serializer" } } impl SerializerDelegate { fn obj<'s>( &self, scope: &mut v8::PinScope<'s, '_>, ) -> v8::Local<'s, v8::Object> { v8::Local::new(scope, &self.obj) } } impl v8::ValueSerializerImpl for SerializerDelegate { fn get_shared_array_buffer_id<'s>( &self, scope: &mut v8::PinScope<'s, '_>, shared_array_buffer: v8::Local<'s, v8::SharedArrayBuffer>, ) -> Option<u32> { let obj = self.obj(scope); let key = FastString::from_static("_getSharedArrayBufferId") .v8_string(scope) .unwrap() .into(); if let Some(v) = obj.get(scope, key) && let Ok(fun) = v.try_cast::<v8::Function>() { return fun .call(scope, obj.into(), &[shared_array_buffer.into()]) .and_then(|ret| ret.uint32_value(scope)); } None } fn has_custom_host_object(&self, _isolate: &v8::Isolate) -> bool { false } fn throw_data_clone_error<'s>( &self, scope: &mut v8::PinScope<'s, '_>, message: v8::Local<'s, v8::String>, ) { let obj = self.obj(scope); let key = FastString::from_static("_getDataCloneError") .v8_string(scope) .unwrap() .into(); if let Some(v) = obj.get(scope, key) { let fun = v .try_cast::<v8::Function>() .expect("_getDataCloneError should be a function"); if let Some(error) = fun.call(scope, obj.into(), &[message.into()]) { scope.throw_exception(error); return; } } let error = v8::Exception::type_error(scope, message); scope.throw_exception(error); } fn write_host_object<'s>( &self, scope: &mut v8::PinScope<'s, '_>, object: v8::Local<'s, v8::Object>, _value_serializer: &dyn ValueSerializerHelper, ) -> Option<bool> { let obj = self.obj(scope); let key = FastString::from_static("_writeHostObject") .v8_string(scope) .unwrap() .into(); if let Some(v) = obj.get(scope, key) && let Ok(v) = v.try_cast::<v8::Function>() { v.call(scope, obj.into(), &[object.into()])?; return Some(true); } None } fn is_host_object<'s>( &self, _scope: &mut v8::PinScope<'s, '_>, _object: v8::Local<'s, v8::Object>, ) -> Option<bool> { // should never be called because has_custom_host_object returns false None } } #[op2] #[cppgc] pub fn op_v8_new_serializer( scope: &mut v8::PinScope<'_, '_>, obj: v8::Local<v8::Object>, ) -> Serializer<'static> { let obj = v8::Global::new(scope, obj); let inner = v8::ValueSerializer::new(scope, Box::new(SerializerDelegate { obj })); Serializer { inner } } #[op2(fast)] pub fn op_v8_set_treat_array_buffer_views_as_host_objects( #[cppgc] ser: &Serializer, value: bool, ) { ser .inner .set_treat_array_buffer_views_as_host_objects(value); } #[op2] #[serde] pub fn op_v8_release_buffer(#[cppgc] ser: &Serializer) -> ToJsBuffer { ser.inner.release().into() } #[op2(fast)] pub fn op_v8_transfer_array_buffer( #[cppgc] ser: &Serializer, #[smi] id: u32, array_buffer: v8::Local<v8::ArrayBuffer>, ) { ser.inner.transfer_array_buffer(id, array_buffer); } #[op2(fast)] pub fn op_v8_write_double(#[cppgc] ser: &Serializer, double: f64) { ser.inner.write_double(double); } #[op2(fast)] pub fn op_v8_write_header(#[cppgc] ser: &Serializer) { ser.inner.write_header(); } #[op2] pub fn op_v8_write_raw_bytes( #[cppgc] ser: &Serializer, #[anybuffer] source: &[u8], ) { ser.inner.write_raw_bytes(source); } #[op2(fast)] pub fn op_v8_write_uint32(#[cppgc] ser: &Serializer, num: u32) { ser.inner.write_uint32(num); } #[op2(fast)] pub fn op_v8_write_uint64(#[cppgc] ser: &Serializer, hi: u32, lo: u32) { let num = ((hi as u64) << 32) | (lo as u64); ser.inner.write_uint64(num); } #[op2(nofast, reentrant)] pub fn op_v8_write_value( scope: &mut v8::PinScope<'_, '_>, #[cppgc] ser: &Serializer, value: v8::Local<v8::Value>, ) { let context = scope.get_current_context(); ser.inner.write_value(context, value); } struct DeserBuffer { ptr: Option<NonNull<u8>>, // Hold onto backing store to keep the underlying buffer // alive while we hold a reference to it. _backing_store: v8::SharedRef<v8::BackingStore>, } pub struct Deserializer<'a> { buf: DeserBuffer, inner: v8::ValueDeserializer<'a>, } // SAFETY: we're sure this can be GCed unsafe impl deno_core::GarbageCollected for Deserializer<'_> { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"Deserializer" } } pub struct DeserializerDelegate { obj: v8::TracedReference<v8::Object>, } // SAFETY: we're sure this can be GCed unsafe impl GarbageCollected for DeserializerDelegate { fn trace(&self, visitor: &mut v8::cppgc::Visitor) { visitor.trace(&self.obj); } fn get_name(&self) -> &'static std::ffi::CStr { c"DeserializerDelegate" } } impl v8::ValueDeserializerImpl for DeserializerDelegate { fn read_host_object<'s>( &self, scope: &mut v8::PinScope<'s, '_>, _value_deserializer: &dyn v8::ValueDeserializerHelper, ) -> Option<v8::Local<'s, v8::Object>> { let obj = self.obj.get(scope).unwrap(); let key = FastString::from_static("_readHostObject") .v8_string(scope) .unwrap() .into(); let scope = std::pin::pin!(v8::AllowJavascriptExecutionScope::new(scope)); let scope = &mut scope.init(); if let Some(v) = obj.get(scope, key) && let Ok(v) = v.try_cast::<v8::Function>() { let result = v.call(scope, obj.into(), &[])?; match result.try_cast() { Ok(res) => return Some(res), Err(_) => { let msg = FastString::from_static("readHostObject must return an object") .v8_string(scope) .unwrap(); let error = v8::Exception::type_error(scope, msg); scope.throw_exception(error); return None; } } } None } } #[op2] #[cppgc] pub fn op_v8_new_deserializer( scope: &mut v8::PinScope<'_, '_>, obj: v8::Local<v8::Object>, buffer: v8::Local<v8::ArrayBufferView>, ) -> Result<Deserializer<'static>, JsErrorBox> { let offset = buffer.byte_offset(); let len = buffer.byte_length(); let backing_store = buffer.get_backing_store().ok_or_else(|| { JsErrorBox::generic("deserialization buffer has no backing store") })?; let (buf_slice, buf_ptr) = if let Some(data) = backing_store.data() { // SAFETY: the offset is valid for the underlying buffer because we're getting it directly from v8 let data_ptr = unsafe { data.as_ptr().cast::<u8>().add(offset) }; ( // SAFETY: the len is valid, from v8, and the data_ptr is valid (as above) unsafe { std::slice::from_raw_parts(data_ptr.cast_const().cast(), len) }, Some(data.cast()), ) } else { (&[] as &[u8], None::<NonNull<u8>>) }; let obj = v8::TracedReference::new(scope, obj); let inner = v8::ValueDeserializer::new( scope, Box::new(DeserializerDelegate { obj }), buf_slice, ); Ok(Deserializer { inner, buf: DeserBuffer { _backing_store: backing_store, ptr: buf_ptr, }, }) } #[op2(fast)] pub fn op_v8_transfer_array_buffer_de( #[cppgc] deser: &Deserializer, #[smi] id: u32, array_buffer: v8::Local<v8::Value>, ) -> Result<(), deno_core::error::DataError> { if let Ok(shared_array_buffer) = array_buffer.try_cast::<v8::SharedArrayBuffer>() { deser .inner .transfer_shared_array_buffer(id, shared_array_buffer) } let array_buffer = array_buffer.try_cast::<v8::ArrayBuffer>()?; deser.inner.transfer_array_buffer(id, array_buffer); Ok(()) } #[op2(fast)] pub fn op_v8_read_double( #[cppgc] deser: &Deserializer, ) -> Result<f64, JsErrorBox> { let mut double = 0f64; if !deser.inner.read_double(&mut double) { return Err(JsErrorBox::type_error("ReadDouble() failed")); } Ok(double) } #[op2(nofast)] pub fn op_v8_read_header( scope: &mut v8::PinScope<'_, '_>, #[cppgc] deser: &Deserializer, ) -> bool { let context = scope.get_current_context(); let res = deser.inner.read_header(context); res.unwrap_or_default() } #[op2(fast)] #[number] pub fn op_v8_read_raw_bytes( #[cppgc] deser: &Deserializer, #[number] length: usize, ) -> usize { let Some(buf_ptr) = deser.buf.ptr else { return 0; }; if let Some(buf) = deser.inner.read_raw_bytes(length) { let ptr = buf.as_ptr(); (ptr as usize) - (buf_ptr.as_ptr() as usize) } else { 0 } } #[op2(fast)] pub fn op_v8_read_uint32( #[cppgc] deser: &Deserializer, ) -> Result<u32, JsErrorBox> { let mut value = 0; if !deser.inner.read_uint32(&mut value) { return Err(JsErrorBox::type_error("ReadUint32() failed")); } Ok(value) } #[op2] #[serde] pub fn op_v8_read_uint64( #[cppgc] deser: &Deserializer, ) -> Result<(u32, u32), JsErrorBox> { let mut val = 0; if !deser.inner.read_uint64(&mut val) { return Err(JsErrorBox::type_error("ReadUint64() failed")); } Ok(((val >> 32) as u32, val as u32)) } #[op2(fast)] pub fn op_v8_get_wire_format_version(#[cppgc] deser: &Deserializer) -> u32 { deser.inner.get_wire_format_version() } #[op2(reentrant)] pub fn op_v8_read_value<'s>( scope: &mut v8::PinScope<'s, '_>, #[cppgc] deser: &Deserializer, ) -> v8::Local<'s, v8::Value> { let context = scope.get_current_context(); let val = deser.inner.read_value(context); val.unwrap_or_else(|| v8::null(scope).into()) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/dns.rs
ext/node/ops/dns.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::RefCell; use std::net::IpAddr; use std::net::SocketAddr; use std::rc::Rc; use std::str::FromStr; #[cfg(target_family = "windows")] use std::sync::OnceLock; use deno_core::OpState; use deno_core::op2; use deno_core::unsync::spawn_blocking; use deno_error::JsError; use deno_net::ops::NetPermToken; use deno_permissions::PermissionCheckError; use deno_permissions::PermissionsContainer; use hyper_util::client::legacy::connect::dns::GaiResolver; use hyper_util::client::legacy::connect::dns::Name; use socket2::SockAddr; use tower_service::Service; #[derive(Debug, thiserror::Error, JsError)] pub enum DnsError { #[class(type)] #[error(transparent)] AddrParseError(#[from] std::net::AddrParseError), #[class(inherit)] #[error(transparent)] Permission(#[from] PermissionCheckError), #[class(type)] #[error("Could not resolve the hostname \"{0}\"")] Resolution(String), #[class(inherit)] #[error("{0}")] Io( #[from] #[inherit] std::io::Error, ), #[class(generic)] #[error("{0}")] #[property("uv_errcode" = self.code())] RawUvErr(i32), #[cfg(not(any(unix, windows)))] #[class(generic)] #[error("Unsupported platform.")] UnsupportedPlatform, } impl DnsError { fn code(&self) -> i32 { match self { Self::RawUvErr(code) => *code, _ => 0, } } } #[cfg(target_family = "windows")] static WINSOCKET_INIT: OnceLock<i32> = OnceLock::new(); #[op2(async, stack_trace)] #[cppgc] pub async fn op_node_getaddrinfo( state: Rc<RefCell<OpState>>, #[string] hostname: String, port: Option<u16>, ) -> Result<NetPermToken, DnsError> { { let mut state_ = state.borrow_mut(); let permissions = state_.borrow_mut::<PermissionsContainer>(); permissions.check_net(&(hostname.as_str(), port), "node:dns.lookup()")?; } let mut resolver = GaiResolver::new(); let name = Name::from_str(&hostname) .map_err(|_| DnsError::Resolution(hostname.clone()))?; let resolved_ips = resolver .call(name) .await .map_err(|_| DnsError::Resolution(hostname.clone()))? .map(|addr| addr.ip().to_string()) .collect::<Vec<_>>(); Ok(NetPermToken { hostname, port, resolved_ips, }) } #[op2(async, stack_trace)] #[serde] pub async fn op_node_getnameinfo( state: Rc<RefCell<OpState>>, #[string] ip: String, #[smi] port: u16, ) -> Result<(String, String), DnsError> { { let mut state_ = state.borrow_mut(); let permissions = state_.borrow_mut::<PermissionsContainer>(); permissions .check_net(&(ip.as_str(), Some(port)), "node:dns.lookupService()")?; } let ip_addr: IpAddr = ip.parse()?; let socket_addr = SocketAddr::new(ip_addr, port); match spawn_blocking(move || getnameinfo(socket_addr)).await { Ok(result) => result, Err(err) => Err(DnsError::Io(err.into())), } } fn getnameinfo(socket_addr: SocketAddr) -> Result<(String, String), DnsError> { let sock: SockAddr = socket_addr.into(); let c_sockaddr = sock.as_ptr(); let c_sockaddr_len = sock.len(); #[cfg(unix)] { const NI_MAXSERV: u32 = 32; let mut c_host = [0_u8; libc::NI_MAXHOST as usize]; let mut c_service = [0_u8; NI_MAXSERV as usize]; // SAFETY: Calling getnameinfo let code = unsafe { libc::getnameinfo( c_sockaddr, c_sockaddr_len, c_host.as_mut_ptr() as _, c_host.len() as _, c_service.as_mut_ptr() as _, c_service.len() as _, libc::NI_NAMEREQD as _, ) }; assert_success(code)?; // SAFETY: c_host is initialized by getnameinfo on success. let host_cstr = unsafe { std::ffi::CStr::from_ptr(c_host.as_ptr() as _) }; // SAFETY: c_service is initialized by getnameinfo on success. let service_cstr = unsafe { std::ffi::CStr::from_ptr(c_service.as_ptr() as _) }; Ok(( host_cstr.to_string_lossy().into_owned(), service_cstr.to_string_lossy().into_owned(), )) } #[cfg(windows)] { use std::os::windows::ffi::OsStringExt; use winapi::shared::minwindef::MAKEWORD; use windows_sys::Win32::Networking::WinSock; // SAFETY: winapi call let wsa_startup_code = *WINSOCKET_INIT.get_or_init(|| unsafe { let mut wsa_data: WinSock::WSADATA = std::mem::zeroed(); WinSock::WSAStartup(MAKEWORD(2, 2), &mut wsa_data) }); assert_success(wsa_startup_code)?; let mut c_host = [0_u16; WinSock::NI_MAXHOST as usize]; let mut c_service = [0_u16; WinSock::NI_MAXSERV as usize]; // SAFETY: Calling getnameinfo let code = unsafe { WinSock::GetNameInfoW( c_sockaddr as _, c_sockaddr_len, c_host.as_mut_ptr() as _, c_host.len() as _, c_service.as_mut_ptr() as _, c_service.len() as _, WinSock::NI_NAMEREQD as _, ) }; assert_success(code)?; let host_str_len = c_host.iter().take_while(|&&c| c != 0).count(); let host_str = std::ffi::OsString::from_wide(&c_host[..host_str_len]) .to_string_lossy() .into_owned(); let service_str_len = c_service.iter().take_while(|&&c| c != 0).count(); let service_str = std::ffi::OsString::from_wide(&c_service[..service_str_len]) .to_string_lossy() .into_owned(); Ok((host_str, service_str)) } #[cfg(not(any(unix, windows)))] { Err(DnsError::UnsupportedPlatform) } } #[cfg(any(unix, windows))] fn assert_success(code: i32) -> Result<(), DnsError> { #[cfg(windows)] use windows_sys::Win32::Networking::WinSock; use crate::ops::constant; if code == 0 { return Ok(()); } #[cfg(unix)] let err = match code { libc::EAI_AGAIN => DnsError::RawUvErr(constant::UV_EAI_AGAIN), libc::EAI_BADFLAGS => DnsError::RawUvErr(constant::UV_EAI_BADFLAGS), libc::EAI_FAIL => DnsError::RawUvErr(constant::UV_EAI_FAIL), libc::EAI_FAMILY => DnsError::RawUvErr(constant::UV_EAI_FAMILY), libc::EAI_MEMORY => DnsError::RawUvErr(constant::UV_EAI_MEMORY), libc::EAI_NONAME => DnsError::RawUvErr(constant::UV_EAI_NONAME), libc::EAI_OVERFLOW => DnsError::RawUvErr(constant::UV_EAI_OVERFLOW), libc::EAI_SYSTEM => DnsError::Io(std::io::Error::last_os_error()), _ => DnsError::Io(std::io::Error::from_raw_os_error(code)), }; #[cfg(windows)] let err = match code { WinSock::WSATRY_AGAIN => DnsError::RawUvErr(constant::UV_EAI_AGAIN), WinSock::WSAEINVAL => DnsError::RawUvErr(constant::UV_EAI_BADFLAGS), WinSock::WSANO_RECOVERY => DnsError::RawUvErr(constant::UV_EAI_FAIL), WinSock::WSAEAFNOSUPPORT => DnsError::RawUvErr(constant::UV_EAI_FAMILY), WinSock::WSA_NOT_ENOUGH_MEMORY => { DnsError::RawUvErr(constant::UV_EAI_MEMORY) } WinSock::WSAHOST_NOT_FOUND => DnsError::RawUvErr(constant::UV_EAI_NONAME), WinSock::WSATYPE_NOT_FOUND => DnsError::RawUvErr(constant::UV_EAI_SERVICE), WinSock::WSAESOCKTNOSUPPORT => { DnsError::RawUvErr(constant::UV_EAI_SOCKTYPE) } _ => DnsError::Io(std::io::Error::from_raw_os_error(code)), }; Err(err) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/worker_threads.rs
ext/node/ops/worker_threads.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::path::Path; use std::path::PathBuf; use deno_core::OpState; use deno_core::op2; use deno_core::url::Url; use deno_error::JsErrorBox; use deno_permissions::PermissionsContainer; use crate::ExtNodeSys; use crate::NodeRequireLoaderRc; #[must_use = "the resolved return value to mitigate time-of-check to time-of-use issues"] fn ensure_read_permission<'a>( state: &mut OpState, file_path: Cow<'a, Path>, ) -> Result<Cow<'a, Path>, JsErrorBox> { let loader = state.borrow::<NodeRequireLoaderRc>().clone(); let permissions = state.borrow_mut::<PermissionsContainer>(); loader.ensure_read_permission(permissions, file_path) } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum WorkerThreadsFilenameError { #[class(inherit)] #[error(transparent)] Permission(JsErrorBox), #[class(inherit)] #[error("{0}")] UrlParse( #[from] #[inherit] url::ParseError, ), #[class(generic)] #[error("Relative path entries must start with '.' or '..'")] InvalidRelativeUrl, #[class(generic)] #[error("URL from Path-String")] UrlFromPathString, #[class(generic)] #[error("URL to Path-String")] UrlToPathString, #[class(generic)] #[error("URL to Path")] UrlToPath, #[class(generic)] #[error("File not found [{0:?}]")] FileNotFound(PathBuf), #[class(inherit)] #[error(transparent)] Fs( #[from] #[inherit] deno_io::fs::FsError, ), #[class(inherit)] #[error(transparent)] Io( #[from] #[inherit] std::io::Error, ), } // todo(dsherret): we should remove this and do all this work inside op_create_worker #[op2(stack_trace)] #[string] pub fn op_worker_threads_filename<TSys: ExtNodeSys + 'static>( state: &mut OpState, #[string] specifier: &str, ) -> Result<Option<String>, WorkerThreadsFilenameError> { if specifier.starts_with("data:") { return Ok(None); // use input } let url: Url = if specifier.starts_with("file:") { Url::parse(specifier)? } else { let path = Path::new(specifier); if path.is_relative() && !specifier.starts_with('.') { return Err(WorkerThreadsFilenameError::InvalidRelativeUrl); } let path = ensure_read_permission(state, Cow::Borrowed(path)) .map_err(WorkerThreadsFilenameError::Permission)?; let sys = state.borrow::<TSys>(); let canonicalized_path = deno_path_util::strip_unc_prefix(sys.fs_canonicalize(&path)?); Url::from_file_path(canonicalized_path) .map_err(|_| WorkerThreadsFilenameError::UrlFromPathString)? }; let url_path = url .to_file_path() .map_err(|_| WorkerThreadsFilenameError::UrlToPathString)?; let url_path = ensure_read_permission(state, Cow::Owned(url_path)) .map_err(WorkerThreadsFilenameError::Permission)?; let sys = state.borrow::<TSys>(); if !sys.fs_exists_no_err(&url_path) { return Err(WorkerThreadsFilenameError::FileNotFound( url_path.to_path_buf(), )); } Ok(Some(url.into())) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/util.rs
ext/node/ops/util.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::path::Path; use deno_core::OpState; use deno_core::ResourceHandle; use deno_core::ResourceHandleFd; use deno_core::op2; use deno_core::v8; use deno_error::JsErrorBox; use node_resolver::InNpmPackageChecker; use node_resolver::NpmPackageFolderResolver; use crate::ExtNodeSys; use crate::NodeResolverRc; #[repr(u32)] enum HandleType { #[allow(dead_code)] Tcp = 0, Tty, #[allow(dead_code)] Udp, File, Pipe, Unknown, } #[op2(fast)] pub fn op_node_guess_handle_type(state: &mut OpState, rid: u32) -> u32 { let handle = match state.resource_table.get_handle(rid) { Ok(handle) => handle, _ => return HandleType::Unknown as u32, }; let handle_type = match handle { ResourceHandle::Fd(handle) => guess_handle_type(handle), _ => HandleType::Unknown, }; handle_type as u32 } #[cfg(windows)] fn guess_handle_type(handle: ResourceHandleFd) -> HandleType { use winapi::um::consoleapi::GetConsoleMode; use winapi::um::fileapi::GetFileType; use winapi::um::winbase::FILE_TYPE_CHAR; use winapi::um::winbase::FILE_TYPE_DISK; use winapi::um::winbase::FILE_TYPE_PIPE; // SAFETY: Call to win32 fileapi. `handle` is a valid fd. match unsafe { GetFileType(handle) } { FILE_TYPE_DISK => HandleType::File, FILE_TYPE_CHAR => { let mut mode = 0; // SAFETY: Call to win32 consoleapi. `handle` is a valid fd. // `mode` is a valid pointer. if unsafe { GetConsoleMode(handle, &mut mode) } == 1 { HandleType::Tty } else { HandleType::File } } FILE_TYPE_PIPE => HandleType::Pipe, _ => HandleType::Unknown, } } #[cfg(unix)] fn guess_handle_type(handle: ResourceHandleFd) -> HandleType { use std::io::IsTerminal; // SAFETY: The resource remains open for the duration of borrow_raw. if unsafe { std::os::fd::BorrowedFd::borrow_raw(handle).is_terminal() } { return HandleType::Tty; } // SAFETY: It is safe to zero-initialize a `libc::stat` struct. let mut s = unsafe { std::mem::zeroed() }; // SAFETY: Call to libc if unsafe { libc::fstat(handle, &mut s) } == 1 { return HandleType::Unknown; } match s.st_mode & 61440 { libc::S_IFREG | libc::S_IFCHR => HandleType::File, libc::S_IFIFO => HandleType::Pipe, libc::S_IFSOCK => HandleType::Tcp, _ => HandleType::Unknown, } } #[op2(fast)] pub fn op_node_view_has_buffer(buffer: v8::Local<v8::ArrayBufferView>) -> bool { buffer.has_buffer() } /// Checks if the current call site is from a dependency package. #[op2(fast)] pub fn op_node_call_is_from_dependency< TInNpmPackageChecker: InNpmPackageChecker + 'static, TNpmPackageFolderResolver: NpmPackageFolderResolver + 'static, TSys: ExtNodeSys + 'static, >( state: &mut OpState, scope: &mut v8::PinScope<'_, '_>, ) -> bool { // non internal call site should appear in < 20 frames let Some(stack_trace) = v8::StackTrace::current_stack_trace(scope, 20) else { return false; }; let mut only_internal = true; for i in 0..stack_trace.get_frame_count() { let Some(frame) = stack_trace.get_frame(scope, i) else { continue; }; if !frame.is_user_javascript() { continue; } let Some(script) = frame.get_script_name(scope) else { continue; }; let name = script.to_rust_string_lossy(scope); if name.starts_with("node:") || name.starts_with("ext:") { continue; } else { only_internal = false; } if name.starts_with("https:") || name.contains("/node_modules/") || name.contains(r"\node_modules\") { return true; } let Ok(specifier) = url::Url::parse(&name) else { continue; }; if only_internal { return true; } return state.borrow::<NodeResolverRc< TInNpmPackageChecker, TNpmPackageFolderResolver, TSys, >>().in_npm_package(&specifier); } only_internal } #[op2(fast)] pub fn op_node_in_npm_package< TInNpmPackageChecker: InNpmPackageChecker + 'static, TNpmPackageFolderResolver: NpmPackageFolderResolver + 'static, TSys: ExtNodeSys + 'static, >( state: &mut OpState, #[string] path: &str, ) -> bool { let specifier = if deno_path_util::specifier_has_uri_scheme(path) { match url::Url::parse(path) { Ok(url) => url, Err(_) => return false, } } else { match deno_path_util::url_from_file_path(Path::new(path)) { Ok(url) => url, Err(_) => return false, } }; state.borrow::<NodeResolverRc< TInNpmPackageChecker, TNpmPackageFolderResolver, TSys, >>().in_npm_package(&specifier) } #[op2] pub fn op_node_get_own_non_index_properties<'s>( scope: &mut v8::PinScope<'s, '_>, obj: v8::Local<'s, v8::Object>, #[smi] filter: u32, ) -> Result<v8::Local<'s, v8::Array>, JsErrorBox> { let mut property_filter = v8::PropertyFilter::ALL_PROPERTIES; if filter & 1 << 0 != 0 { property_filter = property_filter | v8::PropertyFilter::ONLY_WRITABLE; } if filter & 1 << 1 != 0 { property_filter = property_filter | v8::PropertyFilter::ONLY_ENUMERABLE; } if filter & 1 << 2 != 0 { property_filter = property_filter | v8::PropertyFilter::ONLY_CONFIGURABLE; } if filter & 1 << 3 != 0 { property_filter = property_filter | v8::PropertyFilter::SKIP_STRINGS; } if filter & 1 << 4 != 0 { property_filter = property_filter | v8::PropertyFilter::SKIP_SYMBOLS; } obj .get_property_names( scope, v8::GetPropertyNamesArgs { index_filter: v8::IndexFilter::SkipIndices, property_filter, key_conversion: v8::KeyConversionMode::NoNumbers, mode: v8::KeyCollectionMode::OwnOnly, }, ) .ok_or_else(|| { JsErrorBox::type_error("Failed to get own non-index properties") }) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/mod.rs
ext/node/ops/mod.rs
// Copyright 2018-2025 the Deno authors. MIT license. pub mod blocklist; pub mod buffer; pub mod constant; pub mod crypto; pub mod dns; pub mod fs; pub mod handle_wrap; pub mod http; pub mod http2; pub mod idna; pub mod inspector; pub mod ipc; pub mod os; pub mod perf_hooks; pub mod process; pub mod require; pub mod sqlite; pub mod tls; pub mod util; pub mod v8; pub mod vm; pub mod winerror; pub mod worker_threads; pub mod zlib;
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/constant.rs
ext/node/ops/constant.rs
// Copyright 2018-2025 the Deno authors. MIT license. use deno_core::op2; use serde::Serialize; #[derive(Debug, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] /// https://github.com/nodejs/node/blob/ce4a16f50ae289bf6c7834b592ca47ad4634dd79/src/node_constants.cc#L1044-L1225 pub struct FsConstants { uv_fs_symlink_dir: i32, uv_fs_symlink_junction: i32, o_rdonly: i32, o_wronly: i32, o_rdwr: i32, uv_dirent_unknown: i32, uv_dirent_file: i32, uv_dirent_dir: i32, uv_dirent_link: i32, uv_dirent_fifo: i32, uv_dirent_socket: i32, uv_dirent_char: i32, uv_dirent_block: i32, #[serde(skip_serializing_if = "Option::is_none")] s_ifmt: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_ifreg: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_ifdir: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_ifchr: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_ifblk: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_ififo: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_iflnk: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_ifsock: Option<i32>, o_creat: i32, o_excl: i32, uv_fs_o_filemap: i32, #[serde(skip_serializing_if = "Option::is_none")] o_noctty: Option<i32>, o_trunc: i32, o_append: i32, #[serde(skip_serializing_if = "Option::is_none")] o_directory: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] o_noatime: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] o_nofollow: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] o_sync: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] o_dsync: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] o_symlink: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] o_direct: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] o_nonblock: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_irwxu: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_irusr: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_iwusr: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_ixusr: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_irwxg: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_irgrp: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_iwgrp: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_ixgrp: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_irwxo: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_iroth: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_iwoth: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] s_ixoth: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] f_ok: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] r_ok: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] w_ok: Option<i32>, #[serde(skip_serializing_if = "Option::is_none")] x_ok: Option<i32>, uv_fs_copyfile_excl: i32, copyfile_excl: i32, uv_fs_copyfile_ficlone: i32, copyfile_ficlone: i32, uv_fs_copyfile_ficlone_force: i32, copyfile_ficlone_force: i32, } // https://github.com/nodejs/node/blob/9d2368f64329bf194c4e82b349e76fdad879d32a/deps/uv/include/uv.h#L1616-L1626 pub const UV_FS_SYMLINK_DIR: i32 = 1; pub const UV_FS_SYMLINK_JUNCTION: i32 = 2; // https://github.com/nodejs/node/blob/9d2368f64329bf194c4e82b349e76fdad879d32a/deps/uv/include/uv.h#L1254-L1263 pub const UV_DIRENT_UNKNOWN: i32 = 0; pub const UV_DIRENT_FILE: i32 = 1; pub const UV_DIRENT_DIR: i32 = 2; pub const UV_DIRENT_LINK: i32 = 3; pub const UV_DIRENT_FIFO: i32 = 4; pub const UV_DIRENT_SOCKET: i32 = 5; pub const UV_DIRENT_CHAR: i32 = 6; pub const UV_DIRENT_BLOCK: i32 = 7; // https://github.com/nodejs/node/blob/9d2368f64329bf194c4e82b349e76fdad879d32a/deps/uv/include/uv.h#L1485-L1501 pub const UV_FS_COPYFILE_EXCL: i32 = 1; pub const UV_FS_COPYFILE_FICLONE: i32 = 2; pub const UV_FS_COPYFILE_FICLONE_FORCE: i32 = 4; // https://github.com/nodejs/node/blob/591ba692bfe30408e6a67397e7d18bfa1b9c3561/deps/uv/include/uv/errno.h#L35-L48 pub const UV_EAI_ADDRFAMILY: i32 = -3000; pub const UV_EAI_AGAIN: i32 = -3001; pub const UV_EAI_BADFLAGS: i32 = -3002; pub const UV_EAI_CANCELED: i32 = -3003; pub const UV_EAI_FAIL: i32 = -3004; pub const UV_EAI_FAMILY: i32 = -3005; pub const UV_EAI_MEMORY: i32 = -3006; pub const UV_EAI_NODATA: i32 = -3007; pub const UV_EAI_NONAME: i32 = -3008; pub const UV_EAI_OVERFLOW: i32 = -3009; pub const UV_EAI_SERVICE: i32 = -3010; pub const UV_EAI_SOCKTYPE: i32 = -3011; pub const UV_EAI_BADHINTS: i32 = -3013; pub const UV_EAI_PROTOCOL: i32 = -3014; #[cfg(unix)] /// https://github.com/nodejs/node/blob/9d2368f64329bf194c4e82b349e76fdad879d32a/deps/uv/include/uv/unix.h#L506 pub const UV_FS_O_FILEMAP: i32 = 0; #[cfg(not(unix))] /// https://github.com/nodejs/node/blob/4dafa7747f7d2804aed3f3400d04f1ec6af24160/deps/uv/include/uv/win.h#L678 pub const UV_FS_O_FILEMAP: i32 = 0x20000000; impl Default for FsConstants { fn default() -> Self { FsConstants { uv_fs_symlink_dir: UV_FS_SYMLINK_DIR, uv_fs_symlink_junction: UV_FS_SYMLINK_JUNCTION, o_rdonly: libc::O_RDONLY, o_wronly: libc::O_WRONLY, o_rdwr: libc::O_RDWR, uv_dirent_unknown: UV_DIRENT_UNKNOWN, uv_dirent_file: UV_DIRENT_FILE, uv_dirent_dir: UV_DIRENT_DIR, uv_dirent_link: UV_DIRENT_LINK, uv_dirent_fifo: UV_DIRENT_FIFO, uv_dirent_socket: UV_DIRENT_SOCKET, uv_dirent_char: UV_DIRENT_CHAR, uv_dirent_block: UV_DIRENT_BLOCK, s_ifmt: None, s_ifreg: None, s_ifdir: None, s_ifchr: None, s_ifblk: None, s_ififo: None, s_iflnk: None, s_ifsock: None, o_creat: libc::O_CREAT, o_excl: libc::O_EXCL, uv_fs_o_filemap: UV_FS_O_FILEMAP, o_noctty: None, o_trunc: libc::O_TRUNC, o_append: libc::O_APPEND, o_directory: None, o_noatime: None, o_nofollow: None, o_sync: None, o_dsync: None, o_symlink: None, o_direct: None, o_nonblock: None, s_irwxu: None, s_irusr: None, s_iwusr: None, s_ixusr: None, s_irwxg: None, s_irgrp: None, s_iwgrp: None, s_ixgrp: None, s_irwxo: None, s_iroth: None, s_iwoth: None, s_ixoth: None, f_ok: None, r_ok: None, w_ok: None, x_ok: None, uv_fs_copyfile_excl: UV_FS_COPYFILE_EXCL, copyfile_excl: UV_FS_COPYFILE_EXCL, uv_fs_copyfile_ficlone: UV_FS_COPYFILE_FICLONE, copyfile_ficlone: UV_FS_COPYFILE_FICLONE, uv_fs_copyfile_ficlone_force: UV_FS_COPYFILE_FICLONE_FORCE, copyfile_ficlone_force: UV_FS_COPYFILE_FICLONE_FORCE, } } } #[cfg(unix)] fn common_unix_fs_constants() -> FsConstants { FsConstants { s_ifmt: Some(libc::S_IFMT as i32), s_ifreg: Some(libc::S_IFREG as i32), s_ifdir: Some(libc::S_IFDIR as i32), s_ifchr: Some(libc::S_IFCHR as i32), s_ifblk: Some(libc::S_IFBLK as i32), s_ififo: Some(libc::S_IFIFO as i32), s_iflnk: Some(libc::S_IFLNK as i32), s_ifsock: Some(libc::S_IFSOCK as i32), o_noctty: Some(libc::O_NOCTTY), o_directory: Some(libc::O_DIRECTORY), o_nofollow: Some(libc::O_NOFOLLOW), o_sync: Some(libc::O_SYNC), o_dsync: Some(libc::O_DSYNC), o_nonblock: Some(libc::O_NONBLOCK), s_irwxu: Some(libc::S_IRWXU as i32), s_irusr: Some(libc::S_IRUSR as i32), s_iwusr: Some(libc::S_IWUSR as i32), s_ixusr: Some(libc::S_IXUSR as i32), s_irwxg: Some(libc::S_IRWXG as i32), s_irgrp: Some(libc::S_IRGRP as i32), s_iwgrp: Some(libc::S_IWGRP as i32), s_ixgrp: Some(libc::S_IXGRP as i32), s_irwxo: Some(libc::S_IRWXO as i32), s_iroth: Some(libc::S_IROTH as i32), s_iwoth: Some(libc::S_IWOTH as i32), s_ixoth: Some(libc::S_IXOTH as i32), f_ok: Some(libc::F_OK), r_ok: Some(libc::R_OK), w_ok: Some(libc::W_OK), x_ok: Some(libc::X_OK), ..Default::default() } } #[cfg(target_os = "macos")] #[op2] #[serde] pub fn op_node_fs_constants() -> FsConstants { let mut constants = common_unix_fs_constants(); constants.o_symlink = Some(libc::O_SYMLINK); constants } #[cfg(any(target_os = "android", target_os = "linux"))] #[op2] #[serde] pub fn op_node_fs_constants() -> FsConstants { let mut constants = common_unix_fs_constants(); constants.o_noatime = Some(libc::O_NOATIME); constants.o_direct = Some(libc::O_DIRECT); constants } #[cfg(windows)] #[op2] #[serde] pub fn op_node_fs_constants() -> FsConstants { let mut constants = FsConstants::default(); // https://github.com/nodejs/node/blob/4dafa7747f7d2804aed3f3400d04f1ec6af24160/deps/uv/include/uv/win.h#L65-L68 // https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_stat_lx_information const S_IFIFO: i32 = 0x1000; // https://github.com/nodejs/node/blob/4dafa7747f7d2804aed3f3400d04f1ec6af24160/deps/uv/include/uv/win.h#L61-L63 const S_IFLNK: i32 = 0xA000; // https://github.com/nodejs/node/blob/4dafa7747f7d2804aed3f3400d04f1ec6af24160/deps/uv/include/uv/win.h#L661-L672 const F_OK: i32 = 0; const R_OK: i32 = 4; const W_OK: i32 = 2; const X_OK: i32 = 1; // https://github.com/nodejs/node/blob/9d2368f64329bf194c4e82b349e76fdad879d32a/src/node_constants.cc#L52-L57 constants.s_irusr = Some(libc::S_IREAD); constants.s_iwusr = Some(libc::S_IWRITE); constants.s_ifmt = Some(libc::S_IFMT); constants.s_ifreg = Some(libc::S_IFREG); constants.s_ifdir = Some(libc::S_IFDIR); constants.s_ifchr = Some(libc::S_IFCHR); constants.f_ok = Some(F_OK); constants.r_ok = Some(R_OK); constants.w_ok = Some(W_OK); constants.x_ok = Some(X_OK); constants.s_iflnk = Some(S_IFLNK); constants.s_ififo = Some(S_IFIFO); constants }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/require.rs
ext/node/ops/require.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::path::Path; use std::path::PathBuf; use std::rc::Rc; use boxed_error::Boxed; use deno_core::FastString; use deno_core::JsRuntimeInspector; use deno_core::OpState; use deno_core::op2; use deno_core::url::Url; use deno_core::v8; use deno_error::JsErrorBox; use deno_package_json::PackageJsonRc; use deno_path_util::normalize_path; use deno_path_util::url_from_file_path; use deno_path_util::url_to_file_path; use deno_permissions::PermissionsContainer; use node_resolver::InNpmPackageChecker; use node_resolver::NodeResolutionKind; use node_resolver::NpmPackageFolderResolver; use node_resolver::ResolutionMode; use node_resolver::UrlOrPath; use node_resolver::UrlOrPathRef; use node_resolver::cache::NodeResolutionThreadLocalCache; use node_resolver::errors::PackageJsonLoadError; use sys_traits::FsMetadataValue; use crate::ExtNodeSys; use crate::NodeRequireLoaderRc; use crate::NodeResolverRc; use crate::PackageJsonResolverRc; #[must_use = "the resolved return value to mitigate time-of-check to time-of-use issues"] fn ensure_read_permission<'a>( state: &mut OpState, file_path: Cow<'a, Path>, ) -> Result<Cow<'a, Path>, JsErrorBox> { let loader = state.borrow::<NodeRequireLoaderRc>().clone(); let permissions = state.borrow_mut::<PermissionsContainer>(); loader.ensure_read_permission(permissions, file_path) } #[derive(Debug, Boxed, deno_error::JsError)] pub struct RequireError(pub Box<RequireErrorKind>); #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum RequireErrorKind { #[class(inherit)] #[error(transparent)] UrlParse( #[from] #[inherit] url::ParseError, ), #[class(inherit)] #[error(transparent)] Permission(#[inherit] JsErrorBox), #[class(generic)] #[properties(inherit)] #[error(transparent)] PackageExportsResolve( #[from] node_resolver::errors::PackageExportsResolveError, ), #[class(generic)] #[properties(inherit)] #[error(transparent)] PackageJsonLoad(#[from] node_resolver::errors::PackageJsonLoadError), #[class(generic)] #[properties(inherit)] #[error(transparent)] PackageImportsResolve( #[from] node_resolver::errors::PackageImportsResolveError, ), #[class(generic)] #[properties(inherit)] #[error(transparent)] FilePathConversion(#[from] deno_path_util::UrlToFilePathError), #[class(generic)] #[properties(inherit)] #[error(transparent)] UrlConversion(#[from] deno_path_util::PathToUrlError), #[class(inherit)] #[error(transparent)] Fs( #[from] #[inherit] deno_io::fs::FsError, ), #[class(inherit)] #[error(transparent)] Io( #[from] #[inherit] std::io::Error, ), #[class(inherit)] #[error(transparent)] ReadModule( #[from] #[inherit] JsErrorBox, ), #[class(inherit)] #[error(transparent)] UnableToGetCwd(UnableToGetCwdError), } #[derive(Debug, thiserror::Error, deno_error::JsError)] #[error("Unable to get CWD")] #[class(inherit)] pub struct UnableToGetCwdError(#[source] pub std::io::Error); #[op2] #[serde] pub fn op_require_init_paths() -> Vec<String> { // todo(dsherret): this code is node compat mode specific and // we probably don't want it for small mammal, so ignore it for now // let (home_dir, node_path) = if cfg!(windows) { // ( // std::env::var("USERPROFILE").unwrap_or_else(|_| "".into()), // std::env::var("NODE_PATH").unwrap_or_else(|_| "".into()), // ) // } else { // ( // std::env::var("HOME").unwrap_or_else(|_| "".into()), // std::env::var("NODE_PATH").unwrap_or_else(|_| "".into()), // ) // }; // let mut prefix_dir = std::env::current_exe().unwrap(); // if cfg!(windows) { // prefix_dir = prefix_dir.join("..").join("..") // } else { // prefix_dir = prefix_dir.join("..") // } // let mut paths = vec![prefix_dir.join("lib").join("node")]; // if !home_dir.is_empty() { // paths.insert(0, PathBuf::from(&home_dir).join(".node_libraries")); // paths.insert(0, PathBuf::from(&home_dir).join(".nod_modules")); // } // let mut paths = paths // .into_iter() // .map(|p| p.to_string_lossy().into_owned()) // .collect(); // if !node_path.is_empty() { // let delimiter = if cfg!(windows) { ";" } else { ":" }; // let mut node_paths: Vec<String> = node_path // .split(delimiter) // .filter(|e| !e.is_empty()) // .map(|s| s.to_string()) // .collect(); // node_paths.append(&mut paths); // paths = node_paths; // } vec![] } #[op2(stack_trace)] #[serde] pub fn op_require_node_module_paths<TSys: ExtNodeSys + 'static>( state: &mut OpState, #[string] from: &str, ) -> Result<Vec<String>, RequireError> { let sys = state.borrow::<TSys>(); // Guarantee that "from" is absolute. let from = if from.starts_with("file:///") { Cow::Owned(url_to_file_path(&Url::parse(from)?)?) } else { let current_dir = &sys .env_current_dir() .map_err(|e| RequireErrorKind::UnableToGetCwd(UnableToGetCwdError(e)))?; normalize_path(Cow::Owned(current_dir.join(from))) }; if cfg!(windows) { // return root node_modules when path is 'D:\\'. let from_str = from.to_str().unwrap(); if from_str.len() >= 3 { let bytes = from_str.as_bytes(); if bytes[from_str.len() - 1] == b'\\' && bytes[from_str.len() - 2] == b':' { let p = format!("{}node_modules", from_str); return Ok(vec![p]); } } } else { // Return early not only to avoid unnecessary work, but to *avoid* returning // an array of two items for a root: [ '//node_modules', '/node_modules' ] if from.to_string_lossy() == "/" { return Ok(vec!["/node_modules".to_string()]); } } let loader = state.borrow::<NodeRequireLoaderRc>(); Ok(loader.resolve_require_node_module_paths(&from)) } #[op2] #[string] pub fn op_require_proxy_path(#[string] filename: &str) -> Option<String> { // Allow a directory to be passed as the filename let trailing_slash = if cfg!(windows) { // Node also counts a trailing forward slash as a // directory for node on Windows, but not backslashes // on non-Windows platforms filename.ends_with('\\') || filename.ends_with('/') } else { filename.ends_with('/') }; if trailing_slash { let p = Path::new(filename); Some(p.join("noop.js").to_string_lossy().into_owned()) } else { None // filename as-is } } #[op2(fast)] pub fn op_require_is_request_relative(#[string] request: &str) -> bool { if request.starts_with("./") || request.starts_with("../") || request == ".." { return true; } if cfg!(windows) { if request.starts_with(".\\") { return true; } if request.starts_with("..\\") { return true; } } false } #[op2] #[string] pub fn op_require_resolve_deno_dir< TInNpmPackageChecker: InNpmPackageChecker + 'static, TNpmPackageFolderResolver: NpmPackageFolderResolver + 'static, TSys: ExtNodeSys + 'static, >( state: &mut OpState, #[string] request: &str, #[string] parent_filename: &str, ) -> Result<Option<String>, deno_path_util::PathToUrlError> { let resolver = state.borrow::<NodeResolverRc< TInNpmPackageChecker, TNpmPackageFolderResolver, TSys, >>(); let path = Path::new(parent_filename); Ok( resolver .resolve_package_folder_from_package( request, &UrlOrPathRef::from_path(path), ) .ok() .map(|p| p.to_string_lossy().into_owned()), ) } #[op2(fast)] pub fn op_require_is_deno_dir_package< TInNpmPackageChecker: InNpmPackageChecker + 'static, TNpmPackageFolderResolver: NpmPackageFolderResolver + 'static, TSys: ExtNodeSys + 'static, >( state: &mut OpState, #[string] path: &str, ) -> bool { let resolver = state.borrow::<NodeResolverRc< TInNpmPackageChecker, TNpmPackageFolderResolver, TSys, >>(); match deno_path_util::url_from_file_path(Path::new(path)) { Ok(specifier) => resolver.in_npm_package(&specifier), Err(_) => false, } } #[op2] #[serde] pub fn op_require_resolve_lookup_paths( #[string] request: &str, #[serde] maybe_parent_paths: Option<Vec<String>>, #[string] parent_filename: &str, ) -> Option<Vec<String>> { if !request.starts_with('.') || (request.len() > 1 && !request.starts_with("..") && !request.starts_with("./") && (!cfg!(windows) || !request.starts_with(".\\"))) { let module_paths = vec![]; let mut paths = module_paths; if let Some(mut parent_paths) = maybe_parent_paths && !parent_paths.is_empty() { paths.append(&mut parent_paths); } if !paths.is_empty() { return Some(paths); } else { return None; } } // In REPL, parent.filename is null. // if (!parent || !parent.id || !parent.filename) { // // Make require('./path/to/foo') work - normally the path is taken // // from realpath(__filename) but in REPL there is no filename // const mainPaths = ['.']; // debug('looking for %j in %j', request, mainPaths); // return mainPaths; // } let p = Path::new(parent_filename); Some(vec![p.parent().unwrap().to_string_lossy().into_owned()]) } #[op2(fast)] pub fn op_require_path_is_absolute(#[string] p: &str) -> bool { Path::new(p).is_absolute() } #[op2(fast, stack_trace)] pub fn op_require_stat<TSys: ExtNodeSys + 'static>( state: &mut OpState, #[string] path: &str, ) -> Result<i32, JsErrorBox> { let path = Cow::Borrowed(Path::new(path)); let path = if path.ends_with("node_modules") { // skip stat permission checks for node_modules directories // because they're noisy and it's fine path } else { ensure_read_permission(state, path)? }; let sys = state.borrow::<TSys>(); if let Ok(metadata) = sys.fs_metadata(&path) { if metadata.file_type().is_file() { return Ok(0); } else { return Ok(1); } } Ok(-1) } #[op2(stack_trace)] #[string] pub fn op_require_real_path<TSys: ExtNodeSys + 'static>( state: &mut OpState, #[string] request: &str, ) -> Result<String, RequireError> { let path = Cow::Borrowed(Path::new(request)); let path = ensure_read_permission(state, path) .map_err(RequireErrorKind::Permission)?; let sys = state.borrow::<TSys>(); let canonicalized_path = deno_path_util::strip_unc_prefix(match sys.fs_canonicalize(&path) { Ok(path) => path, Err(err) => { if path.ends_with("$deno$eval.cjs") || path.ends_with("$deno$eval.cts") || path.ends_with("$deno$stdin.cjs") || path.ends_with("$deno$stdin.cts") { path.to_path_buf() } else { return Err(RequireErrorKind::Io(err).into_box()); } } }); Ok(canonicalized_path.to_string_lossy().into_owned()) } fn path_resolve<'a>(mut parts: impl Iterator<Item = &'a str>) -> PathBuf { let mut p = PathBuf::from(parts.next().unwrap()); for part in parts { p = p.join(part); } normalize_path(Cow::Owned(p)).into_owned() } #[op2] #[string] pub fn op_require_path_resolve(#[serde] parts: Vec<String>) -> String { path_resolve(parts.iter().map(|s| s.as_str())) .to_string_lossy() .into_owned() } #[op2] #[string] pub fn op_require_path_dirname( #[string] request: &str, ) -> Result<String, JsErrorBox> { let p = Path::new(request); if let Some(parent) = p.parent() { Ok(parent.to_string_lossy().into_owned()) } else { Err(JsErrorBox::generic("Path doesn't have a parent")) } } #[op2] #[string] pub fn op_require_path_basename( #[string] request: &str, ) -> Result<String, JsErrorBox> { let p = Path::new(request); if let Some(path) = p.file_name() { Ok(path.to_string_lossy().into_owned()) } else { Err(JsErrorBox::generic("Path doesn't have a file name")) } } #[op2(stack_trace)] #[string] pub fn op_require_try_self< TInNpmPackageChecker: InNpmPackageChecker + 'static, TNpmPackageFolderResolver: NpmPackageFolderResolver + 'static, TSys: ExtNodeSys + 'static, >( state: &mut OpState, #[string] parent_path: &str, #[string] request: &str, ) -> Result<Option<String>, RequireError> { let pkg_json_resolver = state.borrow::<PackageJsonResolverRc<TSys>>(); let pkg = pkg_json_resolver .get_closest_package_json(Path::new(parent_path)) .ok() .flatten(); let Some(pkg) = pkg else { return Ok(None); }; if pkg.exports.is_none() { return Ok(None); } let Some(pkg_name) = &pkg.name else { return Ok(None); }; let expansion = if request == pkg_name { Cow::Borrowed(".") } else if let Some(slash_with_export) = request .strip_prefix(pkg_name) .filter(|t| t.starts_with('/')) { Cow::Owned(format!(".{}", slash_with_export)) } else { return Ok(None); }; if let Some(exports) = &pkg.exports { let node_resolver = state.borrow::<NodeResolverRc< TInNpmPackageChecker, TNpmPackageFolderResolver, TSys, >>(); let referrer = UrlOrPathRef::from_path(&pkg.path); // invalidate the resolution cache in case things have changed NodeResolutionThreadLocalCache::clear(); let r = node_resolver.package_exports_resolve( &pkg.path, &expansion, exports, Some(&referrer), ResolutionMode::Require, node_resolver.require_conditions(), NodeResolutionKind::Execution, )?; Ok(Some(url_or_path_to_string(r)?)) } else { Ok(None) } } #[op2(stack_trace)] #[to_v8] pub fn op_require_read_file( state: &mut OpState, #[string] file_path: &str, ) -> Result<FastString, RequireError> { let file_path = Cow::Borrowed(Path::new(file_path)); // todo(dsherret): there's multiple borrows to NodeRequireLoaderRc here let file_path = ensure_read_permission(state, file_path) .map_err(RequireErrorKind::Permission)?; let loader = state.borrow::<NodeRequireLoaderRc>(); loader .load_text_file_lossy(&file_path) .map_err(|e| RequireErrorKind::ReadModule(e).into_box()) } #[op2] #[string] pub fn op_require_as_file_path(#[string] file_or_url: &str) -> Option<String> { if let Ok(url) = Url::parse(file_or_url) && let Ok(p) = url.to_file_path() { return Some(p.to_string_lossy().into_owned()); } None // use original input } #[op2(stack_trace)] #[string] pub fn op_require_resolve_exports< TInNpmPackageChecker: InNpmPackageChecker + 'static, TNpmPackageFolderResolver: NpmPackageFolderResolver + 'static, TSys: ExtNodeSys + 'static, >( state: &mut OpState, uses_local_node_modules_dir: bool, #[string] modules_path_str: &str, #[string] _request: &str, #[string] name: &str, #[string] expansion: &str, #[string] parent_path: &str, ) -> Result<Option<String>, RequireError> { let sys = state.borrow::<TSys>(); let node_resolver = state.borrow::<NodeResolverRc< TInNpmPackageChecker, TNpmPackageFolderResolver, TSys, >>(); let pkg_json_resolver = state.borrow::<PackageJsonResolverRc<TSys>>(); let modules_path = Path::new(&modules_path_str); let modules_specifier = deno_path_util::url_from_file_path(modules_path)?; let pkg_path = if node_resolver.in_npm_package(&modules_specifier) && !uses_local_node_modules_dir { Cow::Borrowed(modules_path) } else { let mod_dir = path_resolve([modules_path_str, name].into_iter()); if sys.fs_is_dir_no_err(&mod_dir) { Cow::Owned(mod_dir) } else { Cow::Borrowed(modules_path) } }; let Some(pkg) = pkg_json_resolver.load_package_json(&pkg_path.join("package.json"))? else { return Ok(None); }; let Some(exports) = &pkg.exports else { return Ok(None); }; let referrer = if parent_path.is_empty() { None } else { Some(PathBuf::from(parent_path)) }; NodeResolutionThreadLocalCache::clear(); let r = node_resolver.package_exports_resolve( &pkg.path, &format!(".{expansion}"), exports, referrer .as_ref() .map(|r| UrlOrPathRef::from_path(r)) .as_ref(), ResolutionMode::Require, node_resolver.require_conditions(), NodeResolutionKind::Execution, )?; Ok(Some(url_or_path_to_string(r)?)) } deno_error::js_error_wrapper!( PackageJsonLoadError, JsPackageJsonLoadError, "Error" ); #[op2(fast)] pub fn op_require_is_maybe_cjs( state: &mut OpState, #[string] filename: &str, ) -> Result<bool, JsPackageJsonLoadError> { let filename = Path::new(filename); let Ok(url) = url_from_file_path(filename) else { return Ok(false); }; let loader = state.borrow::<NodeRequireLoaderRc>(); loader.is_maybe_cjs(&url).map_err(Into::into) } #[op2(stack_trace)] #[serde] pub fn op_require_read_package_scope<TSys: ExtNodeSys + 'static>( state: &mut OpState, #[string] package_json_path: &str, ) -> Option<PackageJsonRc> { let pkg_json_resolver = state.borrow::<PackageJsonResolverRc<TSys>>(); let package_json_path = Path::new(package_json_path); if package_json_path.file_name() != Some("package.json".as_ref()) { // permissions: do not allow reading a non-package.json file return None; } pkg_json_resolver .load_package_json(package_json_path) .ok() .flatten() } #[op2(stack_trace)] #[string] pub fn op_require_package_imports_resolve< TInNpmPackageChecker: InNpmPackageChecker + 'static, TNpmPackageFolderResolver: NpmPackageFolderResolver + 'static, TSys: ExtNodeSys + 'static, >( state: &mut OpState, #[string] referrer_filename: &str, #[string] request: &str, ) -> Result<Option<String>, RequireError> { let referrer_path = Cow::Borrowed(Path::new(referrer_filename)); let referrer_path = ensure_read_permission(state, referrer_path) .map_err(RequireErrorKind::Permission)?; let pkg_json_resolver = state.borrow::<PackageJsonResolverRc<TSys>>(); let Some(pkg) = pkg_json_resolver.get_closest_package_json(&referrer_path)? else { return Ok(None); }; if pkg.imports.is_some() { let node_resolver = state.borrow::<NodeResolverRc< TInNpmPackageChecker, TNpmPackageFolderResolver, TSys, >>(); NodeResolutionThreadLocalCache::clear(); let url = node_resolver.resolve_package_import( request, Some(&UrlOrPathRef::from_path(&referrer_path)), Some(&pkg), ResolutionMode::Require, NodeResolutionKind::Execution, )?; Ok(Some(url_or_path_to_string(url)?)) } else { Ok(None) } } #[op2(fast, reentrant)] pub fn op_require_break_on_next_statement(state: Rc<RefCell<OpState>>) { let inspector = { state.borrow().borrow::<Rc<JsRuntimeInspector>>().clone() }; inspector.wait_for_session_and_break_on_next_statement() } #[op2(fast)] pub fn op_require_can_parse_as_esm( scope: &mut v8::PinScope<'_, '_>, #[string] source: &str, ) -> bool { v8::tc_scope!(scope, scope); let Some(source) = v8::String::new(scope, source) else { return false; }; let origin = v8::ScriptOrigin::new( scope, source.into(), 0, 0, false, 0, None, true, false, true, None, ); let mut source = v8::script_compiler::Source::new(source, Some(&origin)); v8::script_compiler::compile_module(scope, &mut source).is_some() } fn url_or_path_to_string( url: UrlOrPath, ) -> Result<String, deno_path_util::UrlToFilePathError> { if url.is_file() { Ok(url.into_path()?.to_string_lossy().into_owned()) } else { Ok(url.to_string_lossy().into_owned()) } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/winerror.rs
ext/node/ops/winerror.rs
// Copyright 2018-2025 the Deno authors. MIT license. /* Copyright Joyent, Inc. and other Node contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ // This module ports: // - https://github.com/libuv/libuv/blob/master/src/win/error.c #![allow(unused)] use deno_core::op2; #[op2] #[string] pub fn op_node_sys_to_uv_error(err: i32) -> String { let uv_err = match err { ERROR_ACCESS_DENIED => "EACCES", ERROR_NOACCESS => "EACCES", WSAEACCES => "EACCES", ERROR_CANT_ACCESS_FILE => "EACCES", ERROR_ADDRESS_ALREADY_ASSOCIATED => "EADDRINUSE", WSAEADDRINUSE => "EADDRINUSE", WSAEADDRNOTAVAIL => "EADDRNOTAVAIL", WSAEAFNOSUPPORT => "EAFNOSUPPORT", WSAEWOULDBLOCK => "EAGAIN", WSAEALREADY => "EALREADY", ERROR_INVALID_FLAGS => "EBADF", ERROR_INVALID_HANDLE => "EBADF", ERROR_LOCK_VIOLATION => "EBUSY", ERROR_PIPE_BUSY => "EBUSY", ERROR_SHARING_VIOLATION => "EBUSY", ERROR_OPERATION_ABORTED => "ECANCELED", WSAEINTR => "ECANCELED", ERROR_NO_UNICODE_TRANSLATION => "ECHARSET", ERROR_CONNECTION_ABORTED => "ECONNABORTED", WSAECONNABORTED => "ECONNABORTED", ERROR_CONNECTION_REFUSED => "ECONNREFUSED", WSAECONNREFUSED => "ECONNREFUSED", ERROR_NETNAME_DELETED => "ECONNRESET", WSAECONNRESET => "ECONNRESET", ERROR_ALREADY_EXISTS => "EEXIST", ERROR_FILE_EXISTS => "EEXIST", ERROR_BUFFER_OVERFLOW => "EFAULT", WSAEFAULT => "EFAULT", ERROR_HOST_UNREACHABLE => "EHOSTUNREACH", WSAEHOSTUNREACH => "EHOSTUNREACH", ERROR_INSUFFICIENT_BUFFER => "EINVAL", ERROR_INVALID_DATA => "EINVAL", ERROR_INVALID_NAME => "ENOENT", ERROR_INVALID_PARAMETER => "EINVAL", WSAEINVAL => "EINVAL", WSAEPFNOSUPPORT => "EINVAL", ERROR_NOT_A_REPARSE_POINT => "EINVAL", ERROR_BEGINNING_OF_MEDIA => "EIO", ERROR_BUS_RESET => "EIO", ERROR_CRC => "EIO", ERROR_DEVICE_DOOR_OPEN => "EIO", ERROR_DEVICE_REQUIRES_CLEANING => "EIO", ERROR_DISK_CORRUPT => "EIO", ERROR_EOM_OVERFLOW => "EIO", ERROR_FILEMARK_DETECTED => "EIO", ERROR_GEN_FAILURE => "EIO", ERROR_INVALID_BLOCK_LENGTH => "EIO", ERROR_IO_DEVICE => "EIO", ERROR_NO_DATA_DETECTED => "EIO", ERROR_NO_SIGNAL_SENT => "EIO", ERROR_OPEN_FAILED => "EIO", ERROR_SETMARK_DETECTED => "EIO", ERROR_SIGNAL_REFUSED => "EIO", WSAEISCONN => "EISCONN", ERROR_CANT_RESOLVE_FILENAME => "ELOOP", ERROR_TOO_MANY_OPEN_FILES => "EMFILE", WSAEMFILE => "EMFILE", WSAEMSGSIZE => "EMSGSIZE", ERROR_FILENAME_EXCED_RANGE => "ENAMETOOLONG", ERROR_NETWORK_UNREACHABLE => "ENETUNREACH", WSAENETUNREACH => "ENETUNREACH", WSAENOBUFS => "ENOBUFS", ERROR_BAD_PATHNAME => "ENOENT", ERROR_DIRECTORY => "ENOTDIR", ERROR_ENVVAR_NOT_FOUND => "ENOENT", ERROR_FILE_NOT_FOUND => "ENOENT", ERROR_INVALID_DRIVE => "ENOENT", ERROR_INVALID_REPARSE_DATA => "ENOENT", ERROR_MOD_NOT_FOUND => "ENOENT", ERROR_PATH_NOT_FOUND => "ENOENT", WSAHOST_NOT_FOUND => "ENOENT", WSANO_DATA => "ENOENT", ERROR_NOT_ENOUGH_MEMORY => "ENOMEM", ERROR_OUTOFMEMORY => "ENOMEM", ERROR_CANNOT_MAKE => "ENOSPC", ERROR_DISK_FULL => "ENOSPC", ERROR_EA_TABLE_FULL => "ENOSPC", ERROR_END_OF_MEDIA => "ENOSPC", ERROR_HANDLE_DISK_FULL => "ENOSPC", ERROR_NOT_CONNECTED => "ENOTCONN", WSAENOTCONN => "ENOTCONN", ERROR_DIR_NOT_EMPTY => "ENOTEMPTY", WSAENOTSOCK => "ENOTSOCK", ERROR_NOT_SUPPORTED => "ENOTSUP", ERROR_BROKEN_PIPE => "EOF", ERROR_PRIVILEGE_NOT_HELD => "EPERM", ERROR_BAD_PIPE => "EPIPE", ERROR_NO_DATA => "EPIPE", ERROR_PIPE_NOT_CONNECTED => "EPIPE", WSAESHUTDOWN => "EPIPE", WSAEPROTONOSUPPORT => "EPROTONOSUPPORT", ERROR_WRITE_PROTECT => "EROFS", ERROR_SEM_TIMEOUT => "ETIMEDOUT", WSAETIMEDOUT => "ETIMEDOUT", ERROR_NOT_SAME_DEVICE => "EXDEV", ERROR_INVALID_FUNCTION => "EISDIR", ERROR_META_EXPANSION_TOO_LONG => "E2BIG", WSAESOCKTNOSUPPORT => "ESOCKTNOSUPPORT", _ => "UNKNOWN", }; uv_err.to_string() } /*++ Copyright (c) Microsoft Corporation. All rights reserved. You may only use this code if you agree to the terms of the Windows Research Kernel Source Code License agreement (see License.txt). If you do not agree to the terms, do not use the code. Module: winderror.h Abstract: Win32 API functions --*/ // This module ports: // - https://raw.githubusercontent.com/mic101/windows/master/WRK-v1.2/public/sdk/inc/winerror.h // MessageId: ERROR_SUCCESS // // MessageText: // // The operation completed successfully. // pub const ERROR_SUCCESS: i32 = 0; // // MessageId: ERROR_INVALID_FUNCTION // // MessageText: // // Incorrect function. // pub const ERROR_INVALID_FUNCTION: i32 = 1; // dderror // // MessageId: ERROR_FILE_NOT_FOUND // // MessageText: // // The system cannot find the file specified. // pub const ERROR_FILE_NOT_FOUND: i32 = 2; // // MessageId: ERROR_PATH_NOT_FOUND // // MessageText: // // The system cannot find the path specified. // pub const ERROR_PATH_NOT_FOUND: i32 = 3; // // MessageId: ERROR_TOO_MANY_OPEN_FILES // // MessageText: // // The system cannot open the file. // pub const ERROR_TOO_MANY_OPEN_FILES: i32 = 4; // // MessageId: ERROR_ACCESS_DENIED // // MessageText: // // Access is denied. // pub const ERROR_ACCESS_DENIED: i32 = 5; // // MessageId: ERROR_INVALID_HANDLE // // MessageText: // // The handle is invalid. // pub const ERROR_INVALID_HANDLE: i32 = 6; // // MessageId: ERROR_ARENA_TRASHED // // MessageText: // // The storage control blocks were destroyed. // pub const ERROR_ARENA_TRASHED: i32 = 7; // // MessageId: ERROR_NOT_ENOUGH_MEMORY // // MessageText: // // Not enough storage is available to process this command. // pub const ERROR_NOT_ENOUGH_MEMORY: i32 = 8; // dderror // // MessageId: ERROR_INVALID_BLOCK // // MessageText: // // The storage control block address is invalid. // pub const ERROR_INVALID_BLOCK: i32 = 9; // // MessageId: ERROR_BAD_ENVIRONMENT // // MessageText: // // The environment is incorrect. // pub const ERROR_BAD_ENVIRONMENT: i32 = 10; // // MessageId: ERROR_BAD_FORMAT // // MessageText: // // An attempt was made to load a program with an incorrect format. // pub const ERROR_BAD_FORMAT: i32 = 11; // // MessageId: ERROR_INVALID_ACCESS // // MessageText: // // The access code is invalid. // pub const ERROR_INVALID_ACCESS: i32 = 12; // // MessageId: ERROR_INVALID_DATA // // MessageText: // // The data is invalid. // pub const ERROR_INVALID_DATA: i32 = 13; // // MessageId: ERROR_OUTOFMEMORY // // MessageText: // // Not enough storage is available to complete this operation. // pub const ERROR_OUTOFMEMORY: i32 = 14; // // MessageId: ERROR_INVALID_DRIVE // // MessageText: // // The system cannot find the drive specified. // pub const ERROR_INVALID_DRIVE: i32 = 15; // // MessageId: ERROR_CURRENT_DIRECTORY // // MessageText: // // The directory cannot be removed. // pub const ERROR_CURRENT_DIRECTORY: i32 = 16; // // MessageId: ERROR_NOT_SAME_DEVICE // // MessageText: // // The system cannot move the file to a different disk drive. // pub const ERROR_NOT_SAME_DEVICE: i32 = 17; // // MessageId: ERROR_NO_MORE_FILES // // MessageText: // // There are no more files. // pub const ERROR_NO_MORE_FILES: i32 = 18; // // MessageId: ERROR_WRITE_PROTECT // // MessageText: // // The media is write protected. // pub const ERROR_WRITE_PROTECT: i32 = 19; // // MessageId: ERROR_BAD_UNIT // // MessageText: // // The system cannot find the device specified. // pub const ERROR_BAD_UNIT: i32 = 20; // // MessageId: ERROR_NOT_READY // // MessageText: // // The device is not ready. // pub const ERROR_NOT_READY: i32 = 21; // // MessageId: ERROR_BAD_COMMAND // // MessageText: // // The device does not recognize the command. // pub const ERROR_BAD_COMMAND: i32 = 22; // // MessageId: ERROR_CRC // // MessageText: // // Data error (cyclic redundancy check). // pub const ERROR_CRC: i32 = 23; // // MessageId: ERROR_BAD_LENGTH // // MessageText: // // The program issued a command but the command length is incorrect. // pub const ERROR_BAD_LENGTH: i32 = 24; // // MessageId: ERROR_SEEK // // MessageText: // // The drive cannot locate a specific area or track on the disk. // pub const ERROR_SEEK: i32 = 25; // // MessageId: ERROR_NOT_DOS_DISK // // MessageText: // // The specified disk or diskette cannot be accessed. // pub const ERROR_NOT_DOS_DISK: i32 = 26; // // MessageId: ERROR_SECTOR_NOT_FOUND // // MessageText: // // The drive cannot find the sector requested. // pub const ERROR_SECTOR_NOT_FOUND: i32 = 27; // // MessageId: ERROR_OUT_OF_PAPER // // MessageText: // // The printer is out of paper. // pub const ERROR_OUT_OF_PAPER: i32 = 28; // // MessageId: ERROR_WRITE_FAULT // // MessageText: // // The system cannot write to the specified device. // pub const ERROR_WRITE_FAULT: i32 = 29; // // MessageId: ERROR_READ_FAULT // // MessageText: // // The system cannot read from the specified device. // pub const ERROR_READ_FAULT: i32 = 30; // // MessageId: ERROR_GEN_FAILURE // // MessageText: // // A device attached to the system is not functioning. // pub const ERROR_GEN_FAILURE: i32 = 31; // // MessageId: ERROR_SHARING_VIOLATION // // MessageText: // // The process cannot access the file because it is being used by another process. // pub const ERROR_SHARING_VIOLATION: i32 = 32; // // MessageId: ERROR_LOCK_VIOLATION // // MessageText: // // The process cannot access the file because another process has locked a portion of the file. // pub const ERROR_LOCK_VIOLATION: i32 = 33; // // MessageId: ERROR_WRONG_DISK // // MessageText: // // The wrong diskette is in the drive. // Insert %2 (Volume Serial Number: %3) into drive %1. // pub const ERROR_WRONG_DISK: i32 = 34; // // MessageId: ERROR_SHARING_BUFFER_EXCEEDED // // MessageText: // // Too many files opened for sharing. // pub const ERROR_SHARING_BUFFER_EXCEEDED: i32 = 36; // // MessageId: ERROR_HANDLE_EOF // // MessageText: // // Reached the end of the file. // pub const ERROR_HANDLE_EOF: i32 = 38; // // MessageId: ERROR_HANDLE_DISK_FULL // // MessageText: // // The disk is full. // pub const ERROR_HANDLE_DISK_FULL: i32 = 39; // // MessageId: ERROR_NOT_SUPPORTED // // MessageText: // // The request is not supported. // pub const ERROR_NOT_SUPPORTED: i32 = 50; // // MessageId: ERROR_REM_NOT_LIST // // MessageText: // // Windows cannot find the network path. Verify that the network path is correct and the destination computer is not busy or turned off. If Windows still cannot find the network path, contact your network administrator. // pub const ERROR_REM_NOT_LIST: i32 = 51; // // MessageId: ERROR_DUP_NAME // // MessageText: // // You were not connected because a duplicate name exists on the network. Go to System in Control Panel to change the computer name and try again. // pub const ERROR_DUP_NAME: i32 = 52; // // MessageId: ERROR_BAD_NETPATH // // MessageText: // // The network path was not found. // pub const ERROR_BAD_NETPATH: i32 = 53; // // MessageId: ERROR_NETWORK_BUSY // // MessageText: // // The network is busy. // pub const ERROR_NETWORK_BUSY: i32 = 54; // // MessageId: ERROR_DEV_NOT_EXIST // // MessageText: // // The specified network resource or device is no longer available. // pub const ERROR_DEV_NOT_EXIST: i32 = 55; // dderror // // MessageId: ERROR_TOO_MANY_CMDS // // MessageText: // // The network BIOS command limit has been reached. // pub const ERROR_TOO_MANY_CMDS: i32 = 56; // // MessageId: ERROR_ADAP_HDW_ERR // // MessageText: // // A network adapter hardware error occurred. // pub const ERROR_ADAP_HDW_ERR: i32 = 57; // // MessageId: ERROR_BAD_NET_RESP // // MessageText: // // The specified server cannot perform the requested operation. // pub const ERROR_BAD_NET_RESP: i32 = 58; // // MessageId: ERROR_UNEXP_NET_ERR // // MessageText: // // An unexpected network error occurred. // pub const ERROR_UNEXP_NET_ERR: i32 = 59; // // MessageId: ERROR_BAD_REM_ADAP // // MessageText: // // The remote adapter is not compatible. // pub const ERROR_BAD_REM_ADAP: i32 = 60; // // MessageId: ERROR_PRINTQ_FULL // // MessageText: // // The printer queue is full. // pub const ERROR_PRINTQ_FULL: i32 = 61; // // MessageId: ERROR_NO_SPOOL_SPACE // // MessageText: // // Space to store the file waiting to be printed is not available on the server. // pub const ERROR_NO_SPOOL_SPACE: i32 = 62; // // MessageId: ERROR_PRINT_CANCELLED // // MessageText: // // Your file waiting to be printed was deleted. // pub const ERROR_PRINT_CANCELLED: i32 = 63; // // MessageId: ERROR_NETNAME_DELETED // // MessageText: // // The specified network name is no longer available. // pub const ERROR_NETNAME_DELETED: i32 = 64; // // MessageId: ERROR_NETWORK_ACCESS_DENIED // // MessageText: // // Network access is denied. // pub const ERROR_NETWORK_ACCESS_DENIED: i32 = 65; // // MessageId: ERROR_BAD_DEV_TYPE // // MessageText: // // The network resource type is not correct. // pub const ERROR_BAD_DEV_TYPE: i32 = 66; // // MessageId: ERROR_BAD_NET_NAME // // MessageText: // // The network name cannot be found. // pub const ERROR_BAD_NET_NAME: i32 = 67; // // MessageId: ERROR_TOO_MANY_NAMES // // MessageText: // // The name limit for the local computer network adapter card was exceeded. // pub const ERROR_TOO_MANY_NAMES: i32 = 68; // // MessageId: ERROR_TOO_MANY_SESS // // MessageText: // // The network BIOS session limit was exceeded. // pub const ERROR_TOO_MANY_SESS: i32 = 69; // // MessageId: ERROR_SHARING_PAUSED // // MessageText: // // The remote server has been paused or is in the process of being started. // pub const ERROR_SHARING_PAUSED: i32 = 70; // // MessageId: ERROR_REQ_NOT_ACCEP // // MessageText: // // No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept. // pub const ERROR_REQ_NOT_ACCEP: i32 = 71; // // MessageId: ERROR_REDIR_PAUSED // // MessageText: // // The specified printer or disk device has been paused. // pub const ERROR_REDIR_PAUSED: i32 = 72; // // MessageId: ERROR_FILE_EXISTS // // MessageText: // // The file exists. // pub const ERROR_FILE_EXISTS: i32 = 80; // // MessageId: ERROR_CANNOT_MAKE // // MessageText: // // The directory or file cannot be created. // pub const ERROR_CANNOT_MAKE: i32 = 82; // // MessageId: ERROR_FAIL_I24 // // MessageText: // // Fail on INT 24. // pub const ERROR_FAIL_I24: i32 = 83; // // MessageId: ERROR_OUT_OF_STRUCTURES // // MessageText: // // Storage to process this request is not available. // pub const ERROR_OUT_OF_STRUCTURES: i32 = 84; // // MessageId: ERROR_ALREADY_ASSIGNED // // MessageText: // // The local device name is already in use. // pub const ERROR_ALREADY_ASSIGNED: i32 = 85; // // MessageId: ERROR_INVALID_PASSWORD // // MessageText: // // The specified network password is not correct. // pub const ERROR_INVALID_PASSWORD: i32 = 86; // // MessageId: ERROR_INVALID_PARAMETER // // MessageText: // // The parameter is incorrect. // pub const ERROR_INVALID_PARAMETER: i32 = 87; // dderror // // MessageId: ERROR_NET_WRITE_FAULT // // MessageText: // // A write fault occurred on the network. // pub const ERROR_NET_WRITE_FAULT: i32 = 88; // // MessageId: ERROR_NO_PROC_SLOTS // // MessageText: // // The system cannot start another process at this time. // pub const ERROR_NO_PROC_SLOTS: i32 = 89; // // MessageId: ERROR_TOO_MANY_SEMAPHORES // // MessageText: // // Cannot create another system semaphore. // pub const ERROR_TOO_MANY_SEMAPHORES: i32 = 100; // // MessageId: ERROR_EXCL_SEM_ALREADY_OWNED // // MessageText: // // The exclusive semaphore is owned by another process. // pub const ERROR_EXCL_SEM_ALREADY_OWNED: i32 = 101; // // MessageId: ERROR_SEM_IS_SET // // MessageText: // // The semaphore is set and cannot be closed. // pub const ERROR_SEM_IS_SET: i32 = 102; // // MessageId: ERROR_TOO_MANY_SEM_REQUESTS // // MessageText: // // The semaphore cannot be set again. // pub const ERROR_TOO_MANY_SEM_REQUESTS: i32 = 103; // // MessageId: ERROR_INVALID_AT_INTERRUPT_TIME // // MessageText: // // Cannot request exclusive semaphores at interrupt time. // pub const ERROR_INVALID_AT_INTERRUPT_TIME: i32 = 104; // // MessageId: ERROR_SEM_OWNER_DIED // // MessageText: // // The previous ownership of this semaphore has ended. // pub const ERROR_SEM_OWNER_DIED: i32 = 105; // // MessageId: ERROR_SEM_USER_LIMIT // // MessageText: // // Insert the diskette for drive %1. // pub const ERROR_SEM_USER_LIMIT: i32 = 106; // // MessageId: ERROR_DISK_CHANGE // // MessageText: // // The program stopped because an alternate diskette was not inserted. // pub const ERROR_DISK_CHANGE: i32 = 107; // // MessageId: ERROR_DRIVE_LOCKED // // MessageText: // // The disk is in use or locked by another process. // pub const ERROR_DRIVE_LOCKED: i32 = 108; // // MessageId: ERROR_BROKEN_PIPE // // MessageText: // // The pipe has been ended. // pub const ERROR_BROKEN_PIPE: i32 = 109; // // MessageId: ERROR_OPEN_FAILED // // MessageText: // // The system cannot open the device or file specified. // pub const ERROR_OPEN_FAILED: i32 = 110; // // MessageId: ERROR_BUFFER_OVERFLOW // // MessageText: // // The file name is too long. // pub const ERROR_BUFFER_OVERFLOW: i32 = 111; // // MessageId: ERROR_DISK_FULL // // MessageText: // // There is not enough space on the disk. // pub const ERROR_DISK_FULL: i32 = 112; // // MessageId: ERROR_NO_MORE_SEARCH_HANDLES // // MessageText: // // No more internal file identifiers available. // pub const ERROR_NO_MORE_SEARCH_HANDLES: i32 = 113; // // MessageId: ERROR_INVALID_TARGET_HANDLE // // MessageText: // // The target internal file identifier is incorrect. // pub const ERROR_INVALID_TARGET_HANDLE: i32 = 114; // // MessageId: ERROR_INVALID_CATEGORY // // MessageText: // // The IOCTL call made by the application program is not correct. // pub const ERROR_INVALID_CATEGORY: i32 = 117; // // MessageId: ERROR_INVALID_VERIFY_SWITCH // // MessageText: // // The verify-on-write switch parameter value is not correct. // pub const ERROR_INVALID_VERIFY_SWITCH: i32 = 118; // // MessageId: ERROR_BAD_DRIVER_LEVEL // // MessageText: // // The system does not support the command requested. // pub const ERROR_BAD_DRIVER_LEVEL: i32 = 119; // // MessageId: ERROR_CALL_NOT_IMPLEMENTED // // MessageText: // // This function is not supported on this system. // pub const ERROR_CALL_NOT_IMPLEMENTED: i32 = 120; // // MessageId: ERROR_SEM_TIMEOUT // // MessageText: // // The semaphore timeout period has expired. // pub const ERROR_SEM_TIMEOUT: i32 = 121; // // MessageId: ERROR_INSUFFICIENT_BUFFER // // MessageText: // // The data area passed to a system call is too small. // pub const ERROR_INSUFFICIENT_BUFFER: i32 = 122; // dderror // // MessageId: ERROR_INVALID_NAME // // MessageText: // // The filename, directory name, or volume label syntax is incorrect. // pub const ERROR_INVALID_NAME: i32 = 123; // dderror // // MessageId: ERROR_INVALID_LEVEL // // MessageText: // // The system call level is not correct. // pub const ERROR_INVALID_LEVEL: i32 = 124; // // MessageId: ERROR_NO_VOLUME_LABEL // // MessageText: // // The disk has no volume label. // pub const ERROR_NO_VOLUME_LABEL: i32 = 125; // // MessageId: ERROR_MOD_NOT_FOUND // // MessageText: // // The specified module could not be found. // pub const ERROR_MOD_NOT_FOUND: i32 = 126; // // MessageId: ERROR_PROC_NOT_FOUND // // MessageText: // // The specified procedure could not be found. // pub const ERROR_PROC_NOT_FOUND: i32 = 127; // // MessageId: ERROR_WAIT_NO_CHILDREN // // MessageText: // // There are no child processes to wait for. // pub const ERROR_WAIT_NO_CHILDREN: i32 = 128; // // MessageId: ERROR_CHILD_NOT_COMPLETE // // MessageText: // // The %1 application cannot be run in Win32 mode. // pub const ERROR_CHILD_NOT_COMPLETE: i32 = 129; // // MessageId: ERROR_DIRECT_ACCESS_HANDLE // // MessageText: // // Attempt to use a file handle to an open disk partition for an operation other than raw disk I/O. // pub const ERROR_DIRECT_ACCESS_HANDLE: i32 = 130; // // MessageId: ERROR_NEGATIVE_SEEK // // MessageText: // // An attempt was made to move the file pointer before the beginning of the file. // pub const ERROR_NEGATIVE_SEEK: i32 = 131; // // MessageId: ERROR_SEEK_ON_DEVICE // // MessageText: // // The file pointer cannot be set on the specified device or file. // pub const ERROR_SEEK_ON_DEVICE: i32 = 132; // // MessageId: ERROR_IS_JOIN_TARGET // // MessageText: // // A JOIN or SUBST command cannot be used for a drive that contains previously joined drives. // pub const ERROR_IS_JOIN_TARGET: i32 = 133; // // MessageId: ERROR_IS_JOINED // // MessageText: // // An attempt was made to use a JOIN or SUBST command on a drive that has already been joined. // pub const ERROR_IS_JOINED: i32 = 134; // // MessageId: ERROR_IS_SUBSTED // // MessageText: // // An attempt was made to use a JOIN or SUBST command on a drive that has already been substituted. // pub const ERROR_IS_SUBSTED: i32 = 135; // // MessageId: ERROR_NOT_JOINED // // MessageText: // // The system tried to delete the JOIN of a drive that is not joined. // pub const ERROR_NOT_JOINED: i32 = 136; // // MessageId: ERROR_NOT_SUBSTED // // MessageText: // // The system tried to delete the substitution of a drive that is not substituted. // pub const ERROR_NOT_SUBSTED: i32 = 137; // // MessageId: ERROR_JOIN_TO_JOIN // // MessageText: // // The system tried to join a drive to a directory on a joined drive. // pub const ERROR_JOIN_TO_JOIN: i32 = 138; // // MessageId: ERROR_SUBST_TO_SUBST // // MessageText: // // The system tried to substitute a drive to a directory on a substituted drive. // pub const ERROR_SUBST_TO_SUBST: i32 = 139; // // MessageId: ERROR_JOIN_TO_SUBST // // MessageText: // // The system tried to join a drive to a directory on a substituted drive. // pub const ERROR_JOIN_TO_SUBST: i32 = 140; // // MessageId: ERROR_SUBST_TO_JOIN // // MessageText: // // The system tried to SUBST a drive to a directory on a joined drive. // pub const ERROR_SUBST_TO_JOIN: i32 = 141; // // MessageId: ERROR_BUSY_DRIVE // // MessageText: // // The system cannot perform a JOIN or SUBST at this time. // pub const ERROR_BUSY_DRIVE: i32 = 142; // // MessageId: ERROR_SAME_DRIVE // // MessageText: // // The system cannot join or substitute a drive to or for a directory on the same drive. // pub const ERROR_SAME_DRIVE: i32 = 143; // // MessageId: ERROR_DIR_NOT_ROOT // // MessageText: // // The directory is not a subdirectory of the root directory. // pub const ERROR_DIR_NOT_ROOT: i32 = 144; // // MessageId: ERROR_DIR_NOT_EMPTY // // MessageText: // // The directory is not empty. // pub const ERROR_DIR_NOT_EMPTY: i32 = 145; // // MessageId: ERROR_IS_SUBST_PATH // // MessageText: // // The path specified is being used in a substitute. // pub const ERROR_IS_SUBST_PATH: i32 = 146; // // MessageId: ERROR_IS_JOIN_PATH // // MessageText: // // Not enough resources are available to process this command. // pub const ERROR_IS_JOIN_PATH: i32 = 147; // // MessageId: ERROR_PATH_BUSY // // MessageText: // // The path specified cannot be used at this time. // pub const ERROR_PATH_BUSY: i32 = 148; // // MessageId: ERROR_IS_SUBST_TARGET // // MessageText: // // An attempt was made to join or substitute a drive for which a directory on the drive is the target of a previous substitute. // pub const ERROR_IS_SUBST_TARGET: i32 = 149; // // MessageId: ERROR_SYSTEM_TRACE // // MessageText: // // System trace information was not specified in your CONFIG.SYS file, or tracing is disallowed. // pub const ERROR_SYSTEM_TRACE: i32 = 150; // // MessageId: ERROR_INVALID_EVENT_COUNT // // MessageText: // // The number of specified semaphore events for DosMuxSemWait is not correct. // pub const ERROR_INVALID_EVENT_COUNT: i32 = 151; // // MessageId: ERROR_TOO_MANY_MUXWAITERS // // MessageText: // // DosMuxSemWait did not execute; too many semaphores are already set. // pub const ERROR_TOO_MANY_MUXWAITERS: i32 = 152; // // MessageId: ERROR_INVALID_LIST_FORMAT // // MessageText: // // The DosMuxSemWait list is not correct. // pub const ERROR_INVALID_LIST_FORMAT: i32 = 153; // // MessageId: ERROR_LABEL_TOO_LONG // // MessageText: // // The volume label you entered exceeds the label character limit of the target file system. // pub const ERROR_LABEL_TOO_LONG: i32 = 154; // // MessageId: ERROR_TOO_MANY_TCBS // // MessageText: // // Cannot create another thread. // pub const ERROR_TOO_MANY_TCBS: i32 = 155; // // MessageId: ERROR_SIGNAL_REFUSED // // MessageText: // // The recipient process has refused the signal. // pub const ERROR_SIGNAL_REFUSED: i32 = 156; // // MessageId: ERROR_DISCARDED // // MessageText: // // The segment is already discarded and cannot be locked. // pub const ERROR_DISCARDED: i32 = 157; // // MessageId: ERROR_NOT_LOCKED // // MessageText: // // The segment is already unlocked. // pub const ERROR_NOT_LOCKED: i32 = 158; // // MessageId: ERROR_BAD_THREADID_ADDR // // MessageText: // // The address for the thread ID is not correct. // pub const ERROR_BAD_THREADID_ADDR: i32 = 159; // // MessageId: ERROR_BAD_ARGUMENTS // // MessageText: // // One or more arguments are not correct. // pub const ERROR_BAD_ARGUMENTS: i32 = 160; // // MessageId: ERROR_BAD_PATHNAME // // MessageText: // // The specified path is invalid. // pub const ERROR_BAD_PATHNAME: i32 = 161; // // MessageId: ERROR_SIGNAL_PENDING // // MessageText: // // A signal is already pending. // pub const ERROR_SIGNAL_PENDING: i32 = 162; // // MessageId: ERROR_MAX_THRDS_REACHED // // MessageText: // // No more threads can be created in the system. // pub const ERROR_MAX_THRDS_REACHED: i32 = 164; // // MessageId: ERROR_LOCK_FAILED // // MessageText: // // Unable to lock a region of a file. // pub const ERROR_LOCK_FAILED: i32 = 167; // // MessageId: ERROR_BUSY // // MessageText: // // The requested resource is in use. // pub const ERROR_BUSY: i32 = 170; // dderror // // MessageId: ERROR_CANCEL_VIOLATION // // MessageText: // // A lock request was not outstanding for the supplied cancel region. // pub const ERROR_CANCEL_VIOLATION: i32 = 173; // // MessageId: ERROR_ATOMIC_LOCKS_NOT_SUPPORTED // // MessageText: // // The file system does not support atomic changes to the lock type. // pub const ERROR_ATOMIC_LOCKS_NOT_SUPPORTED: i32 = 174; // // MessageId: ERROR_INVALID_SEGMENT_NUMBER // // MessageText: // // The system detected a segment number that was not correct. // pub const ERROR_INVALID_SEGMENT_NUMBER: i32 = 180; // // MessageId: ERROR_INVALID_ORDINAL // // MessageText: // // The operating system cannot run %1. // pub const ERROR_INVALID_ORDINAL: i32 = 182; // // MessageId: ERROR_ALREADY_EXISTS // // MessageText: // // Cannot create a file when that file already exists. // pub const ERROR_ALREADY_EXISTS: i32 = 183; // // MessageId: ERROR_INVALID_FLAG_NUMBER // // MessageText: // // The flag passed is not correct. // pub const ERROR_INVALID_FLAG_NUMBER: i32 = 186; // // MessageId: ERROR_SEM_NOT_FOUND // // MessageText: // // The specified system semaphore name was not found. // pub const ERROR_SEM_NOT_FOUND: i32 = 187; // // MessageId: ERROR_INVALID_STARTING_CODESEG // // MessageText: // // The operating system cannot run %1. // pub const ERROR_INVALID_STARTING_CODESEG: i32 = 188; // // MessageId: ERROR_INVALID_STACKSEG // // MessageText: // // The operating system cannot run %1. // pub const ERROR_INVALID_STACKSEG: i32 = 189; // // MessageId: ERROR_INVALID_MODULETYPE // // MessageText: // // The operating system cannot run %1. // pub const ERROR_INVALID_MODULETYPE: i32 = 190; // // MessageId: ERROR_INVALID_EXE_SIGNATURE // // MessageText: // // Cannot run %1 in Win32 mode. // pub const ERROR_INVALID_EXE_SIGNATURE: i32 = 191; // // MessageId: ERROR_EXE_MARKED_INVALID // // MessageText: // // The operating system cannot run %1. // pub const ERROR_EXE_MARKED_INVALID: i32 = 192; // // MessageId: ERROR_BAD_EXE_FORMAT // // MessageText: // // %1 is not a valid Win32 application. // pub const ERROR_BAD_EXE_FORMAT: i32 = 193; // // MessageId: ERROR_ITERATED_DATA_EXCEEDS_64k // // MessageText: // // The operating system cannot run %1. // // deno-lint-ignore camelcase pub const ERROR_ITERATED_DATA_EXCEEDS_64K: i32 = 194; // // MessageId: ERROR_INVALID_MINALLOCSIZE // // MessageText: // // The operating system cannot run %1. // pub const ERROR_INVALID_MINALLOCSIZE: i32 = 195; // // MessageId: ERROR_DYNLINK_FROM_INVALID_RING // // MessageText: // // The operating system cannot run this application program. // pub const ERROR_DYNLINK_FROM_INVALID_RING: i32 = 196; // // MessageId: ERROR_IOPL_NOT_ENABLED // // MessageText: // // The operating system is not presently configured to run this application. // pub const ERROR_IOPL_NOT_ENABLED: i32 = 197; // // MessageId: ERROR_INVALID_SEGDPL // // MessageText: // // The operating system cannot run %1. // pub const ERROR_INVALID_SEGDPL: i32 = 198; // // MessageId: ERROR_AUTODATASEG_EXCEEDS_64k // // MessageText: // // The operating system cannot run this application program. // // deno-lint-ignore camelcase pub const ERROR_AUTODATASEG_EXCEEDS_64K: i32 = 199; // // MessageId: ERROR_RING2SEG_MUST_BE_MOVABLE // // MessageText: // // The code segment cannot be greater than or equal to 64K. // pub const ERROR_RING2SEG_MUST_BE_MOVABLE: i32 = 200; // // MessageId: ERROR_RELOC_CHAIN_XEEDS_SEGLIM // // MessageText: // // The operating system cannot run %1. // pub const ERROR_RELOC_CHAIN_XEEDS_SEGLIM: i32 = 201; // // MessageId: ERROR_INFLOOP_IN_RELOC_CHAIN // // MessageText: // // The operating system cannot run %1. // pub const ERROR_INFLOOP_IN_RELOC_CHAIN: i32 = 202; // // MessageId: ERROR_ENVVAR_NOT_FOUND // // MessageText: // // The system could not find the environment option that was entered. // pub const ERROR_ENVVAR_NOT_FOUND: i32 = 203; // // MessageId: ERROR_NO_SIGNAL_SENT // // MessageText: // // No process in the command subtree has a signal handler. // pub const ERROR_NO_SIGNAL_SENT: i32 = 205; // // MessageId: ERROR_FILENAME_EXCED_RANGE // // MessageText: // // The filename or extension is too long. // pub const ERROR_FILENAME_EXCED_RANGE: i32 = 206; // // MessageId: ERROR_RING2_STACK_IN_USE // // MessageText: // // The ring 2 stack is in use. // pub const ERROR_RING2_STACK_IN_USE: i32 = 207; // // MessageId: ERROR_META_EXPANSION_TOO_LONG // // MessageText: // // The global filename characters, * or ?, are entered incorrectly or too many global filename characters are specified. // pub const ERROR_META_EXPANSION_TOO_LONG: i32 = 208; // // MessageId: ERROR_INVALID_SIGNAL_NUMBER // // MessageText: // // The signal being posted is not correct. // pub const ERROR_INVALID_SIGNAL_NUMBER: i32 = 209; // // MessageId: ERROR_THREAD_1_INACTIVE // // MessageText: // // The signal handler cannot be set. // pub const ERROR_THREAD_1_INACTIVE: i32 = 210; // // MessageId: ERROR_LOCKED // // MessageText: // // The segment is locked and cannot be reallocated. // pub const ERROR_LOCKED: i32 = 212; // // MessageId: ERROR_TOO_MANY_MODULES // // MessageText: // // Too many dynamic-link modules are attached to this program or dynamic-link module. // pub const ERROR_TOO_MANY_MODULES: i32 = 214; // // MessageId: ERROR_NESTING_NOT_ALLOWED // // MessageText: // // Cannot nest calls to LoadModule. // pub const ERROR_NESTING_NOT_ALLOWED: i32 = 215; // // MessageId: ERROR_EXE_MACHINE_TYPE_MISMATCH //
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
true
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/http2.rs
ext/node/ops/http2.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::collections::HashMap; use std::future::poll_fn; use std::rc::Rc; use std::task::Poll; use bytes::Bytes; use deno_core::AsyncRefCell; use deno_core::BufView; use deno_core::ByteString; use deno_core::CancelFuture; use deno_core::CancelHandle; use deno_core::JsBuffer; use deno_core::OpState; use deno_core::RcRef; use deno_core::Resource; use deno_core::ResourceId; use deno_core::error::ResourceError; use deno_core::op2; use deno_core::serde::Serialize; use deno_net::raw::NetworkStream; use deno_net::raw::take_network_stream_resource; use h2; use h2::Reason; use h2::RecvStream; use http; use http::HeaderMap; use http::Response; use http::StatusCode; use http::header::HeaderName; use http::header::HeaderValue; use http::request::Parts; use url::Url; pub struct Http2Client { pub client: AsyncRefCell<h2::client::SendRequest<BufView>>, pub url: Url, } impl Resource for Http2Client { fn name(&self) -> Cow<'_, str> { "http2Client".into() } } #[derive(Debug)] pub struct Http2ClientConn { pub conn: AsyncRefCell<h2::client::Connection<NetworkStream, BufView>>, cancel_handle: CancelHandle, } impl Resource for Http2ClientConn { fn name(&self) -> Cow<'_, str> { "http2ClientConnection".into() } fn close(self: Rc<Self>) { self.cancel_handle.cancel() } } #[derive(Debug)] pub struct Http2ClientStream { pub response: AsyncRefCell<h2::client::ResponseFuture>, pub stream: AsyncRefCell<h2::SendStream<BufView>>, } impl Resource for Http2ClientStream { fn name(&self) -> Cow<'_, str> { "http2ClientStream".into() } } #[derive(Debug)] pub struct Http2ClientResponseBody { pub body: AsyncRefCell<h2::RecvStream>, pub trailers_rx: AsyncRefCell<Option<tokio::sync::oneshot::Receiver<Option<HeaderMap>>>>, pub trailers_tx: AsyncRefCell<Option<tokio::sync::oneshot::Sender<Option<HeaderMap>>>>, } impl Resource for Http2ClientResponseBody { fn name(&self) -> Cow<'_, str> { "http2ClientResponseBody".into() } } #[derive(Debug)] pub struct Http2ServerConnection { pub conn: AsyncRefCell<h2::server::Connection<NetworkStream, BufView>>, } impl Resource for Http2ServerConnection { fn name(&self) -> Cow<'_, str> { "http2ServerConnection".into() } } pub struct Http2ServerSendResponse { pub send_response: AsyncRefCell<h2::server::SendResponse<BufView>>, } impl Resource for Http2ServerSendResponse { fn name(&self) -> Cow<'_, str> { "http2ServerSendResponse".into() } } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum Http2Error { #[class(inherit)] #[error(transparent)] Resource( #[from] #[inherit] ResourceError, ), #[class(inherit)] #[error(transparent)] UrlParse( #[from] #[inherit] url::ParseError, ), #[class(generic)] #[error(transparent)] H2(#[from] h2::Error), #[class(inherit)] #[error(transparent)] TakeNetworkStream( #[from] #[inherit] deno_net::raw::TakeNetworkStreamError, ), } #[op2(async)] #[serde] pub async fn op_http2_connect( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, #[string] url: String, ) -> Result<(ResourceId, ResourceId), Http2Error> { // No permission check necessary because we're using an existing connection let network_stream = { let mut state = state.borrow_mut(); take_network_stream_resource(&mut state.resource_table, rid)? }; let url = Url::parse(&url)?; let (client, conn) = h2::client::Builder::new().handshake(network_stream).await?; let mut state = state.borrow_mut(); let client_rid = state.resource_table.add(Http2Client { client: AsyncRefCell::new(client), url, }); let conn_rid = state.resource_table.add(Http2ClientConn { conn: AsyncRefCell::new(conn), cancel_handle: CancelHandle::new(), }); Ok((client_rid, conn_rid)) } #[op2(async)] #[smi] pub async fn op_http2_listen( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<ResourceId, Http2Error> { let stream = take_network_stream_resource(&mut state.borrow_mut().resource_table, rid)?; let conn = h2::server::Builder::new().handshake(stream).await?; Ok( state .borrow_mut() .resource_table .add(Http2ServerConnection { conn: AsyncRefCell::new(conn), }), ) } #[op2(async)] #[serde] pub async fn op_http2_accept( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result< Option<(Vec<(ByteString, ByteString)>, ResourceId, ResourceId)>, Http2Error, > { let resource = state .borrow() .resource_table .get::<Http2ServerConnection>(rid)?; let mut conn = RcRef::map(&resource, |r| &r.conn).borrow_mut().await; match conn.accept().await { Some(res) => { let (req, resp) = res?; let (parts, body) = req.into_parts(); let (trailers_tx, trailers_rx) = tokio::sync::oneshot::channel(); let stm = state .borrow_mut() .resource_table .add(Http2ClientResponseBody { body: AsyncRefCell::new(body), trailers_rx: AsyncRefCell::new(Some(trailers_rx)), trailers_tx: AsyncRefCell::new(Some(trailers_tx)), }); let Parts { uri, method, headers, .. } = parts; let mut req_headers = Vec::with_capacity(headers.len() + 4); req_headers.push(( ByteString::from(":method"), ByteString::from(method.as_str()), )); req_headers.push(( ByteString::from(":scheme"), ByteString::from(uri.scheme().map(|s| s.as_str()).unwrap_or("http")), )); req_headers.push(( ByteString::from(":path"), ByteString::from( uri.path_and_query().map(|p| p.as_str()).unwrap_or(""), ), )); req_headers.push(( ByteString::from(":authority"), ByteString::from(uri.authority().map(|a| a.as_str()).unwrap_or("")), )); for (key, val) in headers.iter() { req_headers.push((key.as_str().into(), val.as_bytes().into())); } let resp = state .borrow_mut() .resource_table .add(Http2ServerSendResponse { send_response: AsyncRefCell::new(resp), }); Ok(Some((req_headers, stm, resp))) } _ => Ok(None), } } #[op2(async)] #[serde] pub async fn op_http2_send_response( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, #[smi] status: u16, #[serde] headers: Vec<(ByteString, ByteString)>, ) -> Result<(ResourceId, u32), Http2Error> { let resource = state .borrow() .resource_table .get::<Http2ServerSendResponse>(rid)?; let mut send_response = RcRef::map(resource, |r| &r.send_response) .borrow_mut() .await; let mut response = Response::new(()); if let Ok(status) = StatusCode::from_u16(status) { *response.status_mut() = status; } for (name, value) in headers { response.headers_mut().append( HeaderName::from_bytes(&name).unwrap(), HeaderValue::from_bytes(&value).unwrap(), ); } let stream = send_response.send_response(response, false)?; let stream_id = stream.stream_id(); Ok((rid, stream_id.into())) } #[op2(async)] pub async fn op_http2_poll_client_connection( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<(), Http2Error> { let resource = state.borrow().resource_table.get::<Http2ClientConn>(rid)?; let cancel_handle = RcRef::map(resource.clone(), |this| &this.cancel_handle); let mut conn = RcRef::map(resource, |this| &this.conn).borrow_mut().await; match (&mut *conn).or_cancel(cancel_handle).await { Ok(result) => result?, Err(_) => { // TODO(bartlomieju): probably need a better mechanism for closing the connection // cancelled } } Ok(()) } #[op2(async)] #[serde] pub async fn op_http2_client_request( state: Rc<RefCell<OpState>>, #[smi] client_rid: ResourceId, // TODO(bartlomieju): maybe use a vector with fixed layout to save sending // 4 strings of keys? #[serde] mut pseudo_headers: HashMap<String, String>, #[serde] headers: Vec<(ByteString, ByteString)>, ) -> Result<(ResourceId, u32), Http2Error> { let resource = state .borrow() .resource_table .get::<Http2Client>(client_rid)?; let url = resource.url.clone(); let pseudo_path = pseudo_headers.remove(":path").unwrap_or("/".to_string()); let pseudo_method = pseudo_headers .remove(":method") .unwrap_or("GET".to_string()); // TODO(bartlomieju): handle all pseudo-headers (:authority, :scheme) let _pseudo_authority = pseudo_headers .remove(":authority") .unwrap_or("/".to_string()); let _pseudo_scheme = pseudo_headers .remove(":scheme") .unwrap_or("http".to_string()); let url = url.join(&pseudo_path)?; let mut req = http::Request::builder() .uri(url.as_str()) .method(pseudo_method.as_str()); for (name, value) in headers { req.headers_mut().unwrap().append( HeaderName::from_bytes(&name).unwrap(), HeaderValue::from_bytes(&value).unwrap(), ); } let request = req.body(()).unwrap(); let resource = { let state = state.borrow(); state.resource_table.get::<Http2Client>(client_rid)? }; let mut client = RcRef::map(&resource, |r| &r.client).borrow_mut().await; poll_fn(|cx| client.poll_ready(cx)).await?; let (response, stream) = client.send_request(request, false).unwrap(); let stream_id = stream.stream_id(); let stream_rid = state.borrow_mut().resource_table.add(Http2ClientStream { response: AsyncRefCell::new(response), stream: AsyncRefCell::new(stream), }); Ok((stream_rid, stream_id.into())) } #[op2(async)] pub async fn op_http2_client_send_data( state: Rc<RefCell<OpState>>, #[smi] stream_rid: ResourceId, #[buffer] data: JsBuffer, end_of_stream: bool, ) -> Result<(), Http2Error> { let resource = state .borrow() .resource_table .get::<Http2ClientStream>(stream_rid)?; let mut stream = RcRef::map(&resource, |r| &r.stream).borrow_mut().await; stream.send_data(data.to_vec().into(), end_of_stream)?; Ok(()) } #[op2(async)] pub async fn op_http2_client_reset_stream( state: Rc<RefCell<OpState>>, #[smi] stream_rid: ResourceId, #[smi] code: u32, ) -> Result<(), ResourceError> { let resource = state .borrow() .resource_table .get::<Http2ClientStream>(stream_rid)?; let mut stream = RcRef::map(&resource, |r| &r.stream).borrow_mut().await; stream.send_reset(h2::Reason::from(code)); Ok(()) } #[op2(async)] pub async fn op_http2_client_send_trailers( state: Rc<RefCell<OpState>>, #[smi] stream_rid: ResourceId, #[serde] trailers: Vec<(ByteString, ByteString)>, ) -> Result<(), Http2Error> { let resource = state .borrow() .resource_table .get::<Http2ClientStream>(stream_rid)?; let mut stream = RcRef::map(&resource, |r| &r.stream).borrow_mut().await; let mut trailers_map = http::HeaderMap::new(); for (name, value) in trailers { trailers_map.insert( HeaderName::from_bytes(&name).unwrap(), HeaderValue::from_bytes(&value).unwrap(), ); } stream.send_trailers(trailers_map)?; Ok(()) } #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub struct Http2ClientResponse { headers: Vec<(ByteString, ByteString)>, body_rid: ResourceId, status_code: u16, } #[op2(async)] #[serde] pub async fn op_http2_client_get_response( state: Rc<RefCell<OpState>>, #[smi] stream_rid: ResourceId, ) -> Result<(Http2ClientResponse, bool), Http2Error> { let resource = state .borrow() .resource_table .get::<Http2ClientStream>(stream_rid)?; let mut response_future = RcRef::map(&resource, |r| &r.response).borrow_mut().await; let response = (&mut *response_future).await?; let (parts, body) = response.into_parts(); let status = parts.status; let mut res_headers = Vec::new(); for (key, val) in parts.headers.iter() { res_headers.push((key.as_str().into(), val.as_bytes().into())); } let end_stream = body.is_end_stream(); let (trailers_tx, trailers_rx) = tokio::sync::oneshot::channel(); let body_rid = state .borrow_mut() .resource_table .add(Http2ClientResponseBody { body: AsyncRefCell::new(body), trailers_rx: AsyncRefCell::new(Some(trailers_rx)), trailers_tx: AsyncRefCell::new(Some(trailers_tx)), }); Ok(( Http2ClientResponse { headers: res_headers, body_rid, status_code: status.into(), }, end_stream, )) } enum DataOrTrailers { Data(Bytes), Trailers(HeaderMap), Eof, } fn poll_data_or_trailers( cx: &mut std::task::Context, body: &mut RecvStream, ) -> Poll<Result<DataOrTrailers, h2::Error>> { if let Poll::Ready(trailers) = body.poll_trailers(cx) { match trailers? { Some(trailers) => { return Poll::Ready(Ok(DataOrTrailers::Trailers(trailers))); } _ => { return Poll::Ready(Ok(DataOrTrailers::Eof)); } } } if let Poll::Ready(Some(data)) = body.poll_data(cx) { let data = data?; body.flow_control().release_capacity(data.len())?; return Poll::Ready(Ok(DataOrTrailers::Data(data))); // If `poll_data` returns `Ready(None)`, poll one more time to check for trailers } // Return pending here as poll_data will keep the waker Poll::Pending } #[op2(async)] #[serde] pub async fn op_http2_client_get_response_body_chunk( state: Rc<RefCell<OpState>>, #[smi] body_rid: ResourceId, ) -> Result<(Option<Vec<u8>>, bool, bool), Http2Error> { let resource = state .borrow() .resource_table .get::<Http2ClientResponseBody>(body_rid)?; let mut body = RcRef::map(&resource, |r| &r.body).borrow_mut().await; loop { let result = poll_fn(|cx| poll_data_or_trailers(cx, &mut body)).await; if let Err(err) = result { match err.reason() { Some(Reason::NO_ERROR) => return Ok((None, true, false)), Some(Reason::CANCEL) => return Ok((None, false, true)), _ => return Err(err.into()), } } match result.unwrap() { DataOrTrailers::Data(data) => { return Ok((Some(data.to_vec()), false, false)); } DataOrTrailers::Trailers(trailers) => { if let Some(trailers_tx) = RcRef::map(&resource, |r| &r.trailers_tx) .borrow_mut() .await .take() { _ = trailers_tx.send(Some(trailers)); }; continue; } DataOrTrailers::Eof => { RcRef::map(&resource, |r| &r.trailers_tx) .borrow_mut() .await .take(); return Ok((None, true, false)); } }; } } #[op2(async)] #[serde] pub async fn op_http2_client_get_response_trailers( state: Rc<RefCell<OpState>>, #[smi] body_rid: ResourceId, ) -> Result<Option<Vec<(ByteString, ByteString)>>, ResourceError> { let resource = state .borrow() .resource_table .get::<Http2ClientResponseBody>(body_rid)?; let trailers = RcRef::map(&resource, |r| &r.trailers_rx) .borrow_mut() .await .take(); if let Some(trailers) = trailers { match trailers.await { Ok(Some(trailers)) => { let mut v = Vec::with_capacity(trailers.len()); for (key, value) in trailers.iter() { v.push(( ByteString::from(key.as_str()), ByteString::from(value.as_bytes()), )); } Ok(Some(v)) } _ => Ok(None), } } else { Ok(None) } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/buffer.rs
ext/node/ops/buffer.rs
// Copyright 2018-2025 the Deno authors. MIT license. use deno_core::op2; use deno_core::v8; use deno_error::JsErrorBox; #[op2(fast)] pub fn op_is_ascii(#[buffer] buf: &[u8]) -> bool { buf.is_ascii() } #[op2(fast)] pub fn op_is_utf8(#[buffer] buf: &[u8]) -> bool { std::str::from_utf8(buf).is_ok() } #[op2] #[buffer] pub fn op_transcode( #[buffer] source: &[u8], #[string] from_encoding: &str, #[string] to_encoding: &str, ) -> Result<Vec<u8>, JsErrorBox> { match (from_encoding, to_encoding) { ("utf8", "ascii") => Ok(utf8_to_ascii(source)), ("utf8", "latin1") => Ok(utf8_to_latin1(source)), ("utf8", "utf16le") => utf8_to_utf16le(source), ("utf16le", "utf8") => utf16le_to_utf8(source), ("latin1", "utf16le") | ("ascii", "utf16le") => { Ok(latin1_ascii_to_utf16le(source)) } (from, to) => Err(JsErrorBox::generic(format!( "Unable to transcode Buffer {from}->{to}" ))), } } fn latin1_ascii_to_utf16le(source: &[u8]) -> Vec<u8> { let mut result = Vec::with_capacity(source.len() * 2); for &byte in source { result.push(byte); result.push(0); } result } fn utf16le_to_utf8(source: &[u8]) -> Result<Vec<u8>, JsErrorBox> { let ucs2_vec: Vec<u16> = source .chunks(2) .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]])) .collect(); String::from_utf16(&ucs2_vec) .map(|utf8_string| utf8_string.into_bytes()) .map_err(|e| JsErrorBox::generic(format!("Invalid UTF-16 sequence: {}", e))) } fn utf8_to_utf16le(source: &[u8]) -> Result<Vec<u8>, JsErrorBox> { let utf8_string = std::str::from_utf8(source).map_err(JsErrorBox::from_err)?; let ucs2_vec: Vec<u16> = utf8_string.encode_utf16().collect(); let bytes: Vec<u8> = ucs2_vec.iter().flat_map(|&x| x.to_le_bytes()).collect(); Ok(bytes) } fn utf8_to_latin1(source: &[u8]) -> Vec<u8> { let mut latin1_bytes = Vec::with_capacity(source.len()); let mut i = 0; while i < source.len() { match source[i] { byte if byte <= 0x7F => { // ASCII character latin1_bytes.push(byte); i += 1; } byte if (0xC2..=0xDF).contains(&byte) && i + 1 < source.len() => { // 2-byte UTF-8 sequence let codepoint = ((byte as u16 & 0x1F) << 6) | (source[i + 1] as u16 & 0x3F); latin1_bytes.push(if codepoint <= 0xFF { codepoint as u8 } else { b'?' }); i += 2; } _ => { // 3-byte or 4-byte UTF-8 sequence, or invalid UTF-8 latin1_bytes.push(b'?'); // Skip to the next valid UTF-8 start byte i += 1; while i < source.len() && (source[i] & 0xC0) == 0x80 { i += 1; } } } } latin1_bytes } fn utf8_to_ascii(source: &[u8]) -> Vec<u8> { let mut ascii_bytes = Vec::with_capacity(source.len()); let mut i = 0; while i < source.len() { match source[i] { byte if byte <= 0x7F => { // ASCII character ascii_bytes.push(byte); i += 1; } _ => { // Non-ASCII character ascii_bytes.push(b'?'); // Skip to the next valid UTF-8 start byte i += 1; while i < source.len() && (source[i] & 0xC0) == 0x80 { i += 1; } } } } ascii_bytes } #[op2(fast)] #[smi] pub fn op_node_buffer_compare( #[buffer] buf1: &[u8], #[buffer] buf2: &[u8], ) -> i32 { buf1.cmp(buf2) as i32 } #[op2(fast)] #[smi] pub fn op_node_buffer_compare_offset( #[buffer] source: &[u8], #[buffer] target: &[u8], #[smi] source_start: usize, #[smi] target_start: usize, #[smi] source_end: usize, #[smi] target_end: usize, ) -> Result<i32, JsErrorBox> { if source_start > source.len() { return Err(JsErrorBox::from_err(BufferError::OutOfRangeNamed( "sourceStart".to_string(), ))); } if target_start > target.len() { return Err(JsErrorBox::from_err(BufferError::OutOfRangeNamed( "targetStart".to_string(), ))); } if source_start > source_end { panic!("source_start > source_end"); } if target_start > target_end { panic!("target_start > target_end"); } Ok( source[source_start..source_end].cmp(&target[target_start..target_end]) as i32, ) } #[op2] pub fn op_node_decode_utf8<'a>( scope: &mut v8::PinScope<'a, '_>, buf: v8::Local<v8::ArrayBufferView>, start: v8::Local<v8::Value>, end: v8::Local<v8::Value>, ) -> Result<v8::Local<'a, v8::String>, JsErrorBox> { let buf = buf.get_contents(&mut [0; v8::TYPED_ARRAY_MAX_SIZE_IN_HEAP]); let start = parse_array_index(scope, start, 0).map_err(JsErrorBox::from_err)?; let mut end = parse_array_index(scope, end, buf.len()).map_err(JsErrorBox::from_err)?; if end < start { end = start; } if end > buf.len() { return Err(JsErrorBox::from_err(BufferError::OutOfRange)); } let buffer = &buf[start..end]; if buffer.len() <= 256 && buffer.is_ascii() { v8::String::new_from_one_byte(scope, buffer, v8::NewStringType::Normal) .ok_or_else(|| JsErrorBox::from_err(BufferError::StringTooLong)) } else { v8::String::new_from_utf8(scope, buffer, v8::NewStringType::Normal) .ok_or_else(|| JsErrorBox::from_err(BufferError::StringTooLong)) } } #[derive(Debug, thiserror::Error, deno_error::JsError)] enum BufferError { #[error( "Cannot create a string longer than 0x{:x} characters", v8::String::MAX_LENGTH )] #[class(generic)] #[property("code" = "ERR_STRING_TOO_LONG")] StringTooLong, #[error("Invalid type")] #[class(generic)] InvalidType, #[error("Index out of range")] #[class(range)] #[property("code" = "ERR_OUT_OF_RANGE")] OutOfRange, #[error("The value of \"{0}\" is out of range.")] #[class(range)] #[property("code" = "ERR_OUT_OF_RANGE")] OutOfRangeNamed(String), } #[inline(always)] fn parse_array_index( scope: &mut v8::PinScope<'_, '_>, arg: v8::Local<v8::Value>, default: usize, ) -> Result<usize, BufferError> { if arg.is_undefined() { return Ok(default); } let Some(arg) = arg.integer_value(scope) else { return Err(BufferError::InvalidType); }; if arg < 0 { return Err(BufferError::OutOfRange); } if arg > isize::MAX as i64 { return Err(BufferError::OutOfRange); } Ok(arg as usize) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/inspector.rs
ext/node/ops/inspector.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::RefCell; use std::rc::Rc; use deno_core::GarbageCollected; use deno_core::InspectorMsg; use deno_core::InspectorSessionKind; use deno_core::JsRuntimeInspector; use deno_core::OpState; use deno_core::op2; use deno_core::v8; use deno_error::JsErrorBox; use deno_permissions::PermissionsContainer; pub struct InspectorServerUrl(pub String); #[op2(fast)] pub fn op_inspector_enabled() -> bool { // TODO: hook up to InspectorServer false } #[op2(stack_trace)] pub fn op_inspector_open( _state: &mut OpState, _port: Option<u16>, #[string] _host: Option<String>, ) -> Result<(), JsErrorBox> { // TODO: hook up to InspectorServer /* let server = state.borrow_mut::<InspectorServer>(); if let Some(host) = host { server.set_host(host); } if let Some(port) = port { server.set_port(port); } state .borrow_mut::<P>() .check_net((server.host(), Some(server.port())), "inspector.open")?; */ Ok(()) } #[op2(fast)] pub fn op_inspector_close() { // TODO: hook up to InspectorServer } #[op2] #[string] pub fn op_inspector_url( state: &mut OpState, ) -> Result<Option<String>, InspectorConnectError> { state .borrow_mut::<PermissionsContainer>() .check_sys("inspector", "inspector.url")?; Ok( state .try_borrow::<InspectorServerUrl>() .map(|url| url.0.to_string()), ) } #[op2(fast)] pub fn op_inspector_wait(state: &OpState) -> bool { match state.try_borrow::<Rc<JsRuntimeInspector>>() { Some(inspector) => { inspector.wait_for_session_and_break_on_next_statement(); true } None => false, } } #[op2(fast)] pub fn op_inspector_emit_protocol_event( #[string] _event_name: String, #[string] _params: String, ) { // TODO: inspector channel & protocol notifications } struct JSInspectorSession { session: RefCell<Option<deno_core::LocalInspectorSession>>, } // SAFETY: we're sure this can be GCed unsafe impl GarbageCollected for JSInspectorSession { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"JSInspectorSession" } } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum InspectorConnectError { #[class(inherit)] #[error(transparent)] Permission( #[from] #[inherit] deno_permissions::PermissionCheckError, ), #[class(generic)] #[error("connectToMainThread not supported")] ConnectToMainThreadUnsupported, } #[op2(stack_trace)] #[cppgc] pub fn op_inspector_connect<'s>( isolate: &v8::Isolate, scope: &mut v8::PinScope<'s, '_>, state: &mut OpState, connect_to_main_thread: bool, callback: v8::Local<'s, v8::Function>, ) -> Result<JSInspectorSession, InspectorConnectError> { state .borrow_mut::<PermissionsContainer>() .check_sys("inspector", "inspector.Session.connect")?; if connect_to_main_thread { return Err(InspectorConnectError::ConnectToMainThreadUnsupported); } let context = scope.get_current_context(); let context = v8::Global::new(scope, context); let callback = v8::Global::new(scope, callback); let inspector = state.borrow::<Rc<JsRuntimeInspector>>().clone(); // SAFETY: just grabbing the raw pointer let isolate = unsafe { isolate.as_raw_isolate_ptr() }; // The inspector connection does not keep the event loop alive but // when the inspector sends a message to the frontend, the JS that // that runs may keep the event loop alive so we have to call back // synchronously, instead of using the usual LocalInspectorSession // UnboundedReceiver<InspectorMsg> API. let callback = Box::new(move |message: InspectorMsg| { // SAFETY: This function is called directly by the inspector, so // 1) The isolate is still valid // 2) We are on the same thread as the Isolate let mut isolate = unsafe { v8::Isolate::from_raw_isolate_ptr(isolate) }; v8::callback_scope!(unsafe let scope, &mut isolate); let context = v8::Local::new(scope, context.clone()); let scope = &mut v8::ContextScope::new(scope, context); v8::tc_scope!(let scope, scope); let recv = v8::undefined(scope); if let Some(message) = v8::String::new(scope, &message.content) { let callback = v8::Local::new(scope, callback.clone()); callback.call(scope, recv.into(), &[message.into()]); } }); let session = JsRuntimeInspector::create_local_session( inspector, callback, InspectorSessionKind::NonBlocking { wait_for_disconnect: false, }, ); Ok(JSInspectorSession { session: RefCell::new(Some(session)), }) } #[op2(fast, reentrant)] pub fn op_inspector_dispatch( #[cppgc] inspector: &JSInspectorSession, #[string] message: String, ) { if let Some(session) = &mut *inspector.session.borrow_mut() { session.dispatch(message); } } #[op2(fast)] pub fn op_inspector_disconnect(#[cppgc] inspector: &JSInspectorSession) { inspector.session.borrow_mut().take(); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/ipc.rs
ext/node/ops/ipc.rs
// Copyright 2018-2025 the Deno authors. MIT license. pub use impl_::*; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum ChildIpcSerialization { Json, Advanced, } impl std::str::FromStr for ChildIpcSerialization { type Err = deno_core::anyhow::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "json" => Ok(ChildIpcSerialization::Json), "advanced" => Ok(ChildIpcSerialization::Advanced), _ => Err(deno_core::anyhow::anyhow!( "Invalid serialization type: {}", s )), } } } pub struct ChildPipeFd(pub i64, pub ChildIpcSerialization); mod impl_ { use std::cell::RefCell; use std::future::Future; use std::io; use std::rc::Rc; use deno_core::CancelFuture; use deno_core::OpState; use deno_core::RcRef; use deno_core::ResourceId; use deno_core::ToV8; use deno_core::op2; use deno_core::serde; use deno_core::serde::Serializer; use deno_core::serde_json; use deno_core::v8; use deno_core::v8::ValueDeserializerHelper; use deno_core::v8::ValueSerializerHelper; use deno_error::JsErrorBox; pub use deno_process::ipc::INITIAL_CAPACITY; use deno_process::ipc::IpcAdvancedStreamError; use deno_process::ipc::IpcAdvancedStreamResource; use deno_process::ipc::IpcJsonStreamError; pub use deno_process::ipc::IpcJsonStreamResource; pub use deno_process::ipc::IpcRefTracker; use serde::Serialize; use crate::ChildPipeFd; use crate::ops::ipc::ChildIpcSerialization; /// Wrapper around v8 value that implements Serialize. struct SerializeWrapper<'a, 'b, 'c>( RefCell<&'b mut v8::PinScope<'a, 'c>>, v8::Local<'a, v8::Value>, ); impl Serialize for SerializeWrapper<'_, '_, '_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serialize_v8_value(*self.0.borrow_mut(), self.1, serializer) } } /// Serialize a v8 value directly into a serde serializer. /// This allows us to go from v8 values to JSON without having to /// deserialize into a `serde_json::Value` and then reserialize to JSON fn serialize_v8_value<'a, S: Serializer>( scope: &mut v8::PinScope<'a, '_>, value: v8::Local<'a, v8::Value>, ser: S, ) -> Result<S::Ok, S::Error> { use serde::ser::Error; if value.is_null_or_undefined() { ser.serialize_unit() } else if value.is_number() || value.is_number_object() { let num_value = value.number_value(scope).unwrap(); if (num_value as i64 as f64) == num_value { ser.serialize_i64(num_value as i64) } else { ser.serialize_f64(num_value) } } else if value.is_string() { let str = deno_core::serde_v8::to_utf8(value.try_into().unwrap(), scope); ser.serialize_str(&str) } else if value.is_string_object() { let str = deno_core::serde_v8::to_utf8( value.to_string(scope).ok_or_else(|| { S::Error::custom(deno_error::JsErrorBox::generic( "toString on string object failed", )) })?, scope, ); ser.serialize_str(&str) } else if value.is_boolean() { ser.serialize_bool(value.is_true()) } else if value.is_boolean_object() { ser.serialize_bool(value.boolean_value(scope)) } else if value.is_array() { use serde::ser::SerializeSeq; let array = value.cast::<v8::Array>(); let length = array.length(); let mut seq = ser.serialize_seq(Some(length as usize))?; for i in 0..length { let element = array.get_index(scope, i).unwrap(); seq .serialize_element(&SerializeWrapper(RefCell::new(scope), element))?; } seq.end() } else if value.is_object() { use serde::ser::SerializeMap; if value.is_array_buffer_view() { let buffer = value.cast::<v8::ArrayBufferView>(); let mut buf = vec![0u8; buffer.byte_length()]; let copied = buffer.copy_contents(&mut buf); debug_assert_eq!(copied, buf.len()); return ser.serialize_bytes(&buf); } let object = value.cast::<v8::Object>(); // node uses `JSON.stringify`, so to match its behavior (and allow serializing custom objects) // we need to respect the `toJSON` method if it exists. let to_json_key = v8::String::new_from_utf8( scope, b"toJSON", v8::NewStringType::Internalized, ) .unwrap() .into(); if let Some(to_json) = object.get(scope, to_json_key) && let Ok(to_json) = to_json.try_cast::<v8::Function>() { let json_value = to_json.call(scope, object.into(), &[]).unwrap(); return serialize_v8_value(scope, json_value, ser); } let keys = object .get_own_property_names( scope, v8::GetPropertyNamesArgs { ..Default::default() }, ) .unwrap(); let num_keys = keys.length(); let mut map = ser.serialize_map(Some(num_keys as usize))?; for i in 0..num_keys { let key = keys.get_index(scope, i).unwrap(); let key_str = key.to_rust_string_lossy(scope); let value = object.get(scope, key).unwrap(); if value.is_undefined() { continue; } map.serialize_entry( &key_str, &SerializeWrapper(RefCell::new(scope), value), )?; } map.end() } else { // TODO(nathanwhit): better error message Err(S::Error::custom(JsErrorBox::type_error(format!( "Unsupported type: {}", value.type_repr() )))) } } // Open IPC pipe from bootstrap options. #[op2] #[to_v8] pub fn op_node_child_ipc_pipe( state: &mut OpState, ) -> Result<Option<(ResourceId, u8)>, io::Error> { let (fd, serialization) = match state.try_borrow_mut::<crate::ChildPipeFd>() { Some(ChildPipeFd(fd, serialization)) => (*fd, *serialization), None => return Ok(None), }; log::debug!("op_node_child_ipc_pipe: {:?}, {:?}", fd, serialization); let ref_tracker = IpcRefTracker::new(state.external_ops_tracker.clone()); match serialization { ChildIpcSerialization::Json => Ok(Some(( state .resource_table .add(IpcJsonStreamResource::new(fd, ref_tracker)?), 0, ))), ChildIpcSerialization::Advanced => Ok(Some(( state .resource_table .add(IpcAdvancedStreamResource::new(fd, ref_tracker)?), 1, ))), } } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum IpcError { #[class(inherit)] #[error(transparent)] Resource(#[from] deno_core::error::ResourceError), #[class(inherit)] #[error(transparent)] IpcAdvancedStream(#[from] IpcAdvancedStreamError), #[class(inherit)] #[error(transparent)] IpcJsonStream(#[from] IpcJsonStreamError), #[class(inherit)] #[error(transparent)] Canceled(#[from] deno_core::Canceled), #[class(inherit)] #[error("failed to serialize json value: {0}")] SerdeJson(serde_json::Error), #[class(type)] #[error("Failed to read header")] ReadHeaderFailed, #[class(type)] #[error("Failed to read value")] ReadValueFailed, } #[op2(async)] pub fn op_node_ipc_write_json<'a>( scope: &mut v8::PinScope<'a, '_>, state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, value: v8::Local<'a, v8::Value>, // using an array as an "out parameter". // index 0 is a boolean indicating whether the queue is under the limit. // // ideally we would just return `Result<(impl Future, bool), ..>`, but that's not // supported by `op2` currently. queue_ok: v8::Local<'a, v8::Array>, ) -> Result<impl Future<Output = Result<(), io::Error>> + use<>, IpcError> { let mut serialized = Vec::with_capacity(64); let mut ser = serde_json::Serializer::new(&mut serialized); serialize_v8_value(scope, value, &mut ser).map_err(IpcError::SerdeJson)?; serialized.push(b'\n'); let stream = state .borrow() .resource_table .get::<IpcJsonStreamResource>(rid)?; let old = stream .queued_bytes .fetch_add(serialized.len(), std::sync::atomic::Ordering::Relaxed); if old + serialized.len() > 2 * INITIAL_CAPACITY { // sending messages too fast let v = false.to_v8(scope).unwrap(); // Infallible queue_ok.set_index(scope, 0, v); } Ok(async move { let cancel = stream.cancel.clone(); let result = stream .clone() .write_msg_bytes(&serialized) .or_cancel(cancel) .await; // adjust count even on error stream .queued_bytes .fetch_sub(serialized.len(), std::sync::atomic::Ordering::Relaxed); result??; Ok(()) }) } pub struct AdvancedSerializerDelegate { constants: AdvancedIpcConstants, } impl AdvancedSerializerDelegate { fn new(constants: AdvancedIpcConstants) -> Self { Self { constants } } } const ARRAY_BUFFER_VIEW_TAG: u32 = 0; const NOT_ARRAY_BUFFER_VIEW_TAG: u32 = 1; fn ab_view_to_index<'s>( scope: &mut v8::PinScope<'s, '_>, view: v8::Local<'s, v8::ArrayBufferView>, constants: &AdvancedIpcConstants, ) -> Option<u32> { if view.is_int8_array() { Some(0) } else if view.is_uint8_array() { let constructor = view .get( scope, v8::Local::new(scope, &constants.inner.constructor_key).into(), ) .unwrap(); let buffer_constructor = v8::Local::<v8::Value>::from(v8::Local::new( scope, &constants.inner.buffer_constructor, )); if constructor == buffer_constructor { Some(10) } else { Some(1) } } else if view.is_uint8_clamped_array() { Some(2) } else if view.is_int16_array() { Some(3) } else if view.is_uint16_array() { Some(4) } else if view.is_int32_array() { Some(5) } else if view.is_uint32_array() { Some(6) } else if view.is_float32_array() { Some(7) } else if view.is_float64_array() { Some(8) } else if view.is_data_view() { Some(9) } else if view.is_big_int64_array() { Some(11) } else if view.is_big_uint64_array() { Some(12) } else if view.is_float16_array() { Some(13) } else { None } } impl v8::ValueSerializerImpl for AdvancedSerializerDelegate { fn throw_data_clone_error<'s>( &self, scope: &mut v8::PinScope<'s, '_>, message: v8::Local<'s, v8::String>, ) { let error = v8::Exception::type_error(scope, message); scope.throw_exception(error); } fn has_custom_host_object(&self, _isolate: &v8::Isolate) -> bool { false } fn write_host_object<'s>( &self, scope: &mut v8::PinScope<'s, '_>, object: v8::Local<'s, v8::Object>, value_serializer: &dyn v8::ValueSerializerHelper, ) -> Option<bool> { if object.is_array_buffer_view() { let ab_view = object.cast::<v8::ArrayBufferView>(); value_serializer.write_uint32(ARRAY_BUFFER_VIEW_TAG); let Some(index) = ab_view_to_index(scope, ab_view, &self.constants) else { scope.throw_exception(v8::Exception::type_error( scope, v8::String::new_from_utf8( scope, format!("Unserializable host object: {}", object.type_repr()) .as_bytes(), v8::NewStringType::Normal, ) .unwrap(), )); return None; }; value_serializer.write_uint32(index); value_serializer.write_uint32(ab_view.byte_length() as u32); let mut storage = [0u8; v8::TYPED_ARRAY_MAX_SIZE_IN_HEAP]; let slice = ab_view.get_contents(&mut storage); value_serializer.write_raw_bytes(slice); Some(true) } else { value_serializer.write_uint32(NOT_ARRAY_BUFFER_VIEW_TAG); value_serializer .write_value(scope.get_current_context(), object.into()); Some(true) } } fn get_shared_array_buffer_id<'s>( &self, _scope: &mut v8::PinScope<'s, '_>, _shared_array_buffer: v8::Local<'s, v8::SharedArrayBuffer>, ) -> Option<u32> { None } } #[derive(Clone)] struct AdvancedIpcConstants { inner: Rc<AdvancedIpcConstantsInner>, } struct AdvancedIpcConstantsInner { buffer_constructor: v8::Global<v8::Function>, constructor_key: v8::Global<v8::String>, fast_buffer_prototype: v8::Global<v8::Object>, } #[op2(fast)] pub fn op_node_ipc_buffer_constructor( scope: &mut v8::PinScope<'_, '_>, state: &mut OpState, buffer_constructor: v8::Local<'_, v8::Function>, fast_buffer_prototype: v8::Local<'_, v8::Object>, ) { if state.has::<AdvancedIpcConstants>() { return; } let constants = AdvancedIpcConstants { inner: Rc::new(AdvancedIpcConstantsInner { buffer_constructor: v8::Global::new(scope, buffer_constructor), constructor_key: v8::Global::new( scope, v8::String::new_from_utf8( scope, b"constructor", v8::NewStringType::Internalized, ) .unwrap(), ), fast_buffer_prototype: v8::Global::new(scope, fast_buffer_prototype), }), }; state.put(constants); } #[op2(async)] pub fn op_node_ipc_write_advanced<'a>( scope: &mut v8::PinScope<'a, '_>, state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, value: v8::Local<'a, v8::Value>, // using an array as an "out parameter". // index 0 is a boolean indicating whether the queue is under the limit. // // ideally we would just return `Result<(impl Future, bool), ..>`, but that's not // supported by `op2` currently. queue_ok: v8::Local<'a, v8::Array>, ) -> Result<impl Future<Output = Result<(), io::Error>> + use<>, IpcError> { let constants = state.borrow().borrow::<AdvancedIpcConstants>().clone(); let serializer = AdvancedSerializer::new(scope, constants); let serialized = serializer.serialize(scope, value)?; let stream = state .borrow() .resource_table .get::<IpcAdvancedStreamResource>(rid)?; let old = stream .queued_bytes .fetch_add(serialized.len(), std::sync::atomic::Ordering::Relaxed); if old + serialized.len() > 2 * INITIAL_CAPACITY { // sending messages too fast let Ok(v) = false.to_v8(scope); queue_ok.set_index(scope, 0, v); } Ok(async move { let cancel = stream.cancel.clone(); let result = stream .clone() .write_msg_bytes(&serialized) .or_cancel(cancel) .await; // adjust count even on error stream .queued_bytes .fetch_sub(serialized.len(), std::sync::atomic::Ordering::Relaxed); result??; Ok(()) }) } struct AdvancedSerializer { inner: v8::ValueSerializer<'static>, } impl AdvancedSerializer { fn new( scope: &mut v8::PinScope<'_, '_>, constants: AdvancedIpcConstants, ) -> Self { let inner = v8::ValueSerializer::new( scope, Box::new(AdvancedSerializerDelegate::new(constants)), ); inner.set_treat_array_buffer_views_as_host_objects(true); Self { inner } } fn serialize<'s, 'i>( &self, scope: &mut v8::PinScope<'s, 'i>, value: v8::Local<'s, v8::Value>, ) -> Result<Vec<u8>, IpcError> { self.inner.write_raw_bytes(&[0, 0, 0, 0]); self.inner.write_header(); let context = scope.get_current_context(); self.inner.write_value(context, value); let mut ser = self.inner.release(); let length = ser.len() - 4; ser[0] = ((length >> 24) & 0xFF) as u8; ser[1] = ((length >> 16) & 0xFF) as u8; ser[2] = ((length >> 8) & 0xFF) as u8; ser[3] = (length & 0xFF) as u8; Ok(ser) } } struct AdvancedIpcDeserializer { inner: v8::ValueDeserializer<'static>, } struct AdvancedIpcDeserializerDelegate { constants: AdvancedIpcConstants, } impl v8::ValueDeserializerImpl for AdvancedIpcDeserializerDelegate { fn read_host_object<'s>( &self, scope: &mut v8::PinScope<'s, '_>, deser: &dyn ValueDeserializerHelper, ) -> Option<v8::Local<'s, v8::Object>> { let throw_error = |message: &str| { scope.throw_exception(v8::Exception::type_error( scope, v8::String::new_from_utf8( scope, message.as_bytes(), v8::NewStringType::Normal, ) .unwrap(), )); None }; let mut tag = 0; if !deser.read_uint32(&mut tag) { return throw_error("Failed to read tag"); } match tag { ARRAY_BUFFER_VIEW_TAG => { let mut index = 0; if !deser.read_uint32(&mut index) { return throw_error("Failed to read array buffer view type tag"); } let mut byte_length = 0; if !deser.read_uint32(&mut byte_length) { return throw_error("Failed to read byte length"); } let Some(buf) = deser.read_raw_bytes(byte_length as usize) else { return throw_error("failed to read bytes for typed array"); }; let array_buffer = v8::ArrayBuffer::new(scope, byte_length as usize); // SAFETY: array_buffer is valid as v8 is keeping it alive, and is byte_length bytes // buf is also byte_length bytes long unsafe { std::ptr::copy( buf.as_ptr(), array_buffer.data().unwrap().as_ptr().cast::<u8>(), byte_length as usize, ); } let value = match index { 0 => { v8::Int8Array::new(scope, array_buffer, 0, byte_length as usize) .unwrap() .into() } 1 => { v8::Uint8Array::new(scope, array_buffer, 0, byte_length as usize) .unwrap() .into() } 10 => { let obj: v8::Local<v8::Object> = v8::Uint8Array::new( scope, array_buffer, 0, byte_length as usize, )? .into(); let fast_proto = v8::Local::new( scope, &self.constants.inner.fast_buffer_prototype, ); obj.set_prototype(scope, fast_proto.into()); obj } 2 => v8::Uint8ClampedArray::new( scope, array_buffer, 0, byte_length as usize, )? .into(), 3 => v8::Int16Array::new( scope, array_buffer, 0, byte_length as usize / 2, )? .into(), 4 => v8::Uint16Array::new( scope, array_buffer, 0, byte_length as usize / 2, )? .into(), 5 => v8::Int32Array::new( scope, array_buffer, 0, byte_length as usize / 4, )? .into(), 6 => v8::Uint32Array::new( scope, array_buffer, 0, byte_length as usize / 4, )? .into(), 7 => v8::Float32Array::new( scope, array_buffer, 0, byte_length as usize / 4, ) .unwrap() .into(), 8 => v8::Float64Array::new( scope, array_buffer, 0, byte_length as usize / 8, )? .into(), 9 => { v8::DataView::new(scope, array_buffer, 0, byte_length as usize) .into() } 11 => v8::BigInt64Array::new( scope, array_buffer, 0, byte_length as usize / 8, )? .into(), 12 => v8::BigUint64Array::new( scope, array_buffer, 0, byte_length as usize / 8, )? .into(), // TODO(nathanwhit): this should just be `into()`, but I forgot to impl it in rusty_v8. // the underlying impl is just a transmute though. // SAFETY: float16array is an object 13 => unsafe { std::mem::transmute::< v8::Local<v8::Float16Array>, v8::Local<v8::Object>, >(v8::Float16Array::new( scope, array_buffer, 0, byte_length as usize / 2, )?) }, _ => return None, }; Some(value) } NOT_ARRAY_BUFFER_VIEW_TAG => { let value = deser.read_value(scope.get_current_context()); Some(value.unwrap_or_else(|| v8::null(scope).into()).cast()) } _ => { throw_error(&format!("Invalid tag: {}", tag)); None } } } } impl AdvancedIpcDeserializer { fn new( scope: &mut v8::PinScope<'_, '_>, constants: AdvancedIpcConstants, msg_bytes: &[u8], ) -> Self { let inner = v8::ValueDeserializer::new( scope, Box::new(AdvancedIpcDeserializerDelegate { constants }), msg_bytes, ); Self { inner } } } struct AdvancedIpcReadResult { msg_bytes: Option<Vec<u8>>, constants: AdvancedIpcConstants, } fn make_stop_sentinel<'s>( scope: &mut v8::PinScope<'s, '_>, ) -> v8::Local<'s, v8::Value> { let obj = v8::Object::new(scope); obj.set( scope, v8::String::new_from_utf8(scope, b"cmd", v8::NewStringType::Internalized) .unwrap() .into(), v8::String::new_from_utf8( scope, b"NODE_CLOSE", v8::NewStringType::Internalized, ) .unwrap() .into(), ); obj.into() } impl<'a> deno_core::ToV8<'a> for AdvancedIpcReadResult { type Error = IpcError; fn to_v8( self, scope: &mut v8::PinScope<'a, '_>, ) -> Result<v8::Local<'a, v8::Value>, Self::Error> { let Some(msg_bytes) = self.msg_bytes else { return Ok(make_stop_sentinel(scope)); }; let deser = AdvancedIpcDeserializer::new(scope, self.constants, &msg_bytes); let context = scope.get_current_context(); let header_success = deser.inner.read_header(context).unwrap_or(false); if !header_success { return Err(IpcError::ReadHeaderFailed); } let Some(value) = deser.inner.read_value(context) else { return Err(IpcError::ReadValueFailed); }; Ok(value) } } #[op2(async)] #[to_v8] pub async fn op_node_ipc_read_advanced( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<AdvancedIpcReadResult, IpcError> { let stream = state .borrow() .resource_table .get::<IpcAdvancedStreamResource>(rid)?; let cancel = stream.cancel.clone(); let mut stream = RcRef::map(stream, |r| &r.read_half).borrow_mut().await; let msg_bytes = stream.read_msg_bytes().or_cancel(cancel).await??; Ok(AdvancedIpcReadResult { msg_bytes, constants: state.borrow().borrow::<AdvancedIpcConstants>().clone(), }) } /// Value signaling that the other end ipc channel has closed. /// /// Node reserves objects of this form (`{ "cmd": "NODE_<something>"`) /// for internal use, so we use it here as well to avoid breaking anyone. fn stop_sentinel() -> serde_json::Value { serde_json::json!({ "cmd": "NODE_CLOSE" }) } #[op2(async)] #[serde] pub async fn op_node_ipc_read_json( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<serde_json::Value, IpcError> { let stream = state .borrow() .resource_table .get::<IpcJsonStreamResource>(rid)?; let cancel = stream.cancel.clone(); let mut stream = RcRef::map(stream, |r| &r.read_half).borrow_mut().await; let msgs = stream.read_msg().or_cancel(cancel).await??; if let Some(msg) = msgs { Ok(msg) } else { Ok(stop_sentinel()) } } #[op2(fast)] pub fn op_node_ipc_ref( state: &mut OpState, #[smi] rid: ResourceId, serialization_json: bool, ) { if serialization_json { let stream = state .resource_table .get::<IpcJsonStreamResource>(rid) .expect("Invalid resource ID"); stream.ref_tracker.ref_(); } else { let stream = state .resource_table .get::<IpcAdvancedStreamResource>(rid) .expect("Invalid resource ID"); stream.ref_tracker.ref_(); } } #[op2(fast)] pub fn op_node_ipc_unref( state: &mut OpState, #[smi] rid: ResourceId, serialization_json: bool, ) { if serialization_json { let stream = state .resource_table .get::<IpcJsonStreamResource>(rid) .expect("Invalid resource ID"); stream.ref_tracker.unref(); } else { let stream = state .resource_table .get::<IpcAdvancedStreamResource>(rid) .expect("Invalid resource ID"); stream.ref_tracker.unref(); } } #[cfg(test)] mod tests { use deno_core::JsRuntime; use deno_core::RuntimeOptions; use deno_core::v8; fn wrap_expr(s: &str) -> String { format!("(function () {{ return {s}; }})()") } fn serialize_js_to_json(runtime: &mut JsRuntime, js: String) -> String { let val = runtime.execute_script("", js).unwrap(); deno_core::scope!(scope, runtime); let val = v8::Local::new(scope, val); let mut buf = Vec::new(); let mut ser = deno_core::serde_json::Serializer::new(&mut buf); super::serialize_v8_value(scope, val, &mut ser).unwrap(); String::from_utf8(buf).unwrap() } #[test] fn ipc_serialization() { let mut runtime = JsRuntime::new(RuntimeOptions::default()); let cases = [ ("'hello'", "\"hello\""), ("1", "1"), ("1.5", "1.5"), ("Number.NaN", "null"), ("Infinity", "null"), ("Number.MAX_SAFE_INTEGER", &(2i64.pow(53) - 1).to_string()), ( "Number.MIN_SAFE_INTEGER", &(-(2i64.pow(53) - 1)).to_string(), ), ("[1, 2, 3]", "[1,2,3]"), ("new Uint8Array([1,2,3])", "[1,2,3]"), ( "{ a: 1.5, b: { c: new ArrayBuffer(5) }}", r#"{"a":1.5,"b":{"c":{}}}"#, ), ("new Number(1)", "1"), ("new Boolean(true)", "true"), ("true", "true"), (r#"new String("foo")"#, "\"foo\""), ("null", "null"), ( r#"{ a: "field", toJSON() { return "custom"; } }"#, "\"custom\"", ), (r#"{ a: undefined, b: 1 }"#, "{\"b\":1}"), ]; for (input, expect) in cases { let js = wrap_expr(input); let actual = serialize_js_to_json(&mut runtime, js); assert_eq!(actual, expect); } } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/zlib/stream.rs
ext/node/ops/zlib/stream.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ffi::c_int; use std::ops::Deref; use std::ops::DerefMut; use super::mode::Flush; use super::mode::Mode; pub struct StreamWrapper { pub strm: zlib::z_stream, } impl Default for StreamWrapper { fn default() -> Self { Self { strm: zlib::z_stream { next_in: std::ptr::null_mut(), avail_in: 0, total_in: 0, next_out: std::ptr::null_mut(), avail_out: 0, total_out: 0, msg: std::ptr::null_mut(), state: std::ptr::null_mut(), zalloc: super::alloc::zalloc, zfree: super::alloc::zfree, opaque: 0 as zlib::voidpf, data_type: 0, adler: 0, reserved: 0, }, } } } impl Deref for StreamWrapper { type Target = zlib::z_stream; fn deref(&self) -> &Self::Target { &self.strm } } impl DerefMut for StreamWrapper { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.strm } } impl StreamWrapper { pub fn reset(&mut self, mode: Mode) -> c_int { // SAFETY: `self.strm` is an initialized `zlib::z_stream`. unsafe { match mode { Mode::Deflate | Mode::Gzip | Mode::DeflateRaw => { zlib::deflateReset(&mut self.strm) } Mode::Inflate | Mode::Gunzip | Mode::InflateRaw | Mode::Unzip => { zlib::inflateReset(&mut self.strm) } Mode::None => unreachable!(), } } } pub fn end(&mut self, mode: Mode) { // SAFETY: `self.strm` is an initialized `zlib::z_stream`. unsafe { match mode { Mode::Deflate | Mode::Gzip | Mode::DeflateRaw => { zlib::deflateEnd(&mut self.strm); } Mode::Inflate | Mode::Gunzip | Mode::InflateRaw | Mode::Unzip => { zlib::inflateEnd(&mut self.strm); } Mode::None => {} } } } pub fn deflate_init( &mut self, level: c_int, window_bits: c_int, mem_level: c_int, strategy: c_int, ) -> c_int { // SAFETY: `self.strm` is an initialized `zlib::z_stream`. unsafe { zlib::deflateInit2_( &mut self.strm, level, zlib::Z_DEFLATED, window_bits, mem_level, strategy, zlib::zlibVersion(), std::mem::size_of::<zlib::z_stream>() as i32, ) } } pub fn inflate_init(&mut self, window_bits: c_int) -> c_int { // SAFETY: `self.strm` is an initialized `zlib::z_stream`. unsafe { zlib::inflateInit2_( &mut self.strm, window_bits, zlib::zlibVersion(), std::mem::size_of::<zlib::z_stream>() as i32, ) } } pub fn deflate(&mut self, flush: Flush) -> c_int { // SAFETY: `self.strm` is an initialized `zlib::z_stream`. unsafe { zlib::deflate(&mut self.strm, flush as _) } } pub fn inflate(&mut self, flush: Flush) -> c_int { // SAFETY: `self.strm` is an initialized `zlib::z_stream`. unsafe { zlib::inflate(&mut self.strm, flush as _) } } pub fn inflate_set_dictionary(&mut self, dictionary: &[u8]) -> c_int { // SAFETY: `self.strm` is an initialized `zlib::z_stream`. unsafe { zlib::inflateSetDictionary( &mut self.strm, dictionary.as_ptr() as *const _, dictionary.len() as _, ) } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/zlib/alloc.rs
ext/node/ops/zlib/alloc.rs
// Copyright 2018-2025 the Deno authors. MIT license. // Workaround for https://github.com/rust-lang/libz-sys/issues/55 // See https://github.com/rust-lang/flate2-rs/blob/31fb07820345691352aaa64f367c1e482ad9cfdc/src/ffi/c.rs#L60 use std::alloc::Layout; use std::alloc::{self}; use std::os::raw::c_void; use std::ptr; const ALIGN: usize = std::mem::align_of::<usize>(); fn align_up(size: usize, align: usize) -> usize { (size + align - 1) & !(align - 1) } pub extern "C" fn zalloc( _ptr: *mut c_void, items: u32, item_size: u32, ) -> *mut c_void { // We need to multiply `items` and `item_size` to get the actual desired // allocation size. Since `zfree` doesn't receive a size argument we // also need to allocate space for a `usize` as a header so we can store // how large the allocation is to deallocate later. let size = match (items as usize) .checked_mul(item_size as usize) .map(|size| align_up(size, ALIGN)) .and_then(|i| i.checked_add(std::mem::size_of::<usize>())) { Some(i) => i, None => return ptr::null_mut(), }; // Make sure the `size` isn't too big to fail `Layout`'s restrictions let layout = match Layout::from_size_align(size, ALIGN) { Ok(layout) => layout, Err(_) => return ptr::null_mut(), }; // SAFETY: `layout` has non-zero size, guaranteed to be a sentinel address // or a null pointer. unsafe { // Allocate the data, and if successful store the size we allocated // at the beginning and then return an offset pointer. let ptr = alloc::alloc(layout) as *mut usize; if ptr.is_null() { return ptr as *mut c_void; } *ptr = size; ptr.add(1) as *mut c_void } } pub extern "C" fn zfree(_ptr: *mut c_void, address: *mut c_void) { // SAFETY: Move our address being free'd back one pointer, read the size we // stored in `zalloc`, and then free it using the standard Rust // allocator. unsafe { let ptr = (address as *mut usize).offset(-1); let size = *ptr; let layout = Layout::from_size_align_unchecked(size, ALIGN); alloc::dealloc(ptr as *mut u8, layout) } } pub extern "C" fn brotli_alloc( _opaque: *mut brotli::ffi::broccoli::c_void, size: usize, ) -> *mut brotli::ffi::broccoli::c_void { // Allocate space for a `usize` header to store the allocation size let total_size = match size .checked_add(std::mem::size_of::<usize>()) .map(|size| align_up(size, ALIGN)) { Some(i) => i, None => return ptr::null_mut(), }; let layout = match Layout::from_size_align(total_size, ALIGN) { Ok(layout) => layout, Err(_) => return ptr::null_mut(), }; // SAFETY: `layout` has non-zero size unsafe { let ptr = alloc::alloc(layout) as *mut usize; if ptr.is_null() { return ptr as *mut brotli::ffi::broccoli::c_void; } *ptr = total_size; ptr.add(1) as *mut brotli::ffi::broccoli::c_void } } pub extern "C" fn brotli_free( _opaque: *mut brotli::ffi::broccoli::c_void, address: *mut brotli::ffi::broccoli::c_void, ) { if address.is_null() { return; } // SAFETY: Move back one pointer to read the size we stored in `brotli_alloc` unsafe { let ptr = (address as *mut usize).offset(-1); let size = *ptr; let layout = Layout::from_size_align_unchecked(size, ALIGN); alloc::dealloc(ptr as *mut u8, layout) } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/zlib/mod.rs
ext/node/ops/zlib/mod.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::rc::Rc; use brotli::enc::StandardAlloc; use brotli::enc::encode::BrotliEncoderDestroyInstance; use brotli::enc::encode::BrotliEncoderOperation; use brotli::enc::encode::BrotliEncoderStateStruct; use brotli::ffi; use deno_core::op2; use deno_core::v8; use deno_core::v8_static_strings; use deno_error::JsErrorBox; use libc::c_ulong; use zlib::*; mod alloc; pub mod mode; mod stream; use mode::Flush; use mode::Mode; use self::alloc::brotli_alloc; use self::alloc::brotli_free; use self::stream::StreamWrapper; #[inline] fn check(condition: bool, msg: &str) -> Result<(), JsErrorBox> { if condition { Ok(()) } else { Err(JsErrorBox::type_error(msg.to_string())) } } #[derive(Default)] struct ZlibInner { dictionary: Option<Vec<u8>>, err: i32, flush: Flush, init_done: bool, level: i32, mem_level: i32, mode: Mode, strategy: i32, window_bits: i32, write_in_progress: bool, pending_close: bool, gzib_id_bytes_read: u32, result_buffer: Option<*mut u32>, callback: Option<v8::Global<v8::Function>>, strm: StreamWrapper, } const GZIP_HEADER_ID1: u8 = 0x1f; const GZIP_HEADER_ID2: u8 = 0x8b; impl ZlibInner { #[allow(clippy::too_many_arguments)] fn start_write( &mut self, input: &[u8], in_off: u32, in_len: u32, out: &mut [u8], out_off: u32, out_len: u32, flush: Flush, ) -> Result<(), JsErrorBox> { check(self.init_done, "write before init")?; check(!self.write_in_progress, "write already in progress")?; check(!self.pending_close, "close already in progress")?; self.write_in_progress = true; let next_in = input .get(in_off as usize..in_off as usize + in_len as usize) .ok_or_else(|| JsErrorBox::type_error("invalid input range"))? .as_ptr() as *mut _; let next_out = out .get_mut(out_off as usize..out_off as usize + out_len as usize) .ok_or_else(|| JsErrorBox::type_error("invalid output range"))? .as_mut_ptr(); self.strm.avail_in = in_len; self.strm.next_in = next_in; self.strm.avail_out = out_len; self.strm.next_out = next_out; self.flush = flush; Ok(()) } fn do_write(&mut self, flush: Flush) -> Result<(), JsErrorBox> { self.flush = flush; match self.mode { Mode::Deflate | Mode::Gzip | Mode::DeflateRaw => { self.err = self.strm.deflate(flush); } // Auto-detect mode. Mode::Unzip if self.strm.avail_in > 0 => 'blck: { let mut next_expected_header_byte = Some(0); // SAFETY: `self.strm.next_in` is valid pointer to the input buffer. // `self.strm.avail_in` is the length of the input buffer that is only set by // `start_write`. let strm = unsafe { std::slice::from_raw_parts( self.strm.next_in, self.strm.avail_in as usize, ) }; if self.gzib_id_bytes_read == 0 { if strm[0] == GZIP_HEADER_ID1 { self.gzib_id_bytes_read = 1; next_expected_header_byte = Some(1); // Not enough. if self.strm.avail_in == 1 { break 'blck; } } else { self.mode = Mode::Inflate; next_expected_header_byte = None; } } if self.gzib_id_bytes_read == 1 { let byte = match next_expected_header_byte { Some(i) => strm[i], None => break 'blck, }; if byte == GZIP_HEADER_ID2 { self.gzib_id_bytes_read = 2; self.mode = Mode::Gunzip; } else { self.mode = Mode::Inflate; } } else if next_expected_header_byte.is_some() { return Err(JsErrorBox::type_error( "invalid number of gzip magic number bytes read", )); } } _ => {} } match self.mode { Mode::Inflate | Mode::Gunzip | Mode::InflateRaw // We're still reading the header. | Mode::Unzip => { self.err = self.strm.inflate(self.flush); // TODO(@littledivy): Use if let chain when it is stable. // https://github.com/rust-lang/rust/issues/53667 // // Data was encoded with dictionary if let (Z_NEED_DICT, Some(dictionary)) = (self.err, &self.dictionary) { self.err = self.strm.inflate_set_dictionary(dictionary); if self.err == Z_OK { self.err = self.strm.inflate(flush); } else if self.err == Z_DATA_ERROR { self.err = Z_NEED_DICT; } } while self.strm.avail_in > 0 && self.mode == Mode::Gunzip && self.err == Z_STREAM_END // SAFETY: `strm` is a valid pointer to zlib strm. // `strm.next_in` is initialized to the input buffer. && unsafe { *self.strm.next_in } != 0x00 { self.err = self.strm.reset(self.mode); self.err = self.strm.inflate(flush); } } _ => {} } let done = self.strm.avail_out != 0 && self.flush == Flush::Finish; // We're are not done yet, but output buffer is full if self.err == Z_BUF_ERROR && !done { // Set to Z_OK to avoid reporting the error in JS. self.err = Z_OK; } self.write_in_progress = false; Ok(()) } fn init_stream(&mut self) -> Result<(), JsErrorBox> { match self.mode { Mode::Gzip | Mode::Gunzip => self.window_bits += 16, Mode::Unzip => self.window_bits += 32, Mode::DeflateRaw | Mode::InflateRaw => self.window_bits *= -1, _ => {} } self.err = match self.mode { Mode::Deflate | Mode::Gzip | Mode::DeflateRaw => self.strm.deflate_init( self.level, self.window_bits, self.mem_level, self.strategy, ), Mode::Inflate | Mode::Gunzip | Mode::InflateRaw | Mode::Unzip => { self.strm.inflate_init(self.window_bits) } Mode::None => return Err(JsErrorBox::type_error("Unknown mode")), }; self.write_in_progress = false; self.init_done = true; Ok(()) } fn close(&mut self) -> Result<bool, JsErrorBox> { if self.write_in_progress { self.pending_close = true; return Ok(false); } self.pending_close = false; check(self.init_done, "close before init")?; self.strm.end(self.mode); self.mode = Mode::None; Ok(true) } fn reset_stream(&mut self) { self.err = self.strm.reset(self.mode); } fn get_error_info(&self) -> Option<(i32, String)> { let err_str = match self.err { Z_OK | Z_BUF_ERROR => { if self.strm.avail_out != 0 && self.flush == Flush::Finish { "unexpected end of file" } else { return None; } } Z_STREAM_END => return None, Z_NEED_DICT => { if self.dictionary.is_none() { "Missing dictionary" } else { "Bad dictionary" } } _ => "Zlib error", }; let msg = self.strm.msg; Some(( self.err, if !msg.is_null() { // SAFETY: `msg` is a valid pointer to a null-terminated string. unsafe { std::ffi::CStr::from_ptr(msg).to_str().unwrap().to_string() } } else { err_str.to_string() }, )) } fn check_error( error_info: Option<(i32, String)>, scope: &mut v8::PinScope<'_, '_>, this: &v8::Global<v8::Object>, ) -> bool { let Some((err, msg)) = error_info else { return true; // No error, nothing to report. }; let this = v8::Local::new(scope, this); v8_static_strings! { ONERROR_STR = "onerror", } let onerror_str = ONERROR_STR.v8_string(scope).unwrap(); let onerror = this.get(scope, onerror_str.into()).unwrap(); let cb = v8::Local::<v8::Function>::try_from(onerror).unwrap(); let msg = v8::String::new(scope, &msg).unwrap(); let err = v8::Integer::new(scope, err); cb.call(scope, this.into(), &[msg.into(), err.into()]); false } } pub struct Zlib { inner: RefCell<Option<ZlibInner>>, } // SAFETY: we're sure this can be GCed unsafe impl deno_core::GarbageCollected for Zlib { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"Zlib" } } impl deno_core::Resource for Zlib { fn name(&self) -> Cow<'_, str> { "zlib".into() } } #[op2] impl Zlib { #[constructor] #[cppgc] fn new(#[smi] mode: Option<i32>) -> Result<Zlib, mode::ModeError> { let mode = mode.unwrap_or(Mode::Deflate as i32); let mode = Mode::try_from(mode)?; let inner = ZlibInner { mode, ..Default::default() }; Ok(Zlib { inner: RefCell::new(Some(inner)), }) } #[fast] pub fn close(&self) -> Result<(), ZlibError> { let mut resource = self.inner.borrow_mut(); let zlib = resource.as_mut().ok_or(ZlibError::NotInitialized)?; // If there is a pending write, defer the close until the write is done. zlib.close()?; Ok(()) } #[fast] #[smi] pub fn reset(&self) -> Result<i32, ZlibError> { let mut zlib = self.inner.borrow_mut(); let zlib = zlib.as_mut().ok_or(ZlibError::NotInitialized)?; zlib.reset_stream(); Ok(zlib.err) } #[smi] pub fn init( &self, #[smi] window_bits: i32, #[smi] level: i32, #[smi] mem_level: i32, #[smi] strategy: i32, #[buffer] write_result: &mut [u32], #[global] callback: v8::Global<v8::Function>, #[buffer] dictionary: Option<&[u8]>, ) -> Result<i32, ZlibError> { let mut zlib = self.inner.borrow_mut(); let zlib = zlib.as_mut().ok_or(ZlibError::NotInitialized)?; if !((window_bits == 0) && matches!(zlib.mode, Mode::Inflate | Mode::Gunzip | Mode::Unzip)) { check((8..=15).contains(&window_bits), "invalid windowBits")?; } check((-1..=9).contains(&level), "invalid level")?; check((1..=9).contains(&mem_level), "invalid memLevel")?; check( strategy == Z_DEFAULT_STRATEGY || strategy == Z_FILTERED || strategy == Z_HUFFMAN_ONLY || strategy == Z_RLE || strategy == Z_FIXED, "invalid strategy", )?; zlib.level = level; zlib.window_bits = window_bits; zlib.mem_level = mem_level; zlib.strategy = strategy; zlib.flush = Flush::None; zlib.err = Z_OK; zlib.init_stream()?; zlib.dictionary = dictionary.map(|buf| buf.to_vec()); zlib.result_buffer = Some(write_result.as_mut_ptr()); zlib.callback = Some(callback); Ok(zlib.err) } #[fast] #[reentrant] pub fn write_sync( &self, #[this] this: v8::Global<v8::Object>, scope: &mut v8::PinScope<'_, '_>, #[smi] flush: i32, #[buffer] input: &[u8], #[smi] in_off: u32, #[smi] in_len: u32, #[buffer] out: &mut [u8], #[smi] out_off: u32, #[smi] out_len: u32, ) -> Result<(), ZlibError> { let err_info = { let mut zlib = self.inner.borrow_mut(); let zlib = zlib.as_mut().ok_or(ZlibError::NotInitialized)?; let flush = Flush::try_from(flush)?; zlib.start_write(input, in_off, in_len, out, out_off, out_len, flush)?; zlib.do_write(flush)?; // SAFETY: `zlib.result_buffer` is a valid pointer to a mutable slice of u32 of length 2. let result = unsafe { std::slice::from_raw_parts_mut(zlib.result_buffer.unwrap(), 2) }; result[0] = zlib.strm.avail_out; result[1] = zlib.strm.avail_in; zlib.get_error_info() }; ZlibInner::check_error(err_info, scope, &this); Ok(()) } #[fast] #[reentrant] fn write( &self, #[this] this: v8::Global<v8::Object>, scope: &mut v8::PinScope<'_, '_>, #[smi] flush: i32, #[buffer] input: &[u8], #[smi] in_off: u32, #[smi] in_len: u32, #[buffer] out: &mut [u8], #[smi] out_off: u32, #[smi] out_len: u32, ) -> Result<(), ZlibError> { let (err_info, callback) = { let mut zlib = self.inner.borrow_mut(); let zlib = zlib.as_mut().ok_or(ZlibError::NotInitialized)?; let flush = Flush::try_from(flush)?; zlib.start_write(input, in_off, in_len, out, out_off, out_len, flush)?; zlib.do_write(flush)?; // SAFETY: `zlib.result_buffer` is a valid pointer to a mutable slice of u32 of length 2. let result = unsafe { std::slice::from_raw_parts_mut(zlib.result_buffer.unwrap(), 2) }; result[0] = zlib.strm.avail_out; result[1] = zlib.strm.avail_in; ( zlib.get_error_info(), v8::Local::new( scope, zlib.callback.as_ref().expect("callback not set"), ), ) }; if !ZlibInner::check_error(err_info, scope, &this) { return Ok(()); } let this = v8::Local::new(scope, &this); let _ = callback.call(scope, this.into(), &[]); Ok(()) } } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum ZlibError { #[class(type)] #[error("zlib not initialized")] NotInitialized, #[class(inherit)] #[error(transparent)] Mode( #[from] #[inherit] mode::ModeError, ), #[class(inherit)] #[error(transparent)] Other( #[from] #[inherit] JsErrorBox, ), } #[op2] #[string] pub fn op_zlib_err_msg( #[cppgc] resource: &Zlib, ) -> Result<Option<String>, ZlibError> { let mut zlib = resource.inner.borrow_mut(); let zlib = zlib.as_mut().ok_or(ZlibError::NotInitialized)?; let msg = zlib.strm.msg; if msg.is_null() { return Ok(None); } // SAFETY: `msg` is a valid pointer to a null-terminated string. let msg = unsafe { std::ffi::CStr::from_ptr(msg) .to_str() .map_err(|_| JsErrorBox::type_error("invalid error message"))? .to_string() }; Ok(Some(msg)) } #[op2(fast)] pub fn op_zlib_close_if_pending( #[cppgc] resource: &Zlib, ) -> Result<(), ZlibError> { let pending_close = { let mut zlib = resource.inner.borrow_mut(); let zlib = zlib.as_mut().ok_or(ZlibError::NotInitialized)?; zlib.write_in_progress = false; zlib.pending_close }; if pending_close && let Some(mut res) = resource.inner.borrow_mut().take() { let _ = res.close(); } Ok(()) } struct BrotliEncoderCtx { inst: BrotliEncoderStateStruct<StandardAlloc>, write_result: *mut u32, callback: v8::Global<v8::Function>, } pub struct BrotliEncoder { ctx: Rc<RefCell<Option<BrotliEncoderCtx>>>, } // SAFETY: we're sure this can be GCed unsafe impl deno_core::GarbageCollected for BrotliEncoder { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"BrotliEncoder" } } fn encoder_param(i: u32) -> brotli::enc::encode::BrotliEncoderParameter { const _: () = { assert!( std::mem::size_of::<brotli::enc::encode::BrotliEncoderParameter>() == std::mem::size_of::<u32>(), ); }; // SAFETY: `i` is a valid u32 value that corresponds to a BrotliEncoderParameter. unsafe { std::mem::transmute(i) } } #[op2] impl BrotliEncoder { #[constructor] #[cppgc] fn new(#[smi] _mode: i32) -> BrotliEncoder { BrotliEncoder { ctx: Rc::new(RefCell::new(None)), } } fn init( &self, #[buffer] params: &[u32], #[buffer] write_result: &mut [u32], #[global] callback: v8::Global<v8::Function>, ) { let inst = { let mut state = BrotliEncoderStateStruct::new(StandardAlloc::default()); for (i, &value) in params.iter().enumerate() { if value == 0xFFFFFFFF { continue; // Skip setting the parameter, same as C API. } state.set_parameter(encoder_param(i as u32), value); } state }; self.ctx.borrow_mut().replace(BrotliEncoderCtx { inst, write_result: write_result.as_mut_ptr(), callback, }); } #[fast] fn params(&self) { // no-op } #[fast] fn reset(&self) {} #[fast] #[reentrant] pub fn write( &self, #[this] this: v8::Global<v8::Object>, scope: &mut v8::PinScope<'_, '_>, #[smi] flush: u8, #[buffer] input: &[u8], #[smi] in_off: u32, #[smi] in_len: u32, #[buffer] out: &mut [u8], #[smi] out_off: u32, #[smi] out_len: u32, ) -> Result<(), JsErrorBox> { let mut avail_in = in_len as usize; let mut avail_out = out_len as usize; // SAFETY: `inst`, `next_in`, `next_out`, `avail_in`, and `avail_out` are valid pointers. let callback = unsafe { let mut ctx = self.ctx.borrow_mut(); let ctx = ctx.as_mut().expect("BrotliDecoder not initialized"); ctx.inst.compress_stream( std::mem::transmute::<u8, BrotliEncoderOperation>(flush), &mut avail_in, input, &mut (in_off as usize), &mut avail_out, out, &mut (out_off as usize), &mut None, &mut |_, _, _, _| (), ); // SAFETY: `write_result` is a valid pointer to a mutable slice of u32 of length 2. let result = std::slice::from_raw_parts_mut(ctx.write_result, 2); result[0] = avail_out as u32; result[1] = avail_in as u32; v8::Local::new(scope, &ctx.callback) }; let this = v8::Local::new(scope, &this); let _ = callback.call(scope, this.into(), &[]); Ok(()) } #[fast] pub fn write_sync( &self, #[smi] flush: u8, #[buffer] input: &[u8], #[smi] in_off: u32, #[smi] in_len: u32, #[buffer] out: &mut [u8], #[smi] out_off: u32, #[smi] out_len: u32, ) -> Result<(), JsErrorBox> { let mut ctx = self.ctx.borrow_mut(); let ctx = ctx.as_mut().expect("BrotliEncoder not initialized"); let mut avail_in = in_len as usize; let mut avail_out = out_len as usize; // SAFETY: `inst`, `next_in`, `next_out`, `avail_in`, and `avail_out` are valid pointers. unsafe { ctx.inst.compress_stream( std::mem::transmute::<u8, BrotliEncoderOperation>(flush), &mut avail_in, input, &mut (in_off as usize), &mut avail_out, out, &mut (out_off as usize), &mut None, &mut |_, _, _, _| (), ); // SAFETY: `ctx.write_result` is a valid pointer to a mutable slice of u32 of length 2. let result = std::slice::from_raw_parts_mut(ctx.write_result, 2); result[0] = avail_out as u32; result[1] = avail_in as u32; }; Ok(()) } #[fast] fn close(&self) { let mut ctx = self.ctx.borrow_mut(); if let Some(mut ctx) = ctx.take() { BrotliEncoderDestroyInstance(&mut ctx.inst); } } } struct BrotliDecoderCtx { inst: *mut ffi::decompressor::ffi::BrotliDecoderState, write_result: *mut u32, callback: v8::Global<v8::Function>, } pub struct BrotliDecoder { ctx: Rc<RefCell<Option<BrotliDecoderCtx>>>, } // SAFETY: we're sure this can be GCed unsafe impl deno_core::GarbageCollected for BrotliDecoder { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"BrotliDecoder" } } fn decoder_param( i: u32, ) -> Option<ffi::decompressor::ffi::interface::BrotliDecoderParameter> { const _: () = { assert!( std::mem::size_of::< ffi::decompressor::ffi::interface::BrotliDecoderParameter, >() == std::mem::size_of::<u32>(), ); }; match i { 0 => Some(ffi::decompressor::ffi::interface::BrotliDecoderParameter::BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION), 1 => Some(ffi::decompressor::ffi::interface::BrotliDecoderParameter::BROTLI_DECODER_PARAM_LARGE_WINDOW), _ => None } } #[op2] impl BrotliDecoder { #[constructor] #[cppgc] fn new(#[smi] _mode: i32) -> BrotliDecoder { BrotliDecoder { ctx: Rc::new(RefCell::new(None)), } } fn init( &self, #[buffer] params: &[u32], #[buffer] write_result: &mut [u32], #[global] callback: v8::Global<v8::Function>, ) { // SAFETY: creates new brotli decoder instance. `params` is a valid slice of u32 values. let inst = unsafe { let state = ffi::decompressor::ffi::BrotliDecoderCreateInstance( Some(brotli_alloc), Some(brotli_free), std::ptr::null_mut(), ); for (i, &value) in params.iter().enumerate() { if let Some(param) = decoder_param(i as u32) { ffi::decompressor::ffi::BrotliDecoderSetParameter( state, param, value, ); } } state }; self.ctx.borrow_mut().replace(BrotliDecoderCtx { inst, write_result: write_result.as_mut_ptr(), callback, }); } #[fast] fn params(&self) { // no-op } #[fast] fn reset(&self) {} #[fast] #[reentrant] pub fn write( &self, #[this] this: v8::Global<v8::Object>, scope: &mut v8::PinScope<'_, '_>, #[smi] _flush: i32, #[buffer] input: &[u8], #[smi] in_off: u32, #[smi] in_len: u32, #[buffer] out: &mut [u8], #[smi] out_off: u32, #[smi] out_len: u32, ) -> Result<(), JsErrorBox> { let callback = { let ctx = self.ctx.borrow(); let ctx = ctx.as_ref().expect("BrotliDecoder not initialized"); let mut next_in = input .get(in_off as usize..in_off as usize + in_len as usize) .ok_or_else(|| JsErrorBox::type_error("invalid input range"))? .as_ptr(); let mut next_out = out .get_mut(out_off as usize..out_off as usize + out_len as usize) .ok_or_else(|| JsErrorBox::type_error("invalid output range"))? .as_mut_ptr(); let mut avail_in = in_len as usize; let mut avail_out = out_len as usize; // SAFETY: `inst`, `next_in`, `next_out`, `avail_in`, and `avail_out` are valid pointers. unsafe { ffi::decompressor::ffi::BrotliDecoderDecompressStream( ctx.inst, &mut avail_in, &mut next_in, &mut avail_out, &mut next_out, std::ptr::null_mut(), ); // SAFETY: `write_result` is a valid pointer to a mutable slice of u32 of length 2. let result = std::slice::from_raw_parts_mut(ctx.write_result, 2); result[0] = avail_out as u32; result[1] = avail_in as u32; } v8::Local::new(scope, &ctx.callback) }; let this = v8::Local::new(scope, &this); let _ = callback.call(scope, this.into(), &[]); Ok(()) } #[fast] pub fn write_sync( &self, #[smi] _flush: i32, #[buffer] input: &[u8], #[smi] in_off: u32, #[smi] in_len: u32, #[buffer] out: &mut [u8], #[smi] out_off: u32, #[smi] out_len: u32, ) -> Result<(), JsErrorBox> { let mut ctx = self.ctx.borrow_mut(); let ctx = ctx.as_mut().expect("BrotliDecoder not initialized"); let mut next_in = input .get(in_off as usize..in_off as usize + in_len as usize) .ok_or_else(|| JsErrorBox::type_error("invalid input range"))? .as_ptr(); let mut next_out = out .get_mut(out_off as usize..out_off as usize + out_len as usize) .ok_or_else(|| JsErrorBox::type_error("invalid output range"))? .as_mut_ptr(); let mut avail_in = in_len as usize; let mut avail_out = out_len as usize; // SAFETY: `ctx.inst` is a valid pointer to a BrotliDecoderState. unsafe { ffi::decompressor::ffi::BrotliDecoderDecompressStream( ctx.inst, &mut avail_in, &mut next_in, &mut avail_out, &mut next_out, std::ptr::null_mut(), ); // SAFETY: `ctx.write_result` is a valid pointer to a mutable slice of u32 of length 2. let result = std::slice::from_raw_parts_mut(ctx.write_result, 2); result[0] = avail_out as u32; result[1] = avail_in as u32; } Ok(()) } #[fast] fn close(&self) { let mut ctx = self.ctx.borrow_mut(); if let Some(ctx) = ctx.take() { // SAFETY: `ctx.inst` is a valid pointer to a BrotliDecoderState. unsafe { ffi::decompressor::ffi::BrotliDecoderDestroyInstance(ctx.inst); } } } } #[op2(fast)] pub fn op_zlib_crc32_string(#[string] data: &str, value: u32) -> u32 { // SAFETY: `data` is a valid buffer. unsafe { zlib::crc32(value as c_ulong, data.as_ptr(), data.len() as u32) as u32 } } #[op2(fast)] pub fn op_zlib_crc32(#[buffer] data: &[u8], value: u32) -> u32 { // SAFETY: `data` is a valid buffer. unsafe { zlib::crc32(value as c_ulong, data.as_ptr(), data.len() as u32) as u32 } } #[cfg(test)] mod tests { use super::*; #[test] fn zlib_start_write() { // buffer, length, should pass type WriteVector = (&'static [u8], u32, u32, bool); const WRITE_VECTORS: [WriteVector; 8] = [ (b"Hello", 5, 0, true), (b"H", 1, 0, true), (b"", 0, 0, true), // Overrun the buffer (b"H", 5, 0, false), (b"ello", 5, 0, false), (b"Hello", 5, 1, false), (b"H", 1, 1, false), (b"", 0, 1, false), ]; for (input, len, offset, expected) in WRITE_VECTORS.iter() { let mut stream = ZlibInner { mode: Mode::Inflate, ..Default::default() }; stream.init_stream().unwrap(); assert_eq!(stream.err, Z_OK); assert_eq!( stream .start_write(input, *offset, *len, &mut [], 0, 0, Flush::None) .is_ok(), *expected ); assert_eq!(stream.err, Z_OK); stream.close().unwrap(); } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/zlib/mode.rs
ext/node/ops/zlib/mode.rs
// Copyright 2018-2025 the Deno authors. MIT license. #[derive(Debug, thiserror::Error, deno_error::JsError)] #[class(generic)] #[error("bad argument")] pub struct ModeError; macro_rules! repr_i32 { ($(#[$meta:meta])* $vis:vis enum $name:ident { $($(#[$vmeta:meta])* $vname:ident $(= $val:expr)?,)* }) => { $(#[$meta])* $vis enum $name { $($(#[$vmeta])* $vname $(= $val)?,)* } impl core::convert::TryFrom<i32> for $name { type Error = ModeError; fn try_from(v: i32) -> Result<Self, Self::Error> { match v { $(x if x == $name::$vname as i32 => Ok($name::$vname),)* _ => Err(ModeError), } } } } } repr_i32! { #[repr(i32)] #[derive(Clone, Copy, Debug, PartialEq, Default)] pub enum Mode { #[default] None, Deflate, Inflate, Gzip, Gunzip, DeflateRaw, InflateRaw, Unzip, } } repr_i32! { #[repr(i32)] #[derive(Clone, Copy, Debug, PartialEq, Default)] pub enum Flush { #[default] None = zlib::Z_NO_FLUSH, Partial = zlib::Z_PARTIAL_FLUSH, Sync = zlib::Z_SYNC_FLUSH, Full = zlib::Z_FULL_FLUSH, Finish = zlib::Z_FINISH, Block = zlib::Z_BLOCK, Trees = zlib::Z_TREES, } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/sqlite/session.rs
ext/node/ops/sqlite/session.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::Cell; use std::cell::RefCell; use std::ffi::c_void; use std::rc::Weak; use deno_core::FromV8; use deno_core::GarbageCollected; use deno_core::op2; use deno_core::v8; use deno_core::v8_static_strings; use rusqlite::ffi; use super::SqliteError; use super::validators; #[derive(Default)] pub struct SessionOptions { pub table: Option<String>, pub db: Option<String>, } impl FromV8<'_> for SessionOptions { type Error = validators::Error; fn from_v8( scope: &mut v8::PinScope<'_, '_>, value: v8::Local<v8::Value>, ) -> Result<Self, validators::Error> { use validators::Error; if value.is_undefined() { return Ok(SessionOptions::default()); } let obj = v8::Local::<v8::Object>::try_from(value).map_err(|_| { Error::InvalidArgType("The \"options\" argument must be an object.") })?; let mut options = SessionOptions::default(); v8_static_strings! { TABLE_STRING = "table", DB_STRING = "db", } let table_string = TABLE_STRING.v8_string(scope).unwrap(); if let Some(table_value) = obj.get(scope, table_string.into()) && !table_value.is_undefined() { if !table_value.is_string() { return Err(Error::InvalidArgType( "The \"options.table\" argument must be a string.", )); } let table = v8::Local::<v8::String>::try_from(table_value).map_err(|_| { Error::InvalidArgType( "The \"options.table\" argument must be a string.", ) })?; options.table = Some(table.to_rust_string_lossy(scope).to_string()); } let db_string = DB_STRING.v8_string(scope).unwrap(); if let Some(db_value) = obj.get(scope, db_string.into()) && !db_value.is_undefined() { if !db_value.is_string() { return Err(Error::InvalidArgType( "The \"options.db\" argument must be a string.", )); } let db = v8::Local::<v8::String>::try_from(db_value).map_err(|_| { Error::InvalidArgType("The \"options.db\" argument must be a string.") })?; options.db = Some(db.to_rust_string_lossy(scope).to_string()); } Ok(options) } } pub struct Session { pub(crate) inner: *mut ffi::sqlite3_session, pub(crate) freed: Cell<bool>, // Hold a weak reference to the database. pub(crate) db: Weak<RefCell<Option<rusqlite::Connection>>>, } // SAFETY: we're sure this can be GCed unsafe impl GarbageCollected for Session { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"Session" } } impl Drop for Session { fn drop(&mut self) { let _ = self.delete(); } } impl Session { fn delete(&self) -> Result<(), SqliteError> { if self.freed.get() { return Err(SqliteError::SessionClosed); } self.freed.set(true); // Safety: `self.inner` is a valid session. double free is // prevented by `freed` flag. unsafe { ffi::sqlite3session_delete(self.inner); } Ok(()) } } #[op2] impl Session { #[constructor] #[cppgc] fn create(_: bool) -> Session { unreachable!() } // Closes the session. #[fast] #[undefined] fn close(&self) -> Result<(), SqliteError> { let db_rc = self .db .upgrade() .ok_or_else(|| SqliteError::AlreadyClosed)?; if db_rc.borrow().is_none() { return Err(SqliteError::AlreadyClosed); } self.delete() } // Retrieves a changeset containing all changes since the changeset // was created. Can be called multiple times. // // This method is a wrapper around `sqlite3session_changeset()`. #[buffer] fn changeset(&self) -> Result<Box<[u8]>, SqliteError> { let db_rc = self .db .upgrade() .ok_or_else(|| SqliteError::AlreadyClosed)?; if db_rc.borrow().is_none() { return Err(SqliteError::AlreadyClosed); } if self.freed.get() { return Err(SqliteError::SessionClosed); } session_buffer_op(self.inner, ffi::sqlite3session_changeset) } // Similar to the method above, but generates a more compact patchset. // // This method is a wrapper around `sqlite3session_patchset()`. #[buffer] fn patchset(&self) -> Result<Box<[u8]>, SqliteError> { let db_rc = self .db .upgrade() .ok_or_else(|| SqliteError::AlreadyClosed)?; if db_rc.borrow().is_none() { return Err(SqliteError::AlreadyClosed); } if self.freed.get() { return Err(SqliteError::SessionClosed); } session_buffer_op(self.inner, ffi::sqlite3session_patchset) } } fn session_buffer_op( s: *mut ffi::sqlite3_session, f: unsafe extern "C" fn( *mut ffi::sqlite3_session, *mut i32, *mut *mut c_void, ) -> i32, ) -> Result<Box<[u8]>, SqliteError> { let mut n_buffer = 0; let mut p_buffer = std::ptr::null_mut(); // Safety: `s` is a valid session and the buffer is allocated // by sqlite3 and will be freed later. let r = unsafe { f(s, &mut n_buffer, &mut p_buffer) }; if r != ffi::SQLITE_OK { return Err(SqliteError::SessionChangesetFailed); } if n_buffer == 0 { return Ok(Default::default()); } // Safety: n_buffer is the size of the buffer. let buffer = unsafe { std::slice::from_raw_parts(p_buffer as *const u8, n_buffer as usize) } .to_vec() .into_boxed_slice(); // Safety: free sqlite allocated buffer, we copied it into the JS buffer. unsafe { ffi::sqlite3_free(p_buffer); } Ok(buffer) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/sqlite/database.rs
ext/node/ops/sqlite/database.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::Cell; use std::cell::RefCell; use std::ffi::CStr; use std::ffi::CString; use std::ffi::c_char; use std::ffi::c_void; use std::path::Path; use std::ptr::NonNull; use std::ptr::null; use std::rc::Rc; use deno_core::FromV8; use deno_core::GarbageCollected; use deno_core::OpState; use deno_core::convert::OptionUndefined; use deno_core::cppgc; use deno_core::op2; use deno_core::v8; use deno_core::v8_static_strings; use deno_permissions::OpenAccessKind; use deno_permissions::PermissionsContainer; use rusqlite::ffi as libsqlite3_sys; use rusqlite::ffi::SQLITE_DBCONFIG_DQS_DDL; use rusqlite::ffi::SQLITE_DBCONFIG_DQS_DML; use rusqlite::ffi::sqlite3_create_window_function; use rusqlite::ffi::sqlite3_db_filename; use rusqlite::limits::Limit; use super::Session; use super::SqliteError; use super::StatementSync; use super::session::SessionOptions; use super::statement::InnerStatementPtr; use super::statement::check_error_code; use super::statement::check_error_code2; use super::validators; const SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION: i32 = 1005; const SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE: i32 = 1021; const MAX_SAFE_JS_INTEGER: i64 = 9_007_199_254_740_991; struct DatabaseSyncOptions { open: bool, enable_foreign_key_constraints: bool, read_only: bool, allow_extension: bool, enable_double_quoted_string_literals: bool, timeout: u64, } impl<'a> FromV8<'a> for DatabaseSyncOptions { type Error = validators::Error; fn from_v8( scope: &mut v8::PinScope<'a, '_>, value: v8::Local<'a, v8::Value>, ) -> Result<Self, Self::Error> { use validators::Error; if value.is_undefined() { return Ok(Self::default()); } let Ok(obj) = v8::Local::<v8::Object>::try_from(value) else { return Err(Error::InvalidArgType( "The \"options\" argument must be an object.", )); }; let mut options = Self::default(); v8_static_strings! { OPEN_STRING = "open", ENABLE_FOREIGN_KEY_CONSTRAINTS_STRING = "enableForeignKeyConstraints", READ_ONLY_STRING = "readOnly", ALLOW_EXTENSION_STRING = "allowExtension", ENABLE_DOUBLE_QUOTED_STRING_LITERALS_STRING = "enableDoubleQuotedStringLiterals", TIMEOUT_STRING = "timeout", } let open_string = OPEN_STRING.v8_string(scope).unwrap(); if let Some(open) = obj.get(scope, open_string.into()) && !open.is_undefined() { options.open = v8::Local::<v8::Boolean>::try_from(open) .map_err(|_| { Error::InvalidArgType( "The \"options.open\" argument must be a boolean.", ) })? .is_true(); } let read_only_string = READ_ONLY_STRING.v8_string(scope).unwrap(); if let Some(read_only) = obj.get(scope, read_only_string.into()) && !read_only.is_undefined() { options.read_only = v8::Local::<v8::Boolean>::try_from(read_only) .map_err(|_| { Error::InvalidArgType( "The \"options.readOnly\" argument must be a boolean.", ) })? .is_true(); } let enable_foreign_key_constraints_string = ENABLE_FOREIGN_KEY_CONSTRAINTS_STRING .v8_string(scope) .unwrap(); if let Some(enable_foreign_key_constraints) = obj.get(scope, enable_foreign_key_constraints_string.into()) && !enable_foreign_key_constraints.is_undefined() { options.enable_foreign_key_constraints = v8::Local::<v8::Boolean>::try_from(enable_foreign_key_constraints) .map_err(|_| { Error::InvalidArgType( "The \"options.enableForeignKeyConstraints\" argument must be a boolean.", ) })? .is_true(); } let allow_extension_string = ALLOW_EXTENSION_STRING.v8_string(scope).unwrap(); if let Some(allow_extension) = obj.get(scope, allow_extension_string.into()) && !allow_extension.is_undefined() { options.allow_extension = v8::Local::<v8::Boolean>::try_from(allow_extension) .map_err(|_| { Error::InvalidArgType( "The \"options.allowExtension\" argument must be a boolean.", ) })? .is_true(); } let enable_double_quoted_string_literals_string = ENABLE_DOUBLE_QUOTED_STRING_LITERALS_STRING .v8_string(scope) .unwrap(); if let Some(enable_double_quoted_string_literals) = obj.get(scope, enable_double_quoted_string_literals_string.into()) && !enable_double_quoted_string_literals.is_undefined() { options.enable_double_quoted_string_literals = v8::Local::<v8::Boolean>::try_from(enable_double_quoted_string_literals) .map_err(|_| { Error::InvalidArgType( "The \"options.enableDoubleQuotedStringLiterals\" argument must be a boolean.", ) })? .is_true(); } let timeout_string = TIMEOUT_STRING.v8_string(scope).unwrap(); if let Some(timeout) = obj.get(scope, timeout_string.into()) && !timeout.is_undefined() { let timeout = v8::Local::<v8::Integer>::try_from(timeout) .map_err(|_| { Error::InvalidArgType( "The \"options.timeout\" argument must be an integer.", ) })? .value(); if timeout > 0 { options.timeout = timeout as u64; } } Ok(options) } } impl Default for DatabaseSyncOptions { fn default() -> Self { DatabaseSyncOptions { open: true, enable_foreign_key_constraints: true, read_only: false, allow_extension: false, enable_double_quoted_string_literals: false, timeout: 0, } } } struct AggregateFunctionOption<'a> { deterministic: bool, direct_only: bool, use_big_int_arguments: bool, varargs: bool, start: v8::Local<'a, v8::Value>, step: v8::Local<'a, v8::Function>, result: Option<v8::Local<'a, v8::Function>>, inverse: Option<v8::Local<'a, v8::Function>>, } impl<'a> AggregateFunctionOption<'a> { fn from_value( scope: &mut v8::PinScope<'a, '_>, value: v8::Local<'a, v8::Value>, ) -> Result<Self, validators::Error> { use validators::Error; if !value.is_object() { return Err(Error::InvalidArgType( "The \"options\" argument must be an object.", )); } v8_static_strings! { DETERMINISTIC_STRING = "deterministic", DIRECT_ONLY_STRING = "directOnly", USE_BIG_INT_ARGUMENTS_STRING = "useBigIntArguments", VARARGS_STRING = "varargs", START_STRING = "start", STEP_STRING = "step", RESULT_STRING = "result", INVERSE_STRING = "inverse", } let start_key = START_STRING.v8_string(scope).unwrap(); let start_value = v8::Local::<v8::Object>::try_from(value) .unwrap() .get(scope, start_key.into()) .unwrap(); if start_value.is_undefined() { return Err(Error::InvalidArgType( "The \"options.start\" argument must be a function or a primitive value.", )); } let step_key = STEP_STRING.v8_string(scope).unwrap(); let step_value = v8::Local::<v8::Object>::try_from(value) .unwrap() .get(scope, step_key.into()) .unwrap(); let step_function = v8::Local::<v8::Function>::try_from(step_value) .map_err(|_| { Error::InvalidArgType( "The \"options.step\" argument must be a function.", ) })?; let result_key = RESULT_STRING.v8_string(scope).unwrap(); let result_value = v8::Local::<v8::Object>::try_from(value) .unwrap() .get(scope, result_key.into()) .unwrap(); let result_function = if result_value.is_undefined() { None } else { let func = v8::Local::<v8::Function>::try_from(result_value).map_err(|_| { Error::InvalidArgType( "The \"options.result\" argument must be a function.", ) })?; Some(func) }; let mut deterministic = false; let mut use_big_int_arguments = false; let mut varargs = false; let mut direct_only = false; let deterministic_key = DETERMINISTIC_STRING.v8_string(scope).unwrap(); let deterministic_value = v8::Local::<v8::Object>::try_from(value) .unwrap() .get(scope, deterministic_key.into()) .unwrap(); if !deterministic_value.is_undefined() { if !deterministic_value.is_boolean() { return Err(Error::InvalidArgType( "The \"options.deterministic\" argument must be a boolean.", )); } deterministic = deterministic_value.boolean_value(scope); } let use_bigint_key = USE_BIG_INT_ARGUMENTS_STRING.v8_string(scope).unwrap(); let bigint_value = v8::Local::<v8::Object>::try_from(value) .unwrap() .get(scope, use_bigint_key.into()) .unwrap(); if !bigint_value.is_undefined() { if !bigint_value.is_boolean() { return Err(Error::InvalidArgType( "The \"options.useBigIntArguments\" argument must be a boolean.", )); } use_big_int_arguments = bigint_value.boolean_value(scope); } let varargs_key = VARARGS_STRING.v8_string(scope).unwrap(); let varargs_value = v8::Local::<v8::Object>::try_from(value) .unwrap() .get(scope, varargs_key.into()) .unwrap(); if !varargs_value.is_undefined() { if !varargs_value.is_boolean() { return Err(Error::InvalidArgType( "The \"options.varargs\" argument must be a boolean.", )); } varargs = varargs_value.boolean_value(scope); } let direct_only_key = DIRECT_ONLY_STRING.v8_string(scope).unwrap(); let direct_only_value = v8::Local::<v8::Object>::try_from(value) .unwrap() .get(scope, direct_only_key.into()) .unwrap(); if !direct_only_value.is_undefined() { if !direct_only_value.is_boolean() { return Err(Error::InvalidArgType( "The \"options.directOnly\" argument must be a boolean.", )); } direct_only = direct_only_value.boolean_value(scope); } let inverse_key = INVERSE_STRING.v8_string(scope).unwrap(); let inverse_value = v8::Local::<v8::Object>::try_from(value) .unwrap() .get(scope, inverse_key.into()) .unwrap(); let inverse_function = if inverse_value.is_undefined() { None } else { let func = v8::Local::<v8::Function>::try_from(inverse_value).map_err(|_| { Error::InvalidArgType( "The \"options.inverse\" argument must be a function.", ) })?; Some(func) }; Ok(AggregateFunctionOption { deterministic, direct_only, use_big_int_arguments, varargs, start: start_value, step: step_function, result: result_function, inverse: inverse_function, }) } } struct ApplyChangesetOptions<'a> { filter: Option<v8::Local<'a, v8::Value>>, on_conflict: Option<v8::Local<'a, v8::Value>>, } // Note: Can't use `FromV8` here because of lifetime issues with holding // Local references. impl<'a> ApplyChangesetOptions<'a> { fn from_value( scope: &mut v8::PinScope<'a, '_>, value: v8::Local<'a, v8::Value>, ) -> Result<Option<Self>, validators::Error> { use validators::Error; if value.is_undefined() { return Ok(None); } let obj = v8::Local::<v8::Object>::try_from(value).map_err(|_| { Error::InvalidArgType("The \"options\" argument must be an object.") })?; let mut options = Self { filter: None, on_conflict: None, }; v8_static_strings! { FILTER_STRING = "filter", ON_CONFLICT_STRING = "onConflict", } let filter_string = FILTER_STRING.v8_string(scope).unwrap(); if let Some(filter) = obj.get(scope, filter_string.into()) && !filter.is_undefined() { if !filter.is_function() { return Err(Error::InvalidArgType( "The \"options.filter\" argument must be a function.", )); } options.filter = Some(filter); } let on_conflict_string = ON_CONFLICT_STRING.v8_string(scope).unwrap(); if let Some(on_conflict) = obj.get(scope, on_conflict_string.into()) && !on_conflict.is_undefined() { if !on_conflict.is_function() { return Err(Error::InvalidArgType( "The \"options.onConflict\" argument must be a function.", )); } options.on_conflict = Some(on_conflict); } Ok(Some(options)) } } pub struct DatabaseSync { pub conn: Rc<RefCell<Option<rusqlite::Connection>>>, statements: Rc<RefCell<Vec<InnerStatementPtr>>>, options: DatabaseSyncOptions, location: String, ignore_next_sqlite_error: Rc<Cell<bool>>, } // SAFETY: we're sure this can be GCed unsafe impl GarbageCollected for DatabaseSync { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"DatabaseSync" } } fn set_db_config( conn: &rusqlite::Connection, config: i32, value: bool, ) -> bool { // SAFETY: call to sqlite3_db_config is safe because the connection // handle is valid and the parameters are correct. unsafe { let mut set = 0; let r = libsqlite3_sys::sqlite3_db_config( conn.handle(), config, value as i32, &mut set, ); if r != libsqlite3_sys::SQLITE_OK { panic!("Failed to set db config"); } set == value as i32 } } fn open_db( state: &mut OpState, location: &str, options: &DatabaseSyncOptions, ) -> Result<rusqlite::Connection, SqliteError> { let perms = state.borrow::<PermissionsContainer>(); let disable_attach = perms .check_has_all_permissions(Path::new(location)) .is_err(); if location == ":memory:" { let conn = rusqlite::Connection::open_in_memory()?; if disable_attach { assert!(set_db_config( &conn, SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE, false )); conn.set_limit(Limit::SQLITE_LIMIT_ATTACHED, 0)?; } if options.allow_extension { perms.check_ffi_all()?; } else { assert!(set_db_config( &conn, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, false )); } return Ok(conn); } let location = perms .check_open( Cow::Borrowed(Path::new(location)), match options.read_only { true => OpenAccessKind::ReadNoFollow, false => OpenAccessKind::ReadWriteNoFollow, }, Some("node:sqlite"), )? .into_path(); if options.read_only { let conn = rusqlite::Connection::open_with_flags( location, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY, )?; if disable_attach { assert!(set_db_config( &conn, SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE, false )); conn.set_limit(Limit::SQLITE_LIMIT_ATTACHED, 0)?; } if options.allow_extension { perms.check_ffi_all()?; } else { assert!(set_db_config( &conn, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, false )); } return Ok(conn); } let conn = rusqlite::Connection::open(location)?; conn.busy_timeout(std::time::Duration::from_millis(options.timeout))?; if options.allow_extension { perms.check_ffi_all()?; } else { assert!(set_db_config( &conn, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, false )); } if disable_attach { conn.set_limit(Limit::SQLITE_LIMIT_ATTACHED, 0)?; } Ok(conn) } fn is_open( scope: &mut v8::PinScope<'_, '_>, args: &v8::FunctionCallbackArguments, ) -> Result<(), SqliteError> { let this_ = args.this(); let db = cppgc::try_unwrap_cppgc_object::<DatabaseSync>(scope, this_.into()) .ok_or(SqliteError::AlreadyClosed)?; db.conn .borrow() .as_ref() .ok_or(SqliteError::AlreadyClosed)?; Ok(()) } // Represents a single connection to a SQLite database. #[op2] impl DatabaseSync { // Constructs a new `DatabaseSync` instance. // // A SQLite database can be stored in a file or in memory. To // use a file-backed database, the `location` should be a path. // To use an in-memory database, the `location` should be special // name ":memory:". #[constructor] #[cppgc] fn new( state: &mut OpState, #[string] location: String, #[from_v8] options: DatabaseSyncOptions, ) -> Result<DatabaseSync, SqliteError> { let db = if options.open { let db = open_db(state, &location, &options)?; if options.enable_foreign_key_constraints { db.execute("PRAGMA foreign_keys = ON", [])?; } else { db.execute("PRAGMA foreign_keys = OFF", [])?; } set_db_config( &db, SQLITE_DBCONFIG_DQS_DDL, options.enable_double_quoted_string_literals, ); set_db_config( &db, SQLITE_DBCONFIG_DQS_DML, options.enable_double_quoted_string_literals, ); Some(db) } else { None }; Ok(DatabaseSync { conn: Rc::new(RefCell::new(db)), statements: Rc::new(RefCell::new(Vec::new())), location, options, ignore_next_sqlite_error: Rc::new(Cell::new(false)), }) } // Opens the database specified by `location` of this instance. // // This method should only be used when the database is not opened // via the constructor. An exception is thrown if the database is // already opened. #[fast] #[undefined] fn open(&self, state: &mut OpState) -> Result<(), SqliteError> { if self.conn.borrow().is_some() { return Err(SqliteError::AlreadyOpen); } let db = open_db(state, &self.location, &self.options)?; if self.options.enable_foreign_key_constraints { db.execute("PRAGMA foreign_keys = ON", [])?; } else { db.execute("PRAGMA foreign_keys = OFF", [])?; } set_db_config( &db, SQLITE_DBCONFIG_DQS_DDL, self.options.enable_double_quoted_string_literals, ); set_db_config( &db, SQLITE_DBCONFIG_DQS_DML, self.options.enable_double_quoted_string_literals, ); *self.conn.borrow_mut() = Some(db); Ok(()) } // Closes the database connection. An exception is thrown if the // database is not open. #[fast] #[undefined] fn close(&self) -> Result<(), SqliteError> { if self.conn.borrow().is_none() { return Err(SqliteError::AlreadyClosed); } // Finalize all prepared statements for stmt in self.statements.borrow_mut().drain(..) { match stmt.get() { None => continue, Some(ptr) => { // SAFETY: `ptr` is a valid statement handle. unsafe { libsqlite3_sys::sqlite3_finalize(ptr); }; stmt.set(None); } }; } let _ = self.conn.borrow_mut().take(); Ok(()) } // This method allows one or more SQL statements to be executed // without returning any results. // // This method is a wrapper around sqlite3_exec(). #[fast] #[validate(is_open)] #[undefined] fn exec( &self, #[validate(validators::sql_str)] #[string] sql: &str, ) -> Result<(), SqliteError> { let db = self.conn.borrow(); let db = db.as_ref().ok_or(SqliteError::InUse)?; if let Err(err) = db.execute_batch(sql) { if self.consume_ignore_next_sqlite_error() { return Ok(()); } return Err(err.into()); } Ok(()) } // Compiles an SQL statement into a prepared statement. // // This method is a wrapper around `sqlite3_prepare_v2()`. #[validate(is_open)] #[cppgc] fn prepare( &self, #[validate(validators::sql_str)] #[string] sql: &str, ) -> Result<StatementSync, SqliteError> { let db = self.conn.borrow(); let db = db.as_ref().ok_or(SqliteError::InUse)?; // SAFETY: lifetime of the connection is guaranteed by reference // counting. let raw_handle = unsafe { db.handle() }; let mut raw_stmt = std::ptr::null_mut(); // SAFETY: `sql` points to a valid memory location and its length // is correct. let r = unsafe { libsqlite3_sys::sqlite3_prepare_v2( raw_handle, sql.as_ptr() as *const _, sql.len() as i32, &mut raw_stmt, std::ptr::null_mut(), ) }; check_error_code(r, raw_handle)?; let stmt_cell = Rc::new(Cell::new(Some(raw_stmt))); self.statements.borrow_mut().push(stmt_cell.clone()); Ok(StatementSync { inner: stmt_cell, db: Rc::downgrade(&self.conn), statements: Rc::clone(&self.statements), ignore_next_sqlite_error: Rc::clone(&self.ignore_next_sqlite_error), use_big_ints: Cell::new(false), allow_bare_named_params: Cell::new(true), allow_unknown_named_params: Cell::new(false), is_iter_finished: Cell::new(false), }) } #[fast] #[validate(is_open)] #[undefined] fn function<'a>( &self, scope: &mut v8::PinScope<'a, '_>, #[varargs] args: Option<&v8::FunctionCallbackArguments>, ) -> Result<(), SqliteError> { let Some(args) = args.filter(|args| args.length() > 0) else { return Err( validators::Error::InvalidArgType( "The \"name\" argument must be a string.", ) .into(), ); }; if !args.get(0).is_string() { return Err( validators::Error::InvalidArgType( "The \"name\" argument must be a string.", ) .into(), ); } let name = args.get(0).to_rust_string_lossy(scope); let (options_value, function_value) = if args.length() < 3 { (None, args.get(1)) } else { (Some(args.get(1)), args.get(2)) }; let Ok(function) = v8::Local::<v8::Function>::try_from(function_value) else { return Err( validators::Error::InvalidArgType( "The \"function\" argument must be a function.", ) .into(), ); }; let mut use_big_int_arguments = false; let mut varargs = false; let mut deterministic = false; let mut direct_only = false; if let Some(value) = options_value && !value.is_undefined() { if value.is_null() || !value.is_object() { return Err( validators::Error::InvalidArgType( "The \"options\" argument must be an object.", ) .into(), ); } let options = v8::Local::<v8::Object>::try_from(value).unwrap(); v8_static_strings! { USE_BIG_INT_ARGUMENTS = "useBigIntArguments", VARARGS = "varargs", DETERMINISTIC = "deterministic", DIRECT_ONLY = "directOnly", } let use_bigint_key = USE_BIG_INT_ARGUMENTS.v8_string(scope).unwrap(); let bigint_value = options.get(scope, use_bigint_key.into()).unwrap(); if !bigint_value.is_undefined() { if !bigint_value.is_boolean() { return Err( validators::Error::InvalidArgType( "The \"options.useBigIntArguments\" argument must be a boolean.", ) .into(), ); } use_big_int_arguments = bigint_value.boolean_value(scope); } let varargs_key = VARARGS.v8_string(scope).unwrap(); let varargs_value = options.get(scope, varargs_key.into()).unwrap(); if !varargs_value.is_undefined() { if !varargs_value.is_boolean() { return Err( validators::Error::InvalidArgType( "The \"options.varargs\" argument must be a boolean.", ) .into(), ); } varargs = varargs_value.boolean_value(scope); } let deterministic_key = DETERMINISTIC.v8_string(scope).unwrap(); let deterministic_value = options.get(scope, deterministic_key.into()).unwrap(); if !deterministic_value.is_undefined() { if !deterministic_value.is_boolean() { return Err( validators::Error::InvalidArgType( "The \"options.deterministic\" argument must be a boolean.", ) .into(), ); } deterministic = deterministic_value.boolean_value(scope); } let direct_only_key = DIRECT_ONLY.v8_string(scope).unwrap(); let direct_only_value = options.get(scope, direct_only_key.into()).unwrap(); if !direct_only_value.is_undefined() { if !direct_only_value.is_boolean() { return Err( validators::Error::InvalidArgType( "The \"options.directOnly\" argument must be a boolean.", ) .into(), ); } direct_only = direct_only_value.boolean_value(scope); } } v8_static_strings! { LENGTH = "length", } let argc = if varargs { -1 } else { let length_key = LENGTH.v8_string(scope).unwrap(); let length = function.get(scope, length_key.into()).unwrap(); length.int32_value(scope).unwrap_or(0) }; let db = self.conn.borrow(); let db = db.as_ref().ok_or(SqliteError::InUse)?; // SAFETY: lifetime of the connection is guaranteed by reference counting. let raw_handle = unsafe { db.handle() }; let name_cstring = CString::new(name)?; let callback = v8::Global::new(scope, function).into_raw(); let context = v8::Global::new(scope, scope.get_current_context()).into_raw(); let data = Box::new(CustomFunctionData { callback, context, use_big_int_arguments, ignore_next_sqlite_error: Rc::clone(&self.ignore_next_sqlite_error), }); let data_ptr = Box::into_raw(data); let mut text_rep = libsqlite3_sys::SQLITE_UTF8; if deterministic { text_rep |= libsqlite3_sys::SQLITE_DETERMINISTIC; } if direct_only { text_rep |= libsqlite3_sys::SQLITE_DIRECTONLY; } // SAFETY: `raw_handle` is a valid database handle. // `data_ptr` points to a valid memory location. // The v8 handles that are held in `CustomFunctionData` will be // dropped when the data is destroyed via `custom_function_destroy`. let result = unsafe { libsqlite3_sys::sqlite3_create_function_v2( raw_handle, name_cstring.as_ptr(), argc, text_rep, data_ptr as *mut c_void, Some(custom_function_handler), None, None, Some(custom_function_destroy), ) }; check_error_code(result, raw_handle)?; Ok(()) } // Applies a changeset to the database. // // This method is a wrapper around `sqlite3changeset_apply()`. #[fast] #[reentrant] fn apply_changeset<'a>( &self, scope: &mut v8::PinScope<'a, '_>, #[validate(validators::changeset_buffer)] #[buffer] changeset: &[u8], options: v8::Local<'a, v8::Value>, ) -> Result<bool, SqliteError> { let options = ApplyChangesetOptions::from_value(scope, options)?; struct HandlerCtx<'a, 'b, 'c> { scope: &'a mut v8::PinScope<'b, 'c>, confict: Option<v8::Local<'b, v8::Function>>, filter: Option<v8::Local<'b, v8::Function>>, } // Conflict handler callback for `sqlite3changeset_apply()`. unsafe extern "C" fn conflict_handler( p_ctx: *mut c_void, e_conflict: i32, _: *mut libsqlite3_sys::sqlite3_changeset_iter, ) -> i32 { #[allow(clippy::undocumented_unsafe_blocks)] unsafe { let ctx = &mut *(p_ctx as *mut HandlerCtx); if let Some(conflict) = &mut ctx.confict { let recv = v8::undefined(ctx.scope).into(); let args = [v8::Integer::new(ctx.scope, e_conflict).into()]; v8::tc_scope!(tc_scope, ctx.scope); let ret = conflict .call(tc_scope, recv, &args) .unwrap_or_else(|| v8::undefined(tc_scope).into()); if tc_scope.has_caught() { tc_scope.rethrow(); return libsqlite3_sys::SQLITE_CHANGESET_ABORT; } const INVALID_VALUE: i32 = -1; if !ret.is_int32() { return INVALID_VALUE; } let value = ret .int32_value(tc_scope) .unwrap_or(libsqlite3_sys::SQLITE_CHANGESET_ABORT); return value; } libsqlite3_sys::SQLITE_CHANGESET_ABORT } } // Filter handler callback for `sqlite3changeset_apply()`. unsafe extern "C" fn filter_handler( p_ctx: *mut c_void, z_tab: *const c_char, ) -> i32 { #[allow(clippy::undocumented_unsafe_blocks)] unsafe { let ctx = &mut *(p_ctx as *mut HandlerCtx); if let Some(filter) = &mut ctx.filter { let tab = CStr::from_ptr(z_tab).to_str().unwrap(); let recv = v8::undefined(ctx.scope).into(); let args = [v8::String::new(ctx.scope, tab).unwrap().into()]; let ret = filter.call(ctx.scope, recv, &args).unwrap(); return ret.boolean_value(ctx.scope) as i32; } 1 } } let db = self.conn.borrow(); let db = db.as_ref().ok_or(SqliteError::AlreadyClosed)?; // It is safe to use scope in the handlers because they are never // called after the call to `sqlite3changeset_apply()`. let mut ctx = HandlerCtx { scope, confict: None, filter: None, }; if let Some(options) = options { if let Some(filter) = options.filter { let filter_cb: v8::Local<v8::Function> = filter .try_into() .map_err(|_| SqliteError::InvalidCallback("filter"))?; ctx.filter = Some(filter_cb); } if let Some(on_conflict) = options.on_conflict { let on_conflict_cb: v8::Local<v8::Function> = on_conflict .try_into() .map_err(|_| SqliteError::InvalidCallback("onConflict"))?; ctx.confict = Some(on_conflict_cb); } } // SAFETY: lifetime of the connection is guaranteed by reference // counting. let raw_handle = unsafe { db.handle() }; // SAFETY: `changeset` points to a valid memory location and its // length is correct. `ctx` is stack allocated and its lifetime is // longer than the call to `sqlite3changeset_apply()`. unsafe { let r = libsqlite3_sys::sqlite3changeset_apply( raw_handle, changeset.len() as i32, changeset.as_ptr() as *mut _, Some(filter_handler), Some(conflict_handler), &mut ctx as *mut _ as *mut c_void, ); if r == libsqlite3_sys::SQLITE_OK { return Ok(true); } else if r == libsqlite3_sys::SQLITE_ABORT { return Ok(false); } check_error_code2(r)?; Ok(false) } } // Loads a SQLite extension. // // This is a wrapper around `sqlite3_load_extension`. It requires FFI permission // to be granted and allowExtension must be set to true when opening the database. fn load_extension( &self, state: &mut OpState, #[validate(validators::path_str)] #[string] path: &str, #[string] entry_point: Option<String>, ) -> Result<(), SqliteError> { let db = self.conn.borrow(); let db = db.as_ref().ok_or(SqliteError::AlreadyClosed)?; if !self.options.allow_extension { return Err(SqliteError::LoadExensionFailed( "Cannot load SQLite extensions when allowExtension is not enabled" .to_string(), )); } state.borrow::<PermissionsContainer>().check_ffi_all()?; // SAFETY: lifetime of the connection is guaranteed by reference counting. let raw_handle = unsafe { db.handle() }; let path_cstring = std::ffi::CString::new(path.as_bytes())?; let entry_point_cstring = entry_point.map(|ep| std::ffi::CString::new(ep).unwrap_or_default()); let entry_point_ptr = match &entry_point_cstring { Some(cstr) => cstr.as_ptr(), None => std::ptr::null(), }; let mut err_msg: *mut c_char = std::ptr::null_mut(); // SAFETY: Using sqlite3_load_extension with proper error handling let result = unsafe { let res = libsqlite3_sys::sqlite3_load_extension( raw_handle, path_cstring.as_ptr(), entry_point_ptr, &mut err_msg, ); if res != libsqlite3_sys::SQLITE_OK { let error_message = if !err_msg.is_null() { let c_str = std::ffi::CStr::from_ptr(err_msg); let message = c_str.to_string_lossy().into_owned(); libsqlite3_sys::sqlite3_free(err_msg as *mut _); message } else { format!("Failed to load extension with error code: {}", res) }; return Err(SqliteError::LoadExensionFailed(error_message)); } res };
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
true
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/sqlite/validators.rs
ext/node/ops/sqlite/validators.rs
// Copyright 2018-2025 the Deno authors. MIT license. use deno_core::v8; #[derive(Debug, thiserror::Error, deno_error::JsError)] #[property("code" = self.code())] pub enum Error { #[class(type)] #[error("{0}")] InvalidArgType(&'static str), } impl Error { pub fn code(&self) -> ErrorCode { match self { Self::InvalidArgType(_) => ErrorCode::ERR_INVALID_ARG_TYPE, } } } #[allow(non_camel_case_types)] pub enum ErrorCode { ERR_INVALID_ARG_TYPE, } impl std::fmt::Display for ErrorCode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.as_str()) } } impl ErrorCode { pub fn as_str(&self) -> &str { match self { Self::ERR_INVALID_ARG_TYPE => "ERR_INVALID_ARG_TYPE", } } } impl From<ErrorCode> for deno_error::PropertyValue { fn from(code: ErrorCode) -> Self { deno_error::PropertyValue::from(code.as_str().to_string()) } } pub(super) fn sql_str( _: &mut v8::PinScope<'_, '_>, value: v8::Local<v8::Value>, ) -> Result<(), Error> { if value.is_string() { return Ok(()); } Err(Error::InvalidArgType( "The \"sql\" argument must be a string.", )) } pub(super) fn changeset_buffer( _: &mut v8::PinScope<'_, '_>, value: v8::Local<v8::Value>, ) -> Result<(), Error> { if value.is_uint8_array() { return Ok(()); } Err(Error::InvalidArgType( "The \"changeset\" argument must be a Uint8Array.", )) } pub(super) fn name_str( _: &mut v8::PinScope<'_, '_>, value: v8::Local<v8::Value>, ) -> Result<(), Error> { if value.is_string() { return Ok(()); } Err(Error::InvalidArgType( "The \"name\" argument must be a string.", )) } pub(super) fn path_str( _: &mut v8::PinScope<'_, '_>, value: v8::Local<v8::Value>, ) -> Result<(), Error> { if value.is_string() { return Ok(()); } Err(Error::InvalidArgType( "The \"path\" argument must be a string.", )) } pub(super) fn allow_bare_named_params_bool( _: &mut v8::PinScope<'_, '_>, value: v8::Local<v8::Value>, ) -> Result<(), Error> { if value.is_boolean() { return Ok(()); } Err(Error::InvalidArgType( "The \"allowBareNamedParameters\" argument must be a boolean.", )) } pub(super) fn allow_unknown_named_params_bool( _: &mut v8::PinScope<'_, '_>, value: v8::Local<v8::Value>, ) -> Result<(), Error> { if value.is_boolean() { return Ok(()); } Err(Error::InvalidArgType( "The \"enabled\" argument must be a boolean.", )) } pub(super) fn read_big_ints_bool( _: &mut v8::PinScope<'_, '_>, value: v8::Local<v8::Value>, ) -> Result<(), Error> { if value.is_boolean() { return Ok(()); } Err(Error::InvalidArgType( "The \"readBigInts\" argument must be a boolean.", )) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/sqlite/mod.rs
ext/node/ops/sqlite/mod.rs
// Copyright 2018-2025 the Deno authors. MIT license. mod backup; mod database; mod session; mod statement; mod validators; pub use backup::op_node_database_backup; pub use database::DatabaseSync; pub use session::Session; pub use statement::StatementSync; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum SqliteError { #[class(inherit)] #[error(transparent)] #[property("code" = self.code())] Permission(#[from] deno_permissions::PermissionCheckError), #[class(generic)] #[error(transparent)] #[property("code" = self.code())] SqliteError(#[from] rusqlite::Error), #[class(generic)] #[error("{message}")] #[property("code" = self.code())] #[property("errstr" = self.errstr())] SqliteSysError { message: String, errstr: String, #[property] errcode: f64, }, #[class(generic)] #[error("Database is already in use")] #[property("code" = self.code())] InUse, #[class(generic)] #[error("Failed to load SQLite extension: {0}")] #[property("code" = self.code())] LoadExensionFailed(String), #[class(generic)] #[error("Failed to bind parameter. {0}")] #[property("code" = self.code())] FailedBind(&'static str), #[class(type)] #[error("Provided value cannot be bound to SQLite parameter {0}.")] #[property("code" = self.code())] InvalidBindType(i32), #[class(type)] #[error("{0}")] #[property("code" = self.code())] InvalidBindValue(&'static str), #[class(generic)] #[error( "Cannot create bare named parameter '{0}' because of conflicting names '{1}' and '{2}'." )] #[property("code" = self.code())] DuplicateNamedParameter(String, String, String), #[class(generic)] #[error("Unknown named parameter '{0}'")] #[property("code" = self.code())] UnknownNamedParameter(String), #[class(generic)] #[error("unknown column type")] #[property("code" = self.code())] UnknownColumnType, #[class(generic)] #[error("failed to get SQL")] #[property("code" = self.code())] GetSqlFailed, #[class(generic)] #[error("database is not open")] #[property("code" = self.code())] AlreadyClosed, #[class(generic)] #[error("database is already open")] #[property("code" = self.code())] AlreadyOpen, #[class(generic)] #[error("failed to create session")] #[property("code" = self.code())] SessionCreateFailed, #[class(generic)] #[error("failed to retrieve changeset")] #[property("code" = self.code())] SessionChangesetFailed, #[class(generic)] #[error("session is not open")] #[property("code" = self.code())] SessionClosed, #[class(type)] #[error("Illegal constructor")] #[property("code" = self.code())] InvalidConstructor, #[class(generic)] #[error("Expanded SQL text would exceed configured limits")] #[property("code" = self.code())] InvalidExpandedSql, #[class(range)] #[error( "The value of column {0} is too large to be represented as a JavaScript number: {1}" )] #[property("code" = self.code())] NumberTooLarge(i32, i64), #[class(type)] #[error("Invalid callback: {0}")] #[property("code" = self.code())] InvalidCallback(&'static str), #[class(type)] #[error("FromUtf8Error: {0}")] #[property("code" = self.code())] FromNullError(#[from] std::ffi::NulError), #[class(type)] #[error("FromUtf8Error: {0}")] #[property("code" = self.code())] FromUtf8Error(#[from] std::str::Utf8Error), #[class(inherit)] #[error(transparent)] #[property("code" = self.code())] Validation(#[from] validators::Error), #[class(generic)] #[error("statement has been finalized")] #[property("code" = self.code())] StatementFinalized, } #[derive(Debug, PartialEq, Eq)] #[allow(non_camel_case_types)] enum ErrorCode { ERR_SQLITE_ERROR, ERR_ILLEGAL_CONSTRUCTOR, ERR_INVALID_STATE, ERR_OUT_OF_RANGE, ERR_LOAD_SQLITE_EXTENSION, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, } impl std::fmt::Display for ErrorCode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.as_str()) } } impl ErrorCode { pub fn as_str(&self) -> &str { match self { Self::ERR_SQLITE_ERROR => "ERR_SQLITE_ERROR", Self::ERR_ILLEGAL_CONSTRUCTOR => "ERR_ILLEGAL_CONSTRUCTOR", Self::ERR_INVALID_ARG_TYPE => "ERR_INVALID_ARG_TYPE", Self::ERR_INVALID_ARG_VALUE => "ERR_INVALID_ARG_VALUE", Self::ERR_INVALID_STATE => "ERR_INVALID_STATE", Self::ERR_OUT_OF_RANGE => "ERR_OUT_OF_RANGE", Self::ERR_LOAD_SQLITE_EXTENSION => "ERR_LOAD_SQLITE_EXTENSION", } } } impl From<ErrorCode> for deno_error::PropertyValue { fn from(code: ErrorCode) -> Self { deno_error::PropertyValue::from(code.as_str().to_string()) } } impl SqliteError { fn errstr(&self) -> String { match self { Self::SqliteSysError { errstr, .. } => errstr.clone(), _ => unreachable!(), } } fn code(&self) -> ErrorCode { match self { Self::InvalidConstructor => ErrorCode::ERR_ILLEGAL_CONSTRUCTOR, Self::InvalidBindType(_) => ErrorCode::ERR_INVALID_ARG_TYPE, Self::InvalidBindValue(_) => ErrorCode::ERR_INVALID_ARG_VALUE, Self::FailedBind(_) | Self::UnknownNamedParameter(_) | Self::DuplicateNamedParameter(..) | Self::AlreadyClosed | Self::InUse | Self::AlreadyOpen | Self::StatementFinalized => ErrorCode::ERR_INVALID_STATE, Self::NumberTooLarge(_, _) => ErrorCode::ERR_OUT_OF_RANGE, Self::LoadExensionFailed(_) => ErrorCode::ERR_LOAD_SQLITE_EXTENSION, _ => ErrorCode::ERR_SQLITE_ERROR, } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/sqlite/backup.rs
ext/node/ops/sqlite/backup.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::ffi::c_int; use std::rc::Rc; use deno_core::OpState; use deno_core::op2; use deno_core::v8; use deno_core::v8_static_strings; use deno_permissions::OpenAccessKind; use deno_permissions::PermissionsContainer; use rusqlite::Connection; use rusqlite::backup; use super::DatabaseSync; use super::SqliteError; use super::validators; const DEFAULT_BACKUP_RATE: c_int = 100; struct BackupOptions<'a> { source: String, target: String, rate: i32, progress: Option<v8::Local<'a, v8::Function>>, } impl<'a> Default for BackupOptions<'a> { fn default() -> Self { BackupOptions { source: "main".to_string(), target: "main".to_string(), rate: DEFAULT_BACKUP_RATE, progress: None, } } } impl<'a> BackupOptions<'a> { fn from_value( scope: &mut v8::PinScope<'a, '_>, value: v8::Local<'a, v8::Value>, ) -> Result<Self, validators::Error> { let mut options = BackupOptions::default(); if value.is_undefined() { return Ok(options); } let Ok(obj) = v8::Local::<v8::Object>::try_from(value) else { return Err(validators::Error::InvalidArgType( "The \"options\" argument must be an object.", )); }; v8_static_strings! { SOURCE_STRING = "source", TARGET_STRING = "target", RATE_STRING = "rate", PROGRESS_STRING = "progress", } let source_string = SOURCE_STRING.v8_string(scope).unwrap(); if let Some(source_val) = obj.get(scope, source_string.into()) && !source_val.is_undefined() { let source_str = v8::Local::<v8::String>::try_from(source_val).map_err(|_| { validators::Error::InvalidArgType( "The \"options.source\" argument must be a string.", ) })?; options.source = source_str.to_rust_string_lossy(scope); } let target_string = TARGET_STRING.v8_string(scope).unwrap(); if let Some(target_val) = obj.get(scope, target_string.into()) && !target_val.is_undefined() { let target_str = v8::Local::<v8::String>::try_from(target_val).map_err(|_| { validators::Error::InvalidArgType( "The \"options.target\" argument must be a string.", ) })?; options.target = target_str.to_rust_string_lossy(scope); } let rate_string = RATE_STRING.v8_string(scope).unwrap(); if let Some(rate_val) = obj.get(scope, rate_string.into()) && !rate_val.is_undefined() { let rate_int = v8::Local::<v8::Integer>::try_from(rate_val) .map_err(|_| { validators::Error::InvalidArgType( "The \"options.rate\" argument must be an integer.", ) })? .value(); options.rate = i32::try_from(rate_int).map_err(|_| { validators::Error::InvalidArgType( "The \"options.rate\" argument must be an integer.", ) })?; } let progress_string = PROGRESS_STRING.v8_string(scope).unwrap(); if let Some(progress_val) = obj.get(scope, progress_string.into()) && !progress_val.is_undefined() { let progress_fn = v8::Local::<v8::Function>::try_from(progress_val) .map_err(|_| { validators::Error::InvalidArgType( "The \"options.progress\" argument must be a function.", ) })?; options.progress = Some(progress_fn); } Ok(options) } } #[op2(reentrant, stack_trace)] #[smi] pub fn op_node_database_backup<'a>( state: Rc<RefCell<OpState>>, scope: &mut v8::PinScope<'a, '_>, #[cppgc] source_db: &DatabaseSync, #[string] path: &str, options: v8::Local<'a, v8::Value>, ) -> Result<Option<i32>, SqliteError> { use rusqlite::backup::StepResult::Busy; use rusqlite::backup::StepResult::Done; use rusqlite::backup::StepResult::Locked; use rusqlite::backup::StepResult::More; let options = BackupOptions::from_value(scope, options)?; let src_conn_ref = source_db.conn.borrow(); let src_conn = src_conn_ref.as_ref().ok_or(SqliteError::AlreadyClosed)?; let checked_path = { let mut state = state.borrow_mut(); let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_open( Cow::Borrowed(std::path::Path::new(path)), OpenAccessKind::Write, Some("node:sqlite.backup"), )? }; let mut dst_conn = Connection::open(checked_path).map_err(|e| match e { rusqlite::Error::SqliteFailure(err, Some(msg)) => { let message = if err.extended_code == rusqlite::ffi::SQLITE_CANTOPEN { "unable to open database file".to_string() } else { msg }; SqliteError::SqliteSysError { message: message.clone(), errstr: message, errcode: err.extended_code as _, } } other_err => SqliteError::from(other_err), })?; let backup = backup::Backup::new_with_names( src_conn, options.source.as_str(), &mut dst_conn, options.target.as_str(), )?; v8_static_strings! { TOTAL_PAGES_STRING = "totalPages", REMAINING_PAGES_STRING = "remainingPages", } loop { let step_result = backup.step(options.rate)?; if let Some(progress_fn) = options.progress { let progress = backup.progress(); if progress.remaining != 0 { let js_progress_obj = v8::Object::new(scope); let total_pages_string = TOTAL_PAGES_STRING.v8_string(scope).unwrap(); let remaining_pages_string = REMAINING_PAGES_STRING.v8_string(scope).unwrap(); let total_pages_js = v8::Integer::new(scope, progress.pagecount); let remaining_pages_js = v8::Integer::new(scope, progress.remaining); js_progress_obj.set( scope, total_pages_string.into(), total_pages_js.into(), ); js_progress_obj.set( scope, remaining_pages_string.into(), remaining_pages_js.into(), ); let recv = v8::null(scope).into(); let res = progress_fn.call(scope, recv, &[js_progress_obj.into()]); if res.is_none() { // JS exception occurred in progress callback return Ok(None); } } } match step_result { Done => return Ok(Some(backup.progress().pagecount)), More | Busy | Locked | _ => continue, } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/sqlite/statement.rs
ext/node/ops/sqlite/statement.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::Cell; use std::cell::RefCell; use std::rc::Rc; use std::rc::Weak; use deno_core::GarbageCollected; use deno_core::ToV8; use deno_core::op2; use deno_core::v8; use deno_core::v8::GetPropertyNamesArgs; use deno_core::v8_static_strings; use rusqlite::ffi; use super::SqliteError; use super::validators; // ECMA-262, 15th edition, 21.1.2.6. Number.MAX_SAFE_INTEGER (2^53-1) const MAX_SAFE_JS_INTEGER: i64 = 9007199254740991; pub struct RunStatementResult { last_insert_rowid: i64, changes: u64, use_big_ints: bool, } impl<'a> ToV8<'a> for RunStatementResult { type Error = SqliteError; fn to_v8( self, scope: &mut v8::PinScope<'a, '_>, ) -> Result<v8::Local<'a, v8::Value>, SqliteError> { v8_static_strings! { LAST_INSERT_ROW_ID = "lastInsertRowid", CHANGES = "changes", } let obj = v8::Object::new(scope); let last_insert_row_id_str = LAST_INSERT_ROW_ID.v8_string(scope).unwrap(); let last_insert_row_id = if self.use_big_ints { v8::BigInt::new_from_i64(scope, self.last_insert_rowid).into() } else { v8::Number::new(scope, self.last_insert_rowid as f64).into() }; obj .set(scope, last_insert_row_id_str.into(), last_insert_row_id) .unwrap(); let changes_str = CHANGES.v8_string(scope).unwrap(); let changes = if self.use_big_ints { v8::BigInt::new_from_u64(scope, self.changes).into() } else { v8::Number::new(scope, self.changes as f64).into() }; obj.set(scope, changes_str.into(), changes).unwrap(); Ok(obj.into()) } } pub type InnerStatementPtr = Rc<Cell<Option<*mut ffi::sqlite3_stmt>>>; #[derive(Debug)] pub struct StatementSync { pub inner: InnerStatementPtr, pub db: Weak<RefCell<Option<rusqlite::Connection>>>, pub statements: Rc<RefCell<Vec<InnerStatementPtr>>>, pub ignore_next_sqlite_error: Rc<Cell<bool>>, pub use_big_ints: Cell<bool>, pub allow_bare_named_params: Cell<bool>, pub allow_unknown_named_params: Cell<bool>, pub is_iter_finished: Cell<bool>, } impl Drop for StatementSync { fn drop(&mut self) { let mut statements = self.statements.borrow_mut(); let mut finalized_stmt = None; if let Some(pos) = statements .iter() .position(|stmt| Rc::ptr_eq(stmt, &self.inner)) { let stmt = statements.remove(pos); finalized_stmt = stmt.get(); stmt.set(None); } if let Some(ptr) = finalized_stmt { // SAFETY: `ptr` is a valid pointer to a sqlite3_stmt. unsafe { ffi::sqlite3_finalize(ptr); } } } } pub(crate) fn check_error_code( r: i32, db: *mut ffi::sqlite3, ) -> Result<(), SqliteError> { if r != ffi::SQLITE_OK { // SAFETY: lifetime of the connection is guaranteed by reference // counting. let err_message = unsafe { ffi::sqlite3_errmsg(db) }; if !err_message.is_null() { // SAFETY: `err_msg` is a valid pointer to a null-terminated string. let err_message = unsafe { std::ffi::CStr::from_ptr(err_message) } .to_string_lossy() .into_owned(); // SAFETY: `err_str` is a valid pointer to a null-terminated string. let err_str = unsafe { std::ffi::CStr::from_ptr(ffi::sqlite3_errstr(r)) } .to_string_lossy() .into_owned(); return Err(SqliteError::SqliteSysError { message: err_message, errcode: r as _, errstr: err_str, }); } } Ok(()) } pub(crate) fn check_error_code2(r: i32) -> Result<(), SqliteError> { // SAFETY: `ffi::sqlite3_errstr` is a valid function that returns a pointer to a null-terminated // string. let err_str = unsafe { std::ffi::CStr::from_ptr(ffi::sqlite3_errstr(r)) } .to_string_lossy() .into_owned(); Err(SqliteError::SqliteSysError { message: err_str.clone(), errcode: r as _, errstr: err_str, }) } struct ColumnIterator<'a> { stmt: &'a StatementSync, index: i32, count: i32, } impl<'a> ColumnIterator<'a> { fn new(stmt: &'a StatementSync) -> Result<Self, SqliteError> { let count = stmt.column_count()?; Ok(ColumnIterator { stmt, index: 0, count, }) } fn column_count(&self) -> usize { self.count as usize } } impl<'a> Iterator for ColumnIterator<'a> { type Item = Result<(i32, &'a [u8]), SqliteError>; fn next(&mut self) -> Option<Self::Item> { if self.index >= self.count { return None; } let index = self.index; let name = match self.stmt.column_name(index) { Ok(name) => name, Err(_) => return Some(Err(SqliteError::StatementFinalized)), }; self.index += 1; Some(Ok((index, name))) } } // SAFETY: we're sure this can be GCed unsafe impl GarbageCollected for StatementSync { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"StatementSync" } } impl StatementSync { fn stmt_ptr(&self) -> Result<*mut ffi::sqlite3_stmt, SqliteError> { let ptr = self.inner.get(); match ptr { Some(p) => Ok(p), None => Err(SqliteError::StatementFinalized), } } fn assert_statement_finalized(&self) -> Result<(), SqliteError> { if self.inner.get().is_none() { return Err(SqliteError::StatementFinalized); } Ok(()) } // Clear the prepared statement back to its initial state. fn reset(&self) -> Result<(), SqliteError> { let raw = self.stmt_ptr()?; // SAFETY: `raw` is a valid pointer to a sqlite3_stmt // as it lives as long as the StatementSync instance. let r = unsafe { ffi::sqlite3_reset(raw) }; self.check_error_code(r) } // Evaluate the prepared statement. fn step(&self) -> Result<bool, SqliteError> { let raw = self.stmt_ptr()?; // SAFETY: `raw` is a valid pointer to a sqlite3_stmt // as it lives as long as the StatementSync instance. unsafe { let r = ffi::sqlite3_step(raw); if r == ffi::SQLITE_DONE { return Ok(true); } if r != ffi::SQLITE_ROW { self.check_error_code(r)?; } } Ok(false) } fn column_count(&self) -> Result<i32, SqliteError> { let raw = self.stmt_ptr()?; // SAFETY: `raw` is a valid pointer to a sqlite3_stmt // as it lives as long as the StatementSync instance. let count = unsafe { ffi::sqlite3_column_count(raw) }; Ok(count) } fn column_name(&self, index: i32) -> Result<&[u8], SqliteError> { let raw = self.stmt_ptr()?; // SAFETY: `raw` is a valid pointer to a sqlite3_stmt // as it lives as long as the StatementSync instance. unsafe { let name = ffi::sqlite3_column_name(raw, index); Ok(std::ffi::CStr::from_ptr(name as _).to_bytes()) } } fn column_value<'a>( &self, index: i32, scope: &mut v8::PinScope<'a, '_>, ) -> Result<v8::Local<'a, v8::Value>, SqliteError> { let raw = self.stmt_ptr()?; // SAFETY: `raw` is a valid pointer to a sqlite3_stmt // as it lives as long as the StatementSync instance. unsafe { Ok(match ffi::sqlite3_column_type(raw, index) { ffi::SQLITE_INTEGER => { let value = ffi::sqlite3_column_int64(raw, index); if self.use_big_ints.get() { v8::BigInt::new_from_i64(scope, value).into() } else if value.abs() <= MAX_SAFE_JS_INTEGER { v8::Number::new(scope, value as f64).into() } else { return Err(SqliteError::NumberTooLarge(index, value)); } } ffi::SQLITE_FLOAT => { let value = ffi::sqlite3_column_double(raw, index); v8::Number::new(scope, value).into() } ffi::SQLITE_TEXT => { let value = ffi::sqlite3_column_text(raw, index); let value = std::ffi::CStr::from_ptr(value as _); v8::String::new_from_utf8( scope, value.to_bytes(), v8::NewStringType::Normal, ) .unwrap() .into() } ffi::SQLITE_BLOB => { let value = ffi::sqlite3_column_blob(raw, index); let size = ffi::sqlite3_column_bytes(raw, index); let ab = if size == 0 { v8::ArrayBuffer::new(scope, 0) } else { let value = std::slice::from_raw_parts(value as *const u8, size as usize); let bs = v8::ArrayBuffer::new_backing_store_from_vec(value.to_vec()) .make_shared(); v8::ArrayBuffer::with_backing_store(scope, &bs) }; v8::Uint8Array::new(scope, ab, 0, size as _).unwrap().into() } ffi::SQLITE_NULL => v8::null(scope).into(), _ => v8::undefined(scope).into(), }) } } // Read the current row of the prepared statement. fn read_row<'a>( &self, scope: &mut v8::PinScope<'a, '_>, ) -> Result<Option<v8::Local<'a, v8::Object>>, SqliteError> { if self.step()? { return Ok(None); } let iter = ColumnIterator::new(self)?; let num_cols = iter.column_count(); let mut names = Vec::with_capacity(num_cols); let mut values = Vec::with_capacity(num_cols); for item in iter { let (index, name) = item?; let value = self.column_value(index, scope)?; let name = v8::String::new_from_utf8(scope, name, v8::NewStringType::Normal) .unwrap() .into(); names.push(name); values.push(value); } let null = v8::null(scope).into(); let result = v8::Object::with_prototype_and_properties(scope, null, &names, &values); Ok(Some(result)) } fn bind_value( &self, scope: &mut v8::PinScope<'_, '_>, value: v8::Local<v8::Value>, index: i32, ) -> Result<(), SqliteError> { let raw = self.stmt_ptr()?; let r = if value.is_number() { let value = value.number_value(scope).unwrap(); // SAFETY: `raw` is a valid pointer to a sqlite3_stmt // as it lives as long as the StatementSync instance. unsafe { ffi::sqlite3_bind_double(raw, index, value) } } else if value.is_string() { let value = value.to_rust_string_lossy(scope); // SAFETY: `raw` is a valid pointer to a sqlite3_stmt // as it lives as long as the StatementSync instance. // // SQLITE_TRANSIENT is used to indicate that SQLite should make a copy of the data. unsafe { ffi::sqlite3_bind_text( raw, index, value.as_ptr() as *const _, value.len() as i32, ffi::SQLITE_TRANSIENT(), ) } } else if value.is_null() { // SAFETY: `raw` is a valid pointer to a sqlite3_stmt // as it lives as long as the StatementSync instance. unsafe { ffi::sqlite3_bind_null(raw, index) } } else if value.is_array_buffer_view() { let value: v8::Local<v8::ArrayBufferView> = value.try_into().unwrap(); let mut data = value.data(); let mut size = value.byte_length(); // data may be NULL if length is 0 or ab is detached. we need to pass a valid pointer // to sqlite3_bind_blob, so we use a static empty array in this case. if data.is_null() { static EMPTY: [u8; 0] = []; data = EMPTY.as_ptr() as *mut _; size = 0; } // SAFETY: `raw` is a valid pointer to a sqlite3_stmt // as it lives as long as the StatementSync instance. // // SQLITE_TRANSIENT is used to indicate that SQLite should make a copy of the data. unsafe { ffi::sqlite3_bind_blob( raw, index, data, size as i32, ffi::SQLITE_TRANSIENT(), ) } } else if value.is_big_int() { let value: v8::Local<v8::BigInt> = value.try_into().unwrap(); let (as_int, lossless) = value.i64_value(); if !lossless { return Err(SqliteError::InvalidBindValue( "BigInt value is too large to bind", )); } // SAFETY: `raw` is a valid pointer to a sqlite3_stmt // as it lives as long as the StatementSync instance. unsafe { ffi::sqlite3_bind_int64(raw, index, as_int) } } else { return Err(SqliteError::InvalidBindType(index)); }; self.check_error_code(r) } fn check_error_code(&self, r: i32) -> Result<(), SqliteError> { if r != ffi::SQLITE_OK { if self.ignore_next_sqlite_error.get() { self.ignore_next_sqlite_error.set(false); return Ok(()); } let db_rc = self.db.upgrade().ok_or(SqliteError::InUse)?; let db = db_rc.borrow(); let db = db.as_ref().ok_or(SqliteError::InUse)?; // SAFETY: db.handle() is valid unsafe { check_error_code(r, db.handle())?; } } Ok(()) } // Bind the parameters to the prepared statement. fn bind_params( &self, scope: &mut v8::PinScope<'_, '_>, params: Option<&v8::FunctionCallbackArguments>, ) -> Result<(), SqliteError> { let raw = self.stmt_ptr()?; // Reset the prepared statement to its initial state. // SAFETY: `raw` is a valid pointer to a sqlite3_stmt unsafe { let r = ffi::sqlite3_clear_bindings(raw); self.check_error_code(r)?; } let mut anon_start = 0; if let Some(params) = params { let param0 = params.get(0); if param0.is_object() && !param0.is_array_buffer_view() { let obj = v8::Local::<v8::Object>::try_from(param0).unwrap(); let keys = obj .get_property_names(scope, GetPropertyNamesArgs::default()) .unwrap(); // Allow specifying named parameters without the SQLite prefix character to improve // ergonomics. This can be disabled with `StatementSync#setAllowBareNamedParams`. let mut bare_named_params = std::collections::HashMap::new(); if self.allow_bare_named_params.get() { // SAFETY: `raw` is a valid pointer to a sqlite3_stmt. let param_count = unsafe { ffi::sqlite3_bind_parameter_count(raw) }; for i in 1..=param_count { // SAFETY: `raw` is a valid pointer to a sqlite3_stmt. let full_name = unsafe { let name = ffi::sqlite3_bind_parameter_name(raw, i); if name.is_null() { continue; } std::ffi::CStr::from_ptr(name).to_bytes() }; let bare_name = &full_name[1..]; let e = bare_named_params.insert(bare_name, i); if let Some(existing_index) = e { let bare_name_str = std::str::from_utf8(bare_name)?; let full_name_str = std::str::from_utf8(full_name)?; // SAFETY: `raw` is a valid pointer to a sqlite3_stmt. unsafe { let existing_full_name = ffi::sqlite3_bind_parameter_name(raw, existing_index); let existing_full_name_str = std::ffi::CStr::from_ptr(existing_full_name).to_str()?; return Err(SqliteError::DuplicateNamedParameter( bare_name_str.to_string(), existing_full_name_str.to_string(), full_name_str.to_string(), )); } } } } let len = keys.length(); for j in 0..len { let key = keys.get_index(scope, j).unwrap(); let key_str = key.to_rust_string_lossy(scope); let key_c = std::ffi::CString::new(key_str).unwrap(); // SAFETY: `raw` is a valid pointer to a sqlite3_stmt. let mut r = unsafe { ffi::sqlite3_bind_parameter_index(raw, key_c.as_ptr() as *const _) }; if r == 0 { let lookup = bare_named_params.get(key_c.as_bytes()); if let Some(index) = lookup { r = *index; } if r == 0 { if self.allow_unknown_named_params.get() { continue; } return Err(SqliteError::UnknownNamedParameter( key_c.into_string().unwrap(), )); } } let value = obj.get(scope, key).unwrap(); self.bind_value(scope, value, r)?; } anon_start += 1; } // SAFETY: `raw` is a valid pointer to a sqlite3_stmt. let sql_param_count = unsafe { ffi::sqlite3_bind_parameter_count(raw) }; let mut positional_idx = 1; for i in anon_start..params.length() { // Find the next positional parameter slot. // Skip named parameters (:name, $name, @name) but include anonymous (?) // and numbered (?NNN) parameters. while positional_idx <= sql_param_count { // SAFETY: `raw` is a valid pointer to a sqlite3_stmt. let name_ptr = unsafe { ffi::sqlite3_bind_parameter_name(raw, positional_idx) }; if name_ptr.is_null() // SAFETY: short-circuiting guarantees name_ptr is non-null here || unsafe { *name_ptr as u8 == b'?' } { break; } // Named parameter (:name, $name, @name) - skip it positional_idx += 1; } let value = params.get(i); self.bind_value(scope, value, positional_idx)?; positional_idx += 1; } } Ok(()) } } struct ResetGuard<'a>(&'a StatementSync); impl Drop for ResetGuard<'_> { fn drop(&mut self) { let _ = self.0.reset(); } } // Represents a single prepared statement. Cannot be initialized directly via constructor. // Instances are created using `DatabaseSync#prepare`. // // A prepared statement is an efficient binary representation of the SQL used to create it. #[op2] impl StatementSync { #[constructor] #[cppgc] fn new(_: bool) -> Result<StatementSync, SqliteError> { Err(SqliteError::InvalidConstructor) } // Executes a prepared statement and returns the first result as an object. // // The prepared statement does not return any results, this method returns undefined. // Optionally, parameters can be bound to the prepared statement. #[reentrant] fn get<'a>( &self, scope: &mut v8::PinScope<'a, '_>, #[varargs] params: Option<&v8::FunctionCallbackArguments>, ) -> Result<v8::Local<'a, v8::Value>, SqliteError> { self.reset()?; self.bind_params(scope, params)?; let _reset = ResetGuard(self); let entry = self.read_row(scope)?; let result = entry .map(|r| r.into()) .unwrap_or_else(|| v8::undefined(scope).into()); Ok(result) } // Executes a prepared statement and returns an object summarizing the resulting // changes. // // Optionally, parameters can be bound to the prepared statement. #[to_v8] fn run( &self, scope: &mut v8::PinScope<'_, '_>, #[varargs] params: Option<&v8::FunctionCallbackArguments>, ) -> Result<RunStatementResult, SqliteError> { let db_rc = self.db.upgrade().ok_or(SqliteError::InUse)?; let db = db_rc.borrow(); let db = db.as_ref().ok_or(SqliteError::InUse)?; self.bind_params(scope, params)?; let reset = ResetGuard(self); self.step()?; // Reset to return correct change metadata. drop(reset); Ok(RunStatementResult { last_insert_rowid: db.last_insert_rowid(), changes: db.changes(), use_big_ints: self.use_big_ints.get(), }) } // Executes a prepared statement and returns all results as an array of objects. // // If the prepared statement does not return any results, this method returns an empty array. // Optionally, parameters can be bound to the prepared statement. fn all<'a>( &self, scope: &mut v8::PinScope<'a, '_>, #[varargs] params: Option<&v8::FunctionCallbackArguments>, ) -> Result<v8::Local<'a, v8::Array>, SqliteError> { let mut arr = vec![]; self.bind_params(scope, params)?; let _reset = ResetGuard(self); while let Some(result) = self.read_row(scope)? { arr.push(result.into()); } let arr = v8::Array::new_with_elements(scope, &arr); Ok(arr) } fn iterate<'a>( &self, scope: &mut v8::PinScope<'a, '_>, #[varargs] params: Option<&v8::FunctionCallbackArguments>, ) -> Result<v8::Local<'a, v8::Object>, SqliteError> { macro_rules! v8_static_strings { ($($ident:ident = $str:literal),* $(,)?) => { $( pub static $ident: deno_core::FastStaticString = deno_core::ascii_str!($str); )* }; } v8_static_strings! { ITERATOR = "Iterator", PROTOTYPE = "prototype", NEXT = "next", RETURN = "return", DONE = "done", VALUE = "value", } self.reset()?; self.bind_params(scope, params)?; let iterate_next = |scope: &mut v8::PinScope<'_, '_>, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue| { let context = v8::Local::<v8::External>::try_from(args.data()) .expect("Iterator#next expected external data"); // SAFETY: `context` is a valid pointer to a StatementSync instance let statement = unsafe { &mut *(context.value() as *mut StatementSync) }; let names = &[ DONE.v8_string(scope).unwrap().into(), VALUE.v8_string(scope).unwrap().into(), ]; if statement.is_iter_finished.get() { let values = &[ v8::Boolean::new(scope, true).into(), v8::undefined(scope).into(), ]; let null = v8::null(scope).into(); let result = v8::Object::with_prototype_and_properties(scope, null, names, values); rv.set(result.into()); return; } let Ok(Some(row)) = statement.read_row(scope) else { let _ = statement.reset(); statement.is_iter_finished.set(true); let values = &[ v8::Boolean::new(scope, true).into(), v8::undefined(scope).into(), ]; let null = v8::null(scope).into(); let result = v8::Object::with_prototype_and_properties(scope, null, names, values); rv.set(result.into()); return; }; let values = &[v8::Boolean::new(scope, false).into(), row.into()]; let null = v8::null(scope).into(); let result = v8::Object::with_prototype_and_properties(scope, null, names, values); rv.set(result.into()); }; let iterate_return = |scope: &mut v8::PinScope<'_, '_>, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue| { let context = v8::Local::<v8::External>::try_from(args.data()) .expect("Iterator#return expected external data"); // SAFETY: `context` is a valid pointer to a StatementSync instance let statement = unsafe { &mut *(context.value() as *mut StatementSync) }; statement.is_iter_finished.set(true); let _ = statement.reset(); let names = &[ DONE.v8_string(scope).unwrap().into(), VALUE.v8_string(scope).unwrap().into(), ]; let values = &[ v8::Boolean::new(scope, true).into(), v8::undefined(scope).into(), ]; let null = v8::null(scope).into(); let result = v8::Object::with_prototype_and_properties(scope, null, names, values); rv.set(result.into()); }; let external = v8::External::new(scope, self as *const _ as _); let next_func = v8::Function::builder(iterate_next) .data(external.into()) .build(scope) .expect("Failed to create Iterator#next function"); let return_func = v8::Function::builder(iterate_return) .data(external.into()) .build(scope) .expect("Failed to create Iterator#return function"); let global = scope.get_current_context().global(scope); let iter_str = ITERATOR.v8_string(scope).unwrap(); let js_iterator: v8::Local<v8::Object> = { global .get(scope, iter_str.into()) .unwrap() .try_into() .unwrap() }; let proto_str = PROTOTYPE.v8_string(scope).unwrap(); let js_iterator_proto = js_iterator.get(scope, proto_str.into()).unwrap(); let names = &[ NEXT.v8_string(scope).unwrap().into(), RETURN.v8_string(scope).unwrap().into(), ]; let values = &[next_func.into(), return_func.into()]; let iterator = v8::Object::with_prototype_and_properties( scope, js_iterator_proto, names, values, ); self.is_iter_finished.set(false); Ok(iterator) } #[fast] #[undefined] fn set_allow_bare_named_parameters( &self, #[validate(validators::allow_bare_named_params_bool)] enabled: bool, ) -> Result<(), SqliteError> { self.assert_statement_finalized()?; self.allow_bare_named_params.set(enabled); Ok(()) } #[fast] #[undefined] fn set_allow_unknown_named_parameters( &self, #[validate(validators::allow_unknown_named_params_bool)] enabled: bool, ) -> Result<(), SqliteError> { self.assert_statement_finalized()?; self.allow_unknown_named_params.set(enabled); Ok(()) } #[fast] #[undefined] fn set_read_big_ints( &self, #[validate(validators::read_big_ints_bool)] enabled: bool, ) -> Result<(), SqliteError> { self.assert_statement_finalized()?; self.use_big_ints.set(enabled); Ok(()) } #[getter] #[rename("sourceSQL")] #[string] fn source_sql(&self) -> Result<String, SqliteError> { let inner = self.stmt_ptr()?; // SAFETY: `raw` is a valid pointer to a sqlite3_stmt // as it lives as long as the StatementSync instance. let source_sql = unsafe { let raw = ffi::sqlite3_sql(inner); std::ffi::CStr::from_ptr(raw as _) .to_string_lossy() .into_owned() }; Ok(source_sql) } #[getter] #[rename("expandedSQL")] #[string] fn expanded_sql(&self) -> Result<String, SqliteError> { let inner = self.stmt_ptr()?; // SAFETY: `inner` is a valid pointer to a sqlite3_stmt // as it lives as long as the StatementSync instance. unsafe { let raw = ffi::sqlite3_expanded_sql(inner); if raw.is_null() { return Err(SqliteError::InvalidExpandedSql); } let sql = std::ffi::CStr::from_ptr(raw as _) .to_string_lossy() .into_owned(); ffi::sqlite3_free(raw as _); Ok(sql) } } fn columns<'a>( &self, scope: &mut v8::PinScope<'a, '_>, ) -> Result<v8::Local<'a, v8::Array>, SqliteError> { v8_static_strings! { NAME = "name", COLUMN = "column", TABLE = "table", DATABASE = "database", TYPE = "type", } let column_count = self.column_count()?; let mut columns = Vec::with_capacity(column_count as usize); // Pre-create property keys let name_key = NAME.v8_string(scope).unwrap().into(); let column_key = COLUMN.v8_string(scope).unwrap().into(); let table_key = TABLE.v8_string(scope).unwrap().into(); let database_key = DATABASE.v8_string(scope).unwrap().into(); let type_key = TYPE.v8_string(scope).unwrap().into(); let keys = &[name_key, column_key, table_key, database_key, type_key]; let raw = self.stmt_ptr()?; for i in 0..column_count { // name: The name of the column in the result set // SAFETY: `raw` is a valid pointer to a sqlite3_stmt let name = unsafe { let name_ptr = ffi::sqlite3_column_name(raw, i); if !name_ptr.is_null() { let name_cstr = std::ffi::CStr::from_ptr(name_ptr as _); v8::String::new_from_utf8( scope, name_cstr.to_bytes(), v8::NewStringType::Normal, ) .unwrap() .into() } else { v8::null(scope).into() } }; // column: The unaliased name of the column in the origin table // SAFETY: `raw` is a valid pointer to a sqlite3_stmt let column = unsafe { let column_ptr = ffi::sqlite3_column_origin_name(raw, i); if !column_ptr.is_null() { let column_cstr = std::ffi::CStr::from_ptr(column_ptr as _); v8::String::new_from_utf8( scope, column_cstr.to_bytes(), v8::NewStringType::Normal, ) .unwrap() .into() } else { v8::null(scope).into() } }; // table: The unaliased name of the origin table // SAFETY: `raw` is a valid pointer to a sqlite3_stmt let table = unsafe { let table_ptr = ffi::sqlite3_column_table_name(raw, i); if !table_ptr.is_null() { let table_cstr = std::ffi::CStr::from_ptr(table_ptr as _); v8::String::new_from_utf8( scope, table_cstr.to_bytes(), v8::NewStringType::Normal, ) .unwrap() .into() } else { v8::null(scope).into() } }; // database: The unaliased name of the origin database // SAFETY: `raw` is a valid pointer to a sqlite3_stmt let database = unsafe { let database_ptr = ffi::sqlite3_column_database_name(raw, i); if !database_ptr.is_null() { let database_cstr = std::ffi::CStr::from_ptr(database_ptr as _); v8::String::new_from_utf8( scope, database_cstr.to_bytes(), v8::NewStringType::Normal, ) .unwrap() .into() } else { v8::null(scope).into() } }; // type: The declared data type of the column // SAFETY: `raw` is a valid pointer to a sqlite3_stmt let col_type = unsafe { let type_ptr = ffi::sqlite3_column_decltype(raw, i); if !type_ptr.is_null() { let type_cstr = std::ffi::CStr::from_ptr(type_ptr as _); v8::String::new_from_utf8( scope, type_cstr.to_bytes(), v8::NewStringType::Normal, ) .unwrap() .into() } else { v8::null(scope).into() } }; let values = &[name, column, table, database, col_type]; let null = v8::null(scope).into(); let obj = v8::Object::with_prototype_and_properties(scope, null, keys, values); columns.push(obj.into()); } Ok(v8::Array::new_with_elements(scope, &columns)) } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/os/mod.rs
ext/node/ops/os/mod.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::mem::MaybeUninit; use deno_core::OpState; use deno_core::op2; use deno_permissions::PermissionCheckError; use deno_permissions::PermissionsContainer; use sys_traits::EnvHomeDir; mod cpus; pub mod priority; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum OsError { #[class(inherit)] #[error(transparent)] Priority(#[inherit] priority::PriorityError), #[class(inherit)] #[error(transparent)] Permission( #[from] #[inherit] PermissionCheckError, ), #[class(inherit)] #[error("Failed to get user info")] FailedToGetUserInfo( #[source] #[inherit] std::io::Error, ), } #[op2(fast, stack_trace)] pub fn op_node_os_get_priority( state: &mut OpState, pid: u32, ) -> Result<i32, OsError> { { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_sys("getPriority", "node:os.getPriority()")?; } priority::get_priority(pid).map_err(OsError::Priority) } #[op2(fast, stack_trace)] pub fn op_node_os_set_priority( state: &mut OpState, pid: u32, priority: i32, ) -> Result<(), OsError> { { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_sys("setPriority", "node:os.setPriority()")?; } priority::set_priority(pid, priority).map_err(OsError::Priority) } #[derive(serde::Serialize)] pub struct UserInfo { username: String, homedir: String, shell: Option<String>, } #[cfg(unix)] fn get_user_info(uid: u32) -> Result<UserInfo, OsError> { use std::ffi::CStr; let mut pw: MaybeUninit<libc::passwd> = MaybeUninit::uninit(); let mut result: *mut libc::passwd = std::ptr::null_mut(); // SAFETY: libc call, no invariants let max_buf_size = unsafe { libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) }; let buf_size = if max_buf_size < 0 { // from the man page 16_384 } else { max_buf_size as usize }; let mut buf = { let mut b = Vec::<MaybeUninit<libc::c_char>>::with_capacity(buf_size); // SAFETY: MaybeUninit has no initialization invariants, and len == cap unsafe { b.set_len(buf_size); } b }; // SAFETY: libc call, args are correct let s = unsafe { libc::getpwuid_r( uid, pw.as_mut_ptr(), buf.as_mut_ptr().cast(), buf_size, std::ptr::addr_of_mut!(result), ) }; if result.is_null() { if s != 0 { return Err( OsError::FailedToGetUserInfo(std::io::Error::last_os_error()), ); } else { return Err(OsError::FailedToGetUserInfo(std::io::Error::from( std::io::ErrorKind::NotFound, ))); } } // SAFETY: pw was initialized by the call to `getpwuid_r` above let pw = unsafe { pw.assume_init() }; // SAFETY: initialized above, pw alive until end of function, nul terminated let username = unsafe { CStr::from_ptr(pw.pw_name) }; // SAFETY: initialized above, pw alive until end of function, nul terminated let homedir = unsafe { CStr::from_ptr(pw.pw_dir) }; // SAFETY: initialized above, pw alive until end of function, nul terminated let shell = unsafe { CStr::from_ptr(pw.pw_shell) }; Ok(UserInfo { username: username.to_string_lossy().into_owned(), homedir: homedir.to_string_lossy().into_owned(), shell: Some(shell.to_string_lossy().into_owned()), }) } #[cfg(windows)] fn get_user_info(_uid: u32) -> Result<UserInfo, OsError> { use std::ffi::OsString; use std::os::windows::ffi::OsStringExt; use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER; use windows_sys::Win32::Foundation::GetLastError; use windows_sys::Win32::Foundation::HANDLE; use windows_sys::Win32::System::Threading::GetCurrentProcess; use windows_sys::Win32::System::Threading::OpenProcessToken; use windows_sys::Win32::UI::Shell::GetUserProfileDirectoryW; struct Handle(HANDLE); impl Drop for Handle { fn drop(&mut self) { // SAFETY: win32 call unsafe { CloseHandle(self.0); } } } let mut token: MaybeUninit<HANDLE> = MaybeUninit::uninit(); // Get a handle to the current process // SAFETY: win32 call unsafe { if OpenProcessToken( GetCurrentProcess(), windows_sys::Win32::Security::TOKEN_READ, token.as_mut_ptr(), ) == 0 { return Err( OsError::FailedToGetUserInfo(std::io::Error::last_os_error()), ); } } // SAFETY: initialized by call above let token = Handle(unsafe { token.assume_init() }); let mut bufsize = 0; // get the size for the homedir buf (it'll end up in `bufsize`) // SAFETY: win32 call unsafe { GetUserProfileDirectoryW(token.0, std::ptr::null_mut(), &mut bufsize); let err = GetLastError(); if err != ERROR_INSUFFICIENT_BUFFER { return Err(OsError::FailedToGetUserInfo( std::io::Error::from_raw_os_error(err as i32), )); } } let mut path = vec![0; bufsize as usize]; // Actually get the homedir // SAFETY: path is `bufsize` elements unsafe { if GetUserProfileDirectoryW(token.0, path.as_mut_ptr(), &mut bufsize) == 0 { return Err( OsError::FailedToGetUserInfo(std::io::Error::last_os_error()), ); } } // remove trailing nul path.pop(); let homedir_wide = OsString::from_wide(&path); let homedir = homedir_wide.to_string_lossy().into_owned(); Ok(UserInfo { username: deno_whoami::username(), homedir, shell: None, }) } #[op2(stack_trace)] #[serde] pub fn op_node_os_user_info( state: &mut OpState, #[smi] uid: u32, ) -> Result<UserInfo, OsError> { { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions .check_sys("userInfo", "node:os.userInfo()") .map_err(OsError::Permission)?; } get_user_info(uid) } #[op2(fast, stack_trace)] pub fn op_geteuid(state: &mut OpState) -> Result<u32, PermissionCheckError> { { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_sys("uid", "node:os.geteuid()")?; } #[cfg(windows)] let euid = 0; #[cfg(unix)] // SAFETY: Call to libc geteuid. let euid = unsafe { libc::geteuid() }; Ok(euid) } #[op2(fast, stack_trace)] pub fn op_getegid(state: &mut OpState) -> Result<u32, PermissionCheckError> { { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_sys("getegid", "node:os.getegid()")?; } #[cfg(windows)] let egid = 0; #[cfg(unix)] // SAFETY: Call to libc getegid. let egid = unsafe { libc::getegid() }; Ok(egid) } #[op2(stack_trace)] #[serde] pub fn op_cpus(state: &mut OpState) -> Result<Vec<cpus::CpuInfo>, OsError> { { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_sys("cpus", "node:os.cpus()")?; } Ok(cpus::cpu_info().unwrap_or_default()) } #[op2(stack_trace)] #[string] pub fn op_homedir( state: &mut OpState, ) -> Result<Option<String>, PermissionCheckError> { { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_sys("homedir", "node:os.homedir()")?; } Ok( sys_traits::impls::RealSys .env_home_dir() .map(|path| path.to_string_lossy().into_owned()), ) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/os/priority.rs
ext/node/ops/os/priority.rs
// Copyright 2018-2025 the Deno authors. MIT license. pub use impl_::*; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum PriorityError { #[class(inherit)] #[error("{0}")] Io(#[from] std::io::Error), #[cfg(windows)] #[class(type)] #[error("Invalid priority")] InvalidPriority, } #[cfg(unix)] mod impl_ { use errno::Errno; use errno::errno; use errno::set_errno; use libc::PRIO_PROCESS; use libc::id_t; // Ref: https://github.com/libuv/libuv/blob/55376b044b74db40772e8a6e24d67a8673998e02/src/unix/core.c#L1533-L1547 pub fn get_priority(pid: u32) -> Result<i32, super::PriorityError> { set_errno(Errno(0)); match ( // SAFETY: libc::getpriority is unsafe unsafe { libc::getpriority(PRIO_PROCESS, pid as id_t) }, errno(), ) { (-1, Errno(0)) => Ok(-1), (-1, _) => Err(std::io::Error::last_os_error().into()), (priority, _) => Ok(priority), } } pub fn set_priority( pid: u32, priority: i32, ) -> Result<(), super::PriorityError> { // SAFETY: libc::setpriority is unsafe match unsafe { libc::setpriority(PRIO_PROCESS, pid as id_t, priority) } { -1 => Err(std::io::Error::last_os_error().into()), _ => Ok(()), } } } #[cfg(windows)] mod impl_ { use winapi::shared::minwindef::DWORD; use winapi::shared::minwindef::FALSE; use winapi::shared::ntdef::NULL; use winapi::um::handleapi::CloseHandle; use winapi::um::processthreadsapi::GetCurrentProcess; use winapi::um::processthreadsapi::GetPriorityClass; use winapi::um::processthreadsapi::OpenProcess; use winapi::um::processthreadsapi::SetPriorityClass; use winapi::um::winbase::ABOVE_NORMAL_PRIORITY_CLASS; use winapi::um::winbase::BELOW_NORMAL_PRIORITY_CLASS; use winapi::um::winbase::HIGH_PRIORITY_CLASS; use winapi::um::winbase::IDLE_PRIORITY_CLASS; use winapi::um::winbase::NORMAL_PRIORITY_CLASS; use winapi::um::winbase::REALTIME_PRIORITY_CLASS; use winapi::um::winnt::PROCESS_QUERY_LIMITED_INFORMATION; use winapi::um::winnt::PROCESS_SET_INFORMATION; // Taken from: https://github.com/libuv/libuv/blob/a877ca2435134ef86315326ef4ef0c16bdbabf17/include/uv.h#L1318-L1323 const PRIORITY_LOW: i32 = 19; const PRIORITY_BELOW_NORMAL: i32 = 10; const PRIORITY_NORMAL: i32 = 0; const PRIORITY_ABOVE_NORMAL: i32 = -7; const PRIORITY_HIGH: i32 = -14; const PRIORITY_HIGHEST: i32 = -20; // Ported from: https://github.com/libuv/libuv/blob/a877ca2435134ef86315326ef4ef0c16bdbabf17/src/win/util.c#L1649-L1685 pub fn get_priority(pid: u32) -> Result<i32, super::PriorityError> { // SAFETY: Windows API calls unsafe { let handle = if pid == 0 { GetCurrentProcess() } else { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid as DWORD) }; if handle == NULL { Err(std::io::Error::last_os_error().into()) } else { let result = match GetPriorityClass(handle) { 0 => Err(std::io::Error::last_os_error().into()), REALTIME_PRIORITY_CLASS => Ok(PRIORITY_HIGHEST), HIGH_PRIORITY_CLASS => Ok(PRIORITY_HIGH), ABOVE_NORMAL_PRIORITY_CLASS => Ok(PRIORITY_ABOVE_NORMAL), NORMAL_PRIORITY_CLASS => Ok(PRIORITY_NORMAL), BELOW_NORMAL_PRIORITY_CLASS => Ok(PRIORITY_BELOW_NORMAL), IDLE_PRIORITY_CLASS => Ok(PRIORITY_LOW), _ => Ok(PRIORITY_LOW), }; CloseHandle(handle); result } } } // Ported from: https://github.com/libuv/libuv/blob/a877ca2435134ef86315326ef4ef0c16bdbabf17/src/win/util.c#L1688-L1719 pub fn set_priority( pid: u32, priority: i32, ) -> Result<(), super::PriorityError> { // SAFETY: Windows API calls unsafe { let handle = if pid == 0 { GetCurrentProcess() } else { OpenProcess(PROCESS_SET_INFORMATION, FALSE, pid as DWORD) }; if handle == NULL { Err(std::io::Error::last_os_error().into()) } else { #[allow(clippy::manual_range_contains)] let priority_class = if priority < PRIORITY_HIGHEST || priority > PRIORITY_LOW { return Err(super::PriorityError::InvalidPriority); } else if priority < PRIORITY_HIGH { REALTIME_PRIORITY_CLASS } else if priority < PRIORITY_ABOVE_NORMAL { HIGH_PRIORITY_CLASS } else if priority < PRIORITY_NORMAL { ABOVE_NORMAL_PRIORITY_CLASS } else if priority < PRIORITY_BELOW_NORMAL { NORMAL_PRIORITY_CLASS } else if priority < PRIORITY_LOW { BELOW_NORMAL_PRIORITY_CLASS } else { IDLE_PRIORITY_CLASS }; let result = match SetPriorityClass(handle, priority_class) { FALSE => Err(std::io::Error::last_os_error().into()), _ => Ok(()), }; CloseHandle(handle); result } } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/os/cpus.rs
ext/node/ops/os/cpus.rs
// Copyright 2018-2025 the Deno authors. MIT license. use deno_core::serde::Serialize; #[derive(Debug, Default, Serialize, Clone)] pub struct CpuTimes { pub user: u64, pub nice: u64, pub sys: u64, pub idle: u64, pub irq: u64, } #[derive(Debug, Default, Serialize, Clone)] pub struct CpuInfo { pub model: String, /* in MHz */ pub speed: u64, pub times: CpuTimes, } impl CpuInfo { pub fn new() -> Self { Self::default() } } #[cfg(target_os = "macos")] pub fn cpu_info() -> Option<Vec<CpuInfo>> { let mut model: [u8; 512] = [0; 512]; let mut size = std::mem::size_of_val(&model); // Safety: Assumes correct behavior of platform-specific syscalls and data structures. // Relies on specific sysctl names and sysconf parameter existence. unsafe { let ticks = libc::sysconf(libc::_SC_CLK_TCK); let multiplier = 1000u64 / ticks as u64; if libc::sysctlbyname( c"machdep.cpu.brand_string".as_ptr() as *const libc::c_char, model.as_mut_ptr() as _, &mut size, std::ptr::null_mut(), 0, ) != 0 && libc::sysctlbyname( c"hw.model".as_ptr() as *const libc::c_char, model.as_mut_ptr() as _, &mut size, std::ptr::null_mut(), 0, ) != 0 { return None; } let mut cpu_speed: u64 = 0; let mut cpu_speed_size = std::mem::size_of_val(&cpu_speed); libc::sysctlbyname( c"hw.cpufrequency".as_ptr() as *const libc::c_char, &mut cpu_speed as *mut _ as *mut libc::c_void, &mut cpu_speed_size, std::ptr::null_mut(), 0, ); if cpu_speed == 0 { // https://github.com/libuv/libuv/pull/3679 // // hw.cpufrequency sysctl seems to be missing on darwin/arm64 // so we instead hardcode a plausible value. This value matches // what the mach kernel will report when running Rosetta apps. cpu_speed = 2_400_000_000; } unsafe extern "C" { fn mach_host_self() -> std::ffi::c_uint; static mut mach_task_self_: std::ffi::c_uint; } let mut num_cpus: libc::natural_t = 0; let mut info: *mut libc::processor_cpu_load_info_data_t = std::ptr::null_mut(); let mut msg_type: libc::mach_msg_type_number_t = 0; if libc::host_processor_info( mach_host_self(), libc::PROCESSOR_CPU_LOAD_INFO, &mut num_cpus, &mut info as *mut _ as *mut libc::processor_info_array_t, &mut msg_type, ) != 0 { return None; } let mut cpus = vec![CpuInfo::new(); num_cpus as usize]; let info = std::slice::from_raw_parts(info, num_cpus as usize); let model = std::ffi::CStr::from_ptr(model.as_ptr() as _) .to_string_lossy() .into_owned(); for (i, cpu) in cpus.iter_mut().enumerate() { cpu.times.user = info[i].cpu_ticks[libc::CPU_STATE_USER as usize] as u64 * multiplier; cpu.times.nice = info[i].cpu_ticks[libc::CPU_STATE_NICE as usize] as u64 * multiplier; cpu.times.sys = info[i].cpu_ticks[libc::CPU_STATE_SYSTEM as usize] as u64 * multiplier; cpu.times.idle = info[i].cpu_ticks[libc::CPU_STATE_IDLE as usize] as u64 * multiplier; cpu.times.irq = 0; cpu.model.clone_from(&model); cpu.speed = cpu_speed / 1000000; } libc::vm_deallocate( mach_task_self_, info.as_ptr() as libc::vm_address_t, msg_type as _, ); Some(cpus) } } #[cfg(target_os = "windows")] pub fn cpu_info() -> Option<Vec<CpuInfo>> { use std::os::windows::ffi::OsStrExt; use std::os::windows::ffi::OsStringExt; use windows_sys::Wdk::System::SystemInformation::NtQuerySystemInformation; use windows_sys::Wdk::System::SystemInformation::SystemProcessorPerformanceInformation; use windows_sys::Win32::System::WindowsProgramming::SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION; fn encode_wide(s: &str) -> Vec<u16> { std::ffi::OsString::from(s) .encode_wide() .chain(Some(0)) .collect() } // Safety: Assumes correct behavior of platform-specific syscalls and data structures. unsafe { let mut system_info: winapi::um::sysinfoapi::SYSTEM_INFO = std::mem::zeroed(); winapi::um::sysinfoapi::GetSystemInfo(&mut system_info); let cpu_count = system_info.dwNumberOfProcessors as usize; let mut cpus = vec![CpuInfo::new(); cpu_count]; let mut sppi: Vec<SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION> = vec![std::mem::zeroed(); cpu_count]; let sppi_size = std::mem::size_of_val(&sppi[0]) * cpu_count; let mut result_size = 0; let status = NtQuerySystemInformation( SystemProcessorPerformanceInformation, sppi.as_mut_ptr() as *mut _, sppi_size as u32, &mut result_size, ); if status != 0 { return None; } assert_eq!(result_size, sppi_size as u32); for i in 0..cpu_count { let key_name = format!("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\{}", i); let key_name = encode_wide(&key_name); let mut processor_key: windows_sys::Win32::System::Registry::HKEY = std::mem::zeroed(); let err = windows_sys::Win32::System::Registry::RegOpenKeyExW( windows_sys::Win32::System::Registry::HKEY_LOCAL_MACHINE, key_name.as_ptr(), 0, windows_sys::Win32::System::Registry::KEY_QUERY_VALUE, &mut processor_key, ); if err != 0 { return None; } let mut cpu_speed = 0; let mut cpu_speed_size = std::mem::size_of_val(&cpu_speed) as u32; let err = windows_sys::Win32::System::Registry::RegQueryValueExW( processor_key, encode_wide("~MHz").as_ptr() as *mut _, std::ptr::null_mut(), std::ptr::null_mut(), &mut cpu_speed as *mut _ as *mut _, &mut cpu_speed_size, ); if err != 0 { return None; } let cpu_brand: [u16; 512] = [0; 512]; let mut cpu_brand_size = std::mem::size_of_val(&cpu_brand) as u32; let err = windows_sys::Win32::System::Registry::RegQueryValueExW( processor_key, encode_wide("ProcessorNameString").as_ptr() as *mut _, std::ptr::null_mut(), std::ptr::null_mut(), cpu_brand.as_ptr() as *mut _, &mut cpu_brand_size, ); windows_sys::Win32::System::Registry::RegCloseKey(processor_key); if err != 0 { return None; } let cpu_brand = std::ffi::OsString::from_wide(&cpu_brand[..cpu_brand_size as usize]) .into_string() .unwrap(); cpus[i].model = cpu_brand; cpus[i].speed = cpu_speed as u64; cpus[i].times.user = sppi[i].UserTime as u64 / 10000; cpus[i].times.sys = (sppi[i].KernelTime - sppi[i].IdleTime) as u64 / 10000; cpus[i].times.idle = sppi[i].IdleTime as u64 / 10000; /* InterruptTime is Reserved1[1] */ cpus[i].times.irq = sppi[i].Reserved1[1] as u64 / 10000; cpus[i].times.nice = 0; } Some(cpus) } } #[cfg(any(target_os = "android", target_os = "linux"))] pub fn cpu_info() -> Option<Vec<CpuInfo>> { use std::io::BufRead; let mut cpus = vec![CpuInfo::new(); 8192]; /* Kernel maximum */ let fp = std::fs::File::open("/proc/stat").ok()?; let reader = std::io::BufReader::new(fp); let mut count = 0; // Skip the first line which tracks total CPU time across all cores for (i, line) in reader.lines().skip(1).enumerate() { let line = line.ok()?; if !line.starts_with("cpu") { break; } count = i + 1; let mut fields = line.split_whitespace(); fields.next()?; let user = fields.next()?.parse::<u64>().ok()?; let nice = fields.next()?.parse::<u64>().ok()?; let sys = fields.next()?.parse::<u64>().ok()?; let idle = fields.next()?.parse::<u64>().ok()?; let _iowait = fields.next()?.parse::<u64>().ok()?; let irq = fields.next()?.parse::<u64>().ok()?; // sysconf(_SC_CLK_TCK) is fixed at 100 Hz, therefore the // multiplier is always 1000/100 = 10 cpus[i].times.user = user * 10; cpus[i].times.nice = nice * 10; cpus[i].times.sys = sys * 10; cpus[i].times.idle = idle * 10; cpus[i].times.irq = irq * 10; } let fp = std::fs::File::open("/proc/cpuinfo").ok()?; let reader = std::io::BufReader::new(fp); let mut j = 0; for line in reader.lines() { let line = line.ok()?; if !line.starts_with("model name") { continue; } let mut fields = line.splitn(2, ':'); fields.next()?; let model = fields.next()?.trim(); cpus[j].model = model.to_string(); if let Ok(fp) = std::fs::File::open(format!( "/sys/devices/system/cpu/cpu{}/cpufreq/scaling_cur_freq", j )) { let mut reader = std::io::BufReader::new(fp); let mut speed = String::new(); reader.read_line(&mut speed).ok()?; cpus[j].speed = speed.trim().parse::<u64>().ok()? / 1000; } j += 1; } while j < count { cpus[j].model = "unknown".to_string(); j += 1; } cpus.truncate(count); Some(cpus) } #[cfg(target_os = "openbsd")] pub fn cpu_info() -> Option<Vec<CpuInfo>> { // Stub implementation for OpenBSD that returns an array of the correct size // but with dummy values. // Rust's OpenBSD libc bindings don't contain all the symbols needed for a // full implementation, and including them is not planned. let mut mib = [libc::CTL_HW, libc::HW_NCPUONLINE]; // SAFETY: Assumes correct behavior of platform-specific // sysctls and data structures. Relies on specific sysctl // names and parameter existence. unsafe { let mut ncpu: libc::c_uint = 0; let mut size = std::mem::size_of_val(&ncpu) as libc::size_t; // Get number of CPUs online let res = libc::sysctl( mib.as_mut_ptr(), mib.len() as _, &mut ncpu as *mut _ as *mut _, &mut size, std::ptr::null_mut(), 0, ); // If res == 0, the sysctl call was succesful and // ncpuonline contains the number of online CPUs. if res != 0 { return None; } else { let mut cpus = vec![CpuInfo::new(); ncpu as usize]; for (_, cpu) in cpus.iter_mut().enumerate() { cpu.model = "Undisclosed CPU".to_string(); // Return 1 as a dummy value so the tests won't // fail. cpu.speed = 1; cpu.times.user = 1; cpu.times.nice = 1; cpu.times.sys = 1; cpu.times.idle = 1; cpu.times.irq = 1; } return Some(cpus); } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_cpu_info() { let info = cpu_info(); assert!(info.is_some()); let info = info.unwrap(); assert!(!info.is_empty()); for cpu in info { assert!(!cpu.model.is_empty()); assert!(cpu.times.user > 0); assert!(cpu.times.sys > 0); assert!(cpu.times.idle > 0); } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/crypto/primes.rs
ext/node/ops/crypto/primes.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ops::Deref; use num_bigint::BigInt; use num_bigint_dig::RandPrime; use num_integer::Integer; use num_traits::One; use num_traits::Zero; use rand::Rng; #[derive(Clone)] pub struct Prime(pub num_bigint_dig::BigUint); impl Prime { pub fn generate(n: usize) -> Self { let mut rng = rand::thread_rng(); Self(rng.gen_prime(n)) } } impl From<&[u8]> for Prime { fn from(value: &[u8]) -> Self { Self(num_bigint_dig::BigUint::from_bytes_be(value)) } } impl Deref for Prime { type Target = num_bigint_dig::BigUint; fn deref(&self) -> &Self::Target { &self.0 } } struct Witness { pow: BigInt, wit: BigInt, } /// Modified version of bigpowmod() from http://nickle.org/examples/miller-rabin.5c /// Computes core of Miller-Rabin test as suggested by /// Cormen/Leiserson/Rivest. fn witnessexp(b: &BigInt, e: &BigInt, m: &BigInt) -> Witness { if *e == BigInt::zero() { return Witness { pow: BigInt::zero(), wit: BigInt::one(), }; } if *e == BigInt::one() { return Witness { pow: b % m, wit: BigInt::zero(), }; } let ehalf = e / BigInt::from(2); let mut tmp = witnessexp(b, &ehalf, m); if tmp.wit != BigInt::zero() { return tmp; } let t: BigInt = BigInt::pow(&tmp.pow, 2) % m; if t == BigInt::one() && tmp.pow != BigInt::one() && &tmp.pow + BigInt::one() != *m { tmp.wit = tmp.pow; tmp.pow = t; return tmp; } if e % BigInt::from(2) == BigInt::zero() { tmp.pow = t; } else { tmp.pow = (t * b) % m; } tmp } pub(crate) fn is_probably_prime(n: &BigInt, count: usize) -> bool { if *n == BigInt::from(1) { return false; } if *n == BigInt::from(2) { return true; } if n.is_even() { return false; } for p in SMALL_PRIMES.into_iter() { let p = BigInt::from(p); if *n == p { return true; } if n % p == BigInt::zero() { return false; } } let mut rng = rand::thread_rng(); for _ in 0..count { let a = rng.gen_range(BigInt::one()..n.clone()); let we = witnessexp(&a, &(n - BigInt::one()), n); if we.wit != BigInt::zero() || we.pow != BigInt::one() { return false; } } true } static SMALL_PRIMES: [u32; 2047] = [ 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087, 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791, 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857, 5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939, 5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133, 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473, 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833, 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917, 6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997, 7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207, 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411, 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499, 7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561, 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723, 7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919, 7927, 7933, 7937, 7949, 7951, 7963, 7993, 8009, 8011, 8017, 8039, 8053, 8059, 8069, 8081, 8087, 8089, 8093, 8101, 8111, 8117, 8123, 8147, 8161, 8167, 8171, 8179, 8191, 8209, 8219, 8221, 8231, 8233, 8237, 8243, 8263, 8269, 8273, 8287, 8291, 8293, 8297, 8311, 8317, 8329, 8353, 8363, 8369, 8377, 8387, 8389, 8419, 8423, 8429, 8431, 8443, 8447, 8461, 8467, 8501, 8513, 8521, 8527, 8537, 8539, 8543, 8563, 8573, 8581, 8597, 8599, 8609, 8623, 8627, 8629, 8641, 8647, 8663, 8669, 8677, 8681, 8689, 8693, 8699, 8707, 8713, 8719, 8731, 8737, 8741, 8747, 8753, 8761, 8779, 8783, 8803, 8807, 8819, 8821, 8831, 8837, 8839, 8849, 8861, 8863, 8867, 8887, 8893, 8923, 8929, 8933, 8941, 8951, 8963, 8969, 8971, 8999, 9001, 9007, 9011, 9013, 9029, 9041, 9043, 9049, 9059, 9067, 9091, 9103, 9109, 9127, 9133, 9137, 9151, 9157, 9161, 9173, 9181, 9187, 9199, 9203, 9209, 9221, 9227, 9239, 9241, 9257, 9277, 9281, 9283, 9293, 9311, 9319, 9323, 9337, 9341, 9343, 9349, 9371, 9377, 9391, 9397, 9403, 9413, 9419, 9421, 9431, 9433, 9437, 9439, 9461, 9463, 9467, 9473, 9479, 9491, 9497, 9511, 9521, 9533, 9539, 9547, 9551, 9587, 9601, 9613, 9619, 9623, 9629, 9631, 9643, 9649, 9661, 9677, 9679, 9689, 9697, 9719, 9721, 9733, 9739, 9743, 9749, 9767, 9769, 9781, 9787, 9791, 9803, 9811, 9817, 9829, 9833, 9839, 9851, 9857, 9859, 9871, 9883, 9887, 9901, 9907, 9923, 9929, 9931, 9941, 9949, 9967, 9973, 10007, 10009, 10037, 10039, 10061, 10067, 10069, 10079, 10091, 10093, 10099, 10103, 10111, 10133, 10139, 10141, 10151, 10159, 10163, 10169, 10177, 10181, 10193, 10211, 10223, 10243, 10247, 10253, 10259, 10267, 10271, 10273, 10289, 10301, 10303, 10313, 10321, 10331, 10333, 10337, 10343, 10357, 10369, 10391, 10399, 10427, 10429, 10433, 10453, 10457, 10459, 10463, 10477, 10487, 10499, 10501, 10513, 10529, 10531, 10559, 10567, 10589, 10597, 10601, 10607, 10613, 10627, 10631, 10639, 10651, 10657, 10663, 10667, 10687, 10691, 10709, 10711, 10723, 10729, 10733, 10739, 10753, 10771, 10781, 10789, 10799, 10831, 10837, 10847, 10853, 10859, 10861, 10867, 10883, 10889, 10891, 10903, 10909, 10937, 10939, 10949, 10957, 10973, 10979, 10987, 10993, 11003, 11027, 11047, 11057, 11059, 11069, 11071, 11083, 11087, 11093, 11113, 11117, 11119, 11131, 11149, 11159, 11161, 11171, 11173, 11177, 11197, 11213, 11239, 11243, 11251, 11257, 11261, 11273, 11279, 11287, 11299, 11311, 11317, 11321, 11329, 11351, 11353, 11369, 11383, 11393, 11399, 11411, 11423, 11437, 11443, 11447, 11467, 11471, 11483, 11489, 11491, 11497, 11503, 11519, 11527, 11549, 11551, 11579, 11587, 11593, 11597, 11617, 11621, 11633, 11657, 11677, 11681, 11689, 11699, 11701, 11717, 11719, 11731, 11743, 11777, 11779, 11783, 11789, 11801, 11807, 11813, 11821, 11827, 11831, 11833, 11839, 11863, 11867, 11887, 11897, 11903, 11909, 11923, 11927, 11933, 11939, 11941, 11953, 11959, 11969, 11971, 11981, 11987, 12007, 12011, 12037, 12041, 12043, 12049, 12071, 12073, 12097, 12101, 12107, 12109, 12113, 12119, 12143, 12149, 12157, 12161, 12163, 12197, 12203, 12211, 12227, 12239, 12241, 12251, 12253, 12263, 12269, 12277, 12281, 12289, 12301, 12323, 12329, 12343, 12347, 12373, 12377, 12379, 12391, 12401, 12409, 12413, 12421, 12433, 12437, 12451, 12457, 12473, 12479, 12487, 12491, 12497, 12503, 12511, 12517, 12527, 12539, 12541, 12547, 12553, 12569, 12577, 12583, 12589, 12601, 12611, 12613, 12619, 12637, 12641, 12647, 12653, 12659, 12671, 12689, 12697, 12703, 12713, 12721, 12739, 12743, 12757, 12763, 12781, 12791, 12799, 12809, 12821, 12823, 12829, 12841, 12853, 12889, 12893, 12899, 12907, 12911, 12917, 12919, 12923, 12941, 12953, 12959, 12967, 12973, 12979, 12983, 13001, 13003, 13007, 13009, 13033, 13037, 13043, 13049, 13063, 13093, 13099, 13103, 13109, 13121, 13127, 13147, 13151, 13159, 13163, 13171, 13177, 13183, 13187, 13217, 13219, 13229, 13241, 13249, 13259, 13267, 13291, 13297, 13309, 13313, 13327, 13331, 13337, 13339, 13367, 13381, 13397, 13399, 13411, 13417, 13421, 13441, 13451, 13457, 13463, 13469, 13477, 13487, 13499, 13513, 13523, 13537, 13553, 13567, 13577, 13591, 13597, 13613, 13619, 13627, 13633, 13649, 13669, 13679, 13681, 13687, 13691, 13693, 13697, 13709, 13711, 13721, 13723, 13729, 13751, 13757, 13759, 13763, 13781, 13789, 13799, 13807, 13829, 13831, 13841, 13859, 13873, 13877, 13879, 13883, 13901, 13903, 13907, 13913, 13921, 13931, 13933, 13963, 13967, 13997, 13999, 14009, 14011, 14029, 14033, 14051, 14057, 14071, 14081, 14083, 14087, 14107, 14143, 14149, 14153, 14159, 14173, 14177, 14197, 14207, 14221, 14243, 14249, 14251, 14281, 14293, 14303, 14321, 14323, 14327, 14341, 14347, 14369, 14387, 14389, 14401, 14407, 14411, 14419, 14423, 14431, 14437, 14447, 14449, 14461, 14479, 14489, 14503, 14519, 14533, 14537, 14543, 14549, 14551, 14557, 14561, 14563, 14591, 14593, 14621, 14627, 14629, 14633, 14639, 14653, 14657, 14669, 14683, 14699, 14713, 14717, 14723, 14731, 14737, 14741, 14747, 14753, 14759, 14767, 14771, 14779, 14783, 14797, 14813, 14821, 14827, 14831, 14843, 14851, 14867, 14869, 14879, 14887, 14891, 14897, 14923, 14929, 14939, 14947, 14951, 14957, 14969, 14983, 15013, 15017, 15031, 15053, 15061, 15073, 15077, 15083, 15091, 15101, 15107, 15121, 15131, 15137, 15139, 15149, 15161, 15173, 15187, 15193, 15199, 15217, 15227, 15233, 15241, 15259, 15263, 15269, 15271, 15277, 15287, 15289, 15299, 15307, 15313, 15319, 15329, 15331, 15349, 15359, 15361, 15373, 15377, 15383, 15391, 15401, 15413, 15427, 15439, 15443, 15451, 15461, 15467, 15473, 15493, 15497, 15511, 15527, 15541, 15551, 15559, 15569, 15581, 15583, 15601, 15607, 15619, 15629, 15641, 15643, 15647, 15649, 15661, 15667, 15671, 15679, 15683, 15727, 15731, 15733, 15737, 15739, 15749, 15761, 15767, 15773, 15787, 15791, 15797, 15803, 15809, 15817, 15823, 15859, 15877, 15881, 15887, 15889, 15901, 15907, 15913, 15919, 15923, 15937, 15959, 15971, 15973, 15991, 16001, 16007, 16033, 16057, 16061, 16063, 16067, 16069, 16073, 16087, 16091, 16097, 16103, 16111, 16127, 16139, 16141, 16183, 16187, 16189, 16193, 16217, 16223, 16229, 16231, 16249, 16253, 16267, 16273, 16301, 16319, 16333, 16339, 16349, 16361, 16363, 16369, 16381, 16411, 16417, 16421, 16427, 16433, 16447, 16451, 16453, 16477, 16481, 16487, 16493, 16519, 16529, 16547, 16553, 16561, 16567, 16573, 16603, 16607, 16619, 16631, 16633, 16649, 16651, 16657, 16661, 16673, 16691, 16693, 16699, 16703, 16729, 16741, 16747, 16759, 16763, 16787, 16811, 16823, 16829, 16831, 16843, 16871, 16879, 16883, 16889, 16901, 16903, 16921, 16927, 16931, 16937, 16943, 16963, 16979, 16981, 16987, 16993, 17011, 17021, 17027, 17029, 17033, 17041, 17047, 17053, 17077, 17093, 17099, 17107, 17117, 17123, 17137, 17159, 17167, 17183, 17189, 17191, 17203, 17207, 17209, 17231, 17239, 17257, 17291, 17293, 17299, 17317, 17321, 17327, 17333, 17341, 17351, 17359, 17377, 17383, 17387, 17389, 17393, 17401, 17417, 17419, 17431, 17443, 17449, 17467, 17471, 17477, 17483, 17489, 17491, 17497, 17509, 17519, 17539, 17551, 17569, 17573, 17579, 17581, 17597, 17599, 17609, 17623, 17627, 17657, 17659, 17669, 17681, 17683, 17707, 17713, 17729, 17737, 17747, 17749, 17761, 17783, 17789, 17791, 17807, 17827, 17837, 17839, 17851, 17863, ]; #[cfg(test)] mod tests { use num_bigint::BigInt; use super::*; #[test] fn test_prime() { for &p in SMALL_PRIMES.iter() { assert!(is_probably_prime(&BigInt::from(p), 16)); } assert!(is_probably_prime(&BigInt::from(0x7FFF_FFFF), 16)); } #[test] fn test_composite() { assert!(!is_probably_prime(&BigInt::from(0x7FFF_FFFE), 16)); assert!(!is_probably_prime( &BigInt::from(0xFFFF_FFFF_FFFF_FFFF_u64), 16 )); assert!(!is_probably_prime(&BigInt::parse_bytes(b"12345678901234567890123456789012345678901234567890123456789012345678901234567890", 10).unwrap(), 16)); } #[test] fn oeis_a014233() { // https://oeis.org/A014233 // // Smallest odd number for which Miller-Rabin primality test // on bases <= n-th prime does not reveal compositeness. let a014233: [BigInt; 10] = [ 2047u64.into(), 1373653u64.into(), 25326001u64.into(), 3215031751u64.into(), 2152302898747u64.into(), 3474749660383u64.into(), 341550071728321u64.into(), 3825123056546413051u64.into(), BigInt::parse_bytes(b"318665857834031151167461", 10).unwrap(), BigInt::parse_bytes(b"3317044064679887385961981", 10).unwrap(), ]; for p in a014233 { assert!(!is_probably_prime(&p, 16), "{} should be composite", p); } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/crypto/cipher.rs
ext/node/ops/crypto/cipher.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::rc::Rc; use aes::cipher::BlockDecryptMut; use aes::cipher::BlockEncryptMut; use aes::cipher::KeyIvInit; use aes::cipher::KeySizeUser; use aes::cipher::StreamCipher; use aes::cipher::block_padding::Pkcs7; use deno_core::Resource; use deno_error::JsErrorClass; use digest::KeyInit; use digest::generic_array::GenericArray; type Tag = Option<Vec<u8>>; type Aes128Gcm = aead_gcm_stream::AesGcm<aes::Aes128>; type Aes256Gcm = aead_gcm_stream::AesGcm<aes::Aes256>; enum Cipher { Aes128Cbc(Box<cbc::Encryptor<aes::Aes128>>), Aes128Ecb(Box<ecb::Encryptor<aes::Aes128>>), Aes192Ecb(Box<ecb::Encryptor<aes::Aes192>>), Aes256Ecb(Box<ecb::Encryptor<aes::Aes256>>), Aes128Gcm(Box<Aes128Gcm>, Option<usize>), Aes256Gcm(Box<Aes256Gcm>, Option<usize>), Aes256Cbc(Box<cbc::Encryptor<aes::Aes256>>), Aes128Ctr(Box<ctr::Ctr128BE<aes::Aes128>>), Aes192Ctr(Box<ctr::Ctr128BE<aes::Aes192>>), Aes256Ctr(Box<ctr::Ctr128BE<aes::Aes256>>), // TODO(kt3k): add more algorithms Aes192Cbc, etc. } enum Decipher { Aes128Cbc(Box<cbc::Decryptor<aes::Aes128>>), Aes128Ecb(Box<ecb::Decryptor<aes::Aes128>>), Aes192Ecb(Box<ecb::Decryptor<aes::Aes192>>), Aes256Ecb(Box<ecb::Decryptor<aes::Aes256>>), Aes128Gcm(Box<Aes128Gcm>, Option<usize>), Aes256Gcm(Box<Aes256Gcm>, Option<usize>), Aes256Cbc(Box<cbc::Decryptor<aes::Aes256>>), Aes128Ctr(Box<ctr::Ctr128BE<aes::Aes128>>), Aes192Ctr(Box<ctr::Ctr128BE<aes::Aes192>>), Aes256Ctr(Box<ctr::Ctr128BE<aes::Aes256>>), // TODO(kt3k): add more algorithms Aes192Cbc, Aes128GCM, etc. } pub struct CipherContext { cipher: Rc<RefCell<Cipher>>, } pub struct DecipherContext { decipher: Rc<RefCell<Decipher>>, } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum CipherContextError { #[class(type)] #[error("Cipher context is already in use")] ContextInUse, #[class(inherit)] #[error("{0}")] Resource(#[from] deno_core::error::ResourceError), #[class(inherit)] #[error(transparent)] Cipher(#[from] CipherError), } impl CipherContext { pub fn new( algorithm: &str, key: &[u8], iv: &[u8], auth_tag_length: Option<usize>, ) -> Result<Self, CipherContextError> { Ok(Self { cipher: Rc::new(RefCell::new(Cipher::new( algorithm, key, iv, auth_tag_length, )?)), }) } pub fn set_aad(&self, aad: &[u8]) { self.cipher.borrow_mut().set_aad(aad); } pub fn encrypt(&self, input: &[u8], output: &mut [u8]) { self.cipher.borrow_mut().encrypt(input, output); } pub fn take_tag(self) -> Tag { Rc::try_unwrap(self.cipher).ok()?.into_inner().take_tag() } pub fn r#final( self, auto_pad: bool, input: &[u8], output: &mut [u8], ) -> Result<Tag, CipherContextError> { Rc::try_unwrap(self.cipher) .map_err(|_| CipherContextError::ContextInUse)? .into_inner() .r#final(auto_pad, input, output) .map_err(Into::into) } } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum DecipherContextError { #[class(type)] #[error("Decipher context is already in use")] ContextInUse, #[class(inherit)] #[error("{0}")] Resource(#[from] deno_core::error::ResourceError), #[class(inherit)] #[error(transparent)] Decipher(#[from] DecipherError), } impl DecipherContext { pub fn new( algorithm: &str, key: &[u8], iv: &[u8], auth_tag_length: Option<usize>, ) -> Result<Self, DecipherContextError> { Ok(Self { decipher: Rc::new(RefCell::new(Decipher::new( algorithm, key, iv, auth_tag_length, )?)), }) } pub fn validate_auth_tag( &self, length: usize, ) -> Result<(), DecipherContextError> { self.decipher.borrow().validate_auth_tag(length)?; Ok(()) } pub fn set_aad(&self, aad: &[u8]) { self.decipher.borrow_mut().set_aad(aad); } pub fn decrypt(&self, input: &[u8], output: &mut [u8]) { self.decipher.borrow_mut().decrypt(input, output); } pub fn r#final( self, auto_pad: bool, input: &[u8], output: &mut [u8], auth_tag: &[u8], ) -> Result<(), DecipherContextError> { Rc::try_unwrap(self.decipher) .map_err(|_| DecipherContextError::ContextInUse)? .into_inner() .r#final(auto_pad, input, output, auth_tag) .map_err(Into::into) } } impl Resource for CipherContext { fn name(&self) -> Cow<'_, str> { "cryptoCipher".into() } } impl Resource for DecipherContext { fn name(&self) -> Cow<'_, str> { "cryptoDecipher".into() } } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum CipherError { #[class(type)] #[error("IV length must be 12 bytes")] InvalidIvLength, #[class(range)] #[error("Invalid key length")] InvalidKeyLength, #[class(type)] #[error("Invalid initialization vector")] InvalidInitializationVector, #[class(type)] #[error("bad decrypt")] CannotPadInputData, #[class(type)] #[error("Unknown cipher {0}")] UnknownCipher(String), #[class(type)] #[error("Invalid authentication tag length: {0}")] InvalidAuthTag(usize), } impl Cipher { fn new( algorithm_name: &str, key: &[u8], iv: &[u8], auth_tag_length: Option<usize>, ) -> Result<Self, CipherError> { use Cipher::*; Ok(match algorithm_name { "aes128" | "aes-128-cbc" => { Aes128Cbc(Box::new(cbc::Encryptor::new(key.into(), iv.into()))) } "aes-128-ecb" => Aes128Ecb(Box::new(ecb::Encryptor::new(key.into()))), "aes-192-ecb" => Aes192Ecb(Box::new(ecb::Encryptor::new(key.into()))), "aes-256-ecb" => Aes256Ecb(Box::new(ecb::Encryptor::new(key.into()))), "aes-128-gcm" => { if key.len() != aes::Aes128::key_size() { return Err(CipherError::InvalidKeyLength); } if let Some(tag_len) = auth_tag_length && !is_valid_gcm_tag_length(tag_len) { return Err(CipherError::InvalidAuthTag(tag_len)); } let cipher = aead_gcm_stream::AesGcm::<aes::Aes128>::new(key.into(), iv); Aes128Gcm(Box::new(cipher), auth_tag_length) } "aes-256-gcm" => { if key.len() != aes::Aes256::key_size() { return Err(CipherError::InvalidKeyLength); } if let Some(tag_len) = auth_tag_length && !is_valid_gcm_tag_length(tag_len) { return Err(CipherError::InvalidAuthTag(tag_len)); } let cipher = aead_gcm_stream::AesGcm::<aes::Aes256>::new(key.into(), iv); Aes256Gcm(Box::new(cipher), auth_tag_length) } "aes256" | "aes-256-cbc" => { if key.len() != 32 { return Err(CipherError::InvalidKeyLength); } if iv.len() != 16 { return Err(CipherError::InvalidInitializationVector); } Aes256Cbc(Box::new(cbc::Encryptor::new(key.into(), iv.into()))) } "aes-256-ctr" => { if key.len() != 32 { return Err(CipherError::InvalidKeyLength); } if iv.len() != 16 { return Err(CipherError::InvalidInitializationVector); } Aes256Ctr(Box::new(ctr::Ctr128BE::new(key.into(), iv.into()))) } "aes-192-ctr" => { if key.len() != 24 { return Err(CipherError::InvalidKeyLength); } if iv.len() != 16 { return Err(CipherError::InvalidInitializationVector); } Aes192Ctr(Box::new(ctr::Ctr128BE::new(key.into(), iv.into()))) } "aes-128-ctr" => { if key.len() != 16 { return Err(CipherError::InvalidKeyLength); } if iv.len() != 16 { return Err(CipherError::InvalidInitializationVector); } Aes128Ctr(Box::new(ctr::Ctr128BE::new(key.into(), iv.into()))) } _ => return Err(CipherError::UnknownCipher(algorithm_name.to_string())), }) } fn set_aad(&mut self, aad: &[u8]) { use Cipher::*; match self { Aes128Gcm(cipher, _) => { cipher.set_aad(aad); } Aes256Gcm(cipher, _) => { cipher.set_aad(aad); } _ => {} } } /// encrypt encrypts the data in the middle of the input. fn encrypt(&mut self, input: &[u8], output: &mut [u8]) { use Cipher::*; match self { Aes128Cbc(encryptor) => { assert!(input.len().is_multiple_of(16)); for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { encryptor.encrypt_block_b2b_mut(input.into(), output.into()); } } Aes128Ecb(encryptor) => { assert!(input.len().is_multiple_of(16)); for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { encryptor.encrypt_block_b2b_mut(input.into(), output.into()); } } Aes192Ecb(encryptor) => { assert!(input.len().is_multiple_of(16)); for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { encryptor.encrypt_block_b2b_mut(input.into(), output.into()); } } Aes256Ecb(encryptor) => { assert!(input.len().is_multiple_of(16)); for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { encryptor.encrypt_block_b2b_mut(input.into(), output.into()); } } Aes128Gcm(cipher, _) => { output[..input.len()].copy_from_slice(input); cipher.encrypt(output); } Aes256Gcm(cipher, _) => { output[..input.len()].copy_from_slice(input); cipher.encrypt(output); } Aes256Cbc(encryptor) => { assert!(input.len().is_multiple_of(16)); for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { encryptor.encrypt_block_b2b_mut(input.into(), output.into()); } } Aes256Ctr(encryptor) => { encryptor.apply_keystream_b2b(input, output).unwrap(); } Aes192Ctr(encryptor) => { encryptor.apply_keystream_b2b(input, output).unwrap(); } Aes128Ctr(encryptor) => { encryptor.apply_keystream_b2b(input, output).unwrap(); } } } /// r#final encrypts the last block of the input data. fn r#final( self, auto_pad: bool, input: &[u8], output: &mut [u8], ) -> Result<Tag, CipherError> { assert!(input.len() < 16); use Cipher::*; match (self, auto_pad) { (Aes128Cbc(encryptor), true) => { let _ = (*encryptor) .encrypt_padded_b2b_mut::<Pkcs7>(input, output) .map_err(|_| CipherError::CannotPadInputData)?; Ok(None) } (Aes128Cbc(mut encryptor), false) => { encryptor.encrypt_block_b2b_mut( GenericArray::from_slice(input), GenericArray::from_mut_slice(output), ); Ok(None) } (Aes128Ecb(encryptor), true) => { let _ = (*encryptor) .encrypt_padded_b2b_mut::<Pkcs7>(input, output) .map_err(|_| CipherError::CannotPadInputData)?; Ok(None) } (Aes128Ecb(mut encryptor), false) => { encryptor.encrypt_block_b2b_mut( GenericArray::from_slice(input), GenericArray::from_mut_slice(output), ); Ok(None) } (Aes192Ecb(encryptor), true) => { let _ = (*encryptor) .encrypt_padded_b2b_mut::<Pkcs7>(input, output) .map_err(|_| CipherError::CannotPadInputData)?; Ok(None) } (Aes192Ecb(mut encryptor), false) => { encryptor.encrypt_block_b2b_mut( GenericArray::from_slice(input), GenericArray::from_mut_slice(output), ); Ok(None) } (Aes256Ecb(encryptor), true) => { let _ = (*encryptor) .encrypt_padded_b2b_mut::<Pkcs7>(input, output) .map_err(|_| CipherError::CannotPadInputData)?; Ok(None) } (Aes256Ecb(mut encryptor), false) => { encryptor.encrypt_block_b2b_mut( GenericArray::from_slice(input), GenericArray::from_mut_slice(output), ); Ok(None) } (Aes128Gcm(cipher, auth_tag_length), _) => { let mut tag = cipher.finish().to_vec(); if let Some(tag_len) = auth_tag_length { tag.truncate(tag_len); } Ok(Some(tag)) } (Aes256Gcm(cipher, auth_tag_length), _) => { let mut tag = cipher.finish().to_vec(); if let Some(tag_len) = auth_tag_length { tag.truncate(tag_len); } Ok(Some(tag)) } (Aes256Cbc(encryptor), true) => { let _ = (*encryptor) .encrypt_padded_b2b_mut::<Pkcs7>(input, output) .map_err(|_| CipherError::CannotPadInputData)?; Ok(None) } (Aes256Cbc(mut encryptor), false) => { encryptor.encrypt_block_b2b_mut( GenericArray::from_slice(input), GenericArray::from_mut_slice(output), ); Ok(None) } (Aes256Ctr(_) | Aes128Ctr(_) | Aes192Ctr(_), _) => Ok(None), } } fn take_tag(self) -> Tag { use Cipher::*; match self { Aes128Gcm(cipher, auth_tag_length) => { let mut tag = cipher.finish().to_vec(); if let Some(tag_len) = auth_tag_length { tag.truncate(tag_len); } Some(tag) } Aes256Gcm(cipher, auth_tag_length) => { let mut tag = cipher.finish().to_vec(); if let Some(tag_len) = auth_tag_length { tag.truncate(tag_len); } Some(tag) } _ => None, } } } #[derive(Debug, thiserror::Error, deno_error::JsError)] #[property("library" = "Provider routines")] #[property("reason" = self.reason())] #[property("code" = self.code())] pub enum DecipherError { #[class(type)] #[error("IV length must be 12 bytes")] InvalidIvLength, #[class(range)] #[error("Invalid key length")] InvalidKeyLength, #[class(type)] #[error("Invalid authentication tag length: {0}")] InvalidAuthTag(usize), #[class(range)] #[error("error:1C80006B:Provider routines::wrong final block length")] InvalidFinalBlockLength, #[class(type)] #[error("Invalid initialization vector")] InvalidInitializationVector, #[class(type)] #[error("bad decrypt")] CannotUnpadInputData, #[class(type)] #[error("Failed to authenticate data")] DataAuthenticationFailed, #[class(type)] #[error("setAutoPadding(false) not supported for Aes128Gcm yet")] SetAutoPaddingFalseAes128GcmUnsupported, #[class(type)] #[error("setAutoPadding(false) not supported for Aes256Gcm yet")] SetAutoPaddingFalseAes256GcmUnsupported, #[class(type)] #[error("Unknown cipher {0}")] UnknownCipher(String), } impl DecipherError { fn code(&self) -> deno_error::PropertyValue { match self { Self::InvalidIvLength => { deno_error::PropertyValue::String("ERR_CRYPTO_INVALID_IV_LENGTH".into()) } Self::InvalidKeyLength => deno_error::PropertyValue::String( "ERR_CRYPTO_INVALID_KEY_LENGTH".into(), ), Self::InvalidAuthTag(_) => { deno_error::PropertyValue::String("ERR_CRYPTO_INVALID_AUTH_TAG".into()) } Self::InvalidFinalBlockLength => deno_error::PropertyValue::String( "ERR_OSSL_WRONG_FINAL_BLOCK_LENGTH".into(), ), _ => deno_error::PropertyValue::String("ERR_CRYPTO_DECIPHER".into()), } } fn reason(&self) -> deno_error::PropertyValue { match self { Self::InvalidFinalBlockLength => { deno_error::PropertyValue::String("wrong final block length".into()) } _ => deno_error::PropertyValue::String(self.get_message()), } } } macro_rules! assert_block_len { ($input:expr, $len:expr) => { if $input != $len { return Err(DecipherError::InvalidFinalBlockLength); } }; } fn is_valid_gcm_tag_length(tag_len: usize) -> bool { tag_len == 4 || tag_len == 8 || (12..=16).contains(&tag_len) } impl Decipher { fn new( algorithm_name: &str, key: &[u8], iv: &[u8], auth_tag_length: Option<usize>, ) -> Result<Self, DecipherError> { use Decipher::*; Ok(match algorithm_name { "aes-128-cbc" => { Aes128Cbc(Box::new(cbc::Decryptor::new(key.into(), iv.into()))) } "aes-128-ecb" => Aes128Ecb(Box::new(ecb::Decryptor::new(key.into()))), "aes-192-ecb" => Aes192Ecb(Box::new(ecb::Decryptor::new(key.into()))), "aes-256-ecb" => Aes256Ecb(Box::new(ecb::Decryptor::new(key.into()))), "aes-128-gcm" => { if key.len() != aes::Aes128::key_size() { return Err(DecipherError::InvalidKeyLength); } if let Some(tag_len) = auth_tag_length && !is_valid_gcm_tag_length(tag_len) { return Err(DecipherError::InvalidAuthTag(tag_len)); } let decipher = aead_gcm_stream::AesGcm::<aes::Aes128>::new(key.into(), iv); Aes128Gcm(Box::new(decipher), auth_tag_length) } "aes-256-gcm" => { if key.len() != aes::Aes256::key_size() { return Err(DecipherError::InvalidKeyLength); } if let Some(tag_len) = auth_tag_length && !is_valid_gcm_tag_length(tag_len) { return Err(DecipherError::InvalidAuthTag(tag_len)); } let decipher = aead_gcm_stream::AesGcm::<aes::Aes256>::new(key.into(), iv); Aes256Gcm(Box::new(decipher), auth_tag_length) } "aes256" | "aes-256-cbc" => { if key.len() != 32 { return Err(DecipherError::InvalidKeyLength); } if iv.len() != 16 { return Err(DecipherError::InvalidInitializationVector); } Aes256Cbc(Box::new(cbc::Decryptor::new(key.into(), iv.into()))) } "aes-256-ctr" => { if key.len() != 32 { return Err(DecipherError::InvalidKeyLength); } if iv.len() != 16 { return Err(DecipherError::InvalidInitializationVector); } Aes256Ctr(Box::new(ctr::Ctr128BE::new(key.into(), iv.into()))) } "aes-192-ctr" => { if key.len() != 24 { return Err(DecipherError::InvalidKeyLength); } if iv.len() != 16 { return Err(DecipherError::InvalidInitializationVector); } Aes192Ctr(Box::new(ctr::Ctr128BE::new(key.into(), iv.into()))) } "aes-128-ctr" => { if key.len() != 16 { return Err(DecipherError::InvalidKeyLength); } if iv.len() != 16 { return Err(DecipherError::InvalidInitializationVector); } Aes128Ctr(Box::new(ctr::Ctr128BE::new(key.into(), iv.into()))) } _ => { return Err(DecipherError::UnknownCipher(algorithm_name.to_string())); } }) } fn validate_auth_tag(&self, length: usize) -> Result<(), DecipherError> { match self { Decipher::Aes128Gcm(_, Some(tag_len)) | Decipher::Aes256Gcm(_, Some(tag_len)) => { if *tag_len != length { return Err(DecipherError::InvalidAuthTag(length)); } } _ => {} } Ok(()) } fn set_aad(&mut self, aad: &[u8]) { use Decipher::*; match self { Aes128Gcm(decipher, _) => { decipher.set_aad(aad); } Aes256Gcm(decipher, _) => { decipher.set_aad(aad); } _ => {} } } /// decrypt decrypts the data in the middle of the input. fn decrypt(&mut self, input: &[u8], output: &mut [u8]) { use Decipher::*; match self { Aes128Cbc(decryptor) => { assert!(input.len().is_multiple_of(16)); for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { decryptor.decrypt_block_b2b_mut(input.into(), output.into()); } } Aes128Ecb(decryptor) => { assert!(input.len().is_multiple_of(16)); for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { decryptor.decrypt_block_b2b_mut(input.into(), output.into()); } } Aes192Ecb(decryptor) => { assert!(input.len().is_multiple_of(16)); for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { decryptor.decrypt_block_b2b_mut(input.into(), output.into()); } } Aes256Ecb(decryptor) => { assert!(input.len().is_multiple_of(16)); for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { decryptor.decrypt_block_b2b_mut(input.into(), output.into()); } } Aes128Gcm(decipher, _) => { output[..input.len()].copy_from_slice(input); decipher.decrypt(output); } Aes256Gcm(decipher, _) => { output[..input.len()].copy_from_slice(input); decipher.decrypt(output); } Aes256Cbc(decryptor) => { assert!(input.len().is_multiple_of(16)); for (input, output) in input.chunks(16).zip(output.chunks_mut(16)) { decryptor.decrypt_block_b2b_mut(input.into(), output.into()); } } Aes256Ctr(decryptor) => { decryptor.apply_keystream_b2b(input, output).unwrap(); } Aes192Ctr(decryptor) => { decryptor.apply_keystream_b2b(input, output).unwrap(); } Aes128Ctr(decryptor) => { decryptor.apply_keystream_b2b(input, output).unwrap(); } } } /// r#final decrypts the last block of the input data. fn r#final( self, auto_pad: bool, input: &[u8], output: &mut [u8], auth_tag: &[u8], ) -> Result<(), DecipherError> { use Decipher::*; if input.is_empty() && !matches!( self, Aes128Ecb(..) | Aes192Ecb(..) | Aes256Ecb(..) | Aes128Gcm(..) | Aes256Gcm(..) ) { return Ok(()); } match (self, auto_pad) { (Aes128Cbc(decryptor), true) => { assert_block_len!(input.len(), 16); let _ = (*decryptor) .decrypt_padded_b2b_mut::<Pkcs7>(input, output) .map_err(|_| DecipherError::CannotUnpadInputData)?; Ok(()) } (Aes128Cbc(mut decryptor), false) => { decryptor.decrypt_block_b2b_mut( GenericArray::from_slice(input), GenericArray::from_mut_slice(output), ); Ok(()) } (Aes128Ecb(decryptor), true) => { assert_block_len!(input.len(), 16); let _ = (*decryptor) .decrypt_padded_b2b_mut::<Pkcs7>(input, output) .map_err(|_| DecipherError::CannotUnpadInputData)?; Ok(()) } (Aes128Ecb(mut decryptor), false) => { decryptor.decrypt_block_b2b_mut( GenericArray::from_slice(input), GenericArray::from_mut_slice(output), ); Ok(()) } (Aes192Ecb(decryptor), true) => { assert_block_len!(input.len(), 16); let _ = (*decryptor) .decrypt_padded_b2b_mut::<Pkcs7>(input, output) .map_err(|_| DecipherError::CannotUnpadInputData)?; Ok(()) } (Aes192Ecb(mut decryptor), false) => { decryptor.decrypt_block_b2b_mut( GenericArray::from_slice(input), GenericArray::from_mut_slice(output), ); Ok(()) } (Aes256Ecb(decryptor), true) => { assert_block_len!(input.len(), 16); let _ = (*decryptor) .decrypt_padded_b2b_mut::<Pkcs7>(input, output) .map_err(|_| DecipherError::CannotUnpadInputData)?; Ok(()) } (Aes256Ecb(mut decryptor), false) => { decryptor.decrypt_block_b2b_mut( GenericArray::from_slice(input), GenericArray::from_mut_slice(output), ); Ok(()) } (Aes128Gcm(decipher, auth_tag_length), true) => { let tag = decipher.finish(); let tag_slice = tag.as_slice(); let truncated_tag = if let Some(len) = auth_tag_length { &tag_slice[..len] } else { tag_slice }; if truncated_tag == auth_tag { Ok(()) } else { Err(DecipherError::DataAuthenticationFailed) } } (Aes128Gcm(..), false) => { Err(DecipherError::SetAutoPaddingFalseAes128GcmUnsupported) } (Aes256Gcm(decipher, auth_tag_length), true) => { let tag = decipher.finish(); let tag_slice = tag.as_slice(); let truncated_tag = if let Some(len) = auth_tag_length { &tag_slice[..len] } else { tag_slice }; if truncated_tag == auth_tag { Ok(()) } else { Err(DecipherError::DataAuthenticationFailed) } } (Aes256Gcm(..), false) => { Err(DecipherError::SetAutoPaddingFalseAes256GcmUnsupported) } (Aes256Cbc(decryptor), true) => { assert_block_len!(input.len(), 16); let _ = (*decryptor) .decrypt_padded_b2b_mut::<Pkcs7>(input, output) .map_err(|_| DecipherError::CannotUnpadInputData)?; Ok(()) } (Aes256Cbc(mut decryptor), false) => { decryptor.decrypt_block_b2b_mut( GenericArray::from_slice(input), GenericArray::from_mut_slice(output), ); Ok(()) } (Aes256Ctr(mut decryptor), _) => { decryptor.apply_keystream_b2b(input, output).unwrap(); Ok(()) } (Aes192Ctr(mut decryptor), _) => { decryptor.apply_keystream_b2b(input, output).unwrap(); Ok(()) } (Aes128Ctr(mut decryptor), _) => { decryptor.apply_keystream_b2b(input, output).unwrap(); Ok(()) } } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/crypto/digest.rs
ext/node/ops/crypto/digest.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::RefCell; use std::rc::Rc; use deno_core::GarbageCollected; use deno_core::op2; use digest::Digest; use digest::DynDigest; use digest::ExtendableOutput; use digest::Update; mod ring_sha2; pub struct Hasher { pub hash: Rc<RefCell<Option<Hash>>>, } // SAFETY: we're sure this can be GCed unsafe impl GarbageCollected for Hasher { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"Hasher" } } // Make prototype available for JavaScript #[op2] impl Hasher { #[constructor] #[cppgc] fn create(_: bool) -> Hasher { unreachable!() } } impl Hasher { pub fn new( algorithm: &str, output_length: Option<usize>, ) -> Result<Self, HashError> { let hash = Hash::new(algorithm, output_length)?; Ok(Self { hash: Rc::new(RefCell::new(Some(hash))), }) } pub fn update(&self, data: &[u8]) -> bool { if let Some(hash) = self.hash.borrow_mut().as_mut() { hash.update(data); true } else { false } } pub fn digest(&self) -> Option<Box<[u8]>> { let hash = self.hash.borrow_mut().take()?; Some(hash.digest_and_drop()) } pub fn clone_inner( &self, output_length: Option<usize>, ) -> Result<Option<Self>, HashError> { let hash = self.hash.borrow(); let Some(hash) = hash.as_ref() else { return Ok(None); }; let hash = hash.clone_hash(output_length)?; Ok(Some(Self { hash: Rc::new(RefCell::new(Some(hash))), })) } } macro_rules! match_fixed_digest { ($algorithm_name:expr, fn <$type:ident>() $body:block, _ => $other:block) => { match $algorithm_name { "blake2b512" => { type $type = ::blake2::Blake2b512; $body } "blake2s256" => { type $type = ::blake2::Blake2s256; $body } #[allow(dead_code)] _ => crate::ops::crypto::digest::match_fixed_digest_with_eager_block_buffer!($algorithm_name, fn <$type>() $body, _ => $other) } }; } pub(crate) use match_fixed_digest; macro_rules! match_fixed_digest_with_eager_block_buffer { ($algorithm_name:expr, fn <$type:ident>() $body:block, _ => $other:block) => { match $algorithm_name { "rsa-sm3" | "sm3" | "sm3withrsaencryption" => { type $type = ::sm3::Sm3; $body } "rsa-md4" | "md4" | "md4withrsaencryption" => { type $type = ::md4::Md4; $body } "md5-sha1" => { type $type = crate::ops::crypto::md5_sha1::Md5Sha1; $body } _ => crate::ops::crypto::digest::match_fixed_digest_with_oid!($algorithm_name, fn <$type>() $body, _ => $other) } }; } pub(crate) use match_fixed_digest_with_eager_block_buffer; macro_rules! match_fixed_digest_with_oid { ($algorithm_name:expr, fn $(<$type:ident>)?($($hash_algorithm:ident: Option<RsaPssHashAlgorithm>)?) $body:block, _ => $other:block) => { match $algorithm_name { "rsa-md5" | "md5" | "md5withrsaencryption" | "ssl3-md5" => { $(let $hash_algorithm = None;)? $(type $type = ::md5::Md5;)? $body } "rsa-ripemd160" | "ripemd" | "ripemd160" | "ripemd160withrsa" | "rmd160" => { $(let $hash_algorithm = None;)? $(type $type = ::ripemd::Ripemd160;)? $body } "rsa-sha1" | "rsa-sha1-2" | "sha1" | "sha1-2" | "sha1withrsaencryption" | "ssl3-sha1" => { $(let $hash_algorithm = Some(RsaPssHashAlgorithm::Sha1);)? $(type $type = ::sha1::Sha1;)? $body } "rsa-sha224" | "sha224" | "sha224withrsaencryption" => { $(let $hash_algorithm = Some(RsaPssHashAlgorithm::Sha224);)? $(type $type = ::sha2::Sha224;)? $body } "rsa-sha256" | "sha256" | "sha256withrsaencryption" => { $(let $hash_algorithm = Some(RsaPssHashAlgorithm::Sha256);)? $(type $type = ::sha2::Sha256;)? $body } "rsa-sha384" | "sha384" | "sha384withrsaencryption" => { $(let $hash_algorithm = Some(RsaPssHashAlgorithm::Sha384);)? $(type $type = ::sha2::Sha384;)? $body } "rsa-sha512" | "sha512" | "sha512withrsaencryption" => { $(let $hash_algorithm = Some(RsaPssHashAlgorithm::Sha512);)? $(type $type = ::sha2::Sha512;)? $body } "rsa-sha512/224" | "sha512-224" | "sha512-224withrsaencryption" => { $(let $hash_algorithm = Some(RsaPssHashAlgorithm::Sha512_224);)? $(type $type = ::sha2::Sha512_224;)? $body } "rsa-sha512/256" | "sha512-256" | "sha512-256withrsaencryption" => { $(let $hash_algorithm = Some(RsaPssHashAlgorithm::Sha512_256);)? $(type $type = ::sha2::Sha512_256;)? $body } "rsa-sha3-224" | "id-rsassa-pkcs1-v1_5-with-sha3-224" | "sha3-224" => { $(let $hash_algorithm = None;)? $(type $type = ::sha3::Sha3_224;)? $body } "rsa-sha3-256" | "id-rsassa-pkcs1-v1_5-with-sha3-256" | "sha3-256" => { $(let $hash_algorithm = None;)? $(type $type = ::sha3::Sha3_256;)? $body } "rsa-sha3-384" | "id-rsassa-pkcs1-v1_5-with-sha3-384" | "sha3-384" => { $(let $hash_algorithm = None;)? $(type $type = ::sha3::Sha3_384;)? $body } "rsa-sha3-512" | "id-rsassa-pkcs1-v1_5-with-sha3-512" | "sha3-512" => { $(let $hash_algorithm = None;)? $(type $type = ::sha3::Sha3_512;)? $body } _ => $other, } }; } pub(crate) use match_fixed_digest_with_oid; pub enum Hash { FixedSize(Box<dyn DynDigest>), Shake128(Box<sha3::Shake128>, /* output_length: */ Option<usize>), Shake256(Box<sha3::Shake256>, /* output_length: */ Option<usize>), } use Hash::*; #[derive(Debug, thiserror::Error, deno_error::JsError)] #[class(generic)] pub enum HashError { #[error("Output length mismatch for non-extendable algorithm")] OutputLengthMismatch, #[error("Digest method not supported: {0}")] DigestMethodUnsupported(String), } impl Hash { pub fn new( algorithm_name: &str, output_length: Option<usize>, ) -> Result<Self, HashError> { match algorithm_name { "shake128" | "shake-128" => { return Ok(Shake128(Default::default(), output_length)); } "shake256" | "shake-256" => { return Ok(Shake256(Default::default(), output_length)); } "sha256" => { let digest = ring_sha2::RingSha256::new(); if let Some(length) = output_length && length != digest.output_size() { return Err(HashError::OutputLengthMismatch); } return Ok(Hash::FixedSize(Box::new(digest))); } "sha512" => { let digest = ring_sha2::RingSha512::new(); if let Some(length) = output_length && length != digest.output_size() { return Err(HashError::OutputLengthMismatch); } return Ok(Hash::FixedSize(Box::new(digest))); } _ => {} } let algorithm = match_fixed_digest!( algorithm_name, fn <D>() { let digest: D = Digest::new(); if let Some(length) = output_length && length != digest.output_size() { return Err(HashError::OutputLengthMismatch); } FixedSize(Box::new(digest)) }, _ => { return Err(HashError::DigestMethodUnsupported(algorithm_name.to_string())) } ); Ok(algorithm) } pub fn update(&mut self, data: &[u8]) { match self { FixedSize(context) => DynDigest::update(&mut **context, data), Shake128(context, _) => Update::update(&mut **context, data), Shake256(context, _) => Update::update(&mut **context, data), }; } pub fn digest_and_drop(self) -> Box<[u8]> { match self { FixedSize(context) => context.finalize(), // The default output lengths align with Node.js Shake128(context, output_length) => { context.finalize_boxed(output_length.unwrap_or(16)) } Shake256(context, output_length) => { context.finalize_boxed(output_length.unwrap_or(32)) } } } pub fn clone_hash( &self, output_length: Option<usize>, ) -> Result<Self, HashError> { let hash = match self { FixedSize(context) => { if let Some(length) = output_length && length != context.output_size() { return Err(HashError::OutputLengthMismatch); } FixedSize(context.box_clone()) } Shake128(context, _) => Shake128(context.clone(), output_length), Shake256(context, _) => Shake256(context.clone(), output_length), }; Ok(hash) } pub fn get_hashes() -> Vec<&'static str> { vec![ "RSA-MD4", "RSA-MD5", "RSA-RIPEMD160", "RSA-SHA1", "RSA-SHA1-2", "RSA-SHA224", "RSA-SHA256", "RSA-SHA3-224", "RSA-SHA3-256", "RSA-SHA3-384", "RSA-SHA3-512", "RSA-SHA384", "RSA-SHA512", "RSA-SHA512/224", "RSA-SHA512/256", "RSA-SM3", "blake2b512", "blake2s256", "id-rsassa-pkcs1-v1_5-with-sha3-224", "id-rsassa-pkcs1-v1_5-with-sha3-256", "id-rsassa-pkcs1-v1_5-with-sha3-384", "id-rsassa-pkcs1-v1_5-with-sha3-512", "md4", "md4WithRSAEncryption", "md5", "md5-sha1", "md5WithRSAEncryption", "ripemd", "ripemd160", "ripemd160WithRSA", "rmd160", "sha1", "sha1WithRSAEncryption", "sha224", "sha224WithRSAEncryption", "sha256", "sha256WithRSAEncryption", "sha3-224", "sha3-256", "sha3-384", "sha3-512", "sha384", "sha384WithRSAEncryption", "sha512", "sha512-224", "sha512-224WithRSAEncryption", "sha512-256", "sha512-256WithRSAEncryption", "sha512WithRSAEncryption", "shake128", "shake256", "sm3", "sm3WithRSAEncryption", "ssl3-md5", "ssl3-sha1", ] } pub fn get_size(algorithm_name: &str) -> Option<u8> { match algorithm_name { "RSA-MD4" => Some(16), "RSA-MD5" => Some(16), "RSA-RIPEMD160" => Some(20), "RSA-SHA1" => Some(20), "RSA-SHA1-2" => Some(20), "RSA-SHA224" => Some(28), "RSA-SHA256" => Some(32), "RSA-SHA3-224" => Some(28), "RSA-SHA3-256" => Some(32), "RSA-SHA3-384" => Some(48), "RSA-SHA3-512" => Some(64), "RSA-SHA384" => Some(48), "RSA-SHA512" => Some(64), "RSA-SHA512/224" => Some(28), "RSA-SHA512/256" => Some(32), "RSA-SM3" => Some(32), "blake2b512" => Some(64), "blake2s256" => Some(32), "id-rsassa-pkcs1-v1_5-with-sha3-224" => Some(28), "id-rsassa-pkcs1-v1_5-with-sha3-256" => Some(32), "id-rsassa-pkcs1-v1_5-with-sha3-384" => Some(48), "id-rsassa-pkcs1-v1_5-with-sha3-512" => Some(64), "md4" => Some(16), "md4WithRSAEncryption" => Some(16), "md5" => Some(16), "md5-sha1" => Some(20), "md5WithRSAEncryption" => Some(16), "ripemd" => Some(20), "ripemd160" => Some(20), "ripemd160WithRSA" => Some(20), "rmd160" => Some(20), "sha1" => Some(20), "sha1WithRSAEncryption" => Some(20), "sha224" => Some(28), "sha224WithRSAEncryption" => Some(28), "sha256" => Some(32), "sha256WithRSAEncryption" => Some(32), "sha3-224" => Some(28), "sha3-256" => Some(32), "sha3-384" => Some(48), "sha3-512" => Some(64), "sha384" => Some(48), "sha384WithRSAEncryption" => Some(48), "sha512" => Some(64), "sha512-224" => Some(28), "sha512-224WithRSAEncryption" => Some(28), "sha512-256" => Some(32), "sha512-256WithRSAEncryption" => Some(32), "sha512WithRSAEncryption" => Some(64), "shake128" => None, // Variable length "shake256" => None, // Variable length "sm3" => Some(32), "sm3WithRSAEncryption" => Some(32), "ssl3-md5" => Some(16), "ssl3-sha1" => Some(20), _ => None, } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/crypto/sign.rs
ext/node/ops/crypto/sign.rs
// Copyright 2018-2025 the Deno authors. MIT license. use core::ops::Add; use ecdsa::der::MaxOverhead; use ecdsa::der::MaxSize; use elliptic_curve::FieldBytesSize; use elliptic_curve::generic_array::ArrayLength; use rand::rngs::OsRng; use rsa::signature::hazmat::PrehashSigner as _; use rsa::signature::hazmat::PrehashVerifier as _; use rsa::traits::SignatureScheme as _; use spki::der::Decode; use super::keys::AsymmetricPrivateKey; use super::keys::AsymmetricPublicKey; use super::keys::EcPrivateKey; use super::keys::EcPublicKey; use super::keys::KeyObjectHandle; use super::keys::RsaPssHashAlgorithm; use crate::ops::crypto::digest::match_fixed_digest; use crate::ops::crypto::digest::match_fixed_digest_with_oid; fn dsa_signature<C: elliptic_curve::PrimeCurve>( encoding: u32, signature: ecdsa::Signature<C>, ) -> Result<Box<[u8]>, KeyObjectHandlePrehashedSignAndVerifyError> where MaxSize<C>: ArrayLength<u8>, <FieldBytesSize<C> as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>, { match encoding { // DER 0 => Ok(signature.to_der().to_bytes().to_vec().into_boxed_slice()), // IEEE P1363 1 => Ok(signature.to_bytes().to_vec().into_boxed_slice()), _ => Err( KeyObjectHandlePrehashedSignAndVerifyError::InvalidDsaSignatureEncoding, ), } } #[derive(Debug, thiserror::Error, deno_error::JsError)] #[class(type)] pub enum KeyObjectHandlePrehashedSignAndVerifyError { #[error("invalid DSA signature encoding")] InvalidDsaSignatureEncoding, #[error("key is not a private key")] KeyIsNotPrivate, #[error("digest not allowed for RSA signature: {0}")] DigestNotAllowedForRsaSignature(String), #[class(generic)] #[error("failed to sign digest with RSA")] FailedToSignDigestWithRsa, #[error("digest not allowed for RSA-PSS signature: {0}")] DigestNotAllowedForRsaPssSignature(String), #[class(generic)] #[error("failed to sign digest with RSA-PSS")] FailedToSignDigestWithRsaPss, #[error("failed to sign digest with DSA")] FailedToSignDigestWithDsa, #[error( "rsa-pss with different mf1 hash algorithm and hash algorithm is not supported" )] RsaPssHashAlgorithmUnsupported, #[error( "private key does not allow {actual} to be used, expected {expected}" )] PrivateKeyDisallowsUsage { actual: String, expected: String }, #[error("failed to sign digest")] FailedToSignDigest, #[error("x25519 key cannot be used for signing")] X25519KeyCannotBeUsedForSigning, #[error("Ed25519 key cannot be used for prehashed signing")] Ed25519KeyCannotBeUsedForPrehashedSigning, #[error("DH key cannot be used for signing")] DhKeyCannotBeUsedForSigning, #[error("key is not a public or private key")] KeyIsNotPublicOrPrivate, #[error("Invalid DSA signature")] InvalidDsaSignature, #[error("x25519 key cannot be used for verification")] X25519KeyCannotBeUsedForVerification, #[error("Ed25519 key cannot be used for prehashed verification")] Ed25519KeyCannotBeUsedForPrehashedVerification, #[error("DH key cannot be used for verification")] DhKeyCannotBeUsedForVerification, } impl KeyObjectHandle { pub fn sign_prehashed( &self, digest_type: &str, digest: &[u8], pss_salt_length: Option<u32>, dsa_signature_encoding: u32, ) -> Result<Box<[u8]>, KeyObjectHandlePrehashedSignAndVerifyError> { let private_key = self .as_private_key() .ok_or(KeyObjectHandlePrehashedSignAndVerifyError::KeyIsNotPrivate)?; match private_key { AsymmetricPrivateKey::Rsa(key) => { let signer = if digest_type == "md5-sha1" { rsa::pkcs1v15::Pkcs1v15Sign::new_unprefixed() } else { match_fixed_digest_with_oid!( digest_type, fn <D>() { rsa::pkcs1v15::Pkcs1v15Sign::new::<D>() }, _ => { return Err(KeyObjectHandlePrehashedSignAndVerifyError::DigestNotAllowedForRsaSignature(digest_type.to_string())) } ) }; let signature = signer .sign(Some(&mut OsRng), key, digest) .map_err(|_| KeyObjectHandlePrehashedSignAndVerifyError::FailedToSignDigestWithRsa)?; Ok(signature.into()) } AsymmetricPrivateKey::RsaPss(key) => { let mut hash_algorithm = None; let mut salt_length = None; if let Some(details) = &key.details { if details.hash_algorithm != details.mf1_hash_algorithm { return Err(KeyObjectHandlePrehashedSignAndVerifyError::RsaPssHashAlgorithmUnsupported); } hash_algorithm = Some(details.hash_algorithm); salt_length = Some(details.salt_length as usize); } if let Some(s) = pss_salt_length { salt_length = Some(s as usize); } let pss = match_fixed_digest_with_oid!( digest_type, fn <D>(algorithm: Option<RsaPssHashAlgorithm>) { if let Some(hash_algorithm) = hash_algorithm.take() && Some(hash_algorithm) != algorithm { return Err(KeyObjectHandlePrehashedSignAndVerifyError::PrivateKeyDisallowsUsage { actual: digest_type.to_string(), expected: hash_algorithm.as_str().to_string(), }); } if let Some(salt_length) = salt_length { rsa::pss::Pss::new_with_salt::<D>(salt_length) } else { rsa::pss::Pss::new::<D>() } }, _ => { return Err(KeyObjectHandlePrehashedSignAndVerifyError::DigestNotAllowedForRsaPssSignature(digest_type.to_string())); } ); let signature = pss .sign(Some(&mut OsRng), &key.key, digest) .map_err(|_| KeyObjectHandlePrehashedSignAndVerifyError::FailedToSignDigestWithRsaPss)?; Ok(signature.into()) } AsymmetricPrivateKey::Dsa(key) => { let res = match_fixed_digest!( digest_type, fn <D>() { key.sign_prehashed_rfc6979::<D>(digest) }, _ => { return Err(KeyObjectHandlePrehashedSignAndVerifyError::DigestNotAllowedForRsaSignature(digest_type.to_string())) } ); let signature = res.map_err(|_| KeyObjectHandlePrehashedSignAndVerifyError::FailedToSignDigestWithDsa)?; Ok(signature.into()) } AsymmetricPrivateKey::Ec(key) => match key { EcPrivateKey::P224(key) => { let signing_key = p224::ecdsa::SigningKey::from(key); let signature: p224::ecdsa::Signature = signing_key .sign_prehash(digest) .map_err(|_| KeyObjectHandlePrehashedSignAndVerifyError::FailedToSignDigest)?; dsa_signature(dsa_signature_encoding, signature) } EcPrivateKey::P256(key) => { let signing_key = p256::ecdsa::SigningKey::from(key); let signature: p256::ecdsa::Signature = signing_key .sign_prehash(digest) .map_err(|_| KeyObjectHandlePrehashedSignAndVerifyError::FailedToSignDigest)?; dsa_signature(dsa_signature_encoding, signature) } EcPrivateKey::P384(key) => { let signing_key = p384::ecdsa::SigningKey::from(key); let signature: p384::ecdsa::Signature = signing_key .sign_prehash(digest) .map_err(|_| KeyObjectHandlePrehashedSignAndVerifyError::FailedToSignDigest)?; dsa_signature(dsa_signature_encoding, signature) } }, AsymmetricPrivateKey::X25519(_) => { Err(KeyObjectHandlePrehashedSignAndVerifyError::X25519KeyCannotBeUsedForSigning) } AsymmetricPrivateKey::Ed25519(_) => Err(KeyObjectHandlePrehashedSignAndVerifyError::Ed25519KeyCannotBeUsedForPrehashedSigning), AsymmetricPrivateKey::Dh(_) => { Err(KeyObjectHandlePrehashedSignAndVerifyError::DhKeyCannotBeUsedForSigning) } } } pub fn verify_prehashed( &self, digest_type: &str, digest: &[u8], signature: &[u8], pss_salt_length: Option<u32>, dsa_signature_encoding: u32, ) -> Result<bool, KeyObjectHandlePrehashedSignAndVerifyError> { let public_key = self.as_public_key().ok_or( KeyObjectHandlePrehashedSignAndVerifyError::KeyIsNotPublicOrPrivate, )?; match &*public_key { AsymmetricPublicKey::Rsa(key) => { let signer = if digest_type == "md5-sha1" { rsa::pkcs1v15::Pkcs1v15Sign::new_unprefixed() } else { match_fixed_digest_with_oid!( digest_type, fn <D>() { rsa::pkcs1v15::Pkcs1v15Sign::new::<D>() }, _ => { return Err(KeyObjectHandlePrehashedSignAndVerifyError::DigestNotAllowedForRsaSignature(digest_type.to_string())) } ) }; Ok(signer.verify(key, digest, signature).is_ok()) } AsymmetricPublicKey::RsaPss(key) => { let mut hash_algorithm = None; let mut salt_length = None; if let Some(details) = &key.details { if details.hash_algorithm != details.mf1_hash_algorithm { return Err(KeyObjectHandlePrehashedSignAndVerifyError::RsaPssHashAlgorithmUnsupported); } hash_algorithm = Some(details.hash_algorithm); salt_length = Some(details.salt_length as usize); } if let Some(s) = pss_salt_length { salt_length = Some(s as usize); } let pss = match_fixed_digest_with_oid!( digest_type, fn <D>(algorithm: Option<RsaPssHashAlgorithm>) { if let Some(hash_algorithm) = hash_algorithm.take() && Some(hash_algorithm) != algorithm { return Err(KeyObjectHandlePrehashedSignAndVerifyError::PrivateKeyDisallowsUsage { actual: digest_type.to_string(), expected: hash_algorithm.as_str().to_string(), }); } if let Some(salt_length) = salt_length { rsa::pss::Pss::new_with_salt::<D>(salt_length) } else { rsa::pss::Pss::new::<D>() } }, _ => { return Err(KeyObjectHandlePrehashedSignAndVerifyError::DigestNotAllowedForRsaPssSignature(digest_type.to_string())); } ); Ok(pss.verify(&key.key, digest, signature).is_ok()) } AsymmetricPublicKey::Dsa(key) => { let signature = dsa::Signature::from_der(signature) .map_err(|_| KeyObjectHandlePrehashedSignAndVerifyError::InvalidDsaSignature)?; Ok(key.verify_prehash(digest, &signature).is_ok()) } AsymmetricPublicKey::Ec(key) => match key { EcPublicKey::P224(key) => { let verifying_key = p224::ecdsa::VerifyingKey::from(key); let signature = if dsa_signature_encoding == 0 { p224::ecdsa::Signature::from_der(signature) } else { p224::ecdsa::Signature::from_bytes(signature.into()) }; let Ok(signature) = signature else { return Ok(false); }; Ok(verifying_key.verify_prehash(digest, &signature).is_ok()) } EcPublicKey::P256(key) => { let verifying_key = p256::ecdsa::VerifyingKey::from(key); let signature = if dsa_signature_encoding == 0 { p256::ecdsa::Signature::from_der(signature) } else { p256::ecdsa::Signature::from_bytes(signature.into()) }; let Ok(signature) = signature else { return Ok(false); }; Ok(verifying_key.verify_prehash(digest, &signature).is_ok()) } EcPublicKey::P384(key) => { let verifying_key = p384::ecdsa::VerifyingKey::from(key); let signature = if dsa_signature_encoding == 0 { p384::ecdsa::Signature::from_der(signature) } else { p384::ecdsa::Signature::from_bytes(signature.into()) }; let Ok(signature) = signature else { return Ok(false); }; Ok(verifying_key.verify_prehash(digest, &signature).is_ok()) } }, AsymmetricPublicKey::X25519(_) => { Err(KeyObjectHandlePrehashedSignAndVerifyError::X25519KeyCannotBeUsedForVerification) } AsymmetricPublicKey::Ed25519(_) => Err(KeyObjectHandlePrehashedSignAndVerifyError::Ed25519KeyCannotBeUsedForPrehashedVerification), AsymmetricPublicKey::Dh(_) => { Err(KeyObjectHandlePrehashedSignAndVerifyError::DhKeyCannotBeUsedForVerification) } } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/crypto/md5_sha1.rs
ext/node/ops/crypto/md5_sha1.rs
// Copyright 2018-2025 the Deno authors. MIT license. use core::fmt; use digest::HashMarker; use digest::Output; use digest::Reset; use digest::core_api::AlgorithmName; use digest::core_api::BlockSizeUser; use digest::core_api::Buffer; use digest::core_api::BufferKindUser; use digest::core_api::CoreWrapper; use digest::core_api::FixedOutputCore; use digest::core_api::OutputSizeUser; use digest::core_api::UpdateCore; pub type Md5Sha1 = CoreWrapper<Md5Sha1Core>; pub struct Md5Sha1Core { md5: md5::Md5Core, sha1: sha1::Sha1Core, } impl HashMarker for Md5Sha1Core {} impl BlockSizeUser for Md5Sha1Core { type BlockSize = sec1::consts::U64; } impl BufferKindUser for Md5Sha1Core { type BufferKind = digest::block_buffer::Eager; } impl OutputSizeUser for Md5Sha1Core { type OutputSize = sec1::consts::U36; } impl UpdateCore for Md5Sha1Core { #[inline] fn update_blocks(&mut self, blocks: &[digest::core_api::Block<Self>]) { self.md5.update_blocks(blocks); self.sha1.update_blocks(blocks); } } impl FixedOutputCore for Md5Sha1Core { #[inline] fn finalize_fixed_core( &mut self, buffer: &mut Buffer<Self>, out: &mut Output<Self>, ) { let mut md5_output = Output::<md5::Md5Core>::default(); self .md5 .finalize_fixed_core(&mut buffer.clone(), &mut md5_output); let mut sha1_output = Output::<sha1::Sha1Core>::default(); self.sha1.finalize_fixed_core(buffer, &mut sha1_output); out[..16].copy_from_slice(&md5_output); out[16..].copy_from_slice(&sha1_output); } } impl Default for Md5Sha1Core { #[inline] fn default() -> Self { Self { md5: Default::default(), sha1: Default::default(), } } } impl Clone for Md5Sha1Core { #[inline] fn clone(&self) -> Self { Self { md5: self.md5.clone(), sha1: self.sha1.clone(), } } } impl Reset for Md5Sha1Core { #[inline] fn reset(&mut self) { *self = Default::default(); } } impl AlgorithmName for Md5Sha1Core { fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Md5Sha1") } } impl fmt::Debug for Md5Sha1Core { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Md5Sha1Core { ... }") } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/crypto/dh.rs
ext/node/ops/crypto/dh.rs
// Copyright 2018-2025 the Deno authors. MIT license. use num_bigint_dig::BigUint; use num_bigint_dig::RandBigInt; use num_traits::FromPrimitive; use super::primes::Prime; #[derive(Clone)] pub struct PublicKey(BigUint); impl PublicKey { pub fn from_bytes(bytes: &[u8]) -> Self { let public_key = BigUint::from_bytes_be(bytes); Self(public_key) } pub fn into_vec(self) -> Vec<u8> { self.0.to_bytes_be() } } #[derive(Clone)] pub struct PrivateKey(BigUint); impl PrivateKey { pub fn new(exponent_size: usize) -> Self { let mut rng = rand::thread_rng(); let exponent = rng.gen_biguint(exponent_size); Self(exponent) } pub fn from_bytes(bytes: &[u8]) -> Self { let exponent = BigUint::from_bytes_be(bytes); Self(exponent) } /// Diffie-Hellman modular exponentiation. /// s = g^x mod p pub fn compute_public_key( &self, generator: &BigUint, modulus: &BigUint, ) -> PublicKey { let public_key = generator.modpow(&self.0, modulus); PublicKey(public_key) } pub fn into_vec(self) -> Vec<u8> { self.0.to_bytes_be() } } /// Classic DH pub struct DiffieHellman { pub private_key: PrivateKey, pub public_key: PublicKey, } impl DiffieHellman { pub fn group<G>() -> Self where G: DiffieHellmanGroup, { let private_key = PrivateKey::new(G::EXPONENT_SIZE / 8); let generator = BigUint::from_usize(G::GENERATOR).unwrap(); let modulus = BigUint::from_slice(G::MODULUS); let public_key = private_key.compute_public_key(&generator, &modulus); Self { private_key, public_key, } } pub fn new(prime: Prime, generator: usize) -> Self { let private_key = PrivateKey::new(prime.bits()); let generator = BigUint::from_usize(generator).unwrap(); let public_key = private_key.compute_public_key(&generator, &prime); Self { private_key, public_key, } } } /// Well-known modp groups // /// More Modular Exponential (MODP) Diffie-Hellman groups for Internet Key Exchange (IKE) /// https://www.rfc-editor.org/rfc/rfc3526 /// /// Insecure groups `modp1` and `modp2` from https://www.rfc-editor.org/rfc/rfc2409.txt /// are deprecated in Node.js. We don't support them. pub trait DiffieHellmanGroup { const GENERATOR: usize; const MODULUS: &'static [u32]; /// Size of the exponent in bits const EXPONENT_SIZE: usize; } /// 1536-bit MODP Group /// https://www.rfc-editor.org/rfc/rfc3526#section-2 pub struct Modp1536; impl DiffieHellmanGroup for Modp1536 { const GENERATOR: usize = 2; const EXPONENT_SIZE: usize = 192; const MODULUS: &'static [u32] = &[ 0xFFFFFFFF, 0xFFFFFFFF, 0xC90FDAA2, 0x2168C234, 0xC4C6628B, 0x80DC1CD1, 0x29024E08, 0x8A67CC74, 0x020BBEA6, 0x3B139B22, 0x514A0879, 0x8E3404DD, 0xEF9519B3, 0xCD3A431B, 0x302B0A6D, 0xF25F1437, 0x4FE1356D, 0x6D51C245, 0xE485B576, 0x625E7EC6, 0xF44C42E9, 0xA637ED6B, 0x0BFF5CB6, 0xF406B7ED, 0xEE386BFB, 0x5A899FA5, 0xAE9F2411, 0x7C4B1FE6, 0x49286651, 0xECE45B3D, 0xC2007CB8, 0xA163BF05, 0x98DA4836, 0x1C55D39A, 0x69163FA8, 0xFD24CF5F, 0x83655D23, 0xDCA3AD96, 0x1C62F356, 0x208552BB, 0x9ED52907, 0x7096966D, 0x670C354E, 0x4ABC9804, 0xF1746C08, 0xCA237327, 0xFFFFFFFF, 0xFFFFFFFF, ]; } /// 2048-bit MODP Group /// https://www.rfc-editor.org/rfc/rfc3526#section-3 pub struct Modp2048; impl DiffieHellmanGroup for Modp2048 { const GENERATOR: usize = 2; const EXPONENT_SIZE: usize = 256; const MODULUS: &'static [u32] = &[ 0xFFFFFFFF, 0xFFFFFFFF, 0xC90FDAA2, 0x2168C234, 0xC4C6628B, 0x80DC1CD1, 0x29024E08, 0x8A67CC74, 0x020BBEA6, 0x3B139B22, 0x514A0879, 0x8E3404DD, 0xEF9519B3, 0xCD3A431B, 0x302B0A6D, 0xF25F1437, 0x4FE1356D, 0x6D51C245, 0xE485B576, 0x625E7EC6, 0xF44C42E9, 0xA637ED6B, 0x0BFF5CB6, 0xF406B7ED, 0xEE386BFB, 0x5A899FA5, 0xAE9F2411, 0x7C4B1FE6, 0x49286651, 0xECE45B3D, 0xC2007CB8, 0xA163BF05, 0x98DA4836, 0x1C55D39A, 0x69163FA8, 0xFD24CF5F, 0x83655D23, 0xDCA3AD96, 0x1C62F356, 0x208552BB, 0x9ED52907, 0x7096966D, 0x670C354E, 0x4ABC9804, 0xF1746C08, 0xCA18217C, 0x32905E46, 0x2E36CE3B, 0xE39E772C, 0x180E8603, 0x9B2783A2, 0xEC07A28F, 0xB5C55DF0, 0x6F4C52C9, 0xDE2BCBF6, 0x95581718, 0x3995497C, 0xEA956AE5, 0x15D22618, 0x98FA0510, 0x15728E5A, 0x8AACAA68, 0xFFFFFFFF, 0xFFFFFFFF, ]; } /// 3072-bit MODP Group /// https://www.rfc-editor.org/rfc/rfc3526#section-4 pub struct Modp3072; impl DiffieHellmanGroup for Modp3072 { const GENERATOR: usize = 2; const EXPONENT_SIZE: usize = 384; const MODULUS: &'static [u32] = &[ 0xFFFFFFFF, 0xFFFFFFFF, 0xC90FDAA2, 0x2168C234, 0xC4C6628B, 0x80DC1CD1, 0x29024E08, 0x8A67CC74, 0x020BBEA6, 0x3B139B22, 0x514A0879, 0x8E3404DD, 0xEF9519B3, 0xCD3A431B, 0x302B0A6D, 0xF25F1437, 0x4FE1356D, 0x6D51C245, 0xE485B576, 0x625E7EC6, 0xF44C42E9, 0xA637ED6B, 0x0BFF5CB6, 0xF406B7ED, 0xEE386BFB, 0x5A899FA5, 0xAE9F2411, 0x7C4B1FE6, 0x49286651, 0xECE45B3D, 0xC2007CB8, 0xA163BF05, 0x98DA4836, 0x1C55D39A, 0x69163FA8, 0xFD24CF5F, 0x83655D23, 0xDCA3AD96, 0x1C62F356, 0x208552BB, 0x9ED52907, 0x7096966D, 0x670C354E, 0x4ABC9804, 0xF1746C08, 0xCA18217C, 0x32905E46, 0x2E36CE3B, 0xE39E772C, 0x180E8603, 0x9B2783A2, 0xEC07A28F, 0xB5C55DF0, 0x6F4C52C9, 0xDE2BCBF6, 0x95581718, 0x3995497C, 0xEA956AE5, 0x15D22618, 0x98FA0510, 0x15728E5A, 0x8AAAC42D, 0xAD33170D, 0x04507A33, 0xA85521AB, 0xDF1CBA64, 0xECFB8504, 0x58DBEF0A, 0x8AEA7157, 0x5D060C7D, 0xB3970F85, 0xA6E1E4C7, 0xABF5AE8C, 0xDB0933D7, 0x1E8C94E0, 0x4A25619D, 0xCEE3D226, 0x1AD2EE6B, 0xF12FFA06, 0xD98A0864, 0xD8760273, 0x3EC86A64, 0x521F2B18, 0x177B200C, 0xBBE11757, 0x7A615D6C, 0x770988C0, 0xBAD946E2, 0x08E24FA0, 0x74E5AB31, 0x43DB5BFC, 0xE0FD108E, 0x4B82D120, 0xA93AD2CA, 0xFFFFFFFF, 0xFFFFFFFF, ]; } /// 4096-bit MODP Group /// https://www.rfc-editor.org/rfc/rfc3526#section-5 pub struct Modp4096; impl DiffieHellmanGroup for Modp4096 { const GENERATOR: usize = 2; const EXPONENT_SIZE: usize = 512; const MODULUS: &'static [u32] = &[ 0xFFFFFFFF, 0xFFFFFFFF, 0xC90FDAA2, 0x2168C234, 0xC4C6628B, 0x80DC1CD1, 0x29024E08, 0x8A67CC74, 0x020BBEA6, 0x3B139B22, 0x514A0879, 0x8E3404DD, 0xEF9519B3, 0xCD3A431B, 0x302B0A6D, 0xF25F1437, 0x4FE1356D, 0x6D51C245, 0xE485B576, 0x625E7EC6, 0xF44C42E9, 0xA637ED6B, 0x0BFF5CB6, 0xF406B7ED, 0xEE386BFB, 0x5A899FA5, 0xAE9F2411, 0x7C4B1FE6, 0x49286651, 0xECE45B3D, 0xC2007CB8, 0xA163BF05, 0x98DA4836, 0x1C55D39A, 0x69163FA8, 0xFD24CF5F, 0x83655D23, 0xDCA3AD96, 0x1C62F356, 0x208552BB, 0x9ED52907, 0x7096966D, 0x670C354E, 0x4ABC9804, 0xF1746C08, 0xCA18217C, 0x32905E46, 0x2E36CE3B, 0xE39E772C, 0x180E8603, 0x9B2783A2, 0xEC07A28F, 0xB5C55DF0, 0x6F4C52C9, 0xDE2BCBF6, 0x95581718, 0x3995497C, 0xEA956AE5, 0x15D22618, 0x98FA0510, 0x15728E5A, 0x8AAAC42D, 0xAD33170D, 0x04507A33, 0xA85521AB, 0xDF1CBA64, 0xECFB8504, 0x58DBEF0A, 0x8AEA7157, 0x5D060C7D, 0xB3970F85, 0xA6E1E4C7, 0xABF5AE8C, 0xDB0933D7, 0x1E8C94E0, 0x4A25619D, 0xCEE3D226, 0x1AD2EE6B, 0xF12FFA06, 0xD98A0864, 0xD8760273, 0x3EC86A64, 0x521F2B18, 0x177B200C, 0xBBE11757, 0x7A615D6C, 0x770988C0, 0xBAD946E2, 0x08E24FA0, 0x74E5AB31, 0x43DB5BFC, 0xE0FD108E, 0x4B82D120, 0xA9210801, 0x1A723C12, 0xA787E6D7, 0x88719A10, 0xBDBA5B26, 0x99C32718, 0x6AF4E23C, 0x1A946834, 0xB6150BDA, 0x2583E9CA, 0x2AD44CE8, 0xDBBBC2DB, 0x04DE8EF9, 0x2E8EFC14, 0x1FBECAA6, 0x287C5947, 0x4E6BC05D, 0x99B2964F, 0xA090C3A2, 0x233BA186, 0x515BE7ED, 0x1F612970, 0xCEE2D7AF, 0xB81BDD76, 0x2170481C, 0xD0069127, 0xD5B05AA9, 0x93B4EA98, 0x8D8FDDC1, 0x86FFB7DC, 0x90A6C08F, 0x4DF435C9, 0x34063199, 0xFFFFFFFF, 0xFFFFFFFF, ]; } /// 6144-bit MODP Group /// https://www.rfc-editor.org/rfc/rfc3526#section-6 pub struct Modp6144; impl DiffieHellmanGroup for Modp6144 { const GENERATOR: usize = 2; const EXPONENT_SIZE: usize = 768; const MODULUS: &'static [u32] = &[ 0xFFFFFFFF, 0xFFFFFFFF, 0xC90FDAA2, 0x2168C234, 0xC4C6628B, 0x80DC1CD1, 0x29024E08, 0x8A67CC74, 0x020BBEA6, 0x3B139B22, 0x514A0879, 0x8E3404DD, 0xEF9519B3, 0xCD3A431B, 0x302B0A6D, 0xF25F1437, 0x4FE1356D, 0x6D51C245, 0xE485B576, 0x625E7EC6, 0xF44C42E9, 0xA637ED6B, 0x0BFF5CB6, 0xF406B7ED, 0xEE386BFB, 0x5A899FA5, 0xAE9F2411, 0x7C4B1FE6, 0x49286651, 0xECE45B3D, 0xC2007CB8, 0xA163BF05, 0x98DA4836, 0x1C55D39A, 0x69163FA8, 0xFD24CF5F, 0x83655D23, 0xDCA3AD96, 0x1C62F356, 0x208552BB, 0x9ED52907, 0x7096966D, 0x670C354E, 0x4ABC9804, 0xF1746C08, 0xCA18217C, 0x32905E46, 0x2E36CE3B, 0xE39E772C, 0x180E8603, 0x9B2783A2, 0xEC07A28F, 0xB5C55DF0, 0x6F4C52C9, 0xDE2BCBF6, 0x95581718, 0x3995497C, 0xEA956AE5, 0x15D22618, 0x98FA0510, 0x15728E5A, 0x8AAAC42D, 0xAD33170D, 0x04507A33, 0xA85521AB, 0xDF1CBA64, 0xECFB8504, 0x58DBEF0A, 0x8AEA7157, 0x5D060C7D, 0xB3970F85, 0xA6E1E4C7, 0xABF5AE8C, 0xDB0933D7, 0x1E8C94E0, 0x4A25619D, 0xCEE3D226, 0x1AD2EE6B, 0xF12FFA06, 0xD98A0864, 0xD8760273, 0x3EC86A64, 0x521F2B18, 0x177B200C, 0xBBE11757, 0x7A615D6C, 0x770988C0, 0xBAD946E2, 0x08E24FA0, 0x74E5AB31, 0x43DB5BFC, 0xE0FD108E, 0x4B82D120, 0xA9210801, 0x1A723C12, 0xA787E6D7, 0x88719A10, 0xBDBA5B26, 0x99C32718, 0x6AF4E23C, 0x1A946834, 0xB6150BDA, 0x2583E9CA, 0x2AD44CE8, 0xDBBBC2DB, 0x04DE8EF9, 0x2E8EFC14, 0x1FBECAA6, 0x287C5947, 0x4E6BC05D, 0x99B2964F, 0xA090C3A2, 0x233BA186, 0x515BE7ED, 0x1F612970, 0xCEE2D7AF, 0xB81BDD76, 0x2170481C, 0xD0069127, 0xD5B05AA9, 0x93B4EA98, 0x8D8FDDC1, 0x86FFB7DC, 0x90A6C08F, 0x4DF435C9, 0x34028492, 0x36C3FAB4, 0xD27C7026, 0xC1D4DCB2, 0x602646DE, 0xC9751E76, 0x3DBA37BD, 0xF8FF9406, 0xAD9E530E, 0xE5DB382F, 0x413001AE, 0xB06A53ED, 0x9027D831, 0x179727B0, 0x865A8918, 0xDA3EDBEB, 0xCF9B14ED, 0x44CE6CBA, 0xCED4BB1B, 0xDB7F1447, 0xE6CC254B, 0x33205151, 0x2BD7AF42, 0x6FB8F401, 0x378CD2BF, 0x5983CA01, 0xC64B92EC, 0xF032EA15, 0xD1721D03, 0xF482D7CE, 0x6E74FEF6, 0xD55E702F, 0x46980C82, 0xB5A84031, 0x900B1C9E, 0x59E7C97F, 0xBEC7E8F3, 0x23A97A7E, 0x36CC88BE, 0x0F1D45B7, 0xFF585AC5, 0x4BD407B2, 0x2B4154AA, 0xCC8F6D7E, 0xBF48E1D8, 0x14CC5ED2, 0x0F8037E0, 0xA79715EE, 0xF29BE328, 0x06A1D58B, 0xB7C5DA76, 0xF550AA3D, 0x8A1FBFF0, 0xEB19CCB1, 0xA313D55C, 0xDA56C9EC, 0x2EF29632, 0x387FE8D7, 0x6E3C0468, 0x043E8F66, 0x3F4860EE, 0x12BF2D5B, 0x0B7474D6, 0xE694F91E, 0x6DCC4024, 0xFFFFFFFF, 0xFFFFFFFF, ]; } /// 8192-bit MODP Group /// https://www.rfc-editor.org/rfc/rfc3526#section-7 pub struct Modp8192; impl DiffieHellmanGroup for Modp8192 { const GENERATOR: usize = 2; const EXPONENT_SIZE: usize = 1024; const MODULUS: &'static [u32] = &[ 0xFFFFFFFF, 0xFFFFFFFF, 0xC90FDAA2, 0x2168C234, 0xC4C6628B, 0x80DC1CD1, 0x29024E08, 0x8A67CC74, 0x020BBEA6, 0x3B139B22, 0x514A0879, 0x8E3404DD, 0xEF9519B3, 0xCD3A431B, 0x302B0A6D, 0xF25F1437, 0x4FE1356D, 0x6D51C245, 0xE485B576, 0x625E7EC6, 0xF44C42E9, 0xA637ED6B, 0x0BFF5CB6, 0xF406B7ED, 0xEE386BFB, 0x5A899FA5, 0xAE9F2411, 0x7C4B1FE6, 0x49286651, 0xECE45B3D, 0xC2007CB8, 0xA163BF05, 0x98DA4836, 0x1C55D39A, 0x69163FA8, 0xFD24CF5F, 0x83655D23, 0xDCA3AD96, 0x1C62F356, 0x208552BB, 0x9ED52907, 0x7096966D, 0x670C354E, 0x4ABC9804, 0xF1746C08, 0xCA18217C, 0x32905E46, 0x2E36CE3B, 0xE39E772C, 0x180E8603, 0x9B2783A2, 0xEC07A28F, 0xB5C55DF0, 0x6F4C52C9, 0xDE2BCBF6, 0x95581718, 0x3995497C, 0xEA956AE5, 0x15D22618, 0x98FA0510, 0x15728E5A, 0x8AAAC42D, 0xAD33170D, 0x04507A33, 0xA85521AB, 0xDF1CBA64, 0xECFB8504, 0x58DBEF0A, 0x8AEA7157, 0x5D060C7D, 0xB3970F85, 0xA6E1E4C7, 0xABF5AE8C, 0xDB0933D7, 0x1E8C94E0, 0x4A25619D, 0xCEE3D226, 0x1AD2EE6B, 0xF12FFA06, 0xD98A0864, 0xD8760273, 0x3EC86A64, 0x521F2B18, 0x177B200C, 0xBBE11757, 0x7A615D6C, 0x770988C0, 0xBAD946E2, 0x08E24FA0, 0x74E5AB31, 0x43DB5BFC, 0xE0FD108E, 0x4B82D120, 0xA9210801, 0x1A723C12, 0xA787E6D7, 0x88719A10, 0xBDBA5B26, 0x99C32718, 0x6AF4E23C, 0x1A946834, 0xB6150BDA, 0x2583E9CA, 0x2AD44CE8, 0xDBBBC2DB, 0x04DE8EF9, 0x2E8EFC14, 0x1FBECAA6, 0x287C5947, 0x4E6BC05D, 0x99B2964F, 0xA090C3A2, 0x233BA186, 0x515BE7ED, 0x1F612970, 0xCEE2D7AF, 0xB81BDD76, 0x2170481C, 0xD0069127, 0xD5B05AA9, 0x93B4EA98, 0x8D8FDDC1, 0x86FFB7DC, 0x90A6C08F, 0x4DF435C9, 0x34028492, 0x36C3FAB4, 0xD27C7026, 0xC1D4DCB2, 0x602646DE, 0xC9751E76, 0x3DBA37BD, 0xF8FF9406, 0xAD9E530E, 0xE5DB382F, 0x413001AE, 0xB06A53ED, 0x9027D831, 0x179727B0, 0x865A8918, 0xDA3EDBEB, 0xCF9B14ED, 0x44CE6CBA, 0xCED4BB1B, 0xDB7F1447, 0xE6CC254B, 0x33205151, 0x2BD7AF42, 0x6FB8F401, 0x378CD2BF, 0x5983CA01, 0xC64B92EC, 0xF032EA15, 0xD1721D03, 0xF482D7CE, 0x6E74FEF6, 0xD55E702F, 0x46980C82, 0xB5A84031, 0x900B1C9E, 0x59E7C97F, 0xBEC7E8F3, 0x23A97A7E, 0x36CC88BE, 0x0F1D45B7, 0xFF585AC5, 0x4BD407B2, 0x2B4154AA, 0xCC8F6D7E, 0xBF48E1D8, 0x14CC5ED2, 0x0F8037E0, 0xA79715EE, 0xF29BE328, 0x06A1D58B, 0xB7C5DA76, 0xF550AA3D, 0x8A1FBFF0, 0xEB19CCB1, 0xA313D55C, 0xDA56C9EC, 0x2EF29632, 0x387FE8D7, 0x6E3C0468, 0x043E8F66, 0x3F4860EE, 0x12BF2D5B, 0x0B7474D6, 0xE694F91E, 0x6DBE1159, 0x74A3926F, 0x12FEE5E4, 0x38777CB6, 0xA932DF8C, 0xD8BEC4D0, 0x73B931BA, 0x3BC832B6, 0x8D9DD300, 0x741FA7BF, 0x8AFC47ED, 0x2576F693, 0x6BA42466, 0x3AAB639C, 0x5AE4F568, 0x3423B474, 0x2BF1C978, 0x238F16CB, 0xE39D652D, 0xE3FDB8BE, 0xFC848AD9, 0x22222E04, 0xA4037C07, 0x13EB57A8, 0x1A23F0C7, 0x3473FC64, 0x6CEA306B, 0x4BCBC886, 0x2F8385DD, 0xFA9D4B7F, 0xA2C087E8, 0x79683303, 0xED5BDD3A, 0x062B3CF5, 0xB3A278A6, 0x6D2A13F8, 0x3F44F82D, 0xDF310EE0, 0x74AB6A36, 0x4597E899, 0xA0255DC1, 0x64F31CC5, 0x0846851D, 0xF9AB4819, 0x5DED7EA1, 0xB1D510BD, 0x7EE74D73, 0xFAF36BC3, 0x1ECFA268, 0x359046F4, 0xEB879F92, 0x4009438B, 0x481C6CD7, 0x889A002E, 0xD5EE382B, 0xC9190DA6, 0xFC026E47, 0x9558E447, 0x5677E9AA, 0x9E3050E2, 0x765694DF, 0xC81F56E8, 0x80B96E71, 0x60C980DD, 0x98EDD3DF, 0xFFFFFFFF, 0xFFFFFFFF, ]; }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/crypto/mod.rs
ext/node/ops/crypto/mod.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::future::Future; use std::rc::Rc; use aws_lc_rs::signature::Ed25519KeyPair; use deno_core::JsBuffer; use deno_core::OpState; use deno_core::StringOrBuffer; use deno_core::ToJsBuffer; use deno_core::op2; use deno_core::unsync::spawn_blocking; use deno_error::JsErrorBox; use elliptic_curve::sec1::ToEncodedPoint; use hkdf::Hkdf; use keys::AsymmetricPrivateKey; use keys::AsymmetricPublicKey; use keys::EcPrivateKey; use keys::EcPublicKey; use keys::KeyObjectHandle; use num_bigint::BigInt; use num_bigint_dig::BigUint; use p224::NistP224; use p256::NistP256; use p384::NistP384; use rand::Rng; use rand::distributions::Distribution; use rand::distributions::Uniform; use rsa::Oaep; use rsa::Pkcs1v15Encrypt; use rsa::RsaPrivateKey; use rsa::RsaPublicKey; use rsa::pkcs8::DecodePrivateKey; use rsa::pkcs8::DecodePublicKey; pub mod cipher; mod dh; pub mod digest; pub mod keys; mod md5_sha1; mod pkcs3; mod primes; pub mod sign; pub mod x509; use self::digest::match_fixed_digest_with_eager_block_buffer; #[op2(fast)] pub fn op_node_check_prime( #[bigint] num: i64, #[number] checks: usize, ) -> bool { primes::is_probably_prime(&BigInt::from(num), checks) } #[op2] pub fn op_node_check_prime_bytes( #[anybuffer] bytes: &[u8], #[number] checks: usize, ) -> bool { let candidate = BigInt::from_bytes_be(num_bigint::Sign::Plus, bytes); primes::is_probably_prime(&candidate, checks) } #[op2(async)] pub async fn op_node_check_prime_async( #[bigint] num: i64, #[number] checks: usize, ) -> Result<bool, tokio::task::JoinError> { // TODO(@littledivy): use rayon for CPU-bound tasks spawn_blocking(move || primes::is_probably_prime(&BigInt::from(num), checks)) .await } #[op2(async)] pub fn op_node_check_prime_bytes_async( #[anybuffer] bytes: &[u8], #[number] checks: usize, ) -> impl Future<Output = Result<bool, tokio::task::JoinError>> + use<> { let candidate = BigInt::from_bytes_be(num_bigint::Sign::Plus, bytes); // TODO(@littledivy): use rayon for CPU-bound tasks async move { spawn_blocking(move || primes::is_probably_prime(&candidate, checks)).await } } #[op2] #[cppgc] pub fn op_node_create_hash( #[string] algorithm: &str, output_length: Option<u32>, ) -> Result<digest::Hasher, digest::HashError> { digest::Hasher::new(algorithm, output_length.map(|l| l as usize)) } #[op2] #[serde] pub fn op_node_get_hashes() -> Vec<&'static str> { digest::Hash::get_hashes() } #[op2] pub fn op_node_get_hash_size(#[string] algorithm: &str) -> Option<u8> { digest::Hash::get_size(algorithm) } #[op2(fast)] pub fn op_node_hash_update( #[cppgc] hasher: &digest::Hasher, #[buffer] data: &[u8], ) -> bool { hasher.update(data) } #[op2(fast)] pub fn op_node_hash_update_str( #[cppgc] hasher: &digest::Hasher, #[string] data: &str, ) -> bool { hasher.update(data.as_bytes()) } #[op2] #[buffer] pub fn op_node_hash_digest( #[cppgc] hasher: &digest::Hasher, ) -> Option<Box<[u8]>> { hasher.digest() } #[op2] #[string] pub fn op_node_hash_digest_hex( #[cppgc] hasher: &digest::Hasher, ) -> Option<String> { let digest = hasher.digest()?; Some(faster_hex::hex_string(&digest)) } #[op2] #[cppgc] pub fn op_node_hash_clone( #[cppgc] hasher: &digest::Hasher, output_length: Option<u32>, ) -> Result<Option<digest::Hasher>, digest::HashError> { hasher.clone_inner(output_length.map(|l| l as usize)) } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum PrivateEncryptDecryptError { #[class(generic)] #[error(transparent)] Pkcs8(#[from] pkcs8::Error), #[class(generic)] #[error(transparent)] Spki(#[from] spki::Error), #[class(generic)] #[error(transparent)] Utf8(#[from] std::str::Utf8Error), #[class(generic)] #[error(transparent)] Rsa(#[from] rsa::Error), #[class(type)] #[error("Unknown padding")] UnknownPadding, } #[op2] #[serde] pub fn op_node_private_encrypt( #[serde] key: StringOrBuffer, #[serde] msg: StringOrBuffer, #[smi] padding: u32, ) -> Result<ToJsBuffer, PrivateEncryptDecryptError> { let key = RsaPrivateKey::from_pkcs8_pem((&key).try_into()?)?; let mut rng = rand::thread_rng(); match padding { 1 => Ok( key .as_ref() .encrypt(&mut rng, Pkcs1v15Encrypt, &msg)? .into(), ), 4 => Ok( key .as_ref() .encrypt(&mut rng, Oaep::new::<sha1::Sha1>(), &msg)? .into(), ), _ => Err(PrivateEncryptDecryptError::UnknownPadding), } } #[op2] #[serde] pub fn op_node_private_decrypt( #[serde] key: StringOrBuffer, #[serde] msg: StringOrBuffer, #[smi] padding: u32, ) -> Result<ToJsBuffer, PrivateEncryptDecryptError> { let key = RsaPrivateKey::from_pkcs8_pem((&key).try_into()?)?; match padding { 1 => Ok(key.decrypt(Pkcs1v15Encrypt, &msg)?.into()), 4 => Ok(key.decrypt(Oaep::new::<sha1::Sha1>(), &msg)?.into()), _ => Err(PrivateEncryptDecryptError::UnknownPadding), } } #[op2] #[serde] pub fn op_node_public_encrypt( #[serde] key: StringOrBuffer, #[serde] msg: StringOrBuffer, #[smi] padding: u32, ) -> Result<ToJsBuffer, PrivateEncryptDecryptError> { let key = RsaPublicKey::from_public_key_pem((&key).try_into()?)?; let mut rng = rand::thread_rng(); match padding { 1 => Ok(key.encrypt(&mut rng, Pkcs1v15Encrypt, &msg)?.into()), 4 => Ok( key .encrypt(&mut rng, Oaep::new::<sha1::Sha1>(), &msg)? .into(), ), _ => Err(PrivateEncryptDecryptError::UnknownPadding), } } #[op2(fast)] #[smi] pub fn op_node_create_cipheriv( state: &mut OpState, #[string] algorithm: &str, #[buffer] key: &[u8], #[buffer] iv: &[u8], #[smi] auth_tag_length: i32, ) -> Result<u32, cipher::CipherContextError> { let auth_tag_length = if auth_tag_length == -1 { None } else { Some(auth_tag_length as usize) }; let context = cipher::CipherContext::new(algorithm, key, iv, auth_tag_length)?; Ok(state.resource_table.add(context)) } #[op2(fast)] pub fn op_node_cipheriv_set_aad( state: &mut OpState, #[smi] rid: u32, #[buffer] aad: &[u8], ) -> bool { let context = match state.resource_table.get::<cipher::CipherContext>(rid) { Ok(context) => context, Err(_) => return false, }; context.set_aad(aad); true } #[op2(fast)] pub fn op_node_cipheriv_encrypt( state: &mut OpState, #[smi] rid: u32, #[buffer] input: &[u8], #[buffer] output: &mut [u8], ) -> bool { let context = match state.resource_table.get::<cipher::CipherContext>(rid) { Ok(context) => context, Err(_) => return false, }; context.encrypt(input, output); true } #[op2] #[serde] pub fn op_node_cipheriv_final( state: &mut OpState, #[smi] rid: u32, auto_pad: bool, #[buffer] input: &[u8], #[anybuffer] output: &mut [u8], ) -> Result<Option<Vec<u8>>, cipher::CipherContextError> { let context = state.resource_table.take::<cipher::CipherContext>(rid)?; let context = Rc::try_unwrap(context) .map_err(|_| cipher::CipherContextError::ContextInUse)?; context.r#final(auto_pad, input, output) } #[op2] #[buffer] pub fn op_node_cipheriv_take( state: &mut OpState, #[smi] rid: u32, ) -> Result<Option<Vec<u8>>, cipher::CipherContextError> { let context = state.resource_table.take::<cipher::CipherContext>(rid)?; let context = Rc::try_unwrap(context) .map_err(|_| cipher::CipherContextError::ContextInUse)?; Ok(context.take_tag()) } #[op2(fast)] #[smi] pub fn op_node_create_decipheriv( state: &mut OpState, #[string] algorithm: &str, #[buffer] key: &[u8], #[buffer] iv: &[u8], #[smi] auth_tag_length: i32, ) -> Result<u32, cipher::DecipherContextError> { let auth_tag_length = if auth_tag_length == -1 { None } else { Some(auth_tag_length as usize) }; let context = cipher::DecipherContext::new(algorithm, key, iv, auth_tag_length)?; Ok(state.resource_table.add(context)) } #[op2(fast)] pub fn op_node_decipheriv_auth_tag( state: &mut OpState, #[smi] rid: u32, #[smi] length: u32, ) -> Result<(), cipher::DecipherContextError> { let context = state.resource_table.get::<cipher::DecipherContext>(rid)?; context.validate_auth_tag(length as usize) } #[op2(fast)] pub fn op_node_decipheriv_set_aad( state: &mut OpState, #[smi] rid: u32, #[buffer] aad: &[u8], ) -> bool { let context = match state.resource_table.get::<cipher::DecipherContext>(rid) { Ok(context) => context, Err(_) => return false, }; context.set_aad(aad); true } #[op2(fast)] pub fn op_node_decipheriv_decrypt( state: &mut OpState, #[smi] rid: u32, #[buffer] input: &[u8], #[buffer] output: &mut [u8], ) -> bool { let context = match state.resource_table.get::<cipher::DecipherContext>(rid) { Ok(context) => context, Err(_) => return false, }; context.decrypt(input, output); true } #[op2] pub fn op_node_decipheriv_final( state: &mut OpState, #[smi] rid: u32, auto_pad: bool, #[buffer] input: &[u8], #[anybuffer] output: &mut [u8], #[buffer] auth_tag: &[u8], ) -> Result<(), cipher::DecipherContextError> { let context = state.resource_table.take::<cipher::DecipherContext>(rid)?; let context = Rc::try_unwrap(context) .map_err(|_| cipher::DecipherContextError::ContextInUse)?; context.r#final(auto_pad, input, output, auth_tag) } #[op2] #[buffer] pub fn op_node_sign( #[cppgc] handle: &KeyObjectHandle, #[buffer] digest: &[u8], #[string] digest_type: &str, #[smi] pss_salt_length: Option<u32>, #[smi] dsa_signature_encoding: u32, ) -> Result<Box<[u8]>, sign::KeyObjectHandlePrehashedSignAndVerifyError> { handle.sign_prehashed( digest_type, digest, pss_salt_length, dsa_signature_encoding, ) } #[op2] pub fn op_node_verify( #[cppgc] handle: &KeyObjectHandle, #[buffer] digest: &[u8], #[string] digest_type: &str, #[buffer] signature: &[u8], #[smi] pss_salt_length: Option<u32>, #[smi] dsa_signature_encoding: u32, ) -> Result<bool, sign::KeyObjectHandlePrehashedSignAndVerifyError> { handle.verify_prehashed( digest_type, digest, signature, pss_salt_length, dsa_signature_encoding, ) } #[derive(Debug, PartialEq, Eq)] #[allow(non_camel_case_types)] enum ErrorCode { ERR_CRYPTO_INVALID_DIGEST, } impl std::fmt::Display for ErrorCode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.as_str()) } } impl ErrorCode { pub fn as_str(&self) -> &str { match self { Self::ERR_CRYPTO_INVALID_DIGEST => "ERR_CRYPTO_INVALID_DIGEST", } } } impl From<ErrorCode> for deno_error::PropertyValue { fn from(code: ErrorCode) -> Self { deno_error::PropertyValue::from(code.as_str().to_string()) } } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum Pbkdf2Error { #[class(type)] #[error("Invalid digest: {0}")] #[property("code" = self.code())] UnsupportedDigest(String), #[class(inherit)] #[error(transparent)] Join(#[from] tokio::task::JoinError), } impl Pbkdf2Error { fn code(&self) -> ErrorCode { match self { Self::UnsupportedDigest(_) => ErrorCode::ERR_CRYPTO_INVALID_DIGEST, Self::Join(_) => unreachable!(), } } } fn pbkdf2_sync( password: &[u8], salt: &[u8], iterations: u32, algorithm_name: &str, derived_key: &mut [u8], ) -> Result<(), Pbkdf2Error> { match_fixed_digest_with_eager_block_buffer!( algorithm_name, fn <D>() { pbkdf2::pbkdf2_hmac::<D>(password, salt, iterations, derived_key); Ok(()) }, _ => { Err(Pbkdf2Error::UnsupportedDigest(algorithm_name.to_string())) } ) } #[op2] pub fn op_node_pbkdf2( #[anybuffer] password: &[u8], #[anybuffer] salt: &[u8], #[smi] iterations: u32, #[string] digest: &str, #[buffer] derived_key: &mut [u8], ) -> bool { pbkdf2_sync(password, salt, iterations, digest, derived_key).is_ok() } #[op2(fast)] pub fn op_node_pbkdf2_validate( #[string] digest: &str, ) -> Result<(), Pbkdf2Error> { // Validate the digest algorithm name match_fixed_digest_with_eager_block_buffer!( digest, fn <_D>() { Ok(()) }, _ => { Err(Pbkdf2Error::UnsupportedDigest(digest.to_string())) } ) } #[op2(async)] #[serde] pub async fn op_node_pbkdf2_async( #[anybuffer] password: JsBuffer, #[anybuffer] salt: JsBuffer, #[smi] iterations: u32, #[string] digest: String, #[number] keylen: usize, ) -> Result<ToJsBuffer, Pbkdf2Error> { spawn_blocking(move || { let mut derived_key = vec![0; keylen]; pbkdf2_sync(&password, &salt, iterations, &digest, &mut derived_key) .map(|_| derived_key.into()) }) .await? } #[op2(fast)] pub fn op_node_fill_random(#[buffer] buf: &mut [u8]) { rand::thread_rng().fill(buf); } #[op2(async)] #[serde] pub async fn op_node_fill_random_async(#[smi] len: i32) -> ToJsBuffer { spawn_blocking(move || { let mut buf = vec![0u8; len as usize]; rand::thread_rng().fill(&mut buf[..]); buf.into() }) .await .unwrap() } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum HkdfError { #[class(type)] #[error("expected secret key")] ExpectedSecretKey, #[class(type)] #[error("HKDF-Expand failed")] HkdfExpandFailed, #[class(type)] #[error("Unsupported digest: {0}")] UnsupportedDigest(String), #[class(inherit)] #[error(transparent)] Join(#[from] tokio::task::JoinError), } fn hkdf_sync( digest_algorithm: &str, handle: &KeyObjectHandle, salt: &[u8], info: &[u8], okm: &mut [u8], ) -> Result<(), HkdfError> { let Some(ikm) = handle.as_secret_key() else { return Err(HkdfError::ExpectedSecretKey); }; match_fixed_digest_with_eager_block_buffer!( digest_algorithm, fn <D>() { let hk = Hkdf::<D>::new(Some(salt), ikm); hk.expand(info, okm) .map_err(|_| HkdfError::HkdfExpandFailed) }, _ => { Err(HkdfError::UnsupportedDigest(digest_algorithm.to_string())) } ) } #[op2(fast)] pub fn op_node_hkdf( #[string] digest_algorithm: &str, #[cppgc] handle: &KeyObjectHandle, #[buffer] salt: &[u8], #[buffer] info: &[u8], #[buffer] okm: &mut [u8], ) -> Result<(), HkdfError> { hkdf_sync(digest_algorithm, handle, salt, info, okm) } #[op2(async)] #[serde] pub async fn op_node_hkdf_async( #[string] digest_algorithm: String, #[cppgc] handle: &KeyObjectHandle, #[buffer] salt: JsBuffer, #[buffer] info: JsBuffer, #[number] okm_len: usize, ) -> Result<ToJsBuffer, HkdfError> { let handle = handle.clone(); spawn_blocking(move || { let mut okm = vec![0u8; okm_len]; hkdf_sync(&digest_algorithm, &handle, &salt, &info, &mut okm)?; Ok(okm.into()) }) .await? } #[op2] #[serde] pub fn op_node_dh_compute_secret( #[buffer] prime: JsBuffer, #[buffer] private_key: JsBuffer, #[buffer] their_public_key: JsBuffer, ) -> ToJsBuffer { let pubkey: BigUint = BigUint::from_bytes_be(their_public_key.as_ref()); let privkey: BigUint = BigUint::from_bytes_be(private_key.as_ref()); let primei: BigUint = BigUint::from_bytes_be(prime.as_ref()); let shared_secret: BigUint = pubkey.modpow(&privkey, &primei); shared_secret.to_bytes_be().into() } #[op2(fast)] #[number] pub fn op_node_random_int(#[number] min: i64, #[number] max: i64) -> i64 { let mut rng = rand::thread_rng(); // Uniform distribution is required to avoid Modulo Bias // https://en.wikipedia.org/wiki/Fisher–Yates_shuffle#Modulo_bias let dist = Uniform::from(min..max); dist.sample(&mut rng) } #[allow(clippy::too_many_arguments)] fn scrypt( password: StringOrBuffer, salt: StringOrBuffer, keylen: u32, cost: u32, block_size: u32, parallelization: u32, _maxmem: u32, output_buffer: &mut [u8], ) -> Result<(), JsErrorBox> { // Construct Params let params = scrypt::Params::new( cost as u8, block_size, parallelization, keylen as usize, ) .map_err(|_| JsErrorBox::generic("Invalid scrypt param"))?; // Call into scrypt let res = scrypt::scrypt(&password, &salt, &params, output_buffer); if res.is_ok() { Ok(()) } else { // TODO(lev): key derivation failed, so what? Err(JsErrorBox::generic("scrypt key derivation failed")) } } #[allow(clippy::too_many_arguments)] #[op2] pub fn op_node_scrypt_sync( #[serde] password: StringOrBuffer, #[serde] salt: StringOrBuffer, #[smi] keylen: u32, #[smi] cost: u32, #[smi] block_size: u32, #[smi] parallelization: u32, #[smi] maxmem: u32, #[anybuffer] output_buffer: &mut [u8], ) -> Result<(), JsErrorBox> { scrypt( password, salt, keylen, cost, block_size, parallelization, maxmem, output_buffer, ) } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum ScryptAsyncError { #[class(inherit)] #[error(transparent)] Join(#[from] tokio::task::JoinError), #[class(inherit)] #[error(transparent)] Other(JsErrorBox), } #[op2(async)] #[serde] pub async fn op_node_scrypt_async( #[serde] password: StringOrBuffer, #[serde] salt: StringOrBuffer, #[smi] keylen: u32, #[smi] cost: u32, #[smi] block_size: u32, #[smi] parallelization: u32, #[smi] maxmem: u32, ) -> Result<ToJsBuffer, ScryptAsyncError> { spawn_blocking(move || { let mut output_buffer = vec![0u8; keylen as usize]; scrypt( password, salt, keylen, cost, block_size, parallelization, maxmem, &mut output_buffer, ) .map(|_| output_buffer.into()) .map_err(ScryptAsyncError::Other) }) .await? } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum EcdhEncodePubKey { #[class(type)] #[error("Invalid public key")] InvalidPublicKey, #[class(type)] #[error("Unsupported curve")] UnsupportedCurve, #[class(generic)] #[error(transparent)] Sec1(#[from] sec1::Error), } #[op2] #[buffer] pub fn op_node_ecdh_encode_pubkey( #[string] curve: &str, #[buffer] pubkey: &[u8], compress: bool, ) -> Result<Vec<u8>, EcdhEncodePubKey> { use elliptic_curve::sec1::FromEncodedPoint; match curve { "secp256k1" => { let pubkey = elliptic_curve::PublicKey::<k256::Secp256k1>::from_encoded_point( &elliptic_curve::sec1::EncodedPoint::<k256::Secp256k1>::from_bytes( pubkey, )?, ); // CtOption does not expose its variants. if pubkey.is_none().into() { return Err(EcdhEncodePubKey::InvalidPublicKey); } let pubkey = pubkey.unwrap(); Ok(pubkey.to_encoded_point(compress).as_ref().to_vec()) } "prime256v1" | "secp256r1" => { let pubkey = elliptic_curve::PublicKey::<NistP256>::from_encoded_point( &elliptic_curve::sec1::EncodedPoint::<NistP256>::from_bytes(pubkey)?, ); // CtOption does not expose its variants. if pubkey.is_none().into() { return Err(EcdhEncodePubKey::InvalidPublicKey); } let pubkey = pubkey.unwrap(); Ok(pubkey.to_encoded_point(compress).as_ref().to_vec()) } "secp384r1" => { let pubkey = elliptic_curve::PublicKey::<NistP384>::from_encoded_point( &elliptic_curve::sec1::EncodedPoint::<NistP384>::from_bytes(pubkey)?, ); // CtOption does not expose its variants. if pubkey.is_none().into() { return Err(EcdhEncodePubKey::InvalidPublicKey); } let pubkey = pubkey.unwrap(); Ok(pubkey.to_encoded_point(compress).as_ref().to_vec()) } "secp224r1" => { let pubkey = elliptic_curve::PublicKey::<NistP224>::from_encoded_point( &elliptic_curve::sec1::EncodedPoint::<NistP224>::from_bytes(pubkey)?, ); // CtOption does not expose its variants. if pubkey.is_none().into() { return Err(EcdhEncodePubKey::InvalidPublicKey); } let pubkey = pubkey.unwrap(); Ok(pubkey.to_encoded_point(compress).as_ref().to_vec()) } &_ => Err(EcdhEncodePubKey::UnsupportedCurve), } } #[op2(fast)] pub fn op_node_ecdh_generate_keys( #[string] curve: &str, #[buffer] pubbuf: &mut [u8], #[buffer] privbuf: &mut [u8], #[string] format: &str, ) -> Result<(), JsErrorBox> { let mut rng = rand::thread_rng(); let compress = format == "compressed"; match curve { "secp256k1" => { let privkey = elliptic_curve::SecretKey::<k256::Secp256k1>::random(&mut rng); let pubkey = privkey.public_key(); pubbuf.copy_from_slice(pubkey.to_encoded_point(compress).as_ref()); privbuf.copy_from_slice(privkey.to_nonzero_scalar().to_bytes().as_ref()); Ok(()) } "prime256v1" | "secp256r1" => { let privkey = elliptic_curve::SecretKey::<NistP256>::random(&mut rng); let pubkey = privkey.public_key(); pubbuf.copy_from_slice(pubkey.to_encoded_point(compress).as_ref()); privbuf.copy_from_slice(privkey.to_nonzero_scalar().to_bytes().as_ref()); Ok(()) } "secp384r1" => { let privkey = elliptic_curve::SecretKey::<NistP384>::random(&mut rng); let pubkey = privkey.public_key(); pubbuf.copy_from_slice(pubkey.to_encoded_point(compress).as_ref()); privbuf.copy_from_slice(privkey.to_nonzero_scalar().to_bytes().as_ref()); Ok(()) } "secp224r1" => { let privkey = elliptic_curve::SecretKey::<NistP224>::random(&mut rng); let pubkey = privkey.public_key(); pubbuf.copy_from_slice(pubkey.to_encoded_point(compress).as_ref()); privbuf.copy_from_slice(privkey.to_nonzero_scalar().to_bytes().as_ref()); Ok(()) } &_ => Err(JsErrorBox::type_error(format!( "Unsupported curve: {}", curve ))), } } #[op2] pub fn op_node_ecdh_compute_secret( #[string] curve: &str, #[buffer] this_priv: Option<JsBuffer>, #[buffer] their_pub: &mut [u8], #[buffer] secret: &mut [u8], ) { match curve { "secp256k1" => { let their_public_key = elliptic_curve::PublicKey::<k256::Secp256k1>::from_sec1_bytes( their_pub, ) .expect("bad public key"); let this_private_key = elliptic_curve::SecretKey::<k256::Secp256k1>::from_slice( &this_priv.expect("must supply private key"), ) .expect("bad private key"); let shared_secret = elliptic_curve::ecdh::diffie_hellman( this_private_key.to_nonzero_scalar(), their_public_key.as_affine(), ); secret.copy_from_slice(shared_secret.raw_secret_bytes()); } "prime256v1" | "secp256r1" => { let their_public_key = elliptic_curve::PublicKey::<NistP256>::from_sec1_bytes(their_pub) .expect("bad public key"); let this_private_key = elliptic_curve::SecretKey::<NistP256>::from_slice( &this_priv.expect("must supply private key"), ) .expect("bad private key"); let shared_secret = elliptic_curve::ecdh::diffie_hellman( this_private_key.to_nonzero_scalar(), their_public_key.as_affine(), ); secret.copy_from_slice(shared_secret.raw_secret_bytes()); } "secp384r1" => { let their_public_key = elliptic_curve::PublicKey::<NistP384>::from_sec1_bytes(their_pub) .expect("bad public key"); let this_private_key = elliptic_curve::SecretKey::<NistP384>::from_slice( &this_priv.expect("must supply private key"), ) .expect("bad private key"); let shared_secret = elliptic_curve::ecdh::diffie_hellman( this_private_key.to_nonzero_scalar(), their_public_key.as_affine(), ); secret.copy_from_slice(shared_secret.raw_secret_bytes()); } "secp224r1" => { let their_public_key = elliptic_curve::PublicKey::<NistP224>::from_sec1_bytes(their_pub) .expect("bad public key"); let this_private_key = elliptic_curve::SecretKey::<NistP224>::from_slice( &this_priv.expect("must supply private key"), ) .expect("bad private key"); let shared_secret = elliptic_curve::ecdh::diffie_hellman( this_private_key.to_nonzero_scalar(), their_public_key.as_affine(), ); secret.copy_from_slice(shared_secret.raw_secret_bytes()); } &_ => todo!(), } } #[op2(fast)] pub fn op_node_ecdh_compute_public_key( #[string] curve: &str, #[buffer] privkey: &[u8], #[buffer] pubkey: &mut [u8], ) { match curve { "secp256k1" => { let this_private_key = elliptic_curve::SecretKey::<k256::Secp256k1>::from_slice(privkey) .expect("bad private key"); let public_key = this_private_key.public_key(); pubkey.copy_from_slice(public_key.to_sec1_bytes().as_ref()); } "prime256v1" | "secp256r1" => { let this_private_key = elliptic_curve::SecretKey::<NistP256>::from_slice(privkey) .expect("bad private key"); let public_key = this_private_key.public_key(); pubkey.copy_from_slice(public_key.to_sec1_bytes().as_ref()); } "secp384r1" => { let this_private_key = elliptic_curve::SecretKey::<NistP384>::from_slice(privkey) .expect("bad private key"); let public_key = this_private_key.public_key(); pubkey.copy_from_slice(public_key.to_sec1_bytes().as_ref()); } "secp224r1" => { let this_private_key = elliptic_curve::SecretKey::<NistP224>::from_slice(privkey) .expect("bad private key"); let public_key = this_private_key.public_key(); pubkey.copy_from_slice(public_key.to_sec1_bytes().as_ref()); } &_ => todo!(), } } #[inline] fn gen_prime(size: usize) -> ToJsBuffer { primes::Prime::generate(size).0.to_bytes_be().into() } #[op2] #[serde] pub fn op_node_gen_prime(#[number] size: usize) -> ToJsBuffer { gen_prime(size) } #[op2(async)] #[serde] pub async fn op_node_gen_prime_async( #[number] size: usize, ) -> Result<ToJsBuffer, tokio::task::JoinError> { spawn_blocking(move || gen_prime(size)).await } #[derive(Debug, thiserror::Error, deno_error::JsError)] #[class(type)] pub enum DiffieHellmanError { #[error("Expected private key")] ExpectedPrivateKey, #[error("Expected public key")] ExpectedPublicKey, #[error("DH parameters mismatch")] DhParametersMismatch, #[error("Unsupported key type for diffie hellman, or key type mismatch")] UnsupportedKeyTypeForDiffieHellmanOrKeyTypeMismatch, } #[op2] #[buffer] pub fn op_node_diffie_hellman( #[cppgc] private: &KeyObjectHandle, #[cppgc] public: &KeyObjectHandle, ) -> Result<Box<[u8]>, DiffieHellmanError> { let private = private .as_private_key() .ok_or(DiffieHellmanError::ExpectedPrivateKey)?; let public = public .as_public_key() .ok_or(DiffieHellmanError::ExpectedPublicKey)?; let res = match (private, &*public) { ( AsymmetricPrivateKey::Ec(EcPrivateKey::P224(private)), AsymmetricPublicKey::Ec(EcPublicKey::P224(public)), ) => p224::ecdh::diffie_hellman( private.to_nonzero_scalar(), public.as_affine(), ) .raw_secret_bytes() .to_vec() .into_boxed_slice(), ( AsymmetricPrivateKey::Ec(EcPrivateKey::P256(private)), AsymmetricPublicKey::Ec(EcPublicKey::P256(public)), ) => p256::ecdh::diffie_hellman( private.to_nonzero_scalar(), public.as_affine(), ) .raw_secret_bytes() .to_vec() .into_boxed_slice(), ( AsymmetricPrivateKey::Ec(EcPrivateKey::P384(private)), AsymmetricPublicKey::Ec(EcPublicKey::P384(public)), ) => p384::ecdh::diffie_hellman( private.to_nonzero_scalar(), public.as_affine(), ) .raw_secret_bytes() .to_vec() .into_boxed_slice(), ( AsymmetricPrivateKey::X25519(private), AsymmetricPublicKey::X25519(public), ) => private .diffie_hellman(public) .to_bytes() .into_iter() .collect(), (AsymmetricPrivateKey::Dh(private), AsymmetricPublicKey::Dh(public)) => { if private.params.prime != public.params.prime || private.params.base != public.params.base { return Err(DiffieHellmanError::DhParametersMismatch); } // OSIP - Octet-String-to-Integer primitive let public_key = public.key.clone().into_vec(); let pubkey = BigUint::from_bytes_be(&public_key); // Exponentiation (z = y^x mod p) let prime = BigUint::from_bytes_be(private.params.prime.as_bytes()); let private_key = private.key.clone().into_vec(); let private_key = BigUint::from_bytes_be(&private_key); let shared_secret = pubkey.modpow(&private_key, &prime); shared_secret.to_bytes_be().into() } _ => return Err( DiffieHellmanError::UnsupportedKeyTypeForDiffieHellmanOrKeyTypeMismatch, ), }; Ok(res) } #[derive(Debug, thiserror::Error, deno_error::JsError)] #[class(type)] pub enum SignEd25519Error { #[error("Expected private key")] ExpectedPrivateKey, #[error("Expected Ed25519 private key")] ExpectedEd25519PrivateKey, #[error("Invalid Ed25519 private key")] InvalidEd25519PrivateKey, } #[op2(fast)] pub fn op_node_sign_ed25519( #[cppgc] key: &KeyObjectHandle, #[buffer] data: &[u8], #[buffer] signature: &mut [u8], ) -> Result<(), SignEd25519Error> { let private = key .as_private_key() .ok_or(SignEd25519Error::ExpectedPrivateKey)?; let ed25519 = match private { AsymmetricPrivateKey::Ed25519(private) => private, _ => return Err(SignEd25519Error::ExpectedEd25519PrivateKey), }; let pair = Ed25519KeyPair::from_seed_unchecked(ed25519.as_bytes().as_slice()) .map_err(|_| SignEd25519Error::InvalidEd25519PrivateKey)?; signature.copy_from_slice(pair.sign(data).as_ref()); Ok(()) } #[derive(Debug, thiserror::Error, deno_error::JsError)] #[class(type)] pub enum VerifyEd25519Error { #[error("Expected public key")] ExpectedPublicKey, #[error("Expected Ed25519 public key")] ExpectedEd25519PublicKey, } #[op2(fast)] pub fn op_node_verify_ed25519( #[cppgc] key: &KeyObjectHandle, #[buffer] data: &[u8], #[buffer] signature: &[u8], ) -> Result<bool, VerifyEd25519Error> { let public = key .as_public_key() .ok_or(VerifyEd25519Error::ExpectedPublicKey)?; let ed25519 = match &*public { AsymmetricPublicKey::Ed25519(public) => public, _ => return Err(VerifyEd25519Error::ExpectedEd25519PublicKey), }; let verified = aws_lc_rs::signature::UnparsedPublicKey::new( &aws_lc_rs::signature::ED25519, ed25519.as_bytes().as_slice(), ) .verify(data, signature) .is_ok(); Ok(verified) } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum SpkacError { #[error("spkac is too large")] #[property("code" = "ERR_OUT_OF_RANGE")] #[class(range)] BufferOutOfRange, } #[op2(fast)] pub fn op_node_verify_spkac( #[buffer] spkac: &[u8], ) -> Result<bool, SpkacError> { if spkac.len() > i32::MAX as usize { return Err(SpkacError::BufferOutOfRange); } Ok(deno_crypto_provider::spki::verify_spkac(spkac)) } #[op2] #[buffer] pub fn op_node_cert_export_public_key( #[buffer] spkac: &[u8], ) -> Result<Option<Vec<u8>>, SpkacError> { if spkac.len() > i32::MAX as usize { return Err(SpkacError::BufferOutOfRange); } Ok(deno_crypto_provider::spki::export_public_key(spkac)) } #[op2] #[buffer] pub fn op_node_cert_export_challenge( #[buffer] spkac: &[u8], ) -> Result<Option<Vec<u8>>, SpkacError> { if spkac.len() > i32::MAX as usize { return Err(SpkacError::BufferOutOfRange); } Ok(deno_crypto_provider::spki::export_challenge(spkac)) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/crypto/pkcs3.rs
ext/node/ops/crypto/pkcs3.rs
// Copyright 2018-2025 the Deno authors. MIT license. // // PKCS #3: Diffie-Hellman Key Agreement Standard use der::Sequence; use spki::der; use spki::der::asn1; // The parameters fields associated with OID dhKeyAgreement // // DHParameter ::= SEQUENCE { // prime INTEGER, -- p // base INTEGER, -- g // privateValueLength INTEGER OPTIONAL } #[derive(Clone, Sequence)] pub struct DhParameter { pub prime: asn1::Int, pub base: asn1::Int, pub private_value_length: Option<asn1::Int>, }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/crypto/x509.rs
ext/node/ops/crypto/x509.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ops::Deref; use deno_core::ToJsBuffer; use deno_core::op2; use digest::Digest; use x509_parser::der_parser::asn1_rs::Any; use x509_parser::der_parser::asn1_rs::Tag; use x509_parser::der_parser::oid::Oid; pub use x509_parser::error::X509Error; use x509_parser::extensions; use x509_parser::pem; use x509_parser::prelude::*; use yoke::Yoke; use yoke::Yokeable; use super::KeyObjectHandle; enum CertificateSources { Der(Box<[u8]>), Pem(pem::Pem), } #[derive(serde::Serialize, Default)] #[serde(rename_all = "UPPERCASE")] struct SubjectOrIssuer { #[serde(skip_serializing_if = "Option::is_none")] c: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] st: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] l: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] o: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] ou: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] cn: Option<String>, } #[derive(serde::Serialize)] pub struct CertificateObject { ca: bool, raw: ToJsBuffer, subject: SubjectOrIssuer, issuer: SubjectOrIssuer, valid_from: String, valid_to: String, #[serde(rename = "serialNumber")] serial_number: String, fingerprint: String, fingerprint256: String, fingerprint512: String, subjectaltname: String, // RSA key fields #[serde(skip_serializing_if = "Option::is_none")] bits: Option<u32>, #[serde(skip_serializing_if = "Option::is_none")] exponent: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] modulus: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pubkey: Option<ToJsBuffer>, // EC key fields #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "asn1Curve")] asn1_curve: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "nistCurve")] nist_curve: Option<String>, } #[derive(Yokeable)] struct CertificateView<'a> { cert: X509Certificate<'a>, } pub(crate) struct Certificate { inner: Yoke<CertificateView<'static>, Box<CertificateSources>>, } // SAFETY: we're sure this can be GCed unsafe impl deno_core::GarbageCollected for Certificate { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"Certificate" } } impl Certificate { pub fn from_der(der: &[u8]) -> Result<Certificate, X509Error> { let source = CertificateSources::Der(der.to_vec().into_boxed_slice()); let inner = Yoke::<CertificateView<'static>, Box<CertificateSources>>::try_attach_to_cart( Box::new(source), |source| { let cert = match source { CertificateSources::Der(buf) => { X509Certificate::from_der(buf).map(|(_, cert)| cert)? } _ => unreachable!(), }; Ok::<_, X509Error>(CertificateView { cert }) }, )?; Ok(Certificate { inner }) } fn fingerprint<D: Digest>(&self) -> Option<String> { let data = match self.inner.backing_cart().as_ref() { CertificateSources::Pem(pem) => &pem.contents, CertificateSources::Der(der) => der.as_ref(), }; let mut hasher = D::new(); hasher.update(data); let bytes = hasher.finalize(); // OpenSSL returns colon separated upper case hex values. let mut hex = String::with_capacity(bytes.len() * 2); for byte in bytes { hex.push_str(&format!("{:02X}:", byte)); } hex.pop(); Some(hex) } pub fn to_object( &self, _detailed: bool, ) -> Result<CertificateObject, X509Error> { let cert = self.inner.get().deref(); let raw = match self.inner.backing_cart().as_ref() { CertificateSources::Pem(pem) => pem.contents.clone(), CertificateSources::Der(der) => der.to_vec(), }; let valid_from = cert.validity().not_before.to_string(); let valid_to = cert.validity().not_after.to_string(); let mut serial_number = cert.serial.to_str_radix(16); serial_number.make_ascii_uppercase(); let fingerprint = self.fingerprint::<sha1::Sha1>().unwrap_or_default(); let fingerprint256 = self.fingerprint::<sha2::Sha256>().unwrap_or_default(); let fingerprint512 = self.fingerprint::<sha2::Sha512>().unwrap_or_default(); let mut subjectaltname = String::new(); if let Some(subject_alt) = cert .extensions() .iter() .find(|e| { e.oid == x509_parser::oid_registry::OID_X509_EXT_SUBJECT_ALT_NAME }) .and_then(|e| match e.parsed_extension() { extensions::ParsedExtension::SubjectAlternativeName(s) => Some(s), _ => None, }) { let mut alt_names = Vec::new(); for name in &subject_alt.general_names { match name { extensions::GeneralName::DNSName(dns) => { alt_names.push(format!("DNS:{}", dns)); } extensions::GeneralName::RFC822Name(email) => { alt_names.push(format!("email:{}", email)); } extensions::GeneralName::IPAddress(ip) => { alt_names.push(format!( "IP Address:{}", data_encoding::HEXUPPER.encode(ip) )); } _ => {} } } subjectaltname = alt_names.join(", "); } let subject = extract_subject_or_issuer(cert.subject()); let issuer = extract_subject_or_issuer(cert.issuer()); let KeyInfo { bits, exponent, modulus, pubkey, asn1_curve, nist_curve, } = extract_key_info(&cert.tbs_certificate.subject_pki); Ok(CertificateObject { ca: cert.is_ca(), raw: raw.into(), subject, issuer, valid_from, valid_to, serial_number, fingerprint, fingerprint256, fingerprint512, subjectaltname, bits, exponent, modulus, pubkey: pubkey.map(|p| p.into()), asn1_curve, nist_curve, }) } } impl<'a> Deref for CertificateView<'a> { type Target = X509Certificate<'a>; fn deref(&self) -> &Self::Target { &self.cert } } deno_error::js_error_wrapper!(X509Error, JsX509Error, "Error"); #[op2] #[cppgc] pub fn op_node_x509_parse( #[buffer] buf: &[u8], ) -> Result<Certificate, JsX509Error> { let source = match pem::parse_x509_pem(buf) { Ok((_, pem)) => CertificateSources::Pem(pem), Err(_) => CertificateSources::Der(buf.to_vec().into_boxed_slice()), }; let inner = Yoke::<CertificateView<'static>, Box<CertificateSources>>::try_attach_to_cart( Box::new(source), |source| { let cert = match source { CertificateSources::Pem(pem) => pem.parse_x509()?, CertificateSources::Der(buf) => { X509Certificate::from_der(buf).map(|(_, cert)| cert)? } }; Ok::<_, X509Error>(CertificateView { cert }) }, )?; Ok(Certificate { inner }) } #[op2(fast)] pub fn op_node_x509_ca(#[cppgc] cert: &Certificate) -> bool { let cert = cert.inner.get().deref(); cert.is_ca() } #[op2(fast)] pub fn op_node_x509_check_email( #[cppgc] cert: &Certificate, #[string] email: &str, ) -> bool { let cert = cert.inner.get().deref(); let subject = cert.subject(); if subject .iter_email() .any(|e| e.as_str().unwrap_or("") == email) { return true; } let subject_alt = cert .extensions() .iter() .find(|e| e.oid == x509_parser::oid_registry::OID_X509_EXT_SUBJECT_ALT_NAME) .and_then(|e| match e.parsed_extension() { extensions::ParsedExtension::SubjectAlternativeName(s) => Some(s), _ => None, }); if let Some(subject_alt) = subject_alt { for name in &subject_alt.general_names { if let extensions::GeneralName::RFC822Name(n) = name && *n == email { return true; } } } false } #[op2(fast)] pub fn op_node_x509_check_host( #[cppgc] cert: &Certificate, #[string] host: &str, ) -> bool { let cert = cert.inner.get().deref(); let subject = cert.subject(); if subject .iter_common_name() .any(|e| e.as_str().unwrap_or("") == host) { return true; } let subject_alt = cert .extensions() .iter() .find(|e| e.oid == x509_parser::oid_registry::OID_X509_EXT_SUBJECT_ALT_NAME) .and_then(|e| match e.parsed_extension() { extensions::ParsedExtension::SubjectAlternativeName(s) => Some(s), _ => None, }); if let Some(subject_alt) = subject_alt { for name in &subject_alt.general_names { if let extensions::GeneralName::DNSName(n) = name && *n == host { return true; } } } false } #[op2] #[string] pub fn op_node_x509_fingerprint(#[cppgc] cert: &Certificate) -> Option<String> { cert.fingerprint::<sha1::Sha1>() } #[op2] #[string] pub fn op_node_x509_fingerprint256( #[cppgc] cert: &Certificate, ) -> Option<String> { cert.fingerprint::<sha2::Sha256>() } #[op2] #[string] pub fn op_node_x509_fingerprint512( #[cppgc] cert: &Certificate, ) -> Option<String> { cert.fingerprint::<sha2::Sha512>() } #[op2] #[string] pub fn op_node_x509_get_issuer( #[cppgc] cert: &Certificate, ) -> Result<String, JsX509Error> { let cert = cert.inner.get().deref(); x509name_to_string(cert.issuer(), oid_registry()).map_err(Into::into) } #[op2] #[string] pub fn op_node_x509_get_subject( #[cppgc] cert: &Certificate, ) -> Result<String, JsX509Error> { let cert = cert.inner.get().deref(); x509name_to_string(cert.subject(), oid_registry()).map_err(Into::into) } #[op2] #[cppgc] pub fn op_node_x509_public_key( #[cppgc] cert: &Certificate, ) -> Result<KeyObjectHandle, super::keys::X509PublicKeyError> { let cert = cert.inner.get().deref(); let public_key = &cert.tbs_certificate.subject_pki; KeyObjectHandle::new_x509_public_key(public_key) } fn extract_subject_or_issuer(name: &X509Name) -> SubjectOrIssuer { let mut result = SubjectOrIssuer::default(); for rdn in name.iter_rdn() { for attr in rdn.iter() { if let Ok(value_str) = attribute_value_to_string(attr.attr_value(), attr.attr_type()) { match attr.attr_type() { oid if oid == &x509_parser::oid_registry::OID_X509_COUNTRY_NAME => { result.c = Some(value_str); } oid if oid == &x509_parser::oid_registry::OID_X509_STATE_OR_PROVINCE_NAME => { result.st = Some(value_str); } oid if oid == &x509_parser::oid_registry::OID_X509_LOCALITY_NAME => { result.l = Some(value_str); } oid if oid == &x509_parser::oid_registry::OID_X509_ORGANIZATION_NAME => { result.o = Some(value_str); } oid if oid == &x509_parser::oid_registry::OID_X509_ORGANIZATIONAL_UNIT => { result.ou = Some(value_str); } oid if oid == &x509_parser::oid_registry::OID_X509_COMMON_NAME => { result.cn = Some(value_str); } _ => {} } } } } result } // Attempt to convert attribute to string. If type is not a string, return value is the hex // encoding of the attribute value fn attribute_value_to_string( attr: &Any, _attr_type: &Oid, ) -> Result<String, X509Error> { // TODO: replace this with helper function, when it is added to asn1-rs match attr.tag() { Tag::NumericString | Tag::BmpString | Tag::VisibleString | Tag::PrintableString | Tag::GeneralString | Tag::ObjectDescriptor | Tag::GraphicString | Tag::T61String | Tag::VideotexString | Tag::Utf8String | Tag::Ia5String => { let s = core::str::from_utf8(attr.data) .map_err(|_| X509Error::InvalidAttributes)?; Ok(s.to_owned()) } _ => { // type is not a string, get slice and convert it to base64 Ok(data_encoding::HEXUPPER.encode(attr.as_bytes())) } } } fn x509name_to_string( name: &X509Name, oid_registry: &oid_registry::OidRegistry, ) -> Result<String, x509_parser::error::X509Error> { // Lifted from https://github.com/rusticata/x509-parser/blob/4d618c2ed6b1fc102df16797545895f7c67ee0fe/src/x509.rs#L543-L566 // since it's a private function (Copyright 2017 Pierre Chifflier) name.iter_rdn().try_fold(String::new(), |acc, rdn| { rdn .iter() .try_fold(String::new(), |acc2, attr| { let val_str = attribute_value_to_string(attr.attr_value(), attr.attr_type())?; // look ABBREV, and if not found, use shortname let abbrev = match oid2abbrev(attr.attr_type(), oid_registry) { Ok(s) => String::from(s), _ => format!("{:?}", attr.attr_type()), }; let rdn = format!("{}={}", abbrev, val_str); match acc2.len() { 0 => Ok(rdn), _ => Ok(acc2 + " + " + rdn.as_str()), } }) .map(|v| match acc.len() { 0 => v, _ => acc + "\n" + v.as_str(), }) }) } #[op2] #[string] pub fn op_node_x509_get_valid_from(#[cppgc] cert: &Certificate) -> String { let cert = cert.inner.get().deref(); cert.validity().not_before.to_string() } #[op2] #[string] pub fn op_node_x509_get_valid_to(#[cppgc] cert: &Certificate) -> String { let cert = cert.inner.get().deref(); cert.validity().not_after.to_string() } #[op2] #[string] pub fn op_node_x509_get_serial_number(#[cppgc] cert: &Certificate) -> String { let cert = cert.inner.get().deref(); let mut s = cert.serial.to_str_radix(16); s.make_ascii_uppercase(); s } #[op2(fast)] pub fn op_node_x509_key_usage(#[cppgc] cert: &Certificate) -> u16 { let cert = cert.inner.get().deref(); let key_usage = cert .extensions() .iter() .find(|e| e.oid == x509_parser::oid_registry::OID_X509_EXT_KEY_USAGE) .and_then(|e| match e.parsed_extension() { extensions::ParsedExtension::KeyUsage(k) => Some(k), _ => None, }); key_usage.map(|k| k.flags).unwrap_or(0) } #[derive(Default)] struct KeyInfo { bits: Option<u32>, exponent: Option<String>, modulus: Option<String>, pubkey: Option<Vec<u8>>, asn1_curve: Option<String>, nist_curve: Option<String>, } fn extract_key_info(spki: &x509_parser::x509::SubjectPublicKeyInfo) -> KeyInfo { use x509_parser::der_parser::asn1_rs::oid; use x509_parser::public_key::PublicKey; match spki.parsed() { Ok(PublicKey::RSA(key)) => { let modulus_bytes = key.modulus; let exponent_bytes = key.exponent; let bits = Some((modulus_bytes.len() * 8) as u32); let modulus = Some(data_encoding::HEXUPPER.encode(modulus_bytes)); let exponent = Some(data_encoding::HEXUPPER.encode(exponent_bytes)); let pubkey = Some(spki.raw.to_vec()); KeyInfo { bits, exponent, modulus, pubkey, asn1_curve: None, nist_curve: None, } } Ok(PublicKey::EC(point)) => { let pubkey = Some(point.data().to_vec()); let mut asn1_curve = None; let mut nist_curve = None; let mut bits = None; if let Some(params) = &spki.algorithm.parameters && let Ok(curve_oid) = params.as_oid() { const ID_SECP224R1: &[u8] = &oid!(raw 1.3.132.0.33); const ID_SECP256R1: &[u8] = &oid!(raw 1.2.840.10045.3.1.7); const ID_SECP384R1: &[u8] = &oid!(raw 1.3.132.0.34); match curve_oid.as_bytes() { ID_SECP224R1 => { asn1_curve = Some("1.3.132.0.33".to_string()); nist_curve = Some("secp224r1".to_string()); bits = Some(224); } ID_SECP256R1 => { asn1_curve = Some("1.2.840.10045.3.1.7".to_string()); nist_curve = Some("secp256r1".to_string()); bits = Some(256); } ID_SECP384R1 => { asn1_curve = Some("1.3.132.0.34".to_string()); nist_curve = Some("secp384r1".to_string()); bits = Some(384); } _ => { asn1_curve = Some(curve_oid.to_string()); } } } KeyInfo { bits, exponent: None, modulus: None, pubkey, asn1_curve, nist_curve, } } _ => KeyInfo::default(), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_extract_subject_or_issuer() { let cert_pem = b"-----BEGIN CERTIFICATE----- MIICljCCAX4CCQCKmSl7UdG4tjANBgkqhkiG9w0BAQsFADANMQswCQYDVQQDDAJD TjAeFw0yNTAxMjIxNzQyNDFaFw0yNjAxMjIxNzQyNDFaMA0xCzAJBgNVBAMMAkNO MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0K/qV+9PQH3Kg2g6tK6X VxY7F8/2YKi8cKnX0YT5g9QnKjS1v8R9kKvR+LLx0Y1+pT8zFZr7BjU1cKxz8fmY 7P+vKH1R3O5p2qKvOxY4GlO6U3cQ1HtQ9TjIGiXn7T6v9BkKH6k8zL4m5W6Kp4s4 tR9J9n4rGY3j6TxC9h3W3d/dW9H6nF9r3oF9F5KvG0p8H0R7WXoO6h4J5m8J5k6b 5K3E7j9O9J1V9R8h4I5k8h0x7P2s1J8F1c5Z5T8l8e0K8N9J0x8Z8r9m0O0k6F0r 9B3G4e2j8d6F8r0t8I2W4K2v4g1g8N6f4j8c9w2r6m8O3J5I5h5E5i7n8d9v3QAU lQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQAWOKj9Z7ZuY8fz8N3bYh8G4kFh2J7R B6QFzT4M6gF3jl6oJ5E3K0k5z7n9L9T5c4p8x5X8f2w8T2r4N8b4y2B8W6z4N5S8 y8M7R4H0t4R8y6S9c8o8r8g8Y8b8J8t6N8p4M3O4K8f8Z7w8P8T8G8N8q8b8H6H8 r6C3V5F4Z9y8o8i9E4j5V8O5Q7Y8Z4W8n7R8B8l8H8L4P4F8r8c8A4v3O4g8L8S6 8r8t3C6h8Y6k8b3F8w8z8H8g8k8m8B3R6K8C6P4R8f8M6g8Z2N8B8x8Z8F3A2N8R 8r8H8x2F8J2h8c8Y8x8H8g8n4l8x4E8r8p8j8S8m6F3k8L8S8z6A8F8k8B9U8L3R -----END CERTIFICATE-----"; let pem = pem::parse_x509_pem(cert_pem).unwrap().1; let cert = Certificate::from_der(&pem.contents).unwrap(); let cert_inner = cert.inner.get().deref(); let result = extract_subject_or_issuer(cert_inner.subject()); assert_eq!(result.cn, Some("CN".to_string())); assert_eq!(result.c, None); assert_eq!(result.st, None); assert_eq!(result.l, None); assert_eq!(result.o, None); assert_eq!(result.ou, None); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/crypto/keys.rs
ext/node/ops/crypto/keys.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use base64::Engine; use deno_core::GarbageCollected; use deno_core::ToJsBuffer; use deno_core::op2; use deno_core::serde_v8::BigInt as V8BigInt; use deno_core::unsync::spawn_blocking; use deno_error::JsErrorBox; use ed25519_dalek::pkcs8::BitStringRef; use elliptic_curve::JwkEcKey; use num_bigint::BigInt; use num_traits::FromPrimitive as _; use pkcs8::DecodePrivateKey as _; use pkcs8::Document; use pkcs8::EncodePrivateKey as _; use pkcs8::EncryptedPrivateKeyInfo; use pkcs8::PrivateKeyInfo; use pkcs8::SecretDocument; use rand::RngCore as _; use rand::thread_rng; use rsa::RsaPrivateKey; use rsa::RsaPublicKey; use rsa::pkcs1::DecodeRsaPrivateKey as _; use rsa::pkcs1::DecodeRsaPublicKey; use rsa::pkcs1::EncodeRsaPrivateKey as _; use rsa::pkcs1::EncodeRsaPublicKey; use rsa::traits::PrivateKeyParts; use rsa::traits::PublicKeyParts; use sec1::DecodeEcPrivateKey as _; use sec1::LineEnding; use sec1::der::Tag; use sec1::der::Writer as _; use sec1::pem::PemLabel as _; use spki::DecodePublicKey as _; use spki::EncodePublicKey as _; use spki::SubjectPublicKeyInfoRef; use spki::der::AnyRef; use spki::der::Decode as _; use spki::der::Encode as _; use spki::der::PemWriter; use spki::der::Reader as _; use spki::der::asn1; use spki::der::asn1::OctetStringRef; use x509_parser::error::X509Error; use x509_parser::x509; use super::dh; use super::dh::DiffieHellmanGroup; use super::digest::match_fixed_digest_with_oid; use super::pkcs3; use super::pkcs3::DhParameter; use super::primes::Prime; #[derive(Clone)] pub enum KeyObjectHandle { AsymmetricPrivate(AsymmetricPrivateKey), AsymmetricPublic(AsymmetricPublicKey), Secret(Box<[u8]>), } // SAFETY: we're sure this can be GCed unsafe impl GarbageCollected for KeyObjectHandle { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"KeyObjectHandle" } } #[derive(Clone)] pub enum AsymmetricPrivateKey { Rsa(RsaPrivateKey), RsaPss(RsaPssPrivateKey), Dsa(dsa::SigningKey), Ec(EcPrivateKey), X25519(x25519_dalek::StaticSecret), Ed25519(ed25519_dalek::SigningKey), Dh(DhPrivateKey), } #[derive(Clone)] pub struct RsaPssPrivateKey { pub key: RsaPrivateKey, pub details: Option<RsaPssDetails>, } #[derive(Clone, Copy)] pub struct RsaPssDetails { pub hash_algorithm: RsaPssHashAlgorithm, pub mf1_hash_algorithm: RsaPssHashAlgorithm, pub salt_length: u32, } #[derive(Clone, Copy, PartialEq, Eq)] pub enum RsaPssHashAlgorithm { Sha1, Sha224, Sha256, Sha384, Sha512, Sha512_224, Sha512_256, } impl RsaPssHashAlgorithm { pub fn as_str(&self) -> &'static str { match self { RsaPssHashAlgorithm::Sha1 => "sha1", RsaPssHashAlgorithm::Sha224 => "sha224", RsaPssHashAlgorithm::Sha256 => "sha256", RsaPssHashAlgorithm::Sha384 => "sha384", RsaPssHashAlgorithm::Sha512 => "sha512", RsaPssHashAlgorithm::Sha512_224 => "sha512-224", RsaPssHashAlgorithm::Sha512_256 => "sha512-256", } } pub fn salt_length(&self) -> u32 { match self { RsaPssHashAlgorithm::Sha1 => 20, RsaPssHashAlgorithm::Sha224 | RsaPssHashAlgorithm::Sha512_224 => 28, RsaPssHashAlgorithm::Sha256 | RsaPssHashAlgorithm::Sha512_256 => 32, RsaPssHashAlgorithm::Sha384 => 48, RsaPssHashAlgorithm::Sha512 => 64, } } } #[derive(Clone)] pub enum EcPrivateKey { P224(p224::SecretKey), P256(p256::SecretKey), P384(p384::SecretKey), } #[derive(Clone)] pub struct DhPrivateKey { pub key: dh::PrivateKey, pub params: DhParameter, } #[derive(Clone)] pub enum AsymmetricPublicKey { Rsa(rsa::RsaPublicKey), RsaPss(RsaPssPublicKey), Dsa(dsa::VerifyingKey), Ec(EcPublicKey), X25519(x25519_dalek::PublicKey), Ed25519(ed25519_dalek::VerifyingKey), Dh(DhPublicKey), } #[derive(Clone)] pub struct RsaPssPublicKey { pub key: rsa::RsaPublicKey, pub details: Option<RsaPssDetails>, } #[derive(Clone)] pub enum EcPublicKey { P224(p224::PublicKey), P256(p256::PublicKey), P384(p384::PublicKey), } #[derive(Clone)] pub struct DhPublicKey { pub key: dh::PublicKey, pub params: DhParameter, } impl KeyObjectHandle { /// Returns the private key if the handle is an asymmetric private key. pub fn as_private_key(&self) -> Option<&AsymmetricPrivateKey> { match self { KeyObjectHandle::AsymmetricPrivate(key) => Some(key), _ => None, } } /// Returns the public key if the handle is an asymmetric public key. If it is /// a private key, it derives the public key from it and returns that. pub fn as_public_key(&self) -> Option<Cow<'_, AsymmetricPublicKey>> { match self { KeyObjectHandle::AsymmetricPrivate(key) => { Some(Cow::Owned(key.to_public_key())) } KeyObjectHandle::AsymmetricPublic(key) => Some(Cow::Borrowed(key)), _ => None, } } /// Returns the secret key if the handle is a secret key. pub fn as_secret_key(&self) -> Option<&[u8]> { match self { KeyObjectHandle::Secret(key) => Some(key), _ => None, } } } impl AsymmetricPrivateKey { /// Derives the public key from the private key. pub fn to_public_key(&self) -> AsymmetricPublicKey { match self { AsymmetricPrivateKey::Rsa(key) => { AsymmetricPublicKey::Rsa(key.to_public_key()) } AsymmetricPrivateKey::RsaPss(key) => { AsymmetricPublicKey::RsaPss(key.to_public_key()) } AsymmetricPrivateKey::Dsa(key) => { AsymmetricPublicKey::Dsa(key.verifying_key().clone()) } AsymmetricPrivateKey::Ec(key) => { AsymmetricPublicKey::Ec(key.to_public_key()) } AsymmetricPrivateKey::X25519(key) => { AsymmetricPublicKey::X25519(x25519_dalek::PublicKey::from(key)) } AsymmetricPrivateKey::Ed25519(key) => { AsymmetricPublicKey::Ed25519(key.verifying_key()) } AsymmetricPrivateKey::Dh(_) => { panic!("cannot derive public key from DH private key") } } } } impl RsaPssPrivateKey { /// Derives the public key from the private key. pub fn to_public_key(&self) -> RsaPssPublicKey { RsaPssPublicKey { key: self.key.to_public_key(), details: self.details, } } } impl EcPublicKey { pub fn to_jwk(&self) -> Result<JwkEcKey, AsymmetricPublicKeyJwkError> { match self { EcPublicKey::P224(_) => { Err(AsymmetricPublicKeyJwkError::UnsupportedJwkEcCurveP224) } EcPublicKey::P256(key) => Ok(key.to_jwk()), EcPublicKey::P384(key) => Ok(key.to_jwk()), } } } impl EcPrivateKey { /// Derives the public key from the private key. pub fn to_public_key(&self) -> EcPublicKey { match self { EcPrivateKey::P224(key) => EcPublicKey::P224(key.public_key()), EcPrivateKey::P256(key) => EcPublicKey::P256(key.public_key()), EcPrivateKey::P384(key) => EcPublicKey::P384(key.public_key()), } } pub fn to_jwk(&self) -> Result<JwkEcKey, AsymmetricPrivateKeyJwkError> { match self { EcPrivateKey::P224(_) => { Err(AsymmetricPrivateKeyJwkError::UnsupportedJwkEcCurveP224) } EcPrivateKey::P256(key) => Ok(key.to_jwk()), EcPrivateKey::P384(key) => Ok(key.to_jwk()), } } } // https://oidref.com/ const ID_SHA1_OID: rsa::pkcs8::ObjectIdentifier = rsa::pkcs8::ObjectIdentifier::new_unwrap("1.3.14.3.2.26"); const ID_SHA224_OID: rsa::pkcs8::ObjectIdentifier = rsa::pkcs8::ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.4"); const ID_SHA256_OID: rsa::pkcs8::ObjectIdentifier = rsa::pkcs8::ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.1"); const ID_SHA384_OID: rsa::pkcs8::ObjectIdentifier = rsa::pkcs8::ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.2"); const ID_SHA512_OID: rsa::pkcs8::ObjectIdentifier = rsa::pkcs8::ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.3"); const ID_SHA512_224_OID: rsa::pkcs8::ObjectIdentifier = rsa::pkcs8::ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.5"); const ID_SHA512_256_OID: rsa::pkcs8::ObjectIdentifier = rsa::pkcs8::ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.6"); const ID_MFG1: rsa::pkcs8::ObjectIdentifier = rsa::pkcs8::ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.8"); pub const ID_SECP224R1_OID: const_oid::ObjectIdentifier = const_oid::ObjectIdentifier::new_unwrap("1.3.132.0.33"); pub const ID_SECP256R1_OID: const_oid::ObjectIdentifier = const_oid::ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7"); pub const ID_SECP384R1_OID: const_oid::ObjectIdentifier = const_oid::ObjectIdentifier::new_unwrap("1.3.132.0.34"); pub const RSA_ENCRYPTION_OID: const_oid::ObjectIdentifier = const_oid::ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1"); pub const RSASSA_PSS_OID: const_oid::ObjectIdentifier = const_oid::ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10"); pub const DSA_OID: const_oid::ObjectIdentifier = const_oid::ObjectIdentifier::new_unwrap("1.2.840.10040.4.1"); pub const EC_OID: const_oid::ObjectIdentifier = const_oid::ObjectIdentifier::new_unwrap("1.2.840.10045.2.1"); pub const X25519_OID: const_oid::ObjectIdentifier = const_oid::ObjectIdentifier::new_unwrap("1.3.101.110"); pub const ED25519_OID: const_oid::ObjectIdentifier = const_oid::ObjectIdentifier::new_unwrap("1.3.101.112"); pub const DH_KEY_AGREEMENT_OID: const_oid::ObjectIdentifier = const_oid::ObjectIdentifier::new_unwrap("1.2.840.113549.1.3.1"); // The parameters field associated with OID id-RSASSA-PSS // Defined in RFC 3447, section A.2.3 // // RSASSA-PSS-params ::= SEQUENCE { // hashAlgorithm [0] HashAlgorithm DEFAULT sha1, // maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT mgf1SHA1, // saltLength [2] INTEGER DEFAULT 20, // trailerField [3] TrailerField DEFAULT trailerFieldBC // } pub struct RsaPssParameters<'a> { pub hash_algorithm: Option<rsa::pkcs8::AlgorithmIdentifierRef<'a>>, pub mask_gen_algorithm: Option<rsa::pkcs8::AlgorithmIdentifierRef<'a>>, pub salt_length: Option<u32>, } // Context-specific tag number for hashAlgorithm. const HASH_ALGORITHM_TAG: rsa::pkcs8::der::TagNumber = rsa::pkcs8::der::TagNumber::new(0); // Context-specific tag number for maskGenAlgorithm. const MASK_GEN_ALGORITHM_TAG: rsa::pkcs8::der::TagNumber = rsa::pkcs8::der::TagNumber::new(1); // Context-specific tag number for saltLength. const SALT_LENGTH_TAG: rsa::pkcs8::der::TagNumber = rsa::pkcs8::der::TagNumber::new(2); impl<'a> TryFrom<rsa::pkcs8::der::asn1::AnyRef<'a>> for RsaPssParameters<'a> { type Error = rsa::pkcs8::der::Error; fn try_from( any: rsa::pkcs8::der::asn1::AnyRef<'a>, ) -> rsa::pkcs8::der::Result<RsaPssParameters<'a>> { any.sequence(|decoder| { let hash_algorithm = decoder .context_specific::<rsa::pkcs8::AlgorithmIdentifierRef>( HASH_ALGORITHM_TAG, pkcs8::der::TagMode::Explicit, )? .map(TryInto::try_into) .transpose()?; let mask_gen_algorithm = decoder .context_specific::<rsa::pkcs8::AlgorithmIdentifierRef>( MASK_GEN_ALGORITHM_TAG, pkcs8::der::TagMode::Explicit, )? .map(TryInto::try_into) .transpose()?; let salt_length = decoder .context_specific::<u32>( SALT_LENGTH_TAG, pkcs8::der::TagMode::Explicit, )? .map(TryInto::try_into) .transpose()?; Ok(Self { hash_algorithm, mask_gen_algorithm, salt_length, }) }) } } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum X509PublicKeyError { #[class(generic)] #[error(transparent)] X509(#[from] X509Error), #[class(generic)] #[error(transparent)] Rsa(#[from] rsa::Error), #[class(generic)] #[error(transparent)] Asn1(#[from] x509_parser::der_parser::asn1_rs::Error), #[class(generic)] #[error(transparent)] Ec(#[from] elliptic_curve::Error), #[class(type)] #[error("unsupported ec named curve")] UnsupportedEcNamedCurve, #[class(type)] #[error("missing ec parameters")] MissingEcParameters, #[class(type)] #[error("malformed DSS public key")] MalformedDssPublicKey, #[class(type)] #[error("unsupported x509 public key type")] UnsupportedX509KeyType, } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum RsaJwkError { #[class(generic)] #[error(transparent)] Base64(#[from] base64::DecodeError), #[class(generic)] #[error(transparent)] Rsa(#[from] rsa::Error), #[class(type)] #[error("missing RSA private component")] MissingRsaPrivateComponent, } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum EcJwkError { #[class(generic)] #[error(transparent)] Ec(#[from] elliptic_curve::Error), #[class(type)] #[error("unsupported curve: {0}")] UnsupportedCurve(String), } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum EdRawError { #[class(generic)] #[error(transparent)] Ed25519Signature(#[from] ed25519_dalek::SignatureError), #[class(type)] #[error("invalid Ed25519 key")] InvalidEd25519Key, #[class(type)] #[error("unsupported curve")] UnsupportedCurve, } #[derive(Debug, thiserror::Error, deno_error::JsError)] #[class(type)] pub enum AsymmetricPrivateKeyError { #[error("invalid PEM private key: not valid utf8 starting at byte {0}")] InvalidPemPrivateKeyInvalidUtf8(usize), #[error("invalid encrypted PEM private key")] InvalidEncryptedPemPrivateKey, #[error("invalid PEM private key")] InvalidPemPrivateKey, #[error("encrypted private key requires a passphrase to decrypt")] EncryptedPrivateKeyRequiresPassphraseToDecrypt, #[error("invalid PKCS#1 private key")] InvalidPkcs1PrivateKey, #[error("invalid SEC1 private key")] InvalidSec1PrivateKey, #[error("unsupported PEM label: {0}")] UnsupportedPemLabel(String), #[class(inherit)] #[error(transparent)] RsaPssParamsParse( #[from] #[inherit] RsaPssParamsParseError, ), #[error("invalid encrypted PKCS#8 private key")] InvalidEncryptedPkcs8PrivateKey, #[error("invalid PKCS#8 private key")] InvalidPkcs8PrivateKey, #[error("PKCS#1 private key does not support encryption with passphrase")] Pkcs1PrivateKeyDoesNotSupportEncryptionWithPassphrase, #[error("SEC1 private key does not support encryption with passphrase")] Sec1PrivateKeyDoesNotSupportEncryptionWithPassphrase, #[error("unsupported ec named curve")] UnsupportedEcNamedCurve, #[error("invalid private key")] InvalidPrivateKey, #[error("invalid DSA private key")] InvalidDsaPrivateKey, #[error("malformed or missing named curve in ec parameters")] MalformedOrMissingNamedCurveInEcParameters, #[error("unsupported key type: {0}")] UnsupportedKeyType(String), #[error("unsupported key format: {0}")] UnsupportedKeyFormat(String), #[error("invalid x25519 private key")] InvalidX25519PrivateKey, #[error("x25519 private key is the wrong length")] X25519PrivateKeyIsWrongLength, #[error("invalid Ed25519 private key")] InvalidEd25519PrivateKey, #[error("missing dh parameters")] MissingDhParameters, #[error("unsupported private key oid")] UnsupportedPrivateKeyOid, } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum AsymmetricPublicKeyError { #[class(type)] #[error("invalid PEM private key: not valid utf8 starting at byte {0}")] InvalidPemPrivateKeyInvalidUtf8(usize), #[class(type)] #[error("invalid PEM public key")] InvalidPemPublicKey, #[class(type)] #[error("invalid PKCS#1 public key")] InvalidPkcs1PublicKey, #[class(inherit)] #[error(transparent)] AsymmetricPrivateKey( #[from] #[inherit] AsymmetricPrivateKeyError, ), #[class(type)] #[error("invalid x509 certificate")] InvalidX509Certificate, #[class(generic)] #[error(transparent)] X509(#[from] x509_parser::nom::Err<X509Error>), #[class(inherit)] #[error(transparent)] X509PublicKey( #[from] #[inherit] X509PublicKeyError, ), #[class(type)] #[error("unsupported PEM label: {0}")] UnsupportedPemLabel(String), #[class(type)] #[error("invalid SPKI public key")] InvalidSpkiPublicKey, #[class(type)] #[error("unsupported key type: {0}")] UnsupportedKeyType(String), #[class(type)] #[error("unsupported key format: {0}")] UnsupportedKeyFormat(String), #[class(generic)] #[error(transparent)] Spki(#[from] spki::Error), #[class(generic)] #[error(transparent)] Pkcs1(#[from] rsa::pkcs1::Error), #[class(inherit)] #[error(transparent)] RsaPssParamsParse( #[from] #[inherit] RsaPssParamsParseError, ), #[class(type)] #[error("malformed DSS public key")] MalformedDssPublicKey, #[class(type)] #[error("malformed or missing named curve in ec parameters")] MalformedOrMissingNamedCurveInEcParameters, #[class(type)] #[error("malformed or missing public key in ec spki")] MalformedOrMissingPublicKeyInEcSpki, #[class(generic)] #[error(transparent)] Ec(#[from] elliptic_curve::Error), #[class(type)] #[error("unsupported ec named curve")] UnsupportedEcNamedCurve, #[class(type)] #[error("malformed or missing public key in x25519 spki")] MalformedOrMissingPublicKeyInX25519Spki, #[class(type)] #[error("x25519 public key is too short")] X25519PublicKeyIsTooShort, #[class(type)] #[error("invalid Ed25519 public key")] InvalidEd25519PublicKey, #[class(type)] #[error("missing dh parameters")] MissingDhParameters, #[class(type)] #[error("malformed dh parameters")] MalformedDhParameters, #[class(type)] #[error("malformed or missing public key in dh spki")] MalformedOrMissingPublicKeyInDhSpki, #[class(type)] #[error("unsupported private key oid")] UnsupportedPrivateKeyOid, } impl KeyObjectHandle { pub fn new_asymmetric_private_key_from_js( key: &[u8], format: &str, typ: &str, passphrase: Option<&[u8]>, ) -> Result<KeyObjectHandle, AsymmetricPrivateKeyError> { let document = match format { "pem" => { let pem = std::str::from_utf8(key).map_err(|err| { AsymmetricPrivateKeyError::InvalidPemPrivateKeyInvalidUtf8( err.valid_up_to(), ) })?; if let Some(passphrase) = passphrase { SecretDocument::from_pkcs8_encrypted_pem(pem, passphrase).map_err( |_| AsymmetricPrivateKeyError::InvalidEncryptedPemPrivateKey, )? } else { let (label, doc) = SecretDocument::from_pem(pem) .map_err(|_| AsymmetricPrivateKeyError::InvalidPemPrivateKey)?; match label { EncryptedPrivateKeyInfo::PEM_LABEL => { return Err(AsymmetricPrivateKeyError::EncryptedPrivateKeyRequiresPassphraseToDecrypt); } PrivateKeyInfo::PEM_LABEL => doc, rsa::pkcs1::RsaPrivateKey::PEM_LABEL => { SecretDocument::from_pkcs1_der(doc.as_bytes()).map_err(|_| { AsymmetricPrivateKeyError::InvalidPkcs1PrivateKey })? } sec1::EcPrivateKey::PEM_LABEL => { SecretDocument::from_sec1_der(doc.as_bytes()) .map_err(|_| AsymmetricPrivateKeyError::InvalidSec1PrivateKey)? } _ => { return Err(AsymmetricPrivateKeyError::UnsupportedPemLabel( label.to_string(), )); } } } } "der" => match typ { "pkcs8" => { if let Some(passphrase) = passphrase { SecretDocument::from_pkcs8_encrypted_der(key, passphrase).map_err( |_| AsymmetricPrivateKeyError::InvalidEncryptedPkcs8PrivateKey, )? } else { SecretDocument::from_pkcs8_der(key) .map_err(|_| AsymmetricPrivateKeyError::InvalidPkcs8PrivateKey)? } } "pkcs1" => { if passphrase.is_some() { return Err(AsymmetricPrivateKeyError::Pkcs1PrivateKeyDoesNotSupportEncryptionWithPassphrase); } SecretDocument::from_pkcs1_der(key) .map_err(|_| AsymmetricPrivateKeyError::InvalidPkcs1PrivateKey)? } "sec1" => { if passphrase.is_some() { return Err(AsymmetricPrivateKeyError::Sec1PrivateKeyDoesNotSupportEncryptionWithPassphrase); } SecretDocument::from_sec1_der(key) .map_err(|_| AsymmetricPrivateKeyError::InvalidSec1PrivateKey)? } _ => { return Err(AsymmetricPrivateKeyError::UnsupportedKeyType( typ.to_string(), )); } }, _ => { return Err(AsymmetricPrivateKeyError::UnsupportedKeyFormat( format.to_string(), )); } }; let pk_info = PrivateKeyInfo::try_from(document.as_bytes()) .map_err(|_| AsymmetricPrivateKeyError::InvalidPrivateKey)?; let alg = pk_info.algorithm.oid; let private_key = match alg { RSA_ENCRYPTION_OID => { let private_key = rsa::RsaPrivateKey::from_pkcs1_der(pk_info.private_key) .map_err(|_| AsymmetricPrivateKeyError::InvalidPkcs1PrivateKey)?; AsymmetricPrivateKey::Rsa(private_key) } RSASSA_PSS_OID => { let details = parse_rsa_pss_params(pk_info.algorithm.parameters)?; let private_key = rsa::RsaPrivateKey::from_pkcs1_der(pk_info.private_key) .map_err(|_| AsymmetricPrivateKeyError::InvalidPkcs1PrivateKey)?; AsymmetricPrivateKey::RsaPss(RsaPssPrivateKey { key: private_key, details, }) } DSA_OID => { let private_key = dsa::SigningKey::try_from(pk_info) .map_err(|_| AsymmetricPrivateKeyError::InvalidDsaPrivateKey)?; AsymmetricPrivateKey::Dsa(private_key) } EC_OID => { let named_curve = pk_info.algorithm.parameters_oid().map_err(|_| { AsymmetricPrivateKeyError::MalformedOrMissingNamedCurveInEcParameters })?; match named_curve { ID_SECP224R1_OID => { let secret_key = p224::SecretKey::from_sec1_der( pk_info.private_key, ) .map_err(|_| AsymmetricPrivateKeyError::InvalidSec1PrivateKey)?; AsymmetricPrivateKey::Ec(EcPrivateKey::P224(secret_key)) } ID_SECP256R1_OID => { let secret_key = p256::SecretKey::from_sec1_der( pk_info.private_key, ) .map_err(|_| AsymmetricPrivateKeyError::InvalidSec1PrivateKey)?; AsymmetricPrivateKey::Ec(EcPrivateKey::P256(secret_key)) } ID_SECP384R1_OID => { let secret_key = p384::SecretKey::from_sec1_der( pk_info.private_key, ) .map_err(|_| AsymmetricPrivateKeyError::InvalidSec1PrivateKey)?; AsymmetricPrivateKey::Ec(EcPrivateKey::P384(secret_key)) } _ => return Err(AsymmetricPrivateKeyError::UnsupportedEcNamedCurve), } } X25519_OID => { let string_ref = OctetStringRef::from_der(pk_info.private_key) .map_err(|_| AsymmetricPrivateKeyError::InvalidX25519PrivateKey)?; if string_ref.as_bytes().len() != 32 { return Err(AsymmetricPrivateKeyError::X25519PrivateKeyIsWrongLength); } let mut bytes = [0; 32]; bytes.copy_from_slice(string_ref.as_bytes()); AsymmetricPrivateKey::X25519(x25519_dalek::StaticSecret::from(bytes)) } ED25519_OID => { let signing_key = ed25519_dalek::SigningKey::try_from(pk_info) .map_err(|_| AsymmetricPrivateKeyError::InvalidEd25519PrivateKey)?; AsymmetricPrivateKey::Ed25519(signing_key) } DH_KEY_AGREEMENT_OID => { let params = pk_info .algorithm .parameters .ok_or(AsymmetricPrivateKeyError::MissingDhParameters)?; let params = pkcs3::DhParameter::from_der(&params.to_der().unwrap()) .map_err(|_| AsymmetricPrivateKeyError::MissingDhParameters)?; AsymmetricPrivateKey::Dh(DhPrivateKey { key: dh::PrivateKey::from_bytes(pk_info.private_key), params, }) } _ => return Err(AsymmetricPrivateKeyError::UnsupportedPrivateKeyOid), }; Ok(KeyObjectHandle::AsymmetricPrivate(private_key)) } pub fn new_x509_public_key( spki: &x509::SubjectPublicKeyInfo, ) -> Result<KeyObjectHandle, X509PublicKeyError> { use x509_parser::der_parser::asn1_rs::oid; use x509_parser::public_key::PublicKey; let key = match spki.parsed()? { PublicKey::RSA(key) => { let public_key = RsaPublicKey::new( rsa::BigUint::from_bytes_be(key.modulus), rsa::BigUint::from_bytes_be(key.exponent), )?; AsymmetricPublicKey::Rsa(public_key) } PublicKey::EC(point) => { let data = point.data(); if let Some(params) = &spki.algorithm.parameters { let curve_oid = params.as_oid()?; const ID_SECP224R1: &[u8] = &oid!(raw 1.3.132.0.33); const ID_SECP256R1: &[u8] = &oid!(raw 1.2.840.10045.3.1.7); const ID_SECP384R1: &[u8] = &oid!(raw 1.3.132.0.34); match curve_oid.as_bytes() { ID_SECP224R1 => { let public_key = p224::PublicKey::from_sec1_bytes(data)?; AsymmetricPublicKey::Ec(EcPublicKey::P224(public_key)) } ID_SECP256R1 => { let public_key = p256::PublicKey::from_sec1_bytes(data)?; AsymmetricPublicKey::Ec(EcPublicKey::P256(public_key)) } ID_SECP384R1 => { let public_key = p384::PublicKey::from_sec1_bytes(data)?; AsymmetricPublicKey::Ec(EcPublicKey::P384(public_key)) } _ => return Err(X509PublicKeyError::UnsupportedEcNamedCurve), } } else { return Err(X509PublicKeyError::MissingEcParameters); } } PublicKey::DSA(_) => { let verifying_key = dsa::VerifyingKey::from_public_key_der(spki.raw) .map_err(|_| X509PublicKeyError::MalformedDssPublicKey)?; AsymmetricPublicKey::Dsa(verifying_key) } _ => return Err(X509PublicKeyError::UnsupportedX509KeyType), }; Ok(KeyObjectHandle::AsymmetricPublic(key)) } pub fn new_rsa_jwk( jwk: RsaJwkKey, is_public: bool, ) -> Result<KeyObjectHandle, RsaJwkError> { use base64::prelude::BASE64_URL_SAFE_NO_PAD; let n = BASE64_URL_SAFE_NO_PAD.decode(jwk.n.as_bytes())?; let e = BASE64_URL_SAFE_NO_PAD.decode(jwk.e.as_bytes())?; if is_public { let public_key = RsaPublicKey::new( rsa::BigUint::from_bytes_be(&n), rsa::BigUint::from_bytes_be(&e), )?; Ok(KeyObjectHandle::AsymmetricPublic(AsymmetricPublicKey::Rsa( public_key, ))) } else { let d = BASE64_URL_SAFE_NO_PAD.decode( jwk .d .ok_or(RsaJwkError::MissingRsaPrivateComponent)? .as_bytes(), )?; let p = BASE64_URL_SAFE_NO_PAD.decode( jwk .p .ok_or(RsaJwkError::MissingRsaPrivateComponent)? .as_bytes(), )?; let q = BASE64_URL_SAFE_NO_PAD.decode( jwk .q .ok_or(RsaJwkError::MissingRsaPrivateComponent)? .as_bytes(), )?; let mut private_key = RsaPrivateKey::from_components( rsa::BigUint::from_bytes_be(&n), rsa::BigUint::from_bytes_be(&e), rsa::BigUint::from_bytes_be(&d), vec![ rsa::BigUint::from_bytes_be(&p), rsa::BigUint::from_bytes_be(&q), ], )?; private_key.precompute()?; // precompute CRT params Ok(KeyObjectHandle::AsymmetricPrivate( AsymmetricPrivateKey::Rsa(private_key), )) } } pub fn new_ec_jwk( jwk: &JwkEcKey, is_public: bool, ) -> Result<KeyObjectHandle, EcJwkError> { // https://datatracker.ietf.org/doc/html/rfc7518#section-6.2.1.1 let handle = match jwk.crv() { "P-256" if is_public => { KeyObjectHandle::AsymmetricPublic(AsymmetricPublicKey::Ec( EcPublicKey::P256(p256::PublicKey::from_jwk(jwk)?), )) } "P-256" => KeyObjectHandle::AsymmetricPrivate(AsymmetricPrivateKey::Ec( EcPrivateKey::P256(p256::SecretKey::from_jwk(jwk)?), )), "P-384" if is_public => { KeyObjectHandle::AsymmetricPublic(AsymmetricPublicKey::Ec( EcPublicKey::P384(p384::PublicKey::from_jwk(jwk)?), )) } "P-384" => KeyObjectHandle::AsymmetricPrivate(AsymmetricPrivateKey::Ec( EcPrivateKey::P384(p384::SecretKey::from_jwk(jwk)?), )), _ => { return Err(EcJwkError::UnsupportedCurve(jwk.crv().to_string())); } }; Ok(handle) } pub fn new_ed_raw( curve: &str, data: &[u8], is_public: bool, ) -> Result<KeyObjectHandle, EdRawError> { match curve { "Ed25519" => { let data = data.try_into().map_err(|_| EdRawError::InvalidEd25519Key)?; if !is_public { Ok(KeyObjectHandle::AsymmetricPrivate( AsymmetricPrivateKey::Ed25519( ed25519_dalek::SigningKey::from_bytes(data), ), )) } else { Ok(KeyObjectHandle::AsymmetricPublic( AsymmetricPublicKey::Ed25519( ed25519_dalek::VerifyingKey::from_bytes(data)?, ), )) } } "X25519" => { let data: [u8; 32] = data.try_into().map_err(|_| EdRawError::InvalidEd25519Key)?; if !is_public { Ok(KeyObjectHandle::AsymmetricPrivate( AsymmetricPrivateKey::X25519(x25519_dalek::StaticSecret::from( data, )), )) } else { Ok(KeyObjectHandle::AsymmetricPublic( AsymmetricPublicKey::X25519(x25519_dalek::PublicKey::from(data)), )) } } _ => Err(EdRawError::UnsupportedCurve), } } pub fn new_asymmetric_public_key_from_js( key: &[u8], format: &str, typ: &str, passphrase: Option<&[u8]>, ) -> Result<KeyObjectHandle, AsymmetricPublicKeyError> { let document = match format { "pem" => { let pem = std::str::from_utf8(key).map_err(|err| { AsymmetricPublicKeyError::InvalidPemPrivateKeyInvalidUtf8( err.valid_up_to(), ) })?; let (label, document) = Document::from_pem(pem) .map_err(|_| AsymmetricPublicKeyError::InvalidPemPublicKey)?; match label { SubjectPublicKeyInfoRef::PEM_LABEL => document, rsa::pkcs1::RsaPublicKey::PEM_LABEL => { Document::from_pkcs1_der(document.as_bytes()) .map_err(|_| AsymmetricPublicKeyError::InvalidPkcs1PublicKey)? } EncryptedPrivateKeyInfo::PEM_LABEL | PrivateKeyInfo::PEM_LABEL | sec1::EcPrivateKey::PEM_LABEL | rsa::pkcs1::RsaPrivateKey::PEM_LABEL => { let handle = KeyObjectHandle::new_asymmetric_private_key_from_js( key, format, typ, passphrase, )?; match handle { KeyObjectHandle::AsymmetricPrivate(private) => { return Ok(KeyObjectHandle::AsymmetricPublic( private.to_public_key(), )); } KeyObjectHandle::AsymmetricPublic(_) | KeyObjectHandle::Secret(_) => unreachable!(), } } "CERTIFICATE" => { let (_, pem) = x509_parser::pem::parse_x509_pem(pem.as_bytes()) .map_err(|_| AsymmetricPublicKeyError::InvalidX509Certificate)?; let cert = pem.parse_x509()?; let public_key = cert.tbs_certificate.subject_pki; return KeyObjectHandle::new_x509_public_key(&public_key) .map_err(Into::into); } _ => { return Err(AsymmetricPublicKeyError::UnsupportedPemLabel( label.to_string(), )); } } } "der" => match typ { "pkcs1" => Document::from_pkcs1_der(key) .map_err(|_| AsymmetricPublicKeyError::InvalidPkcs1PublicKey)?, "spki" => Document::from_public_key_der(key) .map_err(|_| AsymmetricPublicKeyError::InvalidSpkiPublicKey)?, _ => { return Err(AsymmetricPublicKeyError::UnsupportedKeyType( typ.to_string(), )); } }, _ => { return Err(AsymmetricPublicKeyError::UnsupportedKeyType( format.to_string(), ));
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
true
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/ops/crypto/digest/ring_sha2.rs
ext/node/ops/crypto/digest/ring_sha2.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::marker::PhantomData; use digest::generic_array::ArrayLength; pub trait RingDigestAlgo { fn algorithm() -> &'static aws_lc_rs::digest::Algorithm; type OutputSize: ArrayLength<u8> + 'static; } pub struct RingDigest<Algo: RingDigestAlgo> { context: aws_lc_rs::digest::Context, _phantom: PhantomData<Algo>, } impl<Algo: RingDigestAlgo> Clone for RingDigest<Algo> { fn clone(&self) -> Self { Self { context: self.context.clone(), _phantom: self._phantom, } } } impl<Algo: RingDigestAlgo> digest::HashMarker for RingDigest<Algo> {} impl<Algo: RingDigestAlgo> Default for RingDigest<Algo> { fn default() -> Self { Self { context: aws_lc_rs::digest::Context::new(Algo::algorithm()), _phantom: PhantomData, } } } impl<Algo: RingDigestAlgo> digest::Reset for RingDigest<Algo> { fn reset(&mut self) { self.context = aws_lc_rs::digest::Context::new(Algo::algorithm()) } } impl<Algo: RingDigestAlgo> digest::Update for RingDigest<Algo> { fn update(&mut self, data: &[u8]) { self.context.update(data); } } impl<Algo: RingDigestAlgo> digest::OutputSizeUser for RingDigest<Algo> { type OutputSize = Algo::OutputSize; } impl<Algo: RingDigestAlgo> digest::FixedOutput for RingDigest<Algo> { fn finalize_into(self, out: &mut digest::Output<Self>) { let result = self.context.finish(); out.copy_from_slice(result.as_ref()); } } impl<Algo: RingDigestAlgo> digest::FixedOutputReset for RingDigest<Algo> { fn finalize_into_reset(&mut self, out: &mut digest::Output<Self>) { let context = std::mem::replace( &mut self.context, aws_lc_rs::digest::Context::new(Algo::algorithm()), ); out.copy_from_slice(context.finish().as_ref()); } } pub struct RingSha256Algo; impl RingDigestAlgo for RingSha256Algo { fn algorithm() -> &'static aws_lc_rs::digest::Algorithm { &aws_lc_rs::digest::SHA256 } type OutputSize = digest::typenum::U32; } pub struct RingSha512Algo; impl RingDigestAlgo for RingSha512Algo { fn algorithm() -> &'static aws_lc_rs::digest::Algorithm { &aws_lc_rs::digest::SHA512 } type OutputSize = digest::typenum::U64; } pub type RingSha256 = RingDigest<RingSha256Algo>; pub type RingSha512 = RingDigest<RingSha512Algo>;
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/napi/lib.rs
ext/napi/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. #![allow(non_camel_case_types)] #![allow(non_upper_case_globals)] #![allow(clippy::undocumented_unsafe_blocks)] #![deny(clippy::missing_safety_doc)] //! Symbols to be exported are now defined in this JSON file. //! The `#[napi_sym]` macro checks for missing entries and panics. //! //! `./tools/napi/generate_symbols_list.js` is used to generate the LINK `cli/exports.def` on Windows, //! which is also checked into git. //! //! To add a new napi function: //! 1. Place `#[napi_sym]` on top of your implementation. //! 2. Add the function's identifier to this JSON list. //! 3. Finally, run `tools/napi/generate_symbols_list.js` to update `ext/napi/generated_symbol_exports_list_*.def`. pub mod js_native_api; pub mod node_api; pub mod util; pub mod uv; use core::ptr::NonNull; use std::borrow::Cow; use std::cell::Cell; use std::cell::RefCell; use std::collections::HashMap; pub use std::ffi::CStr; pub use std::os::raw::c_char; pub use std::os::raw::c_void; use std::path::Path; use std::path::PathBuf; pub use std::ptr; use std::rc::Rc; use std::thread_local; use deno_core::ExternalOpsTracker; use deno_core::OpState; use deno_core::V8CrossThreadTaskSpawner; use deno_core::op2; use deno_core::parking_lot::RwLock; use deno_core::url::Url; // Expose common stuff for ease of use. // `use deno_napi::*` pub use deno_core::v8; use deno_permissions::PermissionCheckError; pub use denort_helper::DenoRtNativeAddonLoader; pub use denort_helper::DenoRtNativeAddonLoaderRc; #[cfg(unix)] use libloading::os::unix::*; #[cfg(windows)] use libloading::os::windows::*; pub use value::napi_value; pub mod function; mod value; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum NApiError { #[class(type)] #[error("Invalid path")] InvalidPath, #[class(type)] #[error(transparent)] DenoRtLoad(#[from] denort_helper::LoadError), #[class(type)] #[error(transparent)] LibLoading(#[from] libloading::Error), #[class(type)] #[error("Unable to find register Node-API module at {}", .0.display())] ModuleNotFound(PathBuf), #[class(inherit)] #[error(transparent)] Permission(#[from] PermissionCheckError), } pub type napi_status = i32; pub type napi_env = *mut c_void; pub type napi_callback_info = *mut c_void; pub type napi_deferred = *mut c_void; pub type napi_ref = *mut c_void; pub type napi_threadsafe_function = *mut c_void; pub type napi_handle_scope = *mut c_void; pub type napi_callback_scope = *mut c_void; pub type napi_escapable_handle_scope = *mut c_void; pub type napi_async_cleanup_hook_handle = *mut c_void; pub type napi_async_work = *mut c_void; pub type napi_async_context = *mut c_void; pub const napi_ok: napi_status = 0; pub const napi_invalid_arg: napi_status = 1; pub const napi_object_expected: napi_status = 2; pub const napi_string_expected: napi_status = 3; pub const napi_name_expected: napi_status = 4; pub const napi_function_expected: napi_status = 5; pub const napi_number_expected: napi_status = 6; pub const napi_boolean_expected: napi_status = 7; pub const napi_array_expected: napi_status = 8; pub const napi_generic_failure: napi_status = 9; pub const napi_pending_exception: napi_status = 10; pub const napi_cancelled: napi_status = 11; pub const napi_escape_called_twice: napi_status = 12; pub const napi_handle_scope_mismatch: napi_status = 13; pub const napi_callback_scope_mismatch: napi_status = 14; pub const napi_queue_full: napi_status = 15; pub const napi_closing: napi_status = 16; pub const napi_bigint_expected: napi_status = 17; pub const napi_date_expected: napi_status = 18; pub const napi_arraybuffer_expected: napi_status = 19; pub const napi_detachable_arraybuffer_expected: napi_status = 20; pub const napi_would_deadlock: napi_status = 21; pub const napi_no_external_buffers_allowed: napi_status = 22; pub const napi_cannot_run_js: napi_status = 23; pub static ERROR_MESSAGES: &[&CStr] = &[ c"", c"Invalid argument", c"An object was expected", c"A string was expected", c"A string or symbol was expected", c"A function was expected", c"A number was expected", c"A boolean was expected", c"An array was expected", c"Unknown failure", c"An exception is pending", c"The async work item was cancelled", c"napi_escape_handle already called on scope", c"Invalid handle scope usage", c"Invalid callback scope usage", c"Thread-safe function queue is full", c"Thread-safe function handle is closing", c"A bigint was expected", c"A date was expected", c"An arraybuffer was expected", c"A detachable arraybuffer was expected", c"Main thread would deadlock", c"External buffers are not allowed", c"Cannot run JavaScript", ]; pub const NAPI_AUTO_LENGTH: usize = usize::MAX; thread_local! { pub static MODULE_TO_REGISTER: RefCell<Option<*const NapiModule>> = const { RefCell::new(None) }; } type napi_addon_register_func = unsafe extern "C" fn(env: napi_env, exports: napi_value) -> napi_value; type napi_register_module_v1 = unsafe extern "C" fn(env: napi_env, exports: napi_value) -> napi_value; #[repr(C)] #[derive(Clone)] pub struct NapiModule { pub nm_version: i32, pub nm_flags: u32, nm_filename: *const c_char, pub nm_register_func: napi_addon_register_func, nm_modname: *const c_char, nm_priv: *mut c_void, reserved: [*mut c_void; 4], } pub type napi_valuetype = i32; pub const napi_undefined: napi_valuetype = 0; pub const napi_null: napi_valuetype = 1; pub const napi_boolean: napi_valuetype = 2; pub const napi_number: napi_valuetype = 3; pub const napi_string: napi_valuetype = 4; pub const napi_symbol: napi_valuetype = 5; pub const napi_object: napi_valuetype = 6; pub const napi_function: napi_valuetype = 7; pub const napi_external: napi_valuetype = 8; pub const napi_bigint: napi_valuetype = 9; pub type napi_threadsafe_function_release_mode = i32; pub const napi_tsfn_release: napi_threadsafe_function_release_mode = 0; pub const napi_tsfn_abort: napi_threadsafe_function_release_mode = 1; pub type napi_threadsafe_function_call_mode = i32; pub const napi_tsfn_nonblocking: napi_threadsafe_function_call_mode = 0; pub const napi_tsfn_blocking: napi_threadsafe_function_call_mode = 1; pub type napi_key_collection_mode = i32; pub const napi_key_include_prototypes: napi_key_collection_mode = 0; pub const napi_key_own_only: napi_key_collection_mode = 1; pub type napi_key_filter = i32; pub const napi_key_all_properties: napi_key_filter = 0; pub const napi_key_writable: napi_key_filter = 1; pub const napi_key_enumerable: napi_key_filter = 1 << 1; pub const napi_key_configurable: napi_key_filter = 1 << 2; pub const napi_key_skip_strings: napi_key_filter = 1 << 3; pub const napi_key_skip_symbols: napi_key_filter = 1 << 4; pub type napi_key_conversion = i32; pub const napi_key_keep_numbers: napi_key_conversion = 0; pub const napi_key_numbers_to_strings: napi_key_conversion = 1; pub type napi_typedarray_type = i32; pub const napi_int8_array: napi_typedarray_type = 0; pub const napi_uint8_array: napi_typedarray_type = 1; pub const napi_uint8_clamped_array: napi_typedarray_type = 2; pub const napi_int16_array: napi_typedarray_type = 3; pub const napi_uint16_array: napi_typedarray_type = 4; pub const napi_int32_array: napi_typedarray_type = 5; pub const napi_uint32_array: napi_typedarray_type = 6; pub const napi_float32_array: napi_typedarray_type = 7; pub const napi_float64_array: napi_typedarray_type = 8; pub const napi_bigint64_array: napi_typedarray_type = 9; pub const napi_biguint64_array: napi_typedarray_type = 10; #[repr(C)] #[derive(Clone, Copy, PartialEq)] pub struct napi_type_tag { pub lower: u64, pub upper: u64, } pub type napi_callback = unsafe extern "C" fn( env: napi_env, info: napi_callback_info, ) -> napi_value<'static>; pub type napi_finalize = unsafe extern "C" fn( env: napi_env, data: *mut c_void, finalize_hint: *mut c_void, ); pub type napi_async_execute_callback = unsafe extern "C" fn(env: napi_env, data: *mut c_void); pub type napi_async_complete_callback = unsafe extern "C" fn(env: napi_env, status: napi_status, data: *mut c_void); pub type napi_threadsafe_function_call_js = unsafe extern "C" fn( env: napi_env, js_callback: napi_value, context: *mut c_void, data: *mut c_void, ); pub type napi_async_cleanup_hook = unsafe extern "C" fn( handle: napi_async_cleanup_hook_handle, data: *mut c_void, ); pub type napi_cleanup_hook = unsafe extern "C" fn(data: *mut c_void); pub type napi_property_attributes = i32; pub const napi_default: napi_property_attributes = 0; pub const napi_writable: napi_property_attributes = 1 << 0; pub const napi_enumerable: napi_property_attributes = 1 << 1; pub const napi_configurable: napi_property_attributes = 1 << 2; pub const napi_static: napi_property_attributes = 1 << 10; pub const napi_default_method: napi_property_attributes = napi_writable | napi_configurable; pub const napi_default_jsproperty: napi_property_attributes = napi_enumerable | napi_configurable | napi_writable; #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct napi_property_descriptor<'a> { pub utf8name: *const c_char, pub name: napi_value<'a>, pub method: Option<napi_callback>, pub getter: Option<napi_callback>, pub setter: Option<napi_callback>, pub value: napi_value<'a>, pub attributes: napi_property_attributes, pub data: *mut c_void, } #[repr(C)] #[derive(Debug)] pub struct napi_extended_error_info { pub error_message: *const c_char, pub engine_reserved: *mut c_void, pub engine_error_code: i32, pub error_code: Cell<napi_status>, } #[repr(C)] #[derive(Debug)] pub struct napi_node_version { pub major: u32, pub minor: u32, pub patch: u32, pub release: *const c_char, } pub trait PendingNapiAsyncWork: FnOnce() + Send + 'static {} impl<T> PendingNapiAsyncWork for T where T: FnOnce() + Send + 'static {} pub struct NapiState { // Thread safe functions. pub env_cleanup_hooks: Rc<RefCell<Vec<(napi_cleanup_hook, *mut c_void)>>>, } impl Drop for NapiState { fn drop(&mut self) { let hooks = { let h = self.env_cleanup_hooks.borrow_mut(); h.clone() }; // Hooks are supposed to be run in LIFO order let hooks_to_run = hooks.into_iter().rev(); for hook in hooks_to_run { // This hook might have been removed by a previous hook, in such case skip it here. if !self .env_cleanup_hooks .borrow() .iter() .any(|pair| std::ptr::fn_addr_eq(pair.0, hook.0) && pair.1 == hook.1) { continue; } unsafe { (hook.0)(hook.1); } { self.env_cleanup_hooks.borrow_mut().retain(|pair| { !(std::ptr::fn_addr_eq(pair.0, hook.0) && pair.1 == hook.1) }); } } } } #[repr(C)] #[derive(Debug)] pub struct InstanceData { pub data: *mut c_void, pub finalize_cb: Option<napi_finalize>, pub finalize_hint: *mut c_void, } #[repr(C)] #[derive(Debug)] /// Env that is shared between all contexts in same native module. pub struct EnvShared { pub instance_data: Option<InstanceData>, pub napi_wrap: v8::Global<v8::Private>, pub type_tag: v8::Global<v8::Private>, pub finalize: Option<napi_finalize>, pub finalize_hint: *mut c_void, pub filename: String, } impl EnvShared { pub fn new( napi_wrap: v8::Global<v8::Private>, type_tag: v8::Global<v8::Private>, filename: String, ) -> Self { Self { instance_data: None, napi_wrap, type_tag, finalize: None, finalize_hint: std::ptr::null_mut(), filename, } } } #[repr(C)] pub struct Env { context: NonNull<v8::Context>, pub isolate_ptr: v8::UnsafeRawIsolatePtr, pub open_handle_scopes: usize, pub shared: *mut EnvShared, pub async_work_sender: V8CrossThreadTaskSpawner, cleanup_hooks: Rc<RefCell<Vec<(napi_cleanup_hook, *mut c_void)>>>, external_ops_tracker: ExternalOpsTracker, pub last_error: napi_extended_error_info, pub last_exception: Option<v8::Global<v8::Value>>, pub global: v8::Global<v8::Object>, pub create_buffer: v8::Global<v8::Function>, pub report_error: v8::Global<v8::Function>, } unsafe impl Send for Env {} unsafe impl Sync for Env {} impl Env { #[allow(clippy::too_many_arguments)] pub fn new( isolate_ptr: v8::UnsafeRawIsolatePtr, context: v8::Global<v8::Context>, global: v8::Global<v8::Object>, create_buffer: v8::Global<v8::Function>, report_error: v8::Global<v8::Function>, sender: V8CrossThreadTaskSpawner, cleanup_hooks: Rc<RefCell<Vec<(napi_cleanup_hook, *mut c_void)>>>, external_ops_tracker: ExternalOpsTracker, ) -> Self { Self { isolate_ptr, context: context.into_raw(), global, create_buffer, report_error, shared: std::ptr::null_mut(), open_handle_scopes: 0, async_work_sender: sender, cleanup_hooks, external_ops_tracker, last_error: napi_extended_error_info { error_message: std::ptr::null(), engine_reserved: std::ptr::null_mut(), engine_error_code: 0, error_code: Cell::new(napi_ok), }, last_exception: None, } } pub fn shared(&self) -> &EnvShared { // SAFETY: the lifetime of `EnvShared` always exceeds the lifetime of `Env`. unsafe { &*self.shared } } pub fn shared_mut(&mut self) -> &mut EnvShared { // SAFETY: the lifetime of `EnvShared` always exceeds the lifetime of `Env`. unsafe { &mut *self.shared } } pub fn add_async_work(&mut self, async_work: impl FnOnce() + Send + 'static) { self.async_work_sender.spawn(|_| async_work()); } #[inline] pub fn isolate(&mut self) -> &mut v8::Isolate { // SAFETY: Lifetime of `Isolate` is longer than `Env`. unsafe { v8::Isolate::ref_from_raw_isolate_ptr_mut_unchecked(&mut self.isolate_ptr) } } pub fn context<'s>(&'s self) -> v8::Local<'s, v8::Context> { // SAFETY: `v8::Local` is always non-null pointer; the `PinScope<'_, '_>` is // already on the stack, but we don't have access to it. unsafe { std::mem::transmute::<NonNull<v8::Context>, v8::Local<v8::Context>>( self.context, ) } } pub fn threadsafe_function_ref(&mut self) { self.external_ops_tracker.ref_op(); } pub fn threadsafe_function_unref(&mut self) { self.external_ops_tracker.unref_op(); } pub fn add_cleanup_hook( &mut self, hook: napi_cleanup_hook, data: *mut c_void, ) { let mut hooks = self.cleanup_hooks.borrow_mut(); if hooks .iter() .any(|pair| std::ptr::fn_addr_eq(pair.0, hook) && pair.1 == data) { panic!("Cannot register cleanup hook with same data twice"); } hooks.push((hook, data)); } pub fn remove_cleanup_hook( &mut self, hook: napi_cleanup_hook, data: *mut c_void, ) { let mut hooks = self.cleanup_hooks.borrow_mut(); match hooks .iter() .rposition(|&pair| std::ptr::fn_addr_eq(pair.0, hook) && pair.1 == data) { Some(index) => { hooks.remove(index); } None => panic!("Cannot remove cleanup hook which was not registered"), } } } deno_core::extension!(deno_napi, ops = [ op_napi_open ], options = { deno_rt_native_addon_loader: Option<DenoRtNativeAddonLoaderRc>, }, state = |state, options| { state.put(NapiState { env_cleanup_hooks: Rc::new(RefCell::new(vec![])), }); if let Some(loader) = options.deno_rt_native_addon_loader { state.put(loader); } }, ); unsafe impl Sync for NapiModuleHandle {} unsafe impl Send for NapiModuleHandle {} #[derive(Clone, Copy)] struct NapiModuleHandle(*const NapiModule); static NAPI_LOADED_MODULES: std::sync::LazyLock< RwLock<HashMap<PathBuf, NapiModuleHandle>>, > = std::sync::LazyLock::new(|| RwLock::new(HashMap::new())); #[op2(reentrant, stack_trace)] fn op_napi_open<'scope>( scope: &mut v8::PinScope<'scope, '_>, isolate: &mut v8::Isolate, op_state: Rc<RefCell<OpState>>, #[string] path: &str, global: v8::Local<'scope, v8::Object>, create_buffer: v8::Local<'scope, v8::Function>, report_error: v8::Local<'scope, v8::Function>, ) -> Result<v8::Local<'scope, v8::Value>, NApiError> { // We must limit the OpState borrow because this function can trigger a // re-borrow through the NAPI module. let ( async_work_sender, cleanup_hooks, external_ops_tracker, deno_rt_native_addon_loader, path, ) = { let mut op_state = op_state.borrow_mut(); let permissions = op_state.borrow_mut::<deno_permissions::PermissionsContainer>(); let path = permissions.check_ffi(Cow::Borrowed(Path::new(path)))?; let napi_state = op_state.borrow::<NapiState>(); ( op_state.borrow::<V8CrossThreadTaskSpawner>().clone(), napi_state.env_cleanup_hooks.clone(), op_state.external_ops_tracker.clone(), op_state.try_borrow::<DenoRtNativeAddonLoaderRc>().cloned(), path, ) }; let napi_wrap_name = v8::String::new(scope, "napi_wrap").unwrap(); let napi_wrap = v8::Private::new(scope, Some(napi_wrap_name)); let napi_wrap = v8::Global::new(scope, napi_wrap); let type_tag_name = v8::String::new(scope, "type_tag").unwrap(); let type_tag = v8::Private::new(scope, Some(type_tag_name)); let type_tag = v8::Global::new(scope, type_tag); let url_filename = Url::from_file_path(&path).map_err(|_| NApiError::InvalidPath)?; let env_shared = EnvShared::new(napi_wrap, type_tag, format!("{url_filename}\0")); let ctx = scope.get_current_context(); let mut env = Env::new( unsafe { isolate.as_raw_isolate_ptr() }, v8::Global::new(scope, ctx), v8::Global::new(scope, global), v8::Global::new(scope, create_buffer), v8::Global::new(scope, report_error), async_work_sender, cleanup_hooks, external_ops_tracker, ); env.shared = Box::into_raw(Box::new(env_shared)); let env_ptr = Box::into_raw(Box::new(env)) as _; #[cfg(unix)] let flags = RTLD_LAZY; #[cfg(not(unix))] let flags = 0x00000008; let real_path = match deno_rt_native_addon_loader { Some(loader) => loader.load_and_resolve_path(&path)?, None => Cow::Borrowed(path.as_ref()), }; // SAFETY: opening a DLL calls dlopen #[cfg(unix)] let library = unsafe { Library::open(Some(real_path.as_ref()), flags) }?; // SAFETY: opening a DLL calls dlopen #[cfg(not(unix))] let library = unsafe { Library::load_with_flags(real_path.as_ref(), flags) }?; let maybe_module = MODULE_TO_REGISTER.with(|cell| { let mut slot = cell.borrow_mut(); slot.take() }); // The `module.exports` object. let exports = v8::Object::new(scope); let maybe_exports = if let Some(module_to_register) = maybe_module { NAPI_LOADED_MODULES.write().insert( real_path.to_path_buf(), NapiModuleHandle(module_to_register), ); // SAFETY: napi_register_module guarantees that `module_to_register` is valid. let nm = unsafe { &*module_to_register }; assert_eq!(nm.nm_version, 1); // SAFETY: we are going blind, calling the register function on the other side. unsafe { (nm.nm_register_func)(env_ptr, exports.into()) } } else if let Some(module_to_register) = { NAPI_LOADED_MODULES.read().get(real_path.as_ref()).copied() } { // SAFETY: this originated from `napi_register_module`, so the // pointer should still be valid. let nm = unsafe { &*module_to_register.0 }; assert_eq!(nm.nm_version, 1); // SAFETY: we are going blind, calling the register function on the other side. unsafe { (nm.nm_register_func)(env_ptr, exports.into()) } } else { match unsafe { library.get::<napi_register_module_v1>(b"napi_register_module_v1") } { Ok(init) => { // Initializer callback. // SAFETY: we are going blind, calling the register function on the other side. unsafe { init(env_ptr, exports.into()) } } _ => { return Err(NApiError::ModuleNotFound(path.into_owned())); } } }; let exports = maybe_exports.unwrap_or(exports.into()); // NAPI addons can't be unloaded, so we're going to "forget" the library // object so it lives till the program exit. std::mem::forget(library); Ok(exports) } #[allow(clippy::print_stdout)] pub fn print_linker_flags(name: &str) { let symbols_path = include_str!(concat!(env!("OUT_DIR"), "/napi_symbol_path.txt")); #[cfg(target_os = "windows")] println!("cargo:rustc-link-arg-bin={name}=/DEF:{}", symbols_path); #[cfg(target_os = "macos")] println!( "cargo:rustc-link-arg-bin={name}=-Wl,-exported_symbols_list,{}", symbols_path, ); #[cfg(any( target_os = "linux", target_os = "freebsd", target_os = "openbsd" ))] println!( "cargo:rustc-link-arg-bin={name}=-Wl,--export-dynamic-symbol-list={}", symbols_path, ); #[cfg(target_os = "android")] println!( "cargo:rustc-link-arg-bin={name}=-Wl,--export-dynamic-symbol-list={}", symbols_path, ); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/napi/value.rs
ext/napi/value.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::mem::transmute; use std::ops::Deref; use std::os::raw::c_void; use std::ptr::NonNull; use deno_core::v8; /// An FFI-opaque, nullable wrapper around v8::Local<v8::Value>. /// rusty_v8 Local handle cannot be empty but napi_value can be. #[repr(transparent)] #[derive(Clone, Copy, Debug)] pub struct NapiValue<'s>( Option<NonNull<v8::Value>>, std::marker::PhantomData<&'s ()>, ); pub type napi_value<'s> = NapiValue<'s>; impl<'s> Deref for napi_value<'s> { type Target = Option<v8::Local<'s, v8::Value>>; fn deref(&self) -> &Self::Target { // SAFETY: It is safe to transmute `Option<NonNull<T>>` to `Option<*const T>`. // v8::Local guarantees that *const T is not null but napi_value *can* be null. unsafe { transmute::<&Self, &Self::Target>(self) } } } impl<'s, T> From<v8::Local<'s, T>> for napi_value<'s> where v8::Local<'s, T>: Into<v8::Local<'s, v8::Value>>, { fn from(v: v8::Local<'s, T>) -> Self { Self(Some(NonNull::from(&*v.into())), std::marker::PhantomData) } } impl<'s, T> From<Option<v8::Local<'s, T>>> for napi_value<'s> where v8::Local<'s, T>: Into<v8::Local<'s, v8::Value>>, { fn from(v: Option<v8::Local<'s, T>>) -> Self { if let Some(v) = v { NapiValue::from(v) } else { Self(None, std::marker::PhantomData) } } } const _: () = { assert!( std::mem::size_of::<napi_value>() == std::mem::size_of::<*mut c_void>() ); // Assert "nullable pointer optimization" on napi_value unsafe { type Src<'a> = napi_value<'a>; type Dst = usize; assert!(std::mem::size_of::<Src>() == std::mem::size_of::<Dst>()); union Transmute<'a> { src: Src<'a>, dst: Dst, } Transmute { src: NapiValue(None, std::marker::PhantomData), } .dst }; };
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/napi/function.rs
ext/napi/function.rs
// Copyright 2018-2025 the Deno authors. MIT license. use crate::*; #[repr(C)] #[derive(Debug)] pub struct CallbackInfo { pub env: *mut Env, pub cb: napi_callback, pub data: *mut c_void, pub args: *const c_void, } impl CallbackInfo { #[inline] pub fn new_raw( env: *mut Env, cb: napi_callback, data: *mut c_void, ) -> *mut Self { Box::into_raw(Box::new(Self { env, cb, data, args: std::ptr::null(), })) } } extern "C" fn call_fn(info: *const v8::FunctionCallbackInfo) { let callback_info = unsafe { &*info }; let args = v8::FunctionCallbackArguments::from_function_callback_info(callback_info); let mut rv = v8::ReturnValue::from_function_callback_info(callback_info); // SAFETY: create_function guarantees that the data is a CallbackInfo external. let info_ptr: *mut CallbackInfo = unsafe { let external_value = v8::Local::<v8::External>::cast_unchecked(args.data()); external_value.value() as _ }; // SAFETY: pointer from Box::into_raw. let info = unsafe { &mut *info_ptr }; info.args = &args as *const _ as *const c_void; // SAFETY: calling user provided function pointer. let value = unsafe { (info.cb)(info.env as napi_env, info_ptr as *mut _) }; if let Some(exc) = unsafe { &mut *info.env }.last_exception.take() { v8::callback_scope!(unsafe scope, callback_info); let exc = v8::Local::new(scope, exc); scope.throw_exception(exc); } if let Some(value) = *value { rv.set(value); } } pub fn create_function<'s>( scope: &mut v8::PinScope<'s, '_>, env: *mut Env, name: Option<v8::Local<v8::String>>, cb: napi_callback, data: *mut c_void, ) -> v8::Local<'s, v8::Function> { let external = v8::External::new(scope, CallbackInfo::new_raw(env, cb, data) as *mut _); let function = v8::Function::builder_raw(call_fn) .data(external.into()) .build(scope) .unwrap(); if let Some(v8str) = name { function.set_name(v8str); } function } pub fn create_function_template<'s>( scope: &mut v8::PinScope<'s, '_>, env: *mut Env, name: Option<v8::Local<v8::String>>, cb: napi_callback, cb_info: napi_callback_info, ) -> v8::Local<'s, v8::FunctionTemplate> { let external = v8::External::new(scope, CallbackInfo::new_raw(env, cb, cb_info) as *mut _); let function = v8::FunctionTemplate::builder_raw(call_fn) .data(external.into()) .build(scope); if let Some(v8str) = name { function.set_class_name(v8str); } function }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/napi/js_native_api.rs
ext/napi/js_native_api.rs
// Copyright 2018-2025 the Deno authors. MIT license. #![allow(non_upper_case_globals)] #![deny(unsafe_op_in_unsafe_fn)] const NAPI_VERSION: u32 = 9; use std::ptr::NonNull; use libc::INT_MAX; use napi_sym::napi_sym; use super::util::check_new_from_utf8; use super::util::check_new_from_utf8_len; use super::util::get_array_buffer_ptr; use super::util::make_external_backing_store; use super::util::napi_clear_last_error; use super::util::napi_set_last_error; use super::util::v8_name_from_property_descriptor; use crate::check_arg; use crate::check_env; use crate::function::CallbackInfo; use crate::function::create_function; use crate::function::create_function_template; use crate::*; #[derive(Debug, Clone, Copy, PartialEq)] enum ReferenceOwnership { Runtime, Userland, } enum ReferenceState { Strong(v8::Global<v8::Value>), Weak(v8::Weak<v8::Value>), } struct Reference { env: *mut Env, state: ReferenceState, ref_count: u32, ownership: ReferenceOwnership, finalize_cb: Option<napi_finalize>, finalize_data: *mut c_void, finalize_hint: *mut c_void, } impl Reference { fn new( env: *mut Env, value: v8::Local<v8::Value>, initial_ref_count: u32, ownership: ReferenceOwnership, finalize_cb: Option<napi_finalize>, finalize_data: *mut c_void, finalize_hint: *mut c_void, ) -> Box<Self> { let isolate = unsafe { (*env).isolate() }; let mut reference = Box::new(Reference { env, state: ReferenceState::Strong(v8::Global::new(isolate, value)), ref_count: initial_ref_count, ownership, finalize_cb, finalize_data, finalize_hint, }); if initial_ref_count == 0 { reference.set_weak(); } reference } fn ref_(&mut self) -> u32 { self.ref_count += 1; if self.ref_count == 1 { self.set_strong(); } self.ref_count } fn unref(&mut self) -> u32 { let old_ref_count = self.ref_count; if self.ref_count > 0 { self.ref_count -= 1; } if old_ref_count == 1 && self.ref_count == 0 { self.set_weak(); } self.ref_count } fn reset(&mut self) { self.finalize_cb = None; self.finalize_data = std::ptr::null_mut(); self.finalize_hint = std::ptr::null_mut(); } fn set_strong(&mut self) { if let ReferenceState::Weak(w) = &self.state { let isolate = unsafe { (*self.env).isolate() }; if let Some(g) = w.to_global(isolate) { self.state = ReferenceState::Strong(g); } } } fn set_weak(&mut self) { let reference = self as *mut Reference; if let ReferenceState::Strong(g) = &self.state { let cb = Box::new(move |_: &mut v8::Isolate| { Reference::weak_callback(reference) }); let isolate = unsafe { (*self.env).isolate() }; self.state = ReferenceState::Weak(v8::Weak::with_finalizer(isolate, g, cb)); } } fn weak_callback(reference: *mut Reference) { let reference = unsafe { &mut *reference }; let finalize_cb = reference.finalize_cb; let finalize_data = reference.finalize_data; let finalize_hint = reference.finalize_hint; reference.reset(); // copy this value before the finalize callback, since // it might free the reference (which would be a UAF) let ownership = reference.ownership; if let Some(finalize_cb) = finalize_cb { unsafe { finalize_cb(reference.env as _, finalize_data, finalize_hint); } } if ownership == ReferenceOwnership::Runtime { unsafe { drop(Reference::from_raw(reference)) } } } fn into_raw(r: Box<Reference>) -> *mut Reference { Box::into_raw(r) } unsafe fn from_raw(r: *mut Reference) -> Box<Reference> { unsafe { Box::from_raw(r) } } unsafe fn remove(r: *mut Reference) { let r = unsafe { &mut *r }; if r.ownership == ReferenceOwnership::Userland { r.reset(); } else { unsafe { drop(Reference::from_raw(r)) } } } } #[napi_sym] fn napi_get_last_error_info( env: *mut Env, result: *mut *const napi_extended_error_info, ) -> napi_status { let env = check_env!(env); check_arg!(env, result); if env.last_error.error_code.get() == napi_ok { napi_clear_last_error(env); } else { env.last_error.error_message = ERROR_MESSAGES[env.last_error.error_code.get() as usize].as_ptr(); } unsafe { *result = &env.last_error; } napi_ok } #[napi_sym] fn napi_create_function<'s>( env: &'s mut Env, name: *const c_char, length: usize, cb: Option<napi_callback>, data: *mut c_void, result: *mut napi_value<'s>, ) -> napi_status { let env_ptr = env as *mut Env; check_arg!(env, result); check_arg!(env, cb); let name = if !name.is_null() { match unsafe { check_new_from_utf8_len(env, name, length) } { Ok(s) => Some(s), Err(status) => return status, } } else { None }; unsafe { v8::callback_scope!(unsafe scope, env.context()); *result = create_function(scope, env_ptr, name, cb.unwrap(), data).into(); } napi_ok } #[napi_sym] #[allow(clippy::too_many_arguments)] fn napi_define_class<'s>( env: &'s mut Env, utf8name: *const c_char, length: usize, constructor: Option<napi_callback>, callback_data: *mut c_void, property_count: usize, properties: *const napi_property_descriptor, result: *mut napi_value<'s>, ) -> napi_status { let env_ptr = env as *mut Env; check_arg!(env, result); check_arg!(env, constructor); if property_count > 0 { check_arg!(env, properties); } let name = match unsafe { check_new_from_utf8_len(env, utf8name, length) } { Ok(string) => string, Err(status) => return status, }; v8::callback_scope!(unsafe scope, env.context()); let tpl = { create_function_template( scope, env_ptr, Some(name), constructor.unwrap(), callback_data, ) }; let napi_properties: &[napi_property_descriptor] = if property_count > 0 { unsafe { std::slice::from_raw_parts(properties, property_count) } } else { &[] }; let mut static_property_count = 0; for p in napi_properties { if p.attributes & napi_static != 0 { // Will be handled below static_property_count += 1; continue; } let name = match unsafe { v8_name_from_property_descriptor(env_ptr, p) } { Ok(name) => name, Err(status) => return status, }; let mut accessor_property = v8::PropertyAttribute::NONE; if p.attributes & napi_enumerable == 0 { accessor_property = accessor_property | v8::PropertyAttribute::DONT_ENUM; } if p.attributes & napi_configurable == 0 { accessor_property = accessor_property | v8::PropertyAttribute::DONT_DELETE; } if p.getter.is_some() || p.setter.is_some() { let getter = p .getter .map(|g| create_function_template(scope, env_ptr, None, g, p.data)); let setter = p .setter .map(|s| create_function_template(scope, env_ptr, None, s, p.data)); if getter.is_some() && setter.is_some() && (p.attributes & napi_writable) == 0 { accessor_property = accessor_property | v8::PropertyAttribute::READ_ONLY; } let proto = tpl.prototype_template(scope); proto.set_accessor_property(name, getter, setter, accessor_property); } else if let Some(method) = p.method { let function = create_function_template(scope, env_ptr, None, method, p.data); let proto = tpl.prototype_template(scope); proto.set_with_attr(name, function.into(), accessor_property); } else { let proto = tpl.prototype_template(scope); if (p.attributes & napi_writable) == 0 { accessor_property = accessor_property | v8::PropertyAttribute::READ_ONLY; } proto.set_with_attr(name, p.value.unwrap().into(), accessor_property); } } let value: v8::Local<v8::Value> = tpl.get_function(scope).unwrap().into(); unsafe { *result = value.into(); } if static_property_count > 0 { let mut static_descriptors = Vec::with_capacity(static_property_count); for p in napi_properties { if p.attributes & napi_static != 0 { static_descriptors.push(*p); } } crate::status_call!(unsafe { napi_define_properties( env_ptr, *result, static_descriptors.len(), static_descriptors.as_ptr(), ) }); } napi_ok } #[napi_sym] fn napi_get_property_names( env: *mut Env, object: napi_value, result: *mut napi_value, ) -> napi_status { unsafe { napi_get_all_property_names( env, object, napi_key_include_prototypes, napi_key_enumerable | napi_key_skip_symbols, napi_key_numbers_to_strings, result, ) } } #[napi_sym] fn napi_get_all_property_names<'s>( env: &'s mut Env, object: napi_value, key_mode: napi_key_collection_mode, key_filter: napi_key_filter, key_conversion: napi_key_conversion, result: *mut napi_value<'s>, ) -> napi_status { check_arg!(env, result); v8::callback_scope!(unsafe scope, env.context()); let Some(obj) = object.and_then(|o| o.to_object(scope)) else { return napi_object_expected; }; let mut filter = v8::PropertyFilter::ALL_PROPERTIES; if key_filter & napi_key_writable != 0 { filter = filter | v8::PropertyFilter::ONLY_WRITABLE; } if key_filter & napi_key_enumerable != 0 { filter = filter | v8::PropertyFilter::ONLY_ENUMERABLE; } if key_filter & napi_key_configurable != 0 { filter = filter | v8::PropertyFilter::ONLY_CONFIGURABLE; } if key_filter & napi_key_skip_strings != 0 { filter = filter | v8::PropertyFilter::SKIP_STRINGS; } if key_filter & napi_key_skip_symbols != 0 { filter = filter | v8::PropertyFilter::SKIP_SYMBOLS; } let key_mode = match key_mode { napi_key_include_prototypes => v8::KeyCollectionMode::IncludePrototypes, napi_key_own_only => v8::KeyCollectionMode::OwnOnly, _ => return napi_invalid_arg, }; let key_conversion = match key_conversion { napi_key_keep_numbers => v8::KeyConversionMode::KeepNumbers, napi_key_numbers_to_strings => v8::KeyConversionMode::ConvertToString, _ => return napi_invalid_arg, }; let filter = v8::GetPropertyNamesArgsBuilder::new() .mode(key_mode) .property_filter(filter) .index_filter(v8::IndexFilter::IncludeIndices) .key_conversion(key_conversion) .build(); let property_names = match obj.get_property_names(scope, filter) { Some(n) => n, None => return napi_generic_failure, }; unsafe { *result = property_names.into(); } napi_ok } #[napi_sym] fn napi_set_property( env: &mut Env, object: napi_value, key: napi_value, value: napi_value, ) -> napi_status { check_arg!(env, key); check_arg!(env, value); v8::callback_scope!(unsafe scope, env.context()); let Some(object) = object.and_then(|o| o.to_object(scope)) else { return napi_object_expected; }; if object.set(scope, key.unwrap(), value.unwrap()).is_none() { return napi_generic_failure; }; napi_ok } #[napi_sym] fn napi_has_property( env: &mut Env, object: napi_value, key: napi_value, result: *mut bool, ) -> napi_status { check_arg!(env, key); check_arg!(env, result); v8::callback_scope!(unsafe scope, env.context()); let Some(object) = object.and_then(|o| o.to_object(scope)) else { return napi_object_expected; }; let Some(has) = object.has(scope, key.unwrap()) else { return napi_generic_failure; }; unsafe { *result = has; } napi_ok } #[napi_sym] fn napi_get_property<'s>( env: &'s mut Env, object: napi_value, key: napi_value, result: *mut napi_value<'s>, ) -> napi_status { check_arg!(env, key); check_arg!(env, result); v8::callback_scope!(unsafe scope, env.context()); let Some(object) = object.and_then(|o| o.to_object(scope)) else { return napi_object_expected; }; let Some(value) = object.get(scope, key.unwrap()) else { return napi_generic_failure; }; unsafe { *result = value.into(); } napi_ok } #[napi_sym] fn napi_delete_property( env: &mut Env, object: napi_value, key: napi_value, result: *mut bool, ) -> napi_status { check_arg!(env, key); v8::callback_scope!(unsafe scope, env.context()); let Some(object) = object.and_then(|o| o.to_object(scope)) else { return napi_object_expected; }; let Some(deleted) = object.delete(scope, key.unwrap()) else { return napi_generic_failure; }; if !result.is_null() { unsafe { *result = deleted; } } napi_ok } #[napi_sym] fn napi_has_own_property( env: &mut Env, object: napi_value, key: napi_value, result: *mut bool, ) -> napi_status { check_arg!(env, key); check_arg!(env, result); v8::callback_scope!(unsafe scope, env.context()); let Some(object) = object.and_then(|o| o.to_object(scope)) else { return napi_object_expected; }; let Ok(key) = v8::Local::<v8::Name>::try_from(key.unwrap()) else { return napi_name_expected; }; let Some(has_own) = object.has_own_property(scope, key) else { return napi_generic_failure; }; unsafe { *result = has_own; } napi_ok } #[napi_sym] fn napi_has_named_property<'s>( env: &'s mut Env, object: napi_value<'s>, utf8name: *const c_char, result: *mut bool, ) -> napi_status { let env_ptr = env as *mut Env; check_arg!(env, result); v8::callback_scope!(unsafe scope, env.context()); let Some(object) = object.and_then(|o| o.to_object(scope)) else { return napi_object_expected; }; let key = match unsafe { check_new_from_utf8(env_ptr, utf8name) } { Ok(key) => key, Err(status) => return status, }; let Some(has_property) = object.has(scope, key.into()) else { return napi_generic_failure; }; unsafe { *result = has_property; } napi_ok } #[napi_sym] fn napi_set_named_property<'s>( env: &'s mut Env, object: napi_value<'s>, utf8name: *const c_char, value: napi_value<'s>, ) -> napi_status { check_arg!(env, value); let env_ptr = env as *mut Env; v8::callback_scope!(unsafe scope, env.context()); let Some(object) = object.and_then(|o| o.to_object(scope)) else { return napi_object_expected; }; let key = match unsafe { check_new_from_utf8(env_ptr, utf8name) } { Ok(key) => key, Err(status) => return status, }; let value = value.unwrap(); if !object.set(scope, key.into(), value).unwrap_or(false) { return napi_generic_failure; } napi_ok } #[napi_sym] fn napi_get_named_property<'s>( env: &'s mut Env, object: napi_value<'s>, utf8name: *const c_char, result: *mut napi_value<'s>, ) -> napi_status { check_arg!(env, result); let env_ptr = env as *mut Env; v8::callback_scope!(unsafe scope, env.context()); let Some(object) = object.and_then(|o| o.to_object(scope)) else { return napi_object_expected; }; let key = match unsafe { check_new_from_utf8(env_ptr, utf8name) } { Ok(key) => key, Err(status) => return status, }; let Some(value) = object.get(scope, key.into()) else { return napi_generic_failure; }; unsafe { *result = value.into(); } napi_ok } #[napi_sym] fn napi_set_element<'s>( env: &'s mut Env, object: napi_value<'s>, index: u32, value: napi_value<'s>, ) -> napi_status { check_arg!(env, value); v8::callback_scope!(unsafe scope, env.context()); let Some(object) = object.and_then(|o| o.to_object(scope)) else { return napi_object_expected; }; if !object .set_index(scope, index, value.unwrap()) .unwrap_or(false) { return napi_generic_failure; } napi_ok } #[napi_sym] fn napi_has_element( env: &mut Env, object: napi_value, index: u32, result: *mut bool, ) -> napi_status { check_arg!(env, result); v8::callback_scope!(unsafe scope, env.context()); let Some(object) = object.and_then(|o| o.to_object(scope)) else { return napi_object_expected; }; let Some(has) = object.has_index(scope, index) else { return napi_generic_failure; }; unsafe { *result = has; } napi_ok } #[napi_sym] fn napi_get_element<'s>( env: &'s mut Env, object: napi_value, index: u32, result: *mut napi_value<'s>, ) -> napi_status { check_arg!(env, result); v8::callback_scope!(unsafe scope, env.context()); let Some(object) = object.and_then(|o| o.to_object(scope)) else { return napi_object_expected; }; let Some(value) = object.get_index(scope, index) else { return napi_generic_failure; }; unsafe { *result = value.into(); } napi_ok } #[napi_sym] fn napi_delete_element( env: &mut Env, object: napi_value, index: u32, result: *mut bool, ) -> napi_status { v8::callback_scope!(unsafe scope, env.context()); let Some(object) = object.and_then(|o| o.to_object(scope)) else { return napi_object_expected; }; let Some(deleted) = object.delete_index(scope, index) else { return napi_generic_failure; }; if !result.is_null() { unsafe { *result = deleted; } } napi_ok } #[napi_sym] fn napi_define_properties( env: &mut Env, object: napi_value, property_count: usize, properties: *const napi_property_descriptor, ) -> napi_status { let env_ptr = env as *mut Env; if property_count > 0 { check_arg!(env, properties); } v8::callback_scope!(unsafe scope, env.context()); let Some(object) = object.and_then(|o| o.to_object(scope)) else { return napi_object_expected; }; let properties = if property_count == 0 { &[] } else { unsafe { std::slice::from_raw_parts(properties, property_count) } }; for property in properties { let property_name = match unsafe { v8_name_from_property_descriptor(env_ptr, property) } { Ok(name) => name, Err(status) => return status, }; let writable = property.attributes & napi_writable != 0; let enumerable = property.attributes & napi_enumerable != 0; let configurable = property.attributes & napi_configurable != 0; if property.getter.is_some() || property.setter.is_some() { let local_getter: v8::Local<v8::Value> = if let Some(getter) = property.getter { v8::callback_scope!(unsafe scope, env.context()); create_function(scope, env_ptr, None, getter, property.data).into() } else { v8::undefined(scope).into() }; let local_setter: v8::Local<v8::Value> = if let Some(setter) = property.setter { v8::callback_scope!(unsafe scope, env.context()); create_function(scope, env_ptr, None, setter, property.data).into() } else { v8::undefined(scope).into() }; let mut desc = v8::PropertyDescriptor::new_from_get_set(local_getter, local_setter); desc.set_enumerable(enumerable); desc.set_configurable(configurable); if !object .define_property(scope, property_name, &desc) .unwrap_or(false) { return napi_invalid_arg; } } else if let Some(method) = property.method { let method: v8::Local<v8::Value> = { v8::callback_scope!(unsafe scope, env.context()); let function = create_function(scope, env_ptr, None, method, property.data); function.into() }; let mut desc = v8::PropertyDescriptor::new_from_value_writable(method, writable); desc.set_enumerable(enumerable); desc.set_configurable(configurable); if !object .define_property(scope, property_name, &desc) .unwrap_or(false) { return napi_generic_failure; } } else { let value = property.value.unwrap(); if enumerable & writable & configurable { if !object .create_data_property(scope, property_name, value) .unwrap_or(false) { return napi_invalid_arg; } } else { let mut desc = v8::PropertyDescriptor::new_from_value_writable(value, writable); desc.set_enumerable(enumerable); desc.set_configurable(configurable); if !object .define_property(scope, property_name, &desc) .unwrap_or(false) { return napi_invalid_arg; } } } } napi_ok } #[napi_sym] fn napi_object_freeze(env: &mut Env, object: napi_value) -> napi_status { v8::callback_scope!(unsafe scope, env.context()); let Some(object) = object.and_then(|o| o.to_object(scope)) else { return napi_object_expected; }; if !object .set_integrity_level(scope, v8::IntegrityLevel::Frozen) .unwrap_or(false) { return napi_generic_failure; } napi_ok } #[napi_sym] fn napi_object_seal(env: &mut Env, object: napi_value) -> napi_status { v8::callback_scope!(unsafe scope, env.context()); let Some(object) = object.and_then(|o| o.to_object(scope)) else { return napi_object_expected; }; if !object .set_integrity_level(scope, v8::IntegrityLevel::Sealed) .unwrap_or(false) { return napi_generic_failure; } napi_ok } #[napi_sym] fn napi_is_array( env: *mut Env, value: napi_value, result: *mut bool, ) -> napi_status { let env = check_env!(env); check_arg!(env, value); check_arg!(env, result); let value = value.unwrap(); unsafe { *result = value.is_array(); } napi_clear_last_error(env) } #[napi_sym] fn napi_get_array_length( env: &mut Env, value: napi_value, result: *mut u32, ) -> napi_status { check_arg!(env, value); check_arg!(env, result); let value = value.unwrap(); match v8::Local::<v8::Array>::try_from(value) { Ok(array) => { unsafe { *result = array.length(); } napi_ok } Err(_) => napi_array_expected, } } #[napi_sym] fn napi_strict_equals( env: &mut Env, lhs: napi_value, rhs: napi_value, result: *mut bool, ) -> napi_status { check_arg!(env, lhs); check_arg!(env, rhs); check_arg!(env, result); unsafe { *result = lhs.unwrap().strict_equals(rhs.unwrap()); } napi_ok } #[napi_sym] fn napi_get_prototype<'s>( env: &'s mut Env, object: napi_value, result: *mut napi_value<'s>, ) -> napi_status { check_arg!(env, result); v8::callback_scope!(unsafe scope, env.context()); let Some(object) = object.and_then(|o| o.to_object(scope)) else { return napi_object_expected; }; let Some(proto) = object.get_prototype(scope) else { return napi_generic_failure; }; unsafe { *result = proto.into(); } napi_ok } #[napi_sym] fn napi_create_object( env_ptr: *mut Env, result: *mut napi_value, ) -> napi_status { let env = check_env!(env_ptr); check_arg!(env, result); unsafe { v8::callback_scope!(unsafe scope, env.context()); *result = v8::Object::new(scope).into(); } return napi_clear_last_error(env_ptr); } #[napi_sym] fn napi_create_array( env_ptr: *mut Env, result: *mut napi_value, ) -> napi_status { let env = check_env!(env_ptr); check_arg!(env, result); unsafe { v8::callback_scope!(unsafe scope, env.context()); *result = v8::Array::new(scope, 0).into(); } return napi_clear_last_error(env_ptr); } #[napi_sym] fn napi_create_array_with_length( env_ptr: *mut Env, length: usize, result: *mut napi_value, ) -> napi_status { let env = check_env!(env_ptr); check_arg!(env, result); unsafe { v8::callback_scope!(unsafe scope, env.context()); *result = v8::Array::new(scope, length as _).into(); } return napi_clear_last_error(env_ptr); } #[napi_sym] fn napi_create_string_latin1( env_ptr: *mut Env, string: *const c_char, length: usize, result: *mut napi_value, ) -> napi_status { let env = check_env!(env_ptr); if length > 0 { check_arg!(env, string); } crate::return_status_if_false!( env, (length == NAPI_AUTO_LENGTH) || length <= INT_MAX as _, napi_invalid_arg ); let buffer = if length > 0 { unsafe { std::slice::from_raw_parts( string as _, if length == NAPI_AUTO_LENGTH { std::ffi::CStr::from_ptr(string).to_bytes().len() } else { length }, ) } } else { &[] }; let Some(string) = ({ v8::callback_scope!(unsafe scope, env.context()); v8::String::new_from_one_byte(scope, buffer, v8::NewStringType::Normal) }) else { return napi_set_last_error(env_ptr, napi_generic_failure); }; unsafe { *result = string.into(); } return napi_clear_last_error(env_ptr); } #[napi_sym] pub(crate) fn napi_create_string_utf8( env_ptr: *mut Env, string: *const c_char, length: usize, result: *mut napi_value, ) -> napi_status { let env = check_env!(env_ptr); if length > 0 { check_arg!(env, string); } crate::return_status_if_false!( env, (length == NAPI_AUTO_LENGTH) || length <= INT_MAX as _, napi_invalid_arg ); let buffer = if length > 0 { unsafe { std::slice::from_raw_parts( string as _, if length == NAPI_AUTO_LENGTH { std::ffi::CStr::from_ptr(string).to_bytes().len() } else { length }, ) } } else { &[] }; let Some(string) = ({ v8::callback_scope!(unsafe scope, env.context()); v8::String::new_from_utf8(scope, buffer, v8::NewStringType::Normal) }) else { return napi_set_last_error(env_ptr, napi_generic_failure); }; unsafe { *result = string.into(); } return napi_clear_last_error(env_ptr); } #[napi_sym] fn napi_create_string_utf16( env_ptr: *mut Env, string: *const u16, length: usize, result: *mut napi_value, ) -> napi_status { let env = check_env!(env_ptr); if length > 0 { check_arg!(env, string); } crate::return_status_if_false!( env, (length == NAPI_AUTO_LENGTH) || length <= INT_MAX as _, napi_invalid_arg ); let buffer = if length > 0 { unsafe { std::slice::from_raw_parts( string, if length == NAPI_AUTO_LENGTH { let mut length = 0; while *(string.add(length)) != 0 { length += 1; } length } else { length }, ) } } else { &[] }; v8::callback_scope!(unsafe scope, env.context()); let Some(string) = v8::String::new_from_two_byte(scope, buffer, v8::NewStringType::Normal) else { return napi_set_last_error(env_ptr, napi_generic_failure); }; unsafe { *result = string.into(); } return napi_clear_last_error(env_ptr); } #[napi_sym] fn node_api_create_external_string_latin1( env_ptr: *mut Env, string: *const c_char, length: usize, nogc_finalize_callback: Option<napi_finalize>, finalize_hint: *mut c_void, result: *mut napi_value, copied: *mut bool, ) -> napi_status { let status = unsafe { napi_create_string_latin1(env_ptr, string, length, result) }; if status == napi_ok { unsafe { *copied = true; } if let Some(finalize) = nogc_finalize_callback { unsafe { finalize(env_ptr as napi_env, string as *mut c_void, finalize_hint); } } } status } #[napi_sym] fn node_api_create_external_string_utf16( env_ptr: *mut Env, string: *const u16, length: usize, nogc_finalize_callback: Option<napi_finalize>, finalize_hint: *mut c_void, result: *mut napi_value, copied: *mut bool, ) -> napi_status { let status = unsafe { napi_create_string_utf16(env_ptr, string, length, result) }; if status == napi_ok { unsafe { *copied = true; } if let Some(finalize) = nogc_finalize_callback { unsafe { finalize(env_ptr as napi_env, string as *mut c_void, finalize_hint); } } } status } #[napi_sym] fn node_api_create_property_key_utf16( env_ptr: *mut Env, string: *const u16, length: usize, result: *mut napi_value, ) -> napi_status { let env = check_env!(env_ptr); if length > 0 { check_arg!(env, string); } crate::return_status_if_false!( env, (length == NAPI_AUTO_LENGTH) || length <= INT_MAX as _, napi_invalid_arg ); let buffer = if length > 0 { unsafe { std::slice::from_raw_parts( string, if length == NAPI_AUTO_LENGTH { let mut length = 0; while *(string.add(length)) != 0 { length += 1; } length } else { length }, ) } } else { &[] }; v8::callback_scope!(unsafe scope, env.context()); let Some(string) = v8::String::new_from_two_byte( scope, buffer, v8::NewStringType::Internalized, ) else { return napi_set_last_error(env_ptr, napi_generic_failure); }; unsafe { *result = string.into(); } return napi_clear_last_error(env_ptr); } #[napi_sym] fn napi_create_double( env_ptr: *mut Env, value: f64, result: *mut napi_value, ) -> napi_status { let env = check_env!(env_ptr); check_arg!(env, result); v8::callback_scope!(unsafe scope, env.context()); unsafe { *result = v8::Number::new(scope, value).into(); } napi_clear_last_error(env_ptr) } #[napi_sym] fn napi_create_int32( env_ptr: *mut Env, value: i32, result: *mut napi_value, ) -> napi_status { let env = check_env!(env_ptr); check_arg!(env, result); v8::callback_scope!(unsafe scope, env.context()); unsafe { *result = v8::Integer::new(scope, value).into(); } napi_clear_last_error(env_ptr) } #[napi_sym] fn napi_create_uint32( env_ptr: *mut Env, value: u32, result: *mut napi_value, ) -> napi_status { let env = check_env!(env_ptr); check_arg!(env, result); v8::callback_scope!(unsafe scope, env.context()); unsafe { *result = v8::Integer::new_from_unsigned(scope, value).into(); } napi_clear_last_error(env_ptr) } #[napi_sym] fn napi_create_int64( env_ptr: *mut Env, value: i64, result: *mut napi_value, ) -> napi_status { let env = check_env!(env_ptr); check_arg!(env, result); v8::callback_scope!(unsafe scope, env.context()); unsafe { *result = v8::Number::new(scope, value as _).into(); } napi_clear_last_error(env_ptr) } #[napi_sym] fn napi_create_bigint_int64( env_ptr: *mut Env, value: i64, result: *mut napi_value, ) -> napi_status { let env = check_env!(env_ptr); check_arg!(env, result); v8::callback_scope!(unsafe scope, env.context()); unsafe { *result = v8::BigInt::new_from_i64(scope, value).into(); } napi_clear_last_error(env_ptr) } #[napi_sym] fn napi_create_bigint_uint64( env_ptr: *mut Env, value: u64, result: *mut napi_value, ) -> napi_status { let env = check_env!(env_ptr); check_arg!(env, result); v8::callback_scope!(unsafe scope, env.context()); unsafe { *result = v8::BigInt::new_from_u64(scope, value).into(); } napi_clear_last_error(env_ptr) } #[napi_sym] fn napi_create_bigint_words<'s>( env: &'s mut Env, sign_bit: bool, word_count: usize, words: *const u64, result: *mut napi_value<'s>, ) -> napi_status { check_arg!(env, words); check_arg!(env, result); if word_count > INT_MAX as _ { return napi_invalid_arg; } v8::callback_scope!(unsafe scope, env.context()); match v8::BigInt::new_from_words(scope, sign_bit, unsafe { std::slice::from_raw_parts(words, word_count) }) { Some(value) => unsafe { *result = value.into(); }, None => { return napi_generic_failure; } } napi_ok } #[napi_sym] fn napi_get_boolean( env: *mut Env, value: bool, result: *mut napi_value, ) -> napi_status { let env = check_env!(env); check_arg!(env, result); unsafe { *result = v8::Boolean::new(env.isolate(), value).into(); } return napi_clear_last_error(env); } #[napi_sym] fn napi_create_symbol( env_ptr: *mut Env, description: napi_value, result: *mut napi_value, ) -> napi_status { let env = check_env!(env_ptr); check_arg!(env, result); let description = if let Some(d) = *description { let d = { v8::callback_scope!(unsafe scope, env.context()); d.to_string(scope) }; let Some(d) = d else { return napi_set_last_error(env, napi_string_expected); }; Some(d) } else { None }; v8::callback_scope!(unsafe scope, env.context()); unsafe { *result = v8::Symbol::new(scope, description).into(); } return napi_clear_last_error(env_ptr); } #[napi_sym] fn node_api_symbol_for( env: *mut Env, utf8description: *const c_char, length: usize, result: *mut napi_value, ) -> napi_status { { let env = check_env!(env); check_arg!(env, result); let description_string = match unsafe { check_new_from_utf8_len(env, utf8description, length) } { Ok(s) => s,
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
true
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/napi/build.rs
ext/napi/build.rs
// Copyright 2018-2025 the Deno authors. MIT license. fn main() { let symbols_file_name = match std::env::consts::OS { "android" | "freebsd" | "openbsd" => { "generated_symbol_exports_list_linux.def".to_string() } os => format!("generated_symbol_exports_list_{}.def", os), }; let symbols_path = std::path::Path::new(".") .join(symbols_file_name) .canonicalize() .expect( "Missing symbols list! Generate using tools/napi/generate_symbols_lists.js", ); println!("cargo:rustc-rerun-if-changed={}", symbols_path.display()); let path = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap()) .join("napi_symbol_path.txt"); std::fs::write(path, symbols_path.as_os_str().as_encoded_bytes()).unwrap(); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/napi/util.rs
ext/napi/util.rs
// Copyright 2018-2025 the Deno authors. MIT license. use libc::INT_MAX; use crate::*; #[repr(transparent)] pub(crate) struct SendPtr<T>(pub *const T); impl<T> SendPtr<T> { // silly function to get around `clippy::redundant_locals` pub fn take(self) -> *const T { self.0 } } unsafe impl<T> Send for SendPtr<T> {} unsafe impl<T> Sync for SendPtr<T> {} pub fn get_array_buffer_ptr(ab: v8::Local<v8::ArrayBuffer>) -> *mut c_void { match ab.data() { Some(p) => p.as_ptr(), None => std::ptr::null_mut(), } } struct BufferFinalizer { env: *mut Env, finalize_cb: Option<napi_finalize>, finalize_data: *mut c_void, finalize_hint: *mut c_void, } impl Drop for BufferFinalizer { fn drop(&mut self) { if let Some(finalize_cb) = self.finalize_cb { unsafe { finalize_cb(self.env as _, self.finalize_data, self.finalize_hint); } } } } pub(crate) extern "C" fn backing_store_deleter_callback( data: *mut c_void, _byte_length: usize, deleter_data: *mut c_void, ) { let mut finalizer = unsafe { Box::<BufferFinalizer>::from_raw(deleter_data as _) }; finalizer.finalize_data = data; drop(finalizer); } pub(crate) fn make_external_backing_store( env: *mut Env, data: *mut c_void, byte_length: usize, finalize_data: *mut c_void, finalize_cb: Option<napi_finalize>, finalize_hint: *mut c_void, ) -> v8::UniqueRef<v8::BackingStore> { let finalizer = Box::new(BufferFinalizer { env, finalize_data, finalize_cb, finalize_hint, }); unsafe { v8::ArrayBuffer::new_backing_store_from_ptr( data, byte_length, backing_store_deleter_callback, Box::into_raw(finalizer) as _, ) } } #[macro_export] macro_rules! check_env { ($env: expr) => {{ let env = $env; if env.is_null() { return napi_invalid_arg; } unsafe { &mut *env } }}; } #[macro_export] macro_rules! return_error_status_if_false { ($env: expr, $condition: expr, $status: ident) => { if !$condition { return Err($crate::util::napi_set_last_error($env, $status).into()); } }; } #[macro_export] macro_rules! return_status_if_false { ($env: expr, $condition: expr, $status: ident) => { if !$condition { return $crate::util::napi_set_last_error($env, $status); } }; } pub(crate) unsafe fn check_new_from_utf8_len<'s>( env: *mut Env, str_: *const c_char, len: usize, ) -> Result<v8::Local<'s, v8::String>, napi_status> { let env = unsafe { &mut *env }; return_error_status_if_false!( env, (len == NAPI_AUTO_LENGTH) || len <= INT_MAX as _, napi_invalid_arg ); return_error_status_if_false!(env, !str_.is_null(), napi_invalid_arg); let string = if len == NAPI_AUTO_LENGTH { unsafe { std::ffi::CStr::from_ptr(str_ as *const _) }.to_bytes() } else { unsafe { std::slice::from_raw_parts(str_ as *const u8, len) } }; let result = { let env = unsafe { &mut *(env as *mut Env) }; v8::callback_scope!(unsafe scope, env.context()); v8::String::new_from_utf8(scope, string, v8::NewStringType::Internalized) }; return_error_status_if_false!(env, result.is_some(), napi_generic_failure); Ok(result.unwrap()) } #[inline] pub(crate) unsafe fn check_new_from_utf8<'s>( env: *mut Env, str_: *const c_char, ) -> Result<v8::Local<'s, v8::String>, napi_status> { unsafe { check_new_from_utf8_len(env, str_, NAPI_AUTO_LENGTH) } } pub(crate) unsafe fn v8_name_from_property_descriptor<'s>( env: *mut Env, p: &'s napi_property_descriptor, ) -> Result<v8::Local<'s, v8::Name>, napi_status> { if !p.utf8name.is_null() { unsafe { check_new_from_utf8(env, p.utf8name).map(|v| v.into()) } } else { match *p.name { Some(v) => match v.try_into() { Ok(name) => Ok(name), Err(_) => Err(napi_name_expected), }, None => Err(napi_name_expected), } } } pub(crate) fn napi_clear_last_error(env: *mut Env) -> napi_status { let env = unsafe { &mut *env }; env.last_error.error_code.set(napi_ok); env.last_error.engine_error_code = 0; env.last_error.engine_reserved = std::ptr::null_mut(); env.last_error.error_message = std::ptr::null_mut(); napi_ok } pub(crate) fn napi_set_last_error( env: *const Env, error_code: napi_status, ) -> napi_status { let env = unsafe { &*env }; env.last_error.error_code.set(error_code); error_code } #[macro_export] macro_rules! status_call { ($call: expr) => { let status = $call; if status != napi_ok { return status; } }; } pub trait Nullable { fn is_null(&self) -> bool; } impl<T> Nullable for *mut T { fn is_null(&self) -> bool { (*self).is_null() } } impl<T> Nullable for *const T { fn is_null(&self) -> bool { (*self).is_null() } } impl<T> Nullable for Option<T> { fn is_null(&self) -> bool { self.is_none() } } impl Nullable for napi_value<'_> { fn is_null(&self) -> bool { self.is_none() } } #[macro_export] macro_rules! check_arg { ($env: expr, $ptr: expr) => { $crate::return_status_if_false!( $env, !$crate::util::Nullable::is_null(&$ptr), napi_invalid_arg ); }; } #[macro_export] macro_rules! napi_wrap { ( $( # [ $attr:meta ] )* $vis:vis fn $name:ident $( < $( $x:lifetime ),* > )? ( $env:ident : & $( $lt:lifetime )? mut Env $( , $ident:ident : $ty:ty )* $(,)? ) -> napi_status $body:block ) => { $( # [ $attr ] )* #[unsafe(no_mangle)] $vis unsafe extern "C" fn $name $( < $( $x ),* > )? ( env_ptr : *mut Env , $( $ident : $ty ),* ) -> napi_status { let env: & $( $lt )? mut Env = $crate::check_env!(env_ptr); if env.last_exception.is_some() { return napi_pending_exception; } $crate::util::napi_clear_last_error(env); let scope_env = unsafe { &mut *env_ptr }; deno_core::v8::callback_scope!(unsafe scope, scope_env.context()); deno_core::v8::tc_scope!(try_catch, scope); #[inline(always)] fn inner $( < $( $x ),* > )? ( $env: & $( $lt )? mut Env , $( $ident : $ty ),* ) -> napi_status $body #[cfg(debug_assertions)] log::trace!("NAPI ENTER: {}", stringify!($name)); let result = inner( env, $( $ident ),* ); #[cfg(debug_assertions)] log::trace!("NAPI EXIT: {} {}", stringify!($name), result); if let Some(exception) = try_catch.exception() { let env = unsafe { &mut *env_ptr }; let global = v8::Global::new(env.isolate(), exception); env.last_exception = Some(global); return $crate::util::napi_set_last_error(env_ptr, napi_pending_exception); } if result != napi_ok { return $crate::util::napi_set_last_error(env_ptr, result); } return result; } }; ( $( # [ $attr:meta ] )* $vis:vis fn $name:ident $( < $( $x:lifetime ),* > )? ( $( $ident:ident : $ty:ty ),* $(,)? ) -> napi_status $body:block ) => { $( # [ $attr ] )* #[unsafe(no_mangle)] $vis unsafe extern "C" fn $name $( < $( $x ),* > )? ( $( $ident : $ty ),* ) -> napi_status { #[inline(always)] fn inner $( < $( $x ),* > )? ( $( $ident : $ty ),* ) -> napi_status $body #[cfg(debug_assertions)] log::trace!("NAPI ENTER: {}", stringify!($name)); let result = inner( $( $ident ),* ); #[cfg(debug_assertions)] log::trace!("NAPI EXIT: {} {}", stringify!($name), result); result } }; }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/napi/node_api.rs
ext/napi/node_api.rs
// Copyright 2018-2025 the Deno authors. MIT license. #![deny(unsafe_op_in_unsafe_fn)] use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicU8; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use deno_core::V8CrossThreadTaskSpawner; use deno_core::parking_lot::Condvar; use deno_core::parking_lot::Mutex; use napi_sym::napi_sym; use super::util::SendPtr; use super::util::get_array_buffer_ptr; use super::util::make_external_backing_store; use super::util::napi_clear_last_error; use super::util::napi_set_last_error; use crate::check_arg; use crate::check_env; use crate::*; #[napi_sym] fn napi_module_register(module: *const NapiModule) -> napi_status { MODULE_TO_REGISTER.with(|cell| { let mut slot = cell.borrow_mut(); let prev = slot.replace(module); assert!(prev.is_none()); }); napi_ok } #[napi_sym] fn napi_add_env_cleanup_hook( env: *mut Env, fun: Option<napi_cleanup_hook>, arg: *mut c_void, ) -> napi_status { let env = check_env!(env); check_arg!(env, fun); let fun = fun.unwrap(); env.add_cleanup_hook(fun, arg); napi_ok } #[napi_sym] fn napi_remove_env_cleanup_hook( env: *mut Env, fun: Option<napi_cleanup_hook>, arg: *mut c_void, ) -> napi_status { let env = check_env!(env); check_arg!(env, fun); let fun = fun.unwrap(); env.remove_cleanup_hook(fun, arg); napi_ok } struct AsyncCleanupHandle { env: *mut Env, hook: napi_async_cleanup_hook, data: *mut c_void, } unsafe extern "C" fn async_cleanup_handler(arg: *mut c_void) { unsafe { let handle = Box::<AsyncCleanupHandle>::from_raw(arg as _); (handle.hook)(arg, handle.data); } } #[napi_sym] fn napi_add_async_cleanup_hook( env: *mut Env, hook: Option<napi_async_cleanup_hook>, arg: *mut c_void, remove_handle: *mut napi_async_cleanup_hook_handle, ) -> napi_status { let env = check_env!(env); check_arg!(env, hook); let hook = hook.unwrap(); let handle = Box::into_raw(Box::new(AsyncCleanupHandle { env, hook, data: arg, })) as *mut c_void; env.add_cleanup_hook(async_cleanup_handler, handle); if !remove_handle.is_null() { unsafe { *remove_handle = handle; } } napi_clear_last_error(env) } #[napi_sym] fn napi_remove_async_cleanup_hook( remove_handle: napi_async_cleanup_hook_handle, ) -> napi_status { if remove_handle.is_null() { return napi_invalid_arg; } let handle = unsafe { Box::<AsyncCleanupHandle>::from_raw(remove_handle as _) }; let env = unsafe { &mut *handle.env }; env.remove_cleanup_hook(async_cleanup_handler, remove_handle); napi_ok } #[napi_sym] fn napi_fatal_exception(env: &mut Env, err: napi_value) -> napi_status { check_arg!(env, err); v8::callback_scope!(unsafe scope, env.context()); let report_error = v8::Local::new(scope, &env.report_error); let this = v8::undefined(scope); if report_error .call(scope, this.into(), &[err.unwrap()]) .is_none() { return napi_generic_failure; } napi_ok } #[napi_sym] fn napi_fatal_error( location: *const c_char, location_len: usize, message: *const c_char, message_len: usize, ) -> napi_status { let location = if location.is_null() { None } else { unsafe { Some(if location_len == NAPI_AUTO_LENGTH { std::ffi::CStr::from_ptr(location).to_str().unwrap() } else { let slice = std::slice::from_raw_parts( location as *const u8, location_len as usize, ); std::str::from_utf8(slice).unwrap() }) } }; let message = if message_len == NAPI_AUTO_LENGTH { unsafe { std::ffi::CStr::from_ptr(message).to_str().unwrap() } } else { let slice = unsafe { std::slice::from_raw_parts(message as *const u8, message_len as usize) }; std::str::from_utf8(slice).unwrap() }; if let Some(location) = location { log::error!("NODE API FATAL ERROR: {} {}", location, message); } else { log::error!("NODE API FATAL ERROR: {}", message); } std::process::abort(); } #[napi_sym] fn napi_open_callback_scope( env: *mut Env, _resource_object: napi_value, _context: napi_value, result: *mut napi_callback_scope, ) -> napi_status { let env = check_env!(env); check_arg!(env, result); // we open scope automatically when it's needed unsafe { *result = std::ptr::null_mut(); } napi_clear_last_error(env) } #[napi_sym] fn napi_close_callback_scope( env: *mut Env, scope: napi_callback_scope, ) -> napi_status { let env = check_env!(env); // we close scope automatically when it's needed assert!(scope.is_null()); napi_clear_last_error(env) } // NOTE: we don't support "async_hooks::AsyncContext" so these APIs are noops. #[napi_sym] fn napi_async_init( env: *mut Env, _async_resource: napi_value, _async_resource_name: napi_value, result: *mut napi_async_context, ) -> napi_status { let env = check_env!(env); unsafe { *result = ptr::null_mut(); } napi_clear_last_error(env) } #[napi_sym] fn napi_async_destroy( env: *mut Env, async_context: napi_async_context, ) -> napi_status { let env = check_env!(env); assert!(async_context.is_null()); napi_clear_last_error(env) } #[napi_sym] fn napi_make_callback<'s>( env: &'s mut Env, _async_context: napi_async_context, recv: napi_value, func: napi_value, argc: usize, argv: *const napi_value<'s>, result: *mut napi_value<'s>, ) -> napi_status { check_arg!(env, recv); if argc > 0 { check_arg!(env, argv); } v8::callback_scope!(unsafe scope, env.context()); let Some(recv) = recv.and_then(|v| v.to_object(scope)) else { return napi_object_expected; }; let Some(func) = func.and_then(|v| v8::Local::<v8::Function>::try_from(v).ok()) else { return napi_function_expected; }; let args = if argc > 0 { unsafe { std::slice::from_raw_parts(argv as *mut v8::Local<v8::Value>, argc) } } else { &[] }; // TODO: async_context let Some(v) = func.call(scope, recv.into(), args) else { return napi_generic_failure; }; unsafe { *result = v.into(); } napi_ok } #[napi_sym] fn napi_create_buffer<'s>( env: &'s mut Env, length: usize, data: *mut *mut c_void, result: *mut napi_value<'s>, ) -> napi_status { check_arg!(env, result); v8::callback_scope!(unsafe scope, env.context()); let ab = v8::ArrayBuffer::new(scope, length); let create_buffer = v8::Local::new(scope, &env.create_buffer); let recv = v8::null(scope).into(); let Some(buffer) = create_buffer.call(scope, recv, &[ab.into()]) else { return napi_generic_failure; }; if !data.is_null() { unsafe { *data = get_array_buffer_ptr(ab); } } unsafe { *result = buffer.into(); } napi_ok } #[napi_sym] fn napi_create_external_buffer<'s>( env: &'s mut Env, length: usize, data: *mut c_void, finalize_cb: Option<napi_finalize>, finalize_hint: *mut c_void, result: *mut napi_value<'s>, ) -> napi_status { check_arg!(env, result); let store = make_external_backing_store( env, data, length, ptr::null_mut(), finalize_cb, finalize_hint, ); v8::callback_scope!(unsafe scope, env.context()); let ab = v8::ArrayBuffer::with_backing_store(scope, &store.make_shared()); let create_buffer = v8::Local::new(scope, &env.create_buffer); let recv = v8::null(scope).into(); let Some(buffer) = create_buffer.call(scope, recv, &[ab.into()]) else { return napi_generic_failure; }; unsafe { *result = buffer.into(); } napi_ok } #[napi_sym] fn napi_create_buffer_copy<'s>( env: &'s mut Env, length: usize, data: *mut c_void, result_data: *mut *mut c_void, result: *mut napi_value<'s>, ) -> napi_status { check_arg!(env, result); v8::callback_scope!(unsafe scope, env.context()); let ab = v8::ArrayBuffer::new(scope, length); let create_buffer = v8::Local::new(scope, &env.create_buffer); let recv = v8::null(scope).into(); let Some(buffer) = create_buffer.call(scope, recv, &[ab.into()]) else { return napi_generic_failure; }; let ptr = get_array_buffer_ptr(ab); unsafe { std::ptr::copy(data, ptr, length); } if !result_data.is_null() { unsafe { *result_data = ptr; } } unsafe { *result = buffer.into(); } napi_ok } #[napi_sym] fn napi_is_buffer( env: *mut Env, value: napi_value, result: *mut bool, ) -> napi_status { let env = check_env!(env); check_arg!(env, value); check_arg!(env, result); unsafe { *result = value.unwrap().is_array_buffer_view(); } napi_clear_last_error(env) } #[napi_sym] fn napi_get_buffer_info( env: *mut Env, value: napi_value, data: *mut *mut c_void, length: *mut usize, ) -> napi_status { let env = check_env!(env); check_arg!(env, value); // NB: Any TypedArray instance seems to be accepted by this function // in Node.js. let Some(ta) = value.and_then(|v| v8::Local::<v8::TypedArray>::try_from(v).ok()) else { return napi_set_last_error(env, napi_invalid_arg); }; if !data.is_null() { unsafe { *data = ta.data(); } } if !length.is_null() { unsafe { *length = ta.byte_length(); } } napi_clear_last_error(env) } #[napi_sym] fn napi_get_node_version( env: *mut Env, result: *mut *const napi_node_version, ) -> napi_status { let env = check_env!(env); check_arg!(env, result); const NODE_VERSION: napi_node_version = napi_node_version { major: 20, minor: 11, patch: 1, release: c"Deno".as_ptr(), }; unsafe { *result = &NODE_VERSION as *const napi_node_version; } napi_clear_last_error(env) } struct AsyncWork { state: AtomicU8, env: *mut Env, _async_resource: v8::Global<v8::Object>, _async_resource_name: String, execute: napi_async_execute_callback, complete: Option<napi_async_complete_callback>, data: *mut c_void, } impl AsyncWork { const IDLE: u8 = 0; const QUEUED: u8 = 1; const RUNNING: u8 = 2; } #[napi_sym] pub(crate) fn napi_create_async_work( env: *mut Env, async_resource: napi_value, async_resource_name: napi_value, execute: Option<napi_async_execute_callback>, complete: Option<napi_async_complete_callback>, data: *mut c_void, result: *mut napi_async_work, ) -> napi_status { let env_ptr = env; let env = check_env!(env); check_arg!(env, execute); check_arg!(env, result); let work = { v8::callback_scope!(unsafe scope, env.context()); let resource = if let Some(v) = *async_resource { let Some(resource) = v.to_object(scope) else { return napi_set_last_error(env, napi_object_expected); }; resource } else { v8::Object::new(scope) }; let Some(resource_name) = async_resource_name.and_then(|v| v.to_string(scope)) else { return napi_set_last_error(env, napi_string_expected); }; let resource_name = resource_name.to_rust_string_lossy(scope); Box::new(AsyncWork { state: AtomicU8::new(AsyncWork::IDLE), env: env_ptr, _async_resource: v8::Global::new(scope, resource), _async_resource_name: resource_name, execute: execute.unwrap(), complete, data, }) }; unsafe { *result = Box::into_raw(work) as _; } napi_clear_last_error(env) } #[napi_sym] pub(crate) fn napi_delete_async_work( env: *mut Env, work: napi_async_work, ) -> napi_status { let env = check_env!(env); check_arg!(env, work); drop(unsafe { Box::<AsyncWork>::from_raw(work as _) }); napi_clear_last_error(env) } #[napi_sym] fn napi_get_uv_event_loop( env_ptr: *mut Env, uv_loop: *mut *mut (), ) -> napi_status { let env = check_env!(env_ptr); check_arg!(env, uv_loop); unsafe { *uv_loop = env_ptr.cast(); } 0 } #[napi_sym] pub(crate) fn napi_queue_async_work( env: *mut Env, work: napi_async_work, ) -> napi_status { let env = check_env!(env); check_arg!(env, work); let work = unsafe { &*(work as *mut AsyncWork) }; let result = work .state .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |state| { // allow queue if idle or if running, but not if already queued. if state == AsyncWork::IDLE || state == AsyncWork::RUNNING { Some(AsyncWork::QUEUED) } else { None } }); if result.is_err() { return napi_clear_last_error(env); } let work = SendPtr(work); env.add_async_work(move || { let work = work.take(); let work = unsafe { &*work }; let state = work.state.compare_exchange( AsyncWork::QUEUED, AsyncWork::RUNNING, Ordering::SeqCst, Ordering::SeqCst, ); if state.is_ok() { unsafe { (work.execute)(work.env as _, work.data); } // reset back to idle if its still marked as running let _ = work.state.compare_exchange( AsyncWork::RUNNING, AsyncWork::IDLE, Ordering::SeqCst, Ordering::Relaxed, ); } if let Some(complete) = work.complete { let status = if state.is_ok() { napi_ok } else if state == Err(AsyncWork::IDLE) { napi_cancelled } else { napi_generic_failure }; unsafe { complete(work.env as _, status, work.data); } } // `complete` probably deletes this `work`, so don't use it here. }); napi_clear_last_error(env) } #[napi_sym] fn napi_cancel_async_work(env: *mut Env, work: napi_async_work) -> napi_status { let env = check_env!(env); check_arg!(env, work); let work = unsafe { &*(work as *mut AsyncWork) }; let _ = work.state.compare_exchange( AsyncWork::QUEUED, AsyncWork::IDLE, Ordering::SeqCst, Ordering::Relaxed, ); napi_clear_last_error(env) } extern "C" fn default_call_js_cb( env: napi_env, js_callback: napi_value, _context: *mut c_void, _data: *mut c_void, ) { if let Some(js_callback) = *js_callback && let Ok(js_callback) = v8::Local::<v8::Function>::try_from(js_callback) { let env = unsafe { &mut *(env as *mut Env) }; v8::callback_scope!(unsafe scope, env.context()); let recv = v8::undefined(scope); js_callback.call(scope, recv.into(), &[]); } } struct TsFn { env: *mut Env, func: Option<v8::Global<v8::Function>>, max_queue_size: usize, queue_size: Mutex<usize>, queue_cond: Condvar, thread_count: AtomicUsize, thread_finalize_data: *mut c_void, thread_finalize_cb: Option<napi_finalize>, context: *mut c_void, call_js_cb: napi_threadsafe_function_call_js, _resource: v8::Global<v8::Object>, _resource_name: String, is_closing: AtomicBool, is_closed: Arc<AtomicBool>, sender: V8CrossThreadTaskSpawner, is_ref: AtomicBool, } impl Drop for TsFn { fn drop(&mut self) { assert!( self .is_closed .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed) .is_ok() ); self.unref(); if let Some(finalizer) = self.thread_finalize_cb { unsafe { (finalizer)(self.env as _, self.thread_finalize_data, self.context); } } } } impl TsFn { pub fn acquire(&self) -> napi_status { if self.is_closing.load(Ordering::SeqCst) { return napi_closing; } self.thread_count.fetch_add(1, Ordering::Relaxed); napi_ok } pub fn release( tsfn: *mut TsFn, mode: napi_threadsafe_function_release_mode, ) -> napi_status { let tsfn = unsafe { &mut *tsfn }; let result = tsfn.thread_count.fetch_update( Ordering::Relaxed, Ordering::Relaxed, |x| { if x == 0 { None } else { Some(x - 1) } }, ); if result.is_err() { return napi_invalid_arg; } if (result == Ok(1) || mode == napi_tsfn_abort) && tsfn .is_closing .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) .is_ok() { tsfn.queue_cond.notify_all(); let tsfnptr = SendPtr(tsfn); // drop must be queued in order to preserve ordering consistent // with Node.js and so that the finalizer runs on the main thread. tsfn.sender.spawn(move |_| { let tsfn = unsafe { Box::from_raw(tsfnptr.take() as *mut TsFn) }; drop(tsfn); }); } napi_ok } pub fn ref_(&self) -> napi_status { if self .is_ref .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) .is_ok() { let env = unsafe { &mut *self.env }; env.threadsafe_function_ref(); } napi_ok } pub fn unref(&self) -> napi_status { if self .is_ref .compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst) .is_ok() { let env = unsafe { &mut *self.env }; env.threadsafe_function_unref(); } napi_ok } pub fn call( &self, data: *mut c_void, mode: napi_threadsafe_function_call_mode, ) -> napi_status { if self.is_closing.load(Ordering::SeqCst) { return napi_closing; } if self.max_queue_size > 0 { let mut queue_size = self.queue_size.lock(); while *queue_size >= self.max_queue_size { if mode == napi_tsfn_blocking { self.queue_cond.wait(&mut queue_size); if self.is_closing.load(Ordering::SeqCst) { return napi_closing; } } else { return napi_queue_full; } } *queue_size += 1; } let is_closed = self.is_closed.clone(); let tsfn = SendPtr(self); let data = SendPtr(data); let context = SendPtr(self.context); let call_js_cb = self.call_js_cb; self.sender.spawn(move |scope: &mut v8::PinScope<'_, '_>| { let data = data.take(); // if is_closed then tsfn is freed, don't read from it. if is_closed.load(Ordering::Relaxed) { unsafe { call_js_cb( std::ptr::null_mut(), None::<v8::Local<v8::Value>>.into(), context.take() as _, data as _, ); } } else { let tsfn = tsfn.take(); let tsfn = unsafe { &*tsfn }; if tsfn.max_queue_size > 0 { let mut queue_size = tsfn.queue_size.lock(); let size = *queue_size; *queue_size -= 1; if size == tsfn.max_queue_size { tsfn.queue_cond.notify_one(); } } let func = tsfn.func.as_ref().map(|f| v8::Local::new(scope, f)); unsafe { (tsfn.call_js_cb)( tsfn.env as _, func.into(), tsfn.context, data as _, ); } } }); napi_ok } } #[napi_sym] #[allow(clippy::too_many_arguments)] fn napi_create_threadsafe_function( env: *mut Env, func: napi_value, async_resource: napi_value, async_resource_name: napi_value, max_queue_size: usize, initial_thread_count: usize, thread_finalize_data: *mut c_void, thread_finalize_cb: Option<napi_finalize>, context: *mut c_void, call_js_cb: Option<napi_threadsafe_function_call_js>, result: *mut napi_threadsafe_function, ) -> napi_status { let env = check_env!(env); check_arg!(env, async_resource_name); if initial_thread_count == 0 { return napi_set_last_error(env, napi_invalid_arg); } check_arg!(env, result); let (func, resource, resource_name) = { v8::callback_scope!(unsafe scope, env.context()); let func = if let Some(value) = *func { let Ok(func) = v8::Local::<v8::Function>::try_from(value) else { return napi_set_last_error(env, napi_function_expected); }; Some(v8::Global::new(scope, func)) } else { check_arg!(env, call_js_cb); None }; let resource = if let Some(v) = *async_resource { let Some(resource) = v.to_object(scope) else { return napi_set_last_error(env, napi_object_expected); }; resource } else { v8::Object::new(scope) }; let resource = v8::Global::new(scope, resource); let Some(resource_name) = async_resource_name.and_then(|v| v.to_string(scope)) else { return napi_set_last_error(env, napi_string_expected); }; let resource_name = resource_name.to_rust_string_lossy(scope); (func, resource, resource_name) }; let tsfn = Box::new(TsFn { env, func, max_queue_size, queue_size: Mutex::new(0), queue_cond: Condvar::new(), thread_count: AtomicUsize::new(initial_thread_count), thread_finalize_data, thread_finalize_cb, context, call_js_cb: call_js_cb.unwrap_or(default_call_js_cb), _resource: resource, _resource_name: resource_name, is_closing: AtomicBool::new(false), is_closed: Arc::new(AtomicBool::new(false)), is_ref: AtomicBool::new(false), sender: env.async_work_sender.clone(), }); tsfn.ref_(); unsafe { *result = Box::into_raw(tsfn) as _; } napi_clear_last_error(env) } /// Maybe called from any thread. #[napi_sym] fn napi_get_threadsafe_function_context( func: napi_threadsafe_function, result: *mut *const c_void, ) -> napi_status { assert!(!func.is_null()); let tsfn = unsafe { &*(func as *const TsFn) }; unsafe { *result = tsfn.context; } napi_ok } #[napi_sym] fn napi_call_threadsafe_function( func: napi_threadsafe_function, data: *mut c_void, is_blocking: napi_threadsafe_function_call_mode, ) -> napi_status { assert!(!func.is_null()); let tsfn = unsafe { &*(func as *mut TsFn) }; tsfn.call(data, is_blocking) } #[napi_sym] fn napi_acquire_threadsafe_function( tsfn: napi_threadsafe_function, ) -> napi_status { assert!(!tsfn.is_null()); let tsfn = unsafe { &*(tsfn as *mut TsFn) }; tsfn.acquire() } #[napi_sym] fn napi_release_threadsafe_function( tsfn: napi_threadsafe_function, mode: napi_threadsafe_function_release_mode, ) -> napi_status { assert!(!tsfn.is_null()); TsFn::release(tsfn as _, mode) } #[napi_sym] fn napi_unref_threadsafe_function( _env: &mut Env, func: napi_threadsafe_function, ) -> napi_status { assert!(!func.is_null()); let tsfn = unsafe { &*(func as *mut TsFn) }; tsfn.unref() } #[napi_sym] fn napi_ref_threadsafe_function( _env: &mut Env, func: napi_threadsafe_function, ) -> napi_status { assert!(!func.is_null()); let tsfn = unsafe { &*(func as *mut TsFn) }; tsfn.ref_() } #[napi_sym] fn node_api_get_module_file_name( env: *mut Env, result: *mut *const c_char, ) -> napi_status { let env = check_env!(env); check_arg!(env, result); unsafe { *result = env.shared().filename.as_ptr() as _; } napi_clear_last_error(env) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/napi/uv.rs
ext/napi/uv.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::mem::MaybeUninit; use std::ptr::addr_of_mut; use deno_core::parking_lot::Mutex; use crate::*; fn assert_ok(res: c_int) -> c_int { if res != 0 { log::error!("bad result in uv polyfill: {res}"); // don't panic because that might unwind into // c/c++ std::process::abort(); } res } use std::ffi::c_int; use js_native_api::napi_create_string_utf8; use node_api::napi_create_async_work; use node_api::napi_delete_async_work; use node_api::napi_queue_async_work; const UV_MUTEX_SIZE: usize = { #[cfg(unix)] { std::mem::size_of::<libc::pthread_mutex_t>() } #[cfg(windows)] { std::mem::size_of::<windows_sys::Win32::System::Threading::CRITICAL_SECTION>( ) } }; #[repr(C)] struct uv_mutex_t { mutex: Mutex<()>, _padding: [MaybeUninit<usize>; const { (UV_MUTEX_SIZE - size_of::<Mutex<()>>()) / size_of::<usize>() }], } #[unsafe(no_mangle)] unsafe extern "C" fn uv_mutex_init(lock: *mut uv_mutex_t) -> c_int { unsafe { addr_of_mut!((*lock).mutex).write(Mutex::new(())); 0 } } #[unsafe(no_mangle)] unsafe extern "C" fn uv_mutex_lock(lock: *mut uv_mutex_t) { unsafe { let guard = (*lock).mutex.lock(); // forget the guard so it doesn't unlock when it goes out of scope. // we're going to unlock it manually std::mem::forget(guard); } } #[unsafe(no_mangle)] unsafe extern "C" fn uv_mutex_unlock(lock: *mut uv_mutex_t) { unsafe { (*lock).mutex.force_unlock(); } } #[unsafe(no_mangle)] unsafe extern "C" fn uv_mutex_destroy(_lock: *mut uv_mutex_t) { // no cleanup required } #[repr(C)] #[derive(Clone, Copy, Debug)] #[allow(dead_code)] enum uv_handle_type { UV_UNKNOWN_HANDLE = 0, UV_ASYNC, UV_CHECK, UV_FS_EVENT, UV_FS_POLL, UV_HANDLE, UV_IDLE, UV_NAMED_PIPE, UV_POLL, UV_PREPARE, UV_PROCESS, UV_STREAM, UV_TCP, UV_TIMER, UV_TTY, UV_UDP, UV_SIGNAL, UV_FILE, UV_HANDLE_TYPE_MAX, } const UV_HANDLE_SIZE: usize = 96; #[repr(C)] struct uv_handle_t { // public members pub data: *mut c_void, pub r#loop: *mut uv_loop_t, pub r#type: uv_handle_type, _padding: [MaybeUninit<usize>; const { (UV_HANDLE_SIZE - size_of::<*mut c_void>() - size_of::<*mut uv_loop_t>() - size_of::<uv_handle_type>()) / size_of::<usize>() }], } #[cfg(unix)] const UV_ASYNC_SIZE: usize = 128; #[cfg(windows)] const UV_ASYNC_SIZE: usize = 224; #[repr(C)] struct uv_async_t { // public members pub data: *mut c_void, pub r#loop: *mut uv_loop_t, pub r#type: uv_handle_type, // private async_cb: uv_async_cb, work: napi_async_work, _padding: [MaybeUninit<usize>; const { (UV_ASYNC_SIZE - size_of::<*mut c_void>() - size_of::<*mut uv_loop_t>() - size_of::<uv_handle_type>() - size_of::<uv_async_cb>() - size_of::<napi_async_work>()) / size_of::<usize>() }], } type uv_loop_t = Env; type uv_async_cb = extern "C" fn(handle: *mut uv_async_t); #[unsafe(no_mangle)] unsafe extern "C" fn uv_async_init( r#loop: *mut uv_loop_t, // probably uninitialized r#async: *mut uv_async_t, async_cb: uv_async_cb, ) -> c_int { unsafe { addr_of_mut!((*r#async).r#loop).write(r#loop); addr_of_mut!((*r#async).r#type).write(uv_handle_type::UV_ASYNC); addr_of_mut!((*r#async).async_cb).write(async_cb); let mut resource_name: MaybeUninit<napi_value> = MaybeUninit::uninit(); assert_ok(napi_create_string_utf8( r#loop, c"uv_async".as_ptr(), usize::MAX, resource_name.as_mut_ptr(), )); let resource_name = resource_name.assume_init(); let res = napi_create_async_work( r#loop, None::<v8::Local<'static, v8::Value>>.into(), resource_name, Some(async_exec_wrap), None, r#async.cast(), addr_of_mut!((*r#async).work), ); -res } } #[unsafe(no_mangle)] unsafe extern "C" fn uv_async_send(handle: *mut uv_async_t) -> c_int { unsafe { -napi_queue_async_work((*handle).r#loop, (*handle).work) } } type uv_close_cb = unsafe extern "C" fn(*mut uv_handle_t); #[unsafe(no_mangle)] unsafe extern "C" fn uv_close(handle: *mut uv_handle_t, close: uv_close_cb) { unsafe { if handle.is_null() { close(handle); return; } if let uv_handle_type::UV_ASYNC = (*handle).r#type { let handle: *mut uv_async_t = handle.cast(); napi_delete_async_work((*handle).r#loop, (*handle).work); } close(handle); } } unsafe extern "C" fn async_exec_wrap(_env: napi_env, data: *mut c_void) { let data: *mut uv_async_t = data.cast(); unsafe { ((*data).async_cb)(data); } } #[cfg(test)] mod tests { use super::*; #[test] fn sizes() { assert_eq!( std::mem::size_of::<libuv_sys_lite::uv_mutex_t>(), UV_MUTEX_SIZE ); assert_eq!( std::mem::size_of::<libuv_sys_lite::uv_handle_t>(), UV_HANDLE_SIZE ); assert_eq!( std::mem::size_of::<libuv_sys_lite::uv_async_t>(), UV_ASYNC_SIZE ); assert_eq!(std::mem::size_of::<uv_mutex_t>(), UV_MUTEX_SIZE); assert_eq!(std::mem::size_of::<uv_handle_t>(), UV_HANDLE_SIZE); assert_eq!(std::mem::size_of::<uv_async_t>(), UV_ASYNC_SIZE); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/napi/sym/lib.rs
ext/napi/sym/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. use proc_macro::TokenStream; use quote::quote; use serde::Deserialize; static NAPI_EXPORTS: &str = include_str!("./symbol_exports.json"); #[derive(Deserialize)] struct SymbolExports { pub symbols: Vec<String>, } #[proc_macro_attribute] pub fn napi_sym(_attr: TokenStream, item: TokenStream) -> TokenStream { let func = syn::parse::<syn::ItemFn>(item).expect("expected a function"); let exports: SymbolExports = serde_json::from_str(NAPI_EXPORTS).expect("failed to parse exports"); let name = &func.sig.ident; assert!( exports.symbols.contains(&name.to_string()), "cli/napi/sym/symbol_exports.json is out of sync!" ); TokenStream::from(quote! { crate::napi_wrap! { #func } }) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/cron/local.rs
ext/cron/local.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::OnceCell; use std::cell::RefCell; use std::collections::BTreeMap; use std::collections::HashMap; use std::env; use std::rc::Rc; use std::rc::Weak; use std::sync::Arc; use async_trait::async_trait; use deno_core::futures; use deno_core::futures::FutureExt; use deno_core::unsync::JoinHandle; use deno_core::unsync::spawn; use tokio::sync::OwnedSemaphorePermit; use tokio::sync::Semaphore; use tokio::sync::mpsc; use tokio::sync::mpsc::WeakSender; use crate::CronError; use crate::CronHandle; use crate::CronHandler; use crate::CronSpec; const MAX_CRONS: usize = 100; const DISPATCH_CONCURRENCY_LIMIT: usize = 50; const MAX_BACKOFF_MS: u32 = 60 * 60 * 1_000; // 1 hour const MAX_BACKOFF_COUNT: usize = 5; const DEFAULT_BACKOFF_SCHEDULE: [u32; 5] = [100, 1_000, 5_000, 30_000, 60_000]; pub struct LocalCronHandler { cron_schedule_tx: OnceCell<mpsc::Sender<(String, bool)>>, concurrency_limiter: Arc<Semaphore>, cron_loop_join_handle: OnceCell<JoinHandle<()>>, runtime_state: Rc<RefCell<RuntimeState>>, } struct RuntimeState { crons: HashMap<String, Cron>, scheduled_deadlines: BTreeMap<u64, Vec<String>>, } struct Cron { spec: CronSpec, next_tx: mpsc::WeakSender<()>, current_execution_retries: u32, } impl Cron { fn backoff_schedule(&self) -> &[u32] { self .spec .backoff_schedule .as_deref() .unwrap_or(&DEFAULT_BACKOFF_SCHEDULE) } } impl Default for LocalCronHandler { fn default() -> Self { Self::new() } } impl LocalCronHandler { pub fn new() -> Self { Self { cron_schedule_tx: OnceCell::new(), concurrency_limiter: Arc::new(Semaphore::new(DISPATCH_CONCURRENCY_LIMIT)), cron_loop_join_handle: OnceCell::new(), runtime_state: Rc::new(RefCell::new(RuntimeState { crons: HashMap::new(), scheduled_deadlines: BTreeMap::new(), })), } } async fn cron_loop( runtime_state: Rc<RefCell<RuntimeState>>, mut cron_schedule_rx: mpsc::Receiver<(String, bool)>, ) -> Result<(), CronError> { loop { let earliest_deadline = runtime_state .borrow() .scheduled_deadlines .keys() .next() .copied(); let sleep_fut = if let Some(earliest_deadline) = earliest_deadline { let now = chrono::Utc::now().timestamp_millis() as u64; if let Some(delta) = earliest_deadline.checked_sub(now) { tokio::time::sleep(std::time::Duration::from_millis(delta)).boxed() } else { std::future::ready(()).boxed() } } else { futures::future::pending().boxed() }; let cron_to_schedule = tokio::select! { _ = sleep_fut => None, x = cron_schedule_rx.recv() => { if x.is_none() { return Ok(()); }; x } }; // Schedule next execution of the cron if needed. if let Some((name, prev_success)) = cron_to_schedule { let mut runtime_state = runtime_state.borrow_mut(); if let Some(cron) = runtime_state.crons.get_mut(&name) { let backoff_schedule = cron.backoff_schedule(); let next_deadline = if !prev_success && cron.current_execution_retries < backoff_schedule.len() as u32 { let backoff_ms = backoff_schedule[cron.current_execution_retries as usize]; let now = chrono::Utc::now().timestamp_millis() as u64; cron.current_execution_retries += 1; now + backoff_ms as u64 } else { let next_ts = compute_next_deadline(&cron.spec.cron_schedule)?; cron.current_execution_retries = 0; next_ts }; runtime_state .scheduled_deadlines .entry(next_deadline) .or_default() .push(name.to_string()); } } // Dispatch ready to execute crons. let crons_to_execute = { let mut runtime_state = runtime_state.borrow_mut(); runtime_state.get_ready_crons()? }; for (_, tx) in crons_to_execute { if let Some(tx) = tx.upgrade() { let _ = tx.send(()).await; } } } } } impl RuntimeState { fn get_ready_crons( &mut self, ) -> Result<Vec<(String, WeakSender<()>)>, CronError> { let now = chrono::Utc::now().timestamp_millis() as u64; let ready = { let to_remove = self .scheduled_deadlines .range(..=now) .map(|(ts, _)| *ts) .collect::<Vec<_>>(); to_remove .iter() .flat_map(|ts| { self .scheduled_deadlines .remove(ts) .unwrap() .iter() .map(move |name| (*ts, name.clone())) .collect::<Vec<_>>() }) .filter_map(|(_, name)| { self .crons .get(&name) .map(|c| (name.clone(), c.next_tx.clone())) }) .collect::<Vec<_>>() }; Ok(ready) } } #[async_trait(?Send)] impl CronHandler for LocalCronHandler { type EH = CronExecutionHandle; fn create(&self, spec: CronSpec) -> Result<Self::EH, CronError> { // Ensure that the cron loop is started. self.cron_loop_join_handle.get_or_init(|| { let (cron_schedule_tx, cron_schedule_rx) = mpsc::channel::<(String, bool)>(1); self.cron_schedule_tx.set(cron_schedule_tx).unwrap(); let runtime_state = self.runtime_state.clone(); spawn(async move { LocalCronHandler::cron_loop(runtime_state, cron_schedule_rx) .await .unwrap(); }) }); let mut runtime_state = self.runtime_state.borrow_mut(); if runtime_state.crons.len() > MAX_CRONS { return Err(CronError::TooManyCrons); } if runtime_state.crons.contains_key(&spec.name) { return Err(CronError::AlreadyExists); } // Validate schedule expression. spec .cron_schedule .parse::<saffron::Cron>() .map_err(|_| CronError::InvalidCron)?; // Validate backoff_schedule. if let Some(backoff_schedule) = &spec.backoff_schedule { validate_backoff_schedule(backoff_schedule)?; } let (next_tx, next_rx) = mpsc::channel::<()>(1); let cron = Cron { spec: spec.clone(), next_tx: next_tx.downgrade(), current_execution_retries: 0, }; runtime_state.crons.insert(spec.name.clone(), cron); Ok(CronExecutionHandle { name: spec.name.clone(), cron_schedule_tx: self.cron_schedule_tx.get().unwrap().clone(), concurrency_limiter: self.concurrency_limiter.clone(), runtime_state: Rc::downgrade(&self.runtime_state), inner: RefCell::new(Inner { next_rx: Some(next_rx), shutdown_tx: Some(next_tx), permit: None, }), }) } } pub struct CronExecutionHandle { name: String, runtime_state: Weak<RefCell<RuntimeState>>, cron_schedule_tx: mpsc::Sender<(String, bool)>, concurrency_limiter: Arc<Semaphore>, inner: RefCell<Inner>, } struct Inner { next_rx: Option<mpsc::Receiver<()>>, shutdown_tx: Option<mpsc::Sender<()>>, permit: Option<OwnedSemaphorePermit>, } #[async_trait(?Send)] impl CronHandle for CronExecutionHandle { async fn next(&self, prev_success: bool) -> Result<bool, CronError> { self.inner.borrow_mut().permit.take(); if self .cron_schedule_tx .send((self.name.clone(), prev_success)) .await .is_err() { return Ok(false); }; let Some(mut next_rx) = self.inner.borrow_mut().next_rx.take() else { return Ok(false); }; if next_rx.recv().await.is_none() { return Ok(false); }; let permit = self.concurrency_limiter.clone().acquire_owned().await?; let mut inner = self.inner.borrow_mut(); inner.next_rx = Some(next_rx); inner.permit = Some(permit); Ok(true) } fn close(&self) { if let Some(tx) = self.inner.borrow_mut().shutdown_tx.take() { drop(tx) } if let Some(runtime_state) = self.runtime_state.upgrade() { let mut runtime_state = runtime_state.borrow_mut(); runtime_state.crons.remove(&self.name); } } } fn compute_next_deadline(cron_expression: &str) -> Result<u64, CronError> { let now = chrono::Utc::now(); if let Ok(test_schedule) = env::var("DENO_CRON_TEST_SCHEDULE_OFFSET") && let Ok(offset) = test_schedule.parse::<u64>() { return Ok(now.timestamp_millis() as u64 + offset); } let cron = cron_expression .parse::<saffron::Cron>() .map_err(|_| CronError::InvalidCron)?; let Some(next_deadline) = cron.next_after(now) else { return Err(CronError::InvalidCron); }; Ok(next_deadline.timestamp_millis() as u64) } fn validate_backoff_schedule( backoff_schedule: &[u32], ) -> Result<(), CronError> { if backoff_schedule.len() > MAX_BACKOFF_COUNT { return Err(CronError::InvalidBackoff); } if backoff_schedule.iter().any(|s| *s > MAX_BACKOFF_MS) { return Err(CronError::InvalidBackoff); } Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_compute_next_deadline() { let now = chrono::Utc::now().timestamp_millis() as u64; assert!(compute_next_deadline("*/1 * * * *").unwrap() > now); assert!(compute_next_deadline("* * * * *").unwrap() > now); assert!(compute_next_deadline("bogus").is_err()); assert!(compute_next_deadline("* * * * * *").is_err()); assert!(compute_next_deadline("* * *").is_err()); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/cron/lib.rs
ext/cron/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. mod interface; pub mod local; use std::borrow::Cow; use std::cell::RefCell; use std::rc::Rc; use std::sync::Arc; use deno_core::OpState; use deno_core::Resource; use deno_core::ResourceId; use deno_core::op2; use deno_error::JsErrorBox; use deno_error::JsErrorClass; use deno_features::FeatureChecker; pub use crate::interface::*; pub const UNSTABLE_FEATURE_NAME: &str = "cron"; deno_core::extension!(deno_cron, parameters = [ C: CronHandler ], ops = [ op_cron_create<C>, op_cron_next<C>, ], esm = [ "01_cron.ts" ], options = { cron_handler: C, }, state = |state, options| { state.put(Rc::new(options.cron_handler)); } ); struct CronResource<EH: CronHandle + 'static> { handle: Rc<EH>, } impl<EH: CronHandle + 'static> Resource for CronResource<EH> { fn name(&self) -> Cow<'_, str> { "cron".into() } fn close(self: Rc<Self>) { self.handle.close(); } } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum CronError { #[class(inherit)] #[error(transparent)] Resource(#[from] deno_core::error::ResourceError), #[class(type)] #[error("Cron name cannot exceed 64 characters: current length {0}")] NameExceeded(usize), #[class(type)] #[error( "Invalid cron name: only alphanumeric characters, whitespace, hyphens, and underscores are allowed" )] NameInvalid, #[class(type)] #[error("Cron with this name already exists")] AlreadyExists, #[class(type)] #[error("Too many crons")] TooManyCrons, #[class(type)] #[error("Invalid cron schedule")] InvalidCron, #[class(type)] #[error("Invalid backoff schedule")] InvalidBackoff, #[class(generic)] #[error(transparent)] AcquireError(#[from] tokio::sync::AcquireError), #[class(inherit)] #[error(transparent)] Other(JsErrorBox), } #[op2] #[smi] fn op_cron_create<C>( state: Rc<RefCell<OpState>>, #[string] name: String, #[string] cron_schedule: String, #[serde] backoff_schedule: Option<Vec<u32>>, ) -> Result<ResourceId, CronError> where C: CronHandler + 'static, { let cron_handler = { let state = state.borrow(); state .borrow::<Arc<FeatureChecker>>() .check_or_exit(UNSTABLE_FEATURE_NAME, "Deno.cron"); state.borrow::<Rc<C>>().clone() }; validate_cron_name(&name)?; let handle = cron_handler.create(CronSpec { name, cron_schedule, backoff_schedule, })?; let handle_rid = { let mut state = state.borrow_mut(); state.resource_table.add(CronResource { handle: Rc::new(handle), }) }; Ok(handle_rid) } #[op2(async)] async fn op_cron_next<C>( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, prev_success: bool, ) -> Result<bool, CronError> where C: CronHandler + 'static, { let cron_handler = { let state = state.borrow(); let resource = match state.resource_table.get::<CronResource<C::EH>>(rid) { Ok(resource) => resource, Err(err) => { if err.get_class() == "BadResource" { return Ok(false); } else { return Err(CronError::Resource(err)); } } }; resource.handle.clone() }; cron_handler.next(prev_success).await } fn validate_cron_name(name: &str) -> Result<(), CronError> { if name.len() > 64 { return Err(CronError::NameExceeded(name.len())); } if !name.chars().all(|c| { c.is_ascii_whitespace() || c.is_ascii_alphanumeric() || c == '_' || c == '-' }) { return Err(CronError::NameInvalid); } Ok(()) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/cron/interface.rs
ext/cron/interface.rs
// Copyright 2018-2025 the Deno authors. MIT license. use async_trait::async_trait; use crate::CronError; pub trait CronHandler { type EH: CronHandle + 'static; fn create(&self, spec: CronSpec) -> Result<Self::EH, CronError>; } #[async_trait(?Send)] pub trait CronHandle { async fn next(&self, prev_success: bool) -> Result<bool, CronError>; fn close(&self); } #[derive(Clone)] pub struct CronSpec { pub name: String, pub cron_schedule: String, pub backoff_schedule: Option<Vec<u32>>, }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/console/lib.rs
ext/console/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license.
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/net/resolve_addr.rs
ext/net/resolve_addr.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::net::SocketAddr; use std::net::ToSocketAddrs; use tokio::net::lookup_host; /// Resolve network address *asynchronously*. pub async fn resolve_addr( hostname: &str, port: u16, ) -> Result<impl Iterator<Item = SocketAddr> + '_, std::io::Error> { let addr_port_pair = make_addr_port_pair(hostname, port); let result = lookup_host(addr_port_pair).await?; Ok(result) } /// Resolve network address *synchronously*. pub fn resolve_addr_sync( hostname: &str, port: u16, ) -> Result<impl Iterator<Item = SocketAddr> + use<>, std::io::Error> { let addr_port_pair = make_addr_port_pair(hostname, port); let result = addr_port_pair.to_socket_addrs()?; Ok(result) } fn make_addr_port_pair(hostname: &str, port: u16) -> (&str, u16) { // Default to localhost if given just the port. Example: ":80" if hostname.is_empty() { return ("0.0.0.0", port); } // If this looks like an ipv6 IP address. Example: "[2001:db8::1]" // Then we remove the brackets. let addr = hostname.trim_start_matches('[').trim_end_matches(']'); (addr, port) } #[cfg(test)] mod tests { use std::net::Ipv4Addr; use std::net::Ipv6Addr; use std::net::SocketAddrV4; use std::net::SocketAddrV6; use super::*; #[tokio::test] async fn resolve_addr1() { let expected = vec![SocketAddr::V4(SocketAddrV4::new( Ipv4Addr::new(127, 0, 0, 1), 80, ))]; let actual = resolve_addr("127.0.0.1", 80) .await .unwrap() .collect::<Vec<_>>(); assert_eq!(actual, expected); } #[tokio::test] async fn resolve_addr2() { let expected = vec![SocketAddr::V4(SocketAddrV4::new( Ipv4Addr::new(0, 0, 0, 0), 80, ))]; let actual = resolve_addr("", 80).await.unwrap().collect::<Vec<_>>(); assert_eq!(actual, expected); } #[tokio::test] async fn resolve_addr3() { let expected = vec![SocketAddr::V4(SocketAddrV4::new( Ipv4Addr::new(192, 0, 2, 1), 25, ))]; let actual = resolve_addr("192.0.2.1", 25) .await .unwrap() .collect::<Vec<_>>(); assert_eq!(actual, expected); } #[tokio::test] async fn resolve_addr_ipv6() { let expected = vec![SocketAddr::V6(SocketAddrV6::new( Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0, ))]; let actual = resolve_addr("[2001:db8::1]", 8080) .await .unwrap() .collect::<Vec<_>>(); assert_eq!(actual, expected); } #[tokio::test] async fn resolve_addr_err() { assert!(resolve_addr("INVALID ADDR", 1234).await.is_err()); } #[test] fn resolve_addr_sync1() { let expected = vec![SocketAddr::V4(SocketAddrV4::new( Ipv4Addr::new(127, 0, 0, 1), 80, ))]; let actual = resolve_addr_sync("127.0.0.1", 80) .unwrap() .collect::<Vec<_>>(); assert_eq!(actual, expected); } #[test] fn resolve_addr_sync2() { let expected = vec![SocketAddr::V4(SocketAddrV4::new( Ipv4Addr::new(0, 0, 0, 0), 80, ))]; let actual = resolve_addr_sync("", 80).unwrap().collect::<Vec<_>>(); assert_eq!(actual, expected); } #[test] fn resolve_addr_sync3() { let expected = vec![SocketAddr::V4(SocketAddrV4::new( Ipv4Addr::new(192, 0, 2, 1), 25, ))]; let actual = resolve_addr_sync("192.0.2.1", 25) .unwrap() .collect::<Vec<_>>(); assert_eq!(actual, expected); } #[test] fn resolve_addr_sync_ipv6() { let expected = vec![SocketAddr::V6(SocketAddrV6::new( Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0, ))]; let actual = resolve_addr_sync("[2001:db8::1]", 8080) .unwrap() .collect::<Vec<_>>(); assert_eq!(actual, expected); } #[test] fn resolve_addr_sync_err() { assert!(resolve_addr_sync("INVALID ADDR", 1234).is_err()); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/net/lib.rs
ext/net/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. pub mod io; pub mod ops; pub mod ops_tls; #[cfg(unix)] pub mod ops_unix; #[cfg(windows)] mod ops_win_pipe; mod quic; pub mod raw; pub mod resolve_addr; pub mod tcp; pub mod tunnel; #[cfg(windows)] mod win_pipe; use std::sync::Arc; use deno_core::OpState; use deno_features::FeatureChecker; use deno_tls::RootCertStoreProvider; use deno_tls::rustls::RootCertStore; pub use quic::QuicError; pub const UNSTABLE_FEATURE_NAME: &str = "net"; /// Helper for checking unstable features. Used for sync ops. fn check_unstable(state: &OpState, api_name: &str) { state .borrow::<Arc<FeatureChecker>>() .check_or_exit(UNSTABLE_FEATURE_NAME, api_name); } #[derive(Clone)] pub struct DefaultTlsOptions { pub root_cert_store_provider: Option<Arc<dyn RootCertStoreProvider>>, } impl DefaultTlsOptions { pub fn root_cert_store( &self, ) -> Result<Option<RootCertStore>, deno_error::JsErrorBox> { Ok(match &self.root_cert_store_provider { Some(provider) => Some(provider.get_or_try_init()?.clone()), None => None, }) } } /// `UnsafelyIgnoreCertificateErrors` is a wrapper struct so it can be placed inside `GothamState`; /// using type alias for a `Option<Vec<String>>` could work, but there's a high chance /// that there might be another type alias pointing to a `Option<Vec<String>>`, which /// would override previously used alias. pub struct UnsafelyIgnoreCertificateErrors(pub Option<Vec<String>>); deno_core::extension!(deno_net, deps = [ deno_web ], ops = [ ops::op_net_accept_tcp, ops::op_net_get_ips_from_perm_token, ops::op_net_connect_tcp, ops::op_net_listen_tcp, ops::op_net_listen_udp, ops::op_node_unstable_net_listen_udp, ops::op_net_recv_udp, ops::op_net_send_udp, ops::op_net_join_multi_v4_udp, ops::op_net_join_multi_v6_udp, ops::op_net_leave_multi_v4_udp, ops::op_net_leave_multi_v6_udp, ops::op_net_set_multi_loopback_udp, ops::op_net_set_multi_ttl_udp, ops::op_net_set_broadcast_udp, ops::op_net_validate_multicast, ops::op_dns_resolve, ops::op_set_nodelay, ops::op_set_keepalive, ops::op_net_listen_vsock, ops::op_net_accept_vsock, ops::op_net_connect_vsock, ops::op_net_listen_tunnel, ops::op_net_accept_tunnel, ops_tls::op_tls_key_null, ops_tls::op_tls_key_static, ops_tls::op_tls_cert_resolver_create, ops_tls::op_tls_cert_resolver_poll, ops_tls::op_tls_cert_resolver_resolve, ops_tls::op_tls_cert_resolver_resolve_error, ops_tls::op_tls_start, ops_tls::op_net_connect_tls, ops_tls::op_net_listen_tls, ops_tls::op_net_accept_tls, ops_tls::op_tls_handshake, ops_unix::op_net_accept_unix, ops_unix::op_net_connect_unix, ops_unix::op_net_listen_unix, ops_unix::op_net_listen_unixpacket, ops_unix::op_node_unstable_net_listen_unixpacket, ops_unix::op_net_recv_unixpacket, ops_unix::op_net_send_unixpacket, ops_unix::op_net_unix_stream_from_fd, ops_win_pipe::op_pipe_open, ops_win_pipe::op_pipe_connect, ops_win_pipe::op_pipe_windows_wait, quic::op_quic_connecting_0rtt, quic::op_quic_connecting_1rtt, quic::op_quic_connection_accept_bi, quic::op_quic_connection_accept_uni, quic::op_quic_connection_close, quic::op_quic_connection_closed, quic::op_quic_connection_get_protocol, quic::op_quic_connection_get_remote_addr, quic::op_quic_connection_get_server_name, quic::op_quic_connection_handshake, quic::op_quic_connection_open_bi, quic::op_quic_connection_open_uni, quic::op_quic_connection_get_max_datagram_size, quic::op_quic_connection_read_datagram, quic::op_quic_connection_send_datagram, quic::op_quic_endpoint_close, quic::op_quic_endpoint_connect, quic::op_quic_endpoint_create, quic::op_quic_endpoint_get_addr, quic::op_quic_endpoint_listen, quic::op_quic_incoming_accept, quic::op_quic_incoming_accept_0rtt, quic::op_quic_incoming_ignore, quic::op_quic_incoming_local_ip, quic::op_quic_incoming_refuse, quic::op_quic_incoming_remote_addr, quic::op_quic_incoming_remote_addr_validated, quic::op_quic_listener_accept, quic::op_quic_listener_stop, quic::op_quic_recv_stream_get_id, quic::op_quic_send_stream_get_id, quic::op_quic_send_stream_get_priority, quic::op_quic_send_stream_set_priority, quic::webtransport::op_webtransport_accept, quic::webtransport::op_webtransport_connect, ], esm = [ "01_net.js", "02_tls.js" ], lazy_loaded_esm = [ "03_quic.js" ], options = { root_cert_store_provider: Option<Arc<dyn RootCertStoreProvider>>, unsafely_ignore_certificate_errors: Option<Vec<String>>, }, state = |state, options| { state.put(DefaultTlsOptions { root_cert_store_provider: options.root_cert_store_provider, }); state.put(UnsafelyIgnoreCertificateErrors( options.unsafely_ignore_certificate_errors, )); }, ); /// Stub ops for non-unix platforms. #[cfg(not(unix))] mod ops_unix { use deno_core::op2; macro_rules! stub_op { ($name:ident) => { #[op2(fast)] pub fn $name() -> Result<(), std::io::Error> { let error_msg = format!( "Operation `{:?}` not supported on non-unix platforms.", stringify!($name) ); Err(std::io::Error::new( std::io::ErrorKind::Unsupported, error_msg, )) } }; } stub_op!(op_net_accept_unix); stub_op!(op_net_connect_unix); stub_op!(op_net_listen_unix); stub_op!(op_net_listen_unixpacket); stub_op!(op_node_unstable_net_listen_unixpacket); stub_op!(op_net_recv_unixpacket); stub_op!(op_net_send_unixpacket); stub_op!(op_net_unix_stream_from_fd); } /// Stub ops for non-windows platforms. #[cfg(not(windows))] mod ops_win_pipe { use deno_core::op2; use crate::ops::NetError; #[op2(fast)] #[smi] pub fn op_pipe_open() -> Result<u32, NetError> { Err(NetError::Io(std::io::Error::new( std::io::ErrorKind::Unsupported, "Windows named pipes are not supported on this platform", ))) } #[op2(fast)] #[smi] pub fn op_pipe_connect() -> Result<u32, NetError> { Err(NetError::Io(std::io::Error::new( std::io::ErrorKind::Unsupported, "Windows named pipes are not supported on this platform", ))) } #[op2(fast)] pub fn op_pipe_windows_wait() -> Result<(), NetError> { Err(NetError::Io(std::io::Error::new( std::io::ErrorKind::Unsupported, "Windows named pipes are not supported on this platform", ))) } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/net/io.rs
ext/net/io.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::rc::Rc; use deno_core::AsyncMutFuture; use deno_core::AsyncRefCell; use deno_core::AsyncResult; use deno_core::CancelHandle; use deno_core::CancelTryFuture; use deno_core::RcRef; use deno_core::Resource; use deno_core::futures::TryFutureExt; use deno_error::JsErrorBox; use socket2::SockRef; use tokio::io::AsyncRead; use tokio::io::AsyncReadExt; use tokio::io::AsyncWrite; use tokio::io::AsyncWriteExt; use tokio::net::tcp; #[cfg(unix)] use tokio::net::unix; /// A full duplex resource has a read and write ends that are completely /// independent, like TCP/Unix sockets and TLS streams. #[derive(Debug)] pub struct FullDuplexResource<R, W> { rd: AsyncRefCell<R>, wr: AsyncRefCell<W>, // When a full-duplex resource is closed, all pending 'read' ops are // canceled, while 'write' ops are allowed to complete. Therefore only // 'read' futures should be attached to this cancel handle. cancel_handle: CancelHandle, } impl<R, W> FullDuplexResource<R, W> where R: AsyncRead + Unpin + 'static, W: AsyncWrite + Unpin + 'static, { pub fn new((rd, wr): (R, W)) -> Self { Self { rd: rd.into(), wr: wr.into(), cancel_handle: Default::default(), } } pub fn into_inner(self) -> (R, W) { (self.rd.into_inner(), self.wr.into_inner()) } pub fn rd_borrow_mut(self: &Rc<Self>) -> AsyncMutFuture<R> { RcRef::map(self, |r| &r.rd).borrow_mut() } pub fn wr_borrow_mut(self: &Rc<Self>) -> AsyncMutFuture<W> { RcRef::map(self, |r| &r.wr).borrow_mut() } pub fn cancel_handle(self: &Rc<Self>) -> RcRef<CancelHandle> { RcRef::map(self, |r| &r.cancel_handle) } pub fn cancel_read_ops(&self) { self.cancel_handle.cancel() } pub async fn read( self: Rc<Self>, data: &mut [u8], ) -> Result<usize, std::io::Error> { let mut rd = self.rd_borrow_mut().await; let nread = rd.read(data).try_or_cancel(self.cancel_handle()).await?; Ok(nread) } pub async fn write( self: Rc<Self>, data: &[u8], ) -> Result<usize, std::io::Error> { let mut wr = self.wr_borrow_mut().await; let nwritten = wr.write(data).await?; Ok(nwritten) } pub async fn shutdown(self: Rc<Self>) -> Result<(), std::io::Error> { let mut wr = self.wr_borrow_mut().await; wr.shutdown().await?; Ok(()) } } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum MapError { #[class(inherit)] #[error("{0}")] Io(std::io::Error), #[class(generic)] #[error("Unable to get resources")] NoResources, } pub type TcpStreamResource = FullDuplexResource<tcp::OwnedReadHalf, tcp::OwnedWriteHalf>; impl Resource for TcpStreamResource { deno_core::impl_readable_byob!(); deno_core::impl_writable!(); fn name(&self) -> Cow<'_, str> { "tcpStream".into() } fn shutdown(self: Rc<Self>) -> AsyncResult<()> { Box::pin(self.shutdown().map_err(JsErrorBox::from_err)) } fn close(self: Rc<Self>) { self.cancel_read_ops(); } } impl TcpStreamResource { pub fn set_nodelay(self: Rc<Self>, nodelay: bool) -> Result<(), MapError> { self.map_socket(Box::new(move |socket| socket.set_nodelay(nodelay))) } pub fn set_keepalive( self: Rc<Self>, keepalive: bool, ) -> Result<(), MapError> { self.map_socket(Box::new(move |socket| socket.set_keepalive(keepalive))) } #[allow(clippy::type_complexity)] fn map_socket( self: Rc<Self>, map: Box<dyn FnOnce(SockRef) -> Result<(), std::io::Error>>, ) -> Result<(), MapError> { if let Some(wr) = RcRef::map(self, |r| &r.wr).try_borrow() { let stream = wr.as_ref().as_ref(); let socket = socket2::SockRef::from(stream); return map(socket).map_err(MapError::Io); } Err(MapError::NoResources) } } #[cfg(unix)] pub type UnixStreamResource = FullDuplexResource<unix::OwnedReadHalf, unix::OwnedWriteHalf>; #[cfg(not(unix))] pub struct UnixStreamResource; #[cfg(not(unix))] impl UnixStreamResource { fn read(self: Rc<Self>, _data: &mut [u8]) -> AsyncResult<usize> { unreachable!() } fn write(self: Rc<Self>, _data: &[u8]) -> AsyncResult<usize> { unreachable!() } #[allow(clippy::unused_async)] pub async fn shutdown(self: Rc<Self>) -> Result<(), JsErrorBox> { unreachable!() } pub fn cancel_read_ops(&self) { unreachable!() } } impl Resource for UnixStreamResource { deno_core::impl_readable_byob!(); deno_core::impl_writable!(); fn name(&self) -> Cow<'_, str> { "unixStream".into() } fn shutdown(self: Rc<Self>) -> AsyncResult<()> { Box::pin(self.shutdown().map_err(JsErrorBox::from_err)) } fn close(self: Rc<Self>) { self.cancel_read_ops(); } } #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] pub type VsockStreamResource = FullDuplexResource<tokio_vsock::OwnedReadHalf, tokio_vsock::OwnedWriteHalf>; #[cfg(not(any( target_os = "android", target_os = "linux", target_os = "macos" )))] pub struct VsockStreamResource; #[cfg(not(any( target_os = "android", target_os = "linux", target_os = "macos" )))] impl VsockStreamResource { fn read(self: Rc<Self>, _data: &mut [u8]) -> AsyncResult<usize> { unreachable!() } fn write(self: Rc<Self>, _data: &[u8]) -> AsyncResult<usize> { unreachable!() } #[allow(clippy::unused_async)] pub async fn shutdown(self: Rc<Self>) -> Result<(), JsErrorBox> { unreachable!() } pub fn cancel_read_ops(&self) { unreachable!() } } impl Resource for VsockStreamResource { deno_core::impl_readable_byob!(); deno_core::impl_writable!(); fn name(&self) -> Cow<'_, str> { "vsockStream".into() } fn shutdown(self: Rc<Self>) -> AsyncResult<()> { Box::pin(self.shutdown().map_err(JsErrorBox::from_err)) } fn close(self: Rc<Self>) { self.cancel_read_ops(); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/net/ops_win_pipe.rs
ext/net/ops_win_pipe.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::path::Path; use std::rc::Rc; use deno_core::OpState; use deno_core::ResourceId; use deno_core::op2; use deno_permissions::OpenAccessKind; use deno_permissions::PermissionsContainer; use tokio::net::windows::named_pipe; use crate::ops::NetError; use crate::win_pipe::NamedPipe; #[op2(stack_trace)] #[smi] pub fn op_pipe_open( state: &mut OpState, #[string] path: String, #[smi] max_instances: Option<u32>, is_message_mode: bool, inbound: bool, outbound: bool, #[string] api_name: String, ) -> Result<ResourceId, NetError> { let permissions = state.borrow_mut::<PermissionsContainer>(); let path = permissions .check_open( Cow::Borrowed(Path::new(&path)), OpenAccessKind::ReadWriteNoFollow, Some(&api_name), ) .map_err(NetError::Permission)?; let pipe_mode = if is_message_mode { named_pipe::PipeMode::Message } else { named_pipe::PipeMode::Byte }; let mut opts = named_pipe::ServerOptions::new(); opts .pipe_mode(pipe_mode) .access_inbound(inbound) .access_outbound(outbound); if let Some(max_instances) = max_instances { opts.max_instances(max_instances as usize); } let pipe = NamedPipe::new_server(AsRef::<Path>::as_ref(&path), &opts)?; let rid = state.resource_table.add(pipe); Ok(rid) } #[op2(async, stack_trace)] pub async fn op_pipe_windows_wait( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<(), NetError> { let pipe = state.borrow().resource_table.get::<NamedPipe>(rid)?; pipe.connect().await?; Ok(()) } #[op2(fast)] #[smi] pub fn op_pipe_connect( state: &mut OpState, #[string] path: String, read: bool, write: bool, #[string] api_name: &str, ) -> Result<ResourceId, NetError> { let permissions = state.borrow_mut::<PermissionsContainer>(); let checked_path = permissions .check_open( Cow::Borrowed(Path::new(&path)), OpenAccessKind::ReadWriteNoFollow, Some(api_name), ) .map_err(NetError::Permission)?; // Check if this looks like a named pipe path // Windows named pipes must start with \\.\pipe\ or \\?\pipe\ let is_named_pipe = path.starts_with("\\\\.\\pipe\\") || path.starts_with("\\\\?\\pipe\\") || path.starts_with("//./pipe/") || path.starts_with("//?/pipe/"); if !is_named_pipe { // For non-pipe paths, check if the path exists as a file // If it does, return ENOTSOCK (not a socket) // If it doesn't exist, return ENOENT let path = Path::new(&path); if path.exists() { return Err(NetError::Io(std::io::Error::other( "ENOTSOCK: not a socket", ))); } else { return Err(NetError::Io(std::io::Error::other( "ENOENT: no such file or directory", ))); } } let mut opts = named_pipe::ClientOptions::new(); opts.read(read).write(write); let pipe = NamedPipe::new_client(AsRef::<Path>::as_ref(&checked_path), &opts)?; let rid = state.resource_table.add(pipe); Ok(rid) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/net/raw.rs
ext/net/raw.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::rc::Rc; use deno_core::AsyncRefCell; use deno_core::CancelHandle; use deno_core::Resource; use deno_core::ResourceId; use deno_core::ResourceTable; use deno_core::error::ResourceError; use deno_error::JsErrorBox; use crate::io::TcpStreamResource; use crate::ops_tls::TlsStreamResource; pub trait NetworkStreamTrait: Into<NetworkStream> { type Resource; const RESOURCE_NAME: &'static str; fn local_address(&self) -> Result<NetworkStreamAddress, std::io::Error>; fn peer_address(&self) -> Result<NetworkStreamAddress, std::io::Error>; } #[allow(async_fn_in_trait)] pub trait NetworkStreamListenerTrait: Into<NetworkStreamListener> + Send + Sync { type Stream: NetworkStreamTrait + 'static; type Addr: Into<NetworkStreamAddress> + 'static; /// Additional data, if needed type ResourceData: Default; const RESOURCE_NAME: &'static str; async fn accept(&self) -> std::io::Result<(Self::Stream, Self::Addr)>; fn listen_address(&self) -> Result<Self::Addr, std::io::Error>; } /// A strongly-typed network listener resource for something that /// implements `NetworkListenerTrait`. pub struct NetworkListenerResource<T: NetworkStreamListenerTrait> { pub listener: AsyncRefCell<T>, /// Associated data for this resource. Not required. #[allow(unused)] pub data: T::ResourceData, pub cancel: CancelHandle, } impl<T: NetworkStreamListenerTrait + 'static> Resource for NetworkListenerResource<T> { fn name(&self) -> Cow<'_, str> { T::RESOURCE_NAME.into() } fn close(self: Rc<Self>) { self.cancel.cancel(); } } impl<T: NetworkStreamListenerTrait + 'static> NetworkListenerResource<T> { pub fn new(t: T) -> Self { Self { listener: AsyncRefCell::new(t), data: Default::default(), cancel: Default::default(), } } /// Returns a [`NetworkStreamListener`] from this resource if it is not in use elsewhere. fn take( resource_table: &mut ResourceTable, listener_rid: ResourceId, ) -> Result<Option<NetworkStreamListener>, JsErrorBox> { if let Ok(resource_rc) = resource_table.take::<Self>(listener_rid) { let resource = Rc::try_unwrap(resource_rc) .map_err(|_| JsErrorBox::new("Busy", "Listener is currently in use"))?; return Ok(Some(resource.listener.into_inner().into())); } Ok(None) } } /// Each of the network streams has the exact same pattern for listening, accepting, etc, so /// we just codegen them all via macro to avoid repeating each one of these N times. macro_rules! network_stream { ( $( $( #[ $meta:meta ] )? [$i:ident, $il:ident, $stream:path, $listener:path, $addr:path, $stream_resource:ty, $read_half:ty, $write_half:ty, ] ),* ) => { /// A raw stream of one of the types handled by this extension. #[pin_project::pin_project(project = NetworkStreamProject)] #[allow(clippy::large_enum_variant)] pub enum NetworkStream { $( $( #[ $meta ] )? $i (#[pin] $stream), )* } /// A raw stream of one of the types handled by this extension. #[derive(Copy, Clone, PartialEq, Eq)] pub enum NetworkStreamType { $( $( #[ $meta ] )? $i, )* } /// A raw stream listener of one of the types handled by this extension. pub enum NetworkStreamListener { $( $( #[ $meta ] )? $i( $listener ), )* } #[pin_project::pin_project(project = NetworkStreamReadHalfProject)] pub enum NetworkStreamReadHalf { $( $( #[ $meta ] )? $i( #[pin] $read_half ), )* } #[pin_project::pin_project(project = NetworkStreamWriteHalfProject)] pub enum NetworkStreamWriteHalf { $( $( #[ $meta ] )? $i( #[pin] $write_half ), )* } $( $( #[ $meta ] )? impl NetworkStreamListenerTrait for $listener { type Stream = $stream; type Addr = $addr; type ResourceData = (); const RESOURCE_NAME: &'static str = concat!(stringify!($il), "Listener"); async fn accept(&self) -> std::io::Result<(Self::Stream, Self::Addr)> { <$listener> :: accept(self).await } fn listen_address(&self) -> std::io::Result<Self::Addr> { self.local_addr() } } $( #[ $meta ] )? impl From<$listener> for NetworkStreamListener { fn from(value: $listener) -> Self { Self::$i(value) } } $( #[ $meta ] )? impl NetworkStreamTrait for $stream { type Resource = $stream_resource; const RESOURCE_NAME: &'static str = concat!(stringify!($il), "Stream"); fn local_address(&self) -> Result<NetworkStreamAddress, std::io::Error> { Ok(NetworkStreamAddress::from(self.local_addr()?)) } fn peer_address(&self) -> Result<NetworkStreamAddress, std::io::Error> { Ok(NetworkStreamAddress::from(self.peer_addr()?)) } } $( #[ $meta ] )? impl From<$stream> for NetworkStream { fn from(value: $stream) -> Self { Self::$i(value) } } )* impl NetworkStream { pub fn local_address(&self) -> Result<NetworkStreamAddress, std::io::Error> { match self { $( $( #[ $meta ] )? Self::$i(stm) => Ok(NetworkStreamAddress::from(stm.local_addr()?)), )* } } pub fn peer_address(&self) -> Result<NetworkStreamAddress, std::io::Error> { match self { $( $( #[ $meta ] )? Self::$i(stm) => Ok(NetworkStreamAddress::from(stm.peer_addr()?)), )* } } pub fn stream(&self) -> NetworkStreamType { match self { $( $( #[ $meta ] )? Self::$i(_) => NetworkStreamType::$i, )* } } pub fn into_split(self) -> (NetworkStreamReadHalf, NetworkStreamWriteHalf) { match self { $( $( #[ $meta ] )? Self::$i(stm) => { let (r, w) = stm.into_split(); ( NetworkStreamReadHalf::$i(r), NetworkStreamWriteHalf::$i(w), ) }, )* } } } impl tokio::io::AsyncRead for NetworkStream { fn poll_read( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, buf: &mut tokio::io::ReadBuf<'_>, ) -> std::task::Poll<std::io::Result<()>> { match self.project() { $( $( #[ $meta ] )? NetworkStreamProject::$i(s) => s.poll_read(cx, buf), )* } } } impl tokio::io::AsyncWrite for NetworkStream { fn poll_write( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, buf: &[u8], ) -> std::task::Poll<Result<usize, std::io::Error>> { match self.project() { $( $( #[ $meta ] )? NetworkStreamProject::$i(s) => s.poll_write(cx, buf), )* } } fn poll_flush( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Result<(), std::io::Error>> { match self.project() { $( $( #[ $meta ] )? NetworkStreamProject::$i(s) => s.poll_flush(cx), )* } } fn poll_shutdown( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Result<(), std::io::Error>> { match self.project() { $( $( #[ $meta ] )? NetworkStreamProject::$i(s) => s.poll_shutdown(cx), )* } } fn is_write_vectored(&self) -> bool { match self { $( $( #[ $meta ] )? NetworkStream::$i(s) => s.is_write_vectored(), )* } } fn poll_write_vectored( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, bufs: &[std::io::IoSlice<'_>], ) -> std::task::Poll<Result<usize, std::io::Error>> { match self.project() { $( $( #[ $meta ] )? NetworkStreamProject::$i(s) => s.poll_write_vectored(cx, bufs), )* } } } impl tokio::io::AsyncRead for NetworkStreamReadHalf { fn poll_read( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, buf: &mut tokio::io::ReadBuf<'_>, ) -> std::task::Poll<std::io::Result<()>> { match self.project() { $( $( #[ $meta ] )? NetworkStreamReadHalfProject::$i(s) => s.poll_read(cx, buf), )* } } } impl tokio::io::AsyncWrite for NetworkStreamWriteHalf { fn poll_write( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, buf: &[u8], ) -> std::task::Poll<Result<usize, std::io::Error>> { match self.project() { $( $( #[ $meta ] )? NetworkStreamWriteHalfProject::$i(s) => s.poll_write(cx, buf), )* } } fn poll_flush( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Result<(), std::io::Error>> { match self.project() { $( $( #[ $meta ] )? NetworkStreamWriteHalfProject::$i(s) => s.poll_flush(cx), )* } } fn poll_shutdown( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Result<(), std::io::Error>> { match self.project() { $( $( #[ $meta ] )? NetworkStreamWriteHalfProject::$i(s) => s.poll_shutdown(cx), )* } } fn is_write_vectored(&self) -> bool { match self { $( $( #[ $meta ] )? NetworkStreamWriteHalf::$i(s) => s.is_write_vectored(), )* } } fn poll_write_vectored( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, bufs: &[std::io::IoSlice<'_>], ) -> std::task::Poll<Result<usize, std::io::Error>> { match self.project() { $( $( #[ $meta ] )? NetworkStreamWriteHalfProject::$i(s) => s.poll_write_vectored(cx, bufs), )* } } } impl NetworkStreamListener { /// Accepts a connection on this listener. pub async fn accept(&self) -> Result<(NetworkStream, NetworkStreamAddress), std::io::Error> { Ok(match self { $( $( #[ $meta ] )? Self::$i(s) => { let (stm, addr) = s.accept().await?; (NetworkStream::$i(stm), addr.into()) } )* }) } pub fn listen_address(&self) -> Result<NetworkStreamAddress, std::io::Error> { match self { $( $( #[ $meta ] )? Self::$i(s) => { Ok(NetworkStreamAddress::from(s.listen_address()?)) } )* } } pub fn stream(&self) -> NetworkStreamType { match self { $( $( #[ $meta ] )? Self::$i(_) => { NetworkStreamType::$i } )* } } /// Return a `NetworkStreamListener` if a resource exists for this `ResourceId` and it is currently /// not locked. pub fn take_resource(resource_table: &mut ResourceTable, listener_rid: ResourceId) -> Result<NetworkStreamListener, JsErrorBox> { $( $( #[ $meta ] )? if let Some(resource) = NetworkListenerResource::<$listener>::take(resource_table, listener_rid)? { return Ok(resource) } )* Err(JsErrorBox::from_err(ResourceError::BadResourceId)) } } }; } network_stream!( [ Tcp, tcp, tokio::net::TcpStream, crate::tcp::TcpListener, std::net::SocketAddr, TcpStreamResource, tokio::net::tcp::OwnedReadHalf, tokio::net::tcp::OwnedWriteHalf, ], [ Tls, tls, crate::ops_tls::TlsStream<tokio::net::TcpStream>, crate::ops_tls::TlsListener, std::net::SocketAddr, TlsStreamResource, crate::ops_tls::TlsStreamRead<tokio::net::TcpStream>, crate::ops_tls::TlsStreamWrite<tokio::net::TcpStream>, ], #[cfg(unix)] [ Unix, unix, tokio::net::UnixStream, tokio::net::UnixListener, tokio::net::unix::SocketAddr, crate::io::UnixStreamResource, tokio::net::unix::OwnedReadHalf, tokio::net::unix::OwnedWriteHalf, ], #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] [ Vsock, vsock, tokio_vsock::VsockStream, tokio_vsock::VsockListener, tokio_vsock::VsockAddr, crate::io::VsockStreamResource, tokio_vsock::OwnedReadHalf, tokio_vsock::OwnedWriteHalf, ], [ Tunnel, tunnel, crate::tunnel::TunnelStream, crate::tunnel::TunnelConnection, crate::tunnel::TunnelAddr, crate::tunnel::TunnelStreamResource, crate::tunnel::OwnedReadHalf, crate::tunnel::OwnedWriteHalf, ] ); pub enum NetworkStreamAddress { Ip(std::net::SocketAddr), #[cfg(unix)] Unix(tokio::net::unix::SocketAddr), #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] Vsock(tokio_vsock::VsockAddr), Tunnel(crate::tunnel::TunnelAddr), } impl From<std::net::SocketAddr> for NetworkStreamAddress { fn from(value: std::net::SocketAddr) -> Self { NetworkStreamAddress::Ip(value) } } #[cfg(unix)] impl From<tokio::net::unix::SocketAddr> for NetworkStreamAddress { fn from(value: tokio::net::unix::SocketAddr) -> Self { NetworkStreamAddress::Unix(value) } } #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] impl From<tokio_vsock::VsockAddr> for NetworkStreamAddress { fn from(value: tokio_vsock::VsockAddr) -> Self { NetworkStreamAddress::Vsock(value) } } impl From<crate::tunnel::TunnelAddr> for NetworkStreamAddress { fn from(value: crate::tunnel::TunnelAddr) -> Self { NetworkStreamAddress::Tunnel(value) } } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum TakeNetworkStreamError { #[class("Busy")] #[error("TCP stream is currently in use")] TcpBusy, #[class("Busy")] #[error("TLS stream is currently in use")] TlsBusy, #[cfg(unix)] #[class("Busy")] #[error("Unix socket is currently in use")] UnixBusy, #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] #[class("Busy")] #[error("Vsock socket is currently in use")] VsockBusy, #[class("Busy")] #[error("Tunnel socket is currently in use")] TunnelBusy, #[class(generic)] #[error(transparent)] ReuniteTcp(#[from] tokio::net::tcp::ReuniteError), #[cfg(unix)] #[class(generic)] #[error(transparent)] ReuniteUnix(#[from] tokio::net::unix::ReuniteError), #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] #[class(generic)] #[error("Cannot reunite halves from different streams")] ReuniteVsock, #[class(inherit)] #[error(transparent)] Resource(deno_core::error::ResourceError), } /// In some cases it may be more efficient to extract the resource from the resource table and use it directly (for example, an HTTP server). /// This method will extract a stream from the resource table and return it, unwrapped. pub fn take_network_stream_resource( resource_table: &mut ResourceTable, stream_rid: ResourceId, ) -> Result<NetworkStream, TakeNetworkStreamError> { // The stream we're attempting to unwrap may be in use somewhere else. If that's the case, we cannot proceed // with the process of unwrapping this connection, so we just return a bad resource error. // See also: https://github.com/denoland/deno/pull/16242 if let Ok(resource_rc) = resource_table.take::<TcpStreamResource>(stream_rid) { // This TCP connection might be used somewhere else. let resource = Rc::try_unwrap(resource_rc) .map_err(|_| TakeNetworkStreamError::TcpBusy)?; let (read_half, write_half) = resource.into_inner(); let tcp_stream = read_half.reunite(write_half)?; return Ok(NetworkStream::Tcp(tcp_stream)); } if let Ok(resource_rc) = resource_table.take::<TlsStreamResource>(stream_rid) { // This TLS connection might be used somewhere else. let resource = Rc::try_unwrap(resource_rc) .map_err(|_| TakeNetworkStreamError::TlsBusy)?; let tls_stream = resource.into_tls_stream(); return Ok(NetworkStream::Tls(tls_stream)); } #[cfg(unix)] if let Ok(resource_rc) = resource_table.take::<crate::io::UnixStreamResource>(stream_rid) { // This UNIX socket might be used somewhere else. let resource = Rc::try_unwrap(resource_rc) .map_err(|_| TakeNetworkStreamError::UnixBusy)?; let (read_half, write_half) = resource.into_inner(); let unix_stream = read_half.reunite(write_half)?; return Ok(NetworkStream::Unix(unix_stream)); } #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] if let Ok(resource_rc) = resource_table.take::<crate::io::VsockStreamResource>(stream_rid) { // This Vsock socket might be used somewhere else. let resource = Rc::try_unwrap(resource_rc) .map_err(|_| TakeNetworkStreamError::VsockBusy)?; let (read_half, write_half) = resource.into_inner(); if !read_half.is_pair_of(&write_half) { return Err(TakeNetworkStreamError::ReuniteVsock); } let vsock_stream = read_half.unsplit(write_half); return Ok(NetworkStream::Vsock(vsock_stream)); } if let Ok(resource_rc) = resource_table.take::<crate::tunnel::TunnelStreamResource>(stream_rid) { let resource = Rc::try_unwrap(resource_rc) .map_err(|_| TakeNetworkStreamError::TunnelBusy)?; let stream = resource.into_inner(); return Ok(NetworkStream::Tunnel(stream)); } Err(TakeNetworkStreamError::Resource( ResourceError::BadResourceId, )) } /// In some cases it may be more efficient to extract the resource from the resource table and use it directly (for example, an HTTP server). /// This method will extract a stream from the resource table and return it, unwrapped. pub fn take_network_stream_listener_resource( resource_table: &mut ResourceTable, listener_rid: ResourceId, ) -> Result<NetworkStreamListener, JsErrorBox> { NetworkStreamListener::take_resource(resource_table, listener_rid) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/net/tcp.rs
ext/net/tcp.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::collections::HashMap; use std::net::SocketAddr; use std::sync::Arc; use socket2::Domain; use socket2::Protocol; use socket2::Type; /// Our per-process `Connections`. We can use this to find an existent listener for /// a given local address and clone its socket for us to listen on in our thread. static CONNS: std::sync::OnceLock<std::sync::Mutex<Connections>> = std::sync::OnceLock::new(); /// Maintains a map of listening address to `TcpConnection`. #[derive(Default)] struct Connections { tcp: HashMap<SocketAddr, Arc<TcpConnection>>, } /// Holds an open listener. We clone the underlying file descriptor (unix) or socket handle (Windows) /// and then listen on our copy of it. pub struct TcpConnection { /// The pristine FD that we'll clone for each LB listener #[cfg(unix)] sock: std::os::fd::OwnedFd, #[cfg(not(unix))] sock: std::os::windows::io::OwnedSocket, key: SocketAddr, } impl TcpConnection { /// Boot a load-balanced TCP connection pub fn start(key: SocketAddr, backlog: i32) -> std::io::Result<Self> { let listener = bind_socket_and_listen(key, false, backlog)?; let sock = listener.into(); Ok(Self { sock, key }) } fn listener(&self) -> std::io::Result<tokio::net::TcpListener> { let listener = std::net::TcpListener::from(self.sock.try_clone()?); let listener = tokio::net::TcpListener::from_std(listener)?; Ok(listener) } } /// A TCP socket listener that optionally allows for round-robin load-balancing in-process. pub struct TcpListener { listener: Option<tokio::net::TcpListener>, conn: Option<Arc<TcpConnection>>, } /// Does this platform implement `SO_REUSEPORT` in a load-balancing manner? const REUSE_PORT_LOAD_BALANCES: bool = cfg!(any(target_os = "android", target_os = "linux")); impl TcpListener { /// Bind to a port. On Linux, or when we don't have `SO_REUSEPORT` set, we just bind the port directly. /// On other platforms, we emulate `SO_REUSEPORT` by cloning the socket and having each clone race to /// accept every connection. /// /// ## Why not `SO_REUSEPORT`? /// /// The `SO_REUSEPORT` socket option allows multiple sockets on the same host to bind to the same port. This is /// particularly useful for load balancing or implementing high availability in server applications. /// /// On Linux, `SO_REUSEPORT` allows multiple sockets to bind to the same port, and the kernel will load /// balance incoming connections among those sockets. Each socket can accept connections independently. /// This is useful for scenarios where you want to distribute incoming connections among multiple processes /// or threads. /// /// On macOS (which is based on BSD), the behaviour of `SO_REUSEPORT` is slightly different. When `SO_REUSEPORT` is set, /// multiple sockets can still bind to the same port, but the kernel does not perform load balancing as it does on Linux. /// Instead, it follows a "last bind wins" strategy. This means that the most recently bound socket will receive /// incoming connections exclusively, while the previously bound sockets will not receive any connections. /// This behaviour is less useful for load balancing compared to Linux, but it can still be valuable in certain scenarios. pub fn bind( socket_addr: SocketAddr, reuse_port: bool, backlog: i32, ) -> std::io::Result<Self> { if REUSE_PORT_LOAD_BALANCES && reuse_port { Self::bind_load_balanced(socket_addr, backlog) } else { Self::bind_direct(socket_addr, reuse_port, backlog) } } /// Bind directly to the port, passing `reuse_port` directly to the socket. On platforms other /// than Linux, `reuse_port` does not do any load balancing. pub fn bind_direct( socket_addr: SocketAddr, reuse_port: bool, backlog: i32, ) -> std::io::Result<Self> { // We ignore `reuse_port` on platforms other than Linux to match the existing behaviour. let listener = bind_socket_and_listen(socket_addr, reuse_port, backlog)?; Ok(Self { listener: Some(tokio::net::TcpListener::from_std(listener)?), conn: None, }) } /// Bind to the port in a load-balanced manner. pub fn bind_load_balanced( socket_addr: SocketAddr, backlog: i32, ) -> std::io::Result<Self> { let tcp = &mut CONNS.get_or_init(Default::default).lock().unwrap().tcp; if let Some(conn) = tcp.get(&socket_addr) { let listener = Some(conn.listener()?); return Ok(Self { listener, conn: Some(conn.clone()), }); } let conn = Arc::new(TcpConnection::start(socket_addr, backlog)?); let listener = Some(conn.listener()?); tcp.insert(socket_addr, conn.clone()); Ok(Self { listener, conn: Some(conn), }) } pub async fn accept( &self, ) -> std::io::Result<(tokio::net::TcpStream, SocketAddr)> { let (tcp, addr) = self.listener.as_ref().unwrap().accept().await?; Ok((tcp, addr)) } pub fn local_addr(&self) -> std::io::Result<SocketAddr> { self.listener.as_ref().unwrap().local_addr() } } impl Drop for TcpListener { fn drop(&mut self) { // If we're in load-balancing mode if let Some(conn) = self.conn.take() { let mut tcp = CONNS.get().unwrap().lock().unwrap(); if Arc::strong_count(&conn) == 2 { tcp.tcp.remove(&conn.key); // Close the connection debug_assert_eq!(Arc::strong_count(&conn), 1); drop(conn); } } } } /// Bind a socket to an address and listen with the low-level options we need. #[allow(unused_variables)] fn bind_socket_and_listen( socket_addr: SocketAddr, reuse_port: bool, backlog: i32, ) -> Result<std::net::TcpListener, std::io::Error> { let socket = if socket_addr.is_ipv4() { socket2::Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP))? } else { socket2::Socket::new(Domain::IPV6, Type::STREAM, Some(Protocol::TCP))? }; #[cfg(not(windows))] if REUSE_PORT_LOAD_BALANCES && reuse_port { socket.set_reuse_port(true)?; } #[cfg(not(windows))] // This is required for re-use of a port immediately after closing. There's a small // security trade-off here but we err on the side of convenience. // // https://stackoverflow.com/questions/14388706/how-do-so-reuseaddr-and-so-reuseport-differ // https://stackoverflow.com/questions/26772549/is-it-a-good-idea-to-reuse-port-using-option-so-reuseaddr-which-is-already-in-ti socket.set_reuse_address(true)?; socket.set_nonblocking(true)?; socket.bind(&socket_addr.into())?; socket.listen(backlog)?; let listener = socket.into(); Ok(listener) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/net/ops_unix.rs
ext/net/ops_unix.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::path::Path; use std::path::PathBuf; use std::rc::Rc; use deno_core::AsyncRefCell; use deno_core::CancelHandle; use deno_core::CancelTryFuture; use deno_core::JsBuffer; use deno_core::OpState; use deno_core::RcRef; use deno_core::Resource; use deno_core::ResourceId; use deno_core::op2; use deno_permissions::OpenAccessKind; use deno_permissions::PermissionsContainer; use serde::Deserialize; use serde::Serialize; use tokio::net::UnixDatagram; use tokio::net::UnixListener; pub use tokio::net::UnixStream; use crate::io::UnixStreamResource; use crate::ops::NetError; use crate::raw::NetworkListenerResource; /// A utility function to map OsStrings to Strings pub fn into_string(s: std::ffi::OsString) -> Result<String, NetError> { s.into_string().map_err(NetError::InvalidUtf8) } pub struct UnixDatagramResource { pub socket: AsyncRefCell<UnixDatagram>, pub cancel: CancelHandle, } impl Resource for UnixDatagramResource { fn name(&self) -> Cow<'_, str> { "unixDatagram".into() } fn close(self: Rc<Self>) { self.cancel.cancel(); } } #[derive(Serialize)] pub struct UnixAddr { pub path: Option<String>, } #[derive(Deserialize)] pub struct UnixListenArgs { pub path: String, } #[op2(async)] #[serde] pub async fn op_net_accept_unix( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<(ResourceId, Option<String>, Option<String>), NetError> { let resource = state .borrow() .resource_table .get::<NetworkListenerResource<UnixListener>>(rid) .map_err(|_| NetError::ListenerClosed)?; let listener = RcRef::map(&resource, |r| &r.listener) .try_borrow_mut() .ok_or(NetError::ListenerBusy)?; let cancel = RcRef::map(resource, |r| &r.cancel); let (unix_stream, _socket_addr) = listener .accept() .try_or_cancel(cancel) .await .map_err(crate::ops::accept_err)?; let local_addr = unix_stream.local_addr()?; let remote_addr = unix_stream.peer_addr()?; let local_addr_path = local_addr.as_pathname().map(pathstring).transpose()?; let remote_addr_path = remote_addr.as_pathname().map(pathstring).transpose()?; let resource = UnixStreamResource::new(unix_stream.into_split()); let mut state = state.borrow_mut(); let rid = state.resource_table.add(resource); Ok((rid, local_addr_path, remote_addr_path)) } #[op2(async, stack_trace)] #[serde] pub async fn op_net_connect_unix( state: Rc<RefCell<OpState>>, #[string] address_path: String, ) -> Result<(ResourceId, Option<String>, Option<String>), NetError> { let address_path = { let mut state = state.borrow_mut(); state .borrow_mut::<PermissionsContainer>() .check_open( Cow::Owned(PathBuf::from(address_path)), OpenAccessKind::ReadWriteNoFollow, Some("Deno.connect()"), ) .map_err(NetError::Permission)? }; let unix_stream = UnixStream::connect(address_path).await?; let local_addr = unix_stream.local_addr()?; let remote_addr = unix_stream.peer_addr()?; let local_addr_path = local_addr.as_pathname().map(pathstring).transpose()?; let remote_addr_path = remote_addr.as_pathname().map(pathstring).transpose()?; let mut state_ = state.borrow_mut(); let resource = UnixStreamResource::new(unix_stream.into_split()); let rid = state_.resource_table.add(resource); Ok((rid, local_addr_path, remote_addr_path)) } #[op2(async, stack_trace)] #[serde] pub async fn op_net_recv_unixpacket( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, #[buffer] mut buf: JsBuffer, ) -> Result<(usize, Option<String>), NetError> { let resource = state .borrow() .resource_table .get::<UnixDatagramResource>(rid) .map_err(|_| NetError::SocketClosed)?; let socket = RcRef::map(&resource, |r| &r.socket) .try_borrow_mut() .ok_or(NetError::SocketBusy)?; let cancel = RcRef::map(resource, |r| &r.cancel); let (nread, remote_addr) = socket.recv_from(&mut buf).try_or_cancel(cancel).await?; let path = remote_addr.as_pathname().map(pathstring).transpose()?; Ok((nread, path)) } #[op2(async, stack_trace)] #[number] pub async fn op_net_send_unixpacket( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, #[string] address_path: String, #[buffer] zero_copy: JsBuffer, ) -> Result<usize, NetError> { let address_path = { let mut s = state.borrow_mut(); s.borrow_mut::<PermissionsContainer>() .check_open( Cow::Owned(PathBuf::from(address_path)), OpenAccessKind::WriteNoFollow, Some("Deno.DatagramConn.send()"), ) .map_err(NetError::Permission)? }; let resource = state .borrow() .resource_table .get::<UnixDatagramResource>(rid) .map_err(|_| NetError::SocketClosedNotConnected)?; let socket = RcRef::map(&resource, |r| &r.socket) .try_borrow_mut() .ok_or(NetError::SocketBusy)?; let nwritten = socket.send_to(&zero_copy, address_path).await?; Ok(nwritten) } #[op2(stack_trace)] #[serde] pub fn op_net_listen_unix( state: &mut OpState, #[string] address_path: &str, #[string] api_name: &str, ) -> Result<(ResourceId, Option<String>), NetError> { let permissions = state.borrow_mut::<PermissionsContainer>(); let api_call_expr = format!("{}()", api_name); let address_path = permissions .check_open( Cow::Borrowed(Path::new(address_path)), OpenAccessKind::ReadWriteNoFollow, Some(&api_call_expr), ) .map_err(NetError::Permission)?; let listener = UnixListener::bind(address_path)?; let local_addr = listener.local_addr()?; let pathname = local_addr.as_pathname().map(pathstring).transpose()?; let listener_resource = NetworkListenerResource::new(listener); let rid = state.resource_table.add(listener_resource); Ok((rid, pathname)) } pub fn net_listen_unixpacket( state: &mut OpState, address_path: &str, ) -> Result<(ResourceId, Option<String>), NetError> { let permissions = state.borrow_mut::<PermissionsContainer>(); let address_path = permissions .check_open( Cow::Borrowed(Path::new(address_path)), OpenAccessKind::ReadWriteNoFollow, Some("Deno.listenDatagram()"), ) .map_err(NetError::Permission)?; let socket = UnixDatagram::bind(address_path)?; let local_addr = socket.local_addr()?; let pathname = local_addr.as_pathname().map(pathstring).transpose()?; let datagram_resource = UnixDatagramResource { socket: AsyncRefCell::new(socket), cancel: Default::default(), }; let rid = state.resource_table.add(datagram_resource); Ok((rid, pathname)) } #[op2(stack_trace)] #[serde] pub fn op_net_listen_unixpacket( state: &mut OpState, #[string] path: &str, ) -> Result<(ResourceId, Option<String>), NetError> { super::check_unstable(state, "Deno.listenDatagram"); net_listen_unixpacket(state, path) } #[op2(stack_trace)] #[serde] pub fn op_node_unstable_net_listen_unixpacket( state: &mut OpState, #[string] path: &str, ) -> Result<(ResourceId, Option<String>), NetError> { net_listen_unixpacket(state, path) } pub fn pathstring(pathname: &Path) -> Result<String, NetError> { into_string(pathname.into()) } /// Check if fd is a socket using fstat fn is_socket_fd(fd: i32) -> bool { // SAFETY: It is safe to zero-initialize a libc::stat struct let mut stat_buf: libc::stat = unsafe { std::mem::zeroed() }; // SAFETY: fd is a valid file descriptor, stat_buf is a valid pointer let result = unsafe { libc::fstat(fd, &mut stat_buf) }; if result != 0 { return false; } // S_IFSOCK = 0o140000 on most Unix systems (stat_buf.st_mode & libc::S_IFMT) == libc::S_IFSOCK } #[op2(fast)] #[smi] pub fn op_net_unix_stream_from_fd( state: &mut OpState, fd: i32, ) -> Result<ResourceId, NetError> { use std::os::unix::io::FromRawFd; // Validate fd is non-negative if fd < 0 { return Err(NetError::Io(std::io::Error::new( std::io::ErrorKind::InvalidInput, "Invalid file descriptor", ))); } // Check if fd is a socket - if not, we can't use UnixStream if !is_socket_fd(fd) { return Err(NetError::Io(std::io::Error::new( std::io::ErrorKind::InvalidInput, "File descriptor is not a socket", ))); } // SAFETY: The caller is responsible for passing a valid fd that they own. // The fd will be owned by the created UnixStream from this point on. let std_stream = unsafe { std::os::unix::net::UnixStream::from_raw_fd(fd) }; std_stream.set_nonblocking(true)?; let unix_stream = UnixStream::from_std(std_stream)?; let resource = UnixStreamResource::new(unix_stream.into_split()); let rid = state.resource_table.add(resource); Ok(rid) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/net/quic.rs
ext/net/quic.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::future::Future; use std::net::IpAddr; use std::net::Ipv6Addr; use std::net::SocketAddr; use std::net::SocketAddrV4; use std::net::SocketAddrV6; use std::pin::pin; use std::rc::Rc; use std::sync::Arc; use std::sync::atomic::AtomicI32; use std::sync::atomic::Ordering; use std::task::Context; use std::task::Poll; use std::task::Waker; use std::time::Duration; use deno_core::AsyncRefCell; use deno_core::AsyncResult; use deno_core::BufMutView; use deno_core::BufView; use deno_core::GarbageCollected; use deno_core::JsBuffer; use deno_core::OpState; use deno_core::RcRef; use deno_core::Resource; use deno_core::ResourceId; use deno_core::WriteOutcome; use deno_core::error::ResourceError; use deno_core::op2; use deno_error::JsError; use deno_error::JsErrorBox; use deno_permissions::PermissionCheckError; use deno_permissions::PermissionsContainer; use deno_tls::SocketUse; use deno_tls::TlsClientConfigOptions; use deno_tls::TlsError; use deno_tls::TlsKeys; use deno_tls::TlsKeysHolder; use deno_tls::create_client_config; use quinn::crypto::rustls::QuicClientConfig; use quinn::crypto::rustls::QuicServerConfig; use quinn::rustls::client::ClientSessionMemoryCache; use quinn::rustls::client::ClientSessionStore; use quinn::rustls::client::Resumption; use serde::Deserialize; use serde::Serialize; use crate::DefaultTlsOptions; use crate::UnsafelyIgnoreCertificateErrors; use crate::resolve_addr::resolve_addr_sync; #[derive(Debug, thiserror::Error, JsError)] pub enum QuicError { #[class(generic)] #[error("Endpoint created by 'connectQuic' cannot be used for listening")] CannotListen, #[class(type)] #[error("key and cert are required")] MissingTlsKey, #[class(type)] #[error("Duration is invalid")] InvalidDuration, #[class(generic)] #[error("Unable to resolve hostname")] UnableToResolve, #[class(inherit)] #[error("{0}")] StdIo(#[from] std::io::Error), #[class(inherit)] #[error("{0}")] PermissionCheck(#[from] PermissionCheckError), #[class(range)] #[error("{0}")] VarIntBoundsExceeded(#[from] quinn::VarIntBoundsExceeded), #[class(generic)] #[error("{0}")] Rustls(#[from] quinn::rustls::Error), #[class(inherit)] #[error("{0}")] Tls(#[from] TlsError), #[class(generic)] #[error("{0}")] ConnectionError(#[from] quinn::ConnectionError), #[class(generic)] #[error("{0}")] ConnectError(#[from] quinn::ConnectError), #[class(generic)] #[error("{0}")] SendDatagramError(#[from] quinn::SendDatagramError), #[class("BadResource")] #[error("{0}")] ClosedStream(#[from] quinn::ClosedStream), #[class(generic)] #[error("{0}")] ReadError(#[from] quinn::ReadError), #[class(generic)] #[error("{0}")] WriteError(#[from] quinn::WriteError), #[class("BadResource")] #[error("Invalid {0} resource")] BadResource(&'static str), #[class(range)] #[error( "Connection has reached the maximum number of concurrent outgoing {0} streams" )] MaxStreams(&'static str), #[class(generic)] #[error("Peer does not support WebTransport")] WebTransportPeerUnsupported, #[class(generic)] #[error("{0}")] WebTransportSettingsError(#[from] web_transport_proto::SettingsError), #[class(generic)] #[error("{0}")] WebTransportConnectError(#[from] web_transport_proto::ConnectError), #[class(inherit)] #[error(transparent)] Other(#[from] JsErrorBox), } #[derive(Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct CloseInfo { close_code: u64, reason: String, } #[derive(Debug, Deserialize, Serialize)] struct Addr { hostname: String, port: u16, } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct ListenArgs { alpn_protocols: Option<Vec<String>>, } #[derive(Deserialize, Default, PartialEq)] #[serde(rename_all = "camelCase")] struct TransportConfig { keep_alive_interval: Option<u64>, max_idle_timeout: Option<u64>, max_concurrent_bidirectional_streams: Option<u32>, max_concurrent_unidirectional_streams: Option<u32>, preferred_address_v4: Option<SocketAddrV4>, preferred_address_v6: Option<SocketAddrV6>, congestion_control: Option<String>, } impl TryInto<quinn::TransportConfig> for TransportConfig { type Error = QuicError; fn try_into(self) -> Result<quinn::TransportConfig, Self::Error> { let mut cfg = quinn::TransportConfig::default(); if let Some(interval) = self.keep_alive_interval { cfg.keep_alive_interval(Some(Duration::from_millis(interval))); } if let Some(timeout) = self.max_idle_timeout { cfg.max_idle_timeout(Some( Duration::from_millis(timeout) .try_into() .map_err(|_| QuicError::InvalidDuration)?, )); } if let Some(max) = self.max_concurrent_bidirectional_streams { cfg.max_concurrent_bidi_streams(max.into()); } if let Some(max) = self.max_concurrent_unidirectional_streams { cfg.max_concurrent_uni_streams(max.into()); } if let Some(v) = self.congestion_control { let controller: Option< Arc<dyn quinn::congestion::ControllerFactory + Send + Sync + 'static>, > = match v.as_str() { "low-latency" => { Some(Arc::new(quinn::congestion::BbrConfig::default())) } "throughput" => { Some(Arc::new(quinn::congestion::CubicConfig::default())) } _ => None, }; if let Some(controller) = controller { cfg.congestion_controller_factory(controller); } } Ok(cfg) } } fn apply_server_transport_config( config: &mut quinn::ServerConfig, transport_config: TransportConfig, ) -> Result<(), QuicError> { config.preferred_address_v4(transport_config.preferred_address_v4); config.preferred_address_v6(transport_config.preferred_address_v6); config.transport_config(Arc::new(transport_config.try_into()?)); Ok(()) } struct EndpointResource { endpoint: quinn::Endpoint, can_listen: bool, session_store: Arc<dyn ClientSessionStore>, } // SAFETY: we're sure `EndpointResource` can be GCed unsafe impl GarbageCollected for EndpointResource { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"EndpointResource" } } #[op2] #[cppgc] pub(crate) fn op_quic_endpoint_create( state: Rc<RefCell<OpState>>, #[serde] addr: Addr, can_listen: bool, ) -> Result<EndpointResource, QuicError> { let addr = resolve_addr_sync(&addr.hostname, addr.port)? .next() .ok_or_else(|| QuicError::UnableToResolve)?; if can_listen { state .borrow_mut() .borrow_mut::<PermissionsContainer>() .check_net( &(&addr.ip().to_string(), Some(addr.port())), "new Deno.QuicEndpoint()", )? } else { // If this is not a can-listen, assert that we will bind to an ephemeral port. assert_eq!( addr, SocketAddr::from(( IpAddr::from(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), 0 )) ); } let config = quinn::EndpointConfig::default(); let socket = std::net::UdpSocket::bind(addr)?; let endpoint = quinn::Endpoint::new( config, None, socket, quinn::default_runtime().unwrap(), )?; Ok(EndpointResource { endpoint, can_listen, session_store: Arc::new(ClientSessionMemoryCache::new(256)), }) } #[op2] #[serde] pub(crate) fn op_quic_endpoint_get_addr( #[cppgc] endpoint: &EndpointResource, ) -> Result<Addr, QuicError> { let addr = endpoint.endpoint.local_addr()?; let addr = Addr { hostname: format!("{}", addr.ip()), port: addr.port(), }; Ok(addr) } #[op2(fast)] pub(crate) fn op_quic_endpoint_close( #[cppgc] endpoint: &EndpointResource, #[bigint] close_code: u64, #[string] reason: String, ) -> Result<(), QuicError> { endpoint .endpoint .close(quinn::VarInt::from_u64(close_code)?, reason.as_bytes()); Ok(()) } struct ListenerResource(quinn::Endpoint, Arc<QuicServerConfig>); impl Drop for ListenerResource { fn drop(&mut self) { self.0.set_server_config(None); } } // SAFETY: we're sure `ListenerResource` can be GCed unsafe impl GarbageCollected for ListenerResource { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"ListenerResource" } } #[op2] #[cppgc] pub(crate) fn op_quic_endpoint_listen( #[cppgc] endpoint: &EndpointResource, #[serde] args: ListenArgs, #[serde] transport_config: TransportConfig, #[cppgc] keys: &TlsKeysHolder, ) -> Result<ListenerResource, QuicError> { if !endpoint.can_listen { return Err(QuicError::CannotListen); } let TlsKeys::Static(deno_tls::TlsKey(cert, key)) = keys.take() else { return Err(QuicError::MissingTlsKey); }; let mut crypto = quinn::rustls::ServerConfig::builder_with_protocol_versions(&[ &quinn::rustls::version::TLS13, ]) .with_no_client_auth() .with_single_cert(cert.clone(), key.clone_key())?; // required by QUIC spec. crypto.max_early_data_size = u32::MAX; if let Some(alpn_protocols) = args.alpn_protocols { crypto.alpn_protocols = alpn_protocols .into_iter() .map(|alpn| alpn.into_bytes()) .collect(); } let server_config = Arc::new( QuicServerConfig::try_from(crypto).expect("TLS13 is explicitly configured"), ); let mut config = quinn::ServerConfig::with_crypto(server_config.clone()); apply_server_transport_config(&mut config, transport_config)?; endpoint.endpoint.set_server_config(Some(config)); Ok(ListenerResource(endpoint.endpoint.clone(), server_config)) } struct ConnectionResource( quinn::Connection, RefCell<Option<quinn::ZeroRttAccepted>>, ); // SAFETY: we're sure `ConnectionResource` can be GCed unsafe impl GarbageCollected for ConnectionResource { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"ConnectionResource" } } struct IncomingResource( RefCell<Option<quinn::Incoming>>, Arc<QuicServerConfig>, ); // SAFETY: we're sure `Incoming` can be GCed unsafe impl GarbageCollected for IncomingResource { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"IncomingResource" } } #[op2(async)] #[cppgc] pub(crate) async fn op_quic_listener_accept( #[cppgc] resource: &ListenerResource, ) -> Result<IncomingResource, QuicError> { match resource.0.accept().await { Some(incoming) => Ok(IncomingResource( RefCell::new(Some(incoming)), resource.1.clone(), )), None => Err(QuicError::BadResource("QuicListener")), } } #[op2(fast)] pub(crate) fn op_quic_listener_stop(#[cppgc] resource: &ListenerResource) { resource.0.set_server_config(None); } #[op2] #[string] pub(crate) fn op_quic_incoming_local_ip( #[cppgc] incoming_resource: &IncomingResource, ) -> Result<Option<String>, QuicError> { let Some(incoming) = incoming_resource.0.borrow_mut().take() else { return Err(QuicError::BadResource("QuicIncoming")); }; Ok(incoming.local_ip().map(|ip| ip.to_string())) } #[op2] #[serde] pub(crate) fn op_quic_incoming_remote_addr( #[cppgc] incoming_resource: &IncomingResource, ) -> Result<Addr, QuicError> { let Some(incoming) = incoming_resource.0.borrow_mut().take() else { return Err(QuicError::BadResource("QuicIncoming")); }; let addr = incoming.remote_address(); Ok(Addr { hostname: format!("{}", addr.ip()), port: addr.port(), }) } #[op2(fast)] pub(crate) fn op_quic_incoming_remote_addr_validated( #[cppgc] incoming_resource: &IncomingResource, ) -> Result<bool, QuicError> { let Some(incoming) = incoming_resource.0.borrow_mut().take() else { return Err(QuicError::BadResource("QuicIncoming")); }; Ok(incoming.remote_address_validated()) } fn quic_incoming_accept( incoming_resource: &IncomingResource, transport_config: Option<TransportConfig>, ) -> Result<quinn::Connecting, QuicError> { let Some(incoming) = incoming_resource.0.borrow_mut().take() else { return Err(QuicError::BadResource("QuicIncoming")); }; match transport_config { Some(transport_config) if transport_config != Default::default() => { let mut config = quinn::ServerConfig::with_crypto(incoming_resource.1.clone()); apply_server_transport_config(&mut config, transport_config)?; Ok(incoming.accept_with(Arc::new(config))?) } _ => Ok(incoming.accept()?), } } #[op2(async)] #[cppgc] pub(crate) async fn op_quic_incoming_accept( #[cppgc] incoming_resource: &IncomingResource, #[serde] transport_config: Option<TransportConfig>, ) -> Result<ConnectionResource, QuicError> { let connecting = quic_incoming_accept(incoming_resource, transport_config)?; let conn = connecting.await?; Ok(ConnectionResource(conn, RefCell::new(None))) } #[op2] #[cppgc] pub(crate) fn op_quic_incoming_accept_0rtt( #[cppgc] incoming_resource: &IncomingResource, #[serde] transport_config: Option<TransportConfig>, ) -> Result<ConnectionResource, QuicError> { let connecting = quic_incoming_accept(incoming_resource, transport_config)?; match connecting.into_0rtt() { Ok((conn, zrtt_accepted)) => { Ok(ConnectionResource(conn, RefCell::new(Some(zrtt_accepted)))) } Err(_connecting) => { unreachable!("0.5-RTT always succeeds"); } } } #[op2] #[serde] pub(crate) fn op_quic_incoming_refuse( #[cppgc] incoming: &IncomingResource, ) -> Result<(), QuicError> { let Some(incoming) = incoming.0.borrow_mut().take() else { return Err(QuicError::BadResource("QuicIncoming")); }; incoming.refuse(); Ok(()) } #[op2] #[serde] pub(crate) fn op_quic_incoming_ignore( #[cppgc] incoming: &IncomingResource, ) -> Result<(), QuicError> { let Some(incoming) = incoming.0.borrow_mut().take() else { return Err(QuicError::BadResource("QuicIncoming")); }; incoming.ignore(); Ok(()) } struct ConnectingResource(RefCell<Option<quinn::Connecting>>); // SAFETY: we're sure `ConnectingResource` can be GCed unsafe impl GarbageCollected for ConnectingResource { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"ConnectingResource" } } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct ConnectArgs { addr: Addr, ca_certs: Option<Vec<String>>, alpn_protocols: Option<Vec<String>>, server_name: Option<String>, server_certificate_hashes: Option<Vec<CertificateHash>>, } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct CertificateHash { algorithm: String, value: JsBuffer, } #[op2] #[cppgc] pub(crate) fn op_quic_endpoint_connect( state: Rc<RefCell<OpState>>, #[cppgc] endpoint: &EndpointResource, #[serde] args: ConnectArgs, #[serde] transport_config: TransportConfig, #[cppgc] key_pair: &TlsKeysHolder, ) -> Result<ConnectingResource, QuicError> { state .borrow_mut() .borrow_mut::<PermissionsContainer>() .check_net( &(&args.addr.hostname, Some(args.addr.port)), "Deno.connectQuic()", )?; let sock_addr = resolve_addr_sync(&args.addr.hostname, args.addr.port)? .next() .ok_or_else(|| QuicError::UnableToResolve)?; let root_cert_store = state .borrow() .borrow::<DefaultTlsOptions>() .root_cert_store()?; let unsafely_ignore_certificate_errors = state .borrow() .try_borrow::<UnsafelyIgnoreCertificateErrors>() .and_then(|it| it.0.clone()); let ca_certs = args .ca_certs .unwrap_or_default() .into_iter() .map(|s| s.into_bytes()) .collect::<Vec<_>>(); let mut tls_config = if let Some(hashes) = args.server_certificate_hashes { deno_tls::rustls::ClientConfig::builder() .dangerous() .with_custom_certificate_verifier(Arc::new( webtransport::ServerFingerprints::new( hashes .into_iter() .filter(|h| h.algorithm.to_lowercase() == "sha-256") .map(|h| h.value.to_vec()) .collect(), ), )) .with_no_client_auth() } else { create_client_config(TlsClientConfigOptions { root_cert_store, ca_certs, unsafely_ignore_certificate_errors, unsafely_disable_hostname_verification: false, cert_chain_and_key: key_pair.take(), socket_use: SocketUse::GeneralSsl, })? }; if let Some(alpn_protocols) = args.alpn_protocols { tls_config.alpn_protocols = alpn_protocols.into_iter().map(|s| s.into_bytes()).collect(); } tls_config.enable_early_data = true; tls_config.resumption = Resumption::store(endpoint.session_store.clone()); let client_config = QuicClientConfig::try_from(tls_config).expect("TLS13 supported"); let mut client_config = quinn::ClientConfig::new(Arc::new(client_config)); client_config.transport_config(Arc::new(transport_config.try_into()?)); let connecting = endpoint.endpoint.connect_with( client_config, sock_addr, &args.server_name.unwrap_or(args.addr.hostname), )?; Ok(ConnectingResource(RefCell::new(Some(connecting)))) } #[op2(async)] #[cppgc] pub(crate) async fn op_quic_connecting_1rtt( #[cppgc] connecting: &ConnectingResource, ) -> Result<ConnectionResource, QuicError> { let Some(connecting) = connecting.0.borrow_mut().take() else { return Err(QuicError::BadResource("QuicConnecting")); }; let conn = connecting.await?; Ok(ConnectionResource(conn, RefCell::new(None))) } #[op2] #[cppgc] pub(crate) fn op_quic_connecting_0rtt( #[cppgc] connecting_res: &ConnectingResource, ) -> Option<ConnectionResource> { let connecting = connecting_res.0.borrow_mut().take()?; match connecting.into_0rtt() { Ok((conn, zrtt_accepted)) => { Some(ConnectionResource(conn, RefCell::new(Some(zrtt_accepted)))) } Err(connecting) => { *connecting_res.0.borrow_mut() = Some(connecting); None } } } #[op2] #[string] pub(crate) fn op_quic_connection_get_protocol( #[cppgc] connection: &ConnectionResource, ) -> Option<String> { connection .0 .handshake_data() .and_then(|h| h.downcast::<quinn::crypto::rustls::HandshakeData>().ok()) .and_then(|h| h.protocol) .map(|p| String::from_utf8_lossy(&p).into_owned()) } #[op2] #[string] pub(crate) fn op_quic_connection_get_server_name( #[cppgc] connection: &ConnectionResource, ) -> Option<String> { connection .0 .handshake_data() .and_then(|h| h.downcast::<quinn::crypto::rustls::HandshakeData>().ok()) .and_then(|h| h.server_name) } #[op2] #[serde] pub(crate) fn op_quic_connection_get_remote_addr( #[cppgc] connection: &ConnectionResource, ) -> Result<Addr, QuicError> { let addr = connection.0.remote_address(); Ok(Addr { hostname: format!("{}", addr.ip().to_canonical()), port: addr.port(), }) } #[op2(fast)] pub(crate) fn op_quic_connection_close( #[cppgc] connection: &ConnectionResource, #[bigint] close_code: u64, #[string] reason: String, ) -> Result<(), QuicError> { connection .0 .close(quinn::VarInt::from_u64(close_code)?, reason.as_bytes()); Ok(()) } #[op2(async)] #[serde] pub(crate) async fn op_quic_connection_closed( #[cppgc] connection: &ConnectionResource, ) -> Result<CloseInfo, QuicError> { let e = connection.0.closed().await; match e { quinn::ConnectionError::LocallyClosed => Ok(CloseInfo { close_code: 0, reason: "".into(), }), quinn::ConnectionError::ApplicationClosed(i) => Ok(CloseInfo { close_code: i.error_code.into(), reason: String::from_utf8_lossy(&i.reason).into_owned(), }), e => Err(e.into()), } } #[op2(async)] pub(crate) async fn op_quic_connection_handshake( #[cppgc] connection: &ConnectionResource, ) { let Some(zrtt_accepted) = connection.1.borrow_mut().take() else { return; }; zrtt_accepted.await; } struct SendStreamResource { stream: AsyncRefCell<quinn::SendStream>, stream_id: quinn::StreamId, priority: AtomicI32, } impl SendStreamResource { fn new(stream: quinn::SendStream) -> Self { Self { stream_id: stream.id(), priority: AtomicI32::new(stream.priority().unwrap_or(0)), stream: AsyncRefCell::new(stream), } } } impl Resource for SendStreamResource { fn name(&self) -> Cow<'_, str> { "quicSendStream".into() } fn write(self: Rc<Self>, view: BufView) -> AsyncResult<WriteOutcome> { Box::pin(async move { let mut stream = RcRef::map(self.clone(), |r| &r.stream).borrow_mut().await; stream .set_priority(self.priority.load(Ordering::Relaxed)) .map_err(|e| JsErrorBox::from_err(std::io::Error::from(e)))?; let nwritten = stream .write(&view) .await .map_err(|e| JsErrorBox::from_err(std::io::Error::from(e)))?; Ok(WriteOutcome::Partial { nwritten, view }) }) } fn close(self: Rc<Self>) {} } struct RecvStreamResource { stream: AsyncRefCell<quinn::RecvStream>, stream_id: quinn::StreamId, } impl RecvStreamResource { fn new(stream: quinn::RecvStream) -> Self { Self { stream_id: stream.id(), stream: AsyncRefCell::new(stream), } } } impl Resource for RecvStreamResource { fn name(&self) -> Cow<'_, str> { "quicReceiveStream".into() } fn read(self: Rc<Self>, limit: usize) -> AsyncResult<BufView> { Box::pin(async move { let mut r = RcRef::map(self, |r| &r.stream).borrow_mut().await; let mut data = vec![0; limit]; let nread = r .read(&mut data) .await .map_err(|e| JsErrorBox::from_err(std::io::Error::from(e)))? .unwrap_or(0); data.truncate(nread); Ok(BufView::from(data)) }) } fn read_byob( self: Rc<Self>, mut buf: BufMutView, ) -> AsyncResult<(usize, BufMutView)> { Box::pin(async move { let mut r = RcRef::map(self, |r| &r.stream).borrow_mut().await; let nread = r .read(&mut buf) .await .map_err(|e| JsErrorBox::from_err(std::io::Error::from(e)))? .unwrap_or(0); Ok((nread, buf)) }) } fn shutdown(self: Rc<Self>) -> AsyncResult<()> { Box::pin(async move { let mut r = RcRef::map(self, |r| &r.stream).borrow_mut().await; r.stop(quinn::VarInt::from(0u32)) .map_err(|e| JsErrorBox::from_err(std::io::Error::from(e)))?; Ok(()) }) } } #[op2(async)] #[serde] pub(crate) async fn op_quic_connection_accept_bi( #[cppgc] connection: &ConnectionResource, state: Rc<RefCell<OpState>>, ) -> Result<(ResourceId, ResourceId), QuicError> { match connection.0.accept_bi().await { Ok((tx, rx)) => { let mut state = state.borrow_mut(); let tx_rid = state.resource_table.add(SendStreamResource::new(tx)); let rx_rid = state.resource_table.add(RecvStreamResource::new(rx)); Ok((tx_rid, rx_rid)) } Err(e) => match e { quinn::ConnectionError::LocallyClosed | quinn::ConnectionError::ApplicationClosed(..) => { Err(QuicError::BadResource("QuicConnection")) } _ => Err(e.into()), }, } } #[op2(async)] #[serde] pub(crate) async fn op_quic_connection_open_bi( #[cppgc] connection: &ConnectionResource, state: Rc<RefCell<OpState>>, wait_for_available: bool, ) -> Result<(ResourceId, ResourceId), QuicError> { let (tx, rx) = if wait_for_available { connection.0.open_bi().await? } else { let waker = Waker::noop(); let mut cx = Context::from_waker(waker); match pin!(connection.0.open_bi()).poll(&mut cx) { Poll::Ready(r) => r?, Poll::Pending => { return Err(QuicError::MaxStreams("bidirectional")); } } }; let mut state = state.borrow_mut(); let tx_rid = state.resource_table.add(SendStreamResource::new(tx)); let rx_rid = state.resource_table.add(RecvStreamResource::new(rx)); Ok((tx_rid, rx_rid)) } #[op2(async)] #[serde] pub(crate) async fn op_quic_connection_accept_uni( #[cppgc] connection: &ConnectionResource, state: Rc<RefCell<OpState>>, ) -> Result<ResourceId, QuicError> { match connection.0.accept_uni().await { Ok(rx) => { let rid = state .borrow_mut() .resource_table .add(RecvStreamResource::new(rx)); Ok(rid) } Err(e) => match e { quinn::ConnectionError::LocallyClosed | quinn::ConnectionError::ApplicationClosed(..) => { Err(QuicError::BadResource("QuicConnection")) } _ => Err(e.into()), }, } } #[op2(async)] #[serde] pub(crate) async fn op_quic_connection_open_uni( #[cppgc] connection: &ConnectionResource, state: Rc<RefCell<OpState>>, wait_for_available: bool, ) -> Result<ResourceId, QuicError> { let tx = if wait_for_available { connection.0.open_uni().await? } else { let waker = Waker::noop(); let mut cx = Context::from_waker(waker); match pin!(connection.0.open_uni()).poll(&mut cx) { Poll::Ready(r) => r?, Poll::Pending => { return Err(QuicError::MaxStreams("unidirectional")); } } }; let rid = state .borrow_mut() .resource_table .add(SendStreamResource::new(tx)); Ok(rid) } #[op2(async)] pub(crate) async fn op_quic_connection_send_datagram( #[cppgc] connection: &ConnectionResource, #[buffer] buf: JsBuffer, ) -> Result<(), QuicError> { connection.0.send_datagram_wait(buf.to_vec().into()).await?; Ok(()) } #[op2(async)] #[buffer] pub(crate) async fn op_quic_connection_read_datagram( #[cppgc] connection: &ConnectionResource, ) -> Result<Vec<u8>, QuicError> { let data = connection.0.read_datagram().await?; Ok(data.into()) } #[op2(fast)] pub(crate) fn op_quic_connection_get_max_datagram_size( #[cppgc] connection: &ConnectionResource, ) -> u32 { connection.0.max_datagram_size().unwrap_or(0) as _ } #[op2(fast)] pub(crate) fn op_quic_send_stream_get_priority( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<i32, ResourceError> { let resource = state .borrow() .resource_table .get::<SendStreamResource>(rid)?; Ok(resource.priority.load(Ordering::Relaxed)) } #[op2(fast)] pub(crate) fn op_quic_send_stream_set_priority( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, priority: i32, ) -> Result<(), ResourceError> { let resource = state .borrow() .resource_table .get::<SendStreamResource>(rid)?; resource.priority.store(priority, Ordering::Relaxed); Ok(()) } #[op2(fast)] #[bigint] pub(crate) fn op_quic_send_stream_get_id( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<u64, ResourceError> { let resource = state .borrow() .resource_table .get::<SendStreamResource>(rid)?; let stream_id = quinn::VarInt::from(resource.stream_id).into_inner(); Ok(stream_id) } #[op2(fast)] #[bigint] pub(crate) fn op_quic_recv_stream_get_id( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<u64, ResourceError> { let resource = state .borrow() .resource_table .get::<RecvStreamResource>(rid)?; let stream_id = quinn::VarInt::from(resource.stream_id).into_inner(); Ok(stream_id) } pub(crate) mod webtransport { // MIT License // // Copyright (c) 2023 Luke Curley // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // https://github.com/kixelated/web-transport-rs use deno_core::futures::try_join; use deno_tls::rustls; use rustls::client::danger::ServerCertVerifier; use rustls::crypto::CryptoProvider; use rustls::crypto::verify_tls12_signature; use rustls::crypto::verify_tls13_signature; use sha2::Digest; use sha2::Sha256; use super::*; async fn exchange_settings( state: Rc<RefCell<OpState>>, conn: quinn::Connection, ) -> Result<(u32, u32), QuicError> { use web_transport_proto::Settings; use web_transport_proto::SettingsError; let settings_tx_rid = async { let mut tx = conn.open_uni().await?; let mut settings = Settings::default(); settings.enable_webtransport(1); let mut buf = vec![]; settings.encode(&mut buf); tx.write_all(&buf).await?; let rid = state .borrow_mut() .resource_table .add(SendStreamResource::new(tx)); Ok(rid) }; let settings_rx_rid = async { let mut rx = conn.accept_uni().await?; let mut buf = Vec::new(); loop { let chunk = rx.read_chunk(usize::MAX, true).await?; let chunk = chunk.ok_or(QuicError::WebTransportPeerUnsupported)?; buf.extend_from_slice(&chunk.bytes); let mut limit = std::io::Cursor::new(&buf); let settings = match Settings::decode(&mut limit) { Ok(settings) => settings, Err(SettingsError::UnexpectedEnd) => continue, Err(e) => return Err(e.into()), }; if settings.supports_webtransport() == 0 { return Err(QuicError::WebTransportPeerUnsupported); } break; } let rid = state .borrow_mut() .resource_table .add(RecvStreamResource::new(rx)); Ok(rid) }; let (settings_tx_rid, settings_rx_rid) = try_join!(settings_tx_rid, settings_rx_rid)?; Ok((settings_tx_rid, settings_rx_rid)) } #[op2(async)] #[serde] pub(crate) async fn op_webtransport_connect( state: Rc<RefCell<OpState>>, #[cppgc] connection_resource: &ConnectionResource, #[string] url: String, ) -> Result<(u32, u32, u32, u32), QuicError> { use web_transport_proto::ConnectError; use web_transport_proto::ConnectRequest; use web_transport_proto::ConnectResponse; let conn = connection_resource.0.clone(); let url = url::Url::parse(&url).unwrap(); let (settings_tx_rid, settings_rx_rid) = exchange_settings(state.clone(), conn.clone()).await?; let (connect_tx_rid, connect_rx_rid) = { let (mut tx, mut rx) = conn.open_bi().await?; let request = ConnectRequest { url: url.clone() }; let mut buf = Vec::new(); request.encode(&mut buf); tx.write_all(&buf).await?; buf.clear(); loop { let chunk = rx.read_chunk(usize::MAX, true).await?; let chunk = chunk.ok_or(QuicError::WebTransportPeerUnsupported)?; buf.extend_from_slice(&chunk.bytes); let mut limit = std::io::Cursor::new(&buf); let res = match ConnectResponse::decode(&mut limit) { Ok(res) => res, Err(ConnectError::UnexpectedEnd) => { continue; } Err(e) => return Err(e.into()), }; if res.status != 200 { return Err(QuicError::WebTransportPeerUnsupported); } break; } let mut state = state.borrow_mut(); let tx_rid = state.resource_table.add(SendStreamResource::new(tx)); let rx_rid = state.resource_table.add(RecvStreamResource::new(rx)); (tx_rid, rx_rid) }; Ok(( connect_tx_rid, connect_rx_rid, settings_tx_rid, settings_rx_rid, )) } #[op2(async)] #[serde] pub(crate) async fn op_webtransport_accept( state: Rc<RefCell<OpState>>, #[cppgc] connection_resource: &ConnectionResource, ) -> Result<(String, u32, u32, u32, u32), QuicError> { use web_transport_proto::ConnectError; use web_transport_proto::ConnectRequest; use web_transport_proto::ConnectResponse; let conn = connection_resource.0.clone(); let (settings_tx_rid, settings_rx_rid) = exchange_settings(state.clone(), conn.clone()).await?; let (url, connect_tx_rid, connect_rx_rid) = { let (mut tx, mut rx) = conn.accept_bi().await?; let mut buf = Vec::new(); let req = loop {
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
true
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/net/ops_tls.rs
ext/net/ops_tls.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::convert::From; use std::fs::File; use std::io::BufReader; use std::io::ErrorKind; use std::io::Read; use std::net::SocketAddr; use std::num::NonZeroUsize; use std::path::Path; use std::rc::Rc; use std::sync::Arc; use deno_core::AsyncRefCell; use deno_core::AsyncResult; use deno_core::CancelHandle; use deno_core::CancelTryFuture; use deno_core::OpState; use deno_core::RcRef; use deno_core::Resource; use deno_core::ResourceId; use deno_core::futures::TryFutureExt; use deno_core::op2; use deno_core::v8; use deno_error::JsErrorBox; use deno_permissions::OpenAccessKind; use deno_permissions::PermissionsContainer; use deno_tls::ServerConfigProvider; use deno_tls::SocketUse; use deno_tls::TlsClientConfigOptions; use deno_tls::TlsKey; use deno_tls::TlsKeyLookup; use deno_tls::TlsKeys; use deno_tls::TlsKeysHolder; use deno_tls::create_client_config; use deno_tls::load_certs; use deno_tls::load_private_keys; use deno_tls::new_resolver; use deno_tls::rustls::ClientConnection; use deno_tls::rustls::ServerConfig; use deno_tls::rustls::pki_types::ServerName; pub use rustls_tokio_stream::TlsStream; pub use rustls_tokio_stream::TlsStreamRead; pub use rustls_tokio_stream::TlsStreamWrite; use serde::Deserialize; use tokio::io::AsyncReadExt; use tokio::io::AsyncWriteExt; use tokio::net::TcpStream; use crate::DefaultTlsOptions; use crate::UnsafelyIgnoreCertificateErrors; use crate::io::TcpStreamResource; use crate::ops::IpAddr; use crate::ops::NetError; use crate::ops::TlsHandshakeInfo; use crate::raw::NetworkListenerResource; use crate::resolve_addr::resolve_addr; use crate::resolve_addr::resolve_addr_sync; use crate::tcp::TcpListener; pub(crate) const TLS_BUFFER_SIZE: Option<NonZeroUsize> = NonZeroUsize::new(65536); pub struct TlsListener { pub(crate) tcp_listener: TcpListener, pub(crate) tls_config: Option<Arc<ServerConfig>>, pub(crate) server_config_provider: Option<ServerConfigProvider>, } impl TlsListener { pub async fn accept( &self, ) -> std::io::Result<(TlsStream<TcpStream>, SocketAddr)> { let (tcp, addr) = self.tcp_listener.accept().await?; let tls = if let Some(provider) = &self.server_config_provider { TlsStream::new_server_side_acceptor( tcp, provider.clone(), TLS_BUFFER_SIZE, ) } else { TlsStream::new_server_side( tcp, self.tls_config.clone().unwrap(), TLS_BUFFER_SIZE, ) }; Ok((tls, addr)) } pub fn local_addr(&self) -> std::io::Result<SocketAddr> { self.tcp_listener.local_addr() } } #[derive(Debug)] enum TlsStreamInner { Tcp { rd: AsyncRefCell<TlsStreamRead<TcpStream>>, wr: AsyncRefCell<TlsStreamWrite<TcpStream>>, }, } #[derive(Debug)] pub struct TlsStreamResource { inner: TlsStreamInner, // `None` when a TLS handshake hasn't been done. handshake_info: RefCell<Option<TlsHandshakeInfo>>, cancel_handle: CancelHandle, // Only read and handshake ops get canceled. } impl TlsStreamResource { pub fn new_tcp( (rd, wr): (TlsStreamRead<TcpStream>, TlsStreamWrite<TcpStream>), ) -> Self { Self { inner: TlsStreamInner::Tcp { rd: AsyncRefCell::new(rd), wr: AsyncRefCell::new(wr), }, handshake_info: RefCell::new(None), cancel_handle: Default::default(), } } pub fn into_tls_stream(self) -> TlsStream<TcpStream> { match self.inner { TlsStreamInner::Tcp { rd, wr } => { let read_half = rd.into_inner(); let write_half = wr.into_inner(); read_half.unsplit(write_half) } } } pub fn peer_certificates( &self, ) -> Option< Vec<rustls_tokio_stream::rustls::pki_types::CertificateDer<'static>>, > { self .handshake_info .borrow() .as_ref() .and_then(|info| info.peer_certificates.clone()) } pub async fn read( self: Rc<Self>, data: &mut [u8], ) -> Result<usize, std::io::Error> { let mut rd = RcRef::map(&self, |r| match r.inner { TlsStreamInner::Tcp { ref rd, .. } => rd, }) .borrow_mut() .await; let cancel_handle = RcRef::map(&self, |r| &r.cancel_handle); rd.read(data).try_or_cancel(cancel_handle).await } pub async fn write( self: Rc<Self>, data: &[u8], ) -> Result<usize, std::io::Error> { let mut wr = RcRef::map(&self, |r| match r.inner { TlsStreamInner::Tcp { ref wr, .. } => wr, }) .borrow_mut() .await; let nwritten = wr.write(data).await?; wr.flush().await?; Ok(nwritten) } pub async fn shutdown(self: Rc<Self>) -> Result<(), std::io::Error> { let mut wr = RcRef::map(&self, |r| match r.inner { TlsStreamInner::Tcp { ref wr, .. } => wr, }) .borrow_mut() .await; wr.shutdown().await?; Ok(()) } pub async fn handshake( self: &Rc<Self>, ) -> Result<TlsHandshakeInfo, std::io::Error> { if let Some(tls_info) = &*self.handshake_info.borrow() { return Ok(tls_info.clone()); } let mut wr = RcRef::map(self, |r| match r.inner { TlsStreamInner::Tcp { ref wr, .. } => wr, }) .borrow_mut() .await; let cancel_handle = RcRef::map(self, |r| &r.cancel_handle); let handshake = wr.handshake().try_or_cancel(cancel_handle).await?; let alpn_protocol = handshake.alpn.map(|alpn| alpn.into()); let peer_certificates = handshake.peer_certificates.clone(); let tls_info = TlsHandshakeInfo { alpn_protocol, peer_certificates, }; self.handshake_info.replace(Some(tls_info.clone())); Ok(tls_info) } } impl Resource for TlsStreamResource { deno_core::impl_readable_byob!(); deno_core::impl_writable!(); fn name(&self) -> Cow<'_, str> { "tlsStream".into() } fn shutdown(self: Rc<Self>) -> AsyncResult<()> { Box::pin(self.shutdown().map_err(JsErrorBox::from_err)) } fn close(self: Rc<Self>) { self.cancel_handle.cancel(); } } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct ConnectTlsArgs { cert_file: Option<String>, ca_certs: Vec<String>, alpn_protocols: Option<Vec<String>>, server_name: Option<String>, unsafely_disable_hostname_verification: Option<bool>, } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct StartTlsArgs { rid: ResourceId, ca_certs: Vec<String>, hostname: String, alpn_protocols: Option<Vec<String>>, reject_unauthorized: Option<bool>, unsafely_disable_hostname_verification: Option<bool>, } #[op2] #[cppgc] pub fn op_tls_key_null() -> TlsKeysHolder { TlsKeysHolder::from(TlsKeys::Null) } #[op2(reentrant)] #[cppgc] pub fn op_tls_key_static( #[string] cert: &str, #[string] key: &str, ) -> Result<TlsKeysHolder, deno_tls::TlsError> { let cert = load_certs(&mut BufReader::new(cert.as_bytes()))?; let key = load_private_keys(key.as_bytes())? .into_iter() .next() .unwrap(); Ok(TlsKeysHolder::from(TlsKeys::Static(TlsKey(cert, key)))) } #[op2] pub fn op_tls_cert_resolver_create<'s>( scope: &mut v8::PinScope<'s, '_>, ) -> v8::Local<'s, v8::Array> { let (resolver, lookup) = new_resolver(); let resolver = deno_core::cppgc::make_cppgc_object( scope, TlsKeysHolder::from(TlsKeys::Resolver(resolver)), ); let lookup = deno_core::cppgc::make_cppgc_object(scope, lookup); v8::Array::new_with_elements(scope, &[resolver.into(), lookup.into()]) } #[op2(async)] #[string] pub async fn op_tls_cert_resolver_poll( #[cppgc] lookup: &TlsKeyLookup, ) -> Option<String> { lookup.poll().await } #[op2(fast)] pub fn op_tls_cert_resolver_resolve( #[cppgc] lookup: &TlsKeyLookup, #[string] sni: String, #[cppgc] key: &TlsKeysHolder, ) -> Result<(), NetError> { let TlsKeys::Static(key) = key.take() else { return Err(NetError::UnexpectedKeyType); }; lookup.resolve(sni, Ok(key)); Ok(()) } #[op2(fast)] pub fn op_tls_cert_resolver_resolve_error( #[cppgc] lookup: &TlsKeyLookup, #[string] sni: String, #[string] error: String, ) { lookup.resolve(sni, Err(error)) } #[op2(stack_trace)] #[serde] pub fn op_tls_start( state: Rc<RefCell<OpState>>, #[serde] args: StartTlsArgs, #[cppgc] key_pair: Option<&TlsKeysHolder>, ) -> Result<(ResourceId, IpAddr, IpAddr), NetError> { let rid = args.rid; let reject_unauthorized = args.reject_unauthorized.unwrap_or(true); let hostname = match &*args.hostname { "" => "localhost".to_string(), n => n.to_string(), }; let ca_certs = args .ca_certs .into_iter() .map(|s| s.into_bytes()) .collect::<Vec<_>>(); let hostname_dns = ServerName::try_from(hostname.to_string()) .map_err(|_| NetError::InvalidHostname(hostname))?; // --unsafely-ignore-certificate-errors overrides the `rejectUnauthorized` option. let unsafely_ignore_certificate_errors = if reject_unauthorized { state .borrow() .try_borrow::<UnsafelyIgnoreCertificateErrors>() .and_then(|it| it.0.clone()) } else { Some(Vec::new()) }; let unsafely_disable_hostname_verification = args.unsafely_disable_hostname_verification.unwrap_or(false); let root_cert_store = state .borrow() .borrow::<DefaultTlsOptions>() .root_cert_store() .map_err(NetError::RootCertStore)?; let resource_rc = state .borrow_mut() .resource_table .take::<TcpStreamResource>(rid) .map_err(NetError::Resource)?; // This TCP connection might be used somewhere else. If it's the case, we cannot proceed with the // process of starting a TLS connection on top of this TCP connection, so we just return a Busy error. // See also: https://github.com/denoland/deno/pull/16242 let resource = Rc::try_unwrap(resource_rc).map_err(|_| NetError::TcpStreamBusy)?; let (read_half, write_half) = resource.into_inner(); let tcp_stream = read_half.reunite(write_half).map_err(NetError::Reunite)?; let local_addr = tcp_stream.local_addr()?; let remote_addr = tcp_stream.peer_addr()?; let tls_null = TlsKeysHolder::from(TlsKeys::Null); let key_pair = key_pair.unwrap_or(&tls_null); let mut tls_config = create_client_config(TlsClientConfigOptions { root_cert_store, ca_certs, unsafely_ignore_certificate_errors, unsafely_disable_hostname_verification, cert_chain_and_key: key_pair.take(), socket_use: SocketUse::GeneralSsl, })?; if let Some(alpn_protocols) = args.alpn_protocols { tls_config.alpn_protocols = alpn_protocols.into_iter().map(|s| s.into_bytes()).collect(); } let tls_config = Arc::new(tls_config); let tls_stream = TlsStream::new_client_side( tcp_stream, ClientConnection::new(tls_config, hostname_dns)?, TLS_BUFFER_SIZE, ); let rid = { let mut state_ = state.borrow_mut(); state_ .resource_table .add(TlsStreamResource::new_tcp(tls_stream.into_split())) }; Ok((rid, IpAddr::from(local_addr), IpAddr::from(remote_addr))) } #[op2(async, stack_trace)] #[serde] pub async fn op_net_connect_tls( state: Rc<RefCell<OpState>>, #[serde] addr: IpAddr, #[serde] args: ConnectTlsArgs, #[cppgc] key_pair: &TlsKeysHolder, ) -> Result<(ResourceId, IpAddr, IpAddr), NetError> { let cert_file = args.cert_file.as_deref(); let unsafely_ignore_certificate_errors = state .borrow() .try_borrow::<UnsafelyIgnoreCertificateErrors>() .and_then(|it| it.0.clone()); let unsafely_disable_hostname_verification = args.unsafely_disable_hostname_verification.unwrap_or(false); let cert_file = { let mut s = state.borrow_mut(); let permissions = s.borrow_mut::<PermissionsContainer>(); permissions .check_net(&(&addr.hostname, Some(addr.port)), "Deno.connectTls()") .map_err(NetError::Permission)?; if let Some(path) = cert_file { Some( permissions .check_open( Cow::Borrowed(Path::new(path)), OpenAccessKind::ReadNoFollow, Some("Deno.connectTls()"), ) .map_err(NetError::Permission)?, ) } else { None } }; let mut ca_certs = args .ca_certs .into_iter() .map(|s| s.into_bytes()) .collect::<Vec<_>>(); if let Some(path) = cert_file { let mut buf = Vec::new(); File::open(path)?.read_to_end(&mut buf)?; ca_certs.push(buf); }; let root_cert_store = state .borrow() .borrow::<DefaultTlsOptions>() .root_cert_store() .map_err(NetError::RootCertStore)?; let hostname_dns = if let Some(server_name) = args.server_name { ServerName::try_from(server_name) } else { ServerName::try_from(addr.hostname.clone()) } .map_err(|_| NetError::InvalidHostname(addr.hostname.clone()))?; let connect_addr = resolve_addr(&addr.hostname, addr.port) .await? .next() .ok_or_else(|| NetError::NoResolvedAddress)?; let tcp_stream = TcpStream::connect(connect_addr).await?; let local_addr = tcp_stream.local_addr()?; let remote_addr = tcp_stream.peer_addr()?; let mut tls_config = create_client_config(TlsClientConfigOptions { root_cert_store, ca_certs, unsafely_ignore_certificate_errors, unsafely_disable_hostname_verification, cert_chain_and_key: key_pair.take(), socket_use: SocketUse::GeneralSsl, })?; if let Some(alpn_protocols) = args.alpn_protocols { tls_config.alpn_protocols = alpn_protocols.into_iter().map(|s| s.into_bytes()).collect(); } let tls_config = Arc::new(tls_config); let tls_stream = TlsStream::new_client_side( tcp_stream, ClientConnection::new(tls_config, hostname_dns)?, TLS_BUFFER_SIZE, ); let rid = { let mut state_ = state.borrow_mut(); state_ .resource_table .add(TlsStreamResource::new_tcp(tls_stream.into_split())) }; Ok((rid, IpAddr::from(local_addr), IpAddr::from(remote_addr))) } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct ListenTlsArgs { alpn_protocols: Option<Vec<String>>, reuse_port: bool, #[serde(default)] load_balanced: bool, tcp_backlog: i32, } #[op2(stack_trace)] #[serde] pub fn op_net_listen_tls( state: &mut OpState, #[serde] addr: IpAddr, #[serde] args: ListenTlsArgs, #[cppgc] keys: &TlsKeysHolder, ) -> Result<(ResourceId, IpAddr), NetError> { if args.reuse_port { super::check_unstable(state, "Deno.listenTls({ reusePort: true })"); } { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions .check_net(&(&addr.hostname, Some(addr.port)), "Deno.listenTls()") .map_err(NetError::Permission)?; } let bind_addr = resolve_addr_sync(&addr.hostname, addr.port)? .next() .ok_or(NetError::NoResolvedAddress)?; let tcp_listener = if args.load_balanced { TcpListener::bind_load_balanced(bind_addr, args.tcp_backlog) } else { TcpListener::bind_direct(bind_addr, args.reuse_port, args.tcp_backlog) }?; let local_addr = tcp_listener.local_addr()?; let alpn = args .alpn_protocols .unwrap_or_default() .into_iter() .map(|s| s.into_bytes()) .collect(); let listener = match keys.take() { TlsKeys::Null => return Err(NetError::ListenTlsRequiresKey), TlsKeys::Static(TlsKey(cert, key)) => { let mut tls_config = ServerConfig::builder() .with_no_client_auth() .with_single_cert(cert, key)?; tls_config.alpn_protocols = alpn; TlsListener { tcp_listener, tls_config: Some(tls_config.into()), server_config_provider: None, } } TlsKeys::Resolver(resolver) => TlsListener { tcp_listener, tls_config: None, server_config_provider: Some(resolver.into_server_config_provider(alpn)), }, }; let tls_listener_resource = NetworkListenerResource::new(listener); let rid = state.resource_table.add(tls_listener_resource); Ok((rid, IpAddr::from(local_addr))) } #[op2(async)] #[serde] pub async fn op_net_accept_tls( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<(ResourceId, IpAddr, IpAddr), NetError> { let resource = state .borrow() .resource_table .get::<NetworkListenerResource<TlsListener>>(rid) .map_err(|_| NetError::ListenerClosed)?; let cancel_handle = RcRef::map(&resource, |r| &r.cancel); let listener = RcRef::map(&resource, |r| &r.listener) .try_borrow_mut() .ok_or_else(|| NetError::AcceptTaskOngoing)?; let (tls_stream, remote_addr) = match listener.accept().try_or_cancel(&cancel_handle).await { Ok(tuple) => tuple, Err(err) if err.kind() == ErrorKind::Interrupted => { return Err(NetError::ListenerClosed); } Err(err) => return Err(err.into()), }; let local_addr = tls_stream.local_addr()?; let rid = { let mut state_ = state.borrow_mut(); state_ .resource_table .add(TlsStreamResource::new_tcp(tls_stream.into_split())) }; Ok((rid, IpAddr::from(local_addr), IpAddr::from(remote_addr))) } #[op2(async)] #[serde] pub async fn op_tls_handshake( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<TlsHandshakeInfo, NetError> { let resource = state .borrow() .resource_table .get::<TlsStreamResource>(rid) .map_err(|_| NetError::ListenerClosed)?; resource.handshake().await.map_err(Into::into) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/net/win_pipe.rs
ext/net/win_pipe.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::ffi::OsStr; use std::io; use std::rc::Rc; use deno_core::AsyncRefCell; use deno_core::AsyncResult; use deno_core::CancelHandle; use deno_core::CancelTryFuture; use deno_core::RcRef; use deno_core::Resource; use tokio::io::AsyncReadExt; use tokio::io::AsyncWriteExt; use tokio::io::ReadHalf; use tokio::io::WriteHalf; use tokio::net::windows::named_pipe; /// A Windows named pipe resource that supports concurrent read and write. /// This is achieved by splitting the pipe into separate read and write halves, /// each with its own async lock, allowing duplex communication. pub struct NamedPipe { read_half: AsyncRefCell<NamedPipeRead>, write_half: AsyncRefCell<NamedPipeWrite>, cancel: CancelHandle, /// Server pipe waiting for connection (before split) pending_server: AsyncRefCell<Option<named_pipe::NamedPipeServer>>, } enum NamedPipeRead { Server(ReadHalf<named_pipe::NamedPipeServer>), Client(ReadHalf<named_pipe::NamedPipeClient>), None, } enum NamedPipeWrite { Server(WriteHalf<named_pipe::NamedPipeServer>), Client(WriteHalf<named_pipe::NamedPipeClient>), None, } impl NamedPipe { pub fn new_server( addr: impl AsRef<OsStr>, options: &named_pipe::ServerOptions, ) -> io::Result<NamedPipe> { let server = options.create(addr)?; // Server starts in pending state - will be split after connect() Ok(NamedPipe { read_half: AsyncRefCell::new(NamedPipeRead::None), write_half: AsyncRefCell::new(NamedPipeWrite::None), cancel: Default::default(), pending_server: AsyncRefCell::new(Some(server)), }) } pub fn new_client( addr: impl AsRef<OsStr>, options: &named_pipe::ClientOptions, ) -> io::Result<NamedPipe> { let client = options.open(addr)?; // Client is immediately connected, split into read/write halves let (read, write) = tokio::io::split(client); Ok(NamedPipe { read_half: AsyncRefCell::new(NamedPipeRead::Client(read)), write_half: AsyncRefCell::new(NamedPipeWrite::Client(write)), cancel: Default::default(), pending_server: AsyncRefCell::new(None), }) } pub async fn connect(self: Rc<Self>) -> io::Result<()> { let mut pending = RcRef::map(&self, |s| &s.pending_server).borrow_mut().await; let cancel = RcRef::map(&self, |s| &s.cancel); if let Some(server) = pending.take() { // Wait for client to connect server.connect().try_or_cancel(cancel).await?; // Now split the connected server into read/write halves let (read, write) = tokio::io::split(server); let mut read_half = RcRef::map(&self, |s| &s.read_half).borrow_mut().await; let mut write_half = RcRef::map(&self, |s| &s.write_half).borrow_mut().await; *read_half = NamedPipeRead::Server(read); *write_half = NamedPipeWrite::Server(write); } // Client is already connected, nothing to do Ok(()) } pub async fn write(self: Rc<Self>, buf: &[u8]) -> io::Result<usize> { let mut write_half = RcRef::map(&self, |s| &s.write_half).borrow_mut().await; let cancel = RcRef::map(&self, |s| &s.cancel); match &mut *write_half { NamedPipeWrite::Server(w) => w.write(buf).try_or_cancel(cancel).await, NamedPipeWrite::Client(w) => w.write(buf).try_or_cancel(cancel).await, NamedPipeWrite::None => Err(io::Error::new( io::ErrorKind::NotConnected, "pipe not connected", )), } } pub async fn read(self: Rc<Self>, buf: &mut [u8]) -> io::Result<usize> { let mut read_half = RcRef::map(&self, |s| &s.read_half).borrow_mut().await; let cancel = RcRef::map(&self, |s| &s.cancel); match &mut *read_half { NamedPipeRead::Server(r) => r.read(buf).try_or_cancel(cancel).await, NamedPipeRead::Client(r) => r.read(buf).try_or_cancel(cancel).await, NamedPipeRead::None => Err(io::Error::new( io::ErrorKind::NotConnected, "pipe not connected", )), } } } impl Resource for NamedPipe { deno_core::impl_readable_byob!(); deno_core::impl_writable!(); fn name(&self) -> Cow<'_, str> { Cow::Borrowed("namedPipe") } fn close(self: Rc<Self>) { self.cancel.cancel(); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/net/ops.rs
ext/net/ops.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::net::Ipv4Addr; use std::net::Ipv6Addr; use std::net::SocketAddr; use std::rc::Rc; use std::str::FromStr; use deno_core::AsyncRefCell; use deno_core::ByteString; use deno_core::CancelFuture; use deno_core::CancelHandle; use deno_core::CancelTryFuture; use deno_core::JsBuffer; use deno_core::OpState; use deno_core::RcRef; use deno_core::Resource; use deno_core::ResourceId; use deno_core::op2; use deno_permissions::PermissionsContainer; use hickory_proto::ProtoError; use hickory_proto::ProtoErrorKind; use hickory_proto::rr::record_data::RData; use hickory_proto::rr::record_type::RecordType; use hickory_resolver::ResolveError; use hickory_resolver::ResolveErrorKind; use hickory_resolver::config::NameServerConfigGroup; use hickory_resolver::config::ResolverConfig; use hickory_resolver::config::ResolverOpts; use hickory_resolver::name_server::TokioConnectionProvider; use hickory_resolver::system_conf; use quinn::rustls; use serde::Deserialize; use serde::Serialize; use socket2::Domain; use socket2::Protocol; use socket2::Socket; use socket2::Type; use tokio::net::TcpStream; use tokio::net::UdpSocket; use crate::io::TcpStreamResource; use crate::raw::NetworkListenerResource; use crate::resolve_addr::resolve_addr; use crate::resolve_addr::resolve_addr_sync; use crate::tcp::TcpListener; use crate::tunnel::TunnelAddr; pub type Fd = u32; #[derive(Serialize, Clone, Debug)] #[serde(rename_all = "camelCase")] pub struct TlsHandshakeInfo { pub alpn_protocol: Option<ByteString>, #[serde(skip_serializing)] pub peer_certificates: Option<Vec<rustls::pki_types::CertificateDer<'static>>>, } #[derive(Debug, Deserialize, Serialize)] pub struct IpAddr { pub hostname: String, pub port: u16, } impl From<SocketAddr> for IpAddr { fn from(addr: SocketAddr) -> Self { Self { hostname: addr.ip().to_string(), port: addr.port(), } } } impl From<TunnelAddr> for IpAddr { fn from(addr: TunnelAddr) -> Self { Self { hostname: addr.hostname(), port: addr.port(), } } } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum NetError { #[class("BadResource")] #[error("Listener has been closed")] ListenerClosed, #[class("Busy")] #[error("Listener already in use")] ListenerBusy, #[class("BadResource")] #[error("Socket has been closed")] SocketClosed, #[class("NotConnected")] #[error("Socket has been closed")] SocketClosedNotConnected, #[class("Busy")] #[error("Socket already in use")] SocketBusy, #[class(inherit)] #[error("{0}")] Io(#[from] std::io::Error), #[class("Busy")] #[error("Another accept task is ongoing")] AcceptTaskOngoing, #[class(inherit)] #[error(transparent)] Permission(#[from] deno_permissions::PermissionCheckError), #[class(inherit)] #[error("{0}")] Resource(#[from] deno_core::error::ResourceError), #[class(generic)] #[error("No resolved address found")] NoResolvedAddress, #[class(generic)] #[error("{0}")] AddrParse(#[from] std::net::AddrParseError), #[class(inherit)] #[error("{0}")] Map(crate::io::MapError), #[class(inherit)] #[error("{0}")] Canceled(#[from] deno_core::Canceled), #[class("NotFound")] #[error("{0}")] DnsNotFound(ResolveError), #[class("NotConnected")] #[error("{0}")] DnsNotConnected(ResolveError), #[class("TimedOut")] #[error("{0}")] DnsTimedOut(ResolveError), #[class(generic)] #[error("{0}")] Dns(#[from] ResolveError), #[class("NotSupported")] #[error("Provided record type is not supported")] UnsupportedRecordType, #[class("InvalidData")] #[error("File name or path {0:?} is not valid UTF-8")] InvalidUtf8(std::ffi::OsString), #[class(generic)] #[error("unexpected key type")] UnexpectedKeyType, #[class(type)] #[error("Invalid hostname: '{0}'")] InvalidHostname(String), #[class("Busy")] #[error("TCP stream is currently in use")] TcpStreamBusy, #[class(generic)] #[error("{0}")] Rustls(#[from] deno_tls::rustls::Error), #[class(inherit)] #[error("{0}")] Tls(#[from] deno_tls::TlsError), #[class("InvalidData")] #[error("Error creating TLS certificate: Deno.listenTls requires a key")] ListenTlsRequiresKey, #[class(inherit)] #[error("{0}")] RootCertStore(deno_error::JsErrorBox), #[class(generic)] #[error("{0}")] Reunite(tokio::net::tcp::ReuniteError), #[class(generic)] #[error("VSOCK is not supported on this platform")] VsockUnsupported, #[class(generic)] #[error("Tunnel is not open")] TunnelMissing, } pub(crate) fn accept_err(e: std::io::Error) -> NetError { if let std::io::ErrorKind::Interrupted = e.kind() { NetError::ListenerClosed } else { NetError::Io(e) } } #[op2(async)] #[serde] pub async fn op_net_accept_tcp( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<(ResourceId, IpAddr, IpAddr, Option<Fd>), NetError> { let resource = state .borrow() .resource_table .get::<NetworkListenerResource<TcpListener>>(rid) .map_err(|_| NetError::ListenerClosed)?; let listener = RcRef::map(&resource, |r| &r.listener) .try_borrow_mut() .ok_or_else(|| NetError::AcceptTaskOngoing)?; let cancel = RcRef::map(resource, |r| &r.cancel); let (tcp_stream, _socket_addr) = listener .accept() .try_or_cancel(cancel) .await .map_err(accept_err)?; let mut _fd_raw: Option<Fd> = None; #[cfg(not(windows))] { use std::os::fd::AsFd; use std::os::fd::AsRawFd; let fd = tcp_stream.as_fd(); _fd_raw = Some(fd.as_raw_fd() as u32); } let local_addr = tcp_stream.local_addr()?; let remote_addr = tcp_stream.peer_addr()?; let mut state = state.borrow_mut(); let rid = state .resource_table .add(TcpStreamResource::new(tcp_stream.into_split())); Ok(( rid, IpAddr::from(local_addr), IpAddr::from(remote_addr), _fd_raw, )) } #[op2(async)] #[serde] pub async fn op_net_recv_udp( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, #[buffer] mut buf: JsBuffer, ) -> Result<(usize, IpAddr), NetError> { let resource = state .borrow_mut() .resource_table .get::<UdpSocketResource>(rid) .map_err(|_| NetError::SocketClosed)?; let socket = RcRef::map(&resource, |r| &r.socket).borrow().await; let cancel_handle = RcRef::map(&resource, |r| &r.cancel); let (nread, remote_addr) = socket .recv_from(&mut buf) .try_or_cancel(cancel_handle) .await?; Ok((nread, IpAddr::from(remote_addr))) } #[op2(async, stack_trace)] #[number] pub async fn op_net_send_udp( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, #[serde] addr: IpAddr, #[buffer] zero_copy: JsBuffer, ) -> Result<usize, NetError> { { let mut s = state.borrow_mut(); s.borrow_mut::<PermissionsContainer>().check_net( &(&addr.hostname, Some(addr.port)), "Deno.DatagramConn.send()", )?; } let addr = resolve_addr(&addr.hostname, addr.port) .await? .next() .ok_or(NetError::NoResolvedAddress)?; let resource = state .borrow_mut() .resource_table .get::<UdpSocketResource>(rid) .map_err(|_| NetError::SocketClosed)?; let socket = RcRef::map(&resource, |r| &r.socket).borrow().await; let nwritten = socket.send_to(&zero_copy, &addr).await?; Ok(nwritten) } #[op2(fast)] pub fn op_net_validate_multicast( #[string] address: String, #[string] multi_interface: String, ) -> Result<(), NetError> { let addr = Ipv4Addr::from_str(address.as_str())?; let interface_addr = Ipv4Addr::from_str(multi_interface.as_str())?; if !addr.is_multicast() { return Err(NetError::InvalidHostname(address)); } if !interface_addr.is_multicast() { return Err(NetError::InvalidHostname(multi_interface)); } Ok(()) } #[op2(async)] pub async fn op_net_join_multi_v4_udp( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, #[string] address: String, #[string] multi_interface: String, ) -> Result<(), NetError> { let resource = state .borrow_mut() .resource_table .get::<UdpSocketResource>(rid) .map_err(|_| NetError::SocketClosed)?; let socket = RcRef::map(&resource, |r| &r.socket).borrow().await; let addr = Ipv4Addr::from_str(address.as_str())?; let interface_addr = Ipv4Addr::from_str(multi_interface.as_str())?; socket.join_multicast_v4(addr, interface_addr)?; Ok(()) } #[op2(async)] pub async fn op_net_join_multi_v6_udp( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, #[string] address: String, #[smi] multi_interface: u32, ) -> Result<(), NetError> { let resource = state .borrow_mut() .resource_table .get::<UdpSocketResource>(rid) .map_err(|_| NetError::SocketClosed)?; let socket = RcRef::map(&resource, |r| &r.socket).borrow().await; let addr = Ipv6Addr::from_str(address.as_str())?; socket.join_multicast_v6(&addr, multi_interface)?; Ok(()) } #[op2(async)] pub async fn op_net_leave_multi_v4_udp( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, #[string] address: String, #[string] multi_interface: String, ) -> Result<(), NetError> { let resource = state .borrow_mut() .resource_table .get::<UdpSocketResource>(rid) .map_err(|_| NetError::SocketClosed)?; let socket = RcRef::map(&resource, |r| &r.socket).borrow().await; let addr = Ipv4Addr::from_str(address.as_str())?; let interface_addr = Ipv4Addr::from_str(multi_interface.as_str())?; socket.leave_multicast_v4(addr, interface_addr)?; Ok(()) } #[op2(async)] pub async fn op_net_leave_multi_v6_udp( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, #[string] address: String, #[smi] multi_interface: u32, ) -> Result<(), NetError> { let resource = state .borrow_mut() .resource_table .get::<UdpSocketResource>(rid) .map_err(|_| NetError::SocketClosed)?; let socket = RcRef::map(&resource, |r| &r.socket).borrow().await; let addr = Ipv6Addr::from_str(address.as_str())?; socket.leave_multicast_v6(&addr, multi_interface)?; Ok(()) } #[op2(async)] pub async fn op_net_set_multi_loopback_udp( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, is_v4_membership: bool, loopback: bool, ) -> Result<(), NetError> { let resource = state .borrow_mut() .resource_table .get::<UdpSocketResource>(rid) .map_err(|_| NetError::SocketClosed)?; let socket = RcRef::map(&resource, |r| &r.socket).borrow().await; if is_v4_membership { socket.set_multicast_loop_v4(loopback)?; } else { socket.set_multicast_loop_v6(loopback)?; } Ok(()) } #[op2(async)] pub async fn op_net_set_multi_ttl_udp( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, #[smi] ttl: u32, ) -> Result<(), NetError> { let resource = state .borrow_mut() .resource_table .get::<UdpSocketResource>(rid) .map_err(|_| NetError::SocketClosed)?; let socket = RcRef::map(&resource, |r| &r.socket).borrow().await; socket.set_multicast_ttl_v4(ttl)?; Ok(()) } #[op2(async)] pub async fn op_net_set_broadcast_udp( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, broadcast: bool, ) -> Result<(), NetError> { let resource = state .borrow_mut() .resource_table .get::<UdpSocketResource>(rid) .map_err(|_| NetError::SocketClosed)?; let socket = RcRef::map(&resource, |r| &r.socket).borrow().await; socket.set_broadcast(broadcast)?; Ok(()) } /// If this token is present in op_net_connect_tcp call and /// the hostname matches with one of the resolved IPs, then /// the permission check is performed against the original hostname. pub struct NetPermToken { pub hostname: String, pub port: Option<u16>, pub resolved_ips: Vec<String>, } // SAFETY: we're sure `NetPermToken` can be GCed unsafe impl deno_core::GarbageCollected for NetPermToken { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"NetPermToken" } } impl NetPermToken { /// Checks if the given address is included in the resolved IPs. pub fn includes(&self, addr: &str) -> bool { self.resolved_ips.iter().any(|ip| ip == addr) } } #[op2] #[serde] pub fn op_net_get_ips_from_perm_token( #[cppgc] token: &NetPermToken, ) -> Vec<String> { token.resolved_ips.clone() } #[op2(async, stack_trace)] #[serde] pub async fn op_net_connect_tcp( state: Rc<RefCell<OpState>>, #[serde] addr: IpAddr, #[cppgc] net_perm_token: Option<&NetPermToken>, #[smi] resource_abort_id: Option<ResourceId>, ) -> Result<(ResourceId, IpAddr, IpAddr), NetError> { op_net_connect_tcp_inner(state, addr, net_perm_token, resource_abort_id).await } #[inline] pub async fn op_net_connect_tcp_inner( state: Rc<RefCell<OpState>>, addr: IpAddr, net_perm_token: Option<&NetPermToken>, resource_abort_id: Option<ResourceId>, ) -> Result<(ResourceId, IpAddr, IpAddr), NetError> { { let mut state_ = state.borrow_mut(); // If token exists and the address matches to its resolved ips, // then we can check net permission against token.hostname, instead of addr.hostname let hostname_to_check = match net_perm_token { Some(token) if token.includes(&addr.hostname) => token.hostname.clone(), _ => addr.hostname.clone(), }; state_ .borrow_mut::<PermissionsContainer>() .check_net(&(&hostname_to_check, Some(addr.port)), "Deno.connect()")?; } let addr = resolve_addr(&addr.hostname, addr.port) .await? .next() .ok_or_else(|| NetError::NoResolvedAddress)?; let cancel_handle = resource_abort_id.and_then(|rid| { state .borrow_mut() .resource_table .get::<CancelHandle>(rid) .ok() }); let tcp_stream_result = if let Some(cancel_handle) = &cancel_handle { TcpStream::connect(&addr).or_cancel(cancel_handle).await? } else { TcpStream::connect(&addr).await }; if let Some(cancel_rid) = resource_abort_id && let Ok(res) = state.borrow_mut().resource_table.take_any(cancel_rid) { res.close(); } let tcp_stream = match tcp_stream_result { Ok(tcp_stream) => tcp_stream, Err(e) => return Err(NetError::Io(e)), }; let local_addr = tcp_stream.local_addr()?; let remote_addr = tcp_stream.peer_addr()?; let mut state_ = state.borrow_mut(); let rid = state_ .resource_table .add(TcpStreamResource::new(tcp_stream.into_split())); Ok((rid, IpAddr::from(local_addr), IpAddr::from(remote_addr))) } struct UdpSocketResource { socket: AsyncRefCell<UdpSocket>, cancel: CancelHandle, } impl Resource for UdpSocketResource { fn name(&self) -> Cow<'_, str> { "udpSocket".into() } fn close(self: Rc<Self>) { self.cancel.cancel() } } #[op2(stack_trace)] #[serde] pub fn op_net_listen_tcp( state: &mut OpState, #[serde] addr: IpAddr, reuse_port: bool, load_balanced: bool, tcp_backlog: i32, ) -> Result<(ResourceId, IpAddr), NetError> { if reuse_port { super::check_unstable(state, "Deno.listen({ reusePort: true })"); } state .borrow_mut::<PermissionsContainer>() .check_net(&(&addr.hostname, Some(addr.port)), "Deno.listen()")?; let addr = resolve_addr_sync(&addr.hostname, addr.port)? .next() .ok_or_else(|| NetError::NoResolvedAddress)?; let listener = if load_balanced { TcpListener::bind_load_balanced(addr, tcp_backlog) } else { TcpListener::bind_direct(addr, reuse_port, tcp_backlog) }?; let local_addr = listener.local_addr()?; let listener_resource = NetworkListenerResource::new(listener); let rid = state.resource_table.add(listener_resource); Ok((rid, IpAddr::from(local_addr))) } fn net_listen_udp( state: &mut OpState, addr: IpAddr, reuse_address: bool, loopback: bool, ) -> Result<(ResourceId, IpAddr), NetError> { state .borrow_mut::<PermissionsContainer>() .check_net(&(&addr.hostname, Some(addr.port)), "Deno.listenDatagram()")?; let addr = resolve_addr_sync(&addr.hostname, addr.port)? .next() .ok_or_else(|| NetError::NoResolvedAddress)?; let domain = if addr.is_ipv4() { Domain::IPV4 } else { Domain::IPV6 }; let socket_tmp = Socket::new(domain, Type::DGRAM, Some(Protocol::UDP))?; if reuse_address { // This logic is taken from libuv: // // On the BSDs, SO_REUSEPORT implies SO_REUSEADDR but with some additional // refinements for programs that use multicast. // // Linux as of 3.9 has a SO_REUSEPORT socket option but with semantics that // are different from the BSDs: it _shares_ the port rather than steal it // from the current listener. While useful, it's not something we can // emulate on other platforms so we don't enable it. #[cfg(any( target_os = "windows", target_os = "android", target_os = "linux" ))] socket_tmp.set_reuse_address(true)?; #[cfg(all(unix, not(any(target_os = "android", target_os = "linux"))))] socket_tmp.set_reuse_port(true)?; } let socket_addr = socket2::SockAddr::from(addr); socket_tmp.bind(&socket_addr)?; socket_tmp.set_nonblocking(true)?; // Enable messages to be sent to the broadcast address (255.255.255.255) by default socket_tmp.set_broadcast(true)?; if domain == Domain::IPV4 { socket_tmp.set_multicast_loop_v4(loopback)?; } else { socket_tmp.set_multicast_loop_v6(loopback)?; } let std_socket: std::net::UdpSocket = socket_tmp.into(); let socket = UdpSocket::from_std(std_socket)?; let local_addr = socket.local_addr()?; let socket_resource = UdpSocketResource { socket: AsyncRefCell::new(socket), cancel: Default::default(), }; let rid = state.resource_table.add(socket_resource); Ok((rid, IpAddr::from(local_addr))) } #[op2(stack_trace)] #[serde] pub fn op_net_listen_udp( state: &mut OpState, #[serde] addr: IpAddr, reuse_address: bool, loopback: bool, ) -> Result<(ResourceId, IpAddr), NetError> { super::check_unstable(state, "Deno.listenDatagram"); net_listen_udp(state, addr, reuse_address, loopback) } #[op2(stack_trace)] #[serde] pub fn op_node_unstable_net_listen_udp( state: &mut OpState, #[serde] addr: IpAddr, reuse_address: bool, loopback: bool, ) -> Result<(ResourceId, IpAddr), NetError> { net_listen_udp(state, addr, reuse_address, loopback) } #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] #[op2(async, stack_trace)] #[serde] pub async fn op_net_connect_vsock( state: Rc<RefCell<OpState>>, #[smi] cid: u32, #[smi] port: u32, ) -> Result<(ResourceId, (u32, u32), (u32, u32)), NetError> { use std::sync::Arc; use deno_features::FeatureChecker; use tokio_vsock::VsockAddr; use tokio_vsock::VsockStream; state .borrow() .borrow::<Arc<FeatureChecker>>() .check_or_exit("vsock", "Deno.connect"); state .borrow_mut() .borrow_mut::<PermissionsContainer>() .check_net_vsock(cid, port, "Deno.connect()")?; let addr = VsockAddr::new(cid, port); let vsock_stream = VsockStream::connect(addr).await?; let local_addr = vsock_stream.local_addr()?; let remote_addr = vsock_stream.peer_addr()?; let rid = state .borrow_mut() .resource_table .add(crate::io::VsockStreamResource::new( vsock_stream.into_split(), )); Ok(( rid, (local_addr.cid(), local_addr.port()), (remote_addr.cid(), remote_addr.port()), )) } #[cfg(not(any( target_os = "android", target_os = "linux", target_os = "macos" )))] #[op2] #[serde] pub fn op_net_connect_vsock() -> Result<(), NetError> { Err(NetError::VsockUnsupported) } #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] #[op2(stack_trace)] #[serde] pub fn op_net_listen_vsock( state: &mut OpState, #[smi] cid: u32, #[smi] port: u32, ) -> Result<(ResourceId, u32, u32), NetError> { use std::sync::Arc; use deno_features::FeatureChecker; use tokio_vsock::VsockAddr; use tokio_vsock::VsockListener; state .borrow::<Arc<FeatureChecker>>() .check_or_exit("vsock", "Deno.listen"); state.borrow_mut::<PermissionsContainer>().check_net_vsock( cid, port, "Deno.listen()", )?; let addr = VsockAddr::new(cid, port); let listener = VsockListener::bind(addr)?; let local_addr = listener.local_addr()?; let listener_resource = NetworkListenerResource::new(listener); let rid = state.resource_table.add(listener_resource); Ok((rid, local_addr.cid(), local_addr.port())) } #[cfg(not(any( target_os = "android", target_os = "linux", target_os = "macos" )))] #[op2] #[serde] pub fn op_net_listen_vsock() -> Result<(), NetError> { Err(NetError::VsockUnsupported) } #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] #[op2(async)] #[serde] pub async fn op_net_accept_vsock( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<(ResourceId, (u32, u32), (u32, u32)), NetError> { use tokio_vsock::VsockListener; let resource = state .borrow() .resource_table .get::<NetworkListenerResource<VsockListener>>(rid) .map_err(|_| NetError::ListenerClosed)?; let listener = RcRef::map(&resource, |r| &r.listener) .try_borrow_mut() .ok_or_else(|| NetError::AcceptTaskOngoing)?; let cancel = RcRef::map(resource, |r| &r.cancel); let (vsock_stream, _socket_addr) = listener .accept() .try_or_cancel(cancel) .await .map_err(accept_err)?; let local_addr = vsock_stream.local_addr()?; let remote_addr = vsock_stream.peer_addr()?; let mut state = state.borrow_mut(); let rid = state .resource_table .add(crate::io::VsockStreamResource::new( vsock_stream.into_split(), )); Ok(( rid, (local_addr.cid(), local_addr.port()), (remote_addr.cid(), remote_addr.port()), )) } #[cfg(not(any( target_os = "android", target_os = "linux", target_os = "macos" )))] #[op2] #[serde] pub fn op_net_accept_vsock() -> Result<(), NetError> { Err(NetError::VsockUnsupported) } #[op2] #[serde] pub fn op_net_listen_tunnel( state: &mut OpState, ) -> Result<(ResourceId, IpAddr), NetError> { let Some(listener) = super::tunnel::get_tunnel() else { return Err(NetError::TunnelMissing); }; let listener = listener.clone(); let local_addr = listener.local_addr()?.into(); let rid = state .resource_table .add(crate::raw::NetworkListenerResource::new(listener)); Ok((rid, local_addr)) } #[op2(async)] #[serde] pub async fn op_net_accept_tunnel( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<(ResourceId, IpAddr, IpAddr), NetError> { let resource = state .borrow() .resource_table .get::<NetworkListenerResource<crate::tunnel::TunnelConnection>>(rid) .map_err(|_| NetError::ListenerClosed)?; let listener = RcRef::map(&resource, |r| &r.listener) .try_borrow_mut() .ok_or_else(|| NetError::AcceptTaskOngoing)?; let cancel = RcRef::map(resource, |r| &r.cancel); let (stream, _) = listener .accept() .try_or_cancel(cancel) .await .map_err(accept_err)?; let local_addr = stream.local_addr()?; let remote_addr = stream.peer_addr()?; let rid = state .borrow_mut() .resource_table .add(crate::tunnel::TunnelStreamResource::new(stream)); Ok((rid, local_addr.into(), remote_addr.into())) } #[derive(Serialize, Eq, PartialEq, Debug)] #[serde(untagged)] pub enum DnsRecordData { A(String), Aaaa(String), Aname(String), Caa { critical: bool, tag: String, value: String, }, Cname(String), Mx { preference: u16, exchange: String, }, Naptr { order: u16, preference: u16, flags: String, services: String, regexp: String, replacement: String, }, Ns(String), Ptr(String), Soa { mname: String, rname: String, serial: u32, refresh: i32, retry: i32, expire: i32, minimum: u32, }, Srv { priority: u16, weight: u16, port: u16, target: String, }, Txt(Vec<String>), } #[derive(Serialize, Eq, PartialEq, Debug)] #[serde()] pub struct DnsRecordWithTtl { pub data: DnsRecordData, pub ttl: u32, } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct ResolveAddrArgs { cancel_rid: Option<ResourceId>, query: String, record_type: RecordType, options: Option<ResolveDnsOption>, } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct ResolveDnsOption { name_server: Option<NameServer>, } fn default_port() -> u16 { 53 } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct NameServer { ip_addr: String, #[serde(default = "default_port")] port: u16, } #[op2(async, stack_trace)] #[serde] pub async fn op_dns_resolve( state: Rc<RefCell<OpState>>, #[serde] args: ResolveAddrArgs, ) -> Result<Vec<DnsRecordWithTtl>, NetError> { let ResolveAddrArgs { query, record_type, options, cancel_rid, } = args; let (config, opts) = if let Some(name_server) = options.as_ref().and_then(|o| o.name_server.as_ref()) { let group = NameServerConfigGroup::from_ips_clear( &[name_server.ip_addr.parse()?], name_server.port, true, ); ( ResolverConfig::from_parts(None, vec![], group), ResolverOpts::default(), ) } else { system_conf::read_system_conf()? }; { let mut s = state.borrow_mut(); let perm = s.borrow_mut::<PermissionsContainer>(); // Checks permission against the name servers which will be actually queried. for ns in config.name_servers() { let socker_addr = &ns.socket_addr; let ip = socker_addr.ip().to_string(); let port = socker_addr.port(); perm.check_net(&(&ip, Some(port)), "Deno.resolveDns()")?; } } let provider = TokioConnectionProvider::default(); let resolver = hickory_resolver::Resolver::builder_with_config(config, provider) .with_options(opts) .build(); let lookup_fut = resolver.lookup(query, record_type); let cancel_handle = cancel_rid.and_then(|rid| { state .borrow_mut() .resource_table .get::<CancelHandle>(rid) .ok() }); let lookup = if let Some(cancel_handle) = cancel_handle { let lookup_rv = lookup_fut.or_cancel(cancel_handle).await; if let Some(cancel_rid) = cancel_rid && let Ok(res) = state.borrow_mut().resource_table.take_any(cancel_rid) { res.close(); }; lookup_rv? } else { lookup_fut.await }; lookup .map_err(|e| match e.kind() { ResolveErrorKind::Proto(ProtoError { kind, .. }) if matches!(**kind, ProtoErrorKind::NoRecordsFound { .. }) => { NetError::DnsNotFound(e) } ResolveErrorKind::Proto(ProtoError { kind, .. }) if matches!(**kind, ProtoErrorKind::NoConnections) => { NetError::DnsNotConnected(e) } ResolveErrorKind::Proto(ProtoError { kind, .. }) if matches!(**kind, ProtoErrorKind::Timeout) => { NetError::DnsTimedOut(e) } _ => NetError::Dns(e), })? .records() .iter() .filter_map(|rec| { let r = format_rdata(record_type)(rec.data()).transpose(); r.map(|maybe_data| { maybe_data.map(|data| DnsRecordWithTtl { data, ttl: rec.ttl(), }) }) }) .collect::<Result<Vec<DnsRecordWithTtl>, NetError>>() } #[op2(fast)] pub fn op_set_nodelay( state: &mut OpState, #[smi] rid: ResourceId, nodelay: bool, ) -> Result<(), NetError> { op_set_nodelay_inner(state, rid, nodelay) } #[inline] pub fn op_set_nodelay_inner( state: &mut OpState, rid: ResourceId, nodelay: bool, ) -> Result<(), NetError> { let resource: Rc<TcpStreamResource> = state.resource_table.get::<TcpStreamResource>(rid)?; resource.set_nodelay(nodelay).map_err(NetError::Map) } #[op2(fast)] pub fn op_set_keepalive( state: &mut OpState, #[smi] rid: ResourceId, keepalive: bool, ) -> Result<(), NetError> { op_set_keepalive_inner(state, rid, keepalive) } #[inline] pub fn op_set_keepalive_inner( state: &mut OpState, rid: ResourceId, keepalive: bool, ) -> Result<(), NetError> { let resource: Rc<TcpStreamResource> = state.resource_table.get::<TcpStreamResource>(rid)?; resource.set_keepalive(keepalive).map_err(NetError::Map) } fn format_rdata( ty: RecordType, ) -> impl Fn(&RData) -> Result<Option<DnsRecordData>, NetError> { use RecordType::*; move |r: &RData| -> Result<Option<DnsRecordData>, NetError> { let record = match ty { A => r.as_a().map(ToString::to_string).map(DnsRecordData::A), AAAA => r .as_aaaa() .map(ToString::to_string) .map(DnsRecordData::Aaaa), ANAME => r .as_aname() .map(ToString::to_string) .map(DnsRecordData::Aname), CAA => r.as_caa().map(|caa| { DnsRecordData::Caa { critical: caa.issuer_critical(), tag: caa.tag().to_string(), // hickory_proto now handles CAA records encoding within the CAA struct, we can assume that it's safe to unwrap here value: str::from_utf8(caa.raw_value()).unwrap().to_string(), } }), CNAME => r .as_cname() .map(ToString::to_string) .map(DnsRecordData::Cname), MX => r.as_mx().map(|mx| DnsRecordData::Mx { preference: mx.preference(), exchange: mx.exchange().to_string(), }), NAPTR => r.as_naptr().map(|naptr| DnsRecordData::Naptr { order: naptr.order(), preference: naptr.preference(), flags: String::from_utf8(naptr.flags().to_vec()).unwrap(), services: String::from_utf8(naptr.services().to_vec()).unwrap(), regexp: String::from_utf8(naptr.regexp().to_vec()).unwrap(), replacement: naptr.replacement().to_string(), }), NS => r.as_ns().map(ToString::to_string).map(DnsRecordData::Ns), PTR => r.as_ptr().map(ToString::to_string).map(DnsRecordData::Ptr), SOA => r.as_soa().map(|soa| DnsRecordData::Soa { mname: soa.mname().to_string(), rname: soa.rname().to_string(), serial: soa.serial(), refresh: soa.refresh(), retry: soa.retry(), expire: soa.expire(), minimum: soa.minimum(), }), SRV => r.as_srv().map(|srv| DnsRecordData::Srv { priority: srv.priority(), weight: srv.weight(), port: srv.port(), target: srv.target().to_string(), }), TXT => r.as_txt().map(|txt| { let texts: Vec<String> = txt .iter() .map(|bytes| { // Tries to parse these bytes as Latin-1 bytes.iter().map(|&b| b as char).collect::<String>() }) .collect(); DnsRecordData::Txt(texts) }), _ => return Err(NetError::UnsupportedRecordType), }; Ok(record) } } #[cfg(test)] mod tests { use std::net::Ipv4Addr; use std::net::Ipv6Addr; use std::net::ToSocketAddrs; use std::sync::Mutex; use deno_core::JsRuntime; use deno_core::RuntimeOptions; use deno_core::futures::FutureExt; use hickory_proto::rr::Name; use hickory_proto::rr::rdata::SOA; use hickory_proto::rr::rdata::a::A; use hickory_proto::rr::rdata::aaaa::AAAA; use hickory_proto::rr::rdata::caa::CAA; use hickory_proto::rr::rdata::caa::KeyValue; use hickory_proto::rr::rdata::mx::MX; use hickory_proto::rr::rdata::name::ANAME; use hickory_proto::rr::rdata::name::CNAME; use hickory_proto::rr::rdata::name::NS; use hickory_proto::rr::rdata::name::PTR; use hickory_proto::rr::rdata::naptr::NAPTR; use hickory_proto::rr::rdata::srv::SRV; use hickory_proto::rr::rdata::txt::TXT; use hickory_proto::rr::record_data::RData; use socket2::SockRef; use super::*; #[test] fn rdata_to_return_record_a() { let func = format_rdata(RecordType::A); let rdata = RData::A(A(Ipv4Addr::new(127, 0, 0, 1))); assert_eq!( func(&rdata).unwrap(), Some(DnsRecordData::A("127.0.0.1".to_string())) ); } #[test] fn rdata_to_return_record_aaaa() { let func = format_rdata(RecordType::AAAA); let rdata = RData::AAAA(AAAA(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1))); assert_eq!( func(&rdata).unwrap(), Some(DnsRecordData::Aaaa("::1".to_string())) ); } #[test] fn rdata_to_return_record_aname() { let func = format_rdata(RecordType::ANAME); let rdata = RData::ANAME(ANAME(Name::new())); assert_eq!( func(&rdata).unwrap(), Some(DnsRecordData::Aname("".to_string())) ); } #[test] fn rdata_to_return_record_caa() { let func = format_rdata(RecordType::CAA); let rdata = RData::CAA(CAA::new_issue( false, Some(Name::parse("example.com", None).unwrap()), vec![KeyValue::new("account", "123456")], ));
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
true
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/net/tunnel.rs
ext/net/tunnel.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::collections::HashMap; use std::net::SocketAddr; use std::rc::Rc; use std::sync::OnceLock; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use deno_core::AsyncMutFuture; use deno_core::AsyncRefCell; use deno_core::AsyncResult; use deno_core::CancelHandle; use deno_core::CancelTryFuture; use deno_core::RcRef; use deno_core::Resource; use deno_core::futures::TryFutureExt; use deno_error::JsErrorBox; pub use deno_tunnel::Authentication; pub use deno_tunnel::Error; pub use deno_tunnel::Event; pub use deno_tunnel::OwnedReadHalf; pub use deno_tunnel::OwnedWriteHalf; pub use deno_tunnel::TunnelAddr; pub use deno_tunnel::TunnelConnection; pub use deno_tunnel::TunnelStream; pub use deno_tunnel::quinn; use tokio::io::AsyncReadExt; use tokio::io::AsyncWriteExt; static TUNNEL: OnceLock<TunnelConnection> = OnceLock::new(); static RUN_BEFORE_EXIT: AtomicBool = AtomicBool::new(true); pub fn set_tunnel(tunnel: TunnelConnection) { if TUNNEL.set(tunnel).is_ok() { deno_signals::before_exit(before_exit_internal); } } fn before_exit_internal() { if RUN_BEFORE_EXIT.load(Ordering::Relaxed) { before_exit(); } } pub fn disable_before_exit() { RUN_BEFORE_EXIT.store(false, Ordering::Relaxed); } pub fn before_exit() { log::trace!("deno_net::tunnel::before_exit >"); if let Some(tunnel) = get_tunnel() { // stay alive long enough to actually send the close frame, since // we can't rely on the linux kernel to close this like with tcp. deno_core::futures::executor::block_on(tunnel.close(1u32, b"")); } log::trace!("deno_net::tunnel::before_exit <"); } pub fn get_tunnel() -> Option<&'static TunnelConnection> { TUNNEL.get() } #[derive(Debug)] pub struct TunnelStreamResource { tx: AsyncRefCell<OwnedWriteHalf>, rx: AsyncRefCell<OwnedReadHalf>, cancel_handle: CancelHandle, } impl TunnelStreamResource { pub fn new(stream: TunnelStream) -> Self { let (read_half, write_half) = stream.into_split(); Self { tx: AsyncRefCell::new(write_half), rx: AsyncRefCell::new(read_half), cancel_handle: Default::default(), } } pub fn into_inner(self) -> TunnelStream { let tx = self.tx.into_inner(); let rx = self.rx.into_inner(); rx.unsplit(tx) } fn rd_borrow_mut(self: &Rc<Self>) -> AsyncMutFuture<OwnedReadHalf> { RcRef::map(self, |r| &r.rx).borrow_mut() } fn wr_borrow_mut(self: &Rc<Self>) -> AsyncMutFuture<OwnedWriteHalf> { RcRef::map(self, |r| &r.tx).borrow_mut() } pub fn cancel_handle(self: &Rc<Self>) -> RcRef<CancelHandle> { RcRef::map(self, |r| &r.cancel_handle) } } impl Resource for TunnelStreamResource { fn read(self: Rc<Self>, limit: usize) -> AsyncResult<deno_core::BufView> { Box::pin(async move { let mut vec = vec![0; limit]; let nread = self .rd_borrow_mut() .await .read(&mut vec) .map_err(|e| JsErrorBox::generic(format!("{e}"))) .try_or_cancel(self.cancel_handle()) .await?; if nread != vec.len() { vec.truncate(nread); } Ok(vec.into()) }) } fn read_byob( self: Rc<Self>, mut buf: deno_core::BufMutView, ) -> AsyncResult<(usize, deno_core::BufMutView)> { Box::pin(async move { let nread = self .rd_borrow_mut() .await .read(&mut buf) .map_err(|e| JsErrorBox::generic(format!("{e}"))) .try_or_cancel(self.cancel_handle()) .await?; Ok((nread, buf)) }) } fn write( self: Rc<Self>, buf: deno_core::BufView, ) -> AsyncResult<deno_core::WriteOutcome> { Box::pin(async move { let nwritten = self .wr_borrow_mut() .await .write(&buf) .await .map_err(|e| JsErrorBox::generic(format!("{e}")))?; Ok(deno_core::WriteOutcome::Partial { nwritten, view: buf, }) }) } fn name(&self) -> std::borrow::Cow<'_, str> { "tunnelStream".into() } fn shutdown(self: Rc<Self>) -> AsyncResult<()> { Box::pin(async move { let mut wr = self.wr_borrow_mut().await; wr.reset(0u32) .map_err(|e| JsErrorBox::generic(format!("{e}")))?; Ok(()) }) } fn close(self: Rc<Self>) { self.cancel_handle.cancel() } } #[allow(dead_code)] #[derive(Debug, serde::Serialize, serde::Deserialize)] enum StreamHeader { Control { token: String, org: String, app: String, }, Stream { local_addr: SocketAddr, remote_addr: SocketAddr, }, Agent {}, } #[allow(dead_code)] #[derive(Debug, serde::Serialize, serde::Deserialize)] enum ControlMessage { Authenticated { metadata: HashMap<String, String>, addr: SocketAddr, hostnames: Vec<String>, env: HashMap<String, String>, }, Routed {}, Migrate {}, }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/url/lib.rs
ext/url/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license.
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/canvas/image_ops.rs
ext/canvas/image_ops.rs
// Copyright 2018-2025 the Deno authors. MIT license. use bytemuck::cast_slice; use bytemuck::cast_slice_mut; use image::ColorType; use image::DynamicImage; use image::GenericImageView; use image::ImageBuffer; use image::Luma; use image::LumaA; use image::Pixel; use image::Primitive; use image::Rgb; use image::Rgba; use lcms2::PixelFormat; use lcms2::Pod; use lcms2::Profile; use lcms2::Transform; use num_traits::NumCast; use num_traits::SaturatingMul; use crate::CanvasError; pub(crate) trait PremultiplyAlpha { fn premultiply_alpha(&self) -> Self; } impl<T: Primitive> PremultiplyAlpha for LumaA<T> { fn premultiply_alpha(&self) -> Self { let max_t = T::DEFAULT_MAX_VALUE; let mut pixel = [self.0[0], self.0[1]]; let alpha_index = pixel.len() - 1; let alpha = pixel[alpha_index]; let normalized_alpha = alpha.to_f32().unwrap() / max_t.to_f32().unwrap(); if normalized_alpha == 0.0 { return LumaA([pixel[0], pixel[alpha_index]]); } for rgb in pixel.iter_mut().take(alpha_index) { *rgb = NumCast::from((rgb.to_f32().unwrap() * normalized_alpha).round()) .unwrap() } LumaA([pixel[0], pixel[alpha_index]]) } } impl<T: Primitive> PremultiplyAlpha for Rgba<T> { fn premultiply_alpha(&self) -> Self { let max_t = T::DEFAULT_MAX_VALUE; let mut pixel = [self.0[0], self.0[1], self.0[2], self.0[3]]; let alpha_index = pixel.len() - 1; let alpha = pixel[alpha_index]; let normalized_alpha = alpha.to_f32().unwrap() / max_t.to_f32().unwrap(); if normalized_alpha == 0.0 { return Rgba([pixel[0], pixel[1], pixel[2], pixel[alpha_index]]); } for rgb in pixel.iter_mut().take(alpha_index) { *rgb = NumCast::from((rgb.to_f32().unwrap() * normalized_alpha).round()) .unwrap() } Rgba([pixel[0], pixel[1], pixel[2], pixel[alpha_index]]) } } fn process_premultiply_alpha<I, P, S>(image: &I) -> ImageBuffer<P, Vec<S>> where I: GenericImageView<Pixel = P>, P: Pixel<Subpixel = S> + PremultiplyAlpha + 'static, S: Primitive + 'static, { let (width, height) = image.dimensions(); let mut out = ImageBuffer::new(width, height); for (x, y, pixel) in image.pixels() { let pixel = pixel.premultiply_alpha(); out.put_pixel(x, y, pixel); } out } /// Premultiply the alpha channel of the image. pub(crate) fn premultiply_alpha( image: DynamicImage, ) -> Result<DynamicImage, CanvasError> { match image { DynamicImage::ImageLumaA8(image) => { Ok(process_premultiply_alpha(&image).into()) } DynamicImage::ImageLumaA16(image) => { Ok(process_premultiply_alpha(&image).into()) } DynamicImage::ImageRgba8(image) => { Ok(process_premultiply_alpha(&image).into()) } DynamicImage::ImageRgba16(image) => { Ok(process_premultiply_alpha(&image).into()) } DynamicImage::ImageRgb32F(_) => { Err(CanvasError::UnsupportedColorType(image.color())) } DynamicImage::ImageRgba32F(_) => { Err(CanvasError::UnsupportedColorType(image.color())) } // If the image does not have an alpha channel, return the image as is. _ => Ok(image), } } pub(crate) trait UnpremultiplyAlpha { /// To determine if the image is premultiplied alpha, /// checking premultiplied RGBA value is one where any of the R/G/B channel values exceeds the alpha channel value.\ /// https://www.w3.org/TR/webgpu/#color-spaces fn is_premultiplied_alpha(&self) -> bool; fn unpremultiply_alpha(&self) -> Self; } impl<T: Primitive + SaturatingMul + Ord> UnpremultiplyAlpha for Rgba<T> { fn is_premultiplied_alpha(&self) -> bool { let max_t = T::DEFAULT_MAX_VALUE; let pixel = [self.0[0], self.0[1], self.0[2]]; let alpha_index = self.0.len() - 1; let alpha = self.0[alpha_index]; match pixel.iter().max() { Some(rgb_max) => rgb_max < &max_t.saturating_mul(&alpha), // usually doesn't reach here None => false, } } fn unpremultiply_alpha(&self) -> Self { let max_t = T::DEFAULT_MAX_VALUE; let mut pixel = [self.0[0], self.0[1], self.0[2], self.0[3]]; let alpha_index = pixel.len() - 1; let alpha = pixel[alpha_index]; // avoid to divide by zero if alpha.to_f32().unwrap() == 0.0 { return Rgba([pixel[0], pixel[1], pixel[2], pixel[alpha_index]]); } for rgb in pixel.iter_mut().take(alpha_index) { let unchecked_value = (rgb.to_f32().unwrap() / (alpha.to_f32().unwrap() / max_t.to_f32().unwrap())) .round(); let checked_value = if unchecked_value > max_t.to_f32().unwrap() { max_t.to_f32().unwrap() } else { unchecked_value }; *rgb = NumCast::from(checked_value).unwrap(); } Rgba([pixel[0], pixel[1], pixel[2], pixel[alpha_index]]) } } impl<T: Primitive + SaturatingMul + Ord> UnpremultiplyAlpha for LumaA<T> { fn is_premultiplied_alpha(&self) -> bool { let max_t = T::DEFAULT_MAX_VALUE; let pixel = [self.0[0]]; let alpha_index = self.0.len() - 1; let alpha = self.0[alpha_index]; pixel[0] < max_t.saturating_mul(&alpha) } fn unpremultiply_alpha(&self) -> Self { let max_t = T::DEFAULT_MAX_VALUE; let mut pixel = [self.0[0], self.0[1]]; let alpha_index = pixel.len() - 1; let alpha = pixel[alpha_index]; // avoid to divide by zero if alpha.to_f32().unwrap() == 0.0 { return LumaA([pixel[0], pixel[alpha_index]]); } for rgb in pixel.iter_mut().take(alpha_index) { let unchecked_value = (rgb.to_f32().unwrap() / (alpha.to_f32().unwrap() / max_t.to_f32().unwrap())) .round(); let checked_value = if unchecked_value > max_t.to_f32().unwrap() { max_t.to_f32().unwrap() } else { unchecked_value }; *rgb = NumCast::from(checked_value).unwrap(); } LumaA([pixel[0], pixel[alpha_index]]) } } fn is_premultiplied_alpha<I, P, S>(image: &I) -> bool where I: GenericImageView<Pixel = P>, P: Pixel<Subpixel = S> + UnpremultiplyAlpha + 'static, S: Primitive + 'static, { image .pixels() .any(|(_, _, pixel)| pixel.is_premultiplied_alpha()) } fn process_unpremultiply_alpha<I, P, S>(image: &I) -> ImageBuffer<P, Vec<S>> where I: GenericImageView<Pixel = P>, P: Pixel<Subpixel = S> + UnpremultiplyAlpha + 'static, S: Primitive + 'static, { let (width, height) = image.dimensions(); let mut out = ImageBuffer::new(width, height); for (x, y, pixel) in image.pixels() { let pixel = pixel.unpremultiply_alpha(); out.put_pixel(x, y, pixel); } out } /// Invert the premultiplied alpha channel of the image. pub(crate) fn unpremultiply_alpha( image: DynamicImage, ) -> Result<DynamicImage, CanvasError> { match image { DynamicImage::ImageLumaA8(image) => Ok(if is_premultiplied_alpha(&image) { process_unpremultiply_alpha(&image).into() } else { image.into() }), DynamicImage::ImageLumaA16(image) => { Ok(if is_premultiplied_alpha(&image) { process_unpremultiply_alpha(&image).into() } else { image.into() }) } DynamicImage::ImageRgba8(image) => Ok(if is_premultiplied_alpha(&image) { process_unpremultiply_alpha(&image).into() } else { image.into() }), DynamicImage::ImageRgba16(image) => Ok(if is_premultiplied_alpha(&image) { process_unpremultiply_alpha(&image).into() } else { image.into() }), DynamicImage::ImageRgb32F(_) => { Err(CanvasError::UnsupportedColorType(image.color())) } DynamicImage::ImageRgba32F(_) => { Err(CanvasError::UnsupportedColorType(image.color())) } // If the image does not have an alpha channel, return the image as is. _ => Ok(image), } } pub(crate) trait SliceToPixel { fn slice_to_pixel(pixel: &[u8]) -> Self; } impl<T: Primitive + Pod> SliceToPixel for Luma<T> { fn slice_to_pixel(pixel: &[u8]) -> Self { let pixel: &[T] = cast_slice(pixel); let pixel = [pixel[0]]; Luma(pixel) } } impl<T: Primitive + Pod> SliceToPixel for LumaA<T> { fn slice_to_pixel(pixel: &[u8]) -> Self { let pixel: &[T] = cast_slice(pixel); let pixel = [pixel[0], pixel[1]]; LumaA(pixel) } } impl<T: Primitive + Pod> SliceToPixel for Rgb<T> { fn slice_to_pixel(pixel: &[u8]) -> Self { let pixel: &[T] = cast_slice(pixel); let pixel = [pixel[0], pixel[1], pixel[2]]; Rgb(pixel) } } impl<T: Primitive + Pod> SliceToPixel for Rgba<T> { fn slice_to_pixel(pixel: &[u8]) -> Self { let pixel: &[T] = cast_slice(pixel); let pixel = [pixel[0], pixel[1], pixel[2], pixel[3]]; Rgba(pixel) } } pub(crate) trait TransformColorProfile { fn transform_color_profile<P, S>( &mut self, transformer: &Transform<u8, u8>, ) -> P where P: Pixel<Subpixel = S> + SliceToPixel + 'static, S: Primitive + 'static; } macro_rules! impl_transform_color_profile { ($type:ty) => { impl TransformColorProfile for $type { fn transform_color_profile<P, S>( &mut self, transformer: &Transform<u8, u8>, ) -> P where P: Pixel<Subpixel = S> + SliceToPixel + 'static, S: Primitive + 'static, { let mut pixel = cast_slice_mut(self.0.as_mut_slice()); transformer.transform_in_place(&mut pixel); P::slice_to_pixel(&pixel) } } }; } impl_transform_color_profile!(Luma<u8>); impl_transform_color_profile!(Luma<u16>); impl_transform_color_profile!(LumaA<u8>); impl_transform_color_profile!(LumaA<u16>); impl_transform_color_profile!(Rgb<u8>); impl_transform_color_profile!(Rgb<u16>); impl_transform_color_profile!(Rgba<u8>); impl_transform_color_profile!(Rgba<u16>); fn process_icc_profile_conversion<I, P, S>( image: &I, color: ColorType, input_icc_profile: Profile, output_icc_profile: Profile, ) -> Result<ImageBuffer<P, Vec<S>>, CanvasError> where I: GenericImageView<Pixel = P>, P: Pixel<Subpixel = S> + SliceToPixel + TransformColorProfile + 'static, S: Primitive + 'static, { let (width, height) = image.dimensions(); let mut out = ImageBuffer::new(width, height); let pixel_format = match color { ColorType::L8 => Ok(PixelFormat::GRAY_8), ColorType::L16 => Ok(PixelFormat::GRAY_16), ColorType::La8 => Ok(PixelFormat::GRAYA_8), ColorType::La16 => Ok(PixelFormat::GRAYA_16), ColorType::Rgb8 => Ok(PixelFormat::RGB_8), ColorType::Rgb16 => Ok(PixelFormat::RGB_16), ColorType::Rgba8 => Ok(PixelFormat::RGBA_8), ColorType::Rgba16 => Ok(PixelFormat::RGBA_16), _ => Err(CanvasError::UnsupportedColorType(color)), }?; let transformer = Transform::new( &input_icc_profile, pixel_format, &output_icc_profile, pixel_format, output_icc_profile.header_rendering_intent(), ) .map_err(CanvasError::Lcms)?; for (x, y, mut pixel) in image.pixels() { let pixel = pixel.transform_color_profile(&transformer); out.put_pixel(x, y, pixel); } Ok(out) } /// Convert the color space of the image from the ICC profile to sRGB. pub(crate) fn to_srgb_from_icc_profile( image: DynamicImage, icc_profile: Option<Vec<u8>>, ) -> Result<DynamicImage, CanvasError> { match icc_profile { // If there is no color profile information, return the image as is. None => Ok(image), Some(icc_profile) => match Profile::new_icc(&icc_profile) { // If the color profile information is invalid, return the image as is. Err(_) => Ok(image), Ok(icc_profile) => { let srgb_icc_profile = Profile::new_srgb(); let color = image.color(); match image { DynamicImage::ImageLuma8(image) => Ok( process_icc_profile_conversion( &image, color, icc_profile, srgb_icc_profile, )? .into(), ), DynamicImage::ImageLuma16(image) => Ok( process_icc_profile_conversion( &image, color, icc_profile, srgb_icc_profile, )? .into(), ), DynamicImage::ImageLumaA8(image) => Ok( process_icc_profile_conversion( &image, color, icc_profile, srgb_icc_profile, )? .into(), ), DynamicImage::ImageLumaA16(image) => Ok( process_icc_profile_conversion( &image, color, icc_profile, srgb_icc_profile, )? .into(), ), DynamicImage::ImageRgb8(image) => Ok( process_icc_profile_conversion( &image, color, icc_profile, srgb_icc_profile, )? .into(), ), DynamicImage::ImageRgb16(image) => Ok( process_icc_profile_conversion( &image, color, icc_profile, srgb_icc_profile, )? .into(), ), DynamicImage::ImageRgba8(image) => Ok( process_icc_profile_conversion( &image, color, icc_profile, srgb_icc_profile, )? .into(), ), DynamicImage::ImageRgba16(image) => Ok( process_icc_profile_conversion( &image, color, icc_profile, srgb_icc_profile, )? .into(), ), DynamicImage::ImageRgb32F(_) => { Err(CanvasError::UnsupportedColorType(image.color())) } DynamicImage::ImageRgba32F(_) => { Err(CanvasError::UnsupportedColorType(image.color())) } _ => Err(CanvasError::UnsupportedColorType(image.color())), } } }, } } /// Create an image buffer from raw bytes. fn process_image_buffer_from_raw_bytes<P, S>( width: u32, height: u32, buffer: &[u8], bytes_per_pixel: usize, ) -> ImageBuffer<P, Vec<S>> where P: Pixel<Subpixel = S> + SliceToPixel + 'static, S: Primitive + 'static, { let mut out = ImageBuffer::new(width, height); for (index, buffer) in buffer.chunks_exact(bytes_per_pixel).enumerate() { let pixel = P::slice_to_pixel(buffer); out.put_pixel(index as u32, index as u32, pixel); } out } pub(crate) fn create_image_from_raw_bytes( width: u32, height: u32, buffer: &[u8], ) -> Result<DynamicImage, CanvasError> { let total_pixels = (width * height) as usize; // avoid to divide by zero let bytes_per_pixel = buffer .len() .checked_div(total_pixels) .ok_or(CanvasError::InvalidSizeZero(width, height))?; // convert from a bytes per pixel to the color type of the image // https://github.com/image-rs/image/blob/2c986d353333d2604f0c3f1fcef262cc763c0001/src/color.rs#L38-L49 match bytes_per_pixel { 1 => Ok(DynamicImage::ImageLuma8( process_image_buffer_from_raw_bytes( width, height, buffer, bytes_per_pixel, ), )), 2 => Ok( // NOTE: ImageLumaA8 is also the same bytes per pixel. DynamicImage::ImageLuma16(process_image_buffer_from_raw_bytes( width, height, buffer, bytes_per_pixel, )), ), 3 => Ok(DynamicImage::ImageRgb8( process_image_buffer_from_raw_bytes( width, height, buffer, bytes_per_pixel, ), )), 4 => Ok( // NOTE: ImageLumaA16 is also the same bytes per pixel. DynamicImage::ImageRgba8(process_image_buffer_from_raw_bytes( width, height, buffer, bytes_per_pixel, )), ), 6 => Ok(DynamicImage::ImageRgb16( process_image_buffer_from_raw_bytes( width, height, buffer, bytes_per_pixel, ), )), 8 => Ok(DynamicImage::ImageRgba16( process_image_buffer_from_raw_bytes( width, height, buffer, bytes_per_pixel, ), )), 12 => Err(CanvasError::UnsupportedColorType(ColorType::Rgb32F)), 16 => Err(CanvasError::UnsupportedColorType(ColorType::Rgba32F)), _ => Err(CanvasError::UnsupportedColorType(ColorType::L8)), } } #[cfg(test)] mod tests { use image::Rgba; use super::*; #[test] fn test_premultiply_alpha() { let rgba = Rgba::<u8>([255, 128, 0, 128]); let rgba = rgba.premultiply_alpha(); assert_eq!(rgba, Rgba::<u8>([128, 64, 0, 128])); let rgba = Rgba::<u8>([255, 255, 255, 255]); let rgba = rgba.premultiply_alpha(); assert_eq!(rgba, Rgba::<u8>([255, 255, 255, 255])); } #[test] fn test_unpremultiply_alpha() { let rgba = Rgba::<u8>([127, 0, 0, 127]); let rgba = rgba.unpremultiply_alpha(); assert_eq!(rgba, Rgba::<u8>([255, 0, 0, 127])); // https://github.com/denoland/deno/issues/28732 let rgba = Rgba::<u8>([247, 0, 0, 233]); let rgba = rgba.unpremultiply_alpha(); assert_eq!(rgba, Rgba::<u8>([255, 0, 0, 233])); let rgba = Rgba::<u8>([255, 0, 0, 0]); let rgba = rgba.unpremultiply_alpha(); assert_eq!(rgba, Rgba::<u8>([255, 0, 0, 0])); } #[test] fn test_process_image_buffer_from_raw_bytes() { let buffer = &[255, 255, 0, 0, 0, 0, 255, 255]; let color = ColorType::Rgba16; let bytes_per_pixel = color.bytes_per_pixel() as usize; let image = DynamicImage::ImageRgba16(process_image_buffer_from_raw_bytes( 1, 1, buffer, bytes_per_pixel, )) .to_rgba16(); assert_eq!(image.get_pixel(0, 0), &Rgba::<u16>([65535, 0, 0, 65535])); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/canvas/lib.rs
ext/canvas/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. mod image_ops; mod op_create_image_bitmap; pub use image; use image::ColorType; use op_create_image_bitmap::op_create_image_bitmap; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum CanvasError { /// Image formats that is 32-bit depth are not supported currently due to the following reasons: /// - e.g. OpenEXR, it's not covered by the spec. /// - JPEG XL supported by WebKit, but it cannot be called a standard today. /// https://github.com/whatwg/mimesniff/issues/143 /// #[class(type)] #[error("Unsupported color type and bit depth: '{0:?}'")] UnsupportedColorType(ColorType), #[class("DOMExceptionInvalidStateError")] #[error("Cannot decode image '{0}'")] InvalidImage(image::ImageError), #[class("DOMExceptionInvalidStateError")] #[error( "The chunk data is not big enough with the specified width: {0} and height: {1}" )] NotBigEnoughChunk(u32, u32), #[class("DOMExceptionInvalidStateError")] #[error("The width: {0} or height: {1} could not be zero")] InvalidSizeZero(u32, u32), #[class(generic)] #[error(transparent)] Lcms(#[from] lcms2::Error), #[class(generic)] #[error(transparent)] Image(#[from] image::ImageError), } impl CanvasError { /// Convert an [`image::ImageError`] to an [`CanvasError::InvalidImage`]. fn image_error_to_invalid_image(error: image::ImageError) -> Self { CanvasError::InvalidImage(error) } } deno_core::extension!( deno_canvas, deps = [deno_webidl, deno_web, deno_webgpu], ops = [op_create_image_bitmap], lazy_loaded_esm = ["01_image.js"], );
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/canvas/op_create_image_bitmap.rs
ext/canvas/op_create_image_bitmap.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::io::BufReader; use std::io::Cursor; use deno_core::JsBuffer; use deno_core::ToJsBuffer; use deno_core::op2; // use image::codecs::webp::WebPDecoder; use image::DynamicImage; use image::ImageDecoder; use image::RgbaImage; use image::codecs::bmp::BmpDecoder; // use image::codecs::gif::GifDecoder; use image::codecs::ico::IcoDecoder; use image::codecs::jpeg::JpegDecoder; use image::codecs::png::PngDecoder; use image::imageops::FilterType; use image::imageops::overlay; use image::metadata::Orientation; use crate::CanvasError; use crate::image_ops::create_image_from_raw_bytes; use crate::image_ops::premultiply_alpha as process_premultiply_alpha; use crate::image_ops::to_srgb_from_icc_profile; use crate::image_ops::unpremultiply_alpha; #[derive(Debug, PartialEq)] enum ImageBitmapSource { Blob, ImageData, ImageBitmap, } #[derive(Debug, PartialEq)] enum ImageOrientation { FlipY, FromImage, } #[derive(Debug, PartialEq)] enum PremultiplyAlpha { Default, Premultiply, None, } #[derive(Debug, PartialEq)] enum ColorSpaceConversion { Default, None, } #[derive(Debug, PartialEq)] enum ResizeQuality { Pixelated, Low, Medium, High, } #[derive(Debug, PartialEq)] enum MimeType { NoMatch, Png, Jpeg, Gif, Bmp, Ico, Webp, } type DecodeBitmapDataReturn = (DynamicImage, u32, u32, Option<Orientation>, Option<Vec<u8>>); fn decode_bitmap_data( buf: &[u8], width: u32, height: u32, image_bitmap_source: &ImageBitmapSource, mime_type: MimeType, ) -> Result<DecodeBitmapDataReturn, CanvasError> { let (image, width, height, orientation, icc_profile) = match image_bitmap_source { ImageBitmapSource::Blob => { // // About the animated image // > Blob .4 // > ... If this is an animated image, imageBitmap's bitmap data must only be taken from // > the default image of the animation (the one that the format defines is to be used when animation is // > not supported or is disabled), or, if there is no such image, the first frame of the animation. // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html // // see also browser implementations: (The implementation of Gecko and WebKit is hard to read.) // https://source.chromium.org/chromium/chromium/src/+/bdbc054a6cabbef991904b5df9066259505cc686:third_party/blink/renderer/platform/image-decoders/image_decoder.h;l=175-189 // let (image, orientation, icc_profile) = match mime_type { MimeType::Png => { // If PngDecoder decodes an animated image, it returns the default image if one is set, or the first frame if not. let mut decoder = PngDecoder::new(BufReader::new(Cursor::new(buf))) .map_err(CanvasError::image_error_to_invalid_image)?; let orientation = decoder.orientation()?; let icc_profile = decoder.icc_profile()?; ( DynamicImage::from_decoder(decoder) .map_err(CanvasError::image_error_to_invalid_image)?, orientation, icc_profile, ) } MimeType::Jpeg => { let mut decoder = JpegDecoder::new(BufReader::new(Cursor::new(buf))) .map_err(CanvasError::image_error_to_invalid_image)?; let orientation = decoder.orientation()?; let icc_profile = decoder.icc_profile()?; ( DynamicImage::from_decoder(decoder) .map_err(CanvasError::image_error_to_invalid_image)?, orientation, icc_profile, ) } MimeType::Gif => { // NOTE: Temporarily not supported due to build size concerns // https://github.com/denoland/deno/pull/25517#issuecomment-2626044644 unimplemented!(); // The GifDecoder decodes the first frame. // let mut decoder = GifDecoder::new(BufReader::new(Cursor::new(buf))) // .map_err(CanvasError::image_error_to_invalid_image)?; // let orientation = decoder.orientation()?; // let icc_profile = decoder.icc_profile()?; // ( // DynamicImage::from_decoder(decoder) // .map_err(CanvasError::image_error_to_invalid_image)?, // orientation, // icc_profile, // ) } MimeType::Bmp => { let mut decoder = BmpDecoder::new(BufReader::new(Cursor::new(buf))) .map_err(CanvasError::image_error_to_invalid_image)?; let orientation = decoder.orientation()?; let icc_profile = decoder.icc_profile()?; ( DynamicImage::from_decoder(decoder) .map_err(CanvasError::image_error_to_invalid_image)?, orientation, icc_profile, ) } MimeType::Ico => { let mut decoder = IcoDecoder::new(BufReader::new(Cursor::new(buf))) .map_err(CanvasError::image_error_to_invalid_image)?; let orientation = decoder.orientation()?; let icc_profile = decoder.icc_profile()?; ( DynamicImage::from_decoder(decoder) .map_err(CanvasError::image_error_to_invalid_image)?, orientation, icc_profile, ) } MimeType::Webp => { // NOTE: Temporarily not supported due to build size concerns // https://github.com/denoland/deno/pull/25517#issuecomment-2626044644 unimplemented!(); // The WebPDecoder decodes the first frame. // let mut decoder = // WebPDecoder::new(BufReader::new(Cursor::new(buf))) // .map_err(CanvasError::image_error_to_invalid_image)?; // let orientation = decoder.orientation()?; // let icc_profile = decoder.icc_profile()?; // ( // DynamicImage::from_decoder(decoder) // .map_err(CanvasError::image_error_to_invalid_image)?, // orientation, // icc_profile, // ) } // This pattern is unreachable due to current block is already checked by the ImageBitmapSource above. MimeType::NoMatch => unreachable!(), }; let width = image.width(); let height = image.height(); (image, width, height, Some(orientation), icc_profile) } ImageBitmapSource::ImageData => { // > 4.12.5.1.15 Pixel manipulation // > imagedata.data // > Returns the one-dimensional array containing the data in RGBA order, as integers in the range 0 to 255. // https://html.spec.whatwg.org/multipage/canvas.html#pixel-manipulation let image = match RgbaImage::from_raw(width, height, buf.into()) { Some(image) => image.into(), None => { return Err(CanvasError::NotBigEnoughChunk(width, height)); } }; (image, width, height, None, None) } ImageBitmapSource::ImageBitmap => { let image = create_image_from_raw_bytes(width, height, buf)?; (image, width, height, None, None) } }; Ok((image, width, height, orientation, icc_profile)) } /// According to the spec, it's not clear how to handle the color space conversion. /// /// Therefore, if you interpret the specification description from the implementation and wpt results, it will be as follows. /// /// Let val be the value of the colorSpaceConversion member of options, and then run these substeps: /// 1. If val is "default", to convert to the sRGB color space. /// 2. If val is "none", to use the decoded image data as is. /// /// related issue in whatwg /// https://github.com/whatwg/html/issues/10578 /// /// reference in wpt /// https://github.com/web-platform-tests/wpt/blob/d575dc75ede770df322fbc5da3112dcf81f192ec/html/canvas/element/manual/imagebitmap/createImageBitmap-colorSpaceConversion.html#L18 /// https://wpt.live/html/canvas/element/manual/imagebitmap/createImageBitmap-colorSpaceConversion.html fn apply_color_space_conversion( image: DynamicImage, icc_profile: Option<Vec<u8>>, color_space_conversion: &ColorSpaceConversion, ) -> Result<DynamicImage, CanvasError> { match color_space_conversion { // return the decoded image as is. ColorSpaceConversion::None => Ok(image), ColorSpaceConversion::Default => { to_srgb_from_icc_profile(image, icc_profile) } } } fn apply_premultiply_alpha( image: DynamicImage, image_bitmap_source: &ImageBitmapSource, premultiply_alpha: &PremultiplyAlpha, ) -> Result<DynamicImage, CanvasError> { match premultiply_alpha { // 1. PremultiplyAlpha::Default => Ok(image), // https://html.spec.whatwg.org/multipage/canvas.html#convert-from-premultiplied // 2. PremultiplyAlpha::Premultiply => process_premultiply_alpha(image), // 3. PremultiplyAlpha::None => { // NOTE: It's not clear how to handle the case of ImageData. // https://issues.chromium.org/issues/339759426 // https://github.com/whatwg/html/issues/5365 if *image_bitmap_source == ImageBitmapSource::ImageData { return Ok(image); } unpremultiply_alpha(image) } } } #[derive(Debug, PartialEq)] struct ParsedArgs { resize_width: Option<u32>, resize_height: Option<u32>, sx: Option<i32>, sy: Option<i32>, sw: Option<i32>, sh: Option<i32>, image_orientation: ImageOrientation, premultiply_alpha: PremultiplyAlpha, color_space_conversion: ColorSpaceConversion, resize_quality: ResizeQuality, image_bitmap_source: ImageBitmapSource, mime_type: MimeType, } #[allow(clippy::too_many_arguments)] fn parse_args( sx: i32, sy: i32, sw: i32, sh: i32, image_orientation: u8, premultiply_alpha: u8, color_space_conversion: u8, resize_width: u32, resize_height: u32, resize_quality: u8, image_bitmap_source: u8, mime_type: u8, ) -> ParsedArgs { let resize_width = if resize_width == 0 { None } else { Some(resize_width) }; let resize_height = if resize_height == 0 { None } else { Some(resize_height) }; let sx = if sx == 0 { None } else { Some(sx) }; let sy = if sy == 0 { None } else { Some(sy) }; let sw = if sw == 0 { None } else { Some(sw) }; let sh = if sh == 0 { None } else { Some(sh) }; // Their unreachable wildcard patterns are validated in JavaScript-side. let image_orientation = match image_orientation { 0 => ImageOrientation::FromImage, 1 => ImageOrientation::FlipY, _ => unreachable!(), }; let premultiply_alpha = match premultiply_alpha { 0 => PremultiplyAlpha::Default, 1 => PremultiplyAlpha::Premultiply, 2 => PremultiplyAlpha::None, _ => unreachable!(), }; let color_space_conversion = match color_space_conversion { 0 => ColorSpaceConversion::Default, 1 => ColorSpaceConversion::None, _ => unreachable!(), }; let resize_quality = match resize_quality { 0 => ResizeQuality::Low, 1 => ResizeQuality::Pixelated, 2 => ResizeQuality::Medium, 3 => ResizeQuality::High, _ => unreachable!(), }; let image_bitmap_source = match image_bitmap_source { 0 => ImageBitmapSource::Blob, 1 => ImageBitmapSource::ImageData, 2 => ImageBitmapSource::ImageBitmap, _ => unreachable!(), }; let mime_type = match mime_type { 0 => MimeType::NoMatch, 1 => MimeType::Png, 2 => MimeType::Jpeg, 3 => MimeType::Gif, 4 => MimeType::Bmp, 5 => MimeType::Ico, 6 => MimeType::Webp, _ => unreachable!(), }; ParsedArgs { resize_width, resize_height, sx, sy, sw, sh, image_orientation, premultiply_alpha, color_space_conversion, resize_quality, image_bitmap_source, mime_type, } } #[op2] #[serde] #[allow(clippy::too_many_arguments)] pub(super) fn op_create_image_bitmap( #[buffer] buf: JsBuffer, width: u32, height: u32, sx: i32, sy: i32, sw: i32, sh: i32, image_orientation: u8, premultiply_alpha: u8, color_space_conversion: u8, resize_width: u32, resize_height: u32, resize_quality: u8, image_bitmap_source: u8, mime_type: u8, ) -> Result<(ToJsBuffer, u32, u32), CanvasError> { let ParsedArgs { resize_width, resize_height, sx, sy, sw, sh, image_orientation, premultiply_alpha, color_space_conversion, resize_quality, image_bitmap_source, mime_type, } = parse_args( sx, sy, sw, sh, image_orientation, premultiply_alpha, color_space_conversion, resize_width, resize_height, resize_quality, image_bitmap_source, mime_type, ); // 6. Switch on image: let (image, width, height, orientation, icc_profile) = decode_bitmap_data(&buf, width, height, &image_bitmap_source, mime_type)?; // crop bitmap data // 2. #[rustfmt::skip] let source_rectangle: [[i32; 2]; 4] = if let (Some(sx), Some(sy), Some(sw), Some(sh)) = (sx, sy, sw, sh) { [ [sx, sy], [sx + sw, sy], [sx + sw, sy + sh], [sx, sy + sh] ] } else { [ [0, 0], [width as i32, 0], [width as i32, height as i32], [0, height as i32], ] }; /* * The cropping works differently than the spec specifies: * The spec states to create an infinite surface and place the top-left corner * of the image a 0,0 and crop based on sourceRectangle. * * We instead create a surface the size of sourceRectangle, and position * the image at the correct location, which is the inverse of the x & y of * sourceRectangle's top-left corner. */ let input_x = -(source_rectangle[0][0] as i64); let input_y = -(source_rectangle[0][1] as i64); let surface_width = (source_rectangle[1][0] - source_rectangle[0][0]) as u32; let surface_height = (source_rectangle[3][1] - source_rectangle[0][1]) as u32; // 3. let output_width = if let Some(resize_width) = resize_width { resize_width } else if let Some(resize_height) = resize_height { (surface_width * resize_height).div_ceil(surface_height) } else { surface_width }; // 4. let output_height = if let Some(resize_height) = resize_height { resize_height } else if let Some(resize_width) = resize_width { (surface_height * resize_width).div_ceil(surface_width) } else { surface_height }; // 5. let image = if !(width == surface_width && height == surface_height && input_x == 0 && input_y == 0) { let mut surface = DynamicImage::new(surface_width, surface_height, image.color()); overlay(&mut surface, &image, input_x, input_y); surface } else { image }; // 7. let filter_type = match resize_quality { ResizeQuality::Pixelated => FilterType::Nearest, ResizeQuality::Low => FilterType::Triangle, ResizeQuality::Medium => FilterType::CatmullRom, ResizeQuality::High => FilterType::Lanczos3, }; // should use resize_exact // https://github.com/image-rs/image/issues/1220#issuecomment-632060015 let mut image = image.resize_exact(output_width, output_height, filter_type); // 8. let image = match image_bitmap_source { ImageBitmapSource::Blob => { // Note: According to browser behavior and wpt results, if Exif contains image orientation, // it applies the rotation from it before following the value of imageOrientation. // This is not stated in the spec but in MDN currently. // https://github.com/mdn/content/pull/34366 // SAFETY: The orientation is always Some if the image is from a Blob. let orientation = orientation.unwrap(); DynamicImage::apply_orientation(&mut image, orientation); match image_orientation { ImageOrientation::FlipY => image.flipv(), ImageOrientation::FromImage => image, } } ImageBitmapSource::ImageData | ImageBitmapSource::ImageBitmap => { match image_orientation { ImageOrientation::FlipY => image.flipv(), ImageOrientation::FromImage => image, } } }; // 9. let image = apply_color_space_conversion(image, icc_profile, &color_space_conversion)?; // 10. let image = apply_premultiply_alpha(image, &image_bitmap_source, &premultiply_alpha)?; Ok((image.into_bytes().into(), output_width, output_height)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_args() { let parsed_args = parse_args(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); assert_eq!( parsed_args, ParsedArgs { resize_width: None, resize_height: None, sx: None, sy: None, sw: None, sh: None, image_orientation: ImageOrientation::FromImage, premultiply_alpha: PremultiplyAlpha::Default, color_space_conversion: ColorSpaceConversion::Default, resize_quality: ResizeQuality::Low, image_bitmap_source: ImageBitmapSource::Blob, mime_type: MimeType::NoMatch, } ); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/broadcast_channel/lib.rs
ext/broadcast_channel/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license.
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/kv/config.rs
ext/kv/config.rs
// Copyright 2018-2025 the Deno authors. MIT license. #[derive(Clone, Copy, Debug)] pub struct KvConfig { pub max_write_key_size_bytes: usize, pub max_read_key_size_bytes: usize, pub max_value_size_bytes: usize, pub max_read_ranges: usize, pub max_read_entries: usize, pub max_checks: usize, pub max_mutations: usize, pub max_watched_keys: usize, pub max_total_mutation_size_bytes: usize, pub max_total_key_size_bytes: usize, } impl KvConfig { pub fn builder() -> KvConfigBuilder { KvConfigBuilder::default() } } #[derive(Default)] pub struct KvConfigBuilder { max_write_key_size_bytes: Option<usize>, max_value_size_bytes: Option<usize>, max_read_ranges: Option<usize>, max_read_entries: Option<usize>, max_checks: Option<usize>, max_mutations: Option<usize>, max_watched_keys: Option<usize>, max_total_mutation_size_bytes: Option<usize>, max_total_key_size_bytes: Option<usize>, } impl KvConfigBuilder { pub fn new() -> Self { Self::default() } pub fn max_write_key_size_bytes( &mut self, max_write_key_size_bytes: usize, ) -> &mut Self { self.max_write_key_size_bytes = Some(max_write_key_size_bytes); self } pub fn max_value_size_bytes( &mut self, max_value_size_bytes: usize, ) -> &mut Self { self.max_value_size_bytes = Some(max_value_size_bytes); self } pub fn max_read_ranges(&mut self, max_read_ranges: usize) -> &mut Self { self.max_read_ranges = Some(max_read_ranges); self } pub fn max_read_entries(&mut self, max_read_entries: usize) -> &mut Self { self.max_read_entries = Some(max_read_entries); self } pub fn max_checks(&mut self, max_checks: usize) -> &mut Self { self.max_checks = Some(max_checks); self } pub fn max_mutations(&mut self, max_mutations: usize) -> &mut Self { self.max_mutations = Some(max_mutations); self } pub fn max_watched_keys(&mut self, max_watched_keys: usize) -> &mut Self { self.max_watched_keys = Some(max_watched_keys); self } pub fn max_total_mutation_size_bytes( &mut self, max_total_mutation_size_bytes: usize, ) -> &mut Self { self.max_total_mutation_size_bytes = Some(max_total_mutation_size_bytes); self } pub fn max_total_key_size_bytes( &mut self, max_total_key_size_bytes: usize, ) -> &mut Self { self.max_total_key_size_bytes = Some(max_total_key_size_bytes); self } pub fn build(&self) -> KvConfig { const MAX_WRITE_KEY_SIZE_BYTES: usize = 2048; // range selectors can contain 0x00 or 0xff suffixes const MAX_READ_KEY_SIZE_BYTES: usize = MAX_WRITE_KEY_SIZE_BYTES + 1; const MAX_VALUE_SIZE_BYTES: usize = 65536; const MAX_READ_RANGES: usize = 10; const MAX_READ_ENTRIES: usize = 1000; const MAX_CHECKS: usize = 100; const MAX_MUTATIONS: usize = 1000; const MAX_WATCHED_KEYS: usize = 10; const MAX_TOTAL_MUTATION_SIZE_BYTES: usize = 800 * 1024; const MAX_TOTAL_KEY_SIZE_BYTES: usize = 80 * 1024; KvConfig { max_write_key_size_bytes: self .max_write_key_size_bytes .unwrap_or(MAX_WRITE_KEY_SIZE_BYTES), max_read_key_size_bytes: self .max_write_key_size_bytes .map(|x| // range selectors can contain 0x00 or 0xff suffixes x + 1) .unwrap_or(MAX_READ_KEY_SIZE_BYTES), max_value_size_bytes: self .max_value_size_bytes .unwrap_or(MAX_VALUE_SIZE_BYTES), max_read_ranges: self.max_read_ranges.unwrap_or(MAX_READ_RANGES), max_read_entries: self.max_read_entries.unwrap_or(MAX_READ_ENTRIES), max_checks: self.max_checks.unwrap_or(MAX_CHECKS), max_mutations: self.max_mutations.unwrap_or(MAX_MUTATIONS), max_watched_keys: self.max_watched_keys.unwrap_or(MAX_WATCHED_KEYS), max_total_mutation_size_bytes: self .max_total_mutation_size_bytes .unwrap_or(MAX_TOTAL_MUTATION_SIZE_BYTES), max_total_key_size_bytes: self .max_total_key_size_bytes .unwrap_or(MAX_TOTAL_KEY_SIZE_BYTES), } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/kv/dynamic.rs
ext/kv/dynamic.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::RefCell; use std::rc::Rc; use async_trait::async_trait; use deno_core::OpState; use deno_error::JsErrorBox; use denokv_proto::CommitResult; use denokv_proto::ReadRangeOutput; use denokv_proto::WatchStream; use crate::AtomicWrite; use crate::Database; use crate::DatabaseHandler; use crate::QueueMessageHandle; use crate::ReadRange; use crate::SnapshotReadOptions; use crate::sqlite::SqliteDbHandler; pub struct MultiBackendDbHandler { backends: Vec<(&'static [&'static str], Box<dyn DynamicDbHandler>)>, } impl MultiBackendDbHandler { pub fn new( backends: Vec<(&'static [&'static str], Box<dyn DynamicDbHandler>)>, ) -> Self { Self { backends } } pub fn remote_or_sqlite( default_storage_dir: Option<std::path::PathBuf>, versionstamp_rng_seed: Option<u64>, http_options: crate::remote::HttpOptions, ) -> Self { Self::new(vec![ ( &["https://", "http://"], Box::new(crate::remote::RemoteDbHandler::new(http_options)), ), ( &[""], Box::new(SqliteDbHandler::new( default_storage_dir, versionstamp_rng_seed, )), ), ]) } } #[async_trait(?Send)] impl DatabaseHandler for MultiBackendDbHandler { type DB = RcDynamicDb; async fn open( &self, state: Rc<RefCell<OpState>>, mut path: Option<String>, ) -> Result<Self::DB, JsErrorBox> { if path.is_none() && let Ok(x) = std::env::var("DENO_KV_DEFAULT_PATH") && !x.is_empty() { path = Some(x); } if let Some(path) = &mut path && let Ok(prefix) = std::env::var("DENO_KV_PATH_PREFIX") { *path = format!("{}{}", prefix, path); } for (prefixes, handler) in &self.backends { for &prefix in *prefixes { if prefix.is_empty() { return handler.dyn_open(state.clone(), path.clone()).await; } let Some(path) = &path else { continue; }; if path.starts_with(prefix) { return handler.dyn_open(state.clone(), Some(path.clone())).await; } } } Err(JsErrorBox::type_error(format!( "No backend supports the given path: {:?}", path ))) } } #[async_trait(?Send)] pub trait DynamicDbHandler { async fn dyn_open( &self, state: Rc<RefCell<OpState>>, path: Option<String>, ) -> Result<RcDynamicDb, JsErrorBox>; } #[async_trait(?Send)] impl DatabaseHandler for Box<dyn DynamicDbHandler> { type DB = RcDynamicDb; async fn open( &self, state: Rc<RefCell<OpState>>, path: Option<String>, ) -> Result<Self::DB, JsErrorBox> { (**self).dyn_open(state, path).await } } #[async_trait(?Send)] impl<T, DB> DynamicDbHandler for T where T: DatabaseHandler<DB = DB>, DB: Database + 'static, { async fn dyn_open( &self, state: Rc<RefCell<OpState>>, path: Option<String>, ) -> Result<RcDynamicDb, JsErrorBox> { Ok(RcDynamicDb(Rc::new(self.open(state, path).await?))) } } #[async_trait(?Send)] pub trait DynamicDb { async fn dyn_snapshot_read( &self, requests: Vec<ReadRange>, options: SnapshotReadOptions, ) -> Result<Vec<ReadRangeOutput>, JsErrorBox>; async fn dyn_atomic_write( &self, write: AtomicWrite, ) -> Result<Option<CommitResult>, JsErrorBox>; async fn dyn_dequeue_next_message( &self, ) -> Result<Option<Box<dyn QueueMessageHandle>>, JsErrorBox>; fn dyn_watch(&self, keys: Vec<Vec<u8>>) -> WatchStream; fn dyn_close(&self); } #[derive(Clone)] pub struct RcDynamicDb(Rc<dyn DynamicDb>); #[async_trait(?Send)] impl Database for RcDynamicDb { type QMH = Box<dyn QueueMessageHandle>; async fn snapshot_read( &self, requests: Vec<ReadRange>, options: SnapshotReadOptions, ) -> Result<Vec<ReadRangeOutput>, JsErrorBox> { (*self.0).dyn_snapshot_read(requests, options).await } async fn atomic_write( &self, write: AtomicWrite, ) -> Result<Option<CommitResult>, JsErrorBox> { (*self.0).dyn_atomic_write(write).await } async fn dequeue_next_message( &self, ) -> Result<Option<Box<dyn QueueMessageHandle>>, JsErrorBox> { (*self.0).dyn_dequeue_next_message().await } fn watch(&self, keys: Vec<Vec<u8>>) -> WatchStream { (*self.0).dyn_watch(keys) } fn close(&self) { (*self.0).dyn_close() } } #[async_trait(?Send)] impl<T, QMH> DynamicDb for T where T: Database<QMH = QMH>, QMH: QueueMessageHandle + 'static, { async fn dyn_snapshot_read( &self, requests: Vec<ReadRange>, options: SnapshotReadOptions, ) -> Result<Vec<ReadRangeOutput>, JsErrorBox> { Ok(self.snapshot_read(requests, options).await?) } async fn dyn_atomic_write( &self, write: AtomicWrite, ) -> Result<Option<CommitResult>, JsErrorBox> { Ok(self.atomic_write(write).await?) } async fn dyn_dequeue_next_message( &self, ) -> Result<Option<Box<dyn QueueMessageHandle>>, JsErrorBox> { Ok( self .dequeue_next_message() .await? .map(|x| Box::new(x) as Box<dyn QueueMessageHandle>), ) } fn dyn_watch(&self, keys: Vec<Vec<u8>>) -> WatchStream { self.watch(keys) } fn dyn_close(&self) { self.close() } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/kv/lib.rs
ext/kv/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. pub mod config; pub mod dynamic; mod interface; pub mod remote; pub mod sqlite; use std::borrow::Cow; use std::cell::RefCell; use std::num::NonZeroU32; use std::rc::Rc; use std::sync::Arc; use std::time::Duration; use base64::Engine; use base64::prelude::BASE64_URL_SAFE; use boxed_error::Boxed; use chrono::DateTime; use chrono::Utc; use deno_core::AsyncRefCell; use deno_core::ByteString; use deno_core::CancelFuture; use deno_core::CancelHandle; use deno_core::JsBuffer; use deno_core::OpState; use deno_core::RcRef; use deno_core::Resource; use deno_core::ResourceId; use deno_core::ToJsBuffer; use deno_core::futures::StreamExt; use deno_core::op2; use deno_core::serde_v8::AnyValue; use deno_core::serde_v8::BigInt; use deno_error::JsErrorBox; use deno_error::JsErrorClass; use deno_features::FeatureChecker; use denokv_proto::AtomicWrite; use denokv_proto::Check; use denokv_proto::Consistency; use denokv_proto::Database; use denokv_proto::Enqueue; use denokv_proto::Key; use denokv_proto::KeyPart; use denokv_proto::KvEntry; use denokv_proto::KvValue; use denokv_proto::Mutation; use denokv_proto::MutationKind; use denokv_proto::QueueMessageHandle; use denokv_proto::ReadRange; use denokv_proto::SnapshotReadOptions; use denokv_proto::WatchKeyOutput; use denokv_proto::WatchStream; use denokv_proto::decode_key; use denokv_proto::encode_key; use log::debug; use serde::Deserialize; use serde::Serialize; pub use crate::config::*; pub use crate::interface::*; pub const UNSTABLE_FEATURE_NAME: &str = "kv"; deno_core::extension!(deno_kv, deps = [ deno_web ], parameters = [ DBH: DatabaseHandler ], ops = [ op_kv_database_open<DBH>, op_kv_snapshot_read<DBH>, op_kv_atomic_write<DBH>, op_kv_encode_cursor, op_kv_dequeue_next_message<DBH>, op_kv_finish_dequeued_message<DBH>, op_kv_watch<DBH>, op_kv_watch_next, ], esm = [ "01_db.ts" ], options = { handler: DBH, config: KvConfig, }, state = |state, options| { state.put(Rc::new(options.config)); state.put(Rc::new(options.handler)); } ); struct DatabaseResource<DB: Database + 'static> { db: DB, cancel_handle: Rc<CancelHandle>, } impl<DB: Database + 'static> Resource for DatabaseResource<DB> { fn name(&self) -> Cow<'_, str> { "database".into() } fn close(self: Rc<Self>) { self.db.close(); self.cancel_handle.cancel(); } } struct DatabaseWatcherResource { stream: AsyncRefCell<WatchStream>, db_cancel_handle: Rc<CancelHandle>, cancel_handle: Rc<CancelHandle>, } impl Resource for DatabaseWatcherResource { fn name(&self) -> Cow<'_, str> { "databaseWatcher".into() } fn close(self: Rc<Self>) { self.cancel_handle.cancel() } } #[derive(Debug, Boxed, deno_error::JsError)] pub struct KvError(pub Box<KvErrorKind>); #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum KvErrorKind { #[class(inherit)] #[error(transparent)] DatabaseHandler(JsErrorBox), #[class(inherit)] #[error(transparent)] Resource(#[from] deno_core::error::ResourceError), #[class(type)] #[error("Too many ranges (max {0})")] TooManyRanges(usize), #[class(type)] #[error("Too many entries (max {0})")] TooManyEntries(usize), #[class(type)] #[error("Too many checks (max {0})")] TooManyChecks(usize), #[class(type)] #[error("Too many mutations (max {0})")] TooManyMutations(usize), #[class(type)] #[error("Too many keys (max {0})")] TooManyKeys(usize), #[class(type)] #[error("limit must be greater than 0")] InvalidLimit, #[class(type)] #[error("Invalid boundary key")] InvalidBoundaryKey, #[class(type)] #[error("Key too large for read (max {0} bytes)")] KeyTooLargeToRead(usize), #[class(type)] #[error("Key too large for write (max {0} bytes)")] KeyTooLargeToWrite(usize), #[class(type)] #[error("Total mutation size too large (max {0} bytes)")] TotalMutationTooLarge(usize), #[class(type)] #[error("Total key size too large (max {0} bytes)")] TotalKeyTooLarge(usize), #[class(inherit)] #[error(transparent)] Kv(JsErrorBox), #[class(inherit)] #[error(transparent)] Io(#[from] std::io::Error), #[class(type)] #[error("Queue message not found")] QueueMessageNotFound, #[class(type)] #[error("Start key is not in the keyspace defined by prefix")] StartKeyNotInKeyspace, #[class(type)] #[error("End key is not in the keyspace defined by prefix")] EndKeyNotInKeyspace, #[class(type)] #[error("Start key is greater than end key")] StartKeyGreaterThanEndKey, #[class(inherit)] #[error("Invalid check")] InvalidCheck(#[source] KvCheckError), #[class(inherit)] #[error("Invalid mutation")] InvalidMutation(#[source] KvMutationError), #[class(inherit)] #[error("Invalid enqueue")] InvalidEnqueue(#[source] std::io::Error), #[class(type)] #[error("key cannot be empty")] EmptyKey, #[class(type)] #[error("Value too large (max {0} bytes)")] ValueTooLarge(usize), #[class(type)] #[error("enqueue payload too large (max {0} bytes)")] EnqueuePayloadTooLarge(usize), #[class(type)] #[error("invalid cursor")] InvalidCursor, #[class(type)] #[error("cursor out of bounds")] CursorOutOfBounds, #[class(type)] #[error("Invalid range")] InvalidRange, } #[op2(async, stack_trace)] #[smi] async fn op_kv_database_open<DBH>( state: Rc<RefCell<OpState>>, #[string] path: Option<String>, ) -> Result<ResourceId, KvError> where DBH: DatabaseHandler + 'static, { let handler = { let state = state.borrow(); state .borrow::<Arc<FeatureChecker>>() .check_or_exit(UNSTABLE_FEATURE_NAME, "Deno.openKv"); state.borrow::<Rc<DBH>>().clone() }; let db = handler .open(state.clone(), path) .await .map_err(KvErrorKind::DatabaseHandler)?; let rid = state.borrow_mut().resource_table.add(DatabaseResource { db, cancel_handle: CancelHandle::new_rc(), }); Ok(rid) } type KvKey = Vec<AnyValue>; fn key_part_from_v8(value: AnyValue) -> KeyPart { match value { AnyValue::Bool(false) => KeyPart::False, AnyValue::Bool(true) => KeyPart::True, AnyValue::Number(n) => KeyPart::Float(n), AnyValue::BigInt(n) => KeyPart::Int(n), AnyValue::String(s) => KeyPart::String(s), AnyValue::V8Buffer(buf) => KeyPart::Bytes(buf.to_vec()), AnyValue::RustBuffer(_) => unreachable!(), } } fn key_part_to_v8(value: KeyPart) -> AnyValue { match value { KeyPart::False => AnyValue::Bool(false), KeyPart::True => AnyValue::Bool(true), KeyPart::Float(n) => AnyValue::Number(n), KeyPart::Int(n) => AnyValue::BigInt(n), KeyPart::String(s) => AnyValue::String(s), KeyPart::Bytes(buf) => AnyValue::RustBuffer(buf.into()), } } #[derive(Debug, Deserialize)] #[serde(tag = "kind", content = "value", rename_all = "snake_case")] enum FromV8Value { V8(JsBuffer), Bytes(JsBuffer), U64(BigInt), } #[derive(Debug, Serialize)] #[serde(tag = "kind", content = "value", rename_all = "snake_case")] enum ToV8Value { V8(ToJsBuffer), Bytes(ToJsBuffer), U64(BigInt), } impl TryFrom<FromV8Value> for KvValue { type Error = num_bigint::TryFromBigIntError<num_bigint::BigInt>; fn try_from(value: FromV8Value) -> Result<Self, Self::Error> { Ok(match value { FromV8Value::V8(buf) => KvValue::V8(buf.to_vec()), FromV8Value::Bytes(buf) => KvValue::Bytes(buf.to_vec()), FromV8Value::U64(n) => { KvValue::U64(num_bigint::BigInt::from(n).try_into()?) } }) } } impl From<KvValue> for ToV8Value { fn from(value: KvValue) -> Self { match value { KvValue::V8(buf) => ToV8Value::V8(buf.into()), KvValue::Bytes(buf) => ToV8Value::Bytes(buf.into()), KvValue::U64(n) => ToV8Value::U64(num_bigint::BigInt::from(n).into()), } } } #[derive(Serialize)] struct ToV8KvEntry { key: KvKey, value: ToV8Value, versionstamp: ByteString, } impl TryFrom<KvEntry> for ToV8KvEntry { type Error = std::io::Error; fn try_from(entry: KvEntry) -> Result<Self, Self::Error> { Ok(ToV8KvEntry { key: decode_key(&entry.key)? .0 .into_iter() .map(key_part_to_v8) .collect(), value: entry.value.into(), versionstamp: faster_hex::hex_string(&entry.versionstamp).into(), }) } } #[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] enum V8Consistency { Strong, Eventual, } impl From<V8Consistency> for Consistency { fn from(value: V8Consistency) -> Self { match value { V8Consistency::Strong => Consistency::Strong, V8Consistency::Eventual => Consistency::Eventual, } } } // (prefix, start, end, limit, reverse, cursor) type SnapshotReadRange = ( Option<KvKey>, Option<KvKey>, Option<KvKey>, u32, bool, Option<ByteString>, ); #[op2(async)] #[serde] async fn op_kv_snapshot_read<DBH>( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, #[serde] ranges: Vec<SnapshotReadRange>, #[serde] consistency: V8Consistency, ) -> Result<Vec<Vec<ToV8KvEntry>>, KvError> where DBH: DatabaseHandler + 'static, { let db = { let state = state.borrow(); let resource = state .resource_table .get::<DatabaseResource<DBH::DB>>(rid) .map_err(KvErrorKind::Resource)?; resource.db.clone() }; let config = { let state = state.borrow(); state.borrow::<Rc<KvConfig>>().clone() }; if ranges.len() > config.max_read_ranges { return Err(KvErrorKind::TooManyRanges(config.max_read_ranges).into_box()); } let mut total_entries = 0usize; let read_ranges = ranges .into_iter() .map(|(prefix, start, end, limit, reverse, cursor)| { let selector = RawSelector::from_tuple(prefix, start, end)?; let (start, end) = decode_selector_and_cursor(&selector, reverse, cursor.as_ref())?; check_read_key_size(&start, &config)?; check_read_key_size(&end, &config)?; total_entries += limit as usize; Ok(ReadRange { start, end, limit: NonZeroU32::new(limit).ok_or(KvErrorKind::InvalidLimit)?, reverse, }) }) .collect::<Result<Vec<_>, KvError>>()?; if total_entries > config.max_read_entries { return Err( KvErrorKind::TooManyEntries(config.max_read_entries).into_box(), ); } let opts = SnapshotReadOptions { consistency: consistency.into(), }; let output_ranges = db .snapshot_read(read_ranges, opts) .await .map_err(KvErrorKind::Kv)?; let output_ranges = output_ranges .into_iter() .map(|x| { x.entries .into_iter() .map(TryInto::try_into) .collect::<Result<Vec<_>, std::io::Error>>() }) .collect::<Result<Vec<_>, std::io::Error>>()?; Ok(output_ranges) } struct QueueMessageResource<QPH: QueueMessageHandle + 'static> { handle: QPH, } impl<QMH: QueueMessageHandle + 'static> Resource for QueueMessageResource<QMH> { fn name(&self) -> Cow<'_, str> { "queueMessage".into() } } #[op2(async)] #[serde] async fn op_kv_dequeue_next_message<DBH>( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<Option<(ToJsBuffer, ResourceId)>, KvError> where DBH: DatabaseHandler + 'static, { let db = { let state = state.borrow(); let resource = match state.resource_table.get::<DatabaseResource<DBH::DB>>(rid) { Ok(resource) => resource, Err(err) => { if err.get_class() == "BadResource" { return Ok(None); } else { return Err(KvErrorKind::Resource(err).into_box()); } } }; resource.db.clone() }; let Some(mut handle) = db.dequeue_next_message().await.map_err(KvErrorKind::Kv)? else { return Ok(None); }; let payload = handle.take_payload().await.map_err(KvErrorKind::Kv)?.into(); let handle_rid = { let mut state = state.borrow_mut(); state.resource_table.add(QueueMessageResource { handle }) }; Ok(Some((payload, handle_rid))) } #[op2] #[smi] fn op_kv_watch<DBH>( state: &mut OpState, #[smi] rid: ResourceId, #[serde] keys: Vec<KvKey>, ) -> Result<ResourceId, KvError> where DBH: DatabaseHandler + 'static, { let resource = state .resource_table .get::<DatabaseResource<DBH::DB>>(rid) .map_err(KvErrorKind::Resource)?; let config = state.borrow::<Rc<KvConfig>>().clone(); if keys.len() > config.max_watched_keys { return Err(KvErrorKind::TooManyKeys(config.max_watched_keys).into_box()); } let keys: Vec<Vec<u8>> = keys .into_iter() .map(encode_v8_key) .collect::<std::io::Result<_>>()?; for k in &keys { check_read_key_size(k, &config)?; } let stream = resource.db.watch(keys); let rid = state.resource_table.add(DatabaseWatcherResource { stream: AsyncRefCell::new(stream), db_cancel_handle: resource.cancel_handle.clone(), cancel_handle: CancelHandle::new_rc(), }); Ok(rid) } #[derive(Serialize)] #[serde(rename_all = "camelCase", untagged)] enum WatchEntry { Changed(Option<ToV8KvEntry>), Unchanged, } #[op2(async)] #[serde] async fn op_kv_watch_next( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<Option<Vec<WatchEntry>>, KvError> { let resource = { let state = state.borrow(); let resource = state .resource_table .get::<DatabaseWatcherResource>(rid) .map_err(KvErrorKind::Resource)?; resource.clone() }; let db_cancel_handle = resource.db_cancel_handle.clone(); let cancel_handle = resource.cancel_handle.clone(); let stream = RcRef::map(resource, |r| &r.stream) .borrow_mut() .or_cancel(db_cancel_handle.clone()) .or_cancel(cancel_handle.clone()) .await; let Ok(Ok(mut stream)) = stream else { return Ok(None); }; // We hold a strong reference to `resource`, so we can't rely on the stream // being dropped when the db connection is closed let Ok(Ok(Some(res))) = stream .next() .or_cancel(db_cancel_handle) .or_cancel(cancel_handle) .await else { return Ok(None); }; let entries = res.map_err(KvErrorKind::Kv)?; let entries = entries .into_iter() .map(|entry| { Ok(match entry { WatchKeyOutput::Changed { entry } => { WatchEntry::Changed(entry.map(TryInto::try_into).transpose()?) } WatchKeyOutput::Unchanged => WatchEntry::Unchanged, }) }) .collect::<Result<_, KvError>>()?; Ok(Some(entries)) } #[op2(async)] async fn op_kv_finish_dequeued_message<DBH>( state: Rc<RefCell<OpState>>, #[smi] handle_rid: ResourceId, success: bool, ) -> Result<(), KvError> where DBH: DatabaseHandler + 'static, { let handle = { let mut state = state.borrow_mut(); let handle = state .resource_table .take::<QueueMessageResource<<<DBH>::DB as Database>::QMH>>(handle_rid) .map_err(|_| KvErrorKind::QueueMessageNotFound)?; Rc::try_unwrap(handle) .map_err(|_| KvErrorKind::QueueMessageNotFound)? .handle }; // if we fail to finish the message, there is not much we can do and the // message will be retried anyway, so we just ignore the error if let Err(err) = handle.finish(success).await { debug!("Failed to finish dequeued message: {}", err); }; Ok(()) } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum KvCheckError { #[class(type)] #[error("invalid versionstamp")] InvalidVersionstamp, #[class(inherit)] #[error(transparent)] Io(std::io::Error), } type V8KvCheck = (KvKey, Option<ByteString>); fn check_from_v8(value: V8KvCheck) -> Result<Check, KvCheckError> { let versionstamp = match value.1 { Some(data) => { let mut out = [0u8; 10]; if data.len() != out.len() * 2 { return Err(KvCheckError::InvalidVersionstamp); } faster_hex::hex_decode(&data, &mut out) .map_err(|_| KvCheckError::InvalidVersionstamp)?; Some(out) } None => None, }; Ok(Check { key: encode_v8_key(value.0).map_err(KvCheckError::Io)?, versionstamp, }) } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum KvMutationError { #[class(generic)] #[error(transparent)] BigInt(#[from] num_bigint::TryFromBigIntError<num_bigint::BigInt>), #[class(inherit)] #[error(transparent)] Io( #[from] #[inherit] std::io::Error, ), #[class(type)] #[error("Invalid mutation '{0}' with value")] InvalidMutationWithValue(String), #[class(type)] #[error("Invalid mutation '{0}' without value")] InvalidMutationWithoutValue(String), } type V8KvMutation = (KvKey, String, Option<FromV8Value>, Option<u64>); fn mutation_from_v8( (value, current_timstamp): (V8KvMutation, DateTime<Utc>), ) -> Result<Mutation, KvMutationError> { let key = encode_v8_key(value.0)?; let kind = match (value.1.as_str(), value.2) { ("set", Some(value)) => MutationKind::Set(value.try_into()?), ("delete", None) => MutationKind::Delete, ("sum", Some(value)) => MutationKind::Sum { value: value.try_into()?, min_v8: vec![], max_v8: vec![], clamp: false, }, ("min", Some(value)) => MutationKind::Min(value.try_into()?), ("max", Some(value)) => MutationKind::Max(value.try_into()?), ("setSuffixVersionstampedKey", Some(value)) => { MutationKind::SetSuffixVersionstampedKey(value.try_into()?) } (op, Some(_)) => { return Err(KvMutationError::InvalidMutationWithValue(op.to_string())); } (op, None) => { return Err(KvMutationError::InvalidMutationWithoutValue(op.to_string())); } }; Ok(Mutation { key, kind, expire_at: value .3 .map(|expire_in| current_timstamp + Duration::from_millis(expire_in)), }) } type V8Enqueue = (JsBuffer, u64, Vec<KvKey>, Option<Vec<u32>>); fn enqueue_from_v8( value: V8Enqueue, current_timestamp: DateTime<Utc>, ) -> Result<Enqueue, std::io::Error> { Ok(Enqueue { payload: value.0.to_vec(), deadline: current_timestamp + chrono::Duration::milliseconds(value.1 as i64), keys_if_undelivered: value .2 .into_iter() .map(encode_v8_key) .collect::<std::io::Result<_>>()?, backoff_schedule: value.3, }) } fn encode_v8_key(key: KvKey) -> Result<Vec<u8>, std::io::Error> { encode_key(&Key(key.into_iter().map(key_part_from_v8).collect())) } enum RawSelector { Prefixed { prefix: Vec<u8>, start: Option<Vec<u8>>, end: Option<Vec<u8>>, }, Range { start: Vec<u8>, end: Vec<u8>, }, } impl RawSelector { fn from_tuple( prefix: Option<KvKey>, start: Option<KvKey>, end: Option<KvKey>, ) -> Result<Self, KvError> { let prefix = prefix.map(encode_v8_key).transpose()?; let start = start.map(encode_v8_key).transpose()?; let end = end.map(encode_v8_key).transpose()?; match (prefix, start, end) { (Some(prefix), None, None) => Ok(Self::Prefixed { prefix, start: None, end: None, }), (Some(prefix), Some(start), None) => { if !start.starts_with(&prefix) || start.len() == prefix.len() { return Err(KvErrorKind::StartKeyNotInKeyspace.into_box()); } Ok(Self::Prefixed { prefix, start: Some(start), end: None, }) } (Some(prefix), None, Some(end)) => { if !end.starts_with(&prefix) || end.len() == prefix.len() { return Err(KvErrorKind::EndKeyNotInKeyspace.into_box()); } Ok(Self::Prefixed { prefix, start: None, end: Some(end), }) } (None, Some(start), Some(end)) => { if start > end { return Err(KvErrorKind::StartKeyGreaterThanEndKey.into_box()); } Ok(Self::Range { start, end }) } (None, Some(start), None) => { let end = start.iter().copied().chain(Some(0)).collect(); Ok(Self::Range { start, end }) } _ => Err(KvErrorKind::InvalidRange.into_box()), } } fn start(&self) -> Option<&[u8]> { match self { Self::Prefixed { start, .. } => start.as_deref(), Self::Range { start, .. } => Some(start), } } fn end(&self) -> Option<&[u8]> { match self { Self::Prefixed { end, .. } => end.as_deref(), Self::Range { end, .. } => Some(end), } } fn common_prefix(&self) -> &[u8] { match self { Self::Prefixed { prefix, .. } => prefix, Self::Range { start, end } => common_prefix_for_bytes(start, end), } } fn range_start_key(&self) -> Vec<u8> { match self { Self::Prefixed { start: Some(start), .. } => start.clone(), Self::Range { start, .. } => start.clone(), Self::Prefixed { prefix, .. } => { prefix.iter().copied().chain(Some(0)).collect() } } } fn range_end_key(&self) -> Vec<u8> { match self { Self::Prefixed { end: Some(end), .. } => end.clone(), Self::Range { end, .. } => end.clone(), Self::Prefixed { prefix, .. } => { prefix.iter().copied().chain(Some(0xff)).collect() } } } } fn common_prefix_for_bytes<'a>(a: &'a [u8], b: &'a [u8]) -> &'a [u8] { let mut i = 0; while i < a.len() && i < b.len() && a[i] == b[i] { i += 1; } &a[..i] } fn encode_cursor( selector: &RawSelector, boundary_key: &[u8], ) -> Result<String, KvError> { let common_prefix = selector.common_prefix(); if !boundary_key.starts_with(common_prefix) { return Err(KvErrorKind::InvalidBoundaryKey.into_box()); } Ok(BASE64_URL_SAFE.encode(&boundary_key[common_prefix.len()..])) } fn decode_selector_and_cursor( selector: &RawSelector, reverse: bool, cursor: Option<&ByteString>, ) -> Result<(Vec<u8>, Vec<u8>), KvError> { let Some(cursor) = cursor else { return Ok((selector.range_start_key(), selector.range_end_key())); }; let common_prefix = selector.common_prefix(); let cursor = BASE64_URL_SAFE .decode(cursor) .map_err(|_| KvErrorKind::InvalidCursor)?; let first_key: Vec<u8>; let last_key: Vec<u8>; if reverse { first_key = selector.range_start_key(); last_key = common_prefix .iter() .copied() .chain(cursor.iter().copied()) .collect(); } else { first_key = common_prefix .iter() .copied() .chain(cursor.iter().copied()) .chain(Some(0)) .collect(); last_key = selector.range_end_key(); } // Defend against out-of-bounds reading if let Some(start) = selector.start() && &first_key[..] < start { return Err(KvErrorKind::CursorOutOfBounds.into_box()); } if let Some(end) = selector.end() && &last_key[..] > end { return Err(KvErrorKind::CursorOutOfBounds.into_box()); } Ok((first_key, last_key)) } #[op2(async)] #[string] async fn op_kv_atomic_write<DBH>( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, #[serde] checks: Vec<V8KvCheck>, #[serde] mutations: Vec<V8KvMutation>, #[serde] enqueues: Vec<V8Enqueue>, ) -> Result<Option<String>, KvError> where DBH: DatabaseHandler + 'static, { let current_timestamp = chrono::Utc::now(); let db = { let state = state.borrow(); let resource = state .resource_table .get::<DatabaseResource<DBH::DB>>(rid) .map_err(KvErrorKind::Resource)?; resource.db.clone() }; let config = { let state = state.borrow(); state.borrow::<Rc<KvConfig>>().clone() }; if checks.len() > config.max_checks { return Err(KvErrorKind::TooManyChecks(config.max_checks).into_box()); } if mutations.len() + enqueues.len() > config.max_mutations { return Err(KvErrorKind::TooManyMutations(config.max_mutations).into_box()); } let checks = checks .into_iter() .map(check_from_v8) .collect::<Result<Vec<Check>, KvCheckError>>() .map_err(KvErrorKind::InvalidCheck)?; let mutations = mutations .into_iter() .map(|mutation| mutation_from_v8((mutation, current_timestamp))) .collect::<Result<Vec<Mutation>, KvMutationError>>() .map_err(KvErrorKind::InvalidMutation)?; let enqueues = enqueues .into_iter() .map(|e| enqueue_from_v8(e, current_timestamp)) .collect::<Result<Vec<Enqueue>, std::io::Error>>() .map_err(KvErrorKind::InvalidEnqueue)?; let mut total_payload_size = 0usize; let mut total_key_size = 0usize; for key in checks .iter() .map(|c| &c.key) .chain(mutations.iter().map(|m| &m.key)) { if key.is_empty() { return Err(KvErrorKind::EmptyKey.into_box()); } total_payload_size += check_write_key_size(key, &config)?; } for (key, value) in mutations .iter() .flat_map(|m| m.kind.value().map(|x| (&m.key, x))) { let key_size = check_write_key_size(key, &config)?; total_payload_size += check_value_size(value, &config)? + key_size; total_key_size += key_size; } for enqueue in &enqueues { total_payload_size += check_enqueue_payload_size(&enqueue.payload, &config)?; if let Some(schedule) = enqueue.backoff_schedule.as_ref() { total_payload_size += 4 * schedule.len(); } } if total_payload_size > config.max_total_mutation_size_bytes { return Err( KvErrorKind::TotalMutationTooLarge(config.max_total_mutation_size_bytes) .into_box(), ); } if total_key_size > config.max_total_key_size_bytes { return Err( KvErrorKind::TotalKeyTooLarge(config.max_total_key_size_bytes).into_box(), ); } let atomic_write = AtomicWrite { checks, mutations, enqueues, }; let result = db .atomic_write(atomic_write) .await .map_err(KvErrorKind::Kv)?; Ok(result.map(|res| faster_hex::hex_string(&res.versionstamp))) } // (prefix, start, end) type EncodeCursorRangeSelector = (Option<KvKey>, Option<KvKey>, Option<KvKey>); #[op2] #[string] fn op_kv_encode_cursor( #[serde] (prefix, start, end): EncodeCursorRangeSelector, #[serde] boundary_key: KvKey, ) -> Result<String, KvError> { let selector = RawSelector::from_tuple(prefix, start, end)?; let boundary_key = encode_v8_key(boundary_key)?; let cursor = encode_cursor(&selector, &boundary_key)?; Ok(cursor) } fn check_read_key_size(key: &[u8], config: &KvConfig) -> Result<(), KvError> { if key.len() > config.max_read_key_size_bytes { Err( KvErrorKind::KeyTooLargeToRead(config.max_read_key_size_bytes).into_box(), ) } else { Ok(()) } } fn check_write_key_size( key: &[u8], config: &KvConfig, ) -> Result<usize, KvError> { if key.len() > config.max_write_key_size_bytes { Err( KvErrorKind::KeyTooLargeToWrite(config.max_write_key_size_bytes) .into_box(), ) } else { Ok(key.len()) } } fn check_value_size( value: &KvValue, config: &KvConfig, ) -> Result<usize, KvError> { let payload = match value { KvValue::Bytes(x) => x, KvValue::V8(x) => x, KvValue::U64(_) => return Ok(8), }; if payload.len() > config.max_value_size_bytes { Err(KvErrorKind::ValueTooLarge(config.max_value_size_bytes).into_box()) } else { Ok(payload.len()) } } fn check_enqueue_payload_size( payload: &[u8], config: &KvConfig, ) -> Result<usize, KvError> { if payload.len() > config.max_value_size_bytes { Err( KvErrorKind::EnqueuePayloadTooLarge(config.max_value_size_bytes) .into_box(), ) } else { Ok(payload.len()) } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/kv/interface.rs
ext/kv/interface.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::RefCell; use std::rc::Rc; use async_trait::async_trait; use deno_core::OpState; use deno_error::JsErrorBox; use denokv_proto::Database; #[async_trait(?Send)] pub trait DatabaseHandler { type DB: Database + 'static; async fn open( &self, state: Rc<RefCell<OpState>>, path: Option<String>, ) -> Result<Self::DB, JsErrorBox>; }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/kv/remote.rs
ext/kv/remote.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::RefCell; use std::rc::Rc; use std::sync::Arc; use anyhow::Context; use async_trait::async_trait; use bytes::Bytes; use deno_core::OpState; use deno_core::futures::Stream; use deno_error::JsErrorBox; use deno_fetch::CreateHttpClientOptions; use deno_fetch::create_http_client; use deno_permissions::PermissionsContainer; use deno_tls::Proxy; use deno_tls::RootCertStoreProvider; use deno_tls::TlsKeys; use deno_tls::rustls::RootCertStore; use denokv_remote::MetadataEndpoint; use denokv_remote::Remote; use denokv_remote::RemoteResponse; use denokv_remote::RemoteTransport; use http_body_util::BodyExt; use url::Url; use crate::DatabaseHandler; #[derive(Clone)] pub struct HttpOptions { pub user_agent: String, pub root_cert_store_provider: Option<Arc<dyn RootCertStoreProvider>>, pub proxy: Option<Proxy>, pub unsafely_ignore_certificate_errors: Option<Vec<String>>, pub client_cert_chain_and_key: TlsKeys, } impl HttpOptions { pub fn root_cert_store(&self) -> Result<Option<RootCertStore>, JsErrorBox> { Ok(match &self.root_cert_store_provider { Some(provider) => Some(provider.get_or_try_init()?.clone()), None => None, }) } } pub struct RemoteDbHandler { http_options: HttpOptions, } impl RemoteDbHandler { pub fn new(http_options: HttpOptions) -> Self { Self { http_options } } } pub struct PermissionChecker { state: Rc<RefCell<OpState>>, } impl Clone for PermissionChecker { fn clone(&self) -> Self { Self { state: self.state.clone(), } } } impl denokv_remote::RemotePermissions for PermissionChecker { fn check_net_url(&self, url: &Url) -> Result<(), JsErrorBox> { let mut state = self.state.borrow_mut(); let permissions = state.borrow_mut::<PermissionsContainer>(); permissions .check_net_url(url, "Deno.openKv") .map_err(JsErrorBox::from_err) } } #[derive(Clone)] pub struct FetchClient(deno_fetch::Client); pub struct FetchResponse(http::Response<deno_fetch::ResBody>); impl RemoteTransport for FetchClient { type Response = FetchResponse; async fn post( &self, url: Url, headers: http::HeaderMap, body: Bytes, ) -> Result<(Url, http::StatusCode, Self::Response), JsErrorBox> { let body = deno_fetch::ReqBody::full(body); let mut req = http::Request::new(body); *req.method_mut() = http::Method::POST; *req.uri_mut() = url.as_str().parse().map_err(|e: http::uri::InvalidUri| { JsErrorBox::type_error(e.to_string()) })?; *req.headers_mut() = headers; let res = self .0 .clone() .send(req) .await .map_err(JsErrorBox::from_err)?; let status = res.status(); Ok((url, status, FetchResponse(res))) } } impl RemoteResponse for FetchResponse { async fn bytes(self) -> Result<Bytes, JsErrorBox> { Ok(self.0.collect().await?.to_bytes()) } fn stream( self, ) -> impl Stream<Item = Result<Bytes, JsErrorBox>> + Send + Sync { self.0.into_body().into_data_stream() } async fn text(self) -> Result<String, JsErrorBox> { let bytes = self.bytes().await?; Ok( std::str::from_utf8(&bytes) .map_err(JsErrorBox::from_err)? .into(), ) } } #[async_trait(?Send)] impl DatabaseHandler for RemoteDbHandler { type DB = Remote<PermissionChecker, FetchClient>; async fn open( &self, state: Rc<RefCell<OpState>>, path: Option<String>, ) -> Result<Self::DB, JsErrorBox> { const ENV_VAR_NAME: &str = "DENO_KV_ACCESS_TOKEN"; let Some(url) = path else { return Err(JsErrorBox::type_error("Missing database url")); }; let Ok(parsed_url) = Url::parse(&url) else { return Err(JsErrorBox::type_error(format!( "Invalid database url: {}", url ))); }; { let mut state = state.borrow_mut(); let permissions = state.borrow_mut::<PermissionsContainer>(); permissions .check_env(ENV_VAR_NAME) .map_err(JsErrorBox::from_err)?; permissions .check_net_url(&parsed_url, "Deno.openKv") .map_err(JsErrorBox::from_err)?; } let access_token = std::env::var(ENV_VAR_NAME) .map_err(anyhow::Error::from) .with_context(|| { "Missing DENO_KV_ACCESS_TOKEN environment variable. Please set it to your access token from https://dash.deno.com/account." }).map_err(|e| JsErrorBox::generic(e.to_string()))?; let metadata_endpoint = MetadataEndpoint { url: parsed_url.clone(), access_token: access_token.clone(), }; let options = &self.http_options; let client = create_http_client( &options.user_agent, CreateHttpClientOptions { root_cert_store: options.root_cert_store()?, ca_certs: vec![], proxy: options.proxy.clone(), dns_resolver: Default::default(), unsafely_ignore_certificate_errors: options .unsafely_ignore_certificate_errors .clone(), client_cert_chain_and_key: options .client_cert_chain_and_key .clone() .try_into() .unwrap(), pool_max_idle_per_host: None, pool_idle_timeout: None, http1: false, http2: true, local_address: None, client_builder_hook: None, }, ) .map_err(JsErrorBox::from_err)?; let fetch_client = FetchClient(client); let permissions = PermissionChecker { state: state.clone(), }; let remote = Remote::new(fetch_client, permissions, metadata_endpoint); Ok(remote) } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/kv/sqlite.rs
ext/kv/sqlite.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::collections::HashMap; use std::path::PathBuf; use std::rc::Rc; use std::sync::Arc; use std::sync::Mutex; use std::sync::OnceLock; use async_trait::async_trait; use deno_core::OpState; use deno_core::unsync::spawn_blocking; use deno_error::JsErrorBox; use deno_permissions::OpenAccessKind; use deno_permissions::PermissionsContainer; pub use denokv_sqlite::SqliteBackendError; use denokv_sqlite::SqliteConfig; use denokv_sqlite::SqliteNotifier; use rand::SeedableRng; use rusqlite::OpenFlags; use crate::DatabaseHandler; static SQLITE_NOTIFIERS_MAP: OnceLock<Mutex<HashMap<PathBuf, SqliteNotifier>>> = OnceLock::new(); pub struct SqliteDbHandler { pub default_storage_dir: Option<PathBuf>, versionstamp_rng_seed: Option<u64>, } impl SqliteDbHandler { pub fn new( default_storage_dir: Option<PathBuf>, versionstamp_rng_seed: Option<u64>, ) -> Self { Self { default_storage_dir, versionstamp_rng_seed, } } } deno_error::js_error_wrapper!( SqliteBackendError, JsSqliteBackendError, "TypeError" ); #[derive(Debug)] enum Mode { Disk, InMemory, } #[async_trait(?Send)] impl DatabaseHandler for SqliteDbHandler { type DB = denokv_sqlite::Sqlite; async fn open( &self, state: Rc<RefCell<OpState>>, path: Option<String>, ) -> Result<Self::DB, JsErrorBox> { enum PathOrInMemory { InMemory, Path(PathBuf), } #[must_use = "the resolved return value to mitigate time-of-check to time-of-use issues"] fn validate_path( state: &RefCell<OpState>, path: Option<String>, ) -> Result<Option<PathOrInMemory>, JsErrorBox> { let Some(path) = path else { return Ok(None); }; if path == ":memory:" { return Ok(Some(PathOrInMemory::InMemory)); } if path.is_empty() { return Err(JsErrorBox::type_error("Filename cannot be empty")); } if path.starts_with(':') { return Err(JsErrorBox::type_error( "Filename cannot start with ':' unless prefixed with './'", )); } { let state = state.borrow(); let permissions = state.borrow::<PermissionsContainer>(); let path = permissions .check_open( Cow::Owned(PathBuf::from(path)), OpenAccessKind::ReadWriteNoFollow, Some("Deno.openKv"), ) .map_err(JsErrorBox::from_err)?; Ok(Some(PathOrInMemory::Path(path.into_owned_path()))) } } let path = validate_path(&state, path)?; let default_storage_dir = self.default_storage_dir.clone(); type ConnGen = Arc<dyn Fn() -> rusqlite::Result<rusqlite::Connection> + Send + Sync>; let (conn_gen, notifier_key): (ConnGen, _) = spawn_blocking(move || { denokv_sqlite::sqlite_retry_loop(move || { let mode = match std::env::var("DENO_KV_DB_MODE") .unwrap_or_default() .as_str() { "disk" | "" => Mode::Disk, "memory" => Mode::InMemory, _ => { log::warn!("Unknown DENO_KV_DB_MODE value, defaulting to disk"); Mode::Disk } }; if matches!(mode, Mode::InMemory) { return Ok::<_, SqliteBackendError>(( Arc::new(rusqlite::Connection::open_in_memory) as ConnGen, None, )); } let (conn, notifier_key) = match (path.as_ref(), &default_storage_dir) { (Some(PathOrInMemory::InMemory), _) | (None, None) => ( Arc::new(rusqlite::Connection::open_in_memory) as ConnGen, None, ), (Some(PathOrInMemory::Path(path)), _) => { let flags = OpenFlags::default().difference(OpenFlags::SQLITE_OPEN_URI); let resolved_path = deno_path_util::fs::canonicalize_path_maybe_not_exists( // todo(dsherret): probably should use the FileSystem in the op state instead &sys_traits::impls::RealSys, path, ) .map_err(JsErrorBox::from_err)?; let path = path.clone(); ( Arc::new(move || { rusqlite::Connection::open_with_flags(&path, flags) }) as ConnGen, Some(resolved_path), ) } (None, Some(path)) => { std::fs::create_dir_all(path).map_err(JsErrorBox::from_err)?; let path = path.join("kv.sqlite3"); let path2 = path.clone(); ( Arc::new(move || rusqlite::Connection::open(&path2)) as ConnGen, Some(path), ) } }; Ok::<_, SqliteBackendError>((conn, notifier_key)) }) }) .await .unwrap() .map_err(JsErrorBox::from_err)?; let notifier = if let Some(notifier_key) = notifier_key { SQLITE_NOTIFIERS_MAP .get_or_init(Default::default) .lock() .unwrap() .entry(notifier_key) .or_default() .clone() } else { SqliteNotifier::default() }; let versionstamp_rng_seed = self.versionstamp_rng_seed; let config = SqliteConfig { batch_timeout: None, num_workers: 1, }; denokv_sqlite::Sqlite::new( move || { let conn = conn_gen().map_err(|e| JsErrorBox::generic(e.to_string()))?; conn .pragma_update(None, "journal_mode", "wal") .map_err(|e| JsErrorBox::generic(e.to_string()))?; Ok(( conn, match versionstamp_rng_seed { Some(seed) => Box::new(rand::rngs::StdRng::seed_from_u64(seed)), None => Box::new(rand::rngs::StdRng::from_entropy()), }, )) }, notifier, config, ) .map_err(|e| JsErrorBox::generic(e.to_string())) } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/bundle/src/lib.rs
ext/bundle/src/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::RefCell; use std::rc::Rc; use std::sync::Arc; use async_trait::async_trait; use deno_core::OpState; use deno_core::error::AnyError; use deno_core::op2; use deno_error::JsErrorBox; deno_core::extension!( deno_bundle_runtime, deps = [ deno_web ], ops = [ op_bundle, ], esm = [ "bundle.ts" ], options = { bundle_provider: Option<Arc<dyn BundleProvider>>, }, state = |state, options| { if let Some(bundle_provider) = options.bundle_provider { state.put(bundle_provider); } else { state.put::<Arc<dyn BundleProvider>>(Arc::new(())); } }, ); #[async_trait] impl BundleProvider for () { async fn bundle( &self, _options: BundleOptions, ) -> Result<BuildResponse, AnyError> { Err(deno_core::anyhow::anyhow!( "default BundleProvider does not do anything" )) } } #[async_trait] pub trait BundleProvider: Send + Sync { async fn bundle( &self, options: BundleOptions, ) -> Result<BuildResponse, AnyError>; } #[derive(Clone, Debug, Eq, PartialEq, Default, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct BundleOptions { pub entrypoints: Vec<String>, #[serde(default)] pub output_path: Option<String>, #[serde(default)] pub output_dir: Option<String>, #[serde(default)] pub external: Vec<String>, #[serde(default)] pub format: BundleFormat, #[serde(default)] pub minify: bool, #[serde(default)] pub code_splitting: bool, #[serde(default = "tru")] pub inline_imports: bool, #[serde(default)] pub packages: PackageHandling, #[serde(default)] pub sourcemap: Option<SourceMapType>, #[serde(default)] pub platform: BundlePlatform, #[serde(default = "tru")] pub write: bool, } fn tru() -> bool { true } #[derive(Clone, Debug, Eq, PartialEq, Copy, Default, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum BundlePlatform { Browser, #[default] Deno, } #[derive(Clone, Debug, Eq, PartialEq, Copy, Default, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum BundleFormat { #[default] Esm, Cjs, Iife, } #[derive(Clone, Debug, Eq, PartialEq, Copy, Default, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum SourceMapType { #[default] Linked, Inline, External, } impl std::fmt::Display for BundleFormat { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { BundleFormat::Esm => write!(f, "esm"), BundleFormat::Cjs => write!(f, "cjs"), BundleFormat::Iife => write!(f, "iife"), } } } impl std::fmt::Display for SourceMapType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { SourceMapType::Linked => write!(f, "linked"), SourceMapType::Inline => write!(f, "inline"), SourceMapType::External => write!(f, "external"), } } } #[derive(Clone, Debug, Eq, PartialEq, Copy, Default, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum PackageHandling { #[default] Bundle, External, } impl std::fmt::Display for PackageHandling { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { PackageHandling::Bundle => write!(f, "bundle"), PackageHandling::External => write!(f, "external"), } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct Message { pub text: String, pub location: Option<Location>, pub notes: Vec<Note>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct PartialMessage { pub id: Option<String>, pub plugin_name: Option<String>, pub text: Option<String>, pub location: Option<Location>, pub notes: Option<Vec<Note>>, pub detail: Option<u32>, } #[derive(Debug, Clone, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct BuildOutputFile { pub path: String, pub contents: Option<Vec<u8>>, pub hash: String, } #[derive(Debug, Clone, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct BuildResponse { pub errors: Vec<Message>, pub warnings: Vec<Message>, pub output_files: Option<Vec<BuildOutputFile>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct Note { pub text: String, pub location: Option<Location>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct Location { pub file: String, pub namespace: Option<String>, pub line: u32, pub column: u32, pub length: Option<u32>, pub suggestion: Option<String>, } fn deserialize_regex<'de, D>(deserializer: D) -> Result<regex::Regex, D::Error> where D: serde::Deserializer<'de>, { use serde::Deserialize; let s = String::deserialize(deserializer)?; regex::Regex::new(&s).map_err(serde::de::Error::custom) } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct OnResolveOptions { #[serde(deserialize_with = "deserialize_regex")] pub filter: regex::Regex, pub namespace: Option<String>, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct OnLoadOptions { #[serde(deserialize_with = "deserialize_regex")] pub filter: regex::Regex, pub namespace: Option<String>, } #[op2(async)] #[serde] pub async fn op_bundle( state: Rc<RefCell<OpState>>, #[serde] options: BundleOptions, ) -> Result<BuildResponse, JsErrorBox> { // eprintln!("op_bundle: {:?}", options); let provider = { let state = state.borrow(); state.borrow::<Arc<dyn BundleProvider>>().clone() }; provider .bundle(options) .await .map_err(|e| JsErrorBox::generic(e.to_string())) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/signals/lib.rs
ext/signals/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::collections::HashMap; use std::sync::Mutex; use std::sync::OnceLock; use std::sync::atomic::AtomicU32; use std::sync::atomic::Ordering; use signal_hook::consts::*; use tokio::sync::watch; mod dict; pub use dict::*; #[cfg(windows)] static SIGHUP: i32 = 1; static COUNTER: AtomicU32 = AtomicU32::new(0); type Handler = Box<dyn Fn() + Send>; type Handlers = HashMap<i32, Vec<(u32, bool, Handler)>>; static HANDLERS: OnceLock<(Handle, Mutex<Handlers>)> = OnceLock::new(); #[cfg(unix)] struct Handle(signal_hook::iterator::Handle); #[cfg(windows)] struct Handle; fn handle_signal(signal: i32) -> bool { let Some((_, handlers)) = HANDLERS.get() else { return false; }; let handlers = handlers.lock().unwrap(); let Some(handlers) = handlers.get(&signal) else { return false; }; let mut handled = false; for (_, prevent_default, f) in handlers { if *prevent_default { handled = true; } f(); } handled } #[cfg(unix)] fn init() -> Handle { use signal_hook::iterator::Signals; let mut signals = Signals::new([SIGHUP, SIGTERM, SIGINT]).unwrap(); let handle = signals.handle(); std::thread::spawn(move || { for signal in signals.forever() { let handled = handle_signal(signal); if !handled { if signal == SIGHUP || signal == SIGTERM || signal == SIGINT { run_exit(); } signal_hook::low_level::emulate_default_handler(signal).unwrap(); } } }); Handle(handle) } #[cfg(windows)] fn init() -> Handle { unsafe extern "system" fn handle(ctrl_type: u32) -> i32 { let signal = match ctrl_type { 0 => SIGINT, 1 => SIGBREAK, 2 => SIGHUP, 5 => SIGTERM, 6 => SIGTERM, _ => return 0, }; let handled = handle_signal(signal); handled as _ } // SAFETY: Registering handler unsafe { winapi::um::consoleapi::SetConsoleCtrlHandler(Some(handle), 1); } Handle } pub fn register( signal: i32, prevent_default: bool, f: Box<dyn Fn() + Send>, ) -> Result<u32, std::io::Error> { if is_forbidden(signal) { return Err(std::io::Error::other(format!( "Refusing to register signal {signal}" ))); } let (handle, handlers) = HANDLERS.get_or_init(|| { let handle = init(); let handlers = Mutex::new(HashMap::new()); (handle, handlers) }); let id = COUNTER.fetch_add(1, Ordering::Relaxed); let mut handlers = handlers.lock().unwrap(); match handlers.entry(signal) { std::collections::hash_map::Entry::Occupied(mut v) => { v.get_mut().push((id, prevent_default, f)) } std::collections::hash_map::Entry::Vacant(v) => { v.insert(vec![(id, prevent_default, f)]); #[cfg(unix)] { handle.0.add_signal(signal).unwrap(); } #[cfg(windows)] { let _ = handle; } } } Ok(id) } pub fn unregister(signal: i32, id: u32) { let Some((_, handlers)) = HANDLERS.get() else { return; }; let mut handlers = handlers.lock().unwrap(); let Some(handlers) = handlers.get_mut(&signal) else { return; }; let Some(index) = handlers.iter().position(|v| v.0 == id) else { return; }; let _ = handlers.swap_remove(index); } static BEFORE_EXIT: OnceLock<Mutex<Vec<Handler>>> = OnceLock::new(); pub fn before_exit(f: fn()) { BEFORE_EXIT .get_or_init(|| Mutex::new(vec![])) .lock() .unwrap() .push(Box::new(f)); } pub fn run_exit() { if let Some(fns) = BEFORE_EXIT.get() { let fns = fns.lock().unwrap(); for f in fns.iter() { f(); } } } pub fn is_forbidden(signo: i32) -> bool { FORBIDDEN.contains(&signo) } pub struct SignalStream { rx: watch::Receiver<()>, } impl SignalStream { pub async fn recv(&mut self) -> Option<()> { self.rx.changed().await.ok() } } pub fn signal_stream(signo: i32) -> Result<SignalStream, std::io::Error> { let (tx, rx) = watch::channel(()); let cb = Box::new(move || { tx.send_replace(()); }); register(signo, true, cb)?; Ok(SignalStream { rx }) } pub async fn ctrl_c() -> std::io::Result<()> { let mut stream = signal_stream(libc::SIGINT)?; match stream.recv().await { Some(_) => Ok(()), None => Err(std::io::Error::other("failed to receive SIGINT signal")), } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/signals/dict.rs
ext/signals/dict.rs
// Copyright 2018-2025 the Deno authors. MIT license. #[cfg(target_os = "windows")] #[derive(Debug, thiserror::Error)] #[error( "Windows only supports ctrl-c (SIGINT), ctrl-break (SIGBREAK), and ctrl-close (SIGUP), but got {0}" )] pub struct InvalidSignalStrError(pub String); #[cfg(any( target_os = "android", target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "macos", target_os = "solaris", target_os = "illumos" ))] #[derive(Debug, thiserror::Error)] #[error("Invalid signal: {0}")] pub struct InvalidSignalStrError(pub String); #[cfg(target_os = "windows")] #[derive(Debug, thiserror::Error)] #[error( "Windows only supports ctrl-c (SIGINT), ctrl-break (SIGBREAK), and ctrl-close (SIGUP), but got {0}" )] pub struct InvalidSignalIntError(pub libc::c_int); #[cfg(any( target_os = "android", target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "macos", target_os = "solaris", target_os = "illumos" ))] #[derive(Debug, thiserror::Error)] #[error("Invalid signal: {0}")] pub struct InvalidSignalIntError(pub libc::c_int); macro_rules! first_literal { ($head:literal $(, $tail:literal)*) => { $head }; } macro_rules! signal_dict { ($(($number:literal, $($name:literal)|+)),*) => { pub const SIGNAL_NUMS: &'static [libc::c_int] = &[ $( $number ),* ]; pub fn signal_str_to_int(s: &str) -> Result<libc::c_int, InvalidSignalStrError> { match s { $($($name)|* => Ok($number),)* _ => Err(InvalidSignalStrError(s.to_string())), } } pub fn signal_int_to_str(s: libc::c_int) -> Result<&'static str, InvalidSignalIntError> { match s { $($number => Ok(first_literal!($($name),+)),)* _ => Err(InvalidSignalIntError(s)), } } } } #[cfg(target_os = "freebsd")] signal_dict!( (1, "SIGHUP"), (2, "SIGINT"), (3, "SIGQUIT"), (4, "SIGILL"), (5, "SIGTRAP"), (6, "SIGABRT" | "SIGIOT"), (7, "SIGEMT"), (8, "SIGFPE"), (9, "SIGKILL"), (10, "SIGBUS"), (11, "SIGSEGV"), (12, "SIGSYS"), (13, "SIGPIPE"), (14, "SIGALRM"), (15, "SIGTERM"), (16, "SIGURG"), (17, "SIGSTOP"), (18, "SIGTSTP"), (19, "SIGCONT"), (20, "SIGCHLD"), (21, "SIGTTIN"), (22, "SIGTTOU"), (23, "SIGIO"), (24, "SIGXCPU"), (25, "SIGXFSZ"), (26, "SIGVTALRM"), (27, "SIGPROF"), (28, "SIGWINCH"), (29, "SIGINFO"), (30, "SIGUSR1"), (31, "SIGUSR2"), (32, "SIGTHR"), (33, "SIGLIBRT") ); #[cfg(target_os = "openbsd")] signal_dict!( (1, "SIGHUP"), (2, "SIGINT"), (3, "SIGQUIT"), (4, "SIGILL"), (5, "SIGTRAP"), (6, "SIGABRT" | "SIGIOT"), (7, "SIGEMT"), (8, "SIGKILL"), (10, "SIGBUS"), (11, "SIGSEGV"), (12, "SIGSYS"), (13, "SIGPIPE"), (14, "SIGALRM"), (15, "SIGTERM"), (16, "SIGURG"), (17, "SIGSTOP"), (18, "SIGTSTP"), (19, "SIGCONT"), (20, "SIGCHLD"), (21, "SIGTTIN"), (22, "SIGTTOU"), (23, "SIGIO"), (24, "SIGXCPU"), (25, "SIGXFSZ"), (26, "SIGVTALRM"), (27, "SIGPROF"), (28, "SIGWINCH"), (29, "SIGINFO"), (30, "SIGUSR1"), (31, "SIGUSR2"), (32, "SIGTHR") ); #[cfg(any(target_os = "android", target_os = "linux"))] signal_dict!( (1, "SIGHUP"), (2, "SIGINT"), (3, "SIGQUIT"), (4, "SIGILL"), (5, "SIGTRAP"), (6, "SIGABRT" | "SIGIOT"), (7, "SIGBUS"), (8, "SIGFPE"), (9, "SIGKILL"), (10, "SIGUSR1"), (11, "SIGSEGV"), (12, "SIGUSR2"), (13, "SIGPIPE"), (14, "SIGALRM"), (15, "SIGTERM"), (16, "SIGSTKFLT"), (17, "SIGCHLD"), (18, "SIGCONT"), (19, "SIGSTOP"), (20, "SIGTSTP"), (21, "SIGTTIN"), (22, "SIGTTOU"), (23, "SIGURG"), (24, "SIGXCPU"), (25, "SIGXFSZ"), (26, "SIGVTALRM"), (27, "SIGPROF"), (28, "SIGWINCH"), (29, "SIGIO" | "SIGPOLL"), (30, "SIGPWR"), (31, "SIGSYS" | "SIGUNUSED") ); #[cfg(target_os = "macos")] signal_dict!( (1, "SIGHUP"), (2, "SIGINT"), (3, "SIGQUIT"), (4, "SIGILL"), (5, "SIGTRAP"), (6, "SIGABRT" | "SIGIOT"), (7, "SIGEMT"), (8, "SIGFPE"), (9, "SIGKILL"), (10, "SIGBUS"), (11, "SIGSEGV"), (12, "SIGSYS"), (13, "SIGPIPE"), (14, "SIGALRM"), (15, "SIGTERM"), (16, "SIGURG"), (17, "SIGSTOP"), (18, "SIGTSTP"), (19, "SIGCONT"), (20, "SIGCHLD"), (21, "SIGTTIN"), (22, "SIGTTOU"), (23, "SIGIO"), (24, "SIGXCPU"), (25, "SIGXFSZ"), (26, "SIGVTALRM"), (27, "SIGPROF"), (28, "SIGWINCH"), (29, "SIGINFO"), (30, "SIGUSR1"), (31, "SIGUSR2") ); #[cfg(any(target_os = "solaris", target_os = "illumos"))] signal_dict!( (1, "SIGHUP"), (2, "SIGINT"), (3, "SIGQUIT"), (4, "SIGILL"), (5, "SIGTRAP"), (6, "SIGABRT" | "SIGIOT"), (7, "SIGEMT"), (8, "SIGFPE"), (9, "SIGKILL"), (10, "SIGBUS"), (11, "SIGSEGV"), (12, "SIGSYS"), (13, "SIGPIPE"), (14, "SIGALRM"), (15, "SIGTERM"), (16, "SIGUSR1"), (17, "SIGUSR2"), (18, "SIGCHLD"), (19, "SIGPWR"), (20, "SIGWINCH"), (21, "SIGURG"), (22, "SIGPOLL"), (23, "SIGSTOP"), (24, "SIGTSTP"), (25, "SIGCONT"), (26, "SIGTTIN"), (27, "SIGTTOU"), (28, "SIGVTALRM"), (29, "SIGPROF"), (30, "SIGXCPU"), (31, "SIGXFSZ"), (32, "SIGWAITING"), (33, "SIGLWP"), (34, "SIGFREEZE"), (35, "SIGTHAW"), (36, "SIGCANCEL"), (37, "SIGLOST"), (38, "SIGXRES"), (39, "SIGJVM1"), (40, "SIGJVM2") ); #[cfg(target_os = "windows")] signal_dict!((1, "SIGHUP"), (2, "SIGINT"), (21, "SIGBREAK"));
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/os/sys_info.rs
ext/os/sys_info.rs
// Copyright 2018-2025 the Deno authors. MIT license. #[cfg(target_family = "windows")] use std::sync::Once; type LoadAvg = (f64, f64, f64); const DEFAULT_LOADAVG: LoadAvg = (0.0, 0.0, 0.0); pub fn loadavg() -> LoadAvg { #[cfg(any(target_os = "android", target_os = "linux"))] { use libc::SI_LOAD_SHIFT; let mut info = std::mem::MaybeUninit::uninit(); // SAFETY: `info` is a valid pointer to a `libc::sysinfo` struct. let res = unsafe { libc::sysinfo(info.as_mut_ptr()) }; if res == 0 { // SAFETY: `sysinfo` returns 0 on success, and `info` is initialized. let info = unsafe { info.assume_init() }; ( info.loads[0] as f64 / (1 << SI_LOAD_SHIFT) as f64, info.loads[1] as f64 / (1 << SI_LOAD_SHIFT) as f64, info.loads[2] as f64 / (1 << SI_LOAD_SHIFT) as f64, ) } else { DEFAULT_LOADAVG } } #[cfg(any( target_vendor = "apple", target_os = "freebsd", target_os = "openbsd" ))] { let mut l: [f64; 3] = [0.; 3]; // SAFETY: `&mut l` is a valid pointer to an array of 3 doubles if unsafe { libc::getloadavg(&mut l as *mut f64, l.len() as _) } < 3 { DEFAULT_LOADAVG } else { (l[0], l[1], l[2]) } } #[cfg(target_os = "windows")] { DEFAULT_LOADAVG } } pub fn os_release() -> String { #[cfg(target_os = "linux")] { #[allow(clippy::disallowed_methods)] match std::fs::read_to_string("/proc/sys/kernel/osrelease") { Ok(mut s) => { s.pop(); // pop '\n' s } _ => String::from(""), } } #[cfg(target_os = "android")] { let mut info = std::mem::MaybeUninit::uninit(); // SAFETY: `info` is a valid pointer to a `libc::utsname` struct. let res = unsafe { libc::uname(info.as_mut_ptr()) }; if res != 0 { return String::from(""); } // SAFETY: `uname` returns 0 on success, and `info` is initialized. let mut info = unsafe { info.assume_init() }; let len = info.release.len(); info.release[len - 1] = 0; // SAFETY: `info.release` is a valid pointer and NUL-terminated. let c_str = unsafe { std::ffi::CStr::from_ptr(info.release.as_ptr()) }; c_str.to_string_lossy().into_owned() } #[cfg(any( target_vendor = "apple", target_os = "freebsd", target_os = "openbsd" ))] { let mut s = [0u8; 256]; let mut mib = [libc::CTL_KERN, libc::KERN_OSRELEASE]; // 256 is enough. let mut len = s.len(); // SAFETY: `sysctl` is thread-safe. // `s` is only accessed if sysctl() succeeds and agrees with the `len` set // by sysctl(). if unsafe { libc::sysctl( mib.as_mut_ptr(), mib.len() as _, s.as_mut_ptr() as _, &mut len, std::ptr::null_mut(), 0, ) } == -1 { return String::from("Unknown"); } // without the NUL terminator String::from_utf8_lossy(&s[..len - 1]).to_string() } #[cfg(target_family = "windows")] { use ntapi::ntrtl::RtlGetVersion; use winapi::shared::ntdef::NT_SUCCESS; use winapi::um::winnt::RTL_OSVERSIONINFOEXW; let mut version_info = std::mem::MaybeUninit::<RTL_OSVERSIONINFOEXW>::uninit(); // SAFETY: we need to initialize dwOSVersionInfoSize. unsafe { (*version_info.as_mut_ptr()).dwOSVersionInfoSize = std::mem::size_of::<RTL_OSVERSIONINFOEXW>() as u32; } // SAFETY: `version_info` is pointer to a valid `RTL_OSVERSIONINFOEXW` struct and // dwOSVersionInfoSize is set to the size of RTL_OSVERSIONINFOEXW. if !NT_SUCCESS(unsafe { RtlGetVersion(version_info.as_mut_ptr() as *mut _) }) { String::from("") } else { // SAFETY: we assume that RtlGetVersion() initializes the fields. let version_info = unsafe { version_info.assume_init() }; format!( "{}.{}.{}", version_info.dwMajorVersion, version_info.dwMinorVersion, version_info.dwBuildNumber ) } } } #[cfg(target_family = "windows")] static WINSOCKET_INIT: Once = Once::new(); pub fn hostname() -> String { #[cfg(target_family = "unix")] // SAFETY: `sysconf` returns a system constant. unsafe { let buf_size = libc::sysconf(libc::_SC_HOST_NAME_MAX) as usize; let mut buf = vec![0u8; buf_size + 1]; let len = buf.len(); if libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, len) < 0 { return String::from(""); } // ensure NUL termination buf[len - 1] = 0; std::ffi::CStr::from_ptr(buf.as_ptr() as *const libc::c_char) .to_string_lossy() .into_owned() } #[cfg(target_family = "windows")] { use std::ffi::OsString; use std::mem; use std::os::windows::ffi::OsStringExt; use winapi::shared::minwindef::MAKEWORD; use winapi::um::winsock2::GetHostNameW; use winapi::um::winsock2::WSAStartup; let namelen = 256; let mut name: Vec<u16> = vec![0u16; namelen]; // Start winsock to make `GetHostNameW` work correctly // https://github.com/retep998/winapi-rs/issues/296 // SAFETY: winapi call WINSOCKET_INIT.call_once(|| unsafe { let mut data = mem::zeroed(); let wsa_startup_result = WSAStartup(MAKEWORD(2, 2), &mut data); if wsa_startup_result != 0 { panic!("Failed to start winsocket"); } }); let err = // SAFETY: length of wide string is 256 chars or less. // https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-gethostnamew unsafe { GetHostNameW(name.as_mut_ptr(), namelen as libc::c_int) }; if err == 0 { // TODO(@littledivy): Probably not the most efficient way. let len = name.iter().take_while(|&&c| c != 0).count(); OsString::from_wide(&name[..len]) .to_string_lossy() .into_owned() } else { String::from("") } } } #[derive(serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct MemInfo { pub total: u64, pub free: u64, pub available: u64, pub buffers: u64, pub cached: u64, pub swap_total: u64, pub swap_free: u64, } pub fn mem_info() -> Option<MemInfo> { let mut mem_info = MemInfo { total: 0, free: 0, available: 0, buffers: 0, cached: 0, swap_total: 0, swap_free: 0, }; #[cfg(any(target_os = "android", target_os = "linux"))] { let mut info = std::mem::MaybeUninit::uninit(); // SAFETY: `info` is a valid pointer to a `libc::sysinfo` struct. let res = unsafe { libc::sysinfo(info.as_mut_ptr()) }; if res == 0 { // SAFETY: `sysinfo` initializes the struct. let info = unsafe { info.assume_init() }; let mem_unit = info.mem_unit as u64; mem_info.swap_total = info.totalswap * mem_unit; mem_info.swap_free = info.freeswap * mem_unit; mem_info.total = info.totalram * mem_unit; mem_info.free = info.freeram * mem_unit; mem_info.available = mem_info.free; mem_info.buffers = info.bufferram * mem_unit; } // Gets the available memory from /proc/meminfo in linux for compatibility #[allow(clippy::disallowed_methods)] if let Ok(meminfo) = std::fs::read_to_string("/proc/meminfo") { let line = meminfo.lines().find(|l| l.starts_with("MemAvailable:")); if let Some(line) = line { let mem = line.split_whitespace().nth(1); let mem = mem.and_then(|v| v.parse::<u64>().ok()); mem_info.available = mem.unwrap_or(0) * 1024; } } } #[cfg(target_vendor = "apple")] { let mut mib: [i32; 2] = [0, 0]; mib[0] = libc::CTL_HW; mib[1] = libc::HW_MEMSIZE; // SAFETY: // - We assume that `mach_host_self` always returns a valid value. // - sysconf returns a system constant. unsafe { let mut size = std::mem::size_of::<u64>(); libc::sysctl( mib.as_mut_ptr(), mib.len() as _, &mut mem_info.total as *mut _ as *mut libc::c_void, &mut size, std::ptr::null_mut(), 0, ); let mut xs: libc::xsw_usage = std::mem::zeroed::<libc::xsw_usage>(); mib[0] = libc::CTL_VM; mib[1] = libc::VM_SWAPUSAGE; let mut size = std::mem::size_of::<libc::xsw_usage>(); libc::sysctl( mib.as_mut_ptr(), mib.len() as _, &mut xs as *mut _ as *mut libc::c_void, &mut size, std::ptr::null_mut(), 0, ); mem_info.swap_total = xs.xsu_total; mem_info.swap_free = xs.xsu_avail; unsafe extern "C" { fn mach_host_self() -> std::ffi::c_uint; } let mut count: u32 = libc::HOST_VM_INFO64_COUNT as _; let mut stat = std::mem::zeroed::<libc::vm_statistics64>(); if libc::host_statistics64( // TODO(@littledivy): Put this in a once_cell. mach_host_self(), libc::HOST_VM_INFO64, &mut stat as *mut libc::vm_statistics64 as *mut _, &mut count, ) == libc::KERN_SUCCESS { // TODO(@littledivy): Put this in a once_cell let page_size = libc::sysconf(libc::_SC_PAGESIZE) as u64; mem_info.available = (stat.free_count as u64 + stat.inactive_count as u64) * page_size; mem_info.free = (stat.free_count as u64 - stat.speculative_count as u64) * page_size; } } } #[cfg(target_family = "windows")] // SAFETY: // - `mem_status` is a valid pointer to a `libc::MEMORYSTATUSEX` struct. // - `dwLength` is set to the size of the struct. unsafe { use std::mem; use winapi::shared::minwindef; use winapi::um::psapi::GetPerformanceInfo; use winapi::um::psapi::PERFORMANCE_INFORMATION; use winapi::um::sysinfoapi; let mut mem_status = mem::MaybeUninit::<sysinfoapi::MEMORYSTATUSEX>::uninit(); let length = mem::size_of::<sysinfoapi::MEMORYSTATUSEX>() as minwindef::DWORD; (*mem_status.as_mut_ptr()).dwLength = length; let result = sysinfoapi::GlobalMemoryStatusEx(mem_status.as_mut_ptr()); if result != 0 { let stat = mem_status.assume_init(); mem_info.total = stat.ullTotalPhys; mem_info.available = 0; mem_info.free = stat.ullAvailPhys; mem_info.cached = 0; mem_info.buffers = 0; // `stat.ullTotalPageFile` is reliable only from GetPerformanceInfo() // // See https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/ns-sysinfoapi-memorystatusex // and https://github.com/GuillaumeGomez/sysinfo/issues/534 let mut perf_info = mem::MaybeUninit::<PERFORMANCE_INFORMATION>::uninit(); let result = GetPerformanceInfo( perf_info.as_mut_ptr(), mem::size_of::<PERFORMANCE_INFORMATION>() as minwindef::DWORD, ); if result == minwindef::TRUE { let perf_info = perf_info.assume_init(); let swap_total = perf_info.PageSize * perf_info .CommitLimit .saturating_sub(perf_info.PhysicalTotal); let swap_free = perf_info.PageSize * perf_info .CommitLimit .saturating_sub(perf_info.PhysicalTotal) .saturating_sub(perf_info.PhysicalAvailable); mem_info.swap_total = (swap_total / 1000) as u64; mem_info.swap_free = (swap_free / 1000) as u64; } } } Some(mem_info) } pub fn os_uptime() -> u64 { let uptime: u64; #[cfg(any(target_os = "android", target_os = "linux"))] { let mut info = std::mem::MaybeUninit::uninit(); // SAFETY: `info` is a valid pointer to a `libc::sysinfo` struct. let res = unsafe { libc::sysinfo(info.as_mut_ptr()) }; uptime = if res == 0 { // SAFETY: `sysinfo` initializes the struct. let info = unsafe { info.assume_init() }; info.uptime as u64 } else { 0 } } #[cfg(any( target_vendor = "apple", target_os = "freebsd", target_os = "openbsd" ))] { use std::mem; use std::time::Duration; use std::time::SystemTime; let mut request = [libc::CTL_KERN, libc::KERN_BOOTTIME]; // SAFETY: `boottime` is only accessed if sysctl() succeeds // and agrees with the `size` set by sysctl(). let mut boottime: libc::timeval = unsafe { mem::zeroed() }; let mut size: libc::size_t = mem::size_of_val(&boottime) as libc::size_t; // SAFETY: `sysctl` is thread-safe. let res = unsafe { libc::sysctl( &mut request[0], 2, &mut boottime as *mut libc::timeval as *mut libc::c_void, &mut size, std::ptr::null_mut(), 0, ) }; uptime = if res == 0 { SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .map(|d| { (d - Duration::new( boottime.tv_sec as u64, boottime.tv_usec as u32 * 1000, )) .as_secs() }) .unwrap_or_default() } else { 0 } } #[cfg(target_family = "windows")] // SAFETY: windows API usage unsafe { // Windows is the only one that returns `uptime` in millisecond precision, // so we need to get the seconds out of it to be in sync with other envs. uptime = winapi::um::sysinfoapi::GetTickCount64() / 1000; } uptime }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/os/lib.rs
ext/os/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::collections::HashMap; use std::env; use std::ffi::OsString; use std::ops::ControlFlow; use std::sync::Arc; use std::sync::atomic::AtomicI32; use std::sync::atomic::Ordering; use deno_core::OpState; use deno_core::op2; use deno_core::v8; use deno_path_util::normalize_path; use deno_permissions::PermissionCheckError; use deno_permissions::PermissionState; use deno_permissions::PermissionsContainer; use serde::Serialize; mod ops; pub mod sys_info; pub use ops::signal::SignalError; // The full list of environment variables supported by Node.js is available // at https://nodejs.org/api/cli.html#environment-variables const SORTED_NODE_ENV_VAR_ALLOWLIST: [&str; 4] = ["FORCE_COLOR", "NODE_DEBUG", "NODE_OPTIONS", "NO_COLOR"]; #[derive(Clone, Default)] pub struct ExitCode(Arc<AtomicI32>); impl ExitCode { pub fn get(&self) -> i32 { self.0.load(Ordering::Relaxed) } pub fn set(&mut self, code: i32) { self.0.store(code, Ordering::Relaxed); } } pub fn exit(code: i32) -> ! { deno_signals::run_exit(); #[allow(clippy::disallowed_methods)] std::process::exit(code); } deno_core::extension!( deno_os, ops = [ op_env, op_exec_path, op_exit, op_delete_env, op_get_env, op_get_env_no_permission_check, 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, ops::signal::op_signal_bind, ops::signal::op_signal_unbind, ops::signal::op_signal_poll, ], esm = ["30_os.js", "40_signals.js"], options = { exit_code: Option<ExitCode>, }, state = |state, options| { if let Some(exit_code) = options.exit_code { state.put::<ExitCode>(exit_code); } } ); #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum OsError { #[class(inherit)] #[error(transparent)] Permission(#[from] PermissionCheckError), #[class("InvalidData")] #[error("File name or path {0:?} is not valid UTF-8")] InvalidUtf8(std::ffi::OsString), #[class(type)] #[error("Key is an empty string.")] EnvEmptyKey, #[class(type)] #[error("Key contains invalid characters: {0:?}")] EnvInvalidKey(String), #[class(type)] #[error("Value contains invalid characters: {0:?}")] EnvInvalidValue(String), #[class(inherit)] #[error(transparent)] Var(#[from] env::VarError), #[class(inherit)] #[error("{0}")] Io(#[from] std::io::Error), } #[op2] #[string] fn op_exec_path() -> Result<String, OsError> { let current_exe = env::current_exe().unwrap(); // normalize path so it doesn't include '.' or '..' components let path = normalize_path(Cow::Owned(current_exe)); path .into_owned() .into_os_string() .into_string() .map_err(OsError::InvalidUtf8) } fn dt_change_notif(isolate: &mut v8::Isolate, key: &str) { unsafe extern "C" { #[cfg(unix)] fn tzset(); #[cfg(windows)] fn _tzset(); } if key == "TZ" { // SAFETY: tzset/_tzset (libc) is called to update the timezone information unsafe { #[cfg(unix)] tzset(); #[cfg(windows)] _tzset(); } isolate.date_time_configuration_change_notification( v8::TimeZoneDetection::Redetect, ); } } #[op2(fast, stack_trace)] fn op_set_env( state: &mut OpState, scope: &mut v8::PinScope<'_, '_>, #[string] key: &str, #[string] value: &str, ) -> Result<(), OsError> { if check_env_with_maybe_exit(state, key)?.is_break() { return Ok(()); } 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())); } #[allow(clippy::undocumented_unsafe_blocks)] unsafe { env::set_var(key, value) }; dt_change_notif(scope, key); Ok(()) } fn check_env_with_maybe_exit( state: &mut OpState, key: &str, ) -> Result<ControlFlow<()>, PermissionCheckError> { match state.borrow_mut::<PermissionsContainer>().check_env(key) { Ok(()) => Ok(ControlFlow::Continue(())), Err(PermissionCheckError::PermissionDenied(err)) if err.state == PermissionState::Ignored => { Ok(ControlFlow::Break(())) } Err(err) => Err(err), } } #[op2(stack_trace)] #[serde] fn op_env( state: &mut OpState, ) -> Result<HashMap<String, String>, PermissionCheckError> { fn map_kv(kv: (OsString, OsString)) -> Option<(String, String)> { kv.0 .into_string() .ok() .and_then(|key| kv.1.into_string().ok().map(|value| (key, value))) } let permissions_container = state.borrow::<PermissionsContainer>(); let grant_all = match permissions_container.check_env_all() { Ok(()) => true, Err(PermissionCheckError::PermissionDenied(err)) => match err.state { PermissionState::Granted | PermissionState::Prompt | PermissionState::Denied => return Err(err.into()), PermissionState::GrantedPartial | PermissionState::DeniedPartial | PermissionState::Ignored => false, }, Err(err) => return Err(err), }; Ok( env::vars_os() .filter_map(|kv| { let (k, v) = map_kv(kv)?; let state = if grant_all { PermissionState::Granted } else { permissions_container.query_env(Some(&k)) }; match state { PermissionState::Granted | PermissionState::GrantedPartial => { Some((k, v)) } PermissionState::Ignored | PermissionState::Prompt | PermissionState::Denied | PermissionState::DeniedPartial => None, } }) .collect(), ) } fn get_env_var(key: &str) -> Result<Option<String>, OsError> { 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] #[string] fn op_get_env_no_permission_check( #[string] key: &str, ) -> Result<Option<String>, OsError> { get_env_var(key) } #[op2(stack_trace)] #[string] fn op_get_env( state: &mut OpState, #[string] key: &str, ) -> Result<Option<String>, OsError> { let skip_permission_check = SORTED_NODE_ENV_VAR_ALLOWLIST.binary_search(&key).is_ok(); if !skip_permission_check && check_env_with_maybe_exit(state, key)?.is_break() { return Ok(None); } get_env_var(key) } #[op2(fast, stack_trace)] fn op_delete_env( state: &mut OpState, #[string] key: &str, ) -> Result<(), OsError> { if check_env_with_maybe_exit(state, key)?.is_break() { return Ok(()); } if key.is_empty() || key.contains(&['=', '\0'] as &[char]) { return Err(OsError::EnvInvalidKey(key.to_string())); } #[allow(clippy::undocumented_unsafe_blocks)] unsafe { env::remove_var(key) }; Ok(()) } #[op2(fast)] fn op_set_exit_code(state: &mut OpState, #[smi] code: i32) { if let Some(exit_code) = state.try_borrow_mut::<ExitCode>() { exit_code.set(code); } } #[op2(fast)] #[smi] fn op_get_exit_code(state: &mut OpState) -> i32 { state .try_borrow::<ExitCode>() .map(|e| e.get()) .unwrap_or_default() } #[op2(fast)] fn op_exit(state: &mut OpState) { if let Some(exit_code) = state.try_borrow::<ExitCode>() { exit(exit_code.get()) } } #[op2(stack_trace)] #[serde] fn op_loadavg( state: &mut OpState, ) -> Result<(f64, f64, f64), PermissionCheckError> { 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, PermissionCheckError> { 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, PermissionCheckError> { 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(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>, PermissionCheckError> { 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>, PermissionCheckError> { 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>, PermissionCheckError> { 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>, PermissionCheckError> { 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>, PermissionCheckError> { state .borrow_mut::<PermissionsContainer>() .check_sys("uid", "Deno.uid()")?; Ok(None) } #[op2(fast)] fn op_runtime_cpu_usage(#[buffer] out: &mut [f64]) { let (sys, user) = get_cpu_usage(); out[0] = sys.as_micros() as f64; out[1] = user.as_micros() as f64; } #[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(fast)] fn op_runtime_memory_usage( scope: &mut v8::PinScope<'_, '_>, #[buffer] out: &mut [f64], ) { let s = scope.get_heap_statistics(); let (rss, heap_total, heap_used, external) = ( rss(), s.total_heap_size() as u64, s.used_heap_size() as u64, s.external_memory() as u64, ); out[0] = rss as f64; out[1] = heap_total as f64; out[2] = heap_used as f64; out[3] = external as f64; } #[cfg(any(target_os = "android", target_os = "linux"))] fn rss() -> u64 { // 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) -> (u64, 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 u64 - '0' as u64; } 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 u64 } #[cfg(target_os = "macos")] fn rss() -> u64 { // 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 { unsafe extern "C" { static mut mach_task_self_: std::ffi::c_uint; } libc::task_info( 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 } #[cfg(target_os = "openbsd")] fn rss() -> u64 { // 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 u64; // 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 u64 } } else { 0 } } #[cfg(windows)] fn rss() -> u64 { 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 as u64 } else { 0 } } } fn os_uptime(state: &mut OpState) -> Result<u64, PermissionCheckError> { 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, PermissionCheckError> { os_uptime(state) } #[cfg(test)] mod test { use crate::SORTED_NODE_ENV_VAR_ALLOWLIST; #[test] fn ensure_node_env_var_list_sorted() { // ensure this is sorted for binary search let mut items = SORTED_NODE_ENV_VAR_ALLOWLIST.to_vec(); items.sort(); assert_eq!(items, SORTED_NODE_ENV_VAR_ALLOWLIST); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/os/ops/signal.rs
ext/os/ops/signal.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::rc::Rc; use deno_core::AsyncRefCell; use deno_core::OpState; use deno_core::RcRef; use deno_core::Resource; use deno_core::ResourceId; use deno_core::error::ResourceError; use deno_core::op2; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum SignalError { #[class(type)] #[error(transparent)] InvalidSignalStr(#[from] deno_signals::InvalidSignalStrError), #[class(type)] #[error(transparent)] InvalidSignalInt(#[from] deno_signals::InvalidSignalIntError), #[class(type)] #[error("Binding to signal '{0}' is not allowed")] SignalNotAllowed(String), #[class(inherit)] #[error("{0}")] Io(#[from] std::io::Error), } struct SignalStreamResource { signo: i32, id: u32, rx: AsyncRefCell<tokio::sync::watch::Receiver<()>>, } impl Resource for SignalStreamResource { fn name(&self) -> Cow<'_, str> { "signal".into() } fn close(self: Rc<Self>) { deno_signals::unregister(self.signo, self.id); } } #[op2(fast)] #[smi] pub fn op_signal_bind( state: &mut OpState, #[string] sig: &str, ) -> Result<ResourceId, SignalError> { let signo = deno_signals::signal_str_to_int(sig)?; if deno_signals::is_forbidden(signo) { return Err(SignalError::SignalNotAllowed(sig.to_string())); } let (tx, rx) = tokio::sync::watch::channel(()); let id = deno_signals::register( signo, true, Box::new(move || { let _ = tx.send(()); }), )?; let rid = state.resource_table.add(SignalStreamResource { signo, id, rx: AsyncRefCell::new(rx), }); Ok(rid) } #[op2(async)] pub async fn op_signal_poll( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<bool, ResourceError> { let resource = state .borrow_mut() .resource_table .get::<SignalStreamResource>(rid)?; let mut rx = RcRef::map(&resource, |r| &r.rx).borrow_mut().await; Ok(rx.changed().await.is_err()) } #[op2(fast)] pub fn op_signal_unbind( state: &mut OpState, #[smi] rid: ResourceId, ) -> Result<(), ResourceError> { let resource = state.resource_table.take::<SignalStreamResource>(rid)?; resource.close(); Ok(()) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/os/ops/mod.rs
ext/os/ops/mod.rs
// Copyright 2018-2025 the Deno authors. MIT license. pub mod signal;
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/ffi/lib.rs
ext/ffi/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::mem::size_of; use std::os::raw::c_char; use std::os::raw::c_short; mod call; mod callback; mod dlfcn; mod ir; mod repr; mod r#static; mod symbol; mod turbocall; pub use call::CallError; use call::op_ffi_call_nonblocking; use call::op_ffi_call_ptr; use call::op_ffi_call_ptr_nonblocking; pub use callback::CallbackError; use callback::op_ffi_unsafe_callback_close; use callback::op_ffi_unsafe_callback_create; use callback::op_ffi_unsafe_callback_ref; pub use denort_helper::DenoRtNativeAddonLoader; pub use denort_helper::DenoRtNativeAddonLoaderRc; pub use dlfcn::DlfcnError; use dlfcn::ForeignFunction; use dlfcn::op_ffi_load; pub use ir::IRError; pub use repr::ReprError; use repr::*; pub use r#static::StaticError; use r#static::op_ffi_get_static; use symbol::NativeType; use symbol::Symbol; use turbocall::op_ffi_get_turbocall_target; #[cfg(not(target_pointer_width = "64"))] compile_error!("platform not supported"); const _: () = { assert!(size_of::<c_char>() == 1); assert!(size_of::<c_short>() == 2); assert!(size_of::<*const ()>() == 8); }; pub const UNSTABLE_FEATURE_NAME: &str = "ffi"; deno_core::extension!(deno_ffi, deps = [ deno_web ], ops = [ op_ffi_load, op_ffi_get_static, op_ffi_call_nonblocking, op_ffi_call_ptr, op_ffi_call_ptr_nonblocking, op_ffi_ptr_create, op_ffi_ptr_equals, op_ffi_ptr_of, op_ffi_ptr_of_exact, op_ffi_ptr_offset, op_ffi_ptr_value, op_ffi_get_buf, op_ffi_buf_copy_into, op_ffi_cstr_read, op_ffi_read_bool, op_ffi_read_u8, op_ffi_read_i8, op_ffi_read_u16, op_ffi_read_i16, op_ffi_read_u32, op_ffi_read_i32, op_ffi_read_u64, op_ffi_read_i64, op_ffi_read_f32, op_ffi_read_f64, op_ffi_read_ptr, op_ffi_unsafe_callback_create, op_ffi_unsafe_callback_close, op_ffi_unsafe_callback_ref, op_ffi_get_turbocall_target, ], esm = [ "00_ffi.js" ], options = { deno_rt_native_addon_loader: Option<DenoRtNativeAddonLoaderRc>, }, state = |state, options| { if let Some(loader) = options.deno_rt_native_addon_loader { state.put(loader); } }, );
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/ffi/call.rs
ext/ffi/call.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::RefCell; use std::ffi::c_void; use std::future::Future; use std::rc::Rc; use deno_core::OpState; use deno_core::ResourceId; use deno_core::op2; use deno_core::serde_json::Value; use deno_core::serde_v8::BigInt as V8BigInt; use deno_core::serde_v8::ExternalPointer; use deno_core::unsync::spawn_blocking; use deno_core::v8; use deno_permissions::PermissionsContainer; use libffi::middle::Arg; use num_bigint::BigInt; use serde::Serialize; use crate::ForeignFunction; use crate::callback::PtrSymbol; use crate::dlfcn::DynamicLibraryResource; use crate::ir::*; use crate::symbol::NativeType; use crate::symbol::Symbol; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum CallError { #[class(type)] #[error(transparent)] IR(#[from] IRError), #[class(generic)] #[error("Nonblocking FFI call failed: {0}")] NonblockingCallFailure(#[source] tokio::task::JoinError), #[class(type)] #[error("Invalid FFI symbol name: '{0}'")] InvalidSymbol(String), #[class(inherit)] #[error(transparent)] Permission(#[from] deno_permissions::PermissionCheckError), #[class(inherit)] #[error(transparent)] Resource(#[from] deno_core::error::ResourceError), #[class(inherit)] #[error(transparent)] Callback(#[from] super::CallbackError), } // SAFETY: Makes an FFI call unsafe fn ffi_call_rtype_struct( cif: &libffi::middle::Cif, fn_ptr: &libffi::middle::CodePtr, call_args: Vec<Arg>, out_buffer: *mut u8, ) { #[allow(clippy::undocumented_unsafe_blocks)] unsafe { libffi::raw::ffi_call( cif.as_raw_ptr(), Some(*fn_ptr.as_safe_fun()), out_buffer as *mut c_void, call_args.as_ptr() as *mut *mut c_void, ); } } // A one-off synchronous FFI call. pub(crate) fn ffi_call_sync<'scope>( scope: &mut v8::PinScope<'scope, '_>, args: v8::FunctionCallbackArguments, symbol: &Symbol, out_buffer: Option<OutBuffer>, ) -> Result<NativeValue, CallError> where 'scope: 'scope, { let Symbol { parameter_types, result_type, cif, ptr: fun_ptr, .. } = symbol; let mut ffi_args: Vec<NativeValue> = Vec::with_capacity(parameter_types.len()); for (index, native_type) in parameter_types.iter().enumerate() { let value = args.get(index as i32); match native_type { NativeType::Bool => { ffi_args.push(ffi_parse_bool_arg(value)?); } NativeType::U8 => { ffi_args.push(ffi_parse_u8_arg(value)?); } NativeType::I8 => { ffi_args.push(ffi_parse_i8_arg(value)?); } NativeType::U16 => { ffi_args.push(ffi_parse_u16_arg(value)?); } NativeType::I16 => { ffi_args.push(ffi_parse_i16_arg(value)?); } NativeType::U32 => { ffi_args.push(ffi_parse_u32_arg(value)?); } NativeType::I32 => { ffi_args.push(ffi_parse_i32_arg(value)?); } NativeType::U64 => { ffi_args.push(ffi_parse_u64_arg(scope, value)?); } NativeType::I64 => { ffi_args.push(ffi_parse_i64_arg(scope, value)?); } NativeType::USize => { ffi_args.push(ffi_parse_usize_arg(scope, value)?); } NativeType::ISize => { ffi_args.push(ffi_parse_isize_arg(scope, value)?); } NativeType::F32 => { ffi_args.push(ffi_parse_f32_arg(value)?); } NativeType::F64 => { ffi_args.push(ffi_parse_f64_arg(value)?); } NativeType::Buffer => { ffi_args.push(ffi_parse_buffer_arg(value)?); } NativeType::Struct(_) => { ffi_args.push(ffi_parse_struct_arg(scope, value)?); } NativeType::Pointer => { ffi_args.push(ffi_parse_pointer_arg(scope, value)?); } NativeType::Function => { ffi_args.push(ffi_parse_function_arg(scope, value)?); } NativeType::Void => { unreachable!(); } } } let call_args: Vec<Arg> = ffi_args .iter() .enumerate() // SAFETY: Creating a `Arg` from a `NativeValue` is pretty safe. .map(|(i, v)| unsafe { v.as_arg(parameter_types.get(i).unwrap()) }) .collect(); // SAFETY: types in the `Cif` match the actual calling convention and // types of symbol. unsafe { Ok(match result_type { NativeType::Void => NativeValue { void_value: cif.call::<()>(*fun_ptr, &call_args), }, NativeType::Bool => NativeValue { bool_value: cif.call::<bool>(*fun_ptr, &call_args), }, NativeType::U8 => NativeValue { u8_value: cif.call::<u8>(*fun_ptr, &call_args), }, NativeType::I8 => NativeValue { i8_value: cif.call::<i8>(*fun_ptr, &call_args), }, NativeType::U16 => NativeValue { u16_value: cif.call::<u16>(*fun_ptr, &call_args), }, NativeType::I16 => NativeValue { i16_value: cif.call::<i16>(*fun_ptr, &call_args), }, NativeType::U32 => NativeValue { u32_value: cif.call::<u32>(*fun_ptr, &call_args), }, NativeType::I32 => NativeValue { i32_value: cif.call::<i32>(*fun_ptr, &call_args), }, NativeType::U64 => NativeValue { u64_value: cif.call::<u64>(*fun_ptr, &call_args), }, NativeType::I64 => NativeValue { i64_value: cif.call::<i64>(*fun_ptr, &call_args), }, NativeType::USize => NativeValue { usize_value: cif.call::<usize>(*fun_ptr, &call_args), }, NativeType::ISize => NativeValue { isize_value: cif.call::<isize>(*fun_ptr, &call_args), }, NativeType::F32 => NativeValue { f32_value: cif.call::<f32>(*fun_ptr, &call_args), }, NativeType::F64 => NativeValue { f64_value: cif.call::<f64>(*fun_ptr, &call_args), }, NativeType::Pointer | NativeType::Function | NativeType::Buffer => { NativeValue { pointer: cif.call::<*mut c_void>(*fun_ptr, &call_args), } } NativeType::Struct(_) => NativeValue { void_value: ffi_call_rtype_struct( &symbol.cif, &symbol.ptr, call_args, out_buffer.unwrap().0, ), }, }) } } #[derive(Serialize)] #[serde(untagged)] pub enum FfiValue { Value(Value), BigInt(V8BigInt), External(ExternalPointer), } fn ffi_call( call_args: Vec<NativeValue>, cif: &libffi::middle::Cif, fun_ptr: libffi::middle::CodePtr, parameter_types: &[NativeType], result_type: NativeType, out_buffer: Option<OutBuffer>, ) -> FfiValue { let call_args: Vec<Arg> = call_args .iter() .enumerate() .map(|(index, ffi_arg)| { // SAFETY: the union field is initialized unsafe { ffi_arg.as_arg(parameter_types.get(index).unwrap()) } }) .collect(); // SAFETY: types in the `Cif` match the actual calling convention and // types of symbol. unsafe { match result_type { NativeType::Void => { cif.call::<()>(fun_ptr, &call_args); FfiValue::Value(Value::from(())) } NativeType::Bool => { FfiValue::Value(Value::from(cif.call::<bool>(fun_ptr, &call_args))) } NativeType::U8 => { FfiValue::Value(Value::from(cif.call::<u8>(fun_ptr, &call_args))) } NativeType::I8 => { FfiValue::Value(Value::from(cif.call::<i8>(fun_ptr, &call_args))) } NativeType::U16 => { FfiValue::Value(Value::from(cif.call::<u16>(fun_ptr, &call_args))) } NativeType::I16 => { FfiValue::Value(Value::from(cif.call::<i16>(fun_ptr, &call_args))) } NativeType::U32 => { FfiValue::Value(Value::from(cif.call::<u32>(fun_ptr, &call_args))) } NativeType::I32 => { FfiValue::Value(Value::from(cif.call::<i32>(fun_ptr, &call_args))) } NativeType::U64 => FfiValue::BigInt(V8BigInt::from(BigInt::from( cif.call::<u64>(fun_ptr, &call_args), ))), NativeType::I64 => FfiValue::BigInt(V8BigInt::from(BigInt::from( cif.call::<i64>(fun_ptr, &call_args), ))), NativeType::USize => FfiValue::BigInt(V8BigInt::from(BigInt::from( cif.call::<usize>(fun_ptr, &call_args), ))), NativeType::ISize => FfiValue::BigInt(V8BigInt::from(BigInt::from( cif.call::<isize>(fun_ptr, &call_args), ))), NativeType::F32 => { FfiValue::Value(Value::from(cif.call::<f32>(fun_ptr, &call_args))) } NativeType::F64 => { FfiValue::Value(Value::from(cif.call::<f64>(fun_ptr, &call_args))) } NativeType::Pointer | NativeType::Function | NativeType::Buffer => { FfiValue::External(ExternalPointer::from( cif.call::<*mut c_void>(fun_ptr, &call_args), )) } NativeType::Struct(_) => { ffi_call_rtype_struct(cif, &fun_ptr, call_args, out_buffer.unwrap().0); FfiValue::Value(Value::Null) } } } } #[op2(async, stack_trace)] #[serde] pub fn op_ffi_call_ptr_nonblocking( scope: &mut v8::PinScope<'_, '_>, state: Rc<RefCell<OpState>>, pointer: *mut c_void, #[serde] def: ForeignFunction, parameters: v8::Local<v8::Array>, out_buffer: Option<v8::Local<v8::TypedArray>>, ) -> Result<impl Future<Output = Result<FfiValue, CallError>> + use<>, CallError> where { { let mut state = state.borrow_mut(); let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; }; let symbol = PtrSymbol::new(pointer, &def)?; let call_args = ffi_parse_args(scope, parameters, &def.parameters)?; let out_buffer_ptr = out_buffer_as_ptr(scope, out_buffer); let join_handle = spawn_blocking(move || { let PtrSymbol { cif, ptr } = symbol.clone(); ffi_call( call_args, &cif, ptr, &def.parameters, def.result, out_buffer_ptr, ) }); Ok(async move { let result = join_handle .await .map_err(CallError::NonblockingCallFailure)?; // SAFETY: Same return type declared to libffi; trust user to have it right beyond that. Ok(result) }) } /// A non-blocking FFI call. #[op2(async)] #[serde] pub fn op_ffi_call_nonblocking( scope: &mut v8::PinScope<'_, '_>, state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, #[string] symbol: String, parameters: v8::Local<v8::Array>, out_buffer: Option<v8::Local<v8::TypedArray>>, ) -> Result<impl Future<Output = Result<FfiValue, CallError>> + use<>, CallError> { let symbol = { let state = state.borrow(); let resource = state.resource_table.get::<DynamicLibraryResource>(rid)?; let symbols = &resource.symbols; *symbols .get(&symbol) .ok_or_else(|| CallError::InvalidSymbol(symbol))? .clone() }; let call_args = ffi_parse_args(scope, parameters, &symbol.parameter_types)?; let out_buffer_ptr = out_buffer_as_ptr(scope, out_buffer); let join_handle = spawn_blocking(move || { let Symbol { cif, ptr, parameter_types, result_type, .. } = symbol.clone(); ffi_call( call_args, &cif, ptr, &parameter_types, result_type, out_buffer_ptr, ) }); Ok(async move { let result = join_handle .await .map_err(CallError::NonblockingCallFailure)?; // SAFETY: Same return type declared to libffi; trust user to have it right beyond that. Ok(result) }) } #[op2(reentrant, stack_trace)] #[serde] pub fn op_ffi_call_ptr( scope: &mut v8::PinScope<'_, '_>, state: Rc<RefCell<OpState>>, pointer: *mut c_void, #[serde] def: ForeignFunction, parameters: v8::Local<v8::Array>, out_buffer: Option<v8::Local<v8::TypedArray>>, ) -> Result<FfiValue, CallError> { { let mut state = state.borrow_mut(); let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; }; let symbol = PtrSymbol::new(pointer, &def)?; let call_args = ffi_parse_args(scope, parameters, &def.parameters)?; let out_buffer_ptr = out_buffer_as_ptr(scope, out_buffer); let result = ffi_call( call_args, &symbol.cif, symbol.ptr, &def.parameters, def.result.clone(), out_buffer_ptr, ); // SAFETY: Same return type declared to libffi; trust user to have it right beyond that. Ok(result) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/ffi/dlfcn.rs
ext/ffi/dlfcn.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::collections::HashMap; use std::ffi::c_void; use std::path::Path; use std::rc::Rc; use deno_core::GarbageCollected; use deno_core::OpState; use deno_core::Resource; use deno_core::op2; use deno_core::v8; use deno_error::JsErrorBox; use deno_error::JsErrorClass; use deno_permissions::PermissionsContainer; use denort_helper::DenoRtNativeAddonLoaderRc; use dlopen2::raw::Library; use serde::Deserialize; use serde_value::ValueDeserializer; use crate::ir::out_buffer_as_ptr; use crate::symbol::NativeType; use crate::symbol::Symbol; use crate::turbocall; use crate::turbocall::Turbocall; deno_error::js_error_wrapper!(dlopen2::Error, JsDlopen2Error, |err| { match err { dlopen2::Error::NullCharacter(_) => "InvalidData".into(), dlopen2::Error::OpeningLibraryError(e) => e.get_class(), dlopen2::Error::SymbolGettingError(e) => e.get_class(), dlopen2::Error::AddrNotMatchingDll(e) => e.get_class(), dlopen2::Error::NullSymbol => "NotFound".into(), } }); #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum DlfcnError { #[class(generic)] #[error("Failed to register symbol {symbol}: {error}")] RegisterSymbol { symbol: String, #[source] error: dlopen2::Error, }, #[class(generic)] #[error(transparent)] Dlopen(#[from] dlopen2::Error), #[class(inherit)] #[error(transparent)] Permission(#[from] deno_permissions::PermissionCheckError), #[class(inherit)] #[error(transparent)] DenoRtLoad(#[from] denort_helper::LoadError), #[class(inherit)] #[error(transparent)] Other(#[from] JsErrorBox), } pub struct DynamicLibraryResource { lib: Library, pub symbols: HashMap<String, Box<Symbol>>, } impl Resource for DynamicLibraryResource { fn name(&self) -> Cow<'_, str> { "dynamicLibrary".into() } fn close(self: Rc<Self>) { drop(self) } } impl DynamicLibraryResource { pub fn get_static(&self, symbol: String) -> Result<*mut c_void, DlfcnError> { // By default, Err returned by this function does not tell // which symbol wasn't exported. So we'll modify the error // message to include the name of symbol. // // SAFETY: The obtained T symbol is the size of a pointer. match unsafe { self.lib.symbol::<*mut c_void>(&symbol) } { Ok(value) => Ok(Ok(value)), Err(error) => Err(DlfcnError::RegisterSymbol { symbol, error }), }? } } #[derive(Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct ForeignFunction { name: Option<String>, pub parameters: Vec<NativeType>, pub result: NativeType, #[serde(rename = "nonblocking")] non_blocking: Option<bool>, #[serde(rename = "optional")] #[serde(default = "default_optional")] optional: bool, } fn default_optional() -> bool { false } // ForeignStatic's name and type fields are read and used by // serde_v8 to determine which variant a ForeignSymbol is. // They are not used beyond that and are thus marked with underscores. #[derive(Deserialize, Debug)] struct ForeignStatic { #[serde(rename(deserialize = "name"))] _name: Option<String>, #[serde(rename(deserialize = "type"))] _type: String, } #[derive(Debug)] enum ForeignSymbol { ForeignFunction(ForeignFunction), ForeignStatic(#[allow(dead_code)] ForeignStatic), } impl<'de> Deserialize<'de> for ForeignSymbol { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let value = serde_value::Value::deserialize(deserializer)?; // Probe a ForeignStatic and if that doesn't match, assume ForeignFunction to improve error messages match ForeignStatic::deserialize(ValueDeserializer::<D::Error>::new( value.clone(), )) { Ok(res) => Ok(ForeignSymbol::ForeignStatic(res)), _ => { ForeignFunction::deserialize(ValueDeserializer::<D::Error>::new(value)) .map(ForeignSymbol::ForeignFunction) } } } } #[op2(stack_trace)] pub fn op_ffi_load<'scope>( scope: &mut v8::PinScope<'scope, '_>, state: Rc<RefCell<OpState>>, #[string] path: &str, #[serde] symbols: HashMap<String, ForeignSymbol>, ) -> Result<v8::Local<'scope, v8::Value>, DlfcnError> { let (path, denort_helper) = { let mut state = state.borrow_mut(); let permissions = state.borrow_mut::<PermissionsContainer>(); ( permissions .check_ffi_partial_with_path(Cow::Borrowed(Path::new(path)))?, state.try_borrow::<DenoRtNativeAddonLoaderRc>().cloned(), ) }; let real_path = match denort_helper { Some(loader) => loader.load_and_resolve_path(&path)?, None => Cow::Borrowed(path.as_ref()), }; let lib = Library::open(real_path.as_ref()).map_err(|e| { dlopen2::Error::OpeningLibraryError(std::io::Error::other(format_error( e, &real_path, ))) })?; let mut resource = DynamicLibraryResource { lib, symbols: HashMap::new(), }; let obj = v8::Object::new(scope); for (symbol_key, foreign_symbol) in symbols { match foreign_symbol { ForeignSymbol::ForeignStatic(_) => { // No-op: Statics will be handled separately and are not part of the Rust-side resource. } ForeignSymbol::ForeignFunction(foreign_fn) => 'register_symbol: { let symbol = match &foreign_fn.name { Some(symbol) => symbol, None => &symbol_key, }; // By default, Err returned by this function does not tell // which symbol wasn't exported. So we'll modify the error // message to include the name of symbol. let fn_ptr = // SAFETY: The obtained T symbol is the size of a pointer. match unsafe { resource.lib.symbol::<*const c_void>(symbol) } { Ok(value) => Ok(value), Err(error) => if foreign_fn.optional { let null: v8::Local<v8::Value> = v8::null(scope).into(); let func_key = v8::String::new(scope, &symbol_key).unwrap(); obj.set(scope, func_key.into(), null); break 'register_symbol; } else { Err(DlfcnError::RegisterSymbol { symbol: symbol.to_owned(), error, }) }, }?; let ptr = libffi::middle::CodePtr::from_ptr(fn_ptr as _); let cif = libffi::middle::Cif::new( foreign_fn .parameters .clone() .into_iter() .map(libffi::middle::Type::try_from) .collect::<Result<Vec<_>, _>>()?, foreign_fn.result.clone().try_into()?, ); let func_key = v8::String::new(scope, &symbol_key).unwrap(); let sym = Box::new(Symbol { name: symbol_key.clone(), cif, ptr, parameter_types: foreign_fn.parameters, result_type: foreign_fn.result, }); resource.symbols.insert(symbol_key, sym.clone()); match foreign_fn.non_blocking { // Generate functions for synchronous calls. Some(false) | None => { let function = make_sync_fn(scope, sym); obj.set(scope, func_key.into(), function.into()); } // This optimization is not yet supported for non-blocking calls. _ => {} }; } } } let mut state = state.borrow_mut(); let out = v8::Array::new(scope, 2); let rid = state.resource_table.add(resource); let rid_v8 = v8::Integer::new_from_unsigned(scope, rid); out.set_index(scope, 0, rid_v8.into()); out.set_index(scope, 1, obj.into()); Ok(out.into()) } pub struct FunctionData { // Held in a box to keep memory while function is alive. #[allow(unused)] pub symbol: Box<Symbol>, // Held in a box to keep inner data alive while function is alive. #[allow(unused)] turbocall: Option<Turbocall>, } // SAFETY: we're sure `FunctionData` can be GCed unsafe impl GarbageCollected for FunctionData { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"FunctionData" } } // Create a JavaScript function for synchronous FFI call to // the given symbol. fn make_sync_fn<'s>( scope: &mut v8::PinScope<'s, '_>, symbol: Box<Symbol>, ) -> v8::Local<'s, v8::Function> { let turbocall = if turbocall::is_compatible(&symbol) { match turbocall::compile_trampoline(&symbol) { Ok(trampoline) => { let turbocall = turbocall::make_template(&symbol, trampoline); Some(turbocall) } Err(e) => { log::warn!("Failed to compile FFI turbocall: {e}"); None } } } else { None }; let c_function = turbocall.as_ref().map(|turbocall| { v8::fast_api::CFunction::new( turbocall.trampoline.ptr(), &turbocall.c_function_info, ) }); let data = FunctionData { symbol, turbocall }; let data = deno_core::cppgc::make_cppgc_object(scope, data); let builder = v8::FunctionTemplate::builder(sync_fn_impl).data(data.into()); let func = if let Some(c_function) = c_function { builder.build_fast(scope, &[c_function]) } else { builder.build(scope) }; func.get_function(scope).unwrap() } fn sync_fn_impl<'s>( scope: &mut v8::PinScope<'s, '_>, args: v8::FunctionCallbackArguments<'s>, mut rv: v8::ReturnValue, ) { let data = deno_core::cppgc::try_unwrap_cppgc_object::<FunctionData>( scope, args.data(), ) .unwrap(); let out_buffer = match data.symbol.result_type { NativeType::Struct(_) => { let argc = args.length(); out_buffer_as_ptr( scope, Some( v8::Local::<v8::TypedArray>::try_from(args.get(argc - 1)).unwrap(), ), ) } _ => None, }; match crate::call::ffi_call_sync(scope, args, &data.symbol, out_buffer) { Ok(result) => { let result = // SAFETY: Same return type declared to libffi; trust user to have it right beyond that. unsafe { result.to_v8(scope, data.symbol.result_type.clone()) }; rv.set(result); } Err(err) => deno_core::error::throw_js_error_class(scope, &err), }; } // `path` is only used on Windows. #[allow(unused_variables)] pub(crate) fn format_error( e: dlopen2::Error, path: &std::path::Path, ) -> String { match e { #[cfg(target_os = "windows")] // This calls FormatMessageW with library path // as replacement for the insert sequences. // Unlike libstd which passes the FORMAT_MESSAGE_IGNORE_INSERTS // flag without any arguments. // // https://github.com/denoland/deno/issues/11632 dlopen2::Error::OpeningLibraryError(e) => { use std::os::windows::ffi::OsStrExt; use winapi::shared::minwindef::DWORD; use winapi::shared::winerror::ERROR_INSUFFICIENT_BUFFER; use winapi::um::errhandlingapi::GetLastError; use winapi::um::winbase::FORMAT_MESSAGE_ARGUMENT_ARRAY; use winapi::um::winbase::FORMAT_MESSAGE_FROM_SYSTEM; use winapi::um::winbase::FormatMessageW; use winapi::um::winnt::LANG_SYSTEM_DEFAULT; use winapi::um::winnt::MAKELANGID; use winapi::um::winnt::SUBLANG_SYS_DEFAULT; let err_num = match e.raw_os_error() { Some(err_num) => err_num, // This should never hit unless dlopen changes its error type. None => return e.to_string(), }; // Language ID (0x0800) let lang_id = MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT) as DWORD; let mut buf = vec![0; 500]; let path = path .as_os_str() .encode_wide() .chain(Some(0)) .collect::<Vec<_>>(); let arguments = [path.as_ptr()]; loop { // SAFETY: // winapi call to format the error message let length = unsafe { FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, std::ptr::null_mut(), err_num as DWORD, lang_id as DWORD, buf.as_mut_ptr(), buf.len() as DWORD, arguments.as_ptr() as _, ) }; if length == 0 { // SAFETY: // winapi call to get the last error message let err_num = unsafe { GetLastError() }; if err_num == ERROR_INSUFFICIENT_BUFFER { buf.resize(buf.len() * 2, 0); continue; } // Something went wrong, just return the original error. return e.to_string(); } let msg = String::from_utf16_lossy(&buf[..length as usize]); return msg; } } _ => e.to_string(), } } #[cfg(test)] mod tests { use serde_json::json; use super::ForeignFunction; use super::ForeignSymbol; use crate::symbol::NativeType; #[cfg(target_os = "windows")] #[test] fn test_format_error() { use super::format_error; // BAD_EXE_FORMAT let err = dlopen2::Error::OpeningLibraryError( std::io::Error::from_raw_os_error(0x000000C1), ); assert_eq!( format_error(err, &std::path::PathBuf::from("foo.dll")), "foo.dll is not a valid Win32 application.\r\n".to_string(), ); } /// Ensure that our custom serialize for ForeignSymbol is working using `serde_json`. #[test] fn test_serialize_foreign_symbol() { let symbol: ForeignSymbol = serde_json::from_value(json! {{ "name": "test", "type": "type is unused" }}) .expect("Failed to parse"); assert!(matches!(symbol, ForeignSymbol::ForeignStatic(..))); let symbol: ForeignSymbol = serde_json::from_value(json! {{ "name": "test", "parameters": ["i64"], "result": "bool" }}) .expect("Failed to parse"); if let ForeignSymbol::ForeignFunction(ForeignFunction { name: Some(expected_name), parameters, .. }) = symbol { assert_eq!(expected_name, "test"); assert_eq!(parameters, vec![NativeType::I64]); } else { panic!("Failed to parse ForeignFunction as expected"); } } #[test] fn test_serialize_foreign_symbol_failures() { let error = serde_json::from_value::<ForeignSymbol>(json! {{ "name": "test", "parameters": ["int"], "result": "bool" }}) .expect_err("Expected this to fail"); assert!(error.to_string().contains("expected one of")); let error = serde_json::from_value::<ForeignSymbol>(json! {{ "name": "test", "parameters": ["i64"], "result": "int" }}) .expect_err("Expected this to fail"); assert!(error.to_string().contains("expected one of")); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/ffi/callback.rs
ext/ffi/callback.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::ffi::c_void; use std::future::Future; use std::future::IntoFuture; use std::pin::Pin; use std::ptr; use std::ptr::NonNull; use std::rc::Rc; use std::sync::atomic; use std::sync::atomic::AtomicU32; use std::task::Poll; use deno_core::CancelFuture; use deno_core::CancelHandle; use deno_core::OpState; use deno_core::Resource; use deno_core::ResourceId; use deno_core::V8CrossThreadTaskSpawner; use deno_core::op2; use deno_core::v8; use deno_permissions::PermissionsContainer; use libffi::middle::Cif; use serde::Deserialize; use crate::ForeignFunction; use crate::symbol::NativeType; static THREAD_ID_COUNTER: AtomicU32 = AtomicU32::new(1); thread_local! { static LOCAL_THREAD_ID: RefCell<u32> = const { RefCell::new(0) }; } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum CallbackError { #[class(inherit)] #[error(transparent)] Resource(#[from] deno_core::error::ResourceError), #[class(inherit)] #[error(transparent)] Permission(#[from] deno_permissions::PermissionCheckError), #[class(inherit)] #[error(transparent)] Other(#[from] deno_error::JsErrorBox), } #[derive(Clone)] pub struct PtrSymbol { pub cif: libffi::middle::Cif, pub ptr: libffi::middle::CodePtr, } impl PtrSymbol { pub fn new( fn_ptr: *mut c_void, def: &ForeignFunction, ) -> Result<Self, CallbackError> { let ptr = libffi::middle::CodePtr::from_ptr(fn_ptr as _); let cif = libffi::middle::Cif::new( def .parameters .clone() .into_iter() .map(libffi::middle::Type::try_from) .collect::<Result<Vec<_>, _>>()?, def.result.clone().try_into()?, ); Ok(Self { cif, ptr }) } } #[allow(clippy::non_send_fields_in_send_ty)] // SAFETY: unsafe trait must have unsafe implementation unsafe impl Send for PtrSymbol {} // SAFETY: unsafe trait must have unsafe implementation unsafe impl Sync for PtrSymbol {} struct UnsafeCallbackResource { cancel: Rc<CancelHandle>, // Closure is never directly touched, but it keeps the C callback alive // until `close()` method is called. #[allow(dead_code)] closure: libffi::middle::Closure<'static>, info: *mut CallbackInfo, } impl Resource for UnsafeCallbackResource { fn name(&self) -> Cow<'_, str> { "unsafecallback".into() } fn close(self: Rc<Self>) { self.cancel.cancel(); } } struct CallbackInfo { pub async_work_sender: V8CrossThreadTaskSpawner, pub callback: NonNull<v8::Function>, pub context: NonNull<v8::Context>, pub parameters: Box<[NativeType]>, pub result: NativeType, pub thread_id: u32, } impl Future for CallbackInfo { type Output = (); fn poll( self: Pin<&mut Self>, _cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Self::Output> { // The future for the CallbackInfo never resolves: It can only be canceled. Poll::Pending } } struct TaskArgs { cif: NonNull<libffi::low::ffi_cif>, result: NonNull<c_void>, args: *const *const c_void, info: NonNull<CallbackInfo>, } // SAFETY: we know these are valid Send-safe pointers as they are for FFI unsafe impl Send for TaskArgs {} impl TaskArgs { fn run(&mut self, scope: &mut v8::PinScope<'_, '_>) { // SAFETY: making a call using Send-safe pointers turned back into references. We know the // lifetime of these will last because we block on the result of the spawn call. unsafe { do_ffi_callback( scope, self.cif.as_ref(), self.info.as_ref(), self.result.as_mut(), self.args, ) } } } unsafe extern "C" fn deno_ffi_callback( cif: &libffi::low::ffi_cif, result: &mut c_void, args: *const *const c_void, info: &CallbackInfo, ) { #[allow(clippy::undocumented_unsafe_blocks)] unsafe { LOCAL_THREAD_ID.with(|s| { if *s.borrow() == info.thread_id { // Call from main thread. If this callback is being triggered due to a // function call coming from Deno itself, then this callback will build // ontop of that stack. // If this callback is being triggered outside of Deno (for example from a // signal handler) then this will either create an empty new stack if // Deno currently has nothing running and is waiting for promises to resolve, // or will (very incorrectly) build ontop of whatever stack exists. // The callback will even be called through from a `while (true)` liveloop, but // it somehow cannot change the values that the loop sees, even if they both // refer the same `let bool_value`. let context: NonNull<v8::Context> = info.context; let context = std::mem::transmute::< NonNull<v8::Context>, v8::Local<v8::Context>, >(context); v8::callback_scope!(unsafe cb_scope, context); v8::scope!(scope, cb_scope); do_ffi_callback(scope, cif, info, result, args); } else { let async_work_sender = &info.async_work_sender; let mut args = TaskArgs { cif: NonNull::from(cif), result: NonNull::from(result), args, info: NonNull::from(info), }; async_work_sender.spawn_blocking(move |scope| { // We don't have a lot of choice here, so just print an unhandled exception message v8::tc_scope!(tc_scope, scope); args.run(tc_scope); if tc_scope.exception().is_some() { log::error!("Illegal unhandled exception in nonblocking callback"); } }); } }); } } unsafe fn do_ffi_callback( scope: &mut v8::PinScope<'_, '_>, cif: &libffi::low::ffi_cif, info: &CallbackInfo, result: &mut c_void, args: *const *const c_void, ) { #[allow(clippy::undocumented_unsafe_blocks)] unsafe { let callback: NonNull<v8::Function> = info.callback; let func = std::mem::transmute::< NonNull<v8::Function>, v8::Local<v8::Function>, >(callback); let result = result as *mut c_void; let vals: &[*const c_void] = std::slice::from_raw_parts(args, info.parameters.len()); let arg_types = std::slice::from_raw_parts(cif.arg_types, cif.nargs as usize); let mut params: Vec<v8::Local<v8::Value>> = vec![]; for ((index, native_type), val) in info.parameters.iter().enumerate().zip(vals) { let value: v8::Local<v8::Value> = match native_type { NativeType::Bool => { let value = *((*val) as *const bool); v8::Boolean::new(scope, value).into() } NativeType::F32 => { let value = *((*val) as *const f32); v8::Number::new(scope, value as f64).into() } NativeType::F64 => { let value = *((*val) as *const f64); v8::Number::new(scope, value).into() } NativeType::I8 => { let value = *((*val) as *const i8); v8::Integer::new(scope, value as i32).into() } NativeType::U8 => { let value = *((*val) as *const u8); v8::Integer::new_from_unsigned(scope, value as u32).into() } NativeType::I16 => { let value = *((*val) as *const i16); v8::Integer::new(scope, value as i32).into() } NativeType::U16 => { let value = *((*val) as *const u16); v8::Integer::new_from_unsigned(scope, value as u32).into() } NativeType::I32 => { let value = *((*val) as *const i32); v8::Integer::new(scope, value).into() } NativeType::U32 => { let value = *((*val) as *const u32); v8::Integer::new_from_unsigned(scope, value).into() } NativeType::I64 | NativeType::ISize => { let result = *((*val) as *const i64); v8::BigInt::new_from_i64(scope, result).into() } NativeType::U64 | NativeType::USize => { let result = *((*val) as *const u64); v8::BigInt::new_from_u64(scope, result).into() } NativeType::Pointer | NativeType::Buffer | NativeType::Function => { let result = *((*val) as *const *mut c_void); if result.is_null() { v8::null(scope).into() } else { v8::External::new(scope, result).into() } } NativeType::Struct(_) => { let size = arg_types[index].as_ref().unwrap().size; let ptr = (*val) as *const u8; let slice = std::slice::from_raw_parts(ptr, size); let boxed = Box::from(slice); let store = v8::ArrayBuffer::new_backing_store_from_boxed_slice(boxed); let ab = v8::ArrayBuffer::with_backing_store(scope, &store.make_shared()); let local_value: v8::Local<v8::Value> = v8::Uint8Array::new(scope, ab, 0, ab.byte_length()) .unwrap() .into(); local_value } NativeType::Void => unreachable!(), }; params.push(value); } let recv = v8::undefined(scope); let call_result = func.call(scope, recv.into(), &params); if call_result.is_none() { // JS function threw an exception. Set the return value to zero and return. // The exception continue propagating up the call chain when the event loop // resumes. match info.result { NativeType::Bool => { *(result as *mut bool) = false; } NativeType::U32 | NativeType::I32 => { // zero is equal for signed and unsigned alike *(result as *mut u32) = 0; } NativeType::F32 => { *(result as *mut f32) = 0.0; } NativeType::F64 => { *(result as *mut f64) = 0.0; } NativeType::U8 | NativeType::I8 => { // zero is equal for signed and unsigned alike *(result as *mut u8) = 0; } NativeType::U16 | NativeType::I16 => { // zero is equal for signed and unsigned alike *(result as *mut u16) = 0; } NativeType::Pointer | NativeType::Buffer | NativeType::Function | NativeType::U64 | NativeType::I64 => { *(result as *mut usize) = 0; } NativeType::Void => { // nop } _ => { unreachable!(); } }; return; } let value = call_result.unwrap(); match info.result { NativeType::Bool => { let value = if let Ok(value) = v8::Local::<v8::Boolean>::try_from(value) { value.is_true() } else { value.boolean_value(scope) }; *(result as *mut bool) = value; } NativeType::F32 => { let value = if let Ok(value) = v8::Local::<v8::Number>::try_from(value) { value.value() as f32 } else { // Fallthrough, probably UB. value .number_value(scope) .expect("Unable to deserialize result parameter.") as f32 }; *(result as *mut f32) = value; } NativeType::F64 => { let value = if let Ok(value) = v8::Local::<v8::Number>::try_from(value) { value.value() } else { // Fallthrough, probably UB. value .number_value(scope) .expect("Unable to deserialize result parameter.") }; *(result as *mut f64) = value; } NativeType::Buffer => { let pointer: *mut u8 = if let Ok(value) = v8::Local::<v8::ArrayBufferView>::try_from(value) { let byte_offset = value.byte_offset(); let pointer = value .buffer(scope) .expect("Unable to deserialize result parameter.") .data(); if let Some(non_null) = pointer { // SAFETY: Pointer is non-null, and V8 guarantees that the byte_offset // is within the buffer backing store. non_null.as_ptr().add(byte_offset) as *mut u8 } else { ptr::null_mut() } } else if let Ok(value) = v8::Local::<v8::ArrayBuffer>::try_from(value) { let pointer = value.data(); if let Some(non_null) = pointer { non_null.as_ptr() as *mut u8 } else { ptr::null_mut() } } else { ptr::null_mut() }; *(result as *mut *mut u8) = pointer; } NativeType::Pointer | NativeType::Function => { let pointer: *mut c_void = if let Ok(external) = v8::Local::<v8::External>::try_from(value) { external.value() } else { // TODO(@aapoalas): Start throwing errors into JS about invalid callback return values. ptr::null_mut() }; *(result as *mut *mut c_void) = pointer; } NativeType::I8 => { let value = if let Ok(value) = v8::Local::<v8::Int32>::try_from(value) { value.value() as i8 } else { // Fallthrough, essentially UB. value .int32_value(scope) .expect("Unable to deserialize result parameter.") as i8 }; *(result as *mut i8) = value; } NativeType::U8 => { let value = if let Ok(value) = v8::Local::<v8::Uint32>::try_from(value) { value.value() as u8 } else { // Fallthrough, essentially UB. value .uint32_value(scope) .expect("Unable to deserialize result parameter.") as u8 }; *(result as *mut u8) = value; } NativeType::I16 => { let value = if let Ok(value) = v8::Local::<v8::Int32>::try_from(value) { value.value() as i16 } else { // Fallthrough, essentially UB. value .int32_value(scope) .expect("Unable to deserialize result parameter.") as i16 }; *(result as *mut i16) = value; } NativeType::U16 => { let value = if let Ok(value) = v8::Local::<v8::Uint32>::try_from(value) { value.value() as u16 } else { // Fallthrough, essentially UB. value .uint32_value(scope) .expect("Unable to deserialize result parameter.") as u16 }; *(result as *mut u16) = value; } NativeType::I32 => { let value = if let Ok(value) = v8::Local::<v8::Int32>::try_from(value) { value.value() } else { // Fallthrough, essentially UB. value .int32_value(scope) .expect("Unable to deserialize result parameter.") }; *(result as *mut i32) = value; } NativeType::U32 => { let value = if let Ok(value) = v8::Local::<v8::Uint32>::try_from(value) { value.value() } else { // Fallthrough, essentially UB. value .uint32_value(scope) .expect("Unable to deserialize result parameter.") }; *(result as *mut u32) = value; } NativeType::I64 | NativeType::ISize => { if let Ok(value) = v8::Local::<v8::BigInt>::try_from(value) { *(result as *mut i64) = value.i64_value().0; } else if let Ok(value) = v8::Local::<v8::Int32>::try_from(value) { *(result as *mut i64) = value.value() as i64; } else if let Ok(value) = v8::Local::<v8::Number>::try_from(value) { *(result as *mut i64) = value.value() as i64; } else { *(result as *mut i64) = value .integer_value(scope) .expect("Unable to deserialize result parameter."); } } NativeType::U64 | NativeType::USize => { if let Ok(value) = v8::Local::<v8::BigInt>::try_from(value) { *(result as *mut u64) = value.u64_value().0; } else if let Ok(value) = v8::Local::<v8::Uint32>::try_from(value) { *(result as *mut u64) = value.value() as u64; } else if let Ok(value) = v8::Local::<v8::Number>::try_from(value) { *(result as *mut u64) = value.value() as u64; } else { *(result as *mut u64) = value .integer_value(scope) .expect("Unable to deserialize result parameter.") as u64; } } NativeType::Struct(_) => { let size; let pointer = if let Ok(value) = v8::Local::<v8::ArrayBufferView>::try_from(value) { let byte_offset = value.byte_offset(); let ab = value .buffer(scope) .expect("Unable to deserialize result parameter."); size = value.byte_length(); ab.data() .expect("Unable to deserialize result parameter.") .as_ptr() .add(byte_offset) } else if let Ok(value) = v8::Local::<v8::ArrayBuffer>::try_from(value) { size = value.byte_length(); value .data() .expect("Unable to deserialize result parameter.") .as_ptr() } else { panic!("Unable to deserialize result parameter."); }; std::ptr::copy_nonoverlapping( pointer as *mut u8, result as *mut u8, std::cmp::min(size, (*cif.rtype).size), ); } NativeType::Void => { // nop } }; } } #[op2(async)] pub fn op_ffi_unsafe_callback_ref( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<impl Future<Output = ()>, CallbackError> { let state = state.borrow(); let callback_resource = state.resource_table.get::<UnsafeCallbackResource>(rid)?; Ok(async move { let info: &mut CallbackInfo = // SAFETY: CallbackInfo pointer stays valid as long as the resource is still alive. unsafe { callback_resource.info.as_mut().unwrap() }; // Ignore cancellation rejection let _ = info .into_future() .or_cancel(callback_resource.cancel.clone()) .await; }) } #[derive(Deserialize)] pub struct RegisterCallbackArgs { parameters: Vec<NativeType>, result: NativeType, } #[op2(stack_trace)] pub fn op_ffi_unsafe_callback_create<'scope>( state: &mut OpState, scope: &mut v8::PinScope<'scope, '_>, #[serde] args: RegisterCallbackArgs, cb: v8::Local<v8::Function>, ) -> Result<v8::Local<'scope, v8::Value>, CallbackError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; let thread_id: u32 = LOCAL_THREAD_ID.with(|s| { let value = *s.borrow(); if value == 0 { let res = THREAD_ID_COUNTER.fetch_add(1, atomic::Ordering::SeqCst); s.replace(res); res } else { value } }); if thread_id == 0 { panic!("Isolate ID counter overflowed u32"); } let async_work_sender = state.borrow::<V8CrossThreadTaskSpawner>().clone(); let callback = v8::Global::new(scope, cb).into_raw(); let current_context = scope.get_current_context(); let context = v8::Global::new(scope, current_context).into_raw(); let info: *mut CallbackInfo = Box::leak(Box::new(CallbackInfo { async_work_sender, callback, context, parameters: args.parameters.clone().into(), result: args.result.clone(), thread_id, })); let cif = Cif::new( args .parameters .into_iter() .map(libffi::middle::Type::try_from) .collect::<Result<Vec<_>, _>>()?, libffi::middle::Type::try_from(args.result)?, ); // SAFETY: CallbackInfo is leaked, is not null and stays valid as long as the callback exists. let closure = libffi::middle::Closure::new(cif, deno_ffi_callback, unsafe { info.as_ref().unwrap() }); let ptr = *closure.code_ptr() as *mut c_void; let resource = UnsafeCallbackResource { cancel: CancelHandle::new_rc(), closure, info, }; let rid = state.resource_table.add(resource); let rid_local = v8::Integer::new_from_unsigned(scope, rid); let ptr_local: v8::Local<v8::Value> = v8::External::new(scope, ptr).into(); let array = v8::Array::new(scope, 2); array.set_index(scope, 0, rid_local.into()); array.set_index(scope, 1, ptr_local); let array_value: v8::Local<v8::Value> = array.into(); Ok(array_value) } #[op2(fast)] pub fn op_ffi_unsafe_callback_close( state: &mut OpState, scope: &mut v8::PinScope<'_, '_>, #[smi] rid: ResourceId, ) -> Result<(), CallbackError> { // SAFETY: This drops the closure and the callback info associated with it. // Any retained function pointers to the closure become dangling pointers. // It is up to the user to know that it is safe to call the `close()` on the // UnsafeCallback instance. unsafe { let callback_resource = state.resource_table.take::<UnsafeCallbackResource>(rid)?; let info = Box::from_raw(callback_resource.info); let _ = v8::Global::from_raw(scope, info.callback); let _ = v8::Global::from_raw(scope, info.context); callback_resource.close(); } Ok(()) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/ffi/static.rs
ext/ffi/static.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ptr; use deno_core::OpState; use deno_core::ResourceId; use deno_core::op2; use deno_core::v8; use crate::dlfcn::DynamicLibraryResource; use crate::symbol::NativeType; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum StaticError { #[class(inherit)] #[error(transparent)] Dlfcn(super::DlfcnError), #[class(type)] #[error("Invalid FFI static type 'void'")] InvalidTypeVoid, #[class(type)] #[error("Invalid FFI static type 'struct'")] InvalidTypeStruct, #[class(inherit)] #[error(transparent)] Resource(#[from] deno_core::error::ResourceError), } #[op2] pub fn op_ffi_get_static<'scope>( scope: &mut v8::PinScope<'scope, '_>, state: &mut OpState, #[smi] rid: ResourceId, #[string] name: String, #[serde] static_type: NativeType, optional: bool, ) -> Result<v8::Local<'scope, v8::Value>, StaticError> { let resource = state.resource_table.get::<DynamicLibraryResource>(rid)?; let data_ptr = match resource.get_static(name) { Ok(data_ptr) => data_ptr, Err(err) => { if optional { let null: v8::Local<v8::Value> = v8::null(scope).into(); return Ok(null); } else { return Err(StaticError::Dlfcn(err)); } } }; Ok(match static_type { NativeType::Void => { return Err(StaticError::InvalidTypeVoid); } NativeType::Bool => { // SAFETY: ptr is user provided let result = unsafe { ptr::read_unaligned(data_ptr as *const bool) }; let boolean: v8::Local<v8::Value> = v8::Boolean::new(scope, result).into(); boolean } NativeType::U8 => { // SAFETY: ptr is user provided let result = unsafe { ptr::read_unaligned(data_ptr as *const u8) }; let number: v8::Local<v8::Value> = v8::Integer::new_from_unsigned(scope, result as u32).into(); number } NativeType::I8 => { // SAFETY: ptr is user provided let result = unsafe { ptr::read_unaligned(data_ptr as *const i8) }; let number: v8::Local<v8::Value> = v8::Integer::new(scope, result as i32).into(); number } NativeType::U16 => { // SAFETY: ptr is user provided let result = unsafe { ptr::read_unaligned(data_ptr as *const u16) }; let number: v8::Local<v8::Value> = v8::Integer::new_from_unsigned(scope, result as u32).into(); number } NativeType::I16 => { // SAFETY: ptr is user provided let result = unsafe { ptr::read_unaligned(data_ptr as *const i16) }; let number: v8::Local<v8::Value> = v8::Integer::new(scope, result as i32).into(); number } NativeType::U32 => { // SAFETY: ptr is user provided let result = unsafe { ptr::read_unaligned(data_ptr as *const u32) }; let number: v8::Local<v8::Value> = v8::Integer::new_from_unsigned(scope, result).into(); number } NativeType::I32 => { // SAFETY: ptr is user provided let result = unsafe { ptr::read_unaligned(data_ptr as *const i32) }; let number: v8::Local<v8::Value> = v8::Integer::new(scope, result).into(); number } NativeType::U64 => { // SAFETY: ptr is user provided let result = unsafe { ptr::read_unaligned(data_ptr as *const u64) }; let integer: v8::Local<v8::Value> = v8::BigInt::new_from_u64(scope, result).into(); integer } NativeType::I64 => { // SAFETY: ptr is user provided let result = unsafe { ptr::read_unaligned(data_ptr as *const i64) }; let integer: v8::Local<v8::Value> = v8::BigInt::new_from_i64(scope, result).into(); integer } NativeType::USize => { // SAFETY: ptr is user provided let result = unsafe { ptr::read_unaligned(data_ptr as *const usize) }; let integer: v8::Local<v8::Value> = v8::BigInt::new_from_u64(scope, result as u64).into(); integer } NativeType::ISize => { // SAFETY: ptr is user provided let result = unsafe { ptr::read_unaligned(data_ptr as *const isize) }; let integer: v8::Local<v8::Value> = v8::BigInt::new_from_i64(scope, result as i64).into(); integer } NativeType::F32 => { // SAFETY: ptr is user provided let result = unsafe { ptr::read_unaligned(data_ptr as *const f32) }; let number: v8::Local<v8::Value> = v8::Number::new(scope, result as f64).into(); number } NativeType::F64 => { // SAFETY: ptr is user provided let result = unsafe { ptr::read_unaligned(data_ptr as *const f64) }; let number: v8::Local<v8::Value> = v8::Number::new(scope, result).into(); number } NativeType::Pointer | NativeType::Function | NativeType::Buffer => { let external: v8::Local<v8::Value> = v8::External::new(scope, data_ptr).into(); external } NativeType::Struct(_) => { return Err(StaticError::InvalidTypeStruct); } }) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/ffi/ir.rs
ext/ffi/ir.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ffi::c_void; use std::ptr; use deno_core::v8; use libffi::middle::Arg; use crate::symbol::NativeType; #[derive(Debug, thiserror::Error, deno_error::JsError)] #[class(type)] pub enum IRError { #[error("Invalid FFI u8 type, expected boolean")] InvalidU8ExpectedBoolean, #[error("Invalid FFI u8 type, expected unsigned integer")] InvalidU8ExpectedUnsignedInteger, #[error("Invalid FFI i8 type, expected integer")] InvalidI8, #[error("Invalid FFI u16 type, expected unsigned integer")] InvalidU16, #[error("Invalid FFI i16 type, expected integer")] InvalidI16, #[error("Invalid FFI u32 type, expected unsigned integer")] InvalidU32, #[error("Invalid FFI i32 type, expected integer")] InvalidI32, #[error("Invalid FFI u64 type, expected unsigned integer")] InvalidU64, #[error("Invalid FFI i64 type, expected integer")] InvalidI64, #[error("Invalid FFI usize type, expected unsigned integer")] InvalidUsize, #[error("Invalid FFI isize type, expected integer")] InvalidIsize, #[error("Invalid FFI f32 type, expected number")] InvalidF32, #[error("Invalid FFI f64 type, expected number")] InvalidF64, #[error("Invalid FFI pointer type, expected null, or External")] InvalidPointerType, #[error( "Invalid FFI buffer type, expected null, ArrayBuffer, or ArrayBufferView" )] InvalidBufferType, #[error("Invalid FFI ArrayBufferView, expected data in the buffer")] InvalidArrayBufferView, #[error("Invalid FFI ArrayBuffer, expected data in buffer")] InvalidArrayBuffer, #[error("Invalid FFI struct type, expected ArrayBuffer, or ArrayBufferView")] InvalidStructType, #[error("Invalid FFI function type, expected null, or External")] InvalidFunctionType, } pub struct OutBuffer(pub *mut u8); // SAFETY: OutBuffer is allocated by us in 00_ffi.js and is guaranteed to be // only used for the purpose of writing return value of structs. unsafe impl Send for OutBuffer {} // SAFETY: See above unsafe impl Sync for OutBuffer {} pub fn out_buffer_as_ptr( scope: &mut v8::PinScope<'_, '_>, out_buffer: Option<v8::Local<v8::TypedArray>>, ) -> Option<OutBuffer> { match out_buffer { Some(out_buffer) => { let ab = out_buffer.buffer(scope).unwrap(); ab.data() .map(|non_null| OutBuffer(non_null.as_ptr() as *mut u8)) } None => None, } } /// Intermediate format for easy translation from NativeType + V8 value /// to libffi argument types. #[repr(C)] pub union NativeValue { pub void_value: (), pub bool_value: bool, pub u8_value: u8, pub i8_value: i8, pub u16_value: u16, pub i16_value: i16, pub u32_value: u32, pub i32_value: i32, pub u64_value: u64, pub i64_value: i64, pub usize_value: usize, pub isize_value: isize, pub f32_value: f32, pub f64_value: f64, pub pointer: *mut c_void, } impl NativeValue { pub unsafe fn as_arg(&self, native_type: &NativeType) -> Arg { #[allow(clippy::undocumented_unsafe_blocks)] unsafe { match native_type { NativeType::Void => unreachable!(), NativeType::Bool => Arg::new(&self.bool_value), NativeType::U8 => Arg::new(&self.u8_value), NativeType::I8 => Arg::new(&self.i8_value), NativeType::U16 => Arg::new(&self.u16_value), NativeType::I16 => Arg::new(&self.i16_value), NativeType::U32 => Arg::new(&self.u32_value), NativeType::I32 => Arg::new(&self.i32_value), NativeType::U64 => Arg::new(&self.u64_value), NativeType::I64 => Arg::new(&self.i64_value), NativeType::USize => Arg::new(&self.usize_value), NativeType::ISize => Arg::new(&self.isize_value), NativeType::F32 => Arg::new(&self.f32_value), NativeType::F64 => Arg::new(&self.f64_value), NativeType::Pointer | NativeType::Buffer | NativeType::Function => { Arg::new(&self.pointer) } NativeType::Struct(_) => Arg::new(&*self.pointer), } } } // SAFETY: native_type must correspond to the type of value represented by the union field #[inline] pub unsafe fn to_v8<'scope>( &self, scope: &mut v8::PinScope<'scope, '_>, native_type: NativeType, ) -> v8::Local<'scope, v8::Value> { #[allow(clippy::undocumented_unsafe_blocks)] unsafe { match native_type { NativeType::Void => v8::undefined(scope).into(), NativeType::Bool => v8::Boolean::new(scope, self.bool_value).into(), NativeType::U8 => { v8::Integer::new_from_unsigned(scope, self.u8_value as u32).into() } NativeType::I8 => v8::Integer::new(scope, self.i8_value as i32).into(), NativeType::U16 => { v8::Integer::new_from_unsigned(scope, self.u16_value as u32).into() } NativeType::I16 => { v8::Integer::new(scope, self.i16_value as i32).into() } NativeType::U32 => { v8::Integer::new_from_unsigned(scope, self.u32_value).into() } NativeType::I32 => v8::Integer::new(scope, self.i32_value).into(), NativeType::U64 => { v8::BigInt::new_from_u64(scope, self.u64_value).into() } NativeType::I64 => { v8::BigInt::new_from_i64(scope, self.i64_value).into() } NativeType::USize => { v8::BigInt::new_from_u64(scope, self.usize_value as u64).into() } NativeType::ISize => { v8::BigInt::new_from_i64(scope, self.isize_value as i64).into() } NativeType::F32 => v8::Number::new(scope, self.f32_value as f64).into(), NativeType::F64 => v8::Number::new(scope, self.f64_value).into(), NativeType::Pointer | NativeType::Buffer | NativeType::Function => { let local_value: v8::Local<v8::Value> = if self.pointer.is_null() { v8::null(scope).into() } else { v8::External::new(scope, self.pointer).into() }; local_value } NativeType::Struct(_) => v8::null(scope).into(), } } } } // SAFETY: unsafe trait must have unsafe implementation unsafe impl Send for NativeValue {} #[inline] pub fn ffi_parse_bool_arg( arg: v8::Local<v8::Value>, ) -> Result<NativeValue, IRError> { let bool_value = v8::Local::<v8::Boolean>::try_from(arg) .map_err(|_| IRError::InvalidU8ExpectedBoolean)? .is_true(); Ok(NativeValue { bool_value }) } #[inline] pub fn ffi_parse_u8_arg( arg: v8::Local<v8::Value>, ) -> Result<NativeValue, IRError> { let u8_value = v8::Local::<v8::Uint32>::try_from(arg) .map_err(|_| IRError::InvalidU8ExpectedUnsignedInteger)? .value() as u8; Ok(NativeValue { u8_value }) } #[inline] pub fn ffi_parse_i8_arg( arg: v8::Local<v8::Value>, ) -> Result<NativeValue, IRError> { let i8_value = v8::Local::<v8::Int32>::try_from(arg) .map_err(|_| IRError::InvalidI8)? .value() as i8; Ok(NativeValue { i8_value }) } #[inline] pub fn ffi_parse_u16_arg( arg: v8::Local<v8::Value>, ) -> Result<NativeValue, IRError> { let u16_value = v8::Local::<v8::Uint32>::try_from(arg) .map_err(|_| IRError::InvalidU16)? .value() as u16; Ok(NativeValue { u16_value }) } #[inline] pub fn ffi_parse_i16_arg( arg: v8::Local<v8::Value>, ) -> Result<NativeValue, IRError> { let i16_value = v8::Local::<v8::Int32>::try_from(arg) .map_err(|_| IRError::InvalidI16)? .value() as i16; Ok(NativeValue { i16_value }) } #[inline] pub fn ffi_parse_u32_arg( arg: v8::Local<v8::Value>, ) -> Result<NativeValue, IRError> { let u32_value = v8::Local::<v8::Uint32>::try_from(arg) .map_err(|_| IRError::InvalidU32)? .value(); Ok(NativeValue { u32_value }) } #[inline] pub fn ffi_parse_i32_arg( arg: v8::Local<v8::Value>, ) -> Result<NativeValue, IRError> { let i32_value = v8::Local::<v8::Int32>::try_from(arg) .map_err(|_| IRError::InvalidI32)? .value(); Ok(NativeValue { i32_value }) } #[inline] pub fn ffi_parse_u64_arg( scope: &mut v8::PinScope<'_, '_>, arg: v8::Local<v8::Value>, ) -> Result<NativeValue, IRError> { // Order of checking: // 1. BigInt: Uncommon and not supported by Fast API, so optimise slow call for this case. // 2. Number: Common, supported by Fast API, so let that be the optimal case. let u64_value: u64 = if let Ok(value) = v8::Local::<v8::BigInt>::try_from(arg) { value.u64_value().0 } else if let Ok(value) = v8::Local::<v8::Number>::try_from(arg) { value.integer_value(scope).unwrap() as u64 } else { return Err(IRError::InvalidU64); }; Ok(NativeValue { u64_value }) } #[inline] pub fn ffi_parse_i64_arg( scope: &mut v8::PinScope<'_, '_>, arg: v8::Local<v8::Value>, ) -> Result<NativeValue, IRError> { // Order of checking: // 1. BigInt: Uncommon and not supported by Fast API, so optimise slow call for this case. // 2. Number: Common, supported by Fast API, so let that be the optimal case. let i64_value: i64 = if let Ok(value) = v8::Local::<v8::BigInt>::try_from(arg) { value.i64_value().0 } else if let Ok(value) = v8::Local::<v8::Number>::try_from(arg) { value.integer_value(scope).unwrap() } else { return Err(IRError::InvalidI64); }; Ok(NativeValue { i64_value }) } #[inline] pub fn ffi_parse_usize_arg( scope: &mut v8::PinScope<'_, '_>, arg: v8::Local<v8::Value>, ) -> Result<NativeValue, IRError> { // Order of checking: // 1. BigInt: Uncommon and not supported by Fast API, so optimise slow call for this case. // 2. Number: Common, supported by Fast API, so let that be the optimal case. let usize_value: usize = if let Ok(value) = v8::Local::<v8::BigInt>::try_from(arg) { value.u64_value().0 as usize } else if let Ok(value) = v8::Local::<v8::Number>::try_from(arg) { value.integer_value(scope).unwrap() as usize } else { return Err(IRError::InvalidUsize); }; Ok(NativeValue { usize_value }) } #[inline] pub fn ffi_parse_isize_arg( scope: &mut v8::PinScope<'_, '_>, arg: v8::Local<v8::Value>, ) -> Result<NativeValue, IRError> { // Order of checking: // 1. BigInt: Uncommon and not supported by Fast API, so optimise slow call for this case. // 2. Number: Common, supported by Fast API, so let that be the optimal case. let isize_value: isize = if let Ok(value) = v8::Local::<v8::BigInt>::try_from(arg) { value.i64_value().0 as isize } else if let Ok(value) = v8::Local::<v8::Number>::try_from(arg) { value.integer_value(scope).unwrap() as isize } else { return Err(IRError::InvalidIsize); }; Ok(NativeValue { isize_value }) } #[inline] pub fn ffi_parse_f32_arg( arg: v8::Local<v8::Value>, ) -> Result<NativeValue, IRError> { let f32_value = v8::Local::<v8::Number>::try_from(arg) .map_err(|_| IRError::InvalidF32)? .value() as f32; Ok(NativeValue { f32_value }) } #[inline] pub fn ffi_parse_f64_arg( arg: v8::Local<v8::Value>, ) -> Result<NativeValue, IRError> { let f64_value = v8::Local::<v8::Number>::try_from(arg) .map_err(|_| IRError::InvalidF64)? .value(); Ok(NativeValue { f64_value }) } #[inline] pub fn ffi_parse_pointer_arg( _scope: &mut v8::PinScope<'_, '_>, arg: v8::Local<v8::Value>, ) -> Result<NativeValue, IRError> { let pointer = if let Ok(value) = v8::Local::<v8::External>::try_from(arg) { value.value() } else if arg.is_null() { ptr::null_mut() } else { return Err(IRError::InvalidPointerType); }; Ok(NativeValue { pointer }) } #[inline] pub fn parse_buffer_arg( arg: v8::Local<v8::Value>, ) -> Result<*mut c_void, IRError> { // Order of checking: // 1. ArrayBuffer: Fairly common and not supported by Fast API, optimise this case. // 2. ArrayBufferView: Common and supported by Fast API // 5. Null: Very uncommon / can be represented by a 0. if let Ok(value) = v8::Local::<v8::ArrayBuffer>::try_from(arg) { Ok(value.data().map(|p| p.as_ptr()).unwrap_or(ptr::null_mut())) } else if let Ok(value) = v8::Local::<v8::ArrayBufferView>::try_from(arg) { const { // We don't keep `buffer` around when this function returns, // so assert that it will be unused. assert!(deno_core::v8::TYPED_ARRAY_MAX_SIZE_IN_HEAP == 0); } let mut buffer = [0; deno_core::v8::TYPED_ARRAY_MAX_SIZE_IN_HEAP]; // SAFETY: `buffer` is unused due to above, returned pointer is not // dereferenced by rust code, and we keep it alive at least as long // as the turbocall. let (ptr, len) = unsafe { value.get_contents_raw_parts(&mut buffer) }; if ptr == buffer.as_mut_ptr() { // Empty TypedArray instances can hit this path because their base pointer // isn't cleared properly: https://issues.chromium.org/issues/40643872 debug_assert_eq!(len, 0); Ok(ptr::null_mut()) } else { Ok(ptr as _) } } else if arg.is_null() { Ok(ptr::null_mut()) } else { Err(IRError::InvalidBufferType) } } #[inline] pub fn ffi_parse_buffer_arg( arg: v8::Local<v8::Value>, ) -> Result<NativeValue, IRError> { let pointer = parse_buffer_arg(arg)?; Ok(NativeValue { pointer }) } #[inline] pub fn ffi_parse_struct_arg( scope: &mut v8::PinScope<'_, '_>, arg: v8::Local<v8::Value>, ) -> Result<NativeValue, IRError> { // Order of checking: // 1. ArrayBuffer: Fairly common and not supported by Fast API, optimise this case. // 2. ArrayBufferView: Common and supported by Fast API let pointer = if let Ok(value) = v8::Local::<v8::ArrayBuffer>::try_from(arg) { if let Some(non_null) = value.data() { non_null.as_ptr() } else { return Err(IRError::InvalidArrayBuffer); } } else if let Ok(value) = v8::Local::<v8::ArrayBufferView>::try_from(arg) { let byte_offset = value.byte_offset(); let pointer = value .buffer(scope) .ok_or(IRError::InvalidArrayBufferView)? .data(); if let Some(non_null) = pointer { // SAFETY: Pointer is non-null, and V8 guarantees that the byte_offset // is within the buffer backing store. unsafe { non_null.as_ptr().add(byte_offset) } } else { return Err(IRError::InvalidArrayBufferView); } } else { return Err(IRError::InvalidStructType); }; Ok(NativeValue { pointer }) } #[inline] pub fn ffi_parse_function_arg( _scope: &mut v8::PinScope<'_, '_>, arg: v8::Local<v8::Value>, ) -> Result<NativeValue, IRError> { let pointer = if let Ok(value) = v8::Local::<v8::External>::try_from(arg) { value.value() } else if arg.is_null() { ptr::null_mut() } else { return Err(IRError::InvalidFunctionType); }; Ok(NativeValue { pointer }) } pub fn ffi_parse_args<'scope>( scope: &mut v8::PinScope<'scope, '_>, args: v8::Local<v8::Array>, parameter_types: &[NativeType], ) -> Result<Vec<NativeValue>, IRError> where 'scope: 'scope, { if parameter_types.is_empty() { return Ok(vec![]); } let mut ffi_args: Vec<NativeValue> = Vec::with_capacity(parameter_types.len()); for (index, native_type) in parameter_types.iter().enumerate() { let value = args.get_index(scope, index as u32).unwrap(); match native_type { NativeType::Bool => { ffi_args.push(ffi_parse_bool_arg(value)?); } NativeType::U8 => { ffi_args.push(ffi_parse_u8_arg(value)?); } NativeType::I8 => { ffi_args.push(ffi_parse_i8_arg(value)?); } NativeType::U16 => { ffi_args.push(ffi_parse_u16_arg(value)?); } NativeType::I16 => { ffi_args.push(ffi_parse_i16_arg(value)?); } NativeType::U32 => { ffi_args.push(ffi_parse_u32_arg(value)?); } NativeType::I32 => { ffi_args.push(ffi_parse_i32_arg(value)?); } NativeType::U64 => { ffi_args.push(ffi_parse_u64_arg(scope, value)?); } NativeType::I64 => { ffi_args.push(ffi_parse_i64_arg(scope, value)?); } NativeType::USize => { ffi_args.push(ffi_parse_usize_arg(scope, value)?); } NativeType::ISize => { ffi_args.push(ffi_parse_isize_arg(scope, value)?); } NativeType::F32 => { ffi_args.push(ffi_parse_f32_arg(value)?); } NativeType::F64 => { ffi_args.push(ffi_parse_f64_arg(value)?); } NativeType::Buffer => { ffi_args.push(ffi_parse_buffer_arg(value)?); } NativeType::Struct(_) => { ffi_args.push(ffi_parse_struct_arg(scope, value)?); } NativeType::Pointer => { ffi_args.push(ffi_parse_pointer_arg(scope, value)?); } NativeType::Function => { ffi_args.push(ffi_parse_function_arg(scope, value)?); } NativeType::Void => { unreachable!(); } } } Ok(ffi_args) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/ffi/repr.rs
ext/ffi/repr.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ffi::CStr; use std::ffi::c_char; use std::ffi::c_void; use std::ptr; use deno_core::OpState; use deno_core::op2; use deno_core::v8; use deno_permissions::PermissionsContainer; #[derive(Debug, thiserror::Error, deno_error::JsError)] #[class(type)] pub enum ReprError { #[error("Invalid pointer to offset, pointer is null")] InvalidOffset, #[error("Invalid ArrayBuffer pointer, pointer is null")] InvalidArrayBuffer, #[error("Destination length is smaller than source length")] DestinationLengthTooShort, #[error("Invalid CString pointer, pointer is null")] InvalidCString, #[error("Invalid CString pointer, string exceeds max length")] CStringTooLong, #[error("Invalid bool pointer, pointer is null")] InvalidBool, #[error("Invalid u8 pointer, pointer is null")] InvalidU8, #[error("Invalid i8 pointer, pointer is null")] InvalidI8, #[error("Invalid u16 pointer, pointer is null")] InvalidU16, #[error("Invalid i16 pointer, pointer is null")] InvalidI16, #[error("Invalid u32 pointer, pointer is null")] InvalidU32, #[error("Invalid i32 pointer, pointer is null")] InvalidI32, #[error("Invalid u64 pointer, pointer is null")] InvalidU64, #[error("Invalid i64 pointer, pointer is null")] InvalidI64, #[error("Invalid f32 pointer, pointer is null")] InvalidF32, #[error("Invalid f64 pointer, pointer is null")] InvalidF64, #[error("Invalid pointer pointer, pointer is null")] InvalidPointer, #[class(inherit)] #[error(transparent)] Permission(#[from] deno_permissions::PermissionCheckError), } #[op2(fast, stack_trace)] pub fn op_ffi_ptr_create( state: &mut OpState, #[bigint] ptr_number: usize, ) -> Result<*mut c_void, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; Ok(ptr_number as *mut c_void) } #[op2(fast, stack_trace)] pub fn op_ffi_ptr_equals( state: &mut OpState, a: *const c_void, b: *const c_void, ) -> Result<bool, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; Ok(a == b) } #[op2(stack_trace)] pub fn op_ffi_ptr_of( state: &mut OpState, #[anybuffer] buf: *const u8, ) -> Result<*mut c_void, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; Ok(buf as *mut c_void) } #[op2(fast, stack_trace)] pub fn op_ffi_ptr_of_exact( state: &mut OpState, buf: v8::Local<v8::ArrayBufferView>, ) -> Result<*mut c_void, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; let Some(buf) = buf.get_backing_store() else { return Ok(0 as _); }; let Some(buf) = buf.data() else { return Ok(0 as _); }; Ok(buf.as_ptr() as _) } #[op2(fast, stack_trace)] pub fn op_ffi_ptr_offset( state: &mut OpState, ptr: *mut c_void, #[number] offset: isize, ) -> Result<*mut c_void, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; if ptr.is_null() { return Err(ReprError::InvalidOffset); } // TODO(mmastrac): Create a RawPointer that can safely do pointer math. // SAFETY: Using `ptr.offset` is *actually unsafe* and has generated UB, but our FFI code relies on this working so we're going to // try and ask the compiler to be less undefined here by using `ptr.wrapping_offset`. Ok(ptr.wrapping_offset(offset)) } unsafe extern "C" fn noop_deleter_callback( _data: *mut c_void, _byte_length: usize, _deleter_data: *mut c_void, ) { } #[op2(fast, stack_trace)] #[bigint] pub fn op_ffi_ptr_value( state: &mut OpState, ptr: *mut c_void, ) -> Result<usize, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; Ok(ptr as usize) } #[op2(stack_trace)] pub fn op_ffi_get_buf<'scope>( scope: &mut v8::PinScope<'scope, '_>, state: &mut OpState, ptr: *mut c_void, #[number] offset: isize, #[number] len: usize, ) -> Result<v8::Local<'scope, v8::ArrayBuffer>, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; if ptr.is_null() { return Err(ReprError::InvalidArrayBuffer); } // SAFETY: Trust the user to have provided a real pointer, offset, and a valid matching size to it. Since this is a foreign pointer, we should not do any deletion. let backing_store = unsafe { v8::ArrayBuffer::new_backing_store_from_ptr( ptr.offset(offset), len, noop_deleter_callback, ptr::null_mut(), ) } .make_shared(); let array_buffer = v8::ArrayBuffer::with_backing_store(scope, &backing_store); Ok(array_buffer) } #[op2(stack_trace)] pub fn op_ffi_buf_copy_into( state: &mut OpState, src: *mut c_void, #[number] offset: isize, #[anybuffer] dst: &mut [u8], #[number] len: usize, ) -> Result<(), ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; if src.is_null() { Err(ReprError::InvalidArrayBuffer) } else if dst.len() < len { Err(ReprError::DestinationLengthTooShort) } else { let src = src as *const c_void; // SAFETY: src and offset are user defined. // dest is properly aligned and is valid for writes of len * size_of::<T>() bytes. unsafe { ptr::copy::<u8>(src.offset(offset) as *const u8, dst.as_mut_ptr(), len) }; Ok(()) } } #[op2(stack_trace)] pub fn op_ffi_cstr_read<'scope>( scope: &mut v8::PinScope<'scope, '_>, state: &mut OpState, ptr: *mut c_void, #[number] offset: isize, ) -> Result<v8::Local<'scope, v8::String>, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; if ptr.is_null() { return Err(ReprError::InvalidCString); } let cstr = // SAFETY: Pointer and offset are user provided. unsafe { CStr::from_ptr(ptr.offset(offset) as *const c_char) }.to_bytes(); #[allow(clippy::unnecessary_lazy_evaluations)] let value = v8::String::new_from_utf8(scope, cstr, v8::NewStringType::Normal) .ok_or_else(|| ReprError::CStringTooLong)?; Ok(value) } #[op2(fast, stack_trace)] pub fn op_ffi_read_bool( state: &mut OpState, ptr: *mut c_void, #[number] offset: isize, ) -> Result<bool, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; if ptr.is_null() { return Err(ReprError::InvalidBool); } // SAFETY: ptr and offset are user provided. Ok(unsafe { ptr::read_unaligned::<bool>(ptr.offset(offset) as *const bool) }) } #[op2(fast, stack_trace)] pub fn op_ffi_read_u8( state: &mut OpState, ptr: *mut c_void, #[number] offset: isize, ) -> Result<u32, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; if ptr.is_null() { return Err(ReprError::InvalidU8); } // SAFETY: ptr and offset are user provided. Ok(unsafe { ptr::read_unaligned::<u8>(ptr.offset(offset) as *const u8) as u32 }) } #[op2(fast, stack_trace)] pub fn op_ffi_read_i8( state: &mut OpState, ptr: *mut c_void, #[number] offset: isize, ) -> Result<i32, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; if ptr.is_null() { return Err(ReprError::InvalidI8); } // SAFETY: ptr and offset are user provided. Ok(unsafe { ptr::read_unaligned::<i8>(ptr.offset(offset) as *const i8) as i32 }) } #[op2(fast, stack_trace)] pub fn op_ffi_read_u16( state: &mut OpState, ptr: *mut c_void, #[number] offset: isize, ) -> Result<u32, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; if ptr.is_null() { return Err(ReprError::InvalidU16); } // SAFETY: ptr and offset are user provided. Ok(unsafe { ptr::read_unaligned::<u16>(ptr.offset(offset) as *const u16) as u32 }) } #[op2(fast, stack_trace)] pub fn op_ffi_read_i16( state: &mut OpState, ptr: *mut c_void, #[number] offset: isize, ) -> Result<i32, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; if ptr.is_null() { return Err(ReprError::InvalidI16); } // SAFETY: ptr and offset are user provided. Ok(unsafe { ptr::read_unaligned::<i16>(ptr.offset(offset) as *const i16) as i32 }) } #[op2(fast, stack_trace)] pub fn op_ffi_read_u32( state: &mut OpState, ptr: *mut c_void, #[number] offset: isize, ) -> Result<u32, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; if ptr.is_null() { return Err(ReprError::InvalidU32); } // SAFETY: ptr and offset are user provided. Ok(unsafe { ptr::read_unaligned::<u32>(ptr.offset(offset) as *const u32) }) } #[op2(fast, stack_trace)] pub fn op_ffi_read_i32( state: &mut OpState, ptr: *mut c_void, #[number] offset: isize, ) -> Result<i32, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; if ptr.is_null() { return Err(ReprError::InvalidI32); } // SAFETY: ptr and offset are user provided. Ok(unsafe { ptr::read_unaligned::<i32>(ptr.offset(offset) as *const i32) }) } #[op2(fast, stack_trace)] #[bigint] pub fn op_ffi_read_u64( state: &mut OpState, ptr: *mut c_void, // Note: The representation of 64-bit integers is function-wide. We cannot // choose to take this parameter as a number while returning a bigint. #[bigint] offset: isize, ) -> Result<u64, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; if ptr.is_null() { return Err(ReprError::InvalidU64); } let value = // SAFETY: ptr and offset are user provided. unsafe { ptr::read_unaligned::<u64>(ptr.offset(offset) as *const u64) }; Ok(value) } #[op2(fast, stack_trace)] #[bigint] pub fn op_ffi_read_i64( state: &mut OpState, ptr: *mut c_void, // Note: The representation of 64-bit integers is function-wide. We cannot // choose to take this parameter as a number while returning a bigint. #[bigint] offset: isize, ) -> Result<i64, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; if ptr.is_null() { return Err(ReprError::InvalidI64); } let value = // SAFETY: ptr and offset are user provided. unsafe { ptr::read_unaligned::<i64>(ptr.offset(offset) as *const i64) }; // SAFETY: Length and alignment of out slice were asserted to be correct. Ok(value) } #[op2(fast, stack_trace)] pub fn op_ffi_read_f32( state: &mut OpState, ptr: *mut c_void, #[number] offset: isize, ) -> Result<f32, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; if ptr.is_null() { return Err(ReprError::InvalidF32); } // SAFETY: ptr and offset are user provided. Ok(unsafe { ptr::read_unaligned::<f32>(ptr.offset(offset) as *const f32) }) } #[op2(fast, stack_trace)] pub fn op_ffi_read_f64( state: &mut OpState, ptr: *mut c_void, #[number] offset: isize, ) -> Result<f64, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; if ptr.is_null() { return Err(ReprError::InvalidF64); } // SAFETY: ptr and offset are user provided. Ok(unsafe { ptr::read_unaligned::<f64>(ptr.offset(offset) as *const f64) }) } #[op2(fast, stack_trace)] pub fn op_ffi_read_ptr( state: &mut OpState, ptr: *mut c_void, #[number] offset: isize, ) -> Result<*mut c_void, ReprError> { let permissions = state.borrow_mut::<PermissionsContainer>(); permissions.check_ffi_partial_no_path()?; if ptr.is_null() { return Err(ReprError::InvalidPointer); } // SAFETY: ptr and offset are user provided. Ok(unsafe { ptr::read_unaligned::<*mut c_void>(ptr.offset(offset) as *const *mut c_void) }) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/ffi/symbol.rs
ext/ffi/symbol.rs
// Copyright 2018-2025 the Deno authors. MIT license. use deno_error::JsErrorBox; /// Defines the accepted types that can be used as /// parameters and return values in FFI. #[derive(Clone, Debug, serde::Deserialize, Eq, PartialEq)] #[serde(rename_all = "lowercase")] pub enum NativeType { Void, Bool, U8, I8, U16, I16, U32, I32, U64, I64, USize, ISize, F32, F64, Pointer, Buffer, Function, Struct(Box<[NativeType]>), } impl TryFrom<NativeType> for libffi::middle::Type { type Error = JsErrorBox; fn try_from(native_type: NativeType) -> Result<Self, Self::Error> { Ok(match native_type { NativeType::Void => libffi::middle::Type::void(), NativeType::U8 | NativeType::Bool => libffi::middle::Type::u8(), NativeType::I8 => libffi::middle::Type::i8(), NativeType::U16 => libffi::middle::Type::u16(), NativeType::I16 => libffi::middle::Type::i16(), NativeType::U32 => libffi::middle::Type::u32(), NativeType::I32 => libffi::middle::Type::i32(), NativeType::U64 => libffi::middle::Type::u64(), NativeType::I64 => libffi::middle::Type::i64(), NativeType::USize => libffi::middle::Type::usize(), NativeType::ISize => libffi::middle::Type::isize(), NativeType::F32 => libffi::middle::Type::f32(), NativeType::F64 => libffi::middle::Type::f64(), NativeType::Pointer | NativeType::Buffer | NativeType::Function => { libffi::middle::Type::pointer() } NativeType::Struct(fields) => { libffi::middle::Type::structure(match !fields.is_empty() { true => fields .iter() .map(|field| field.clone().try_into()) .collect::<Result<Vec<_>, _>>()?, false => { return Err(JsErrorBox::type_error( "Struct must have at least one field", )); } }) } }) } } #[derive(Clone)] pub struct Symbol { pub name: String, pub cif: libffi::middle::Cif, pub ptr: libffi::middle::CodePtr, pub parameter_types: Vec<NativeType>, pub result_type: NativeType, } #[allow(clippy::non_send_fields_in_send_ty)] // SAFETY: unsafe trait must have unsafe implementation unsafe impl Send for Symbol {} // SAFETY: unsafe trait must have unsafe implementation unsafe impl Sync for Symbol {}
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/ffi/turbocall.rs
ext/ffi/turbocall.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ffi::c_void; use std::sync::LazyLock; use deno_core::OpState; use deno_core::op2; use deno_core::v8; use deno_core::v8::fast_api; use crate::NativeType; use crate::Symbol; use crate::dlfcn::FunctionData; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum TurbocallError { #[class(generic)] #[error(transparent)] SetError(#[from] cranelift::prelude::settings::SetError), #[class(generic)] #[error("Cranelift ISA error: {0}")] IsaError(&'static str), #[class(generic)] #[error(transparent)] CodegenError(#[from] cranelift::codegen::CodegenError), #[class(generic)] #[error(transparent)] VerifierError(#[from] cranelift::codegen::verifier::VerifierErrors), #[class(generic)] #[error("{0}")] CompileError(String), #[class(generic)] #[error(transparent)] Stdio(#[from] std::io::Error), } pub(crate) fn is_compatible(sym: &Symbol) -> bool { !matches!(sym.result_type, NativeType::Struct(_)) && !sym .parameter_types .iter() .any(|t| matches!(t, NativeType::Struct(_))) } /// Trampoline for fast-call FFI functions /// /// Calls the FFI function without the first argument (the receiver) pub(crate) struct Trampoline(memmap2::Mmap); impl Trampoline { pub(crate) fn ptr(&self) -> *const c_void { self.0.as_ptr() as *const c_void } } #[allow(unused)] pub(crate) fn compile_trampoline( sym: &Symbol, ) -> Result<Trampoline, TurbocallError> { use cranelift::prelude::*; let mut flag_builder = settings::builder(); flag_builder.set("is_pic", "true")?; flag_builder.set("opt_level", "speed_and_size")?; let flags = settings::Flags::new(flag_builder); let isa = cranelift_native::builder() .map_err(TurbocallError::IsaError)? .finish(flags)?; let mut wrapper_sig = cranelift::codegen::ir::Signature::new(isa.default_call_conv()); let mut target_sig = cranelift::codegen::ir::Signature::new(isa.default_call_conv()); let mut raise_sig = cranelift::codegen::ir::Signature::new(isa.default_call_conv()); #[cfg(target_pointer_width = "32")] const ISIZE: Type = types::I32; #[cfg(target_pointer_width = "64")] const ISIZE: Type = types::I64; fn convert(t: &NativeType, wrapper: bool) -> AbiParam { match t { NativeType::U8 => { if wrapper { AbiParam::new(types::I32) } else { AbiParam::new(types::I8).uext() } } NativeType::I8 => { if wrapper { AbiParam::new(types::I32) } else { AbiParam::new(types::I8).sext() } } NativeType::U16 => { if wrapper { AbiParam::new(types::I32) } else { AbiParam::new(types::I16).uext() } } NativeType::I16 => { if wrapper { AbiParam::new(types::I32) } else { AbiParam::new(types::I16).sext() } } NativeType::Bool => { if wrapper { AbiParam::new(types::I32) } else { AbiParam::new(types::I8).uext() } } NativeType::U32 => AbiParam::new(types::I32), NativeType::I32 => AbiParam::new(types::I32), NativeType::U64 => AbiParam::new(types::I64), NativeType::I64 => AbiParam::new(types::I64), NativeType::USize => AbiParam::new(ISIZE), NativeType::ISize => AbiParam::new(ISIZE), NativeType::F32 => AbiParam::new(types::F32), NativeType::F64 => AbiParam::new(types::F64), NativeType::Pointer => AbiParam::new(ISIZE), NativeType::Buffer => AbiParam::new(ISIZE), NativeType::Function => AbiParam::new(ISIZE), NativeType::Struct(_) => AbiParam::new(types::INVALID), NativeType::Void => AbiParam::new(types::INVALID), } } // *const FastApiCallbackOptions raise_sig.params.push(AbiParam::new(ISIZE)); // Local<Value> receiver wrapper_sig.params.push(AbiParam::new(ISIZE)); for pty in &sym.parameter_types { target_sig.params.push(convert(pty, false)); wrapper_sig.params.push(convert(pty, true)); } // const FastApiCallbackOptions& options wrapper_sig.params.push(AbiParam::new(ISIZE)); if !matches!(sym.result_type, NativeType::Struct(_) | NativeType::Void) { target_sig.returns.push(convert(&sym.result_type, false)); wrapper_sig.returns.push(convert(&sym.result_type, true)); } let mut ab_sig = cranelift::codegen::ir::Signature::new(isa.default_call_conv()); ab_sig.params.push(AbiParam::new(ISIZE)); ab_sig.returns.push(AbiParam::new(ISIZE)); let mut ctx = cranelift::codegen::Context::new(); let mut fn_builder_ctx = FunctionBuilderContext::new(); ctx.func = cranelift::codegen::ir::Function::with_name_signature( cranelift::codegen::ir::UserFuncName::testcase(format!( "{}_wrapper", sym.name )), wrapper_sig, ); let mut f = FunctionBuilder::new(&mut ctx.func, &mut fn_builder_ctx); let target_sig = f.import_signature(target_sig); let ab_sig = f.import_signature(ab_sig); let raise_sig = f.import_signature(raise_sig); { // Define blocks let entry = f.create_block(); f.append_block_params_for_function_params(entry); let error = f.create_block(); f.set_cold_block(error); // Define variables let mut vidx = 0; for pt in &sym.parameter_types { let target_v = Variable::new(vidx); vidx += 1; let wrapper_v = Variable::new(vidx); vidx += 1; f.declare_var(target_v, convert(pt, false).value_type); f.declare_var(wrapper_v, convert(pt, true).value_type); } let options_v = Variable::new(vidx); vidx += 1; f.declare_var(options_v, ISIZE); // Go! f.switch_to_block(entry); f.seal_block(entry); let args = f.block_params(entry).to_owned(); let mut vidx = 1; let mut argx = 1; for _ in &sym.parameter_types { f.def_var(Variable::new(vidx), args[argx]); argx += 1; vidx += 2; } f.def_var(options_v, args[argx]); static TRACE_TURBO: LazyLock<bool> = LazyLock::new(|| { std::env::var("DENO_UNSTABLE_FFI_TRACE_TURBO").as_deref() == Ok("1") }); if *TRACE_TURBO { let options = f.use_var(options_v); let trace_fn = f.ins().iconst(ISIZE, turbocall_trace as usize as i64); f.ins().call_indirect(ab_sig, trace_fn, &[options]); } let mut next = f.create_block(); let mut vidx = 0; for nty in &sym.parameter_types { let target_v = Variable::new(vidx); vidx += 1; let wrapper_v = Variable::new(vidx); vidx += 1; let arg = f.use_var(wrapper_v); match nty { NativeType::U8 | NativeType::I8 | NativeType::Bool => { let v = f.ins().ireduce(types::I8, arg); f.def_var(target_v, v); } NativeType::U16 | NativeType::I16 => { let v = f.ins().ireduce(types::I16, arg); f.def_var(target_v, v); } NativeType::Buffer => { let callee = f.ins().iconst(ISIZE, turbocall_ab_contents as usize as i64); let call = f.ins().call_indirect(ab_sig, callee, &[arg]); let result = f.inst_results(call)[0]; f.def_var(target_v, result); let sentinel = f.ins().iconst(ISIZE, isize::MAX as i64); let condition = f.ins().icmp(IntCC::Equal, result, sentinel); f.ins().brif(condition, error, &[], next, &[]); // switch to new block f.switch_to_block(next); f.seal_block(next); next = f.create_block(); } _ => { f.def_var(target_v, arg); } } } let mut args = Vec::with_capacity(sym.parameter_types.len()); let mut vidx = 0; for _ in &sym.parameter_types { args.push(f.use_var(Variable::new(vidx))); vidx += 2; // skip wrapper arg } let callee = f.ins().iconst(ISIZE, sym.ptr.as_ptr() as i64); let call = f.ins().call_indirect(target_sig, callee, &args); let mut results = f.inst_results(call).to_owned(); match sym.result_type { NativeType::U8 | NativeType::U16 | NativeType::Bool => { results[0] = f.ins().uextend(types::I32, results[0]); } NativeType::I8 | NativeType::I16 => { results[0] = f.ins().sextend(types::I32, results[0]); } _ => {} } f.ins().return_(&results); f.switch_to_block(error); f.seal_block(error); if !f.is_unreachable() { let options = f.use_var(options_v); let callee = f.ins().iconst(ISIZE, turbocall_raise as usize as i64); f.ins().call_indirect(raise_sig, callee, &[options]); let rty = convert(&sym.result_type, true); if rty.value_type.is_invalid() { f.ins().return_(&[]); } else { let zero = if rty.value_type == types::F32 { f.ins().f32const(0.0) } else if rty.value_type == types::F64 { f.ins().f64const(0.0) } else { f.ins().iconst(rty.value_type, 0) }; f.ins().return_(&[zero]); } } } f.finalize(); cranelift::codegen::verifier::verify_function(&ctx.func, isa.flags())?; let mut ctrl_plane = Default::default(); ctx.optimize(&*isa, &mut ctrl_plane)?; log::trace!("Turbocall IR:\n{}", ctx.func.display()); let code_info = ctx .compile(&*isa, &mut ctrl_plane) .map_err(|e| TurbocallError::CompileError(format!("{e:?}")))?; let data = code_info.buffer.data(); let mut mutable = memmap2::MmapMut::map_anon(data.len())?; mutable.copy_from_slice(data); let buffer = mutable.make_exec()?; Ok(Trampoline(buffer)) } pub(crate) struct Turbocall { pub trampoline: Trampoline, // Held in a box to keep the memory alive for CFunctionInfo #[allow(unused)] pub param_info: Box<[fast_api::CTypeInfo]>, // Held in a box to keep the memory alive for V8 #[allow(unused)] pub c_function_info: Box<fast_api::CFunctionInfo>, } pub(crate) fn make_template(sym: &Symbol, trampoline: Trampoline) -> Turbocall { let param_info = std::iter::once(fast_api::Type::V8Value.as_info()) // Receiver .chain(sym.parameter_types.iter().map(|t| t.into())) .chain(std::iter::once(fast_api::Type::CallbackOptions.as_info())) .collect::<Box<_>>(); let ret = if sym.result_type == NativeType::Buffer { // Buffer can be used as a return type and converts differently than in parameters. fast_api::Type::Pointer.as_info() } else { (&sym.result_type).into() }; let c_function_info = Box::new(fast_api::CFunctionInfo::new( ret, &param_info, fast_api::Int64Representation::BigInt, )); Turbocall { trampoline, param_info, c_function_info, } } impl From<&NativeType> for fast_api::CTypeInfo { fn from(native_type: &NativeType) -> Self { match native_type { NativeType::Bool => fast_api::Type::Bool.as_info(), NativeType::U8 | NativeType::U16 | NativeType::U32 => { fast_api::Type::Uint32.as_info() } NativeType::I8 | NativeType::I16 | NativeType::I32 => { fast_api::Type::Int32.as_info() } NativeType::F32 => fast_api::Type::Float32.as_info(), NativeType::F64 => fast_api::Type::Float64.as_info(), NativeType::Void => fast_api::Type::Void.as_info(), NativeType::I64 => fast_api::Type::Int64.as_info(), NativeType::U64 => fast_api::Type::Uint64.as_info(), NativeType::ISize => fast_api::Type::Int64.as_info(), NativeType::USize => fast_api::Type::Uint64.as_info(), NativeType::Pointer | NativeType::Function => { fast_api::Type::Pointer.as_info() } NativeType::Buffer => fast_api::Type::V8Value.as_info(), NativeType::Struct(_) => fast_api::Type::V8Value.as_info(), } } } extern "C" fn turbocall_ab_contents( v: deno_core::v8::Local<deno_core::v8::Value>, ) -> *mut c_void { super::ir::parse_buffer_arg(v).unwrap_or(isize::MAX as _) } unsafe extern "C" fn turbocall_raise( options: *const deno_core::v8::fast_api::FastApiCallbackOptions, ) { // SAFETY: This is called with valid FastApiCallbackOptions from within fast callback. v8::callback_scope!(unsafe scope, unsafe { &*options }); let exception = deno_core::error::to_v8_error(scope, &crate::IRError::InvalidBufferType); scope.throw_exception(exception); } pub struct TurbocallTarget(String); unsafe extern "C" fn turbocall_trace( options: *const deno_core::v8::fast_api::FastApiCallbackOptions, ) { // SAFETY: This is called with valid FastApiCallbackOptions from within fast callback. v8::callback_scope!(unsafe let scope, unsafe { &*options }); let func_data = deno_core::cppgc::try_unwrap_cppgc_object::<FunctionData>( scope, // SAFETY: This is valid if the options are valid. unsafe { (&*options).data }, ) .unwrap(); deno_core::JsRuntime::op_state_from(scope) .borrow_mut() .put(TurbocallTarget(func_data.symbol.name.clone())); } #[op2] #[string] pub fn op_ffi_get_turbocall_target(state: &mut OpState) -> Option<String> { state.try_take::<TurbocallTarget>().map(|t| t.0) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/io/lib.rs
ext/io/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::fs::File as StdFile; use std::future::Future; use std::io; use std::io::ErrorKind; use std::io::Read; use std::io::Seek; use std::io::Write; #[cfg(unix)] use std::os::fd::AsRawFd; #[cfg(unix)] use std::os::unix::io::FromRawFd; #[cfg(windows)] use std::os::windows::io::FromRawHandle; use std::path::Path; use std::path::PathBuf; #[cfg(unix)] use std::process::Stdio as StdStdio; use std::rc::Rc; #[cfg(windows)] use std::sync::Arc; use deno_core::AsyncMutFuture; use deno_core::AsyncRefCell; use deno_core::AsyncResult; use deno_core::BufMutView; use deno_core::BufView; use deno_core::CancelFuture; use deno_core::CancelHandle; use deno_core::CancelTryFuture; use deno_core::JsBuffer; use deno_core::OpState; use deno_core::RcRef; use deno_core::Resource; use deno_core::ResourceHandle; use deno_core::ResourceHandleFd; use deno_core::futures::TryFutureExt; use deno_core::op2; use deno_core::unsync::TaskQueue; use deno_core::unsync::spawn_blocking; use deno_error::JsErrorBox; #[cfg(windows)] use deno_subprocess_windows::Stdio as StdStdio; use fs::FileResource; use fs::FsError; use fs::FsResult; use fs::FsStat; use fs3::FileExt; use once_cell::sync::Lazy; #[cfg(windows)] use parking_lot::Condvar; #[cfg(windows)] use parking_lot::Mutex; use tokio::io::AsyncRead; use tokio::io::AsyncReadExt; use tokio::io::AsyncWrite; use tokio::io::AsyncWriteExt; use tokio::process; #[cfg(windows)] use winapi::um::processenv::GetStdHandle; #[cfg(windows)] use winapi::um::winbase; pub mod fs; mod pipe; #[cfg(windows)] mod winpipe; mod bi_pipe; pub use bi_pipe::BiPipe; pub use bi_pipe::BiPipeRead; pub use bi_pipe::BiPipeResource; pub use bi_pipe::BiPipeWrite; pub use bi_pipe::RawBiPipeHandle; pub use bi_pipe::bi_pipe_pair_raw; pub use pipe::AsyncPipeRead; pub use pipe::AsyncPipeWrite; pub use pipe::PipeRead; pub use pipe::PipeWrite; pub use pipe::RawPipeHandle; pub use pipe::pipe; /// Abstraction over `AsRawFd` (unix) and `AsRawHandle` (windows) pub trait AsRawIoHandle { fn as_raw_io_handle(&self) -> RawIoHandle; } #[cfg(unix)] impl<T> AsRawIoHandle for T where T: std::os::unix::io::AsRawFd, { fn as_raw_io_handle(&self) -> RawIoHandle { self.as_raw_fd() } } #[cfg(windows)] impl<T> AsRawIoHandle for T where T: std::os::windows::io::AsRawHandle, { fn as_raw_io_handle(&self) -> RawIoHandle { self.as_raw_handle() } } /// Abstraction over `IntoRawFd` (unix) and `IntoRawHandle` (windows) pub trait IntoRawIoHandle { fn into_raw_io_handle(self) -> RawIoHandle; } #[cfg(unix)] impl<T> IntoRawIoHandle for T where T: std::os::unix::io::IntoRawFd, { fn into_raw_io_handle(self) -> RawIoHandle { self.into_raw_fd() } } #[cfg(windows)] impl<T> IntoRawIoHandle for T where T: std::os::windows::io::IntoRawHandle, { fn into_raw_io_handle(self) -> RawIoHandle { self.into_raw_handle() } } /// Abstraction over `FromRawFd` (unix) and `FromRawHandle` (windows) pub trait FromRawIoHandle: Sized { /// Constructs a type from a raw io handle (fd/HANDLE). /// /// # Safety /// /// Refer to the standard library docs ([unix](https://doc.rust-lang.org/stable/std/os/windows/io/trait.FromRawHandle.html#tymethod.from_raw_handle)) ([windows](https://doc.rust-lang.org/stable/std/os/fd/trait.FromRawFd.html#tymethod.from_raw_fd)) /// unsafe fn from_raw_io_handle(handle: RawIoHandle) -> Self; } #[cfg(unix)] impl<T> FromRawIoHandle for T where T: std::os::unix::io::FromRawFd, { unsafe fn from_raw_io_handle(fd: RawIoHandle) -> T { // SAFETY: upheld by caller unsafe { T::from_raw_fd(fd) } } } #[cfg(windows)] impl<T> FromRawIoHandle for T where T: std::os::windows::io::FromRawHandle, { unsafe fn from_raw_io_handle(fd: RawIoHandle) -> T { // SAFETY: upheld by caller unsafe { T::from_raw_handle(fd) } } } #[cfg(unix)] pub type RawIoHandle = std::os::fd::RawFd; #[cfg(windows)] pub type RawIoHandle = std::os::windows::io::RawHandle; pub fn close_raw_handle(handle: RawIoHandle) { #[cfg(unix)] { // SAFETY: libc call unsafe { libc::close(handle); } } #[cfg(windows)] { // SAFETY: win32 call unsafe { windows_sys::Win32::Foundation::CloseHandle(handle as _); } } } // Store the stdio fd/handles in global statics in order to keep them // alive for the duration of the application since the last handle/fd // being dropped will close the corresponding pipe. #[cfg(unix)] pub static STDIN_HANDLE: Lazy<StdFile> = Lazy::new(|| { // SAFETY: corresponds to OS stdin unsafe { StdFile::from_raw_fd(0) } }); #[cfg(unix)] pub static STDOUT_HANDLE: Lazy<StdFile> = Lazy::new(|| { // SAFETY: corresponds to OS stdout unsafe { StdFile::from_raw_fd(1) } }); #[cfg(unix)] pub static STDERR_HANDLE: Lazy<StdFile> = Lazy::new(|| { // SAFETY: corresponds to OS stderr unsafe { StdFile::from_raw_fd(2) } }); #[cfg(windows)] pub static STDIN_HANDLE: Lazy<StdFile> = Lazy::new(|| { // SAFETY: corresponds to OS stdin unsafe { StdFile::from_raw_handle(GetStdHandle(winbase::STD_INPUT_HANDLE)) } }); #[cfg(windows)] pub static STDOUT_HANDLE: Lazy<StdFile> = Lazy::new(|| { // SAFETY: corresponds to OS stdout unsafe { StdFile::from_raw_handle(GetStdHandle(winbase::STD_OUTPUT_HANDLE)) } }); #[cfg(windows)] pub static STDERR_HANDLE: Lazy<StdFile> = Lazy::new(|| { // SAFETY: corresponds to OS stderr unsafe { StdFile::from_raw_handle(GetStdHandle(winbase::STD_ERROR_HANDLE)) } }); deno_core::extension!(deno_io, deps = [ deno_web ], ops = [ op_read_with_cancel_handle, op_read_create_cancel_handle, ], esm = [ "12_io.js" ], options = { stdio: Option<Stdio>, }, middleware = |op| match op.name { "op_print" => op_print(), _ => op, }, state = |state, options| { if let Some(stdio) = options.stdio { #[cfg(windows)] let stdin_state = { let st = Arc::new(Mutex::new(WinTtyState::default())); state.put(st.clone()); st }; #[cfg(unix)] let stdin_state = (); let t = &mut state.resource_table; let rid = t.add(fs::FileResource::new( Rc::new(match stdio.stdin.pipe { StdioPipeInner::Inherit => StdFileResourceInner::new( StdFileResourceKind::Stdin(stdin_state), STDIN_HANDLE.try_clone().unwrap(), None, ), StdioPipeInner::File(pipe) => StdFileResourceInner::file(pipe, None), }), "stdin".to_string(), )); assert_eq!(rid, 0, "stdin must have ResourceId 0"); let rid = t.add(FileResource::new( Rc::new(match stdio.stdout.pipe { StdioPipeInner::Inherit => StdFileResourceInner::new( StdFileResourceKind::Stdout, STDOUT_HANDLE.try_clone().unwrap(), None, ), StdioPipeInner::File(pipe) => StdFileResourceInner::file(pipe, None), }), "stdout".to_string(), )); assert_eq!(rid, 1, "stdout must have ResourceId 1"); let rid = t.add(FileResource::new( Rc::new(match stdio.stderr.pipe { StdioPipeInner::Inherit => StdFileResourceInner::new( StdFileResourceKind::Stderr, STDERR_HANDLE.try_clone().unwrap(), None, ), StdioPipeInner::File(pipe) => StdFileResourceInner::file(pipe, None), }), "stderr".to_string(), )); assert_eq!(rid, 2, "stderr must have ResourceId 2"); } }, ); #[derive(Default)] pub struct StdioPipe { pipe: StdioPipeInner, } impl StdioPipe { pub const fn inherit() -> Self { StdioPipe { pipe: StdioPipeInner::Inherit, } } pub fn file(f: impl Into<StdFile>) -> Self { StdioPipe { pipe: StdioPipeInner::File(f.into()), } } } #[derive(Default)] enum StdioPipeInner { #[default] Inherit, File(StdFile), } impl Clone for StdioPipe { fn clone(&self) -> Self { match &self.pipe { StdioPipeInner::Inherit => Self { pipe: StdioPipeInner::Inherit, }, StdioPipeInner::File(pipe) => Self { pipe: StdioPipeInner::File(pipe.try_clone().unwrap()), }, } } } /// Specify how stdin, stdout, and stderr are piped. /// By default, inherits from the process. #[derive(Clone, Default)] pub struct Stdio { pub stdin: StdioPipe, pub stdout: StdioPipe, pub stderr: StdioPipe, } #[derive(Debug)] pub struct WriteOnlyResource<S> { stream: AsyncRefCell<S>, } impl<S: 'static> From<S> for WriteOnlyResource<S> { fn from(stream: S) -> Self { Self { stream: stream.into(), } } } impl<S> WriteOnlyResource<S> where S: AsyncWrite + Unpin + 'static, { pub fn borrow_mut(self: &Rc<Self>) -> AsyncMutFuture<S> { RcRef::map(self, |r| &r.stream).borrow_mut() } async fn write(self: Rc<Self>, data: &[u8]) -> Result<usize, io::Error> { let mut stream = self.borrow_mut().await; let nwritten = stream.write(data).await?; Ok(nwritten) } async fn shutdown(self: Rc<Self>) -> Result<(), io::Error> { let mut stream = self.borrow_mut().await; stream.shutdown().await?; Ok(()) } pub fn into_inner(self) -> S { self.stream.into_inner() } } #[derive(Debug)] pub struct ReadOnlyResource<S> { stream: AsyncRefCell<S>, cancel_handle: CancelHandle, } impl<S: 'static> From<S> for ReadOnlyResource<S> { fn from(stream: S) -> Self { Self { stream: stream.into(), cancel_handle: Default::default(), } } } impl<S> ReadOnlyResource<S> where S: AsyncRead + Unpin + 'static, { pub fn borrow_mut(self: &Rc<Self>) -> AsyncMutFuture<S> { RcRef::map(self, |r| &r.stream).borrow_mut() } pub fn cancel_handle(self: &Rc<Self>) -> RcRef<CancelHandle> { RcRef::map(self, |r| &r.cancel_handle) } pub fn cancel_read_ops(&self) { self.cancel_handle.cancel() } async fn read(self: Rc<Self>, data: &mut [u8]) -> Result<usize, io::Error> { let mut rd = self.borrow_mut().await; let nread = rd.read(data).try_or_cancel(self.cancel_handle()).await?; Ok(nread) } pub fn into_inner(self) -> S { self.stream.into_inner() } } pub type ChildStdinResource = WriteOnlyResource<process::ChildStdin>; impl Resource for ChildStdinResource { fn name(&self) -> Cow<'_, str> { "childStdin".into() } deno_core::impl_writable!(); fn shutdown(self: Rc<Self>) -> AsyncResult<()> { Box::pin(self.shutdown().map_err(JsErrorBox::from_err)) } } pub type ChildStdoutResource = ReadOnlyResource<process::ChildStdout>; impl Resource for ChildStdoutResource { deno_core::impl_readable_byob!(); fn name(&self) -> Cow<'_, str> { "childStdout".into() } fn close(self: Rc<Self>) { self.cancel_read_ops(); } } pub type ChildStderrResource = ReadOnlyResource<process::ChildStderr>; impl Resource for ChildStderrResource { deno_core::impl_readable_byob!(); fn name(&self) -> Cow<'_, str> { "childStderr".into() } fn close(self: Rc<Self>) { self.cancel_read_ops(); } } #[cfg(windows)] #[derive(Default)] pub struct WinTtyState { pub cancelled: bool, pub reading: bool, pub screen_buffer_info: Option<winapi::um::wincon::CONSOLE_SCREEN_BUFFER_INFO>, pub cvar: Arc<Condvar>, } #[derive(Clone)] enum StdFileResourceKind { File, // For stdout and stderr, we sometimes instead use std::io::stdout() directly, // because we get some Windows specific functionality for free by using Rust // std's wrappers. So we take a bit of a complexity hit in order to not // have to duplicate the functionality in Rust's std/src/sys/windows/stdio.rs #[cfg(windows)] Stdin(Arc<Mutex<WinTtyState>>), #[cfg(not(windows))] Stdin(()), Stdout, Stderr, } pub struct StdFileResourceInner { kind: StdFileResourceKind, // We can't use an AsyncRefCell here because we need to allow // access to the resource synchronously at any time and // asynchronously one at a time in order cell: RefCell<Option<StdFile>>, // Used to keep async actions in order and only allow one // to occur at a time cell_async_task_queue: Rc<TaskQueue>, handle: ResourceHandleFd, maybe_path: Option<PathBuf>, } impl StdFileResourceInner { pub fn file(fs_file: StdFile, maybe_path: Option<PathBuf>) -> Self { StdFileResourceInner::new(StdFileResourceKind::File, fs_file, maybe_path) } fn new( kind: StdFileResourceKind, fs_file: StdFile, maybe_path: Option<PathBuf>, ) -> Self { // We know this will be an fd let handle = ResourceHandle::from_fd_like(&fs_file).as_fd_like().unwrap(); StdFileResourceInner { kind, handle, cell: RefCell::new(Some(fs_file)), cell_async_task_queue: Default::default(), maybe_path, } } fn with_sync<F, R>(&self, action: F) -> FsResult<R> where F: FnOnce(&mut StdFile) -> FsResult<R>, { match self.cell.try_borrow_mut() { Ok(mut cell) if cell.is_some() => action(cell.as_mut().unwrap()), _ => Err(fs::FsError::FileBusy), } } fn with_inner_blocking_task<F, R: 'static + Send>( &self, action: F, ) -> impl Future<Output = R> + '_ where F: FnOnce(&mut StdFile) -> R + Send + 'static, { // we want to restrict this to one async action at a time let acquire_fut = self.cell_async_task_queue.acquire(); async move { let permit = acquire_fut.await; // we take the value out of the cell, use it on a blocking task, // then put it back into the cell when we're done let mut did_take = false; let mut cell_value = { let mut cell = self.cell.borrow_mut(); match cell.as_mut().unwrap().try_clone().ok() { Some(value) => value, None => { did_take = true; cell.take().unwrap() } } }; let (cell_value, result) = spawn_blocking(move || { let result = action(&mut cell_value); (cell_value, result) }) .await .unwrap(); if did_take { // put it back self.cell.borrow_mut().replace(cell_value); } drop(permit); // explicit for clarity result } } fn with_blocking_task<F, R: 'static + Send>( &self, action: F, ) -> impl Future<Output = R> + use<F, R> where F: FnOnce() -> R + Send + 'static, { // we want to restrict this to one async action at a time let acquire_fut = self.cell_async_task_queue.acquire(); async move { let _permit = acquire_fut.await; spawn_blocking(action).await.unwrap() } } #[cfg(windows)] async fn handle_stdin_read( &self, state: Arc<Mutex<WinTtyState>>, mut buf: BufMutView, ) -> FsResult<(usize, BufMutView)> { loop { let state = state.clone(); let fut = self.with_inner_blocking_task(move |file| { /* Start reading, and set the reading flag to true */ state.lock().reading = true; let nread = match file.read(&mut buf) { Ok(nread) => nread, Err(e) => return Err((e.into(), buf)), }; let mut state = state.lock(); state.reading = false; /* If we canceled the read by sending a VK_RETURN event, restore the screen state to undo the visual effect of the VK_RETURN event */ if state.cancelled { if let Some(screen_buffer_info) = state.screen_buffer_info { // SAFETY: WinAPI calls to open conout$ and restore visual state. unsafe { let handle = winapi::um::fileapi::CreateFileW( "conout$" .encode_utf16() .chain(Some(0)) .collect::<Vec<_>>() .as_ptr(), winapi::um::winnt::GENERIC_READ | winapi::um::winnt::GENERIC_WRITE, winapi::um::winnt::FILE_SHARE_READ | winapi::um::winnt::FILE_SHARE_WRITE, std::ptr::null_mut(), winapi::um::fileapi::OPEN_EXISTING, 0, std::ptr::null_mut(), ); let mut pos = screen_buffer_info.dwCursorPosition; /* If the cursor was at the bottom line of the screen buffer, the VK_RETURN would have caused the buffer contents to scroll up by one line. The right position to reset the cursor to is therefore one line higher */ if pos.Y == screen_buffer_info.dwSize.Y - 1 { pos.Y -= 1; } winapi::um::wincon::SetConsoleCursorPosition(handle, pos); winapi::um::handleapi::CloseHandle(handle); } } /* Reset the cancelled flag */ state.cancelled = false; /* Unblock the main thread */ state.cvar.notify_one(); return Err((FsError::FileBusy, buf)); } Ok((nread, buf)) }); match fut.await { Err((FsError::FileBusy, b)) => { buf = b; continue; } other => return other.map_err(|(e, _)| e), } } } } #[async_trait::async_trait(?Send)] impl crate::fs::File for StdFileResourceInner { fn maybe_path(&self) -> Option<&Path> { self.maybe_path.as_deref() } fn write_sync(self: Rc<Self>, buf: &[u8]) -> FsResult<usize> { // Rust will line buffer and we don't want that behavior // (see https://github.com/denoland/deno/issues/948), so flush stdout and stderr. // Although an alternative solution could be to bypass Rust's std by // using the raw fds/handles, it will cause encoding issues on Windows // that we get solved for free by using Rust's stdio wrappers (see // std/src/sys/windows/stdio.rs in Rust's source code). match self.kind { StdFileResourceKind::File => self.with_sync(|file| Ok(file.write(buf)?)), StdFileResourceKind::Stdin(_) => { Err(Into::<std::io::Error>::into(ErrorKind::Unsupported).into()) } StdFileResourceKind::Stdout => { // bypass the file and use std::io::stdout() let mut stdout = std::io::stdout().lock(); let nwritten = stdout.write(buf)?; stdout.flush()?; Ok(nwritten) } StdFileResourceKind::Stderr => { // bypass the file and use std::io::stderr() let mut stderr = std::io::stderr().lock(); let nwritten = stderr.write(buf)?; stderr.flush()?; Ok(nwritten) } } } fn read_sync(self: Rc<Self>, buf: &mut [u8]) -> FsResult<usize> { match self.kind { StdFileResourceKind::File | StdFileResourceKind::Stdin(_) => { self.with_sync(|file| Ok(file.read(buf)?)) } StdFileResourceKind::Stdout | StdFileResourceKind::Stderr => { Err(FsError::NotSupported) } } } fn write_all_sync(self: Rc<Self>, buf: &[u8]) -> FsResult<()> { match self.kind { StdFileResourceKind::File => { self.with_sync(|file| Ok(file.write_all(buf)?)) } StdFileResourceKind::Stdin(_) => { Err(Into::<std::io::Error>::into(ErrorKind::Unsupported).into()) } StdFileResourceKind::Stdout => { // bypass the file and use std::io::stdout() let mut stdout = std::io::stdout().lock(); stdout.write_all(buf)?; stdout.flush()?; Ok(()) } StdFileResourceKind::Stderr => { // bypass the file and use std::io::stderr() let mut stderr = std::io::stderr().lock(); stderr.write_all(buf)?; stderr.flush()?; Ok(()) } } } async fn write_all(self: Rc<Self>, buf: BufView) -> FsResult<()> { match self.kind { StdFileResourceKind::File => { self .with_inner_blocking_task(move |file| Ok(file.write_all(&buf)?)) .await } StdFileResourceKind::Stdin(_) => { Err(Into::<std::io::Error>::into(ErrorKind::Unsupported).into()) } StdFileResourceKind::Stdout => { self .with_blocking_task(move || { // bypass the file and use std::io::stdout() let mut stdout = std::io::stdout().lock(); stdout.write_all(&buf)?; stdout.flush()?; Ok(()) }) .await } StdFileResourceKind::Stderr => { self .with_blocking_task(move || { // bypass the file and use std::io::stderr() let mut stderr = std::io::stderr().lock(); stderr.write_all(&buf)?; stderr.flush()?; Ok(()) }) .await } } } async fn write( self: Rc<Self>, view: BufView, ) -> FsResult<deno_core::WriteOutcome> { match self.kind { StdFileResourceKind::File => { self .with_inner_blocking_task(|file| { let nwritten = file.write(&view)?; Ok(deno_core::WriteOutcome::Partial { nwritten, view }) }) .await } StdFileResourceKind::Stdin(_) => { Err(Into::<std::io::Error>::into(ErrorKind::Unsupported).into()) } StdFileResourceKind::Stdout => { self .with_blocking_task(|| { // bypass the file and use std::io::stdout() let mut stdout = std::io::stdout().lock(); let nwritten = stdout.write(&view)?; stdout.flush()?; Ok(deno_core::WriteOutcome::Partial { nwritten, view }) }) .await } StdFileResourceKind::Stderr => { self .with_blocking_task(|| { // bypass the file and use std::io::stderr() let mut stderr = std::io::stderr().lock(); let nwritten = stderr.write(&view)?; stderr.flush()?; Ok(deno_core::WriteOutcome::Partial { nwritten, view }) }) .await } } } fn read_all_sync(self: Rc<Self>) -> FsResult<Cow<'static, [u8]>> { match self.kind { StdFileResourceKind::File | StdFileResourceKind::Stdin(_) => { let mut buf = Vec::new(); self.with_sync(|file| Ok(file.read_to_end(&mut buf)?))?; Ok(Cow::Owned(buf)) } StdFileResourceKind::Stdout | StdFileResourceKind::Stderr => { Err(FsError::NotSupported) } } } async fn read_all_async(self: Rc<Self>) -> FsResult<Cow<'static, [u8]>> { match self.kind { StdFileResourceKind::File | StdFileResourceKind::Stdin(_) => { self .with_inner_blocking_task(|file| { let mut buf = Vec::new(); file.read_to_end(&mut buf)?; Ok(Cow::Owned(buf)) }) .await } StdFileResourceKind::Stdout | StdFileResourceKind::Stderr => { Err(FsError::NotSupported) } } } fn chmod_sync(self: Rc<Self>, mode: u32) -> FsResult<()> { #[cfg(unix)] { use std::os::unix::prelude::PermissionsExt; self.with_sync(|file| { Ok(file.set_permissions(std::fs::Permissions::from_mode(mode))?) }) } #[cfg(windows)] { self.with_sync(|file| { let mut permissions = file.metadata()?.permissions(); if mode & libc::S_IWRITE as u32 > 0 { // clippy warning should only be applicable to Unix platforms // https://rust-lang.github.io/rust-clippy/master/index.html#permissions_set_readonly_false #[allow(clippy::permissions_set_readonly_false)] permissions.set_readonly(false); } else { permissions.set_readonly(true); } file.set_permissions(permissions)?; Ok(()) }) } } async fn chmod_async(self: Rc<Self>, mode: u32) -> FsResult<()> { #[cfg(unix)] { use std::os::unix::prelude::PermissionsExt; self .with_inner_blocking_task(move |file| { Ok(file.set_permissions(std::fs::Permissions::from_mode(mode))?) }) .await } #[cfg(windows)] { self .with_inner_blocking_task(move |file| { let mut permissions = file.metadata()?.permissions(); if mode & libc::S_IWRITE as u32 > 0 { // clippy warning should only be applicable to Unix platforms // https://rust-lang.github.io/rust-clippy/master/index.html#permissions_set_readonly_false #[allow(clippy::permissions_set_readonly_false)] permissions.set_readonly(false); } else { permissions.set_readonly(true); } file.set_permissions(permissions)?; Ok(()) }) .await } #[cfg(not(any(unix, windows)))] { Err(FsError::NotSupported) } } fn chown_sync( self: Rc<Self>, _uid: Option<u32>, _gid: Option<u32>, ) -> FsResult<()> { #[cfg(unix)] { let owner = _uid.map(nix::unistd::Uid::from_raw); let group = _gid.map(nix::unistd::Gid::from_raw); let res = nix::unistd::fchown(self.handle, owner, group); if let Err(err) = res { Err(io::Error::from_raw_os_error(err as i32).into()) } else { Ok(()) } } #[cfg(not(unix))] Err(FsError::NotSupported) } async fn chown_async( self: Rc<Self>, _uid: Option<u32>, _gid: Option<u32>, ) -> FsResult<()> { #[cfg(unix)] { self .with_inner_blocking_task(move |file| { use std::os::fd::AsFd; let owner = _uid.map(nix::unistd::Uid::from_raw); let group = _gid.map(nix::unistd::Gid::from_raw); nix::unistd::fchown(file.as_fd().as_raw_fd(), owner, group) .map_err(|err| io::Error::from_raw_os_error(err as i32).into()) }) .await } #[cfg(not(unix))] Err(FsError::NotSupported) } fn seek_sync(self: Rc<Self>, pos: io::SeekFrom) -> FsResult<u64> { self.with_sync(|file| Ok(file.seek(pos)?)) } async fn seek_async(self: Rc<Self>, pos: io::SeekFrom) -> FsResult<u64> { self .with_inner_blocking_task(move |file| Ok(file.seek(pos)?)) .await } fn datasync_sync(self: Rc<Self>) -> FsResult<()> { self.with_sync(|file| Ok(file.sync_data()?)) } async fn datasync_async(self: Rc<Self>) -> FsResult<()> { self .with_inner_blocking_task(|file| Ok(file.sync_data()?)) .await } fn sync_sync(self: Rc<Self>) -> FsResult<()> { self.with_sync(|file| Ok(file.sync_all()?)) } async fn sync_async(self: Rc<Self>) -> FsResult<()> { self .with_inner_blocking_task(|file| Ok(file.sync_all()?)) .await } fn stat_sync(self: Rc<Self>) -> FsResult<FsStat> { #[cfg(unix)] { self.with_sync(|file| Ok(file.metadata().map(FsStat::from_std)?)) } #[cfg(windows)] { self.with_sync(|file| { let mut fs_stat = file.metadata().map(FsStat::from_std)?; stat_extra(file, &mut fs_stat)?; Ok(fs_stat) }) } #[cfg(not(any(unix, windows)))] { Err(FsError::NotSupported) } } async fn stat_async(self: Rc<Self>) -> FsResult<FsStat> { #[cfg(unix)] { self .with_inner_blocking_task(|file| { Ok(file.metadata().map(FsStat::from_std)?) }) .await } #[cfg(windows)] { self .with_inner_blocking_task(|file| { let mut fs_stat = file.metadata().map(FsStat::from_std)?; stat_extra(file, &mut fs_stat)?; Ok(fs_stat) }) .await } #[cfg(not(any(unix, windows)))] { Err(FsError::NotSupported) } } fn lock_sync(self: Rc<Self>, exclusive: bool) -> FsResult<()> { self.with_sync(|file| { if exclusive { file.lock_exclusive()?; } else { fs3::FileExt::lock_shared(file)?; } Ok(()) }) } async fn lock_async(self: Rc<Self>, exclusive: bool) -> FsResult<()> { self .with_inner_blocking_task(move |file| { if exclusive { file.lock_exclusive()?; } else { fs3::FileExt::lock_shared(file)?; } Ok(()) }) .await } fn unlock_sync(self: Rc<Self>) -> FsResult<()> { self.with_sync(|file| Ok(fs3::FileExt::unlock(file)?)) } async fn unlock_async(self: Rc<Self>) -> FsResult<()> { self .with_inner_blocking_task(|file| Ok(fs3::FileExt::unlock(file)?)) .await } fn truncate_sync(self: Rc<Self>, len: u64) -> FsResult<()> { self.with_sync(|file| Ok(file.set_len(len)?)) } async fn truncate_async(self: Rc<Self>, len: u64) -> FsResult<()> { self .with_inner_blocking_task(move |file| Ok(file.set_len(len)?)) .await } fn utime_sync( self: Rc<Self>, atime_secs: i64, atime_nanos: u32, mtime_secs: i64, mtime_nanos: u32, ) -> FsResult<()> { let atime = filetime::FileTime::from_unix_time(atime_secs, atime_nanos); let mtime = filetime::FileTime::from_unix_time(mtime_secs, mtime_nanos); self.with_sync(|file| { filetime::set_file_handle_times(file, Some(atime), Some(mtime))?; Ok(()) }) } async fn utime_async( self: Rc<Self>, atime_secs: i64, atime_nanos: u32, mtime_secs: i64, mtime_nanos: u32, ) -> FsResult<()> { let atime = filetime::FileTime::from_unix_time(atime_secs, atime_nanos); let mtime = filetime::FileTime::from_unix_time(mtime_secs, mtime_nanos); self .with_inner_blocking_task(move |file| { filetime::set_file_handle_times(file, Some(atime), Some(mtime))?; Ok(()) }) .await } async fn read_byob( self: Rc<Self>, mut buf: BufMutView, ) -> FsResult<(usize, BufMutView)> { match &self.kind { /* On Windows, we need to handle special read cancellation logic for stdin */ #[cfg(windows)] StdFileResourceKind::Stdin(state) => { self.handle_stdin_read(state.clone(), buf).await } _ => { self .with_inner_blocking_task(|file| { let nread = file.read(&mut buf)?; Ok((nread, buf)) }) .await } } } fn try_clone_inner(self: Rc<Self>) -> FsResult<Rc<dyn fs::File>> { let inner: &Option<_> = &self.cell.borrow(); match inner { Some(inner) => Ok(Rc::new(StdFileResourceInner { kind: self.kind.clone(), cell: RefCell::new(Some(inner.try_clone()?)), cell_async_task_queue: Default::default(), handle: self.handle, maybe_path: self.maybe_path.clone(), })), None => Err(FsError::FileBusy), } } fn as_stdio(self: Rc<Self>) -> FsResult<StdStdio> { match self.kind { StdFileResourceKind::File => self.with_sync(|file| { let file = file.try_clone()?; Ok(file.into()) }), _ => Ok(StdStdio::inherit()), } } fn backing_fd(self: Rc<Self>) -> Option<ResourceHandleFd> { Some(self.handle) } } pub struct ReadCancelResource(Rc<CancelHandle>); impl Resource for ReadCancelResource { fn name(&self) -> Cow<'_, str> { "readCancel".into() } fn close(self: Rc<Self>) { self.0.cancel(); } } #[op2(fast)] #[smi] pub fn op_read_create_cancel_handle(state: &mut OpState) -> u32 { state .resource_table .add(ReadCancelResource(CancelHandle::new_rc())) } #[op2(async)] pub async fn op_read_with_cancel_handle( state: Rc<RefCell<OpState>>, #[smi] rid: u32, #[smi] cancel_handle: u32, #[buffer] buf: JsBuffer, ) -> Result<u32, JsErrorBox> { let (fut, cancel_rc) = { let state = state.borrow(); let cancel_handle = state .resource_table .get::<ReadCancelResource>(cancel_handle) .unwrap() .0 .clone(); ( FileResource::with_file(&state, rid, |file| { let view = BufMutView::from(buf); Ok(file.read_byob(view)) }), cancel_handle, ) }; fut? .or_cancel(cancel_rc) .await .map_err(|_| JsErrorBox::generic("cancelled"))? .map(|(n, _)| n as u32) .map_err(JsErrorBox::from_err) } // override op_print to use the stdout and stderr in the resource table #[op2(fast)] pub fn op_print( state: &mut OpState, #[string] msg: &str, is_err: bool, ) -> Result<(), JsErrorBox> { let rid = if is_err { 2 } else { 1 }; FileResource::with_file(state, rid, move |file| { file .write_all_sync(msg.as_bytes()) .map_err(JsErrorBox::from_err) }) } #[cfg(windows)] pub fn stat_extra(file: &std::fs::File, fsstat: &mut FsStat) -> FsResult<()> { use std::os::windows::io::AsRawHandle; unsafe fn get_dev( handle: winapi::shared::ntdef::HANDLE, ) -> std::io::Result<u64> { use winapi::shared::minwindef::FALSE; use winapi::um::fileapi::BY_HANDLE_FILE_INFORMATION;
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
true
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/io/bi_pipe.rs
ext/io/bi_pipe.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::rc::Rc; use deno_core::AsyncRefCell; use deno_core::AsyncResult; use deno_core::CancelHandle; use deno_core::CancelTryFuture; use deno_core::RcRef; use tokio::io::AsyncReadExt; use tokio::io::AsyncWriteExt; pub type RawBiPipeHandle = super::RawIoHandle; /// One end of a bidirectional pipe. This implements the /// `Resource` trait. pub struct BiPipeResource { read_half: AsyncRefCell<BiPipeRead>, write_half: AsyncRefCell<BiPipeWrite>, cancel: CancelHandle, raw_handle: RawBiPipeHandle, } #[cfg(windows)] // workaround because `RawHandle` doesn't impl `AsRawHandle` mod as_raw_handle { use super::RawBiPipeHandle; pub(super) struct RawHandleWrap(pub(super) RawBiPipeHandle); impl std::os::windows::io::AsRawHandle for RawHandleWrap { fn as_raw_handle(&self) -> std::os::windows::prelude::RawHandle { self.0 } } } impl deno_core::Resource for BiPipeResource { fn close(self: Rc<Self>) { self.cancel.cancel(); } fn backing_handle(self: Rc<Self>) -> Option<deno_core::ResourceHandle> { #[cfg(unix)] { Some(deno_core::ResourceHandle::from_fd_like(&self.raw_handle)) } #[cfg(windows)] { Some(deno_core::ResourceHandle::from_fd_like( &as_raw_handle::RawHandleWrap(self.raw_handle), )) } } deno_core::impl_readable_byob!(); deno_core::impl_writable!(); } impl BiPipeResource { pub fn from_raw_handle(raw: RawBiPipeHandle) -> Result<Self, std::io::Error> { let pipe = BiPipe::from_raw(raw)?; let (read, write) = pipe.split(); Ok(Self { raw_handle: raw, read_half: AsyncRefCell::new(read), write_half: AsyncRefCell::new(write), cancel: Default::default(), }) } pub async fn read( self: Rc<Self>, data: &mut [u8], ) -> Result<usize, std::io::Error> { let mut rd = RcRef::map(&self, |r| &r.read_half).borrow_mut().await; let cancel_handle = RcRef::map(&self, |r| &r.cancel); rd.read(data).try_or_cancel(cancel_handle).await } pub async fn write( self: Rc<Self>, data: &[u8], ) -> Result<usize, std::io::Error> { let mut wr = RcRef::map(self, |r| &r.write_half).borrow_mut().await; let nwritten = wr.write(data).await?; wr.flush().await?; Ok(nwritten) } } /// One end of a bidirectional pipe #[pin_project::pin_project] pub struct BiPipe { #[pin] read_end: BiPipeRead, #[pin] write_end: BiPipeWrite, } impl BiPipe { pub fn from_raw(raw: RawBiPipeHandle) -> Result<Self, std::io::Error> { let (read_end, write_end) = from_raw(raw)?; Ok(Self { read_end, write_end, }) } pub fn split(self) -> (BiPipeRead, BiPipeWrite) { (self.read_end, self.write_end) } pub fn unsplit(read_end: BiPipeRead, write_end: BiPipeWrite) -> Self { Self { read_end, write_end, } } } #[pin_project::pin_project] pub struct BiPipeRead { #[cfg(unix)] #[pin] inner: tokio::net::unix::OwnedReadHalf, #[cfg(windows)] #[pin] inner: tokio::io::ReadHalf<tokio::net::windows::named_pipe::NamedPipeClient>, } #[cfg(unix)] impl From<tokio::net::unix::OwnedReadHalf> for BiPipeRead { fn from(value: tokio::net::unix::OwnedReadHalf) -> Self { Self { inner: value } } } #[cfg(windows)] impl From<tokio::io::ReadHalf<tokio::net::windows::named_pipe::NamedPipeClient>> for BiPipeRead { fn from( value: tokio::io::ReadHalf< tokio::net::windows::named_pipe::NamedPipeClient, >, ) -> Self { Self { inner: value } } } #[pin_project::pin_project] pub struct BiPipeWrite { #[cfg(unix)] #[pin] inner: tokio::net::unix::OwnedWriteHalf, #[cfg(windows)] #[pin] inner: tokio::io::WriteHalf<tokio::net::windows::named_pipe::NamedPipeClient>, } #[cfg(unix)] impl From<tokio::net::unix::OwnedWriteHalf> for BiPipeWrite { fn from(value: tokio::net::unix::OwnedWriteHalf) -> Self { Self { inner: value } } } #[cfg(windows)] impl From<tokio::io::WriteHalf<tokio::net::windows::named_pipe::NamedPipeClient>> for BiPipeWrite { fn from( value: tokio::io::WriteHalf< tokio::net::windows::named_pipe::NamedPipeClient, >, ) -> Self { Self { inner: value } } } #[cfg(unix)] fn from_raw( stream: RawBiPipeHandle, ) -> Result<(BiPipeRead, BiPipeWrite), std::io::Error> { use std::os::fd::FromRawFd; use nix::sys::socket::AddressFamily; use nix::sys::socket::SockaddrLike; use nix::sys::socket::SockaddrStorage; use nix::sys::socket::getsockname; if getsockname::<SockaddrStorage>(stream) .ok() .and_then(|a| a.family()) != Some(AddressFamily::Unix) { return Err(std::io::Error::other("fd is not from BiPipe")); } // SAFETY: We validated above that this is from a unix stream. let unix_stream = unsafe { std::os::unix::net::UnixStream::from_raw_fd(stream) }; unix_stream.set_nonblocking(true)?; let unix_stream = tokio::net::UnixStream::from_std(unix_stream)?; let (read, write) = unix_stream.into_split(); Ok((BiPipeRead { inner: read }, BiPipeWrite { inner: write })) } #[cfg(windows)] fn from_raw( handle: RawBiPipeHandle, ) -> Result<(BiPipeRead, BiPipeWrite), std::io::Error> { // Safety: We cannot use `get_osfhandle` because Deno statically links to msvcrt. It is not guaranteed that the // fd handle map will be the same. let pipe = unsafe { tokio::net::windows::named_pipe::NamedPipeClient::from_raw_handle( handle as _, )? }; let (read, write) = tokio::io::split(pipe); Ok((BiPipeRead { inner: read }, BiPipeWrite { inner: write })) } impl tokio::io::AsyncRead for BiPipeRead { fn poll_read( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, buf: &mut tokio::io::ReadBuf<'_>, ) -> std::task::Poll<std::io::Result<()>> { self.project().inner.poll_read(cx, buf) } } impl tokio::io::AsyncRead for BiPipe { fn poll_read( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, buf: &mut tokio::io::ReadBuf<'_>, ) -> std::task::Poll<std::io::Result<()>> { self.project().read_end.poll_read(cx, buf) } } // implement `AsyncWrite` for `$name`, delegating // the impl to `$field`. `$name` must have a `project` method // with a projected `$field` (e.g. with `pin_project::pin_project`) macro_rules! impl_async_write { (for $name: ident -> self.$field: ident) => { impl tokio::io::AsyncWrite for $name { fn poll_write_vectored( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, bufs: &[std::io::IoSlice<'_>], ) -> std::task::Poll<Result<usize, std::io::Error>> { self.project().$field.poll_write_vectored(cx, bufs) } fn is_write_vectored(&self) -> bool { self.$field.is_write_vectored() } fn poll_write( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, buf: &[u8], ) -> std::task::Poll<Result<usize, std::io::Error>> { self.project().$field.poll_write(cx, buf) } fn poll_flush( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Result<(), std::io::Error>> { self.project().$field.poll_flush(cx) } fn poll_shutdown( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Result<(), std::io::Error>> { self.project().$field.poll_shutdown(cx) } } }; } impl_async_write!(for BiPipeWrite -> self.inner); impl_async_write!(for BiPipe -> self.write_end); /// Creates both sides of a bidirectional pipe, returning the raw /// handles to the underlying OS resources. pub fn bi_pipe_pair_raw() -> Result<(RawBiPipeHandle, RawBiPipeHandle), std::io::Error> { #[cfg(unix)] { // SockFlag is broken on macOS // https://github.com/nix-rust/nix/issues/861 let mut fds = [-1, -1]; #[cfg(not(target_os = "macos"))] let flags = libc::SOCK_CLOEXEC; #[cfg(target_os = "macos")] let flags = 0; // SAFETY: libc call, fds are correct size+align let ret = unsafe { libc::socketpair( libc::AF_UNIX, libc::SOCK_STREAM | flags, 0, fds.as_mut_ptr(), ) }; if ret != 0 { return Err(std::io::Error::last_os_error()); } if cfg!(target_os = "macos") { let fcntl = |fd: i32, flag: libc::c_int| -> Result<(), std::io::Error> { // SAFETY: libc call, fd is valid let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) }; if flags == -1 { return Err(fail(fds)); } // SAFETY: libc call, fd is valid let ret = unsafe { libc::fcntl(fd, libc::F_SETFD, flags | flag) }; if ret == -1 { return Err(fail(fds)); } Ok(()) }; fn fail(fds: [i32; 2]) -> std::io::Error { // SAFETY: libc call, fds are valid unsafe { libc::close(fds[0]); libc::close(fds[1]); } std::io::Error::last_os_error() } // SOCK_CLOEXEC is not supported on macOS. fcntl(fds[0], libc::FD_CLOEXEC)?; fcntl(fds[1], libc::FD_CLOEXEC)?; } let fd1 = fds[0]; let fd2 = fds[1]; Ok((fd1, fd2)) } #[cfg(windows)] { // TODO(nathanwhit): more granular unsafe blocks // SAFETY: win32 calls unsafe { use std::io; use std::os::windows::ffi::OsStrExt; use std::path::Path; use std::ptr; use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED; use windows_sys::Win32::Foundation::ERROR_PIPE_CONNECTED; use windows_sys::Win32::Foundation::GENERIC_READ; use windows_sys::Win32::Foundation::GENERIC_WRITE; use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; use windows_sys::Win32::Security::SECURITY_ATTRIBUTES; use windows_sys::Win32::Storage::FileSystem::CreateFileW; use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_FIRST_PIPE_INSTANCE; use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OVERLAPPED; use windows_sys::Win32::Storage::FileSystem::OPEN_EXISTING; use windows_sys::Win32::Storage::FileSystem::PIPE_ACCESS_DUPLEX; use windows_sys::Win32::System::Pipes::ConnectNamedPipe; use windows_sys::Win32::System::Pipes::CreateNamedPipeW; use windows_sys::Win32::System::Pipes::PIPE_READMODE_BYTE; use windows_sys::Win32::System::Pipes::PIPE_TYPE_BYTE; let (path, hd1) = loop { let name = format!("\\\\.\\pipe\\{}", uuid::Uuid::new_v4()); let mut path = Path::new(&name) .as_os_str() .encode_wide() .collect::<Vec<_>>(); path.push(0); let hd1 = CreateNamedPipeW( path.as_ptr(), PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, 65536, 65536, 0, std::ptr::null_mut(), ); if hd1 == INVALID_HANDLE_VALUE { let err = io::Error::last_os_error(); /* If the pipe name is already in use, try again. */ if err.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) { continue; } return Err(err); } break (path, hd1); }; /* Create child pipe handle. */ let s = SECURITY_ATTRIBUTES { nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32, lpSecurityDescriptor: ptr::null_mut(), bInheritHandle: 1, }; let hd2 = CreateFileW( path.as_ptr(), GENERIC_READ | GENERIC_WRITE, 0, &s, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, std::ptr::null_mut(), ); if hd2 == INVALID_HANDLE_VALUE { return Err(io::Error::last_os_error()); } // Will not block because we have create the pair. if ConnectNamedPipe(hd1, ptr::null_mut()) == 0 { let err = std::io::Error::last_os_error(); if err.raw_os_error() != Some(ERROR_PIPE_CONNECTED as i32) { CloseHandle(hd2); return Err(err); } } Ok((hd1 as _, hd2 as _)) } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false