1 #![allow(clippy::assertions_on_constants)]
2 #![allow(clippy::type_complexity)]
3 #![allow(clippy::cognitive_complexity)]
4 #![allow(clippy::upper_case_acronyms)]
5 #![allow(clippy::unnecessary_wraps)]
6 #![allow(clippy::field_reassign_with_default)]
7 #![allow(dead_code)]
8 
9 #[global_allocator]
10 static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
11 
12 #[macro_use]
13 extern crate clap;
14 #[macro_use]
15 extern crate derivative;
16 #[macro_use]
17 extern crate log;
18 #[macro_use]
19 extern crate serde_derive;
20 #[macro_use]
21 extern crate serde_big_array;
22 #[cfg(feature = "metrics")]
23 #[macro_use]
24 extern crate prometheus;
25 
26 mod anonymized_dns;
27 mod blacklist;
28 mod cache;
29 mod config;
30 mod crypto;
31 mod dns;
32 mod dnscrypt;
33 mod dnscrypt_certs;
34 mod errors;
35 mod globals;
36 #[cfg(feature = "metrics")]
37 mod metrics;
38 mod resolver;
39 #[cfg(feature = "metrics")]
40 mod varz;
41 
42 use anonymized_dns::*;
43 use blacklist::*;
44 use cache::*;
45 use config::*;
46 use crypto::*;
47 use dns::*;
48 use dnscrypt::*;
49 use dnscrypt_certs::*;
50 use errors::*;
51 use globals::*;
52 #[cfg(feature = "metrics")]
53 use varz::*;
54 
55 use byteorder::{BigEndian, ByteOrder};
56 use clap::Arg;
57 use clockpro_cache::ClockProCache;
58 use dnsstamps::{InformalProperty, WithInformalProperty};
59 use futures::join;
60 use futures::prelude::*;
61 use parking_lot::Mutex;
62 use parking_lot::RwLock;
63 use privdrop::PrivDrop;
64 use rand::prelude::*;
65 use siphasher::sip128::SipHasher13;
66 use std::collections::vec_deque::VecDeque;
67 use std::convert::TryFrom;
68 use std::fs::File;
69 use std::io::prelude::*;
70 use std::net::SocketAddr;
71 use std::path::Path;
72 use std::sync::atomic::{AtomicU32, Ordering};
73 use std::sync::Arc;
74 use std::time::Duration;
75 use tokio::io::{AsyncReadExt, AsyncWriteExt};
76 use tokio::net::{TcpListener, TcpSocket, TcpStream, UdpSocket};
77 use tokio::runtime::Handle;
78 use tokio::sync::oneshot;
79 
80 const TCP_BACKLOG: i32 = 1024;
81 
82 #[derive(Debug)]
83 pub struct UdpClientCtx {
84     net_udp_socket: std::net::UdpSocket,
85     client_addr: SocketAddr,
86 }
87 
88 #[derive(Debug)]
89 pub struct TcpClientCtx {
90     client_connection: TcpStream,
91 }
92 
93 #[derive(Debug)]
94 pub enum ClientCtx {
95     Udp(UdpClientCtx),
96     Tcp(TcpClientCtx),
97 }
98 
maybe_truncate_response( client_ctx: &ClientCtx, packet: Vec<u8>, response: Vec<u8>, original_packet_size: usize, ) -> Result<Vec<u8>, Error>99 fn maybe_truncate_response(
100     client_ctx: &ClientCtx,
101     packet: Vec<u8>,
102     response: Vec<u8>,
103     original_packet_size: usize,
104 ) -> Result<Vec<u8>, Error> {
105     if let ClientCtx::Udp(_) = client_ctx {
106         let encrypted_response_min_len = response.len() + DNSCRYPT_RESPONSE_MIN_OVERHEAD;
107         if encrypted_response_min_len > original_packet_size
108             || encrypted_response_min_len > DNSCRYPT_UDP_RESPONSE_MAX_SIZE
109         {
110             return dns::serve_truncated_response(packet);
111         }
112     }
113     Ok(response)
114 }
115 
respond_to_query(client_ctx: ClientCtx, response: Vec<u8>) -> Result<(), Error>116 pub async fn respond_to_query(client_ctx: ClientCtx, response: Vec<u8>) -> Result<(), Error> {
117     match client_ctx {
118         ClientCtx::Udp(client_ctx) => {
119             let net_udp_socket = client_ctx.net_udp_socket;
120             net_udp_socket.send_to(&response, client_ctx.client_addr)?;
121         }
122         ClientCtx::Tcp(client_ctx) => {
123             let response_len = response.len();
124             ensure!(
125                 response_len <= DNSCRYPT_TCP_RESPONSE_MAX_SIZE,
126                 "Packet too large"
127             );
128             let mut client_connection = client_ctx.client_connection;
129             let mut binlen = [0u8, 0];
130             BigEndian::write_u16(&mut binlen[..], response_len as u16);
131             client_connection.write_all(&binlen).await?;
132             client_connection.write_all(&response).await?;
133             client_connection.flush().await?;
134         }
135     }
136     Ok(())
137 }
138 
encrypt_and_respond_to_query( globals: Arc<Globals>, client_ctx: ClientCtx, packet: Vec<u8>, response: Vec<u8>, original_packet_size: usize, shared_key: Option<SharedKey>, nonce: Option<[u8; DNSCRYPT_FULL_NONCE_SIZE]>, ) -> Result<(), Error>139 async fn encrypt_and_respond_to_query(
140     globals: Arc<Globals>,
141     client_ctx: ClientCtx,
142     packet: Vec<u8>,
143     response: Vec<u8>,
144     original_packet_size: usize,
145     shared_key: Option<SharedKey>,
146     nonce: Option<[u8; DNSCRYPT_FULL_NONCE_SIZE]>,
147 ) -> Result<(), Error> {
148     ensure!(dns::is_response(&response), "Packet is not a response");
149     let max_response_size = match client_ctx {
150         ClientCtx::Udp(_) => original_packet_size,
151         ClientCtx::Tcp(_) => DNSCRYPT_TCP_RESPONSE_MAX_SIZE,
152     };
153     let response = match &shared_key {
154         None => response,
155         Some(shared_key) => dnscrypt::encrypt(
156             maybe_truncate_response(&client_ctx, packet, response, original_packet_size)?,
157             shared_key,
158             nonce.as_ref().unwrap(),
159             max_response_size,
160         )?,
161     };
162     globals.varz.client_queries_resolved.inc();
163     if dns::rcode_nxdomain(&response) {
164         globals.varz.client_queries_rcode_nxdomain.inc();
165     }
166     respond_to_query(client_ctx, response).await
167 }
168 
handle_client_query( globals: Arc<Globals>, client_ctx: ClientCtx, encrypted_packet: Vec<u8>, ) -> Result<(), Error>169 async fn handle_client_query(
170     globals: Arc<Globals>,
171     client_ctx: ClientCtx,
172     encrypted_packet: Vec<u8>,
173 ) -> Result<(), Error> {
174     let original_packet_size = encrypted_packet.len();
175     ensure!(original_packet_size >= DNS_HEADER_SIZE, "Short packet");
176     debug_assert!(DNSCRYPT_QUERY_MIN_OVERHEAD > ANONYMIZED_DNSCRYPT_QUERY_MAGIC.len());
177     if globals.anonymized_dns_enabled
178         && original_packet_size >= ANONYMIZED_DNSCRYPT_QUERY_MAGIC.len() + DNS_HEADER_SIZE
179         && encrypted_packet[..ANONYMIZED_DNSCRYPT_QUERY_MAGIC.len()]
180             == ANONYMIZED_DNSCRYPT_QUERY_MAGIC
181     {
182         return handle_anonymized_dns(
183             globals,
184             client_ctx,
185             &encrypted_packet[ANONYMIZED_DNSCRYPT_QUERY_MAGIC.len()..],
186         )
187         .await;
188     }
189     if !globals.dnscrypt_enabled {
190         return Ok(());
191     }
192     let mut dnscrypt_encryption_params_set = vec![];
193     for params in &**globals.dnscrypt_encryption_params_set.read() {
194         dnscrypt_encryption_params_set.push((*params).clone())
195     }
196     let (shared_key, nonce, mut packet) =
197         match dnscrypt::decrypt(&encrypted_packet, &dnscrypt_encryption_params_set) {
198             Ok(x) => x,
199             Err(_) => {
200                 let packet = encrypted_packet;
201                 if let Some(synth_packet) = serve_certificates(
202                     &packet,
203                     &globals.provider_name,
204                     &dnscrypt_encryption_params_set,
205                 )? {
206                     return encrypt_and_respond_to_query(
207                         globals,
208                         client_ctx,
209                         packet,
210                         synth_packet,
211                         original_packet_size,
212                         None,
213                         None,
214                     )
215                     .await;
216                 }
217                 bail!("Unencrypted query");
218             }
219         };
220     ensure!(packet.len() >= DNS_HEADER_SIZE, "Short packet");
221     ensure!(qdcount(&packet) == 1, "No question");
222     ensure!(
223         !dns::is_response(&packet),
224         "Question expected, but got a response instead"
225     );
226     if let Some(tokens) = &globals.access_control_tokens {
227         match query_meta(&mut packet)? {
228             None => bail!("No access token"),
229             Some(token) => ensure!(tokens.contains(&token), "Access token not found"),
230         }
231     }
232     let response =
233         resolver::get_cached_response_or_resolve(&globals, &client_ctx, &mut packet).await?;
234     encrypt_and_respond_to_query(
235         globals,
236         client_ctx,
237         packet,
238         response,
239         original_packet_size,
240         Some(shared_key),
241         Some(nonce),
242     )
243     .await
244 }
245 
tls_proxy( globals: Arc<Globals>, binlen: [u8; 2], mut client_connection: TcpStream, ) -> Result<(), Error>246 async fn tls_proxy(
247     globals: Arc<Globals>,
248     binlen: [u8; 2],
249     mut client_connection: TcpStream,
250 ) -> Result<(), Error> {
251     let tls_upstream_addr = match &globals.tls_upstream_addr {
252         None => return Ok(()),
253         Some(tls_upstream_addr) => tls_upstream_addr,
254     };
255     let socket = match globals.external_addr {
256         Some(x @ SocketAddr::V4(_)) => {
257             let socket = TcpSocket::new_v4()?;
258             socket.set_reuseaddr(true).ok();
259             socket.bind(x)?;
260             socket
261         }
262         Some(x @ SocketAddr::V6(_)) => {
263             let socket = TcpSocket::new_v6()?;
264             socket.set_reuseaddr(true).ok();
265             socket.bind(x)?;
266             socket
267         }
268         None => match tls_upstream_addr {
269             SocketAddr::V4(_) => TcpSocket::new_v4()?,
270             SocketAddr::V6(_) => TcpSocket::new_v6()?,
271         },
272     };
273     let mut ext_socket = socket.connect(*tls_upstream_addr).await?;
274     let (mut erh, mut ewh) = ext_socket.split();
275     let (mut rh, mut wh) = client_connection.split();
276     ewh.write_all(&binlen).await?;
277     let fut_proxy_1 = tokio::io::copy(&mut rh, &mut ewh);
278     let fut_proxy_2 = tokio::io::copy(&mut erh, &mut wh);
279     match join!(fut_proxy_1, fut_proxy_2) {
280         (Ok(_), Ok(_)) => Ok(()),
281         _ => bail!("TLS proxy error"),
282     }
283 }
284 
tcp_acceptor(globals: Arc<Globals>, tcp_listener: TcpListener) -> Result<(), Error>285 async fn tcp_acceptor(globals: Arc<Globals>, tcp_listener: TcpListener) -> Result<(), Error> {
286     let runtime_handle = globals.runtime_handle.clone();
287     let timeout = globals.tcp_timeout;
288     let concurrent_connections = globals.tcp_concurrent_connections.clone();
289     let active_connections = globals.tcp_active_connections.clone();
290     while let Ok((mut client_connection, _client_addr)) = tcp_listener.accept().await {
291         let (tx, rx) = oneshot::channel::<()>();
292         {
293             let mut active_connections = active_connections.lock();
294             if active_connections.len() >= globals.tcp_max_active_connections as _ {
295                 let tx_oldest = active_connections.pop_back().unwrap();
296                 let _ = tx_oldest.send(());
297             }
298             active_connections.push_front(tx);
299         }
300         let _count = concurrent_connections.fetch_add(1, Ordering::Relaxed);
301         #[cfg(feature = "metrics")]
302         let varz = globals.varz.clone();
303         #[cfg(feature = "metrics")]
304         {
305             varz.inflight_tcp_queries.set(_count.saturating_add(1) as _);
306             varz.client_queries_tcp.inc();
307         }
308         client_connection.set_nodelay(true)?;
309         let globals = globals.clone();
310         let concurrent_connections = concurrent_connections.clone();
311         let fut = async {
312             let mut binlen = [0u8, 0];
313             client_connection.read_exact(&mut binlen).await?;
314             let packet_len = BigEndian::read_u16(&binlen) as usize;
315             if packet_len == 0x1603 {
316                 return tls_proxy(globals, binlen, client_connection).await;
317             }
318             ensure!(
319                 (DNS_HEADER_SIZE..=DNSCRYPT_TCP_QUERY_MAX_SIZE).contains(&packet_len),
320                 "Unexpected TCP query size"
321             );
322             let mut packet = vec![0u8; packet_len];
323             client_connection.read_exact(&mut packet).await?;
324             let client_ctx = ClientCtx::Tcp(TcpClientCtx { client_connection });
325             let _ = handle_client_query(globals, client_ctx, packet).await;
326             Ok(())
327         };
328         let fut_abort = rx;
329         let fut_all = tokio::time::timeout(timeout, future::select(fut.boxed(), fut_abort));
330         runtime_handle.spawn(fut_all.map(move |_| {
331             let _count = concurrent_connections.fetch_sub(1, Ordering::Relaxed);
332             #[cfg(feature = "metrics")]
333             varz.inflight_tcp_queries.set(_count.saturating_sub(1) as _);
334         }));
335     }
336     Ok(())
337 }
338 
339 #[allow(unreachable_code)]
udp_acceptor( globals: Arc<Globals>, net_udp_socket: std::net::UdpSocket, ) -> Result<(), Error>340 async fn udp_acceptor(
341     globals: Arc<Globals>,
342     net_udp_socket: std::net::UdpSocket,
343 ) -> Result<(), Error> {
344     let runtime_handle = globals.runtime_handle.clone();
345     let tokio_udp_socket = UdpSocket::try_from(net_udp_socket.try_clone()?)?;
346     let timeout = globals.udp_timeout;
347     let concurrent_connections = globals.udp_concurrent_connections.clone();
348     let active_connections = globals.udp_active_connections.clone();
349     loop {
350         let mut packet = vec![0u8; DNSCRYPT_UDP_QUERY_MAX_SIZE];
351         let (packet_len, client_addr) = tokio_udp_socket.recv_from(&mut packet).await?;
352         if packet_len < DNS_HEADER_SIZE {
353             continue;
354         }
355         let net_udp_socket = net_udp_socket.try_clone()?;
356         packet.truncate(packet_len);
357         let client_ctx = ClientCtx::Udp(UdpClientCtx {
358             net_udp_socket,
359             client_addr,
360         });
361         let (tx, rx) = oneshot::channel::<()>();
362         {
363             let mut active_connections = active_connections.lock();
364             if active_connections.len() >= globals.tcp_max_active_connections as _ {
365                 let tx_oldest = active_connections.pop_back().unwrap();
366                 let _ = tx_oldest.send(());
367             }
368             active_connections.push_front(tx);
369         }
370         let _count = concurrent_connections.fetch_add(1, Ordering::Relaxed);
371         #[cfg(feature = "metrics")]
372         let varz = globals.varz.clone();
373         #[cfg(feature = "metrics")]
374         {
375             varz.inflight_udp_queries.set(_count.saturating_add(1) as _);
376             varz.client_queries_udp.inc();
377         }
378         let globals = globals.clone();
379         let concurrent_connections = concurrent_connections.clone();
380         let fut = handle_client_query(globals, client_ctx, packet);
381         let fut_abort = rx;
382         let fut_all = tokio::time::timeout(timeout, future::select(fut.boxed(), fut_abort));
383         runtime_handle.spawn(fut_all.map(move |_| {
384             let _count = concurrent_connections.fetch_sub(1, Ordering::Relaxed);
385             #[cfg(feature = "metrics")]
386             varz.inflight_udp_queries.set(_count.saturating_sub(1) as _);
387         }));
388     }
389 }
390 
start( globals: Arc<Globals>, runtime_handle: Handle, listeners: Vec<(std::net::TcpListener, std::net::UdpSocket)>, ) -> Result<(), Error>391 async fn start(
392     globals: Arc<Globals>,
393     runtime_handle: Handle,
394     listeners: Vec<(std::net::TcpListener, std::net::UdpSocket)>,
395 ) -> Result<(), Error> {
396     for listener in listeners {
397         let tcp_listener_str = format!("{:?}", listener.0);
398         let tokio_tcp_listener = match TcpListener::from_std(listener.0) {
399             Ok(tcp_listener) => tcp_listener,
400             Err(e) => bail!("{}/TCP: {}", tcp_listener_str, e),
401         };
402         runtime_handle.spawn(tcp_acceptor(globals.clone(), tokio_tcp_listener).map(|_| {}));
403         runtime_handle.spawn(udp_acceptor(globals.clone(), listener.1).map(|_| {}));
404     }
405     Ok(())
406 }
407 
bind_listeners( listen_addrs: &[SocketAddr], ) -> Result<Vec<(std::net::TcpListener, std::net::UdpSocket)>, Error>408 fn bind_listeners(
409     listen_addrs: &[SocketAddr],
410 ) -> Result<Vec<(std::net::TcpListener, std::net::UdpSocket)>, Error> {
411     let mut sockets = Vec::with_capacity(listen_addrs.len());
412     for listen_addr in listen_addrs {
413         let tcp_listener: std::net::TcpListener = match listen_addr {
414             SocketAddr::V4(_) => {
415                 let kindy = socket2::Socket::new(
416                     socket2::Domain::IPV4,
417                     socket2::Type::STREAM,
418                     Some(socket2::Protocol::TCP),
419                 )?;
420                 kindy.set_reuse_address(true)?;
421                 kindy.bind(&(*listen_addr).into())?;
422                 kindy.listen(TCP_BACKLOG as _)?;
423                 kindy.into()
424             }
425             SocketAddr::V6(_) => {
426                 let kindy = socket2::Socket::new(
427                     socket2::Domain::IPV6,
428                     socket2::Type::STREAM,
429                     Some(socket2::Protocol::TCP),
430                 )?;
431                 kindy.set_reuse_address(true)?;
432                 kindy.set_only_v6(true)?;
433                 kindy.bind(&(*listen_addr).into())?;
434                 kindy.listen(TCP_BACKLOG as _)?;
435                 kindy.into()
436             }
437         };
438         tcp_listener.set_nonblocking(true)?;
439         let udp_socket: std::net::UdpSocket = match listen_addr {
440             SocketAddr::V4(_) => {
441                 let kindy = socket2::Socket::new(
442                     socket2::Domain::IPV4,
443                     socket2::Type::DGRAM,
444                     Some(socket2::Protocol::UDP),
445                 )?;
446                 kindy.set_reuse_address(true)?;
447                 kindy.bind(&(*listen_addr).into())?;
448                 kindy.into()
449             }
450             SocketAddr::V6(_) => {
451                 let kindy = socket2::Socket::new(
452                     socket2::Domain::IPV6,
453                     socket2::Type::DGRAM,
454                     Some(socket2::Protocol::UDP),
455                 )?;
456                 kindy.set_reuse_address(true)?;
457                 kindy.set_only_v6(true)?;
458                 kindy.bind(&(*listen_addr).into())?;
459                 kindy.into()
460             }
461         };
462         udp_socket.set_nonblocking(true)?;
463         sockets.push((tcp_listener, udp_socket))
464     }
465     Ok(sockets)
466 }
467 
privdrop(config: &Config) -> Result<(), Error>468 fn privdrop(config: &Config) -> Result<(), Error> {
469     let mut pd = PrivDrop::default();
470     if let Some(user) = &config.user {
471         pd = pd.user(user);
472     }
473     if let Some(group) = &config.group {
474         pd = pd.group(group);
475     }
476     if let Some(chroot) = &config.chroot {
477         if !config.daemonize {
478             pd = pd.chroot(chroot);
479         }
480     }
481     if config.user.is_some() || config.group.is_some() || config.chroot.is_some() {
482         info!("Dropping privileges");
483         pd.apply()?;
484     }
485     if config.daemonize {
486         let mut daemon = daemonize_simple::Daemonize::default();
487         daemon.stdout_file = config.log_file.clone();
488         daemon.stderr_file = config.log_file.clone();
489         daemon.pid_file = config.pid_file.clone();
490         if let Some(chroot) = &config.chroot {
491             daemon.chdir = Some(chroot.into());
492             daemon.chroot = true;
493         }
494         daemon
495             .doit()
496             .map_err(|e| anyhow!("Unable to daemonize: [{}]", e))?;
497     }
498     Ok(())
499 }
500 
main() -> Result<(), Error>501 fn main() -> Result<(), Error> {
502     env_logger::Builder::from_default_env()
503         .write_style(env_logger::WriteStyle::Never)
504         .format_module_path(false)
505         .format_timestamp(None)
506         .filter_level(log::LevelFilter::Info)
507         .target(env_logger::Target::Stdout)
508         .init();
509 
510     crypto::init()?;
511     let time_updater = coarsetime::Updater::new(1000).start()?;
512     let matches = app_from_crate!()
513         .arg(
514             Arg::with_name("config")
515                 .long("config")
516                 .short("c")
517                 .value_name("file")
518                 .takes_value(true)
519                 .default_value("encrypted-dns.toml")
520                 .help("Path to the configuration file"),
521         )
522         .arg(
523             Arg::with_name("import-from-dnscrypt-wrapper")
524                 .long("import-from-dnscrypt-wrapper")
525                 .value_name("secret.key file")
526                 .takes_value(true)
527                 .help("Path to the dnscrypt-wrapper secret key"),
528         )
529         .arg(
530             Arg::with_name("dry-run")
531                 .long("dry-run")
532                 .takes_value(false)
533                 .help("Only print the connection information and quit"),
534         )
535         .get_matches();
536 
537     let config_path = matches.value_of("config").unwrap();
538     let config = Config::from_path(config_path)?;
539     let dnscrypt_enabled = config.dnscrypt.enabled.unwrap_or(true);
540     let provider_name = match &config.dnscrypt.provider_name {
541         provider_name if provider_name.starts_with("2.dnscrypt-cert.") => provider_name.to_string(),
542         provider_name => format!("2.dnscrypt-cert.{}", provider_name),
543     };
544     let external_addr = config.external_addr.map(|addr| SocketAddr::new(addr, 0));
545 
546     let listen_addrs: Vec<_> = config.listen_addrs.iter().map(|x| x.local).collect();
547     let listeners = bind_listeners(&listen_addrs)
548         .map_err(|e| {
549             error!("Unable to listen to the requested IPs and ports: [{}]", e);
550             std::process::exit(1);
551         })
552         .unwrap();
553     privdrop(&config)?;
554 
555     let mut runtime_builder = tokio::runtime::Builder::new_multi_thread();
556     runtime_builder.enable_all();
557     runtime_builder.thread_name("encrypted-dns-");
558     let runtime = runtime_builder.build()?;
559 
560     let key_cache_capacity = config.dnscrypt.key_cache_capacity;
561     let cache_capacity = config.cache_capacity;
562     let state_file = &config.state_file;
563 
564     if let Some(secret_key_path) = matches.value_of("import-from-dnscrypt-wrapper") {
565         let secret_key_path = Path::new(secret_key_path);
566         warn!("Importing dnscrypt-wrapper key");
567         let mut key = vec![];
568         File::open(secret_key_path)?.read_to_end(&mut key)?;
569         if key.len() != 64 {
570             bail!("Key doesn't have the expected size");
571         }
572         let mut sign_sk_u8 = [0u8; 64];
573         let mut sign_pk_u8 = [0u8; 32];
574         sign_sk_u8.copy_from_slice(&key);
575         sign_pk_u8.copy_from_slice(&key[32..]);
576         let provider_kp = SignKeyPair {
577             sk: SignSK::from_bytes(sign_sk_u8),
578             pk: SignPK::from_bytes(sign_pk_u8),
579         };
580         runtime.block_on(
581             State::with_key_pair(provider_kp, key_cache_capacity).async_save(state_file),
582         )?;
583         warn!("Key successfully imported");
584     }
585 
586     let (state, state_is_new) = match State::from_file(state_file, key_cache_capacity) {
587         Err(_) => {
588             warn!("No state file found... creating a new provider key");
589             let state = State::new(key_cache_capacity);
590             runtime.block_on(state.async_save(state_file))?;
591             (state, true)
592         }
593         Ok(state) => {
594             info!(
595                 "State file [{}] found; using existing provider key",
596                 state_file.as_os_str().to_string_lossy()
597             );
598             (state, false)
599         }
600     };
601     let provider_kp = state.provider_kp;
602     for listen_addr_s in &config.listen_addrs {
603         info!("Public server address: {}", listen_addr_s.external);
604         info!("Provider public key: {}", provider_kp.pk.as_string());
605         info!("Provider name: {}", provider_name);
606         let mut stamp = dnsstamps::DNSCryptBuilder::new(dnsstamps::DNSCryptProvider::new(
607             provider_name.clone(),
608             provider_kp.pk.as_bytes().to_vec(),
609         ))
610         .with_addr(listen_addr_s.external.to_string());
611         if config.dnscrypt.dnssec {
612             stamp = stamp.with_informal_property(InformalProperty::DNSSEC);
613         }
614         if config.dnscrypt.no_filters {
615             stamp = stamp.with_informal_property(InformalProperty::NoFilters);
616         }
617         if config.dnscrypt.no_logs {
618             stamp = stamp.with_informal_property(InformalProperty::NoLogs);
619         }
620         let stamp = stamp.serialize().unwrap();
621         info!("DNS Stamp: {}", stamp);
622 
623         if let Some(anonymized_dns) = &config.anonymized_dns {
624             if anonymized_dns.enabled {
625                 let relay_stamp = dnsstamps::DNSCryptRelayBuilder::new()
626                     .with_addr(listen_addr_s.external.to_string())
627                     .serialize()
628                     .unwrap();
629                 info!("DNS Stamp for Anonymized DNS relaying: {}", relay_stamp);
630             }
631         }
632     }
633     if matches.is_present("dry-run") {
634         return Ok(());
635     }
636     let dnscrypt_encryption_params_set = state
637         .dnscrypt_encryption_params_set
638         .into_iter()
639         .map(Arc::new)
640         .collect::<Vec<_>>();
641 
642     let (sh_k0, sh_k1) = rand::thread_rng().gen();
643     let hasher = SipHasher13::new_with_keys(sh_k0, sh_k1);
644 
645     let cache = Cache::new(
646         ClockProCache::new(cache_capacity)
647             .map_err(|e| anyhow!("Unable to create the DNS cache: [{}]", e))?,
648         config.cache_ttl_min,
649         config.cache_ttl_max,
650         config.cache_ttl_error,
651     );
652     let cert_cache = Cache::new(
653         ClockProCache::new(RELAYED_CERT_CACHE_SIZE)
654             .map_err(|e| anyhow!("Unable to create the relay cert cache: [{}]", e))?,
655         RELAYED_CERT_CACHE_TTL,
656         RELAYED_CERT_CACHE_TTL,
657         RELAYED_CERT_CACHE_TTL,
658     );
659     let blacklist = match config.filtering.domain_blacklist {
660         None => None,
661         Some(path) => Some(
662             BlackList::load(&path)
663                 .map_err(|e| anyhow!("Unable to load the blacklist [{:?}]: [{}]", path, e))?,
664         ),
665     };
666     let undelegated_list = match config.filtering.undelegated_list {
667         None => None,
668         Some(path) => Some(BlackList::load(&path).map_err(|e| {
669             anyhow!(
670                 "Unable to load the list of undelegated TLDs [{:?}]: [{}]",
671                 path,
672                 e
673             )
674         })?),
675     };
676     let ignore_unqualified_hostnames = config
677         .filtering
678         .ignore_unqualified_hostnames
679         .unwrap_or(true);
680     let (
681         anonymized_dns_enabled,
682         anonymized_dns_allowed_ports,
683         anonymized_dns_allow_non_reserved_ports,
684         anonymized_dns_blacklisted_ips,
685     ) = match config.anonymized_dns {
686         None => (false, vec![], false, vec![]),
687         Some(anonymized_dns) => (
688             anonymized_dns.enabled,
689             anonymized_dns.allowed_ports,
690             anonymized_dns.allow_non_reserved_ports.unwrap_or(false),
691             anonymized_dns.blacklisted_ips,
692         ),
693     };
694     let access_control_tokens = match config.access_control {
695         Some(access_control) if access_control.enabled && !access_control.tokens.is_empty() => {
696             info!("Access control enabled");
697             Some(access_control.tokens)
698         }
699         _ => None,
700     };
701     let runtime_handle = runtime.handle();
702     let globals = Arc::new(Globals {
703         runtime_handle: runtime_handle.clone(),
704         state_file: state_file.to_path_buf(),
705         dnscrypt_encryption_params_set: Arc::new(RwLock::new(Arc::new(
706             dnscrypt_encryption_params_set,
707         ))),
708         provider_name,
709         provider_kp,
710         listen_addrs,
711         upstream_addr: config.upstream_addr,
712         tls_upstream_addr: config.tls.upstream_addr,
713         external_addr,
714         tcp_timeout: Duration::from_secs(u64::from(config.tcp_timeout)),
715         udp_timeout: Duration::from_secs(u64::from(config.udp_timeout)),
716         udp_concurrent_connections: Arc::new(AtomicU32::new(0)),
717         tcp_concurrent_connections: Arc::new(AtomicU32::new(0)),
718         udp_max_active_connections: config.udp_max_active_connections,
719         tcp_max_active_connections: config.tcp_max_active_connections,
720         udp_active_connections: Arc::new(Mutex::new(VecDeque::with_capacity(
721             config.udp_max_active_connections as _,
722         ))),
723         tcp_active_connections: Arc::new(Mutex::new(VecDeque::with_capacity(
724             config.tcp_max_active_connections as _,
725         ))),
726         key_cache_capacity,
727         hasher,
728         cache,
729         cert_cache,
730         blacklist,
731         undelegated_list,
732         ignore_unqualified_hostnames,
733         dnscrypt_enabled,
734         anonymized_dns_enabled,
735         anonymized_dns_allowed_ports,
736         anonymized_dns_allow_non_reserved_ports,
737         anonymized_dns_blacklisted_ips,
738         access_control_tokens,
739         my_ip: config.my_ip.map(|ip| ip.as_bytes().to_ascii_lowercase()),
740         client_ttl_holdon: config.client_ttl_holdon.unwrap_or(60),
741         #[cfg(feature = "metrics")]
742         varz: Varz::default(),
743     });
744     let updater = DNSCryptEncryptionParamsUpdater::new(globals.clone());
745     if !state_is_new {
746         updater.update();
747     }
748     #[cfg(feature = "metrics")]
749     {
750         if let Some(metrics_config) = config.metrics {
751             runtime_handle.spawn(
752                 metrics::prometheus_service(
753                     globals.varz.clone(),
754                     metrics_config,
755                     runtime_handle.clone(),
756                 )
757                 .map_err(|e| {
758                     error!("Unable to start the metrics service: [{}]", e);
759                     std::process::exit(1);
760                 })
761                 .map(|_| ()),
762             );
763         }
764     }
765     runtime_handle.spawn(
766         start(globals, runtime_handle.clone(), listeners)
767             .map_err(|e| {
768                 error!("Unable to start the service: [{}]", e);
769                 std::process::exit(1);
770             })
771             .map(|_| ()),
772     );
773     runtime.block_on(updater.run());
774     time_updater.stop()?;
775     Ok(())
776 }
777