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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/*-
* cdns-rs - a simple sync/async DNS query library
* Copyright (C) 2020  Aleksandr Morozov, RELKOM s.r.o
* Copyright (C) 2021-2022  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.
*/

use std::collections::VecDeque;
use std::net::IpAddr;
use std::sync::Arc;

use crate::error::*;
use crate::{internal_error};

use super::caches::CACHE;
use super::query::{QDns};
use super::{QuerySetup, QDnsQueriesRes, ResolveConfig};
use super::common::{QType, DnsRdata, DnsSoa};

/// Resolves the A and AAAA query.
///
/// # Arguments
/// 
/// * `fqdn` - [AsRef<str>] a domain name
/// 
/// * `custom_resolv` - a custom [ResolveConfig] wrapped in [Arc]
/// 
/// # Returns
/// 
/// [CDnsResult] - Ok with inner type [Vec] [DnsSoa]. If vector is empty
///     then no results found.
/// 
/// [CDnsResult] - Err with error description 
pub async 
fn resolve_fqdn<C>(fqdn: C, custom_resolv: Option<Arc<ResolveConfig>>) -> CDnsResult<Vec<IpAddr>>
where C: AsRef<str>
{
    let resolvers = 
        custom_resolv.map_or(CACHE.clone_resolve_list().await?, |f| f);

    // forming request
    let dns = 
        QDns::make_a_aaaa_request(resolvers, fqdn.as_ref(), QuerySetup::default());

    // sending request and receiving results
    let res = dns.query().await;
  
    // extracting data
    let mut iplist: Vec<IpAddr> = vec![];

    match res
    {
        QDnsQueriesRes::DnsOk{ res } =>
        {
            for r in res
            {
                if r.is_ok() == false
                {
                    // skip errors
                    continue;
                }

                for dnsr in r.get_responses()
                {
                    match dnsr.rdata
                    {
                        DnsRdata::A{ ip } => iplist.push(IpAddr::from(ip)),
                        DnsRdata::AAAA{ ip } => iplist.push(IpAddr::from(ip)),
                        _ => continue,
                    }
                }
            }
        },
        QDnsQueriesRes::DnsNotAvailable =>
        {
            internal_error!(CDnsErrorType::DnsNotAvailable, "");
        }
    }

    return Ok(iplist);
}

/// Resolves the MX record by domain name. It returns a list of domains.
/// The list is sorted by the `preference`.
/// 
/// # Arguments
/// 
/// * `fqdn` - [AsRef<str>] a domain name
/// 
/// * `custom_resolv` - a custom [ResolveConfig] wrapped in [Arc]
/// 
/// # Returns
/// 
/// [CDnsResult] - Ok with inner type [Vec] [DnsSoa]. If vector is empty
///     then no results found.
/// 
/// [CDnsResult] - Err with error description 
pub async 
fn resolve_mx<C>(fqdn: C, custom_resolv: Option<Arc<ResolveConfig>>) -> CDnsResult<Vec<String>>
where C: AsRef<str>
{
    let resolvers = 
        custom_resolv.map_or(CACHE.clone_resolve_list().await?, |f| f);

    let mut dns_req = 
        QDns::make_empty(resolvers, 1, QuerySetup::default());

    dns_req.add_request(QType::MX, fqdn.as_ref());

    // sending request and receiving results
    let res = dns_req.query().await;
  
    // extracting data
    let mut mxlist: VecDeque<(u16, String)> = VecDeque::with_capacity(5);

    match res
    {
        QDnsQueriesRes::DnsOk{ res } =>
        {
            for r in res
            {
                if r.is_ok() == false
                {
                    // skip errors
                    continue;
                }

                for dnsr in r.get_responses()
                {
                    match dnsr.rdata
                    {
                        DnsRdata::MX{ ref preference, ref exchange } => 
                        {
                            //iterate and search for the suitable place
                            let mut index: usize = 0;

                            for (pref, _) in mxlist.iter()
                            {
                                if *pref >= *preference
                                {
                                    break;
                                }

                                index += 1;
                            }

                            if index == mxlist.len()
                            {
                                // push back
                                mxlist.push_back((*preference, exchange.clone()));
                            }
                            else
                            {
                                mxlist.insert(index, (*preference, exchange.clone()));
                            }
                        }
                        _ => continue,
                    }
                }
            }
        },
        QDnsQueriesRes::DnsNotAvailable =>
        {
            internal_error!(CDnsErrorType::DnsNotAvailable, "");
        }
    }

    return Ok(mxlist.into_iter().map( |(_, ip)| ip).collect());
}

