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.1" );
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 1 ▶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 eval {
495 add_fake_delegation( $domain, @opt_ns );
496 1;
497 } or do {
498 print STDERR $@;
499 return $EXIT_USAGE_ERROR;
500 };
501 }
502  
503 if ( @opt_ds ) {
504 add_fake_ds( $domain, @opt_ds );
505 }
506  
507 if ( not $opt_raw ) {
508 $translator = Zonemaster::Engine::Translator->new;
509 $translator->locale( $opt_locale )
510 if $opt_locale;
511  
512 %header_names = (
513 seconds => __( 'Seconds' ),
514 level => __( 'Level' ),
515 module => __( 'Module' ),
516 testcase => __( 'Testcase' ),
517 message => __( 'Message' )
518 );
519 foreach ( keys %header_names ) {
520 $field_width{$_} = _max( $field_width{$_}, length( decode_utf8( $header_names{$_} ) ) );
521 $remaining_space{$_} = $field_width{$_} - length( decode_utf8( $header_names{$_} ) );
522 }
523 }
524  
525 if ( $opt_profile or @opt_test ) {
526 # Separate initialization from main output in human readable output mode
527 print "\n" if $fh_diag eq *STDOUT;
528 }
529  
530 if ( not $opt_raw and not $opt_json ) {
531 my $header = q{};
532  
533 if ( $opt_time ) {
534 $header .= sprintf "%s%s ", $header_names{seconds}, " " x $remaining_space{seconds};
535 }
536 if ( $opt_show_level ) {
537 $header .= sprintf "%s%s ", $header_names{level}, " " x $remaining_space{level};
538 }
539 if ( $opt_show_module ) {
540 $header .= sprintf "%s%s ", $header_names{module}, " " x $remaining_space{module};
541 }
542 if ( $opt_show_testcase ) {
543 $header .= sprintf "%s%s ", $header_names{testcase}, " " x $remaining_space{testcase};
544 }
545 $header .= sprintf "%s\n", $header_names{message};
546  
547 if ( $opt_time ) {
548 $header .= sprintf "%s ", "=" x $field_width{seconds};
549 }
550 if ( $opt_show_level ) {
551 $header .= sprintf "%s ", "=" x $field_width{level};
552 }
553 if ( $opt_show_module ) {
554 $header .= sprintf "%s ", "=" x $field_width{module};
555 }
556 if ( $opt_show_testcase ) {
557 $header .= sprintf "%s ", "=" x $field_width{testcase};
558 }
559 $header .= sprintf "%s\n", "=" x $field_width{message};
560  
561 print $header;
562 } ## end if ( not $opt_raw and ...)
563  
564 # Now we are ready to actually print messages, including those that are
565 # currently in the hold queue.
566 while ( my $entry = pop @held_messages ) {
567 $message_printer->( $entry );
568 }
569 Zonemaster::Engine->logger->callback( $message_printer );
570  
571 # Actually run tests!
572 eval { Zonemaster::Engine->test_zone( $domain ); };
573  
574 if ( $@ ) {
575 my $err = $@;
576 if ( blessed $err and $err->isa( "Zonemaster::Engine::Exception::NormalExit" ) ) {
577 say STDERR "Exited early: " . $err->message;
578 }
579 else {
580 die $err; # Don't know what it is, rethrow
581 }
582 }
583  
584 if ( not $opt_raw and not $opt_json ) {
585 if ( not $printed_something ) {
586 say __( "Looks OK." );
587 }
588 }
589  
590 my $json_output = {};
591  
592 if ( $opt_count ) {
593 my %entries;
594 foreach my $e ( @{ Zonemaster::Engine->logger->entries } ) {
595 $entries{$e->level}{$e->tag} += 1;
596 }
597  
598 if ( $opt_json ) {
599 $json_output->{count} = {};
600 foreach my $level ( sort { $numeric{$b} <=> $numeric{$a} } keys %counter ) {
601 $json_output->{count}{by_level}{$level} = $counter{$level};
602 }
603  
604 foreach my $level ( sort { $numeric{$b} <=> $numeric{$a} } keys %entries ) {
605 foreach my $tag ( sort keys %{ $entries{$level} } ) {
606 $json_output->{count}{by_message_tag}{$level}{$tag} = $entries{$level}{$tag};
607 }
608 }
609 }
610 else {
611 my $header1 = __( 'Level' );
612 my $max1 = length $header1;
613 my $header2 = __( 'Number of log entries' );
614 my $max2 = length $header2;
615  
616 foreach my $level ( sort { $numeric{$b} <=> $numeric{$a} } keys %counter ) {
617 my $len = length translate_severity( $level );
618 $max1 = $len if $len > $max1;
619 }
620  
621 printf "\n\n%${max1}s\t%${max2}s", $header1, $header2;
622 printf "\n%s\t%s\n", '=' x $max1, '=' x $max2;
623  
624 foreach my $level ( sort { $numeric{$b} <=> $numeric{$a} } keys %counter ) {
625 printf "%${max1}s\t%${max2}d\n", translate_severity( $level ), $counter{$level};
626 }
627  
628 my $header3 = __( 'Message tag' );
629 my $max3 = max map { length "$_" } ( ( map { keys %{ $_ } } ( values %entries ) ), $header3 );
630 my $header4 = __( 'Count' );
631 my $max4 = max map { length "$_" } ( ( map { values %{ $_ } } ( values %entries ) ), $header4 );
632  
633 printf "\n%${max1}s\t%${max3}s\t%${max4}s", $header1, $header3, $header4;
634 printf "\n%${max1}s\t%${max3}s\t%${max4}s\n", '=' x $max1, '=' x $max3, '=' x $max4;
635 foreach my $level ( sort { $numeric{$b} <=> $numeric{$a} } keys %entries ) {
636 foreach my $tag ( sort keys %{ $entries{$level} } ) {
637 printf "%${max1}s\t%${max3}s\t%${max4}s\n", $level, $tag, $entries{$level}{$tag};
638 }
639 }
640 }
641 }
642  
643 if ( $opt_nstimes ) {
644 my $zone = Zonemaster::Engine->zone( $domain );
645 my %all_nss = %{ Zonemaster::Engine::Nameserver::object_cache };
646 my @child_nss = @{ $zone->ns };
647 my @parent_nss = @{ $zone->parent->ns };
648 my @all_responded_nss;
649  
650 foreach my $ns_name ( keys %all_nss ) {
651 foreach my $ns ( values %{ $all_nss{$ns_name} } ) {
652 push @all_responded_nss, $ns if scalar @{ $ns->times } > 0;
653 }
654 }
655  
656 my %nss_filter = map { $_ => undef } ( @child_nss, @parent_nss );
657 my @other_nss = grep { ! exists $nss_filter{$_} } @all_responded_nss;
658  
659 if ( $opt_json ) {
660 my @times;
661  
662 my sub json_nstimes {
663 my ( $ns ) = @_;
664 return {
665 'ns' => $ns->string,
666 'max' => 1000 * $ns->max_time,
667 'min' => 1000 * $ns->min_time,
668 'avg' => 1000 * $ns->average_time,
669 'stddev' => 1000 * $ns->stddev_time,
670 'median' => 1000 * $ns->median_time,
671 'total' => 1000 * $ns->sum_time,
672 'count' => scalar @{ $ns->times }
673 };
674 }
675  
676 my %section_mapping = (
677 'child' => \@child_nss,
678 'parent' => \@parent_nss,
679 'other' => \@other_nss
680 );
681  
682 foreach my $section_name ( sort keys %section_mapping ) {
683 my @entries = map { json_nstimes( $_ ) } sort @{ $section_mapping{$section_name} };
684 push @times, { $section_name => \@entries };
685 }
686  
687 $json_output->{nstimes} = \@times;
688 }
689 else {
690 my $header = __( 'Name servers' );
691 my $max = max map { length( "$_" ) } ( ( @child_nss, @parent_nss, @all_responded_nss ), $header );
692 printf "\n%${max}s %s\n", $header, ' Max Min Avg Stddev Median Total Count';
693 printf "%${max}s %s\n", '=' x $max, ' ========== ========== ========== ========== ========== =========== ===========';
694  
695 my $total_queries_count = 0;
696 my $total_queries_times = 0;
697 my %nss_already_processed;
698  
699 my sub print_nstimes {
700 my ( $ns, $max, $total_queries_count, $total_queries_times, $nss_already_processed_ref ) = @_;
701 my %nss_already_processed = %{ $nss_already_processed_ref };
702  
703 printf "%${max}s ", $ns->string;
704 printf "%11.2f ", 1000 * $ns->max_time;
705 printf "%10.2f ", 1000 * $ns->min_time;
706 printf "%10.2f ", 1000 * $ns->average_time;
707 printf "%10.2f ", 1000 * $ns->stddev_time;
708 printf "%10.2f ", 1000 * $ns->median_time;
709 printf "%11.2f ", 1000 * $ns->sum_time;
710 printf "%11d\n", scalar @{ $ns->times };
711 $total_queries_count += scalar @{ $ns->times } unless $nss_already_processed{$ns};
712 $total_queries_times += ( 1000 * $ns->sum_time ) unless $nss_already_processed{$ns};
713  
714 return $total_queries_count, $total_queries_times;
715 }
716  
717 my %section_mapping = (
718 1 => { __( 'Child zone' ) => \@child_nss },
719 2 => { __( 'Parent zone' ) => \@parent_nss },
720 3 => { __( 'Other' ) => \@other_nss }
721 );
722  
723 foreach my $section_order ( sort keys %section_mapping ) {
724 foreach my $section_header ( keys % { $section_mapping{$section_order} } ) {
725 printf "%s %s\n", $section_header, '-' x ( ( $max - length $section_header ) - 1 );
726  
727 foreach my $section_nss ( sort @{ $section_mapping{$section_order}{$section_header} } ) {
728 ( $total_queries_count, $total_queries_times ) =
729 print_nstimes( $section_nss, $max, $total_queries_count, $total_queries_times, \%nss_already_processed );
730 $nss_already_processed{$section_nss} = 1;
731 }
732 }
733 }
734  
735 printf "%${max}s %s\n", '=' x $max, ' ========== ========== ========== ========== ========== =========== ===========';
736 printf "%${max}s %67.2f %11s\n", __( 'Grand total' ), $total_queries_times, $total_queries_count;
737 }
738 } ## end if ( $opt_nstimes )
739  
740 if ( $opt_elapsed ) {
741 my $last = Zonemaster::Engine->logger->entries->[-1];
742  
743 if ( $opt_json ) {
744 $json_output->{elapsed} = $last->timestamp;
745 }
746 else {
747 printf "\nTotal test run time: %0.1f seconds.\n", $last->timestamp;
748 }
749 }
750  
751 if ( $opt_json and not $opt_json_stream ) {
752 my $res = Zonemaster::Engine->logger->json( $opt_level );
753 $res = $JSON->decode( $res );
754 foreach ( @$res ) {
755 unless ( $opt_raw ) {
756 my %e = %$_;
757 my $entry = Zonemaster::Engine::Logger::Entry->new( \%e );
758 $_->{message} = $translator->translate_tag( $entry );
759 }
760 delete $_->{timestamp} unless $opt_time;
761 delete $_->{level} unless $opt_show_level;
762 delete $_->{module} unless $opt_show_module;
763 delete $_->{testcase} unless $opt_show_testcase;
764 }
765 $json_output->{results} = $res;
766 }
767  
768 if ( scalar keys %$json_output ) {
769 say $JSON->encode( $json_output );
770 }
771  
772 if ( $opt_save ) {
773 Zonemaster::Engine->save_cache( $opt_save );
774 }
775  
776 return $EXIT_SUCCESS;
777 } ## end sub run
778  
779 sub check_fake_delegation {
780 my ( $domain, @ns ) = @_;
781  
782 foreach my $pair ( @ns ) {
783 my ( $name, $ip ) = split( '/', $pair, 2 );
784  
785 if ( $pair =~ tr/\/// > 1 or not $name ) {
786 die __( "--ns must be a name or a name/ip pair." ) . "\n";
787 }
788  
789 ( my $errors, $name ) = normalize_name( decode( 'utf8', $name ) );
790  
791 if ( scalar @$errors > 0 ) {
792 my $error_message = "Invalid name in --ns argument:\n";
793 foreach my $err ( @$errors ) {
794 $error_message .= "\t" . $err->string . "\n";
795 }
796 die $error_message;
797 }
798  
799 if ( $ip ) {
800 my $net_ip = Net::IP::XS->new( $ip );
801 unless ( validate_ipv4( $ip ) or validate_ipv6( $ip ) ) {
802 die Net::IP::XS::Error()
803 ? "Invalid IP address in --ns argument:\n\t" . Net::IP::XS::Error() . "\n"
804 : "Invalid IP address in --ns argument.\n";
805 }
806 }
807 } ## end foreach my $pair ( @ns )
808  
809 return;
810 } ## end sub check_fake_delegation
811  
812 sub check_fake_ds {
813 my ( @ds ) = @_;
814  
815 foreach my $str ( @ds ) {
816 unless ( $str =~ /$DS_RE/ ) {
817 say STDERR __(
818 "--ds ds data must be in the form \"keytag,algorithm,type,digest\". E.g. space is not permitted anywhere in the string."
819 );
820 exit( 1 );
821 }
822 }
823  
824 return;
825 }
826  
827 sub add_fake_delegation {
828 my ( $domain, @ns ) = @_;
829 my @ns_with_no_ip;
830 my %data;
831  
832 foreach my $pair ( @ns ) {
833 my ( $name, $ip ) = split( '/', $pair, 2 );
834  
835 ( my $errors, $name ) = normalize_name( decode( 'utf8', $name ) );
836  
837 if ( $ip ) {
838 push @{ $data{$name} }, $ip;
839 }
840 else {
841 push @ns_with_no_ip, $name;
842 }
843 }
844  
845 foreach my $ns ( @ns_with_no_ip ) {
846 if ( not exists $data{$ns} ) {
847 $data{$ns} = undef;
848 }
849 }
850  
851 return Zonemaster::Engine->add_fake_delegation( $domain => \%data );
852  
853 } ## end sub add_fake_delegation
854  
855 sub add_fake_ds {
856 my ( $domain, @ds ) = @_;
857 my @data;
858  
859 foreach my $str ( @ds ) {
860 my ( $tag, $algo, $type, $digest ) = split( /,/, $str );
861 push @data, { keytag => $tag, algorithm => $algo, type => $type, digest => $digest };
862 }
863  
864 Zonemaster::Engine->add_fake_ds( $domain => \@data );
865  
866 return;
867 }
868  
869 sub print_versions {
870 say 'Zonemaster-CLI version ' . __PACKAGE__->VERSION;
871 say 'Zonemaster-Engine version ' . $Zonemaster::Engine::VERSION;
872 say 'Zonemaster-LDNS version ' . $Zonemaster::LDNS::VERSION;
873 say 'NL NetLabs LDNS version ' . Zonemaster::LDNS::lib_version();
874  
875 return;
876 }
877  
878 my @spinner_strings = ( ' | ', ' / ', ' - ', ' \\ ' );
879  
880 sub print_spinner {
881 state $counter = 0;
882 state $last_spin = [ 0, 0 ];
883  
884 my $time = [ Time::HiRes::gettimeofday() ];
885 if ( Time::HiRes::tv_interval( $last_spin, $time ) > 0.1 ) {
886 $last_spin = $time;
887 printf "%s\r", $spinner_strings[ $counter++ % 4 ];
888 }
889 }
890  
891 sub print_test_list {
892 my %methods = Zonemaster::Engine->all_methods;
893 my $maxlen = max map {
894 map { length( $_ ) }
895 @$_
896 } values %methods;
897  
898 foreach my $module ( sort keys %methods ) {
899 say $module;
900 foreach my $method ( sort @{ $methods{$module} } ) {
901 printf " %${maxlen}s\n", $method;
902 }
903 print "\n";
904 }
905  
906 return;
907 }
908  
909 sub do_dump_profile {
910 my $json = JSON::XS->new->canonical->pretty;
911  
912 print $json->encode( Zonemaster::Engine::Profile->effective->{q{profile}} );
913  
914 return;
915 }
916  
917 sub translate_severity {
918 my $severity = shift;
919 if ( $severity eq "DEBUG" ) {
920 return __( "DEBUG" );
921 }
922 elsif ( $severity eq "INFO" ) {
923 return __( "INFO" );
924 }
925 elsif ( $severity eq "NOTICE" ) {
926 return __( "NOTICE" );
927 }
928 elsif ( $severity eq "WARNING" ) {
929 return __( "WARNING" );
930 }
931 elsif ( $severity eq "ERROR" ) {
932 return __( "ERROR" );
933 }
934 elsif ( $severity eq "CRITICAL" ) {
935 return __( "CRITICAL" );
936 }
937 else {
938 return $severity;
939 }
940 } ## end sub translate_severity
941  
942 sub _max {
943 my ( $a, $b ) = @_;
944 $a //= 0;
945 $b //= 0;
946 return ( $a > $b ? $a : $b );
947 }
948  
949 1;
950  
951 __END__
« CLI/TestCaseSet.pm ↑ Summary