Skip to content
Merged
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
75 changes: 65 additions & 10 deletions src/done.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
// SPDX-License-Identifier: MIT

use crate::{
append_bytes, append_i32, parse_i32, DecodeError, DecodeErrorKind,
Emitable, EncodeError, ErrorContext, Field, Parseable, Rest,
append_bytes, append_i32, error::NLMSGERR_ATTR_MSG, parse_i32, DecodeError,
DecodeErrorKind, Emitable, EncodeError, ErrorContext, Field, NlasIterator,
Parseable, Rest,
};

const CODE: Field = 0..4;
Expand Down Expand Up @@ -55,20 +56,16 @@ impl<T: AsRef<[u8]>> DoneBuffer<T> {

impl<'a, T: AsRef<[u8]> + ?Sized> DoneBuffer<&'a T> {
/// Return a pointer to the extended ack attributes.
///
/// The kernel appends these attributes after the error code when the
/// `NETLINK_EXT_ACK` socket option is enabled. Use
/// [`DoneMessage::extended_ack_message`] to get the kernel message.
pub fn extended_ack(&self) -> &'a [u8] {
let data = self.buffer.as_ref();
&data[EXTENDED_ACK]
}
}

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();
&mut data[EXTENDED_ACK]
}
}

impl<T: AsRef<[u8]> + AsMut<[u8]>> DoneBuffer<T> {
/// set the error code field
pub fn set_code(&mut self, value: i32) {
Expand All @@ -81,9 +78,31 @@ impl<T: AsRef<[u8]> + AsMut<[u8]>> DoneBuffer<T> {
#[non_exhaustive]
pub struct DoneMessage {
pub code: i32,
/// Raw extended ACK attributes appended after [`Self::code`].
///
/// The kernel only appends attributes when the `NETLINK_EXT_ACK` socket
/// option is enabled.
pub extended_ack: Vec<u8>,
}

impl DoneMessage {
/// Return the human readable message from the extended ACK attributes, if
/// the kernel provided one.
pub fn extended_ack_message(&self) -> Option<&str> {
for attribute in NlasIterator::new(&self.extended_ack).ok()? {
if attribute.kind() == NLMSGERR_ATTR_MSG {
let value = attribute.value();
let end = value
.iter()
.position(|byte| *byte == 0)
.unwrap_or(value.len());
return std::str::from_utf8(&value[..end]).ok();
}
}
None
}
}

impl Emitable for DoneMessage {
fn emit_value(&self, out: &mut Vec<u8>) -> Result<(), EncodeError> {
append_i32(out, self.code);
Expand Down Expand Up @@ -133,4 +152,40 @@ mod tests {
let got = DoneMessage::parse(&done_buf).unwrap();
assert_eq!(got, expected);
}

#[test]
fn parse_real_nlmon_ext_ack_capture() {
// Captured with nlmon while sending an RTM_GETLINK dump request with
// strict checking enabled and an unsupported ifi_index filter. The
// kernel replied with NLMSG_DONE carrying NLMSGERR_ATTR_MSG.
#[rustfmt::skip]
static PAYLOAD: [u8; 60] = [
0xea, 0xff, 0xff, 0xff, 0x38, 0x00, 0x01, 0x00,
0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x20, 0x62,
0x79, 0x20, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65,
0x20, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x20, 0x6e,
0x6f, 0x74, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f,
0x72, 0x74, 0x65, 0x64, 0x20, 0x66, 0x6f, 0x72,
0x20, 0x6c, 0x69, 0x6e, 0x6b, 0x20, 0x64, 0x75,
0x6d, 0x70, 0x73, 0x00,
];

let buf = DoneBuffer::new(&PAYLOAD).unwrap();
assert_eq!(buf.code(), -22);
assert_eq!(buf.extended_ack(), &PAYLOAD[4..]);

let msg = DoneMessage::parse(&buf).unwrap();
assert_eq!(msg.code, -22);
assert_eq!(msg.extended_ack, PAYLOAD[4..].to_vec());
assert_eq!(
msg.extended_ack_message(),
Some("Filter by device index not supported for link dumps")
);
}

#[test]
fn extended_ack_message_without_attributes() {
let msg = DoneMessage::default();
assert_eq!(msg.extended_ack_message(), None);
}
}
40 changes: 19 additions & 21 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: MIT

use std::{fmt, io, num::NonZeroI32};
use std::{fmt, io};

use crate::{
append_bytes, append_i32, append_u32, buffer::NETLINK_HEADER_LEN,
Expand All @@ -14,7 +14,7 @@ const PAYLOAD: Rest = 4..;
const ERROR_HEADER_LEN: usize = PAYLOAD.start;

/// Error message string.
const NLMSGERR_ATTR_MSG: u16 = 1;
pub(crate) const NLMSGERR_ATTR_MSG: u16 = 1;
/// Offset of the invalid attribute in the original message, counting from the
/// beginning of the header.
const NLMSGERR_ATTR_OFFS: u16 = 2;
Expand Down Expand Up @@ -537,12 +537,10 @@ impl<T: AsRef<[u8]>> ErrorBuffer<T> {

/// Return the error code.
///
/// Returns `None` when there is no error to report (the message is an ACK),
/// or a `Some(e)` if there is a non-zero error code `e` to report (the
/// message is a NACK).
pub fn code(&self) -> Option<NonZeroI32> {
/// Returns `0` for acknowledgements and a negative errno for errors.
pub fn code(&self) -> i32 {
let data = self.buffer.as_ref();
NonZeroI32::new(parse_i32(&data[CODE]).unwrap())
parse_i32(&data[CODE]).unwrap()
}
}

Expand Down Expand Up @@ -650,14 +648,14 @@ impl<T: AsRef<[u8]> + AsMut<[u8]>> ErrorBuffer<T> {
pub struct ErrorMessage {
/// The error code.
///
/// Holds `None` when there is no error to report (the message is an ACK),
/// or a `Some(e)` if there is a non-zero error code `e` to report (the
/// message is a NACK).
/// Holds `0` when there is no error to report (the message is an ACK), or
/// a negative errno when there is an error to report (the message is a
/// NACK).
///
/// See [Netlink message types] for details.
///
/// [Netlink message types]: https://kernel.org/doc/html/next/userspace-api/netlink/intro.html#netlink-message-types
pub code: Option<NonZeroI32>,
pub code: i32,
/// The echoed original request, without the extended ACK attributes.
///
/// When the enclosing message has neither
Expand All @@ -672,7 +670,7 @@ pub struct ErrorMessage {

impl Emitable for ErrorMessage {
fn emit_value(&self, out: &mut Vec<u8>) -> Result<(), EncodeError> {
append_i32(out, self.raw_code());
append_i32(out, self.code);
append_bytes(out, &self.header);
self.extended_ack.emit(out)
}
Expand All @@ -696,7 +694,7 @@ impl<T: AsRef<[u8]>> Parseable<ErrorBuffer<&T>> for ErrorMessage {
impl ErrorMessage {
/// Returns the raw error code.
pub fn raw_code(&self) -> i32 {
self.code.map_or(0, NonZeroI32::get)
self.code
}

/// According to [`netlink(7)`](https://linux.die.net/man/7/netlink)
Expand Down Expand Up @@ -772,7 +770,7 @@ mod tests {
fn into_io_error() {
let io_err = io::Error::from_raw_os_error(95);
let err_msg = ErrorMessage {
code: NonZeroI32::new(-95),
code: -95,
header: vec![],
extended_ack: vec![],
};
Expand All @@ -791,7 +789,7 @@ mod tests {
.expect("failed to parse NLMSG_ERROR");
assert_eq!(
ErrorMessage {
code: None,
code: 0,
header: Vec::new(),
extended_ack: Vec::new(),
},
Expand All @@ -802,21 +800,21 @@ mod tests {

#[test]
fn parse_nack() {
let error_code = NonZeroI32::new(-1234).unwrap();
let error_code: i32 = -1234;
let mut bytes = vec![0, 0, 0, 0];
bytes.copy_from_slice(&error_code.get().to_ne_bytes());
bytes.copy_from_slice(&error_code.to_ne_bytes());
let msg = ErrorBuffer::new(&bytes)
.and_then(|buf| ErrorMessage::parse(&buf))
.expect("failed to parse NLMSG_ERROR");
assert_eq!(
ErrorMessage {
code: Some(error_code),
code: error_code,
header: Vec::new(),
extended_ack: Vec::new(),
},
msg
);
assert_eq!(msg.raw_code(), error_code.get());
assert_eq!(msg.raw_code(), error_code);
}

#[test]
Expand All @@ -826,7 +824,7 @@ mod tests {
let msg = ErrorBuffer::new(&bytes)
.and_then(|buf| ErrorMessage::parse(&buf))
.expect("failed to parse NLMSG_ERROR");
assert_eq!(msg.code, NonZeroI32::new(i32::MIN));
assert_eq!(msg.code, i32::MIN);
assert_eq!(msg.raw_code(), i32::MIN);

let io_err = msg.to_io();
Expand Down Expand Up @@ -880,7 +878,7 @@ mod extended_ack_tests {
let payload = error_payload(-22, &request, &attributes);

let msg = parse(&payload, NLM_F_CAPPED | NLM_F_ACK_TLVS).unwrap();
assert_eq!(msg.code, NonZeroI32::new(-22));
assert_eq!(msg.code, -22);
assert_eq!(msg.header, request);
assert_eq!(msg.extended_ack, attributes);
assert_eq!(msg.extended_ack_message(), Some("invalid argument"));
Expand Down
54 changes: 49 additions & 5 deletions src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ where
mod tests {
use super::*;

use std::{mem::size_of, num::NonZeroI32};
use std::mem::size_of;

fn emit<T: Emitable>(value: &T) -> Vec<u8> {
let mut out = Vec::new();
Expand Down Expand Up @@ -316,6 +316,50 @@ mod tests {
assert_eq!(got, want);
}

#[test]
fn parse_real_nlmon_done_ext_ack_capture() {
use crate::{NLM_F_ACK_TLVS, NLM_F_MULTIPART};

// Captured with nlmon while sending an RTM_GETLINK dump request with
// strict checking enabled and an unsupported ifi_index filter. The
// kernel replied with NLMSG_DONE carrying NLMSGERR_ATTR_MSG.
#[rustfmt::skip]
static PKT: [u8; 76] = [
0x4c, 0x00, 0x00, 0x00, 0x03, 0x00, 0x02, 0x02,
0x34, 0x12, 0x00, 0x00, 0x54, 0x64, 0x00, 0x00,
0xea, 0xff, 0xff, 0xff, 0x38, 0x00, 0x01, 0x00,
0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x20, 0x62,
0x79, 0x20, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65,
0x20, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x20, 0x6e,
0x6f, 0x74, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f,
0x72, 0x74, 0x65, 0x64, 0x20, 0x66, 0x6f, 0x72,
0x20, 0x6c, 0x69, 0x6e, 0x6b, 0x20, 0x64, 0x75,
0x6d, 0x70, 0x73, 0x00,
];

let got = NetlinkMessage::<FakeNetlinkInnerMessage>::deserialize(PKT)
.unwrap();
assert_eq!(got.header.length, 76);
assert_eq!(got.header.message_type, NLMSG_DONE);
assert_eq!(got.header.flags, NLM_F_ACK_TLVS | NLM_F_MULTIPART);
assert_eq!(got.header.sequence_number, 0x1234);
assert_eq!(got.header.port_number, 0x6454);

match &got.payload {
NetlinkPayload::Done(done) => {
assert_eq!(done.code, -22);
assert_eq!(
done.extended_ack_message(),
Some("Filter by device index not supported for link dumps")
);
}
payload => panic!("unexpected payload: {payload:?}"),
}

// Re-emitting the parsed message must reproduce the captured bytes.
assert_eq!(emit(&got), PKT);
}

#[test]
fn emit_computes_header() {
let header = NetlinkHeader {
Expand Down Expand Up @@ -415,7 +459,7 @@ mod tests {
..Default::default()
},
NetlinkPayload::Error(ErrorMessage {
code: NonZeroI32::new(-22),
code: -22,
header: request,
extended_ack: attributes.clone(),
}),
Expand Down Expand Up @@ -489,7 +533,7 @@ mod tests {

match &got.payload {
NetlinkPayload::Error(error) => {
assert_eq!(error.code, NonZeroI32::new(-22));
assert_eq!(error.code, -22);
assert_eq!(error.header, expected_request);
assert_eq!(error.extended_ack, expected_ack);
assert_eq!(
Expand All @@ -506,11 +550,11 @@ mod tests {

#[test]
fn test_error() {
let error_code = NonZeroI32::new(-8765).unwrap();
let error_code = -8765;

let header = NetlinkHeader::default();
let error_msg = ErrorMessage {
code: Some(error_code),
code: error_code,
header: vec![],
extended_ack: vec![],
};
Expand Down
Loading