CLI.pm

filter: Statementstmt 97.0% 65 / 67 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 23 / 23 Podpod n/a totaltotal 97.7% 88 / 90 CC 1 SCAR 0.1
CC
1
Cov
97%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« CLI/TestCaseSet.pm ↑ Summary
1 # Brief help module to define the exception we use for early exits.
2 package Zonemaster::Engine::Exception::NormalExit;
3 1 ▶use v5.26;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use parent 'Zonemaster::Engine::Exception';
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 # The actual interesting module.
8 package Zonemaster::CLI;
9  
10 1 ▶use v5.26;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 1 ▶use version; our $VERSION = version->declare( "v8.0.3" );
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 1 ▶use Locale::TextDomain 'Zonemaster-CLI';
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 1 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 1 ▶use File::Slurp;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶use Getopt::Long qw[GetOptionsFromArray :config gnu_compat bundling no_auto_abbrev];
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 ▶use JSON::XS;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 1 ▶use List::Util qw[max uniq];
Subroutine BEGIN: called CC=1 SCAR=0.0
23 1 ▶use Net::IP::XS;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 1 ▶use Pod::Usage;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 1 ▶use POSIX qw[setlocale LC_MESSAGES LC_CTYPE];
Subroutine BEGIN: called CC=1 SCAR=0.0
26 1 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 1 ▶use Scalar::Util qw[blessed];
Subroutine BEGIN: called CC=1 SCAR=0.0
28 1 ▶use Time::HiRes;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 1 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
30 1 ▶use Zonemaster::CLI::TestCaseSet;
Subroutine BEGIN: called CC=1 SCAR=0.0
31 1 ▶use Zonemaster::Engine::Exception;
Subroutine BEGIN: called CC=1 SCAR=0.0
32 1 ▶use Zonemaster::Engine::Logger::Entry;
Subroutine BEGIN: called CC=1 SCAR=0.0
33 0 ▶use Zonemaster::Engine::Normalization qw[normalize_name];
Subroutine BEGIN: called CC=1 SCAR=2.6
34 use Zonemaster::Engine::Translator;
35 use Zonemaster::Engine::Util qw[parse_hints];
36 use Zonemaster::Engine::Validation qw[validate_ipv4 validate_ipv6];
37 use Zonemaster::Engine;
38 use Zonemaster::LDNS;
39  
40 our %numeric = Zonemaster::Engine::Logger::Entry->levels;
41 our $JSON = JSON::XS->new->allow_blessed->convert_blessed->canonical;
42 our $SCRIPT = $0;
43  
44 Readonly our $EXIT_SUCCESS => 0;
45 Readonly our $EXIT_GENERIC_ERROR => 1;
46 Readonly our $EXIT_USAGE_ERROR => 2;
47  
48 Readonly our $DS_RE => qr/^(?:[[:digit:]]+,){3}[[:xdigit:]]+$/;
49  
50 STDOUT->autoflush( 1 );
51  
52 sub my_pod2usage {
53 my ( %opts ) = @_;
54  
55 pod2usage(
56 -input => $SCRIPT,
57 -output => $opts{output},
58 -verbose => $opts{verbosity},
59 -exitcode => 'NOEXIT',
60 );
61  
62 return;
63 }
64  
65 # Returns an integer representing an OS exit status.
66 sub run {
67 my ( $class, @argv ) = @_;
68  
69 my $opt_count = 0;
70 my @opt_ds = ();
71 my $opt_dump_profile = 0;
72 my $opt_elapsed = 0;
73 my $opt_encoding = undef;
74 my $opt_help = 0;
75 my $opt_hints;
76 my $opt_ipv4 = undef;
77 my $opt_ipv6 = undef;
78 my $opt_json = undef;
79 my $opt_json_stream = 0;
80 my $opt_json_translate = undef;
81 my $opt_level = 'NOTICE';
82 my $opt_list_tests = 0;
83 my $opt_locale = undef;
84 my @opt_ns = ();
85 my $opt_nstimes = 0;
86 my $opt_profile;
87 my $opt_progress = undef;
88 my $opt_raw;
89 my $opt_restore;
90 my $opt_save;
91 my $opt_show_level = 1;
92 my $opt_show_module = 0;
93 my $opt_show_testcase = 0;
94 my $opt_sourceaddr4;
95 my $opt_sourceaddr6;
96 my $opt_stop_level = '';
97 my @opt_test = ();
98 my $opt_time = 1;
99 my $opt_version = 0;
100  
101 {
102 local $SIG{__WARN__} = sub { print STDERR $_[0] };
103  
104 GetOptionsFromArray(
105 \@argv,
106 'count!' => \$opt_count,
107 'ds=s' => \@opt_ds,
108 'dump-profile!' => \$opt_dump_profile,
109 'dump_profile!' => \$opt_dump_profile,
110 'elapsed!' => \$opt_elapsed,
111 'encoding=s' => \$opt_encoding,
112 'hints=s' => \$opt_hints,
113 'help|h|usage|?!' => \$opt_help,
114 'ipv4!' => \$opt_ipv4,
115 'ipv6!' => \$opt_ipv6,
116 'json!' => \$opt_json,
117 'json-stream!' => \$opt_json_stream,
118 'json_stream!' => \$opt_json_stream,
119 'json-translate!' => \$opt_json_translate,
120 'json_translate!' => \$opt_json_translate,
121 'level=s' => \$opt_level,
122 'list-tests!' => \$opt_list_tests,
123 'list_tests!' => \$opt_list_tests,
124 'locale=s' => \$opt_locale,
125 'ns=s' => \@opt_ns,
126 'nstimes!' => \$opt_nstimes,
127 'profile=s' => \$opt_profile,
128 'progress!' => \$opt_progress,
129 'raw!' => \$opt_raw,
130 'restore=s' => \$opt_restore,
131 'save=s' => \$opt_save,
132 'show-level!' => \$opt_show_level,
133 'show_level!' => \$opt_show_level,
134 'show-module!' => \$opt_show_module,
135 'show_module!' => \$opt_show_module,
136 'show-testcase!' => \$opt_show_testcase,
137 'show_testcase!' => \$opt_show_testcase,
138 'sourceaddr4=s' => \$opt_sourceaddr4,
139 'sourceaddr6=s' => \$opt_sourceaddr6,
140 'stop-level=s' => \$opt_stop_level,
141 'stop_level=s' => \$opt_stop_level,
142 'test=s' => \@opt_test,
143 'time!' => \$opt_time,
144 'version!' => \$opt_version,
145 )
146 or do {
147 my_pod2usage( verbosity => 0, output => \*STDERR );
148 return 2;
149 };
150 }
151  
152 if ( $opt_help ) {
153 my_pod2usage( verbosity => 1, output => \*STDOUT );
154 say "Severity levels from highest to lowest:";
155 say " CRITICAL, ERROR, WARNING, NOTICE, INFO, DEBUG, DEBUG2, DEBUG3";
156  
157 return 0;
158 }
159  
160 $opt_level = uc $opt_level;
161 $opt_stop_level = uc $opt_stop_level;
162  
163 my @accumulator;
164 my %counter;
165 my $printed_something;
166  
167 if ( $opt_locale ) {
168 undef $ENV{LANGUAGE};
169 $ENV{LC_ALL} = $opt_locale;
170 }
171  
172 # Set LC_MESSAGES and LC_CTYPE separately
173 # (https://www.gnu.org/software/gettext/manual/html_node/Triggering.html#Triggering)
174 if ( not defined setlocale( LC_MESSAGES, "" ) ) {
175 my $locale = ( $ENV{LANGUAGE} || $ENV{LC_ALL} || $ENV{LC_MESSAGES} );
176 say STDERR __x(
177 "Warning: setting locale category LC_MESSAGES to {locale} failed -- is it installed on this system?",
178 locale => $locale ) . "\n\n";
179 }
180  
181 if ( not defined setlocale( LC_CTYPE, "" ) ) {
182 my $locale = ( $ENV{LC_ALL} || $ENV{LC_CTYPE} );
183 say STDERR __x(
184 "Warning: setting locale category LC_CTYPE to {locale} failed -- is it installed on this system?",
185 locale => $locale ) . "\n\n";
186 }
187  
188 if ( $opt_version ) {
189 print_versions();
190 return $EXIT_SUCCESS;
191 }
192  
193 if ( $opt_list_tests ) {
194 print_test_list();
195 return $EXIT_SUCCESS;
196 }
197  
198 # errors and warnings
199 if ( defined $opt_encoding ) {
200 say STDERR __( "Warning: deprecated --encoding, simply remove it from your usage." );
201 }
202  
203 if ( $opt_json_stream and defined $opt_json and not $opt_json ) {
204 say STDERR __( "Error: --json-stream and --no-json cannot be used together." );
205 return $EXIT_USAGE_ERROR;
206 }
207  
208 if ( defined $opt_json_translate ) {
209 unless ( $opt_json or $opt_json_stream ) {
210 printf STDERR __( "Warning: --json-translate has no effect without either --json or --json-stream." )
211 . "\n";
212 }
213 if ( $opt_json_translate ) {
214 printf STDERR __( "Warning: deprecated --json-translate, use --no-raw instead." ) . "\n";
215 }
216 else {
217 printf STDERR __( "Warning: deprecated --no-json-translate, use --raw instead." ) . "\n";
218 }
219 }
220  
221 # align values
222 $opt_json = 1 if $opt_json_stream;
223 $opt_raw //= defined $opt_json_translate ? !$opt_json_translate : 0;
224  
225 # Filehandle for diagnostics output
226 my $fh_diag = ( $opt_json or $opt_raw or $opt_dump_profile )
227 ? *STDERR # Structured output mode (e.g. JSON)
228 : *STDOUT; # Human readable output mode
229  
230 my $show_progress = $opt_progress // !!-t STDOUT && !$opt_json && !$opt_raw;
231  
232 if ( $opt_profile ) {
233 say $fh_diag __x( "Loading profile from {path}.", path => $opt_profile );
234 my $json = read_file( $opt_profile );
235 my $foo = Zonemaster::Engine::Profile->from_json( $json );
236 my $profile = Zonemaster::Engine::Profile->default;
237 $profile->merge( $foo );
238 Zonemaster::Engine::Profile->effective->merge( $profile );
239 }
240  
241 if ( defined $opt_sourceaddr4 ) {
242 local $@;
243 eval {
244 Zonemaster::Engine::Profile->effective->set( q{resolver.source4}, $opt_sourceaddr4 );
245 1;
246 } or do {
247 say STDERR __x( "Error: invalid value for --sourceaddr4: {reason}", reason => $@ );
248 return $EXIT_USAGE_ERROR;
249 };
250 }
251  
252 if ( defined $opt_sourceaddr6 ) {
253 local $@;
254 eval {
255 Zonemaster::Engine::Profile->effective->set( q{resolver.source6}, $opt_sourceaddr6 );
256 1;
257 } or do {
258 say STDERR __x( "Error: invalid value for --sourceaddr6: {reason}", reason => $@ );
259 return $EXIT_USAGE_ERROR;
260 };
261 }
262  
263 {
264 my %all_methods = Zonemaster::Engine->all_methods;
265 my $cases = Zonemaster::CLI::TestCaseSet->new( #
266 Zonemaster::Engine::Profile->effective->get( q{test_cases} ),
267 \%all_methods,
268 );
269  
270 for my $test ( @opt_test ) {
271 my @modifiers = Zonemaster::CLI::TestCaseSet->parse_modifier_expr( $test );
272 while ( @modifiers ) {
273 my $op = shift @modifiers;
274 my $term = shift @modifiers;
275  
276 if ( !$cases->apply_modifier( $op, $term ) ) {
277 say STDERR __x( "Error: unrecognized term '{term}' in --test.", term => $term ) . "\n";
278 return $EXIT_USAGE_ERROR;
279 }
280 }
281 }
282  
283 Zonemaster::Engine::Profile->effective->set( q{test_cases}, [ $cases->to_list ] ),
284 }
285  
286 # These two must come after any profile from command line has been loaded
287 # to make any IPv4/IPv6 option override the profile setting.
288 if ( defined( $opt_ipv4 ) ) {
289 Zonemaster::Engine::Profile->effective->set( q{net.ipv4}, $opt_ipv4 );
290 }
291 if ( defined( $opt_ipv6 ) ) {
292 Zonemaster::Engine::Profile->effective->set( q{net.ipv6}, $opt_ipv6 );
293 }
294  
295 if ( $opt_dump_profile ) {
296 do_dump_profile();
297 return $EXIT_SUCCESS;
298 }
299  
300 if ( $opt_stop_level and not defined( $numeric{$opt_stop_level} ) ) {
301 say STDERR __x( "Failed to recognize stop level '{level}'.", level => $opt_stop_level );
302 return $EXIT_USAGE_ERROR;
303 }
304  
305 if ( not defined $numeric{$opt_level} ) {
306 say STDERR __( "--level must be one of CRITICAL, ERROR, WARNING, NOTICE, INFO, DEBUG, DEBUG2 or DEBUG3." );
307 return $EXIT_USAGE_ERROR;
308 }
309  
310 if ( $opt_restore ) {
311 Zonemaster::Engine->preload_cache( $opt_restore );
312 }
313  
314 my $level_width = 0;
315 foreach ( keys %numeric ) {
316 if ( $numeric{$opt_level} <= $numeric{$_} ) {
317 my $width_l10n = length( decode_utf8( translate_severity( $_ ) ) );
318 $level_width = $width_l10n if $width_l10n > $level_width;
319 }
320 }
321  
322 my $translator;
323 my %field_width = (
324 seconds => 7,
325 level => $level_width,
326 module => 12,
327 testcase => 14
328 );
329 my %header_names = ();
330 my %remaining_space = ();
331  
332 # Callback defined here so it closes over the setup above.
333 # But we can’t use it right now because the translator isn’t initialized.
334 my $message_printer = sub {
335 my ( $entry ) = @_;
336  
337 print_spinner() if $show_progress;
338  
339 my $entry_level = $entry->level;
340  
341 $counter{ uc $entry_level } += 1;
342  
343 if ( $numeric{ uc $entry_level } >= $numeric{$opt_level} ) {
344 $printed_something = 1;
345  
346 if ( $opt_json and $opt_json_stream ) {
347 my %r;
348  
349 $r{timestamp} = $entry->timestamp if $opt_time;
350 $r{module} = $entry->module if $opt_show_module;
351 $r{testcase} = $entry->testcase if $opt_show_testcase;
352 $r{tag} = $entry->tag;
353 $r{level} = $entry_level if $opt_show_level;
354 $r{args} = $entry->args if $entry->args;
355 $r{message} = $translator->translate_tag( $entry ) unless $opt_raw;
356  
357 say $JSON->encode( \%r );
358 }
359 elsif ( $opt_json and not $opt_json_stream ) {
360 # Don't do anything
361 }
362 else {
363 my $prefix = q{};
364 if ( $opt_time ) {
365 $prefix .= sprintf "%*.2f ", ${ field_width { seconds } }, $entry->timestamp;
366 }
367  
368 if ( $opt_show_level ) {
369 $prefix .= $opt_raw ? $entry->level : translate_severity( $entry->level );
370 my $space_l10n =
371 ${ field_width { level } } - length( decode_utf8( translate_severity( $entry_level ) ) ) + 1;
372 $prefix .= ' ' x $space_l10n;
373 }
374  
375 if ( $opt_show_module ) {
376 $prefix .= sprintf "%-*s ", ${ field_width { module } }, $entry->module;
377 }
378  
379 if ( $opt_show_testcase ) {
380 $prefix .= sprintf "%-*s ", ${ field_width { testcase } }, $entry->testcase;
381 }
382  
383 if ( $opt_raw ) {
384 $prefix .= $entry->tag;
385  
386 my $message = $entry->argstr;
387 my @lines = split /\n/, $message;
388  
389 printf "%s%s %s\n", $prefix, ' ', @lines ? shift @lines : '';
390 for my $line ( @lines ) {
391 printf "%s%s %s\n", $prefix, '>', $line;
392 }
393 }
394 else {
395 if ( $entry_level eq q{DEBUG3}
396 and scalar( keys %{ $entry->args } ) == 1
397 and defined $entry->args->{packet} )
398 {
399 my $packet = $entry->args->{packet};
400 my $padding = q{ } x length $prefix;
401 $entry->args->{packet} = q{};
402 printf "%s%s\n", $prefix, $translator->translate_tag( $entry );
403 foreach my $line ( split /\n/, $packet ) {
404 printf "%s%s\n", $padding, $line;
405 }
406 }
407 else {
408 printf "%s%s\n", $prefix, $translator->translate_tag( $entry );
409 }
410 }
411 } ## end else [ if ( $opt_json and $opt_json_stream)]
412 } ## end if ( $numeric{ uc $entry_level...})
413 if ( $opt_stop_level and $numeric{ uc $entry->level } >= $numeric{$opt_stop_level} ) {
414 die(
415 Zonemaster::Engine::Exception::NormalExit->new(
416 { message => "Saw message at level " . $entry->level }
417 )
418 );
419 }
420 };
421  
422 # Instead, hold early messages in a temporary queue and switch to the
423 # actual callback when we are ready.
424 my @held_messages;
425 Zonemaster::Engine->logger->callback(
426 sub {
427 my ( $entry ) = @_;
428 push @held_messages, @_;
429 }
430 );
431  
432 if ( @argv > 1 ) {
433 say STDERR __(
434 "Only one domain can be given for testing. Did you forget to prepend an option with '--<OPTION>'?" );
435 return $EXIT_USAGE_ERROR;
436 }
437 elsif ( @argv < 1 ) {
438 say STDERR __( "Must give the name of a domain to test." );
439 return $EXIT_USAGE_ERROR;
440 }
441  
442 my ( $domain ) = @argv;
443  
444 ( my $errors, $domain ) = normalize_name( decode( 'utf8', $domain ) );
445  
446 if ( @opt_ns ) {
447 local $@;
448 eval {
449 check_fake_delegation( $domain, @opt_ns );
450 1;
451 } or do {
452 print STDERR $@;
453 return $EXIT_USAGE_ERROR;
454 };
455 }
456  
457 if ( @opt_ds ) {
458 check_fake_ds( @opt_ds );
459 }
460  
461 if ( scalar @$errors > 0 ) {
462 my $error_message;
463 foreach my $err ( @$errors ) {
464 $error_message .= $err->string . "\n";
465 }
466 print STDERR $error_message;
467 return $EXIT_USAGE_ERROR;
468 }
469  
470 if ( defined $opt_hints ) {
471 my $hints_data;
472 my $error = undef;
473 try {
474 my $hints_text = read_file( $opt_hints ) // die "read_file failed\n";
475 local $SIG{__WARN__} = \&die;
476 $hints_data = parse_hints( $hints_text )
477 }
478 catch {
479 $error = $_;
480 };
481  
482 if ( defined $error ) {
483 print STDERR __x( "Error loading hints file: {message}", message => $error );
484 return $EXIT_USAGE_ERROR;
485 }
486  
487 Zonemaster::Engine::Recursor->remove_fake_addresses( '.' );
488 Zonemaster::Engine::Recursor->add_fake_addresses( '.', $hints_data );
489 } ## end if ( defined $opt_hints)
490  
491 # This can generate early log messages.
492 if ( @opt_ns ) {
493 local $@;
494 if ( $domain eq '.' ) {
495 Zonemaster::Engine::Recursor->remove_fake_addresses( '.' );
496 }
497  
498 eval {
499 add_fake_delegation( $domain, @opt_ns );
500 1;
501 } or do {
502 print STDERR $@;
503 return $EXIT_USAGE_ERROR;
504 };
505 }
506  
507 if ( @opt_ds ) {
508 add_fake_ds( $domain, @opt_ds );
509 }
510  
511 if ( not $opt_raw ) {
512 $translator = Zonemaster::Engine::Translator->new;
513 $translator->locale( $opt_locale )
514 if $opt_locale;
515  
516 %header_names = (
517 seconds => __( 'Seconds' ),
518 level => __( 'Level' ),
519 module => __( 'Module' ),
520 testcase => __( 'Testcase' ),
521 message => __( 'Message' )
522 );
523 foreach ( keys %header_names ) {
524 $field_width{$_} = _max( $field_width{$_}, length( decode_utf8( $header_names{$_} ) ) );
525 $remaining_space{$_} = $field_width{$_} - length( decode_utf8( $header_names{$_} ) );
526 }
527 }
528  
529 if ( $opt_profile or @opt_test ) {
530 # Separate initialization from main output in human readable output mode
531 print "\n" if $fh_diag eq *STDOUT;
532 }
533  
534 if ( not $opt_raw and not $opt_json ) {
535 my $header = q{};
536  
537 if ( $opt_time ) {
538 $header .= sprintf "%s%s ", $header_names{seconds}, " " x $remaining_space{seconds};
539 }
540 if ( $opt_show_level ) {
541 $header .= sprintf "%s%s ", $header_names{level}, " " x $remaining_space{level};
542 }
543 if ( $opt_show_module ) {
544 $header .= sprintf "%s%s ", $header_names{module}, " " x $remaining_space{module};
545 }
546 if ( $opt_show_testcase ) {
547 $header .= sprintf "%s%s ", $header_names{testcase}, " " x $remaining_space{testcase};
548 }
549 $header .= sprintf "%s\n", $header_names{message};
550  
551 if ( $opt_time ) {
552 $header .= sprintf "%s ", "=" x $field_width{seconds};
553 }
554 if ( $opt_show_level ) {
555 $header .= sprintf "%s ", "=" x $field_width{level};
556 }
557 if ( $opt_show_module ) {
558 $header .= sprintf "%s ", "=" x $field_width{module};
559 }
560 if ( $opt_show_testcase ) {
561 $header .= sprintf "%s ", "=" x $field_width{testcase};
562 }
563 $header .= sprintf "%s\n", "=" x $field_width{message};
564  
565 print $header;
566 } ## end if ( not $opt_raw and ...)
567  
568 # Now we are ready to actually print messages, including those that are
569 # currently in the hold queue.
570 while ( my $entry = pop @held_messages ) {
571 $message_printer->( $entry );
572 }
573 Zonemaster::Engine->logger->callback( $message_printer );
574  
575 # Actually run tests!
576 eval { Zonemaster::Engine->test_zone( $domain ); };
577  
578 if ( $@ ) {
579 my $err = $@;
580 if ( blessed $err and $err->isa( "Zonemaster::Engine::Exception::NormalExit" ) ) {
581 say STDERR "Exited early: " . $err->message;
582 }
583 else {
584 die $err; # Don't know what it is, rethrow
585 }
586 }
587  
588 if ( not $opt_raw and not $opt_json ) {
589 if ( not $printed_something ) {
590 say __( "Looks OK." );
591 }
592 }
593  
594 my $json_output = {};
595  
596 if ( $opt_count ) {
597 my %entries;
598 foreach my $e ( @{ Zonemaster::Engine->logger->entries } ) {
599 $entries{$e->level}{$e->tag} += 1;
600 }
601  
602 if ( $opt_json ) {
603 $json_output->{count} = {};
604 foreach my $level ( sort { $numeric{$b} <=> $numeric{$a} } keys %counter ) {
605 $json_output->{count}{by_level}{$level} = $counter{$level};
606 }
607  
608 foreach my $level ( sort { $numeric{$b} <=> $numeric{$a} } keys %entries ) {
609 foreach my $tag ( sort keys %{ $entries{$level} } ) {
610 $json_output->{count}{by_message_tag}{$level}{$tag} = $entries{$level}{$tag};
611 }
612 }
613 }
614 else {
615 my $header1 = __( 'Level' );
616 my $max1 = length $header1;
617 my $header2 = __( 'Number of log entries' );
618 my $max2 = length $header2;
619  
620 foreach my $level ( sort { $numeric{$b} <=> $numeric{$a} } keys %counter ) {
621 my $len = length translate_severity( $level );
622 $max1 = $len if $len > $max1;
623 }
624  
625 printf "\n\n%${max1}s\t%${max2}s", $header1, $header2;
626 printf "\n%s\t%s\n", '=' x $max1, '=' x $max2;
627  
628 foreach my $level ( sort { $numeric{$b} <=> $numeric{$a} } keys %counter ) {
629 printf "%${max1}s\t%${max2}d\n", translate_severity( $level ), $counter{$level};
630 }
631  
632 my $header3 = __( 'Message tag' );
633 my $max3 = max map { length "$_" } ( ( map { keys %{ $_ } } ( values %entries ) ), $header3 );
634 my $header4 = __( 'Count' );
635 my $max4 = max map { length "$_" } ( ( map { values %{ $_ } } ( values %entries ) ), $header4 );
636  
637 printf "\n%${max1}s\t%${max3}s\t%${max4}s", $header1, $header3, $header4;
638 printf "\n%${max1}s\t%${max3}s\t%${max4}s\n", '=' x $max1, '=' x $max3, '=' x $max4;
639 foreach my $level ( sort { $numeric{$b} <=> $numeric{$a} } keys %entries ) {
640 foreach my $tag ( sort keys %{ $entries{$level} } ) {
641 printf "%${max1}s\t%${max3}s\t%${max4}s\n", $level, $tag, $entries{$level}{$tag};
642 }
643 }
644 }
645 }
646  
647 if ( $opt_nstimes ) {
648 my $zone = Zonemaster::Engine->zone( $domain );
649 my %all_nss = %{ Zonemaster::Engine::Nameserver::object_cache };
650 my @child_nss = @{ $zone->ns };
651 my @parent_nss = @{ $zone->parent->ns };
652 my @all_responded_nss;
653  
654 foreach my $ns_name ( keys %all_nss ) {
655 foreach my $ns ( values %{ $all_nss{$ns_name} } ) {
656 push @all_responded_nss, $ns if scalar @{ $ns->times } > 0;
657 }
658 }
659  
660 my %nss_filter = map { $_ => undef } ( @child_nss, @parent_nss );
661 my @other_nss = grep { ! exists $nss_filter{$_} } @all_responded_nss;
662  
663 if ( $opt_json ) {
664 my @times;
665  
666 my sub json_nstimes {
667 my ( $ns ) = @_;
668 return {
669 'ns' => $ns->string,
670 'max' => 1000 * $ns->max_time,
671 'min' => 1000 * $ns->min_time,
672 'avg' => 1000 * $ns->average_time,
673 'stddev' => 1000 * $ns->stddev_time,
674 'median' => 1000 * $ns->median_time,
675 'total' => 1000 * $ns->sum_time,
676 'count' => scalar @{ $ns->times }
677 };
678 }
679  
680 my %section_mapping = (
681 'child' => \@child_nss,
682 'parent' => \@parent_nss,
683 'other' => \@other_nss
684 );
685  
686 foreach my $section_name ( sort keys %section_mapping ) {
687 my @entries = map { json_nstimes( $_ ) } sort @{ $section_mapping{$section_name} };
688 push @times, { $section_name => \@entries };
689 }
690  
691 $json_output->{nstimes} = \@times;
692 }
693 else {
694 my $header = __( 'Name servers' );
695 my $max = max map { length( "$_" ) } ( ( @child_nss, @parent_nss, @all_responded_nss ), $header );
696 printf "\n%${max}s %s\n", $header, ' Max Min Avg Stddev Median Total Count';
697 printf "%${max}s %s\n", '=' x $max, ' ========== ========== ========== ========== ========== =========== ===========';
698  
699 my $total_queries_count = 0;
700 my $total_queries_times = 0;
701 my %nss_already_processed;
702  
703 my sub print_nstimes {
704 my ( $ns, $max, $total_queries_count, $total_queries_times, $nss_already_processed_ref ) = @_;
705 my %nss_already_processed = %{ $nss_already_processed_ref };
706  
707 printf "%${max}s ", $ns->string;
708 printf "%11.2f ", 1000 * $ns->max_time;
709 printf "%10.2f ", 1000 * $ns->min_time;
710 printf "%10.2f ", 1000 * $ns->average_time;
711 printf "%10.2f ", 1000 * $ns->stddev_time;
712 printf "%10.2f ", 1000 * $ns->median_time;
713 printf "%11.2f ", 1000 * $ns->sum_time;
714 printf "%11d\n", scalar @{ $ns->times };
715 $total_queries_count += scalar @{ $ns->times } unless $nss_already_processed{$ns};
716 $total_queries_times += ( 1000 * $ns->sum_time ) unless $nss_already_processed{$ns};
717  
718 return $total_queries_count, $total_queries_times;
719 }
720  
721 my %section_mapping = (
722 1 => { __( 'Child zone' ) => \@child_nss },
723 2 => { __( 'Parent zone' ) => \@parent_nss },
724 3 => { __( 'Other' ) => \@other_nss }
725 );
726  
727 foreach my $section_order ( sort keys %section_mapping ) {
728 foreach my $section_header ( keys % { $section_mapping{$section_order} } ) {
729 printf "%s %s\n", $section_header, '-' x ( ( $max - length $section_header ) - 1 );
730  
731 foreach my $section_nss ( sort @{ $section_mapping{$section_order}{$section_header} } ) {
732 ( $total_queries_count, $total_queries_times ) =
733 print_nstimes( $section_nss, $max, $total_queries_count, $total_queries_times, \%nss_already_processed );
734 $nss_already_processed{$section_nss} = 1;
735 }
736 }
737 }
738  
739 printf "%${max}s %s\n", '=' x $max, ' ========== ========== ========== ========== ========== =========== ===========';
740 printf "%${max}s %67.2f %11s\n", __( 'Grand total' ), $total_queries_times, $total_queries_count;
741 }
742 } ## end if ( $opt_nstimes )
743  
744 if ( $opt_elapsed ) {
745 my $last = Zonemaster::Engine->logger->entries->[-1];
746  
747 if ( $opt_json ) {
748 $json_output->{elapsed} = $last->timestamp;
749 }
750 else {
751 printf "\nTotal test run time: %0.1f seconds.\n", $last->timestamp;
752 }
753 }
754  
755 if ( $opt_json and not $opt_json_stream ) {
756 my $res = Zonemaster::Engine->logger->json( $opt_level );
757 $res = $JSON->decode( $res );
758 foreach ( @$res ) {
759 unless ( $opt_raw ) {
760 my %e = %$_;
761 my $entry = Zonemaster::Engine::Logger::Entry->new( \%e );
762 $_->{message} = $translator->translate_tag( $entry );
763 }
764 delete $_->{timestamp} unless $opt_time;
765 delete $_->{level} unless $opt_show_level;
766 delete $_->{module} unless $opt_show_module;
767 delete $_->{testcase} unless $opt_show_testcase;
768 }
769 $json_output->{results} = $res;
770 }
771  
772 if ( scalar keys %$json_output ) {
773 say $JSON->encode( $json_output );
774 }
775  
776 if ( $opt_save ) {
777 Zonemaster::Engine->save_cache( $opt_save );
778 }
779  
780 return $EXIT_SUCCESS;
781 } ## end sub run
782  
783 sub check_fake_delegation {
784 my ( $domain, @ns ) = @_;
785  
786 foreach my $pair ( @ns ) {
787 my ( $name, $ip ) = split( '/', $pair, 2 );
788  
789 if ( $pair =~ tr/\/// > 1 or not $name ) {
790 die __( "--ns must be a name or a name/ip pair." ) . "\n";
791 }
792  
793 ( my $errors, $name ) = normalize_name( decode( 'utf8', $name ) );
794  
795 if ( scalar @$errors > 0 ) {
796 my $error_message = "Invalid name in --ns argument:\n";
797 foreach my $err ( @$errors ) {
798 $error_message .= "\t" . $err->string . "\n";
799 }
800 die $error_message;
801 }
802  
803 if ( $ip ) {
804 my $net_ip = Net::IP::XS->new( $ip );
805 unless ( validate_ipv4( $ip ) or validate_ipv6( $ip ) ) {
806 die Net::IP::XS::Error()
807 ? "Invalid IP address in --ns argument:\n\t" . Net::IP::XS::Error() . "\n"
808 : "Invalid IP address in --ns argument.\n";
809 }
810 }
811 } ## end foreach my $pair ( @ns )
812  
813 return;
814 } ## end sub check_fake_delegation
815  
816 sub check_fake_ds {
817 my ( @ds ) = @_;
818  
819 foreach my $str ( @ds ) {
820 unless ( $str =~ /$DS_RE/ ) {
821 say STDERR __(
822 "--ds ds data must be in the form \"keytag,algorithm,type,digest\". E.g. space is not permitted anywhere in the string."
823 );
824 exit( 1 );
825 }
826 }
827  
828 return;
829 }
830  
831 sub add_fake_delegation {
832 my ( $domain, @ns ) = @_;
833 my @ns_with_no_ip;
834 my %data;
835  
836 foreach my $pair ( @ns ) {
837 my ( $name, $ip ) = split( '/', $pair, 2 );
838  
839 ( my $errors, $name ) = normalize_name( decode( 'utf8', $name ) );
840  
841 if ( $ip ) {
842 push @{ $data{$name} }, $ip;
843 }
844 else {
845 push @ns_with_no_ip, $name;
846 }
847 }
848  
849 foreach my $ns ( @ns_with_no_ip ) {
850 if ( not exists $data{$ns} ) {
851 $data{$ns} = undef;
852 }
853 }
854  
855 return Zonemaster::Engine->add_fake_delegation( $domain => \%data );
856  
857 } ## end sub add_fake_delegation
858  
859 sub add_fake_ds {
860 my ( $domain, @ds ) = @_;
861 my @data;
862  
863 foreach my $str ( @ds ) {
864 my ( $tag, $algo, $type, $digest ) = split( /,/, $str );
865 push @data, { keytag => $tag, algorithm => $algo, type => $type, digest => $digest };
866 }
867  
868 Zonemaster::Engine->add_fake_ds( $domain => \@data );
869  
870 return;
871 }
872  
873 sub print_versions {
874 say 'Zonemaster-CLI version ' . __PACKAGE__->VERSION;
875 say 'Zonemaster-Engine version ' . $Zonemaster::Engine::VERSION;
876 say 'Zonemaster-LDNS version ' . $Zonemaster::LDNS::VERSION;
877 say 'NL NetLabs LDNS version ' . Zonemaster::LDNS::lib_version();
878  
879 return;
880 }
881  
882 my @spinner_strings = ( ' | ', ' / ', ' - ', ' \\ ' );
883  
884 sub print_spinner {
885 state $counter = 0;
886 state $last_spin = [ 0, 0 ];
887  
888 my $time = [ Time::HiRes::gettimeofday() ];
889 if ( Time::HiRes::tv_interval( $last_spin, $time ) > 0.1 ) {
890 $last_spin = $time;
891 printf "%s\r", $spinner_strings[ $counter++ % 4 ];
892 }
893 }
894  
895 sub print_test_list {
896 my %methods = Zonemaster::Engine->all_methods;
897 my $maxlen = max map {
898 map { length( $_ ) }
899 @$_
900 } values %methods;
901  
902 foreach my $module ( sort keys %methods ) {
903 say $module;
904 foreach my $method ( sort @{ $methods{$module} } ) {
905 printf " %${maxlen}s\n", $method;
906 }
907 print "\n";
908 }
909  
910 return;
911 }
912  
913 sub do_dump_profile {
914 my $json = JSON::XS->new->canonical->pretty;
915  
916 print $json->encode( Zonemaster::Engine::Profile->effective->{q{profile}} );
917  
918 return;
919 }
920  
921 sub translate_severity {
922 my $severity = shift;
923 if ( $severity eq "DEBUG" ) {
924 return __( "DEBUG" );
925 }
926 elsif ( $severity eq "INFO" ) {
927 return __( "INFO" );
928 }
929 elsif ( $severity eq "NOTICE" ) {
930 return __( "NOTICE" );
931 }
932 elsif ( $severity eq "WARNING" ) {
933 return __( "WARNING" );
934 }
935 elsif ( $severity eq "ERROR" ) {
936 return __( "ERROR" );
937 }
938 elsif ( $severity eq "CRITICAL" ) {
939 return __( "CRITICAL" );
940 }
941 else {
942 return $severity;
943 }
944 } ## end sub translate_severity
945  
946 sub _max {
947 my ( $a, $b ) = @_;
948 $a //= 0;
949 $b //= 0;
950 return ( $a > $b ? $a : $b );
951 }
952  
953 1;
954  
955 __END__
« CLI/TestCaseSet.pm ↑ Summary