-
Notifications
You must be signed in to change notification settings - Fork 429
/
trust-dns.rs
779 lines (685 loc) · 25.5 KB
/
trust-dns.rs
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
// Copyright 2015-2018 Benjamin Fry <benjaminfry@me.com>
//
// 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.
//! The `trust-dns` binary for running a DNS server
//!
//! ```text
//! Usage: trust-dns [options]
//! trust-dns (-h | --help | --version)
//!
//! Options:
//! -q, --quiet Disable INFO messages, WARN and ERROR will remain
//! -d, --debug Turn on DEBUG messages (default is only INFO)
//! -h, --help Show this message
//! -v, --version Show the version of trust-dns
//! -c FILE, --config=FILE Path to configuration file, default is /etc/named.toml
//! -z DIR, --zonedir=DIR Path to the root directory for all zone files, see also config toml
//! -p PORT, --port=PORT Override the listening port
//! --tls-port=PORT Override the listening port for TLS connections
//! ```
// BINARY WARNINGS
#![warn(
clippy::dbg_macro,
clippy::unimplemented,
missing_copy_implementations,
missing_docs,
non_snake_case,
non_upper_case_globals,
rust_2018_idioms,
unreachable_pub
)]
#![recursion_limit = "128"]
use std::{
env, fmt,
net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs},
path::{Path, PathBuf},
sync::Arc,
};
use clap::Parser;
use time::OffsetDateTime;
use tokio::{
net::{TcpListener, UdpSocket},
runtime,
};
use tracing::{debug, error, info, warn, Event, Subscriber};
use tracing_subscriber::{
fmt::{format, FmtContext, FormatEvent, FormatFields, FormattedFields},
layer::SubscriberExt,
registry::LookupSpan,
util::SubscriberInitExt,
};
use trust_dns_client::rr::Name;
#[cfg(feature = "dns-over-tls")]
use trust_dns_server::config::dnssec::{self, TlsCertConfig};
#[cfg(feature = "resolver")]
use trust_dns_server::store::forwarder::ForwardAuthority;
#[cfg(feature = "recursor")]
use trust_dns_server::store::recursor::RecursiveAuthority;
#[cfg(feature = "sqlite")]
use trust_dns_server::store::sqlite::{SqliteAuthority, SqliteConfig};
use trust_dns_server::{
authority::{AuthorityObject, Catalog, ZoneType},
config::{Config, ZoneConfig},
server::ServerFuture,
store::{
file::{FileAuthority, FileConfig},
StoreConfig,
},
};
#[cfg(feature = "dnssec")]
use {trust_dns_client::rr::rdata::key::KeyUsage, trust_dns_server::authority::DnssecAuthority};
#[cfg(feature = "dnssec")]
async fn load_keys<A, L>(
authority: &mut A,
zone_name: Name,
zone_config: &ZoneConfig,
) -> Result<(), String>
where
A: DnssecAuthority<Lookup = L>,
L: Send + Sync + Sized + 'static,
{
if zone_config.is_dnssec_enabled() {
for key_config in zone_config.get_keys() {
info!(
"adding key to zone: {:?}, is_zsk: {}, is_auth: {}",
key_config.key_path(),
key_config.is_zone_signing_key(),
key_config.is_zone_update_auth()
);
if key_config.is_zone_signing_key() {
let zone_signer = key_config.try_into_signer(zone_name.clone()).map_err(|e| {
format!("failed to load key: {:?} msg: {}", key_config.key_path(), e)
})?;
authority
.add_zone_signing_key(zone_signer)
.await
.expect("failed to add zone signing key to authority");
}
if key_config.is_zone_update_auth() {
let update_auth_signer =
key_config.try_into_signer(zone_name.clone()).map_err(|e| {
format!("failed to load key: {:?} msg: {}", key_config.key_path(), e)
})?;
let public_key = update_auth_signer
.key()
.to_sig0key_with_usage(update_auth_signer.algorithm(), KeyUsage::Host)
.expect("failed to get sig0 key");
authority
.add_update_auth_key(zone_name.clone(), public_key)
.await
.expect("failed to add update auth key to authority");
}
}
info!("signing zone: {}", zone_config.get_zone()?);
authority.secure_zone().await.expect("failed to sign zone");
}
Ok(())
}
#[cfg(not(feature = "dnssec"))]
#[allow(clippy::unnecessary_wraps)]
async fn load_keys<T>(
_authority: &mut T,
_zone_name: Name,
_zone_config: &ZoneConfig,
) -> Result<(), String> {
Ok(())
}
#[cfg_attr(not(feature = "dnssec"), allow(unused_mut, unused))]
#[warn(clippy::wildcard_enum_match_arm)] // make sure all cases are handled despite of non_exhaustive
async fn load_zone(
zone_dir: &Path,
zone_config: &ZoneConfig,
) -> Result<Box<dyn AuthorityObject>, String> {
debug!("loading zone with config: {:#?}", zone_config);
let zone_name: Name = zone_config.get_zone().expect("bad zone name");
let zone_name_for_signer = zone_name.clone();
let zone_path: Option<String> = zone_config.file.clone();
let zone_type: ZoneType = zone_config.get_zone_type();
let is_axfr_allowed = zone_config.is_axfr_allowed();
#[allow(unused_variables)]
let is_dnssec_enabled = zone_config.is_dnssec_enabled();
if zone_config.is_update_allowed() {
warn!("allow_update is deprecated in [[zones]] section, it belongs in [[zones.stores]]");
}
// load the zone
let authority: Box<dyn AuthorityObject> = match zone_config.stores {
#[cfg(feature = "sqlite")]
Some(StoreConfig::Sqlite(ref config)) => {
if zone_path.is_some() {
warn!("ignoring [[zones.file]] instead using [[zones.stores.zone_file_path]]");
}
let mut authority = SqliteAuthority::try_from_config(
zone_name,
zone_type,
is_axfr_allowed,
is_dnssec_enabled,
Some(zone_dir),
config,
)
.await?;
// load any keys for the Zone, if it is a dynamic update zone, then keys are required
load_keys(&mut authority, zone_name_for_signer, zone_config).await?;
Box::new(Arc::new(authority)) as Box<dyn AuthorityObject>
}
Some(StoreConfig::File(ref config)) => {
if zone_path.is_some() {
warn!("ignoring [[zones.file]] instead using [[zones.stores.zone_file_path]]");
}
let mut authority = FileAuthority::try_from_config(
zone_name,
zone_type,
is_axfr_allowed,
Some(zone_dir),
config,
)?;
// load any keys for the Zone, if it is a dynamic update zone, then keys are required
load_keys(&mut authority, zone_name_for_signer, zone_config).await?;
Box::new(Arc::new(authority)) as Box<dyn AuthorityObject>
}
#[cfg(feature = "resolver")]
Some(StoreConfig::Forward(ref config)) => {
let forwarder = ForwardAuthority::try_from_config(zone_name, zone_type, config)?;
Box::new(Arc::new(forwarder)) as Box<dyn AuthorityObject>
}
#[cfg(feature = "recursor")]
Some(StoreConfig::Recursor(ref config)) => {
let recursor =
RecursiveAuthority::try_from_config(zone_name, zone_type, config, Some(zone_dir));
let authority = recursor.await?;
Box::new(Arc::new(authority)) as Box<dyn AuthorityObject>
}
#[cfg(feature = "sqlite")]
None if zone_config.is_update_allowed() => {
warn!(
"using deprecated SQLite load configuration, please move to [[zones.stores]] form"
);
let zone_file_path = zone_path.ok_or("file is a necessary parameter of zone_config")?;
let journal_file_path = PathBuf::from(zone_file_path.clone())
.with_extension("jrnl")
.to_str()
.map(String::from)
.ok_or("non-unicode characters in file name")?;
let config = SqliteConfig {
zone_file_path,
journal_file_path,
allow_update: zone_config.is_update_allowed(),
};
let mut authority = SqliteAuthority::try_from_config(
zone_name,
zone_type,
is_axfr_allowed,
is_dnssec_enabled,
Some(zone_dir),
&config,
)
.await?;
// load any keys for the Zone, if it is a dynamic update zone, then keys are required
load_keys(&mut authority, zone_name_for_signer, zone_config).await?;
Box::new(Arc::new(authority)) as Box<dyn AuthorityObject>
}
None => {
let config = FileConfig {
zone_file_path: zone_path.ok_or("file is a necessary parameter of zone_config")?,
};
let mut authority = FileAuthority::try_from_config(
zone_name,
zone_type,
is_axfr_allowed,
Some(zone_dir),
&config,
)?;
// load any keys for the Zone, if it is a dynamic update zone, then keys are required
load_keys(&mut authority, zone_name_for_signer, zone_config).await?;
Box::new(Arc::new(authority)) as Box<dyn AuthorityObject>
}
Some(_) => {
panic!("unrecognized authority type, check enabled features");
}
};
info!("zone successfully loaded: {}", zone_config.get_zone()?);
Ok(authority)
}
/// Cli struct for all options managed with clap derive api.
#[derive(Debug, Parser)]
#[clap(name = "Trust-DNS named server", version, about)]
struct Cli {
/// Disable INFO messages, WARN and ERROR will remain
#[clap(short = 'q', long = "quiet", conflicts_with = "debug")]
pub(crate) quiet: bool,
/// Turn on `DEBUG` messages (default is only `INFO`)
#[clap(short = 'd', long = "debug", conflicts_with = "quiet")]
pub(crate) debug: bool,
/// Path to configuration file of named server,
/// by default `/etc/named.toml`
#[clap(
short = 'c',
long = "config",
default_value = "/etc/named.toml",
value_name = "NAME",
value_hint=clap::ValueHint::FilePath,
)]
pub(crate) config: PathBuf,
/// Path to the root directory for all zone files,
/// see also config toml
#[clap(short = 'z', long = "zonedir", value_name = "DIR", value_hint=clap::ValueHint::DirPath)]
pub(crate) zonedir: Option<PathBuf>,
/// Listening port for DNS queries,
/// overrides any value in config file
#[clap(short = 'p', long = "port", value_name = "PORT")]
pub(crate) port: Option<u16>,
/// Listening port for DNS over TLS queries,
/// overrides any value in config file
#[clap(long = "tls-port", value_name = "TLS-PORT")]
pub(crate) tls_port: Option<u16>,
/// Listening port for DNS over HTTPS queries,
/// overrides any value in config file
#[clap(long = "https-port", value_name = "HTTPS-PORT")]
pub(crate) https_port: Option<u16>,
/// Listening port for DNS over QUIC queries,
/// overrides any value in config file
#[clap(long = "quic-port", value_name = "QUIC-PORT")]
pub(crate) quic_port: Option<u16>,
}
/// Main method for running the named server.
///
/// `Note`: Tries to avoid panics, in favor of always starting.
#[allow(unused_mut)]
fn main() {
let args = Cli::parse();
// TODO: this should be set after loading config, but it's necessary for initial log lines, no?
if args.quiet {
quiet();
} else if args.debug {
debug();
} else {
default();
}
info!("Trust-DNS {} starting", trust_dns_client::version());
// start up the server for listening
let config = args.config.clone();
let config_path = Path::new(&config);
info!("loading configuration from: {:?}", config_path);
let config = Config::read_config(config_path)
.unwrap_or_else(|e| panic!("could not read config {}: {:?}", config_path.display(), e));
let directory_config = config.get_directory().to_path_buf();
let zonedir = args.zonedir.clone();
let zone_dir: PathBuf = zonedir
.as_ref()
.map(PathBuf::from)
.unwrap_or_else(|| directory_config.clone());
// TODO: allow for num threads configured...
let mut runtime = runtime::Builder::new_multi_thread()
.enable_all()
.worker_threads(4)
.thread_name("trust-dns-server-runtime")
.build()
.expect("failed to initialize Tokio Runtime");
let mut catalog: Catalog = Catalog::new();
// configure our server based on the config_path
for zone in config.get_zones() {
let zone_name = zone
.get_zone()
.unwrap_or_else(|_| panic!("bad zone name in {:?}", config_path));
match runtime.block_on(load_zone(&zone_dir, zone)) {
Ok(authority) => catalog.upsert(zone_name.into(), authority),
Err(error) => panic!("could not load zone {}: {}", zone_name, error),
}
}
// TODO: support all the IPs asked to listen on...
// TODO:, there should be the option to listen on any port, IP and protocol option...
let v4addr = config
.get_listen_addrs_ipv4()
.expect("Error with parsing provided by configuration Ipv4");
let v6addr = config
.get_listen_addrs_ipv6()
.expect("Error with parsing provided by configuration Ipv6");
let mut listen_addrs: Vec<IpAddr> = v4addr
.into_iter()
.map(IpAddr::V4)
.chain(v6addr.into_iter().map(IpAddr::V6))
.collect();
let listen_port: u16 = args.port.unwrap_or_else(|| config.get_listen_port());
let tcp_request_timeout = config.get_tcp_request_timeout();
if listen_addrs.is_empty() {
listen_addrs.push(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)));
}
let sockaddrs: Vec<SocketAddr> = listen_addrs
.iter()
.flat_map(|x| (*x, listen_port).to_socket_addrs().unwrap())
.collect();
// now, run the server, based on the config
#[cfg_attr(not(feature = "dns-over-tls"), allow(unused_mut))]
let mut server = ServerFuture::new(catalog);
// load all the listeners
for udp_socket in &sockaddrs {
info!("binding UDP to {:?}", udp_socket);
let udp_socket = runtime
.block_on(UdpSocket::bind(udp_socket))
.unwrap_or_else(|_| panic!("could not bind to udp: {}", udp_socket));
info!(
"listening for UDP on {:?}",
udp_socket
.local_addr()
.expect("could not lookup local address")
);
let _guard = runtime.enter();
server.register_socket(udp_socket);
}
// and TCP as necessary
for tcp_listener in &sockaddrs {
info!("binding TCP to {:?}", tcp_listener);
let tcp_listener = runtime
.block_on(TcpListener::bind(tcp_listener))
.unwrap_or_else(|_| panic!("could not bind to tcp: {}", tcp_listener));
info!(
"listening for TCP on {:?}",
tcp_listener
.local_addr()
.expect("could not lookup local address")
);
let _guard = runtime.enter();
server.register_listener(tcp_listener, tcp_request_timeout);
}
let tls_cert_config = config.get_tls_cert();
// and TLS as necessary
// TODO: we should add some more control from configs to enable/disable TLS/HTTPS/QUIC
if let Some(_tls_cert_config) = tls_cert_config {
// setup TLS listeners
#[cfg(feature = "dns-over-tls")]
config_tls(
&args,
&mut server,
&config,
_tls_cert_config,
&zone_dir,
&listen_addrs,
&mut runtime,
);
// setup HTTPS listeners
#[cfg(feature = "dns-over-https")]
config_https(
&args,
&mut server,
&config,
_tls_cert_config,
&zone_dir,
&listen_addrs,
&mut runtime,
);
// setup QUIC listeners
#[cfg(feature = "dns-over-quic")]
config_quic(
&args,
&mut server,
&config,
_tls_cert_config,
&zone_dir,
&listen_addrs,
&mut runtime,
);
}
// config complete, starting!
banner();
info!("awaiting connections...");
// TODO: how to do threads? should we do a bunch of listener threads and then query threads?
// Ideally the processing would be n-threads for receiving, which hand off to m-threads for
// request handling. It would generally be the case that n <= m.
info!("Server starting up");
match runtime.block_on(server.block_until_done()) {
Ok(()) => {
// we're exiting for some reason...
info!("Trust-DNS {} stopping", trust_dns_client::version());
}
Err(e) => {
let error_msg = format!(
"Trust-DNS {} has encountered an error: {}",
trust_dns_client::version(),
e
);
error!("{}", error_msg);
panic!("{}", error_msg);
}
};
}
#[cfg(feature = "dns-over-tls")]
fn config_tls(
args: &Cli,
server: &mut ServerFuture<Catalog>,
config: &Config,
tls_cert_config: &TlsCertConfig,
zone_dir: &Path,
listen_addrs: &[IpAddr],
runtime: &mut runtime::Runtime,
) {
use futures::TryFutureExt;
let tls_listen_port: u16 = args
.tls_port
.unwrap_or_else(|| config.get_tls_listen_port());
let tls_sockaddrs: Vec<SocketAddr> = listen_addrs
.iter()
.flat_map(|x| (*x, tls_listen_port).to_socket_addrs().unwrap())
.collect();
if tls_sockaddrs.is_empty() {
warn!("a tls certificate was specified, but no TLS addresses configured to listen on");
}
for tls_listener in &tls_sockaddrs {
info!(
"loading cert for DNS over TLS: {:?}",
tls_cert_config.get_path()
);
let tls_cert = dnssec::load_cert(zone_dir, tls_cert_config)
.expect("error loading tls certificate file");
info!("binding TLS to {:?}", tls_listener);
let tls_listener = runtime.block_on(
TcpListener::bind(tls_listener)
.unwrap_or_else(|_| panic!("could not bind to tls: {}", tls_listener)),
);
info!(
"listening for TLS on {:?}",
tls_listener
.local_addr()
.expect("could not lookup local address")
);
let _guard = runtime.enter();
server
.register_tls_listener(tls_listener, config.get_tcp_request_timeout(), tls_cert)
.expect("could not register TLS listener");
}
}
#[cfg(feature = "dns-over-https")]
fn config_https(
args: &Cli,
server: &mut ServerFuture<Catalog>,
config: &Config,
tls_cert_config: &TlsCertConfig,
zone_dir: &Path,
listen_addrs: &[IpAddr],
runtime: &mut runtime::Runtime,
) {
use futures::TryFutureExt;
let https_listen_port: u16 = args
.https_port
.unwrap_or_else(|| config.get_https_listen_port());
let https_sockaddrs: Vec<SocketAddr> = listen_addrs
.iter()
.flat_map(|x| (*x, https_listen_port).to_socket_addrs().unwrap())
.collect();
if https_sockaddrs.is_empty() {
warn!("a tls certificate was specified, but no HTTPS addresses configured to listen on");
}
for https_listener in &https_sockaddrs {
info!(
"loading cert for DNS over TLS named {} from {:?}",
tls_cert_config.get_endpoint_name(),
tls_cert_config.get_path()
);
// TODO: see about modifying native_tls to impl Clone for Pkcs12
let tls_cert = dnssec::load_cert(zone_dir, tls_cert_config)
.expect("error loading tls certificate file");
info!("binding HTTPS to {:?}", https_listener);
let https_listener = runtime.block_on(
TcpListener::bind(https_listener)
.unwrap_or_else(|_| panic!("could not bind to tls: {}", https_listener)),
);
info!(
"listening for HTTPS on {:?}",
https_listener
.local_addr()
.expect("could not lookup local address")
);
let _guard = runtime.enter();
server
.register_https_listener(
https_listener,
config.get_tcp_request_timeout(),
tls_cert,
tls_cert_config.get_endpoint_name().to_string(),
)
.expect("could not register HTTPS listener");
}
}
#[cfg(feature = "dns-over-quic")]
fn config_quic(
args: &Cli,
server: &mut ServerFuture<Catalog>,
config: &Config,
tls_cert_config: &TlsCertConfig,
zone_dir: &Path,
listen_addrs: &[IpAddr],
runtime: &mut runtime::Runtime,
) {
use futures::TryFutureExt;
let quic_listen_port: u16 = args
.quic_port
.unwrap_or_else(|| config.get_quic_listen_port());
let quic_sockaddrs: Vec<SocketAddr> = listen_addrs
.iter()
.flat_map(|x| (*x, quic_listen_port).to_socket_addrs().unwrap())
.collect();
if quic_sockaddrs.is_empty() {
warn!("a tls certificate was specified, but no QUIC addresses configured to listen on");
}
for quic_listener in &quic_sockaddrs {
info!(
"loading cert for DNS over TLS named {} from {:?}",
tls_cert_config.get_endpoint_name(),
tls_cert_config.get_path()
);
// TODO: see about modifying native_tls to impl Clone for Pkcs12
let tls_cert = dnssec::load_cert(zone_dir, tls_cert_config)
.expect("error loading tls certificate file");
info!("binding QUIC to {:?}", quic_listener);
let quic_listener = runtime.block_on(
UdpSocket::bind(quic_listener)
.unwrap_or_else(|_| panic!("could not bind to tls: {}", quic_listener)),
);
info!(
"listening for QUIC on {:?}",
quic_listener
.local_addr()
.expect("could not lookup local address")
);
let _guard = runtime.enter();
server
.register_quic_listener(
quic_listener,
config.get_tcp_request_timeout(),
tls_cert,
tls_cert_config.get_endpoint_name().to_string(),
)
.expect("could not register QUIC listener");
}
}
fn banner() {
info!("");
info!(" o o o ");
info!(" | | | ");
info!(" --O-- o-o o o o-o --O-- o-o o-O o-o o-o ");
info!(" | | | | \\ | | | | | \\ ");
info!(" o o o--o o-o o o-o o o o-o ");
info!("");
}
struct TdnsFormatter;
impl<S, N> FormatEvent<S, N> for TdnsFormatter
where
S: Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
{
fn format_event(
&self,
ctx: &FmtContext<'_, S, N>,
mut writer: format::Writer<'_>,
event: &Event<'_>,
) -> fmt::Result {
let now = OffsetDateTime::now_utc();
let now_secs = now.unix_timestamp();
// Format values from the event's's metadata:
let metadata = event.metadata();
write!(
&mut writer,
"{}:{}:{}",
now_secs,
metadata.level(),
metadata.target()
)?;
if let Some(line) = metadata.line() {
write!(&mut writer, ":{line}")?;
}
// Format all the spans in the event's span context.
if let Some(scope) = ctx.event_scope() {
for span in scope.from_root() {
write!(writer, ":{}", span.name())?;
let ext = span.extensions();
let fields = &ext
.get::<FormattedFields<N>>()
.expect("will never be `None`");
// Skip formatting the fields if the span had no fields.
if !fields.is_empty() {
write!(writer, "{{{fields}}}")?;
}
}
}
// Write fields on the event
write!(writer, ":")?;
ctx.field_format().format_fields(writer.by_ref(), event)?;
writeln!(writer)
}
}
fn get_env() -> String {
env::var("RUST_LOG").unwrap_or_default()
}
fn all_trust_dns(level: impl ToString) -> String {
format!(
"named={level},trust_dns={level},{env}",
level = level.to_string().to_lowercase(),
env = get_env()
)
}
/// appends trust-dns-server debug to RUST_LOG
pub fn debug() {
logger(tracing::Level::DEBUG);
}
/// appends trust-dns-server info to RUST_LOG
pub fn default() {
logger(tracing::Level::INFO);
}
/// appends trust-dns-server error to RUST_LOG
pub fn quiet() {
logger(tracing::Level::ERROR);
}
// TODO: add dep on util crate, share logging config...
fn logger(level: tracing::Level) {
// Setup tracing for logging based on input
let filter = tracing_subscriber::EnvFilter::builder()
.with_default_directive(tracing::Level::WARN.into())
.parse(all_trust_dns(level))
.expect("failed to configure tracing/logging");
let formatter = tracing_subscriber::fmt::layer().event_format(TdnsFormatter);
tracing_subscriber::registry()
.with(formatter)
.with(filter)
.init();
}