Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/vendor/uefi/src/proto/network/pxe.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / vendor / uefi / src / proto / network / pxe.rs` 1200 lines · 43177 bytes Raw Blame History 1 // SPDX-License-Identifier: MIT OR Apache-2.0 2 3 //! PXE Base Code protocol. 4 5 use crate::polyfill::maybe_uninit_slice_as_mut_ptr; 6 use crate::proto::unsafe_protocol; 7 use crate::util::{ptr_write_unaligned_and_add, usize_from_u32}; 8 use crate::{CStr8, Result, Status, StatusExt}; 9 use core::fmt::{self, Debug, Display, Formatter}; 10 use core::iter::from_fn; 11 use core::mem::MaybeUninit; 12 use core::net::{IpAddr, Ipv4Addr}; 13 use core::ptr::{self, null, null_mut}; 14 use core::{error, result, str}; 15 use ptr_meta::Pointee; 16 use uefi::proto::network::EfiMacAddr; 17 use uefi_raw::protocol::network::pxe::{ 18 PxeBaseCodeDiscoverInfo, PxeBaseCodeMode, PxeBaseCodeProtocol, PxeBaseCodeTftpOpcode, 19 }; 20 use uefi_raw::{Boolean, Char8, IpAddress as EfiIpAddr}; 21 22 pub use uefi_raw::protocol::network::pxe::{ 23 PxeBaseCodeArpEntry as ArpEntry, PxeBaseCodeBootType as BootstrapType, 24 PxeBaseCodeDhcpV4Flags as DhcpV4Flags, PxeBaseCodeDhcpV4Packet as DhcpV4Packet, 25 PxeBaseCodeDhcpV6Packet as DhcpV6Packet, PxeBaseCodeIcmpError as IcmpError, 26 PxeBaseCodeIcmpErrorEcho as IcmpErrorEcho, PxeBaseCodeIcmpErrorUnion as IcmpErrorUnion, 27 PxeBaseCodeIpFilter as IpFilter, PxeBaseCodeIpFilterFlags as IpFilters, 28 PxeBaseCodeMtftpInfo as MtftpInfo, PxeBaseCodePacket as Packet, 29 PxeBaseCodeRouteEntry as RouteEntry, PxeBaseCodeSrvlist as Server, 30 PxeBaseCodeTftpError as TftpError, PxeBaseCodeUdpOpFlags as UdpOpFlags, 31 }; 32 33 /// PXE Base Code [`Protocol`]. 34 /// 35 /// [`Protocol`]: uefi::proto::Protocol 36 #[derive(Debug)] 37 #[repr(transparent)] 38 #[unsafe_protocol(PxeBaseCodeProtocol::GUID)] 39 pub struct BaseCode(PxeBaseCodeProtocol); 40 41 impl BaseCode { 42 /// Enables the use of the PXE Base Code Protocol functions. 43 pub fn start(&mut self, use_ipv6: bool) -> Result { 44 // SAFETY: The memory is valid. 45 unsafe { (self.0.start)(&mut self.0, use_ipv6.into()) }.to_result() 46 } 47 48 /// Disables the use of the PXE Base Code Protocol functions. 49 pub fn stop(&mut self) -> Result { 50 // SAFETY: The memory is valid. 51 unsafe { (self.0.stop)(&mut self.0) }.to_result() 52 } 53 54 /// Attempts to complete a DHCPv4 D.O.R.A. (discover / offer / request / 55 /// acknowledge) or DHCPv6 S.A.R.R (solicit / advertise / request / reply) sequence. 56 pub fn dhcp(&mut self, sort_offers: bool) -> Result { 57 // SAFETY: The memory is valid. 58 unsafe { (self.0.dhcp)(&mut self.0, sort_offers.into()) }.to_result() 59 } 60 61 /// Attempts to complete the PXE Boot Server and/or boot image discovery 62 /// sequence. 63 pub fn discover( 64 &mut self, 65 ty: BootstrapType, 66 layer: &mut u16, 67 use_bis: bool, 68 info: Option<&DiscoverInfo>, 69 ) -> Result { 70 let info: *const PxeBaseCodeDiscoverInfo = info 71 .map(|info| ptr::from_ref(info).cast()) 72 .unwrap_or(null()); 73 74 // SAFETY: The memory is valid. 75 unsafe { (self.0.discover)(&mut self.0, ty, layer, use_bis.into(), info) }.to_result() 76 } 77 78 /// Returns the size of a file located on a TFTP server. 79 pub fn tftp_get_file_size(&mut self, server_ip: &IpAddr, filename: &CStr8) -> Result { 80 let mut buffer_size = 0; 81 82 let server_ip = EfiIpAddr::from(*server_ip); 83 // SAFETY: The memory is valid. 84 let status = unsafe { 85 (self.0.mtftp)( 86 &mut self.0, 87 PxeBaseCodeTftpOpcode::TFTP_GET_FILE_SIZE, 88 null_mut(), 89 Boolean::FALSE, 90 &mut buffer_size, 91 null(), 92 &server_ip, 93 cstr8_to_ptr(filename), 94 null(), 95 Boolean::FALSE, 96 ) 97 }; 98 status.to_result_with_val(|| buffer_size) 99 } 100 101 /// Reads a file located on a TFTP server. 102 pub fn tftp_read_file( 103 &mut self, 104 server_ip: &IpAddr, 105 filename: &CStr8, 106 buffer: Option<&mut [u8]>, 107 ) -> Result { 108 let (buffer_ptr, mut buffer_size, dont_use_buffer) = if let Some(buffer) = buffer { 109 let buffer_size = u64::try_from(buffer.len()).unwrap(); 110 (buffer.as_mut_ptr().cast(), buffer_size, Boolean::FALSE) 111 } else { 112 (null_mut(), 0, Boolean::TRUE) 113 }; 114 115 let server_ip = EfiIpAddr::from(*server_ip); 116 // SAFETY: The memory is valid. 117 let status = unsafe { 118 (self.0.mtftp)( 119 &mut self.0, 120 PxeBaseCodeTftpOpcode::TFTP_READ_FILE, 121 buffer_ptr, 122 Boolean::FALSE, 123 &mut buffer_size, 124 null(), 125 &server_ip, 126 cstr8_to_ptr(filename), 127 null(), 128 dont_use_buffer, 129 ) 130 }; 131 status.to_result_with_val(|| buffer_size) 132 } 133 134 /// Writes to a file located on a TFTP server. 135 pub fn tftp_write_file( 136 &mut self, 137 server_ip: &IpAddr, 138 filename: &CStr8, 139 overwrite: bool, 140 buffer: &[u8], 141 ) -> Result { 142 let buffer_ptr = buffer.as_ptr().cast_mut().cast(); 143 let mut buffer_size = u64::try_from(buffer.len()).expect("buffer length should fit in u64"); 144 145 let server_ip = EfiIpAddr::from(*server_ip); 146 // SAFETY: The memory is valid. 147 unsafe { 148 (self.0.mtftp)( 149 &mut self.0, 150 PxeBaseCodeTftpOpcode::TFTP_WRITE_FILE, 151 buffer_ptr, 152 overwrite.into(), 153 &mut buffer_size, 154 null(), 155 &server_ip, 156 cstr8_to_ptr(filename), 157 null(), 158 Boolean::FALSE, 159 ) 160 } 161 .to_result() 162 } 163 164 /// Reads a directory listing of a directory on a TFTP server. 165 pub fn tftp_read_dir<'a>( 166 &mut self, 167 server_ip: &IpAddr, 168 directory_name: &CStr8, 169 buffer: &'a mut [u8], 170 ) -> Result, ReadDirParseError>> + 'a> 171 { 172 let buffer_ptr = buffer.as_mut_ptr().cast(); 173 let mut buffer_size = u64::try_from(buffer.len()).expect("buffer length should fit in u64"); 174 175 let server_ip = EfiIpAddr::from(*server_ip); 176 // SAFETY: The memory is valid. 177 let status = unsafe { 178 (self.0.mtftp)( 179 &mut self.0, 180 PxeBaseCodeTftpOpcode::TFTP_READ_DIRECTORY, 181 buffer_ptr, 182 Boolean::FALSE, 183 &mut buffer_size, 184 null(), 185 &server_ip, 186 cstr8_to_ptr(directory_name), 187 null(), 188 Boolean::FALSE, 189 ) 190 }; 191 status.to_result()?; 192 193 let buffer_size = usize::try_from(buffer_size).expect("buffer length should fit in usize"); 194 let buffer = &buffer[..buffer_size]; 195 196 let mut iterator = buffer.split_inclusive(|b| *b == 0); 197 let mut parse_next = move || { 198 let filename = iterator.next().ok_or(ReadDirParseError)?; 199 if filename == [0] { 200 // This is the final entry. 201 return Ok(None); 202 } 203 let filename = CStr8::from_bytes_with_nul(filename).unwrap(); 204 205 let information_string = iterator.next().ok_or(ReadDirParseError)?; 206 let (_null_terminator, information_string) = information_string.split_last().unwrap(); 207 let information_string = 208 str::from_utf8(information_string).map_err(|_| ReadDirParseError)?; 209 210 let (size, rest) = information_string 211 .split_once(' ') 212 .ok_or(ReadDirParseError)?; 213 let (year, rest) = rest.split_once('-').ok_or(ReadDirParseError)?; 214 let (month, rest) = rest.split_once('-').ok_or(ReadDirParseError)?; 215 let (day, rest) = rest.split_once(' ').ok_or(ReadDirParseError)?; 216 let (hour, rest) = rest.split_once(':').ok_or(ReadDirParseError)?; 217 let (minute, second) = rest.split_once(':').ok_or(ReadDirParseError)?; 218 219 let size = size.parse().map_err(|_| ReadDirParseError)?; 220 let year = year.parse().map_err(|_| ReadDirParseError)?; 221 let month = month.parse().map_err(|_| ReadDirParseError)?; 222 let day = day.parse().map_err(|_| ReadDirParseError)?; 223 let hour = hour.parse().map_err(|_| ReadDirParseError)?; 224 let minute = minute.parse().map_err(|_| ReadDirParseError)?; 225 let second = second.parse().map_err(|_| ReadDirParseError)?; 226 227 Ok(Some(TftpFileInfo { 228 filename, 229 size, 230 year, 231 month, 232 day, 233 hour, 234 minute, 235 second, 236 })) 237 }; 238 Ok(from_fn(move || parse_next().transpose()).fuse()) 239 } 240 241 /// Returns the size of a file located on a MTFTP server. 242 pub fn mtftp_get_file_size( 243 &mut self, 244 server_ip: &IpAddr, 245 filename: &CStr8, 246 info: &MtftpInfo, 247 ) -> Result { 248 let mut buffer_size = 0; 249 250 let server_ip = EfiIpAddr::from(*server_ip); 251 // SAFETY: The memory is valid. 252 let status = unsafe { 253 (self.0.mtftp)( 254 &mut self.0, 255 PxeBaseCodeTftpOpcode::MTFTP_GET_FILE_SIZE, 256 null_mut(), 257 Boolean::FALSE, 258 &mut buffer_size, 259 null(), 260 &server_ip, 261 cstr8_to_ptr(filename), 262 info, 263 Boolean::FALSE, 264 ) 265 }; 266 status.to_result_with_val(|| buffer_size) 267 } 268 269 /// Reads a file located on a MTFTP server. 270 pub fn mtftp_read_file( 271 &mut self, 272 server_ip: &IpAddr, 273 filename: &CStr8, 274 buffer: Option<&mut [u8]>, 275 info: &MtftpInfo, 276 ) -> Result { 277 let (buffer_ptr, mut buffer_size, dont_use_buffer) = if let Some(buffer) = buffer { 278 let buffer_size = u64::try_from(buffer.len()).unwrap(); 279 (buffer.as_mut_ptr().cast(), buffer_size, Boolean::FALSE) 280 } else { 281 (null_mut(), 0, Boolean::TRUE) 282 }; 283 284 let server_ip = EfiIpAddr::from(*server_ip); 285 // SAFETY: The memory is valid. 286 let status = unsafe { 287 (self.0.mtftp)( 288 &mut self.0, 289 PxeBaseCodeTftpOpcode::MTFTP_READ_FILE, 290 buffer_ptr, 291 Boolean::FALSE, 292 &mut buffer_size, 293 null(), 294 &server_ip, 295 cstr8_to_ptr(filename), 296 info, 297 dont_use_buffer, 298 ) 299 }; 300 status.to_result_with_val(|| buffer_size) 301 } 302 303 /// Reads a directory listing of a directory on a MTFTP server. 304 pub fn mtftp_read_dir<'a>( 305 &mut self, 306 server_ip: &IpAddr, 307 buffer: &'a mut [u8], 308 info: &MtftpInfo, 309 ) -> Result, ReadDirParseError>> + 'a> 310 { 311 let buffer_ptr = buffer.as_mut_ptr().cast(); 312 let mut buffer_size = u64::try_from(buffer.len()).expect("buffer length should fit in u64"); 313 314 let server_ip = EfiIpAddr::from(*server_ip); 315 // SAFETY: The memory is valid. 316 let status = unsafe { 317 (self.0.mtftp)( 318 &mut self.0, 319 PxeBaseCodeTftpOpcode::MTFTP_READ_DIRECTORY, 320 buffer_ptr, 321 Boolean::FALSE, 322 &mut buffer_size, 323 null(), 324 &server_ip, 325 null_mut(), 326 info, 327 Boolean::FALSE, 328 ) 329 }; 330 status.to_result()?; 331 332 let buffer_size = usize::try_from(buffer_size).expect("buffer length should fit in usize"); 333 let buffer = &buffer[..buffer_size]; 334 335 let mut iterator = buffer.split_inclusive(|b| *b == 0); 336 let mut parse_next = move || { 337 let filename = iterator.next().ok_or(ReadDirParseError)?; 338 if filename == [0] { 339 // This is the final entry. 340 return Ok(None); 341 } 342 let filename = CStr8::from_bytes_with_nul(filename).unwrap(); 343 344 let multicast_ip = iterator.next().ok_or(ReadDirParseError)?; 345 let (_null_terminator, multicast_ip) = multicast_ip.split_last().unwrap(); 346 let multicast_ip = str::from_utf8(multicast_ip).map_err(|_| ReadDirParseError)?; 347 let mut octets = multicast_ip.split('.'); 348 let mut buffer = [0; 4]; 349 for b in buffer.iter_mut() { 350 let octet = octets.next().ok_or(ReadDirParseError)?; 351 let octet = octet.parse().map_err(|_| ReadDirParseError)?; 352 *b = octet; 353 } 354 if octets.next().is_some() { 355 // The IP should have exact 4 octets, not more. 356 return Err(ReadDirParseError); 357 } 358 let ip_address = IpAddr::V4(Ipv4Addr::from(buffer)); 359 360 let information_string = iterator.next().ok_or(ReadDirParseError)?; 361 let (_null_terminator, information_string) = information_string.split_last().unwrap(); 362 let information_string = 363 str::from_utf8(information_string).map_err(|_| ReadDirParseError)?; 364 365 let (size, rest) = information_string 366 .split_once(' ') 367 .ok_or(ReadDirParseError)?; 368 let (year, rest) = rest.split_once('-').ok_or(ReadDirParseError)?; 369 let (month, rest) = rest.split_once('-').ok_or(ReadDirParseError)?; 370 let (day, rest) = rest.split_once(' ').ok_or(ReadDirParseError)?; 371 let (hour, rest) = rest.split_once(':').ok_or(ReadDirParseError)?; 372 let (minute, second) = rest.split_once(':').ok_or(ReadDirParseError)?; 373 374 let size = size.parse().map_err(|_| ReadDirParseError)?; 375 let year = year.parse().map_err(|_| ReadDirParseError)?; 376 let month = month.parse().map_err(|_| ReadDirParseError)?; 377 let day = day.parse().map_err(|_| ReadDirParseError)?; 378 let hour = hour.parse().map_err(|_| ReadDirParseError)?; 379 let minute = minute.parse().map_err(|_| ReadDirParseError)?; 380 let second = second.parse().map_err(|_| ReadDirParseError)?; 381 382 Ok(Some(MtftpFileInfo { 383 filename, 384 ip_address, 385 size, 386 year, 387 month, 388 day, 389 hour, 390 minute, 391 second, 392 })) 393 }; 394 Ok(from_fn(move || parse_next().transpose()).fuse()) 395 } 396 397 /// Writes a UDP packet to the network interface. 398 #[expect(clippy::too_many_arguments)] 399 pub fn udp_write( 400 &mut self, 401 op_flags: UdpOpFlags, 402 dest_ip: &IpAddr, 403 dest_port: u16, 404 gateway_ip: Option<&IpAddr>, 405 src_ip: Option<&IpAddr>, 406 src_port: Option<&mut u16>, 407 header: Option<&[u8]>, 408 buffer: &[u8], 409 ) -> Result { 410 let header_size_tmp; 411 let (header_size, header_ptr) = if let Some(header) = header { 412 header_size_tmp = header.len(); 413 (Some(&header_size_tmp), header.as_ptr().cast()) 414 } else { 415 (None, null()) 416 }; 417 418 let dest_ip = EfiIpAddr::from(*dest_ip); 419 let gateway_ip = gateway_ip.map(|ip| EfiIpAddr::from(*ip)); 420 let src_ip = src_ip.map(|ip| EfiIpAddr::from(*ip)); 421 // SAFETY: The memory is valid. 422 unsafe { 423 (self.0.udp_write)( 424 &mut self.0, 425 op_flags, 426 &dest_ip, 427 &dest_port, 428 opt_ip_addr_to_ptr(gateway_ip.as_ref()), 429 opt_ip_addr_to_ptr(src_ip.as_ref()), 430 opt_mut_to_ptr(src_port), 431 opt_ref_to_ptr(header_size), 432 header_ptr, 433 &buffer.len(), 434 buffer.as_ptr().cast(), 435 ) 436 } 437 .to_result() 438 } 439 440 /// Reads a UDP packet from the network interface. 441 /// 442 /// # Arguments 443 /// - `op_flags`: [`UdpOpFlags`] specifying the behavior of the function 444 /// - `dest_ip`: The behavior depends on whether 445 /// [`UdpOpFlags::ANY_DEST_IP`] is set. If it not set, packets must match 446 /// the specified IP. Otherwise, the corresponding IP is written into the 447 /// provided buffer. 448 /// - `dest_port`: The behavior depends on whether 449 /// [`UdpOpFlags::ANY_DEST_PORT`] is set. If it not set, packets must match 450 /// the specified port. Otherwise, the corresponding port is written into 451 /// the provided buffer. 452 /// - `src_ip`: The behavior depends on whether 453 /// [`UdpOpFlags::ANY_SRC_IP`] is set. If it not set, packets must match 454 /// the specified IP. Otherwise, the corresponding IP is written into the 455 /// provided buffer. 456 /// - `src_port`: The behavior depends on whether 457 /// [`UdpOpFlags::ANY_SRC_PORT`] is set. If it not set, packets must match 458 /// the specified port. Otherwise, the corresponding port is written into 459 /// the provided buffer. 460 /// - `header`: Optional header of the data inside `buffer`. 461 /// - `buffer`: Buffer for the UDP packet's content. 462 #[expect(clippy::too_many_arguments)] 463 pub fn udp_read( 464 &mut self, 465 op_flags: UdpOpFlags, 466 mut dest_ip: Option<&mut IpAddr>, 467 dest_port: Option<&mut u16>, 468 mut src_ip: Option<&mut IpAddr>, 469 src_port: Option<&mut u16>, 470 header: Option<&mut [u8]>, 471 buffer: &mut [u8], 472 ) -> Result { 473 let mut header_size_tmp; 474 let (header_size, header_ptr) = if let Some(header) = header { 475 header_size_tmp = header.len(); 476 // The spec declares `HeaderSize` as an IN parameter, but EDK2 477 // writes the actual header size back through it. The pointer 478 // must therefore carry write permission. 479 ( 480 ptr::from_mut(&mut header_size_tmp).cast_const(), 481 header.as_mut_ptr().cast(), 482 ) 483 } else { 484 (null(), null_mut()) 485 }; 486 487 let mut buffer_size = buffer.len(); 488 489 let mut dest_ip_efi = dest_ip.as_ref().map(|ip| EfiIpAddr::from(**ip)); 490 let mut src_ip_efi = src_ip.as_ref().map(|ip| EfiIpAddr::from(**ip)); 491 492 // SAFETY: The memory is valid. 493 let status = unsafe { 494 (self.0.udp_read)( 495 &mut self.0, 496 op_flags, 497 opt_ip_addr_to_ptr_mut(dest_ip_efi.as_mut()), 498 opt_mut_to_ptr(dest_port), 499 opt_ip_addr_to_ptr_mut(src_ip_efi.as_mut()), 500 opt_mut_to_ptr(src_port), 501 header_size, 502 header_ptr, 503 &mut buffer_size, 504 buffer.as_mut_ptr().cast(), 505 ) 506 }; 507 508 // Translate IP types back into the higher-level types. 509 let fn_replace_ip = |core_ip: &mut Option<&mut IpAddr>, efi_ip: Option| { 510 if let Some(core_ip_location) = core_ip 511 && let Some(efi_ip) = efi_ip 512 { 513 // SAFETY: We trust that `using_ipv6()` tells the truth. 514 let core_ip = unsafe { efi_ip.into_core_addr(self.mode().using_ipv6()) }; 515 **core_ip_location = core_ip; 516 } 517 }; 518 519 fn_replace_ip(&mut dest_ip, dest_ip_efi); 520 fn_replace_ip(&mut src_ip, src_ip_efi); 521 522 status.to_result_with_val(|| buffer_size) 523 } 524 525 /// Updates the IP receive filters of a network device and enables software 526 /// filtering. 527 pub fn set_ip_filter(&mut self, new_filter: &IpFilter) -> Result { 528 // SAFETY: The memory is valid. 529 unsafe { (self.0.set_ip_filter)(&mut self.0, new_filter) }.to_result() 530 } 531 532 /// Uses the ARP protocol to resolve a MAC address. 533 pub fn arp(&mut self, ip_addr: &IpAddr, mac_addr: Option<&mut EfiMacAddr>) -> Result { 534 let ip_addr = EfiIpAddr::from(*ip_addr); 535 // SAFETY: The memory is valid. 536 unsafe { (self.0.arp)(&mut self.0, &ip_addr, opt_mut_to_ptr(mac_addr)) }.to_result() 537 } 538 539 /// Updates the parameters that affect the operation of the PXE Base Code 540 /// Protocol. 541 pub fn set_parameters( 542 &mut self, 543 new_auto_arp: Option, 544 new_send_guid: Option, 545 new_ttl: Option, 546 new_tos: Option, 547 new_make_callback: Option, 548 ) -> Result { 549 // SAFETY: The memory is valid. 550 unsafe { 551 (self.0.set_parameters)( 552 &mut self.0, 553 opt_bool_to_ptr(&new_auto_arp), 554 opt_bool_to_ptr(&new_send_guid), 555 opt_ref_to_ptr(new_ttl.as_ref()), 556 opt_ref_to_ptr(new_tos.as_ref()), 557 opt_bool_to_ptr(&new_make_callback), 558 ) 559 } 560 .to_result() 561 } 562 563 /// Updates the station IP address and/or subnet mask values of a network 564 /// device. 565 pub fn set_station_ip( 566 &mut self, 567 new_station_ip: Option<&IpAddr>, 568 new_subnet_mask: Option<&IpAddr>, 569 ) -> Result { 570 let new_station_ip = new_station_ip.map(|ip| EfiIpAddr::from(*ip)); 571 let new_subnet_mask = new_subnet_mask.map(|mask| EfiIpAddr::from(*mask)); 572 // SAFETY: The memory is valid. 573 unsafe { 574 (self.0.set_station_ip)( 575 &mut self.0, 576 opt_ip_addr_to_ptr(new_station_ip.as_ref()), 577 opt_ip_addr_to_ptr(new_subnet_mask.as_ref()), 578 ) 579 } 580 .to_result() 581 } 582 583 /// Updates the contents of the cached DHCP and Discover packets. 584 #[expect(clippy::too_many_arguments)] 585 pub fn set_packets( 586 &mut self, 587 new_dhcp_discover_valid: Option, 588 new_dhcp_ack_received: Option, 589 new_proxy_offer_received: Option, 590 new_pxe_discover_valid: Option, 591 new_pxe_reply_received: Option, 592 new_pxe_bis_reply_received: Option, 593 new_dhcp_discover: Option<&Packet>, 594 new_dhcp_ack: Option<&Packet>, 595 new_proxy_offer: Option<&Packet>, 596 new_pxe_discover: Option<&Packet>, 597 new_pxe_reply: Option<&Packet>, 598 new_pxe_bis_reply: Option<&Packet>, 599 ) -> Result { 600 // SAFETY: The memory is valid. 601 unsafe { 602 (self.0.set_packets)( 603 &mut self.0, 604 opt_bool_to_ptr(&new_dhcp_discover_valid), 605 opt_bool_to_ptr(&new_dhcp_ack_received), 606 opt_bool_to_ptr(&new_proxy_offer_received), 607 opt_bool_to_ptr(&new_pxe_discover_valid), 608 opt_bool_to_ptr(&new_pxe_reply_received), 609 opt_bool_to_ptr(&new_pxe_bis_reply_received), 610 opt_ref_to_ptr(new_dhcp_discover), 611 opt_ref_to_ptr(new_dhcp_ack), 612 opt_ref_to_ptr(new_proxy_offer), 613 opt_ref_to_ptr(new_pxe_discover), 614 opt_ref_to_ptr(new_pxe_reply), 615 opt_ref_to_ptr(new_pxe_bis_reply), 616 ) 617 } 618 .to_result() 619 } 620 621 /// Returns a reference to the `Mode` struct. 622 #[must_use] 623 pub const fn mode(&self) -> &Mode { 624 // SAFETY: The memory is valid. 625 unsafe { &*(self.0.mode.cast()) } 626 } 627 } 628 629 /// Convert a `&CStr8` to a `*const uefi_raw::Char8`. 630 const fn cstr8_to_ptr(s: &CStr8) -> *const Char8 { 631 s.as_ptr().cast() 632 } 633 634 /// Convert an `&Option` to a `*const Boolean`. 635 /// 636 /// This is always a valid conversion; `bool` is an 8-bit `0` or `1`. 637 fn opt_bool_to_ptr(arg: &Option) -> *const Boolean { 638 arg.as_ref() 639 .map(|arg| ptr::from_ref(arg).cast::()) 640 .unwrap_or_else(null) 641 } 642 643 /// Convert an `Option<&EfiIpAddr>` to a `*const uefi_raw::EfiIpAddr`. 644 fn opt_ip_addr_to_ptr(arg: Option<&EfiIpAddr>) -> *const EfiIpAddr { 645 arg.map(|arg| &raw const *arg).unwrap_or_else(null) 646 } 647 648 /// Convert an `Option<&mut EfiIpAddr>` to a `*mut uefi_raw::EfiIpAddr`. 649 fn opt_ip_addr_to_ptr_mut(arg: Option<&mut EfiIpAddr>) -> *mut EfiIpAddr { 650 arg.map(|arg| &raw mut *arg).unwrap_or_else(null_mut) 651 } 652 653 /// Convert an `Option<&T>` to a `*const T`. 654 fn opt_ref_to_ptr(opt: Option<&T>) -> *const T { 655 opt.map(ptr::from_ref).unwrap_or(null()) 656 } 657 658 /// Convert an `Option<&mut T>` to a `*mut T`. 659 fn opt_mut_to_ptr(opt: Option<&mut T>) -> *mut T { 660 opt.map(ptr::from_mut).unwrap_or(null_mut()) 661 } 662 663 opaque_type! { 664 /// Opaque type that should be used to represent a pointer to a [`DiscoverInfo`] in 665 /// foreign function interfaces. This type produces a thin pointer, unlike 666 /// [`DiscoverInfo`]. 667 pub struct FfiDiscoverInfo; 668 } 669 670 /// This struct contains optional parameters for [`BaseCode::discover`]. 671 /// 672 /// Corresponds to the `EFI_PXE_BASE_CODE_DISCOVER_INFO` type in the C API. 673 #[repr(C)] 674 #[derive(Debug, Pointee)] 675 pub struct DiscoverInfo { 676 use_m_cast: bool, 677 use_b_cast: bool, 678 use_u_cast: bool, 679 must_use_list: bool, 680 server_m_cast_ip: EfiIpAddr, 681 ip_cnt: u16, 682 _padding: [u8; 2], 683 srv_list: [Server], 684 } 685 686 impl DiscoverInfo { 687 /// Create a `DiscoverInfo`. 688 /// 689 /// The `buffer` must be at least aligned to four bytes. 690 pub fn new_in_buffer<'buf>( 691 buffer: &'buf mut [MaybeUninit], 692 use_m_cast: bool, 693 use_b_cast: bool, 694 use_u_cast: bool, 695 must_use_list: bool, 696 server_m_cast_ip: EfiIpAddr, 697 srv_list: &[Server], 698 ) -> Result<&'buf mut Self> { 699 let server_count = srv_list.len(); 700 assert!(server_count <= u16::MAX as usize, "too many servers"); 701 702 let required_size = Self::base_struct_size() + size_of_val(srv_list); 703 704 if buffer.len() < required_size { 705 return Err(Status::BUFFER_TOO_SMALL.into()); 706 } 707 708 // Alignment check. 709 if buffer.as_ptr().align_offset(Self::base_struct_alignment()) != 0 { 710 return Err(Status::INVALID_PARAMETER.into()); 711 } 712 713 let mut ptr: *mut u8 = maybe_uninit_slice_as_mut_ptr(buffer); 714 // SAFETY: The memory is valid. 715 unsafe { 716 ptr_write_unaligned_and_add(&mut ptr, use_m_cast); 717 ptr_write_unaligned_and_add(&mut ptr, use_b_cast); 718 ptr_write_unaligned_and_add(&mut ptr, use_u_cast); 719 ptr_write_unaligned_and_add(&mut ptr, must_use_list); 720 ptr_write_unaligned_and_add(&mut ptr, server_m_cast_ip); 721 ptr_write_unaligned_and_add(&mut ptr, server_count as u16); 722 // Align server list (4-byte alignment). The padding is a field 723 // of the struct and must be initialized, e.g. `Debug` reads it. 724 ptr_write_unaligned_and_add(&mut ptr, [0_u8; 2]); 725 ptr::copy(srv_list.as_ptr(), ptr.cast(), server_count); 726 727 let ptr: *mut Self = 728 ptr_meta::from_raw_parts_mut(buffer.as_mut_ptr().cast(), server_count); 729 Ok(&mut *ptr) 730 } 731 } 732 733 /// Returns the fixed size of the structure without the dynamic portion. 734 const fn base_struct_size() -> usize { 735 size_of::() * 4 + size_of::() + size_of::() + 2 /* padding before server list */ 736 } 737 738 /// Alignment of the base struct. 739 const fn base_struct_alignment() -> usize { 740 4 741 } 742 743 /// Returns whether discovery should use multicast. 744 #[must_use] 745 pub const fn use_m_cast(&self) -> bool { 746 self.use_m_cast 747 } 748 749 /// Returns whether discovery should use broadcast. 750 #[must_use] 751 pub const fn use_b_cast(&self) -> bool { 752 self.use_b_cast 753 } 754 755 /// Returns whether discovery should use unicast. 756 #[must_use] 757 pub const fn use_u_cast(&self) -> bool { 758 self.use_u_cast 759 } 760 761 /// Returns whether discovery should only accept boot servers in the server 762 /// list (boot server verification). 763 #[must_use] 764 pub const fn must_use_list(&self) -> bool { 765 self.must_use_list 766 } 767 768 /// Returns the address used in multicast discovery. 769 #[must_use] 770 pub const fn server_m_cast_ip(&self) -> &EfiIpAddr { 771 &self.server_m_cast_ip 772 } 773 774 /// Returns the amount of Boot Server. 775 #[must_use] 776 pub const fn ip_cnt(&self) -> u16 { 777 self.ip_cnt 778 } 779 780 /// Returns the Boot Server list used for unicast discovery or boot server 781 /// verification. 782 #[must_use] 783 pub const fn srv_list(&self) -> &[Server] { 784 &self.srv_list 785 } 786 } 787 788 /// The data values in this structure are read-only and are updated by the 789 /// [`BaseCode`]. 790 /// 791 /// Corresponds to the `EFI_PXE_BASE_CODE_MODE` type in the C API. 792 #[repr(transparent)] 793 #[derive(Debug)] 794 pub struct Mode(PxeBaseCodeMode); 795 796 impl Mode { 797 /// `true` if this device has been started by calling [`BaseCode::start`]. 798 /// This field is set to `true` by [`BaseCode::start`] and to `false` by 799 /// the [`BaseCode::stop`] function. 800 #[must_use] 801 pub fn started(&self) -> bool { 802 self.0.started.into() 803 } 804 805 /// `true` if the UNDI protocol supports IPv6 806 #[must_use] 807 pub fn ipv6_available(&self) -> bool { 808 self.0.ipv6_available.into() 809 } 810 811 /// `true` if this PXE Base Code Protocol implementation supports IPv6. 812 #[must_use] 813 pub fn ipv6_supported(&self) -> bool { 814 self.0.ipv6_supported.into() 815 } 816 817 /// `true` if this device is currently using IPv6. This field is set by 818 /// [`BaseCode::start`]. 819 #[must_use] 820 pub fn using_ipv6(&self) -> bool { 821 self.0.using_ipv6.into() 822 } 823 824 /// `true` if this PXE Base Code implementation supports Boot Integrity 825 /// Services (BIS). This field is set by [`BaseCode::start`]. 826 #[must_use] 827 pub fn bis_supported(&self) -> bool { 828 self.0.bis_supported.into() 829 } 830 831 /// `true` if this device and the platform support Boot Integrity Services 832 /// (BIS). This field is set by [`BaseCode::start`]. 833 #[must_use] 834 pub fn bis_detected(&self) -> bool { 835 self.0.bis_detected.into() 836 } 837 838 /// `true` for automatic ARP packet generation, `false` otherwise. This 839 /// field is initialized to `true` by [`BaseCode::start`] and can be 840 /// modified with [`BaseCode::set_parameters`]. 841 #[must_use] 842 pub fn auto_arp(&self) -> bool { 843 self.0.auto_arp.into() 844 } 845 846 /// This field is used to change the Client Hardware Address (chaddr) field 847 /// in the DHCP and Discovery packets. Set to `true` to send the SystemGuid 848 /// (if one is available). Set to `false` to send the client NIC MAC 849 /// address. This field is initialized to `false` by [`BaseCode::start`] 850 /// and can be modified with [`BaseCode::set_parameters`]. 851 #[must_use] 852 pub fn send_guid(&self) -> bool { 853 self.0.send_guid.into() 854 } 855 856 /// This field is initialized to `false` by [`BaseCode::start`] and set to 857 /// `true` when [`BaseCode::dhcp`] completes successfully. When `true`, 858 /// [`Self::dhcp_discover`] is valid. This field can also be changed by 859 /// [`BaseCode::set_packets`]. 860 #[must_use] 861 pub fn dhcp_discover_valid(&self) -> bool { 862 self.0.dhcp_discover_valid.into() 863 } 864 865 /// This field is initialized to `false` by [`BaseCode::start`] and set to 866 /// `true` when [`BaseCode::dhcp`] completes successfully. When `true`, 867 /// [`Self::dhcp_ack`] is valid. This field can also be changed by 868 /// [`BaseCode::set_packets`]. 869 #[must_use] 870 pub fn dhcp_ack_received(&self) -> bool { 871 self.0.dhcp_ack_received.into() 872 } 873 874 /// This field is initialized to `false` by [`BaseCode::start`] and set to 875 /// `true` when [`BaseCode::dhcp`] completes successfully and a proxy DHCP 876 /// offer packet was received. When `true`, [`Self::proxy_offer`] is valid. 877 /// This field can also be changed by [`BaseCode::set_packets`]. 878 #[must_use] 879 pub fn proxy_offer_received(&self) -> bool { 880 self.0.proxy_offer_received.into() 881 } 882 883 /// When `true`, [`Self::pxe_discover`] is valid. This field is set to 884 /// `false` by [`BaseCode::start`] and [`BaseCode::dhcp`], and can be set 885 /// to `true` or `false` by [`BaseCode::discover`] and 886 /// [`BaseCode::set_packets`]. 887 #[must_use] 888 pub fn pxe_discover_valid(&self) -> bool { 889 self.0.pxe_discover_valid.into() 890 } 891 892 /// When `true`, [`Self::pxe_reply`] is valid. This field is set to `false` 893 /// by [`BaseCode::start`] and [`BaseCode::dhcp`], and can be set to `true` 894 /// or `false` by [`BaseCode::discover`] and [`BaseCode::set_packets`]. 895 #[must_use] 896 pub fn pxe_reply_received(&self) -> bool { 897 self.0.pxe_reply_received.into() 898 } 899 900 /// When `true`, [`Self::pxe_bis_reply`] is valid. This field is set to 901 /// `false` by [`BaseCode::start`] and [`BaseCode::dhcp`], and can be set 902 /// to `true` or `false` by the [`BaseCode::discover`] and 903 /// [`BaseCode::set_packets`]. 904 #[must_use] 905 pub fn pxe_bis_reply_received(&self) -> bool { 906 self.0.pxe_bis_reply_received.into() 907 } 908 909 /// Indicates whether [`Self::icmp_error`] has been updated. This field is 910 /// reset to `false` by [`BaseCode::start`], [`BaseCode::dhcp`], 911 /// [`BaseCode::discover`],[`BaseCode::udp_read`], [`BaseCode::udp_write`], 912 /// [`BaseCode::arp`] and any of the TFTP/MTFTP operations. If an ICMP 913 /// error is received, this field will be set to `true` after 914 /// [`Self::icmp_error`] is updated. 915 #[must_use] 916 pub fn icmp_error_received(&self) -> bool { 917 self.0.icmp_error_received.into() 918 } 919 920 /// Indicates whether [`Self::tftp_error`] has been updated. This field is 921 /// reset to `false` by [`BaseCode::start`] and any of the TFTP/MTFTP 922 /// operations. If a TFTP error is received, this field will be set to 923 /// `true` after [`Self::tftp_error`] is updated. 924 #[must_use] 925 pub fn tftp_error_received(&self) -> bool { 926 self.0.tftp_error_received.into() 927 } 928 929 /// When `false`, callbacks will not be made. When `true`, make callbacks 930 /// to the PXE Base Code Callback Protocol. This field is reset to `false` 931 /// by [`BaseCode::start`] if the PXE Base Code Callback Protocol is not 932 /// available. It is reset to `true` by [`BaseCode::start`] if the PXE Base 933 /// Code Callback Protocol is available. 934 #[must_use] 935 pub fn make_callbacks(&self) -> bool { 936 self.0.make_callbacks.into() 937 } 938 939 /// The "time to live" field of the IP header. This field is initialized to 940 /// `16` by [`BaseCode::start`] and can be modified by 941 /// [`BaseCode::set_parameters`]. 942 #[must_use] 943 pub const fn ttl(&self) -> u8 { 944 self.0.ttl 945 } 946 947 /// The type of service field of the IP header. This field is initialized 948 /// to `0` by [`BaseCode::start`], and can be modified with 949 /// [`BaseCode::set_parameters`]. 950 #[must_use] 951 pub const fn tos(&self) -> u8 { 952 self.0.tos 953 } 954 955 /// The device’s current IP address. This field is initialized to a zero 956 /// address by Start(). This field is set when [`BaseCode::dhcp`] completes 957 /// successfully. This field can also be set by 958 /// [`BaseCode::set_station_ip`]. This field must be set to a valid IP 959 /// address by either [`BaseCode::dhcp`] or [`BaseCode::set_station_ip`] 960 /// before [`BaseCode::discover`], [`BaseCode::udp_read`], 961 /// [`BaseCode::udp_write`], [`BaseCode::arp`] and any of the TFTP/MTFTP 962 /// operations are called. 963 #[must_use] 964 pub fn station_ip(&self) -> IpAddr { 965 let efi_ip = self.0.station_ip; 966 // SAFETY: We trust that `using_ipv6()` tells the truth. 967 unsafe { efi_ip.into_core_addr(self.using_ipv6()) } 968 } 969 970 /// The device's current subnet mask. This field is initialized to a zero 971 /// address by [`BaseCode::start`]. This field is set when 972 /// [`BaseCode::dhcp`] completes successfully. This field can also be set 973 /// by [`BaseCode::set_station_ip`]. This field must be set to a valid 974 /// subnet mask by either [`BaseCode::dhcp`] or 975 /// [`BaseCode::set_station_ip`] before [`BaseCode::discover`], 976 /// [`BaseCode::udp_read`], [`BaseCode::udp_write`], 977 /// [`BaseCode::arp`] or any of the TFTP/MTFTP operations are called. 978 #[must_use] 979 pub fn subnet_mask(&self) -> IpAddr { 980 let efi_ip = self.0.subnet_mask; 981 // SAFETY: We trust that `using_ipv6()` tells the truth. 982 unsafe { efi_ip.into_core_addr(self.using_ipv6()) } 983 } 984 985 /// Cached DHCP Discover packet. This field is zero-filled by the 986 /// [`BaseCode::start`] function, and is set when [`BaseCode::dhcp`] 987 /// completes successfully. The contents of this field can replaced by 988 /// [`BaseCode::set_packets`]. 989 #[must_use] 990 pub const fn dhcp_discover(&self) -> &Packet { 991 &self.0.dhcp_discover 992 } 993 994 /// Cached DHCP Ack packet. This field is zero-filled by 995 /// [`BaseCode::start`], and is set when [`BaseCode::dhcp`] completes 996 /// successfully. The contents of this field can be replaced by 997 /// [`BaseCode::set_packets`]. 998 #[must_use] 999 pub const fn dhcp_ack(&self) -> &Packet { 1000 &self.0.dhcp_ack 1001 } 1002 1003 /// Cached Proxy Offer packet. This field is zero-filled by 1004 /// [`BaseCode::start`], and is set when [`BaseCode::dhcp`] completes 1005 /// successfully. The contents of this field can be replaced by 1006 /// [`BaseCode::set_packets`]. 1007 #[must_use] 1008 pub const fn proxy_offer(&self) -> &Packet { 1009 &self.0.proxy_offer 1010 } 1011 1012 /// Cached PXE Discover packet. This field is zero-filled by 1013 /// [`BaseCode::start`], and is set when [`BaseCode::discover`] completes 1014 /// successfully. The contents of this field can be replaced by 1015 /// [`BaseCode::set_packets`]. 1016 #[must_use] 1017 pub const fn pxe_discover(&self) -> &Packet { 1018 &self.0.pxe_discover 1019 } 1020 1021 /// Cached PXE Reply packet. This field is zero-filled by 1022 /// [`BaseCode::start`], and is set when [`BaseCode::discover`] completes 1023 /// successfully. The contents of this field can be replaced by the 1024 /// [`BaseCode::set_packets`] function. 1025 #[must_use] 1026 pub const fn pxe_reply(&self) -> &Packet { 1027 &self.0.pxe_reply 1028 } 1029 1030 /// Cached PXE BIS Reply packet. This field is zero-filled by 1031 /// [`BaseCode::start`], and is set when [`BaseCode::discover`] completes 1032 /// successfully. This field can be replaced by [`BaseCode::set_packets`]. 1033 #[must_use] 1034 pub const fn pxe_bis_reply(&self) -> &Packet { 1035 &self.0.pxe_bis_reply 1036 } 1037 1038 /// The current IP receive filter settings. The receive filter is disabled 1039 /// and the number of IP receive filters is set to zero by 1040 /// [`BaseCode::start`], and is set by [`BaseCode::set_ip_filter`]. 1041 #[must_use] 1042 pub const fn ip_filter(&self) -> &IpFilter { 1043 &self.0.ip_filter 1044 } 1045 1046 /// Cached ARP entries. 1047 #[must_use] 1048 pub const fn arp_cache(&self) -> &[ArpEntry] { 1049 self.0 1050 .arp_cache 1051 .split_at(usize_from_u32(self.0.arp_cache_entries)) 1052 .0 1053 } 1054 1055 /// The number of valid entries in the current route table. This field is 1056 /// reset to zero by [`BaseCode::start`]. 1057 #[must_use] 1058 pub const fn route_table_entries(&self) -> u32 { 1059 self.0.route_table_entries 1060 } 1061 1062 /// Array of route table entries. 1063 #[must_use] 1064 pub const fn route_table(&self) -> &[RouteEntry] { 1065 self.0 1066 .route_table 1067 .split_at(usize_from_u32(self.0.route_table_entries)) 1068 .0 1069 } 1070 1071 /// ICMP error packet. This field is updated when an ICMP error is received 1072 /// and is undefined until the first ICMP error is received. This field is 1073 /// zero-filled by [`BaseCode::start`]. 1074 #[must_use] 1075 pub const fn icmp_error(&self) -> &IcmpError { 1076 &self.0.icmp_error 1077 } 1078 1079 /// TFTP error packet. This field is updated when a TFTP error is received 1080 /// and is undefined until the first TFTP error is received. This field is 1081 /// zero-filled by the [`BaseCode::start`] function. 1082 #[must_use] 1083 pub const fn tftp_error(&self) -> &TftpError { 1084 &self.0.tftp_error 1085 } 1086 } 1087 1088 /// Returned by [`BaseCode::tftp_read_dir`]. 1089 #[expect(missing_docs)] 1090 #[derive(Debug)] 1091 pub struct TftpFileInfo<'a> { 1092 pub filename: &'a CStr8, 1093 pub size: u64, 1094 pub year: u16, 1095 pub month: u8, 1096 pub day: u8, 1097 pub hour: u8, 1098 pub minute: u8, 1099 pub second: f32, 1100 } 1101 1102 /// Returned by [`BaseCode::mtftp_read_dir`]. 1103 #[expect(missing_docs)] 1104 #[derive(Debug)] 1105 pub struct MtftpFileInfo<'a> { 1106 pub filename: &'a CStr8, 1107 pub ip_address: IpAddr, 1108 pub size: u64, 1109 pub year: u16, 1110 pub month: u8, 1111 pub day: u8, 1112 pub hour: u8, 1113 pub minute: u8, 1114 pub second: f32, 1115 } 1116 1117 /// Returned if a server sends a malformed response in 1118 /// [`BaseCode::tftp_read_dir`] or [`BaseCode::mtftp_read_dir`]. 1119 #[derive(Clone, Copy, Debug)] 1120 pub struct ReadDirParseError; 1121 1122 impl Display for ReadDirParseError { 1123 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 1124 write!(f, "{self:?}") 1125 } 1126 } 1127 1128 impl error::Error for ReadDirParseError {} 1129 1130 #[cfg(test)] 1131 mod tests { 1132 use super::*; 1133 1134 #[repr(C, align(4))] 1135 struct Aligned4(T); 1136 1137 // It is not trivial to do these checks for a dynamically sized type in 1138 // const evaluation, therefore we use a unit test. 1139 #[test] 1140 fn abi_of_discover_info() { 1141 let mut buffer = Aligned4([MaybeUninit::new(0_u8); 100]); 1142 let info = DiscoverInfo::new_in_buffer( 1143 &mut buffer.0, 1144 false, 1145 false, 1146 false, 1147 false, 1148 EfiIpAddr::new_v4([0; 4]), 1149 &[], 1150 ) 1151 .unwrap(); 1152 1153 assert_eq!(size_of_val(info), DiscoverInfo::base_struct_size()); 1154 assert_eq!(align_of_val(info), DiscoverInfo::base_struct_alignment()); 1155 // As in EDK2 1156 assert_eq!(4, DiscoverInfo::base_struct_alignment()); 1157 1158 let server_list = [ 1159 Server::new(BootstrapType(123), None), 1160 Server::new(BootstrapType(456), None), 1161 ]; 1162 let info = DiscoverInfo::new_in_buffer( 1163 &mut buffer.0, 1164 false, 1165 false, 1166 false, 1167 false, 1168 EfiIpAddr::new_v4([0; 4]), 1169 &server_list, 1170 ) 1171 .unwrap(); 1172 1173 assert_eq!( 1174 size_of_val(info), 1175 DiscoverInfo::base_struct_size() + size_of_val(&server_list) 1176 ); 1177 } 1178 1179 // Miri fails if `new_in_buffer` leaves any byte of the returned struct 1180 // uninitialized. 1181 #[cfg(feature = "alloc")] 1182 #[test] 1183 fn discover_info_fully_initialized() { 1184 use alloc::format; 1185 1186 let mut buffer = Aligned4([MaybeUninit::::uninit(); 100]); 1187 let info = DiscoverInfo::new_in_buffer( 1188 &mut buffer.0, 1189 false, 1190 false, 1191 false, 1192 false, 1193 EfiIpAddr::new_v4([0; 4]), 1194 &[Server::new(BootstrapType(123), None)], 1195 ) 1196 .unwrap(); 1197 1198 assert!(format!("{info:?}").contains("DiscoverInfo")); 1199 } 1200 }