Refactoring code for Session Tickets
[CGIscriptor.git] / CGIscriptor.pl
blob0776cf78f3f6aa2aa6e08bb3bc9a05daa1f85c58
1 #! /usr/bin/perl
3 # (configure the first line to contain YOUR path to perl 5.000+)
5 # CGIscriptor.pl
6 # Version 2.3
7 # 15 January 2002
9 # YOU NEED:
11 # perl 5.0 or higher (see: "http://www.perl.org/")
13 # Notes:
15 if(grep(/\-\-help/i, @ARGV))
17 print << 'ENDOFPREHELPTEXT1';
18 # CGIscriptor.pl is a Perl program will run on any WWW server that
19 # runs Perl scripts, just add a line like the following to your
20 # httpd.conf file (Apache example):
22 # ScriptAlias /SHTML/ "/real-path/CGIscriptor.pl/"
24 # URL's that refer to http://www.your.address/SHTML/... will now be handled
25 # by CGIscriptor.pl, which can use a private directory tree (default is the
26 # DOCUMENT_ROOT directory tree, but it can be anywhere, see below).
27 # NOTE: if you cannot use a ScriptAlias, there is a way to use .htaccess
28 # instead. See below.
30 # This file contains all documentation as comments. These comments
31 # can be removed to speed up loading (e.g., `egrep -v '^#' CGIscriptor.pl` >
32 # leanScriptor.pl). A bare bones version of CGIscriptor.pl, lacking
33 # documentation, most comments, access control, example functions etc.
34 # (but still with the copyright notice and some minimal documentation)
35 # can be obtained by calling CGIscriptor.pl with the '-slim'
36 # command line argument, e.g.,
37 # >CGIscriptor.pl -slim >slimCGIscriptor.pl
39 # CGIscriptor.pl can be run from the command line as
40 # `CGIscriptor.pl <path> <query>`, inside a perl script with
41 # 'do CGIscriptor.pl' after setting $ENV{PATH_INFO} and $ENV{QUERY_STRING},
42 # or CGIscriptor.pl can be loaded with 'require "/real-path/CGIscriptor.pl"'.
43 # In the latter case, requests are processed by 'Handle_Request();'
44 # (again after setting $ENV{PATH_INFO} and $ENV{QUERY_STRING}).
46 # The --help command line switch will print the manual.
48 # Running demo's and more information can be found at
49 # http://www.fon.hum.uva.nl/rob/OSS/OSS.html
51 # A pocket-size HTTP daemon, CGIservlet.pl, is available from my web site
52 # or CPAN that can use CGIscriptor.pl as the base of a µWWW server and
53 # demonstrates its use.
55 ENDOFPREHELPTEXT1
57 # Configuration, copyright notice, and user manual follow the next
58 # (Changes) section.
60 ############################################################################
62 # Changes (document ALL changes with date, name and email here):
63 # 22 May 2012 - Added Access control with Session Tickets linked to
64 # IP Address and PATH_INFO.
65 # 21 May 2012 - Corrected the links generated by CGIscriptor::BrowseDirs
66 # Will link to current base URL when the HTTP server is '.' or '~'
67 # 29 Oct 2009 - Adapted David A. Wheeler's suggestion about filenames:
68 # CGIsafeFileName does not accept filenames starting with '-'
69 # (http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html)
70 # 08 Oct 2009 - Some corrections in the README.txt file, eg, new email address
71 # 28 Jan 2005 - Added a file selector to performTranslation.
72 # Changed %TranslationTable to @TranslationTable
73 # and patterns to lists.
74 # 27 Jan 2005 - Added a %TranslationTable with associated
75 # performTranslation(\$text) function to allow
76 # run changes in the web pages. Say, to translate
77 # legacy pages with <%=...%> delimiters to the new
78 # <SCRIPT TYPE=..></SCRIPT> format.
79 # 27 Jan 2005 - Small bug of extra '\n' in output removed from the
80 # Other Languages Code.
81 # 10 May 2004 - Belated upload of latest version (2.3) to CPAN
82 # 07 Oct 2003 - Corrected error '\s' -> '\\s' in rebol scripting
83 # language call
84 # 07 Oct 2003 - Corrected omitted INS tags in <DIV><INS> handling
85 # 20 May 2003 - Added a --help switch to print the manual.
86 # 06 Mar 2003 - Adapted the blurb at the end of the file.
87 # 03 Mar 2003 - Added a user definable dieHandler function to catch all
88 # "die" calls. Also "enhanced" the STDERR printout.
89 # 10 Feb 2003 - Split off the reading of the POST part of a query
90 # from Initialize_output. This was suggested by Gerd Franke
91 # to allow for the catching of the file_path using a
92 # POST based lookup. That is, he needed the POST part
93 # to change the file_path.
94 # 03 Feb 2003 - %{$name}; => %{$name} = (); in defineCGIvariableHash.
95 # 03 Feb 2003 - \1 better written as $1 in
96 # $directive =~ s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/$1/g
97 # 29 Jan 2003 - This makes "CLASS="ssperl" CSS-compatible Gerd Franke
98 # added:
99 # $ServerScriptContentClass = "ssperl";
100 # changed in ProcessFile():
101 # unless(($CurrentContentType =~
102 # 28 Jan 2003 - Added 'INS' Tag! Gerd Franke
103 # 20 Dec 2002 - Removed useless $Directoryseparator variable.
104 # Update comments and documentation.
105 # 18 Dec 2002 - Corrected bug in Accept/Reject processing.
106 # Files didn't work.
107 # 24 Jul 2002 - Added .htaccess documentation (from Gerd Franke)
108 # Also added a note that RawFilePattern can be a
109 # complete file name.
110 # 19 Mar 2002 - Added SRC pseudo-files PREFIX and POSTFIX. These
111 # switch to prepending or to appending the content
112 # of the SRC attribute. Default is prefixing. You
113 # can add as many of these switches as you like.
114 # 13 Mar 2002 - Do not search for tag content if a tag closes with
115 # />, i.e., <DIV ... /> will be handled the XML/XHTML way.
116 # 25 Jan 2002 - Added 'curl' and 'snarf' to SRC attribute URL handling
117 # (replaces wget).
118 # 25 Jan 2002 - Found a bug in SAFEqx, now executes qx() in a scalar context
119 # (i.o. a list context). This is necessary for binary results.
120 # 24 Jan 2002 - Disambiguated -T $SRCfile to -T "$SRCfile" (and -e) and
121 # changed the order of if/elsif to allow removing these
122 # conditions in systems with broken -T functions.
123 # (I also removed a spurious ')' bracket)
124 # 17 Jan 2002 - Changed DIV tag SRC from <SOURCE> to sysread(SOURCE,...)
125 # to support binary files.
126 # 17 Jan 2002 - Removed WhiteSpace from $FileAllowedCharacters.
127 # 17 Jan 2002 - Allow "file://" prefix in SRC attribute. It is simply
128 # stipped from the path.
129 # 15 Jan 2002 - Version 2.2
130 # 15 Jan 2002 - Debugged and completed URL support (including
131 # CGIscriptor::read_url() function)
132 # 07 Jan 2002 - Added automatic (magic) URL support to the SRC attribute
133 # with the main::GET_URL function. Uses wget -O underlying.
134 # 04 Jan 2002 - Added initialization of $NewDirective in InsertForeignScript
135 # (i.e., my $NewDirective = "";) to clear old output
136 # (this was a realy anoying bug).
137 # 03 Jan 2002 - Added a <DIV CLASS='text/ssperl' ID='varname'></DIV>
138 # tags that assign the body text as-is (literally)
139 # to $varname. Allows standard HTML-tools to handle
140 # Cascading Style Sheet templates. This implements a
141 # design by Gerd Franke (franke@roo.de).
142 # 03 Jan 2002 - I finaly gave in and allowed SRC files to expand ~/.
143 # 12 Oct 2001 - Normalized spelling of "CGIsafFileName" in documentation.
144 # 09 Oct 2001 - Added $ENV{'CGI_BINARY_FILE'} to log files to
145 # detect unwanted indexing of TAR files by webcrawlers.
146 # 10 Sep 2001 - Added $YOUR_SCRIPTS directory to @INC for 'require'.
147 # 22 Aug 2001 - Added .txt (Content-type: text/plain) as a default
148 # processed file type. Was processed via BinaryMapFile.
149 # 31 May 2001 - Changed =~ inside CGIsafeEmailAddress that was buggy.
150 # 29 May 2001 - Updated $CGI_HOME to point to $ENV{DOCUMENT_ROOT} io
151 # the root of PATH_TRANSLATED. DOCUMENT_ROOT can now
152 # be manipulated to achieve a "Sub Root".
153 # NOTE: you can have $YOUR_HTML_FILES != DOCUMENT_ROOT
154 # 28 May 2001 - Changed CGIscriptor::BrowsDirs function for security
155 # and debugging (it now works).
156 # 21 May 2001 - defineCGIvariableHash will ADD values to existing
157 # hashes,instead of replacing existing hashes.
158 # 17 May 2001 - Interjected a '&' when pasting POST to GET data
159 # 24 Apr 2001 - Blocked direct requests for BinaryMapFile.
160 # 16 Aug 2000 - Added hash table extraction for CGI parameters with
161 # CGIparseValueHash (used with structured parameters).
162 # Use: CGI='%<CGI-partial-name>' (fill in your name in <>)
163 # Will collect all <CGI-partial-name><key>=value pairs in
164 # $<CGI-partial-name>{<key>} = value;
165 # 16 Aug 2000 - Adapted SAFEqx to protect @PARAMETER values.
166 # 09 Aug 2000 - Added support for non-filesystem input by way of
167 # the CGI_FILE_CONTENTS and CGI_DATA_ACCESS_CODE
168 # environment variables.
169 # 26 Jul 2000 - On the command-line, file-path '-' indicates STDIN.
170 # This allows CGIscriptor to be used in pipes.
171 # Default, $BLOCK_STDIN_HTTP_REQUEST=1 will block this
172 # in an HTTP request (i.e., in a web server).
173 # 26 Jul 2000 - Blocked 'Content-type: text/html' if the SERVER_PROTOCOL
174 # is not HTTP or another protocol. Changed the default
175 # source directory to DOCUMENT_ROOT (i.o. the incorrect
176 # SERVER_ROOT).
177 # 24 Jul 2000 - -slim Command-line argument added to remove all
178 # comments, security, etc.. Updated documentation.
179 # 05 Jul 2000 - Added IF and UNLESS attributes to make the
180 # execution of all <META> and <SCRIPT> code
181 # conditional.
182 # 05 Jul 2000 - Rewrote and isolated the code for extracting
183 # quoted items from CGI and SRC attributes.
184 # Now all attributes expect the same set of
185 # quotes: '', "", ``, (), {}, [] and the same
186 # preceded by a \, e.g., "\((aap)\)" will be
187 # extracted as "(aap)".
188 # 17 Jun 2000 - Construct @ARGV list directly in CGIexecute
189 # name-space (i.o. by evaluation) from
190 # CGI attributes to prevent interference with
191 # the processing for non perl scripts.
192 # Changed CGIparseValueList to prevent runaway
193 # loops.
194 # 16 Jun 2000 - Added a direct (interpolated) display mode
195 # (text/ssdisplay) and a user log mode
196 # (text/sslogfile).
197 # 06 Jun 2000 - Replace "print $Result" with a syswrite loop to
198 # allow large string output.
199 # 02 Jun 2000 - Corrected shrubCGIparameter($CGI_VALUE) to realy
200 # remove all control characters. Changed Interpreter
201 # initialization to shrub interpolated CGI parameters.
202 # Added 'text/ssmailto' interpreter script.
203 # 22 May 2000 - Changed some of the comments
204 # 09 May 2000 - Added list extraction for CGI parameters with
205 # CGIparseValueList (used with multiple selections).
206 # Use: CGI='@<CGI-parameter>' (fill in your name in <>)
207 # 09 May 2000 - Added a 'Not Present' condition to CGIparseValue.
208 # 27 Apr 2000 - Updated documentation to reflect changes.
209 # 27 Apr 2000 - SRC attribute "cleaned". Supported for external
210 # interpreters.
211 # 27 Apr 2000 - CGI attribute can be used in <SCRIPT> tag.
212 # 27 Apr 2000 - Gprolog, M4 support added.
213 # 26 Apr 2000 - Lisp (rep) support added.
214 # 20 Apr 2000 - Use of external interpreters now functional.
215 # 20 Apr 2000 - Removed bug from extracting Content types (RegExp)
216 # 10 Mar 2000 - Qualified unconditional removal of '#' that preclude
217 # the use of $#foo, i.e., I changed
218 # s/[^\\]\#[^\n\f\r]*([\n\f\r])/\1/g
219 # to
220 # s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/\1/g
221 # 03 Mar 2000 - Added a '$BlockPathAccess' variable to "hide"
222 # things like, e.g., CVS information in CVS subtrees
223 # 10 Feb 2000 - URLencode/URLdecode have been made case-insensitive
224 # 10 Feb 2000 - Added a BrowseDirs function (CGIscriptor package)
225 # 01 Feb 2000 - A BinaryMapFile in the ~/ directory has precedence
226 # over a "burried" BinaryMapFile.
227 # 04 Oct 1999 - Added two functions to check file names and email addresses
228 # (CGIscriptor::CGIsafeFileName and
229 # CGIscriptor::CGIsafeEmailAddress)
230 # 28 Sept 1999 - Corrected bug in sysread call for reading POST method
231 # to allow LONG posts.
232 # 28 Sept 1999 - Changed CGIparseValue to handle multipart/form-data.
233 # 29 July 1999 - Refer to BinaryMapFile from CGIscriptor directory, if
234 # this directory exists.
235 # 07 June 1999 - Limit file-pattern matching to LAST extension
236 # 04 June 1999 - Default text/html content type is printed only once.
237 # 18 May 1999 - Bug in replacement of ~/ and ./ removed.
238 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
239 # 15 May 1999 - Changed the name of the execute package to CGIexecute.
240 # Changed the processing of the Accept and Reject file.
241 # Added a full expression evaluation to Access Control.
242 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
243 # 27 Apr 1999 - Brought CGIscriptor under the GNU GPL. Made CGIscriptor
244 # Version 1.1 a module that can be called with 'require "CGIscriptor.pl"'.
245 # Requests are serviced by "Handle_Request()". CGIscriptor
246 # can still be called as a isolated perl script and a shell
247 # command.
248 # Changed the "factory default setting" so that it will run
249 # from the DOCUMENT_ROOT directory.
250 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
251 # 29 Mar 1999 - Remove second debugging STDERR switch. Moved most code
252 # to subroutines to change CGIscriptor into a module.
253 # Added mapping to process unsupported file types (e.g., binary
254 # pictures). See $BinaryMapFile.
255 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
256 # 24 Sept 1998 - Changed text of license (Rob van Son, R.J.J.H.vanSon@uva.nl)
257 # Removed a double setting of filepatterns and maximum query
258 # size. Changed email address. Removed some typos from the
259 # comments.
260 # 02 June 1998 - Bug fixed in URLdecode. Changing the foreach loop variable
261 # caused quiting CGIscriptor.(Rob van Son, R.J.J.H.vanSon@uva.nl)
262 # 02 June 1998 - $SS_PUB and $SS_SCRIPT inserted an extra /, removed.
263 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
266 # Known Bugs:
268 # 23 Mar 2000
269 # It is not possible to use operators or variables to construct variable names,
270 # e.g., $bar = \@{$foo}; won't work. However, eval('$bar = \@{'.$foo.'};');
271 # will indeed work. If someone could tell me why, I would be obliged.
274 ############################################################################
276 # OBLIGATORY USER CONFIGURATION
278 # Configure the directories where all user files can be found (this
279 # is the equivalent of the server root directory of a WWW-server).
280 # These directories can be located ANYWHERE. For security reasons, it is
281 # better to locate them outside the WWW-tree of your HTTP server, unless
282 # CGIscripter handles ALL requests.
284 # For convenience, the defaults are set to the root of the WWW server.
285 # However, this might not be safe!
287 # ~/ text files
288 # $YOUR_HTML_FILES = "/usr/pub/WWW/SHTML"; # or SS_PUB as environment var
289 # (patch to use the parent directory of CGIscriptor as document root, should be removed)
290 if($ENV{'SCRIPT_FILENAME'}) # && $ENV{'SCRIPT_FILENAME'} !~ /\Q$ENV{'DOCUMENT_ROOT'}\E/)
292 $ENV{'DOCUMENT_ROOT'} = $ENV{'SCRIPT_FILENAME'};
293 $ENV{'DOCUMENT_ROOT'} =~ s@/CGIscriptor.*$@@ig;
296 # Just enter your own directory path here
297 $YOUR_HTML_FILES = $ENV{'DOCUMENT_ROOT'}; # default is the DOCUMENT_ROOT
299 # ./ script files (recommended to be different from the previous)
300 # $YOUR_SCRIPTS = "/usr/pub/WWW/scripts"; # or SS_SCRIPT as environment var
301 $YOUR_SCRIPTS = $YOUR_HTML_FILES; # This might be a SECURITY RISK
303 # End of obligatory user configuration
304 # (note: there is more non-essential user configuration below)
306 ############################################################################
308 # OPTIONAL USER CONFIGURATION (all values are used CASE INSENSITIVE)
310 # Script content-types: TYPE="Content-type" (user defined mime-type)
311 $ServerScriptContentType = "text/ssperl"; # Server Side Perl scripts
312 # CSS require a simple class
313 $ServerScriptContentClass = $ServerScriptContentType =~ m!/! ?
314 $' : "ssperl"; # Server Side Perl CSS classes
316 $ShellScriptContentType = "text/osshell"; # OS shell scripts
317 # # (Server Side perl ``-execution)
319 # Accessible file patterns, block any request that doesn't match.
320 # Matches any file with the extension .(s)htm(l), .txt, or .xmr
321 # (\. is used in regexp)
322 # Note: die unless $PATH_INFO =~ m@($FilePattern)$@is;
323 $FilePattern = ".shtml|.htm|.html|.xml|.xmr|.txt";
325 # The table with the content type MIME types
326 # (allows to differentiate MIME types, if needed)
327 %ContentTypeTable =
329 '.html' => 'text/html',
330 '.shtml' => 'text/html',
331 '.htm' => 'text/html',
332 '.xml' => 'text/xml',
333 '.txt' => 'text/plain'
337 # File pattern post-processing
338 $FilePattern =~ s/([@.])/\\$1/g; # Convert . and @ to \. and \@
340 # File patterns of files which require a login.
341 %LoginRequiredPatterns = (
342 '^/Private/' => "Private/.Sessions\tPrivate/.Passwords\tLogin.html\t12h"
344 # Session Ticket Directory: .Session/
345 # Password Directory: .Password/
346 # Login page: Login.html
347 # Valid for: 12h
349 # Raw files must contain their own Content-type (xmr <- x-multipart-replace).
350 # THIS IS A SUBSET OF THE FILES DEFINED IN $FilePattern
351 $RawFilePattern = ".xmr";
352 # (In principle, this could contain a full file specification, e.g.,
353 # ".xmr|relocated.html")
355 # Raw File pattern post-processing
356 $RawFilePattern =~ s/([@.])/\\$1/g; # Convert . and @ to \. and \@
358 # Server protocols for which "Content-type: text/html\n\n" should be printed
359 # (you should not bother with these, except for HTTP, they are mostly imaginary)
360 $ContentTypeServerProtocols = 'HTTP|MAIL|MIME';
362 # Block access to all (sub-) paths and directories that match the
363 # following (URL) path (is used as:
364 # 'die if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@;' )
365 $BlockPathAccess = '/(CVS|\.git)/'; # Protect CVS and .git information
367 # All (blocked) other file-types can be mapped to a single "binary-file"
368 # processor (a kind of pseudo-file path). This can either be an error
369 # message (e.g., "illegal file") or contain a script that serves binary
370 # files.
371 # Note: the real file path wil be stored in $ENV{CGI_BINARY_FILE}.
372 $BinaryMapFile = "/BinaryMapFile.xmr";
373 # Allow for the addition of a CGIscriptor directory
374 # Note that a BinaryMapFile in the root "~/" directory has precedence
375 $BinaryMapFile = "/CGIscriptor".$BinaryMapFile
376 if ! -e "$YOUR_HTML_FILES".$BinaryMapFile
377 && -e "$YOUR_HTML_FILES/CGIscriptor".$BinaryMapFile;
380 # List of all characters that are allowed in file names and paths.
381 # All requests containing illegal characters are blocked. This
382 # blocks most tricks (e.g., adding "\000", "\n", or other control
383 # characters, also blocks URI's using %FF)
384 # THIS IS A SECURITY FEATURE
385 # (this is also used to parse filenames in SRC= features, note the
386 # '-quotes, they are essential)
387 $FileAllowedChars = '\w\.\~\/\:\*\?\-'; # Covers Unix and Mac, but NO spaces
389 # Maximum size of the Query (number of characters clients can send
390 # covers both GET & POST combined)
391 $MaximumQuerySize = 2**20 - 1; # = 2**14 - 1
394 # Embeded URL get function used in SRC attributes and CGIscriptor::read_url
395 # (returns a string with the PERL code to transfer the URL contents, e.g.,
396 # "SAFEqx(\'curl \"http://www.fon.hum.uva.nl\"\')")
397 # "SAFEqx(\'wget --quiet --output-document=- \"http://www.fon.hum.uva.nl\"\')")
398 # Be sure to handle <BASE HREF='URL'> and allow BOTH
399 # direct printing GET_URL($URL [, 0]) and extracting the content of
400 # the $URL for post-processing GET_URL($URL, 1).
401 # You get the WHOLE file, including HTML header.
402 # The shell command Use $URL where the URL should go
403 # ('wget', 'snarf' or 'curl', uncomment the one you would like to use)
404 my $GET_URL_shell_command = 'wget --quiet --output-document=- $URL';
405 #my $GET_URL_shell_command = 'snarf $URL -';
406 #my $GET_URL_shell_command = 'curl $URL';
408 sub GET_URL # ($URL, $ValueNotPrint) -> content_of_url
410 my $URL = shift || return;
411 my $ValueNotPrint = shift || 0;
413 # Check URL for illegal characters
414 return "print '<h1>Illegal URL<h1>'\"\n\";" if $URL =~ /[^$FileAllowedChars\%]/;
416 # Include URL in final command
417 my $CurrentCommand = $GET_URL_shell_command;
418 $CurrentCommand =~ s/\$URL/$URL/g;
420 # Print to STDOUT or return a value
421 my $BlockPrint = "print STDOUT ";
422 $BlockPrint = "" if $ValueNotPrint;
424 my $Commands = <<"GETURLCODE";
425 # Get URL
427 my \$Page = "";
429 # Simple, using shell command
430 \$Page = SAFEqx('$CurrentCommand');
432 # Add a BASE tage to the header
433 \$Page =~ s!\\</head!\\<base href='$URL'\\>\\</head!ig unless \$Page =~ m!\\<base!;
435 # Print the URL value, or return it as a value
436 $BlockPrint\$Page;
438 GETURLCODE
439 return $Commands;
442 # As files can get rather large (and binary), you might want to use
443 # some more intelligent reading procedure, e.g.,
444 # Direct Perl
445 # # open(URLHANDLE, '/usr/bin/wget --quiet --output-document=- "$URL"|') || die "wget: \$!";
446 # #open(URLHANDLE, '/usr/bin/snarf "$URL" -|') || die "snarf: \$!";
447 # open(URLHANDLE, '/usr/bin/curl "$URL"|') || die "curl: \$!";
448 # my \$text = "";
449 # while(sysread(URLHANDLE,\$text, 1024) > 0)
451 # \$Page .= \$text;
452 # };
453 # close(URLHANDLE) || die "\$!";
454 # However, this doesn't work with the CGIexecute->evaluate() function.
455 # You get an error: 'No child processes at (eval 16) line 15, <file0> line 8.'
457 # You can forget the next two variables, they are only needed when
458 # you don't want to use a regular file system (i.e., with open)
459 # but use some kind of database/RAM image for accessing (generating)
460 # the data.
462 # Name of the environment variable that contains the file contents
463 # when reading directly from Database/RAM. When this environment variable,
464 # $ENV{$CGI_FILE_CONTENTS}, is not false, no real file will be read.
465 $CGI_FILE_CONTENTS = 'CGI_FILE_CONTENTS';
466 # Uncomment the following if you want to force the use of the data access code
467 # $ENV{$CGI_FILE_CONTENTS} = '-'; # Force use of $ENV{$CGI_DATA_ACCESS_CODE}
469 # Name of the environment variable that contains the RAM access perl
470 # code needed to read additional "files", i.e.,
471 # $ENV{$CGI_FILE_CONTENTS} = eval("\@_=('$file_path'); do{$ENV{$CGI_DATA_ACCESS_CODE}}");
472 # When $ENV{$CGI_FILE_CONTENTS} eq '-', this code is executed to generate the data.
473 $CGI_DATA_ACCESS_CODE = 'CGI_DATA_ACCESS_CODE';
475 # You can, of course, fill this yourself, e.g.,
476 # $ENV{$CGI_DATA_ACCESS_CODE} =
477 # 'open(INPUT, "<$_[0]"); while(<INPUT>){print;};close(INPUT);'
480 # DEBUGGING
482 # Suppress error messages, this can be changed for debugging or error-logging
483 #open(STDERR, "/dev/null"); # (comment out for use in debugging)
485 # SPECIAL: Remove Comments, security, etc. if the command line is
486 # '>CGIscriptor.pl -slim >slimCGIscriptor.pl'
487 $TrimDownCGIscriptor = 1 if $ARGV[0] =~ /^\-slim/i;
489 # If CGIscriptor is used from the command line, the command line
490 # arguments are interpreted as the file (1st) and the Query String (rest).
491 # Get the arguments
492 $ENV{'PATH_INFO'} = shift(@ARGV) unless exists($ENV{'PATH_INFO'}) || grep(/\-\-help/i, @ARGV);
493 $ENV{'QUERY_STRING'} = join("&", @ARGV) unless exists($ENV{'QUERY_STRING'});
496 # Handle bail-outs in a user definable way.
497 # Catch Die and replace it with your own function.
498 # Ends with a call to "die $_[0];"
500 sub dieHandler # ($ErrorCode, "Message", @_) -> DEAD
502 my $ErrorCode = shift;
503 my $ErrorMessage = shift;
505 # Place your own reporting functions here
507 # Now, kill everything (default)
508 print STDERR "$ErrorCode: $ErrorMessage\n";
509 die $ErrorMessage;
513 # End of optional user configuration
514 # (note: there is more non-essential user configuration below)
516 if(grep(/\-\-help/i, @ARGV))
518 print << 'ENDOFPREHELPTEXT2';
520 ###############################################################################
522 # Author and Copyright (c):
523 # Rob van Son, © 1995,1996,1997,1998,1999,2000,2001,2002-2012
524 # NKI-AVL Amsterdam
525 # r.v.son@nki.nl
526 # Institute of Phonetic Sciences & IFOTT/ACLS
527 # University of Amsterdam
528 # Email: R.J.J.H.vanSon@gmail.com
529 # Email: R.J.J.H.vanSon@uva.nl
530 # WWW : http://www.fon.hum.uva.nl/rob/
532 # License for use and disclaimers
534 # CGIscriptor merges plain ASCII HTML files transparantly
535 # with CGI variables, in-line PERL code, shell commands,
536 # and executable scripts in other scripting languages.
538 # This program is free software; you can redistribute it and/or
539 # modify it under the terms of the GNU General Public License
540 # as published by the Free Software Foundation; either version 2
541 # of the License, or (at your option) any later version.
543 # This program is distributed in the hope that it will be useful,
544 # but WITHOUT ANY WARRANTY; without even the implied warranty of
545 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
546 # GNU General Public License for more details.
548 # You should have received a copy of the GNU General Public License
549 # along with this program; if not, write to the Free Software
550 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
553 # Contributors:
554 # Rob van Son (R.J.J.H.vanSon@uva.nl)
555 # Gerd Franke franke@roo.de (designed the <DIV> behaviour)
557 #######################################################
558 ENDOFPREHELPTEXT2
560 #######################################################>>>>>>>>>>Start Remove
562 # You can skip the following code, it is an auto-splice
563 # procedure.
565 # Construct a slimmed down version of CGIscriptor
566 # (i.e., CGIscriptor.pl -slim > slimCGIscriptor.pl)
568 if($TrimDownCGIscriptor)
570 open(CGISCRIPTOR, "<CGIscriptor.pl")
571 || dieHandler(1, "<CGIscriptor.pl not slimmed down: $!\n");
572 my $SKIPtext = 0;
573 my $SKIPComments = 0;
575 while(<CGISCRIPTOR>)
577 my $SKIPline = 0;
579 ++$LineCount;
581 # Start of SKIP text
582 $SKIPtext = 1 if /[\>]{10}Start Remove/;
583 $SKIPComments = 1 if $SKIPtext == 1;
585 # Skip this line?
586 $SKIPline = 1 if $SKIPtext || ($SKIPComments && /^\s*\#/);
588 ++$PrintCount unless $SKIPline;
590 print STDOUT $_ unless $SKIPline;
592 # End of SKIP text ?
593 $SKIPtext = 0 if /[\<]{10}End Remove/;
595 # Ready!
596 print STDERR "\# Printed $PrintCount out of $LineCount lines\n";
597 exit;
600 #######################################################
602 if(grep(/\-\-help/i, @ARGV))
604 print << 'ENDOFHELPTEXT';
606 # HYPE
608 # CGIscriptor merges plain ASCII HTML files transparantly and safely
609 # with CGI variables, in-line PERL code, shell commands, and executable
610 # scripts in many languages (on-line and real-time). It combines the
611 # "ease of use" of HTML files with the versatillity of specialized
612 # scripts and PERL programs. It hides all the specifics and
613 # idiosyncrasies of correct output and CGI coding and naming. Scripts
614 # do not have to be aware of HTML, HTTP, or CGI conventions just as HTML
615 # files can be ignorant of scripts and the associated values. CGIscriptor
616 # complies with the W3C HTML 4.0 recommendations.
617 # In addition to its use as a WWW embeded CGI processor, it can
618 # be used as a command-line document preprocessor (text-filter).
620 # THIS IS HOW IT WORKS
622 # The aim of CGIscriptor is to execute "plain" scripts inside a text file
623 # using any required CGIparameters and environment variables. It
624 # is optimized to transparantly process HTML files inside a WWW server.
625 # The native language is Perl, but many other scripting languages
626 # can be used.
628 # CGIscriptor reads text files from the requested input file (i.e., from
629 # $YOUR_HTML_FILES$PATH_INFO) and writes them to <STDOUT> (i.e., the
630 # client requesting the service) preceded by the obligatory
631 # "Content-type: text/html\n\n" or "Content-type: text/plain\n\n" string
632 # (except for "raw" files which supply their own Content-type message
633 # and only if the SERVER_PROTOCOL supports HTTP, MAIL, or MIME).
635 # When CGIscriptor encounters an embedded script, indicated by an HTML4 tag
637 # <SCRIPT TYPE="text/ssperl" [CGI="$VAR='default value'"] [SRC="ScriptSource"]>
638 # PERL script
639 # </SCRIPT>
641 # or
643 # <SCRIPT TYPE="text/osshell" [CGI="$name='default value'"] [SRC="ScriptSource"]>
644 # OS Shell script
645 # </SCRIPT>
647 # construct (anything between []-brackets is optional, other MIME-types
648 # and scripting languages are supported), the embedded script is removed
649 # and both the contents of the source file (i.e., "do 'ScriptSource'")
650 # AND the script are evaluated as a PERL program (i.e., by eval()),
651 # shell script (i.e., by a "safe" version of `Command`, qx) or an external
652 # interpreter. The output of the eval() function takes the place of the
653 # original <SCRIPT></SCRIPT> construct in the output string. Any CGI
654 # parameters declared by the CGI attribute are available as simple perl
655 # variables, and can subsequently be made available as variables to other
656 # scripting languages (e.g., bash, python, or lisp).
658 # Example: printing "Hello World"
659 # <HTML><HEAD><TITLE>Hello World</TITLE>
660 # <BODY>
661 # <H1><SCRIPT TYPE="text/ssperl">"Hello World"</SCRIPT></H1>
662 # </BODY></HTML>
664 # Save this in a file, hello.html, in the directory you indicated with
665 # $YOUR_HTML_FILES and access http://your_server/SHTML/hello.html
666 # (or to whatever name you use as an alias for CGIscriptor.pl).
667 # This is realy ALL you need to do to get going.
669 # You can use any values that are delivered in CGI-compliant form (i.e.,
670 # the "?name=value" type URL additions) transparently as "$name" variables
671 # in your scripts IFF you have declared them in the CGI attribute of
672 # a META or SCRIPT tag before e.g.:
673 # <META CONTENT="text/ssperl; CGI='$name = `default value`'
674 # [SRC='ScriptSource']">
675 # or
676 # <SCRIPT TYPE="text/ssperl" CGI="$name = 'default value'"
677 # [SRC='ScriptSource']>
678 # After such a 'CGI' attribute, you can use $name as an ordinary PERL variable
679 # (the ScriptSource file is immediately evaluated with "do 'ScriptSource'").
680 # The CGIscriptor script allows you to write ordinary HTML files which will
681 # include dynamic CGI aware (run time) features, such as on-line answers
682 # to specific CGI requests, queries, or the results of calculations.
684 # For example, if you wanted to answer questions of clients, you could write
685 # a Perl program called "Answer.pl" with a function "AnswerQuestion()"
686 # that prints out the answer to requests given as arguments. You then write
687 # an HTML page "Respond.html" containing the following fragment:
689 # <center>
690 # The Answer to your question
691 # <META CONTENT="text/ssperl; CGI='$Question'">
692 # <h3><SCRIPT TYPE="text/ssperl">$Question</SCRIPT></h3>
693 # is
694 # <h3><SCRIPT TYPE="text/ssperl" SRC="./PATH/Answer.pl">
695 # AnswerQuestion($Question);
696 # </SCRIPT></h3>
697 # </center>
698 # <FORM ACTION=Respond.html METHOD=GET>
699 # Next question: <INPUT NAME="Question" TYPE=TEXT SIZE=40><br>
700 # <INPUT TYPE=SUBMIT VALUE="Ask">
701 # </FORM>
703 # The output could look like the following (in HTML-speak):
705 # <CENTER>
706 # The Answer to your question
707 # <h3>What is the capital of the Netherlands?</h3>
708 # is
709 # <h3>Amsterdam</h3>
710 # </CENTER>
711 # <FORM ACTION=Respond.html METHOD=GET>
712 # Next question: <INPUT NAME="Question" TYPE=TEXT SIZE=40><br>
713 # <INPUT TYPE=SUBMIT VALUE="Ask">
715 # Note that the function "Answer.pl" does know nothing about CGI or HTML,
716 # it just prints out answers to arguments. Likewise, the text has no
717 # provisions for scripts or CGI like constructs. Also, it is completely
718 # trivial to extend this "program" to use the "Answer" later in the page
719 # to call up other information or pictures/sounds. The final text never
720 # shows any cue as to what the original "source" looked like, i.e.,
721 # where you store your scripts and how they are called.
723 # There are some extra's. The argument of the files called in a SRC= tag
724 # can access the CGI variables declared in the preceding META tag from
725 # the @ARGV array. Executable files are called as:
726 # `file '$ARGV[0]' ... ` (e.g., `Answer.pl \'$Question\'`;)
727 # The files called from SRC can even be (CGIscriptor) html files which are
728 # processed in-line. Furthermore, the SRC= tag can contain a perl block
729 # that is evaluated. That is,
730 # <META CONTENT="text/ssperl; CGI='$Question' SRC='{$Question}'">
731 # will result in the evaluation of "print do {$Question};" and the VALUE
732 # of $Question will be printed. Note that these "SRC-blocks" can be
733 # preceded and followed by other file names, but only a single block is
734 # allowed in a SRC= tag.
736 # One of the major hassles of dynamic WWW pages is the fact that several
737 # mutually incompatible browsers and platforms must be supported. For example,
738 # the way sound is played automatically is different for Netscape and
739 # Internet Explorer, and for each browser it is different again on
740 # Unix, MacOS, and Windows. Realy dangerous is processing user-supplied
741 # (form-) values to construct email addresses, file names, or database
742 # queries. All Apache WWW-server exploits reported in the media are
743 # based on faulty CGI-scripts that didn't check their user-data properly.
745 # There is no panacee for these problems, but a lot of work and problems
746 # can be saved by allowing easy and transparent control over which
747 # <SCRIPT></SCRIPT> blocks are executed on what CGI-data. CGIscriptor
748 # supplies such a method in the form of a pair of attributes:
749 # IF='...condition..' and UNLESS='...condition...'. When added to a
750 # script tag, the whole block (including the SRC attribute) will be
751 # ignored if the condition is false (IF) or true (UNLESS).
752 # For example, the following block will NOT be evaluated if the value
753 # of the CGI variable FILENAME is NOT a valid filename:
755 # <SCRIPT TYPE='text/ssperl' CGI='$FILENAME'
756 # IF='CGIscriptor::CGIsafeFileName($FILENAME)'>
757 # .....
758 # </SCRIPT>
760 # (the function CGIsafeFileName(String) returns an empty string ("")
761 # if the String argument is not a valid filename).
762 # The UNLESS attribute is the mirror image of IF.
764 # A user manual follows the HTML 4 and security paragraphs below.
766 ##########################################################################
768 # HTML 4 compliance
770 # In general, CGIscriptor.pl complies with the HTML 4 recommendations of
771 # the W3C. This means that any software to manage Web sites will be able
772 # to handle CGIscriptor files, as will web agents.
774 # All script code should be placed between <SCRIPT></SCRIPT> tags, the
775 # script type is indicated with TYPE="mime-type", the LANGUAGE
776 # feature is ignored, and a SRC feature is implemented. All CGI specific
777 # features are delegated to the CGI attribute.
779 # However, the behavior deviates from the W3C recommendations at some
780 # points. Most notably:
781 # 0- The scripts are executed at the server side, invissible to the
782 # client (i.e., the browser)
783 # 1- The mime-types are personal and idiosyncratic, but can be adapted.
784 # 2- Code in the body of a <SCRIPT></SCRIPT> tag-pair is still evaluated
785 # when a SRC feature is present.
786 # 3- The SRC attribute reads a list of files.
787 # 4- The files in a SRC attribute are processed according to file type.
788 # 5- The SRC attribute evaluates inline Perl code.
789 # 6- Processed META, DIV, INS tags are removed from the output
790 # document.
791 # 7- All attributes of the processed META tags, except CONTENT, are ignored
792 # (i.e., deleted from the output).
793 # 8- META tags can be placed ANYWHERE in the document.
794 # 9- Through the SRC feature, META tags can have visible output in the
795 # document.
796 # 10- The CGI attribute that declares CGI parameters, can be used
797 # inside the <SCRIPT> tag.
798 # 11- Use of an extended quote set, i.e., '', "", ``, (), {}, []
799 # and their \-slashed combinations: \'\', \"\", \`\`, \(\),
800 # \{\}, \[\].
801 # 12- IF and UNLESS attributes to <SCRIPT>, <META>, <DIV>, <INS> tags.
802 # 13- <DIV> tags cannot be nested, DIV tags are not
803 # rendered with new-lines.
804 # 14- The XML style <TAG .... /> is recognized and handled correctly.
805 # (i.e., no content is processed)
807 # The reasons for these choices are:
808 # You can still write completely HTML4 compliant documents. CGIscriptor
809 # will not force you to write "deviant" code. However, it allows you to
810 # do so (which is, in fact, just as bad). The prime design principle
811 # was to allow users to include plain Perl code. The code itself should
812 # be "enhancement free". Therefore, extra features were needed to
813 # supply easy access to CGI and Web site components. For security
814 # reasons these have to be declared explicitly. The SRC feature
815 # transparently manages access to external files, especially the safe
816 # use of executable files.
817 # The CGI attribute handles the declarations of external (CGI) variables
818 # in the SCRIPT and META tag's.
819 # EVERYTHING THE CGI ATTRIBUTE AND THE META TAG DO CAN BE DONE INSIDE
820 # A <SCRIPT></SCRIPT> TAG CONSTRUCT.
822 # The reason for the IF, UNLESS, and SRC attributes (and their Perl code
823 # evaluation) were build into the META and SCRIPT tags is part laziness,
824 # part security. The SRC blocks allows more compact documents and easier
825 # debugging. The values of the CGI variables can be immediately screened
826 # for security by IF or UNLESS conditions, and even SRC attributes (e.g.,
827 # email addresses and file names), and a few commands can be called
828 # without having to add another Perl TAG pair. This is especially important
829 # for documents that require the use of other (more restricted) "scripting"
830 # languages and facilities that lag transparent control structures.
832 ##########################################################################
834 # SECURITY
836 # Your WWW site is a few keystrokes away from a few hundred million internet
837 # users. A fair percentage of these users knows more about your computer
838 # than you do. And some of these just might have bad intentions.
840 # To ensure uncompromized operation of your server and platform, several
841 # features are incorporated in CGIscriptor.pl to enhance security.
842 # First of all, you should check the source of this program. No security
843 # measures will help you when you download programs from anonymous sources.
844 # If you want to use THIS file, please make sure that it is uncompromized.
845 # The best way to do this is to contact the source and try to determine
846 # whether s/he is reliable (and accountable).
848 # BE AWARE THAT ANY PROGRAMMER CAN CHANGE THIS PROGRAM IN SUCH A WAY THAT
849 # IT WILL SET THE DOORS TO YOUR SYSTEM WIDE OPEN
851 # I would like to ask any user who finds bugs that could compromise
852 # security to report them to me (and any other bug too,
853 # Email: R.J.J.H.vanSon@uva.nl or ifa@hum.uva.nl).
855 # Security features
857 # 1 Invisibility
858 # The inner workings of the HTML source files are completely hidden
859 # from the client. Only the HTTP header and the ever changing content
860 # of the output distinguish it from the output of a plain, fixed HTML
861 # file. Names, structures, and arguments of the "embedded" scripts
862 # are invisible to the client. Error output is suppressed except
863 # during debugging (user configurable).
865 # 2 Separate directory trees
866 # Directories containing Inline text and script files can reside on
867 # separate trees, distinct from those of the HTTP server. This means
868 # that NEITHER the text files, NOR the script files can be read by
869 # clients other than through CGIscriptor.pl, UNLESS they are
870 # EXPLICITELY made available.
872 # 3 Requests are NEVER "evaluated"
873 # All client supplied values are used as literal values (''-quoted).
874 # Client supplied ''-quotes are ALWAYS removed. Therefore, as long as the
875 # embedded scripts do NOT themselves evaluate these values, clients CANNOT
876 # supply executable commands. Be sure to AVOID scripts like:
878 # <META CONTENT="text/ssperl; CGI='$UserValue'">
879 # <SCRIPT TYPE="text/ssperl">$dir = `ls -1 $UserValue`;</SCRIPT>
881 # These are a recipe for disaster. However, the following quoted
882 # form should be save (but is still not adviced):
884 # <SCRIPT TYPE="text/ssperl">$dir = `ls -1 \'$UserValue\'`;</SCRIPT>
886 # A special function, SAFEqx(), will automatically do exactly this,
887 # e.g., SAFEqx('ls -1 $UserValue') will execute `ls -1 \'$UserValue\'`
888 # with $UserValue interpolated. I recommend to use SAFEqx() instead
889 # of backticks whenever you can. The OS shell scripts inside
891 # <SCRIPT TYPE="text/osshell">ls -1 $UserValue</SCRIPT>
893 # are handeld by SAFEqx and automatically ''-quoted.
895 # 4 Logging of requests
896 # All requests can be logged separate from the Host server. The level of
897 # detail is user configurable: Including or excluding the actual queries.
898 # This allows for the inspection of (im-) proper use.
900 # 5 Access control: Clients
901 # The Remote addresses can be checked against a list of authorized
902 # (i.e., accepted) or non-authorized (i.e., rejected) clients. Both
903 # REMOTE_HOST and REMOTE_ADDR are tested so clients without a proper
904 # HOST name can be (in-) excluded by their IP-address. Client patterns
905 # containing all numbers and dots are considered IP-addresses, all others
906 # domain names. No wild-cards or regexp's are allowed, only partial
907 # addresses.
908 # Matching of names is done from the back to the front (domain first,
909 # i.e., $REMOTE_HOST =~ /\Q$pattern\E$/is), so including ".edu" will
910 # accept or reject all clients from the domain EDU. Matching of
911 # IP-addresses is done from the front to the back (domain first, i.e.,
912 # $REMOTE_ADDR =~ /^\Q$pattern\E/is), so including "128." will (in-)
913 # exclude all clients whose IP-address starts with 128.
914 # There are two special symbols: "-" matches HOSTs with no name and "*"
915 # matches ALL HOSTS/clients.
916 # For those needing more expressional power, lines starting with
917 # "-e" are evaluated by the perl eval() function. E.g.,
918 # '-e $REMOTE_HOST =~ /\.edu$/is;' will accept/reject clients from the
919 # domain '.edu'.
921 # 6 Access control: Files
922 # In principle, CGIscriptor could read ANY file in the directory
923 # tree as discussed in 1. However, for security reasons this is
924 # restricted to text files. It can be made more restricted by entering
925 # a global file pattern (e.g., ".html"). This is done by default.
926 # For each client requesting access, the file pattern(s) can be made
927 # more restrictive than the global pattern by entering client specific
928 # file patterns in the Access Control files (see 5).
929 # For example: if the ACCEPT file contained the lines
930 # * DEMO
931 # .hum.uva.nl LET
932 # 145.18.230.
933 # Then all clients could request paths containing "DEMO" or "demo", e.g.
934 # "/my/demo/file.html" ($PATH_INFO =~ /\Q$pattern\E/), Clients from
935 # *.hum.uva.nl could also request paths containing "LET or "let", e.g.
936 # "/my/let/file.html", and clients from the local cluster
937 # 145.18.230.[0-9]+ could access ALL files.
938 # Again, for those needing more expressional power, lines starting with
939 # "-e" are evaluated. For instance:
940 # '-e $REMOTE_HOST =~ /\.edu$/is && $PATH_INFO =~ m@/DEMO/@is;'
941 # will accept/reject requests for files from the directory "/demo/" from
942 # clients from the domain '.edu'.
944 # Access control: Login
945 # Specific paths can be controlled by Session Tickets which must be
946 # present as a SESSIONTICKET CGI variable in the request. These paths are
947 # defined in %LoginRequiredPatterns as pairs of:
948 # ('regexp' => 'SessionPath\tPasswordPath\tLogin.html').
949 # Session Tickets are stored in a separate directory (SessionPath, e.g.,
950 # "Private/.Session") as files with the exact same name of the SESSIONTICKET CGI
951 # Type: SESSION
952 # IPaddress: <127.0.0.1>
953 # AllowedPaths: <^/Private/Name/>
954 # Expires: <3600>
955 # ...
956 # Other content can follow. It is adviced that Session Tickets should be deleted
957 # after some (idle) time. The IP address should be the IP number at login, and
958 # the SESSIONTICKET will be rejected if it is presented from another IP address.
959 # AllowedPaths is a perl regexp. Be careful how they match. Make sure to delimit
960 # the names to prevent access to overlapping names, eg, "^/Private/Rob" will also
961 # match "^/Private/Robert", however, "^/Private/Rob/" will not. Expires is the
962 # time the ticket will remain valid after creation (file ctime). Time can be given
963 # in s[econds] (default), m[inutes], h[hours], or d[ays], eg, "24h" means 24 hours.
964 # None of these need be present, but the Ticket must have a non-zero size.
966 # 7 Query length limiting
967 # The length of the Query string can be limited. If CONTENT_LENGTH is larger
968 # than this limit, the request is rejected. The combined length of the
969 # Query string and the POST input is checked before any processing is done.
970 # This will prevent clients from overloading the scripts.
971 # The actual, combined, Query Size is accessible as a variable through
972 # $CGI_Content_Length.
974 # 8 Illegal filenames, paths, and protected directories
975 # One of the primary security concerns in handling CGI-scripts is the
976 # use of "funny" characters in the requests that con scripts in executing
977 # malicious commands. Examples are inserting ';', null bytes, or <newline>
978 # characters in URL's and filenames, followed by executable commands. A
979 # special variable $FileAllowedChars stores a string of all allowed
980 # characters. Any request that translates to a filename with a character
981 # OUTSIDE this set will be rejected.
982 # In general, all (readable files) in the DocumentRoot tree are accessible.
983 # This might not be what you want. For instance, your DocumentRoot directory
984 # might be the working directory of a CVS project and contain sensitive
985 # information (e.g., the password to get to the repository). You can block
986 # access to these subdirectories by adding the corresponding patterns to
987 # the $BlockPathAccess variable. For instance, $BlockPathAccess = '/CVS/'
988 # will block any request that contains '/CVS/' or:
989 # die if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@;
991 # 9 The execution of code blocks can be controlled in a transparent way
992 # by adding IF or UNLESS conditions in the tags themselves. That is,
993 # a simple check of the validity of filenames or email addresses can
994 # be done before any code is executed.
996 ###############################################################################
998 # USER MANUAL (sort of)
1000 # CGIscriptor removes embedded scripts, indicated by an HTML 4 type
1001 # <SCRIPT TYPE='text/ssperl'> </SCRIPT> or <SCRIPT TYPE='text/osshell'>
1002 # </SCRIPT> constructs. CGIscriptor also recognizes XML-type
1003 # <SCRIPT TYPE='text/ssperl'/> constructs. These are usefull when
1004 # the necessary code is already available in the TAG itself (e.g.,
1005 # using external files). The contents of the directive are executed by
1006 # the PERL eval() and `` functions (in a separate name space). The
1007 # result of the eval() function replaces the <SCRIPT> </SCRIPT> construct
1008 # in the output file. You can use the values that are delivered in
1009 # CGI-compliant form (i.e., the "?name=value&.." type URL additions)
1010 # transparently as "$name" variables in your directives after they are
1011 # defined in a <META> or <SCRIPT> tag.
1012 # If you define the variable "$CGIscriptorResults" in a CGI attribute, all
1013 # subsequent <SCRIPT> and <META> results (including the defining
1014 # tag) will also be pushed onto a stack: @CGIscriptorResults. This list
1015 # behaves like any other, ordinary list and can be manipulated.
1017 # Both GET and POST requests are accepted. These two methods are treated
1018 # equal. Variables, i.e., those values that are determined when a file is
1019 # processed, are indicated in the CGI attribute by $<name> or $<name>=<default>
1020 # in which <name> is the name of the variable and <default> is the value
1021 # used when there is NO current CGI value for <name> (you can use
1022 # white-spaces in $<name>=<default> but really DO make sure that the
1023 # default value is followed by white space or is quoted). Names can contain
1024 # any alphanumeric characters and _ (i.e., names match /[\w]+/).
1025 # If the Content-type: is 'multipart/*', the input is treated as a
1026 # MIME multipart message and automatically delimited. CGI variables get
1027 # the "raw" (i.e., undecoded) body of the corresponding message part.
1029 # Variables can be CGI variables, i.e., those from the QUERY_STRING,
1030 # environment variables, e.g., REMOTE_USER, REMOTE_HOST, or REMOTE_ADDR,
1031 # or predefined values, e.g., CGI_Decoded_QS (The complete, decoded,
1032 # query string), CGI_Content_Length (the length of the decoded query
1033 # string), CGI_Year, CGI_Month, CGI_Time, and CGI_Hour (the current
1034 # date and time).
1036 # All these are available when defined in a CGI attribute. All environment
1037 # variables are accessible as $ENV{'name'}. So, to access the REMOTE_HOST
1038 # and the REMOTE_USER, use, e.g.:
1040 # <SCRIPT TYPE='text/ssperl'>
1041 # ($ENV{'REMOTE_HOST'}||"-")." $ENV{'REMOTE_USER'}"
1042 # </SCRIPT>
1044 # (This will print a "-" if REMOTE_HOST is not known)
1045 # Another way to do this is:
1047 # <META CONTENT="text/ssperl; CGI='$REMOTE_HOST = - $REMOTE_USER'">
1048 # <SCRIPT TYPE='text/ssperl'>"$REMOTE_HOST $REMOTE_USER"</SCRIPT>
1049 # or
1050 # <META CONTENT='text/ssperl; CGI="$REMOTE_HOST = - $REMOTE_USER"
1051 # SRC={"$REMOTE_HOST $REMOTE_USER\n"}'>
1053 # This is possible because ALL environment variables are available as
1054 # CGI variables. The environment variables take precedence over CGI
1055 # names in case of a "name clash". For instance:
1056 # <META CONTENT="text/ssperl; CGI='$HOME' SRC={$HOME}">
1057 # Will print the current HOME directory (environment) irrespective whether
1058 # there is a CGI variable from the query
1059 # (e.g., Where do you live? <INPUT TYPE="TEXT" NAME="HOME">)
1060 # THIS IS A SECURITY FEATURE. It prevents clients from changing
1061 # the values of defined environment variables (e.g., by supplying
1062 # a bogus $REMOTE_ADDR). Although $ENV{} is not changed by the META tags,
1063 # it would make the use of declared variables insecure. You can still
1064 # access CGI variables after a name clash with
1065 # CGIscriptor::CGIparseValue(<name>).
1067 # Some CGI variables are present several times in the query string
1068 # (e.g., from multiple selections). These should be defined as
1069 # @VARIABLENAME=default in the CGI attribute. The list @VARIABLENAME
1070 # will contain ALL VARIABLENAME values from the query, or a single
1071 # default value. If there is an ENVIRONMENT variable of the
1072 # same name, it will be used instead of the default AND the query
1073 # values. The corresponding function is
1074 # CGIscriptor::CGIparseValueList(<name>)
1076 # CGI variables collected in a @VARIABLENAME list are unordered.
1077 # When more structured variables are needed, a hash table can be used.
1078 # A variable defined as %VARIABLE=default will collect all
1079 # CGI-parameters whose name start with 'VARIABLE' in a hash table with
1080 # the remainder of the name as a key. For instance, %PERSON will
1081 # collect PERSONname='John Doe', PERSONbirthdate='01 Jan 00', and
1082 # PERSONspouse='Alice' into a hash table %PERSON such that $PERSON{'spouse'}
1083 # equals 'Alice'. Any default value or environment value will be stored
1084 # under the "" key. If there is an ENVIRONMENT variable of the same name,
1085 # it will be used instead of the default AND the query values. The
1086 # corresponding function is CGIscriptor::CGIparseValueHash(<name>)
1088 # This method of first declaring your environment and CGI variables
1089 # before being able to use them in the scripts might seem somewhat
1090 # clumsy, but it protects you from inadvertedly printing out the values of
1091 # system environment variables when their names coincide with those used
1092 # in the CGI forms. It also prevents "clients" from supplying CGI
1093 # parameter values for your private variables.
1094 # THIS IS A SECURITY FEATURE!
1097 # NON-HTML CONTENT TYPES
1099 # Normally, CGIscriptor prints the standard "Content-type: text/html\n\n"
1100 # message before anything is printed. This has been extended to include
1101 # plain text (.txt) files, for which the Content-type (MIME type)
1102 # 'text/plain' is printed. In all other respects, text files are treated
1103 # as HTML files (this can be switched off by removing '.txt' from the
1104 # $FilePattern variable) . When the content type should be something else,
1105 # e.g., with multipart files, use the $RawFilePattern (.xmr, see also next
1106 # item). CGIscriptor will not print a Content-type message for this file
1107 # type (which must supply its OWN Content-type message). Raw files must
1108 # still conform to the <SCRIPT></SCRIPT> and <META> tag specifications.
1111 # NON-HTML FILES
1113 # CGIscriptor is intended to process HTML and text files only. You can
1114 # create documents of any mime-type on-the-fly using "raw" text files,
1115 # e.g., with the .xmr extension. However, CGIscriptor will not process
1116 # binary files of any type, e.g., pictures or sounds. Given the sheer
1117 # number of formats, I do not have any intention to do so. However,
1118 # an escape route has been provided. You can construct a genuine raw
1119 # (.xmr) text file that contains the perl code to service any file type
1120 # you want. If the global $BinaryMapFile variable contains the path to
1121 # this file (e.g., /BinaryMapFile.xmr), this file will be called
1122 # whenever an unsupported (non-HTML) file type is requested. The path
1123 # to the requested binary file is stored in $ENV('CGI_BINARY_FILE')
1124 # and can be used like any other CGI-variable. Servicing binary files
1125 # then becomes supplying the correct Content-type (e.g., print
1126 # "Content-type: image/jpeg\n\n";) and reading the file and writing it
1127 # to STDOUT (e.g., using sysread() and syswrite()).
1130 # THE META TAG
1132 # All attributes of a META tag are ignored, except the
1133 # CONTENT='text/ssperl; CGI=" ... " [SRC=" ... "]' attribute. The string
1134 # inside the quotes following the CONTENT= indication (white-space is
1135 # ignored, "" '' `` (){}[]-quote pairs are allowed, plus their \ versions)
1136 # MUST start with any of the CGIscriptor mime-types (e.g.: text/ssperl or
1137 # text/osshell) and a comma or semicolon.
1138 # The quoted string following CGI= contains a white-space separated list
1139 # of declarations of the CGI (and Environment) values and default values
1140 # used when no CGI values are supplied by the query string.
1142 # If the default value is a longer string containing special characters,
1143 # possibly spanning several lines, the string must be enclosed in quotes.
1144 # You may use any pair of quotes or brackets from the list '', "", ``, (),
1145 # [], or {} to distinguish default values (or preceded by \, e.g., \(...\)
1146 # is different from (...)). The outermost pair will always be used and any
1147 # other quotes inside the string are considered to be part of the string
1148 # value, e.g.,
1150 # $Value = {['this'
1151 # "and" (this)]}
1152 # will result in $Value getting the default value: ['this'
1153 # "and" (this)]
1154 # (NOTE that the newline is part of the default value!).
1156 # Internally, for defining and initializing CGI (ENV) values, the META
1157 # and SCRIPT tags use the functions "defineCGIvariable($name, $default)"
1158 # (scalars) and "defineCGIvariableList($name, $default)" (lists).
1159 # These functions can be used inside scripts as
1160 # "CGIscriptor::defineCGIvariable($name, $default)" and
1161 # "CGIscriptor::defineCGIvariableList($name, $default)".
1162 # "CGIscriptor::defineCGIvariableHash($name, $default)".
1164 # The CGI attribute will be processed exactly identical when used inside
1165 # the <SCRIPT> tag. However, this use is not according to the
1166 # HTML 4.0 specifications of the W3C.
1169 # THE DIV/INS TAGS
1171 # There is a problem when constructing html files containing
1172 # server-side perl scripts with standard HTML tools. These
1173 # tools will refuse to process any text between <SCRIPT></SCRIPT>
1174 # tags. This is quite annoying when you want to use large
1175 # HTML templates where you will fill in values.
1177 # For this purpose, CGIscriptor will read the neutral
1178 # <DIV CLASS="ssperl" ID="varname"></DIV> or
1179 # <INS CLASS="ssperl" ID="varname"></INS>
1180 # tag (in Cascading Style Sheet manner) Note that
1181 # "varname" has NO '$' before it, it is a bare name.
1182 # Any text between these <DIV ...></DIV> or
1183 # <INS ...></INS>tags will be assigned to '$varname'
1184 # as is (e.g., as a literal).
1185 # No processing or interpolation will be performed.
1186 # There is also NO nesting possible. Do NOT nest a
1187 # </DIV> inside a <DIV></DIV>! Moreover, neither INS nor
1188 # DIV tags do ensure a block structure in the final
1189 # rendering (i.e., no empty lines).
1191 # Note that <DIV CLASS="ssperl" ID="varname"/>
1192 # is handled the XML way. No content is processed,
1193 # but varname is defined, and any SRC directives are
1194 # processed.
1196 # You can use $varname like any other variable name.
1197 # However, $varname is NOT a CGI variable and will be
1198 # completely internal to your script. There is NO
1199 # interaction between $varname and the outside world.
1201 # To interpolate a DIV derived text, you can use:
1202 # $varname =~ s/([\]])/\\\1/g; # Mark ']'-quotes
1203 # $varname = eval("qq[$varname]"); # Interpolate all values
1205 # The DIV tags will process IF, UNLESS, CGI and
1206 # SRC attributes. The SRC files will be pre-pended to the
1207 # body text of the tag. SRC blocks are NOT executed.
1209 # CONDITIONAL PROCESSING: THE 'IF' AND 'UNLESS' ATTRIBUTES
1211 # It is often necessary to include code-blocks that should be executed
1212 # conditionally, e.g., only for certain browsers or operating system.
1213 # Furthermore, quite often sanity and security checks are necessary
1214 # before user (form) data can be processed, e.g., with respect to
1215 # email addresses and filenames.
1217 # Checks added to the code are often difficult to find, interpret or
1218 # maintain and in general mess up the code flow. This kind of confussion
1219 # is dangerous.
1220 # Also, for many of the supported "foreign" scripting languages, adding
1221 # these checks is cumbersome or even impossible.
1223 # As a uniform method for asserting the correctness of "context", two
1224 # attributes are added to all supported tags: IF and UNLESS.
1225 # They both evaluate their value and block execution when the
1226 # result is <FALSE> (IF) or <TRUE> (UNLESS) in Perl, e.g.,
1227 # UNLESS='$NUMBER \> 100;' blocks execution if $NUMBER <= 100. Note that
1228 # the backslash in the '\>' is removed and only used to differentiate
1229 # this conditional '>' from the tag-closing '>'. For symmetry, the
1230 # backslash in '\<' is also removed. Inside these conditionals,
1231 # ~/ and ./ are expanded to their respective directory root paths.
1233 # For example, the following tag will be ignored when the filename is
1234 # invalid:
1236 # <SCRIPT TYPE='text/ssperl' CGI='$FILENAME'
1237 # IF='CGIscriptor::CGIsafeFileName($FILENAME);'>
1238 # ...
1239 # </SCRIPT>
1241 # The IF and UNLESS values must be quoted. The same quotes are supported
1242 # as with the other attributes. The SRC attribute is ignored when IF and
1243 # UNLESS block execution.
1245 # NOTE: 'IF' and 'UNLESS' always evaluate perl code.
1248 # THE MAGIC SOURCE ATTRIBUTE (SRC=)
1250 # The SRC attribute inside tags accepts a list of filenames and URL's
1251 # separated by "," comma's (or ";" semicolons).
1252 # ALL the variable values defined in the CGI attribute are available
1253 # in @ARGV as if the file or block was executed from the command line,
1254 # in the exact order in which they were declared in the preceding CGI
1255 # attribute.
1257 # First, a SRC={}-block will be evaluated as if the code inside the
1258 # block was part of a <SCRIPT></SCRIPT> construct, i.e.,
1259 # "print do { code };'';" or `code` (i.e., SAFEqx('code)).
1260 # Only a single block is evaluated. Note that this is processed less
1261 # efficiently than <SCRIPT> </SCRIPT> blocks. Type of evaluation
1262 # depends on the content-type: Perl for text/ssperl and OS shell for
1263 # text/osshell. For other mime types (scripting languages), anything in
1264 # the source block is put in front of the code block "inside" the tag.
1266 # Second, executable files (i.e., -x filename != 0) are evaluated as:
1267 # print `filename \'$ARGV[0]\' \'$ARGV[1]\' ...`
1268 # That is, you can actually call executables savely from the SRC tag.
1270 # Third, text files that match the file pattern, used by CGIscriptor to
1271 # check whether files should be processed ($FilePattern), are
1272 # processed in-line (i.e., recursively) by CGIscriptor as if the code
1273 # was inserted in the original source file. Recursions, i.e., calling
1274 # a file inside itself, are blocked. If you need them, you have to code
1275 # them explicitely using "main::ProcessFile($file_path)".
1277 # Fourth, Perl text files (i.e., -T filename != 0) are evaluated as:
1278 # "do FileName;'';".
1280 # Last, URL's (i.e., starting with 'HTTP://', 'FTP://', 'GOPHER://',
1281 # 'TELNET://', 'WHOIS://' etc.) are loaded
1282 # and printed. The loading and handling of <BASE> and document header
1283 # is done by a command generated by main::GET_URL($URL [, 0]). You can enter your
1284 # own code (default is curl, wget, or snarf and some post-processing to add a <BASE> tag).
1286 # There are two pseudo-file names: PREFIX and POSTFIX. These implement
1287 # a switch from prefixing the SRC code/files (PREFIX, default) before the
1288 # content of the tag to appending the code after the content of the tag
1289 # (POSTFIX). The switches are done in the order in which the PREFIX and
1290 # POSTFIX labels are encountered. You can mix PREFIX and POSTFIX labels
1291 # in any order with the SRC files. Note that the ORDER of file execution
1292 # is determined for prefixed and postfixed files seperately.
1294 # File paths can be preceded by the URL protocol prefix "file://". This
1295 # is simply STRIPPED from the name.
1297 # Example:
1298 # The request
1299 # "http://cgi-bin/Action_Forms.pl/Statistics/Sign_Test.html?positive=8&negative=22
1300 # will result in printing "${SS_PUB}/Statistics/Sign_Test.html"
1301 # With QUERY_STRING = "positive=8&negative=22"
1303 # on encountering the lines:
1304 # <META CONTENT="text/osshell; CGI='$positive=11 $negative=3'">
1305 # <b><SCRIPT LANGUAGE=PERL TYPE="text/ssperl" SRC="./Statistics/SignTest.pl">
1306 # </SCRIPT></b><p>"
1308 # This line will be processed as:
1309 # "<b>`${SS_SCRIPT}/Statistics/SignTest.pl '8' '22'`</b><p>"
1311 # In which "${SS_SCRIPT}/Statistics/SignTest.pl" is an executable script,
1312 # This line will end up printed as:
1313 # "<b>p <= 0.0161</b><p>"
1315 # Note that the META tag itself will never be printed, and is invisible to
1316 # the outside world.
1318 # The SRC files in a DIV or INS tag will be added (pre-pended) to the body
1319 # of the <DIV></DIV> tag. Blocks are NOT executed! If you do not
1320 # need any content, you can use the <DIV...../> format.
1323 # THE CGISCRIPTOR ROOT DIRECTORIES ~/ AND ./
1325 # Inside <SCRIPT></SCRIPT> tags, filepaths starting
1326 # with "~/" are replaced by "$YOUR_HTML_FILES/", this way files in the
1327 # public directories can be accessed without direct reference to the
1328 # actual paths. Filepaths starting with "./" are replaced by
1329 # "$YOUR_SCRIPTS/" and this should only be used for scripts.
1331 # Note: this replacement can seriously affect Perl scripts. Watch
1332 # out for constructs like $a =~ s/aap\./noot./g, use
1333 # $a =~ s@aap\.@noot.@g instead.
1335 # CGIscriptor.pl will assign the values of $SS_PUB and $SS_SCRIPT
1336 # (i.e., $YOUR_HTML_FILES and $YOUR_SCRIPTS) to the environment variables
1337 # $SS_PUB and $SS_SCRIPT. These can be accessed by the scripts that are
1338 # executed.
1339 # Values not preceded by $, ~/, or ./ are used as literals
1342 # OS SHELL SCRIPT EVALUATION (CONTENT-TYPE=TEXT/OSSHELL)
1344 # OS scripts are executed by a "safe" version of the `` operator (i.e.,
1345 # SAFEqx(), see also below) and any output is printed. CGIscriptor will
1346 # interpolate the script and replace all user-supplied CGI-variables by
1347 # their ''-quoted values (actually, all variables defined in CGI attributes
1348 # are quoted). Other Perl variables are interpolated in a simple fasion,
1349 # i.e., $scalar by their value, @list by join(' ', @list), and %hash by
1350 # their name=value pairs. Complex references, e.g., @$variable, are all
1351 # evaluated in a scalar context. Quotes should be used with care.
1352 # NOTE: the results of the shell script evaluation will appear in the
1353 # @CGIscriptorResults stack just as any other result.
1354 # All occurrences of $@% that should NOT be interpolated must be
1355 # preceeded by a "\". Interpolation can be switched off completely by
1356 # setting $CGIscriptor::NoShellScriptInterpolation = 1
1357 # (set to 0 or undef to switch interpolation on again)
1358 # i.e.,
1359 # <SCRIPT TYPE="text/ssperl">
1360 # $CGIscriptor::NoShellScriptInterpolation = 1;
1361 # </SCRIPT>
1364 # RUN TIME TRANSLATION OF INPUT FILES
1366 # Allows general and global conversions of files using Regular Expressions.
1367 # Very handy (but costly) to rewrite legacy pages to a new format.
1368 # Select files to use it on with
1369 # my $TranslationPaths = 'filepattern';
1370 # This is costly. For efficiency, define:
1371 # $TranslationPaths = ''; when not using translations.
1372 # Accepts general regular expressions: [$pattern, $replacement]
1374 # Define:
1375 # my $TranslationPaths = 'filepattern'; # Pattern matching PATH_INFO
1377 # push(@TranslationTable, ['pattern', 'replacement']);
1378 # e.g. (for Ruby Rails):
1379 # push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
1380 # push(@TranslationTable, ['%>', '</SCRIPT>']);
1382 # Runs:
1383 # my $currentRegExp;
1384 # foreach $currentRegExp (@TranslationTable)
1386 # my ($pattern, $replacement) = @$currentRegExp;
1387 # $$text =~ s!$pattern!$replacement!msg;
1388 # };
1391 # EVALUATION OF OTHER SCRIPTING LANGUAGES
1393 # Adding a MIME-type and an interpreter command to
1394 # %ScriptingLanguages automatically will catch any other
1395 # scripting language in the standard
1396 # <SCRIPT TYPE="[mime]"></SCRIPT> manner.
1397 # E.g., adding: $ScriptingLanguages{'text/sspython'} = 'python';
1398 # will actually execute the folowing code in an HTML page
1399 # (ignore 'REMOTE_HOST' for the moment):
1400 # <SCRIPT TYPE="text/sspython">
1401 # # A Python script
1402 # x = ["A","real","python","script","Hello","World","and", REMOTE_HOST]
1403 # print x[4:8] # Prints the list ["Hello","World","and", REMOTE_HOST]
1404 # </SCRIPT>
1406 # The script code is NOT interpolated by perl, EXCEPT for those
1407 # interpreters that cannot handle variables themselves.
1408 # Currently, several interpreters are pre-installed:
1410 # Perl test - "text/testperl" => 'perl',
1411 # Python - "text/sspython" => 'python',
1412 # Ruby - "text/ssruby" => 'ruby',
1413 # Tcl - "text/sstcl" => 'tcl',
1414 # Awk - "text/ssawk" => 'awk -f-',
1415 # Gnu Lisp - "text/sslisp" => 'rep | tail +5 '.
1416 # "| egrep -v '> |^rep. |^nil\\\$'",
1417 # XLispstat - "text/xlispstat" => 'xlispstat | tail +7 '.
1418 # "| egrep -v '> \\\$|^NIL'",
1419 # Gnu Prolog- "text/ssprolog" => 'gprolog',
1420 # M4 macro's- "text/ssm4" => 'm4',
1421 # Born shell- "text/sh" => 'sh',
1422 # Bash - "text/bash" => 'bash',
1423 # C-shell - "text/csh" => 'csh',
1424 # Korn shell- "text/ksh" => 'ksh',
1425 # Praat - "text/sspraat" => "praat - | sed 's/Praat > //g'",
1426 # R - "text/ssr" => "R --vanilla --slave | sed 's/^[\[0-9\]*] //g'",
1427 # REBOL - "text/ssrebol" =>
1428 # "rebol --quiet|egrep -v '^[> ]* == '|sed 's/^\s*\[> \]* //g'",
1429 # PostgreSQL- "text/postgresql" => 'psql 2>/dev/null',
1430 # (psql)
1432 # Note that the "value" of $ScriptingLanguages{mime} must be a command
1433 # that reads Standard Input and writes to standard output. Any extra
1434 # output of interactive interpreters (banners, echo's, prompts)
1435 # should be removed by piping the output through 'tail', 'grep',
1436 # 'sed', or even 'awk' or 'perl'.
1438 # For access to CGI variables there is a special hashtable:
1439 # %ScriptingCGIvariables.
1440 # CGI variables can be accessed in three ways.
1441 # 1. If the mime type is not present in %ScriptingCGIvariables,
1442 # nothing is done and the script itself should parse the relevant
1443 # environment variables.
1444 # 2. If the mime type IS present in %ScriptingCGIvariables, but it's
1445 # value is empty, e.g., $ScriptingCGIvariables{"text/sspraat"} = '';,
1446 # the script text is interpolated by perl. That is, all $var, @array,
1447 # %hash, and \-slashes are replaced by their respective values.
1448 # 3. In all other cases, the CGI and environment variables are added
1449 # in front of the script according to the format stored in
1450 # %ScriptingCGIvariables. That is, the following (pseudo-)code is
1451 # executed for each CGI- or Environment variable defined in the CGI-tag:
1452 # printf(INTERPRETER, $ScriptingCGIvariables{$mime}, $CGI_NAME, $CGI_VALUE);
1454 # For instance, "text/testperl" => '$%s = "%s";' defines variable
1455 # definitions for Perl, and "text/sspython" => '%s = "%s"' for Python
1456 # (note that these definitions are not save, the real ones contain '-quotes).
1458 # THIS WILL NOT WORK FOR @VARIABLES, the (empty) $VARIABLES will be used
1459 # instead.
1461 # The $CGI_VALUE parameters are "shrubed" of all control characters
1462 # and quotes (by &shrubCGIparameter($CGI_VALUE)) for the options 2 and 3.
1463 # Control characters are replaced by \0<octal ascii value> (the exception
1464 # is \015, the newline, which is replaced by \n) and quotes
1465 # and backslashes by their HTML character
1466 # value (' -> &#39; ` -> &#96; " -> &quot; \ -> &#92; & -> &amper;).
1467 # For example:
1468 # if a client would supply the string value (in standard perl, e.g.,
1469 # \n means <newline>)
1470 # "/dev/null';\nrm -rf *;\necho '"
1471 # it would be processed as
1472 # '/dev/null&#39;;\nrm -rf *;\necho &#39;'
1473 # (e.g., sh or bash would process the latter more according to your
1474 # intentions).
1475 # If your intepreter requires different protection measures, you will
1476 # have to supply these in %main::SHRUBcharacterTR (string => translation),
1477 # e.g., $SHRUBcharacterTR{"\'"} = "&#39;";
1479 # Currently, the following definitions are used:
1480 # %ScriptingCGIvariables = (
1481 # "text/testperl" => "\$\%s = '\%s';", # Perl $VAR = 'value' (for testing)
1482 # "text/sspython" => "\%s = '\%s'", # Python VAR = 'value'
1483 # "text/ssruby" => '@%s = "%s"', # Ruby @VAR = "value"
1484 # "text/sstcl" => 'set %s "%s"', # TCL set VAR "value"
1485 # "text/ssawk" => '%s = "%s";', # Awk VAR = "value";
1486 # "text/sslisp" => '(setq %s "%s")', # Gnu lisp (rep) (setq VAR "value")
1487 # "text/xlispstat" => '(setq %s "%s")', # Xlispstat (setq VAR "value")
1488 # "text/ssprolog" => '', # Gnu prolog (interpolated)
1489 # "text/ssm4" => "define(`\%s', `\%s')", # M4 macro's define(`VAR', `value')
1490 # "text/sh" => "\%s='\%s';", # Born shell VAR='value';
1491 # "text/bash" => "\%s='\%s';", # Born again shell VAR='value';
1492 # "text/csh" => "\$\%s = '\%s';", # C shell $VAR = 'value';
1493 # "text/ksh" => "\$\%s = '\%s';", # Korn shell $VAR = 'value';
1494 # "text/sspraat" => '', # Praat (interpolation)
1495 # "text/ssr" => '%s <- "%s";', # R VAR <- "value";
1496 # "text/ssrebol" => '%s: copy "%s"', # REBOL VAR: copy "value"
1497 # "text/postgresql" => '', # PostgreSQL (interpolation)
1498 # "" => ""
1499 # );
1501 # Four tables allow fine-tuning of interpreter with code that should be
1502 # added before and after each code block:
1504 # Code added before each script block
1505 # %ScriptingPrefix = (
1506 # "text/testperl" => "\# Prefix Code;", # Perl script testing
1507 # "text/ssm4" => 'divert(0)' # M4 macro's (open STDOUT)
1508 # );
1509 # Code added at the end of each script block
1510 # %ScriptingPostfix = (
1511 # "text/testperl" => "\# Postfix Code;", # Perl script testing
1512 # "text/ssm4" => 'divert(-1)' # M4 macro's (block STDOUT)
1513 # );
1514 # Initialization code, inserted directly after opening (NEVER interpolated)
1515 # %ScriptingInitialization = (
1516 # "text/testperl" => "\# Initialization Code;", # Perl script testing
1517 # "text/ssawk" => 'BEGIN {', # Server Side awk scripts
1518 # "text/sslisp" => '(prog1 nil ', # Lisp (rep)
1519 # "text/xlispstat" => '(prog1 nil ', # xlispstat
1520 # "text/ssm4" => 'divert(-1)' # M4 macro's (block STDOUT)
1521 # );
1522 # Cleanup code, inserted before closing (NEVER interpolated)
1523 # %ScriptingCleanup = (
1524 # "text/testperl" => "\# Cleanup Code;", # Perl script testing
1525 # "text/sspraat" => 'Quit',
1526 # "text/ssawk" => '};', # Server Side awk scripts
1527 # "text/sslisp" => '(princ "\n" standard-output)).' # Closing print to rep
1528 # "text/xlispstat" => '(print "" *standard-output*)).' # Closing print to xlispstat
1529 # "text/postgresql" => '\q',
1530 # );
1533 # The SRC attribute is NOT magical for these interpreters. In short,
1534 # all code inside a source file or {} block is written verbattim
1535 # to the interpreter. No (pre-)processing or executional magic is done.
1537 # A serious shortcomming of the described mechanism for handling other
1538 # (scripting) languages, with respect to standard perl scripts
1539 # (i.e., 'text/ssperl'), is that the code is only executed when
1540 # the pipe to the interpreter is closed. So the pipe has to be
1541 # closed at the end of each block. This means that the state of the
1542 # interpreter (e.g., all variable values) is lost after the closing of
1543 # the next </SCRIPT> tag. The standard 'text/ssperl' scripts retain
1544 # all values and definitions.
1546 # APPLICATION MIME TYPES
1548 # To ease some important auxilliary functions from within the
1549 # html pages I have added them as MIME types. This uses
1550 # the mechanism that is also used for the evaluation of
1551 # other scripting languages, with interpolation of CGI
1552 # parameters (and perl-variables). Actually, these are
1553 # defined exactly like any other "scripting language".
1555 # text/ssdisplay: display some (HTML) text with interpolated
1556 # variables (uses `cat`).
1557 # text/sslogfile: write (append) the interpolated block to the file
1558 # mentioned on the first, non-empty line
1559 # (the filename can be preceded by 'File: ',
1560 # note the space after the ':',
1561 # uses `awk .... >> <filename>`).
1562 # text/ssmailto: send email directly from within the script block.
1563 # The first line of the body must contain
1564 # To:Name@Valid.Email.Address
1565 # (note: NO space between 'To:' and the email adres)
1566 # For other options see the mailto man pages.
1567 # It works by directly sending the (interpolated)
1568 # content of the text block to a pipe into the
1569 # Linux program 'mailto'.
1571 # In these script blocks, all Perl variables will be
1572 # replaced by their values. All CGI variables are cleaned before
1573 # they are used. These CGI variables must be redefined with a
1574 # CGI attribute to restore their original values.
1575 # In general, this will be more secure than constructing
1576 # e.g., your own email command lines. For instance, Mailto will
1577 # not execute any odd (forged) email addres, but just stops
1578 # when the email address is invalid and awk will construct
1579 # any filename you give it (e.g. '<File;rm\\\040-f' would end up
1580 # as a "valid" UNIX filename). Note that it will also gladly
1581 # store this file anywhere (/../../../etc/passwd will work!).
1582 # Use the CGIscriptor::CGIsafeFileName() function to clean the
1583 # filename.
1585 # SHELL SCRIPT PIPING
1587 # If a shell script starts with the UNIX style "#! <shell command> \n"
1588 # line, the rest of the shell script is piped into the indicated command,
1589 # i.e.,
1590 # open(COMMAND, "| command");print COMMAND $RestOfScript;
1592 # In many ways this is equivalent to the MIME-type profiling for
1593 # evaluating other scripting languages as discussed above. The
1594 # difference breaks down to convenience. Shell script piping is a
1595 # "raw" implementation. It allows you to control all aspects of
1596 # execution. Using the MIME-type profiling is easier, but has a
1597 # lot of defaults built in that might get in the way. Another
1598 # difference is that shell script piping uses the SAFEqx() function,
1599 # and MIME-type profiling does not.
1601 # Execution of shell scripts is under the control of the Perl Script blocks
1602 # in the document. The MIME-type triggered execution of <SCRIPT></SCRIPT>
1603 # blocks can be simulated easily. You can switch to a different shell,
1604 # e.g. tcl, completely by executing the following Perl commands inside
1605 # your document:
1607 # <SCRIPT TYPE="text/ssperl">
1608 # $main::ShellScriptContentType = "text/ssTcl"; # Yes, you can do this
1609 # CGIscriptor::RedirectShellScript('/usr/bin/tcl'); # Pipe to Tcl
1610 # $CGIscriptor::NoShellScriptInterpolation = 1;
1611 # </SCRIPT>
1613 # After this script is executed, CGIscriptor will parse scripts of
1614 # TYPE="text/ssTcl" and pipe their contents into '|/usr/bin/tcl'
1615 # WITHOUT interpolation (i.e., NO substitution of Perl variables).
1616 # The crucial function is :
1617 # CGIscriptor::RedirectShellScript('/usr/bin/tcl')
1618 # After executing this function, all shell scripts AND all
1619 # calls to SAFEqx()) are piped into '|/usr/bin/tcl'. If the argument
1620 # of RedirectShellScript is empty, e.g., '', the original (default)
1621 # value is reset.
1623 # The standard output, STDOUT, of any pipe is send to the client.
1624 # Currently, you should be carefull with quotes in such a piped script.
1625 # The results of a pipe is NOT put on the @CGIscriptorResults stack.
1626 # As a result, you do not have access to the output of any piped (#!)
1627 # process! If you want such access, execute
1628 # <SCRIPT TYPE="text/osshell">echo "script"|command</SCRIPT>
1629 # or
1630 # <SCRIPT TYPE="text/ssperl">
1631 # $resultvar = SAFEqx('echo "script"|command');
1632 # </SCRIPT>.
1634 # Safety is never complete. Although SAFEqx() prevents some of the
1635 # most obvious forms of attacks and security slips, it cannot prevent
1636 # them all. Especially, complex combinations of quotes and intricate
1637 # variable references cannot be handled safely by SAFEqx. So be on
1638 # guard.
1641 # PERL CODE EVALUATION (CONTENT-TYPE=TEXT/SSPERL)
1643 # All PERL scripts are evaluated inside a PERL package. This package
1644 # has a separate name space. This isolated name space protects the
1645 # CGIscriptor.pl program against interference from user code. However,
1646 # some variables, e.g., $_, are global and cannot be protected. You are
1647 # advised NOT to use such global variable names. You CAN write
1648 # directives that directly access the variables in the main program.
1649 # You do so at your own risk (there is definitely enough rope available
1650 # to hang yourself). The behavior of CGIscriptor becomes undefined if
1651 # you change its private variables during run time. The PERL code
1652 # directives are used as in:
1653 # $Result = eval($directive); print $Result;'';
1654 # ($directive contains all text between <SCRIPT></SCRIPT>).
1655 # That is, the <directive> is treated as ''-quoted string and
1656 # the result is treated as a scalar. To prevent the VALUE of the code
1657 # block from appearing on the client's screen, end the directive with
1658 # ';""</SCRIPT>'. Evaluated directives return the last value, just as
1659 # eval(), blocks, and subroutines, but only as a scalar.
1661 # IMPORTANT: All PERL variables defined are persistent. Each <SCRIPT>
1662 # </SCRIPT> construct is evaluated as a {}-block with associated scope
1663 # (e.g., for "my $var;" declarations). This means that values assigned
1664 # to a PERL variable can be used throughout the document unless they
1665 # were declared with "my". The following will actually work as intended
1666 # (note that the ``-quotes in this example are NOT evaluated, but used
1667 # as simple quotes):
1669 # <META CONTENT="text/ssperl; CGI=`$String='abcdefg'`">
1670 # anything ...
1671 # <SCRIPT TYPE=text/ssperl>@List = split('', $String);</SCRIPT>
1672 # anything ...
1673 # <SCRIPT TYPE=text/ssperl>join(", ", @List[1..$#List]);</SCRIPT>
1675 # The first <SCRIPT TYPE=text/ssperl></SCRIPT> construct will return the
1676 # value scalar(@List), the second <SCRIPT TYPE=text/ssperl></SCRIPT>
1677 # construct will print the elements of $String separated by commas, leaving
1678 # out the first element, i.e., $List[0].
1680 # Another warning: './' and '~/' are ALWAYS replaced by the values of
1681 # $YOUR_SCRIPTS and $YOUR_HTML_FILES, respectively . This can interfere
1682 # with pattern matching, e.g., $a =~ s/aap\./noot\./g will result in the
1683 # evaluations of $a =~ s/aap\\${YOUR_SCRIPTS}noot\\${YOUR_SCRIPTS}g. Use
1684 # s@<regexp>.@<replacement>.@g instead.
1687 # USER EXTENSIONS
1689 # A CGIscriptor package is attached to the bottom of this file. With
1690 # this package you can personalize your version of CGIscriptor by
1691 # including often used perl routines. These subroutines can be
1692 # accessed by prefixing their names with CGIscriptor::, e.g.,
1693 # <SCRIPT LANGUAGE=PERL TYPE=text/ssperl>
1694 # CGIscriptor::ListDocs("/Books/*") # List all documents in /Books
1695 # </SCRIPT>
1696 # It already contains some useful subroutines for Document Management.
1697 # As it is a separate package, it has its own namespace, isolated from
1698 # both the evaluator and the main program. To access variables from
1699 # the document <SCRIPT></SCRIPT> blocks, use $CGIexecute::<var>.
1701 # Currently, the following functions are implemented
1702 # (precede them with CGIscriptor::, see below for more information)
1703 # - SAFEqx ('String') -> result of qx/"String"/ # Safe application of ``-quotes
1704 # Is used by text/osshell Shell scripts. Protects all CGI
1705 # (client-supplied) values with single quotes before executing the
1706 # commands (one of the few functions that also works WITHOUT CGIscriptor::
1707 # in front)
1708 # - defineCGIvariable ($name[, $default) -> 0/1 (i.e., failure/success)
1709 # Is used by the META tag to define and initialize CGI and ENV
1710 # name/value pairs. Tries to obtain an initializing value from (in order):
1711 # $ENV{$name}
1712 # The Query string
1713 # The default value given (if any)
1714 # (one of the few functions that also works WITHOUT CGIscriptor::
1715 # in front)
1716 # - CGIsafeFileName (FileName) -> FileName or ""
1717 # Check a string against the Allowed File Characters (and ../ /..).
1718 # Returns an empty string for unsafe filenames.
1719 # - CGIsafeEmailAddress (Email) -> Email or ""
1720 # Check a string against correct email address pattern.
1721 # Returns an empty string for unsafe addresses.
1722 # - RedirectShellScript ('CommandString') -> FILEHANDLER or undef
1723 # Open a named PIPE for SAFEqx to receive ALL shell scripts
1724 # - URLdecode (URL encoded string) -> plain string # Decode URL encoded argument
1725 # - URLencode (plain string) -> URL encoded string # Encode argument as URL code
1726 # - CGIparseValue (ValueName [, URL_encoded_QueryString]) -> Decoded value
1727 # Extract the value of a CGI variable from the global or a private
1728 # URL-encoded query (multipart POST raw, NOT decoded)
1729 # - CGIparseValueList (ValueName [, URL_encoded_QueryString])
1730 # -> List of decoded values
1731 # As CGIparseValue, but now assembles ALL values of ValueName into a list.
1732 # - CGIparseHeader (ValueName [, URL_encoded_QueryString]) -> Header
1733 # Extract the header of a multipart CGI variable from the global or a private
1734 # URL-encoded query ("" when not a multipart variable or absent)
1735 # - CGIparseForm ([URL_encoded_QueryString]) -> Decoded Form
1736 # Decode the complete global URL-encoded query or a private
1737 # URL-encoded query
1738 # - read_url(URL) # Returns the page from URL (with added base tag, both FTP and HTTP)
1739 # Uses main::GET_URL(URL, 1) to get at the command to read the URL.
1740 # - BrowseDirs(RootDirectory [, Pattern, Startdir, CGIname]) # print browsable directories
1741 # - ListDocs(Pattern [,ListType]) # Prints a nested HTML directory listing of
1742 # all documents, e.g., ListDocs("/*", "dl");.
1743 # - HTMLdocTree(Pattern [,ListType]) # Prints a nested HTML listing of all
1744 # local links starting from a given document, e.g.,
1745 # HTMLdocTree("/Welcome.html", "dl");
1748 # THE RESULTS STACK: @CGISCRIPTORRESULTS
1750 # If the pseudo-variable "$CGIscriptorResults" has been defined in a
1751 # META tag, all subsequent SCRIPT and META results are pushed
1752 # on the @CGIscriptorResults stack. This list is just another
1753 # Perl variable and can be used and manipulated like any other list.
1754 # $CGIscriptorResults[-1] is always the last result.
1755 # This is only of limited use, e.g., to use the results of an OS shell
1756 # script inside a Perl script. Will NOT contain the results of Pipes
1757 # or code from MIME-profiling.
1760 # USEFULL CGI PREDEFINED VARIABLES (DO NOT ASSIGN TO THESE)
1762 # $CGI_HOME - The DocumentRoot directory
1763 # $CGI_Decoded_QS - The complete decoded Query String
1764 # $CGI_Content_Length - The ACTUAL length of the Query String
1765 # $CGI_Date - Current date and time
1766 # $CGI_Year $CGI_Month $CGI_Day $CGI_WeekDay - Current Date
1767 # $CGI_Time - Current Time
1768 # $CGI_Hour $CGI_Minutes $CGI_Seconds - Current Time, split
1769 # GMT Date/Time:
1770 # $CGI_GMTYear $CGI_GMTMonth $CGI_GMTDay $CGI_GMTWeekDay $CGI_GMTYearDay
1771 # $CGI_GMTHour $CGI_GMTMinutes $CGI_GMTSeconds $CGI_GMTisdst
1774 # USEFULL CGI ENVIRONMENT VARIABLES
1776 # Variables accessible (in APACHE) as $ENV{<name>}
1777 # (see: "http://hoohoo.ncsa.uiuc.edu/cgi/env.html"):
1779 # QUERY_STRING - The query part of URL, that is, everything that follows the
1780 # question mark.
1781 # PATH_INFO - Extra path information given after the script name
1782 # PATH_TRANSLATED - Extra pathinfo translated through the rule system.
1783 # (This doesn't always make sense.)
1784 # REMOTE_USER - If the server supports user authentication, and the script is
1785 # protected, this is the username they have authenticated as.
1786 # REMOTE_HOST - The hostname making the request. If the server does not have
1787 # this information, it should set REMOTE_ADDR and leave this unset
1788 # REMOTE_ADDR - The IP address of the remote host making the request.
1789 # REMOTE_IDENT - If the HTTP server supports RFC 931 identification, then this
1790 # variable will be set to the remote user name retrieved from
1791 # the server. Usage of this variable should be limited to logging
1792 # only.
1793 # AUTH_TYPE - If the server supports user authentication, and the script
1794 # is protected, this is the protocol-specific authentication
1795 # method used to validate the user.
1796 # CONTENT_TYPE - For queries which have attached information, such as HTTP
1797 # POST and PUT, this is the content type of the data.
1798 # CONTENT_LENGTH - The length of the said content as given by the client.
1799 # SERVER_SOFTWARE - The name and version of the information server software
1800 # answering the request (and running the gateway).
1801 # Format: name/version
1802 # SERVER_NAME - The server's hostname, DNS alias, or IP address as it
1803 # would appear in self-referencing URLs
1804 # GATEWAY_INTERFACE - The revision of the CGI specification to which this
1805 # server complies. Format: CGI/revision
1806 # SERVER_PROTOCOL - The name and revision of the information protocol this
1807 # request came in with. Format: protocol/revision
1808 # SERVER_PORT - The port number to which the request was sent.
1809 # REQUEST_METHOD - The method with which the request was made. For HTTP,
1810 # this is "GET", "HEAD", "POST", etc.
1811 # SCRIPT_NAME - A virtual path to the script being executed, used for
1812 # self-referencing URLs.
1813 # HTTP_ACCEPT - The MIME types which the client will accept, as given by
1814 # HTTP headers. Other protocols may need to get this
1815 # information from elsewhere. Each item in this list should
1816 # be separated by commas as per the HTTP spec.
1817 # Format: type/subtype, type/subtype
1818 # HTTP_USER_AGENT - The browser the client is using to send the request.
1819 # General format: software/version library/version.
1822 # INSTRUCTIONS FOR RUNNING CGIscriptor ON UNIX
1824 # CGIscriptor.pl will run on any WWW server that runs Perl scripts, just add
1825 # a line like the following to your srm.conf file (Apache example):
1827 # ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
1829 # URL's that refer to http://www.your.address/SHTML/... will now be handled
1830 # by CGIscriptor.pl, which can use a private directory tree (default is the
1831 # DOCUMENT_ROOT directory tree, but it can be anywhere, see manual).
1833 # If your hosting ISP won't let you add ScriptAlias lines you can use
1834 # the following "rewrite"-based "scriptalias" in .htaccess
1835 # (from Gerd Franke)
1837 # RewriteEngine On
1838 # RewriteBase /
1839 # RewriteCond %{REQUEST_FILENAME} .html$
1840 # RewriteCond %{SCRIPT_FILENAME} !cgiscriptor.pl$
1841 # RewriteCond %{REQUEST_FILENAME} -f
1842 # RewriteRule ^(.*)$ /cgi-bin/cgiscriptor.pl/$1?&%{QUERY_STRING}
1844 # Everthing with the extension ".html" and not including "cgiscriptor.pl"
1845 # in the url and where the file "path/filename.html" exists is redirected
1846 # to "/cgi.bin/cgiscriptor.pl/path/filename.html?query".
1847 # The user configuration should get the same path-level as the
1848 # .htaccess-file:
1850 # # Just enter your own directory path here
1851 # $YOUR_HTML_FILES = "$ENV{'DOCUMENT_ROOT'}";
1852 # # use DOCUMENT_ROOT only, if .htaccess lies in the root-directory.
1854 # If this .htaccess goes in a specific directory, the path to this
1855 # directory must be added to $ENV{'DOCUMENT_ROOT'}.
1857 # The CGIscriptor file contains all documentation as comments. These
1858 # comments can be removed to speed up loading (e.g., `egrep -v '^#'
1859 # CGIscriptor.pl` > leanScriptor.pl). A bare bones version of
1860 # CGIscriptor.pl, lacking documentation, most comments, access control,
1861 # example functions etc. (but still with the copyright notice and some
1862 # minimal documentation) can be obtained by calling CGIscriptor.pl on the
1863 # command line with the '-slim' command line argument, e.g.,
1865 # >CGIscriptor.pl -slim > slimCGIscriptor.pl
1867 # CGIscriptor.pl can be run from the command line with <path> and <query> as
1868 # arguments, as `CGIscriptor.pl <path> <query>`, inside a perl script
1869 # with 'do CGIscriptor.pl' after setting $ENV{PATH_INFO}
1870 # and $ENV{QUERY_STRING}, or CGIscriptor.pl can be loaded with 'require
1871 # "/real-path/CGIscriptor.pl"'. In the latter case, requests are processed
1872 # by 'Handle_Request();' (again after setting $ENV{PATH_INFO} and
1873 # $ENV{QUERY_STRING}).
1875 # Using the command line execution option, CGIscriptor.pl can be used as a
1876 # document (meta-)preprocessor. If the first argument is '-', STDIN will be read.
1877 # For example:
1879 # > cat MyDynamicDocument.html | CGIscriptor.pl - '[QueryString]' > MyStaticFile.html
1881 # This command line will produce a STATIC file with the DYNAMIC content of
1882 # MyDocument.html "interpolated".
1884 # This option would be very dangerous when available over the internet.
1885 # If someone could sneak a 'http://www.your.domain/-' URL past your
1886 # server, CGIscriptor could EXECUTE any POSTED contend.
1887 # Therefore, for security reasons, STDIN will NOT be read
1888 # if ANY of the HTTP server environment variables is set (e.g.,
1889 # SERVER_PORT, SERVER_PROTOCOL, SERVER_NAME, SERVER_SOFTWARE,
1890 # HTTP_USER_AGENT, REMOTE_ADDR).
1891 # This block on processing STDIN on HTTP requests can be lifted by setting
1892 # $BLOCK_STDIN_HTTP_REQUEST = 0;
1893 # In the security configuration. Butbe carefull when doing this.
1894 # It can be very dangerous.
1896 # Running demo's and more information can be found at
1897 # http://www.fon.hum.uva.nl/~rob/OSS/OSS.html
1899 # A pocket-size HTTP daemon, CGIservlet.pl, is available from my web site or
1900 # CPAN that can use CGIscriptor.pl as the base of a µWWW server and
1901 # demonstrates its use.
1904 # PROCESSING NON-FILESYSTEM DATA
1906 # Normally, HTTP (WWW) requests map onto file that can be accessed
1907 # using the perl open() function. That is, the web server runs on top of
1908 # some directory structure. However, we can envission (and put to good
1909 # use) other systems that do not use a normal file system. The whole CGI
1910 # was developed to make dynamic document generation possible.
1912 # A special case is where we want to have it both: A normal web server
1913 # with normal "file data", but not a normal files system. For instance,
1914 # we want or normal Web Site to run directly from a RAM hash table or
1915 # other database, instead of from disk. But we do NOT want to code the
1916 # whole site structure in CGI.
1918 # CGIscriptor can do this. If the web server fills an environment variable
1919 # $ENV{'CGI_FILE_CONTENT'} with the content of the "file", then the content
1920 # of this variable is processed instead of opening a file. If this environment
1921 # variable has the value '-', the content of another environment variable,
1922 # $ENV{'CGI_DATA_ACCESS_CODE'} is executed as:
1923 # eval("\@_ = ($file_path); do {$ENV{'CGI_DATA_ACCESS_CODE'}};")
1924 # and the result is processed as if it was the content of the requested
1925 # file.
1926 # (actually, the names of the environment variables are user configurable,
1927 # they are stored in the local variables $CGI_FILE_CONTENT and
1928 # $CGI_DATA_ACCESS_CODE)
1930 # When using this mechanism, the SRC attribute mechanism will only partially work.
1931 # Only the "recursive" calls to CGIscriptor (the ProcessFile() function)
1932 # will work, the automagical execution of SRC files won't. (In this case,
1933 # the SRC attribute won't work either for other scripting languages)
1936 # NON-UNIX PLATFORMS
1938 # CGIscriptor.pl was mainly developed and tested on UNIX. However, as I
1939 # coded part of the time on an Apple Macintosh under MacPerl, I made sure
1940 # CGIscriptor did run under MacPerl (with command line options). But only
1941 # as an independend script, not as part of a HTTP server. I have used it
1942 # under Apache in Windows XP.
1944 ENDOFHELPTEXT
1945 exit;
1947 ###############################################################################
1949 # SECURITY CONFIGURATION
1951 # Special configurations related to SECURITY
1952 # (i.e., optional, see also environment variables below)
1954 # LOGGING
1955 # Log Clients and the requested paths (Redundant when loging Queries)
1957 $ClientLog = "./Client.log"; # (uncomment for use)
1959 # Format: Localtime | REMOTE_USER REMOTE_IDENT REMOTE_HOST REMOTE_ADDRESS \
1960 # PATH_INFO CONTENT_LENGTH (actually, the real query+post length)
1962 # Log Clients and the queries, the CGIQUERYDECODE is required if you want
1963 # to log queries. If you log Queries, the loging of Clients is redundant
1964 # (note that queries can be quite long, so this might not be a good idea)
1966 #$QueryLog = "./Query.log"; # (uncomment for use)
1968 # ACCESS CONTROL
1969 # the Access files should contain Hostnames or IP addresses,
1970 # i.e. REMOTE_HOST or REMOTE_ADDR, each on a separate line
1971 # optionally followed by one ore more file patterns, e.g., "edu /DEMO".
1972 # Matching is done "domain first". For example ".edu" matches all
1973 # clients whose "name" ends in ".edu" or ".EDU". The file pattern
1974 # "/DEMO" matches all paths that contain the strings "/DEMO" or "/demo"
1975 # (both matchings are done case-insensitive).
1976 # The name special symbol "-" matches ALL clients who do not supply a
1977 # REMOTE_HOST name, "*" matches all clients.
1978 # Lines starting with '-e' are evaluated. A non-zero return value indicates
1979 # a match. You can use $REMOTE_HOST, $REMOTE_ADDR, and $PATH_INFO. These
1980 # lines are evaluated in the program's own name-space. So DO NOT assign to
1981 # variables.
1983 # Accept the following users (remove comment # and adapt filename)
1984 $CGI_Accept = -s "$YOUR_SCRIPTS/ACCEPT.lis" ? "$YOUR_SCRIPTS/ACCEPT.lis" : ''; # (uncomment for use)
1986 # Reject requests from the following users (remove comment # and
1987 # adapt filename, this is only of limited use)
1988 $CGI_Reject = -s "$YOUR_SCRIPTS/REJECT.lis" ? "$YOUR_SCRIPTS/REJECT.lis" : ''; # (uncomment for use)
1990 # Empty lines or comment lines starting with '#' are ignored in both
1991 # $CGI_Accept and $CGI_Reject.
1993 # Block STDIN (i.e., '-') requests when servicing an HTTP request
1994 # Comment this out if you realy want to use STDIN in an on-line web server
1995 $BLOCK_STDIN_HTTP_REQUEST = 1;
1998 # End of security configuration
2000 ##################################################<<<<<<<<<<End Remove
2002 # PARSING CGI VALUES FROM THE QUERY STRING (USER CONFIGURABLE)
2004 # The CGI parse commands. These commands extract the values of the
2005 # CGI variables from the URL encoded Query String.
2006 # If you want to use your own CGI decoders, you can call them here
2007 # instead, using your own PATH and commenting/uncommenting the
2008 # appropriate lines
2010 # CGI parse command for individual values
2011 # (if $List > 0, returns a list value, if $List < 0, a hash table, this is optional)
2012 sub YOUR_CGIPARSE # ($Name [, $List]) -> Decoded value
2014 my $Name = shift;
2015 my $List = shift || 0;
2016 # Use one of the following by uncommenting
2017 if(!$List) # Simple value
2019 return CGIscriptor::CGIparseValue($Name) ;
2021 elsif($List < 0) # Hash tables
2023 return CGIscriptor::CGIparseValueHash($Name); # Defined in CGIscriptor below
2025 else # Lists
2027 return CGIscriptor::CGIparseValueList($Name); # Defined in CGIscriptor below
2030 # return `/PATH/cgiparse -value $Name`; # Shell commands
2031 # require "/PATH/cgiparse.pl"; return cgivalue($Name); # Library
2033 # Complete queries
2034 sub YOUR_CGIQUERYDECODE
2036 # Use one of the following by uncommenting
2037 return CGIscriptor::CGIparseForm(); # Defined in CGIscriptor below
2038 # return `/PATH/cgiparse -form`; # Shell commands
2039 # require "/PATH/cgiparse.pl"; return cgiform(); # Library
2042 # End of configuration
2044 #######################################################################
2046 # Translating input files.
2047 # Allows general and global conversions of files using Regular Expressions
2048 # Translations are applied in the order of definition.
2050 # Define:
2051 # my $TranslationPaths = 'pattern'; # Pattern matching PATH_INFO
2053 # push(@TranslationTable, ['pattern', 'replacement']);
2054 # e.g. (for Ruby Rails):
2055 # push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2056 # push(@TranslationTable, ['%>', '</SCRIPT>']);
2058 # Runs:
2059 # my $currentRegExp;
2060 # foreach $currentRegExp (keys(%TranslationTable))
2062 # my $currentRegExp;
2063 # foreach $currentRegExp (@TranslationTable)
2065 # my ($pattern, $replacement) = @$currentRegExp;
2066 # $$text =~ s!$pattern!$replacement!msg;
2067 # };
2068 # };
2070 # Configuration section
2072 #######################################################################
2074 # The file paths on which to apply the translation
2075 my $TranslationPaths = ''; # NO files
2076 #$TranslationPaths = '.'; # ANY file
2077 # $TranslationPaths = '\.html'; # HTML files
2079 my @TranslationTable = ();
2080 # Some legacy code
2081 push(@TranslationTable, ['\<\s*CGI\s+([^\>])*\>', '\<SCRIPT TYPE=\"text/ssperl\"\>$1\<\/SCRIPT>']);
2082 # Ruby Rails?
2083 push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2084 push(@TranslationTable, ['%>', '</SCRIPT>']);
2086 sub performTranslation # (\$text)
2088 my $text = shift || return;
2089 if(@TranslationTable && $TranslationPaths && $ENV{'PATH_INFO'} =~ m!$TranslationPaths!)
2091 my $currentRegExp;
2092 foreach $currentRegExp (@TranslationTable)
2094 my ($pattern, $replacement) = @$currentRegExp;
2095 $$text =~ s!$pattern!$replacement!msg;
2100 #######################################################################
2102 # Seamless access to other (Scripting) Languages
2103 # TYPE='text/ss<interpreter>'
2105 # Configuration section
2107 #######################################################################
2109 # OTHER SCRIPTING LANGUAGES AT THE SERVER SIDE (MIME => OScommand)
2110 # Yes, it realy is this simple! (unbelievable, isn't it)
2111 # NOTE: Some interpreters require some filtering to obtain "clean" output
2113 %ScriptingLanguages = (
2114 "text/testperl" => 'perl', # Perl for testing
2115 "text/sspython" => 'python', # Python
2116 "text/ssruby" => 'ruby', # Ruby
2117 "text/sstcl" => 'tcl', # TCL
2118 "text/ssawk" => 'awk -f-', # Awk
2119 "text/sslisp" => # lisp (rep, GNU)
2120 'rep | tail +4 '."| egrep -v '> |^rep. |^nil\\\$'",
2121 "text/xlispstat" => # xlispstat
2122 'xlispstat | tail +7 ' ."| egrep -v '> \\\$|^NIL'",
2123 "text/ssprolog" => # Prolog (GNU)
2124 "gprolog | tail +4 | sed 's/^| ?- //'",
2125 "text/ssm4" => 'm4', # M4 macro's
2126 "text/sh" => 'sh', # Born shell
2127 "text/bash" => 'bash', # Born again shell
2128 "text/csh" => 'csh', # C shell
2129 "text/ksh" => 'ksh', # Korn shell
2130 "text/sspraat" => # Praat (sound/speech analysis)
2131 "praat - | sed 's/Praat > //g'",
2132 "text/ssr" => # R
2133 "R --vanilla --slave | sed 's/^[\[0-9\]*] //'",
2134 "text/ssrebol" => # REBOL
2135 "rebol --quiet|egrep -v '^[> ]* == '|sed 's/^\\s*\[> \]* //'",
2136 "text/postgresql" => 'psql 2>/dev/null',
2138 # Not real scripting, but the use of other applications
2139 "text/ssmailto" => "awk 'NF||F{F=1;print \\\$0;}'|mailto >/dev/null", # Send mail from server
2140 "text/ssdisplay" => 'cat', # Display, (interpolation)
2141 "text/sslogfile" => # Log to file, (interpolation)
2142 "awk 'NF||L {if(!L){L=tolower(\\\$1)~/^file:\\\$/ ? \\\$2 : \\\$1;}else{print \\\$0 >> L;};}'",
2144 "" => ""
2147 # To be able to access the CGI variables in your script, they
2148 # should be passed to the scripting language in a readable form
2149 # Here you can enter how they should be printed (the first %s
2150 # is replaced by the NAME of the CGI variable as it apears in the
2151 # META tag, the second by its VALUE).
2152 # For Perl this would be:
2153 # "text/testperl" => '$%s = "%s";',
2154 # which would be executed as
2155 # printf('$%s = "%s";', $CGI_NAME, $CGI_VALUE);
2157 # If the hash table value doesn't exist, nothing is done
2158 # (you have to parse the Environment variables yourself).
2159 # If it DOES exist but is empty (e.g., "text/sspraat" => '',)
2160 # Perl string interpolation of variables (i.e., $var, @array,
2161 # %hash) is performed. This means that $@%\ must be protected
2162 # with a \.
2164 %ScriptingCGIvariables = (
2165 "text/testperl" => "\$\%s = '\%s';", # Perl $VAR = 'value'; (for testing)
2166 "text/sspython" => "\%s = '\%s'", # Python VAR = 'value'
2167 "text/ssruby" => '@%s = "%s"', # Ruby @VAR = 'value'
2168 "text/sstcl" => 'set %s "%s"', # TCL set VAR "value"
2169 "text/ssawk" => '%s = "%s";', # Awk VAR = 'value';
2170 "text/sslisp" => '(setq %s "%s")', # Gnu lisp (rep) (setq VAR "value")
2171 "text/xlispstat" => '(setq %s "%s")', # xlispstat (setq VAR "value")
2172 "text/ssprolog" => '', # Gnu prolog (interpolated)
2173 "text/ssm4" => "define(`\%s', `\%s')", # M4 macro's define(`VAR', `value')
2174 "text/sh" => "\%s='\%s'", # Born shell VAR='value'
2175 "text/bash" => "\%s='\%s'", # Born again shell VAR='value'
2176 "text/csh" => "\$\%s='\%s';", # C shell $VAR = 'value';
2177 "text/ksh" => "\$\%s='\%s';", # Korn shell $VAR = 'value';
2179 "text/ssrebol" => '%s: copy "%s"', # REBOL VAR: copy "value"
2180 "text/sspraat" => '', # Praat (interpolation)
2181 "text/ssr" => '%s <- "%s";', # R VAR <- "value";
2182 "text/postgresql" => '', # PostgreSQL (interpolation)
2184 # Not real scripting, but the use of other applications
2185 "text/ssmailto" => '', # MAILTO, (interpolation)
2186 "text/ssdisplay" => '', # Display, (interpolation)
2187 "text/sslogfile" => '', # Log to file, (interpolation)
2189 "" => ""
2192 # If you want something added in front or at the back of each script
2193 # block as send to the interpreter add it here.
2194 # mime => "string", e.g., "text/sspython" => "python commands"
2195 %ScriptingPrefix = (
2196 "text/testperl" => "\# Prefix Code;", # Perl script testing
2197 "text/ssm4" => 'divert(0)', # M4 macro's (open STDOUT)
2199 "" => ""
2201 # If you want something added at the end of each script block
2202 %ScriptingPostfix = (
2203 "text/testperl" => "\# Postfix Code;", # Perl script testing
2204 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2206 "" => ""
2208 # If you need initialization code, directly after opening
2209 %ScriptingInitialization = (
2210 "text/testperl" => "\# Initialization Code;", # Perl script testing
2211 "text/ssawk" => 'BEGIN {', # Server Side awk scripts (VAR = "value")
2212 "text/sslisp" => '(prog1 nil ', # Lisp (rep)
2213 "text/xlispstat" => '(prog1 nil ', # xlispstat
2214 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2216 "" => ""
2218 # If you need cleanup code before closing
2219 %ScriptingCleanup = (
2220 "text/testperl" => "\# Cleanup Code;", # Perl script testing
2221 "text/sspraat" => 'Quit',
2222 "text/ssawk" => '};', # Server Side awk scripts (VAR = "value")
2223 "text/sslisp" => '(princ "\n" standard-output)).', # Closing print to rep
2224 "text/xlispstat" => '(print ""))', # Closing print to xlispstat
2225 "text/postgresql" => '\q', # quit psql
2226 "text/ssdisplay" => "", # close cat
2228 "" => ""
2231 # End of configuration for foreign scripting languages
2233 ###############################################################################
2235 # Initialization Code
2238 sub Initialize_Request
2240 ###############################################################################
2242 # ENVIRONMENT VARIABLES
2244 # Use environment variables to configure CGIscriptor on a temporary basis.
2245 # If you define any of the configurable variables as environment variables,
2246 # these are used instead of the "hard coded" values above.
2248 $SS_PUB = $ENV{'SS_PUB'} || $YOUR_HTML_FILES;
2249 $SS_SCRIPT = $ENV{'SS_SCRIPT'} || $YOUR_SCRIPTS;
2252 # Substitution strings, these are used internally to handle the
2253 # directory separator strings, e.g., '~/' -> 'SS_PUB:' (Mac)
2254 $HOME_SUB = $SS_PUB;
2255 $SCRIPT_SUB = $SS_SCRIPT;
2258 # Make sure all script are reliably loaded
2259 push(@INC, $SS_SCRIPT);
2262 # Add the directory separator to the "home" directories.
2263 # (This is required for ~/ and ./ substitution)
2264 $HOME_SUB .= '/' if $HOME_SUB;
2265 $SCRIPT_SUB .= '/' if $SCRIPT_SUB;
2267 $CGI_HOME = $ENV{'DOCUMENT_ROOT'};
2268 $ENV{'PATH_TRANSLATED'} =~ /$ENV{'PATH_INFO'}/is;
2269 $CGI_HOME = $` unless $ENV{'DOCUMENT_ROOT'}; # Get the DOCUMENT_ROOT directory
2270 $default_values{'CGI_HOME'} = $CGI_HOME;
2271 $ENV{'HOME'} = $CGI_HOME;
2272 # Set SS_PUB and SS_SCRIPT as Environment variables (make them available
2273 # to the scripts)
2274 $ENV{'SS_PUB'} = $SS_PUB unless $ENV{'SS_PUB'};
2275 $ENV{'SS_SCRIPT'} = $SS_SCRIPT unless $ENV{'SS_SCRIPT'};
2277 $FilePattern = $ENV{'FilePattern'} || $FilePattern;
2278 $MaximumQuerySize = $ENV{'MaximumQuerySize'} || $MaximumQuerySize;
2279 $ClientLog = $ENV{'ClientLog'} || $ClientLog;
2280 $QueryLog = $ENV{'QueryLog'} || $QueryLog;
2281 $CGI_Accept = $ENV{'CGI_Accept'} || $CGI_Accept;
2282 $CGI_Reject = $ENV{'CGI_Reject'} || $CGI_Reject;
2284 # Parse file names
2285 $CGI_Accept =~ s@^\~/@$HOME_SUB@g if $CGI_Accept;
2286 $CGI_Reject =~ s@^\~/@$HOME_SUB@g if $CGI_Reject;
2287 $ClientLog =~ s@^\~/@$HOME_SUB@g if $ClientLog;
2288 $QueryLog =~ s@^\~/@$HOME_SUB@g if $QueryLog;
2290 $CGI_Accept =~ s@^\./@$SCRIPT_SUB@g if $CGI_Accept;
2291 $CGI_Reject =~ s@^\./@$SCRIPT_SUB@g if $CGI_Reject;
2292 $ClientLog =~ s@^\./@$SCRIPT_SUB@g if $ClientLog;
2293 $QueryLog =~ s@^\./@$SCRIPT_SUB@g if $QueryLog;
2295 @CGIscriptorResults = (); # A stack of results
2297 # end of Environment variables
2299 #############################################################################
2301 # Define and Store "standard" values
2303 # BEFORE doing ANYTHING check the size of Query String
2304 length($ENV{'QUERY_STRING'}) <= $MaximumQuerySize || dieHandler(2, "QUERY TOO LONG\n");
2306 # The Translated Query String and the Actual length of the (decoded)
2307 # Query String
2308 if($ENV{'QUERY_STRING'})
2310 # If this can contain '`"-quotes, be carefull to use it QUOTED
2311 $default_values{CGI_Decoded_QS} = YOUR_CGIQUERYDECODE();
2312 $default_values{CGI_Content_Length} = length($default_values{CGI_Decoded_QS});
2315 # Get the current Date and time and store them as default variables
2317 # Get Local Time
2318 $LocalTime = localtime;
2320 # CGI_Year CGI_Month CGI_Day CGI_WeekDay CGI_Time
2321 # CGI_Hour CGI_Minutes CGI_Seconds
2323 $default_values{CGI_Date} = $LocalTime;
2324 ($default_values{CGI_WeekDay},
2325 $default_values{CGI_Month},
2326 $default_values{CGI_Day},
2327 $default_values{CGI_Time},
2328 $default_values{CGI_Year}) = split(' ', $LocalTime);
2329 ($default_values{CGI_Hour},
2330 $default_values{CGI_Minutes},
2331 $default_values{CGI_Seconds}) = split(':', $default_values{CGI_Time});
2333 # GMT:
2334 # CGI_GMTYear CGI_GMTMonth CGI_GMTDay CGI_GMTWeekDay CGI_GMTYearDay
2335 # CGI_GMTHour CGI_GMTMinutes CGI_GMTSeconds CGI_GMTisdst
2337 ($default_values{CGI_GMTSeconds},
2338 $default_values{CGI_GMTMinutes},
2339 $default_values{CGI_GMTHour},
2340 $default_values{CGI_GMTDay},
2341 $default_values{CGI_GMTMonth},
2342 $default_values{CGI_GMTYear},
2343 $default_values{CGI_GMTWeekDay},
2344 $default_values{CGI_GMTYearDay},
2345 $default_values{CGI_GMTisdst}) = gmtime;
2349 # End of Initialize Request
2351 ###################################################################
2353 # SECURITY: ACCESS CONTROL
2355 # Check the credentials of each client (use pattern matching, domain first).
2356 # This subroutine will kill-off (die) the current process whenever access
2357 # is denied.
2359 sub Access_Control
2361 # >>>>>>>>>>Start Remove
2363 # ACCEPTED CLIENTS
2365 # Only accept clients which are authorized, reject all unnamed clients
2366 # if REMOTE_HOST is given.
2367 # If file patterns are given, check whether the user is authorized for
2368 # THIS file.
2369 if($CGI_Accept)
2371 # Use local variables, REMOTE_HOST becomes '-' if undefined
2372 my $REMOTE_HOST = $ENV{REMOTE_HOST} || '-';
2373 my $REMOTE_ADDR = $ENV{REMOTE_ADDR};
2374 my $PATH_INFO = $ENV{'PATH_INFO'};
2376 open(CGI_Accept, "<$CGI_Accept") || dieHandler(3, "$CGI_Accept: $!\n");
2377 $NoAccess = 1;
2378 while(<CGI_Accept>)
2380 next unless /\S/; # Skip empty lines
2381 next if /^\s*\#/; # Skip comments
2383 # Full expressions
2384 if(/^\s*-e\s/is)
2386 my $Accept = $'; # Get the expression
2387 $NoAccess &&= eval($Accept); # evaluate the expresion
2389 else
2391 my ($Accept, @FilePatternList) = split;
2392 if($Accept eq '*' # Always match
2393 ||$REMOTE_HOST =~ /\Q$Accept\E$/is # REMOTE_HOST matches
2394 || (
2395 $Accept =~ /^[0-9\.]+$/
2396 && $REMOTE_ADDR =~ /^\Q$Accept\E/ # IP address matches
2400 if($FilePatternList[0])
2402 foreach $Pattern (@FilePatternList)
2404 # Check whether this patterns is accepted
2405 $NoAccess &&= ($PATH_INFO !~ m@\Q$Pattern\E@is);
2408 else
2410 $NoAccess = 0; # No file patterns -> Accepted
2414 # Blocked
2415 last unless $NoAccess;
2417 close(CGI_Accept);
2418 if($NoAccess){ dieHandler(4, "No Access: $PATH_INFO\n");};
2422 # REJECTED CLIENTS
2424 # Reject named clients, accept all unnamed clients
2425 if($CGI_Reject)
2427 # Use local variables, REMOTE_HOST becomes '-' if undefined
2428 my $REMOTE_HOST = $ENV{'REMOTE_HOST'} || '-';
2429 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
2430 my $PATH_INFO = $ENV{'PATH_INFO'};
2432 open(CGI_Reject, "<$CGI_Reject") || dieHandler(5, "$CGI_Reject: $!\n");
2433 $NoAccess = 0;
2434 while(<CGI_Reject>)
2436 next unless /\S/; # Skip empty lines
2437 next if /^\s*\#/; # Skip comments
2439 # Full expressions
2440 if(/^-e\s/is)
2442 my $Reject = $'; # Get the expression
2443 $NoAccess ||= eval($Reject); # evaluate the expresion
2445 else
2447 my ($Reject, @FilePatternList) = split;
2448 if($Reject eq '*' # Always match
2449 ||$REMOTE_HOST =~ /\Q$Reject\E$/is # REMOTE_HOST matches
2450 ||($Reject =~ /^[0-9\.]+$/
2451 && $REMOTE_ADDR =~ /^\Q$Reject\E/is # IP address matches
2455 if($FilePatternList[0])
2457 foreach $Pattern (@FilePatternList)
2459 $NoAccess ||= ($PATH_INFO =~ m@\Q$Pattern\E@is);
2462 else
2464 $NoAccess = 1; # No file patterns -> Rejected
2468 last if $NoAccess;
2470 close(CGI_Reject);
2471 if($NoAccess){ dieHandler(6, "Request rejected: $PATH_INFO\n");};
2474 ##########################################################<<<<<<<<<<End Remove
2477 # Get the filename
2479 # Does the filename contain any illegal characters (e.g., |, >, or <)
2480 dieHandler(7, "Illegal request: $ENV{'PATH_INFO'}\n") if $ENV{'PATH_INFO'} =~ /[^$FileAllowedChars]/;
2481 # Does the pathname contain an illegal (blocked) "directory"
2482 dieHandler(8, "Illegal request: $ENV{'PATH_INFO'}\n") if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@; # Access is blocked
2483 # Does the pathname contain a direct referencer to BinaryMapFile
2484 dieHandler(9, "Illegal request: $ENV{'PATH_INFO'}\n") if $BinaryMapFile && $ENV{'PATH_INFO'} =~ m@\Q$BinaryMapFile\E@; # Access is blocked
2486 # SECURITY: Is PATH_INFO allowed?
2487 if($FilePattern && $ENV{'PATH_INFO'} && $ENV{'PATH_INFO'} ne '-' &&
2488 ($ENV{'PATH_INFO'} !~ m@($FilePattern)$@is))
2490 # Unsupported file types can be processed by a special raw-file
2491 if($BinaryMapFile)
2493 $ENV{'CGI_BINARY_FILE'} = $ENV{'PATH_INFO'};
2494 $ENV{'PATH_INFO'} = $BinaryMapFile;
2496 else
2498 dieHandler(10, "Illegal file\n");
2504 # End of Security Access Control
2507 ############################################################################
2509 # Get the POST part of the query and add it to the QUERY_STRING.
2512 sub Get_POST_part_of_query
2515 # If POST, Read data from stdin to QUERY_STRING
2516 if($ENV{'REQUEST_METHOD'} =~ /POST/is)
2518 # SECURITY: Check size of Query String
2519 $ENV{'CONTENT_LENGTH'} <= $MaximumQuerySize || dieHandler(11, "Query too long: $ENV{'CONTENT_LENGTH'}\n"); # Query too long
2520 my $QueryRead = 0;
2521 my $SystemRead = $ENV{'CONTENT_LENGTH'};
2522 $ENV{'QUERY_STRING'} .= '&' if length($ENV{'QUERY_STRING'}) > 0;
2523 while($SystemRead > 0)
2525 $QueryRead = sysread(STDIN, $Post, $SystemRead); # Limit length
2526 $ENV{'QUERY_STRING'} .= $Post;
2527 $SystemRead -= $QueryRead;
2529 # Update decoded Query String
2530 $default_values{CGI_Decoded_QS} = YOUR_CGIQUERYDECODE();
2531 $default_values{CGI_Content_Length} =
2532 length($default_values{CGI_Decoded_QS});
2536 # End of getting POST part of query
2539 ############################################################################
2541 # Start (HTML) output and logging
2542 # (if there are irregularities, it can kill the current process)
2545 sub Initialize_output
2547 # Construct the REAL file path (except for STDIN on the command line)
2548 my $file_path = $ENV{'PATH_INFO'} ne '-' ? $SS_PUB . $ENV{'PATH_INFO'} : '-';
2549 $file_path =~ s/\?.*$//; # Remove query
2550 # This is only necessary if your server does not catch ../ directives
2551 $file_path !~ m@\.\./@ || dieHandler(12, "Illegal ../ Construct\n"); # SECURITY: Do not allow ../ constructs
2553 # Block STDIN use (-) if CGIscriptor is servicing a HTTP request
2554 if($file_path eq '-')
2556 dieHandler(13, "STDIN request in On Line system\n") if $BLOCK_STDIN_HTTP_REQUEST
2557 && ($ENV{'SERVER_SOFTWARE'}
2558 || $ENV{'SERVER_NAME'}
2559 || $ENV{'GATEWAY_INTERFACE'}
2560 || $ENV{'SERVER_PROTOCOL'}
2561 || $ENV{'SERVER_PORT'}
2562 || $ENV{'REMOTE_ADDR'}
2563 || $ENV{'HTTP_USER_AGENT'});
2568 if($ClientLog)
2570 open(ClientLog, ">>$ClientLog");
2571 print ClientLog "$LocalTime | ",
2572 ($ENV{REMOTE_USER} || "-"), " ",
2573 ($ENV{REMOTE_IDENT} || "-"), " ",
2574 ($ENV{REMOTE_HOST} || "-"), " ",
2575 $ENV{REMOTE_ADDR}, " ",
2576 $ENV{PATH_INFO}, " ",
2577 $ENV{'CGI_BINARY_FILE'}, " ",
2578 ($default_values{CGI_Content_Length} || "-"),
2579 "\n";
2580 close(ClientLog);
2582 if($QueryLog)
2584 open(QueryLog, ">>$QueryLog");
2585 print QueryLog "$LocalTime\n",
2586 ($ENV{REMOTE_USER} || "-"), " ",
2587 ($ENV{REMOTE_IDENT} || "-"), " ",
2588 ($ENV{REMOTE_HOST} || "-"), " ",
2589 $ENV{REMOTE_ADDR}, ": ",
2590 $ENV{PATH_INFO}, " ",
2591 $ENV{'CGI_BINARY_FILE'}, "\n";
2593 # Write Query to Log file
2594 print QueryLog $default_values{CGI_Decoded_QS}, "\n\n";
2595 close(QueryLog);
2598 # Return the file path
2599 return $file_path;
2602 # End of Initialize output
2605 ############################################################################
2607 # Handle login access
2609 # Access is based on a valid session ticket.
2610 # Session tickets should be dependend on user name
2611 # and IP address. The patterns of URLs for which a
2612 # session ticket is needed and the login URL are stored in
2613 # %LoginRequiredPatterns as:
2614 # 'RegEx pattern' -> 'SessionPath\tPasswordPath\tLogin URL'
2617 sub Log_In_Access # () -> Access Allowed
2619 # No patterns, no login
2620 return 1 unless %LoginRequiredPatterns;
2622 # Get and initialize values
2623 my ($SessionPath, $PasswordsPath, $Login, $valid_duration) = ("", "", "", 0);
2624 my $PATH_INFO = $ENV{'PATH_INFO'};
2625 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
2627 CGIexecute::defineCGIvariable('SESSIONTICKET', "");
2628 my $SESSIONTICKET = ${"CGIexecute::SESSIONTICKET"};
2630 foreach my $pattern (keys(%LoginRequiredPatterns))
2632 if($PATH_INFO =~ m#$pattern#)
2634 # Fall through a sieve of requirements
2635 ($SessionPath, $PasswordsPath, $Login, $valid_duration) = split(/\t/, $LoginRequiredPatterns{$pattern});
2636 # Is there a session ticket of this name?
2637 goto Login unless $SESSIONTICKET && (-s "$SessionPath/$SESSIONTICKET");
2638 my $ticket_valid = check_ticket_validity ("SESSION", "$SessionPath/$SESSIONTICKET", $REMOTE_ADDR, $PATH_INFO);
2639 goto Login unless $ticket_valid;
2641 return 1;
2644 return 1;
2646 Login:
2648 return 0;
2651 sub check_ticket_validity # ($type, $ticket, $address, $path)
2653 my $type = shift || "SESSION";
2654 my $ticket = shift || "";
2655 my $path = shift || "";
2657 # Is there a session ticket of this name?
2658 return 0 unless -s "$ticket";
2660 # Get SessionTicket file stats
2661 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)
2662 = stat("$ticket");
2664 # There is a session ticket, is it linked to this IP address?
2665 open(SESSION, "<$ticket") || die "$ticket: $!\n";
2666 my @sessionlines = <SESSION>;
2667 close(SESSION);
2669 # Is this the right type of ticket
2670 return unless grep(/Type:\s+$type\s*$/isg, @sessionlines);
2672 # Does the IP address match?
2673 my $IPmatches = 0;
2674 my @IPlines = grep(/^\s*IPaddress:\s+/isg,@sessionlines);
2675 foreach my $IPline (@IPlines)
2677 chomp($IPline);
2678 if($IPline =~ /^\s*IPaddress:\s+(.*)$/)
2680 $IPpattern = $1;
2681 $IPpattern =~ s/\./\\./g;
2682 ++$IPmatches if $address =~ m#^$IPpattern$#ig;
2685 return 0 unless !@IPlines || $IPmatches;
2687 # Is the path allowed
2688 my $Pathmatches = 0;
2689 my @AllowedLines = grep(/^\s*AllowedPaths:\s+/,@sessionlines);
2690 foreach my $Allowedline (@AllowedLines)
2692 chomp($Allowedline);
2693 if($Allowedline =~ /^\s*AllowedPaths:\s+(.*)$/)
2695 $Pathpattern = $1;
2696 ++$Pathmatches if $path =~ m#$Pathpattern#ig;
2699 return 0 unless !@AllowedLines || $Pathmatches;
2701 # Is the ticket expired?
2702 my $Expired = 0;
2703 my @ExpireLines = grep(/^\s*Expires:\s+/,@sessionlines);
2704 foreach my $Expireline (@ExpireLines)
2706 chomp($Expireline);
2707 if($Expireline =~ /^\s*Expires:\s+(.*)\s*$/)
2709 $ExpireTime = $1;
2711 if($ExpireTime =~ /\s*d(ays)?\s*$/)
2713 $ExpireTime = 24*3600*$`;
2715 elsif($ExpireTime =~ /\s*m(inutes)?\s*$/)
2717 $ExpireTime = 60*$`;
2719 elsif($ExpireTime =~ /\s*h(ours)?\s*$/)
2721 $ExpireTime = 3600*$`;
2723 elsif($ExpireTime =~ /\s*s(econds)?\s*$/)
2725 $ExpireTime = $`;
2728 my $ActualExpireTime = $ExpireTime + $ctime;
2729 my $CurrentTime = time();
2730 ++$Expired if($CurrentTime > $ActualExpireTime);
2733 return 0 if @ExpireLines && $Expired;
2735 return 1;
2739 # Handle login access
2742 ############################################################################
2744 # Handle foreign interpreters (i.e., scripting languages)
2746 # Insert perl code to execute scripts in foreign scripting languages.
2747 # Actually, the scripts inside the <SCRIPT></SCRIPT> blocks are piped
2748 # into an interpreter.
2749 # The code presented here is fairly confusing because it
2750 # actually writes perl code code to the output.
2752 # A table with the file handles
2753 %SCRIPTINGINPUT = ();
2755 # A function to clean up Client delivered CGI parameter values
2756 # (i.e., quote all odd characters)
2757 %SHRUBcharacterTR =
2759 "\'" => '&#39;',
2760 "\`" => '&#96;',
2761 "\"" => '&quot;',
2762 '&' => '&amper;',
2763 "\\" => '&#92;'
2766 sub shrubCGIparameter # ($String) -> Cleaned string
2768 my $String = shift || "";
2770 # Change all quotes [`'"] into HTML character entities
2771 my ($Char, $Transcript) = ('&', $SHRUBcharacterTR{'&'});
2773 # Protect &
2774 $String =~ s/\Q$Char\E/$Transcript/isg if $Transcript;
2776 while( ($Char, $Transcript) = each %SHRUBcharacterTR)
2778 next if $Char eq '&';
2779 $String =~ s/\Q$Char\E/$Transcript/isg;
2782 # Replace newlines
2783 $String =~ s/[\n]/\\n/g;
2784 # Replace control characters with their backslashed octal ordinal numbers
2785 $String =~ s/([^\S \t])/(sprintf("\\0%o", ord($1)))/eisg; #
2786 $String =~ s/([\x00-\x08\x0A-\x1F])/(sprintf("\\0%o", ord($1)))/eisg; #
2788 return $String;
2792 # The initial open statements: Open a pipe to the foreign script interpreter
2793 sub OpenForeignScript # ($ContentType) -> $DirectivePrefix
2795 my $ContentType = lc(shift) || return "";
2796 my $NewDirective = "";
2798 return $NewDirective if($SCRIPTINGINPUT{$ContentType});
2800 # Construct a unique file handle name
2801 $SCRIPTINGFILEHANDLE = uc($ContentType);
2802 $SCRIPTINGFILEHANDLE =~ s/\W/\_/isg;
2803 $SCRIPTINGINPUT{$ContentType} = $SCRIPTINGFILEHANDLE
2804 unless $SCRIPTINGINPUT{$ContentType};
2806 # Create the relevant script: Open the pipe to the interpreter
2807 $NewDirective .= <<"BLOCKCGISCRIPTOROPEN";
2808 # Open interpreter for '$ContentType'
2809 # Open pipe to interpreter (if it isn't open already)
2810 open($SCRIPTINGINPUT{$ContentType}, "|$ScriptingLanguages{$ContentType}") || main::dieHandler(14, "$ContentType: \$!\\n");
2811 BLOCKCGISCRIPTOROPEN
2813 # Insert Initialization code and CGI variables
2814 $NewDirective .= InitializeForeignScript($ContentType);
2816 # Ready
2817 return $NewDirective;
2821 # The final closing code to stop the interpreter
2822 sub CloseForeignScript # ($ContentType) -> $DirectivePrefix
2824 my $ContentType = lc(shift) || return "";
2825 my $NewDirective = "";
2827 # Do nothing unless the pipe realy IS open
2828 return "" unless $SCRIPTINGINPUT{$ContentType};
2830 # Initial comment
2831 $NewDirective .= "\# Close interpreter for '$ContentType'\n";
2834 # Write the Postfix code
2835 $NewDirective .= CleanupForeignScript($ContentType);
2837 # Create the relevant script: Close the pipe to the interpreter
2838 $NewDirective .= <<"BLOCKCGISCRIPTORCLOSE";
2839 close($SCRIPTINGINPUT{$ContentType}) || main::dieHandler(15, \"$ContentType: \$!\\n\");
2840 select(STDOUT); \$|=1;
2842 BLOCKCGISCRIPTORCLOSE
2844 # Remove the file handler of the foreign script
2845 delete($SCRIPTINGINPUT{$ContentType});
2847 return $NewDirective;
2851 # The initialization code for the foreign script interpreter
2852 sub InitializeForeignScript # ($ContentType) -> $DirectivePrefix
2854 my $ContentType = lc(shift) || return "";
2855 my $NewDirective = "";
2857 # Add initialization code
2858 if($ScriptingInitialization{$ContentType})
2860 $NewDirective .= <<"BLOCKCGISCRIPTORINIT";
2861 # Initialization Code for '$ContentType'
2862 # Select relevant output filehandle
2863 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
2865 # The Initialization code (if any)
2866 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}INITIALIZATIONCODE';
2867 $ScriptingInitialization{$ContentType}
2868 ${ContentType}INITIALIZATIONCODE
2870 BLOCKCGISCRIPTORINIT
2873 # Add all CGI variables defined
2874 if(exists($ScriptingCGIvariables{$ContentType}))
2876 # Start writing variable definitions to the Interpreter
2877 if($ScriptingCGIvariables{$ContentType})
2879 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEF";
2880 # CGI variables (from the %default_values table)
2881 print $SCRIPTINGINPUT{$ContentType} << '${ContentType}CGIVARIABLES';
2882 BLOCKCGISCRIPTORVARDEF
2885 my ($N, $V);
2886 foreach $N (keys(%default_values))
2888 # Determine whether the parameter has been defined
2889 # (the eval is a workaround to get at the variable value)
2890 next unless eval("defined(\$CGIexecute::$N)");
2892 # Get the value from the EXECUTION environment
2893 $V = eval("\$CGIexecute::$N");
2894 # protect control characters (i.e., convert them to \0.. form)
2895 $V = shrubCGIparameter($V);
2897 # Protect interpolated variables
2898 eval("\$CGIexecute::$N = '$V';") unless $ScriptingCGIvariables{$ContentType};
2900 # Print the actual declaration for this scripting language
2901 if($ScriptingCGIvariables{$ContentType})
2903 $NewDirective .= sprintf($ScriptingCGIvariables{$ContentType}, $N, $V);
2904 $NewDirective .= "\n";
2908 # Stop writing variable definitions to the Interpreter
2909 if($ScriptingCGIvariables{$ContentType})
2911 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEFEND";
2912 ${ContentType}CGIVARIABLES
2913 BLOCKCGISCRIPTORVARDEFEND
2918 $NewDirective .= << "BLOCKCGISCRIPTOREND";
2920 # Select STDOUT filehandle
2921 select(STDOUT); \$|=1;
2923 BLOCKCGISCRIPTOREND
2925 return $NewDirective;
2929 # The cleanup code for the foreign script interpreter
2930 sub CleanupForeignScript # ($ContentType) -> $DirectivePrefix
2932 my $ContentType = lc(shift) || return "";
2933 my $NewDirective = "";
2935 # Return if not needed
2936 return $NewDirective unless $ScriptingCleanup{$ContentType};
2938 # Create the relevant script: Open the pipe to the interpreter
2939 $NewDirective .= <<"BLOCKCGISCRIPTORSTOP";
2940 # Cleanup Code for '$ContentType'
2941 # Select relevant output filehandle
2942 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
2943 # Print Cleanup code to foreign script
2944 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}SCRIPTSTOP';
2945 $ScriptingCleanup{$ContentType}
2946 ${ContentType}SCRIPTSTOP
2948 # Select STDOUT filehandle
2949 select(STDOUT); \$|=1;
2950 BLOCKCGISCRIPTORSTOP
2952 return $NewDirective;
2956 # The prefix code for each <script></script> block
2957 sub PrefixForeignScript # ($ContentType) -> $DirectivePrefix
2959 my $ContentType = lc(shift) || return "";
2960 my $NewDirective = "";
2962 # Return if not needed
2963 return $NewDirective unless $ScriptingPrefix{$ContentType};
2965 my $Quote = "\'";
2966 # If the CGIvariables parameter is defined, but empty, interpolate
2967 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
2968 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
2969 !$ScriptingCGIvariables{$ContentType};
2971 # Add initialization code
2972 $NewDirective .= <<"BLOCKCGISCRIPTORPREFIX";
2973 # Prefix Code for '$ContentType'
2974 # Select relevant output filehandle
2975 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
2977 # The block Prefix code (if any)
2978 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}PREFIXCODE$Quote;
2979 $ScriptingPrefix{$ContentType}
2980 ${ContentType}PREFIXCODE
2981 # Select STDOUT filehandle
2982 select(STDOUT); \$|=1;
2983 BLOCKCGISCRIPTORPREFIX
2985 return $NewDirective;
2989 # The postfix code for each <script></script> block
2990 sub PostfixForeignScript # ($ContentType) -> $DirectivePrefix
2992 my $ContentType = lc(shift) || return "";
2993 my $NewDirective = "";
2995 # Return if not needed
2996 return $NewDirective unless $ScriptingPostfix{$ContentType};
2998 my $Quote = "\'";
2999 # If the CGIvariables parameter is defined, but empty, interpolate
3000 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
3001 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
3002 !$ScriptingCGIvariables{$ContentType};
3004 # Create the relevant script: Open the pipe to the interpreter
3005 $NewDirective .= <<"BLOCKCGISCRIPTORPOSTFIX";
3006 # Postfix Code for '$ContentType'
3007 # Select filehandle to interpreter
3008 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
3009 # Print postfix code to foreign script
3010 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SCRIPTPOSTFIX$Quote;
3011 $ScriptingPostfix{$ContentType}
3012 ${ContentType}SCRIPTPOSTFIX
3013 # Select STDOUT filehandle
3014 select(STDOUT); \$|=1;
3015 BLOCKCGISCRIPTORPOSTFIX
3017 return $NewDirective;
3020 sub InsertForeignScript # ($ContentType, $directive, @SRCfile) -> $NewDirective
3022 my $ContentType = lc(shift) || return "";
3023 my $directive = shift || return "";
3024 my @SRCfile = @_;
3025 my $NewDirective = "";
3027 my $Quote = "\'";
3028 # If the CGIvariables parameter is defined, but empty, interpolate
3029 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
3030 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
3031 !$ScriptingCGIvariables{$ContentType};
3033 # Create the relevant script
3034 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
3035 # Insert Code for '$ContentType'
3036 # Select filehandle to interpreter
3037 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
3038 BLOCKCGISCRIPTORINSERT
3040 # Use SRC feature files
3041 my $ThisSRCfile;
3042 while($ThisSRCfile = shift(@_))
3044 # Handle blocks
3045 if($ThisSRCfile =~ /^\s*\{\s*/)
3047 my $Block = $';
3048 $Block = $` if $Block =~ /\s*\}\s*$/;
3049 $NewDirective .= <<"BLOCKCGISCRIPTORSRCBLOCK";
3050 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SRCBLOCKCODE$Quote;
3051 $Block
3052 ${ContentType}SRCBLOCKCODE
3053 BLOCKCGISCRIPTORSRCBLOCK
3055 next;
3058 # Handle files
3059 $NewDirective .= <<"BLOCKCGISCRIPTORSRCFILES";
3060 # Read $ThisSRCfile
3061 open(SCRIPTINGSOURCE, "<$ThisSRCfile") || main::dieHandler(16, "$ThisSRCfILE: \$!");
3062 while(<SCRIPTINGSOURCE>)
3064 print $SCRIPTINGINPUT{$ContentType} \$_;
3066 close(SCRIPTINGSOURCE);
3068 BLOCKCGISCRIPTORSRCFILES
3072 # Add the directive
3073 if($directive)
3075 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
3076 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}DIRECTIVECODE$Quote;
3077 $directive
3078 ${ContentType}DIRECTIVECODE
3079 BLOCKCGISCRIPTORINSERT
3083 $NewDirective .= <<"BLOCKCGISCRIPTORSELECT";
3084 # Select STDOUT filehandle
3085 select(STDOUT); \$|=1;
3086 BLOCKCGISCRIPTORSELECT
3088 # Ready
3089 return $NewDirective;
3092 sub CloseAllForeignScripts # Call CloseForeignScript on all open scripts
3094 my $ContentType;
3095 foreach $ContentType (keys(%SCRIPTINGINPUT))
3097 my $directive = CloseForeignScript($ContentType);
3098 print STDERR "\nDirective $CGI_Date: ", $directive;
3099 CGIexecute->evaluate($directive);
3104 # End of handling foreign (external) scripting languages.
3106 ############################################################################
3108 # A subroutine to handle "nested" quotes, it cuts off the leading
3109 # item or quoted substring
3110 # E.g.,
3111 # ' A_word and more words' -> @('A_word', ' and more words')
3112 # '"quoted string" The rest' -> @('quoted string', ' The rest')
3113 # (this is needed for parsing the <TAGS> and their attributes)
3114 my $SupportedQuotes = "\'\"\`\(\{\[";
3115 my %QuotePairs = ('('=>')','['=>']','{'=>'}'); # Brackets
3116 sub ExtractQuotedItem # ($String) -> @($QuotedString, $RestOfString)
3118 my @Result = ();
3119 my $String = shift || return @Result;
3121 if($String =~ /^\s*([\w\/\-\.]+)/is)
3123 push(@Result, $1, $');
3125 elsif($String =~ /^\s*(\\?)([\Q$SupportedQuotes\E])/is)
3127 my $BackSlash = $1 || "";
3128 my $OpenQuote = $2;
3129 my $CloseQuote = $OpenQuote;
3130 $CloseQuote = $QuotePairs{$OpenQuote} if $QuotePairs{$OpenQuote};
3132 if($BackSlash)
3134 $String =~ /^\s*\\\Q$OpenQuote\E/i;
3135 my $Onset = $';
3136 $Onset =~ /\\\Q$CloseQuote\E/i;
3137 my $Rest = $';
3138 my $Item = $`;
3139 push(@Result, $Item, $Rest);
3142 else
3144 $String =~ /^\s*\Q$OpenQuote\E([^\Q$CloseQuote\E]*)\Q$CloseQuote\E/i;
3145 push(@Result, $1, $');
3148 else
3150 push(@Result, "", $String);
3152 return @Result;
3155 # Now, start with the real work
3157 # Control the output of the Content-type: text/html\n\n message
3158 my $SupressContentType = 0;
3160 # Process a file
3161 sub ProcessFile # ($file_path)
3163 my $file_path = shift || return 0;
3166 # Generate a unique file handle (for recursions)
3167 my @SRClist = ();
3168 my $FileHandle = "file";
3169 my $n = 0;
3170 while(!eof($FileHandle.$n)) {++$n;};
3171 $FileHandle .= $n;
3173 # Start HTML output
3174 # Use the default Content-type if this is NOT a raw file
3175 unless(($RawFilePattern && $ENV{'PATH_INFO'} =~ m@($RawFilePattern)$@i)
3176 || $SupressContentType)
3178 $ENV{'PATH_INFO'} =~ m@($FilePattern)$@i;
3179 my $ContentType = $ContentTypeTable{$1};
3180 print "Content-type: $ContentType\n";
3181 print "\n";
3182 $SupressContentType = 1; # Content type has been printed
3186 # Get access to the actual data. This can be from RAM (by way of an
3187 # environment variable) or by opening a file.
3189 # Handle the use of RAM images (file-data is stored in the
3190 # $CGI_FILE_CONTENTS environment variable)
3191 # Note that this environment variable will be cleared, i.e., it is strictly for
3192 # single-use only!
3193 if($ENV{$CGI_FILE_CONTENTS})
3195 # File has been read already
3196 $_ = $ENV{$CGI_FILE_CONTENTS};
3197 # Sorry, you have to do the reading yourself (dynamic document creation?)
3198 # NOTE: you must read the whole document at once
3199 if($_ eq '-')
3201 $_ = eval("\@_=('$file_path'); do{$ENV{$CGI_DATA_ACCESS_CODE}}");
3203 else # Clear environment variable
3205 $ENV{$CGI_FILE_CONTENTS} = '-';
3208 # Open Only PLAIN TEXT files (or STDIN) and NO executable files (i.e., scripts).
3209 # THIS IS A SECURITY FEATURE!
3210 elsif($file_path eq '-' || (-e "$file_path" && -r _ && -T _ && -f _ && ! (-x _ || -X _) ))
3212 open($FileHandle, $file_path) || dieHandler(17, "<h2>File not found</h2>\n");
3213 push(@OpenFiles, $file_path);
3214 $_ = <$FileHandle>; # Read first line
3216 else
3218 print "<h2>File not found</h2>\n";
3219 dieHandler(18, "$file_path\n");
3222 $| = 1; # Flush output buffers
3224 # Initialize variables
3225 my $METAarguments = ""; # The CGI arguments from the latest META tag
3226 my @METAvalues = (); # The ''-quoted CGI values from the latest META tag
3227 my $ClosedTag = 0; # <TAG> </TAG> versus <TAG/>
3230 # Send document to output
3231 # Process the requested document.
3232 # Do a loop BEFORE reading input again (this catches the RAM/Database
3233 # type of documents).
3234 do {
3237 # Handle translations if needed
3239 performTranslation(\$_) if $TranslationPaths;
3241 # Catch <SCRIPT LANGUAGE="PERL" TYPE="text/ssperl" > directives in $_
3242 # There can be more than 1 <SCRIPT> or META tags on a line
3243 while(/\<\s*(SCRIPT|META|DIV|INS)\s/is)
3245 my $directive = "";
3246 # Store rest of line
3247 my $Before = $`;
3248 my $ScriptTag = $&;
3249 my $After = $';
3250 my $TagType = uc($1);
3251 # The before part can be send to the output
3252 print $Before;
3254 # Read complete Tag from after and/or file
3255 until($After =~ /([^\\])\>/)
3257 $After .= <$FileHandle>;
3258 performTranslation(\$After) if $TranslationPaths;
3261 if($After =~ /([^\\])\>/)
3263 $ScriptTag .= $`.$&; # Keep the Script Tag intact
3264 $After = $';
3266 else
3268 dieHandler(19, "Closing > not found\n");
3271 # The tag could be closed by />, we handle this in the XML way
3272 # and don't process any content (we ignore whitespace)
3273 $ClosedTag = ($ScriptTag =~ m@[^\\]/\s*\>\s*$@) ? 1 : 0;
3276 # TYPE or CLASS?
3277 my $TypeName = ($TagType =~ /META/is) ? "CONTENT" : "TYPE";
3278 $TypeName = "CLASS" if $TagType eq 'DIV' || $TagType eq 'INS';
3280 # Parse <SCRIPT> or <META> directive
3281 # If NOT (TYPE|CONTENT)="text/ssperl" (i.e., $ServerScriptContentType),
3282 # send the line to the output and go to the next loop
3283 my $CurrentContentType = "";
3284 if($ScriptTag =~ /(^|\s)$TypeName\s*=\s*/is)
3286 my ($Type) = ExtractQuotedItem($');
3287 $Type =~ /^\s*([\w\/\-]+)\s*[\,\;]?/;
3288 $CurrentContentType = lc($1); # Note: mime-types are "case-less"
3289 # CSS classes are aliases of $ServerScriptContentType
3290 if($TypeName eq "CLASS" && $CurrentContentType eq $ServerScriptContentClass)
3292 $CurrentContentType = $ServerScriptContentType;
3297 # Not a known server-side content type, print and continue
3298 unless(($CurrentContentType =~
3299 /$ServerScriptContentType|$ShellScriptContentType/is) ||
3300 $ScriptingLanguages{$CurrentContentType})
3302 print $ScriptTag;
3303 $_ = $After;
3304 next;
3308 # A known server-side content type, evaluate
3310 # First, handle \> and \<
3311 $ScriptTag =~ s/\\\>/\>/isg;
3312 $ScriptTag =~ s/\\\</\</isg;
3314 # Extract the CGI, SRC, ID, IF and UNLESS attributes
3315 my %ScriptTagAttributes = ();
3316 while($ScriptTag =~ /(^|\s)(CGI|IF|UNLESS|SRC|ID)\s*=\s*/is)
3318 my $Attribute = $2;
3319 my $Rest = $';
3320 my $Value = "";
3321 ($Value, $ScriptTag) = ExtractQuotedItem($Rest);
3322 $ScriptTagAttributes{uc($Attribute)} = $Value;
3326 # The attribute used to define the CGI variables
3327 # Extract CGI-variables from
3328 # <META CONTENT="text/ssperl; CGI='' SRC=''">
3329 # <SCRIPT TYPE='text/ssperl' CGI='' SRC=''>
3330 # <DIV CLASS='ssperl' CGI='' SRC='' ID=""> tags
3331 # <INS CLASS='ssperl' CGI='' SRC='' ID=""> tags
3332 if($ScriptTagAttributes{'CGI'})
3334 @ARGV = (); # Reset ARGV
3335 $ARGC = 0;
3336 $METAarguments = ""; # Reset the META CGI arguments
3337 @METAvalues = ();
3338 my $Meta_CGI = $ScriptTagAttributes{'CGI'};
3340 # Process default values of variables ($<name> = 'default value')
3341 # Allowed quotes are '', "", ``, (), [], and {}
3342 while($Meta_CGI =~ /(^\s*|[^\\])([\$\@\%]?)([\w\-]+)\s*/is)
3344 my $varType = $2 || '$'; # Variable or list
3345 my $name = $3; # The Name
3346 my $default = "";
3347 $Meta_CGI = $';
3349 if($Meta_CGI =~ /^\s*\=\s*/is)
3351 # Locate (any) default value
3352 ($default, $Meta_CGI) = ExtractQuotedItem($'); # Cut the parameter from the CGI
3354 $RemainingTag = $Meta_CGI;
3357 # Define CGI (or ENV) variable, initalize it from the
3358 # Query string or the default value
3360 # Also construct the @ARGV and @_ arrays. This allows other (SRC=) Perl
3361 # scripts to access the CGI arguments defined in the META tag
3362 # (Not for CGI inside <SCRIPT> tags)
3363 if($varType eq '$')
3365 CGIexecute::defineCGIvariable($name, $default)
3366 || dieHandler(20, "INVALID CGI name/value pair ($name, $default)\n");
3367 push(@METAvalues, "'".${"CGIexecute::$name"}."'");
3368 # Add value to the @ARGV list
3369 push(@ARGV, ${"CGIexecute::$name"});
3370 ++$ARGC;
3372 elsif($varType eq '@')
3374 CGIexecute::defineCGIvariableList($name, $default)
3375 || dieHandler(21, "INVALID CGI name/value list pair ($name, $default)\n");
3376 push(@METAvalues, "'".join("'", @{"CGIexecute::$name"})."'");
3377 # Add value to the @ARGV list
3378 push(@ARGV, @{"CGIexecute::$name"});
3379 $ARGC = scalar(@CGIexecute::ARGV);
3381 elsif($varType eq '%')
3383 CGIexecute::defineCGIvariableHash($name, $default)
3384 || dieHandler(22, "INVALID CGI name/value hash pair ($name, $default)\n");
3385 my @PairList = map {"$_ => ".${"CGIexecute::$name"}{$_}} keys(%{"CGIexecute::$name"});
3386 push(@METAvalues, "'".join("'", @PairList)."'");
3387 # Add value to the @ARGV list
3388 push(@ARGV, %{"CGIexecute::$name"});
3389 $ARGC = scalar(@CGIexecute::ARGV);
3392 # Store the values for internal and later use
3393 $METAarguments .= "$varType".$name.","; # A string of CGI variable names
3395 push(@METAvalues, "\'".eval("\"$varType\{CGIexecute::$name\}\"")."\'"); # ALWAYS add '-quotes around values
3400 # The IF (conditional execution) Attribute
3401 # Evaluate the condition and stop unless it evaluates to true
3402 if($ScriptTagAttributes{'IF'})
3404 my $IFcondition = $ScriptTagAttributes{'IF'};
3406 # Convert SCRIPT calls, ./<script>
3407 $IFcondition =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
3409 # Convert FILE calls, ~/<file>
3410 $IFcondition =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
3412 # Block execution if necessary
3413 unless(CGIexecute->evaluate($IFcondition))
3415 %ScriptTagAttributes = ();
3416 $CurrentContentType = "";
3420 # The UNLESS (conditional execution) Attribute
3421 # Evaluate the condition and stop if it evaluates to true
3422 if($ScriptTagAttributes{'UNLESS'})
3424 my $UNLESScondition = $ScriptTagAttributes{'UNLESS'};
3426 # Convert SCRIPT calls, ./<script>
3427 $UNLESScondition =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
3429 # Convert FILE calls, ~/<file>
3430 $UNLESScondition =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
3432 # Block execution if necessary
3433 if(CGIexecute->evaluate($UNLESScondition))
3435 %ScriptTagAttributes = ();
3436 $CurrentContentType = "";
3440 # The SRC (Source File) Attribute
3441 # Extract any source script files and add them in
3442 # front of the directive
3443 # The SRC list should be emptied
3444 @SRClist = ();
3445 my $SRCtag = "";
3446 my $Prefix = 1;
3447 my $PrefixDirective = "";
3448 my $PostfixDirective = "";
3449 # There is a SRC attribute
3450 if($ScriptTagAttributes{'SRC'})
3452 $SRCtag = $ScriptTagAttributes{'SRC'};
3453 # Remove "file://" prefixes
3454 $SRCtag =~ s@([^\w\/\\]|^)file\://([^\s\/\@\=])@$1$2@gis;
3455 # Expand script filenames "./Script"
3456 $SRCtag =~ s@([^\w\/\\]|^)\./([^\s\/\@\=])@$1$SCRIPT_SUB/$2@gis;
3457 # Expand script filenames "~/Script"
3458 $SRCtag =~ s@([^\w\/\\]|^)\~/([^\s\/\@\=])@$1$HOME_SUB/$2@gis;
3461 # File source tags
3462 while($SRCtag =~ /\S/is)
3464 my $SRCdirective = "";
3466 # Pseudo file, just a switch to go from PREFIXING to POSTFIXING
3467 # SRC files
3468 if($SRCtag =~ /^[\s\;\,]*(POSTFIX|PREFIX)([^$FileAllowedChars]|$)/is)
3470 my $InsertionPlace = $1;
3471 $SRCtag = $2.$';
3473 $Prefix = $InsertionPlace =~ /POSTFIX/i ? 0 : 1;
3474 # Go to next round
3475 next;
3477 # {}-blocks are just evaluated by "do"
3478 elsif($SRCtag =~ /^[\s\;\,]*\{/is)
3480 my $SRCblock = $';
3481 if($SRCblock =~ /\}[\s\;\,]*([^\}]*)$/is)
3483 $SRCblock = $`;
3484 $SRCtag = $1.$';
3485 # SAFEqx shell script blocks
3486 if($CurrentContentType =~ /$ShellScriptContentType/is)
3488 # Handle ''-quotes inside the script
3489 $SRCblock =~ s/[\']/\\$&/gis;
3491 $SRCblock = "print do { SAFEqx(\'".$SRCblock."\'); };'';";
3492 $SRCdirective .= $SRCblock."\n";
3494 # do { SRCblocks }
3495 elsif($CurrentContentType =~ /$ServerScriptContentType/is)
3497 $SRCblock = "print do { $SRCblock };'';";
3498 $SRCdirective .= $SRCblock."\n";
3500 else # The interpreter should handle this
3502 push(@SRClist, "{ $SRCblock }");
3506 else
3507 { dieHandler(23, "Closing \} missing\n");};
3509 # Files are processed as Text or Executable files
3510 elsif($SRCtag =~ /[\s\;\,]*([$FileAllowedChars]+)[\;\,\s]*/is)
3512 my $SrcFile = $1;
3513 $SRCtag = $';
3515 # We are handling one of the external interpreters
3516 if($ScriptingLanguages{$CurrentContentType})
3518 push(@SRClist, $SrcFile);
3520 # We are at the start of a DIV tag, just load all SRC files and/or URL's
3521 elsif($TagType eq 'DIV' || $TagType eq 'INS') # All files are prepended in DIV's
3523 # $SrcFile is a URL pointing to an HTTP or FTP server
3524 if($SrcFile =~ m!^([a-z]+)\://!)
3526 my $URLoutput = CGIscriptor::read_url($SrcFile);
3527 $SRCdirective .= $URLoutput;
3529 # SRC file is an existing file
3530 elsif(-e "$SrcFile")
3532 open(DIVSOURCE, "<$SrcFile") || dieHandler(24, "<$SrcFile: $!\n");
3533 my $Content;
3534 while(sysread(DIVSOURCE, $Content, 1024) > 0)
3536 $SRCdirective .= $Content;
3538 close(DIVSOURCE);
3541 # Executable files are executed as
3542 # `$SrcFile 'ARGV[0]' 'ARGV[1]'`
3543 elsif(-x "$SrcFile")
3545 $SRCdirective .= "print \`$SrcFile @METAvalues\`;'';\n";
3547 # Handle 'standard' files, using ProcessFile
3548 elsif((-T "$SrcFile" || $ENV{$CGI_FILE_CONTENTS})
3549 && $SrcFile =~ m@($FilePattern)$@) # A recursion
3552 # Do not process still open files because it can lead
3553 # to endless recursions
3554 if(grep(/^$SrcFile$/, @OpenFiles))
3555 { dieHandler(25, "$SrcFile allready opened (endless recursion)\n")};
3556 # Prepare meta arguments
3557 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
3558 # Process the file
3559 $SRCdirective .= "main::ProcessFile(\'$SrcFile\');'';\n";
3561 elsif($SrcFile =~ m!^([a-z]+)\://!) # URL's are loaded and printed
3563 $SRCdirective .= GET_URL($SrcFile);
3565 elsif(-T "$SrcFile") # Textfiles are "do"-ed (Perl execution)
3567 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
3568 $SRCdirective .= "do \'$SrcFile\';'';\n";
3570 else # This one could not be resolved (should be handled by BinaryMapFile)
3572 $SRCdirective .= 'print "'.$SrcFile.' cannot be used"'."\n";
3577 # Postfix or Prefix
3578 if($Prefix)
3580 $PrefixDirective .= $SRCdirective;
3582 else
3584 $PostfixDirective .= $SRCdirective;
3587 # The prefix should be handled immediately
3588 $directive .= $PrefixDirective;
3589 $PrefixDirective = "";
3593 # Handle the content of the <SCRIPT></SCRIPT> tags
3594 # Do not process the content of <SCRIPT/>
3595 if($TagType =~ /SCRIPT/is && !$ClosedTag) # The <SCRIPT> TAG
3597 my $EndScriptTag = "";
3599 # Execute SHELL scripts with SAFEqx()
3600 if($CurrentContentType =~ /$ShellScriptContentType/is)
3602 $directive .= "SAFEqx(\'";
3605 # Extract Program
3606 while($After !~ /\<\s*\/SCRIPT[^\>]*\>/is && !eof($FileHandle))
3608 $After .= <$FileHandle>;
3609 performTranslation(\$After) if $TranslationPaths;
3612 if($After =~ /\<\s*\/SCRIPT[^\>]*\>/is)
3614 $directive .= $`;
3615 $EndScriptTag = $&;
3616 $After = $';
3618 else
3620 dieHandler(26, "Missing </SCRIPT> end tag in $ENV{'PATH_INFO'}\n");
3623 # Process only when content should be executed
3624 if($CurrentContentType)
3627 # Remove all comments from Perl scripts
3628 # (NOT from OS shell scripts)
3629 $directive =~ s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/$1/g
3630 if $CurrentContentType =~ /$ServerScriptContentType/i;
3632 # Convert SCRIPT calls, ./<script>
3633 $directive =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
3635 # Convert FILE calls, ~/<file>
3636 $directive =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
3638 # Execute SHELL scripts with SAFEqx(), closing bracket
3639 if($CurrentContentType =~ /$ShellScriptContentType/i)
3641 # Handle ''-quotes inside the script
3642 $directive =~ /SAFEqx\(\'/;
3643 $directive = $`.$&;
3644 my $Executable = $';
3645 $Executable =~ s/[\']/\\$&/gs;
3647 $directive .= $Executable."\');"; # Closing bracket
3650 else
3652 $directive = "";
3655 # Handle the content of the <DIV></DIV> tags
3656 # Do not process the content of <DIV/>
3657 elsif(($TagType eq 'DIV' || $TagType eq 'INS') && !$ClosedTag) # The <DIV> TAGs
3659 my $EndScriptTag = "";
3661 # Extract Text
3662 while($After !~ /\<\s*\/$TagType[^\>]*\>/is && !eof($FileHandle))
3664 $After .= <$FileHandle>;
3665 performTranslation(\$After) if $TranslationPaths;
3668 if($After =~ /\<\s*\/$TagType[^\>]*\>/is)
3670 $directive .= $`;
3671 $EndScriptTag = $&;
3672 $After = $';
3674 else
3676 dieHandler(27, "Missing </$TagType> end tag in $ENV{'PATH_INFO'}\n");
3679 # Add the Postfixed directives (but only when it contains something printable)
3680 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
3681 $PostfixDirective = "";
3684 # Process only when content should be handled
3685 if($CurrentContentType)
3688 # Get the name (ID), and clean it (i.e., remove anything that is NOT part of
3689 # a valid Perl name). Names should not contain $, but we can handle it.
3690 my $name = $ScriptTagAttributes{'ID'};
3691 $name =~ /^\s*[\$\@\%]?([\w\-]+)/;
3692 $name = $1;
3694 # Assign DIV contents to $NAME value OUTSIDE the CGI values!
3695 CGIexecute::defineCGIexecuteVariable($name, $directive);
3696 $directive = "";
3699 # Nothing to execute
3700 $directive = "";
3704 # Handle Foreign scripting languages
3705 if($ScriptingLanguages{$CurrentContentType})
3707 my $newDirective = "";
3708 $newDirective .= OpenForeignScript($CurrentContentType); # Only if not already done
3709 $newDirective .= PrefixForeignScript($CurrentContentType);
3710 $newDirective .= InsertForeignScript($CurrentContentType, $directive, @SRClist);
3711 $newDirective .= PostfixForeignScript($CurrentContentType);
3712 $newDirective .= CloseForeignScript($CurrentContentType); # This shouldn't be necessary
3714 $newDirective .= '"";';
3716 $directive = $newDirective;
3720 # Add the Postfixed directives (but only when it contains something printable)
3721 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
3722 $PostfixDirective = "";
3725 # EXECUTE the script and print the results
3727 # Use this to debug the program
3728 # print STDERR "Directive $CGI_Date: \n", $directive, "\n\n";
3730 my $Result = CGIexecute->evaluate($directive) if $directive; # Evaluate as PERL code
3731 $Result =~ s/\n$//g; # Remove final newline
3733 # Print the Result of evaluating the directive
3734 # (this will handle LARGE, >64 kB output)
3735 my $BytesWritten = 1;
3736 while($Result && $BytesWritten)
3738 $BytesWritten = syswrite(STDOUT, $Result, 64);
3739 $Result = substr($Result, $BytesWritten);
3741 # print $Result; # Could be used instead of above code
3743 # Store result if wanted, i.e., if $CGIscriptorResults has been
3744 # defined in a <META> tag.
3745 push(@CGIexecute::CGIscriptorResults, $Result)
3746 if exists($default_values{'CGIscriptorResults'});
3748 # Process the rest of the input line (this could contain
3749 # another directive)
3750 $_ = $After;
3752 print $_;
3753 } while(<$FileHandle>); # Read and Test AFTER first loop!
3755 close ($FileHandle);
3756 dieHandler(28, "Error in recursion\n") unless pop(@OpenFiles) == $file_path;
3760 ###############################################################################
3762 # Call the whole package
3764 sub Handle_Request
3766 my $file_path = "";
3768 # Initialization Code
3769 Initialize_Request();
3771 # SECURITY: ACCESS CONTROL
3772 Access_Control();
3774 # Read the POST part of the query, if there is one
3775 Get_POST_part_of_query();
3777 # Start (HTML) output and logging
3778 $file_path = Initialize_output();
3780 # Check login access or divert to login procedure
3781 $access_allowed = Log_In_Access();
3782 return "" unless $access_allowed;
3784 # Record which files are still open (to avoid endless recursions)
3785 my @OpenFiles = ();
3787 # Record whether the default HTML ContentType has already been printed
3788 # but only if the SERVER uses HTTP or some other protocol that might interpret
3789 # a content MIME type.
3791 $SupressContentType = !("$ENV{'SERVER_PROTOCOL'}" =~ /($ContentTypeServerProtocols)/i);
3793 # Process the specified file
3794 ProcessFile($file_path) if $file_path ne $SS_PUB;
3796 # Cleanup all open external (foreign) interpreters
3797 CloseAllForeignScripts();
3800 "" # SUCCESS
3803 # Make a single call to handle an (empty) request
3804 Handle_Request();
3807 # END OF PACKAGE MAIN
3810 ####################################################################################
3812 # The CGIEXECUTE PACKAGE
3814 ####################################################################################
3816 # Isolate the evaluation of directives as PERL code from the rest of the program.
3817 # Remember that each package has its own name space.
3818 # Note that only the FIRST argument of execute->evaluate is actually evaluated,
3819 # all other arguments are accessible inside the first argument as $_[0] to $_[$#_].
3821 package CGIexecute;
3823 sub evaluate
3825 my $self = shift;
3826 my $directive = shift;
3827 $directive = eval($directive);
3828 warn $@ if $@; # Write an error message to STDERR
3829 $directive; # Return value of directive
3833 # defineCGIexecuteVariable($name [, $value]) -> 0/1
3835 # Define and intialize variables inside CGIexecute
3836 # Does no sanity checking, for internal use only
3838 sub defineCGIexecuteVariable # ($name [, $value]) -> 0/1
3840 my $name = shift || return 0; # The Name
3841 my $value = shift || ""; # The value
3843 ${$name} = $value;
3845 return 1;
3848 # defineCGIvariable($name [, $default]) -> 0/1
3850 # Define and intialize CGI variables
3851 # Tries (in order) $ENV{$name}, the Query string and the
3852 # default value.
3853 # Removes all '-quotes etc.
3855 sub defineCGIvariable # ($name [, $default]) -> 0/1
3857 my $name = shift || return 0; # The Name
3858 my $default = shift || ""; # The default value
3860 # Remove \-quoted characters
3861 $default =~ s/\\(.)/$1/g;
3862 # Store default values
3863 $::default_values{$name} = $default if $default;
3865 # Process variables
3866 my $temp = undef;
3867 # If there is a user supplied value, it replaces the
3868 # default value.
3870 # Environment values have precedence
3871 if(exists($ENV{$name}))
3873 $temp = $ENV{$name};
3875 # Get name and its value from the query string
3876 elsif($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
3878 $temp = ::YOUR_CGIPARSE($name);
3880 # Defined values must exist for security
3881 elsif(!exists($::default_values{$name}))
3883 $::default_values{$name} = undef;
3886 # SECURITY, do not allow '- and `-quotes in
3887 # client values.
3888 # Remove all existing '-quotes
3889 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
3890 $temp =~ s/[\']/&#8217;/igs; # Remove all single quotes
3891 $temp =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
3892 # If $temp is empty, use the default value (if it exists)
3893 unless($temp =~ /\S/ || length($temp) > 0) # I.e., $temp is empty
3895 $temp = $::default_values{$name};
3896 # Remove all existing '-quotes
3897 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
3898 $temp =~ s/[\']/&#8217;/igs; # Remove all single quotes
3899 $temp =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
3901 else # Store current CGI values and remove defaults
3903 $::default_values{$name} = $temp;
3905 # Define the CGI variable and its value (in the execute package)
3906 ${$name} = $temp;
3908 # return SUCCES
3909 return 1;
3912 sub defineCGIvariableList # ($name [, $default]) -> 0/1)
3914 my $name = shift || return 0; # The Name
3915 my $default = shift || ""; # The default value
3917 # Defined values must exist for security
3918 if(!exists($::default_values{$name}))
3920 $::default_values{$name} = $default;
3923 my @temp = ();
3926 # For security:
3927 # Environment values have precedence
3928 if(exists($ENV{$name}))
3930 push(@temp, $ENV{$name});
3932 # Get name and its values from the query string
3933 if($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
3935 push(@temp, ::YOUR_CGIPARSE($name, 1)); # Extract LIST
3937 else
3939 push(@temp, $::default_values{$name});
3943 # SECURITY, do not allow '- and `-quotes in
3944 # client values.
3945 # Remove all existing '-quotes
3946 @temp = map {s/([\r\f]+\n)/\n/g; $_} @temp; # Only \n is allowed
3947 @temp = map {s/[\']/&#8217;/igs; $_} @temp; # Remove all single quotes
3948 @temp = map {s/[\`]/&#8216;/igs; $_} @temp; # Remove all backtick quotes
3950 # Store current CGI values and remove defaults
3951 $::default_values{$name} = $temp[0];
3953 # Define the CGI variable and its value (in the execute package)
3954 @{$name} = @temp;
3956 # return SUCCES
3957 return 1;
3960 sub defineCGIvariableHash # ($name [, $default]) -> 0/1) Note: '$name{""} = $default';
3962 my $name = shift || return 0; # The Name
3963 my $default = shift || ""; # The default value
3965 # Defined values must exist for security
3966 if(!exists($::default_values{$name}))
3968 $::default_values{$name} = $default;
3971 my %temp = ();
3974 # For security:
3975 # Environment values have precedence
3976 if(exists($ENV{$name}))
3978 $temp{""} = $ENV{$name};
3980 # Get name and its values from the query string
3981 if($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
3983 %temp = ::YOUR_CGIPARSE($name, -1); # Extract HASH table
3985 elsif($::default_values{$name} ne "")
3987 $temp{""} = $::default_values{$name};
3991 # SECURITY, do not allow '- and `-quotes in
3992 # client values.
3993 # Remove all existing '-quotes
3994 my $Key;
3995 foreach $Key (keys(%temp))
3997 $temp{$Key} =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
3998 $temp{$Key} =~ s/[\']/&#8217;/igs; # Remove all single quotes
3999 $temp{$Key} =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
4002 # Store current CGI values and remove defaults
4003 $::default_values{$name} = $temp{""};
4005 # Define the CGI variable and its value (in the execute package)
4006 %{$name} = ();
4007 my $tempKey;
4008 foreach $tempKey (keys(%temp))
4010 ${$name}{$tempKey} = $temp{$tempKey};
4013 # return SUCCES
4014 return 1;
4018 # SAFEqx('CommandString')
4020 # A special function that is a safe alternative to backtick quotes (and qx//)
4021 # with client-supplied CGI values. All CGI variables are surrounded by
4022 # single ''-quotes (except between existing \'\'-quotes, don't try to be
4023 # too smart). All variables are then interpolated. Simple (@) lists are
4024 # expanded with join(' ', @List), and simple (%) hash tables expanded
4025 # as a list of "key=value" pairs. Complex variables, e.g., @$var, are
4026 # evaluated in a scalar context (e.g., as scalar(@$var)). All occurrences of
4027 # $@% that should NOT be interpolated must be preceeded by a "\".
4028 # If the first line of the String starts with "#! interpreter", the
4029 # remainder of the string is piped into interpreter (after interpolation), i.e.,
4030 # open(INTERPRETER, "|interpreter");print INTERPRETER remainder;
4031 # just like in UNIX. There are some problems with quotes. Be carefull in
4032 # using them. You do not have access to the output of any piped (#!)
4033 # process! If you want such access, execute
4034 # <SCRIPT TYPE="text/osshell">echo "script"|interpreter</SCRIPT> or
4035 # <SCRIPT TYPE="text/ssperl">$resultvar = SAFEqx('echo "script"|interpreter');
4036 # </SCRIPT>.
4038 # SAFEqx ONLY WORKS WHEN THE STRING ITSELF IS SURROUNDED BY SINGLE QUOTES
4039 # (SO THAT IT IS NOT INTERPOLATED BEFORE IT CAN BE PROTECTED)
4040 sub SAFEqx # ('String') -> result of executing qx/"String"/
4042 my $CommandString = shift;
4043 my $NewCommandString = "";
4045 # Only interpolate when required (check the On/Off switch)
4046 unless($CGIscriptor::NoShellScriptInterpolation)
4049 # Handle existing single quotes around CGI values
4050 while($CommandString =~ /\'[^\']+\'/s)
4052 my $CurrentQuotedString = $&;
4053 $NewCommandString .= $`;
4054 $CommandString = $'; # The remaining string
4055 # Interpolate CGI variables between quotes
4056 # (e.g., '$CGIscriptorResults[-1]')
4057 $CurrentQuotedString =~
4058 s/(^|[^\\])([\$\@])((\w*)([\{\[][\$\@\%]?[\:\w\-]+[\}\]])*)/if(exists($main::default_values{$4})){
4059 "$1".eval("$2$3")}else{"$&"}/egs;
4061 # Combine result with previous result
4062 $NewCommandString .= $CurrentQuotedString;
4064 $CommandString = $NewCommandString.$CommandString;
4066 # Select known CGI variables and surround them with single quotes,
4067 # then interpolate all variables
4068 $CommandString =~
4069 s/(^|[^\\])([\$\@\%]+)((\w*)([\{\[][\w\:\$\"\-]+[\}\]])*)/
4070 if($2 eq '$' && exists($main::default_values{$4}))
4071 {"$1\'".eval("\$$3")."\'";}
4072 elsif($2 eq '@'){$1.join(' ', @{"$3"});}
4073 elsif($2 eq '%'){my $t=$1;map {$t.=" $_=".${"$3"}{$_}}
4074 keys(%{"$3"});$t}
4075 else{$1.eval("${2}$3");
4076 }/egs;
4078 # Remove backslashed [$@%]
4079 $CommandString =~ s/\\([\$\@\%])/$1/gs;
4082 # Debugging
4083 # return $CommandString;
4085 # Handle UNIX style "#! shell command\n" constructs as
4086 # a pipe into the shell command. The output cannot be tapped.
4087 my $ReturnValue = "";
4088 if($CommandString =~ /^\s*\#\!([^\f\n\r]+)[\f\n\r]/is)
4090 my $ShellScripts = $';
4091 my $ShellCommand = $1;
4092 open(INTERPRETER, "|$ShellCommand") || dieHandler(29, "\'$ShellCommand\' PIPE not opened: &!\n");
4093 select(INTERPRETER);$| = 1;
4094 print INTERPRETER $ShellScripts;
4095 close(INTERPRETER);
4096 select(STDOUT);$| = 1;
4098 # Shell scripts which are redirected to an existing named pipe.
4099 # The output cannot be tapped.
4100 elsif($CGIscriptor::ShellScriptPIPE)
4102 CGIscriptor::printSAFEqxPIPE($CommandString);
4104 else # Plain ``-backtick execution
4106 # Execute the commands
4107 $ReturnValue = qx/$CommandString/;
4109 return $ReturnValue;
4112 ####################################################################################
4114 # The CGIscriptor PACKAGE
4116 ####################################################################################
4118 # Isolate the evaluation of CGIscriptor functions, i.e., those prefixed with
4119 # "CGIscriptor::"
4121 package CGIscriptor;
4124 # The Interpolation On/Off switch
4125 my $NoShellScriptInterpolation = undef;
4126 # The ShellScript redirection pipe
4127 my $ShellScriptPIPE = undef;
4129 # Open a named PIPE for SAFEqx to receive ALL shell scripts
4130 sub RedirectShellScript # ('CommandString')
4132 my $CommandString = shift || undef;
4134 if($CommandString)
4136 $ShellScriptPIPE = "ShellScriptNamedPipe";
4137 open($ShellScriptPIPE, "|$CommandString")
4138 || main::dieHandler(30, "\'|$CommandString\' PIPE open failed: $!\n");
4140 else
4142 close($ShellScriptPIPE);
4143 $ShellScriptPIPE = undef;
4145 return $ShellScriptPIPE;
4148 # Print to redirected shell script pipe
4149 sub printSAFEqxPIPE # ("String") -> print return value
4151 my $String = shift || undef;
4153 select($ShellScriptPIPE); $| = 1;
4154 my $returnvalue = print $ShellScriptPIPE ($String);
4155 select(STDOUT); $| = 1;
4157 return $returnvalue;
4160 # a pointer to CGIexecute::SAFEqx
4161 sub SAFEqx # ('String') -> result of qx/"String"/
4163 my $CommandString = shift;
4164 return CGIexecute::SAFEqx($CommandString);
4168 # a pointer to CGIexecute::defineCGIvariable
4169 sub defineCGIvariable # ($name[, $default]) ->0/1
4171 my $name = shift;
4172 my $default = shift;
4173 return CGIexecute::defineCGIvariable($name, $default);
4177 # Decode URL encoded arguments
4178 sub URLdecode # (URL encoded input) -> string
4180 my $output = "";
4181 my $char;
4182 my $Value;
4183 foreach $Value (@_)
4185 my $EncodedValue = $Value; # Do not change the loop variable
4186 # Convert all "+" to " "
4187 $EncodedValue =~ s/\+/ /g;
4188 # Convert all hexadecimal codes (%FF) to their byte values
4189 while($EncodedValue =~ /\%([0-9A-F]{2})/i)
4191 $output .= $`.chr(hex($1));
4192 $EncodedValue = $';
4194 $output .= $EncodedValue; # The remaining part of $Value
4196 $output;
4199 # Encode arguments as URL codes.
4200 sub URLencode # (input) -> URL encoded string
4202 my $output = "";
4203 my $char;
4204 my $Value;
4205 foreach $Value (@_)
4207 my @CharList = split('', $Value);
4208 foreach $char (@CharList)
4210 if($char =~ /\s/)
4211 { $output .= "+";}
4212 elsif($char =~ /\w\-/)
4213 { $output .= $char;}
4214 else
4216 $output .= uc(sprintf("%%%2.2x", ord($char)));
4220 $output;
4223 # Extract the value of a CGI variable from the URL-encoded $string
4224 # Also extracts the data blocks from a multipart request. Does NOT
4225 # decode the multipart blocks
4226 sub CGIparseValue # (ValueName [, URL_encoded_QueryString [, \$QueryReturnReference]]) -> Decoded value
4228 my $ValueName = shift;
4229 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4230 my $ReturnReference = shift || undef;
4231 my $output = "";
4233 if($QueryString =~ /(^|\&)$ValueName\=([^\&]*)(\&|$)/)
4235 $output = URLdecode($2);
4236 $$ReturnReference = $' if ref($ReturnReference);
4238 # Get multipart POST or PUT methods
4239 elsif($main::ENV{'CONTENT_TYPE'} =~ m@(multipart/([\w\-]+)\;\s+boundary\=([\S]+))@i)
4241 my $MultipartType = $2;
4242 my $BoundaryString = $3;
4243 # Remove the boundary-string
4244 my $temp = $QueryString;
4245 $temp =~ /^\Q--$BoundaryString\E/m;
4246 $temp = $';
4248 # Identify the newline character(s), this is the first character in $temp
4249 my $NewLine = "\r\n"; # Actually, this IS the correct one
4250 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
4252 # Is this correct??? I have to check.
4253 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
4254 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
4255 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
4256 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
4259 # search through all data blocks
4260 while($temp =~ /^\Q--$BoundaryString\E/m)
4262 my $DataBlock = $`;
4263 $temp = $';
4264 # Get the empty line after the header
4265 $DataBlock =~ /$NewLine$NewLine/;
4266 $Header = $`;
4267 $output = $';
4268 my $Header = $`;
4269 $output = $';
4271 # Remove newlines from the header
4272 $Header =~ s/$NewLine/ /g;
4274 # Look whether this block is the one you are looking for
4275 # Require the quotes!
4276 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
4278 my $i;
4279 for($i=length($NewLine); $i; --$i)
4281 chop($output);
4283 # OK, get out
4284 last;
4286 # reinitialize the output
4287 $output = "";
4289 $$ReturnReference = $temp if ref($ReturnReference);
4291 elsif($QueryString !~ /(^|\&)$ValueName\=/) # The value simply isn't there
4293 return undef;
4294 $$ReturnReference = undef if ref($ReturnReference);
4296 else
4298 print "ERROR: $ValueName $main::ENV{'CONTENT_TYPE'}\n";
4300 return $output;
4304 # Get a list of values for the same ValueName. Uses CGIparseValue
4306 sub CGIparseValueList # (ValueName [, URL_encoded_QueryString]) -> List of decoded values
4308 my $ValueName = shift;
4309 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4310 my @output = ();
4311 my $RestQueryString;
4312 my $Value;
4313 while($QueryString &&
4314 (($Value = CGIparseValue($ValueName, $QueryString, \$RestQueryString))
4315 || defined($Value)))
4317 push(@output, $Value);
4318 $QueryString = $RestQueryString; # QueryString is consumed!
4320 # ready, return list with values
4321 return @output;
4324 sub CGIparseValueHash # (ValueName [, URL_encoded_QueryString]) -> Hash table of decoded values
4326 my $ValueName = shift;
4327 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4328 my $RestQueryString;
4329 my %output = ();
4330 while($QueryString && $QueryString =~ /(^|\&)$ValueName([\w]*)\=/)
4332 my $Key = $2;
4333 my $Value = CGIparseValue("$ValueName$Key", $QueryString, \$RestQueryString);
4334 $output{$Key} = $Value;
4335 $QueryString = $RestQueryString; # QueryString is consumed!
4337 # ready, return list with values
4338 return %output;
4341 sub CGIparseForm # ([URL_encoded_QueryString]) -> Decoded Form (NO multipart)
4343 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4344 my $output = "";
4346 $QueryString =~ s/\&/\n/g;
4347 $output = URLdecode($QueryString);
4349 $output;
4352 # Extract the header of a multipart CGI variable from the POST input
4353 sub CGIparseHeader # (ValueName [, URL_encoded_QueryString]) -> Decoded value
4355 my $ValueName = shift;
4356 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4357 my $output = "";
4359 if($main::ENV{'CONTENT_TYPE'} =~ m@(multipart/([\w\-]+)\;\s+boundary\=([\S]+))@i)
4361 my $MultipartType = $2;
4362 my $BoundaryString = $3;
4363 # Remove the boundary-string
4364 my $temp = $QueryString;
4365 $temp =~ /^\Q--$BoundaryString\E/m;
4366 $temp = $';
4368 # Identify the newline character(s), this is the first character in $temp
4369 my $NewLine = "\r\n"; # Actually, this IS the correct one
4370 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
4372 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
4373 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
4374 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
4375 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
4378 # search through all data blocks
4379 while($temp =~ /^\Q--$BoundaryString\E/m)
4381 my $DataBlock = $`;
4382 $temp = $';
4383 # Get the empty line after the header
4384 $DataBlock =~ /$NewLine$NewLine/;
4385 $Header = $`;
4386 my $Header = $`;
4388 # Remove newlines from the header
4389 $Header =~ s/$NewLine/ /g;
4391 # Look whether this block is the one you are looking for
4392 # Require the quotes!
4393 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
4395 $output = $Header;
4396 last;
4398 # reinitialize the output
4399 $output = "";
4402 return $output;
4406 # Checking variables for security (e.g., file names and email addresses)
4407 # File names are tested against the $::FileAllowedChars and $::BlockPathAccess variables
4408 sub CGIsafeFileName # FileName -> FileName or ""
4410 my $FileName = shift || "";
4411 return "" if $FileName =~ m?[^$::FileAllowedChars]?;
4412 return "" if $FileName =~ m!(^|/|\:)\-!;
4413 return "" if $FileName =~ m@\.\.\Q$::DirectorySeparator\E@; # Higher directory not allowed
4414 return "" if $FileName =~ m@\Q$::DirectorySeparator\E\.\.@; # Higher directory not allowed
4415 return "" if $::BlockPathAccess && $FileName =~ m@$::BlockPathAccess@; # Invisible (blocked) file
4417 return $FileName;
4420 sub CGIsafeEmailAddress # email -> email or ""
4422 my $Email = shift || "";
4423 return "" unless $Email =~ m/^[\w\.\-]+[\@][\w\.\-\:]+$/;
4424 return $Email;
4427 # Get a URL from the web. Needs main::GET_URL($URL) function
4428 # (i.e., curl, snarf, or wget)
4429 sub read_url # ($URL) -> page/file
4431 my $URL = shift || return "";
4433 # Get the commands to read the URL, do NOT add a print command
4434 my $URL_command = main::GET_URL($URL, 1);
4435 # execute the commands, i.e., actually read it
4436 my $URLcontent = CGIexecute->evaluate($URL_command);
4438 # Ready, return the content.
4439 return $URLcontent;
4442 ################################################>>>>>>>>>>Start Remove
4444 # BrowseDirs(RootDirectory [, Pattern, Start])
4446 # usage:
4447 # <SCRIPT TYPE='text/ssperl'>
4448 # CGIscriptor::BrowseDirs('Sounds', '\.aifc$', 'Speech', 'DIRECTORY')
4449 # </SCRIPT>
4451 # Allows to browse subdirectories. Start should be relative to the RootDirectory,
4452 # e.g., the full path of the directory 'Speech' is '~/Sounds/Speech'.
4453 # Only files which fit /$Pattern/ and directories are displayed.
4454 # Directories down or up the directory tree are supplied with a
4455 # GET request with the name of the CGI variable in the fourth argument (default
4456 # is 'BROWSEDIRS'). So the correct call for a subdirectory could be:
4457 # CGIscriptor::BrowseDirs('Sounds', '\.aifc$', $DIRECTORY, 'DIRECTORY')
4459 sub BrowseDirs # (RootDirectory [, Pattern, Start, CGIvariable, HTTPserver]) -> Print HTML code
4461 my $RootDirectory = shift; # || return 0;
4462 my $Pattern = shift || '\S';
4463 my $Start = shift || "";
4464 my $CGIvariable = shift || "BROWSEDIRS";
4465 my $HTTPserver = shift || '';
4467 $Start = CGIscriptor::URLdecode($Start); # Sometimes, too much has been encoded
4468 $Start =~ s@//+@/@g;
4469 $Start =~ s@[^/]+/\.\.@@ig;
4470 $Start =~ s@^\.\.@@ig;
4471 $Start =~ s@/\.$@@ig;
4472 $Start =~ s!/+$!!g;
4473 $Start .= "/" if $Start;
4475 my @Directory = glob("$::CGI_HOME/$RootDirectory/$Start");
4476 $CurrentDirectory = shift(@Directory);
4477 $CurrentDirectory = $' if $CurrentDirectory =~ m@(/\.\./)+@;
4478 $CurrentDirectory =~ s@^$::CGI_HOME@@g;
4479 print "<h1>";
4480 print "$CurrentDirectory" if $CurrentDirectory;
4481 print "</h1>\n";
4482 opendir(BROWSE, "$::CGI_HOME/$RootDirectory/$Start") || main::dieHandler(31, "$::CGI_HOME/$RootDirectory/$Start $!");
4483 my @AllFiles = sort grep(!/^([\.]+[^\.]|\~)/, readdir(BROWSE));
4485 # Print directories
4486 my $file;
4487 print "<pre><ul TYPE='NONE'>\n";
4488 foreach $file (@AllFiles)
4490 next unless -d "$::CGI_HOME/$RootDirectory/$Start$file";
4491 # Check whether this file should be visible
4492 next if $::BlockPathAccess &&
4493 "/$RootDirectory/$Start$file/" =~ m@$::BlockPathAccess@;
4495 my $NewURL = $Start ? "$Start$file" : $file;
4496 $NewURL = CGIscriptor::URLencode($NewURL);
4497 print "<dt><a href='";
4498 print "$ENV{SCRIPT_NAME}" if $ENV{SCRIPT_NAME} !~ m@[^\w+\-/]@;
4499 print "$ENV{PATH_INFO}?$CGIvariable=$NewURL'>$file</a></dt>\n";
4501 print "</ul></pre>\n";
4503 # Print files
4504 print "<pre><ul TYPE='CIRCLE'>\n";
4505 my $TotalSize = 0;
4506 foreach $file (@AllFiles)
4508 next if $file =~ /^\./;
4509 next if -d "$::CGI_HOME/$RootDirectory/$Start$file";
4510 next if -l "$::CGI_HOME/$RootDirectory/$Start$file";
4511 # Check whether this file should be visible
4512 next if $::BlockPathAccess &&
4513 "$::CGI_HOME/$RootDirectory/$Start$file" =~ m@$::BlockPathAccess@;
4515 if($file =~ m@$Pattern@)
4517 my $Date = localtime($^T - (-M "$::CGI_HOME/$RootDirectory/$Start$file")*3600*24);
4518 my $Size = -s "$::CGI_HOME/$RootDirectory/$Start$file";
4519 $Size = sprintf("%6.0F kB", $Size/1024);
4520 my $Type = `file $::CGI_HOME/$RootDirectory/$Start$file`;
4521 $Type =~ s@\s*$::CGI_HOME/$RootDirectory/$Start$file\s*\:\s*@@ig;
4522 chomp($Type);
4524 print "<li>";
4525 if($HTTPserver =~ /^\s*[\.\~]\s*$/)
4527 print "<a href='$Start$file'>";
4529 elsif($HTTPserver)
4531 print "<a href='$HTTPserver/$RootDirectory/$Start$file'>";
4533 printf("%-40s", "$file</a>") if $HTTPserver;
4534 printf("%-40s", "$file") unless $HTTPserver;
4535 print "\t$Size\t$Date\t$Type";
4536 print "</li>\n";
4539 print "</ul></pre>";
4541 return 1;
4545 # ListDocs(Pattern [,ListType])
4547 # usage:
4548 # <SCRIPT TYPE=text/ssperl>
4549 # CGIscriptor::ListDocs("/*", "dl");
4550 # </SCRIPT>
4552 # This subroutine is very usefull to manage collections of independent
4553 # documents. The resulting list will display the tree-like directory
4554 # structure. If this routine is too slow for online use, you can
4555 # store the result and use a link to that stored file.
4557 # List HTML and Text files with title and first header (HTML)
4558 # or filename and first meaningfull line (general text files).
4559 # The listing starts at the ServerRoot directory. Directories are
4560 # listed recursively.
4562 # You can change the list type (default is dl).
4563 # e.g.,
4564 # <dt><a href=<file.html>>title</a>
4565 # <dd>First Header
4566 # <dt><a href=<file.txt>>file.txt</a>
4567 # <dd>First meaningfull line of text
4569 sub ListDocs # ($Pattern [, prefix]) e.g., ("/Books/*", [, "dl"])
4571 my $Pattern = shift;
4572 $Pattern =~ /\*/;
4573 my $ListType = shift || "dl";
4574 my $Prefix = lc($ListType) eq "dl" ? "dt" : "li";
4575 my $URL_root = "http://$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}";
4576 my @FileList = glob("$::CGI_HOME$Pattern");
4577 my ($FileName, $Path, $Link);
4579 # Print List markers
4580 print "<$ListType>\n";
4582 # Glob all files
4583 File: foreach $FileName (@FileList)
4585 # Check whether this file should be visible
4586 next if $::BlockPathAccess && $FileName =~ m@$::BlockPathAccess@;
4588 # Recursively list files in all directories
4589 if(-d $FileName)
4591 $FileName =~ m@([^/]*)$@;
4592 my $DirName = $1;
4593 print "<$Prefix>$DirName\n";
4594 $Pattern =~ m@([^/]*)$@;
4595 &ListDocs("$`$DirName/$1", $ListType);
4596 next;
4598 # Use textfiles
4599 elsif(-T "$FileName")
4601 open(TextFile, $FileName) || next;
4603 # Ignore all other file types
4604 else
4605 { next;};
4607 # Get file path for link
4608 $FileName =~ /$::CGI_HOME/;
4609 print "<$Prefix><a href=$URL_root$'>";
4610 # Initialize all variables
4611 my $Line = "";
4612 my $TitleFound = 0;
4613 my $Caption = "";
4614 my $Title = "";
4615 # Read file and step through
4616 while(<TextFile>)
4618 chop $_;
4619 $Line = $_;
4620 # HTML files
4621 if($FileName =~ /\.ht[a-zA-Z]*$/i)
4623 # Catch Title
4624 while(!$Title)
4626 if($Line =~ m@<title>([^<]*)</title>@i)
4628 $Title = $1;
4629 $Line = $';
4631 else
4633 $Line .= <TextFile> || goto Print;
4634 chop $Line;
4637 # Catch First Header
4638 while(!$Caption)
4640 if($Line =~ m@</h1>@i)
4642 $Caption = $`;
4643 $Line = $';
4644 $Caption =~ m@<h1>@i;
4645 $Caption = $';
4646 $Line = $`.$Caption.$Line;
4648 else
4650 $Line .= <TextFile> || goto Print;
4651 chop $Line;
4655 # Other text files
4656 else
4658 # Title equals file name
4659 $FileName =~ /([^\/]+)$/;
4660 $Title = $1;
4661 # Catch equals First Meaningfull line
4662 while(!$Caption)
4664 if($Line =~ /[A-Z]/ &&
4665 ($Line =~ /subject|title/i || $Line =~ /^[\w,\.\s\?\:]+$/)
4666 && $Line !~ /Newsgroup/ && $Line !~ /\:\s*$/)
4668 $Line =~ s/\<[^\>]+\>//g;
4669 $Caption = $Line;
4671 else
4673 $Line = <TextFile> || goto Print;
4677 Print: # Print title and subject
4678 print "$Title</a>\n";
4679 print "<dd>$Caption\n" if $ListType eq "dl";
4680 $TitleFound = 0;
4681 $Caption = "";
4682 close TextFile;
4683 next File;
4686 # Print Closing List Marker
4687 print "</$ListType>\n";
4688 ""; # Empty return value
4692 # HTMLdocTree(Pattern [,ListType])
4694 # usage:
4695 # <SCRIPT TYPE=text/ssperl>
4696 # CGIscriptor::HTMLdocTree("/Welcome.html", "dl");
4697 # </SCRIPT>
4699 # The following subroutine is very usefull for checking large document
4700 # trees. Starting from the root (s), it reads all files and prints out
4701 # a nested list of links to all attached files. Non-existing or misplaced
4702 # files are flagged. This is quite a file-i/o intensive routine
4703 # so you would not like it to be accessible to everyone. If you want to
4704 # use the result, save the whole resulting page to disk and use a link
4705 # to this file.
4707 # HTMLdocTree takes an HTML file or file pattern and constructs nested lists
4708 # with links to *local* files (i.e., only links to the local server are
4709 # followed). The list entries are the document titles.
4710 # If the list type is <dl>, the first <H1> header is used too.
4711 # For each file matching the pattern, a list is made recursively of all
4712 # HTML documents that are linked from it and are stored in the same directory
4713 # or a sub-directory. Warnings are given for missing files.
4714 # The listing starts for the ServerRoot directory.
4715 # You can change the default list type <dl> (<dl>, <ul>, <ol>).
4717 %LinkUsed = ();
4719 sub HTMLdocTree # ($Pattern [, listtype])
4720 # e.g., ("/Welcome.html", [, "ul"])
4722 my $Pattern = shift;
4723 my $ListType = shift || "dl";
4724 my $Prefix = lc($ListType) eq "dl" ? "dt" : "li";
4725 my $URL_root = "http://$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}";
4726 my ($Filename, $Path, $Link);
4727 my %LocalLinks = {};
4729 # Read files (glob them for expansion of wildcards)
4730 my @FileList = glob("$::CGI_HOME$Pattern");
4731 foreach $Path (@FileList)
4733 # Get URL_path
4734 $Path =~ /$::CGI_HOME/;
4735 my $URL_path = $';
4736 # Check whether this file should be visible
4737 next if $::BlockPathAccess && $URL_path =~ m@$::BlockPathAccess@;
4739 my $Title = $URL_path;
4740 my $Caption = "";
4741 # Current file should not be used again
4742 ++$LinkUsed{$URL_path};
4743 # Open HTML doc
4744 unless(open(TextFile, $Path))
4746 print "<$Prefix>$Title <blink>(not found)</blink><br>\n";
4747 next;
4749 while(<TextFile>)
4751 chop $_;
4752 $Line = $_;
4753 # Catch Title
4754 while($Line =~ m@<title>@i)
4756 if($Line =~ m@<title>([^<]*)</title>@i)
4758 $Title = $1;
4759 $Line = $';
4761 else
4763 $Line .= <TextFile>;
4764 chop $Line;
4767 # Catch First Header
4768 while(!$Caption && $Line =~ m@<h1>@i)
4770 if($Line =~ m@</h[1-9]>@i)
4772 $Caption = $`;
4773 $Line = $';
4774 $Caption =~ m@<h1>@i;
4775 $Caption = $';
4776 $Line = $`.$Caption.$Line;
4778 else
4780 $Line .= <TextFile>;
4781 chop $Line;
4784 # Catch and print Links
4785 while($Line =~ m@<a href\=([^>]*)>@i)
4787 $Link = $1;
4788 $Line = $';
4789 # Remove quotes
4790 $Link =~ s/\"//g;
4791 # Remove extras
4792 $Link =~ s/[\#\?].*$//g;
4793 # Remove Servername
4794 if($Link =~ m@(http://|^)@i)
4796 $Link = $';
4797 # Only build tree for current server
4798 next unless $Link =~ m@$::ENV{'SERVER_NAME'}|^/@;
4799 # Remove server name and port
4800 $Link =~ s@^[^\/]*@@g;
4802 # Store the current link
4803 next if $LinkUsed{$Link} || $Link eq $URL_path;
4804 ++$LinkUsed{$Link};
4805 ++$LocalLinks{$Link};
4809 close TextFile;
4810 print "<$Prefix>";
4811 print "<a href=http://";
4812 print "$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}$URL_path>";
4813 print "$Title</a>\n";
4814 print "<br>$Caption\n"
4815 if $Caption && $Caption ne $Title && $ListType =~ /dl/i;
4816 print "<$ListType>\n";
4817 foreach $Link (keys(%LocalLinks))
4819 &HTMLdocTree($Link, $ListType);
4821 print "</$ListType>\n";
4825 ###########################<<<<<<<<<<End Remove
4827 # Make require happy
4830 =head1 NAME
4832 CGIscriptor -
4834 =head1 DESCRIPTION
4836 A flexible HTML 4 compliant script/module for CGI-aware
4837 embeded Perl, shell-scripts, and other scripting languages,
4838 executed at the server side.
4840 =head1 README
4842 Executes embeded Perl code in HTML pages with easy
4843 access to CGI variables. Also processes embeded shell
4844 scripts and scripts in any other language with an
4845 interactive interpreter (e.g., in-line Python, Tcl,
4846 Ruby, Awk, Lisp, Xlispstat, Prolog, M4, R, REBOL, Praat,
4847 sh, bash, csh, ksh).
4849 CGIscriptor is very flexible and hides all the specifics
4850 and idiosyncrasies of correct output and CGI coding and naming.
4851 CGIscriptor complies with the W3C HTML 4.0 recommendations.
4853 This Perl program will run on any WWW server that runs
4854 Perl scripts, just add a line like the following to your
4855 srm.conf file (Apache example):
4857 ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
4859 URL's that refer to http://www.your.address/SHTML/... will
4860 now be handled by CGIscriptor.pl, which can use a private
4861 directory tree (default is the DOCUMENT_ROOT directory tree,
4862 but it can be anywhere).
4864 =head1 PREREQUISITES
4867 =head1 COREQUISITES
4870 =pod OSNAMES
4872 Linux, *BSD, *nix, MS WinXP
4874 =pod SCRIPT CATEGORIES
4876 Servers
4880 =cut