package Input_validator;<P>#The Input_validator class implements a domain specific language
#for CGI input validation. The syntax of the language is as follows:
# { parameter1 { expression1, expression2 , ...} { action1() action2() ... },
#parameter2 ... }
#expressions take the form:
#rule(argument1 argument2 ...)
#or [parameter] { expression }
#each rule is run against the most recently encountered parameter and returns
#true if the parameter 'passes' the rules inspections, false otherwise.
#expressions can be separated with 'and', ',' (equivalent to and) and 'or'.
#{action}, if present is executed if the preceeding {expression} evaulates to false.
#rule arguments contained in single quotes are interpreted literally, use \' for a literal
#single quote and \\ for a literal slash. Because the rules are probably enclosed in
#double quotes, you need two \'s for the script to get one '. Therefore, in a double-
#quoted rule string, a single quote in a literal look like \\' and a literal \ looks like
#\\\\.<P>use strict;
require CGI;<P>#A hash table consiting of "rule name"->reference to code that implements the rule
my %rules = (
"true", sub { 1 },
"false", sub { 0 }
);<P>#date returns true if the current parameter looks like a date
$rules{date} = sub
{
my $self = shift;
my $current_parameter = shift;
$current_parameter or iv_error("Match requires a parameter");
if (CGI::param($current_parameter) =~ /^\d{1,2}\/\d{1,2}\/\d{4}$/ ) { 1 } else { 0 }
};
#time returns true if the current parameter looks like a time
$rules{time} = sub
{
my $self = shift;
my $current_parameter = shift;
my $argument = shift;
if (CGI::param($current_parameter) =~ /^\d{1,2}:\d{2}$/ || CGI::param($current_parameter) =~ /^\d{1,2}:\d{2}\s*(am)|(pm)$/i ) { 1 } else { 0 }
};
#matches returns true if the current parameter passes the supplied regexp
$rules{match} = sub
{
my $self = shift;
my $current_parameter = shift;
my $argument = shift;
$current_parameter or iv_error("Match requires a parameter");
if (CGI::param($current_parameter) =~ /$argument/ ) { 1 } else { 0 }
};<P>#eq returns true if the current parameter exactly matches the supplied argument
$rules{eq} = sub
{
my $self = shift;
my $current_parameter = shift;
my $argument = shift;
$current_parameter or iv_error("Eq requires a parameter");
if ($argument eq CGI::param($current_parameter)) { 1 } else { 0 }
};<P>
#The list of params supplied as an argument must exist
$rules{require} = sub
{
my $self = shift;
my $current_parameter = shift;
my @arguments = @_;
my $return = 1;
my $argument;
foreach $argument (@arguments) { unless (CGI::param($argument)) { $return = 0} }
return $return
}; <P>#returns true if the parameter is shorter than the supplied numeric argument
$rules{shorterThan} = sub
{
my $self = shift;
my $current_parameter = shift;
my $argument = shift;
$current_parameter or iv_error("ShorterThan requires a parameter");
($argument && $argument =~ /^\d*$/) or iv_error("Invalid argument $argument to shorterThan. Try a number.");
if (length(CGI::param($current_parameter)) < $argument) { 1 } else { 0 }
};
$rules{number} = sub
{
my $self = shift;
my $current_parameter = shift;
$current_parameter or iv_error("Number requires a parameter");
if (CGI::param($current_parameter) =~ /^\d*$/) { 1 } else { 0 }
};
#A similar table of actions
my %actions = ( );<P>#error adds any arguments onto the array of errors that is accessible through the ->errors() method
$actions{error} = sub
{
my $self = shift;
my $current_parameter = shift;
my $error;
foreach $error (@_)
{ push @{ $self->{errors} }, $error }
};<P>#replace replaces the current parameter with the supplied argument
$actions{replace} = sub
{
my $self = shift;
my $current_parameter = shift;
my $replacement = shift;
$current_parameter or iv_error("Replace requires a parameter");
CGI::param($current_parameter, $replacement)
};<P>#clear deletes the contents of the current_parameter
$actions{clear} = sub
{
my $self = shift;
my $current_parameter = shift;
$current_parameter or iv_error("Clear requires a parameter");
CGI::Delete($current_parameter)
};
#Initialize a new instance and return it.
sub new
{
my $proto = shift;
my %args = @_;
my $class = ref($proto) || $proto;
my $self = {};
$self->{errors} = [ ];
$self->{inputOK}= undef;
$self->{debug} = $args{debug};
bless ($self, $class);
return $self
}<P>#print debug information
sub debug
{
my $self = shift;
my $level = shift;
if ($self->{debug} >= $level) { print @_, "\n
\n" }
}<P>#return a list of any error messages
sub errors
{
my $self = shift;
return @{ $self->{errors} }
}<P>
#return the validation status
sub inputOK
{
my $self = shift;
return $self->{inputOK}
}<P>
#take the rules string and return a reference to an array
#containing the tokenized rules
sub tokenize_rules
{
my $self = shift;
my $rules = shift;
my ($i, $token, @tokens);
my ($inLiteral, $buffer, $inComment) = undef;
#use split to create the array of tokens (including each whitespace as its own token)
@tokens = split(/([!#'\n\s\{\}\(\),\\])/,$rules);
#remove null tokens, they confuse the scanner
for($i = 0; $i < scalar(@tokens);$i++)
{ if (!($tokens[$i])) { splice(@tokens,$i,1);$i-- } }
#Scan through the array of tokens, and coalesce any string contained within single quotes
#into one token, and throw away any token between # and \n
for($i = 0; $i < scalar(@tokens);$i++)
{
#If we are currently inside a literal (we've seen the first ', but not the ending ')
if ($inLiteral)
{
#if this token is the ending '
if ($tokens[$i] eq "'")
{
$inLiteral = 0;
#splice the buffer back in in place of the ending '
splice(@tokens, $i, 1, $buffer);
$buffer = ""
}
#If this token is a \
elsif ($tokens[$i] eq "\\" )
{
#add the next token to the buffer without looking at it and splice it and the \ out.
$buffer .= $tokens[$i+1];
splice(@tokens, $i, 2);
$i--;
}
#normal token inside a literal
else
{
#splice it out and add it to the buffer
$buffer .= $tokens[$i];
splice(@tokens,$i,1);
$i--;
}
}
elsif ($inComment)
{
if ($tokens[$i] eq "\n") { $inComment = 0 }
else { splice(@tokens,$i,1); $i-- }
}
#Scan through the array, if we find a single quote, splice it out and begin processing the literal.
else
{
if ($tokens[$i] eq "'")
{
$inLiteral = 1;
splice(@tokens,$i,1);
$i--
}
elsif ($tokens[$i] eq "#")
{
$inComment = 1;
splice(@tokens,$i,1);
$i--
}
}
}
#If inLiteral is still set when we're done, then the literal must not have been terminated correctly,
#the ruleset can end in a comment, however
if ($inLiteral) { iv_error("Unmatched single quote") }
#remove whitespace-only tokens
for($i = 0; $i < scalar(@tokens);$i++)
{
if ($tokens[$i] =~ /^[\s|\n]*$/) { splice(@tokens,$i,1);$i-- }
}
debug($self, 3, join("*\n
", @tokens));
return \@tokens
}<P>#handle errors in the ruleset
sub iv_error
{
die shift
}<P>#Run the ruleset
sub validate
{
my $self = shift;
my $rules = shift;
my $tokens = tokenize_rules($self, $rules);
my $token = shift(@$tokens);
#The ruleset itself is a valid list of expressions, so we
#just shift off the first { and let recursion handle the rest
if ($token eq '{')
{ $self->{inputOK} = evaluate_expression_list($self, $tokens, "") }
else { iv_error("Input_validator ruleset must be enclosed in \{ \}") }
}<P>sub evaluate_expression_list
{
my $self = shift;
my $tokens = shift;
my $current_parameter = shift;
my ($status_so_far, $return, $token, $action, $operator, @stack);
#here we take an expression-list enclosed in {} and evaluate it to either 1 or 0
#(true or false). The whole ruleset is an expression-list, and the state of the input
#(valid, or not) is determined by evaluating the ruleset. An expression list is a
#sequence of expressions separated by operators. Valid operators are 'and' and ','
#which both mean logical AND and 'or' which means logical OR. The value of an
#expression list is determined by evaluating each of its individual expressions in turn
#and logicaly combining it with the return value of the next expression using
#the intervening operator. Sub-expression lists are handled by recursion.
debug($self, 1,"Came down into evaluate_expression_list, current_parameter = $current_parameter");
#keep shifting tokens off the bottom, until we run out
while ($token = shift(@$tokens))
{
#action_parameter is the parameter that the action-list (if there is one)
#will run against.
my ($action_parameter) = $current_parameter;
my ($not);
#if we get to } then we have finished evaluating this expression list, and can return
#the result so far back up. If status_so_far is undefined (this in an empty
#expression list) return true.
if ($token eq '}')
{
debug($self, 1,"Returning out of evaluate_expression_list, returning '$status_so_far'.");
if (defined($status_so_far)) {return $status_so_far }
else { return 1 }
}
#! before either an expression or a rule performs logical-negation on the
#return of the expression or rule
elsif ($token eq '!')
{
$not = 1;
$token = shift @$tokens
}
#a { indicates a sub-expression-list. Call ourself recursively
if ($token eq '{')
{
$return = evaluate_expression_list($self, $tokens, $current_parameter);
debug($self, 2,"return=$return")
}
#if the current token is neither { nor } then we need to look at the next
#token to figure out what to do.
#
#If the next token is { then the current token must be a parameter
#that the sub-expression-list should be run against. Call ourself recursively
#passing the $token down as the $current_parameter argument.
elsif ($tokens->[0] eq '{')
{
#make sure $token is a valid parameter before we pass it down
($token =~ /^[\w-]*$/) or iv_error("Invalid parameter $token before \{");
#we are evaluating an expression list, with $token as the parameter so
#if there is an action list after this expression list it should also run
#with $token as the parameter.
$action_parameter = $token;
shift @$tokens;
$return = evaluate_expression_list($self, $tokens, $token);
debug($self, 2,"return=$return")
}
# ( tells us that the token is a rule, and we should evaluate the rule. We pass it
#the current parameter, and the result of getArgumentList which shifts all of the
#arguments up to the ) off.
elsif ($tokens->[0] eq '(')
{
#make sure $token is defined as a rule first.
defined($rules{$token}) or iv_error("Undefined rule $token.");
shift @$tokens;
debug($self, 2,"Calling rule $token.");
$return = &{$rules{$token}}($self, $current_parameter, getArgumentList($tokens));
debug($self, 1,"$token returned '$return'")
}
else { iv_error("Syntax error evaluating expression-list near $token") }<P> #if we were preceeded by ! then negate the answer.
#we do this before we evaluate the action-list, so the decision
#to act or not is based on the return *after* the logical
#negation. It would be best to use extra {}'s to avoid
#ambiguity, I guess.
if ($not) { $return = !$return; debug($self,2,"return negated to $return") }<P> #Good language design is beyond me, maybe I should read a book.
#
#I think this is OK. If the value of the current_parameter is null then
#return true, no matter what else. I want null input to be valid, so you
#can call the script with no parameters and not get an error.
#If I don't do it this way by default, then explicit allows of
#null input would litter all my programs.
#
#We check for this after checking for negation, so null input
#never triggers an action-list.
if ( $current_parameter && !(CGI::param($current_parameter)) )
{ $return = 1; debug($self,2,"Unconditional true return for null parameter") }
#if there is another { after the expression then it encloses an action list.
#do_action_list knows whether to actually act or not, based on $return,
#but we need to call it in either case, to get the action_list shifted off
#the list of tokens.
if ($tokens->[0] eq '{')
{
shift @$tokens;
#this bit enclosed in its own block
DO_ACTIONS:
{
while ($action = shift @$tokens)
{
if ($action eq '}') { last DO_ACTIONS }
else
{
(defined($actions{$action})) or iv_error("Undefined action $action.");
(shift @$tokens eq '(') or iv_error("Syntax error near $action while evaluating action list.");
if (!$return)
{
debug($self, 1,"Calling action $action.");
&{$actions{$action}}($self,$current_parameter,getArgumentList($tokens))
}
else { getArgumentList($tokens) }
}
}
iv_error("Unexpected end of ruleset while evauating action list.")
}
}<P> if ($operator eq 'and' || $operator eq ',')
{ debug($self, 2,"AND:$status_so_far:$return"); $status_so_far = $status_so_far && $return }
elsif ($operator eq 'or')
{ debug($self, 2,"OR:$status_so_far:$return"); $status_so_far = $status_so_far || $return }
elsif (!defined($operator))
{ debug($self, 2,"NONE:$status_so_far:$return"); $status_so_far = 1 && $return }
else
{ iv_error("Invalid operator $operator.")}
debug($self, 2,"status '$status_so_far' after operator $operator");
undef $operator;<P> if ($tokens->[0] =~ /^(and)|,|(or)$/) { $operator = shift @$tokens }
elsif (!($tokens->[0] eq '}')) { iv_error("Operator required after $token {} [{}].") }
}
iv_error("Unexpected end of ruleset")
}<P>#Scan forward through the token until the ending ) is found
#and retrurn all of the tokens found in an array.
sub getArgumentList
{
my $tokens = shift;
my ($token, @argList);<P> while ($token = shift @$tokens)
{
if ($token eq ')') { return @argList }
else { push @argList, $token }
}
iv_error("Unexpected end of ruleset while evaluating argument list")
}
1;