1 use core::cmp::min; 2 3 use alloc::{boxed::Box, sync::Arc}; 4 use num_traits::{FromPrimitive, ToPrimitive}; 5 use smoltcp::wire; 6 7 use crate::{ 8 filesystem::vfs::{ 9 file::{File, FileMode}, 10 syscall::{IoVec, IoVecs}, 11 }, 12 libs::spinlock::SpinLockGuard, 13 mm::{verify_area, VirtAddr}, 14 net::socket::{AddressFamily, SOL_SOCKET}, 15 process::ProcessManager, 16 syscall::{Syscall, SystemError}, 17 }; 18 19 use super::{ 20 socket::{ 21 PosixSocketType, RawSocket, SocketHandleItem, SocketInode, SocketOptions, TcpSocket, 22 UdpSocket, HANDLE_MAP, 23 }, 24 Endpoint, Protocol, ShutdownType, Socket, 25 }; 26 27 /// Flags for socket, socketpair, accept4 28 const SOCK_CLOEXEC: FileMode = FileMode::O_CLOEXEC; 29 const SOCK_NONBLOCK: FileMode = FileMode::O_NONBLOCK; 30 31 impl Syscall { 32 /// @brief sys_socket系统调用的实际执行函数 33 /// 34 /// @param address_family 地址族 35 /// @param socket_type socket类型 36 /// @param protocol 传输协议 37 pub fn socket( 38 address_family: usize, 39 socket_type: usize, 40 protocol: usize, 41 ) -> Result<usize, SystemError> { 42 let address_family = AddressFamily::try_from(address_family as u16)?; 43 let socket_type = PosixSocketType::try_from((socket_type & 0xf) as u8)?; 44 // kdebug!("do_socket: address_family: {address_family:?}, socket_type: {socket_type:?}, protocol: {protocol}"); 45 // 根据地址族和socket类型创建socket 46 let socket: Box<dyn Socket> = match address_family { 47 AddressFamily::Unix | AddressFamily::INet => match socket_type { 48 PosixSocketType::Stream => Box::new(TcpSocket::new(SocketOptions::default())), 49 PosixSocketType::Datagram => Box::new(UdpSocket::new(SocketOptions::default())), 50 PosixSocketType::Raw => Box::new(RawSocket::new( 51 Protocol::from(protocol as u8), 52 SocketOptions::default(), 53 )), 54 _ => { 55 // kdebug!("do_socket: EINVAL"); 56 return Err(SystemError::EINVAL); 57 } 58 }, 59 _ => { 60 // kdebug!("do_socket: EAFNOSUPPORT"); 61 return Err(SystemError::EAFNOSUPPORT); 62 } 63 }; 64 let handle_item = SocketHandleItem::new(&socket); 65 HANDLE_MAP 66 .write_irqsave() 67 .insert(socket.socket_handle(), handle_item); 68 // kdebug!("do_socket: socket: {socket:?}"); 69 let socketinode: Arc<SocketInode> = SocketInode::new(socket); 70 let f = File::new(socketinode, FileMode::O_RDWR)?; 71 // kdebug!("do_socket: f: {f:?}"); 72 // 把socket添加到当前进程的文件描述符表中 73 let binding = ProcessManager::current_pcb().fd_table(); 74 let mut fd_table_guard = binding.write(); 75 76 let fd = fd_table_guard.alloc_fd(f, None).map(|x| x as usize); 77 drop(fd_table_guard); 78 // kdebug!("do_socket: fd: {fd:?}"); 79 return fd; 80 } 81 82 /// @brief sys_setsockopt系统调用的实际执行函数 83 /// 84 /// @param fd 文件描述符 85 /// @param level 选项级别 86 /// @param optname 选项名称 87 /// @param optval 选项值 88 /// @param optlen optval缓冲区长度 89 pub fn setsockopt( 90 fd: usize, 91 level: usize, 92 optname: usize, 93 optval: &[u8], 94 ) -> Result<usize, SystemError> { 95 let socket_inode: Arc<SocketInode> = ProcessManager::current_pcb() 96 .get_socket(fd as i32) 97 .ok_or(SystemError::EBADF)?; 98 // 获取内层的socket(真正的数据) 99 let socket: SpinLockGuard<Box<dyn Socket>> = socket_inode.inner(); 100 return socket.setsockopt(level, optname, optval).map(|_| 0); 101 } 102 103 /// @brief sys_getsockopt系统调用的实际执行函数 104 /// 105 /// 参考:https://man7.org/linux/man-pages/man2/setsockopt.2.html 106 /// 107 /// @param fd 文件描述符 108 /// @param level 选项级别 109 /// @param optname 选项名称 110 /// @param optval 返回的选项值 111 /// @param optlen 返回的optval缓冲区长度 112 pub fn getsockopt( 113 fd: usize, 114 level: usize, 115 optname: usize, 116 optval: *mut u8, 117 optlen: *mut u32, 118 ) -> Result<usize, SystemError> { 119 // 获取socket 120 let optval = optval as *mut u32; 121 let binding: Arc<SocketInode> = ProcessManager::current_pcb() 122 .get_socket(fd as i32) 123 .ok_or(SystemError::EBADF)?; 124 let socket = binding.inner(); 125 126 if level as u8 == SOL_SOCKET { 127 let optname = PosixSocketOption::try_from(optname as i32) 128 .map_err(|_| SystemError::ENOPROTOOPT)?; 129 match optname { 130 PosixSocketOption::SO_SNDBUF => { 131 // 返回发送缓冲区大小 132 unsafe { 133 *optval = socket.metadata()?.send_buf_size as u32; 134 *optlen = core::mem::size_of::<u32>() as u32; 135 } 136 return Ok(0); 137 } 138 PosixSocketOption::SO_RCVBUF => { 139 let optval = optval as *mut u32; 140 // 返回默认的接收缓冲区大小 141 unsafe { 142 *optval = socket.metadata()?.recv_buf_size as u32; 143 *optlen = core::mem::size_of::<u32>() as u32; 144 } 145 return Ok(0); 146 } 147 _ => { 148 return Err(SystemError::ENOPROTOOPT); 149 } 150 } 151 } 152 drop(socket); 153 154 // To manipulate options at any other level the 155 // protocol number of the appropriate protocol controlling the 156 // option is supplied. For example, to indicate that an option is 157 // to be interpreted by the TCP protocol, level should be set to the 158 // protocol number of TCP. 159 160 let posix_protocol = 161 PosixIpProtocol::try_from(level as u16).map_err(|_| SystemError::ENOPROTOOPT)?; 162 if posix_protocol == PosixIpProtocol::TCP { 163 let optname = PosixTcpSocketOptions::try_from(optname as i32) 164 .map_err(|_| SystemError::ENOPROTOOPT)?; 165 match optname { 166 PosixTcpSocketOptions::Congestion => return Ok(0), 167 _ => { 168 return Err(SystemError::ENOPROTOOPT); 169 } 170 } 171 } 172 return Err(SystemError::ENOPROTOOPT); 173 } 174 175 /// @brief sys_connect系统调用的实际执行函数 176 /// 177 /// @param fd 文件描述符 178 /// @param addr SockAddr 179 /// @param addrlen 地址长度 180 /// 181 /// @return 成功返回0,失败返回错误码 182 pub fn connect(fd: usize, addr: *const SockAddr, addrlen: usize) -> Result<usize, SystemError> { 183 let endpoint: Endpoint = SockAddr::to_endpoint(addr, addrlen)?; 184 let socket: Arc<SocketInode> = ProcessManager::current_pcb() 185 .get_socket(fd as i32) 186 .ok_or(SystemError::EBADF)?; 187 let mut socket = unsafe { socket.inner_no_preempt() }; 188 // kdebug!("connect to {:?}...", endpoint); 189 socket.connect(endpoint)?; 190 return Ok(0); 191 } 192 193 /// @brief sys_bind系统调用的实际执行函数 194 /// 195 /// @param fd 文件描述符 196 /// @param addr SockAddr 197 /// @param addrlen 地址长度 198 /// 199 /// @return 成功返回0,失败返回错误码 200 pub fn bind(fd: usize, addr: *const SockAddr, addrlen: usize) -> Result<usize, SystemError> { 201 let endpoint: Endpoint = SockAddr::to_endpoint(addr, addrlen)?; 202 let socket: Arc<SocketInode> = ProcessManager::current_pcb() 203 .get_socket(fd as i32) 204 .ok_or(SystemError::EBADF)?; 205 let mut socket = unsafe { socket.inner_no_preempt() }; 206 socket.bind(endpoint)?; 207 return Ok(0); 208 } 209 210 /// @brief sys_sendto系统调用的实际执行函数 211 /// 212 /// @param fd 文件描述符 213 /// @param buf 发送缓冲区 214 /// @param flags 标志 215 /// @param addr SockAddr 216 /// @param addrlen 地址长度 217 /// 218 /// @return 成功返回发送的字节数,失败返回错误码 219 pub fn sendto( 220 fd: usize, 221 buf: &[u8], 222 _flags: u32, 223 addr: *const SockAddr, 224 addrlen: usize, 225 ) -> Result<usize, SystemError> { 226 let endpoint = if addr.is_null() { 227 None 228 } else { 229 Some(SockAddr::to_endpoint(addr, addrlen)?) 230 }; 231 232 let socket: Arc<SocketInode> = ProcessManager::current_pcb() 233 .get_socket(fd as i32) 234 .ok_or(SystemError::EBADF)?; 235 let socket = unsafe { socket.inner_no_preempt() }; 236 return socket.write(buf, endpoint); 237 } 238 239 /// @brief sys_recvfrom系统调用的实际执行函数 240 /// 241 /// @param fd 文件描述符 242 /// @param buf 接收缓冲区 243 /// @param flags 标志 244 /// @param addr SockAddr 245 /// @param addrlen 地址长度 246 /// 247 /// @return 成功返回接收的字节数,失败返回错误码 248 pub fn recvfrom( 249 fd: usize, 250 buf: &mut [u8], 251 _flags: u32, 252 addr: *mut SockAddr, 253 addrlen: *mut u32, 254 ) -> Result<usize, SystemError> { 255 let socket: Arc<SocketInode> = ProcessManager::current_pcb() 256 .get_socket(fd as i32) 257 .ok_or(SystemError::EBADF)?; 258 let mut socket = unsafe { socket.inner_no_preempt() }; 259 260 let (n, endpoint) = socket.read(buf); 261 drop(socket); 262 263 let n: usize = n?; 264 265 // 如果有地址信息,将地址信息写入用户空间 266 if !addr.is_null() { 267 let sockaddr_in = SockAddr::from(endpoint); 268 unsafe { 269 sockaddr_in.write_to_user(addr, addrlen)?; 270 } 271 } 272 return Ok(n); 273 } 274 275 /// @brief sys_recvmsg系统调用的实际执行函数 276 /// 277 /// @param fd 文件描述符 278 /// @param msg MsgHdr 279 /// @param flags 标志,暂时未使用 280 /// 281 /// @return 成功返回接收的字节数,失败返回错误码 282 pub fn recvmsg(fd: usize, msg: &mut MsgHdr, _flags: u32) -> Result<usize, SystemError> { 283 // 检查每个缓冲区地址是否合法,生成iovecs 284 let mut iovs = unsafe { IoVecs::from_user(msg.msg_iov, msg.msg_iovlen, true)? }; 285 286 let socket: Arc<SocketInode> = ProcessManager::current_pcb() 287 .get_socket(fd as i32) 288 .ok_or(SystemError::EBADF)?; 289 let mut socket = unsafe { socket.inner_no_preempt() }; 290 291 let mut buf = iovs.new_buf(true); 292 // 从socket中读取数据 293 let (n, endpoint) = socket.read(&mut buf); 294 drop(socket); 295 296 let n: usize = n?; 297 298 // 将数据写入用户空间的iovecs 299 iovs.scatter(&buf[..n]); 300 301 let sockaddr_in = SockAddr::from(endpoint); 302 unsafe { 303 sockaddr_in.write_to_user(msg.msg_name, &mut msg.msg_namelen)?; 304 } 305 return Ok(n); 306 } 307 308 /// @brief sys_listen系统调用的实际执行函数 309 /// 310 /// @param fd 文件描述符 311 /// @param backlog 队列最大连接数 312 /// 313 /// @return 成功返回0,失败返回错误码 314 pub fn listen(fd: usize, backlog: usize) -> Result<usize, SystemError> { 315 let socket: Arc<SocketInode> = ProcessManager::current_pcb() 316 .get_socket(fd as i32) 317 .ok_or(SystemError::EBADF)?; 318 let mut socket = unsafe { socket.inner_no_preempt() }; 319 socket.listen(backlog)?; 320 return Ok(0); 321 } 322 323 /// @brief sys_shutdown系统调用的实际执行函数 324 /// 325 /// @param fd 文件描述符 326 /// @param how 关闭方式 327 /// 328 /// @return 成功返回0,失败返回错误码 329 pub fn shutdown(fd: usize, how: usize) -> Result<usize, SystemError> { 330 let socket: Arc<SocketInode> = ProcessManager::current_pcb() 331 .get_socket(fd as i32) 332 .ok_or(SystemError::EBADF)?; 333 let mut socket = unsafe { socket.inner_no_preempt() }; 334 socket.shutdown(ShutdownType::from_bits_truncate(how as u8))?; 335 return Ok(0); 336 } 337 338 /// @brief sys_accept系统调用的实际执行函数 339 /// 340 /// @param fd 文件描述符 341 /// @param addr SockAddr 342 /// @param addrlen 地址长度 343 /// 344 /// @return 成功返回新的文件描述符,失败返回错误码 345 pub fn accept(fd: usize, addr: *mut SockAddr, addrlen: *mut u32) -> Result<usize, SystemError> { 346 return Self::do_accept(fd, addr, addrlen, 0); 347 } 348 349 /// sys_accept4 - accept a connection on a socket 350 /// 351 /// 352 /// If flags is 0, then accept4() is the same as accept(). The 353 /// following values can be bitwise ORed in flags to obtain different 354 /// behavior: 355 /// 356 /// - SOCK_NONBLOCK 357 /// Set the O_NONBLOCK file status flag on the open file 358 /// description (see open(2)) referred to by the new file 359 /// descriptor. Using this flag saves extra calls to fcntl(2) 360 /// to achieve the same result. 361 /// 362 /// - SOCK_CLOEXEC 363 /// Set the close-on-exec (FD_CLOEXEC) flag on the new file 364 /// descriptor. See the description of the O_CLOEXEC flag in 365 /// open(2) for reasons why this may be useful. 366 pub fn accept4( 367 fd: usize, 368 addr: *mut SockAddr, 369 addrlen: *mut u32, 370 mut flags: u32, 371 ) -> Result<usize, SystemError> { 372 // 如果flags不合法,返回错误 373 if (flags & (!(SOCK_CLOEXEC | SOCK_NONBLOCK)).bits()) != 0 { 374 return Err(SystemError::EINVAL); 375 } 376 377 if SOCK_NONBLOCK != FileMode::O_NONBLOCK && ((flags & SOCK_NONBLOCK.bits()) != 0) { 378 flags = (flags & !SOCK_NONBLOCK.bits()) | FileMode::O_NONBLOCK.bits(); 379 } 380 381 return Self::do_accept(fd, addr, addrlen, flags); 382 } 383 384 fn do_accept( 385 fd: usize, 386 addr: *mut SockAddr, 387 addrlen: *mut u32, 388 flags: u32, 389 ) -> Result<usize, SystemError> { 390 let socket: Arc<SocketInode> = ProcessManager::current_pcb() 391 .get_socket(fd as i32) 392 .ok_or(SystemError::EBADF)?; 393 // kdebug!("accept: socket={:?}", socket); 394 let mut socket = unsafe { socket.inner_no_preempt() }; 395 // 从socket中接收连接 396 let (new_socket, remote_endpoint) = socket.accept()?; 397 drop(socket); 398 399 // kdebug!("accept: new_socket={:?}", new_socket); 400 // Insert the new socket into the file descriptor vector 401 let new_socket: Arc<SocketInode> = SocketInode::new(new_socket); 402 403 let mut file_mode = FileMode::O_RDWR; 404 if flags & FileMode::O_NONBLOCK.bits() != 0 { 405 file_mode |= FileMode::O_NONBLOCK; 406 } 407 if flags & FileMode::O_CLOEXEC.bits() != 0 { 408 file_mode |= FileMode::O_CLOEXEC; 409 } 410 411 let new_fd = ProcessManager::current_pcb() 412 .fd_table() 413 .write() 414 .alloc_fd(File::new(new_socket, file_mode)?, None)?; 415 // kdebug!("accept: new_fd={}", new_fd); 416 if !addr.is_null() { 417 // kdebug!("accept: write remote_endpoint to user"); 418 // 将对端地址写入用户空间 419 let sockaddr_in = SockAddr::from(remote_endpoint); 420 unsafe { 421 sockaddr_in.write_to_user(addr, addrlen)?; 422 } 423 } 424 return Ok(new_fd as usize); 425 } 426 427 /// @brief sys_getsockname系统调用的实际执行函数 428 /// 429 /// Returns the current address to which the socket 430 /// sockfd is bound, in the buffer pointed to by addr. 431 /// 432 /// @param fd 文件描述符 433 /// @param addr SockAddr 434 /// @param addrlen 地址长度 435 /// 436 /// @return 成功返回0,失败返回错误码 437 pub fn getsockname( 438 fd: usize, 439 addr: *mut SockAddr, 440 addrlen: *mut u32, 441 ) -> Result<usize, SystemError> { 442 if addr.is_null() { 443 return Err(SystemError::EINVAL); 444 } 445 let socket: Arc<SocketInode> = ProcessManager::current_pcb() 446 .get_socket(fd as i32) 447 .ok_or(SystemError::EBADF)?; 448 let socket = socket.inner(); 449 let endpoint: Endpoint = socket.endpoint().ok_or(SystemError::EINVAL)?; 450 drop(socket); 451 452 let sockaddr_in = SockAddr::from(endpoint); 453 unsafe { 454 sockaddr_in.write_to_user(addr, addrlen)?; 455 } 456 return Ok(0); 457 } 458 459 /// @brief sys_getpeername系统调用的实际执行函数 460 /// 461 /// @param fd 文件描述符 462 /// @param addr SockAddr 463 /// @param addrlen 地址长度 464 /// 465 /// @return 成功返回0,失败返回错误码 466 pub fn getpeername( 467 fd: usize, 468 addr: *mut SockAddr, 469 addrlen: *mut u32, 470 ) -> Result<usize, SystemError> { 471 if addr.is_null() { 472 return Err(SystemError::EINVAL); 473 } 474 475 let socket: Arc<SocketInode> = ProcessManager::current_pcb() 476 .get_socket(fd as i32) 477 .ok_or(SystemError::EBADF)?; 478 let socket = socket.inner(); 479 let endpoint: Endpoint = socket.peer_endpoint().ok_or(SystemError::EINVAL)?; 480 drop(socket); 481 482 let sockaddr_in = SockAddr::from(endpoint); 483 unsafe { 484 sockaddr_in.write_to_user(addr, addrlen)?; 485 } 486 return Ok(0); 487 } 488 } 489 490 // 参考资料: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/netinet_in.h.html#tag_13_32 491 #[repr(C)] 492 #[derive(Debug, Clone, Copy)] 493 pub struct SockAddrIn { 494 pub sin_family: u16, 495 pub sin_port: u16, 496 pub sin_addr: u32, 497 pub sin_zero: [u8; 8], 498 } 499 500 #[repr(C)] 501 #[derive(Debug, Clone, Copy)] 502 pub struct SockAddrUn { 503 pub sun_family: u16, 504 pub sun_path: [u8; 108], 505 } 506 507 #[repr(C)] 508 #[derive(Debug, Clone, Copy)] 509 pub struct SockAddrLl { 510 pub sll_family: u16, 511 pub sll_protocol: u16, 512 pub sll_ifindex: u32, 513 pub sll_hatype: u16, 514 pub sll_pkttype: u8, 515 pub sll_halen: u8, 516 pub sll_addr: [u8; 8], 517 } 518 519 #[repr(C)] 520 #[derive(Debug, Clone, Copy)] 521 pub struct SockAddrNl { 522 nl_family: u16, 523 nl_pad: u16, 524 nl_pid: u32, 525 nl_groups: u32, 526 } 527 528 #[repr(C)] 529 #[derive(Debug, Clone, Copy)] 530 pub struct SockAddrPlaceholder { 531 pub family: u16, 532 pub data: [u8; 14], 533 } 534 535 #[repr(C)] 536 #[derive(Clone, Copy)] 537 pub union SockAddr { 538 pub family: u16, 539 pub addr_in: SockAddrIn, 540 pub addr_un: SockAddrUn, 541 pub addr_ll: SockAddrLl, 542 pub addr_nl: SockAddrNl, 543 pub addr_ph: SockAddrPlaceholder, 544 } 545 546 impl SockAddr { 547 /// @brief 把用户传入的SockAddr转换为Endpoint结构体 548 pub fn to_endpoint(addr: *const SockAddr, len: usize) -> Result<Endpoint, SystemError> { 549 verify_area( 550 VirtAddr::new(addr as usize), 551 core::mem::size_of::<SockAddr>(), 552 ) 553 .map_err(|_| SystemError::EFAULT)?; 554 555 let addr = unsafe { addr.as_ref() }.ok_or(SystemError::EFAULT)?; 556 if len < addr.len()? { 557 return Err(SystemError::EINVAL); 558 } 559 unsafe { 560 match AddressFamily::try_from(addr.family)? { 561 AddressFamily::INet => { 562 let addr_in: SockAddrIn = addr.addr_in; 563 564 let ip: wire::IpAddress = wire::IpAddress::from(wire::Ipv4Address::from_bytes( 565 &u32::from_be(addr_in.sin_addr).to_be_bytes()[..], 566 )); 567 let port = u16::from_be(addr_in.sin_port); 568 569 return Ok(Endpoint::Ip(Some(wire::IpEndpoint::new(ip, port)))); 570 } 571 AddressFamily::Packet => { 572 // TODO: support packet socket 573 return Err(SystemError::EINVAL); 574 } 575 AddressFamily::Netlink => { 576 // TODO: support netlink socket 577 return Err(SystemError::EINVAL); 578 } 579 AddressFamily::Unix => { 580 return Err(SystemError::EINVAL); 581 } 582 _ => { 583 return Err(SystemError::EINVAL); 584 } 585 } 586 } 587 } 588 589 /// @brief 获取地址长度 590 pub fn len(&self) -> Result<usize, SystemError> { 591 let ret = match AddressFamily::try_from(unsafe { self.family })? { 592 AddressFamily::INet => Ok(core::mem::size_of::<SockAddrIn>()), 593 AddressFamily::Packet => Ok(core::mem::size_of::<SockAddrLl>()), 594 AddressFamily::Netlink => Ok(core::mem::size_of::<SockAddrNl>()), 595 AddressFamily::Unix => Err(SystemError::EINVAL), 596 _ => Err(SystemError::EINVAL), 597 }; 598 599 return ret; 600 } 601 602 /// @brief 把SockAddr的数据写入用户空间 603 /// 604 /// @param addr 用户空间的SockAddr的地址 605 /// @param len 要写入的长度 606 /// 607 /// @return 成功返回写入的长度,失败返回错误码 608 pub unsafe fn write_to_user( 609 &self, 610 addr: *mut SockAddr, 611 addr_len: *mut u32, 612 ) -> Result<usize, SystemError> { 613 // 当用户传入的地址或者长度为空时,直接返回0 614 if addr.is_null() || addr_len.is_null() { 615 return Ok(0); 616 } 617 618 // 检查用户传入的地址是否合法 619 verify_area( 620 VirtAddr::new(addr as usize), 621 core::mem::size_of::<SockAddr>(), 622 ) 623 .map_err(|_| SystemError::EFAULT)?; 624 625 verify_area( 626 VirtAddr::new(addr_len as usize), 627 core::mem::size_of::<u32>(), 628 ) 629 .map_err(|_| SystemError::EFAULT)?; 630 631 let to_write = min(self.len()?, *addr_len as usize); 632 if to_write > 0 { 633 let buf = core::slice::from_raw_parts_mut(addr as *mut u8, to_write); 634 buf.copy_from_slice(core::slice::from_raw_parts( 635 self as *const SockAddr as *const u8, 636 to_write, 637 )); 638 } 639 *addr_len = self.len()? as u32; 640 return Ok(to_write); 641 } 642 } 643 644 impl From<Endpoint> for SockAddr { 645 fn from(value: Endpoint) -> Self { 646 match value { 647 Endpoint::Ip(ip_endpoint) => { 648 // 未指定地址 649 if let None = ip_endpoint { 650 return SockAddr { 651 addr_ph: SockAddrPlaceholder { 652 family: AddressFamily::Unspecified as u16, 653 data: [0; 14], 654 }, 655 }; 656 } 657 // 指定了地址 658 let ip_endpoint = ip_endpoint.unwrap(); 659 match ip_endpoint.addr { 660 wire::IpAddress::Ipv4(ipv4_addr) => { 661 let addr_in = SockAddrIn { 662 sin_family: AddressFamily::INet as u16, 663 sin_port: ip_endpoint.port.to_be(), 664 sin_addr: u32::from_be_bytes(ipv4_addr.0).to_be(), 665 sin_zero: [0; 8], 666 }; 667 668 return SockAddr { addr_in }; 669 } 670 _ => { 671 unimplemented!("not support ipv6"); 672 } 673 } 674 } 675 676 Endpoint::LinkLayer(link_endpoint) => { 677 let addr_ll = SockAddrLl { 678 sll_family: AddressFamily::Packet as u16, 679 sll_protocol: 0, 680 sll_ifindex: link_endpoint.interface as u32, 681 sll_hatype: 0, 682 sll_pkttype: 0, 683 sll_halen: 0, 684 sll_addr: [0; 8], 685 }; 686 687 return SockAddr { addr_ll }; 688 } // _ => { 689 // // todo: support other endpoint, like Netlink... 690 // unimplemented!("not support {value:?}"); 691 // } 692 } 693 } 694 } 695 696 #[repr(C)] 697 #[derive(Debug, Clone, Copy)] 698 pub struct MsgHdr { 699 /// 指向一个SockAddr结构体的指针 700 pub msg_name: *mut SockAddr, 701 /// SockAddr结构体的大小 702 pub msg_namelen: u32, 703 /// scatter/gather array 704 pub msg_iov: *mut IoVec, 705 /// elements in msg_iov 706 pub msg_iovlen: usize, 707 /// 辅助数据 708 pub msg_control: *mut u8, 709 /// 辅助数据长度 710 pub msg_controllen: usize, 711 /// 接收到的消息的标志 712 pub msg_flags: u32, 713 } 714 715 #[derive(Debug, Clone, Copy, FromPrimitive, ToPrimitive, PartialEq, Eq)] 716 pub enum PosixIpProtocol { 717 /// Dummy protocol for TCP. 718 IP = 0, 719 /// Internet Control Message Protocol. 720 ICMP = 1, 721 /// Internet Group Management Protocol. 722 IGMP = 2, 723 /// IPIP tunnels (older KA9Q tunnels use 94). 724 IPIP = 4, 725 /// Transmission Control Protocol. 726 TCP = 6, 727 /// Exterior Gateway Protocol. 728 EGP = 8, 729 /// PUP protocol. 730 PUP = 12, 731 /// User Datagram Protocol. 732 UDP = 17, 733 /// XNS IDP protocol. 734 IDP = 22, 735 /// SO Transport Protocol Class 4. 736 TP = 29, 737 /// Datagram Congestion Control Protocol. 738 DCCP = 33, 739 /// IPv6-in-IPv4 tunnelling. 740 IPv6 = 41, 741 /// RSVP Protocol. 742 RSVP = 46, 743 /// Generic Routing Encapsulation. (Cisco GRE) (rfc 1701, 1702) 744 GRE = 47, 745 /// Encapsulation Security Payload protocol 746 ESP = 50, 747 /// Authentication Header protocol 748 AH = 51, 749 /// Multicast Transport Protocol. 750 MTP = 92, 751 /// IP option pseudo header for BEET 752 BEETPH = 94, 753 /// Encapsulation Header. 754 ENCAP = 98, 755 /// Protocol Independent Multicast. 756 PIM = 103, 757 /// Compression Header Protocol. 758 COMP = 108, 759 /// Stream Control Transport Protocol 760 SCTP = 132, 761 /// UDP-Lite protocol (RFC 3828) 762 UDPLITE = 136, 763 /// MPLS in IP (RFC 4023) 764 MPLSINIP = 137, 765 /// Ethernet-within-IPv6 Encapsulation 766 ETHERNET = 143, 767 /// Raw IP packets 768 RAW = 255, 769 /// Multipath TCP connection 770 MPTCP = 262, 771 } 772 773 impl TryFrom<u16> for PosixIpProtocol { 774 type Error = SystemError; 775 776 fn try_from(value: u16) -> Result<Self, Self::Error> { 777 match <Self as FromPrimitive>::from_u16(value) { 778 Some(p) => Ok(p), 779 None => Err(SystemError::EPROTONOSUPPORT), 780 } 781 } 782 } 783 784 impl Into<u16> for PosixIpProtocol { 785 fn into(self) -> u16 { 786 <Self as ToPrimitive>::to_u16(&self).unwrap() 787 } 788 } 789 790 #[allow(non_camel_case_types)] 791 #[derive(Debug, Clone, Copy, FromPrimitive, ToPrimitive, PartialEq, Eq)] 792 pub enum PosixSocketOption { 793 SO_DEBUG = 1, 794 SO_REUSEADDR = 2, 795 SO_TYPE = 3, 796 SO_ERROR = 4, 797 SO_DONTROUTE = 5, 798 SO_BROADCAST = 6, 799 SO_SNDBUF = 7, 800 SO_RCVBUF = 8, 801 SO_SNDBUFFORCE = 32, 802 SO_RCVBUFFORCE = 33, 803 SO_KEEPALIVE = 9, 804 SO_OOBINLINE = 10, 805 SO_NO_CHECK = 11, 806 SO_PRIORITY = 12, 807 SO_LINGER = 13, 808 SO_BSDCOMPAT = 14, 809 SO_REUSEPORT = 15, 810 SO_PASSCRED = 16, 811 SO_PEERCRED = 17, 812 SO_RCVLOWAT = 18, 813 SO_SNDLOWAT = 19, 814 SO_RCVTIMEO_OLD = 20, 815 SO_SNDTIMEO_OLD = 21, 816 817 SO_SECURITY_AUTHENTICATION = 22, 818 SO_SECURITY_ENCRYPTION_TRANSPORT = 23, 819 SO_SECURITY_ENCRYPTION_NETWORK = 24, 820 821 SO_BINDTODEVICE = 25, 822 823 /// 与SO_GET_FILTER相同 824 SO_ATTACH_FILTER = 26, 825 SO_DETACH_FILTER = 27, 826 827 SO_PEERNAME = 28, 828 829 SO_ACCEPTCONN = 30, 830 831 SO_PEERSEC = 31, 832 SO_PASSSEC = 34, 833 834 SO_MARK = 36, 835 836 SO_PROTOCOL = 38, 837 SO_DOMAIN = 39, 838 839 SO_RXQ_OVFL = 40, 840 841 /// 与SCM_WIFI_STATUS相同 842 SO_WIFI_STATUS = 41, 843 SO_PEEK_OFF = 42, 844 845 /* Instruct lower device to use last 4-bytes of skb data as FCS */ 846 SO_NOFCS = 43, 847 848 SO_LOCK_FILTER = 44, 849 SO_SELECT_ERR_QUEUE = 45, 850 SO_BUSY_POLL = 46, 851 SO_MAX_PACING_RATE = 47, 852 SO_BPF_EXTENSIONS = 48, 853 SO_INCOMING_CPU = 49, 854 SO_ATTACH_BPF = 50, 855 // SO_DETACH_BPF = SO_DETACH_FILTER, 856 SO_ATTACH_REUSEPORT_CBPF = 51, 857 SO_ATTACH_REUSEPORT_EBPF = 52, 858 859 SO_CNX_ADVICE = 53, 860 SCM_TIMESTAMPING_OPT_STATS = 54, 861 SO_MEMINFO = 55, 862 SO_INCOMING_NAPI_ID = 56, 863 SO_COOKIE = 57, 864 SCM_TIMESTAMPING_PKTINFO = 58, 865 SO_PEERGROUPS = 59, 866 SO_ZEROCOPY = 60, 867 /// 与SCM_TXTIME相同 868 SO_TXTIME = 61, 869 870 SO_BINDTOIFINDEX = 62, 871 872 SO_TIMESTAMP_OLD = 29, 873 SO_TIMESTAMPNS_OLD = 35, 874 SO_TIMESTAMPING_OLD = 37, 875 SO_TIMESTAMP_NEW = 63, 876 SO_TIMESTAMPNS_NEW = 64, 877 SO_TIMESTAMPING_NEW = 65, 878 879 SO_RCVTIMEO_NEW = 66, 880 SO_SNDTIMEO_NEW = 67, 881 882 SO_DETACH_REUSEPORT_BPF = 68, 883 884 SO_PREFER_BUSY_POLL = 69, 885 SO_BUSY_POLL_BUDGET = 70, 886 887 SO_NETNS_COOKIE = 71, 888 SO_BUF_LOCK = 72, 889 SO_RESERVE_MEM = 73, 890 SO_TXREHASH = 74, 891 SO_RCVMARK = 75, 892 } 893 894 impl TryFrom<i32> for PosixSocketOption { 895 type Error = SystemError; 896 897 fn try_from(value: i32) -> Result<Self, Self::Error> { 898 match <Self as FromPrimitive>::from_i32(value) { 899 Some(p) => Ok(p), 900 None => Err(SystemError::EINVAL), 901 } 902 } 903 } 904 905 impl Into<i32> for PosixSocketOption { 906 fn into(self) -> i32 { 907 <Self as ToPrimitive>::to_i32(&self).unwrap() 908 } 909 } 910 911 #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, ToPrimitive)] 912 pub enum PosixTcpSocketOptions { 913 /// Turn off Nagle's algorithm. 914 NoDelay = 1, 915 /// Limit MSS. 916 MaxSegment = 2, 917 /// Never send partially complete segments. 918 Cork = 3, 919 /// Start keeplives after this period. 920 KeepIdle = 4, 921 /// Interval between keepalives. 922 KeepIntvl = 5, 923 /// Number of keepalives before death. 924 KeepCnt = 6, 925 /// Number of SYN retransmits. 926 Syncnt = 7, 927 /// Lifetime for orphaned FIN-WAIT-2 state. 928 Linger2 = 8, 929 /// Wake up listener only when data arrive. 930 DeferAccept = 9, 931 /// Bound advertised window 932 WindowClamp = 10, 933 /// Information about this connection. 934 Info = 11, 935 /// Block/reenable quick acks. 936 QuickAck = 12, 937 /// Congestion control algorithm. 938 Congestion = 13, 939 /// TCP MD5 Signature (RFC2385). 940 Md5Sig = 14, 941 /// Use linear timeouts for thin streams 942 ThinLinearTimeouts = 16, 943 /// Fast retrans. after 1 dupack. 944 ThinDupack = 17, 945 /// How long for loss retry before timeout. 946 UserTimeout = 18, 947 /// TCP sock is under repair right now. 948 Repair = 19, 949 RepairQueue = 20, 950 QueueSeq = 21, 951 RepairOptions = 22, 952 /// Enable FastOpen on listeners 953 FastOpen = 23, 954 Timestamp = 24, 955 /// Limit number of unsent bytes in write queue. 956 NotSentLowat = 25, 957 /// Get Congestion Control (optional) info. 958 CCInfo = 26, 959 /// Record SYN headers for new connections. 960 SaveSyn = 27, 961 /// Get SYN headers recorded for connection. 962 SavedSyn = 28, 963 /// Get/set window parameters. 964 RepairWindow = 29, 965 /// Attempt FastOpen with connect. 966 FastOpenConnect = 30, 967 /// Attach a ULP to a TCP connection. 968 ULP = 31, 969 /// TCP MD5 Signature with extensions. 970 Md5SigExt = 32, 971 /// Set the key for Fast Open(cookie). 972 FastOpenKey = 33, 973 /// Enable TFO without a TFO cookie. 974 FastOpenNoCookie = 34, 975 ZeroCopyReceive = 35, 976 /// Notify bytes available to read as a cmsg on read. 977 /// 与TCP_CM_INQ相同 978 INQ = 36, 979 /// delay outgoing packets by XX usec 980 TxDelay = 37, 981 } 982 983 impl TryFrom<i32> for PosixTcpSocketOptions { 984 type Error = SystemError; 985 986 fn try_from(value: i32) -> Result<Self, Self::Error> { 987 match <Self as FromPrimitive>::from_i32(value) { 988 Some(p) => Ok(p), 989 None => Err(SystemError::EINVAL), 990 } 991 } 992 } 993 994 impl Into<i32> for PosixTcpSocketOptions { 995 fn into(self) -> i32 { 996 <Self as ToPrimitive>::to_i32(&self).unwrap() 997 } 998 } 999