Skip to content

Instantly share code, notes, and snippets.

@paveljurca
Last active October 11, 2015 17:41
Show Gist options
  • Save paveljurca/aea55a0ae6551dbec455 to your computer and use it in GitHub Desktop.
Save paveljurca/aea55a0ae6551dbec455 to your computer and use it in GitHub Desktop.
HTTP::Server gone evil
package ServCGI;
########################
# NO security! #
# No sense! #
# quick and dirty #
########################
use HTTP::Server::Simple::CGI;
use base qw(HTTP::Server::Simple::CGI);
use File::Basename;
#use autodie;
use constant TEXT_PLAIN => "Content-Type: text/plain; charset=utf-8\n\n";
use constant TEXT_HTML => "Content-Type: text/html\n\n";
my %dispatch_ext = (
'/' => \&html, #ROOT 'hack'
'html' => \&html,
'pl' => \&pl,
);
sub handle_request {
my ($self, $cgi) = @_;
my $path = $cgi->path_info();
my ($ext) = $path =~ /([^.]+)$/;
my $handler = $dispatch_ext{$ext};
if (ref $handler eq 'CODE') {
my $res = $handler->($path);
if ($res) {
print("HTTP/1.1 200 OK\r\n", $res);
}
else {
print("HTTP/1.1 404 Not Found\r\n",
TEXT_PLAIN, 'not found');
}
}
else {
print("HTTP/1.1 400 Bad Request\r\n",
TEXT_PLAIN, 'bad request');
}
}
## !!
# CGI scripts inside the ./pl/* directory
sub pl {
#NO subfolders
my $f = basename(shift);
# pretty nasty way !!
# no %ENV for instance
# malfunction
my $res = `perl pl/$f` if -e 'pl/' . $f;
return $res;
}
sub html {
#NO subfolders
my $f = basename(shift);
############ ROOT #############
$f = 'index.html' if $f eq '/';
###############################
# /ahoj./ PASSES in!!
# so it looks for the exact '/' file
#print STDERR $f;
open(my $fh, '<:encoding(utf8)', $f)
if -e $f or return;
local $/; #slurp mode ON
my $res = TEXT_HTML . <$fh>;
close($fh);
return $res;
}
### RUN it!
#ServCGI->new(8080)->run();
my $pid = ServCGI->new()->background();
open(my $fh, '>', '.pid')
or die qq($pid\n);
print $fh qq($pid\n);
### KILL it!
#$> kill -9 `head -n1 ./.pid`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment