Undone previous changes as they would never work
[CGIscriptor.git] / CGIservlet.pl
blob1544df0361768c3dd86ac553383be4e015ee4ea4
1 #! /usr/bin/perl
3 # Put the full path to perl on the first line, run the program with
4 # `perl CGIservlet`, or put a symbolic link to perl in
5 # the startup directory if you need a special version of perl.
7 if(grep(/\-\-help/i, @ARGV))
9 print << 'ENDOFHELPTEXT';
10 # CGIservlet:
11 # A HTTPd "connector" for running CGI scripts on unix systems as WWW
12 # accessible Web sites. The servlet starts a true HTTP daemon that channels
13 # HTTP requests to forked daughter processes. CGIservlet.pl is NOT a
14 # full fledged server. Moreover, this servlet is definitely NOT intended
15 # as a replacement of a real server (e.g., Apache). It's design goal was
16 # SIMPLICITY, and not mileage.
18 # Note that a HTTP server can be accessed on your local machine WITHOUT
19 # internet access (but WITH a DNS?):
20 # use "http://localhost[:port]/[path]" or "http://127.0.0.1[:port]/[path]"
21 # as the URL. It is also easy to restrict access to the servlet to localhost
22 # users (i.e., the computer running the servlet).
24 # Suggested uses:
25 # - A testbed for CGI-scripts and document-trees outside the primary server.
26 # When developing new scripts and services, you don't want to mess up your
27 # current Web-site. CGIservlet is an easy way to start a temporary (private)
28 # server. CGIservlet allows to test separate HTTP server components, e.g.,
29 # user authentication, in isolation.
31 # - A special purpose temporary server (WWW everywhere/anytime).
32 # We run identification and other experiments over the inter-/intra-net using
33 # CGI-scripts. This means a lot of development and changes and only little
34 # actual run-time. The people doing this do not want "scripting" access to our
35 # departmental server with all its restrictions and security. So we need a
36 # small, lightweigth, easy-to-configure server that can be run by each
37 # investigator on her own account (and risk).
39 # - Interactive WWW presentations.
40 # Not everyone is content with the features of "standard" office presentation
41 # software. HTML and its associated browsers are an alternative (especially
42 # under Linux). However, you need a server to realize the full interactive
43 # nature of the WWW. CGIservlet with the necessary scripts can be run from
44 # a floppie (a Web server in 100 kB). The CGIservlet can actually run a
45 # (small) web site from RAM, without disk access (if you DO NOT use the
46 # 2>pid.log redirection on startup).
47 # With the "localhost" or "127.0.0.1" id in your browser you can use the
48 # servlet standalone.
50 # When the servlet is started with the -r option, only requests from "localhost"
51 # or "127.0.0.1" are accepted (default) or from addresses indicated after the
52 # -r switch.
54 # Running demo's and more information can be found at
55 # http://www.fon.hum.uva.nl/rob/OSS/OSS.html
58 ############################################################################
60 # Changes (document ALL changes with date, name and email here):
62 # 05 Apr 2013 - Renamed COOKIE_JAR into HTTP_COOKIE
63 # 28 Mar 2013 - Version 1.4.
64 # 18 Jun 2012 - Added --env, %UserEnv user defined ENV variables. Freeze %ENV.
65 # 06 Jun 2012 - Added HTTP Cookie string to an Environment variable: COOKIE_JAR
66 # 29 May 2012 - Added .log -> / to @RegAliasTranslation, blocks attempts to read
67 # log files.
68 # 22 May 2012 - Blocked "hidden" files and directories starting with "." in
69 # default @RegAliasTranslation. Removed obsolete CVS reference.
70 # 21 May 2012 - Inserted the -m[emory] switch for loading and serving from RAM.
71 # The option was mentioned in the manual, but the cli switch was
72 # never added.
73 # 22 Jul 2003 - Plain output using binary print io. `cat ...`
74 # 22 Jul 2003 - Added 'use CGI::Carp qw(fatalsToBrowser);' line
75 # for debugging. Standard this is commented out
76 # for security reasons (suggested by Jochen_Hayek@ACM.org).
77 # 22 Jul 2003 - Added error checking to doarg (suggested by Jochen_Hayek@ACM.org)
78 # 22 Jul 2003 - Removed SERVER_PORT from HTTP_HOST (Bug found by Jochen_Hayek@ACM.org)
79 # 22 Jul 2003 - Updated documentation. Added CGIservlet directory
80 # to the search path of CGIservletSETUP.pl
81 # 20 May 2003 - Made sure recycled (double) pid's do not mess up the
82 # @brood list and added a --help switch.
83 # 20 May 2003 - Added a maximum running time for child processes
84 # with command line switch -xterm.
85 # 15 Jan 2002 - Version 1.3
86 # 19 Oct 2001 - Included browsing of directories and a new -s
87 # security switch. With security toggled of
88 # directories can be browsed and all mime-types
89 # are served, either as 'text/plain' or as
90 # 'application/octed-stream'.
91 # 18 May 2001 - Added some HTTP HTTP lines.
92 # 13 Jun 2000 - Included the possibility to add POST request
93 # to GET query-strings (and change the request
94 # method). The -l ($Maxlength) maximum length
95 # option now covers POST requests too.
96 # 8 Dec 1999 - Included hooks for compression when running from RAM.
97 # 2 Dec 1999 - Autoflush enabled.
98 # 2 Dec 1999 - Allow running a Web Site from RAM.
99 # 2 Dec 1999 - Changed the behavior of CGIservletSETUP. CGIservlet
100 # will eval ALL setup files, the one in the CGIscriptor
101 # subdirectory (if any) AND the one in the current
102 # directory. (also added a close(SETUP) command)
103 # 26 Nov 1999 - Added some minimal security for 'automatic', out of
104 # the box installation.
105 # 26 Nov 1999 - Made the text/osshell mime-type functional (i.e.,
106 # without any scripts, implement a dynamic web server)
107 # Linited to '.cgi' extension.
108 # 26 Nov 1999 - Added aliasing of URL paths, both one-to-one lookups
109 # and full regular expression, i.e., $Path =~ s/.../.../g
110 # replace commands
111 # 28 Sep 1999 - Made all client supplied HTTP parameter names lowercase
112 # to handle inconsistencies in case use.
113 # 29 Jul 1999 - Allowed for a SETUP configuration file 'CGIservletSETUP.pl'.
114 # Use $beginarg from the 'CGIscriptor/' directory if it exists.
115 # (R.J.J.H.vanSon@gmail.com)
118 ############################################################################
120 # Known bugs
122 # 23 Mar 2000 - An odd server side network error is reported by Netscape
123 # when a Post is initiated from a Javascript Submit of a
124 # <FORM>. This was found on Red Hat 6.1 Linux with perl 5.00503,
125 # 5.00503 and 5.6.0. But not on IRIX or Red Hat 5.0, 7.x.
127 ############################################################################
130 # Inner workings:
131 # Whenever an HTTP request is received, the specified CGI script is
132 # started inside a child process as if it was inside a real server (e.g.,
133 # Apache). The evironment variables are set more or less as in Apache.
134 # Note that CGIservlet only uses a SINGLE script for ALL requests.
135 # No attemps for security are made, it is the script's responsibility to
136 # check access rights and the validity of the request.
137 # When no scripts are given, CGIservlet runs as a bare bone WWW server
138 # configurable to execute scripts (the default setting is as a
139 # STATIC server).
141 # Author and copyright (c) :
142 # Rob van Son
143 # email:
144 # R.J.J.H.vanSon@gmail.com
145 # r.v.son@nki.nl
146 # NKI/AVL Amsterdam
148 # copying freely from the mhttpd server by Jerry LeVan (levan@eagle.eku.edu)
149 # Date: July 22, 2012
150 # Version:1.4
151 # Env: Perl 5.002 and later
154 ################################################################################
156 # LICENSE #
158 # This program is free software; you can redistribute it and/or #
159 # modify it under the terms of the GNU General Public License #
160 # as published by the Free Software Foundation; either version 2 #
161 # of the License, or (at your option) any later version. #
163 # This program is distributed in the hope that it will be useful, #
164 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
165 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
166 # GNU General Public License for more details. #
168 # You should have received a copy of the GNU General Public License #
169 # along with this program; if not, write to the Free Software #
170 # Foundation, Inc., 59 Temple Place - Suite 330, #
171 # Boston, MA 02111-1307, USA. #
173 ################################################################################
175 # Note: CGIservlet.pl was directly inspired by Jerry LeVan's
176 # (levan@eagle.eku.edu) simple mhttpd server which again was
177 # inspired by work of others. CGIservlet is used as a bare bones
178 # socket server for a single CGI script at a time.
180 # Use: CGIservlet.pl -<switch> <argument> 2>pid.log & (sh/bash)
181 # CGIservlet.pl -<switch> <argument> >&pid.log & (csh)
183 # The servlet prints out pid and port number on STDERR. It is
184 # adviced to store these in a separate file (this will become the
185 # error log).
186 # NOTE: When running CGIservlet from a Memmory Image (i.e. RAM),
187 # do NOT redirect the error output to a file, but use something
188 # like MAILTO or /dev/null!
190 # Stop: sh pid.log (kills the server process)
192 # The first line in the file that receives STDERR output is a command
193 # to stop CGIservlet.
195 # examples:
196 # CGIservlet.pl -p 2345 -d /cgi-bin/CGIscriptor.pl -t /WWW 2>pid.log &
197 # CGIservlet.pl -p 8080 -b 'require "CGIscriptor.pl";' -t $PWD -e \
198 # 'Handle_Request();' 2>pid.log &
200 # The following example settings implement a static WWW server using 'cat'
201 # (and prohibiting Queries):
202 # -p 8008
203 # -t `pwd`
204 # -b ''
205 # -e
206 # '$ENV{QUERY_STRING}="";$ENV{PATH_INFO}=~/\.([\w]+)$/; "Content-type: ".$mimeType{uc($1)}."\n\n";'
207 # -d 'cat -u -s'
208 # -w '/index.html'
209 # -c 32
210 # -l 512
212 # This is identical to the (static) behaviour of CGIservlet when
213 # -e '' -d '' -x '' is used.
214 # The CGIservlet command should be run from the intended server-root directory.
216 # Another setting will use a package 'CGIscriptor.pl' with a function
217 # 'HandleRequest()' to implement an interactive WWW server with inline
218 # Perl scripting:
219 # -p 8080
220 # -t `pwd`
221 # -b 'require "CGIscriptor.pl";'
222 # -e 'HandleRequest();'
223 # -d ''
224 # -w '/index.html'
225 # -c 32
226 # -l 32767
228 # Look below or in the CGIservletSETUP.pl file for the current default
229 # settings.
232 # ###############################################################################
234 # There are many switches to tailor the workings of CGIservlet.pl.
235 # Some are fairly esoteric and you should only look for them if you
236 # need something special urgently. When building a Web site,
237 # the specific options you need will "suggest" themselves (e.g., port
238 # number, script, or server-root directory). Most default settings
239 # should work fine.
241 # You can add your own configuration in a file called
242 # 'CGIservletSETUP.pl'. This file will be executed ("eval"-ed)
243 # after the default setup, but before the command line options take
244 # effect. CGIservlet looks for the SETUP file in the startup directory
245 # and in the CGIscriptor subdirectory.
246 # (Note that the $beginarg variable is evaluated AFTER the setup file).
248 # In any case, it is best to change the default settings instead of
249 # using the option switches. All defaults are put in a single block.
251 # switches and arguments:
252 # Realy important
253 # -p[ort] port number
254 # For example -p 2345
255 # Obviously the port CGIservlet listenes to. Suggested Default: -p 8008
257 # -a[lias] Alias1 RealURL1 ...
258 # For example -a '/Stimulus.aifc' '/catAIFC.xmr'
259 # Replaces the given Alias URL path by its real URL path. Accepts full
260 # regular expressions too (identified by NON-URL characters).
261 # That is, on each request it performs (in order):
262 # if($AliasTranslation{$Path})
263 # {
264 # $Path = $AliasTranslation{$Path};
266 # elsif(@RegAliasTranslation)
267 # {
268 # my $i;
269 # for($i=0; $i<scalar(@RegAliasTranslation); ++$i)
270 # {
271 # my $Alias = $RegAliasTranslation[$i];
272 # my $RealURL = $RegURLTranslation[$i];
273 # last if ($Path =~ s#$Alias#$RealURL#g);
274 # };
275 # };
276 # The effects can be quite drastic, so be
277 # carefull. Note also, that entering many Regular Expression
278 # aliases could slow down your servlet. Checking stops after
279 # the first match.
280 # Full regular expression alias translations are done in the
281 # order given! They are recognized as Aliases containing
282 # regexp's (i.e., non-URL) operator characters like '^' and
283 # '$'.
284 # Note: The command line is NOT a good place for entering
285 # Aliases, change the code below or add aliases to
286 # CGIservletSETUP.pl.
288 # --help
289 # Prints the manual
291 # Script related
292 # -b[egin] perl commands
293 # For example -b 'require "CGIscriptor.pl";' or
294 # 'require "/WWW/cgi-bin/XMLelement.pl";'
295 # Perl commands evaluated at server startup
297 # -d[o] perl script file
298 # For example -d '/WWW/cgi-bin/CGIscriptor.pl'
299 # The actual CGI-script started as a perl {do "scriptfile"} command.
300 # The PATH_INFO and the QUERY are pushed on @ARGV.
302 # -x shell command
303 # -qx shell command
304 # -exec shell command
305 # OS shell script or command, e.g., -x 'CGIscriptor.pl' or
306 # -x '/WWW/cgi-bin/my-script'
307 # The actual CGI-script started as `my-script \'$Path\' \'$QueryString\'`.
308 # -qx and -exec[ute] are aliases of -x. For security reasons, Paths or
309 # queries containing '-quotes are rejected.
311 # -e[val] perl commands
312 # For example -e 'Handle_Request();'
313 # The argument is evaluated as perl code. The actual CGI-script
314 # can be loaded once with -b 'require module.pm' and you only have to
315 # call the central function(s).
317 # WWW-tree related
318 # -t[extroot] path
319 # For example -t "$PWD" or -t "/WWW/documents"
320 # The root of the server hierachy. Defaults to the working directory
321 # at startup time (`pwd`)
323 # -w[elcome] filepath
324 # For example -w "/index.html" (default)
325 # The default welcome page used when no path is entered. Note that
326 # this path can point to anything (or nothing real at all).
328 # Security related
329 # The following arguments supply some rudimentary security. It is the
330 # responsibility of the script to ensure that the requests are indeed
331 # "legal".
333 # -c[hildren] maximum child processes
334 # For example -c 32
335 # The maximum number of subprocesses started. If there are more requests,
336 # the oldest requests are "killed". This should take care of "zombie"
337 # processes and server overloading. Note that new requests will be
338 # serviced irrespective of the success of killing it's older siblings.
340 # -xtime maximum running time of a child
341 # For example -xtime 36000
342 # The maximum time a child may run in seconds. After a new request has
343 # been servised, all children that have run for longer than this time
344 # will be killed. This stops runaway processes, often connected to
345 # web-crawlers.
347 # -l[ength] maximum length of HTTP request in bytes
348 # For example -l 32768
349 # This prevents overloading the server with enormous queries. Reading of
350 # requests simply stops when this limit is reached. This DOES affect
351 # POST requests. If the combined length of the COMPLETE HTTP request,
352 # including headers, exceeds this limit, the whole request is dropped.
354 # -r[estrict] [Remote-address [Remote-host]]
355 # For example -r 127.0.0.1 (default of -r)
356 # A space separated list of client IP addresses and/or domain names that
357 # should be serviced. Default, i.e., '-r' without any addresses or domain
358 # names, is the localhost IP address '127.0.0.1'.
359 # When using CGIservlet for local purposes only (e.g., development or a
360 # presentation), it would be unsafe to allow others to access the servlet.
361 # If -r is used (or the corresponding @RemoteAddr or @RemoteHost lists are
362 # filled in the code below), all requests from clients whose Remote-address
363 # or Remote-host do not match the indicated addresses will be rejected.
364 # Partial addresses and domain names are allowed. Matching is done according
365 # to Remote-addr =~ /^\Q$pattern\E/ (front to back) and
366 # Remote-host =~ /\Q$pattern\E$/ (back to front)
368 # --env name=value,name=value
369 # Watch double dash. Define $ENV{name}=value for every pair. These are
370 # internally stored in %UserEnv, eg, $UserEnv{name}=value; This is set anew
371 # in the Child with every request. That is, Changes in %ENV are not stored.
373 # -s[ecure]
374 # No arguments.
375 # A toggle switch that blocks all access to files with undefined
376 # mime-types (or to serve ascii files as "text/plain"), and blocking directory
377 # browsing. Defaults to blocking what is not explicitely allowed.
379 # -m[emory]
380 # No arguments.
381 # Reads complete Web site into memory and runs from this image.
382 # Set $UseRAMimage = 1; to activate memory-only running.
383 # Under certain circumstance, this can improve security.
384 # Note, however, that running osshellscripts from this image
385 # makes any "security" related claims very shaky.
387 # Speedup
388 # -n[oname]
389 # No arguments.
390 # Retrieving the domain name of the Client (i.e., Remote-host) is a
391 # very slow process and normally useless. To skip it, enter this
392 # option. Note that you cannot use '-r Remote-host' anymore after
393 # you enter -n, only IP addresses will work.
395 # Configuration with the CGIservletSETUP.pl file
397 # You can add your own configuration in a file
398 # called 'CGIservletSETUP.pl'. This file will be executed ("eval"-ed)
399 # after the default setup, but before the command line options take
400 # effect. CGIservlet looks for the SETUP file in the startup directory
401 # and in the CGIservlet and CGIscriptor subdirectories.
402 # (Note that the $beginarg variable is evaluated even later).
404 # Changing POST to GET requests
406 # CGIservlet normally only handles requests with the GET method. Processing
407 # the input from POST requests is left to the reading application. POST
408 # requests add some extra complexity to processing requests. Sometimes,
409 # the reading application doesn't handle POST requests. CGIservlet
410 # already has to manage the HTTP request. Therefore, it can easily
411 # handle the POST request. If the variable $POSTtoGET is set to any
412 # non-false value, the content of whole POST request is added to the
413 # QUERY_STRING environment variable (preceeded by a '&' if necessary).
414 # The content-length is set to 0. If $POSTtoGET equals 'GET', the method
415 # will also be changed to 'GET'.
417 # remarks:
418 # All of the arguments of -d, -e, and -x are processed sequentially
419 # in this order. This might not be what you want so you should be
420 # carefull when using multiple executable arguments.
421 # If none of the executable arguments is DEFINED (i.e., they are entered
422 # as -d '' -e '' -x ''), each request is treated as a simple
423 # text-retrieval. THIS CAN BE A SECURITY RISK!
425 # The wiring of an interactive web-server, which also calls shell
426 # scripts with the extension '.cgi', is in place. You can
427 # "activate" it by changing the "my $ExecuteOSshell = 0;" line to
428 # "my $ExecuteOSshell = 1;".
429 # If you have trouble doing this, it might be a good idea
430 # to reconsider using a dynamic web server. Executing shell
431 # scripts inside a web server is a rather dangerous practise.
433 # CGIservlet can run its "standard" web server from memory.
434 # At startup, all files are read into a hash table. Upon
435 # request, the contents of the file are placed in the
436 # environment variable: CGI_FILE_CONTENTS.
437 # No further disk access is necessary. This means that:
438 # 1 CGIservlet can run a WWW site from a removable disk,
439 # e.g., a floppy
440 # 2 The web servlet can run without any read or write privilege.
441 # 3 The integrity of the Web-site contents can be secured at the
442 # level you want
444 # To compres the memory (RAM) immage, you should hook the
445 # compression function to
446 # $CompressRAMimage = sub { return shift;};
447 # and the decompression function to
448 # $DecompressRAMimage = sub { return shift;};
451 ENDOFHELPTEXT
452 exit;
454 ###################################################################################
456 require 5.002;
457 use strict; # Should realy be used!
458 use Socket;
459 use Carp; # could come in handy (can be missed, I think)
461 # For debugging: uncommenting the use-line below will send
462 # nicely formanted output to the client. However, it is
463 # generally not a good idea to enable clients to test your
464 # scripts and look for holes (SECURITY).
465 # use CGI::Carp qw(fatalsToBrowser);
467 $| = 1; # Autoflush (i'm not sure whether this is usefull)
469 my $version = "1.301";
470 my $program = "CGIservlet.pl";
472 ##################################################################
474 # print some information to STDERR, e.g., the process number #
476 ##################################################################
477 sub logmsg { print STDERR "kill -KILL $$;exit;\n", # Stop CGIservlet
478 "$0 $$: @_ at ", scalar localtime, "\n" }
480 ############################################################
482 # Parse arguments (you can define DEFAULT VALUES here) #
484 ############################################################
486 my $port = 8008; # The port number
488 # Add POST requests to the QUERY_STRING, change method to
489 # GET if the value is 'GET'
490 my $POSTtoGET = 0; # Add POST requests to the query string
492 # (Fast) direct translation of full URL paths
493 my %AliasTranslation = (); # Alias => RealURL pairs (ONLY paths)
494 # Regular expression alias translation, in order of application
495 # (this can be quite slow)
496 my @RegAliasTranslation = ('^(\..*|.*/\..*)$','\.htm$', '^.*\.log$'); # Full regular expression alias/url pairs: URL
497 my @RegURLTranslation = ('/','.html', '/'); # Full regular expression alias/url pairs: PATH
499 my $textroot = $ENV{'PWD'} || `pwd`; # current working directory
500 chomp($textroot); # Remove nasty newline, if present
501 my $doarg = ''; # do "filename",
503 my $beginarg = ''; # eval($Argument) at the start of the program
504 my $evalarg = ''; # eval($Argument) for each request
505 my $execarg = ''; # execute `command \'$textroot$Path\' \'$QueryString\'`
507 my $welcome = '/index.html'; # Default path
509 # Rudimentary security, overflow detection
510 my $MaxBrood = 32; # Maximum number of running children
511 my $MaxTime = 36000; # Maximum time a child may run in seconds
512 my $MaxLength = 2**15; # Maximum Request Length
513 my $Secure = 1; # Block browsing directories and text files or not
514 my %UserEnv = ();
516 # If one of the following lists contains any client addresses or names, all others are
517 # blocked (be carefull, your site will be inaccessible if you misspell them).
518 my @RemoteHost = (); # Accepted Hosts, suggest: localhost
519 my @RemoteAddr = (); # Accepted IP addresses, suggest: @RemoteAddr=('127.0.0.1')
520 my $DefaultRemoteAddr = '127.0.0.1'; # default, use localhost IP address
521 my $NONAME = 0; # if 1, do NOT ask for REMOTE_HOST (faster)
523 # Initialization ready
524 my %FrozenEnv = %ENV; # Freeze %ENV
526 # Store the whole Web Site in a hash table and use this RAM memory image (if non-zero)
527 my $UseRAMimage = 0;
528 # Empty function handlers for data compression
529 # In general, these must be redefined in the $beginarg
530 my $CompressRAMimage = sub { return shift;};
531 my $DecompressRAMimage = sub { return shift;};
533 # Execute shell CGI scripts when no -d, -e, or -x are supplied
534 my $ExecuteOSshell = 0; # Do you REALY want this? It is dangerous
536 #################################################################
538 # Configure CGIservlet with a setup file (overides the #
539 # default settings, but not the command line options). #
540 # Note that, if it exists, the setup file in the CGIscriptor #
541 # subdirectory is processed EVEN if there is a SETUP file #
542 # in the current directory. #
544 #################################################################
545 # There exists a CGIservlet subdirectory and it contains
546 # a CGIservletSETUP.pl file
547 if((-e './CGIservlet/CGIservletSETUP.pl') &&
548 open(SETUP, '<./CGIservlet/CGIservletSETUP.pl'))
550 # Get the setup code
551 my $SetupCode = join("", <SETUP>);
552 # 'Eval' is used to ensure that the values are entered in the current
553 # package (contrary to what 'do' and 'require' do).
554 (eval $SetupCode) || die "$! $@\n";
555 close(SETUP);
557 # There exists a CGIscriptor subdirectory and it contains
558 # a CGIservletSETUP.pl file
559 if((-e './CGIscriptor/CGIservletSETUP.pl') &&
560 open(SETUP, '<./CGIscriptor/CGIservletSETUP.pl'))
562 # Get the setup code
563 my $SetupCode = join("", <SETUP>);
564 # 'Eval' is used to ensure that the values are entered in the current
565 # package (contrary to what 'do' and 'require' do).
566 (eval $SetupCode) || die "$! $@\n";
567 close(SETUP);
569 # There is a CGIservletSETUP.pl file in the current directory
570 if((-e './CGIservletSETUP.pl') &&
571 open(SETUP, '<./CGIservletSETUP.pl'))
573 # Get the setup code
574 my $SetupCode = join("", <SETUP>);
575 # 'Eval' is used to ensure that the values are entered in the current
576 # package (contrary to what 'do' and 'require' do).
577 (eval $SetupCode) || die "-e $SetupCode: $! $@\n";
578 close(SETUP);
581 ######################################
583 # process arguments and defaults #
585 ######################################
587 while ($_ = shift(@ARGV))
589 # With switches
590 if(/\-p/is) # Port
592 $port = shift(@ARGV);
594 elsif(/\-d/is) # Do
596 $doarg = shift(@ARGV);
598 elsif(/\-(x|qx|exec)/is) # Execute
600 $execarg = shift(@ARGV);
602 elsif(/\-b/is) # Begin
604 $beginarg = shift(@ARGV);
606 elsif(/^\-e/is) # Evaluate
608 $evalarg = shift(@ARGV);
610 elsif(/\-t/is) # Textroot
612 $textroot = shift(@ARGV);
614 elsif(/\-w/is) # Default welcome page
616 $welcome = shift(@ARGV);
618 elsif(/\-c/is) # Maximum Children
620 $MaxBrood = shift(@ARGV) || $MaxBrood;
622 elsif(/\-xtime/is) # Maximum running time
624 $MaxTime = shift(@ARGV) || $MaxTime;
626 elsif(/\-l/is) # Maximum Length
628 $MaxLength = shift(@ARGV) || $MaxLength;
630 elsif(/\-m/is) # Run from RAM
632 $UseRAMimage = 1;
634 elsif(/\-a/is) # Aliases
636 while(@ARGV && $ARGV[0] !~ /^\-/) # while not a parameter
638 my $Alias = shift(@ARGV);
639 my $RealURL = $ARGV[0] !~ /^\-/ ? shift(@ARGV) : "";
640 next unless $Alias && $RealURL;
641 # Store the alias
642 # Simple straight translations
643 unless($Alias =~ m/[\$\Q^*&@!\?(){}[];:\E]/)
645 $AliasTranslation{$Alias} = $RealURL;
647 else # Full regular expressions
649 push(@RegAliasTranslation, $Alias);
650 push(@RegURLTranslation, $RealURL);
655 elsif(/\-r/is) # Remote host or address
657 while(@ARGV && $ARGV[0] !~ /^\-/) # while not a parameter
659 my $Remote = shift(@ARGV);
660 if($Remote =~ /[\d\.]+/) # A host IP address
662 push(@RemoteAddr, $Remote);
664 else # A host domain name, less secure
666 push(@RemoteHost, $Remote);
670 # Use the default Remote Host (Client) IP address (e.g., localhost)
671 # if no addresses or domain names are entered.
672 push(@RemoteAddr, $DefaultRemoteAddr) unless @RemoteAddr || @RemoteHost;
674 elsif(/^\-\-env/is) # Environment variables
676 while(@ARGV && $ARGV[0] !~ /^\-/) # while not a parameter
678 my $envlist = shift(@ARGV);
679 foreach my $envstring (split(',', $envlist))
681 my ($name, $value) = split('=', $envstring);
682 next unless $name;
683 # Store the Environment variable
684 $UserEnv{$name} = $value;
688 elsif(/\-s/is) # Secure or not
690 $Secure = !$Secure; # Toggle blocking directory browsing and ASCII file access
692 elsif(/\-n/is) # Do NOT extract Remote host
694 $NONAME = 1;
696 else # perform unreliable magick without switches
698 if(/^[0-9]+$/ && $_ > 1024) # A (large) number must be a port
700 $port = $_;
702 elsif(-T && /\.pl$/) # Text file with extension .pl is a Perl file
704 $doarg = $_;
706 elsif(-T && /\.pm$/) # Text file with extension .pm is a Perl module file
708 $beginarg = $_;
710 elsif(-x) # Executables can be executed
712 $execarg = $_;
714 elsif(-d) # A directory can only be the root
716 $textroot = $_;
718 elsif(-T && /^\// && /\.html$/) # An html file path is the default path
720 $welcome = $_;
722 elsif(-T) # A text file is something to do
724 $doarg = $_;
726 elsif(/[\s\{\`\[\@\%]/) # I give up, just try it
728 $evalarg = shift(@ARGV);
733 ################################################
735 # All argument values are known. #
736 # Initialize environment variables. #
737 # (should be accessible to eval($beginarg)) #
739 ################################################
741 # Initialize %ENV
742 $ENV{'SERVER_SOFTWARE'} = "$program $version";
743 $ENV{'GATEWAY_INTERFACE'} = "CGI/1.1";
744 $ENV{'SERVER_PORT'} = "$port";
745 $ENV{'CGI_HOME'} = $textroot;
746 $ENV{'SERVER_ROOT'} = $textroot; # Server Root Directory
747 $ENV{'DOCUMENT_ROOT'} = $textroot; # Server Root Directory
748 $ENV{'SCRIPT_NAME'} = $doarg.$execarg.$evalarg; # Combine executable arguments
750 $FrozenEnv{'SERVER_SOFTWARE'} = $ENV{'SERVER_SOFTWARE'};
751 $FrozenEnv{'GATEWAY_INTERFACE'} = $ENV{'GATEWAY_INTERFACE'};
752 $FrozenEnv{'SERVER_PORT'} = $ENV{'SERVER_PORT'};
753 $FrozenEnv{'CGI_HOME'} = $ENV{'CGI_HOME'};
754 $FrozenEnv{'SERVER_ROOT'} = $ENV{'SERVER_ROOT'}; # Server Root Directory
755 $FrozenEnv{'DOCUMENT_ROOT'} = $ENV{'DOCUMENT_ROOT'}; # Server Root Directory
756 $FrozenEnv{'SCRIPT_NAME'} = $ENV{'SCRIPT_NAME'}; # Combine executable arguments
758 ################################################
760 # The initial argument should be evaluated #
762 ################################################
764 eval($beginarg) if $beginarg;
766 ################################################
768 # The initial argument has been evaluated #
770 ################################################
772 # Socket related code
773 my $proto = getprotobyname('tcp');
774 $port = $1 if $port =~ /(\d+)/; # untaint port number
776 socket(Server, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";
777 setsockopt(Server, &SOL_SOCKET, &SO_REUSEADDR,
778 pack("l", 1)) || die "setsockopt: $!";
779 bind(Server, sockaddr_in($port, INADDR_ANY)) || die "bind: $!";
780 listen(Server,SOMAXCONN) || die "listen: $!";
783 # Report start of server
784 logmsg "server started on port $port";
786 # Set up SIG vector (every signal will kill the process that receives it)
787 $SIG{CHLD} = 'IGNORE';
788 $SIG{'KILL'} = "SigHandler";
789 $SIG{'TERM'} = "SigHandler";
790 $SIG{'QUIT'} = "SigHandler";
791 $SIG{'HUP'} = "SigHandler";
793 # Define text mime types served if no scripts are defined
794 # Note that the "text/osshell" mime-type is executed by CGIservlet ITSELF!
795 # You should remove it if you don't want that!
796 my %mimeType = (
797 'HTML'=> "text/html",
798 'TXT' => "text/plain",
799 'PL' => "text/plain", # This is incorrect, of course
800 'JPG' => "image/jpeg",
801 'JPEG' => "image/jpeg",
802 'GIF' => "image/gif",
803 'AU' => "audio/basic",
804 'AIF' => "audio/aiff",
805 'AIFC' => "audio/aiff",
806 'AIFF' => "audio/aiff",
807 'GZ' => "application/gzip",
808 'TGZ' => "application/tar",
809 #'CGI' => "text/osshell", # Executes SERVER side shell scripts, HIGHLY DANGEROUS
810 'WAV' => "audio/wav",
811 'OGG' => "audio/x-vorbis",
812 'PDF' => "application/pdf",
813 'PS' => "application/postscript"
816 ################################################
818 # Fill the RAM image of the web site #
820 ################################################
822 my %WWWramImage = ();
823 if($UseRAMimage)
825 my $TotalSize = 0;
826 my @WWWfilelist = `find $textroot ! -type l ! -type d -print`;
827 my $WWWfile;
828 foreach $WWWfile (@WWWfilelist)
830 chomp($WWWfile);
831 # Skip unsupported file types
832 $WWWfile =~ /\.(\w+)$/;
833 my $WWWfileExtension = uc($1);
834 next unless $mimeType{$WWWfileExtension};
835 # Store GnuZipped image of file
836 $WWWramImage{$WWWfile} = "";
837 open(FILEIN, "<$WWWfile") || die "$WWWfile could not be opened: $!\n";
838 my $Buffer;
839 while(sysread(FILEIN, $Buffer, 1024))
841 $WWWramImage{$WWWfile} .= $Buffer;
843 # Apply compression
844 my $CompressedPtr = &$CompressRAMimage(\${WWWramImage{$WWWfile}});
845 $WWWramImage{$WWWfile} = $$CompressedPtr;
846 $TotalSize += length($WWWramImage{$WWWfile});
849 # Report size of Web RAM image
850 print STDERR "Total number of $TotalSize bytes read in memory image\n";
853 ################################################
855 # The RAM image of the web site has been #
856 # filled. #
858 ################################################
860 # Map HTTP request parameters to Environment variables
861 # HTTP request => Environment variable
862 my %HTTPtype = (
863 'content-length' => 'CONTENT_LENGTH', # Necessary for POST
864 'user-agent' => 'HTTP_USER_AGENT',
865 'accept' => 'HTTP_ACCEPT',
866 'content-type' => 'CONTENT_TYPE',
867 'auth-type' => 'AUTH_TYPE',
868 'ident' => 'REMOTE_IDENT',
869 'referer' => 'HTTP_REFERER',
870 'user' => 'REMOTE_USER',
871 'address' => 'REMOTE_ADDR',
872 'connection' => 'HTTP_CONNECTION',
873 'accept-language' => 'HTTP_ACCEPT_LANGUAGE',
874 'accept-encoding' => 'HTTP_ACCEPT_ENCODING',
875 'accept-charset' => 'HTTP_ACCEPT_CHARSET',
876 'host' => 'HTTP_HOST',
877 'cookie' => 'HTTP_COOKIE'
880 ###############################################################################
882 # Now we start with the real work. When there is a request, get the required #
883 # values and fork a child to service it. #
885 ###############################################################################
887 my @brood = ();
888 my %StartTime = (); # Start time of the children
889 my $child;
891 # When someone knocks on the door
892 for (;;)
894 my $paddr;
896 if(!($paddr = accept(Client,Server)) ) # Knock knock
898 exit 1; # This went terrribly wrong
901 # Fork to child and parent
902 if(($child =fork()) == 0)
904 # this is the child
905 # The child does not need a PID list of the parent
906 @brood = ();
907 %StartTime = ();
909 # Read stuff
910 my ($port,$iaddr) = sockaddr_in($paddr);
911 my $address = inet_ntoa($iaddr); # The IP address of the Client
912 # The following is EXTREMELY slow and generally unnecessary.
913 # Use -n or set $NONAME = 1; if you don't need it.
914 my $name = $NONAME ? '' : gethostbyaddr($iaddr,AF_INET);
915 my @Input = ();
918 # Before doing anything else, check whether the client should be
919 # served at all.
920 # Is IP addr on the list?
921 if(@RemoteAddr && !grep(/^\Q$address\E/, @RemoteAddr))
923 print STDERR "Reject $address $name\n";
924 exit 1;
926 # Is name on the list?
927 if(@RemoteHost && !grep(/\Q$name\E$/, @RemoteHost))
929 print STDERR "Reject $name $address\n";
930 exit 1;
934 # Grab a line without using buffered input... Important for
935 # Post methods since they have to read the Client input stream.
937 my $string = "";
938 my $ch = "";
939 my $HTTPlength = 0;
940 alarm 120 ; # prevent deadly spin if other end goes away
941 while(sysread(Client, $ch, 1)>0)
943 $string .= $ch;
944 ++$HTTPlength;
945 last if $HTTPlength > $MaxLength; # Protect against overflow
947 next if $ch eq "\r"; # skip <cr>
948 if($ch eq "\n")
950 last unless $string =~ /\S/; # stop if empty line
951 push (@Input, split(' ', $string)); # Collect input in list
952 $string = "";
955 alarm 0; # clear alarm
957 # Reset %ENV
958 foreach my $varname (keys(%FrozenEnv))
960 $ENV{$varname} = $FrozenEnv{$varname};
963 # Extract input arguments
964 my $method = shift(@Input);
965 my $Request = shift(@Input);
966 my $protocol = shift(@Input);
967 my ($Path, $QueryString) = split('\?', $Request);
969 # Get rest of Input
970 my $HTTPparameter;
971 my %HTTPtable = ();
972 while($HTTPparameter = lc(shift(@Input)))
974 chop($HTTPparameter);
975 $HTTPtable{$HTTPparameter} = "";
976 while(@Input && $Input[0] !~ /\:$/)
978 $HTTPtable{$HTTPparameter} .= " " if $HTTPtable{$HTTPparameter};
979 $HTTPtable{$HTTPparameter} .= shift(@Input);
982 # Host can get the :SERVER_PORT appended. Set the correct SERVER_PORT
983 # and remove it from the host.
984 if($HTTPtable{'host'})
986 # Store current port number
987 if($HTTPtable{'host'} =~ /\:(\d+)\s*$/)
989 $ENV{'SERVER_PORT'} = $1;
991 # Remove port number from host
992 $HTTPtable{'host'} =~ s/\:(\d+)\s*$//g;
995 # Translate the Aliases
996 $Path = GetAlias($Path);
998 # HTTP servers should always add the default path
999 $Path = $welcome if !$Path || $Path eq '/'; # The common default path
1001 # Set fixed environment variables
1002 $ENV{'PATH_INFO'} = "$Path";
1003 $ENV{'QUERY_STRING'} = "$QueryString";
1004 $ENV{'PATH_TRANSLATED'} = "$textroot$Path";
1005 $ENV{'SERVER_PROTOCOL'} = "$protocol";
1006 $ENV{'REQUEST_METHOD'} = "$method";
1007 $ENV{'REMOTE_ADDR'} = "$address"; # The IP address of the Client
1008 $ENV{'REMOTE_HOST'} = "$name";
1010 # Load all request information in the %ENV.
1011 # MUST be done with a pre-defined list of parameter names (security).
1012 foreach $HTTPparameter (keys(%HTTPtype))
1014 my $Label = $HTTPtype{$HTTPparameter};
1015 # The following adds environment variables FROM THE REQUEST.
1016 # It is a VERY, VERY bad idea to just use the client supplied
1017 # parameter names!
1018 $ENV{$Label} = $HTTPtable{$HTTPparameter} unless exists($ENV{$Label});
1019 # (The last part prevents overwriting existing environment variables)
1022 # SECURITY: Check length of POST request. Stop if request is too long
1023 die if $HTTPlength + $ENV{'CONTENT_LENGTH'} > $MaxLength;
1025 # If POST requests are unwanted, they can be added tot the query string
1026 # NOTE: the method is set to GET if $POSTtoGET equals 'GET', otherwise,
1027 # the method stays POST and only the content length is set to 0
1028 if($POSTtoGET && $ENV{'REQUEST_METHOD'} =~ /^POST$/i)
1030 my $POSTlength = $ENV{'CONTENT_LENGTH'} || 0;
1031 my $ReadBytes = 1;
1033 # Add '&' if there is a query string already
1034 if($ENV{'QUERY_STRING'})
1036 # Before we add something to the string, check length again
1037 die if $HTTPlength + $ENV{'CONTENT_LENGTH'} + 1 > $MaxLength;
1038 # Now add the '&'
1039 $ENV{'QUERY_STRING'} .= '&';
1042 # Read Client
1043 while($POSTlength > 0 && $ReadBytes > 0)
1045 my $Read = "";
1046 $ReadBytes = sysread(Client, $Read, $POSTlength);
1047 $ENV{'QUERY_STRING'} .= $Read;
1048 $POSTlength -= $ReadBytes;
1051 # All has been read, the content length becomes 0
1052 $ENV{'CONTENT_LENGTH'} = 0;
1053 # Method can change
1054 $ENV{'REQUEST_METHOD'} = 'GET' if $POSTtoGET eq 'GET';
1057 # Reset User defience Env variables
1058 foreach my $varname (keys(%UserEnv))
1060 $ENV{$varname} = $UserEnv{$varname};
1062 # Clean out the User Environment variables in the child
1063 %UserEnv = ();
1066 # Connect STDOUT and STDIN to the client
1067 open(STDIN, "<&Client");
1068 open(STDOUT, ">&Client");
1069 print STDOUT "HTTP/1.1 200 OK\n"; # Supply HTTP protocol information
1070 print STDOUT "Date: ".gmtime()." GMT\n"; # Current date
1071 print STDOUT "Server: $program $version\n"; # This program
1072 print STDOUT "Connection: close\n"; # Don't allow persistent connections
1074 # Start processing of request (note that ALL scripts will be executed if
1075 # present, i.e., if -d, -x, and -e are entered, they are alle processed).
1077 # If in memory-only mode, store the requested file in an environment
1078 # variable: CGI_FILE_CONTENTS
1079 undef($ENV{'CGI_FILE_CONTENTS'}); # Make sure the ENV var doesn't exist
1080 if($UseRAMimage)
1082 my $DecompressedPtr = &$DecompressRAMimage(\${WWWramImage{"$textroot$Path"}});
1083 $ENV{'CGI_FILE_CONTENTS'} = $$DecompressedPtr;
1084 # Decompression does not seem to work
1087 # do perl script
1088 @ARGV = ("$textroot$Path", $QueryString);
1089 # This was suggested by Jochen_Hayek@ACM.org
1090 if($doarg)
1092 # The perl script should do the printing
1093 my ($return) = do "$doarg";
1095 warn "couldn't parse $doarg: $@" if $@;
1096 warn "couldn't $doarg: $!" unless defined $return;
1097 warn "couldn't run $doarg" unless $return;
1100 # evaluate perl command
1101 print STDOUT eval($evalarg) if $evalarg;
1103 # execute shell command
1104 if($execarg)
1106 my $shellscript = $execarg;
1108 # Attempts to use Paths or Queries containing '-quotes are rejected.
1109 # Executing these would compromise security.
1110 die "Quotes in path: $textroot$Path\n" if "$textroot$Path" =~ /\'/;
1111 $shellscript .= " '$textroot$Path'" if $Path;
1113 die "Quotes in query: $QueryString\n" if $QueryString =~ /\'/;
1114 $shellscript .= " '$QueryString'" if $QueryString;
1115 $shellscript = qx{$shellscript};
1116 print STDOUT $shellscript;
1119 # Output files if no scripts are given (actually, this should be
1120 # handled by a script). Unknown mimetypes are killed.
1121 # This is more or less a functional (dynamic) Web server in itself.
1122 unless($doarg || $execarg || $evalarg) # Request not already handled
1124 die ".. trick: $address $name $Path $QueryString\n"
1125 if $Path =~ m@\.\./@ ; # No tricks!
1127 # Handle mime-types and directory browsing
1128 $Path =~ /\.([\w]+)$/; # Get extension
1129 my $extension = uc($1);
1130 my $browse = ($Path =~ m@/\s*$@ || -d "$textroot$Path") ? 1 : 0;
1131 my $mime = $browse ? "" : $mimeType{$extension};
1133 # Serve up text and binary files unless they the $Secure option is given
1134 $mime = "text/plain" if !$mime && !$browse && (-T "$textroot$Path") && !$Secure;
1135 $mime = "application/octet-stream" if !$mime && !$browse && (-B "$textroot$Path") && !$Secure;
1137 # Remove final / in directory paths
1138 $Path =~ s@/\s*$@@g;
1140 # Block illegal mime-types
1141 die "Illegal mime type:$extension\n" unless $mime || $browse; # illegal mime's are killed
1143 # Print out the document
1144 if(($mime eq 'text/osshell') && $ExecuteOSshell) # Don't use this unless you know what you're doing
1146 # Note that CGI scripts must supply their own content type
1147 # Some rudimentary security tests
1148 # Kill child if the path contains any non-URL characters
1149 die "ATTACK: ADDR:$ENV{'REMOTE_ADDR'} HOST:$ENV{'REMOTE_HOST'} URL=$Path '$QueryString'\n"
1150 if $Path =~ m@[^\w\-\.\/]@; # Exclusive list of allowed characters
1151 # If you want to execute server side shell scripts, use the 'text/osshell'
1152 # mime-type (see above) but remember that there is NO SECURITY implemented
1153 # whatsoever.
1154 # IF YOU DIDN'T GET THE MESSAGE YET, YOU COULD NOW OPEN YOUR COMPUTER TO THE WHOLE
1155 # INTERNET TO PLAY WITH!
1156 # Plain Web site from DISK
1157 unless($UseRAMimage)
1159 print STDOUT `$textroot$Path`; # This is Russian Roulette
1161 else # Use a RAM image of the web site
1163 my $ShellInterpreter = '/usr/bin/sh';
1164 if($ENV{'CGI_FILE_CONTENTS'} =~ /^\#\!\s*([^\r\n]+)/isg)
1166 $ShellInterpreter = $1;
1168 # Execute shell script
1169 open(RAMOUT, "| $ShellInterpreter") || die "ERROR open RAMOUT $ShellInterpreter $textroot$Path $! $@\n";
1170 (print RAMOUT $ENV{'CGI_FILE_CONTENTS'}) || die "ERROR print RAMOUT $ShellInterpreter $textroot$Path $! $@\n";
1171 close(RAMOUT);
1174 elsif($mime)
1176 # Content-type and document
1177 print STDOUT "Content-type: $mime\n\n";
1178 # Plain Web site from DISK
1179 unless($UseRAMimage)
1181 my $String = "";
1182 my $number_of_bytes = 0;
1183 open(BINARY, "<$textroot$Path") || die "$textroot$Path: $!";
1185 # read and write block of 1024 bytes
1186 while($number_of_bytes = sysread(BINARY, $String, 1024))
1188 syswrite(STDOUT, $String, $number_of_bytes); # Actually print the file content
1190 close(BINARY);
1192 # Alternative output using the UNIX shell
1193 # print STDOUT `cat '$textroot$Path'`; # lazy, let the OS do the work
1195 else # Use a RAM image of the web site
1197 print STDOUT $ENV{'CGI_FILE_CONTENTS'};
1201 elsif($browse && !$Secure) # Block directory browsing in the Secure setup
1203 # Content-type and document
1204 print STDOUT "Content-type: text/html\n\n";
1205 opendir(BROWSE, "$textroot$Path") || die "<$textroot$Path: $!\n";
1207 print "<HTML>\n<HEAD>\n<TITLE>$Path</TITLE></HEAD>\n<BODY>\n<H1>$Path</H1>\n<pre>\n<dl>";
1209 my $DirEntry;
1210 foreach $DirEntry (sort {lc($a) cmp lc($b)} readdir(BROWSE))
1212 my $CurrentPath = $Path;
1213 # Handle '..'
1214 if($DirEntry eq '..')
1216 my $ParentDir = $CurrentPath;
1217 $ParentDir =~ s@/[^/]+$@@g;
1218 $ParentDir = '/' unless $ParentDir;
1219 print "<dt> <a href='$ParentDir'><h3>Parent directory</h3></a></dt>\n";
1221 next if $DirEntry !~ /[^\.\/\\\:]/;
1223 # Get aliases
1224 my $Alias = GetAlias("$CurrentPath/$DirEntry");
1225 if($Alias ne "$CurrentPath/$DirEntry")
1227 $Alias =~ m@/([^/]+)$@;
1228 $CurrentPath = $`;
1229 $DirEntry = $1;
1232 my $Date = localtime($^T - (-M "$textroot$CurrentPath/$DirEntry")*3600*24);
1233 my $Size = -s "$textroot$CurrentPath/$DirEntry";
1234 $Size = sprintf("%6.0F kB", $Size/1024);
1235 my $Type = `file $textroot$CurrentPath/$DirEntry`;
1236 $Type =~ s@\s*$textroot$CurrentPath/$DirEntry\s*\:\s*@@ig;
1237 chomp($Type);
1238 print "<dt> <a href='$CurrentPath/$DirEntry'>";
1239 printf("%-40s", $DirEntry."</a>");
1240 print "\t$Size\t$Date\t$Type</dt>\n";
1242 close(BROWSE);
1243 print "</dl></pre></BODY>\n</HTML>\n";
1248 close(STDOUT) || die "STDOUT: $!\n";
1249 close(STDIN) || die "STDIN: $!\n";
1250 close(Client) || die "Client: $!\n";
1252 exit 0; # Kill Child
1254 else
1257 # parent code...some systems will have to worry about waiting
1258 # before they can actually close the link to the Client
1259 my $current_time = time();
1261 # Determine which of the children are actually still alive
1262 # and kill those that have run for too long (probably not connected anymore)
1263 my @old_brood = @brood;
1264 @brood = (); # empty brood
1265 foreach (@old_brood)
1267 # Kill the child if it runs for longer than MaxTime
1268 if(($StartTime{$_} - $current_time) > $MaxTime)
1270 kill "KILL", $_;
1273 # Store children that are alive
1274 if(kill (0, $_)) # Alive?
1276 push(@brood, $_);
1278 else
1280 delete($StartTime{$_});
1284 # Weed out overflow of children (zombies etc.), keep pid for
1285 # removing the StartTime later on
1286 my $oldest;
1287 for($oldest=0; $oldest < scalar(@brood)-$MaxBrood; ++$oldest)
1289 kill "KILL", $brood[$oldest] if $brood[$oldest]; # Remove
1290 # Do NOT remove the killed children from @brood as the KILL
1291 # might not have worked and you can try again later
1294 # Child pid could be recycled, i.e., $child could be stored
1295 # in @brood already. Remove it
1296 @brood = grep($_ != $child, @brood);
1298 # Push new child on the list, if the fork succeeded
1299 if($child > 0)
1301 push (@brood, $child);
1302 $StartTime{$child} = $current_time;
1304 close Client; # This is it, ready!
1308 # Interupt handler for shutting down
1309 sub SigHandler
1311 my $sig = shift;
1312 exit 1;
1315 # Subroutine for Aliases
1316 # Uses Global variables: %AliasTranslation, @RegAliasTranslation, and @RegURLTranslation
1317 sub GetAlias # ($Path)->AliasURL
1319 my $Path = shift;
1321 # Translate the Aliases
1322 if($AliasTranslation{$Path})
1324 $Path = $AliasTranslation{$Path};
1326 elsif(@RegAliasTranslation)
1328 my $i;
1329 for($i=0; $i<scalar(@RegAliasTranslation); ++$i)
1331 my $Alias = $RegAliasTranslation[$i];
1332 my $RealURL = $RegURLTranslation[$i];
1333 last if ($Path =~ s#$Alias#$RealURL#g);
1336 return $Path;
1339 =head1 NAME
1341 CGIservlet - a HTTPd "connector" for running CGI scripts on unix systems as WWW
1342 accessible Web sites.
1344 =head1 DESCRIPTION
1346 The servlet starts a true HTTP daemon that channels
1347 HTTP requests to forked daughter processes. Can run
1348 a (small) WWW-site from memory.
1350 =head1 README
1352 Whenever an HTTP request is received, the specified CGI script is
1353 started inside a child process as if it was inside a real server (e.g.,
1354 Apache). The evironment variables are set more or less as in Apache.
1355 Note that CGIservlet only uses a SINGLE script for ALL requests.
1356 No attemps for security are made, it is the script's responsibility to
1357 check access rights and the validity of the request.
1358 Can store the files of Web site in memory and serve them
1359 on request.
1361 =head1 PREREQUISITES
1363 This script requires the C<strict>, Socket and Carp modules.
1365 =head1 COREQUISITES
1367 =pod OSNAMES
1369 Unix
1371 =pod SCRIPT CATEGORIES
1376 =cut