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
// Copyright 2017-2021 Lukas Pustina <lukas@pustina.de>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

use core::str::FromStr;
use std::slice::Iter;
use std::sync::Arc;

use futures::stream::{self, StreamExt};
use futures::Future;
use nom::Err;
use tokio::task;
use tracing::{debug, trace};

use crate::nameserver::NameServerConfig;
use crate::services::{Error, Result};
use crate::utils::buffer_unordered_with_breaker::StreamExtBufferUnorderedWithBreaker;
use nom::lib::std::fmt::Formatter;
use std::fmt;
use std::time::Duration;

mod opennic;
mod parser;
mod public_dns;

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ServerListSpec {
    PublicDns { spec: PublicDns },
    OpenNic { spec: OpenNic },
}

impl ServerListSpec {
    pub fn public_dns(&self) -> Option<&PublicDns> {
        match &self {
            ServerListSpec::PublicDns { spec } => Some(spec),
            _ => None,
        }
    }

    pub fn opennic(&self) -> Option<&OpenNic> {
        match &self {
            ServerListSpec::OpenNic { spec } => Some(spec),
            _ => None,
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct PublicDns {
    country: Option<String>,
}

impl Default for PublicDns {
    fn default() -> Self {
        PublicDns { country: None }
    }
}

impl PublicDns {
    pub fn country(&self) -> Option<&String> {
        self.country.as_ref()
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct OpenNic {
    anon: bool,
    number: usize,
    reliability: usize,
    ipv: IPV,
}

impl Default for OpenNic {
    fn default() -> Self {
        OpenNic {
            anon: false,
            number: 10,
            reliability: 95,
            ipv: IPV::All,
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum IPV {
    V4,
    V6,
    All,
}

impl FromStr for IPV {
    type Err = Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "4" => Ok(IPV::V4),
            "6" => Ok(IPV::V6),
            "all" => Ok(IPV::All),
            _ => Err(Self::Err::ParserError {
                what: s.to_string(),
                to: "IPV",
                why: "unsupported IP version".to_string(),
            }),
        }
    }
}

impl fmt::Display for IPV {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let s = match self {
            IPV::V4 => "4",
            IPV::V6 => "6",
            IPV::All => "all",
        };
        f.write_str(s)
    }
}

#[derive(Debug, Clone)]
pub struct ServerListDownloaderOpts {
    max_concurrent_requests: usize,
    abort_on_error: bool,
    timeout: Duration,
}

impl Default for ServerListDownloaderOpts {
    fn default() -> Self {
        ServerListDownloaderOpts::new(8, true, Duration::from_secs(5))
    }
}

impl ServerListDownloaderOpts {
    pub fn new(max_concurrent_requests: usize, abort_on_error: bool, timeout: Duration) -> ServerListDownloaderOpts {
        ServerListDownloaderOpts {
            max_concurrent_requests,
            abort_on_error,
            timeout,
        }
    }
}

#[derive(Clone)]
pub struct ServerListDownloader {
    http_client: Arc<reqwest::Client>,
    opts: Arc<ServerListDownloaderOpts>,
}

impl Default for ServerListDownloader {
    fn default() -> Self {
        ServerListDownloader::new(ServerListDownloaderOpts::default())
    }
}

impl ServerListDownloader {
    pub fn new(opts: ServerListDownloaderOpts) -> ServerListDownloader {
        ServerListDownloader {
            http_client: Arc::new(reqwest::Client::new()),
            opts: Arc::new(opts),
        }
    }

    pub async fn download<I: IntoIterator<Item = ServerListSpec>>(
        &self,
        server_list_specs: I,
    ) -> Result<DownloadResponses> {
        let breaker = create_breaker(self.opts.abort_on_error);

        let futures: Vec<_> = server_list_specs
            .into_iter()
            .map(|spec| single_download(self.clone(), spec))
            .collect();
        let downloads = sliding_window_lookups(futures, breaker, self.opts.max_concurrent_requests);
        let responses = task::spawn(downloads).await?;

        Ok(responses)
    }
}

fn create_breaker(on_error: bool) -> Box<dyn Fn(&DownloadResponse) -> bool + Send> {
    Box::new(move |r: &DownloadResponse| r.is_err() && on_error)
}

async fn single_download(downloader: ServerListDownloader, server_list_spec: ServerListSpec) -> DownloadResponse {
    let res = match server_list_spec {
        ServerListSpec::OpenNic { ref spec } => {
            let list = opennic::download(downloader, spec).await;
            debug!("Download for {:?} is {}", spec, if list.is_ok() { "ok" } else { "err" });
            list
        }
        ServerListSpec::PublicDns { ref spec } => {
            let list = public_dns::download(downloader, spec).await;
            debug!("Download for {:?} is {}", spec, if list.is_ok() { "ok" } else { "err" });
            list
        }
    }
    .into();
    trace!("DownloadResponse: {:?}", res);

    res
}

async fn sliding_window_lookups(
    futures: Vec<impl Future<Output = DownloadResponse>>,
    breaker: Box<dyn Fn(&DownloadResponse) -> bool + Send>,
    max_concurrent: usize,
) -> DownloadResponses {
    let responses = stream::iter(futures)
        .buffered_unordered_with_breaker(max_concurrent, breaker)
        .inspect(|_| trace!("Downloaded nameserver configs"))
        .collect::<Vec<_>>()
        .await;

    DownloadResponses { responses }
}

#[derive(Debug)]
pub enum DownloadResponse {
    Download { nameserver_configs: Vec<NameServerConfig> },
    Error { err: Error },
}

impl DownloadResponse {
    pub fn download(&self) -> Option<&Vec<NameServerConfig>> {
        match &self {
            DownloadResponse::Download { ref nameserver_configs } => Some(nameserver_configs),
            _ => None,
        }
    }

    pub fn is_download(&self) -> bool {
        self.download().is_some()
    }

    pub fn err(&self) -> Option<&Error> {
        match &self {
            DownloadResponse::Error { ref err } => Some(err),
            _ => None,
        }
    }

    pub fn is_err(&self) -> bool {
        self.err().is_some()
    }
}

#[derive(Debug)]
pub struct DownloadResponses {
    responses: Vec<DownloadResponse>,
}

impl DownloadResponses {
    pub fn len(&self) -> usize {
        self.responses.len()
    }

    pub fn is_empty(&self) -> bool {
        self.responses.is_empty()
    }

    pub fn iter(&self) -> Iter<DownloadResponse> {
        self.responses.iter()
    }

    pub fn nameserver_configs(&self) -> impl Iterator<Item = &NameServerConfig> {
        self.responses
            .iter()
            .map(|x| x.download())
            .flatten()
            .map(|x| x.iter())
            .flatten()
    }

    pub fn err(&self) -> impl Iterator<Item = &Error> {
        self.responses.iter().map(|x| x.err()).flatten()
    }
}

impl From<Result<Vec<NameServerConfig>>> for DownloadResponse {
    fn from(res: Result<Vec<NameServerConfig>>) -> Self {
        match res {
            Ok(nameserver_configs) => DownloadResponse::Download { nameserver_configs },
            Err(err) => DownloadResponse::Error { err },
        }
    }
}

impl FromStr for ServerListSpec {
    type Err = Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match parser::parse_server_list_spec(s) {
            Ok((_, result)) => Ok(result),
            Err(Err::Incomplete(_)) => Err(Error::ParserError {
                what: s.to_string(),
                to: "ServerListSpec",
                why: "input is incomplete".to_string(),
            }),
            Err(Err::Error((what, why))) | Err(Err::Failure((what, why))) => Err(Error::ParserError {
                what: what.to_string(),
                to: "ServerListSpec",
                why: why.description().to_string(),
            }),
        }
    }
}