Skip to content

Copy netlink-packet-utils code to netlink-packet-core #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ description = "netlink packet types"
[dependencies]
anyhow = "1.0.31"
byteorder = "1.3.2"
netlink-packet-utils = "0.6.0"

[dev-dependencies]
netlink-packet-route = "0.13.0"
7 changes: 3 additions & 4 deletions src/buffer.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
// SPDX-License-Identifier: MIT

use byteorder::{ByteOrder, NativeEndian};
use netlink_packet_utils::DecodeError;

use crate::{Field, Rest};
use crate::{DecodeError, ErrorContext, Field, Rest};

const LENGTH: Field = 0..4;
const MESSAGE_TYPE: Field = 4..6;
Expand Down Expand Up @@ -158,7 +157,7 @@ impl<T: AsRef<[u8]>> NetlinkBuffer<T> {
/// ```
pub fn new_checked(buffer: T) -> Result<NetlinkBuffer<T>, DecodeError> {
let packet = Self::new(buffer);
packet.check_buffer_length()?;
packet.check_buffer_length().context("invalid netlink buffer length")?;
Ok(packet)
}

Expand Down Expand Up @@ -331,7 +330,7 @@ impl<'a, T: AsRef<[u8]> + ?Sized> NetlinkBuffer<&'a T> {
}
}

