1use std::cell::{Cell, RefCell, RefMut};
2use std::io;
3use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
4use std::time::Duration;
5
6use mio::event::Source;
7use rustc_target::spec::Os;
8
9use crate::shims::files::{EvalContextExt as _, FileDescription, FileDescriptionRef};
10use crate::shims::unix::UnixFileDescription;
11use crate::shims::unix::socket::{
12 EvalContextExt, UnixSocketFileDescription, socket_action_deadline,
13};
14use crate::*;
15
16#[derive(Debug)]
17pub(super) struct UdpSocket {
18 family: socket2::Domain,
21 socket: RefCell<mio::net::UdpSocket>,
23 is_non_block: Cell<bool>,
25 is_bound: Cell<bool>,
27 has_default_destination: Cell<bool>,
29 io_readiness: RefCell<Readiness>,
31 read_timeout: Cell<Option<Duration>>,
37 write_timeout: Cell<Option<Duration>>,
43 watched: ReadinessWatched,
45}
46
47impl UdpSocket {
48 pub fn new<'tcx>(
49 family: socket2::Domain,
50 is_non_block: bool,
51 ecx: &mut MiriInterpCx<'tcx>,
52 ) -> io::Result<FileDescriptionRef<Self>> {
53 let socket =
54 socket2::Socket::new(family, socket2::Type::DGRAM, Some(socket2::Protocol::UDP))?;
55 socket.set_nonblocking(true)?;
58
59 let socket = cfg_select! {
60 unix => {{
63 use std::os::fd::OwnedFd;
64 mio::net::UdpSocket::from(OwnedFd::from(socket))
65 }},
66 windows => {{
67 use std::os::windows::io::OwnedSocket;
68 mio::net::UdpSocket::from(OwnedSocket::from(socket))
69 }},
70 _ => unreachable!("unsupported host platform"),
71 };
72
73 let udp_socket = UdpSocket {
74 family,
75 socket: RefCell::new(socket),
76 is_non_block: Cell::new(is_non_block),
77 is_bound: Cell::new(false),
78 has_default_destination: Cell::new(false),
79 io_readiness: RefCell::new(Readiness::EMPTY),
83 read_timeout: Cell::new(None),
84 write_timeout: Cell::new(None),
85 watched: ReadinessWatched::default(),
86 };
87
88 let fd = ecx.machine.fds.new_ref(udp_socket);
89
90 ecx.machine.blocking_io.register(fd.clone());
93
94 Ok(fd)
95 }
96}
97
98impl FileDescription for UdpSocket {
99 fn name(&self) -> &'static str {
100 "udp socket"
101 }
102
103 fn read<'tcx>(
104 self: FileDescriptionRef<Self>,
105 communicate_allowed: bool,
106 ptr: Pointer,
107 len: u64,
108 ecx: &mut MiriInterpCx<'tcx>,
109 finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
110 ) -> InterpResult<'tcx> {
111 self.recv(
112 communicate_allowed,
113 ptr,
114 len,
115 false,
116 false,
117 ecx,
118 callback!(
119 @capture<'tcx> {
120 finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
121 } |ecx, result: Result<(u64, Option<SocketAddr>), IoError>| {
122 finish.call(ecx, result.map(|(bytes, _)| bytes))
123 }
124 ),
125 )
126 }
127
128 fn write<'tcx>(
129 self: FileDescriptionRef<Self>,
130 communicate_allowed: bool,
131 ptr: Pointer,
132 len: u64,
133 ecx: &mut MiriInterpCx<'tcx>,
134 finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
135 ) -> InterpResult<'tcx> {
136 self.send(
137 communicate_allowed,
138 ptr,
139 len,
140 false,
141 None,
142 ecx,
143 finish,
144 )
145 }
146
147 fn as_unix(self: FileDescriptionRef<Self>) -> FileDescriptionRef<dyn UnixFileDescription> {
148 self
149 }
150
151 fn readiness_watched(&self) -> Option<&ReadinessWatched> {
152 Some(&self.watched)
153 }
154
155 fn readiness(&self) -> Readiness {
156 *self.io_readiness.borrow()
157 }
158}
159
160impl UnixFileDescription for UdpSocket {
161 fn get_flags<'tcx>(&self, ecx: &mut MiriInterpCx<'tcx>) -> InterpResult<'tcx, Scalar> {
162 let mut flags = ecx.eval_libc_i32("O_RDWR");
163
164 if self.is_non_block.get() {
165 flags |= ecx.eval_libc_i32("O_NONBLOCK");
166 }
167
168 interp_ok(Scalar::from_i32(flags))
169 }
170
171 fn set_flags<'tcx>(
172 &self,
173 mut flag: i32,
174 ecx: &mut MiriInterpCx<'tcx>,
175 ) -> InterpResult<'tcx, Scalar> {
176 let o_nonblock = ecx.eval_libc_i32("O_NONBLOCK");
177
178 if flag & o_nonblock == o_nonblock {
180 self.is_non_block.set(true);
181 flag &= !o_nonblock;
182 } else {
183 self.is_non_block.set(false);
184 }
185
186 if flag != 0 {
188 throw_unsup_format!("fcntl: only O_NONBLOCK is supported for sockets")
189 }
190
191 interp_ok(Scalar::from_i32(0))
192 }
193
194 fn as_socket(
195 self: FileDescriptionRef<Self>,
196 ) -> Option<FileDescriptionRef<dyn UnixSocketFileDescription>> {
197 Some(self)
198 }
199}
200
201impl UnixSocketFileDescription for UdpSocket {
202 fn bind<'tcx>(
203 self: FileDescriptionRef<Self>,
204 communicate_allowed: bool,
205 address: SocketAddr,
206 ecx: &mut MiriInterpCx<'tcx>,
207 ) -> InterpResult<'tcx, Result<(), IoError>> {
208 assert!(communicate_allowed, "cannot have `UdpSocket` with isolation enabled!");
209
210 let address_family = match &address {
211 SocketAddr::V4(_) => socket2::Domain::IPV4,
212 SocketAddr::V6(_) => socket2::Domain::IPV6,
213 };
214
215 if self.family != address_family {
216 let err = if matches!(ecx.tcx.sess.target.os, Os::Linux | Os::Android | Os::MacOs) {
219 LibcError("EINVAL")
223 } else {
224 LibcError("EAFNOSUPPORT")
228 };
229 return interp_ok(Err(err));
230 }
231
232 if let Err(e) = self.with_socket_ref(|s| s.bind(&socket2::SockAddr::from(address))).unwrap()
234 {
235 return interp_ok(Err(IoError::HostError(e)));
236 }
237
238 self.is_bound.set(true);
240
241 interp_ok(Ok(()))
242 }
243
244 fn connect<'tcx>(
245 self: FileDescriptionRef<Self>,
246 communicate_allowed: bool,
247 address: SocketAddr,
248 ecx: &mut MiriInterpCx<'tcx>,
249 finish: DynMachineCallback<'tcx, Result<(), IoError>>,
250 ) -> InterpResult<'tcx> {
251 assert!(communicate_allowed, "cannot have `UdpSocket` with isolation enabled!");
252
253 if self.has_default_destination.get() {
254 throw_unsup_format!("calling `connect` a second time on a UDP socket is unsupported");
259 }
260
261 if let Err(e) = self.socket.borrow().connect(address) {
262 return finish.call(ecx, Err(IoError::HostError(e)));
263 }
264
265 self.is_bound.set(true);
269
270 self.has_default_destination.set(true);
271
272 finish.call(ecx, Ok(()))
273 }
274
275 fn send<'tcx>(
276 self: FileDescriptionRef<Self>,
277 communicate_allowed: bool,
278 ptr: Pointer,
279 len: u64,
280 is_non_block: bool,
281 dest_addr: Option<SocketAddr>,
282 ecx: &mut MiriInterpCx<'tcx>,
283 finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
284 ) -> InterpResult<'tcx> {
285 assert!(communicate_allowed, "cannot have `UdpSocket` with isolation enabled!");
286
287 let is_non_block = is_non_block || self.is_non_block.get();
288
289 if is_non_block {
290 let result = ecx.try_non_block_send(&self, ptr, len, dest_addr)?;
293 finish.call(ecx, result)
294 } else {
295 let deadline = socket_action_deadline(ecx, is_non_block, self.write_timeout.get());
296
297 ecx.block_for_send(self, deadline, ptr, len, dest_addr, finish)
300 }
301 }
302
303 fn recv<'tcx>(
304 self: FileDescriptionRef<Self>,
305 communicate_allowed: bool,
306 ptr: Pointer,
307 len: u64,
308 is_peek: bool,
309 is_non_block: bool,
310 ecx: &mut MiriInterpCx<'tcx>,
311 finish: DynMachineCallback<'tcx, Result<(u64, Option<SocketAddr>), IoError>>,
312 ) -> InterpResult<'tcx> {
313 assert!(communicate_allowed, "cannot have `UdpSocket` with isolation enabled!");
314
315 let is_non_block = is_non_block || self.is_non_block.get();
316
317 if is_non_block {
318 let result = ecx.try_non_block_recv(&self, ptr, len, is_peek)?;
321 finish.call(ecx, result.map(|(bytes, addr)| (bytes, Some(addr))))
322 } else {
323 let deadline = socket_action_deadline(ecx, is_non_block, self.read_timeout.get());
324
325 ecx.block_for_recv(self, deadline, ptr, len, is_peek, callback!(
328 @capture<'tcx> {
329 finish: DynMachineCallback<'tcx, Result<(u64, Option<SocketAddr>), IoError>>,
330 } |ecx, result: Result<(u64, SocketAddr), IoError>| {
331 finish.call(ecx, result.map(|(bytes, addr)| (bytes, Some(addr))))
334 }
335 ))
336 }
337 }
338
339 fn setsockopt<'tcx>(
340 self: FileDescriptionRef<Self>,
341 level: i32,
342 option: i32,
343 value_ptr: Pointer,
344 value_len: u64,
345 ecx: &mut MiriInterpCx<'tcx>,
346 ) -> InterpResult<'tcx, Result<(), IoError>> {
347 if level == ecx.eval_libc_i32("SOL_SOCKET") {
348 return ecx.set_generic_socket_option(option, value_ptr, value_len, self);
349 } else if level == ecx.eval_libc_i32("IPPROTO_IP") {
350 let socket = self.socket.borrow();
351 return ecx.set_ip_socket_option(
352 option,
353 value_ptr,
354 value_len,
355 socket2::SockRef::from(&*socket),
356 );
357 }
358
359 throw_unsup_format!(
360 "setsockopt: level {level:#x} is unsupported, only SOL_SOCKET and IPPROTO_IP \
361 are allowed"
362 );
363 }
364
365 fn getsockopt<'tcx>(
366 self: FileDescriptionRef<Self>,
367 level: i32,
368 option: i32,
369 ecx: &mut MiriInterpCx<'tcx>,
370 ) -> InterpResult<'tcx, Result<MPlaceTy<'tcx>, IoError>> {
371 if level == ecx.eval_libc_i32("SOL_SOCKET") {
372 ecx.get_generic_socket_option(option, self)
373 } else if level == ecx.eval_libc_i32("IPPROTO_IP") {
374 let socket = self.socket.borrow();
375 ecx.get_ip_socket_option(option, socket2::SockRef::from(&*socket))
376 } else {
377 throw_unsup_format!(
378 "getsockopt: level {level:#x} is unsupported, only SOL_SOCKET and IPPROTO_IP \
379 are allowed"
380 )
381 }
382 }
383
384 fn getsockname<'tcx>(
385 self: FileDescriptionRef<Self>,
386 communicate_allowed: bool,
387 _ecx: &mut MiriInterpCx<'tcx>,
388 ) -> InterpResult<'tcx, Result<SocketAddr, IoError>> {
389 assert!(communicate_allowed, "cannot have `UdpSocket` with isolation enabled!");
390
391 if !self.is_bound.get() {
392 let address = if self.family == socket2::Domain::IPV4 {
397 SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0))
398 } else {
399 SocketAddr::V6(SocketAddrV6::new(
400 Ipv6Addr::UNSPECIFIED,
401 0,
402 0,
403 0,
404 ))
405 };
406 return interp_ok(Ok(address));
407 }
408
409 interp_ok(self.socket.borrow().local_addr().map_err(IoError::HostError))
410 }
411
412 fn getpeername<'tcx>(
413 self: FileDescriptionRef<Self>,
414 communicate_allowed: bool,
415 ecx: &mut MiriInterpCx<'tcx>,
416 finish: DynMachineCallback<'tcx, Result<SocketAddr, IoError>>,
417 ) -> InterpResult<'tcx> {
418 assert!(communicate_allowed, "cannot have `UdpSocket` with isolation enabled!");
419
420 finish.call(ecx, self.socket.borrow().peer_addr().map_err(IoError::HostError))
421 }
422
423 fn set_read_timeout<'tcx>(
424 self: FileDescriptionRef<Self>,
425 timeout: Option<Duration>,
426 ) -> InterpResult<'tcx> {
427 self.read_timeout.set(timeout);
428 interp_ok(())
429 }
430
431 fn get_read_timeout<'tcx>(
432 self: FileDescriptionRef<Self>,
433 ) -> InterpResult<'tcx, Option<Duration>> {
434 interp_ok(self.read_timeout.get())
435 }
436
437 fn set_write_timeout<'tcx>(
438 self: FileDescriptionRef<Self>,
439 timeout: Option<Duration>,
440 ) -> InterpResult<'tcx> {
441 self.write_timeout.set(timeout);
442 interp_ok(())
443 }
444
445 fn get_write_timeout<'tcx>(
446 self: FileDescriptionRef<Self>,
447 ) -> InterpResult<'tcx, Option<Duration>> {
448 interp_ok(self.write_timeout.get())
449 }
450
451 fn with_socket_ref<T>(&self, cb: impl FnOnce(socket2::SockRef<'_>) -> T) -> Result<T, ()>
452 where
453 Self: Sized,
454 {
455 let socket = self.socket.borrow();
456 Ok(cb(socket2::SockRef::from(&*socket)))
457 }
458}
459
460impl<'tcx> EvalContextPrivExt<'tcx> for crate::MiriInterpCx<'tcx> {}
461trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
462 fn block_for_send(
467 &mut self,
468 socket: FileDescriptionRef<UdpSocket>,
469 deadline: Option<Deadline>,
470 buffer_ptr: Pointer,
471 length: u64,
472 dest_addr: Option<SocketAddr>,
473 finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
474 ) -> InterpResult<'tcx> {
475 let ecx = self.eval_context_mut();
476 ecx.block_thread_for_io(
480 socket.clone(),
481 BlockingIoInterest::Write,
482 deadline.clone(),
483 callback!(@capture<'tcx> {
484 socket: FileDescriptionRef<UdpSocket>,
485 deadline: Option<Deadline>,
486 buffer_ptr: Pointer,
487 length: u64,
488 dest_addr: Option<SocketAddr>,
489 finish: DynMachineCallback<'tcx, Result<u64, IoError>>,
490 } |ecx, kind: UnblockKind| {
491 ecx.machine.blocking_io.remove_blocked_thread(socket.id(), ecx.machine.threads.active_thread());
493
494 match kind {
495 UnblockKind::Ready => { },
496 UnblockKind::TimedOut => return finish.call(ecx, Err(LibcError("EWOULDBLOCK")))
498 }
499
500 match ecx.try_non_block_send(&socket, buffer_ptr, length, dest_addr)? {
501 Err(IoError::HostError(e)) if e.kind() == io::ErrorKind::WouldBlock => {
502 ecx.block_for_send(socket, deadline, buffer_ptr, length, dest_addr, finish)
504 },
505 result => finish.call(ecx, result)
506 }
507 }),
508 )
509 }
510
511 fn try_non_block_send(
515 &mut self,
516 socket: &FileDescriptionRef<UdpSocket>,
517 buffer_ptr: Pointer,
518 length: u64,
519 dest_addr: Option<SocketAddr>,
520 ) -> InterpResult<'tcx, Result<u64, IoError>> {
521 let ecx = self.eval_context_mut();
522
523 let host_socket = socket.socket.borrow();
524
525 if dest_addr.is_some() && socket.has_default_destination.get() {
526 if matches!(ecx.tcx.sess.target.os, Os::FreeBsd | Os::MacOs) {
533 return interp_ok(Err(LibcError("EISCONN")));
536 } else if cfg!(any(target_os = "freebsd", target_vendor = "apple")) {
537 throw_unsup_format!(
541 "sendto: overwriting default destination address is not supported for UDP sockets on BSD hosts"
542 )
543 }
544 }
545
546 let result = ecx.write_to_host(buffer_ptr, length, |bytes| {
548 match dest_addr {
549 Some(dest_addr) => host_socket.send_to(bytes, dest_addr),
550 None => host_socket.send(bytes),
551 }
552 })?;
553
554 if result.is_ok() {
555 assert!(!socket.io_readiness.borrow().write_closed, "successful write after close");
557
558 if dest_addr.is_some() {
559 socket.is_bound.set(true);
561 } else {
562 assert!(socket.is_bound.get());
564 }
565 }
566
567 match result {
568 Err(IoError::HostError(e)) if matches!(e.kind(), io::ErrorKind::WouldBlock) => {
569 socket.io_readiness.borrow_mut().writable = false;
571 ecx.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::DEFAULT)?;
572
573 interp_ok(Err(IoError::HostError(e)))
574 }
575 Err(IoError::HostError(e))
576 if cfg!(windows) && matches!(e.kind(), io::ErrorKind::NotConnected) =>
577 {
578 interp_ok(Err(IoError::LibcError("EDESTADDRREQ")))
581 }
582 Err(IoError::HostError(e))
583 if cfg!(windows)
584 && e.raw_os_error().is_some_and(|errno| errno == 10040) =>
585 {
586 interp_ok(Err(IoError::LibcError("EMSGSIZE")))
595 }
596 result => interp_ok(result),
597 }
598 }
599
600 fn block_for_recv(
604 &mut self,
605 socket: FileDescriptionRef<UdpSocket>,
606 deadline: Option<Deadline>,
607 buffer_ptr: Pointer,
608 length: u64,
609 should_peek: bool,
610 finish: DynMachineCallback<'tcx, Result<(u64, SocketAddr), IoError>>,
611 ) -> InterpResult<'tcx> {
612 let recv = self.eval_context_mut();
613 recv.block_thread_for_io(
617 socket.clone(),
618 BlockingIoInterest::Read,
619 deadline.clone(),
620 callback!(@capture<'tcx> {
621 socket: FileDescriptionRef<UdpSocket>,
622 deadline: Option<Deadline>,
623 buffer_ptr: Pointer,
624 length: u64,
625 should_peek: bool,
626 finish: DynMachineCallback<'tcx, Result<(u64, SocketAddr), IoError>>,
627 } |ecx, kind: UnblockKind| {
628 ecx.machine.blocking_io.remove_blocked_thread(socket.id(), ecx.machine.threads.active_thread());
630
631 match kind {
632 UnblockKind::Ready => { },
633 UnblockKind::TimedOut => return finish.call(ecx, Err(LibcError("EWOULDBLOCK")))
635 }
636
637 match ecx.try_non_block_recv(&socket, buffer_ptr, length, should_peek)? {
638 Err(IoError::HostError(e)) if e.kind() == io::ErrorKind::WouldBlock => {
639 ecx.block_for_recv(socket, deadline, buffer_ptr, length, should_peek, finish)
641 },
642 result => finish.call(ecx, result)
643 }
644 }),
645 )
646 }
647
648 fn try_non_block_recv(
650 &mut self,
651 socket: &FileDescriptionRef<UdpSocket>,
652 buffer_ptr: Pointer,
653 length: u64,
654 should_peek: bool,
655 ) -> InterpResult<'tcx, Result<(u64, SocketAddr), IoError>> {
656 let ecx = self.eval_context_mut();
657
658 let host_socket = socket.socket.borrow();
659
660 let mut origin_addr = None;
663
664 let mut recv_from_host_socket = |buf: &mut [u8]| {
665 let result =
666 if should_peek { host_socket.peek_from(buf) } else { host_socket.recv_from(buf) };
667
668 result.map(|(bytes, addr)| {
669 origin_addr.replace(addr);
672
673 bytes
675 })
676 };
677
678 let result = ecx.read_from_host(buffer_ptr, length, |buf| {
680 if cfg!(windows) {
681 #[expect(clippy::as_conversions)]
694 let mut tmp_buf = [0u8; u16::MAX as usize];
695 let result = recv_from_host_socket(&mut tmp_buf).map(|bytes| {
696 let bytes_received = bytes.min(usize::try_from(length).unwrap());
697 buf[..bytes_received].copy_from_slice(&tmp_buf[..bytes_received]);
698
699 bytes_received
701 });
702
703 if let Err(ref e) = result {
704 assert_ne!(e.raw_os_error(), Some(10040))
707 }
708
709 return result;
710 }
711
712 recv_from_host_socket(buf)
713 })?;
714
715 match result {
716 Err(IoError::HostError(e)) if matches!(e.kind(), io::ErrorKind::WouldBlock) => {
717 socket.io_readiness.borrow_mut().readable = false;
719 ecx.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::DEFAULT)?;
720
721 interp_ok(Err(IoError::HostError(e)))
722 }
723 result => interp_ok(result.map(|bytes| (bytes, origin_addr.unwrap()))),
726 }
727 }
728}
729
730impl SourceFileDescription for UdpSocket {
731 fn with_source(&self, f: &mut dyn FnMut(&mut dyn Source) -> io::Result<()>) -> io::Result<()> {
732 let mut socket = self.socket.borrow_mut();
733 f(&mut *socket)
734 }
735
736 fn get_readiness_mut(&self) -> RefMut<'_, Readiness> {
737 self.io_readiness.borrow_mut()
738 }
739}