Skip to content

Commit fdcc385

Browse files
liangwen12yearjvaclav-rh
authored andcommitted
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 98172e3 commit fdcc385

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
@@ -139,7 +139,7 @@ impl Nla for RuleAttribute {
139139
| Self::SuppressPrefixLen(value)
140140
| Self::Table(value) => emit_u32(buffer, *value).unwrap(),
141141
Self::L3MDev(value) => buffer[0] = (*value).into(),
142-
Self::IpProtocol(value) => buffer[0] = i32::from(*value) as u8,
142+
Self::IpProtocol(value) => buffer[0] = u8::from(*value),
143143
Self::Protocol(value) => buffer[0] = u8::from(*value),
144144
Self::Other(attr) => attr.emit_value(buffer),
145145
}
@@ -209,7 +209,7 @@ impl<'a, T: AsRef<[u8]> + ?Sized> Parseable<NlaBuffer<&'a T>>
209209
.into(),
210210
),
211211
FRA_IP_PROTO => Self::IpProtocol(IpProtocol::from(
212-
parse_u8(payload).context("invalid FRA_IP_PROTO value")? as i32,
212+
parse_u8(payload).context("invalid FRA_IP_PROTO value")?,
213213
)),
214214
FRA_SPORT_RANGE => Self::SourcePortRange(
215215
RulePortRange::parse(payload)

0 commit comments

Comments
 (0)