impl<'a, T: AsRef<[u8]> + AsMut<[u8]> + ?Sized> NetlinkBuffer<&'a mut T> {
impl<T: AsRef<[u8]> + AsMut<[u8]> + ?Sized> NetlinkBuffer<&mut T> {
/// Return a mutable pointer to the payload.
///
/// # Panic
Expand Down
9 changes: 5 additions & 4 deletions src/done.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@
use std::mem::size_of;

use byteorder::{ByteOrder, NativeEndian};
use netlink_packet_utils::DecodeError;

use crate::{Emitable, Field, Parseable, Rest};
use crate::{DecodeError, Emitable, ErrorContext, Field, Parseable, Rest};

const CODE: Field = 0..4;
const EXTENDED_ACK: Rest = 4..;
Expand All @@ -29,7 +28,9 @@ impl<T: AsRef<[u8]>> DoneBuffer<T> {

pub fn new_checked(buffer: T) -> Result<Self, DecodeError> {
let packet = Self::new(buffer);
packet.check_buffer_length()?;
packet
.check_buffer_length()
.context("invalid DoneBuffer length")?;
Ok(packet)
}

Expand Down Expand Up @@ -61,7 +62,7 @@ impl<'a, T: AsRef<[u8]> + ?Sized> DoneBuffer<&'a T> {
}
}

impl<'a, T: AsRef<[u8]> + AsMut<[u8]> + ?Sized> DoneBuffer<&'a mut T> {
impl<T: AsRef<[u8]> + AsMut<[u8]> + ?Sized> DoneBuffer<&mut T> {
/// Return a mutable pointer to the extended ack attributes.
pub fn extended_ack_mut(&mut self) -> &mut [u8] {
let data = self.buffer.as_mut();
Expand Down
116 changes: 107 additions & 9 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,110 @@
use std::{fmt, io, mem::size_of, num::NonZeroI32};

use byteorder::{ByteOrder, NativeEndian};
use netlink_packet_utils::DecodeError;

use crate::{Emitable, Field, Parseable, Rest};

const CODE: Field = 0..4;
const PAYLOAD: Rest = 4..;
const ERROR_HEADER_LEN: usize = PAYLOAD.start;

pub trait ErrorContext {
fn context(self, msg: &str) -> Self;
}

#[derive(Debug)]
pub struct DecodeError {
msg: String,
}

impl ErrorContext for DecodeError {
fn context(self, msg: &str) -> Self {
Self {
msg: format!("{} caused by {}", msg, self.msg),
}
}
}

impl<T> ErrorContext for Result<T, DecodeError>
where
T: Clone,
{
fn context(self, msg: &str) -> Result<T, DecodeError> {
match self {
Ok(t) => Ok(t),
Err(e) => Err(e.context(msg)),
}
}
}

impl From<&str> for DecodeError {
fn from(msg: &str) -> Self {
Self {
msg: msg.to_string(),
}
}
}

impl From<String> for DecodeError {
fn from(msg: String) -> Self {
Self { msg }
}
}

impl From<std::string::FromUtf8Error> for DecodeError {
fn from(err: std::string::FromUtf8Error) -> Self {
Self {
msg: format!("Invalid UTF-8 sequence: {}", err),
}
}
}

impl std::fmt::Display for DecodeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.msg)
}
}

impl std::error::Error for DecodeError {}

impl DecodeError {
pub fn invalid_mac_address(received: usize) -> Self {
Self{
msg: format!("Invalid MAC address. Expected 6 bytes, received {received} bytes"),
}
}

pub fn invalid_ip_address(received: usize) -> Self {
Self{
msg: format!("Invalid IP address. Expected 4 or 16 bytes, received {received} bytes"),
}
}

pub fn invalid_number(expected: usize, received: usize) -> Self {
Self{
msg: format!("Invalid number. Expected {expected} bytes, received {received} bytes"),
}
}

pub fn nla_buffer_too_small(buffer_len: usize, nla_len: usize) -> Self {
Self{
msg: format!("buffer has length {buffer_len}, but an NLA header is {nla_len} bytes"),
}
}

pub fn nla_length_mismatch(buffer_len: usize, nla_len: usize) -> Self {
Self{
msg: format!("buffer has length: {buffer_len}, but the NLA is {nla_len} bytes"),
}
}

pub fn nla_invalid_length(buffer_len: usize, nla_len: usize) -> Self {
Self{
msg: format!("NLA has invalid length: {nla_len} (should be at least {buffer_len} bytes)"),
}
}
}

#[derive(Debug, PartialEq, Eq, Clone)]
#[non_exhaustive]
pub struct ErrorBuffer<T> {
Expand All @@ -29,18 +125,21 @@ impl<T: AsRef<[u8]>> ErrorBuffer<T> {

pub fn new_checked(buffer: T) -> Result<Self, DecodeError> {
let packet = Self::new(buffer);
packet.check_buffer_length()?;
packet
.check_buffer_length()
.context("invalid ErrorBuffer length")?;
Ok(packet)
}

fn check_buffer_length(&self) -> Result<(), DecodeError> {
let len = self.buffer.as_ref().len();
if len < ERROR_HEADER_LEN {
Err(format!(
"invalid ErrorBuffer: length is {len} but ErrorBuffer are \
Err(DecodeError {
msg: format!(
"invalid ErrorBuffer: length is {len} but ErrorBuffer are \
at least {ERROR_HEADER_LEN} bytes"
)
.into())
),
})
} else {
Ok(())
}
Expand All @@ -65,7 +164,7 @@ impl<'a, T: AsRef<[u8]> + ?Sized> ErrorBuffer<&'a T> {
}
}

impl<'a, T: AsRef<[u8]> + AsMut<[u8]> + ?Sized> ErrorBuffer<&'a mut T> {
impl<T: AsRef<[u8]> + AsMut<[u8]> + ?Sized> ErrorBuffer<&mut T> {
/// Return a mutable pointer to the payload.
pub fn payload_mut(&mut self) -> &mut [u8] {
let data = self.buffer.as_mut();
Expand Down Expand Up @@ -199,8 +298,7 @@ mod tests {
#[test]
fn parse_nack() {
// SAFETY: value is non-zero.
const ERROR_CODE: NonZeroI32 =
unsafe { NonZeroI32::new_unchecked(-1234) };
const ERROR_CODE: NonZeroI32 = NonZeroI32::new(-1234).unwrap();
let mut bytes = vec![0, 0, 0, 0];
NativeEndian::write_i32(&mut bytes, ERROR_CODE.get());
let msg = ErrorBuffer::new_checked(&bytes)
Expand Down
8 changes: 4 additions & 4 deletions src/header.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// SPDX-License-Identifier: MIT

use netlink_packet_utils::DecodeError;

use crate::{buffer::NETLINK_HEADER_LEN, Emitable, NetlinkBuffer, Parseable};
use crate::{
buffer::NETLINK_HEADER_LEN, DecodeError, Emitable, NetlinkBuffer, Parseable,
};

/// A Netlink header representation. A netlink header has the following
/// structure:
Expand Down Expand Up @@ -111,7 +111,7 @@ mod tests {
port_number: 0,
};
assert_eq!(repr.buffer_len(), 16);
let mut buf = vec![0; 16];
let mut buf = [0; 16];
repr.emit(&mut buf[..]);
assert_eq!(&buf[..], &IP_LINK_SHOW_PKT[..16]);
}
Expand Down
10 changes: 8 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,5 +268,11 @@ pub use self::message::*;
pub mod constants;
pub use self::constants::*;

pub(crate) use self::utils::traits::*;
pub(crate) use netlink_packet_utils as utils;
pub mod nla;
pub use self::nla::*;

pub mod parsers;
pub use self::parsers::*;

#[macro_use]
mod macros;
Loading