![]() |
More About CGIA Hands-on How-toSMfrom Brass Cannon ConsultingA little vague handwaving can often save hours of tedious explanation. |
In the previous example, we talked about passing a value to a script that lives in the cgi-bin directory. That script then generated html code, just like the text with tags that you would type by hand to create a web page, except that the CGI script can plug in the values you give it and thus change the page that is displayed.
The first example picked different image files based on the URL, so one small routine could serve an unlimited number of different image files.
Here's a more ambitious example. Let's say we wanted to make a Web-based file server, which would download files to the user's hard disk automatically instead of displaying them on screen.
So without further ado, here's my second CGI script. Again, it's written in Perl, sometimes called the "Swiss Army chainsaw" of the Web developer.
#!/usr/bin/perl
@params=split(/=/,$ENV{'QUERY_STRING'});
my $p0 = $params[0];
my $p1 = $params[1];
## Handle URLencodings:
$p0 =~ tr/+/ /;
$p0 =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
$p0 =~ s/,/ /eg;
$p1 =~ tr/+/ /;
$p1 =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
$p1 =~ s/,/ /eg;
## Eat /.. attacks:
$p0 =~ s/\/\.\.//eg;
$p1 =~ s/\/\.\.//eg;
## Force a known starting directory:
my $DD = "/home/www";
## Validate username:
my $user_dir = "$DD/$p0";
if (!(-d $user_dir)) {
print "Content-type: text/html\r\n\r\n";
print "<html><body bgcolor=#FFFF00>";
print ("<br>User $p0 is not set up to download files.<br>");
print ("Please ask admin\@example.com to set up User $p0.<br>");
print "P0: ", $params[0], "+", $p0, " P1: ", $params[1], "+", $p1,"\r\n";
print "</body></html>";
die("Unknown user $p0");
}
## Kill Unix shell escape characters:
$p1 =~ s/([;<>\*\|'\$!#\(\)\[\]\{\}:'"])/\\$1/g;
## Fix up for embedded spaces in filenames:
$p1 =~ s/ /\ /;
my $user_file = $p1;
my $send_file = "$user_dir/$user_file";
if (!(-f $send_file)) {
print "Content-type: text/html\r\n\r\n";
print "<html><body bgcolor=#FFFF00>";
print ("<br>No such file ($user_file)<br>");
print "P0: ", $params[0], "+", $p0, " P1: ", $params[1], "+", $p1,"\r\n";
print "</body></html>";
die("No such file $p1");
}
## Debug:
#print "Content-type: text/html\r\n\r\n";
#print "<html><body>";
#print "P0: ", $params[0], "=", $p0, " P1: ", $params[1], "=", $p1,"\r\n";
#print "<br>SF: ", $send_file, "\r\n";
#if (!(-f $send_file)) {print ("No such file ($!)<br>")}
#print "