CGI-Info
view release on metacpan or search on metacpan
CGI-Info
========
[](https://ci.appveyor.com/project/nigelhorne/cgi-info)
[](https://dl.circleci.com/status-badge/redirect/circleci/8CE7w65gte4YmSREC2GBgW/THucjGauwLPtHu1MMAueHj/tree/main)
[](https://coveralls.io/github/nigelhorne/CGI-Info?branch=master)
[](http://search.cpan.org/~nhorne/CGI-Info/)


[](SECURITY.md)
<!-- [](https://travis-ci.org/nigelhorne/CGI-Info) -->
[](https://x.com/intent/tweet?text=Information+about+the+CGI+Environment+#perl+#CGI&url=https://github.com/nigelhorne/cgi-info&via=nigelhorne)
# NAME
CGI::Info - Information about the CGI environment
# VERSION
Version 1.14
# SYNOPSIS
The `CGI::Info` module is a Perl library designed to provide information about the environment in which a CGI script operates.
It aims to eliminate hard-coded script details,
enhancing code readability and portability.
Additionally, it offers a simple web application firewall to add a layer of security.
All too often,
Perl programs have information such as the script's name
hard-coded into their source.
Generally speaking,
hard-coding is a bad style since it can make programs difficult to read and reduces readability and portability.
CGI::Info attempts to remove that.
Furthermore, to aid script debugging, CGI::Info attempts to do sensible
things when you're not running the program in a CGI environment.
Whilst you shouldn't rely on it alone to provide security to your website,
it is another layer and every little helps.
use CGI::Info;
my $info = CGI::Info->new(allow => { id => qr/^\d+$/ });
my $params = $info->params();
if($info->is_mobile()) {
print "Mobile view\n";
} else {
print "Desktop view\n";
}
my $id = $info->param('id'); # Validated against allow schema
# SUBROUTINES/METHODS
## new
Creates a CGI::Info object.
It takes four optional arguments: allow, logger, expect and upload\_dir,
which are documented in the params() method.
It takes other optional parameters:
- `auto_load`
Enable/disable the AUTOLOAD feature.
The default is to have it enabled.
- `config_dirs`
Where to look for `config_file`
- `config_file`
Points to a configuration file which contains the parameters to `new()`.
The file can be in any common format,
including `YAML`, `XML`, and `INI`.
This allows the parameters to be set at run time.
On non-Windows system,
the class can be configured using environment variables starting with "CGI::Info::".
For example:
export CGI::Info::max_upload_size=65536
It doesn't work on Windows because of the case-insensitive nature of that system.
If the configuration file has a section called `CGI::Info`,
only that section,
and the `global` section,
if any exists,
is used.
- `syslog`
Takes an optional parameter syslog, to log messages to
[Sys::Syslog](https://metacpan.org/pod/Sys%3A%3ASyslog).
It can be a boolean to enable/disable logging to syslog, or a reference
to a hash to be given to Sys::Syslog::setlogsock.
- `cache`
An object that is used to cache IP lookups.
This cache object is an object that understands get() and set() messages,
such as a [CHI](https://metacpan.org/pod/CHI) object.
- `max_upload_size`
The maximum file size in bytes you can upload.
Use `-1` for no limit.
The default is 512 KB (524288 bytes).
The class can be configured at runtime using environment variables and configuration
files; for example, setting `$ENV{'CGI__INFO__carp_on_warn'}` causes warnings to
use [Carp](https://metacpan.org/pod/Carp). For more information see [Object::Configure](https://metacpan.org/pod/Object%3A%3AConfigure).
### API SPECIFICATION
#### INPUT
{
allow => { type => 'hashref', optional => 1 },
auto_load => { type => 'boolean', optional => 1 },
cache => { type => 'object', optional => 1 },
carp_on_warn => { type => 'boolean', optional => 1 },
config_dirs => { type => 'arrayref', optional => 1 },
config_file => { type => 'string', optional => 1 },
logger => { type => 'object', optional => 1 },
max_upload_size=> { type => 'integer', optional => 1, min => -1 },
upload_dir => { type => 'string', optional => 1 },
}
#### OUTPUT
{ type => 'object', isa => 'CGI::Info' }
### MESSAGES
- `use ->new() not ::new() to instantiate`
**Level**: fatal (croak).
**Cause**: called as `CGI::Info::new()` (double-colon) instead of `CGI::Info->new()`.
**Action**: change the call-site to use the arrow notation.
- `Logger must be an object with info() and error() methods`
**Level**: fatal (croak).
**Cause**: the `logger` argument is not a blessed object, or does not
implement `info()`, `warn()`, and `error()` methods.
**Action**: pass a compliant logger such as a [Log::Abstraction](https://metacpan.org/pod/Log%3A%3AAbstraction)-based object.
- `expect has been deprecated, use allow instead`
**Level**: fatal (croak).
**Cause**: the removed `expect` parameter was passed to `new()`.
**Action**: replace `expect => [...]` with `allow => { key => qr/.../ }`.
## script\_name
Retrieves the name of the executing CGI script.
This is useful for POSTing,
thus avoiding hard-coded paths into forms.
use CGI::Info;
my $info = CGI::Info->new();
my $script_name = $info->script_name();
# ...
print "<form method=\"POST\" action=$script_name name=\"my_form\">\n";
### API SPECIFICATION
#### INPUT
None.
#### OUTPUT
{
type => 'string',
'min' => 1,
'nomatch' => qr/^[\/\\]/ # Does not return absolute path
}
## script\_path
Finds the full path name of the script.
use CGI::Info;
my $info = CGI::Info->new();
print 'HTML files are normally stored in ', $info->script_dir(), '/', File::Spec->updir(), "\n";
# or
use lib CGI::Info::script_dir() . '../lib';
## host\_name
Return the host-name of the current web server, according to CGI.
If the name can't be determined from the web server, the system's host-name
is used as a fall back.
This may not be the same as the machine that the CGI script is running on,
some ISPs and other sites run scripts on different machines from those
delivering static content.
There is a good chance that this will be domain\_name() prepended with either
'www' or 'cgi'.
use CGI::Info;
my $info = CGI::Info->new();
my $host_name = $info->host_name();
my $protocol = $info->protocol();
# ...
print "Thank you for visiting our <A HREF=\"$protocol://$host_name\">Website!</A>";
## domain\_name
Domain\_name is the name of the controlling domain for this website.
Usually it will be similar to host\_name, but will lack the http:// or www prefixes.
Can be called as a class method.
## cgi\_host\_url
Return the URL of the machine running the CGI script.
## params
Returns a reference to a hash list of the CGI arguments.
CGI::Info helps you to test your script before deployment on a website:
if it is not in a CGI environment (e.g., the script is being tested from the
command line), the program's command line arguments (a list of key=value pairs)
are used, if there are no command line arguments,
then they are read from stdin as a list of key=value lines.
Also,
you can give one of --tablet, --search-engine,
\--mobile and --robot to mimic those agents. For example:
./script.cgi --mobile name=Nigel
Returns undef if the parameters can't be determined or if none were given.
If an argument is given twice or more, then the values are put in a comma
separated string.
The returned hash value can be passed into [CGI::Untaint](https://metacpan.org/pod/CGI%3A%3AUntaint).
Takes four optional parameters: allow, logger and upload\_dir.
The parameters are passed in a hash, or a reference to a hash.
The latter is more efficient since it puts less on the stack.
Allow is a reference to a hash list of CGI parameters that you will allow.
The value for each entry is either a permitted value,
a regular expression of permitted values for
the key,
a code reference,
or a hash of [Params::Validate::Strict](https://metacpan.org/pod/Params%3A%3AValidate%3A%3AStrict) rules.
Subroutine exceptions propagate normally, allowing custom error handling.
This works alongside existing regex and Params::Validate::Strict patterns.
A undef value means that any value will be allowed.
Arguments not in the list are silently ignored.
This is useful to help to block attacks on your site.
Upload\_dir is a string containing a directory where files being uploaded are to
be stored.
It must be a writeable directory in the temporary area.
Takes an optional parameter logger, which is used for warnings and traces.
It can be an object that understands warn() and trace() messages,
such as a [Log::Log4perl](https://metacpan.org/pod/Log%3A%3ALog4perl) or [Log::Any](https://metacpan.org/pod/Log%3A%3AAny) object,
a reference to code,
a reference to an array,
or a filename.
The allow, logger and upload\_dir arguments can also be passed to the
constructor.
use CGI::Info;
use CGI::Untaint;
# ...
my $info = CGI::Info->new();
my %params;
if($info->params()) {
%params = %{$info->params()};
}
# ...
foreach(keys %params) {
print "$_ => $params{$_}\n";
}
my $u = CGI::Untaint->new(%params);
use CGI::Info;
use CGI::IDS;
# ...
my $info = CGI::Info->new();
my $allowed = {
foo => qr/^\d*$/, # foo must be a number, or empty
bar => undef, # bar can be given and be any value
xyzzy => qr/^[\w\s-]+$/, # must be alphanumeric
# to prevent XSS, and non-empty
# as a sanity check
};
# or
$allowed = {
email => { type => 'string', matches => qr/^[^@]+@[^@]+\.[^@]+$/ }, # String, basic email format check
age => { type => 'integer', min => 0, max => 150 }, # Integer between 0 and 150
bio => { type => 'string', optional => 1 }, # String, optional
ip_address => { type => 'string', matches => qr/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/ }, #Basic IPv4 validation
};
my $paramsref = $info->params(allow => $allowed);
if(defined($paramsref)) {
my $ids = CGI::IDS->new();
$ids->set_scan_keys(scan_keys => 1);
if($ids->detect_attacks(request => $paramsref) > 0) {
die 'horribly';
}
}
If the request is an XML request (i.e. the content type of the POST is text/xml),
CGI::Info will put the request into the params element 'XML', thus:
use CGI::Info;
# ...
my $info = CGI::Info->new();
my $paramsref = $info->params(); # See BUGS below
my $xml = $$paramsref{'XML'};
# ... parse and process the XML request in $xml
Carp if logger is not set and we detect something serious.
Blocks some attacks,
such as SQL and XSS injections,
mustleak and directory traversals,
thus creating a primitive web application firewall (WAF).
Warning - this is an extra layer, not a replacement for your other security layers.
params() returns a ref which means that calling routines can change the hash
for other routines.
Take a local copy before making amendments to the table if you don't want unexpected
things to happen.
# SEE ALSO
- [Configure an Object at Runtime](https://metacpan.org/pod/Object%3A%3AConfigure)
- [Test Dashboard](https://nigelhorne.github.io/CGI-Info/coverage/)
- [HTTP::BrowserDetect](https://metacpan.org/pod/HTTP%3A%3ABrowserDetect)
- [https://github.com/mitchellkrogza/apache-ultimate-bad-bot-blocker](https://github.com/mitchellkrogza/apache-ultimate-bad-bot-blocker)
# REPOSITORY
[https://github.com/nigelhorne/CGI-Info](https://github.com/nigelhorne/CGI-Info)
# SUPPORT
This module is provided as-is without any warranty.
Please report any bugs or feature requests to `bug-cgi-info at rt.cpan.org`,
or through the web interface at
[http://rt.cpan.org/NoAuth/ReportBug.html?Queue=CGI-Info](http://rt.cpan.org/NoAuth/ReportBug.html?Queue=CGI-Info).
I will be notified, and then you'll
automatically be notified of progress on your bug as I make changes.
You can find documentation for this module with the perldoc command.
perldoc CGI::Info
You can also look for information at:
- MetaCPAN
[https://metacpan.org/dist/CGI-Info](https://metacpan.org/dist/CGI-Info)
- RT: CPAN's request tracker
[https://rt.cpan.org/NoAuth/Bugs.html?Dist=CGI-Info](https://rt.cpan.org/NoAuth/Bugs.html?Dist=CGI-Info)
- CPAN Testers' Matrix
[http://matrix.cpantesters.org/?dist=CGI-Info](http://matrix.cpantesters.org/?dist=CGI-Info)
- CPAN Testers Dependencies
[http://deps.cpantesters.org/?module=CGI::Info](http://deps.cpantesters.org/?module=CGI::Info)
## FORMAL SPECIFICATION
### new
-- CGI::Info construction
new : ClassName x Params --> CGIInfo
-- Normal (non-clone) path
new(class, params) ^=
let configured == Object::Configure::configure(class, params)
in CGIInfo {
max_upload_size |-> configured.max_upload_size ?? MAX_UPLOAD_SIZE_DEFAULT,
allow |-> configured.allow ?? null,
upload_dir |-> configured.upload_dir ?? null,
...configured
}
-- Pre-conditions
pre new(class, params) ^=
params.logger = null
v (blessed(params.logger)
^ params.logger.can('warn')
^ params.logger.can('info')
^ params.logger.can('error'))
^ params.expect = null
-- Clone path (invocant is an existing object)
clone : CGIInfo x Params --> CGIInfo
clone(self, params) ^=
let merged == (self (+) params) \ {paramref}
in CGIInfo { ...merged }
### param
Let F be the set of all possible CGI field names, V be the set of all
possible (sanitised) scalar values, and allow : F -> Regex | undef be the
current allow-list schema (undef means all fields are permitted).
param : F? -> V | HashRef | undef
param() = params()
param(f) =
f not in dom(allow) /\ allow /= undef => warn; undef
f in params() => params()(f)
otherwise => undef
Safety invariant: for all f, param(f) /= undef => f in dom(allow) \\/ allow = undef.
## is\_ai
-- is_ai ---------------------------------------------------------
-- Given CGIInfo state i, returns a boolean result.
--
-- AI_PAT is the set of known AI crawler token strings.
--
-- ENV denotes the process environment (a partial function from
-- name to value).
--
AI_PAT == {ClaudeBot, Claude-Web, anthropic-ai, GPTBot,
ChatGPT-User, OAI-SearchBot, Google-Extended,
meta-externalagent, FacebookBot, Applebot-Extended,
PerplexityBot, Amazonbot, YouBot, Diffbot,
cohere-ai, CCBot, Bytespider, AI2Bot, TimpiBot}
is_ai â λ i : CGIInfo â¢
-- Environment override takes absolute priority
IS_AI â dom ENV â¹
(ENV IS_AI â '0' â§ ENV IS_AI â '')
-- Without both IP and UA we cannot classify
â§ IS_AI â dom ENV â§
(REMOTE_ADDR â dom ENV ⨠HTTP_USER_AGENT â dom ENV)
â¹ false
( run in 1.181 second using v1.01-cache-2.11-cpan-b16cb0d3907 )