Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Simple HTTP in under 100 lines

by Corion (Patriarch)
on Oct 04, 2001 at 21:09 UTC ( [id://116767]=perlcraft: print w/replies, xml ) Need Help??

   1: #!/usr/bin/perl -wT
   2: use strict;
   3: use IO::File;
   4: use Cwd;
   5: use HTTP::Daemon;
   6: use HTTP::Status;
   8: $| = 1;
  10: # We are quite explicit about where we listen
  11: my $d = new HTTP::Daemon
  12:                     Reuse => 1,
  13:                     LocalAddr => '',
  14:                     LocalPort => 8889;
  16: my $nofork = $^O =~ /Win32/i; # For easy testing under Win32
  18: $SIG{__WARN__} = sub { warn __stamp(shift) };
  19: $SIG{__DIE__} = sub { die __stamp(shift) };
  20: $SIG{CHLD} = 'IGNORE';
  22: warn "Please contact me at: <URL:" . $d->url . ">\n";
  24: $ENV{PATH} = '/bin:/usr/bin'; # Set our path to something secure
  25: my $root = $ARGV[0] || cwd;
  26: $root = $1 if $root =~ /^(.*)$/; # untaint document root
  27: $root .= "/" unless $root =~ m!/$!;
  29: # This sub Copyright (c) 1996,97,98,99,2000,01 by Randal L. Schwartz
  30: sub __stamp {
  31:   my ($message) = @_;
  32:   my $stamp = sprintf "[$$] [%02d@%02d:%02d:%02d] ", (localtime)[3,2,1,0];
  33:   $message =~ s/^/$stamp/gm;
  34:   $message;
  35: }
  37: sub handleConnection {
  38:   local $SIG{PIPE} = 'IGNORE';
  39:   my ($connection) = @_;
  40:   while (my $r = $connection->get_request()) {
  41:     warn $r->as_string; # Yes, that's verbose.
  43:     my $url = $r->url->path;
  44:     $url = "/$url" unless $url =~ m!^/!; # Remove all suspicious paths
  45:     $url =~ s!/.?.(?=/|$)!/!g;
  46:     $url =~ tr!\x00-\x1F!!d;
  48:     my $response = new HTTP::Response( 404,undef,undef,"404 - Not found." );
  49:     if (-d "$root$url") {
  50:       $url = "$url/" unless $url =~ m!/$!;
  51:       opendir DIR, "$root$url";
  52:       $response->code(200);
  53:       $response->content(
  54:             "<html><head><title>$url</title></head><body><h1>$url</h1><tt>"
  55:             . join( "<br>",
  56:                 map { my ($cmt,$link) = ((-s "$root$url$_")." bytes",$_);
  57:                       -d _ and $cmt = "directory";
  58:                       $link =~ s/([ '"?%&:])/{'%'.unpack("H2",$1)}/eg;
  59:                       "<A href='$url$link'>$_</A> $cmt"
  60:                     } sort grep { /^[^.]/ } readdir DIR )
  61:             . "</tt></body></html>" );
  62:       closedir DIR;
  63:     } else {
  64:       my $file = new IO::File "< $root$url";
  65:       if (defined $file) {
  66:         $response->code( 200 );
  67:         binmode $file;
  68:         my $size = -s $file;
  70:         my ($startrange, $endrange) = (0,$size-1);
  71:         if (defined $r->header("Range")
  72:             and $r->header("Range") =~ /bytes\s*=\s*(\d+)-(\d+)?/) {
  73:           $response->code( 206 );
  74:           ($startrange,$endrange) = ($1,$2 || $endrange);
  75:         };
  76:         $file->seek($startrange,0);
  78:         $response->header(Content_Length => $endrange-$startrange);
  79:         $response->header(Content_Range => "bytes $startrange-$endrange/$size");
  80:         $response->content( sub {
  81:           sysread($file, my ($buf), 16*1024); # No error checking ???
  82:           return $buf;
  83:         });
  84:       };
  85:     };
  86:     warn "Response :",$response->code;
  87:     $connection->send_response($response);
  88:   };
  89:   warn "Handled connection (closed, " . $connection->reason . ")";
  90:   $connection->close;
  91: };
  93: while (my $connection = $d->accept) {
  94:   # Really condensed fork/nofork handler code
  95:   next unless $nofork || ! fork();
  96:   warn "Forked child" unless $nofork;
  97:   handleConnection( $connection );
  98:   die "Child quit." unless $nofork;
  99: }

Replies are listed 'Best First'.
Documentation for the Simple HTTP server in under 100 lines
by Corion (Patriarch) on Oct 04, 2001 at 21:16 UTC

    The objective was to write a simple HTTP server that supported resuming of downloads via the Range heeaders. The server should also be fairly secure, as it runs unattended on my firewall box, and thus, it should also not require any fancy setup that could be misconfigured.

    The server must be run with the taint option of Perl for even more security. I toyed with the idea of locking the server in a chroot() jail, but getting Perl/HTTP::Daemon to work in such a jail is no easy feat, so I ditched the idea (see objective above).

    The server works under both, Win32 and Unix, but under Win32 it dosen't support fork, as the fork emulation is not always working for me. In the spirit of simplicity, it also dosen't support any CGI capabilities, since CGI capabilities present a security hole waiting to be exploited. Also, "hidden" files starting with a dot (".") are not available for download as well. On the upside, the server fully supports persistent connections.

    Of course, the total number of lines is arbitrarily set at 99 lines, as there is much whitespace to be compressed, but I wanted to keep a sensible mix of obfuscation/compression and readability, as I think that maybe other people than me would want to use this code.

    Command line options

    perl -wT [document_root]


    Even though I tried to be as paranoid as possible about my own code, I can't guarantee that the code is secure in any way other than taking up valuable CPU time and/or disk space. If you find any interesting exploits, please add them in a reply here, so others can learn from my mistakes.

    2001-10-05 Update: Fixed small germanism thanks to John M. Dlugosz

    2001-10-05 Update: Fixed missing use strict; at the top of the script. Thanks to ybiC for mentioning it to me. My Pascal upbringing seems to have protected me against violating strict, as no code rework was necessary...

    2004-07-11 Update: Fixed _stamp routine so it actually displays a useful timestamp. Thanks to BrowserUK for finding it in that code.

Re: Simple HTTP in under 100 lines
by BrowserUk (Patriarch) on Jul 11, 2004 at 00:08 UTC

    It's a bit belated and probably something either fixed or forgotten long ago, but you simplified merlyn's _stamp() a step too far.

    This ..., localtime[3,2,1,0];

    should be at least this ..., ( localtime )[ 3, 2, 1, 0 ];.

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    "Memory, processor, disk in that order on the hardware side. Algorithm, algoritm, algorithm on the code side." - tachyon
Re: Simple HTTP in under 100 lines
by GeneralElektrix (Acolyte) on Jul 22, 2013 at 14:25 UTC
    Used this 12 years later as the base for a simple web service on a server for which I cannot modify the Perl distribution. Simple, performant, working smootlhy, multi-forking like a pro. Thank you Corion.
Re: Simple HTTP in under 100 lines
by mattr (Curate) on Nov 13, 2001 at 20:00 UTC
    Interesting! Here's what I got.. - had trouble running it with -wT in line 1; was able to run it after cutting that out as you suggest, perl -wT perlsvrhome
    - could not get -h to work (I think this and above mean my getopts or something is corrupt)

    - does not close connection right away though kills child.
    - sending ctrl-c instead of something like GET / causes child to quit with "Use of uninitialized value at /usr/lib/perl5/site_perl/5.005/HTTP/ line 498." which is a funny reason to quit..
    - was able to download a file set to chmod 700 and ending in .pl

    So I'm not so sure about the security side, although presumably perl's proof against buffer attacks, we are told. How about keeping a list of children and killing them after a certain amount of time just in case? I wanted to do a kill -HUP on it when I had made a lot of children processes, but it just died.


      I use PSI::ESP to address the errors :-)

      • Trouble with running the server without -T on the command line - I get this error every time I try to use taint mode : Too late for -T. I don't know about any way around it except specifying -T on the command line.
      • -h dosen't work. - There is no -h option, so it won't work.
      • Connections are not always closed when a child exits. I'm not sure when this happens - my experience showed that IE kept a child alive until either some timeout happened or I closed that IE window (or visited another URL with that window)
      • Sending ^C to the server gives a funny error message - This is a "problem" with HTTP::Daemon which seems to want to call a ^C (instead of GET) method. I don't know how to fix this without patching HTTP::Daemon.
      • .pl files will be downloaded, even though they are executable and only readable by the user running the webserver. - This works as designed. Everything below the webserver root is exported, and as long as the user under which the webserver is run can read the file it will transfer that file. Note that especially no execution of files is possible.

      I'm not keen to add any more features to that server as it would transcend both the line count limit and the complexity limit - also, this server is used to stream 200MB files over my meager 128kbit line, so each child lives a very long time.

      perl -MHTTP::Daemon -MHTTP::Response -MLWP::Simple -e ' ; # The $d = new HTTP::Daemon and fork and getprint $d->url and exit;#spider ($c = $d->accept())->get_request(); $c->send_response( new #in the HTTP::Response(200,$_,$_,qq(Just another Perl hacker\n))); ' # web
Re: Simple HTTP in under 100 lines
by mischief (Hermit) on Oct 05, 2001 at 21:52 UTC

    Just to be pedantic, I thought I'd point out that this isn't quite 100 lines. Counting IO::File, Cwd, HTTP::Daemon and HTTP::Status, it comes out at about 1702 lines (244 + 808 + 167 + 385 + 98).

      Not to mention all those lines of C for the Perl interpreter.
      A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2024-07-24 16:15 GMT
Find Nodes?
    Voting Booth?

    No recent polls found

    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.