pfctl/rule/
proto.rs

1// Copyright 2025 Mullvad VPN AB.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use crate::{Error, ErrorInternal, Result};
10
11#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
12#[repr(u8)]
13pub enum Proto {
14    #[default]
15    Any = libc::IPPROTO_IP as u8,
16    Tcp = libc::IPPROTO_TCP as u8,
17    Udp = libc::IPPROTO_UDP as u8,
18    Icmp = libc::IPPROTO_ICMP as u8,
19    IcmpV6 = libc::IPPROTO_ICMPV6 as u8,
20}
21
22impl From<Proto> for u8 {
23    fn from(proto: Proto) -> Self {
24        match proto {
25            Proto::Any => libc::IPPROTO_IP as u8,
26            Proto::Tcp => libc::IPPROTO_TCP as u8,
27            Proto::Udp => libc::IPPROTO_UDP as u8,
28            Proto::Icmp => libc::IPPROTO_ICMP as u8,
29            Proto::IcmpV6 => libc::IPPROTO_ICMPV6 as u8,
30        }
31    }
32}
33
34impl TryFrom<u8> for Proto {
35    type Error = crate::Error;
36
37    fn try_from(proto: u8) -> Result<Self> {
38        match proto {
39            v if v == Proto::Any as u8 => Ok(Proto::Any),
40            v if v == Proto::Tcp as u8 => Ok(Proto::Tcp),
41            v if v == Proto::Udp as u8 => Ok(Proto::Udp),
42            v if v == Proto::Icmp as u8 => Ok(Proto::Icmp),
43            v if v == Proto::IcmpV6 as u8 => Ok(Proto::IcmpV6),
44            _ => Err(Error::from(ErrorInternal::InvalidTransportProtocol(proto))),
45        }
46    }
47}