#!/usr/bin/perl -w # vim: set sw=4 ts=4 si et: # Simple single threaded web server written in perl # Author: Guido Socher # # Usage: wwwperl.pl [-p portnumber] [-i ip-to-bind-to] [-t] "command to run" # Example: ./wwwperl.pl "cat /tmp/test.html" # The above example will answer http requests at port 8000 # on any interface that this machine has. # The command "cat /tmp/test.html" will be executed everytime the user connects # and the output of that command will be sent to the user. # Try: # curl -v http://localhost:8000 # sub help(); use vars qw($opt_h $opt_p $opt_i $opt_t); use Getopt::Std; use strict; use Socket; getopts("htp:i:")||die "ERROR: No such option. -h for help.\n"; help() if ($opt_h); help() unless($ARGV[0]); # my $listenport = 8000; $listenport=$opt_p if ($opt_p); print "OK: listenport=$listenport\n"; socket (Server, PF_INET, SOCK_STREAM, 6) || die ("Error socket: $!"); # protocol 6 is tcp setsockopt(Server, SOL_SOCKET,SO_REUSEADDR,1) || die ("Error setsockopt: $!"); my $sockaddr = sockaddr_in($listenport, $opt_i ? inet_aton($opt_i) : INADDR_ANY) || die ("Error sockaddr_in: $!"); bind(Server,$sockaddr) || die ("Error bind: $!"); listen(Server,SOMAXCONN) || die ("Error listen: $!"); my $caddr; my $buffer; while ($caddr = accept(Client, Server)) { recv(Client,$buffer,1000,0); if ($buffer && $buffer=~/^GET /){ print Client "HTTP/1.1 200 OK\r\n"; if ($opt_t){ print Client "Content-Type: text/plain\r\n"; }else{ print Client "Content-Type: text/html\r\n"; } print Client "Server: wwwperl/1.0\r\n"; print Client "Connection: close\r\n"; print Client "\r\n"; print "client:\n$buffer\n"; # run the command and capture the output: open(SF,"$ARGV[0] |")||die "ERROR: can not read from pipe\n"; while(){ print Client $_ ; } close SF; } close Client; } # sub help(){ print "wwwperl.pl -- simple web server in plain perl, no special libs required USAGE: wwwperl.pl [-p portnumber] [-i ip-to-bind-to] [-t] \"command\" This is a single threaded web server which can execute a command and display the output. It does not handle different URL strings. OPTIONS: -h this help -i specify the ip address of a local interface to bind to -p portnumber (default is 8000) -t command produced plain text data and not html EXAMPLE: wwwperl.pl \"cat /tmp/test.html\" \n"; exit; } __END__