pnet_sys-0.35.0/.cargo_vcs_info.json0000644000000001460000000000100127660ustar { "git": { "sha1": "97ece70e2f87744f2ab47b4177c3888289f89a8f" }, "path_in_vcs": "pnet_sys" }pnet_sys-0.35.0/Cargo.toml0000644000000021410000000000100107610ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "pnet_sys" version = "0.35.0" authors = [ "Robert Clipsham ", "Linus Färnstrand ", ] description = "Access to network related system function and calls." homepage = "https://github.com/libpnet/libpnet" readme = "README.md" keywords = [ "networking", "datalink", "ethernet", "raw", ] categories = ["network-programming"] license = "MIT OR Apache-2.0" repository = "https://github.com/libpnet/libpnet" [dependencies.libc] version = "0.2.147" [target."cfg(windows)".dependencies.winapi] version = "0.3.9" features = [ "winsock2", "ws2ipdef", ] pnet_sys-0.35.0/Cargo.toml.orig000064400000000000000000000011511046102023000144420ustar 00000000000000[package] name = "pnet_sys" version = "0.35.0" authors = ["Robert Clipsham ", "Linus Färnstrand "] license = "MIT OR Apache-2.0" homepage = "https://github.com/libpnet/libpnet" repository = "https://github.com/libpnet/libpnet" description = "Access to network related system function and calls." readme = "../README.md" keywords = ["networking", "datalink", "ethernet", "raw"] categories = ["network-programming"] edition = "2021" [dependencies] libc = "0.2.147" [target.'cfg(windows)'.dependencies] winapi = { version = "0.3.9", features = [ "winsock2", "ws2ipdef" ] } pnet_sys-0.35.0/LICENSE-APACHE000064400000000000000000000251371046102023000135110ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. pnet_sys-0.35.0/LICENSE-MIT000064400000000000000000000020501046102023000132060ustar 00000000000000Copyright (c) 2014-2016 Robert Clipsham Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pnet_sys-0.35.0/README.md000064400000000000000000000101641046102023000130360ustar 00000000000000# libpnet [![Crates.io](https://img.shields.io/crates/v/pnet.svg)](https://crates.io/crates/pnet) ![License](https://img.shields.io/crates/l/pnet.svg) [![Documentation](https://docs.rs/pnet/badge.svg)](https://docs.rs/pnet/) Build Status: [![Build Status](https://github.com/libpnet/libpnet/actions/workflows/ci.yml/badge.svg)](https://github.com/libpnet/libpnet/actions/workflows/ci.yml) Discussion and support: * Live chat on IRC - [#libpnet on irc.libera.chat](https://kiwiirc.com/nextclient/irc.libera.chat/libpnet?nick=pnet-user42) * [GitHub Discussions](https://github.com/libpnet/libpnet/discussions) `libpnet` provides a cross-platform API for low level networking using Rust. There are four key components: * The `packet` module, allowing safe construction and manipulation of packets; * The `pnet_macros` crate, providing infrastructure for the packet module; * The `transport` module, which allows implementation of transport protocols; * The `datalink` module, which allows sending and receiving data link packets directly. ## Why? There are lots of reasons to use low level networking, and many more to do it using Rust. A few are outlined here: ### Developing Transport Protocols There are usually two ways to go about developing a new transport layer protocol: * Write it in a scripting language such as Python; * Write it using C. The former is great for trying out new ideas and rapid prototyping, however not so great as a real-world implementation. While you can usually get reasonable performance out of these implementations, they're generally significantly slower than an implementation in C, and not suitable for any "heavy lifting". The next option is to write it in C - this will give you great performance, but comes with a number of other issues: * Lack of memory safety - this is a huge source of security vulnerabilities and other bugs in C-based network stacks. It is far too easy to forget a bounds check or use a pointer after it is freed. * Lack of thread safety - you have to be very careful to make sure the correct locks are used, and used correctly. * Lack of high level abstractions - part of the appeal of scripting languages such as Python is the higher level of abstraction which enables simpler APIs and ease of programming. Using `libpnet` and Rust, you get the best of both worlds. The higher level abstractions, memory and thread safety, alongside the performance of C. ### Network Utilities Many networking utilities such as ping and traceroute rely on being able to manipulate network and transport headers, which isn't possible with standard networking stacks such as those provided by `std::io::net`. ### Data Link Layer It can be useful to work directly at the data link layer, to see packets as they are "on the wire". There are lots of uses for this, including network diagnostics, packet capture and traffic shaping. ## Documentation API documentation for the latest build can be found here: https://docs.rs/pnet/ ## Usage To use `libpnet` in your project, add the following to your Cargo.toml: ``` [dependencies.pnet] version = "0.35.0" ``` `libpnet` should work with the latest stable version of Rust. When running the test suite, there are a number of networking tests which will likely fail - the easiest way to workaround this is to run `cargo test` as a root or administrative user. This can often be avoided, however it is more involved. ### Windows There are three requirements for building on Windows: * You must use a version of Rust which uses the MSVC toolchain * You must have [WinPcap](https://www.winpcap.org/) or [npcap](https://nmap.org/npcap/) installed (tested with version WinPcap 4.1.3) (If using npcap, make sure to install with the "Install Npcap in WinPcap API-compatible Mode") * You must place `Packet.lib` from the [WinPcap Developers pack](https://www.winpcap.org/devel.htm) in a directory named `lib`, in the root of this repository. Alternatively, you can use any of the locations listed in the `%LIB%`/`$Env:LIB` environment variables. For the 64 bit toolchain it is in `WpdPack/Lib/x64/Packet.lib`, for the 32 bit toolchain, it is in `WpdPack/Lib/Packet.lib`. pnet_sys-0.35.0/src/lib.rs000064400000000000000000000147451046102023000134730ustar 00000000000000// Copyright (c) 2014 Robert Clipsham // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![deny(warnings)] extern crate libc; use std::io; use std::mem; #[cfg(unix)] use std::time::Duration; #[cfg(unix)] #[path = "unix.rs"] mod imp; #[cfg(windows)] #[path = "windows.rs"] mod imp; pub use self::imp::public::*; /// Any file descriptor on unix, only sockets on Windows. pub struct FileDesc { pub fd: CSocket, } impl Drop for FileDesc { fn drop(&mut self) { unsafe { close(self.fd); } } } pub fn send_to( socket: CSocket, buffer: &[u8], dst: *const SockAddr, slen: SockLen, ) -> io::Result { let send_len = imp::retry(&mut || unsafe { imp::sendto( socket, buffer.as_ptr() as Buf, buffer.len() as BufLen, 0, dst, slen, ) }); if send_len < 0 { Err(io::Error::last_os_error()) } else { Ok(send_len as usize) } } pub fn recv_from( socket: CSocket, buffer: &mut [u8], caddr: *mut SockAddrStorage, ) -> io::Result { let mut caddrlen = mem::size_of::() as SockLen; let len = imp::retry(&mut || unsafe { imp::recvfrom( socket, buffer.as_ptr() as MutBuf, buffer.len() as BufLen, 0, caddr as *mut SockAddr, &mut caddrlen, ) }); if len < 0 { Err(io::Error::last_os_error()) } else { Ok(len as usize) } } /// Set a timeout for receiving from the socket. #[cfg(unix)] pub fn set_socket_receive_timeout(socket: CSocket, t: Duration) -> io::Result<()> { let ts = duration_to_timeval(t); let r = unsafe { setsockopt( socket, SOL_SOCKET, SO_RCVTIMEO, (&ts as *const libc::timeval) as Buf, mem::size_of::() as SockLen, ) }; if r < 0 { Err(io::Error::last_os_error()) } else if r > 0 { Err(io::Error::new( io::ErrorKind::Other, format!("Unknown return value from getsockopt(): {}", r), )) } else { Ok(()) } } /// Extracts and returns a timeout for reading from the socket. #[cfg(unix)] pub fn get_socket_receive_timeout(socket: CSocket) -> io::Result { let ts = libc::timeval { tv_sec: 0, tv_usec: 0, }; let len: SockLen = mem::size_of::() as SockLen; let r = unsafe { getsockopt( socket, SOL_SOCKET, SO_RCVTIMEO, (&ts as *const libc::timeval) as MutBuf, (&len as *const SockLen) as MutSockLen, ) }; assert_eq!( len, mem::size_of::() as SockLen, "getsockopt did not set size of return value" ); if r < 0 { Err(io::Error::last_os_error()) } else if r > 0 { Err(io::Error::new( io::ErrorKind::Other, format!("Unknown return value from getsockopt(): {}", r), )) } else { Ok(timeval_to_duration(ts)) } } // These functions are taken/adapted from libnative::io::{mod, net} fn htons(u: u16) -> u16 { u.to_be() } fn ntohs(u: u16) -> u16 { u16::from_be(u) } #[cfg(test)] mod tests { use crate::get_socket_receive_timeout; use crate::recv_from; use crate::set_socket_receive_timeout; use std::mem; use std::time::{Duration, Instant}; use crate::CSocket; use crate::SockAddrStorage; fn test_timeout(socket: CSocket) -> Duration { let mut buffer = [0u8; 1024]; let mut caddr: SockAddrStorage = unsafe { mem::zeroed() }; let t0 = Instant::now(); let res = recv_from(socket, &mut buffer, &mut caddr); assert!(!res.is_ok()); Instant::now() - t0 } #[test] fn test_set_socket_receive_timeout_1s() { let socket = unsafe { libc::socket(libc::AF_INET, libc::SOCK_RAW, 1 as libc::c_int) }; let d = Duration::new(1, 0); let res = set_socket_receive_timeout(socket, d.clone()); match res { Err(e) => panic!("set_socket_receive_timeout reslted in error: {}", e), _ => {} }; let t = test_timeout(socket); assert!(t >= Duration::new(1, 0)); assert!(t < Duration::from_millis(1100)); } #[test] fn test_set_socket_receive_timeout_500ms() { let socket = unsafe { libc::socket(libc::AF_INET, libc::SOCK_RAW, 1 as libc::c_int) }; let d = Duration::from_millis(500); let res = set_socket_receive_timeout(socket, d); match res { Err(e) => panic!("set_socket_receive_timeout reslted in error: {}", e), _ => {} }; let t = test_timeout(socket); assert!(t >= Duration::from_millis(500)); assert!(t < Duration::from_millis(600)); } #[test] fn test_set_socket_receive_timeout_1500ms() { let socket = unsafe { libc::socket(libc::AF_INET, libc::SOCK_RAW, 1 as libc::c_int) }; let d = Duration::from_millis(1500); let res = set_socket_receive_timeout(socket, d); match res { Err(e) => panic!("set_socket_receive_timeout reslted in error: {}", e), _ => {} }; let t = test_timeout(socket); assert!(t >= Duration::from_millis(1500)); assert!(t < Duration::from_millis(1600)); } #[test] fn test_get_socket_receive_timeout() { let socket = unsafe { libc::socket(libc::AF_INET, libc::SOCK_RAW, 1 as libc::c_int) }; let s1 = Duration::new(1, 0); set_socket_receive_timeout(socket, s1).ok(); let g1 = get_socket_receive_timeout(socket); match g1 { Err(e) => panic!("get_socket_receive_timeout resulted in error: {}", e), Ok(t) => assert_eq!(s1, t, "Expected to receive 1s timeout"), } let s2 = Duration::from_millis(500); set_socket_receive_timeout(socket, s2).ok(); let g2 = get_socket_receive_timeout(socket); match g2 { Err(e) => panic!("get_socket_receive_timeout resulted in error: {}", e), Ok(t) => assert_eq!(s2, t, "Expected to receive 500ms timeout"), } } } pnet_sys-0.35.0/src/unix.rs000064400000000000000000000226271046102023000137060ustar 00000000000000use super::{htons, ntohs}; use std::io; pub mod public { use libc; use super::{htons, ntohs}; use std::io; use std::mem; use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; use std::time::Duration; pub type CSocket = libc::c_int; pub type Buf = *const libc::c_void; pub type MutBuf = *mut libc::c_void; pub type BufLen = libc::size_t; pub type CouldFail = libc::ssize_t; pub type SockLen = libc::socklen_t; pub type MutSockLen = *mut libc::socklen_t; pub type SockAddr = libc::sockaddr; pub type SockAddrIn = libc::sockaddr_in; pub type SockAddrIn6 = libc::sockaddr_in6; pub type SockAddrStorage = libc::sockaddr_storage; pub type SockAddrFamily = libc::sa_family_t; pub type SockAddrFamily6 = libc::sa_family_t; pub type InAddr = libc::in_addr; pub type In6Addr = libc::in6_addr; #[cfg(not(any( target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "netbsd" )))] pub type TvUsecType = libc::c_long; #[cfg(any( target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "netbsd" ))] pub type TvUsecType = libc::c_int; #[cfg(not(any(target_os = "illumos", target_os = "solaris")))] pub type InAddrType = libc::c_uint; #[cfg(any(target_os = "illumos", target_os = "solaris"))] pub type InAddrType = libc::c_ulonglong; pub const AF_INET: libc::c_int = libc::AF_INET; pub const AF_INET6: libc::c_int = libc::AF_INET6; pub const SOCK_RAW: libc::c_int = libc::SOCK_RAW; pub const SOL_SOCKET: libc::c_int = libc::SOL_SOCKET; pub const SO_RCVTIMEO: libc::c_int = libc::SO_RCVTIMEO; pub const SO_SNDTIMEO: libc::c_int = libc::SO_SNDTIMEO; pub const IPPROTO_IP: libc::c_int = libc::IPPROTO_IP; pub const IP_HDRINCL: libc::c_int = libc::IP_HDRINCL; pub const IP_TTL: libc::c_int = libc::IP_TTL; pub const IP_TOS: libc::c_int = 1; pub const IPPROTO_IPV6: libc::c_int = libc::IPPROTO_IPV6; pub const IPV6_UNICAST_HOPS: libc::c_int = libc::IPV6_UNICAST_HOPS; pub const IPV6_TCLASS: libc::c_int = libc::IPV6_TCLASS; pub use libc::{IFF_BROADCAST, IFF_LOOPBACK, IFF_RUNNING, IFF_MULTICAST, IFF_POINTOPOINT, IFF_UP}; #[cfg(any(target_os = "linux", target_os = "android"))] pub use libc::{IFF_LOWER_UP, IFF_DORMANT}; pub const INVALID_SOCKET: CSocket = -1; pub unsafe fn close(sock: CSocket) { let _ = libc::close(sock); } pub unsafe fn socket(af: libc::c_int, sock: libc::c_int, proto: libc::c_int) -> CSocket { libc::socket(af, sock, proto) } pub unsafe fn getsockopt( socket: CSocket, level: libc::c_int, name: libc::c_int, value: MutBuf, option_len: MutSockLen, ) -> libc::c_int { libc::getsockopt(socket, level, name, value, option_len) } pub unsafe fn setsockopt( socket: CSocket, level: libc::c_int, name: libc::c_int, value: Buf, option_len: SockLen, ) -> libc::c_int { libc::setsockopt(socket, level, name, value, option_len) } /// Convert a platform specific `timeval` into a Duration. pub fn timeval_to_duration(tv: libc::timeval) -> Duration { Duration::new(tv.tv_sec as u64, (tv.tv_usec as u32) * 1000) } /// Convert a Duration into a platform specific `timeval`. pub fn duration_to_timeval(dur: Duration) -> libc::timeval { libc::timeval { tv_sec: dur.as_secs() as libc::time_t, tv_usec: dur.subsec_micros() as TvUsecType, } } /// Convert a platform specific `timespec` into a Duration. pub fn timespec_to_duration(ts: libc::timespec) -> Duration { Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32) } /// Convert a Duration into a platform specific `timespec`. pub fn duration_to_timespec(dur: Duration) -> libc::timespec { libc::timespec { tv_sec: dur.as_secs() as libc::time_t, tv_nsec: (dur.subsec_nanos() as TvUsecType).into(), } } fn make_in6_addr(segments: [u16; 8]) -> In6Addr { // Safety: We're transmuting an array of ints to an array of ints. // There is no padding involved, and they must be the same size. let s6_addr = unsafe { mem::transmute::<[u16; 8], [u8; 16]>([ htons(segments[0]), htons(segments[1]), htons(segments[2]), htons(segments[3]), htons(segments[4]), htons(segments[5]), htons(segments[6]), htons(segments[7]), ]) }; In6Addr { s6_addr } } pub fn addr_to_sockaddr(addr: SocketAddr, storage: &mut SockAddrStorage) -> SockLen { unsafe { let len = match addr { SocketAddr::V4(sa) => { let ip_addr = sa.ip(); let octets = ip_addr.octets(); let inaddr = super::mk_inaddr(u32::from_be( ((octets[0] as u32) << 24) | ((octets[1] as u32) << 16) | ((octets[2] as u32) << 8) | (octets[3] as u32), )); let storage = storage as *mut _ as *mut SockAddrIn; (*storage).sin_family = AF_INET as SockAddrFamily; (*storage).sin_port = htons(addr.port()); (*storage).sin_addr = inaddr; mem::size_of::() } SocketAddr::V6(sa) => { let ip_addr = sa.ip(); let segments = ip_addr.segments(); let inaddr = make_in6_addr(segments); let storage = storage as *mut _ as *mut SockAddrIn6; (*storage).sin6_family = AF_INET6 as SockAddrFamily6; (*storage).sin6_port = htons(addr.port()); (*storage).sin6_addr = inaddr; (*storage).sin6_scope_id = sa.scope_id(); mem::size_of::() } }; len as SockLen } } pub fn sockaddr_to_addr(storage: &SockAddrStorage, len: usize) -> io::Result { match storage.ss_family as libc::c_int { AF_INET => { assert!(len as usize >= mem::size_of::()); let storage: &SockAddrIn = unsafe { mem::transmute(storage) }; let ip = super::ipv4_addr(storage.sin_addr); let a = (ip >> 24) as u8; let b = (ip >> 16) as u8; let c = (ip >> 8) as u8; let d = ip as u8; let sockaddrv4 = SocketAddrV4::new(Ipv4Addr::new(a, b, c, d), ntohs(storage.sin_port)); Ok(SocketAddr::V4(sockaddrv4)) } AF_INET6 => { assert!(len as usize >= mem::size_of::()); let storage: &SockAddrIn6 = unsafe { mem::transmute(storage) }; let arr: [u16; 8] = unsafe { mem::transmute(storage.sin6_addr.s6_addr) }; let a = ntohs(arr[0]); let b = ntohs(arr[1]); let c = ntohs(arr[2]); let d = ntohs(arr[3]); let e = ntohs(arr[4]); let f = ntohs(arr[5]); let g = ntohs(arr[6]); let h = ntohs(arr[7]); let ip = Ipv6Addr::new(a, b, c, d, e, f, g, h); Ok(SocketAddr::V6(SocketAddrV6::new( ip, ntohs(storage.sin6_port), u32::from_be(storage.sin6_flowinfo), storage.sin6_scope_id, ))) } _ => Err(io::Error::new( io::ErrorKind::InvalidData, "expected IPv4 or IPv6 socket", )), } } } use self::public::*; #[inline(always)] pub fn ipv4_addr(addr: InAddr) -> InAddrType { (addr.s_addr as InAddrType).to_be() } #[inline(always)] pub fn mk_inaddr(addr: u32) -> InAddr { InAddr { s_addr: addr } } pub unsafe fn sendto( socket: CSocket, buf: Buf, len: BufLen, flags: libc::c_int, addr: *const SockAddr, addrlen: SockLen, ) -> CouldFail { libc::sendto(socket, buf, len, flags, addr, addrlen) } pub unsafe fn recvfrom( socket: CSocket, buf: MutBuf, len: BufLen, flags: libc::c_int, addr: *mut SockAddr, addrlen: *mut SockLen, ) -> CouldFail { libc::recvfrom(socket, buf, len, flags, addr, addrlen) } #[inline] pub fn retry(f: &mut F) -> libc::ssize_t where F: FnMut() -> libc::ssize_t, { loop { let ret = f(); if ret != -1 || errno() as isize != libc::EINTR as isize { return ret; } } } fn errno() -> i32 { io::Error::last_os_error().raw_os_error().unwrap() } #[cfg(test)] mod tests { use crate::duration_to_timespec; use std::time::Duration; use crate::timespec_to_duration; #[test] fn test_duration_to_timespec() { let d1 = Duration::new(1, 0); let d2 = Duration::from_millis(500); let t1 = duration_to_timespec(d1); let t2 = duration_to_timespec(d2); let r1 = timespec_to_duration(t1); let r2 = timespec_to_duration(t2); assert_eq!(d1, r1); assert_eq!(d2, r2); } } pnet_sys-0.35.0/src/windows.rs000064400000000000000000000173661046102023000144210ustar 00000000000000use winapi::ctypes; use winapi::shared::minwindef; use winapi::um::winsock2; use std::io; use super::{htons, ntohs}; pub mod public { use winapi::ctypes; use winapi::shared::{in6addr, inaddr, ws2def, ws2ipdef}; use winapi::um::winsock2; use super::{htons, ntohs}; use std::io; use std::mem; use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; pub type CSocket = winsock2::SOCKET; pub type Buf = *const ctypes::c_char; pub type MutBuf = *mut ctypes::c_char; pub type BufLen = ctypes::c_int; pub type CouldFail = ctypes::c_int; pub type SockLen = ctypes::c_int; pub type MutSockLen = *mut ctypes::c_int; pub type SockAddr = ws2def::SOCKADDR; pub type SockAddrIn = ws2def::SOCKADDR_IN; pub type SockAddrIn6 = ws2ipdef::SOCKADDR_IN6_LH; pub type SockAddrStorage = ws2def::SOCKADDR_STORAGE; pub type SockAddrFamily = ws2def::ADDRESS_FAMILY; pub type SockAddrFamily6 = ws2def::ADDRESS_FAMILY; pub type InAddr = inaddr::IN_ADDR; pub type In6Addr = in6addr::IN6_ADDR; pub const AF_INET: ctypes::c_int = ws2def::AF_INET; pub const AF_INET6: ctypes::c_int = ws2def::AF_INET6; pub const SOCK_RAW: ctypes::c_int = winsock2::SOCK_RAW; pub const IPPROTO_IP: ctypes::c_int = ws2def::IPPROTO_IP; pub const IP_HDRINCL: ctypes::c_int = ws2ipdef::IP_HDRINCL; pub const IP_TTL: ctypes::c_int = ws2ipdef::IP_TTL; pub const IPPROTO_IPV6: ctypes::c_int = ws2def::IPPROTO_IPV6 as ctypes::c_int; pub const IPV6_UNICAST_HOPS: ctypes::c_int = ws2ipdef::IPV6_UNICAST_HOPS; pub const IFF_UP: ctypes::c_int = 0x00000001; pub const IFF_BROADCAST: ctypes::c_int = 0x00000002; pub const IFF_LOOPBACK: ctypes::c_int = 0x00000004; pub const IFF_POINTTOPOINT: ctypes::c_int = 0x00000008; pub const IFF_POINTOPOINT: ctypes::c_int = IFF_POINTTOPOINT; pub const IFF_MULTICAST: ctypes::c_int = 0x00000010; pub const INVALID_SOCKET: CSocket = winsock2::INVALID_SOCKET; pub unsafe fn close(sock: CSocket) { let _ = winsock2::closesocket(sock); } pub unsafe fn socket(af: ctypes::c_int, sock: ctypes::c_int, proto: ctypes::c_int) -> CSocket { winsock2::socket(af, sock, proto) } pub unsafe fn setsockopt( socket: CSocket, level: ctypes::c_int, name: ctypes::c_int, value: Buf, option_len: SockLen, ) -> ctypes::c_int { winsock2::setsockopt(socket, level, name, value, option_len) } pub fn make_in6_addr(segments: [u16; 8]) -> In6Addr { unsafe { let mut val: In6Addr = mem::zeroed(); *val.u.Word_mut() = [ htons(segments[0]), htons(segments[1]), htons(segments[2]), htons(segments[3]), htons(segments[4]), htons(segments[5]), htons(segments[6]), htons(segments[7]), ]; val } } pub fn addr_to_sockaddr(addr: SocketAddr, storage: &mut SockAddrStorage) -> SockLen { unsafe { let len = match addr { SocketAddr::V4(sa) => { let ip_addr = sa.ip(); let octets = ip_addr.octets(); let inaddr = super::mk_inaddr(u32::from_be( ((octets[0] as u32) << 24) | ((octets[1] as u32) << 16) | ((octets[2] as u32) << 8) | (octets[3] as u32), )); let storage = storage as *mut _ as *mut SockAddrIn; (*storage).sin_family = AF_INET as SockAddrFamily; (*storage).sin_port = htons(addr.port()); (*storage).sin_addr = inaddr; mem::size_of::() } SocketAddr::V6(sa) => { let ip_addr = sa.ip(); let segments = ip_addr.segments(); let inaddr = make_in6_addr(segments); let storage = storage as *mut _ as *mut SockAddrIn6; (*storage).sin6_family = AF_INET6 as SockAddrFamily6; (*storage).sin6_port = htons(addr.port()); (*storage).sin6_addr = inaddr; (*(*storage).u.sin6_scope_id_mut()) = sa.scope_id(); mem::size_of::() } }; len as SockLen } } pub fn sockaddr_to_addr(storage: &SockAddrStorage, len: usize) -> io::Result { unsafe { match storage.ss_family as ctypes::c_int { AF_INET => { assert!(len as usize >= mem::size_of::()); let storage: &SockAddrIn = mem::transmute(storage); let ip = super::ipv4_addr(storage.sin_addr); let a = (ip >> 24) as u8; let b = (ip >> 16) as u8; let c = (ip >> 8) as u8; let d = ip as u8; let sockaddrv4 = SocketAddrV4::new(Ipv4Addr::new(a, b, c, d), ntohs(storage.sin_port)); Ok(SocketAddr::V4(sockaddrv4)) } AF_INET6 => { assert!(len as usize >= mem::size_of::()); let storage: &SockAddrIn6 = mem::transmute(storage); let arr: [u16; 8] = mem::transmute(*storage.sin6_addr.u.Word()); let a = ntohs(arr[0]); let b = ntohs(arr[1]); let c = ntohs(arr[2]); let d = ntohs(arr[3]); let e = ntohs(arr[4]); let f = ntohs(arr[5]); let g = ntohs(arr[6]); let h = ntohs(arr[7]); let ip = Ipv6Addr::new(a, b, c, d, e, f, g, h); Ok(SocketAddr::V6(SocketAddrV6::new( ip, ntohs(storage.sin6_port), u32::from_be(storage.sin6_flowinfo), *storage.u.sin6_scope_id(), ))) } _ => Err(io::Error::new( io::ErrorKind::InvalidData, "expected IPv4 or IPv6 socket", )), } } } pub unsafe fn getsockopt( socket: CSocket, level: libc::c_int, name: libc::c_int, value: MutBuf, option_len: MutSockLen, ) -> libc::c_int { winsock2::getsockopt(socket, level, name, value, option_len) } } use self::public::*; use std::mem; #[inline(always)] pub fn ipv4_addr(addr: InAddr) -> u32 { unsafe { (*addr.S_un.S_addr() as u32).to_be() } } #[inline(always)] pub fn mk_inaddr(addr: u32) -> InAddr { unsafe { let mut val: InAddr = mem::zeroed(); *val.S_un.S_addr_mut() = addr as minwindef::ULONG; val } } pub unsafe fn sendto( socket: CSocket, buf: Buf, len: BufLen, flags: ctypes::c_int, to: *const SockAddr, tolen: SockLen, ) -> CouldFail { winsock2::sendto(socket, buf, len, flags, to, tolen) } pub unsafe fn recvfrom( socket: CSocket, buf: MutBuf, len: BufLen, flags: ctypes::c_int, addr: *mut SockAddr, addrlen: *mut SockLen, ) -> CouldFail { winsock2::recvfrom(socket, buf, len, flags, addr, addrlen) } #[inline] pub fn retry(f: &mut F) -> ctypes::c_int where F: FnMut() -> ctypes::c_int, { loop { let ret = f(); if ret != -1 || errno() as isize != winapi::shared::winerror::WSAEINTR as isize { return ret; } } } fn errno() -> i32 { io::Error::last_os_error().raw_os_error().unwrap() }