socket9 0.1.0-alpha.1

Extended untilities for the networking/unix sockets and raw network sockets
Documentation
/*-
 * socket9 - A RAW networking sockets manipulation and configration basing on 
 * strong types.
 * 
 * Copyright (C) 2021 Aleksandr Morozov, Lucia Hoffmann
 * Copyright (C) 2025 Aleksandr Morozov
 * 
 * The syslog-rs crate can be redistributed and/or modified
 * under the terms of either of the following licenses:
 *
 *   1. EUROPEAN UNION PUBLIC LICENCE v. 1.2 EUPL © the European Union 2007, 2016 OR
 *
 *   2. the Mozilla Public License Version 2.0 (the “MPL”) OR
 *                     
 *   3. The MIT License (MIT)
 */

use std::{ffi::c_int, fmt, io::{self, ErrorKind}, net::{IpAddr, Ipv4Addr, SocketAddr}};

use crate::{AF_INET, LocalFrom, OptRMarker, SO_ORIGINAL_DST, SOL_IP, in_addr, SockOptMarker, sa_family_t, sockaddr_in};
//nat rdr

#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct SoIpOriginalDst(sockaddr_in);

#[cfg(unix)]
impl fmt::Debug for SoIpOriginalDst
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        f.debug_tuple("SoIpOriginalDst").field(&self.0).finish()
    }
}

#[cfg(windows)]
impl fmt::Debug for SoIpOriginalDst
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        f.debug_tuple("SoIpOriginalDst").finish()
    }
}

impl SockOptMarker for SoIpOriginalDst 
{
    const SO_LEVEL: c_int = SOL_IP as c_int;   
    const SO_OPTNAME: c_int = SO_ORIGINAL_DST as c_int;

    type DataType = io::Result<SocketAddr>;
    type InputType = sockaddr_in;

    #[inline]
    fn from(value: Self::InputType) -> Self 
    {
        return Self(value);
    }

    #[inline]
    fn get(self) -> Self::DataType
    {
        if self.0.sin_family != AF_INET as sa_family_t
        {
            return Err(
                io::Error::new(ErrorKind::Other, 
                    format!("expected IPv4, received sin_family: {}", self.0.sin_family))
            );
        }

        let ipv4 = <Ipv4Addr as LocalFrom<in_addr>>::from(self.0.sin_addr);
        
        return Ok(SocketAddr::new(IpAddr::V4(ipv4), self.0.sin_port));
    }

    #[inline]
    fn from_user(_: Self::DataType) -> Self where Self: Sized
    {
        panic!("SoIpOriginalDst cannot write!");
    }
}

impl OptRMarker for SoIpOriginalDst {}