/// Resolves the SOA record
/// 
/// # Arguments
/// 
/// * `fqdn` - [AsRef<str>] a domain name
/// 
/// * `custom_resolv` - a custom [ResolveConfig] wrapped in [Arc]
/// 
/// # Returns
/// 
/// [CDnsResult] - Ok with inner type [Vec] [DnsSoa]. If vector is empty
///     then no results found.
/// 
/// [CDnsResult] - Err with error description 
pub async 
fn resolve_soa<C>(fqdn: C, custom_resolv: Option<Arc<ResolveConfig>>) -> CDnsResult<Vec<DnsSoa>>
where C: AsRef<str>
{
    let resolvers = 
        custom_resolv.map_or(CACHE.clone_resolve_list().await?, |f| f);

    let mut dns_req = 
        QDns::make_empty(resolvers, 1, QuerySetup::default());

    dns_req.add_request(QType::SOA, fqdn.as_ref());

    // sending request and receiving results
    let res = dns_req.query().await;

    let mut soa_list: Vec<DnsSoa> = Vec::new();

    match res
    {
        QDnsQueriesRes::DnsOk{ res } =>
        {
            for r in res
            {
                if r.is_ok() == false
                {
                    // skip errors
                    continue;
                }

                for dnsr in r.move_responses()
                {
                    match dnsr.rdata
                    {
                        DnsRdata::SOA{ soa } =>
                        {
                            soa_list.push(soa);
                        },
                        _ => {}
                    }
                }
            }
        },
        QDnsQueriesRes::DnsNotAvailable => {}
    }

    return Ok(soa_list);
}

/// Resolves the IP address to FQDN
/// 
/// # Arguments
/// 
/// * `ipaddr` - [AsRef<str>] an IP address
/// 
/// * `custom_resolv` - a custom [ResolveConfig] wrapped in [Arc]
/// 
/// # Returns
/// 
/// [CDnsResult] - Ok with inner type [Vec] [DnsSoa]. If vector is empty
///     then no results found.
/// 
/// [CDnsResult] - Err with error description 
pub async 
fn resolve_reverse<C>(ipaddr: C, custom_resolv: Option<Arc<ResolveConfig>>) -> CDnsResult<Vec<String>>
where C: AsRef<str>
{
    let resolvers = 
        custom_resolv.map_or(CACHE.clone_resolve_list().await?, |f| f);

    let mut dns_req = 
        QDns::make_empty(resolvers, 1, QuerySetup::default());

    dns_req.add_request(QType::PTR, ipaddr.as_ref());

    // sending request and receiving results
    let res = dns_req.query().await;

    let mut ptr_list: Vec<String> = Vec::new();

    match res
    {
        QDnsQueriesRes::DnsOk{ res } =>
        {
            for r in res
            {
                if r.is_ok() == false
                {
                    // skip errors
                    continue;
                }

                for dnsr in r.move_responses()
                {
                    match dnsr.rdata
                    {
                        DnsRdata::PTR{ fqdn } =>
                        {
                            ptr_list.push(fqdn);
                        },
                        _ => {}
                    }
                }
            }
        },
        QDnsQueriesRes::DnsNotAvailable => {}
    }

    return Ok(ptr_list);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_mx_resolve()
{
    let mx_doms = resolve_mx("protonmail.com", None).await;

    assert_eq!(mx_doms.is_err(), false);

    let mx_doms = mx_doms.unwrap();

    let mut index = 0;
    for di in mx_doms
    {
        match index
        {
            0 => assert_eq!(di.as_str(), "mail.protonmail.ch"),
            1 => assert_eq!(di.as_str(), "mailsec.protonmail.ch"),
            _ => panic!("test is required to be modified")
        }

        index += 1;

        println!("{}", di);
    }
    
}


#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_a_aaaa_resolve()
{
    let a_aaaa = resolve_fqdn("protonmail.com", None).await;

    assert_eq!(a_aaaa.is_ok(), true);

    let a_aaaa = a_aaaa.unwrap();

    for di in a_aaaa
    {
        println!("{}", di);
    }
    
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_ptr_resolve_fail()
{
    let ptr = resolve_reverse("protonmail.com", None).await;

    assert_eq!(ptr.is_ok(), true);

    let ptr = ptr.unwrap();

    assert_eq!(ptr.len(), 0);
    
}