Advanced-Config
view release on metacpan or search on metacpan
lib/Advanced/Config/Options.pm view on Meta::CPAN
Internal spaces are OK when non-numeric values are expected. In most cases
values with a length of B<0> or B<undef> are not allowed.
Just be aware that some combinations of I<Read> options may result in this
module being unable to parse the config file. If you encounter such a
combination open a CPAN ticket and I'll see what I can do about it. But some
combinations may just be too ambiguous to handle.
Also note that some I<Read> options have B<left> and B<right> variants. These
options are used in pairs and both must anchor the target in order for the rule
to be applied to it. These start/end anchors can be set to the same string or
different strings. Your choice.
=head2 Tag(s) Best Set in Call to the Constructor new().
While not required to set these options during the call to B<new>, changing
their settings later on can cause unexpected issues if you are not careful.
But it's still recommended that most I<Read> Options be set during the call to
B<new> to avoid having to keep on resetting them all the time and limit these
later changes to handle exceptions to your defaults.
=over 4
B<tag_case> - Config files are made up of tag/value pairs. This option controls
whether the tags are case sensitive (B<0>, the default) or case insensitive
(B<1>). IE do tags B<ABC> and B<abc> represent the same tag or not? So if set,
all tags are assumed to be in lower case for the get/set methods!
=back
=head2 Generic Read Options
These options are also usually set during the call to B<new>, but setting them
later on doesn't produce strange behavior if you change the settings later on.
=over 4
B<croak> - This controls what happens when a function hits an unexpected error
while parsing the config file. Set to B<0> to return an error code (default),
B<-1> to return an error code and print a warning to your screen, B<1> to call
die and terminate your program.
B<export> - Tells if we should export all tag/value pairs to perl's %ENV hash
or not. The default is B<0> for I<No>. Set to B<1> if you want this to happen.
But if set, it reverses the meaning of the B<export_lbl> option defined later
on.
B<use_utf8> - Defaults to B<0>. Set to B<1> if the config file was created
using utf8 encoding. (IE Unicode or Wide Characters.) Guessing this
setting wrong means the file will be unusable as a config file.
B<disable_quotes> - Defaults to B<0>. Set to B<1> if you want to disallow
the stripping of balanced quotes in your config files.
B<disable_variables> - Defaults to B<0>. Set to B<1> if you want to disable
variable expansion in your config files when they are loaded into memory.
B<disable_variable_modifiers> - Defaults to B<0>. Set to B<1> if you want to
disable this feature. See L<http://wiki.bash-hackers.org/syntax/pe> for more
details. This feature allows you to put logic into your config files via
your variable definitions. Automatically disabled when variables are
disabled. Useful when you put a lot of special chars into your variable
names.
B<disable_decryption> - Defaults to B<0>. Set to B<1> if you want to disable
decrypting values that have been marked as encrypted. If a variable references
an encrypted value while disable_decription is active, that variable isn't
expanded.
=cut
# B<enable_backquotes> - Defaults to B<0>. Set to B<1> if you want to enable
# this feature. It's disabled by default since it can be considered a security
# hole if an unauthorized user can modify your config file or your code.
=pod
B<trap_recursion> - Defaults to B<0>. Set to B<1> if you want to treat
recursion as a fatal error when loading a config file. By default it just
ignores the recursion request to prevent infinite loops.
B<source_cb_opts> - A work area for holding values between calls to the
callback function. This is expected to be a hash reference to provide any
needed configuration values needed to parse the next config file. This way
you can avoid global variables. Defaults to an empty hash reference.
B<source_cb> - An optional callback routine called each time your config file
sources in another config file. It's main use is when the I<Read Options>
and/or I<Date Format Options> required to parse each config file change between
files. It's automatically called right before the sourced in file is opened up
for parsing.
Once the new file is sourced in, it inherits most of the options currently used
unless you override them. The only ones not inherited deal with decryption.
Here is the callback function's expected definition:
my ($rOpts, $dOpts) = source_callback_func ($file[, $cbOpts]);
$file --> The file being sourced in.
$cbOpts --> A hash reference containing values needed by your callback
function to decide what options are required to source in the
requested file. You may update the contents of this hash to
preserve info between calls. This module will "never" examine
the contents of this hash!
$rOpts --> A reference to the "Read Options" hash used to parse the file
you want to source in. Returns "undef" if the options don't
change. The returned options override what's currently in use by
"load_config" when loading the current file.
$dOpts --> A reference to the "Date Formatting Options" hash used to tell how
to format the special date variables. Returns "undef" if the
options don't change. The returned options override what's
currently in use by "load_config" when loading the current file.
=back
=head2 Parse Read Options
lib/Advanced/Config/Options.pm view on Meta::CPAN
instruction to source in another config file (similar to how it works in a
I<Unix> shell script.) Another common setting for this option is "include".
B<section_left> & B<section_right> - This pair is used to anchor breaking
your config file into multiple independent sections. The defaults are B<[>
and B<]>.
B<variable_left> & B<variable_right> - This pair is used to anchor a variable
definition. Any value between these anchors will be a variable name and it's
value will be used instead, unless you've disabled this expansion. The defaults
are B<${> and B<}>. If you override these anchors to both have the same value,
then the optional variable modifiers are not supported nor are nested variables.
B<quote_left> & B<quote_right> - This pair is used to define what balanced
quotes look like in your config file. By default, it allows you to use either
B<"> or B<'> as a matching pair. But if you override one of them you must
override both. And in that case it can only be with literal values. If the
quotes surrounding a tag's value are balanced, the quotes will be automatically
removed from the value. If they are unbalanced the quotes will not be removed.
=cut
# B<backquote_left> & B<backquote_right> - This pair is used to surround a command
# you wish to run, just like in Perl itself. What the command writes to STDOUT
# becomes the tag's value. Assumes the command takes nothing from STDIN. Due to
# security concerns you must explicitly set these values yourself before they are
# usable. A good value is the backqoute itself (B<`>). But use something else
# if you don't want to be so obvious about it.
=pod
=back
=head2 Modifiers in the trailing Comments for tag/value pairs.
In some cases we need to handle exceptions to the rule. So we define labels
to tell this module that we need to apply special rules to this tag/value pair.
These labels may appear anywhere in the comment. So when looking for "EXPORT",
it will match "B<# Please EXPORT me.>", but won't match "B<# EXPORTED>". This
allows you to put multiple labels in a single comment if needed.
As long as the text is surrounded by white space or punctuation a match will
be found. It is strongly recommended that you don't use punctuation in your
label when you override one with values of your own.
Here are the labels you may override.
=over 4
B<export_lbl> - Defaults to "B<EXPORT>". Tells this module to export this
particular tag/value pair to perl's B<%ENV> hash. If the I<export> option
was also set, it inverts the meaning of this label to mean don't export it!
You can also gain the same functionality by doing one of the following
instead:
export tag = value # Optional unix type shell script prefix.
set tag = value # Optional windows type batch file prefix.
These prefixes allow you to easily use shell/batch files as config files if
they contain no logic.
B<hide_lbl> - Defaults to "B<HIDE>". Tells this module that this tag's value
contains sensitive information. So when fish logging is turned on, this module
will never write it to these logs. If the parser thinks a tag's name suggests
it's a password, it will assume that you put this label in the comment. This
is what triggers the sensitive/mask arguments and return values that some
methods use.
B<encrypt_lbl> - Defaults to "B<ENCRYPT>". Tells this module that you are
waiting for this tag's value to be encrypted in the config file. It assumes
the value is still in clear text. When present it assumes the value is
sensitive as well.
B<decrypt_lbl> - Defaults to "B<DECRYPT>". Tells this module that this value
has already been encrypted and needs to be decrypted before it is used. When
present it assumes that the value is sensitive as well.
B<source_file_section_lbl> - Defaults to "B<DEFAULT>". Tells this module to
use the current section as the default/unlabeled section in the file being
source in. This new value will be inherited should the sourced in file source
in any further files.
=back
=head2 Encryption/Decryption options. (or Encode/Decode options.)
The following options deal with the encryption/decryption of the contents of a
config file. Only the encryption of a tag's value is supported. And this is
triggered by the appropriate label in the comment on the same line after the
value.
Unless you use the B<encrypt_cb> option, this module isn't using true
encryption. It's more a complex obscuring of the tag's value making it very
difficult to retrieve a tag's value without using this module to examine the
config file's contents. It's main use is to prevent casual browsers of your
file system from being able to examine your config files using their favorite
editor to capture sensitive data from your config files.
By default, the I<basename> of the config file's name and the tag's name are the
keys used to encode each value in the config file. This means that each tag's
value in the config file uses a different key to obscure it. But by using just
the defaults, anyone using this module may automatically decode everything in
the config file just by writing a perl program that uses this module.
But by using the options below, you gain additional security even without using
true encryption. Since if you don't know the options used, you can't easily
decode each tag's value even by examining the code. Just be aware that using
too many keys with too similar values could cancel each other out and weaken
the results.
These options are ignored if you've disabled decryption.
When you source in another file in your config files, the current values
for B<alias>, B<pass_phrase> and B<encrypt_by_user> are not inherited. But the
remaining options are. See option B<source_cb> if you need to set them in this
case.
=over 4
B<alias> - Defaults to the empty string. (Meaning no alias provided.) This
option is used to override using the file's I<basename> as one of the
encryption/decryption keys with the I<basename> of the value you provide here.
If you encrypt a file with no I<alias>, and then rename the config file, you
lib/Advanced/Config/Options.pm view on Meta::CPAN
gmtime. The default is B<0>.
=back
=head1 ==================================================================
=head2 Z<>
=head1 FUNCTIONS
As a reminder, there is no need to directly call any of the following functions.
They are documented mostly for the benefit of the developer who uses them to
implement the internals to L<Advanced::Config>.
Most of them are too specialized to be of much use to you.
=over 4
=cut
package Advanced::Config::Options;
use strict;
use warnings;
use vars qw( @ISA @EXPORT @EXPORT_OK $VERSION );
use Exporter;
$VERSION = "1.14";
@ISA = qw( Exporter );
@EXPORT = qw( get_read_opts get_get_opts get_date_opts
apply_get_rules
is_assign_spaces
using_default_quotes
convert_to_regexp_string
convert_to_regexp_modifier
should_we_hide_sensitive_data
make_it_sensitive
sensitive_cnt
croak_helper
set_special_date_vars
change_special_date_vars
);
@EXPORT_OK = qw( );
use Advanced::Config::Date;
use Fred::Fish::DBUG 2.09 qw / on_if_set ADVANCED_CONFIG_FISH /;
# The name of the default section ... (even if no sections are defined!)
use constant DEFAULT_SECTION_NAME => "main"; # Must be in lower case!
my %default_read_opts;
my %default_get_opts;
my %default_date_opts;
my @hide_from_fish;
# ==============================================================
# Get who you're currrently logged in as.
# Put here to avoid circular references between modules.
sub _get_user_id
{
DBUG_ENTER_FUNC ( @_ );
my $user = "??";
eval {
# Mostly used on unix like systms.
$user = getpwuid ($<) || "??";
};
if ( $@ ) {
# Can't use on unix due to sudo issue returns wrong user.
$user = getlogin () || "??";
}
DBUG_RETURN ($user);
}
# ==============================================================
# A stub of the source callback function ...
sub _source_callback_stub
{
DBUG_ENTER_FUNC ( @_ );
my $file = shift;
my $opts = shift;
DBUG_RETURN ( undef, undef );
}
# ==============================================================
# A stub of the encryption/decryption callback function ...
sub _encryption_callback_stub
{
DBUG_MASK_NEXT_FUNC_CALL (2); # Mask $value!
DBUG_ENTER_FUNC ( @_ );
my $mode = shift;
my $tag = shift;
my $value = shift; # Clear text sensitive value ...
my $file = shift;
my $cbOpts = shift;
DBUG_MASK ( 0 );
DBUG_RETURN ( $value );
}
# ==============================================================
# Initialize the global hashes with their default values ...
BEGIN
{
DBUG_ENTER_FUNC ();
# ---------------------------------------------------------------------
# Make sure no hash value is undef !!!
# ---------------------------------------------------------------------
# You can only add to this list, you can't remove anything from it!
# See should_we_hide_sensitive_data () on how this list is used.
DBUG_PRINT ("INFO", "Initializing the tag patterns to hide from fish ...");
push ( @hide_from_fish, "password" );
push ( @hide_from_fish, "pass" );
push ( @hide_from_fish, "pwd" );
# ---------------------------------------------------------------------
DBUG_PRINT ("INFO", "Initializing the READ options global hash ...");
# Should always be set in the constructor ...
$default_read_opts{tag_case} = 0; # Case sensitive tags.
# The generic options ...
my %src_empty;
$default_read_opts{croak} = 0; # Don't croak by default.
$default_read_opts{export} = 0; # Don't export any tag/val pairs.
$default_read_opts{use_utf8} = 0; # Doesn't support utf8/Unicode/Wide Chars.
$default_read_opts{disable_quotes} = 0; # Don't disable balanced quotes.
lib/Advanced/Config/Options.pm view on Meta::CPAN
if ( $get_opts->{split} && $get_opts->{sort} ) {
if ( $is_all_numbers ) {
@{$result{VALUE}} = sort { $a <=> $b } @{$result{VALUE}};
} else {
@{$result{VALUE}} = sort ( @{$result{VALUE}} );
}
@{$result{VALUE}} = reverse ( @{$result{VALUE}} ) if ( $get_opts->{sort} < 0 );
}
DBUG_RETURN ( \%result );
}
# ==============================================================
=item $boolean = is_assign_spaces ( $ropts )
Tells if the assignment operator selected is the special case of using spaces
to separate the tag/value pair. Only returns true if it's B<\\s>.
=cut
# No fish since it's called so frequently, over & over again ...
sub is_assign_spaces
{
# Checking the ${rOpts} settings ...
return ( exists $_[0]->{assign} && $_[0]->{assign} eq "\\s" );
}
# ==============================================================
=item $boolean = using_default_quotes ( $ropts )
This function tells if you are currently using the default quotes. This is the
only case where there can be multiple values for the quote string anchors. All
other cases allow only for a single value for each of the quote string anchors.
=cut
sub using_default_quotes
{
DBUG_ENTER_FUNC ( @_ );
my $ropts = shift;
my $def = 0; # Assume not using the default quotes ...
unless ( $ropts->{disable_quotes} ) {
if ( $ropts->{quote_left} eq $ropts->{quote_right} ) {
if ( $ropts->{quote_left} eq "['\"]" ||
$ropts->{quote_left} eq "[\"']" ) {
$def = 1;
}
}
}
DBUG_RETURN ( $def );
}
# ==============================================================
=item $str = convert_to_regexp_string ( $string[, $no_logs] )
Converts the passed string that may contain special chars for a Perl RegExp
into something that is a literal constant value to Perl's RegExp engine by
turning these problem chars into escape sequences.
It then returns the new string.
If I<$no_logs> is set to a non-zero value, it won't write anything to the logs.
=cut
sub convert_to_regexp_string
{
my $no_fish = $_[1];
DBUG_ENTER_FUNC ( @_ ) unless ( $no_fish );;
my $str = shift;
# The 8 problem chars with special meaning in a RegExp ...
# Chars: . + ^ | $ \ * ?
$str =~ s/([.+^|\$\\*?])/\\$1/g;
# As do these 3 types of brackets: (), {}, []
$str =~ s/([(){}[\]])/\\$1/g;
return DBUG_RETURN ( $str ) unless ( $no_fish );
return ( $str );
}
# ==============================================================
=item $str = convert_to_regexp_modifier ( $string )
Similar to C<convert_to_regexp_string> except that it doesn't convert
all the wild card chars.
Leaves the following RegExp wild card's unescaped!
S<(B<*>, B<?>, B<[>, and B<]>)>
Used when processing variable modifier rules.
=cut
sub convert_to_regexp_modifier
{
DBUG_ENTER_FUNC ( @_ );
my $str = shift;
# The 6 problem chars with special meaning in a RegExp ...
# Chars: . + ^ | $ \ (Skips * ?)
$str =~ s/([.+^|\$\\])/\\$1/g;
# As do these 2 of 3 types of brackets: () & {}, not []
$str =~ s/([(){}])/\\$1/g;
DBUG_RETURN ( $str );
}
# ==============================================================
=item $sensitive = should_we_hide_sensitive_data ( $tag )
Checks the tag against an internal list of patterns to see if there is a match.
This check is done in a case insensitive way.
If there is a match it will return true and the caller should take care about
writing anything about this tag to any log files.
If there is no match it will return false, and you can write what you please to
your logs.
See I<make_it_sensitive> to add additional patterns to the list.
=cut
sub should_we_hide_sensitive_data
{
my $tag = shift;
my $skip_fish = shift; # Undocumented ...
my $sensitive = 0; # Assume it's not to be hidden!
foreach my $hide ( @hide_from_fish ) {
if ( $tag =~ m/${hide}/i ) {
$sensitive = 1; # We found a match! It's sensitive!
}
}
unless ( $skip_fish ) {
DBUG_ENTER_FUNC ( $tag, $skip_fish, @_ );
return DBUG_RETURN ( $sensitive );
}
return ( $sensitive );
}
# ==============================================================
=item make_it_sensitive ( @patterns )
Add these pattern(s) to the internal list of patterns that this module considers
sensitive. Should any tag contain this pattern, that tag's value will be
masked when written to this module's internal logs. Leading/trailing spaces
will be ignored in the pattern. Wild cards are not honored.
The 3 default patterns are password, pass, and pwd.
This pattern affects all L<Advanced::Config> objects loaded into memory. Not
just the current one.
=cut
sub make_it_sensitive
{
DBUG_ENTER_FUNC ( @_ );
my @tags = @_;
foreach my $tag ( @tags ) {
if ( $tag ) {
$tag =~ s/^\s+//;
$tag =~ s/\s+$//;
if ( $tag ) {
$tag = convert_to_regexp_string ( $tag, 1 );
push ( @hide_from_fish, $tag );
}
}
}
DBUG_VOID_RETURN ();
}
# ==============================================================
=item $cnt = sensitive_cnt ( )
Returns a count of how many sensitive patterns are being used.
=cut
sub sensitive_cnt
{
DBUG_ENTER_FUNC ( @_ );
DBUG_RETURN ( scalar (@hide_from_fish) );
}
# ==============================================================
=item @ret = croak_helper ($opts, $croak_message, @croak_return_vals)
This helper method helps standardizes what to do on fatal errors when reading
the config file or what to do if you can't find the tag on lookups.
It knows I<\%opts> is a "Read" option hash if B<croak> is a member and it's
a "Get" option hash if B<required> is a member. Both options use the same
logic when called.
See B<croak> and B<required> on what these options do.
Returns whatever I<@croak_return_vals> references. It may be a single value or
an array of values.
It calls B<warn> or B<die> with the message passed.
=cut
# ==============================================================
# No ENTER/RETURN fish calls on purpose here ...
sub croak_helper
{
my $opts = shift;
my $msg = shift;
my @ret = @_; # Use whatever was passed to me ...
# Look up the needed value in the hash we'd like to test out.
my $croak = 0;
if ( exists $opts->{croak} ) {
$croak = $opts->{croak}; # From the Read Opt Hash ...
} elsif ( exists $opts->{required} ) {
$croak = $opts->{required}; # From the Get Opt Hash ...
}
if ( $croak > 0 ) {
die ($msg, "\n");
# The -9876 value is undocumented where we don't even want the msg in fish!
} elsif ( $croak == -9876 ) {
;
} elsif ( $croak < 0 ) {
warn ($msg, "\n");
} else {
DBUG_PRINT ("WARN", $msg);
}
return ( wantarray ? @ret : $ret[0] );
}
# ==============================================================
=item $lvl = set_special_date_vars ( $date_opts_ref, $date_hash_ref[, $old_hash_ref] )
The I<$date_opts_ref> contains the special date variable formatting options
used to control the formattiong of the data returned via I<$date_hash_ref>.
The relevant tags are: I<date_order>, I<date_sep>, I<month_type>, I<use_gmt>
and I<month_language>. Any missing hash key and it's default is used.
This function populates the following date keys in I<$date_hash_ref> for use
by the config object using the current date/time. These keys are also defined
as the date variables available for use by your config files.
The keys set are: (Shown using the default formats)
today, yesterday, tomorrow -- A formatted date in YYYY-MM-DD format.
( run in 1.464 second using v1.01-cache-2.11-cpan-e1769b4cff6 )