pnet_transport-0.35.0/.cargo_vcs_info.json0000644000000001540000000000100142030ustar { "git": { "sha1": "97ece70e2f87744f2ab47b4177c3888289f89a8f" }, "path_in_vcs": "pnet_transport" }pnet_transport-0.35.0/Cargo.toml0000644000000022240000000000100122010ustar # 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_transport" version = "0.35.0" authors = ["Robert Clipsham "] description = "Cross-platform, transport layer networking." homepage = "https://github.com/libpnet/libpnet" readme = "README.md" keywords = [ "networking", "transport", "raw", "socket", ] categories = ["network-programming"] license = "MIT OR Apache-2.0" repository = "https://github.com/libpnet/libpnet" [dependencies.libc] version = "0.2.147" [dependencies.pnet_base] version = "0.35.0" default-features = false [dependencies.pnet_packet] version = "0.35.0" [dependencies.pnet_sys] version = "0.35.0" [features] default = ["std"] std = ["pnet_base/std"] pnet_transport-0.35.0/Cargo.toml.orig000064400000000000000000000013221046102023000156600ustar 00000000000000[package] name = "pnet_transport" version = "0.35.0" authors = ["Robert Clipsham "] license = "MIT OR Apache-2.0" homepage = "https://github.com/libpnet/libpnet" repository = "https://github.com/libpnet/libpnet" description = "Cross-platform, transport layer networking." readme = "../README.md" keywords = ["networking", "transport", "raw", "socket"] categories = ["network-programming"] edition = "2021" [dependencies] libc = "0.2.147" pnet_base = { path = "../pnet_base", version = "0.35.0", default-features = false } pnet_sys = { path = "../pnet_sys", version = "0.35.0" } pnet_packet = { path = "../pnet_packet", version = "0.35.0" } [features] std = ["pnet_base/std"] default = ["std"] pnet_transport-0.35.0/LICENSE-APACHE000064400000000000000000000251371046102023000147270ustar 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_transport-0.35.0/LICENSE-MIT000064400000000000000000000020501046102023000144240ustar 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_transport-0.35.0/README.md000064400000000000000000000101641046102023000142540ustar 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_transport-0.35.0/src/lib.rs000064400000000000000000000402301046102023000146750ustar 00000000000000// Copyright (c) 2014, 2015 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. //! Support for implementing transport layer protocols //! //! The transport module provides the ability to send and receive packets at //! the transport layer using IPv4 or IPv6. It also enables layer 3 networking //! for specific transport protocols, using IPv4 only. //! //! Note that this is limited by operating system support - for example, on OS //! X and FreeBSD, it is impossible to implement protocols which are already //! implemented in the kernel such as TCP and UDP. #![deny(warnings)] #![macro_use] extern crate libc; extern crate pnet_packet; extern crate pnet_sys; use self::TransportChannelType::{Layer3, Layer4}; use self::TransportProtocol::{Ipv4, Ipv6}; use pnet_packet::icmp::IcmpPacket; use pnet_packet::icmpv6::Icmpv6Packet; use pnet_packet::ip::IpNextHeaderProtocol; use pnet_packet::ipv4::Ipv4Packet; use pnet_packet::tcp::TcpPacket; use pnet_packet::udp::UdpPacket; use pnet_packet::Packet; use std::io; use std::io::Error; #[cfg(unix)] use std::io::ErrorKind; use std::mem; use std::net::{self, IpAddr}; use std::sync::Arc; #[cfg(unix)] use std::time::Duration; /// Represents a transport layer protocol. #[derive(Clone, Copy)] pub enum TransportProtocol { /// Represents a transport protocol built on top of IPv4 Ipv4(IpNextHeaderProtocol), /// Represents a transport protocol built on top of IPv6 Ipv6(IpNextHeaderProtocol), } #[repr(u8)] #[derive(Clone,Copy,Debug,PartialEq)] pub enum Ecn { NotEct = 0x0, Ect1 = 0x1, Ect0 = 0x2, CE = 0x3 } impl From for Ecn { fn from(value: u8) -> Ecn { let ecn_bits = value & 0x3; if ecn_bits == Ecn::Ect0 as u8 { return Ecn::Ect0 } else if ecn_bits == Ecn::Ect1 as u8 { return Ecn::Ect1 } else if ecn_bits == Ecn::CE as u8 { return Ecn::CE } Ecn::NotEct } } /// Type of transport channel to present. #[derive(Clone, Copy)] pub enum TransportChannelType { /// The application will send and receive transport layer packets. Layer4(TransportProtocol), /// The application will send and receive IPv4 packets, with the specified transport protocol. Layer3(IpNextHeaderProtocol), } /// Structure used for sending at the transport layer. Should be created with `transport_channel()`. pub struct TransportSender { pub socket: Arc, channel_type: TransportChannelType, } /// Structure used for receiving at the transport layer. Should be created with `transport_channel()`. pub struct TransportReceiver { pub socket: Arc, pub buffer: Vec, pub channel_type: TransportChannelType, } /// Structure used for holding all configurable options for describing possible options /// for transport channels. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct Config { time_to_live: u8, } /// Create a new `(TransportSender, TransportReceiver)` pair. /// /// This allows for sending and receiving packets at the transport layer. The buffer size should be /// large enough to handle the largest packet you wish to receive. /// /// The channel type specifies what layer to send and receive packets at, and the transport /// protocol you wish to implement. For example, `Layer4(Ipv4(IpNextHeaderProtocols::Udp))` would /// allow sending and receiving UDP packets using IPv4; whereas `Layer3(IpNextHeaderProtocols::Udp)` /// would include the IPv4 Header in received values, and require manual construction of an IP /// header when sending. pub fn transport_channel( buffer_size: usize, channel_type: TransportChannelType, ) -> io::Result<(TransportSender, TransportReceiver)> { // This hack makes sure that winsock is initialised let _ = { let ip = net::Ipv4Addr::new(255, 255, 255, 255); let sockaddr = net::SocketAddr::V4(net::SocketAddrV4::new(ip, 0)); net::UdpSocket::bind(sockaddr) }; let socket = unsafe { match channel_type { Layer4(Ipv4(IpNextHeaderProtocol(proto))) | Layer3(IpNextHeaderProtocol(proto)) => { pnet_sys::socket(pnet_sys::AF_INET, pnet_sys::SOCK_RAW, proto as libc::c_int) } Layer4(Ipv6(IpNextHeaderProtocol(proto))) => { pnet_sys::socket(pnet_sys::AF_INET6, pnet_sys::SOCK_RAW, proto as libc::c_int) } } }; if socket == pnet_sys::INVALID_SOCKET { return Err(Error::last_os_error()); } if matches!(channel_type, Layer3(_) | Layer4(Ipv4(_))) { let hincl: libc::c_int = match channel_type { Layer4(..) => 0, _ => 1, }; let res = unsafe { pnet_sys::setsockopt( socket, pnet_sys::IPPROTO_IP, pnet_sys::IP_HDRINCL, (&hincl as *const libc::c_int) as pnet_sys::Buf, mem::size_of::() as pnet_sys::SockLen, ) }; if res == -1 { let err = Error::last_os_error(); unsafe { pnet_sys::close(socket); } return Err(err); } } let sock = Arc::new(pnet_sys::FileDesc { fd: socket }); let sender = TransportSender { socket: sock.clone(), channel_type, }; let receiver = TransportReceiver { socket: sock, buffer: vec![0; buffer_size], channel_type, }; Ok((sender, receiver)) } /// Create a new `(TransportSender, TransportReceiver)` pair using the additional /// options specified. /// /// For a more exhaustive descriptive, see above. pub fn transport_channel_with( buffer_size: usize, channel_type: TransportChannelType, configuration: Config, ) -> io::Result<(TransportSender, TransportReceiver)> { let (mut sender, receiver) = transport_channel(buffer_size, channel_type)?; sender.set_ttl(configuration.time_to_live)?; Ok((sender, receiver)) } /// Sets a socket option whose value is a byte. Close the socket on error. fn set_sockopt_u8( socket: Arc, level: libc::c_int, name: libc::c_int, value: u8, ) -> io::Result<()> { let value = value as i32; let res = unsafe { pnet_sys::setsockopt( socket.fd, level, name, (&value as *const libc::c_int) as pnet_sys::Buf, mem::size_of::() as pnet_sys::SockLen, ) }; match res { -1 => { let err = Error::last_os_error(); unsafe { pnet_sys::close(socket.fd); } Err(err) } _ => Ok(()), } } impl TransportSender { fn send(&mut self, packet: T, dst: IpAddr) -> io::Result { let mut caddr = unsafe { mem::zeroed() }; let sockaddr = match dst { IpAddr::V4(ip_addr) => net::SocketAddr::V4(net::SocketAddrV4::new(ip_addr, 0)), IpAddr::V6(ip_addr) => net::SocketAddr::V6(net::SocketAddrV6::new(ip_addr, 0, 0, 0)), }; let slen = pnet_sys::addr_to_sockaddr(sockaddr, &mut caddr); let caddr_ptr = (&caddr as *const pnet_sys::SockAddrStorage) as *const pnet_sys::SockAddr; pnet_sys::send_to(self.socket.fd, packet.packet(), caddr_ptr, slen) } /// Send a packet to the provided destination. #[inline] pub fn send_to(&mut self, packet: T, destination: IpAddr) -> io::Result { self.send_to_impl(packet, destination) } /// Sets a time-to-live on the socket, which then applies for all packets sent. pub fn set_ttl(&mut self, time_to_live: u8) -> io::Result<()> { let (level, name) = match self.channel_type { Layer4(Ipv4(_)) | Layer3(_) => (pnet_sys::IPPROTO_IP, pnet_sys::IP_TTL), Layer4(Ipv6(_)) => (pnet_sys::IPPROTO_IPV6, pnet_sys::IPV6_UNICAST_HOPS), }; set_sockopt_u8(self.socket.clone(), level, name, time_to_live) } /// Sets an ECN marking on the socket, which then applies for all packets sent. #[cfg(unix)] pub fn set_ecn(&mut self, tos: Ecn) -> io::Result<()> { let (level, name) = match self.channel_type { Layer4(Ipv4(_)) | Layer3(_) => (pnet_sys::IPPROTO_IP, pnet_sys::IP_TOS), Layer4(Ipv6(_)) => (pnet_sys::IPPROTO_IPV6, pnet_sys::IPV6_TCLASS), }; set_sockopt_u8(self.socket.clone(), level, name, tos as u8) } #[cfg(all( not(target_os = "freebsd"), not(any(target_os = "macos", target_os = "ios", target_os = "tvos")) ))] fn send_to_impl(&mut self, packet: T, dst: IpAddr) -> io::Result { self.send(packet, dst) } #[cfg(any(target_os = "freebsd", target_os = "macos", target_os = "ios", target_os = "tvos"))] fn send_to_impl(&mut self, packet: T, dst: IpAddr) -> io::Result { use pnet_packet::ipv4::MutableIpv4Packet; use pnet_packet::MutablePacket; // FreeBSD and OS X expect total length and fragment offset fields of IPv4 // packets to be in host byte order rather than network byte order. Fragment offset is the // ip_off field in the ip struct and contains both the offset and the three flag bits. // See `man 4 ip`/Raw IP Sockets) if let Layer3(_) = self.channel_type { let mut mut_slice: Vec = vec![0; packet.packet().len()]; let mut new_packet = MutableIpv4Packet::new(&mut mut_slice[..]).unwrap(); new_packet.clone_from(&packet); let length = new_packet.get_total_length().to_be(); new_packet.set_total_length(length); { // Turn fragment offset into host order let d = new_packet.packet_mut(); let host_order = u16::from_be((d[6] as u16) << 8 | d[7] as u16); d[6] = (host_order >> 8) as u8; d[7] = host_order as u8; } return self.send(new_packet, dst); } self.send(packet, dst) } } /// Create an iterator for some packet type. /// /// Usage: /// ```ignore /// transport_channel_iterator!(Ipv4Packet, // Type to iterate over /// Ipv4TransportChannelIterator, // Name for iterator struct /// ipv4_packet_iter) // Name of function to create iterator /// ``` #[macro_export] macro_rules! transport_channel_iterator { ($ty:ident, $iter:ident, $func:ident) => { transport_channel_iterator!($ty, $iter, $func, stringify!($ty)); }; ($ty:ident, $iter:ident, $func:ident, $tyname:expr) => { #[doc = "An iterator over packets of type `"] #[doc = $tyname] #[doc = "`."] pub struct $iter<'a> { tr: &'a mut TransportReceiver, } #[doc = "Return a packet iterator with packets of type `"] #[doc = $tyname] #[doc = "` for some transport receiver."] pub fn $func(tr: &mut TransportReceiver) -> $iter { $iter { tr: tr } } impl<'a> $iter<'a> { #[doc = "Get the next (`"] #[doc = $tyname ] #[doc = "`, `IpAddr`) pair for the given channel."] pub fn next(&mut self) -> io::Result<($ty, IpAddr)> { let mut caddr: pnet_sys::SockAddrStorage = unsafe { mem::zeroed() }; let res = pnet_sys::recv_from(self.tr.socket.fd, &mut self.tr.buffer[..], &mut caddr); let offset = match self.tr.channel_type { Layer4(Ipv4(_)) => { let ip_header = Ipv4Packet::new(&self.tr.buffer[..]).unwrap(); ip_header.get_header_length() as usize * 4usize } Layer3(_) => { fixup_packet(&mut self.tr.buffer[..]); 0 } _ => 0, }; return match res { Ok(len) => { let packet = $ty::new(&self.tr.buffer[offset..len]).unwrap(); let addr = pnet_sys::sockaddr_to_addr( &caddr, mem::size_of::(), ); let ip = match addr.unwrap() { net::SocketAddr::V4(sa) => IpAddr::V4(*sa.ip()), net::SocketAddr::V6(sa) => IpAddr::V6(*sa.ip()), }; Ok((packet, ip)) } Err(e) => Err(e), }; #[cfg(any( target_os = "freebsd", target_os = "macos", target_os = "ios", target_os = "tvos" ))] fn fixup_packet(buffer: &mut [u8]) { use pnet_packet::ipv4::MutableIpv4Packet; let buflen = buffer.len(); let mut new_packet = MutableIpv4Packet::new(buffer).unwrap(); let length = u16::from_be(new_packet.get_total_length()); new_packet.set_total_length(length); // OS X does this awesome thing where it removes the header length // from the total length sometimes. let length = new_packet.get_total_length() as usize + (new_packet.get_header_length() as usize * 4usize); if length == buflen { new_packet.set_total_length(length as u16) } let offset = u16::from_be(new_packet.get_fragment_offset()); new_packet.set_fragment_offset(offset); } #[cfg(all( not(target_os = "freebsd"), not(any(target_os = "macos", target_os = "ios", target_os = "tvos")) ))] fn fixup_packet(_buffer: &mut [u8]) {} } /// Wait only for a timespan of `t` to receive some data, then return. If no data was /// received, then `Ok(None)` is returned. #[cfg(unix)] pub fn next_with_timeout(&mut self, t: Duration) -> io::Result> { let socket_fd = self.tr.socket.fd; let old_timeout = match pnet_sys::get_socket_receive_timeout(socket_fd) { Err(e) => { eprintln!("Can not get socket timeout before receiving: {}", e); return Err(e); } Ok(t) => t, }; match pnet_sys::set_socket_receive_timeout(socket_fd, t) { Err(e) => { eprintln!("Can not set socket timeout for receiving: {}", e); return Err(e); } Ok(_) => {} } let r = match self.next() { Ok(r) => Ok(Some(r)), Err(e) => match e.kind() { ErrorKind::WouldBlock => Ok(None), _ => Err(e), }, }; match pnet_sys::set_socket_receive_timeout(socket_fd, old_timeout) { Err(e) => { eprintln!("Can not reset socket timeout after receiving: {}", e); } _ => {} }; r } } }; } transport_channel_iterator!(Ipv4Packet, Ipv4TransportChannelIterator, ipv4_packet_iter); transport_channel_iterator!(UdpPacket, UdpTransportChannelIterator, udp_packet_iter); transport_channel_iterator!(IcmpPacket, IcmpTransportChannelIterator, icmp_packet_iter); transport_channel_iterator!( Icmpv6Packet, Icmpv6TransportChannelIterator, icmpv6_packet_iter ); transport_channel_iterator!(TcpPacket, TcpTransportChannelIterator, tcp_packet_iter);