The automated check DISA's SCAP Compliance Checker runs to assess this control. Pick a release below to see exactly what it evaluates on the target system.
Perl script — ready to run as-is to check this control.
#!/usr/bin/env perl
use strict;
use warnings;
use File::Temp qw(tempdir);
# SCC assessment for oval:mil.disa.stig.solaris11:def:30
# Combines 1 check(s) with AND logic.
# Extracted from real DISA SCC source and verified to execute standalone.
# NOTE: reference(s) to /etc/shadow were redirected to
# bundled, obviously-synthetic fixture data this script writes out itself
# below, so it runs standalone on any machine, outside the live SCC engine
# -- the check logic itself is real, unmodified DISA SCC source.
sub __scc_write_file {
my ($path, $content) = @_;
my $dir = $path;
$dir =~ s{/[^/]+$}{};
if ($dir && !-d $dir) {
my $acc = '';
for my $part (split m{/}, $dir) {
$acc .= "$part/";
mkdir $acc unless -d $acc;
}
}
open(my $fh, '>', $path) or die "cannot write $path: $!";
print $fh $content;
close $fh;
}
my $__scc_support_dir;
BEGIN {
$__scc_support_dir = tempdir(CLEANUP => 1);
push @INC, $__scc_support_dir;
my %__scc_dep_files = (
'Error.pm' => <<'SCC_DEP_0',
# Error.pm
#
# Copyright (c) 1997-8 Graham Barr <gbarr@ti.com>. All rights reserved.
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.
#
# Based on my original Error.pm, and Exceptions.pm by Peter Seibel
# <peter@weblogic.com> and adapted by Jesse Glick <jglick@sig.bsh.com>.
#
# but modified ***significantly***
package Error;
$Error::VERSION = '0.17029';
use strict;
use warnings;
use 5.004;
use overload (
'""' => 'stringify',
'0+' => 'value',
'bool' => sub { return 1; },
'fallback' => 1
);
$Error::Depth = 0; # Depth to pass to caller()
$Error::Debug = 0; # Generate verbose stack traces
@Error::STACK = (); # Clause stack for try
$Error::THROWN = undef; # last error thrown, a workaround until die $ref works
my $LAST; # Last error created
my %ERROR; # Last error associated with package
sub _throw_Error_Simple
{
my $args = shift;
return Error::Simple->new( $args->{'text'} );
}
$Error::ObjectifyCallback = \&_throw_Error_Simple;
# Exported subs are defined in Error::subs
use Scalar::Util ();
sub import
{
shift;
my @tags = @_;
local $Exporter::ExportLevel = $Exporter::ExportLevel + 1;
@tags = grep {
if ( $_ eq ':warndie' )
{
Error::WarnDie->import();
0;
}
else
{
1;
}
} @tags;
Error::subs->import(@tags);
}
# I really want to use last for the name of this method, but it is a keyword
# which prevent the syntax last Error
sub prior
{
shift; # ignore
return $LAST unless @_;
my $pkg = shift;
return exists $ERROR{$pkg} ? $ERROR{$pkg} : undef
unless ref($pkg);
my $obj = $pkg;
my $err = undef;
if ( $obj->isa('HASH') )
{
$err = $obj->{'__Error__'}
if exists $obj->{'__Error__'};
}
elsif ( $obj->isa('GLOB') )
{
$err = ${*$obj}{'__Error__'}
if exists ${*$obj}{'__Error__'};
}
$err;
}
sub flush
{
shift; #ignore
unless (@_)
{
$LAST = undef;
return;
}
my $pkg = shift;
return unless ref($pkg);
undef $ERROR{$pkg} if defined $ERROR{$pkg};
}
# Return as much information as possible about where the error
# happened. The -stacktrace element only exists if $Error::DEBUG
# was set when the error was created
sub stacktrace
{
my $self = shift;
return $self->{'-stacktrace'}
if exists $self->{'-stacktrace'};
my $text = exists $self->{'-text'} ? $self->{'-text'} : "Died";
$text .= sprintf( " at %s line %d.\n", $self->file, $self->line )
unless ( $text =~ /\n$/s );
$text;
}
sub associate
{
my $err = shift;
my $obj = shift;
return unless ref($obj);
if ( $obj->isa('HASH') )
{
$obj->{'__Error__'} = $err;
}
elsif ( $obj->isa('GLOB') )
{
${*$obj}{'__Error__'} = $err;
}
$obj = ref($obj);
$ERROR{ ref($obj) } = $err;
return;
}
sub new
{
my $self = shift;
my ( $pkg, $file, $line ) = caller($Error::Depth);
my $err = bless {
'-package' => $pkg,
'-file' => $file,
'-line' => $line,
@_
}, $self;
$err->associate( $err->{'-object'} )
if ( exists $err->{'-object'} );
# To always create a stacktrace would be very inefficient, so
# we only do it if $Error::Debug is set
if ($Error::Debug)
{
require Carp;
local $Carp::CarpLevel = $Error::Depth;
my $text = defined( $err->{'-text'} ) ? $err->{'-text'} : "Error";
my $trace = Carp::longmess($text);
# Remove try calls from the trace
$trace =~
s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+Error::subs::try[^\n]+(?=\n)//sog;
$trace =~
s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+Error::subs::run_clauses[^\n]+\n\s+Error::subs::try[^\n]+(?=\n)//sog;
$err->{'-stacktrace'} = $trace;
}
$@ = $LAST = $ERROR{$pkg} = $err;
}
# Throw an error. this contains some very gory code.
sub throw
{
my $self = shift;
local $Error::Depth = $Error::Depth + 1;
# if we are not rethrow-ing then create the object to throw
$self = $self->new(@_) unless ref($self);
die $Error::THROWN = $self;
}
# syntactic sugar for
#
# die with Error( ... );
sub with
{
my $self = shift;
local $Error::Depth = $Error::Depth + 1;
$self->new(@_);
}
# syntactic sugar for
#
# record Error( ... ) and return;
sub record
{
my $self = shift;
local $Error::Depth = $Error::Depth + 1;
$self->new(@_);
}
# catch clause for
#
# try { ... } catch CLASS with { ... }
sub catch
{
my $pkg = shift;
my $code = shift;
my $clauses = shift || {};
my $catch = $clauses->{'catch'} ||= [];
unshift @$catch, $pkg, $code;
$clauses;
}
# Object query methods
sub object
{
my $self = shift;
exists $self->{'-object'} ? $self->{'-object'} : undef;
}
sub file
{
my $self = shift;
exists $self->{'-file'} ? $self->{'-file'} : undef;
}
sub line
{
my $self = shift;
exists $self->{'-line'} ? $self->{'-line'} : undef;
}
sub text
{
my $self = shift;
exists $self->{'-text'} ? $self->{'-text'} : undef;
}
# overload methods
sub stringify
{
my $self = shift;
defined $self->{'-text'} ? $self->{'-text'} : "Died";
}
sub value
{
my $self = shift;
exists $self->{'-value'} ? $self->{'-value'} : undef;
}
package Error::Simple;
$Error::Simple::VERSION = '0.17029';
@Error::Simple::ISA = qw(Error);
sub new
{
my $self = shift;
my $text = "" . shift;
my $value = shift;
my (@args) = ();
local $Error::Depth = $Error::Depth + 1;
@args = ( -file => $1, -line => $2 )
if ( $text =~
s/\s+at\s+(\S+)\s+line\s+(\d+)(?:,\s*<[^>]*>\s+line\s+\d+)?\.?\n?$//s );
push( @args, '-value', 0 + $value )
if defined($value);
$self->SUPER::new( -text => $text, @args );
}
sub stringify
{
my $self = shift;
my $text = $self->SUPER::stringify;
$text .= sprintf( " at %s line %d.\n", $self->file, $self->line )
unless ( $text =~ /\n$/s );
$text;
}
##########################################################################
##########################################################################
# Inspired by code from Jesse Glick <jglick@sig.bsh.com> and
# Peter Seibel <peter@weblogic.com>
package Error::subs;
$Error::subs::VERSION = '0.17029';
use Exporter ();
use vars qw(@EXPORT_OK @ISA %EXPORT_TAGS);
@EXPORT_OK = qw(try with finally except otherwise);
%EXPORT_TAGS = ( try => \@EXPORT_OK );
@ISA = qw(Exporter);
sub run_clauses ($$$\@)
{
my ( $clauses, $err, $wantarray, $result ) = @_;
my $code = undef;
$err = $Error::ObjectifyCallback->( { 'text' => $err } ) unless ref($err);
CATCH:
{
# catch
my $catch;
if ( defined( $catch = $clauses->{'catch'} ) )
{
my $i = 0;
CATCHLOOP:
for ( ; $i < @$catch ; $i += 2 )
{
my $pkg = $catch->[$i];
unless ( defined $pkg )
{
#except
splice( @$catch, $i, 2, $catch->[ $i + 1 ]->($err) );
$i -= 2;
next CATCHLOOP;
}
elsif ( Scalar::Util::blessed($err) && $err->isa($pkg) )
{
$code = $catch->[ $i + 1 ];
while (1)
{
my $more = 0;
local ( $Error::THROWN, $@ );
my $ok = eval {
$@ = $err;
if ($wantarray)
{
@{$result} = $code->( $err, \$more );
}
elsif ( defined($wantarray) )
{
@{$result} = ();
$result->[0] = $code->( $err, \$more );
}
else
{
$code->( $err, \$more );
}
1;
};
if ($ok)
{
next CATCHLOOP if $more;
undef $err;
}
else
{
$err = $@ || $Error::THROWN;
$err = $Error::ObjectifyCallback->(
{ 'text' => $err } )
unless ref($err);
}
last CATCH;
}
}
}
}
# otherwise
my $owise;
if ( defined( $owise = $clauses->{'otherwise'} ) )
{
my $code = $clauses->{'otherwise'};
my $more = 0;
local ( $Error::THROWN, $@ );
my $ok = eval {
$@ = $err;
if ($wantarray)
{
@{$result} = $code->( $err, \$more );
}
elsif ( defined($wantarray) )
{
@{$result} = ();
$result->[0] = $code->( $err, \$more );
}
else
{
$code->( $err, \$more );
}
1;
};
if ($ok)
{
undef $err;
}
else
{
$err = $@ || $Error::THROWN;
$err = $Error::ObjectifyCallback->( { 'text' => $err } )
unless ref($err);
}
}
}
$err;
}
sub try (&;$)
{
my $try = shift;
my $clauses = @_ ? shift : {};
my $ok = 0;
my $err = undef;
my @result = ();
unshift @Error::STACK, $clauses;
my $wantarray = wantarray();
do
{
local $Error::THROWN = undef;
local $@ = undef;
$ok = eval {
if ($wantarray)
{
@result = $try->();
}
elsif ( defined $wantarray )
{
$result[0] = $try->();
}
else
{
$try->();
}
1;
};
$err = $@ || $Error::THROWN
unless $ok;
};
shift @Error::STACK;
$err = run_clauses( $clauses, $err, wantarray, @result )
unless ($ok);
$clauses->{'finally'}->()
if ( defined( $clauses->{'finally'} ) );
if ( defined($err) )
{
if ( Scalar::Util::blessed($err) && $err->can('throw') )
{
throw $err;
}
else
{
die $err;
}
}
wantarray ? @result : $result[0];
}
# Each clause adds a sub to the list of clauses. The finally clause is
# always the last, and the otherwise clause is always added just before
# the finally clause.
#
# All clauses, except the finally clause, add a sub which takes one argument
# this argument will be the error being thrown. The sub will return a code ref
# if that clause can handle that error, otherwise undef is returned.
#
# The otherwise clause adds a sub which unconditionally returns the users
# code reference, this is why it is forced to be last.
#
# The catch clause is defined in Error.pm, as the syntax causes it to
# be called as a method
sub with (&;$)
{
@_;
}
sub finally (&)
{
my $code = shift;
my $clauses = { 'finally' => $code };
$clauses;
}
# The except clause is a block which returns a hashref or a list of
# key-value pairs, where the keys are the classes and the values are subs.
sub except (&;$)
{
my $code = shift;
my $clauses = shift || {};
my $catch = $clauses->{'catch'} ||= [];
my $sub = sub {
my $ref;
my (@array) = $code->( $_[0] );
if ( @array == 1 && ref( $array[0] ) )
{
$ref = $array[0];
$ref = [%$ref]
if ( UNIVERSAL::isa( $ref, 'HASH' ) );
}
else
{
$ref = \@array;
}
@$ref;
};
unshift @{$catch}, undef, $sub;
$clauses;
}
sub otherwise (&;$)
{
my $code = shift;
my $clauses = shift || {};
if ( exists $clauses->{'otherwise'} )
{
require Carp;
Carp::croak("Multiple otherwise clauses");
}
$clauses->{'otherwise'} = $code;
$clauses;
}
1;
package Error::WarnDie;
$Error::WarnDie::VERSION = '0.17029';
sub gen_callstack($)
{
my ($start) = @_;
require Carp;
local $Carp::CarpLevel = $start;
my $trace = Carp::longmess("");
# Remove try calls from the trace
$trace =~
s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+Error::subs::try[^\n]+(?=\n)//sog;
$trace =~
s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+Error::subs::run_clauses[^\n]+\n\s+Error::subs::try[^\n]+(?=\n)//sog;
my @callstack = split( m/\n/, $trace );
return @callstack;
}
my $old_DIE;
my $old_WARN;
sub DEATH
{
my ($e) = @_;
local $SIG{__DIE__} = $old_DIE if ( defined $old_DIE );
die @_ if $^S;
my ( $etype, $message, $location, @callstack );
if ( ref($e) && $e->isa("Error") )
{
$etype = "exception of type " . ref($e);
$message = $e->text;
$location = $e->file . ":" . $e->line;
@callstack = split( m/\n/, $e->stacktrace );
}
else
{
# Don't apply subsequent layer of message formatting
die $e if ( $e =~ m/^\nUnhandled perl error caught at toplevel:\n\n/ );
$etype = "perl error";
my $stackdepth = 0;
while ( caller($stackdepth) =~ m/^Error(?:$|::)/ )
{
++$stackdepth;
}
@callstack = gen_callstack( $stackdepth + 1 );
$message = "$e";
chomp $message;
if ( $message =~ s/ at (.*?) line (\d+)\.$// )
{
$location = $1 . ":" . $2;
}
else
{
my @caller = caller($stackdepth);
$location = $caller[1] . ":" . $caller[2];
}
}
shift @callstack;
# Do it this way in case there are no elements; we don't print a spurious \n
my $callstack = join( "", map { "$_\n" } @callstack );
die
"\nUnhandled $etype caught at toplevel:\n\n $message\n\nThrown from: $location\n\nFull stack trace:\n\n$callstack\n";
}
sub TAXES
{
my ($message) = @_;
local $SIG{__WARN__} = $old_WARN if ( defined $old_WARN );
$message =~ s/ at .*? line \d+\.$//;
chomp $message;
my @callstack = gen_callstack(1);
my $location = shift @callstack;
# $location already starts in a leading space
$message .= $location;
# Do it this way in case there are no elements; we don't print a spurious \n
my $callstack = join( "", map { "$_\n" } @callstack );
warn "$message:\n$callstack";
}
sub import
{
$old_DIE = $SIG{__DIE__};
$old_WARN = $SIG{__WARN__};
$SIG{__DIE__} = \&DEATH;
$SIG{__WARN__} = \&TAXES;
}
1;
__END__
=pod
=encoding UTF-8
=head1 NAME
Error - Error/exception handling in an OO-ish way
=head1 VERSION
version 0.17029
=head1 SYNOPSIS
use Error qw(:try);
throw Error::Simple( "A simple error");
sub xyz {
...
record Error::Simple("A simple error")
and return;
}
unlink($file) or throw Error::Simple("$file: $!",$!);
try {
do_some_stuff();
die "error!" if $condition;
throw Error::Simple "Oops!" if $other_condition;
}
catch Error::IO with {
my $E = shift;
print STDERR "File ", $E->{'-file'}, " had a problem\n";
}
except {
my $E = shift;
my $general_handler=sub {send_message $E->{-description}};
return {
UserException1 => $general_handler,
UserException2 => $general_handler
};
}
otherwise {
print STDERR "Well I don't know what to say\n";
}
finally {
close_the_garage_door_already(); # Should be reliable
}; # Don't forget the trailing ; or you might be surprised
=head1 DESCRIPTION
The C<Error> package provides two interfaces. Firstly C<Error> provides
a procedural interface to exception handling. Secondly C<Error> is a
base class for errors/exceptions that can either be thrown, for
subsequent catch, or can simply be recorded.
Errors in the class C<Error> should not be thrown directly, but the
user should throw errors from a sub-class of C<Error>.
=head1 WARNING
Using the "Error" module is B<no longer recommended> due to the black-magical
nature of its syntactic sugar, which often tends to break. Its maintainers
have stopped actively writing code that uses it, and discourage people
from doing so. See the "SEE ALSO" section below for better recommendations.
=head1 PROCEDURAL INTERFACE
C<Error> exports subroutines to perform exception handling. These will
be exported if the C<:try> tag is used in the C<use> line.
=over 4
=item try BLOCK CLAUSES
C<try> is the main subroutine called by the user. All other subroutines
exported are clauses to the try subroutine.
The BLOCK will be evaluated and, if no error is throw, try will return
the result of the block.
C<CLAUSES> are the subroutines below, which describe what to do in the
event of an error being thrown within BLOCK.
=item catch CLASS with BLOCK
This clauses will cause all errors that satisfy C<$err-E<gt>isa(CLASS)>
to be caught and handled by evaluating C<BLOCK>.
C<BLOCK> will be passed two arguments. The first will be the error
being thrown. The second is a reference to a scalar variable. If this
variable is set by the catch block then, on return from the catch
block, try will continue processing as if the catch block was never
found. The error will also be available in C<$@>.
To propagate the error the catch block may call C<$err-E<gt>throw>
If the scalar reference by the second argument is not set, and the
error is not thrown. Then the current try block will return with the
result from the catch block.
=item except BLOCK
When C<try> is looking for a handler, if an except clause is found
C<BLOCK> is evaluated. The return value from this block should be a
HASHREF or a list of key-value pairs, where the keys are class names
and the values are CODE references for the handler of errors of that
type.
=item otherwise BLOCK
Catch any error by executing the code in C<BLOCK>
When evaluated C<BLOCK> will be passed one argument, which will be the
error being processed. The error will also be available in C<$@>.
Only one otherwise block may be specified per try block
=item finally BLOCK
Execute the code in C<BLOCK> either after the code in the try block has
successfully completed, or if the try block throws an error then
C<BLOCK> will be executed after the handler has completed.
If the handler throws an error then the error will be caught, the
finally block will be executed and the error will be re-thrown.
Only one finally block may be specified per try block
=back
=head1 COMPATIBILITY
L<Moose> exports a keyword called C<with> which clashes with Error's. This
example returns a prototype mismatch error:
package MyTest;
use warnings;
use Moose;
use Error qw(:try);
(Thanks to C<maik.hentsche@amd.com> for the report.).
=head1 CLASS INTERFACE
=head2 CONSTRUCTORS
The C<Error> object is implemented as a HASH. This HASH is initialized
with the arguments that are passed to it's constructor. The elements
that are used by, or are retrievable by the C<Error> class are listed
below, other classes may add to these.
-file
-line
-text
-value
-object
If C<-file> or C<-line> are not specified in the constructor arguments
then these will be initialized with the file name and line number where
the constructor was called from.
If the error is associated with an object then the object should be
passed as the C<-object> argument. This will allow the C<Error> package
to associate the error with the object.
The C<Error> package remembers the last error created, and also the
last error associated with a package. This could either be the last
error created by a sub in that package, or the last error which passed
an object blessed into that package as the C<-object> argument.
=over 4
=item Error->new()
See the Error::Simple documentation.
=item throw ( [ ARGS ] )
Create a new C<Error> object and throw an error, which will be caught
by a surrounding C<try> block, if there is one. Otherwise it will cause
the program to exit.
C<throw> may also be called on an existing error to re-throw it.
=item with ( [ ARGS ] )
Create a new C<Error> object and returns it. This is defined for
syntactic sugar, eg
die with Some::Error ( ... );
=item record ( [ ARGS ] )
Create a new C<Error> object and returns it. This is defined for
syntactic sugar, eg
record Some::Error ( ... )
and return;
=back
=head2 STATIC METHODS
=over 4
=item prior ( [ PACKAGE ] )
Return the last error created, or the last error associated with
C<PACKAGE>
=item flush ( [ PACKAGE ] )
Flush the last error created, or the last error associated with
C<PACKAGE>.It is necessary to clear the error stack before exiting the
package or uncaught errors generated using C<record> will be reported.
$Error->flush;
=back
=head2 OBJECT METHODS
=over 4
=item stacktrace
If the variable C<$Error::Debug> was non-zero when the error was
created, then C<stacktrace> returns a string created by calling
C<Carp::longmess>. If the variable was zero the C<stacktrace> returns
the text of the error appended with the filename and line number of
where the error was created, providing the text does not end with a
newline.
=item object
The object this error was associated with
=item file
The file where the constructor of this error was called from
=item line
The line where the constructor of this error was called from
=item text
The text of the error
=item $err->associate($obj)
Associates an error with an object to allow error propagation. I.e:
$ber->encode(...) or
return Error->prior($ber)->associate($ldap);
=back
=head2 OVERLOAD METHODS
=over 4
=item stringify
A method that converts the object into a string. This method may simply
return the same as the C<text> method, or it may append more
information. For example the file name and line number.
By default this method returns the C<-text> argument that was passed to
the constructor, or the string C<"Died"> if none was given.
=item value
A method that will return a value that can be associated with the
error. For example if an error was created due to the failure of a
system call, then this may return the numeric value of C<$!> at the
time.
By default this method returns the C<-value> argument that was passed
to the constructor.
=back
=head1 PRE-DEFINED ERROR CLASSES
=head2 Error::Simple
This class can be used to hold simple error strings and values. It's
constructor takes two arguments. The first is a text value, the second
is a numeric value. These values are what will be returned by the
overload methods.
If the text value ends with C<at file line 1> as $@ strings do, then
this information will be used to set the C<-file> and C<-line> arguments
of the error object.
This class is used internally if an eval'd block die's with an error
that is a plain string. (Unless C<$Error::ObjectifyCallback> is modified)
=head1 $Error::ObjectifyCallback
This variable holds a reference to a subroutine that converts errors that
are plain strings to objects. It is used by Error.pm to convert textual
errors to objects, and can be overridden by the user.
It accepts a single argument which is a hash reference to named parameters.
Currently the only named parameter passed is C<'text'> which is the text
of the error, but others may be available in the future.
For example the following code will cause Error.pm to throw objects of the
class MyError::Bar by default:
sub throw_MyError_Bar
{
my $args = shift;
my $err = MyError::Bar->new();
$err->{'MyBarText'} = $args->{'text'};
return $err;
}
{
local $Error::ObjectifyCallback = \&throw_MyError_Bar;
# Error handling here.
}
=head1 MESSAGE HANDLERS
C<Error> also provides handlers to extend the output of the C<warn()> perl
function, and to handle the printing of a thrown C<Error> that is not caught
or otherwise handled. These are not installed by default, but are requested
using the C<:warndie> tag in the C<use> line.
use Error qw( :warndie );
These new error handlers are installed in C<$SIG{__WARN__}> and
C<$SIG{__DIE__}>. If these handlers are already defined when the tag is
imported, the old values are stored, and used during the new code. Thus, to
arrange for custom handling of warnings and errors, you will need to perform
something like the following:
BEGIN {
$SIG{__WARN__} = sub {
print STDERR "My special warning handler: $_[0]"
};
}
use Error qw( :warndie );
Note that setting C<$SIG{__WARN__}> after the C<:warndie> tag has been
imported will overwrite the handler that C<Error> provides. If this cannot be
avoided, then the tag can be explicitly C<import>ed later
use Error;
$SIG{__WARN__} = ...;
import Error qw( :warndie );
=head2 EXAMPLE
The C<__DIE__> handler turns messages such as
Can't call method "foo" on an undefined value at examples/warndie.pl line 16.
into
Unhandled perl error caught at toplevel:
Can't call method "foo" on an undefined value
Thrown from: examples/warndie.pl:16
Full stack trace:
main::inner('undef') called at examples/warndie.pl line 20
main::outer('undef') called at examples/warndie.pl line 23
=head1 SEE ALSO
See L<Exception::Class> for a different module providing Object-Oriented
exception handling, along with a convenient syntax for declaring hierarchies
for them. It doesn't provide Error's syntactic sugar of C<try { ... }>,
C<catch { ... }>, etc. which may be a good thing or a bad thing based
on what you want. (Because Error's syntactic sugar tends to break.)
L<Error::Exception> aims to combine L<Error> and L<Exception::Class>
"with correct stringification".
L<TryCatch> and L<Try::Tiny> are similar in concept to Error.pm only providing
a syntax that hopefully breaks less.
=head1 KNOWN BUGS
None, but that does not mean there are not any.
=head1 AUTHORS
Graham Barr <gbarr@pobox.com>
The code that inspired me to write this was originally written by
Peter Seibel <peter@weblogic.com> and adapted by Jesse Glick
<jglick@sig.bsh.com>.
C<:warndie> handlers added by Paul Evans <leonerd@leonerd.org.uk>
=head1 MAINTAINER
Shlomi Fish, L<http://www.shlomifish.org/> .
=head1 PAST MAINTAINERS
Arun Kumar U <u_arunkumar@yahoo.com>
=head1 COPYRIGHT
Copyright (c) 1997-8 Graham Barr. All rights reserved.
This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
=for :stopwords cpan testmatrix url bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan
=head1 SUPPORT
=head2 Websites
The following websites have more information about this module, and may be of help to you. As always,
in addition to those websites please use your favorite search engine to discover more resources.
=over 4
=item *
MetaCPAN
A modern, open-source CPAN search engine, useful to view POD in HTML format.
L<https://metacpan.org/release/Error>
=item *
Search CPAN
The default CPAN search engine, useful to view POD in HTML format.
L<http://search.cpan.org/dist/Error>
=item *
RT: CPAN's Bug Tracker
The RT ( Request Tracker ) website is the default bug/issue tracking system for CPAN.
L<https://rt.cpan.org/Public/Dist/Display.html?Name=Error>
=item *
CPAN Ratings
The CPAN Ratings is a website that allows community ratings and reviews of Perl modules.
L<http://cpanratings.perl.org/d/Error>
=item *
CPANTS
The CPANTS is a website that analyzes the Kwalitee ( code metrics ) of a distribution.
L<http://cpants.cpanauthors.org/dist/Error>
=item *
CPAN Testers
The CPAN Testers is a network of smoke testers who run automated tests on uploaded CPAN distributions.
L<http://www.cpantesters.org/distro/E/Error>
=item *
CPAN Testers Matrix
The CPAN Testers Matrix is a website that provides a visual overview of the test results for a distribution on various Perls/platforms.
L<http://matrix.cpantesters.org/?dist=Error>
=item *
CPAN Testers Dependencies
The CPAN Testers Dependencies is a website that shows a chart of the test results of all dependencies for a distribution.
L<http://deps.cpantesters.org/?module=Error>
=back
=head2 Bugs / Feature Requests
Please report any bugs or feature requests by email to C<bug-error at rt.cpan.org>, or through
the web interface at L<https://rt.cpan.org/Public/Bug/Report.html?Queue=Error>. You will be automatically notified of any
progress on the request by the system.
=head2 Source Code
The code is open to the world, and available for you to hack on. Please feel free to browse it and play
with it, or whatever. If you want to contribute patches, please send me a diff or prod me to pull
from your repository :)
L<https://github.com/shlomif/perl-error.pm>
git clone git://github.com/shlomif/perl-error.pm.git
=head1 AUTHOR
Shlomi Fish ( http://www.shlomifish.org/ )
=head1 BUGS
Please report any bugs or feature requests on the bugtracker website
L<https://github.com/shlomif/perl-error.pm/issues>
When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2020 by Shlomi Fish ( http://www.shlomifish.org/ ).
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
SCC_DEP_0
,
'Error/Simple.pm' => <<'SCC_DEP_1',
# Error/Simple.pm
#
# Copyright (c) 2006 Shlomi Fish <shlomif@shlomifish.org>.
# This file is free software; you can redistribute it and/or
# modify it under the terms of the MIT/X11 license (whereas the licence
# of the Error distribution as a whole is the GPLv1+ and the Artistic
# licence).
package Error::Simple;
$Error::Simple::VERSION = '0.17029';
use strict;
use warnings;
use Error;
1;
__END__
=pod
=encoding UTF-8
=head1 NAME
Error::Simple - the simple error sub-class of Error
=head1 VERSION
version 0.17029
=head1 SYNOPSIS
use base 'Error::Simple';
=head1 DESCRIPTION
The only purpose of this module is to allow one to say:
use base 'Error::Simple';
and the only thing it does is "use" Error.pm. Refer to the documentation
of L<Error> for more information about Error::Simple.
=head1 METHODS
=head2 Error::Simple->new($text [, $value])
Constructs an Error::Simple with the text C<$text> and the optional value
C<$value>.
=head2 $err->stringify()
Error::Simple overloads this method.
=head1 KNOWN BUGS
None.
=head1 AUTHORS
Shlomi Fish ( L<http://www.shlomifish.org/> )
=head1 SEE ALSO
L<Error>
=for :stopwords cpan testmatrix url bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan
=head1 SUPPORT
=head2 Websites
The following websites have more information about this module, and may be of help to you. As always,
in addition to those websites please use your favorite search engine to discover more resources.
=over 4
=item *
MetaCPAN
A modern, open-source CPAN search engine, useful to view POD in HTML format.
L<https://metacpan.org/release/Error>
=item *
Search CPAN
The default CPAN search engine, useful to view POD in HTML format.
L<http://search.cpan.org/dist/Error>
=item *
RT: CPAN's Bug Tracker
The RT ( Request Tracker ) website is the default bug/issue tracking system for CPAN.
L<https://rt.cpan.org/Public/Dist/Display.html?Name=Error>
=item *
CPAN Ratings
The CPAN Ratings is a website that allows community ratings and reviews of Perl modules.
L<http://cpanratings.perl.org/d/Error>
=item *
CPANTS
The CPANTS is a website that analyzes the Kwalitee ( code metrics ) of a distribution.
L<http://cpants.cpanauthors.org/dist/Error>
=item *
CPAN Testers
The CPAN Testers is a network of smoke testers who run automated tests on uploaded CPAN distributions.
L<http://www.cpantesters.org/distro/E/Error>
=item *
CPAN Testers Matrix
The CPAN Testers Matrix is a website that provides a visual overview of the test results for a distribution on various Perls/platforms.
L<http://matrix.cpantesters.org/?dist=Error>
=item *
CPAN Testers Dependencies
The CPAN Testers Dependencies is a website that shows a chart of the test results of all dependencies for a distribution.
L<http://deps.cpantesters.org/?module=Error>
=back
=head2 Bugs / Feature Requests
Please report any bugs or feature requests by email to C<bug-error at rt.cpan.org>, or through
the web interface at L<https://rt.cpan.org/Public/Bug/Report.html?Queue=Error>. You will be automatically notified of any
progress on the request by the system.
=head2 Source Code
The code is open to the world, and available for you to hack on. Please feel free to browse it and play
with it, or whatever. If you want to contribute patches, please send me a diff or prod me to pull
from your repository :)
L<https://github.com/shlomif/perl-error.pm>
git clone git://github.com/shlomif/perl-error.pm.git
=head1 AUTHOR
Shlomi Fish ( http://www.shlomifish.org/ )
=head1 BUGS
Please report any bugs or feature requests on the bugtracker website
L<https://github.com/shlomif/perl-error.pm/issues>
When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2020 by Shlomi Fish ( http://www.shlomifish.org/ ).
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
SCC_DEP_1
,
'Readonly.pm' => <<'SCC_DEP_2',
package Readonly;
use 5.005;
use strict;
#use warnings;
#no warnings 'uninitialized';
package Readonly;
our $VERSION = '2.05';
$VERSION = eval $VERSION;
# Autocroak (Thanks, MJD)
# Only load Carp.pm if module is croaking.
sub croak {
require Carp;
goto &Carp::croak;
}
# These functions may be overridden by Readonly::XS, if installed.
use vars qw/$XSokay/; # Set to true in Readonly::XS, if available
# Predeclare the following, so we can use them recursively
sub _ARRAY (\@);
sub _HASH (\%);
# For perl 5.8.x or higher
# These functions are exposed in perl 5.8.x (Thanks, Leon!)
# They may be overridden by Readonly::XS, if installed on old perl versions
if ($] < 5.008) { # 'Classic' perl
*is_sv_readonly = sub ($) {0};
*make_sv_readonly
= sub ($) { die "make_sv_readonly called but not overridden" };
# See if we can use the XS stuff.
$Readonly::XS::MAGIC_COOKIE = $Readonly::XS::MAGIC_COOKIE
= "Do NOT use or require Readonly::XS unless you're me.";
eval 'use Readonly::XS';
}
else { # Modern perl doesn't need Readonly::XS
*is_sv_readonly = sub ($) { Internals::SvREADONLY($_[0]) };
*make_sv_readonly
= sub ($) { Internals::SvREADONLY($_[0], 1) };
$XSokay = 1; # We're using the new built-ins so this is a white lie
}
# Undo setting readonly
sub _SCALAR ($) {
my ($r_var) = @_;
if ($XSokay) {
Internals::SvREADONLY($r_var, 0) if is_sv_readonly($r_var);
}
else {
return if tied($r_var) !~ 'Readonly::Scalar';
my $r_scalar;
{
my $obj = tied $$r_var;
$r_scalar = $obj;
}
untie $r_var;
$r_var = $r_scalar;
}
}
sub _ARRAY (\@) {
my ($r_var) = @_;
return if !tied(@$r_var);
return if tied(@$r_var) !~ 'Readonly::Array';
my $r_array;
{
my $obj = tied @$r_var;
$r_array = $obj;
}
untie @$r_var;
@$r_var = @$r_array;
# Recursively check child elements for references; clean if Readonly
foreach (@$r_var) {
my $_reftype = ref $_;
if ($_reftype eq 'SCALAR') { _SCALAR($_) }
elsif ($_reftype eq 'ARRAY') {
_ARRAY(@$_);
}
elsif ($_reftype eq 'HASH') {
_HASH(%$_);
}
}
}
sub _HASH (\%) {
my ($r_var) = @_;
return if !tied(%$r_var);
return if tied(%$r_var) !~ 'Readonly::Hash';
my $r_hash;
{
my $obj = tied %$r_var;
$r_hash = $obj;
}
untie %$r_var;
%$r_var = %$r_hash;
# Recursively check child elements for references; clean if Readonly
foreach (values %$r_var) {
my $_reftype = ref $_;
if ($_reftype eq 'SCALAR') { _SCALAR($_) }
elsif ($_reftype eq 'ARRAY') {
_ARRAY(@$_);
}
elsif ($_reftype eq 'HASH') {
_HASH(%$_);
}
}
}
# Common error messages, or portions thereof
use vars qw/$MODIFY $REASSIGN $ODDHASH/;
$MODIFY = 'Modification of a read-only value attempted';
$REASSIGN = 'Attempt to reassign a readonly';
$ODDHASH = 'May not store an odd number of values in a hash';
# ----------------
# Read-only scalars
# ----------------
package Readonly::Scalar;
sub STORABLE_freeze {
my ($self, $cloning) = @_;
Readonly::_SCALAR($$self) if $cloning;
}
sub TIESCALAR {
my $whence
= (caller 2)[3]; # Check if naughty user is trying to tie directly.
Readonly::croak "Invalid tie"
unless $whence && $whence =~ /^Readonly::(?:Scalar1?|Readonly)$/;
my $class = shift;
Readonly::croak "No value specified for readonly scalar" unless @_;
Readonly::croak "Too many values specified for readonly scalar"
unless @_ == 1;
my $value = shift;
return bless \$value, $class;
}
sub FETCH {
my $self = shift;
return $$self;
}
*STORE = *STORE = sub { Readonly::croak $Readonly::MODIFY };
*UNTIE = *UNTIE
= sub { Readonly::croak $Readonly::MODIFY if caller() ne 'Readonly' };
# ----------------
# Read-only arrays
# ----------------
package Readonly::Array;
sub STORABLE_freeze {
my ($self, $cloning) = @_;
Readonly::_ARRAY(@$self) if $cloning;
}
sub TIEARRAY {
my $whence
= (caller 1)[3]; # Check if naughty user is trying to tie directly.
Readonly::croak "Invalid tie" unless $whence =~ /^Readonly::Array1?$/;
my $class = shift;
my @self = @_;
return bless \@self, $class;
}
sub FETCH {
my $self = shift;
my $index = shift;
return $self->[$index];
}
sub FETCHSIZE {
my $self = shift;
return scalar @$self;
}
BEGIN {
eval q{
sub EXISTS
{
my $self = shift;
my $index = shift;
return exists $self->[$index];
}
} if $] >= 5.006; # couldn't do "exists" on arrays before then
}
*STORE = *STORESIZE = *EXTEND = *PUSH = *POP = *UNSHIFT = *SHIFT = *SPLICE
= *CLEAR = *STORE = *STORESIZE = *EXTEND = *PUSH = *POP = *UNSHIFT
= *SHIFT = *SPLICE = *CLEAR = sub { Readonly::croak $Readonly::MODIFY};
*UNTIE = *UNTIE
= sub { Readonly::croak $Readonly::MODIFY if caller() ne 'Readonly' };
# ----------------
# Read-only hashes
# ----------------
package Readonly::Hash;
sub STORABLE_freeze {
my ($self, $cloning) = @_;
Readonly::_HASH(%$self) if $cloning;
}
sub TIEHASH {
my $whence
= (caller 1)[3]; # Check if naughty user is trying to tie directly.
Readonly::croak "Invalid tie" unless $whence =~ /^Readonly::Hash1?$/;
my $class = shift;
# must have an even number of values
Readonly::croak $Readonly::ODDHASH unless (@_ % 2 == 0);
my %self = @_;
return bless \%self, $class;
}
sub FETCH {
my $self = shift;
my $key = shift;
return $self->{$key};
}
sub EXISTS {
my $self = shift;
my $key = shift;
return exists $self->{$key};
}
sub FIRSTKEY {
my $self = shift;
my $dummy = keys %$self;
return scalar each %$self;
}
sub NEXTKEY {
my $self = shift;
return scalar each %$self;
}
*STORE = *DELETE = *CLEAR = *STORE = *DELETE = *CLEAR
= sub { Readonly::croak $Readonly::MODIFY};
*UNTIE = *UNTIE
= sub { Readonly::croak $Readonly::MODIFY if caller() ne 'Readonly'; };
# ----------------------------------------------------------------
# Main package, containing convenience functions (so callers won't
# have to explicitly tie the variables themselves).
# ----------------------------------------------------------------
package Readonly;
use Exporter;
use vars qw/@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS/;
push @ISA, 'Exporter';
push @EXPORT, qw/Readonly/;
push @EXPORT_OK, qw/Scalar Array Hash Scalar1 Array1 Hash1/;
# Predeclare the following, so we can use them recursively
sub Scalar ($$);
sub Array (\@;@);
sub Hash (\%;@);
# Returns true if a string begins with "Readonly::"
# Used to prevent reassignment of Readonly variables.
sub _is_badtype {
my $type = $_[0];
return lc $type if $type =~ s/^Readonly:://;
return;
}
# Shallow Readonly scalar
sub Scalar1 ($$) {
croak "$REASSIGN scalar" if is_sv_readonly($_[0]);
my $badtype = _is_badtype(ref tied $_[0]);
croak "$REASSIGN $badtype" if $badtype;
# xs method: flag scalar as readonly
if ($XSokay) {
$_[0] = $_[1];
make_sv_readonly($_[0]);
return;
}
# pure-perl method: tied scalar
my $tieobj = eval { tie $_[0], 'Readonly::Scalar', $_[1] };
if ($@) {
croak "$REASSIGN scalar" if substr($@, 0, 43) eq $MODIFY;
die $@; # some other error?
}
return $tieobj;
}
# Shallow Readonly array
sub Array1 (\@;@) {
my $badtype = _is_badtype(ref tied $_[0]);
croak "$REASSIGN $badtype" if $badtype;
my $aref = shift;
return tie @$aref, 'Readonly::Array', @_;
}
# Shallow Readonly hash
sub Hash1 (\%;@) {
my $badtype = _is_badtype(ref tied $_[0]);
croak "$REASSIGN $badtype" if $badtype;
my $href = shift;
# If only one value, and it's a hashref, expand it
if (@_ == 1 && ref $_[0] eq 'HASH') {
return tie %$href, 'Readonly::Hash', %{$_[0]};
}
# otherwise, must have an even number of values
croak $ODDHASH unless (@_ % 2 == 0);
return tie %$href, 'Readonly::Hash', @_;
}
# Deep Readonly scalar
sub Scalar ($$) {
croak "$REASSIGN scalar" if is_sv_readonly($_[0]);
my $badtype = _is_badtype(ref tied $_[0]);
croak "$REASSIGN $badtype" if $badtype;
my $value = $_[1];
# Recursively check passed element for references; if any, make them Readonly
foreach ($value) {
if (ref eq 'SCALAR') { Scalar my $v => $$_; $_ = \$v }
elsif (ref eq 'ARRAY') { Array my @v => @$_; $_ = \@v }
elsif (ref eq 'HASH') { Hash my %v => $_; $_ = \%v }
}
# xs method: flag scalar as readonly
if ($XSokay) {
$_[0] = $value;
make_sv_readonly($_[0]);
return;
}
# pure-perl method: tied scalar
my $tieobj = eval { tie $_[0], 'Readonly::Scalar', $value };
if ($@) {
croak "$REASSIGN scalar" if substr($@, 0, 43) eq $MODIFY;
die $@; # some other error?
}
return $tieobj;
}
# Deep Readonly array
sub Array (\@;@) {
my $badtype = _is_badtype(ref tied @{$_[0]});
croak "$REASSIGN $badtype" if $badtype;
my $aref = shift;
my @values = @_;
# Recursively check passed elements for references; if any, make them Readonly
foreach (@values) {
if (ref eq 'SCALAR') { Scalar my $v => $$_; $_ = \$v }
elsif (ref eq 'ARRAY') { Array my @v => @$_; $_ = \@v }
elsif (ref eq 'HASH') { Hash my %v => $_; $_ = \%v }
}
# Lastly, tie the passed reference
return tie @$aref, 'Readonly::Array', @values;
}
# Deep Readonly hash
sub Hash (\%;@) {
my $badtype = _is_badtype(ref tied %{$_[0]});
croak "$REASSIGN $badtype" if $badtype;
my $href = shift;
my @values = @_;
# If only one value, and it's a hashref, expand it
if (@_ == 1 && ref $_[0] eq 'HASH') {
@values = %{$_[0]};
}
# otherwise, must have an even number of values
croak $ODDHASH unless (@values % 2 == 0);
# Recursively check passed elements for references; if any, make them Readonly
foreach (@values) {
if (ref eq 'SCALAR') { Scalar my $v => $$_; $_ = \$v }
elsif (ref eq 'ARRAY') { Array my @v => @$_; $_ = \@v }
elsif (ref eq 'HASH') { Hash my %v => $_; $_ = \%v }
}
return tie %$href, 'Readonly::Hash', @values;
}
sub Clone(\[$@%]) {
require Storable;
my $retval = Storable::dclone($_[0]);
$retval = $$retval if ref $retval eq 'REF';
my $reftype = ref $retval;
if ($reftype eq 'SCALAR') {
_SCALAR($retval);
return $$retval;
}
elsif ($reftype eq 'ARRAY') {
_ARRAY(@$retval);
}
elsif ($reftype eq 'HASH') {
_HASH(%$retval);
return %$retval if wantarray;
}
return $retval;
}
# Common entry-point for all supported data types
eval q{sub Readonly} . ($] < 5.008 ? '' : '(\[$@%]@)') . <<'SUB_READONLY';
{
if (ref $_[0] eq 'SCALAR')
{
croak $MODIFY if is_sv_readonly ${$_[0]};
my $badtype = _is_badtype (ref tied ${$_[0]});
croak "$REASSIGN $badtype" if $badtype;
croak "Readonly scalar must have only one value" if @_ > 2;
# Because of problems with handling \$ prototypes declarations like
# Readonly my @a = ... and Readonly my %h = ... are also caught here
croak 'Invalid initialization by assignment'
if @_ == 1 && defined ${$_[0]};
my $tieobj = eval {tie ${$_[0]}, 'Readonly::Scalar', $_[1]};
# Tie may have failed because user tried to tie a constant, or we screwed up somehow.
if ($@)
{
croak $MODIFY if $@ =~ /^$MODIFY at/; # Point the finger at the user.
die "$@\n"; # Not a modify read-only message; must be our fault.
}
return $tieobj;
}
elsif (ref $_[0] eq 'ARRAY')
{
my $aref = shift;
return Array @$aref, @_;
}
elsif (ref $_[0] eq 'HASH')
{
my $href = shift;
croak $ODDHASH if @_%2 != 0 && !(@_ == 1 && ref $_[0] eq 'HASH');
return Hash %$href, @_;
}
elsif (ref $_[0])
{
croak "Readonly only supports scalar, array, and hash variables.";
}
else
{
croak "First argument to Readonly must be a reference.";
}
}
SUB_READONLY
1;
=head1 NAME
Readonly - Facility for creating read-only scalars, arrays, hashes
=head1 Synopsis
use Readonly;
# Deep Read-only scalar
Readonly::Scalar $sca => $initial_value;
Readonly::Scalar my $sca => $initial_value;
# Deep Read-only array
Readonly::Array @arr => @values;
Readonly::Array my @arr => @values;
# Deep Read-only hash
Readonly::Hash %has => (key => value, key => value, ...);
Readonly::Hash my %has => (key => value, key => value, ...);
# or:
Readonly::Hash %has => {key => value, key => value, ...};
# You can use the read-only variables like any regular variables:
print $sca;
$something = $sca + $arr[2];
next if $has{$some_key};
# But if you try to modify a value, your program will die:
$sca = 7;
push @arr, 'seven';
delete $has{key};
# The error message is "Modification of a read-only value attempted"
# Alternate form (Perl 5.8 and later)
Readonly $sca => $initial_value;
Readonly my $sca => $initial_value;
Readonly @arr => @values;
Readonly my @arr => @values;
Readonly %has => (key => value, key => value, ...);
Readonly my %has => (key => value, key => value, ...);
Readonly my $sca; # Implicit undef, readonly value
# Alternate form (for Perls earlier than v5.8)
Readonly \$sca => $initial_value;
Readonly \my $sca => $initial_value;
Readonly \@arr => @values;
Readonly \my @arr => @values;
Readonly \%has => (key => value, key => value, ...);
Readonly \my %has => (key => value, key => value, ...);
=head1 Description
This is a facility for creating non-modifiable variables. This is useful for
configuration files, headers, etc. It can also be useful as a development and
debugging tool for catching updates to variables that should not be changed.
=head1 Variable Depth
Readonly has the ability to create both deep and shallow readonly variables.
If you pass a C<$ref>, an C<@array> or a C<%hash> to corresponding functions
C<::Scalar()>, C<::Array()> and C<::Hash()>, then those functions recurse over
the data structure, marking everything as readonly. The entire structure is
then non-modifiable. This is normally what you want.
If you want only the top level to be readonly, use the alternate (and poorly
named) C<::Scalar1()>, C<::Array1()>, and C<::Hash1()> functions.
Plain C<Readonly()> creates what the original author calls a "shallow"
readonly variable, which is great if you don't plan to use it on anything but
only one dimensional scalar values.
C<Readonly::Scalar()> makes the variable 'deeply' readonly, so the following
snippet kills over as you expect:
use Readonly;
Readonly::Scalar my $ref => { 1 => 'a' };
$ref->{1} = 'b';
$ref->{2} = 'b';
While the following snippet does B<not> make your structure 'deeply' readonly:
use Readonly;
Readonly my $ref => { 1 => 'a' };
$ref->{1} = 'b';
$ref->{2} = 'b';
=head1
=head1 The Past
The following sections are updated versions of the previous authors
documentation.
=head2 Comparison with "use constant"
Perl provides a facility for creating constant values, via the L<constant>
pragma. There are several problems with this pragma.
=over 2
=item * The constants created have no leading sigils.
=item * These constants cannot be interpolated into strings.
=item * Syntax can get dicey sometimes. For example:
use constant CARRAY => (2, 3, 5, 7, 11, 13);
$a_prime = CARRAY[2]; # wrong!
$a_prime = (CARRAY)[2]; # right -- MUST use parentheses
=item * You have to be very careful in places where barewords are allowed.
For example:
use constant SOME_KEY => 'key';
%hash = (key => 'value', other_key => 'other_value');
$some_value = $hash{SOME_KEY}; # wrong!
$some_value = $hash{+SOME_KEY}; # right
(who thinks to use a unary plus when using a hash to scalarize the key?)
=item * C<use constant> works for scalars and arrays, not hashes.
=item * These constants are global to the package in which they're declared;
cannot be lexically scoped.
=item * Works only at compile time.
=item * Can be overridden:
use constant PI => 3.14159;
...
use constant PI => 2.71828;
(this does generate a warning, however, if you have warnings enabled).
=item * It is very difficult to make and use deep structures (complex data
structures) with C<use constant>.
=back
=head1 Comparison with typeglob constants
Another popular way to create read-only scalars is to modify the symbol table
entry for the variable by using a typeglob:
*a = \'value';
This works fine, but it only works for global variables ("my" variables have
no symbol table entry). Also, the following similar constructs do B<not> work:
*a = [1, 2, 3]; # Does NOT create a read-only array
*a = { a => 'A'}; # Does NOT create a read-only hash
=head2 Pros
Readonly.pm, on the other hand, will work with global variables and with
lexical ("my") variables. It will create scalars, arrays, or hashes, all of
which look and work like normal, read-write Perl variables. You can use them
in scalar context, in list context; you can take references to them, pass them
to functions, anything.
Readonly.pm also works well with complex data structures, allowing you to tag
the whole structure as nonmodifiable, or just the top level.
Also, Readonly variables may not be reassigned. The following code will die:
Readonly::Scalar $pi => 3.14159;
...
Readonly::Scalar $pi => 2.71828;
=head2 Cons
Readonly.pm used to impose a performance penalty. It was pretty slow. How
slow? Run the C<eg/benchmark.pl> script that comes with Readonly. On my test
system, "use constant" (const), typeglob constants (tglob), regular read/write
Perl variables (normal/literal), and the new Readonly (ro/ro_simple) are all
about the same speed, the old, tie based Readonly.pm constants were about 1/22
the speed.
However, there is relief. There is a companion module available, Readonly::XS.
You won't need this if you're using Perl 5.8.x or higher.
I repeat, you do not need Readonly::XS if your environment has perl 5.8.x or
higher. Please see section entitled L<Internals|/"Internals"> for more.
=head1 Functions
=over 4
=item Readonly::Scalar $var => $value;
Creates a nonmodifiable scalar, C<$var>, and assigns a value of C<$value> to
it. Thereafter, its value may not be changed. Any attempt to modify the value
will cause your program to die.
A value I<must> be supplied. If you want the variable to have C<undef> as its
value, you must specify C<undef>.
If C<$value> is a reference to a scalar, array, or hash, then this function
will mark the scalar, array, or hash it points to as being Readonly as well,
and it will recursively traverse the structure, marking the whole thing as
Readonly. Usually, this is what you want. However, if you want only the
C<$value> marked as Readonly, use C<Scalar1>.
If $var is already a Readonly variable, the program will die with an error
about reassigning Readonly variables.
=item Readonly::Array @arr => (value, value, ...);
Creates a nonmodifiable array, C<@arr>, and assigns the specified list of
values to it. Thereafter, none of its values may be changed; the array may not
be lengthened or shortened or spliced. Any attempt to do so will cause your
program to die.
If any of the values passed is a reference to a scalar, array, or hash, then
this function will mark the scalar, array, or hash it points to as being
Readonly as well, and it will recursively traverse the structure, marking the
whole thing as Readonly. Usually, this is what you want. However, if you want
only the hash C<%@arr> itself marked as Readonly, use C<Array1>.
If C<@arr> is already a Readonly variable, the program will die with an error
about reassigning Readonly variables.
=item Readonly::Hash %h => (key => value, key => value, ...);
=item Readonly::Hash %h => {key => value, key => value, ...};
Creates a nonmodifiable hash, C<%h>, and assigns the specified keys and values
to it. Thereafter, its keys or values may not be changed. Any attempt to do so
will cause your program to die.
A list of keys and values may be specified (with parentheses in the synopsis
above), or a hash reference may be specified (curly braces in the synopsis
above). If a list is specified, it must have an even number of elements, or
the function will die.
If any of the values is a reference to a scalar, array, or hash, then this
function will mark the scalar, array, or hash it points to as being Readonly
as well, and it will recursively traverse the structure, marking the whole
thing as Readonly. Usually, this is what you want. However, if you want only
the hash C<%h> itself marked as Readonly, use C<Hash1>.
If C<%h> is already a Readonly variable, the program will die with an error
about reassigning Readonly variables.
=item Readonly $var => $value;
=item Readonly @arr => (value, value, ...);
=item Readonly %h => (key => value, ...);
=item Readonly %h => {key => value, ...};
=item Readonly $var;
The C<Readonly> function is an alternate to the C<Scalar>, C<Array>, and
C<Hash> functions. It has the advantage (if you consider it an advantage) of
being one function. That may make your program look neater, if you're
initializing a whole bunch of constants at once. You may or may not prefer
this uniform style.
It has the disadvantage of having a slightly different syntax for versions of
Perl prior to 5.8. For earlier versions, you must supply a backslash, because
it requires a reference as the first parameter.
Readonly \$var => $value;
Readonly \@arr => (value, value, ...);
Readonly \%h => (key => value, ...);
Readonly \%h => {key => value, ...};
You may or may not consider this ugly.
Note that you can create implicit undefined variables with this function like
so C<Readonly my $var;> while a verbose undefined value must be passed to the
standard C<Scalar>, C<Array>, and C<Hash> functions.
=item Readonly::Scalar1 $var => $value;
=item Readonly::Array1 @arr => (value, value, ...);
=item Readonly::Hash1 %h => (key => value, key => value, ...);
=item Readonly::Hash1 %h => {key => value, key => value, ...};
These alternate functions create shallow Readonly variables, instead of deep
ones. For example:
Readonly::Array1 @shal => (1, 2, {perl=>'Rules', java=>'Bites'}, 4, 5);
Readonly::Array @deep => (1, 2, {perl=>'Rules', java=>'Bites'}, 4, 5);
$shal[1] = 7; # error
$shal[2]{APL}='Weird'; # Allowed! since the hash isn't Readonly
$deep[1] = 7; # error
$deep[2]{APL}='Weird'; # error, since the hash is Readonly
=back
=head1 Cloning
When cloning using L<Storable> or L<Clone> you will notice that the value stays
readonly, which is correct. If you want to clone the value without copying the
readonly flag, use the C<Clone> function:
Readonly::Scalar my $scalar => {qw[this that]};
# $scalar->{'eh'} = 'foo'; # Modification of a read-only value attempted
my $scalar_clone = Readonly::Clone $scalar;
$scalar_clone->{'eh'} = 'foo';
# $scalar_clone is now {this => 'that', eh => 'foo'};
The new variable (C<$scalar_clone>) is a mutable clone of the original
C<$scalar>.
=head1 Examples
These are a few very simple examples:
=head2 Scalars
A plain old read-only value
Readonly::Scalar $a => "A string value";
The value need not be a compile-time constant:
Readonly::Scalar $a => $computed_value;
=head2 Arrays/Lists
A read-only array:
Readonly::Array @a => (1, 2, 3, 4);
The parentheses are optional:
Readonly::Array @a => 1, 2, 3, 4;
You can use Perl's built-in array quoting syntax:
Readonly::Array @a => qw/1 2 3 4/;
You can initialize a read-only array from a variable one:
Readonly::Array @a => @computed_values;
A read-only array can be empty, too:
Readonly::Array @a => ();
Readonly::Array @a; # equivalent
=head2 Hashes
Typical usage:
Readonly::Hash %a => (key1 => 'value1', key2 => 'value2');
A read-only hash can be initialized from a variable one:
Readonly::Hash %a => %computed_values;
A read-only hash can be empty:
Readonly::Hash %a => ();
Readonly::Hash %a; # equivalent
If you pass an odd number of values, the program will die:
Readonly::Hash %a => (key1 => 'value1', "value2");
# This dies with "May not store an odd number of values in a hash"
=head1 Exports
Historically, this module exports the C<Readonly> symbol into the calling
program's namespace by default. The following symbols are also available for
import into your program, if you like: C<Scalar>, C<Scalar1>, C<Array>,
C<Array1>, C<Hash>, and C<Hash1>.
=head1 Internals
Some people simply do not understand the relationship between this module and
Readonly::XS so I'm adding this section. Odds are, they still won't understand
but I like to write so...
In the past, Readonly's "magic" was performed by C<tie()>-ing variables to the
C<Readonly::Scalar>, C<Readonly::Array>, and C<Readonly::Hash> packages (not
to be confused with the functions of the same names) and acting on C<WRITE>,
C<READ>, et. al. While this worked well, it was slow. Very slow. Like 20-30
times slower than accessing variables directly or using one of the other
const-related modules that have cropped up since Readonly was released in
2003.
To 'fix' this, Readonly::XS was written. If installed, Readonly::XS used the
internal methods C<SvREADONLY> and C<SvREADONLY_on> to lock simple scalars. On
the surface, everything was peachy but things weren't the same behind the
scenes. In edge cases, code performed very differently if Readonly::XS was
installed and because it wasn't a required dependency in most code, it made
downstream bugs very hard to track.
In the years since Readonly::XS was released, the then private internal
methods have been exposed and can be used in pure perl. Similar modules were
written to take advantage of this and a patch to Readonly was created. We no
longer need to build and install another module to make Readonly useful on
modern builds of perl.
=over
=item * You do not need to install Readonly::XS.
=item * You should stop listing Readonly::XS as a dependency or expect it to
be installed.
=item * Stop testing the C<$Readonly::XSokay> variable!
=back
=head1 Requirements
Please note that most users of Readonly no longer need to install the
companion module Readonly::XS which is recommended but not required for perl
5.6.x and under. Please do not force it as a requirement in new code and do
not use the package variable C<$Readonly::XSokay> in code/tests. For more, see
L<the section on Readonly's new internals/Internals>.
There are no non-core requirements.
=head1 Bug Reports
If email is better for you, L<my address is mentioned below|/"Author"> but I
would rather have bugs sent through the issue tracker found at
http://github.com/sanko/readonly/issues.
=head1 Acknowledgements
Thanks to Slaven Rezic for the idea of one common function (Readonly) for all
three types of variables (13 April 2002).
Thanks to Ernest Lergon for the idea (and initial code) for deeply-Readonly
data structures (21 May 2002).
Thanks to Damian Conway for the idea (and code) for making the Readonly
function work a lot smoother under perl 5.8+.
=head1 Author
Sanko Robinson <sanko@cpan.org> - http://sankorobinson.com/
CPAN ID: SANKO
Original author: Eric J. Roode, roode@cpan.org
=head1 License and Legal
Copyright (C) 2013-2016 by Sanko Robinson <sanko@cpan.org>
Copyright (c) 2001-2004 by Eric J. Roode. All Rights Reserved.
This module is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.
=cut
SCC_DEP_2
,
'System/Agnostic/ErrorHandling.pm' => <<'SCC_DEP_3',
package ErrorHandling;
use warnings;
use strict;
use System::Agnostic::Troubleshooting;
use System::System_Constants;
my $dl = $System_Constants::PATH_DELIMITER;
###################################################
# Function: handleError
###################################################
# When given an error object, this method handles
# the error.
#
# Parameters:
#
# error - error object
#
# Returns:
#
# nothing
###################################################
sub handleError {
my $error = shift;
my $doNotIncludeContent = shift;
my $errorMsg = $error;
my $dumpStackTraceFlag = 0;
Shared::incrementVariable("remoteScanErrorCounter");
if (ref($error) eq "Error::Simple") #if it is type error simple that means it was thrown.
{
$dumpStackTraceFlag = 1;
my $errorText = $error->{"-text"};
my $errorFile = $error->{"-file"};
my $errorLine = $error->{"-line"};
my $errorPackage = $error->{"-package"};
if ($errorFile =~ /.*\/(.*)\.pm$/i)
{
$errorFile = $1;
}
$errorMsg = qq("$errorText")." from $errorPackage found in $errorFile ($errorLine).";
Logger::debug("Error::Simple Error Message Reported - Full Error Message: $error");
}
unless ($doNotIncludeContent){
$errorMsg = _addContentInfo($errorMsg);
}
Logger::error("$errorMsg");
if ($dumpStackTraceFlag)
{
Troubleshooting->printStackTraceToDebug;
}
else{
my ($package, $filename, $line) = caller();
my ($parentPackage, $parentFile, $parentLine) = caller(1);
Logger::debug("Error reported from: $package line: $line, called by $parentPackage, line: $parentLine");
}
}
###################################################
# Function: printWarning
###################################################
# When given an error object, this method handles
# the error.
#
# Parameters:
#
# error - error object
#
# Returns:
#
# nothing
###################################################
sub printWarning {
my $warn = shift;
my $doNotIncludeContent = shift;
my $warnMsg = $warn;
my $dumpStackTraceFlag = 0;
Shared::incrementVariable("remoteScanErrorCounter");
if (ref($warn) eq "Error::Simple") #if it is type error simple that means it was thrown.
{
$dumpStackTraceFlag = 1;
my $warnText = $warn->{"-text"};
my $warnFile = $warn->{"-file"};
my $warnLine = $warn->{"-line"};
if ($warnFile =~ /.*\/(.*)\.pm$/i)
{
$warnFile = $1;
}
$warnMsg = qq("$warnText")." reported via $warnFile ($warnLine).";
Logger::debug("Error::Simple Error Message Reported - Full Error Message: $warn");
}
unless ($doNotIncludeContent){
$warnMsg = _addContentInfo($warnMsg);
}
Logger::warn("$warnMsg");
if ($dumpStackTraceFlag)
{
Troubleshooting->printStackTraceToDebug;
}
else{
my ($package, $filename, $line) = caller();
my ($parentPackage, $parentFile, $parentLine) = caller(1);
Logger::debug("Warning reported from: $package line: $line, called by $parentPackage, line: $parentLine");
}
}
sub _addContentInfo{
my $error = shift;
if($error =~ /Stream Name/){
# looks like the error was thrown from System SCAP and has content info in it already
}
else{
if (Shared::getVariable("current_content_stream") ne ""){
$error = $error . "\n" . " Stream Name : " . Shared::getVariable("current_content_stream");
}
if (Shared::getVariable("current_content_info") ne ""){
$error = $error . "\n" . Shared::getVariable("current_content_info");
}
}
return $error;
}
###################################################
# Function: parseError
###################################################
# When given an error object and an array
# reference, this method extracts the text, file
# and line number from the error and stores each
# piece of data in the referenced array.
#
# Parameters:
#
#error object, array reference
#
# Returns:
#
# nothing (array reference is modified)
###################################################
sub parseError
{
my $error = shift;
my $errorArray = shift;
#BW.. This function is used in form functionality (Form_BaseOptions.pm and Form_Main_Unlocker)... leaving as is ...
# Initialize variables.
my $errorText = $error->{"-text"};
my $errorFile = $error->{"-file"};
my $errorLine = $error->{"-line"};
# Chomp.
chomp($errorText);
chomp($errorFile);
chomp($errorLine);
# Add the error strings to the array.
push(@{$errorArray}, $errorText);
push(@{$errorArray}, $errorFile);
push(@{$errorArray}, $errorLine);
}
###################################################
# Function: checkAccessErrorResult
###################################################
# Checks the error string for the access error.
#
# Parameters:
#
# nothing
#
# Returns:
#
# error string
###################################################
sub checkAccessErrorResult
{
if (Shared::getVariable("accessErrorString") ne "")
{
return Shared::getVariable("accessErrorString");
}
else
{
return "";
}
}
###################################################
# Function: resetAccessErrorResult
###################################################
# Resets the access error result
#
# Parameters:
#
# nothing
#
# Returns:
#
# nothing
###################################################
sub resetAccessErrorResult
{
Shared::setVariable("accessErrorString","");
Logger::debug("reset to [" . Shared::getVariable("accessErrorString") . "]");
}
1;
SCC_DEP_3
,
'System/Agnostic/Troubleshooting.pm' => <<'SCC_DEP_4',
package Troubleshooting;
use warnings;
use strict;
###################################################
# Function: logCaller
###################################################
# Creates debug message showing who called whom.
# Drop calls to logCaller in packages to aid in
# trouble shooting application flow.
#
# Parameters: None - caller levels are gathered herein.
#
# Returns: None
#
###################################################
sub logCaller {
my @called = caller(1);
my @prevLevel = caller(2);
my $parent = (defined($prevLevel[3])) ? $prevLevel[3] : $called[0];
Logger::trace("$parent($called[2]) called --> $called[3].");
}
###################################################
# Function: printStackTraceToDebug
###################################################
# Ever wondered how your code was called, and the
# stack trace to it? Just call this function, and
# view the results in debug.
# Currently used as part of the error handling in
# System functions.
#
# Parameters:
# None
#
# Returns:
# None
###################################################
sub printStackTraceToDebug
{
my $i;
while ( (my @call_details = (caller($i++))) ){
Logger::debug($call_details[1].":".$call_details[2]." in function ".$call_details[3]);
}
}
###################################################
# Function: printStackTraceToScreen
###################################################
# Ever wondered how your code was called, and the
# stack trace to it? Just call this function, and
# view the results in standard out (does not require
# the logger to function.
#
# Parameters:
# None
#
# Returns:
# None
###################################################
sub printStackTraceToScreen
{
my $i;
my $msg;
while ( (my @call_details = (caller($i++))) ){
$msg = $call_details[1].":".$call_details[2]." in function ".$call_details[3];
print "$msg\n";
}
}
###################################################
# Function: printStackTraceToScreen
###################################################
# Ever wondered what perl modules are currently in
# use? Just call this function, and
# view the results in standard out (does not require
# the logger to function.
#
# Parameters:
# None
#
# Returns:
# None
###################################################
sub printModuleUsageToScreen
{
foreach my $name (sort keys %INC) {
printf "%-50s %s\n", $name, $INC{$name};
}
}
###################################################
# Function: printStackTraceToScreen
###################################################
# Ever wondered what perl modules are currently in
# use? Just call this function, and view the debug
# log. This can only be called after the logger
# is initialized.
#
# Parameters:
# None
#
# Returns:
# None
###################################################
sub printModuleUsageToDebug
{
foreach my $name (sort keys %INC) {
Logger::debug($name . " - " . $INC{$name});
}
}
1;
SCC_DEP_4
,
'System/System_Constants.pm' => <<'SCC_DEP_5',
###################################################
# Package: System_Constants.pm
###################################################
# Purpose: Contains constants used throughout the
# application.
###################################################
package System_Constants;
use warnings;
use strict;
use English qw(-no_match_vars);
use Readonly;
########## CHANGE ONLY THESE VARIABLES ##########
my $applicationMainVersion = "5.5"; # Expected format: x.x(.x)
my $applicationBuildVersion = "Beta1";
########## STOP ##########
my $date = "";
my $applicationBuildVersionSafe = "";
my $applicationVersion = "";
if ($applicationBuildVersion eq "")
{
$applicationBuildVersionSafe = "";
$applicationVersion = $applicationMainVersion;
} else
{
$applicationBuildVersionSafe = "_" . $applicationBuildVersion;
$applicationVersion = $applicationMainVersion . " " . $applicationBuildVersion;
}
my $applicationVersionWindows = "";
if ($applicationMainVersion =~ /^\d\.\d\.\d$/) # APPLICATION_MAIN_VERSION has format x.x.x
{
$applicationVersionWindows = $applicationMainVersion . ".0"; # Used only in Windows (x.x.x).x required
} else
{
$applicationVersionWindows = $applicationMainVersion . ".0.0"; # Used only in Windows (x.x).x.x required
}
my $beta = "";
if ($applicationBuildVersion eq "")
{
$beta = 0;
} else
{
$beta = 1;
}
#Group: Application version constants
Readonly our $APPLICATION_MAIN_VERSION => $applicationMainVersion;
Readonly our $APPLICATION_BUILD_VERSION => $applicationBuildVersion;
Readonly our $APPLICATION_BUILD_VERSION_SAFE => $applicationBuildVersionSafe;
Readonly our $APPLICATION_VERSION => $applicationVersion;
Readonly our $APPLICATION_BUILD_NUMBER => "5785-17727";
Readonly our $APPLICATION_VERSION_SAFE => $APPLICATION_MAIN_VERSION . $APPLICATION_BUILD_VERSION_SAFE;
Readonly our $APPLICATION_VERSION_WINDOWS => $applicationVersionWindows;
Readonly our $APPLICATION_CPE => "cpe:/a:niwc:scc:" . $APPLICATION_VERSION_SAFE;
#Group: Beta constants
Readonly our $BETA => "$beta";
Readonly our $SECONDS_IN_DAY => 86400; # Number of seconds in a day.
Readonly our $BETA_DAYS => 90; # Number of days beta is functional.
Readonly our $BETA_THRESHOLD => 604800; #Number of seconds in 7 days for warning of Expiration of BETA
Readonly our $RELEASE_THRESHOLD => 2592000; #Number of seconds in 30 days for warning of Expiration of RELEASE
Readonly our $BETA_START => 1650021098;
my ($sec, $min, $hour, $day,$month,$year) = (localtime($BETA_START))[0,1,2,3,4,5,6];
$month += 1;
$month = ($month =~ /^\d$/) ? "0$month" : $month;
$day = ($day =~ /^\d$/) ? "0$day" : $day;
$year = $year + 1900;
$date = "$year-$month-$day";
Readonly our $RELEASE_DATE => $date;
# Group: Application name constants.
Readonly our $APPLICATION_NAME => "SCAP Compliance Checker";
Readonly our $APPLICATION_NAME_SHORT => "SCC";
Readonly our $APPLICATION_NAME_SHORT_LC => "scc";
Readonly our $APPLICATION_NAME_SHORT_GUI => $APPLICATION_NAME_SHORT;
Readonly our $APPLICATION_NAME_SHORT_GUI_LC => $APPLICATION_NAME_SHORT_LC;
Readonly our $APPLICATION_NAME_SHORT_CLUI => "C" . $APPLICATION_NAME_SHORT;
Readonly our $APPLICATION_NAME_SHORT_CLUI_LC => "c" . $APPLICATION_NAME_SHORT_LC;
Readonly our $APPLICATION_DESCRIPTION => "SCAP Compliance Checker"; # <--- Used in Windows file information.
Readonly our $APPLICATION_WINDOW_TITLE => $APPLICATION_NAME . " " . $APPLICATION_VERSION;
Readonly our $APPLICATION_URL => "https://www.niwcatlantic.navy.mil/scap/";
# Group: Application name constants for the unlocker application.
# Registry Functionality Constants
# If a call to a registry function (such as getRegValue or getHiveObject) needs to look at 32 bit area of registry,
# specifically the Wow6432Node of the registry, this constant must be used. See functionality in System::Registry.
Readonly our $WOW6432NODE => "Wow6432Node";
# Service Variables
Readonly our $APPLICATION_SERVICE_NAME => "SCAP Compliance Checker Service";
Readonly our $APPLICATION_SERVICE_NAME_SHORT => "SCC_Service32";
Readonly our $APPLICATION_SERVICE_DESCRIPTION => "SCC Service for scanning automation"; # <--- Used in Windows file information.
Readonly our $APPLICATION_SERVICE_TRAY_NAME => "SCAP Compliance Checker Service Tray Icon";
Readonly our $APPLICATION_SERVICE_NAME_TRAY_SHORT => "SCC_Tray";
Readonly our $APPLICATION_SERVICE_TRAY_DESCRIPTION => "SCC Service Tray executable for viewing SCC Service information"; # <--- Used in Windows file information.
Readonly our $APPLICATION_SERVICE_CONFIG_NAME => "SCAP Compliance Checker Service Editor";
Readonly our $APPLICATION_SERVICE_NAME_CONFIG_SHORT => "SCCConfigEditor";
Readonly our $APPLICATION_SERVICE_DESCRIPTION_CONFIG => "SCC Service serviceOptions.xml editor"; # <--- Used in Windows file information.
# Unlocker application name
Readonly our $APPLICATION_NAME_UNLOCKER => "Unlocker for " . $APPLICATION_NAME;
Readonly our $APPLICATION_NAME_UNLOCKER_SHORT => "Unlocker";
Readonly our $APPLICATION_DESCRIPTION_UNLOCKER => "Provides unlock codes for " . $APPLICATION_NAME; # <--- Used in Windows file information.
Readonly our $APPLICATION_WINDOW_TITLE_UNLOCKER => $APPLICATION_NAME . " " . $APPLICATION_VERSION;
# Group: SCAP version constants.
Readonly our $SCAP_VERSION => "1.0, 1.1, 1.2, 1.3";
Readonly our $PRINTABLE_OVAL_VERSIONS => "5.3 -> 5.11.2";
Readonly our $OVAL_VERSION => "5.11.2"; # Note, this system constant is used in System SCAP so cannot be a multiple value like 5.3 -> 5.10.1
Readonly our $XCCDF_VERSION => "1.1.4, 1.2";
Readonly our $CPE_VERSION => "2.3";
Readonly our $CCE_VERSION => "5.0";
Readonly our $OCIL_VERSION => "2.0";
# Max number of characters a filename can be. Windows can handle 214, Unix 256
Readonly our $MAXFILENAMELENGTH => "70";
Readonly our $MAX_WINDOWS_FILEPATH_LENGTH => "256";
# WMI constants.
Readonly our $WBEMFLAGRETURNIMMEDIATELY => 0x10;
Readonly our $WBEMFLAGFORWARDONLY => 0x20;
Readonly our $PATH_DELIMITER => ($OSNAME =~ /^mswin/i) ? '\\' : "/";
Readonly our $DOUBLE_PATH_DELIMITER => $PATH_DELIMITER . $PATH_DELIMITER;
# Windows permissions constants.
Readonly our $FILE_SHARE_READ => 0x1; # Bit mask for enabling permission to read a shared file
# Font constants.
Readonly our $FONT_SOLARIS => "Sans 10 normal";
# Miscellaneous constants.
Readonly our $HTTPSTRING => "http://";
Readonly our $APPLICATION_SHARED_KEY => "8008cfe33264014674ca56bc60a24075b2f2bf5a63921519cd75e2a61e708f49"; # <--- Key shared between applications.
Readonly our $APPLICATION_LANGUAGE => "English"; # <--- Used in Windows file information.
Readonly our $APPLICATION_DEVELOPER => "NIWC Atlantic";
Readonly our $UNKNOWN_COMPLIANCE_STATUS => "Unknown"; # Used when the compliance score doesn't fit into any existing threshold. Change this in XLS code if changed here.
Readonly our $TEXT_HEADER_LENGTH => 70;
Readonly our $BREAK_LINE_LENGTH => 30;
Readonly our $SMALL_BREAK_LINE_LENGTH => 3;
Readonly our $PADDING_LENGTH => 25;
Readonly our $SSC_EMAIL => "scc.fct\@navy.mil";
Readonly::Hash our %AUDIT_SETTINGS => (
0 => "AUDIT_NONE",
1 => "AUDIT_SUCCESS",
2 => "AUDIT_FAILURE",
3 => "AUDIT_SUCCESS_FAILURE");
Readonly::Array our @CREDITS => (
"The development of SCC was originally funded by the Internal Revenue Service (IRS), with later funding from the National Security Agency (NSA), and is currently funded by Defense Information Systems Agency (DISA).
Special thanks to all of our Beta testers! If you would like to assist with Beta testing, please email us.");
#### Contants below were originally in SPAWAR::System_Constants ####
# Temporary constant to ID operating system family.
# Eventually, this will need to be put into the build script
# so that each OS gets set correctly in its build.
Readonly our $OS_FAMILY => 'Linux'; # options might be MS, Linux, UNIX, Mac???
# Group: Bitwise constants
Readonly our $COMPLEMENT => 0xFFFFFFFF; # Used for bitwise complements
# Standard permission constants used with access masks
Readonly our $STANDARD_DELETE => 0x00010000; # Access mask for delete
Readonly our $STANDARD_READ_CONTROL => 0x00020000; # Access mask for read control
Readonly our $STANDARD_WRITE_DAC => 0x00040000; # Access mask for write DAC
Readonly our $STANDARD_WRITE_OWNER => 0x00080000; # Access mask for write owner
Readonly our $STANDARD_SYNCHRONIZE => 0x00100000; # Access mask for synchronizing
Readonly our $ACCESS_SYSTEM_SECURITY => 0x01000000; # Access mask for accessing system security
Readonly our $GENERIC_READ => 0x80000000; # Access mask for read permssions
Readonly our $GENERIC_WRITE => 0x40000000; # Access mask for write permissions
Readonly our $GENERIC_EXECUTE => 0x20000000; # Access mask for execute permissions
Readonly our $GENERIC_ALL => 0x10000000; # Access mask for all permissions
Readonly our $PRINTER_ACCESS_ADMINISTER => 0x00000004;
Readonly our $PRINTER_ACCESS_USE => 0x00000008;
Readonly our $JOB_ACCESS_ADMINISTER => 0x00000010;
Readonly our $JOB_ACCESS_READ => 0x00000020;
# File/directory permission constants used with access masks
Readonly our $FILE_READ_DATA => 0x0001;
Readonly our $FILE_WRITE_DATA => 0x0002;
Readonly our $FILE_APPEND_DATA => 0x0004;
Readonly our $FILE_READ_EA => 0x0008;
Readonly our $FILE_WRITE_EA => 0x0010;
Readonly our $FILE_EXECUTE => 0x0020;
Readonly our $FILE_DELETE_CHILD => 0x0040;
Readonly our $FILE_READ_ATTRIBUTES => 0x0080;
Readonly our $FILE_WRITE_ATTRIBUTES => 0x0100;
Readonly our $FILE_GENERIC_READ => $FILE_READ_ATTRIBUTES | $FILE_READ_DATA | $FILE_READ_EA | $STANDARD_READ_CONTROL | $STANDARD_SYNCHRONIZE;
Readonly our $FILE_GENERIC_WRITE => $FILE_APPEND_DATA | $FILE_WRITE_ATTRIBUTES | $FILE_WRITE_DATA | $FILE_WRITE_EA | $STANDARD_READ_CONTROL | $STANDARD_SYNCHRONIZE;
Readonly our $FILE_GENERIC_EXECUTE => $FILE_READ_ATTRIBUTES | $STANDARD_READ_CONTROL | $FILE_EXECUTE | $STANDARD_SYNCHRONIZE;
Readonly our $FILE_GENERIC_ALL => $FILE_GENERIC_READ | $FILE_GENERIC_WRITE | $FILE_GENERIC_EXECUTE; # Possibly wrong.
# Registry permission constants used with access masks
Readonly our $KEY_QUERY_VALUE => 0x0001;
Readonly our $KEY_SET_VALUE => 0x0002;
Readonly our $KEY_CREATE_SUB_KEY => 0x0004;
Readonly our $KEY_ENUMERATE_SUB_KEYS => 0x0008;
Readonly our $KEY_NOTIFY => 0x0010;
Readonly our $KEY_CREATE_LINK => 0x0020;
Readonly our $KEY_WOW64_64KEY => 0x0100;
Readonly our $KEY_WOW64_32KEY => 0x0200;
Readonly our $KEY_WOW64_RES => 0x0300;
Readonly our $KEY_READ => 0x20019; # Hard-coded combination of other flags.
# Constants used for volume tests
Readonly our $FILE_CASE_SENSITIVE_SEARCH => 0x00000001;
Readonly our $FILE_CASE_PRESERVED_NAMES => 0x00000002;
Readonly our $FILE_UNICODE_ON_DISK => 0x00000004;
Readonly our $FILE_PERSISTENT_ACLS => 0x00000008;
Readonly our $FILE_FILE_COMPRESSION => 0x00000010;
Readonly our $FILE_VOLUME_QUOTAS => 0x00000020;
Readonly our $FILE_SUPPORTS_SPARSE_FILES => 0x00000040;
Readonly our $FILE_SUPPORTS_REPARSE_POINTS => 0x00000080;
Readonly our $FILE_SUPPORTS_REMOTE_STORAGE => 0x00000100;
Readonly our $FILE_VOLUME_IS_COMPRESSED => 0x00008000;
Readonly our $FILE_SUPPORTS_OBJECT_IDS => 0x00010000;
Readonly our $FILE_SUPPORTS_ENCRYPTION => 0x00020000;
Readonly our $FILE_NAMED_STREAMS => 0x00040000;
Readonly our $FILE_READ_ONLY_VOLUME => 0x00080000;
Readonly our $FILE_SEQUENTIAL_WRITE_ONCE => 0x00100000;
Readonly our $FILE_SUPPORTS_TRANSACTIONS => 0x00200000;
Readonly our $FILE_SUPPORTS_HARD_LINKS => 0x00400000;
Readonly our $FILE_SUPPORTS_EXTENDED_ATTRIBUTES => 0x00800000;
Readonly our $FILE_SUPPORTS_OPEN_BY_FILE_ID => 0x01000000;
Readonly our $FILE_SUPPORTS_USN_JOURNAL => 0x02000000;
# Bitmasks for printable standard effective permissions.
Readonly our $DELETE => $STANDARD_DELETE | $STANDARD_SYNCHRONIZE;
Readonly our $TAKE_OWNERSHIP => $STANDARD_WRITE_OWNER | $STANDARD_SYNCHRONIZE;
Readonly our $CHANGE_PERMISSIONS => $STANDARD_WRITE_DAC | $STANDARD_SYNCHRONIZE;
Readonly our $NO_ACCESS => 0;
# Bitmasks for printable file effective permissions.
Readonly our $FULL_CONTROL_FILE => $STANDARD_DELETE | $STANDARD_READ_CONTROL | $STANDARD_WRITE_DAC | $STANDARD_WRITE_OWNER | $STANDARD_SYNCHRONIZE | $FILE_READ_DATA | $FILE_WRITE_DATA | $FILE_APPEND_DATA | $FILE_READ_EA | $FILE_WRITE_EA | $FILE_EXECUTE | $FILE_DELETE_CHILD | $FILE_READ_ATTRIBUTES | $FILE_WRITE_ATTRIBUTES;
Readonly our $MODIFY_FILE => $STANDARD_DELETE | $STANDARD_READ_CONTROL | $STANDARD_SYNCHRONIZE | $FILE_READ_DATA | $FILE_WRITE_DATA | $FILE_APPEND_DATA | $FILE_READ_EA | $FILE_WRITE_EA | $FILE_EXECUTE | $FILE_READ_ATTRIBUTES | $FILE_WRITE_ATTRIBUTES;
Readonly our $READ_WRITE_EXECUTE_FILE => $STANDARD_READ_CONTROL | $STANDARD_SYNCHRONIZE | $FILE_READ_DATA | $FILE_WRITE_DATA | $FILE_APPEND_DATA | $FILE_READ_EA | $FILE_WRITE_EA | $FILE_EXECUTE | $FILE_READ_ATTRIBUTES | $FILE_WRITE_ATTRIBUTES;
Readonly our $READ_EXECUTE_FILE => $STANDARD_READ_CONTROL | $STANDARD_SYNCHRONIZE | $FILE_READ_DATA | $FILE_READ_EA | $FILE_EXECUTE | $FILE_READ_ATTRIBUTES;
Readonly our $READ_FILE => $STANDARD_READ_CONTROL | $STANDARD_SYNCHRONIZE | $FILE_READ_DATA | $FILE_READ_EA | $FILE_READ_ATTRIBUTES;
Readonly our $WRITE_FILE => $STANDARD_SYNCHRONIZE | $FILE_WRITE_DATA | $FILE_APPEND_DATA | $FILE_WRITE_EA | $FILE_WRITE_ATTRIBUTES;
Readonly our $EXECUTE_FILE => $STANDARD_SYNCHRONIZE | $FILE_EXECUTE;
# Bitmasks for printable registry effective permissions.
Readonly our $FULL_CONTROL_REGISTRY => $KEY_QUERY_VALUE | $KEY_SET_VALUE | $KEY_CREATE_SUB_KEY | $KEY_ENUMERATE_SUB_KEYS | $KEY_NOTIFY | $KEY_CREATE_LINK | $STANDARD_DELETE | $STANDARD_WRITE_DAC | $STANDARD_WRITE_OWNER | $STANDARD_READ_CONTROL;
Readonly our $READ_REGISTRY => $KEY_QUERY_VALUE | $KEY_ENUMERATE_SUB_KEYS | $KEY_NOTIFY | $STANDARD_READ_CONTROL;
# Bitmasks for SharedResource permission
Readonly our $ACCESS_NONE => 0x0000;
Readonly our $ACCESS_READ => 0x0001;
Readonly our $ACCESS_WRITE => 0x0002;
Readonly our $ACCESS_CREATE => 0x0004;
Readonly our $ACCESS_EXEC => 0x0008;
Readonly our $ACCESS_DELETE => 0x0010;
Readonly our $ACCESS_ATRIB => 0x0020;
Readonly our $ACCESS_PERM => 0x0040;
Readonly our $ACCESS_ALL => 0x007f;
# Bitmasks for SharedResource types
Readonly our $STYPE_DISKTREE => 0x00;
Readonly our $STYPE_DISKTREE_SPECIAL => 0x80000000;
Readonly our $STYPE_DISKTREE_TEMPORARY => 0x40000000;
Readonly our $STYPE_DISKTREE_SPECIAL_TEMPORARY => 0xC0000000;
Readonly our $STYPE_PRINTQ => 0x010;
Readonly our $STYPE_PRINTQ_SPECIAL => 0x80000001;
Readonly our $STYPE_PRINTQ_TEMPORARY => 0x40000001;
Readonly our $STYPE_PRINTQ_SPECIAL_TEMPORARY => 0xC0000001;
Readonly our $STYPE_DEVICE => 0x02;
Readonly our $STYPE_DEVICE_SPECIAL => 0x80000002;
Readonly our $STYPE_DEVICE_TEMPORARY => 0x40000002;
Readonly our $STYPE_DEVICE_SPECIAL_TEMPORARY => 0xC0000002;
Readonly our $STYPE_IPC => 0x03;
Readonly our $STYPE_IPC_SPECIAL => 0x80000003;
Readonly our $STYPE_IPC_TEMPORARY => 0x40000003;
Readonly our $STYPE_IPC_SPECIAL_TEMPORARY => 0xC0000003;
Readonly our $STYPE_SPECIAL => 0x80000000;
Readonly our $STYPE_TEMPORARY => 0x40000000;
# Hash conntaining bitmask constants for effective permissions.
# Group: Global
# Hash containing bitmask constants for effective permission.
Readonly::Hash our %PRINTABLE_EFFECTIVE_PERMISSIONS => (
FULL_CONTROL_FILE => "Full Control",
MODIFY_FILE => "Modify",
READ_WRITE_EXECUTE_FILE => "Read, Write & Execute",
READ_EXECUTE_FILE => "Read & Execute",
READ_FILE => "Read",
WRITE_FILE => "Write",
EXECUTE_FILE => "Execute",
FULL_CONTROL_REGISTRY => "Full Control",
READ_REGISTRY => "Read",
DELETE => "Delete",
TAKE_OWNERSHIP => "Take Ownership",
CHANGE_PERMISSIONS => "Change Permissions",
NO_ACCESS => "No Access"
);
# Group: UserInterfaceMode
Readonly our $CSCC_UIM => 0;
Readonly our $SCC_UIM => 1;
# Group: Win32LocalSecurityPolcy
Readonly our $WIN32_LOCALSECURITY_POLICY_LIB_VERSION => 0.6;
# Scan Session Schema version
Readonly our $SCAN_SESSION_SCHEMA_VERSION => 0.8;
Readonly our $CREDENTIAL_SCHEMA_VERSION => 0.98;
Readonly our $OCIL_SCHEMA_VERSION => 0.95;
1;
SCC_DEP_5
,
);
for my $rel (keys %__scc_dep_files) {
__scc_write_file("$__scc_support_dir/$rel", $__scc_dep_files{$rel});
}
}
use Error;
use Error::Simple;
use Readonly;
use System::Agnostic::ErrorHandling;
use System::Agnostic::Troubleshooting;
use System::System_Constants;
my $__scc_fixture_dir = "$__scc_support_dir/fixtures";
{
my %__scc_fixture_files = (
'etc/shadow' => <<'SCC_FIXTURE_0',
root:!:19000:0:99999:7:::
daemon:*:19000:0:99999:7:::
^.*$:!!SYNTHETIC-FIXTURE-NOT-A-REAL-HASH!!:19000:0:99999:7:::
SCC_FIXTURE_0
,
);
for my $rel (keys %__scc_fixture_files) {
__scc_write_file("$__scc_fixture_dir/$rel", $__scc_fixture_files{$rel});
}
}
# shadow_object -> Probe_Shadow.pm::_getUsers
sub scc_check_0 {
my @allUsers;
if (-e "$__scc_fixture_dir/etc/shadow") {
open(my $ipf_fh,"<","$__scc_fixture_dir/etc/shadow") || throw Error::Simple("Failed to open /etc/shadow, $!.");
while (my $userLine = <$ipf_fh>) {
if ($userLine =~ /^(.*?):.*$/) { push @allUsers, $1; }
else {
throw Error::Simple("Failed to parse user from shadow file line: $userLine.");
}
}
close $ipf_fh;
}
else { ErrorHandling::handleError( "Expected to find the shadow password file at '/etc/shadow' and did not."); }
return @allUsers;
}
my $r0 = eval { scc_check_0(); }; if ($@) { print STDERR "check 0 died: $@"; exit 1; }
my $overall = ($r0);
print $overall ? "PASS\n" : "FAIL\n";
exit($overall ? 0 : 1);