1use crate::host::{invoke, with_host, JsObj};
13use fusevm::Value;
14use indexmap::IndexMap;
15use std::collections::HashMap;
16use std::net::UdpSocket;
17use std::sync::atomic::{AtomicBool, Ordering};
18use std::sync::Arc;
19use std::time::Duration;
20
21pub const MODULE_METHODS: &[&str] = &["createSocket"];
23
24pub const SOCKET_TAG: &str = "UdpSocket";
26
27pub const SOCKET_METHODS: &[&str] = &[
29 "bind",
30 "send",
31 "close",
32 "address",
33 "setBroadcast",
34 "setTTL",
35 "setMulticastTTL",
36 "setMulticastLoopback",
37 "setMulticastInterface",
38 "addMembership",
39 "dropMembership",
40 "addSourceSpecificMembership",
41 "dropSourceSpecificMembership",
42 "setRecvBufferSize",
43 "setSendBufferSize",
44 "getRecvBufferSize",
45 "getSendBufferSize",
46 "connect",
47 "disconnect",
48 "remoteAddress",
49 "ref",
50 "unref",
51];
52
53const POLL: Duration = Duration::from_millis(200);
55
56struct UdpRec {
58 emitter: Value,
60 socket: Arc<UdpSocket>,
62 stop: Arc<AtomicBool>,
64}
65
66#[derive(Default)]
67struct DgramState {
68 next_id: u64,
69 sockets: HashMap<u64, UdpRec>,
70}
71
72thread_local! {
73 static DGRAM: std::cell::RefCell<DgramState> = std::cell::RefCell::new(DgramState::default());
74}
75
76fn next_id() -> u64 {
77 DGRAM.with(|s| {
78 let mut s = s.borrow_mut();
79 s.next_id += 1;
80 s.next_id
81 })
82}
83
84fn get_prop(recv: &Value, key: &str) -> Option<Value> {
87 with_host(|h| match h.get(recv) {
88 Some(JsObj::Object(p)) => p.get(key).cloned(),
89 _ => None,
90 })
91}
92
93fn set_prop(recv: &Value, key: &str, val: Value) {
94 with_host(|h| {
95 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
96 p.insert(key.to_string(), val);
97 }
98 });
99}
100
101fn u64_prop(recv: &Value, key: &str) -> Option<u64> {
102 get_prop(recv, key).map(|v| with_host(|h| h.to_number(&v)) as u64)
103}
104
105fn is_udp6(recv: &Value) -> bool {
106 get_prop(recv, "@@udptype")
107 .map(|v| with_host(|h| h.str_of(&v)))
108 .as_deref()
109 == Some("udp6")
110}
111
112fn default_bind_host(recv: &Value) -> &'static str {
114 if is_udp6(recv) {
115 "::"
116 } else {
117 "0.0.0.0"
118 }
119}
120
121fn default_send_host(recv: &Value) -> &'static str {
122 if is_udp6(recv) {
123 "::1"
124 } else {
125 "127.0.0.1"
126 }
127}
128
129fn is_num(v: &Value) -> bool {
130 matches!(v, Value::Float(_) | Value::Int(_))
131}
132
133fn is_str(v: &Value) -> bool {
134 matches!(v, Value::Str(_)) || with_host(|h| matches!(h.get(v), Some(JsObj::Str(_))))
135}
136
137fn value_bytes(v: &Value) -> Vec<u8> {
140 let is_buffer =
141 with_host(|h| matches!(h.get(v), Some(JsObj::Object(p)) if p.contains_key("@@bytes")));
142 if is_buffer {
143 return with_host(|h| match h.get(v) {
144 Some(JsObj::Object(p)) => crate::stdlib::buffer::window_bytes_h(h, p),
145 _ => Vec::new(),
146 });
147 }
148 with_host(|h| h.str_of(v)).into_bytes()
149}
150
151fn emitter_dispatch(recv: &Value, method: &str, args: &[Value]) -> Option<Result<Value, String>> {
153 super::events::METHODS
154 .contains(&method)
155 .then(|| super::events::instance_call(recv, method, args.to_vec()))
156}
157
158pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
162 match method {
163 "createSocket" => Some(Ok(create_socket(args))),
164 _ => None,
165 }
166}
167
168pub fn create_socket(args: &[Value]) -> Value {
172 let first = args.first().cloned().unwrap_or(Value::Undef);
173 let sock_type = if is_str(&first) {
174 with_host(|h| h.str_of(&first))
175 } else {
176 with_host(|h| match h.get(&first) {
178 Some(JsObj::Object(p)) => p.get("type").map(|v| h.str_of(v)),
179 _ => None,
180 })
181 .unwrap_or_else(|| "udp4".to_string())
182 };
183 let sock_type = if sock_type == "udp6" { "udp6" } else { "udp4" };
184
185 let mut extra = IndexMap::new();
186 extra.insert("@@udptype".into(), with_host(|h| h.new_str(sock_type)));
187 let socket = super::net::new_emitter_object(SOCKET_TAG, extra);
188
189 if let Some(cb) = args
191 .get(1)
192 .filter(|v| with_host(|h| crate::host::is_callable(h, v)))
193 {
194 let _ = super::events::instance_call(
195 &socket,
196 "on",
197 vec![with_host(|h| h.new_str("message")), cb.clone()],
198 );
199 }
200 socket
201}
202
203pub fn instance_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
206 if let Some(r) = emitter_dispatch(recv, method, &args) {
207 return r;
208 }
209 match method {
210 "bind" => socket_bind(recv, &args),
211 "send" => socket_send(recv, &args),
212 "close" => socket_close(recv, &args),
213 "address" => socket_address(recv),
214 "setBroadcast" => {
217 let on = with_host(|h| h.truthy(args.first().unwrap_or(&Value::Undef)));
218 if let Some(sock) = live_socket(recv) {
219 sock.set_broadcast(on).ok();
220 }
221 Ok(recv.clone())
222 }
223 "setTTL" | "setMulticastTTL" => {
224 let ttl = with_host(|h| h.to_number(args.first().unwrap_or(&Value::Undef))) as u32;
225 if let Some(sock) = live_socket(recv) {
226 if method == "setTTL" {
227 sock.set_ttl(ttl).ok();
228 } else {
229 sock.set_multicast_ttl_v4(ttl).ok();
230 }
231 }
232 Ok(args.first().cloned().unwrap_or(Value::Undef))
233 }
234 "getRecvBufferSize" | "getSendBufferSize" => Ok(Value::Float(65536.0)),
235 "setMulticastLoopback"
239 | "setMulticastInterface"
240 | "addMembership"
241 | "dropMembership"
242 | "addSourceSpecificMembership"
243 | "dropSourceSpecificMembership"
244 | "setRecvBufferSize"
245 | "setSendBufferSize"
246 | "connect"
247 | "disconnect"
248 | "remoteAddress"
249 | "ref"
250 | "unref" => Ok(recv.clone()),
251 _ => Err(crate::host::type_error(&format!(
252 "socket.{method} is not a function"
253 ))),
254 }
255}
256
257fn live_socket(recv: &Value) -> Option<Arc<UdpSocket>> {
259 let id = u64_prop(recv, "@@dgramid")?;
260 DGRAM.with(|s| s.borrow().sockets.get(&id).map(|r| r.socket.clone()))
261}
262
263fn socket_bind(recv: &Value, args: &[Value]) -> Result<Value, String> {
270 let mut port: u16 = 0;
273 let mut host = default_bind_host(recv).to_string();
274 let mut cb: Option<Value> = None;
275
276 if let Some(first) = args.first() {
277 if is_num(first) {
278 port = with_host(|h| h.to_number(first)) as u16;
279 } else if with_host(
280 |h| matches!(h.get(first), Some(JsObj::Object(p)) if !p.contains_key("@@native")),
281 ) {
282 with_host(|h| {
284 if let Some(JsObj::Object(p)) = h.get(first) {
285 if let Some(pv) = p.get("port") {
286 port = h.to_number(pv) as u16;
287 }
288 if let Some(av) = p.get("address").map(|v| h.str_of(v)) {
289 host = av;
290 }
291 }
292 });
293 }
294 }
295 for a in args.iter().skip(1) {
296 if is_str(a) {
297 host = with_host(|h| h.str_of(a));
298 } else if with_host(|h| crate::host::is_callable(h, a)) {
299 cb = Some(a.clone());
300 }
301 }
302
303 do_bind(recv, &host, port)?;
304
305 let socket = recv.clone();
307 let _ = with_host(|h| h.io_sender()).send(Box::new(move || {
308 if let Some(cb) = cb {
309 super::events::instance_call(
310 &socket,
311 "once",
312 vec![with_host(|h| h.new_str("listening")), cb],
313 )?;
314 }
315 super::events::instance_call(&socket, "emit", vec![with_host(|h| h.new_str("listening"))])?;
316 Ok(())
317 }));
318 Ok(recv.clone())
319}
320
321fn do_bind(recv: &Value, host: &str, port: u16) -> Result<Arc<UdpSocket>, String> {
324 if let Some(sock) = live_socket(recv) {
325 return Ok(sock);
326 }
327 let socket =
328 UdpSocket::bind((host, port)).map_err(|e| format!("Error: bind EADDRINUSE: {e}"))?;
329 socket.set_read_timeout(Some(POLL)).ok();
331 let socket = Arc::new(socket);
332
333 let id = next_id();
334 set_prop(recv, "@@dgramid", Value::Float(id as f64));
335 let stop = Arc::new(AtomicBool::new(false));
336 DGRAM.with(|s| {
337 s.borrow_mut().sockets.insert(
338 id,
339 UdpRec {
340 emitter: recv.clone(),
341 socket: socket.clone(),
342 stop: stop.clone(),
343 },
344 );
345 });
346 with_host(|h| h.incr_handle());
347
348 let tx = with_host(|h| h.io_sender());
350 let recv_sock = socket.clone();
351 std::thread::spawn(move || recv_loop(recv_sock, id, stop, tx));
352
353 Ok(socket)
354}
355
356fn recv_loop(
359 socket: Arc<UdpSocket>,
360 id: u64,
361 stop: Arc<AtomicBool>,
362 tx: std::sync::mpsc::Sender<crate::host::IoTask>,
363) {
364 let mut buf = [0u8; 65536];
365 loop {
366 if stop.load(Ordering::Acquire) {
367 break;
368 }
369 match socket.recv_from(&mut buf) {
370 Ok((n, src)) => {
371 let bytes = buf[..n].to_vec();
372 let address = src.ip().to_string();
373 let port = src.port();
374 let family = if src.is_ipv6() { "IPv6" } else { "IPv4" };
375 let _ = tx.send(Box::new(move || {
376 on_message(id, bytes, address, port, family)
377 }));
378 }
379 Err(ref e)
381 if e.kind() == std::io::ErrorKind::WouldBlock
382 || e.kind() == std::io::ErrorKind::TimedOut =>
383 {
384 continue;
385 }
386 Err(_) => break,
387 }
388 }
389}
390
391fn on_message(
394 id: u64,
395 bytes: Vec<u8>,
396 address: String,
397 port: u16,
398 family: &'static str,
399) -> Result<(), String> {
400 let socket = DGRAM.with(|s| s.borrow().sockets.get(&id).map(|r| r.emitter.clone()));
401 let Some(socket) = socket else { return Ok(()) };
402
403 let size = bytes.len();
404 let msg = super::buffer::from_bytes(&bytes);
405 let rinfo = with_host(|h| {
406 let mut m = IndexMap::new();
407 m.insert("address".into(), h.new_str(address));
408 m.insert("family".into(), h.new_str(family));
409 m.insert("port".into(), Value::Float(port as f64));
410 m.insert("size".into(), Value::Float(size as f64));
411 h.new_object(m)
412 });
413 super::events::instance_call(
414 &socket,
415 "emit",
416 vec![with_host(|h| h.new_str("message")), msg, rinfo],
417 )?;
418 Ok(())
419}
420
421fn socket_send(recv: &Value, args: &[Value]) -> Result<Value, String> {
428 let msg = args.first().cloned().unwrap_or(Value::Undef);
429 let full = value_bytes(&msg);
430
431 let mut nums: Vec<f64> = Vec::new();
434 let mut i = 1;
435 while i < args.len() && is_num(&args[i]) {
436 nums.push(with_host(|h| h.to_number(&args[i])));
437 i += 1;
438 }
439 let (offset, length, port) = if nums.len() >= 3 {
440 (
441 nums[0].max(0.0) as usize,
442 nums[1].max(0.0) as usize,
443 nums[2] as u16,
444 )
445 } else if let Some(p) = nums.first() {
446 (0usize, full.len(), *p as u16)
447 } else {
448 return Err(crate::host::type_error("Port should be > 0 and < 65536"));
449 };
450
451 let mut address = default_send_host(recv).to_string();
453 let mut cb: Option<Value> = None;
454 for a in args.iter().skip(i) {
455 if is_str(a) {
456 address = with_host(|h| h.str_of(a));
457 } else if with_host(|h| crate::host::is_callable(h, a)) {
458 cb = Some(a.clone());
459 }
460 }
461
462 let end = offset.saturating_add(length).min(full.len());
464 let start = offset.min(full.len());
465 let data = &full[start..end.max(start)];
466
467 let socket = do_bind(recv, default_bind_host(recv), 0)?;
469 socket
470 .send_to(data, (address.as_str(), port))
471 .map_err(|e| format!("Error: send {e}"))?;
472
473 if let Some(cb) = cb {
475 let _ = with_host(|h| h.io_sender()).send(Box::new(move || {
476 let nul = with_host(|h| h.null());
477 invoke(&cb, vec![nul], None)?;
478 Ok(())
479 }));
480 }
481 Ok(Value::Undef)
482}
483
484fn socket_close(recv: &Value, args: &[Value]) -> Result<Value, String> {
489 if let Some(id) = u64_prop(recv, "@@dgramid") {
490 let rec = DGRAM.with(|s| s.borrow_mut().sockets.remove(&id));
491 if let Some(rec) = rec {
492 rec.stop.store(true, Ordering::Release);
493 with_host(|h| h.decr_handle());
494 let _ = with_host(|h| h.io_sender()).send(Box::new(|| Ok(())));
496 }
497 }
498 if let Some(cb) = args
500 .first()
501 .filter(|v| with_host(|h| crate::host::is_callable(h, v)))
502 {
503 invoke(cb, Vec::new(), None)?;
504 }
505 super::events::instance_call(recv, "emit", vec![with_host(|h| h.new_str("close"))])?;
506 Ok(Value::Undef)
507}
508
509fn socket_address(recv: &Value) -> Result<Value, String> {
512 let socket = live_socket(recv)
513 .ok_or_else(|| "Error: getsockname EBADF: bad file descriptor".to_string())?;
514 let addr = socket
515 .local_addr()
516 .map_err(|e| format!("Error: getsockname {e}"))?;
517 Ok(with_host(|h| {
518 let mut m = IndexMap::new();
519 m.insert("address".into(), h.new_str(addr.ip().to_string()));
520 m.insert(
521 "family".into(),
522 h.new_str(if addr.is_ipv6() { "IPv6" } else { "IPv4" }),
523 );
524 m.insert("port".into(), Value::Float(addr.port() as f64));
525 h.new_object(m)
526 }))
527}