Skip to content

Commit 27d9f7d

Browse files
ip: Replace as u8 casts with explicit From conversions for IpProtocol
According to the IANA protocol number specification (https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml), protocol numbers are always within the u8 range. Using `as` for type conversion is dangerous because it can silently discard higher-order data, leading to bugs that are hard to detect. This change ensures all protocol number conversions are type-safe and explicit, avoiding accidental data loss and aligning the code with the protocol specification.
1 parent 2704b97 commit 27d9f7d

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

src/ip.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,3 +209,16 @@ impl From<IpProtocol> for i32 {
209209
}
210210
}
211211
}
212+
213+
impl From<u8> for IpProtocol {
214+
fn from(d: u8) -> Self {
215+
IpProtocol::from(d as i32)
216+
}
217+
}
218+
219+
impl From<IpProtocol> for u8 {
220+
fn from(p: IpProtocol) -> u8 {
221+
let v: i32 = p.into();
222+
v as u8
223+
}
224+
}

src/rule/attribute.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ impl Nla for RuleAttribute {
142142
| Self::SuppressPrefixLen(value)
143143
| Self::Table(value) => NativeEndian::write_u32(buffer, *value),
144144
Self::L3MDev(value) => buffer[0] = (*value).into(),
145-
Self::IpProtocol(value) => buffer[0] = i32::from(*value) as u8,
145+
Self::IpProtocol(value) => buffer[0] = u8::from(*value),
146146
Self::Protocol(value) => buffer[0] = u8::from(*value),
147147
Self::Other(attr) => attr.emit_value(buffer),
148148
}
@@ -212,7 +212,7 @@ impl<'a, T: AsRef<[u8]> + ?Sized> Parseable<NlaBuffer<&'a T>>
212212
.into(),
213213
),
214214
FRA_IP_PROTO => Self::IpProtocol(IpProtocol::from(
215-
parse_u8(payload).context("invalid FRA_IP_PROTO value")? as i32,
215+
parse_u8(payload).context("invalid FRA_IP_PROTO value")?,
216216
)),
217217
FRA_SPORT_RANGE => Self::SourcePortRange(
218218
RulePortRange::parse(payload)

0 commit comments

Comments
 (0)