1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
/*-
* cdns-rs - a simple sync/async DNS query library
* Copyright (C) 2020  Aleksandr Morozov, RELKOM s.r.o
* Copyright (C) 2021  Aleksandr Morozov
* 
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
* 
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

/// This file contains a networking code.

use std::io::ErrorKind;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::net::UdpSocket;
use std::time::Duration;

use crate::{internal_error, internal_error_map};

use crate::error::*;

/// A types of the communication channels which are supported.
/// It is used for data transmission between DNS client and DNS server.
pub enum NetworkTap
{
    /// A UDP stream
    UdpStream{ sock: UdpSocket, remote_addr: SocketAddr },
}

impl NetworkTap
{
    const IPV4_BIND_ALL: IpAddr = IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0));
    const IPV6_BIND_ALL: IpAddr = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));

    pub 
    fn new_udp(resolver_ip: &IpAddr, bind_ip: Option<&IpAddr>, timeout: Option<Duration>) -> CDnsResult<Self>
    {
        let bind_addr = 
            match resolver_ip
            {
                IpAddr::V4(_) => 
                    SocketAddr::from((bind_ip.unwrap_or(&Self::IPV4_BIND_ALL).clone(), 0)),
                IpAddr::V6(_) => 
                    SocketAddr::from((bind_ip.unwrap_or(&Self::IPV6_BIND_ALL).clone(), 0)),
            };

        //println!("debug: trying to bind: '{}'", bind_addr);

        let socket = 
            UdpSocket::bind(bind_addr).map_err(|e| internal_error_map!(CDnsErrorType::InternalError, "{}", e))?;

        // set socket to timeout after 2 seconds if not timeout set
        socket.set_read_timeout(
            Some(timeout.unwrap_or(Duration::from_secs(2)))
        ).map_err(|e| internal_error_map!(CDnsErrorType::InternalError, "{}", e))?;

        // setting address and port
        let remote_dns_host = SocketAddr::from((resolver_ip.clone(), 53));

        socket.connect(&remote_dns_host).map_err(|e| internal_error_map!(CDnsErrorType::InternalError, "{}", e))?;

        return Ok(
            Self::UdpStream{ sock: socket, remote_addr: remote_dns_host }
        );
    }


    /// Reads the remote host's address and port and returns it.
    /// 
    /// # Returns
    /// 
    /// * [SocketAddr] a reference to remote host address and port
    pub 
    fn get_remote_addr(&self) -> &SocketAddr
    {
        match *self
        {
            Self::UdpStream{ ref remote_addr, .. } => return remote_addr,
        }
    }

    /// Sends data over channel synchroniosly
    /// 
    /// Blocks the current thread until sent
    pub 
    fn send(&mut self, sndbuf: &[u8]) -> CDnsResult<()>
    {
         // sending request
         let n = 
            match *self
            {
                Self::UdpStream{ ref mut sock, .. } =>
                    sock.send(sndbuf).map_err(|e| internal_error_map!(CDnsErrorType::IoError, "{}", e))?,
            };
         
         //println!("debug: r = {}", n);

         return Ok(());
    }

    /// Receives data from channel synchroniosly
    /// 
    /// Blocks the current thread until received or timeout.
    pub 
    fn recv(&mut self, rcvbuf: &mut [u8]) -> CDnsResult<usize>
    {
        match *self
        {
            Self::UdpStream{ ref mut sock, ref remote_addr } =>
            {
                loop
                {
                    match sock.recv_from(rcvbuf)
                    {
                        Ok((rcv_len, rcv_src)) =>
                        {
                            // this should not fail because socket is "connected"
                            if &rcv_src != remote_addr
                            {
                                internal_error!(
                                    CDnsErrorType::DnsResponse, 
                                    "received answer from unknown host: '{}' exp: '{}'", 
                                    remote_addr, 
                                    rcv_src
                                );
                            }

                            return Ok(rcv_len);
                        },
                        Err(ref e) if e.kind() == ErrorKind::WouldBlock =>
                        {
                            // timeout
                            internal_error!(CDnsErrorType::DnsResponse, "request timeout from: '{}'", self.get_remote_addr()); 
                        },
                        Err(ref e) if e.kind() == ErrorKind::Interrupted =>
                        {
                            continue;
                        },
                        Err(e) =>
                        {
                            internal_error!(CDnsErrorType::IoError, "{}", e); 
                        }
                    } // match
                } // loop
            } // UdpStream
        } // match
    } 
}