Added support for Session Control
[CGIscriptor.git] / CGIscriptor.pl
blob06b458014f4c8334835ec8166c6fe6e32b4f18e1
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/' => ".Sessions\t.Passwords\tLogin.html"
345 # Raw files must contain their own Content-type (xmr <- x-multipart-replace).
346 # THIS IS A SUBSET OF THE FILES DEFINED IN $FilePattern
347 $RawFilePattern = ".xmr";
348 # (In principle, this could contain a full file specification, e.g.,
349 # ".xmr|relocated.html")
351 # Raw File pattern post-processing
352 $RawFilePattern =~ s/([@.])/\\$1/g; # Convert . and @ to \. and \@
354 # Server protocols for which "Content-type: text/html\n\n" should be printed
355 # (you should not bother with these, except for HTTP, they are mostly imaginary)
356 $ContentTypeServerProtocols = 'HTTP|MAIL|MIME';
358 # Block access to all (sub-) paths and directories that match the
359 # following (URL) path (is used as:
360 # 'die if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@;' )
361 $BlockPathAccess = '/(CVS|\.git)/'; # Protect CVS and .git information
363 # All (blocked) other file-types can be mapped to a single "binary-file"
364 # processor (a kind of pseudo-file path). This can either be an error
365 # message (e.g., "illegal file") or contain a script that serves binary
366 # files.
367 # Note: the real file path wil be stored in $ENV{CGI_BINARY_FILE}.
368 $BinaryMapFile = "/BinaryMapFile.xmr";
369 # Allow for the addition of a CGIscriptor directory
370 # Note that a BinaryMapFile in the root "~/" directory has precedence
371 $BinaryMapFile = "/CGIscriptor".$BinaryMapFile
372 if ! -e "$YOUR_HTML_FILES".$BinaryMapFile
373 && -e "$YOUR_HTML_FILES/CGIscriptor".$BinaryMapFile;
376 # List of all characters that are allowed in file names and paths.
377 # All requests containing illegal characters are blocked. This
378 # blocks most tricks (e.g., adding "\000", "\n", or other control
379 # characters, also blocks URI's using %FF)
380 # THIS IS A SECURITY FEATURE
381 # (this is also used to parse filenames in SRC= features, note the
382 # '-quotes, they are essential)
383 $FileAllowedChars = '\w\.\~\/\:\*\?\-'; # Covers Unix and Mac, but NO spaces
385 # Maximum size of the Query (number of characters clients can send
386 # covers both GET & POST combined)
387 $MaximumQuerySize = 2**20 - 1; # = 2**14 - 1
390 # Embeded URL get function used in SRC attributes and CGIscriptor::read_url
391 # (returns a string with the PERL code to transfer the URL contents, e.g.,
392 # "SAFEqx(\'curl \"http://www.fon.hum.uva.nl\"\')")
393 # "SAFEqx(\'wget --quiet --output-document=- \"http://www.fon.hum.uva.nl\"\')")
394 # Be sure to handle <BASE HREF='URL'> and allow BOTH
395 # direct printing GET_URL($URL [, 0]) and extracting the content of
396 # the $URL for post-processing GET_URL($URL, 1).
397 # You get the WHOLE file, including HTML header.
398 # The shell command Use $URL where the URL should go
399 # ('wget', 'snarf' or 'curl', uncomment the one you would like to use)
400 my $GET_URL_shell_command = 'wget --quiet --output-document=- $URL';
401 #my $GET_URL_shell_command = 'snarf $URL -';
402 #my $GET_URL_shell_command = 'curl $URL';
404 sub GET_URL # ($URL, $ValueNotPrint) -> content_of_url
406 my $URL = shift || return;
407 my $ValueNotPrint = shift || 0;
409 # Check URL for illegal characters
410 return "print '<h1>Illegal URL<h1>'\"\n\";" if $URL =~ /[^$FileAllowedChars\%]/;
412 # Include URL in final command
413 my $CurrentCommand = $GET_URL_shell_command;
414 $CurrentCommand =~ s/\$URL/$URL/g;
416 # Print to STDOUT or return a value
417 my $BlockPrint = "print STDOUT ";
418 $BlockPrint = "" if $ValueNotPrint;
420 my $Commands = <<"GETURLCODE";
421 # Get URL
423 my \$Page = "";
425 # Simple, using shell command
426 \$Page = SAFEqx('$CurrentCommand');
428 # Add a BASE tage to the header
429 \$Page =~ s!\\</head!\\<base href='$URL'\\>\\</head!ig unless \$Page =~ m!\\<base!;
431 # Print the URL value, or return it as a value
432 $BlockPrint\$Page;
434 GETURLCODE
435 return $Commands;
438 # As files can get rather large (and binary), you might want to use
439 # some more intelligent reading procedure, e.g.,
440 # Direct Perl
441 # # open(URLHANDLE, '/usr/bin/wget --quiet --output-document=- "$URL"|') || die "wget: \$!";
442 # #open(URLHANDLE, '/usr/bin/snarf "$URL" -|') || die "snarf: \$!";
443 # open(URLHANDLE, '/usr/bin/curl "$URL"|') || die "curl: \$!";
444 # my \$text = "";
445 # while(sysread(URLHANDLE,\$text, 1024) > 0)
447 # \$Page .= \$text;
448 # };
449 # close(URLHANDLE) || die "\$!";
450 # However, this doesn't work with the CGIexecute->evaluate() function.
451 # You get an error: 'No child processes at (eval 16) line 15, <file0> line 8.'
453 # You can forget the next two variables, they are only needed when
454 # you don't want to use a regular file system (i.e., with open)
455 # but use some kind of database/RAM image for accessing (generating)
456 # the data.
458 # Name of the environment variable that contains the file contents
459 # when reading directly from Database/RAM. When this environment variable,
460 # $ENV{$CGI_FILE_CONTENTS}, is not false, no real file will be read.
461 $CGI_FILE_CONTENTS = 'CGI_FILE_CONTENTS';
462 # Uncomment the following if you want to force the use of the data access code
463 # $ENV{$CGI_FILE_CONTENTS} = '-'; # Force use of $ENV{$CGI_DATA_ACCESS_CODE}
465 # Name of the environment variable that contains the RAM access perl
466 # code needed to read additional "files", i.e.,
467 # $ENV{$CGI_FILE_CONTENTS} = eval("\@_=('$file_path'); do{$ENV{$CGI_DATA_ACCESS_CODE}}");
468 # When $ENV{$CGI_FILE_CONTENTS} eq '-', this code is executed to generate the data.
469 $CGI_DATA_ACCESS_CODE = 'CGI_DATA_ACCESS_CODE';
471 # You can, of course, fill this yourself, e.g.,
472 # $ENV{$CGI_DATA_ACCESS_CODE} =
473 # 'open(INPUT, "<$_[0]"); while(<INPUT>){print;};close(INPUT);'
476 # DEBUGGING
478 # Suppress error messages, this can be changed for debugging or error-logging
479 #open(STDERR, "/dev/null"); # (comment out for use in debugging)
481 # SPECIAL: Remove Comments, security, etc. if the command line is
482 # '>CGIscriptor.pl -slim >slimCGIscriptor.pl'
483 $TrimDownCGIscriptor = 1 if $ARGV[0] =~ /^\-slim/i;
485 # If CGIscriptor is used from the command line, the command line
486 # arguments are interpreted as the file (1st) and the Query String (rest).
487 # Get the arguments
488 $ENV{'PATH_INFO'} = shift(@ARGV) unless exists($ENV{'PATH_INFO'}) || grep(/\-\-help/i, @ARGV);
489 $ENV{'QUERY_STRING'} = join("&", @ARGV) unless exists($ENV{'QUERY_STRING'});
492 # Handle bail-outs in a user definable way.
493 # Catch Die and replace it with your own function.
494 # Ends with a call to "die $_[0];"
496 sub dieHandler # ($ErrorCode, "Message", @_) -> DEAD
498 my $ErrorCode = shift;
499 my $ErrorMessage = shift;
501 # Place your own reporting functions here
503 # Now, kill everything (default)
504 print STDERR "$ErrorCode: $ErrorMessage\n";
505 die $ErrorMessage;
509 # End of optional user configuration
510 # (note: there is more non-essential user configuration below)
512 if(grep(/\-\-help/i, @ARGV))
514 print << 'ENDOFPREHELPTEXT2';
516 ###############################################################################
518 # Author and Copyright (c):
519 # Rob van Son, © 1995,1996,1997,1998,1999,2000,2001,2002-2012
520 # NKI-AVL Amsterdam
521 # r.v.son@nki.nl
522 # Institute of Phonetic Sciences & IFOTT/ACLS
523 # University of Amsterdam
524 # Email: R.J.J.H.vanSon@gmail.com
525 # Email: R.J.J.H.vanSon@uva.nl
526 # WWW : http://www.fon.hum.uva.nl/rob/
528 # License for use and disclaimers
530 # CGIscriptor merges plain ASCII HTML files transparantly
531 # with CGI variables, in-line PERL code, shell commands,
532 # and executable scripts in other scripting languages.
534 # This program is free software; you can redistribute it and/or
535 # modify it under the terms of the GNU General Public License
536 # as published by the Free Software Foundation; either version 2
537 # of the License, or (at your option) any later version.
539 # This program is distributed in the hope that it will be useful,
540 # but WITHOUT ANY WARRANTY; without even the implied warranty of
541 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
542 # GNU General Public License for more details.
544 # You should have received a copy of the GNU General Public License
545 # along with this program; if not, write to the Free Software
546 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
549 # Contributors:
550 # Rob van Son (R.J.J.H.vanSon@uva.nl)
551 # Gerd Franke franke@roo.de (designed the <DIV> behaviour)
553 #######################################################
554 ENDOFPREHELPTEXT2
556 #######################################################>>>>>>>>>>Start Remove
558 # You can skip the following code, it is an auto-splice
559 # procedure.
561 # Construct a slimmed down version of CGIscriptor
562 # (i.e., CGIscriptor.pl -slim > slimCGIscriptor.pl)
564 if($TrimDownCGIscriptor)
566 open(CGISCRIPTOR, "<CGIscriptor.pl")
567 || dieHandler(1, "<CGIscriptor.pl not slimmed down: $!\n");
568 my $SKIPtext = 0;
569 my $SKIPComments = 0;
571 while(<CGISCRIPTOR>)
573 my $SKIPline = 0;
575 ++$LineCount;
577 # Start of SKIP text
578 $SKIPtext = 1 if /[\>]{10}Start Remove/;
579 $SKIPComments = 1 if $SKIPtext == 1;
581 # Skip this line?
582 $SKIPline = 1 if $SKIPtext || ($SKIPComments && /^\s*\#/);
584 ++$PrintCount unless $SKIPline;
586 print STDOUT $_ unless $SKIPline;
588 # End of SKIP text ?
589 $SKIPtext = 0 if /[\<]{10}End Remove/;
591 # Ready!
592 print STDERR "\# Printed $PrintCount out of $LineCount lines\n";
593 exit;
596 #######################################################
598 if(grep(/\-\-help/i, @ARGV))
600 print << 'ENDOFHELPTEXT';
602 # HYPE
604 # CGIscriptor merges plain ASCII HTML files transparantly and safely
605 # with CGI variables, in-line PERL code, shell commands, and executable
606 # scripts in many languages (on-line and real-time). It combines the
607 # "ease of use" of HTML files with the versatillity of specialized
608 # scripts and PERL programs. It hides all the specifics and
609 # idiosyncrasies of correct output and CGI coding and naming. Scripts
610 # do not have to be aware of HTML, HTTP, or CGI conventions just as HTML
611 # files can be ignorant of scripts and the associated values. CGIscriptor
612 # complies with the W3C HTML 4.0 recommendations.
613 # In addition to its use as a WWW embeded CGI processor, it can
614 # be used as a command-line document preprocessor (text-filter).
616 # THIS IS HOW IT WORKS
618 # The aim of CGIscriptor is to execute "plain" scripts inside a text file
619 # using any required CGIparameters and environment variables. It
620 # is optimized to transparantly process HTML files inside a WWW server.
621 # The native language is Perl, but many other scripting languages
622 # can be used.
624 # CGIscriptor reads text files from the requested input file (i.e., from
625 # $YOUR_HTML_FILES$PATH_INFO) and writes them to <STDOUT> (i.e., the
626 # client requesting the service) preceded by the obligatory
627 # "Content-type: text/html\n\n" or "Content-type: text/plain\n\n" string
628 # (except for "raw" files which supply their own Content-type message
629 # and only if the SERVER_PROTOCOL supports HTTP, MAIL, or MIME).
631 # When CGIscriptor encounters an embedded script, indicated by an HTML4 tag
633 # <SCRIPT TYPE="text/ssperl" [CGI="$VAR='default value'"] [SRC="ScriptSource"]>
634 # PERL script
635 # </SCRIPT>
637 # or
639 # <SCRIPT TYPE="text/osshell" [CGI="$name='default value'"] [SRC="ScriptSource"]>
640 # OS Shell script
641 # </SCRIPT>
643 # construct (anything between []-brackets is optional, other MIME-types
644 # and scripting languages are supported), the embedded script is removed
645 # and both the contents of the source file (i.e., "do 'ScriptSource'")
646 # AND the script are evaluated as a PERL program (i.e., by eval()),
647 # shell script (i.e., by a "safe" version of `Command`, qx) or an external
648 # interpreter. The output of the eval() function takes the place of the
649 # original <SCRIPT></SCRIPT> construct in the output string. Any CGI
650 # parameters declared by the CGI attribute are available as simple perl
651 # variables, and can subsequently be made available as variables to other
652 # scripting languages (e.g., bash, python, or lisp).
654 # Example: printing "Hello World"
655 # <HTML><HEAD><TITLE>Hello World</TITLE>
656 # <BODY>
657 # <H1><SCRIPT TYPE="text/ssperl">"Hello World"</SCRIPT></H1>
658 # </BODY></HTML>
660 # Save this in a file, hello.html, in the directory you indicated with
661 # $YOUR_HTML_FILES and access http://your_server/SHTML/hello.html
662 # (or to whatever name you use as an alias for CGIscriptor.pl).
663 # This is realy ALL you need to do to get going.
665 # You can use any values that are delivered in CGI-compliant form (i.e.,
666 # the "?name=value" type URL additions) transparently as "$name" variables
667 # in your scripts IFF you have declared them in the CGI attribute of
668 # a META or SCRIPT tag before e.g.:
669 # <META CONTENT="text/ssperl; CGI='$name = `default value`'
670 # [SRC='ScriptSource']">
671 # or
672 # <SCRIPT TYPE="text/ssperl" CGI="$name = 'default value'"
673 # [SRC='ScriptSource']>
674 # After such a 'CGI' attribute, you can use $name as an ordinary PERL variable
675 # (the ScriptSource file is immediately evaluated with "do 'ScriptSource'").
676 # The CGIscriptor script allows you to write ordinary HTML files which will
677 # include dynamic CGI aware (run time) features, such as on-line answers
678 # to specific CGI requests, queries, or the results of calculations.
680 # For example, if you wanted to answer questions of clients, you could write
681 # a Perl program called "Answer.pl" with a function "AnswerQuestion()"
682 # that prints out the answer to requests given as arguments. You then write
683 # an HTML page "Respond.html" containing the following fragment:
685 # <center>
686 # The Answer to your question
687 # <META CONTENT="text/ssperl; CGI='$Question'">
688 # <h3><SCRIPT TYPE="text/ssperl">$Question</SCRIPT></h3>
689 # is
690 # <h3><SCRIPT TYPE="text/ssperl" SRC="./PATH/Answer.pl">
691 # AnswerQuestion($Question);
692 # </SCRIPT></h3>
693 # </center>
694 # <FORM ACTION=Respond.html METHOD=GET>
695 # Next question: <INPUT NAME="Question" TYPE=TEXT SIZE=40><br>
696 # <INPUT TYPE=SUBMIT VALUE="Ask">
697 # </FORM>
699 # The output could look like the following (in HTML-speak):
701 # <CENTER>
702 # The Answer to your question
703 # <h3>What is the capital of the Netherlands?</h3>
704 # is
705 # <h3>Amsterdam</h3>
706 # </CENTER>
707 # <FORM ACTION=Respond.html METHOD=GET>
708 # Next question: <INPUT NAME="Question" TYPE=TEXT SIZE=40><br>
709 # <INPUT TYPE=SUBMIT VALUE="Ask">
711 # Note that the function "Answer.pl" does know nothing about CGI or HTML,
712 # it just prints out answers to arguments. Likewise, the text has no
713 # provisions for scripts or CGI like constructs. Also, it is completely
714 # trivial to extend this "program" to use the "Answer" later in the page
715 # to call up other information or pictures/sounds. The final text never
716 # shows any cue as to what the original "source" looked like, i.e.,
717 # where you store your scripts and how they are called.
719 # There are some extra's. The argument of the files called in a SRC= tag
720 # can access the CGI variables declared in the preceding META tag from
721 # the @ARGV array. Executable files are called as:
722 # `file '$ARGV[0]' ... ` (e.g., `Answer.pl \'$Question\'`;)
723 # The files called from SRC can even be (CGIscriptor) html files which are
724 # processed in-line. Furthermore, the SRC= tag can contain a perl block
725 # that is evaluated. That is,
726 # <META CONTENT="text/ssperl; CGI='$Question' SRC='{$Question}'">
727 # will result in the evaluation of "print do {$Question};" and the VALUE
728 # of $Question will be printed. Note that these "SRC-blocks" can be
729 # preceded and followed by other file names, but only a single block is
730 # allowed in a SRC= tag.
732 # One of the major hassles of dynamic WWW pages is the fact that several
733 # mutually incompatible browsers and platforms must be supported. For example,
734 # the way sound is played automatically is different for Netscape and
735 # Internet Explorer, and for each browser it is different again on
736 # Unix, MacOS, and Windows. Realy dangerous is processing user-supplied
737 # (form-) values to construct email addresses, file names, or database
738 # queries. All Apache WWW-server exploits reported in the media are
739 # based on faulty CGI-scripts that didn't check their user-data properly.
741 # There is no panacee for these problems, but a lot of work and problems
742 # can be saved by allowing easy and transparent control over which
743 # <SCRIPT></SCRIPT> blocks are executed on what CGI-data. CGIscriptor
744 # supplies such a method in the form of a pair of attributes:
745 # IF='...condition..' and UNLESS='...condition...'. When added to a
746 # script tag, the whole block (including the SRC attribute) will be
747 # ignored if the condition is false (IF) or true (UNLESS).
748 # For example, the following block will NOT be evaluated if the value
749 # of the CGI variable FILENAME is NOT a valid filename:
751 # <SCRIPT TYPE='text/ssperl' CGI='$FILENAME'
752 # IF='CGIscriptor::CGIsafeFileName($FILENAME)'>
753 # .....
754 # </SCRIPT>
756 # (the function CGIsafeFileName(String) returns an empty string ("")
757 # if the String argument is not a valid filename).
758 # The UNLESS attribute is the mirror image of IF.
760 # A user manual follows the HTML 4 and security paragraphs below.
762 ##########################################################################
764 # HTML 4 compliance
766 # In general, CGIscriptor.pl complies with the HTML 4 recommendations of
767 # the W3C. This means that any software to manage Web sites will be able
768 # to handle CGIscriptor files, as will web agents.
770 # All script code should be placed between <SCRIPT></SCRIPT> tags, the
771 # script type is indicated with TYPE="mime-type", the LANGUAGE
772 # feature is ignored, and a SRC feature is implemented. All CGI specific
773 # features are delegated to the CGI attribute.
775 # However, the behavior deviates from the W3C recommendations at some
776 # points. Most notably:
777 # 0- The scripts are executed at the server side, invissible to the
778 # client (i.e., the browser)
779 # 1- The mime-types are personal and idiosyncratic, but can be adapted.
780 # 2- Code in the body of a <SCRIPT></SCRIPT> tag-pair is still evaluated
781 # when a SRC feature is present.
782 # 3- The SRC attribute reads a list of files.
783 # 4- The files in a SRC attribute are processed according to file type.
784 # 5- The SRC attribute evaluates inline Perl code.
785 # 6- Processed META, DIV, INS tags are removed from the output
786 # document.
787 # 7- All attributes of the processed META tags, except CONTENT, are ignored
788 # (i.e., deleted from the output).
789 # 8- META tags can be placed ANYWHERE in the document.
790 # 9- Through the SRC feature, META tags can have visible output in the
791 # document.
792 # 10- The CGI attribute that declares CGI parameters, can be used
793 # inside the <SCRIPT> tag.
794 # 11- Use of an extended quote set, i.e., '', "", ``, (), {}, []
795 # and their \-slashed combinations: \'\', \"\", \`\`, \(\),
796 # \{\}, \[\].
797 # 12- IF and UNLESS attributes to <SCRIPT>, <META>, <DIV>, <INS> tags.
798 # 13- <DIV> tags cannot be nested, DIV tags are not
799 # rendered with new-lines.
800 # 14- The XML style <TAG .... /> is recognized and handled correctly.
801 # (i.e., no content is processed)
803 # The reasons for these choices are:
804 # You can still write completely HTML4 compliant documents. CGIscriptor
805 # will not force you to write "deviant" code. However, it allows you to
806 # do so (which is, in fact, just as bad). The prime design principle
807 # was to allow users to include plain Perl code. The code itself should
808 # be "enhancement free". Therefore, extra features were needed to
809 # supply easy access to CGI and Web site components. For security
810 # reasons these have to be declared explicitly. The SRC feature
811 # transparently manages access to external files, especially the safe
812 # use of executable files.
813 # The CGI attribute handles the declarations of external (CGI) variables
814 # in the SCRIPT and META tag's.
815 # EVERYTHING THE CGI ATTRIBUTE AND THE META TAG DO CAN BE DONE INSIDE
816 # A <SCRIPT></SCRIPT> TAG CONSTRUCT.
818 # The reason for the IF, UNLESS, and SRC attributes (and their Perl code
819 # evaluation) were build into the META and SCRIPT tags is part laziness,
820 # part security. The SRC blocks allows more compact documents and easier
821 # debugging. The values of the CGI variables can be immediately screened
822 # for security by IF or UNLESS conditions, and even SRC attributes (e.g.,
823 # email addresses and file names), and a few commands can be called
824 # without having to add another Perl TAG pair. This is especially important
825 # for documents that require the use of other (more restricted) "scripting"
826 # languages and facilities that lag transparent control structures.
828 ##########################################################################
830 # SECURITY
832 # Your WWW site is a few keystrokes away from a few hundred million internet
833 # users. A fair percentage of these users knows more about your computer
834 # than you do. And some of these just might have bad intentions.
836 # To ensure uncompromized operation of your server and platform, several
837 # features are incorporated in CGIscriptor.pl to enhance security.
838 # First of all, you should check the source of this program. No security
839 # measures will help you when you download programs from anonymous sources.
840 # If you want to use THIS file, please make sure that it is uncompromized.
841 # The best way to do this is to contact the source and try to determine
842 # whether s/he is reliable (and accountable).
844 # BE AWARE THAT ANY PROGRAMMER CAN CHANGE THIS PROGRAM IN SUCH A WAY THAT
845 # IT WILL SET THE DOORS TO YOUR SYSTEM WIDE OPEN
847 # I would like to ask any user who finds bugs that could compromise
848 # security to report them to me (and any other bug too,
849 # Email: R.J.J.H.vanSon@uva.nl or ifa@hum.uva.nl).
851 # Security features
853 # 1 Invisibility
854 # The inner workings of the HTML source files are completely hidden
855 # from the client. Only the HTTP header and the ever changing content
856 # of the output distinguish it from the output of a plain, fixed HTML
857 # file. Names, structures, and arguments of the "embedded" scripts
858 # are invisible to the client. Error output is suppressed except
859 # during debugging (user configurable).
861 # 2 Separate directory trees
862 # Directories containing Inline text and script files can reside on
863 # separate trees, distinct from those of the HTTP server. This means
864 # that NEITHER the text files, NOR the script files can be read by
865 # clients other than through CGIscriptor.pl, UNLESS they are
866 # EXPLICITELY made available.
868 # 3 Requests are NEVER "evaluated"
869 # All client supplied values are used as literal values (''-quoted).
870 # Client supplied ''-quotes are ALWAYS removed. Therefore, as long as the
871 # embedded scripts do NOT themselves evaluate these values, clients CANNOT
872 # supply executable commands. Be sure to AVOID scripts like:
874 # <META CONTENT="text/ssperl; CGI='$UserValue'">
875 # <SCRIPT TYPE="text/ssperl">$dir = `ls -1 $UserValue`;</SCRIPT>
877 # These are a recipe for disaster. However, the following quoted
878 # form should be save (but is still not adviced):
880 # <SCRIPT TYPE="text/ssperl">$dir = `ls -1 \'$UserValue\'`;</SCRIPT>
882 # A special function, SAFEqx(), will automatically do exactly this,
883 # e.g., SAFEqx('ls -1 $UserValue') will execute `ls -1 \'$UserValue\'`
884 # with $UserValue interpolated. I recommend to use SAFEqx() instead
885 # of backticks whenever you can. The OS shell scripts inside
887 # <SCRIPT TYPE="text/osshell">ls -1 $UserValue</SCRIPT>
889 # are handeld by SAFEqx and automatically ''-quoted.
891 # 4 Logging of requests
892 # All requests can be logged separate from the Host server. The level of
893 # detail is user configurable: Including or excluding the actual queries.
894 # This allows for the inspection of (im-) proper use.
896 # 5 Access control: Clients
897 # The Remote addresses can be checked against a list of authorized
898 # (i.e., accepted) or non-authorized (i.e., rejected) clients. Both
899 # REMOTE_HOST and REMOTE_ADDR are tested so clients without a proper
900 # HOST name can be (in-) excluded by their IP-address. Client patterns
901 # containing all numbers and dots are considered IP-addresses, all others
902 # domain names. No wild-cards or regexp's are allowed, only partial
903 # addresses.
904 # Matching of names is done from the back to the front (domain first,
905 # i.e., $REMOTE_HOST =~ /\Q$pattern\E$/is), so including ".edu" will
906 # accept or reject all clients from the domain EDU. Matching of
907 # IP-addresses is done from the front to the back (domain first, i.e.,
908 # $REMOTE_ADDR =~ /^\Q$pattern\E/is), so including "128." will (in-)
909 # exclude all clients whose IP-address starts with 128.
910 # There are two special symbols: "-" matches HOSTs with no name and "*"
911 # matches ALL HOSTS/clients.
912 # For those needing more expressional power, lines starting with
913 # "-e" are evaluated by the perl eval() function. E.g.,
914 # '-e $REMOTE_HOST =~ /\.edu$/is;' will accept/reject clients from the
915 # domain '.edu'.
917 # 6 Access control: Files
918 # In principle, CGIscriptor could read ANY file in the directory
919 # tree as discussed in 1. However, for security reasons this is
920 # restricted to text files. It can be made more restricted by entering
921 # a global file pattern (e.g., ".html"). This is done by default.
922 # For each client requesting access, the file pattern(s) can be made
923 # more restrictive than the global pattern by entering client specific
924 # file patterns in the Access Control files (see 5).
925 # For example: if the ACCEPT file contained the lines
926 # * DEMO
927 # .hum.uva.nl LET
928 # 145.18.230.
929 # Then all clients could request paths containing "DEMO" or "demo", e.g.
930 # "/my/demo/file.html" ($PATH_INFO =~ /\Q$pattern\E/), Clients from
931 # *.hum.uva.nl could also request paths containing "LET or "let", e.g.
932 # "/my/let/file.html", and clients from the local cluster
933 # 145.18.230.[0-9]+ could access ALL files.
934 # Again, for those needing more expressional power, lines starting with
935 # "-e" are evaluated. For instance:
936 # '-e $REMOTE_HOST =~ /\.edu$/is && $PATH_INFO =~ m@/DEMO/@is;'
937 # will accept/reject requests for files from the directory "/demo/" from
938 # clients from the domain '.edu'.
940 # Access control: Login
941 # Specific paths can be controlled by Session Tickets which must be
942 # present as a SESSIONTICKET CGI variable in the request. These paths are
943 # defined in %LoginRequiredPatterns as pairs of:
944 # ('regexp' => 'SessionPath\tPasswordPath\tLogin.html').
945 # Session Tickets are stored in a separate directory (SessionPath, e.g.,
946 # ".Session") as files with the exact same name of the SESSIONTICKET CGI
947 # variable. Each Session Ticket file has the following structure:
948 # IPaddress: <127.0.0.1>
949 # AllowedPaths: <^/Private/Name/>
950 # ...
951 # Other content can follow. It is adviced that Session Tickets should be deleted
952 # after some (idle) time. The IP address should be the IP number at login, and
953 # the SESSIONTICKET will be rejected if it is presented from another IP address.
954 # AllowedPaths is a perl regexp. Be careful how they match. Make sure to delimit
955 # the names to prevent access to overlapping names, eg, "^/Private/Rob" will also
956 # match "^/Private/Robert", however, "^/Private/Rob/" will not.
958 # 7 Query length limiting
959 # The length of the Query string can be limited. If CONTENT_LENGTH is larger
960 # than this limit, the request is rejected. The combined length of the
961 # Query string and the POST input is checked before any processing is done.
962 # This will prevent clients from overloading the scripts.
963 # The actual, combined, Query Size is accessible as a variable through
964 # $CGI_Content_Length.
966 # 8 Illegal filenames, paths, and protected directories
967 # One of the primary security concerns in handling CGI-scripts is the
968 # use of "funny" characters in the requests that con scripts in executing
969 # malicious commands. Examples are inserting ';', null bytes, or <newline>
970 # characters in URL's and filenames, followed by executable commands. A
971 # special variable $FileAllowedChars stores a string of all allowed
972 # characters. Any request that translates to a filename with a character
973 # OUTSIDE this set will be rejected.
974 # In general, all (readable files) in the DocumentRoot tree are accessible.
975 # This might not be what you want. For instance, your DocumentRoot directory
976 # might be the working directory of a CVS project and contain sensitive
977 # information (e.g., the password to get to the repository). You can block
978 # access to these subdirectories by adding the corresponding patterns to
979 # the $BlockPathAccess variable. For instance, $BlockPathAccess = '/CVS/'
980 # will block any request that contains '/CVS/' or:
981 # die if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@;
983 # 9 The execution of code blocks can be controlled in a transparent way
984 # by adding IF or UNLESS conditions in the tags themselves. That is,
985 # a simple check of the validity of filenames or email addresses can
986 # be done before any code is executed.
988 ###############################################################################
990 # USER MANUAL (sort of)
992 # CGIscriptor removes embedded scripts, indicated by an HTML 4 type
993 # <SCRIPT TYPE='text/ssperl'> </SCRIPT> or <SCRIPT TYPE='text/osshell'>
994 # </SCRIPT> constructs. CGIscriptor also recognizes XML-type
995 # <SCRIPT TYPE='text/ssperl'/> constructs. These are usefull when
996 # the necessary code is already available in the TAG itself (e.g.,
997 # using external files). The contents of the directive are executed by
998 # the PERL eval() and `` functions (in a separate name space). The
999 # result of the eval() function replaces the <SCRIPT> </SCRIPT> construct
1000 # in the output file. You can use the values that are delivered in
1001 # CGI-compliant form (i.e., the "?name=value&.." type URL additions)
1002 # transparently as "$name" variables in your directives after they are
1003 # defined in a <META> or <SCRIPT> tag.
1004 # If you define the variable "$CGIscriptorResults" in a CGI attribute, all
1005 # subsequent <SCRIPT> and <META> results (including the defining
1006 # tag) will also be pushed onto a stack: @CGIscriptorResults. This list
1007 # behaves like any other, ordinary list and can be manipulated.
1009 # Both GET and POST requests are accepted. These two methods are treated
1010 # equal. Variables, i.e., those values that are determined when a file is
1011 # processed, are indicated in the CGI attribute by $<name> or $<name>=<default>
1012 # in which <name> is the name of the variable and <default> is the value
1013 # used when there is NO current CGI value for <name> (you can use
1014 # white-spaces in $<name>=<default> but really DO make sure that the
1015 # default value is followed by white space or is quoted). Names can contain
1016 # any alphanumeric characters and _ (i.e., names match /[\w]+/).
1017 # If the Content-type: is 'multipart/*', the input is treated as a
1018 # MIME multipart message and automatically delimited. CGI variables get
1019 # the "raw" (i.e., undecoded) body of the corresponding message part.
1021 # Variables can be CGI variables, i.e., those from the QUERY_STRING,
1022 # environment variables, e.g., REMOTE_USER, REMOTE_HOST, or REMOTE_ADDR,
1023 # or predefined values, e.g., CGI_Decoded_QS (The complete, decoded,
1024 # query string), CGI_Content_Length (the length of the decoded query
1025 # string), CGI_Year, CGI_Month, CGI_Time, and CGI_Hour (the current
1026 # date and time).
1028 # All these are available when defined in a CGI attribute. All environment
1029 # variables are accessible as $ENV{'name'}. So, to access the REMOTE_HOST
1030 # and the REMOTE_USER, use, e.g.:
1032 # <SCRIPT TYPE='text/ssperl'>
1033 # ($ENV{'REMOTE_HOST'}||"-")." $ENV{'REMOTE_USER'}"
1034 # </SCRIPT>
1036 # (This will print a "-" if REMOTE_HOST is not known)
1037 # Another way to do this is:
1039 # <META CONTENT="text/ssperl; CGI='$REMOTE_HOST = - $REMOTE_USER'">
1040 # <SCRIPT TYPE='text/ssperl'>"$REMOTE_HOST $REMOTE_USER"</SCRIPT>
1041 # or
1042 # <META CONTENT='text/ssperl; CGI="$REMOTE_HOST = - $REMOTE_USER"
1043 # SRC={"$REMOTE_HOST $REMOTE_USER\n"}'>
1045 # This is possible because ALL environment variables are available as
1046 # CGI variables. The environment variables take precedence over CGI
1047 # names in case of a "name clash". For instance:
1048 # <META CONTENT="text/ssperl; CGI='$HOME' SRC={$HOME}">
1049 # Will print the current HOME directory (environment) irrespective whether
1050 # there is a CGI variable from the query
1051 # (e.g., Where do you live? <INPUT TYPE="TEXT" NAME="HOME">)
1052 # THIS IS A SECURITY FEATURE. It prevents clients from changing
1053 # the values of defined environment variables (e.g., by supplying
1054 # a bogus $REMOTE_ADDR). Although $ENV{} is not changed by the META tags,
1055 # it would make the use of declared variables insecure. You can still
1056 # access CGI variables after a name clash with
1057 # CGIscriptor::CGIparseValue(<name>).
1059 # Some CGI variables are present several times in the query string
1060 # (e.g., from multiple selections). These should be defined as
1061 # @VARIABLENAME=default in the CGI attribute. The list @VARIABLENAME
1062 # will contain ALL VARIABLENAME values from the query, or a single
1063 # default value. If there is an ENVIRONMENT variable of the
1064 # same name, it will be used instead of the default AND the query
1065 # values. The corresponding function is
1066 # CGIscriptor::CGIparseValueList(<name>)
1068 # CGI variables collected in a @VARIABLENAME list are unordered.
1069 # When more structured variables are needed, a hash table can be used.
1070 # A variable defined as %VARIABLE=default will collect all
1071 # CGI-parameters whose name start with 'VARIABLE' in a hash table with
1072 # the remainder of the name as a key. For instance, %PERSON will
1073 # collect PERSONname='John Doe', PERSONbirthdate='01 Jan 00', and
1074 # PERSONspouse='Alice' into a hash table %PERSON such that $PERSON{'spouse'}
1075 # equals 'Alice'. Any default value or environment value will be stored
1076 # under the "" key. If there is an ENVIRONMENT variable of the same name,
1077 # it will be used instead of the default AND the query values. The
1078 # corresponding function is CGIscriptor::CGIparseValueHash(<name>)
1080 # This method of first declaring your environment and CGI variables
1081 # before being able to use them in the scripts might seem somewhat
1082 # clumsy, but it protects you from inadvertedly printing out the values of
1083 # system environment variables when their names coincide with those used
1084 # in the CGI forms. It also prevents "clients" from supplying CGI
1085 # parameter values for your private variables.
1086 # THIS IS A SECURITY FEATURE!
1089 # NON-HTML CONTENT TYPES
1091 # Normally, CGIscriptor prints the standard "Content-type: text/html\n\n"
1092 # message before anything is printed. This has been extended to include
1093 # plain text (.txt) files, for which the Content-type (MIME type)
1094 # 'text/plain' is printed. In all other respects, text files are treated
1095 # as HTML files (this can be switched off by removing '.txt' from the
1096 # $FilePattern variable) . When the content type should be something else,
1097 # e.g., with multipart files, use the $RawFilePattern (.xmr, see also next
1098 # item). CGIscriptor will not print a Content-type message for this file
1099 # type (which must supply its OWN Content-type message). Raw files must
1100 # still conform to the <SCRIPT></SCRIPT> and <META> tag specifications.
1103 # NON-HTML FILES
1105 # CGIscriptor is intended to process HTML and text files only. You can
1106 # create documents of any mime-type on-the-fly using "raw" text files,
1107 # e.g., with the .xmr extension. However, CGIscriptor will not process
1108 # binary files of any type, e.g., pictures or sounds. Given the sheer
1109 # number of formats, I do not have any intention to do so. However,
1110 # an escape route has been provided. You can construct a genuine raw
1111 # (.xmr) text file that contains the perl code to service any file type
1112 # you want. If the global $BinaryMapFile variable contains the path to
1113 # this file (e.g., /BinaryMapFile.xmr), this file will be called
1114 # whenever an unsupported (non-HTML) file type is requested. The path
1115 # to the requested binary file is stored in $ENV('CGI_BINARY_FILE')
1116 # and can be used like any other CGI-variable. Servicing binary files
1117 # then becomes supplying the correct Content-type (e.g., print
1118 # "Content-type: image/jpeg\n\n";) and reading the file and writing it
1119 # to STDOUT (e.g., using sysread() and syswrite()).
1122 # THE META TAG
1124 # All attributes of a META tag are ignored, except the
1125 # CONTENT='text/ssperl; CGI=" ... " [SRC=" ... "]' attribute. The string
1126 # inside the quotes following the CONTENT= indication (white-space is
1127 # ignored, "" '' `` (){}[]-quote pairs are allowed, plus their \ versions)
1128 # MUST start with any of the CGIscriptor mime-types (e.g.: text/ssperl or
1129 # text/osshell) and a comma or semicolon.
1130 # The quoted string following CGI= contains a white-space separated list
1131 # of declarations of the CGI (and Environment) values and default values
1132 # used when no CGI values are supplied by the query string.
1134 # If the default value is a longer string containing special characters,
1135 # possibly spanning several lines, the string must be enclosed in quotes.
1136 # You may use any pair of quotes or brackets from the list '', "", ``, (),
1137 # [], or {} to distinguish default values (or preceded by \, e.g., \(...\)
1138 # is different from (...)). The outermost pair will always be used and any
1139 # other quotes inside the string are considered to be part of the string
1140 # value, e.g.,
1142 # $Value = {['this'
1143 # "and" (this)]}
1144 # will result in $Value getting the default value: ['this'
1145 # "and" (this)]
1146 # (NOTE that the newline is part of the default value!).
1148 # Internally, for defining and initializing CGI (ENV) values, the META
1149 # and SCRIPT tags use the functions "defineCGIvariable($name, $default)"
1150 # (scalars) and "defineCGIvariableList($name, $default)" (lists).
1151 # These functions can be used inside scripts as
1152 # "CGIscriptor::defineCGIvariable($name, $default)" and
1153 # "CGIscriptor::defineCGIvariableList($name, $default)".
1154 # "CGIscriptor::defineCGIvariableHash($name, $default)".
1156 # The CGI attribute will be processed exactly identical when used inside
1157 # the <SCRIPT> tag. However, this use is not according to the
1158 # HTML 4.0 specifications of the W3C.
1161 # THE DIV/INS TAGS
1163 # There is a problem when constructing html files containing
1164 # server-side perl scripts with standard HTML tools. These
1165 # tools will refuse to process any text between <SCRIPT></SCRIPT>
1166 # tags. This is quite annoying when you want to use large
1167 # HTML templates where you will fill in values.
1169 # For this purpose, CGIscriptor will read the neutral
1170 # <DIV CLASS="ssperl" ID="varname"></DIV> or
1171 # <INS CLASS="ssperl" ID="varname"></INS>
1172 # tag (in Cascading Style Sheet manner) Note that
1173 # "varname" has NO '$' before it, it is a bare name.
1174 # Any text between these <DIV ...></DIV> or
1175 # <INS ...></INS>tags will be assigned to '$varname'
1176 # as is (e.g., as a literal).
1177 # No processing or interpolation will be performed.
1178 # There is also NO nesting possible. Do NOT nest a
1179 # </DIV> inside a <DIV></DIV>! Moreover, neither INS nor
1180 # DIV tags do ensure a block structure in the final
1181 # rendering (i.e., no empty lines).
1183 # Note that <DIV CLASS="ssperl" ID="varname"/>
1184 # is handled the XML way. No content is processed,
1185 # but varname is defined, and any SRC directives are
1186 # processed.
1188 # You can use $varname like any other variable name.
1189 # However, $varname is NOT a CGI variable and will be
1190 # completely internal to your script. There is NO
1191 # interaction between $varname and the outside world.
1193 # To interpolate a DIV derived text, you can use:
1194 # $varname =~ s/([\]])/\\\1/g; # Mark ']'-quotes
1195 # $varname = eval("qq[$varname]"); # Interpolate all values
1197 # The DIV tags will process IF, UNLESS, CGI and
1198 # SRC attributes. The SRC files will be pre-pended to the
1199 # body text of the tag. SRC blocks are NOT executed.
1201 # CONDITIONAL PROCESSING: THE 'IF' AND 'UNLESS' ATTRIBUTES
1203 # It is often necessary to include code-blocks that should be executed
1204 # conditionally, e.g., only for certain browsers or operating system.
1205 # Furthermore, quite often sanity and security checks are necessary
1206 # before user (form) data can be processed, e.g., with respect to
1207 # email addresses and filenames.
1209 # Checks added to the code are often difficult to find, interpret or
1210 # maintain and in general mess up the code flow. This kind of confussion
1211 # is dangerous.
1212 # Also, for many of the supported "foreign" scripting languages, adding
1213 # these checks is cumbersome or even impossible.
1215 # As a uniform method for asserting the correctness of "context", two
1216 # attributes are added to all supported tags: IF and UNLESS.
1217 # They both evaluate their value and block execution when the
1218 # result is <FALSE> (IF) or <TRUE> (UNLESS) in Perl, e.g.,
1219 # UNLESS='$NUMBER \> 100;' blocks execution if $NUMBER <= 100. Note that
1220 # the backslash in the '\>' is removed and only used to differentiate
1221 # this conditional '>' from the tag-closing '>'. For symmetry, the
1222 # backslash in '\<' is also removed. Inside these conditionals,
1223 # ~/ and ./ are expanded to their respective directory root paths.
1225 # For example, the following tag will be ignored when the filename is
1226 # invalid:
1228 # <SCRIPT TYPE='text/ssperl' CGI='$FILENAME'
1229 # IF='CGIscriptor::CGIsafeFileName($FILENAME);'>
1230 # ...
1231 # </SCRIPT>
1233 # The IF and UNLESS values must be quoted. The same quotes are supported
1234 # as with the other attributes. The SRC attribute is ignored when IF and
1235 # UNLESS block execution.
1237 # NOTE: 'IF' and 'UNLESS' always evaluate perl code.
1240 # THE MAGIC SOURCE ATTRIBUTE (SRC=)
1242 # The SRC attribute inside tags accepts a list of filenames and URL's
1243 # separated by "," comma's (or ";" semicolons).
1244 # ALL the variable values defined in the CGI attribute are available
1245 # in @ARGV as if the file or block was executed from the command line,
1246 # in the exact order in which they were declared in the preceding CGI
1247 # attribute.
1249 # First, a SRC={}-block will be evaluated as if the code inside the
1250 # block was part of a <SCRIPT></SCRIPT> construct, i.e.,
1251 # "print do { code };'';" or `code` (i.e., SAFEqx('code)).
1252 # Only a single block is evaluated. Note that this is processed less
1253 # efficiently than <SCRIPT> </SCRIPT> blocks. Type of evaluation
1254 # depends on the content-type: Perl for text/ssperl and OS shell for
1255 # text/osshell. For other mime types (scripting languages), anything in
1256 # the source block is put in front of the code block "inside" the tag.
1258 # Second, executable files (i.e., -x filename != 0) are evaluated as:
1259 # print `filename \'$ARGV[0]\' \'$ARGV[1]\' ...`
1260 # That is, you can actually call executables savely from the SRC tag.
1262 # Third, text files that match the file pattern, used by CGIscriptor to
1263 # check whether files should be processed ($FilePattern), are
1264 # processed in-line (i.e., recursively) by CGIscriptor as if the code
1265 # was inserted in the original source file. Recursions, i.e., calling
1266 # a file inside itself, are blocked. If you need them, you have to code
1267 # them explicitely using "main::ProcessFile($file_path)".
1269 # Fourth, Perl text files (i.e., -T filename != 0) are evaluated as:
1270 # "do FileName;'';".
1272 # Last, URL's (i.e., starting with 'HTTP://', 'FTP://', 'GOPHER://',
1273 # 'TELNET://', 'WHOIS://' etc.) are loaded
1274 # and printed. The loading and handling of <BASE> and document header
1275 # is done by a command generated by main::GET_URL($URL [, 0]). You can enter your
1276 # own code (default is curl, wget, or snarf and some post-processing to add a <BASE> tag).
1278 # There are two pseudo-file names: PREFIX and POSTFIX. These implement
1279 # a switch from prefixing the SRC code/files (PREFIX, default) before the
1280 # content of the tag to appending the code after the content of the tag
1281 # (POSTFIX). The switches are done in the order in which the PREFIX and
1282 # POSTFIX labels are encountered. You can mix PREFIX and POSTFIX labels
1283 # in any order with the SRC files. Note that the ORDER of file execution
1284 # is determined for prefixed and postfixed files seperately.
1286 # File paths can be preceded by the URL protocol prefix "file://". This
1287 # is simply STRIPPED from the name.
1289 # Example:
1290 # The request
1291 # "http://cgi-bin/Action_Forms.pl/Statistics/Sign_Test.html?positive=8&negative=22
1292 # will result in printing "${SS_PUB}/Statistics/Sign_Test.html"
1293 # With QUERY_STRING = "positive=8&negative=22"
1295 # on encountering the lines:
1296 # <META CONTENT="text/osshell; CGI='$positive=11 $negative=3'">
1297 # <b><SCRIPT LANGUAGE=PERL TYPE="text/ssperl" SRC="./Statistics/SignTest.pl">
1298 # </SCRIPT></b><p>"
1300 # This line will be processed as:
1301 # "<b>`${SS_SCRIPT}/Statistics/SignTest.pl '8' '22'`</b><p>"
1303 # In which "${SS_SCRIPT}/Statistics/SignTest.pl" is an executable script,
1304 # This line will end up printed as:
1305 # "<b>p <= 0.0161</b><p>"
1307 # Note that the META tag itself will never be printed, and is invisible to
1308 # the outside world.
1310 # The SRC files in a DIV or INS tag will be added (pre-pended) to the body
1311 # of the <DIV></DIV> tag. Blocks are NOT executed! If you do not
1312 # need any content, you can use the <DIV...../> format.
1315 # THE CGISCRIPTOR ROOT DIRECTORIES ~/ AND ./
1317 # Inside <SCRIPT></SCRIPT> tags, filepaths starting
1318 # with "~/" are replaced by "$YOUR_HTML_FILES/", this way files in the
1319 # public directories can be accessed without direct reference to the
1320 # actual paths. Filepaths starting with "./" are replaced by
1321 # "$YOUR_SCRIPTS/" and this should only be used for scripts.
1323 # Note: this replacement can seriously affect Perl scripts. Watch
1324 # out for constructs like $a =~ s/aap\./noot./g, use
1325 # $a =~ s@aap\.@noot.@g instead.
1327 # CGIscriptor.pl will assign the values of $SS_PUB and $SS_SCRIPT
1328 # (i.e., $YOUR_HTML_FILES and $YOUR_SCRIPTS) to the environment variables
1329 # $SS_PUB and $SS_SCRIPT. These can be accessed by the scripts that are
1330 # executed.
1331 # Values not preceded by $, ~/, or ./ are used as literals
1334 # OS SHELL SCRIPT EVALUATION (CONTENT-TYPE=TEXT/OSSHELL)
1336 # OS scripts are executed by a "safe" version of the `` operator (i.e.,
1337 # SAFEqx(), see also below) and any output is printed. CGIscriptor will
1338 # interpolate the script and replace all user-supplied CGI-variables by
1339 # their ''-quoted values (actually, all variables defined in CGI attributes
1340 # are quoted). Other Perl variables are interpolated in a simple fasion,
1341 # i.e., $scalar by their value, @list by join(' ', @list), and %hash by
1342 # their name=value pairs. Complex references, e.g., @$variable, are all
1343 # evaluated in a scalar context. Quotes should be used with care.
1344 # NOTE: the results of the shell script evaluation will appear in the
1345 # @CGIscriptorResults stack just as any other result.
1346 # All occurrences of $@% that should NOT be interpolated must be
1347 # preceeded by a "\". Interpolation can be switched off completely by
1348 # setting $CGIscriptor::NoShellScriptInterpolation = 1
1349 # (set to 0 or undef to switch interpolation on again)
1350 # i.e.,
1351 # <SCRIPT TYPE="text/ssperl">
1352 # $CGIscriptor::NoShellScriptInterpolation = 1;
1353 # </SCRIPT>
1356 # RUN TIME TRANSLATION OF INPUT FILES
1358 # Allows general and global conversions of files using Regular Expressions.
1359 # Very handy (but costly) to rewrite legacy pages to a new format.
1360 # Select files to use it on with
1361 # my $TranslationPaths = 'filepattern';
1362 # This is costly. For efficiency, define:
1363 # $TranslationPaths = ''; when not using translations.
1364 # Accepts general regular expressions: [$pattern, $replacement]
1366 # Define:
1367 # my $TranslationPaths = 'filepattern'; # Pattern matching PATH_INFO
1369 # push(@TranslationTable, ['pattern', 'replacement']);
1370 # e.g. (for Ruby Rails):
1371 # push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
1372 # push(@TranslationTable, ['%>', '</SCRIPT>']);
1374 # Runs:
1375 # my $currentRegExp;
1376 # foreach $currentRegExp (@TranslationTable)
1378 # my ($pattern, $replacement) = @$currentRegExp;
1379 # $$text =~ s!$pattern!$replacement!msg;
1380 # };
1383 # EVALUATION OF OTHER SCRIPTING LANGUAGES
1385 # Adding a MIME-type and an interpreter command to
1386 # %ScriptingLanguages automatically will catch any other
1387 # scripting language in the standard
1388 # <SCRIPT TYPE="[mime]"></SCRIPT> manner.
1389 # E.g., adding: $ScriptingLanguages{'text/sspython'} = 'python';
1390 # will actually execute the folowing code in an HTML page
1391 # (ignore 'REMOTE_HOST' for the moment):
1392 # <SCRIPT TYPE="text/sspython">
1393 # # A Python script
1394 # x = ["A","real","python","script","Hello","World","and", REMOTE_HOST]
1395 # print x[4:8] # Prints the list ["Hello","World","and", REMOTE_HOST]
1396 # </SCRIPT>
1398 # The script code is NOT interpolated by perl, EXCEPT for those
1399 # interpreters that cannot handle variables themselves.
1400 # Currently, several interpreters are pre-installed:
1402 # Perl test - "text/testperl" => 'perl',
1403 # Python - "text/sspython" => 'python',
1404 # Ruby - "text/ssruby" => 'ruby',
1405 # Tcl - "text/sstcl" => 'tcl',
1406 # Awk - "text/ssawk" => 'awk -f-',
1407 # Gnu Lisp - "text/sslisp" => 'rep | tail +5 '.
1408 # "| egrep -v '> |^rep. |^nil\\\$'",
1409 # XLispstat - "text/xlispstat" => 'xlispstat | tail +7 '.
1410 # "| egrep -v '> \\\$|^NIL'",
1411 # Gnu Prolog- "text/ssprolog" => 'gprolog',
1412 # M4 macro's- "text/ssm4" => 'm4',
1413 # Born shell- "text/sh" => 'sh',
1414 # Bash - "text/bash" => 'bash',
1415 # C-shell - "text/csh" => 'csh',
1416 # Korn shell- "text/ksh" => 'ksh',
1417 # Praat - "text/sspraat" => "praat - | sed 's/Praat > //g'",
1418 # R - "text/ssr" => "R --vanilla --slave | sed 's/^[\[0-9\]*] //g'",
1419 # REBOL - "text/ssrebol" =>
1420 # "rebol --quiet|egrep -v '^[> ]* == '|sed 's/^\s*\[> \]* //g'",
1421 # PostgreSQL- "text/postgresql" => 'psql 2>/dev/null',
1422 # (psql)
1424 # Note that the "value" of $ScriptingLanguages{mime} must be a command
1425 # that reads Standard Input and writes to standard output. Any extra
1426 # output of interactive interpreters (banners, echo's, prompts)
1427 # should be removed by piping the output through 'tail', 'grep',
1428 # 'sed', or even 'awk' or 'perl'.
1430 # For access to CGI variables there is a special hashtable:
1431 # %ScriptingCGIvariables.
1432 # CGI variables can be accessed in three ways.
1433 # 1. If the mime type is not present in %ScriptingCGIvariables,
1434 # nothing is done and the script itself should parse the relevant
1435 # environment variables.
1436 # 2. If the mime type IS present in %ScriptingCGIvariables, but it's
1437 # value is empty, e.g., $ScriptingCGIvariables{"text/sspraat"} = '';,
1438 # the script text is interpolated by perl. That is, all $var, @array,
1439 # %hash, and \-slashes are replaced by their respective values.
1440 # 3. In all other cases, the CGI and environment variables are added
1441 # in front of the script according to the format stored in
1442 # %ScriptingCGIvariables. That is, the following (pseudo-)code is
1443 # executed for each CGI- or Environment variable defined in the CGI-tag:
1444 # printf(INTERPRETER, $ScriptingCGIvariables{$mime}, $CGI_NAME, $CGI_VALUE);
1446 # For instance, "text/testperl" => '$%s = "%s";' defines variable
1447 # definitions for Perl, and "text/sspython" => '%s = "%s"' for Python
1448 # (note that these definitions are not save, the real ones contain '-quotes).
1450 # THIS WILL NOT WORK FOR @VARIABLES, the (empty) $VARIABLES will be used
1451 # instead.
1453 # The $CGI_VALUE parameters are "shrubed" of all control characters
1454 # and quotes (by &shrubCGIparameter($CGI_VALUE)) for the options 2 and 3.
1455 # Control characters are replaced by \0<octal ascii value> (the exception
1456 # is \015, the newline, which is replaced by \n) and quotes
1457 # and backslashes by their HTML character
1458 # value (' -> &#39; ` -> &#96; " -> &quot; \ -> &#92; & -> &amper;).
1459 # For example:
1460 # if a client would supply the string value (in standard perl, e.g.,
1461 # \n means <newline>)
1462 # "/dev/null';\nrm -rf *;\necho '"
1463 # it would be processed as
1464 # '/dev/null&#39;;\nrm -rf *;\necho &#39;'
1465 # (e.g., sh or bash would process the latter more according to your
1466 # intentions).
1467 # If your intepreter requires different protection measures, you will
1468 # have to supply these in %main::SHRUBcharacterTR (string => translation),
1469 # e.g., $SHRUBcharacterTR{"\'"} = "&#39;";
1471 # Currently, the following definitions are used:
1472 # %ScriptingCGIvariables = (
1473 # "text/testperl" => "\$\%s = '\%s';", # Perl $VAR = 'value' (for testing)
1474 # "text/sspython" => "\%s = '\%s'", # Python VAR = 'value'
1475 # "text/ssruby" => '@%s = "%s"', # Ruby @VAR = "value"
1476 # "text/sstcl" => 'set %s "%s"', # TCL set VAR "value"
1477 # "text/ssawk" => '%s = "%s";', # Awk VAR = "value";
1478 # "text/sslisp" => '(setq %s "%s")', # Gnu lisp (rep) (setq VAR "value")
1479 # "text/xlispstat" => '(setq %s "%s")', # Xlispstat (setq VAR "value")
1480 # "text/ssprolog" => '', # Gnu prolog (interpolated)
1481 # "text/ssm4" => "define(`\%s', `\%s')", # M4 macro's define(`VAR', `value')
1482 # "text/sh" => "\%s='\%s';", # Born shell VAR='value';
1483 # "text/bash" => "\%s='\%s';", # Born again shell VAR='value';
1484 # "text/csh" => "\$\%s = '\%s';", # C shell $VAR = 'value';
1485 # "text/ksh" => "\$\%s = '\%s';", # Korn shell $VAR = 'value';
1486 # "text/sspraat" => '', # Praat (interpolation)
1487 # "text/ssr" => '%s <- "%s";', # R VAR <- "value";
1488 # "text/ssrebol" => '%s: copy "%s"', # REBOL VAR: copy "value"
1489 # "text/postgresql" => '', # PostgreSQL (interpolation)
1490 # "" => ""
1491 # );
1493 # Four tables allow fine-tuning of interpreter with code that should be
1494 # added before and after each code block:
1496 # Code added before each script block
1497 # %ScriptingPrefix = (
1498 # "text/testperl" => "\# Prefix Code;", # Perl script testing
1499 # "text/ssm4" => 'divert(0)' # M4 macro's (open STDOUT)
1500 # );
1501 # Code added at the end of each script block
1502 # %ScriptingPostfix = (
1503 # "text/testperl" => "\# Postfix Code;", # Perl script testing
1504 # "text/ssm4" => 'divert(-1)' # M4 macro's (block STDOUT)
1505 # );
1506 # Initialization code, inserted directly after opening (NEVER interpolated)
1507 # %ScriptingInitialization = (
1508 # "text/testperl" => "\# Initialization Code;", # Perl script testing
1509 # "text/ssawk" => 'BEGIN {', # Server Side awk scripts
1510 # "text/sslisp" => '(prog1 nil ', # Lisp (rep)
1511 # "text/xlispstat" => '(prog1 nil ', # xlispstat
1512 # "text/ssm4" => 'divert(-1)' # M4 macro's (block STDOUT)
1513 # );
1514 # Cleanup code, inserted before closing (NEVER interpolated)
1515 # %ScriptingCleanup = (
1516 # "text/testperl" => "\# Cleanup Code;", # Perl script testing
1517 # "text/sspraat" => 'Quit',
1518 # "text/ssawk" => '};', # Server Side awk scripts
1519 # "text/sslisp" => '(princ "\n" standard-output)).' # Closing print to rep
1520 # "text/xlispstat" => '(print "" *standard-output*)).' # Closing print to xlispstat
1521 # "text/postgresql" => '\q',
1522 # );
1525 # The SRC attribute is NOT magical for these interpreters. In short,
1526 # all code inside a source file or {} block is written verbattim
1527 # to the interpreter. No (pre-)processing or executional magic is done.
1529 # A serious shortcomming of the described mechanism for handling other
1530 # (scripting) languages, with respect to standard perl scripts
1531 # (i.e., 'text/ssperl'), is that the code is only executed when
1532 # the pipe to the interpreter is closed. So the pipe has to be
1533 # closed at the end of each block. This means that the state of the
1534 # interpreter (e.g., all variable values) is lost after the closing of
1535 # the next </SCRIPT> tag. The standard 'text/ssperl' scripts retain
1536 # all values and definitions.
1538 # APPLICATION MIME TYPES
1540 # To ease some important auxilliary functions from within the
1541 # html pages I have added them as MIME types. This uses
1542 # the mechanism that is also used for the evaluation of
1543 # other scripting languages, with interpolation of CGI
1544 # parameters (and perl-variables). Actually, these are
1545 # defined exactly like any other "scripting language".
1547 # text/ssdisplay: display some (HTML) text with interpolated
1548 # variables (uses `cat`).
1549 # text/sslogfile: write (append) the interpolated block to the file
1550 # mentioned on the first, non-empty line
1551 # (the filename can be preceded by 'File: ',
1552 # note the space after the ':',
1553 # uses `awk .... >> <filename>`).
1554 # text/ssmailto: send email directly from within the script block.
1555 # The first line of the body must contain
1556 # To:Name@Valid.Email.Address
1557 # (note: NO space between 'To:' and the email adres)
1558 # For other options see the mailto man pages.
1559 # It works by directly sending the (interpolated)
1560 # content of the text block to a pipe into the
1561 # Linux program 'mailto'.
1563 # In these script blocks, all Perl variables will be
1564 # replaced by their values. All CGI variables are cleaned before
1565 # they are used. These CGI variables must be redefined with a
1566 # CGI attribute to restore their original values.
1567 # In general, this will be more secure than constructing
1568 # e.g., your own email command lines. For instance, Mailto will
1569 # not execute any odd (forged) email addres, but just stops
1570 # when the email address is invalid and awk will construct
1571 # any filename you give it (e.g. '<File;rm\\\040-f' would end up
1572 # as a "valid" UNIX filename). Note that it will also gladly
1573 # store this file anywhere (/../../../etc/passwd will work!).
1574 # Use the CGIscriptor::CGIsafeFileName() function to clean the
1575 # filename.
1577 # SHELL SCRIPT PIPING
1579 # If a shell script starts with the UNIX style "#! <shell command> \n"
1580 # line, the rest of the shell script is piped into the indicated command,
1581 # i.e.,
1582 # open(COMMAND, "| command");print COMMAND $RestOfScript;
1584 # In many ways this is equivalent to the MIME-type profiling for
1585 # evaluating other scripting languages as discussed above. The
1586 # difference breaks down to convenience. Shell script piping is a
1587 # "raw" implementation. It allows you to control all aspects of
1588 # execution. Using the MIME-type profiling is easier, but has a
1589 # lot of defaults built in that might get in the way. Another
1590 # difference is that shell script piping uses the SAFEqx() function,
1591 # and MIME-type profiling does not.
1593 # Execution of shell scripts is under the control of the Perl Script blocks
1594 # in the document. The MIME-type triggered execution of <SCRIPT></SCRIPT>
1595 # blocks can be simulated easily. You can switch to a different shell,
1596 # e.g. tcl, completely by executing the following Perl commands inside
1597 # your document:
1599 # <SCRIPT TYPE="text/ssperl">
1600 # $main::ShellScriptContentType = "text/ssTcl"; # Yes, you can do this
1601 # CGIscriptor::RedirectShellScript('/usr/bin/tcl'); # Pipe to Tcl
1602 # $CGIscriptor::NoShellScriptInterpolation = 1;
1603 # </SCRIPT>
1605 # After this script is executed, CGIscriptor will parse scripts of
1606 # TYPE="text/ssTcl" and pipe their contents into '|/usr/bin/tcl'
1607 # WITHOUT interpolation (i.e., NO substitution of Perl variables).
1608 # The crucial function is :
1609 # CGIscriptor::RedirectShellScript('/usr/bin/tcl')
1610 # After executing this function, all shell scripts AND all
1611 # calls to SAFEqx()) are piped into '|/usr/bin/tcl'. If the argument
1612 # of RedirectShellScript is empty, e.g., '', the original (default)
1613 # value is reset.
1615 # The standard output, STDOUT, of any pipe is send to the client.
1616 # Currently, you should be carefull with quotes in such a piped script.
1617 # The results of a pipe is NOT put on the @CGIscriptorResults stack.
1618 # As a result, you do not have access to the output of any piped (#!)
1619 # process! If you want such access, execute
1620 # <SCRIPT TYPE="text/osshell">echo "script"|command</SCRIPT>
1621 # or
1622 # <SCRIPT TYPE="text/ssperl">
1623 # $resultvar = SAFEqx('echo "script"|command');
1624 # </SCRIPT>.
1626 # Safety is never complete. Although SAFEqx() prevents some of the
1627 # most obvious forms of attacks and security slips, it cannot prevent
1628 # them all. Especially, complex combinations of quotes and intricate
1629 # variable references cannot be handled safely by SAFEqx. So be on
1630 # guard.
1633 # PERL CODE EVALUATION (CONTENT-TYPE=TEXT/SSPERL)
1635 # All PERL scripts are evaluated inside a PERL package. This package
1636 # has a separate name space. This isolated name space protects the
1637 # CGIscriptor.pl program against interference from user code. However,
1638 # some variables, e.g., $_, are global and cannot be protected. You are
1639 # advised NOT to use such global variable names. You CAN write
1640 # directives that directly access the variables in the main program.
1641 # You do so at your own risk (there is definitely enough rope available
1642 # to hang yourself). The behavior of CGIscriptor becomes undefined if
1643 # you change its private variables during run time. The PERL code
1644 # directives are used as in:
1645 # $Result = eval($directive); print $Result;'';
1646 # ($directive contains all text between <SCRIPT></SCRIPT>).
1647 # That is, the <directive> is treated as ''-quoted string and
1648 # the result is treated as a scalar. To prevent the VALUE of the code
1649 # block from appearing on the client's screen, end the directive with
1650 # ';""</SCRIPT>'. Evaluated directives return the last value, just as
1651 # eval(), blocks, and subroutines, but only as a scalar.
1653 # IMPORTANT: All PERL variables defined are persistent. Each <SCRIPT>
1654 # </SCRIPT> construct is evaluated as a {}-block with associated scope
1655 # (e.g., for "my $var;" declarations). This means that values assigned
1656 # to a PERL variable can be used throughout the document unless they
1657 # were declared with "my". The following will actually work as intended
1658 # (note that the ``-quotes in this example are NOT evaluated, but used
1659 # as simple quotes):
1661 # <META CONTENT="text/ssperl; CGI=`$String='abcdefg'`">
1662 # anything ...
1663 # <SCRIPT TYPE=text/ssperl>@List = split('', $String);</SCRIPT>
1664 # anything ...
1665 # <SCRIPT TYPE=text/ssperl>join(", ", @List[1..$#List]);</SCRIPT>
1667 # The first <SCRIPT TYPE=text/ssperl></SCRIPT> construct will return the
1668 # value scalar(@List), the second <SCRIPT TYPE=text/ssperl></SCRIPT>
1669 # construct will print the elements of $String separated by commas, leaving
1670 # out the first element, i.e., $List[0].
1672 # Another warning: './' and '~/' are ALWAYS replaced by the values of
1673 # $YOUR_SCRIPTS and $YOUR_HTML_FILES, respectively . This can interfere
1674 # with pattern matching, e.g., $a =~ s/aap\./noot\./g will result in the
1675 # evaluations of $a =~ s/aap\\${YOUR_SCRIPTS}noot\\${YOUR_SCRIPTS}g. Use
1676 # s@<regexp>.@<replacement>.@g instead.
1679 # USER EXTENSIONS
1681 # A CGIscriptor package is attached to the bottom of this file. With
1682 # this package you can personalize your version of CGIscriptor by
1683 # including often used perl routines. These subroutines can be
1684 # accessed by prefixing their names with CGIscriptor::, e.g.,
1685 # <SCRIPT LANGUAGE=PERL TYPE=text/ssperl>
1686 # CGIscriptor::ListDocs("/Books/*") # List all documents in /Books
1687 # </SCRIPT>
1688 # It already contains some useful subroutines for Document Management.
1689 # As it is a separate package, it has its own namespace, isolated from
1690 # both the evaluator and the main program. To access variables from
1691 # the document <SCRIPT></SCRIPT> blocks, use $CGIexecute::<var>.
1693 # Currently, the following functions are implemented
1694 # (precede them with CGIscriptor::, see below for more information)
1695 # - SAFEqx ('String') -> result of qx/"String"/ # Safe application of ``-quotes
1696 # Is used by text/osshell Shell scripts. Protects all CGI
1697 # (client-supplied) values with single quotes before executing the
1698 # commands (one of the few functions that also works WITHOUT CGIscriptor::
1699 # in front)
1700 # - defineCGIvariable ($name[, $default) -> 0/1 (i.e., failure/success)
1701 # Is used by the META tag to define and initialize CGI and ENV
1702 # name/value pairs. Tries to obtain an initializing value from (in order):
1703 # $ENV{$name}
1704 # The Query string
1705 # The default value given (if any)
1706 # (one of the few functions that also works WITHOUT CGIscriptor::
1707 # in front)
1708 # - CGIsafeFileName (FileName) -> FileName or ""
1709 # Check a string against the Allowed File Characters (and ../ /..).
1710 # Returns an empty string for unsafe filenames.
1711 # - CGIsafeEmailAddress (Email) -> Email or ""
1712 # Check a string against correct email address pattern.
1713 # Returns an empty string for unsafe addresses.
1714 # - RedirectShellScript ('CommandString') -> FILEHANDLER or undef
1715 # Open a named PIPE for SAFEqx to receive ALL shell scripts
1716 # - URLdecode (URL encoded string) -> plain string # Decode URL encoded argument
1717 # - URLencode (plain string) -> URL encoded string # Encode argument as URL code
1718 # - CGIparseValue (ValueName [, URL_encoded_QueryString]) -> Decoded value
1719 # Extract the value of a CGI variable from the global or a private
1720 # URL-encoded query (multipart POST raw, NOT decoded)
1721 # - CGIparseValueList (ValueName [, URL_encoded_QueryString])
1722 # -> List of decoded values
1723 # As CGIparseValue, but now assembles ALL values of ValueName into a list.
1724 # - CGIparseHeader (ValueName [, URL_encoded_QueryString]) -> Header
1725 # Extract the header of a multipart CGI variable from the global or a private
1726 # URL-encoded query ("" when not a multipart variable or absent)
1727 # - CGIparseForm ([URL_encoded_QueryString]) -> Decoded Form
1728 # Decode the complete global URL-encoded query or a private
1729 # URL-encoded query
1730 # - read_url(URL) # Returns the page from URL (with added base tag, both FTP and HTTP)
1731 # Uses main::GET_URL(URL, 1) to get at the command to read the URL.
1732 # - BrowseDirs(RootDirectory [, Pattern, Startdir, CGIname]) # print browsable directories
1733 # - ListDocs(Pattern [,ListType]) # Prints a nested HTML directory listing of
1734 # all documents, e.g., ListDocs("/*", "dl");.
1735 # - HTMLdocTree(Pattern [,ListType]) # Prints a nested HTML listing of all
1736 # local links starting from a given document, e.g.,
1737 # HTMLdocTree("/Welcome.html", "dl");
1740 # THE RESULTS STACK: @CGISCRIPTORRESULTS
1742 # If the pseudo-variable "$CGIscriptorResults" has been defined in a
1743 # META tag, all subsequent SCRIPT and META results are pushed
1744 # on the @CGIscriptorResults stack. This list is just another
1745 # Perl variable and can be used and manipulated like any other list.
1746 # $CGIscriptorResults[-1] is always the last result.
1747 # This is only of limited use, e.g., to use the results of an OS shell
1748 # script inside a Perl script. Will NOT contain the results of Pipes
1749 # or code from MIME-profiling.
1752 # USEFULL CGI PREDEFINED VARIABLES (DO NOT ASSIGN TO THESE)
1754 # $CGI_HOME - The DocumentRoot directory
1755 # $CGI_Decoded_QS - The complete decoded Query String
1756 # $CGI_Content_Length - The ACTUAL length of the Query String
1757 # $CGI_Date - Current date and time
1758 # $CGI_Year $CGI_Month $CGI_Day $CGI_WeekDay - Current Date
1759 # $CGI_Time - Current Time
1760 # $CGI_Hour $CGI_Minutes $CGI_Seconds - Current Time, split
1761 # GMT Date/Time:
1762 # $CGI_GMTYear $CGI_GMTMonth $CGI_GMTDay $CGI_GMTWeekDay $CGI_GMTYearDay
1763 # $CGI_GMTHour $CGI_GMTMinutes $CGI_GMTSeconds $CGI_GMTisdst
1766 # USEFULL CGI ENVIRONMENT VARIABLES
1768 # Variables accessible (in APACHE) as $ENV{<name>}
1769 # (see: "http://hoohoo.ncsa.uiuc.edu/cgi/env.html"):
1771 # QUERY_STRING - The query part of URL, that is, everything that follows the
1772 # question mark.
1773 # PATH_INFO - Extra path information given after the script name
1774 # PATH_TRANSLATED - Extra pathinfo translated through the rule system.
1775 # (This doesn't always make sense.)
1776 # REMOTE_USER - If the server supports user authentication, and the script is
1777 # protected, this is the username they have authenticated as.
1778 # REMOTE_HOST - The hostname making the request. If the server does not have
1779 # this information, it should set REMOTE_ADDR and leave this unset
1780 # REMOTE_ADDR - The IP address of the remote host making the request.
1781 # REMOTE_IDENT - If the HTTP server supports RFC 931 identification, then this
1782 # variable will be set to the remote user name retrieved from
1783 # the server. Usage of this variable should be limited to logging
1784 # only.
1785 # AUTH_TYPE - If the server supports user authentication, and the script
1786 # is protected, this is the protocol-specific authentication
1787 # method used to validate the user.
1788 # CONTENT_TYPE - For queries which have attached information, such as HTTP
1789 # POST and PUT, this is the content type of the data.
1790 # CONTENT_LENGTH - The length of the said content as given by the client.
1791 # SERVER_SOFTWARE - The name and version of the information server software
1792 # answering the request (and running the gateway).
1793 # Format: name/version
1794 # SERVER_NAME - The server's hostname, DNS alias, or IP address as it
1795 # would appear in self-referencing URLs
1796 # GATEWAY_INTERFACE - The revision of the CGI specification to which this
1797 # server complies. Format: CGI/revision
1798 # SERVER_PROTOCOL - The name and revision of the information protocol this
1799 # request came in with. Format: protocol/revision
1800 # SERVER_PORT - The port number to which the request was sent.
1801 # REQUEST_METHOD - The method with which the request was made. For HTTP,
1802 # this is "GET", "HEAD", "POST", etc.
1803 # SCRIPT_NAME - A virtual path to the script being executed, used for
1804 # self-referencing URLs.
1805 # HTTP_ACCEPT - The MIME types which the client will accept, as given by
1806 # HTTP headers. Other protocols may need to get this
1807 # information from elsewhere. Each item in this list should
1808 # be separated by commas as per the HTTP spec.
1809 # Format: type/subtype, type/subtype
1810 # HTTP_USER_AGENT - The browser the client is using to send the request.
1811 # General format: software/version library/version.
1814 # INSTRUCTIONS FOR RUNNING CGIscriptor ON UNIX
1816 # CGIscriptor.pl will run on any WWW server that runs Perl scripts, just add
1817 # a line like the following to your srm.conf file (Apache example):
1819 # ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
1821 # URL's that refer to http://www.your.address/SHTML/... will now be handled
1822 # by CGIscriptor.pl, which can use a private directory tree (default is the
1823 # DOCUMENT_ROOT directory tree, but it can be anywhere, see manual).
1825 # If your hosting ISP won't let you add ScriptAlias lines you can use
1826 # the following "rewrite"-based "scriptalias" in .htaccess
1827 # (from Gerd Franke)
1829 # RewriteEngine On
1830 # RewriteBase /
1831 # RewriteCond %{REQUEST_FILENAME} .html$
1832 # RewriteCond %{SCRIPT_FILENAME} !cgiscriptor.pl$
1833 # RewriteCond %{REQUEST_FILENAME} -f
1834 # RewriteRule ^(.*)$ /cgi-bin/cgiscriptor.pl/$1?&%{QUERY_STRING}
1836 # Everthing with the extension ".html" and not including "cgiscriptor.pl"
1837 # in the url and where the file "path/filename.html" exists is redirected
1838 # to "/cgi.bin/cgiscriptor.pl/path/filename.html?query".
1839 # The user configuration should get the same path-level as the
1840 # .htaccess-file:
1842 # # Just enter your own directory path here
1843 # $YOUR_HTML_FILES = "$ENV{'DOCUMENT_ROOT'}";
1844 # # use DOCUMENT_ROOT only, if .htaccess lies in the root-directory.
1846 # If this .htaccess goes in a specific directory, the path to this
1847 # directory must be added to $ENV{'DOCUMENT_ROOT'}.
1849 # The CGIscriptor file contains all documentation as comments. These
1850 # comments can be removed to speed up loading (e.g., `egrep -v '^#'
1851 # CGIscriptor.pl` > leanScriptor.pl). A bare bones version of
1852 # CGIscriptor.pl, lacking documentation, most comments, access control,
1853 # example functions etc. (but still with the copyright notice and some
1854 # minimal documentation) can be obtained by calling CGIscriptor.pl on the
1855 # command line with the '-slim' command line argument, e.g.,
1857 # >CGIscriptor.pl -slim > slimCGIscriptor.pl
1859 # CGIscriptor.pl can be run from the command line with <path> and <query> as
1860 # arguments, as `CGIscriptor.pl <path> <query>`, inside a perl script
1861 # with 'do CGIscriptor.pl' after setting $ENV{PATH_INFO}
1862 # and $ENV{QUERY_STRING}, or CGIscriptor.pl can be loaded with 'require
1863 # "/real-path/CGIscriptor.pl"'. In the latter case, requests are processed
1864 # by 'Handle_Request();' (again after setting $ENV{PATH_INFO} and
1865 # $ENV{QUERY_STRING}).
1867 # Using the command line execution option, CGIscriptor.pl can be used as a
1868 # document (meta-)preprocessor. If the first argument is '-', STDIN will be read.
1869 # For example:
1871 # > cat MyDynamicDocument.html | CGIscriptor.pl - '[QueryString]' > MyStaticFile.html
1873 # This command line will produce a STATIC file with the DYNAMIC content of
1874 # MyDocument.html "interpolated".
1876 # This option would be very dangerous when available over the internet.
1877 # If someone could sneak a 'http://www.your.domain/-' URL past your
1878 # server, CGIscriptor could EXECUTE any POSTED contend.
1879 # Therefore, for security reasons, STDIN will NOT be read
1880 # if ANY of the HTTP server environment variables is set (e.g.,
1881 # SERVER_PORT, SERVER_PROTOCOL, SERVER_NAME, SERVER_SOFTWARE,
1882 # HTTP_USER_AGENT, REMOTE_ADDR).
1883 # This block on processing STDIN on HTTP requests can be lifted by setting
1884 # $BLOCK_STDIN_HTTP_REQUEST = 0;
1885 # In the security configuration. Butbe carefull when doing this.
1886 # It can be very dangerous.
1888 # Running demo's and more information can be found at
1889 # http://www.fon.hum.uva.nl/~rob/OSS/OSS.html
1891 # A pocket-size HTTP daemon, CGIservlet.pl, is available from my web site or
1892 # CPAN that can use CGIscriptor.pl as the base of a µWWW server and
1893 # demonstrates its use.
1896 # PROCESSING NON-FILESYSTEM DATA
1898 # Normally, HTTP (WWW) requests map onto file that can be accessed
1899 # using the perl open() function. That is, the web server runs on top of
1900 # some directory structure. However, we can envission (and put to good
1901 # use) other systems that do not use a normal file system. The whole CGI
1902 # was developed to make dynamic document generation possible.
1904 # A special case is where we want to have it both: A normal web server
1905 # with normal "file data", but not a normal files system. For instance,
1906 # we want or normal Web Site to run directly from a RAM hash table or
1907 # other database, instead of from disk. But we do NOT want to code the
1908 # whole site structure in CGI.
1910 # CGIscriptor can do this. If the web server fills an environment variable
1911 # $ENV{'CGI_FILE_CONTENT'} with the content of the "file", then the content
1912 # of this variable is processed instead of opening a file. If this environment
1913 # variable has the value '-', the content of another environment variable,
1914 # $ENV{'CGI_DATA_ACCESS_CODE'} is executed as:
1915 # eval("\@_ = ($file_path); do {$ENV{'CGI_DATA_ACCESS_CODE'}};")
1916 # and the result is processed as if it was the content of the requested
1917 # file.
1918 # (actually, the names of the environment variables are user configurable,
1919 # they are stored in the local variables $CGI_FILE_CONTENT and
1920 # $CGI_DATA_ACCESS_CODE)
1922 # When using this mechanism, the SRC attribute mechanism will only partially work.
1923 # Only the "recursive" calls to CGIscriptor (the ProcessFile() function)
1924 # will work, the automagical execution of SRC files won't. (In this case,
1925 # the SRC attribute won't work either for other scripting languages)
1928 # NON-UNIX PLATFORMS
1930 # CGIscriptor.pl was mainly developed and tested on UNIX. However, as I
1931 # coded part of the time on an Apple Macintosh under MacPerl, I made sure
1932 # CGIscriptor did run under MacPerl (with command line options). But only
1933 # as an independend script, not as part of a HTTP server. I have used it
1934 # under Apache in Windows XP.
1936 ENDOFHELPTEXT
1937 exit;
1939 ###############################################################################
1941 # SECURITY CONFIGURATION
1943 # Special configurations related to SECURITY
1944 # (i.e., optional, see also environment variables below)
1946 # LOGGING
1947 # Log Clients and the requested paths (Redundant when loging Queries)
1949 $ClientLog = "./Client.log"; # (uncomment for use)
1951 # Format: Localtime | REMOTE_USER REMOTE_IDENT REMOTE_HOST REMOTE_ADDRESS \
1952 # PATH_INFO CONTENT_LENGTH (actually, the real query+post length)
1954 # Log Clients and the queries, the CGIQUERYDECODE is required if you want
1955 # to log queries. If you log Queries, the loging of Clients is redundant
1956 # (note that queries can be quite long, so this might not be a good idea)
1958 #$QueryLog = "./Query.log"; # (uncomment for use)
1960 # ACCESS CONTROL
1961 # the Access files should contain Hostnames or IP addresses,
1962 # i.e. REMOTE_HOST or REMOTE_ADDR, each on a separate line
1963 # optionally followed by one ore more file patterns, e.g., "edu /DEMO".
1964 # Matching is done "domain first". For example ".edu" matches all
1965 # clients whose "name" ends in ".edu" or ".EDU". The file pattern
1966 # "/DEMO" matches all paths that contain the strings "/DEMO" or "/demo"
1967 # (both matchings are done case-insensitive).
1968 # The name special symbol "-" matches ALL clients who do not supply a
1969 # REMOTE_HOST name, "*" matches all clients.
1970 # Lines starting with '-e' are evaluated. A non-zero return value indicates
1971 # a match. You can use $REMOTE_HOST, $REMOTE_ADDR, and $PATH_INFO. These
1972 # lines are evaluated in the program's own name-space. So DO NOT assign to
1973 # variables.
1975 # Accept the following users (remove comment # and adapt filename)
1976 $CGI_Accept = -s "$YOUR_SCRIPTS/ACCEPT.lis" ? "$YOUR_SCRIPTS/ACCEPT.lis" : ''; # (uncomment for use)
1978 # Reject requests from the following users (remove comment # and
1979 # adapt filename, this is only of limited use)
1980 $CGI_Reject = -s "$YOUR_SCRIPTS/REJECT.lis" ? "$YOUR_SCRIPTS/REJECT.lis" : ''; # (uncomment for use)
1982 # Empty lines or comment lines starting with '#' are ignored in both
1983 # $CGI_Accept and $CGI_Reject.
1985 # Block STDIN (i.e., '-') requests when servicing an HTTP request
1986 # Comment this out if you realy want to use STDIN in an on-line web server
1987 $BLOCK_STDIN_HTTP_REQUEST = 1;
1990 # End of security configuration
1992 ##################################################<<<<<<<<<<End Remove
1994 # PARSING CGI VALUES FROM THE QUERY STRING (USER CONFIGURABLE)
1996 # The CGI parse commands. These commands extract the values of the
1997 # CGI variables from the URL encoded Query String.
1998 # If you want to use your own CGI decoders, you can call them here
1999 # instead, using your own PATH and commenting/uncommenting the
2000 # appropriate lines
2002 # CGI parse command for individual values
2003 # (if $List > 0, returns a list value, if $List < 0, a hash table, this is optional)
2004 sub YOUR_CGIPARSE # ($Name [, $List]) -> Decoded value
2006 my $Name = shift;
2007 my $List = shift || 0;
2008 # Use one of the following by uncommenting
2009 if(!$List) # Simple value
2011 return CGIscriptor::CGIparseValue($Name) ;
2013 elsif($List < 0) # Hash tables
2015 return CGIscriptor::CGIparseValueHash($Name); # Defined in CGIscriptor below
2017 else # Lists
2019 return CGIscriptor::CGIparseValueList($Name); # Defined in CGIscriptor below
2022 # return `/PATH/cgiparse -value $Name`; # Shell commands
2023 # require "/PATH/cgiparse.pl"; return cgivalue($Name); # Library
2025 # Complete queries
2026 sub YOUR_CGIQUERYDECODE
2028 # Use one of the following by uncommenting
2029 return CGIscriptor::CGIparseForm(); # Defined in CGIscriptor below
2030 # return `/PATH/cgiparse -form`; # Shell commands
2031 # require "/PATH/cgiparse.pl"; return cgiform(); # Library
2034 # End of configuration
2036 #######################################################################
2038 # Translating input files.
2039 # Allows general and global conversions of files using Regular Expressions
2040 # Translations are applied in the order of definition.
2042 # Define:
2043 # my $TranslationPaths = 'pattern'; # Pattern matching PATH_INFO
2045 # push(@TranslationTable, ['pattern', 'replacement']);
2046 # e.g. (for Ruby Rails):
2047 # push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2048 # push(@TranslationTable, ['%>', '</SCRIPT>']);
2050 # Runs:
2051 # my $currentRegExp;
2052 # foreach $currentRegExp (keys(%TranslationTable))
2054 # my $currentRegExp;
2055 # foreach $currentRegExp (@TranslationTable)
2057 # my ($pattern, $replacement) = @$currentRegExp;
2058 # $$text =~ s!$pattern!$replacement!msg;
2059 # };
2060 # };
2062 # Configuration section
2064 #######################################################################
2066 # The file paths on which to apply the translation
2067 my $TranslationPaths = ''; # NO files
2068 #$TranslationPaths = '.'; # ANY file
2069 # $TranslationPaths = '\.html'; # HTML files
2071 my @TranslationTable = ();
2072 # Some legacy code
2073 push(@TranslationTable, ['\<\s*CGI\s+([^\>])*\>', '\<SCRIPT TYPE=\"text/ssperl\"\>$1\<\/SCRIPT>']);
2074 # Ruby Rails?
2075 push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2076 push(@TranslationTable, ['%>', '</SCRIPT>']);
2078 sub performTranslation # (\$text)
2080 my $text = shift || return;
2081 if(@TranslationTable && $TranslationPaths && $ENV{'PATH_INFO'} =~ m!$TranslationPaths!)
2083 my $currentRegExp;
2084 foreach $currentRegExp (@TranslationTable)
2086 my ($pattern, $replacement) = @$currentRegExp;
2087 $$text =~ s!$pattern!$replacement!msg;
2092 #######################################################################
2094 # Seamless access to other (Scripting) Languages
2095 # TYPE='text/ss<interpreter>'
2097 # Configuration section
2099 #######################################################################
2101 # OTHER SCRIPTING LANGUAGES AT THE SERVER SIDE (MIME => OScommand)
2102 # Yes, it realy is this simple! (unbelievable, isn't it)
2103 # NOTE: Some interpreters require some filtering to obtain "clean" output
2105 %ScriptingLanguages = (
2106 "text/testperl" => 'perl', # Perl for testing
2107 "text/sspython" => 'python', # Python
2108 "text/ssruby" => 'ruby', # Ruby
2109 "text/sstcl" => 'tcl', # TCL
2110 "text/ssawk" => 'awk -f-', # Awk
2111 "text/sslisp" => # lisp (rep, GNU)
2112 'rep | tail +4 '."| egrep -v '> |^rep. |^nil\\\$'",
2113 "text/xlispstat" => # xlispstat
2114 'xlispstat | tail +7 ' ."| egrep -v '> \\\$|^NIL'",
2115 "text/ssprolog" => # Prolog (GNU)
2116 "gprolog | tail +4 | sed 's/^| ?- //'",
2117 "text/ssm4" => 'm4', # M4 macro's
2118 "text/sh" => 'sh', # Born shell
2119 "text/bash" => 'bash', # Born again shell
2120 "text/csh" => 'csh', # C shell
2121 "text/ksh" => 'ksh', # Korn shell
2122 "text/sspraat" => # Praat (sound/speech analysis)
2123 "praat - | sed 's/Praat > //g'",
2124 "text/ssr" => # R
2125 "R --vanilla --slave | sed 's/^[\[0-9\]*] //'",
2126 "text/ssrebol" => # REBOL
2127 "rebol --quiet|egrep -v '^[> ]* == '|sed 's/^\\s*\[> \]* //'",
2128 "text/postgresql" => 'psql 2>/dev/null',
2130 # Not real scripting, but the use of other applications
2131 "text/ssmailto" => "awk 'NF||F{F=1;print \\\$0;}'|mailto >/dev/null", # Send mail from server
2132 "text/ssdisplay" => 'cat', # Display, (interpolation)
2133 "text/sslogfile" => # Log to file, (interpolation)
2134 "awk 'NF||L {if(!L){L=tolower(\\\$1)~/^file:\\\$/ ? \\\$2 : \\\$1;}else{print \\\$0 >> L;};}'",
2136 "" => ""
2139 # To be able to access the CGI variables in your script, they
2140 # should be passed to the scripting language in a readable form
2141 # Here you can enter how they should be printed (the first %s
2142 # is replaced by the NAME of the CGI variable as it apears in the
2143 # META tag, the second by its VALUE).
2144 # For Perl this would be:
2145 # "text/testperl" => '$%s = "%s";',
2146 # which would be executed as
2147 # printf('$%s = "%s";', $CGI_NAME, $CGI_VALUE);
2149 # If the hash table value doesn't exist, nothing is done
2150 # (you have to parse the Environment variables yourself).
2151 # If it DOES exist but is empty (e.g., "text/sspraat" => '',)
2152 # Perl string interpolation of variables (i.e., $var, @array,
2153 # %hash) is performed. This means that $@%\ must be protected
2154 # with a \.
2156 %ScriptingCGIvariables = (
2157 "text/testperl" => "\$\%s = '\%s';", # Perl $VAR = 'value'; (for testing)
2158 "text/sspython" => "\%s = '\%s'", # Python VAR = 'value'
2159 "text/ssruby" => '@%s = "%s"', # Ruby @VAR = 'value'
2160 "text/sstcl" => 'set %s "%s"', # TCL set VAR "value"
2161 "text/ssawk" => '%s = "%s";', # Awk VAR = 'value';
2162 "text/sslisp" => '(setq %s "%s")', # Gnu lisp (rep) (setq VAR "value")
2163 "text/xlispstat" => '(setq %s "%s")', # xlispstat (setq VAR "value")
2164 "text/ssprolog" => '', # Gnu prolog (interpolated)
2165 "text/ssm4" => "define(`\%s', `\%s')", # M4 macro's define(`VAR', `value')
2166 "text/sh" => "\%s='\%s'", # Born shell VAR='value'
2167 "text/bash" => "\%s='\%s'", # Born again shell VAR='value'
2168 "text/csh" => "\$\%s='\%s';", # C shell $VAR = 'value';
2169 "text/ksh" => "\$\%s='\%s';", # Korn shell $VAR = 'value';
2171 "text/ssrebol" => '%s: copy "%s"', # REBOL VAR: copy "value"
2172 "text/sspraat" => '', # Praat (interpolation)
2173 "text/ssr" => '%s <- "%s";', # R VAR <- "value";
2174 "text/postgresql" => '', # PostgreSQL (interpolation)
2176 # Not real scripting, but the use of other applications
2177 "text/ssmailto" => '', # MAILTO, (interpolation)
2178 "text/ssdisplay" => '', # Display, (interpolation)
2179 "text/sslogfile" => '', # Log to file, (interpolation)
2181 "" => ""
2184 # If you want something added in front or at the back of each script
2185 # block as send to the interpreter add it here.
2186 # mime => "string", e.g., "text/sspython" => "python commands"
2187 %ScriptingPrefix = (
2188 "text/testperl" => "\# Prefix Code;", # Perl script testing
2189 "text/ssm4" => 'divert(0)', # M4 macro's (open STDOUT)
2191 "" => ""
2193 # If you want something added at the end of each script block
2194 %ScriptingPostfix = (
2195 "text/testperl" => "\# Postfix Code;", # Perl script testing
2196 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2198 "" => ""
2200 # If you need initialization code, directly after opening
2201 %ScriptingInitialization = (
2202 "text/testperl" => "\# Initialization Code;", # Perl script testing
2203 "text/ssawk" => 'BEGIN {', # Server Side awk scripts (VAR = "value")
2204 "text/sslisp" => '(prog1 nil ', # Lisp (rep)
2205 "text/xlispstat" => '(prog1 nil ', # xlispstat
2206 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2208 "" => ""
2210 # If you need cleanup code before closing
2211 %ScriptingCleanup = (
2212 "text/testperl" => "\# Cleanup Code;", # Perl script testing
2213 "text/sspraat" => 'Quit',
2214 "text/ssawk" => '};', # Server Side awk scripts (VAR = "value")
2215 "text/sslisp" => '(princ "\n" standard-output)).', # Closing print to rep
2216 "text/xlispstat" => '(print ""))', # Closing print to xlispstat
2217 "text/postgresql" => '\q', # quit psql
2218 "text/ssdisplay" => "", # close cat
2220 "" => ""
2223 # End of configuration for foreign scripting languages
2225 ###############################################################################
2227 # Initialization Code
2230 sub Initialize_Request
2232 ###############################################################################
2234 # ENVIRONMENT VARIABLES
2236 # Use environment variables to configure CGIscriptor on a temporary basis.
2237 # If you define any of the configurable variables as environment variables,
2238 # these are used instead of the "hard coded" values above.
2240 $SS_PUB = $ENV{'SS_PUB'} || $YOUR_HTML_FILES;
2241 $SS_SCRIPT = $ENV{'SS_SCRIPT'} || $YOUR_SCRIPTS;
2244 # Substitution strings, these are used internally to handle the
2245 # directory separator strings, e.g., '~/' -> 'SS_PUB:' (Mac)
2246 $HOME_SUB = $SS_PUB;
2247 $SCRIPT_SUB = $SS_SCRIPT;
2250 # Make sure all script are reliably loaded
2251 push(@INC, $SS_SCRIPT);
2254 # Add the directory separator to the "home" directories.
2255 # (This is required for ~/ and ./ substitution)
2256 $HOME_SUB .= '/' if $HOME_SUB;
2257 $SCRIPT_SUB .= '/' if $SCRIPT_SUB;
2259 $CGI_HOME = $ENV{'DOCUMENT_ROOT'};
2260 $ENV{'PATH_TRANSLATED'} =~ /$ENV{'PATH_INFO'}/is;
2261 $CGI_HOME = $` unless $ENV{'DOCUMENT_ROOT'}; # Get the DOCUMENT_ROOT directory
2262 $default_values{'CGI_HOME'} = $CGI_HOME;
2263 $ENV{'HOME'} = $CGI_HOME;
2264 # Set SS_PUB and SS_SCRIPT as Environment variables (make them available
2265 # to the scripts)
2266 $ENV{'SS_PUB'} = $SS_PUB unless $ENV{'SS_PUB'};
2267 $ENV{'SS_SCRIPT'} = $SS_SCRIPT unless $ENV{'SS_SCRIPT'};
2269 $FilePattern = $ENV{'FilePattern'} || $FilePattern;
2270 $MaximumQuerySize = $ENV{'MaximumQuerySize'} || $MaximumQuerySize;
2271 $ClientLog = $ENV{'ClientLog'} || $ClientLog;
2272 $QueryLog = $ENV{'QueryLog'} || $QueryLog;
2273 $CGI_Accept = $ENV{'CGI_Accept'} || $CGI_Accept;
2274 $CGI_Reject = $ENV{'CGI_Reject'} || $CGI_Reject;
2276 # Parse file names
2277 $CGI_Accept =~ s@^\~/@$HOME_SUB@g if $CGI_Accept;
2278 $CGI_Reject =~ s@^\~/@$HOME_SUB@g if $CGI_Reject;
2279 $ClientLog =~ s@^\~/@$HOME_SUB@g if $ClientLog;
2280 $QueryLog =~ s@^\~/@$HOME_SUB@g if $QueryLog;
2282 $CGI_Accept =~ s@^\./@$SCRIPT_SUB@g if $CGI_Accept;
2283 $CGI_Reject =~ s@^\./@$SCRIPT_SUB@g if $CGI_Reject;
2284 $ClientLog =~ s@^\./@$SCRIPT_SUB@g if $ClientLog;
2285 $QueryLog =~ s@^\./@$SCRIPT_SUB@g if $QueryLog;
2287 @CGIscriptorResults = (); # A stack of results
2289 # end of Environment variables
2291 #############################################################################
2293 # Define and Store "standard" values
2295 # BEFORE doing ANYTHING check the size of Query String
2296 length($ENV{'QUERY_STRING'}) <= $MaximumQuerySize || dieHandler(2, "QUERY TOO LONG\n");
2298 # The Translated Query String and the Actual length of the (decoded)
2299 # Query String
2300 if($ENV{'QUERY_STRING'})
2302 # If this can contain '`"-quotes, be carefull to use it QUOTED
2303 $default_values{CGI_Decoded_QS} = YOUR_CGIQUERYDECODE();
2304 $default_values{CGI_Content_Length} = length($default_values{CGI_Decoded_QS});
2307 # Get the current Date and time and store them as default variables
2309 # Get Local Time
2310 $LocalTime = localtime;
2312 # CGI_Year CGI_Month CGI_Day CGI_WeekDay CGI_Time
2313 # CGI_Hour CGI_Minutes CGI_Seconds
2315 $default_values{CGI_Date} = $LocalTime;
2316 ($default_values{CGI_WeekDay},
2317 $default_values{CGI_Month},
2318 $default_values{CGI_Day},
2319 $default_values{CGI_Time},
2320 $default_values{CGI_Year}) = split(' ', $LocalTime);
2321 ($default_values{CGI_Hour},
2322 $default_values{CGI_Minutes},
2323 $default_values{CGI_Seconds}) = split(':', $default_values{CGI_Time});
2325 # GMT:
2326 # CGI_GMTYear CGI_GMTMonth CGI_GMTDay CGI_GMTWeekDay CGI_GMTYearDay
2327 # CGI_GMTHour CGI_GMTMinutes CGI_GMTSeconds CGI_GMTisdst
2329 ($default_values{CGI_GMTSeconds},
2330 $default_values{CGI_GMTMinutes},
2331 $default_values{CGI_GMTHour},
2332 $default_values{CGI_GMTDay},
2333 $default_values{CGI_GMTMonth},
2334 $default_values{CGI_GMTYear},
2335 $default_values{CGI_GMTWeekDay},
2336 $default_values{CGI_GMTYearDay},
2337 $default_values{CGI_GMTisdst}) = gmtime;
2341 # End of Initialize Request
2343 ###################################################################
2345 # SECURITY: ACCESS CONTROL
2347 # Check the credentials of each client (use pattern matching, domain first).
2348 # This subroutine will kill-off (die) the current process whenever access
2349 # is denied.
2351 sub Access_Control
2353 # >>>>>>>>>>Start Remove
2355 # ACCEPTED CLIENTS
2357 # Only accept clients which are authorized, reject all unnamed clients
2358 # if REMOTE_HOST is given.
2359 # If file patterns are given, check whether the user is authorized for
2360 # THIS file.
2361 if($CGI_Accept)
2363 # Use local variables, REMOTE_HOST becomes '-' if undefined
2364 my $REMOTE_HOST = $ENV{REMOTE_HOST} || '-';
2365 my $REMOTE_ADDR = $ENV{REMOTE_ADDR};
2366 my $PATH_INFO = $ENV{'PATH_INFO'};
2368 open(CGI_Accept, "<$CGI_Accept") || dieHandler(3, "$CGI_Accept: $!\n");
2369 $NoAccess = 1;
2370 while(<CGI_Accept>)
2372 next unless /\S/; # Skip empty lines
2373 next if /^\s*\#/; # Skip comments
2375 # Full expressions
2376 if(/^\s*-e\s/is)
2378 my $Accept = $'; # Get the expression
2379 $NoAccess &&= eval($Accept); # evaluate the expresion
2381 else
2383 my ($Accept, @FilePatternList) = split;
2384 if($Accept eq '*' # Always match
2385 ||$REMOTE_HOST =~ /\Q$Accept\E$/is # REMOTE_HOST matches
2386 || (
2387 $Accept =~ /^[0-9\.]+$/
2388 && $REMOTE_ADDR =~ /^\Q$Accept\E/ # IP address matches
2392 if($FilePatternList[0])
2394 foreach $Pattern (@FilePatternList)
2396 # Check whether this patterns is accepted
2397 $NoAccess &&= ($PATH_INFO !~ m@\Q$Pattern\E@is);
2400 else
2402 $NoAccess = 0; # No file patterns -> Accepted
2406 # Blocked
2407 last unless $NoAccess;
2409 close(CGI_Accept);
2410 if($NoAccess){ dieHandler(4, "No Access: $PATH_INFO\n");};
2414 # REJECTED CLIENTS
2416 # Reject named clients, accept all unnamed clients
2417 if($CGI_Reject)
2419 # Use local variables, REMOTE_HOST becomes '-' if undefined
2420 my $REMOTE_HOST = $ENV{'REMOTE_HOST'} || '-';
2421 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
2422 my $PATH_INFO = $ENV{'PATH_INFO'};
2424 open(CGI_Reject, "<$CGI_Reject") || dieHandler(5, "$CGI_Reject: $!\n");
2425 $NoAccess = 0;
2426 while(<CGI_Reject>)
2428 next unless /\S/; # Skip empty lines
2429 next if /^\s*\#/; # Skip comments
2431 # Full expressions
2432 if(/^-e\s/is)
2434 my $Reject = $'; # Get the expression
2435 $NoAccess ||= eval($Reject); # evaluate the expresion
2437 else
2439 my ($Reject, @FilePatternList) = split;
2440 if($Reject eq '*' # Always match
2441 ||$REMOTE_HOST =~ /\Q$Reject\E$/is # REMOTE_HOST matches
2442 ||($Reject =~ /^[0-9\.]+$/
2443 && $REMOTE_ADDR =~ /^\Q$Reject\E/is # IP address matches
2447 if($FilePatternList[0])
2449 foreach $Pattern (@FilePatternList)
2451 $NoAccess ||= ($PATH_INFO =~ m@\Q$Pattern\E@is);
2454 else
2456 $NoAccess = 1; # No file patterns -> Rejected
2460 last if $NoAccess;
2462 close(CGI_Reject);
2463 if($NoAccess){ dieHandler(6, "Request rejected: $PATH_INFO\n");};
2466 ##########################################################<<<<<<<<<<End Remove
2469 # Get the filename
2471 # Does the filename contain any illegal characters (e.g., |, >, or <)
2472 dieHandler(7, "Illegal request: $ENV{'PATH_INFO'}\n") if $ENV{'PATH_INFO'} =~ /[^$FileAllowedChars]/;
2473 # Does the pathname contain an illegal (blocked) "directory"
2474 dieHandler(8, "Illegal request: $ENV{'PATH_INFO'}\n") if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@; # Access is blocked
2475 # Does the pathname contain a direct referencer to BinaryMapFile
2476 dieHandler(9, "Illegal request: $ENV{'PATH_INFO'}\n") if $BinaryMapFile && $ENV{'PATH_INFO'} =~ m@\Q$BinaryMapFile\E@; # Access is blocked
2478 # SECURITY: Is PATH_INFO allowed?
2479 if($FilePattern && $ENV{'PATH_INFO'} && $ENV{'PATH_INFO'} ne '-' &&
2480 ($ENV{'PATH_INFO'} !~ m@($FilePattern)$@is))
2482 # Unsupported file types can be processed by a special raw-file
2483 if($BinaryMapFile)
2485 $ENV{'CGI_BINARY_FILE'} = $ENV{'PATH_INFO'};
2486 $ENV{'PATH_INFO'} = $BinaryMapFile;
2488 else
2490 dieHandler(10, "Illegal file\n");
2496 # End of Security Access Control
2499 ############################################################################
2501 # Get the POST part of the query and add it to the QUERY_STRING.
2504 sub Get_POST_part_of_query
2507 # If POST, Read data from stdin to QUERY_STRING
2508 if($ENV{'REQUEST_METHOD'} =~ /POST/is)
2510 # SECURITY: Check size of Query String
2511 $ENV{'CONTENT_LENGTH'} <= $MaximumQuerySize || dieHandler(11, "Query too long: $ENV{'CONTENT_LENGTH'}\n"); # Query too long
2512 my $QueryRead = 0;
2513 my $SystemRead = $ENV{'CONTENT_LENGTH'};
2514 $ENV{'QUERY_STRING'} .= '&' if length($ENV{'QUERY_STRING'}) > 0;
2515 while($SystemRead > 0)
2517 $QueryRead = sysread(STDIN, $Post, $SystemRead); # Limit length
2518 $ENV{'QUERY_STRING'} .= $Post;
2519 $SystemRead -= $QueryRead;
2521 # Update decoded Query String
2522 $default_values{CGI_Decoded_QS} = YOUR_CGIQUERYDECODE();
2523 $default_values{CGI_Content_Length} =
2524 length($default_values{CGI_Decoded_QS});
2528 # End of getting POST part of query
2531 ############################################################################
2533 # Start (HTML) output and logging
2534 # (if there are irregularities, it can kill the current process)
2537 sub Initialize_output
2539 # Construct the REAL file path (except for STDIN on the command line)
2540 my $file_path = $ENV{'PATH_INFO'} ne '-' ? $SS_PUB . $ENV{'PATH_INFO'} : '-';
2541 $file_path =~ s/\?.*$//; # Remove query
2542 # This is only necessary if your server does not catch ../ directives
2543 $file_path !~ m@\.\./@ || dieHandler(12, "Illegal ../ Construct\n"); # SECURITY: Do not allow ../ constructs
2545 # Block STDIN use (-) if CGIscriptor is servicing a HTTP request
2546 if($file_path eq '-')
2548 dieHandler(13, "STDIN request in On Line system\n") if $BLOCK_STDIN_HTTP_REQUEST
2549 && ($ENV{'SERVER_SOFTWARE'}
2550 || $ENV{'SERVER_NAME'}
2551 || $ENV{'GATEWAY_INTERFACE'}
2552 || $ENV{'SERVER_PROTOCOL'}
2553 || $ENV{'SERVER_PORT'}
2554 || $ENV{'REMOTE_ADDR'}
2555 || $ENV{'HTTP_USER_AGENT'});
2560 if($ClientLog)
2562 open(ClientLog, ">>$ClientLog");
2563 print ClientLog "$LocalTime | ",
2564 ($ENV{REMOTE_USER} || "-"), " ",
2565 ($ENV{REMOTE_IDENT} || "-"), " ",
2566 ($ENV{REMOTE_HOST} || "-"), " ",
2567 $ENV{REMOTE_ADDR}, " ",
2568 $ENV{PATH_INFO}, " ",
2569 $ENV{'CGI_BINARY_FILE'}, " ",
2570 ($default_values{CGI_Content_Length} || "-"),
2571 "\n";
2572 close(ClientLog);
2574 if($QueryLog)
2576 open(QueryLog, ">>$QueryLog");
2577 print QueryLog "$LocalTime\n",
2578 ($ENV{REMOTE_USER} || "-"), " ",
2579 ($ENV{REMOTE_IDENT} || "-"), " ",
2580 ($ENV{REMOTE_HOST} || "-"), " ",
2581 $ENV{REMOTE_ADDR}, ": ",
2582 $ENV{PATH_INFO}, " ",
2583 $ENV{'CGI_BINARY_FILE'}, "\n";
2585 # Write Query to Log file
2586 print QueryLog $default_values{CGI_Decoded_QS}, "\n\n";
2587 close(QueryLog);
2590 # Return the file path
2591 return $file_path;
2594 # End of Initialize output
2597 ############################################################################
2599 # Handle login access
2601 # Access is based on a valid session ticket.
2602 # Session tickets should be dependend on user name
2603 # and IP address. The patterns of URLs for which a
2604 # session ticket is needed and the login URL are stored in
2605 # %LoginRequiredPatterns as:
2606 # 'RegEx pattern' -> 'SessionPath\tPasswordPath\tLogin URL'
2609 sub Log_In_Access # () -> Access Allowed
2611 # No patterns, no login
2612 return 1 unless %LoginRequiredPatterns;
2614 # Get and initialize values
2615 my ($SessionPath, $PasswordsPath, $Login) = ("", "", "");
2616 my $PATH_INFO = $ENV{'PATH_INFO'};
2617 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
2619 CGIexecute::defineCGIvariable('SESSIONTICKET', "");
2620 my $SESSIONTICKET = ${"CGIexecute::SESSIONTICKET"};
2622 foreach my $pattern (keys(%LoginRequiredPatterns))
2624 if($PATH_INFO =~ m#$pattern#)
2626 # Fall through a sieve of requirements
2627 ($SessionPath, $PasswordsPath, $Login) = split(/\t/, $LoginRequiredPatterns{$pattern});
2628 # Is there a session ticket of this name?
2629 goto Login unless $SESSIONTICKET && (-s "$SessionPath/$SESSIONTICKET");
2631 # There is a session ticket, is it linked to this IP address?
2632 open(SESSION, "<$SessionPath/$SESSIONTICKET") || die "$SessionPath/$SESSIONTICKET: $!\n";
2633 my @sessionlines = <SESSION>;
2634 close(SESSION);
2635 if($sessionlines[0] =~ /^\s*IPaddress:\s+([0-9\.]+)\s*(\n|$)/isg)
2637 my $sessionipaddress = $1;
2638 goto Login unless $REMOTE_ADDR eq $sessionipaddress;
2640 if($sessionlines[1] =~ /^\s*AllowedPaths:\s+([^\n\t]+)\s*(\n|$)/isg)
2642 my $allowedPaths = $1;
2643 return 1 unless $allowedPaths =~ /\S/;
2644 goto Login unless $PATH_INFO =~ m#$allowedPaths#sg;
2646 else
2648 return 1;
2650 return 1;
2653 return 1;
2655 Login:
2657 return 0;
2660 End of Initialize output
2663 ############################################################################
2665 # Handle foreign interpreters (i.e., scripting languages)
2667 # Insert perl code to execute scripts in foreign scripting languages.
2668 # Actually, the scripts inside the <SCRIPT></SCRIPT> blocks are piped
2669 # into an interpreter.
2670 # The code presented here is fairly confusing because it
2671 # actually writes perl code code to the output.
2673 # A table with the file handles
2674 %SCRIPTINGINPUT = ();
2676 # A function to clean up Client delivered CGI parameter values
2677 # (i.e., quote all odd characters)
2678 %SHRUBcharacterTR =
2680 "\'" => '&#39;',
2681 "\`" => '&#96;',
2682 "\"" => '&quot;',
2683 '&' => '&amper;',
2684 "\\" => '&#92;'
2687 sub shrubCGIparameter # ($String) -> Cleaned string
2689 my $String = shift || "";
2691 # Change all quotes [`'"] into HTML character entities
2692 my ($Char, $Transcript) = ('&', $SHRUBcharacterTR{'&'});
2694 # Protect &
2695 $String =~ s/\Q$Char\E/$Transcript/isg if $Transcript;
2697 while( ($Char, $Transcript) = each %SHRUBcharacterTR)
2699 next if $Char eq '&';
2700 $String =~ s/\Q$Char\E/$Transcript/isg;
2703 # Replace newlines
2704 $String =~ s/[\n]/\\n/g;
2705 # Replace control characters with their backslashed octal ordinal numbers
2706 $String =~ s/([^\S \t])/(sprintf("\\0%o", ord($1)))/eisg; #
2707 $String =~ s/([\x00-\x08\x0A-\x1F])/(sprintf("\\0%o", ord($1)))/eisg; #
2709 return $String;
2713 # The initial open statements: Open a pipe to the foreign script interpreter
2714 sub OpenForeignScript # ($ContentType) -> $DirectivePrefix
2716 my $ContentType = lc(shift) || return "";
2717 my $NewDirective = "";
2719 return $NewDirective if($SCRIPTINGINPUT{$ContentType});
2721 # Construct a unique file handle name
2722 $SCRIPTINGFILEHANDLE = uc($ContentType);
2723 $SCRIPTINGFILEHANDLE =~ s/\W/\_/isg;
2724 $SCRIPTINGINPUT{$ContentType} = $SCRIPTINGFILEHANDLE
2725 unless $SCRIPTINGINPUT{$ContentType};
2727 # Create the relevant script: Open the pipe to the interpreter
2728 $NewDirective .= <<"BLOCKCGISCRIPTOROPEN";
2729 # Open interpreter for '$ContentType'
2730 # Open pipe to interpreter (if it isn't open already)
2731 open($SCRIPTINGINPUT{$ContentType}, "|$ScriptingLanguages{$ContentType}") || main::dieHandler(14, "$ContentType: \$!\\n");
2732 BLOCKCGISCRIPTOROPEN
2734 # Insert Initialization code and CGI variables
2735 $NewDirective .= InitializeForeignScript($ContentType);
2737 # Ready
2738 return $NewDirective;
2742 # The final closing code to stop the interpreter
2743 sub CloseForeignScript # ($ContentType) -> $DirectivePrefix
2745 my $ContentType = lc(shift) || return "";
2746 my $NewDirective = "";
2748 # Do nothing unless the pipe realy IS open
2749 return "" unless $SCRIPTINGINPUT{$ContentType};
2751 # Initial comment
2752 $NewDirective .= "\# Close interpreter for '$ContentType'\n";
2755 # Write the Postfix code
2756 $NewDirective .= CleanupForeignScript($ContentType);
2758 # Create the relevant script: Close the pipe to the interpreter
2759 $NewDirective .= <<"BLOCKCGISCRIPTORCLOSE";
2760 close($SCRIPTINGINPUT{$ContentType}) || main::dieHandler(15, \"$ContentType: \$!\\n\");
2761 select(STDOUT); \$|=1;
2763 BLOCKCGISCRIPTORCLOSE
2765 # Remove the file handler of the foreign script
2766 delete($SCRIPTINGINPUT{$ContentType});
2768 return $NewDirective;
2772 # The initialization code for the foreign script interpreter
2773 sub InitializeForeignScript # ($ContentType) -> $DirectivePrefix
2775 my $ContentType = lc(shift) || return "";
2776 my $NewDirective = "";
2778 # Add initialization code
2779 if($ScriptingInitialization{$ContentType})
2781 $NewDirective .= <<"BLOCKCGISCRIPTORINIT";
2782 # Initialization Code for '$ContentType'
2783 # Select relevant output filehandle
2784 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
2786 # The Initialization code (if any)
2787 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}INITIALIZATIONCODE';
2788 $ScriptingInitialization{$ContentType}
2789 ${ContentType}INITIALIZATIONCODE
2791 BLOCKCGISCRIPTORINIT
2794 # Add all CGI variables defined
2795 if(exists($ScriptingCGIvariables{$ContentType}))
2797 # Start writing variable definitions to the Interpreter
2798 if($ScriptingCGIvariables{$ContentType})
2800 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEF";
2801 # CGI variables (from the %default_values table)
2802 print $SCRIPTINGINPUT{$ContentType} << '${ContentType}CGIVARIABLES';
2803 BLOCKCGISCRIPTORVARDEF
2806 my ($N, $V);
2807 foreach $N (keys(%default_values))
2809 # Determine whether the parameter has been defined
2810 # (the eval is a workaround to get at the variable value)
2811 next unless eval("defined(\$CGIexecute::$N)");
2813 # Get the value from the EXECUTION environment
2814 $V = eval("\$CGIexecute::$N");
2815 # protect control characters (i.e., convert them to \0.. form)
2816 $V = shrubCGIparameter($V);
2818 # Protect interpolated variables
2819 eval("\$CGIexecute::$N = '$V';") unless $ScriptingCGIvariables{$ContentType};
2821 # Print the actual declaration for this scripting language
2822 if($ScriptingCGIvariables{$ContentType})
2824 $NewDirective .= sprintf($ScriptingCGIvariables{$ContentType}, $N, $V);
2825 $NewDirective .= "\n";
2829 # Stop writing variable definitions to the Interpreter
2830 if($ScriptingCGIvariables{$ContentType})
2832 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEFEND";
2833 ${ContentType}CGIVARIABLES
2834 BLOCKCGISCRIPTORVARDEFEND
2839 $NewDirective .= << "BLOCKCGISCRIPTOREND";
2841 # Select STDOUT filehandle
2842 select(STDOUT); \$|=1;
2844 BLOCKCGISCRIPTOREND
2846 return $NewDirective;
2850 # The cleanup code for the foreign script interpreter
2851 sub CleanupForeignScript # ($ContentType) -> $DirectivePrefix
2853 my $ContentType = lc(shift) || return "";
2854 my $NewDirective = "";
2856 # Return if not needed
2857 return $NewDirective unless $ScriptingCleanup{$ContentType};
2859 # Create the relevant script: Open the pipe to the interpreter
2860 $NewDirective .= <<"BLOCKCGISCRIPTORSTOP";
2861 # Cleanup Code for '$ContentType'
2862 # Select relevant output filehandle
2863 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
2864 # Print Cleanup code to foreign script
2865 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}SCRIPTSTOP';
2866 $ScriptingCleanup{$ContentType}
2867 ${ContentType}SCRIPTSTOP
2869 # Select STDOUT filehandle
2870 select(STDOUT); \$|=1;
2871 BLOCKCGISCRIPTORSTOP
2873 return $NewDirective;
2877 # The prefix code for each <script></script> block
2878 sub PrefixForeignScript # ($ContentType) -> $DirectivePrefix
2880 my $ContentType = lc(shift) || return "";
2881 my $NewDirective = "";
2883 # Return if not needed
2884 return $NewDirective unless $ScriptingPrefix{$ContentType};
2886 my $Quote = "\'";
2887 # If the CGIvariables parameter is defined, but empty, interpolate
2888 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
2889 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
2890 !$ScriptingCGIvariables{$ContentType};
2892 # Add initialization code
2893 $NewDirective .= <<"BLOCKCGISCRIPTORPREFIX";
2894 # Prefix Code for '$ContentType'
2895 # Select relevant output filehandle
2896 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
2898 # The block Prefix code (if any)
2899 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}PREFIXCODE$Quote;
2900 $ScriptingPrefix{$ContentType}
2901 ${ContentType}PREFIXCODE
2902 # Select STDOUT filehandle
2903 select(STDOUT); \$|=1;
2904 BLOCKCGISCRIPTORPREFIX
2906 return $NewDirective;
2910 # The postfix code for each <script></script> block
2911 sub PostfixForeignScript # ($ContentType) -> $DirectivePrefix
2913 my $ContentType = lc(shift) || return "";
2914 my $NewDirective = "";
2916 # Return if not needed
2917 return $NewDirective unless $ScriptingPostfix{$ContentType};
2919 my $Quote = "\'";
2920 # If the CGIvariables parameter is defined, but empty, interpolate
2921 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
2922 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
2923 !$ScriptingCGIvariables{$ContentType};
2925 # Create the relevant script: Open the pipe to the interpreter
2926 $NewDirective .= <<"BLOCKCGISCRIPTORPOSTFIX";
2927 # Postfix Code for '$ContentType'
2928 # Select filehandle to interpreter
2929 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
2930 # Print postfix code to foreign script
2931 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SCRIPTPOSTFIX$Quote;
2932 $ScriptingPostfix{$ContentType}
2933 ${ContentType}SCRIPTPOSTFIX
2934 # Select STDOUT filehandle
2935 select(STDOUT); \$|=1;
2936 BLOCKCGISCRIPTORPOSTFIX
2938 return $NewDirective;
2941 sub InsertForeignScript # ($ContentType, $directive, @SRCfile) -> $NewDirective
2943 my $ContentType = lc(shift) || return "";
2944 my $directive = shift || return "";
2945 my @SRCfile = @_;
2946 my $NewDirective = "";
2948 my $Quote = "\'";
2949 # If the CGIvariables parameter is defined, but empty, interpolate
2950 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
2951 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
2952 !$ScriptingCGIvariables{$ContentType};
2954 # Create the relevant script
2955 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
2956 # Insert Code for '$ContentType'
2957 # Select filehandle to interpreter
2958 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
2959 BLOCKCGISCRIPTORINSERT
2961 # Use SRC feature files
2962 my $ThisSRCfile;
2963 while($ThisSRCfile = shift(@_))
2965 # Handle blocks
2966 if($ThisSRCfile =~ /^\s*\{\s*/)
2968 my $Block = $';
2969 $Block = $` if $Block =~ /\s*\}\s*$/;
2970 $NewDirective .= <<"BLOCKCGISCRIPTORSRCBLOCK";
2971 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SRCBLOCKCODE$Quote;
2972 $Block
2973 ${ContentType}SRCBLOCKCODE
2974 BLOCKCGISCRIPTORSRCBLOCK
2976 next;
2979 # Handle files
2980 $NewDirective .= <<"BLOCKCGISCRIPTORSRCFILES";
2981 # Read $ThisSRCfile
2982 open(SCRIPTINGSOURCE, "<$ThisSRCfile") || main::dieHandler(16, "$ThisSRCfILE: \$!");
2983 while(<SCRIPTINGSOURCE>)
2985 print $SCRIPTINGINPUT{$ContentType} \$_;
2987 close(SCRIPTINGSOURCE);
2989 BLOCKCGISCRIPTORSRCFILES
2993 # Add the directive
2994 if($directive)
2996 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
2997 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}DIRECTIVECODE$Quote;
2998 $directive
2999 ${ContentType}DIRECTIVECODE
3000 BLOCKCGISCRIPTORINSERT
3004 $NewDirective .= <<"BLOCKCGISCRIPTORSELECT";
3005 # Select STDOUT filehandle
3006 select(STDOUT); \$|=1;
3007 BLOCKCGISCRIPTORSELECT
3009 # Ready
3010 return $NewDirective;
3013 sub CloseAllForeignScripts # Call CloseForeignScript on all open scripts
3015 my $ContentType;
3016 foreach $ContentType (keys(%SCRIPTINGINPUT))
3018 my $directive = CloseForeignScript($ContentType);
3019 print STDERR "\nDirective $CGI_Date: ", $directive;
3020 CGIexecute->evaluate($directive);
3025 # End of handling foreign (external) scripting languages.
3027 ############################################################################
3029 # A subroutine to handle "nested" quotes, it cuts off the leading
3030 # item or quoted substring
3031 # E.g.,
3032 # ' A_word and more words' -> @('A_word', ' and more words')
3033 # '"quoted string" The rest' -> @('quoted string', ' The rest')
3034 # (this is needed for parsing the <TAGS> and their attributes)
3035 my $SupportedQuotes = "\'\"\`\(\{\[";
3036 my %QuotePairs = ('('=>')','['=>']','{'=>'}'); # Brackets
3037 sub ExtractQuotedItem # ($String) -> @($QuotedString, $RestOfString)
3039 my @Result = ();
3040 my $String = shift || return @Result;
3042 if($String =~ /^\s*([\w\/\-\.]+)/is)
3044 push(@Result, $1, $');
3046 elsif($String =~ /^\s*(\\?)([\Q$SupportedQuotes\E])/is)
3048 my $BackSlash = $1 || "";
3049 my $OpenQuote = $2;
3050 my $CloseQuote = $OpenQuote;
3051 $CloseQuote = $QuotePairs{$OpenQuote} if $QuotePairs{$OpenQuote};
3053 if($BackSlash)
3055 $String =~ /^\s*\\\Q$OpenQuote\E/i;
3056 my $Onset = $';
3057 $Onset =~ /\\\Q$CloseQuote\E/i;
3058 my $Rest = $';
3059 my $Item = $`;
3060 push(@Result, $Item, $Rest);
3063 else
3065 $String =~ /^\s*\Q$OpenQuote\E([^\Q$CloseQuote\E]*)\Q$CloseQuote\E/i;
3066 push(@Result, $1, $');
3069 else
3071 push(@Result, "", $String);
3073 return @Result;
3076 # Now, start with the real work
3078 # Control the output of the Content-type: text/html\n\n message
3079 my $SupressContentType = 0;
3081 # Process a file
3082 sub ProcessFile # ($file_path)
3084 my $file_path = shift || return 0;
3087 # Generate a unique file handle (for recursions)
3088 my @SRClist = ();
3089 my $FileHandle = "file";
3090 my $n = 0;
3091 while(!eof($FileHandle.$n)) {++$n;};
3092 $FileHandle .= $n;
3094 # Start HTML output
3095 # Use the default Content-type if this is NOT a raw file
3096 unless(($RawFilePattern && $ENV{'PATH_INFO'} =~ m@($RawFilePattern)$@i)
3097 || $SupressContentType)
3099 $ENV{'PATH_INFO'} =~ m@($FilePattern)$@i;
3100 my $ContentType = $ContentTypeTable{$1};
3101 print "Content-type: $ContentType\n";
3102 print "\n";
3103 $SupressContentType = 1; # Content type has been printed
3107 # Get access to the actual data. This can be from RAM (by way of an
3108 # environment variable) or by opening a file.
3110 # Handle the use of RAM images (file-data is stored in the
3111 # $CGI_FILE_CONTENTS environment variable)
3112 # Note that this environment variable will be cleared, i.e., it is strictly for
3113 # single-use only!
3114 if($ENV{$CGI_FILE_CONTENTS})
3116 # File has been read already
3117 $_ = $ENV{$CGI_FILE_CONTENTS};
3118 # Sorry, you have to do the reading yourself (dynamic document creation?)
3119 # NOTE: you must read the whole document at once
3120 if($_ eq '-')
3122 $_ = eval("\@_=('$file_path'); do{$ENV{$CGI_DATA_ACCESS_CODE}}");
3124 else # Clear environment variable
3126 $ENV{$CGI_FILE_CONTENTS} = '-';
3129 # Open Only PLAIN TEXT files (or STDIN) and NO executable files (i.e., scripts).
3130 # THIS IS A SECURITY FEATURE!
3131 elsif($file_path eq '-' || (-e "$file_path" && -r _ && -T _ && -f _ && ! (-x _ || -X _) ))
3133 open($FileHandle, $file_path) || dieHandler(17, "<h2>File not found</h2>\n");
3134 push(@OpenFiles, $file_path);
3135 $_ = <$FileHandle>; # Read first line
3137 else
3139 print "<h2>File not found</h2>\n";
3140 dieHandler(18, "$file_path\n");
3143 $| = 1; # Flush output buffers
3145 # Initialize variables
3146 my $METAarguments = ""; # The CGI arguments from the latest META tag
3147 my @METAvalues = (); # The ''-quoted CGI values from the latest META tag
3148 my $ClosedTag = 0; # <TAG> </TAG> versus <TAG/>
3151 # Send document to output
3152 # Process the requested document.
3153 # Do a loop BEFORE reading input again (this catches the RAM/Database
3154 # type of documents).
3155 do {
3158 # Handle translations if needed
3160 performTranslation(\$_) if $TranslationPaths;
3162 # Catch <SCRIPT LANGUAGE="PERL" TYPE="text/ssperl" > directives in $_
3163 # There can be more than 1 <SCRIPT> or META tags on a line
3164 while(/\<\s*(SCRIPT|META|DIV|INS)\s/is)
3166 my $directive = "";
3167 # Store rest of line
3168 my $Before = $`;
3169 my $ScriptTag = $&;
3170 my $After = $';
3171 my $TagType = uc($1);
3172 # The before part can be send to the output
3173 print $Before;
3175 # Read complete Tag from after and/or file
3176 until($After =~ /([^\\])\>/)
3178 $After .= <$FileHandle>;
3179 performTranslation(\$After) if $TranslationPaths;
3182 if($After =~ /([^\\])\>/)
3184 $ScriptTag .= $`.$&; # Keep the Script Tag intact
3185 $After = $';
3187 else
3189 dieHandler(19, "Closing > not found\n");
3192 # The tag could be closed by />, we handle this in the XML way
3193 # and don't process any content (we ignore whitespace)
3194 $ClosedTag = ($ScriptTag =~ m@[^\\]/\s*\>\s*$@) ? 1 : 0;
3197 # TYPE or CLASS?
3198 my $TypeName = ($TagType =~ /META/is) ? "CONTENT" : "TYPE";
3199 $TypeName = "CLASS" if $TagType eq 'DIV' || $TagType eq 'INS';
3201 # Parse <SCRIPT> or <META> directive
3202 # If NOT (TYPE|CONTENT)="text/ssperl" (i.e., $ServerScriptContentType),
3203 # send the line to the output and go to the next loop
3204 my $CurrentContentType = "";
3205 if($ScriptTag =~ /(^|\s)$TypeName\s*=\s*/is)
3207 my ($Type) = ExtractQuotedItem($');
3208 $Type =~ /^\s*([\w\/\-]+)\s*[\,\;]?/;
3209 $CurrentContentType = lc($1); # Note: mime-types are "case-less"
3210 # CSS classes are aliases of $ServerScriptContentType
3211 if($TypeName eq "CLASS" && $CurrentContentType eq $ServerScriptContentClass)
3213 $CurrentContentType = $ServerScriptContentType;
3218 # Not a known server-side content type, print and continue
3219 unless(($CurrentContentType =~
3220 /$ServerScriptContentType|$ShellScriptContentType/is) ||
3221 $ScriptingLanguages{$CurrentContentType})
3223 print $ScriptTag;
3224 $_ = $After;
3225 next;
3229 # A known server-side content type, evaluate
3231 # First, handle \> and \<
3232 $ScriptTag =~ s/\\\>/\>/isg;
3233 $ScriptTag =~ s/\\\</\</isg;
3235 # Extract the CGI, SRC, ID, IF and UNLESS attributes
3236 my %ScriptTagAttributes = ();
3237 while($ScriptTag =~ /(^|\s)(CGI|IF|UNLESS|SRC|ID)\s*=\s*/is)
3239 my $Attribute = $2;
3240 my $Rest = $';
3241 my $Value = "";
3242 ($Value, $ScriptTag) = ExtractQuotedItem($Rest);
3243 $ScriptTagAttributes{uc($Attribute)} = $Value;
3247 # The attribute used to define the CGI variables
3248 # Extract CGI-variables from
3249 # <META CONTENT="text/ssperl; CGI='' SRC=''">
3250 # <SCRIPT TYPE='text/ssperl' CGI='' SRC=''>
3251 # <DIV CLASS='ssperl' CGI='' SRC='' ID=""> tags
3252 # <INS CLASS='ssperl' CGI='' SRC='' ID=""> tags
3253 if($ScriptTagAttributes{'CGI'})
3255 @ARGV = (); # Reset ARGV
3256 $ARGC = 0;
3257 $METAarguments = ""; # Reset the META CGI arguments
3258 @METAvalues = ();
3259 my $Meta_CGI = $ScriptTagAttributes{'CGI'};
3261 # Process default values of variables ($<name> = 'default value')
3262 # Allowed quotes are '', "", ``, (), [], and {}
3263 while($Meta_CGI =~ /(^\s*|[^\\])([\$\@\%]?)([\w\-]+)\s*/is)
3265 my $varType = $2 || '$'; # Variable or list
3266 my $name = $3; # The Name
3267 my $default = "";
3268 $Meta_CGI = $';
3270 if($Meta_CGI =~ /^\s*\=\s*/is)
3272 # Locate (any) default value
3273 ($default, $Meta_CGI) = ExtractQuotedItem($'); # Cut the parameter from the CGI
3275 $RemainingTag = $Meta_CGI;
3278 # Define CGI (or ENV) variable, initalize it from the
3279 # Query string or the default value
3281 # Also construct the @ARGV and @_ arrays. This allows other (SRC=) Perl
3282 # scripts to access the CGI arguments defined in the META tag
3283 # (Not for CGI inside <SCRIPT> tags)
3284 if($varType eq '$')
3286 CGIexecute::defineCGIvariable($name, $default)
3287 || dieHandler(20, "INVALID CGI name/value pair ($name, $default)\n");
3288 push(@METAvalues, "'".${"CGIexecute::$name"}."'");
3289 # Add value to the @ARGV list
3290 push(@ARGV, ${"CGIexecute::$name"});
3291 ++$ARGC;
3293 elsif($varType eq '@')
3295 CGIexecute::defineCGIvariableList($name, $default)
3296 || dieHandler(21, "INVALID CGI name/value list pair ($name, $default)\n");
3297 push(@METAvalues, "'".join("'", @{"CGIexecute::$name"})."'");
3298 # Add value to the @ARGV list
3299 push(@ARGV, @{"CGIexecute::$name"});
3300 $ARGC = scalar(@CGIexecute::ARGV);
3302 elsif($varType eq '%')
3304 CGIexecute::defineCGIvariableHash($name, $default)
3305 || dieHandler(22, "INVALID CGI name/value hash pair ($name, $default)\n");
3306 my @PairList = map {"$_ => ".${"CGIexecute::$name"}{$_}} keys(%{"CGIexecute::$name"});
3307 push(@METAvalues, "'".join("'", @PairList)."'");
3308 # Add value to the @ARGV list
3309 push(@ARGV, %{"CGIexecute::$name"});
3310 $ARGC = scalar(@CGIexecute::ARGV);
3313 # Store the values for internal and later use
3314 $METAarguments .= "$varType".$name.","; # A string of CGI variable names
3316 push(@METAvalues, "\'".eval("\"$varType\{CGIexecute::$name\}\"")."\'"); # ALWAYS add '-quotes around values
3321 # The IF (conditional execution) Attribute
3322 # Evaluate the condition and stop unless it evaluates to true
3323 if($ScriptTagAttributes{'IF'})
3325 my $IFcondition = $ScriptTagAttributes{'IF'};
3327 # Convert SCRIPT calls, ./<script>
3328 $IFcondition =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
3330 # Convert FILE calls, ~/<file>
3331 $IFcondition =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
3333 # Block execution if necessary
3334 unless(CGIexecute->evaluate($IFcondition))
3336 %ScriptTagAttributes = ();
3337 $CurrentContentType = "";
3341 # The UNLESS (conditional execution) Attribute
3342 # Evaluate the condition and stop if it evaluates to true
3343 if($ScriptTagAttributes{'UNLESS'})
3345 my $UNLESScondition = $ScriptTagAttributes{'UNLESS'};
3347 # Convert SCRIPT calls, ./<script>
3348 $UNLESScondition =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
3350 # Convert FILE calls, ~/<file>
3351 $UNLESScondition =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
3353 # Block execution if necessary
3354 if(CGIexecute->evaluate($UNLESScondition))
3356 %ScriptTagAttributes = ();
3357 $CurrentContentType = "";
3361 # The SRC (Source File) Attribute
3362 # Extract any source script files and add them in
3363 # front of the directive
3364 # The SRC list should be emptied
3365 @SRClist = ();
3366 my $SRCtag = "";
3367 my $Prefix = 1;
3368 my $PrefixDirective = "";
3369 my $PostfixDirective = "";
3370 # There is a SRC attribute
3371 if($ScriptTagAttributes{'SRC'})
3373 $SRCtag = $ScriptTagAttributes{'SRC'};
3374 # Remove "file://" prefixes
3375 $SRCtag =~ s@([^\w\/\\]|^)file\://([^\s\/\@\=])@$1$2@gis;
3376 # Expand script filenames "./Script"
3377 $SRCtag =~ s@([^\w\/\\]|^)\./([^\s\/\@\=])@$1$SCRIPT_SUB/$2@gis;
3378 # Expand script filenames "~/Script"
3379 $SRCtag =~ s@([^\w\/\\]|^)\~/([^\s\/\@\=])@$1$HOME_SUB/$2@gis;
3382 # File source tags
3383 while($SRCtag =~ /\S/is)
3385 my $SRCdirective = "";
3387 # Pseudo file, just a switch to go from PREFIXING to POSTFIXING
3388 # SRC files
3389 if($SRCtag =~ /^[\s\;\,]*(POSTFIX|PREFIX)([^$FileAllowedChars]|$)/is)
3391 my $InsertionPlace = $1;
3392 $SRCtag = $2.$';
3394 $Prefix = $InsertionPlace =~ /POSTFIX/i ? 0 : 1;
3395 # Go to next round
3396 next;
3398 # {}-blocks are just evaluated by "do"
3399 elsif($SRCtag =~ /^[\s\;\,]*\{/is)
3401 my $SRCblock = $';
3402 if($SRCblock =~ /\}[\s\;\,]*([^\}]*)$/is)
3404 $SRCblock = $`;
3405 $SRCtag = $1.$';
3406 # SAFEqx shell script blocks
3407 if($CurrentContentType =~ /$ShellScriptContentType/is)
3409 # Handle ''-quotes inside the script
3410 $SRCblock =~ s/[\']/\\$&/gis;
3412 $SRCblock = "print do { SAFEqx(\'".$SRCblock."\'); };'';";
3413 $SRCdirective .= $SRCblock."\n";
3415 # do { SRCblocks }
3416 elsif($CurrentContentType =~ /$ServerScriptContentType/is)
3418 $SRCblock = "print do { $SRCblock };'';";
3419 $SRCdirective .= $SRCblock."\n";
3421 else # The interpreter should handle this
3423 push(@SRClist, "{ $SRCblock }");
3427 else
3428 { dieHandler(23, "Closing \} missing\n");};
3430 # Files are processed as Text or Executable files
3431 elsif($SRCtag =~ /[\s\;\,]*([$FileAllowedChars]+)[\;\,\s]*/is)
3433 my $SrcFile = $1;
3434 $SRCtag = $';
3436 # We are handling one of the external interpreters
3437 if($ScriptingLanguages{$CurrentContentType})
3439 push(@SRClist, $SrcFile);
3441 # We are at the start of a DIV tag, just load all SRC files and/or URL's
3442 elsif($TagType eq 'DIV' || $TagType eq 'INS') # All files are prepended in DIV's
3444 # $SrcFile is a URL pointing to an HTTP or FTP server
3445 if($SrcFile =~ m!^([a-z]+)\://!)
3447 my $URLoutput = CGIscriptor::read_url($SrcFile);
3448 $SRCdirective .= $URLoutput;
3450 # SRC file is an existing file
3451 elsif(-e "$SrcFile")
3453 open(DIVSOURCE, "<$SrcFile") || dieHandler(24, "<$SrcFile: $!\n");
3454 my $Content;
3455 while(sysread(DIVSOURCE, $Content, 1024) > 0)
3457 $SRCdirective .= $Content;
3459 close(DIVSOURCE);
3462 # Executable files are executed as
3463 # `$SrcFile 'ARGV[0]' 'ARGV[1]'`
3464 elsif(-x "$SrcFile")
3466 $SRCdirective .= "print \`$SrcFile @METAvalues\`;'';\n";
3468 # Handle 'standard' files, using ProcessFile
3469 elsif((-T "$SrcFile" || $ENV{$CGI_FILE_CONTENTS})
3470 && $SrcFile =~ m@($FilePattern)$@) # A recursion
3473 # Do not process still open files because it can lead
3474 # to endless recursions
3475 if(grep(/^$SrcFile$/, @OpenFiles))
3476 { dieHandler(25, "$SrcFile allready opened (endless recursion)\n")};
3477 # Prepare meta arguments
3478 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
3479 # Process the file
3480 $SRCdirective .= "main::ProcessFile(\'$SrcFile\');'';\n";
3482 elsif($SrcFile =~ m!^([a-z]+)\://!) # URL's are loaded and printed
3484 $SRCdirective .= GET_URL($SrcFile);
3486 elsif(-T "$SrcFile") # Textfiles are "do"-ed (Perl execution)
3488 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
3489 $SRCdirective .= "do \'$SrcFile\';'';\n";
3491 else # This one could not be resolved (should be handled by BinaryMapFile)
3493 $SRCdirective .= 'print "'.$SrcFile.' cannot be used"'."\n";
3498 # Postfix or Prefix
3499 if($Prefix)
3501 $PrefixDirective .= $SRCdirective;
3503 else
3505 $PostfixDirective .= $SRCdirective;
3508 # The prefix should be handled immediately
3509 $directive .= $PrefixDirective;
3510 $PrefixDirective = "";
3514 # Handle the content of the <SCRIPT></SCRIPT> tags
3515 # Do not process the content of <SCRIPT/>
3516 if($TagType =~ /SCRIPT/is && !$ClosedTag) # The <SCRIPT> TAG
3518 my $EndScriptTag = "";
3520 # Execute SHELL scripts with SAFEqx()
3521 if($CurrentContentType =~ /$ShellScriptContentType/is)
3523 $directive .= "SAFEqx(\'";
3526 # Extract Program
3527 while($After !~ /\<\s*\/SCRIPT[^\>]*\>/is && !eof($FileHandle))
3529 $After .= <$FileHandle>;
3530 performTranslation(\$After) if $TranslationPaths;
3533 if($After =~ /\<\s*\/SCRIPT[^\>]*\>/is)
3535 $directive .= $`;
3536 $EndScriptTag = $&;
3537 $After = $';
3539 else
3541 dieHandler(26, "Missing </SCRIPT> end tag in $ENV{'PATH_INFO'}\n");
3544 # Process only when content should be executed
3545 if($CurrentContentType)
3548 # Remove all comments from Perl scripts
3549 # (NOT from OS shell scripts)
3550 $directive =~ s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/$1/g
3551 if $CurrentContentType =~ /$ServerScriptContentType/i;
3553 # Convert SCRIPT calls, ./<script>
3554 $directive =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
3556 # Convert FILE calls, ~/<file>
3557 $directive =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
3559 # Execute SHELL scripts with SAFEqx(), closing bracket
3560 if($CurrentContentType =~ /$ShellScriptContentType/i)
3562 # Handle ''-quotes inside the script
3563 $directive =~ /SAFEqx\(\'/;
3564 $directive = $`.$&;
3565 my $Executable = $';
3566 $Executable =~ s/[\']/\\$&/gs;
3568 $directive .= $Executable."\');"; # Closing bracket
3571 else
3573 $directive = "";
3576 # Handle the content of the <DIV></DIV> tags
3577 # Do not process the content of <DIV/>
3578 elsif(($TagType eq 'DIV' || $TagType eq 'INS') && !$ClosedTag) # The <DIV> TAGs
3580 my $EndScriptTag = "";
3582 # Extract Text
3583 while($After !~ /\<\s*\/$TagType[^\>]*\>/is && !eof($FileHandle))
3585 $After .= <$FileHandle>;
3586 performTranslation(\$After) if $TranslationPaths;
3589 if($After =~ /\<\s*\/$TagType[^\>]*\>/is)
3591 $directive .= $`;
3592 $EndScriptTag = $&;
3593 $After = $';
3595 else
3597 dieHandler(27, "Missing </$TagType> end tag in $ENV{'PATH_INFO'}\n");
3600 # Add the Postfixed directives (but only when it contains something printable)
3601 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
3602 $PostfixDirective = "";
3605 # Process only when content should be handled
3606 if($CurrentContentType)
3609 # Get the name (ID), and clean it (i.e., remove anything that is NOT part of
3610 # a valid Perl name). Names should not contain $, but we can handle it.
3611 my $name = $ScriptTagAttributes{'ID'};
3612 $name =~ /^\s*[\$\@\%]?([\w\-]+)/;
3613 $name = $1;
3615 # Assign DIV contents to $NAME value OUTSIDE the CGI values!
3616 CGIexecute::defineCGIexecuteVariable($name, $directive);
3617 $directive = "";
3620 # Nothing to execute
3621 $directive = "";
3625 # Handle Foreign scripting languages
3626 if($ScriptingLanguages{$CurrentContentType})
3628 my $newDirective = "";
3629 $newDirective .= OpenForeignScript($CurrentContentType); # Only if not already done
3630 $newDirective .= PrefixForeignScript($CurrentContentType);
3631 $newDirective .= InsertForeignScript($CurrentContentType, $directive, @SRClist);
3632 $newDirective .= PostfixForeignScript($CurrentContentType);
3633 $newDirective .= CloseForeignScript($CurrentContentType); # This shouldn't be necessary
3635 $newDirective .= '"";';
3637 $directive = $newDirective;
3641 # Add the Postfixed directives (but only when it contains something printable)
3642 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
3643 $PostfixDirective = "";
3646 # EXECUTE the script and print the results
3648 # Use this to debug the program
3649 # print STDERR "Directive $CGI_Date: \n", $directive, "\n\n";
3651 my $Result = CGIexecute->evaluate($directive) if $directive; # Evaluate as PERL code
3652 $Result =~ s/\n$//g; # Remove final newline
3654 # Print the Result of evaluating the directive
3655 # (this will handle LARGE, >64 kB output)
3656 my $BytesWritten = 1;
3657 while($Result && $BytesWritten)
3659 $BytesWritten = syswrite(STDOUT, $Result, 64);
3660 $Result = substr($Result, $BytesWritten);
3662 # print $Result; # Could be used instead of above code
3664 # Store result if wanted, i.e., if $CGIscriptorResults has been
3665 # defined in a <META> tag.
3666 push(@CGIexecute::CGIscriptorResults, $Result)
3667 if exists($default_values{'CGIscriptorResults'});
3669 # Process the rest of the input line (this could contain
3670 # another directive)
3671 $_ = $After;
3673 print $_;
3674 } while(<$FileHandle>); # Read and Test AFTER first loop!
3676 close ($FileHandle);
3677 dieHandler(28, "Error in recursion\n") unless pop(@OpenFiles) == $file_path;
3681 ###############################################################################
3683 # Call the whole package
3685 sub Handle_Request
3687 my $file_path = "";
3689 # Initialization Code
3690 Initialize_Request();
3692 # SECURITY: ACCESS CONTROL
3693 Access_Control();
3695 # Read the POST part of the query, if there is one
3696 Get_POST_part_of_query();
3698 # Start (HTML) output and logging
3699 $file_path = Initialize_output();
3701 # Check login access or divert to login procedure
3702 $access_allowed = Log_In_Access();
3703 return "" unless $access_allowed;
3705 # Record which files are still open (to avoid endless recursions)
3706 my @OpenFiles = ();
3708 # Record whether the default HTML ContentType has already been printed
3709 # but only if the SERVER uses HTTP or some other protocol that might interpret
3710 # a content MIME type.
3712 $SupressContentType = !("$ENV{'SERVER_PROTOCOL'}" =~ /($ContentTypeServerProtocols)/i);
3714 # Process the specified file
3715 ProcessFile($file_path) if $file_path ne $SS_PUB;
3717 # Cleanup all open external (foreign) interpreters
3718 CloseAllForeignScripts();
3721 "" # SUCCESS
3724 # Make a single call to handle an (empty) request
3725 Handle_Request();
3728 # END OF PACKAGE MAIN
3731 ####################################################################################
3733 # The CGIEXECUTE PACKAGE
3735 ####################################################################################
3737 # Isolate the evaluation of directives as PERL code from the rest of the program.
3738 # Remember that each package has its own name space.
3739 # Note that only the FIRST argument of execute->evaluate is actually evaluated,
3740 # all other arguments are accessible inside the first argument as $_[0] to $_[$#_].
3742 package CGIexecute;
3744 sub evaluate
3746 my $self = shift;
3747 my $directive = shift;
3748 $directive = eval($directive);
3749 warn $@ if $@; # Write an error message to STDERR
3750 $directive; # Return value of directive
3754 # defineCGIexecuteVariable($name [, $value]) -> 0/1
3756 # Define and intialize variables inside CGIexecute
3757 # Does no sanity checking, for internal use only
3759 sub defineCGIexecuteVariable # ($name [, $value]) -> 0/1
3761 my $name = shift || return 0; # The Name
3762 my $value = shift || ""; # The value
3764 ${$name} = $value;
3766 return 1;
3769 # defineCGIvariable($name [, $default]) -> 0/1
3771 # Define and intialize CGI variables
3772 # Tries (in order) $ENV{$name}, the Query string and the
3773 # default value.
3774 # Removes all '-quotes etc.
3776 sub defineCGIvariable # ($name [, $default]) -> 0/1
3778 my $name = shift || return 0; # The Name
3779 my $default = shift || ""; # The default value
3781 # Remove \-quoted characters
3782 $default =~ s/\\(.)/$1/g;
3783 # Store default values
3784 $::default_values{$name} = $default if $default;
3786 # Process variables
3787 my $temp = undef;
3788 # If there is a user supplied value, it replaces the
3789 # default value.
3791 # Environment values have precedence
3792 if(exists($ENV{$name}))
3794 $temp = $ENV{$name};
3796 # Get name and its value from the query string
3797 elsif($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
3799 $temp = ::YOUR_CGIPARSE($name);
3801 # Defined values must exist for security
3802 elsif(!exists($::default_values{$name}))
3804 $::default_values{$name} = undef;
3807 # SECURITY, do not allow '- and `-quotes in
3808 # client values.
3809 # Remove all existing '-quotes
3810 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
3811 $temp =~ s/[\']/&#8217;/igs; # Remove all single quotes
3812 $temp =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
3813 # If $temp is empty, use the default value (if it exists)
3814 unless($temp =~ /\S/ || length($temp) > 0) # I.e., $temp is empty
3816 $temp = $::default_values{$name};
3817 # Remove all existing '-quotes
3818 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
3819 $temp =~ s/[\']/&#8217;/igs; # Remove all single quotes
3820 $temp =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
3822 else # Store current CGI values and remove defaults
3824 $::default_values{$name} = $temp;
3826 # Define the CGI variable and its value (in the execute package)
3827 ${$name} = $temp;
3829 # return SUCCES
3830 return 1;
3833 sub defineCGIvariableList # ($name [, $default]) -> 0/1)
3835 my $name = shift || return 0; # The Name
3836 my $default = shift || ""; # The default value
3838 # Defined values must exist for security
3839 if(!exists($::default_values{$name}))
3841 $::default_values{$name} = $default;
3844 my @temp = ();
3847 # For security:
3848 # Environment values have precedence
3849 if(exists($ENV{$name}))
3851 push(@temp, $ENV{$name});
3853 # Get name and its values from the query string
3854 if($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
3856 push(@temp, ::YOUR_CGIPARSE($name, 1)); # Extract LIST
3858 else
3860 push(@temp, $::default_values{$name});
3864 # SECURITY, do not allow '- and `-quotes in
3865 # client values.
3866 # Remove all existing '-quotes
3867 @temp = map {s/([\r\f]+\n)/\n/g; $_} @temp; # Only \n is allowed
3868 @temp = map {s/[\']/&#8217;/igs; $_} @temp; # Remove all single quotes
3869 @temp = map {s/[\`]/&#8216;/igs; $_} @temp; # Remove all backtick quotes
3871 # Store current CGI values and remove defaults
3872 $::default_values{$name} = $temp[0];
3874 # Define the CGI variable and its value (in the execute package)
3875 @{$name} = @temp;
3877 # return SUCCES
3878 return 1;
3881 sub defineCGIvariableHash # ($name [, $default]) -> 0/1) Note: '$name{""} = $default';
3883 my $name = shift || return 0; # The Name
3884 my $default = shift || ""; # The default value
3886 # Defined values must exist for security
3887 if(!exists($::default_values{$name}))
3889 $::default_values{$name} = $default;
3892 my %temp = ();
3895 # For security:
3896 # Environment values have precedence
3897 if(exists($ENV{$name}))
3899 $temp{""} = $ENV{$name};
3901 # Get name and its values from the query string
3902 if($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
3904 %temp = ::YOUR_CGIPARSE($name, -1); # Extract HASH table
3906 elsif($::default_values{$name} ne "")
3908 $temp{""} = $::default_values{$name};
3912 # SECURITY, do not allow '- and `-quotes in
3913 # client values.
3914 # Remove all existing '-quotes
3915 my $Key;
3916 foreach $Key (keys(%temp))
3918 $temp{$Key} =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
3919 $temp{$Key} =~ s/[\']/&#8217;/igs; # Remove all single quotes
3920 $temp{$Key} =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
3923 # Store current CGI values and remove defaults
3924 $::default_values{$name} = $temp{""};
3926 # Define the CGI variable and its value (in the execute package)
3927 %{$name} = ();
3928 my $tempKey;
3929 foreach $tempKey (keys(%temp))
3931 ${$name}{$tempKey} = $temp{$tempKey};
3934 # return SUCCES
3935 return 1;
3939 # SAFEqx('CommandString')
3941 # A special function that is a safe alternative to backtick quotes (and qx//)
3942 # with client-supplied CGI values. All CGI variables are surrounded by
3943 # single ''-quotes (except between existing \'\'-quotes, don't try to be
3944 # too smart). All variables are then interpolated. Simple (@) lists are
3945 # expanded with join(' ', @List), and simple (%) hash tables expanded
3946 # as a list of "key=value" pairs. Complex variables, e.g., @$var, are
3947 # evaluated in a scalar context (e.g., as scalar(@$var)). All occurrences of
3948 # $@% that should NOT be interpolated must be preceeded by a "\".
3949 # If the first line of the String starts with "#! interpreter", the
3950 # remainder of the string is piped into interpreter (after interpolation), i.e.,
3951 # open(INTERPRETER, "|interpreter");print INTERPRETER remainder;
3952 # just like in UNIX. There are some problems with quotes. Be carefull in
3953 # using them. You do not have access to the output of any piped (#!)
3954 # process! If you want such access, execute
3955 # <SCRIPT TYPE="text/osshell">echo "script"|interpreter</SCRIPT> or
3956 # <SCRIPT TYPE="text/ssperl">$resultvar = SAFEqx('echo "script"|interpreter');
3957 # </SCRIPT>.
3959 # SAFEqx ONLY WORKS WHEN THE STRING ITSELF IS SURROUNDED BY SINGLE QUOTES
3960 # (SO THAT IT IS NOT INTERPOLATED BEFORE IT CAN BE PROTECTED)
3961 sub SAFEqx # ('String') -> result of executing qx/"String"/
3963 my $CommandString = shift;
3964 my $NewCommandString = "";
3966 # Only interpolate when required (check the On/Off switch)
3967 unless($CGIscriptor::NoShellScriptInterpolation)
3970 # Handle existing single quotes around CGI values
3971 while($CommandString =~ /\'[^\']+\'/s)
3973 my $CurrentQuotedString = $&;
3974 $NewCommandString .= $`;
3975 $CommandString = $'; # The remaining string
3976 # Interpolate CGI variables between quotes
3977 # (e.g., '$CGIscriptorResults[-1]')
3978 $CurrentQuotedString =~
3979 s/(^|[^\\])([\$\@])((\w*)([\{\[][\$\@\%]?[\:\w\-]+[\}\]])*)/if(exists($main::default_values{$4})){
3980 "$1".eval("$2$3")}else{"$&"}/egs;
3982 # Combine result with previous result
3983 $NewCommandString .= $CurrentQuotedString;
3985 $CommandString = $NewCommandString.$CommandString;
3987 # Select known CGI variables and surround them with single quotes,
3988 # then interpolate all variables
3989 $CommandString =~
3990 s/(^|[^\\])([\$\@\%]+)((\w*)([\{\[][\w\:\$\"\-]+[\}\]])*)/
3991 if($2 eq '$' && exists($main::default_values{$4}))
3992 {"$1\'".eval("\$$3")."\'";}
3993 elsif($2 eq '@'){$1.join(' ', @{"$3"});}
3994 elsif($2 eq '%'){my $t=$1;map {$t.=" $_=".${"$3"}{$_}}
3995 keys(%{"$3"});$t}
3996 else{$1.eval("${2}$3");
3997 }/egs;
3999 # Remove backslashed [$@%]
4000 $CommandString =~ s/\\([\$\@\%])/$1/gs;
4003 # Debugging
4004 # return $CommandString;
4006 # Handle UNIX style "#! shell command\n" constructs as
4007 # a pipe into the shell command. The output cannot be tapped.
4008 my $ReturnValue = "";
4009 if($CommandString =~ /^\s*\#\!([^\f\n\r]+)[\f\n\r]/is)
4011 my $ShellScripts = $';
4012 my $ShellCommand = $1;
4013 open(INTERPRETER, "|$ShellCommand") || dieHandler(29, "\'$ShellCommand\' PIPE not opened: &!\n");
4014 select(INTERPRETER);$| = 1;
4015 print INTERPRETER $ShellScripts;
4016 close(INTERPRETER);
4017 select(STDOUT);$| = 1;
4019 # Shell scripts which are redirected to an existing named pipe.
4020 # The output cannot be tapped.
4021 elsif($CGIscriptor::ShellScriptPIPE)
4023 CGIscriptor::printSAFEqxPIPE($CommandString);
4025 else # Plain ``-backtick execution
4027 # Execute the commands
4028 $ReturnValue = qx/$CommandString/;
4030 return $ReturnValue;
4033 ####################################################################################
4035 # The CGIscriptor PACKAGE
4037 ####################################################################################
4039 # Isolate the evaluation of CGIscriptor functions, i.e., those prefixed with
4040 # "CGIscriptor::"
4042 package CGIscriptor;
4045 # The Interpolation On/Off switch
4046 my $NoShellScriptInterpolation = undef;
4047 # The ShellScript redirection pipe
4048 my $ShellScriptPIPE = undef;
4050 # Open a named PIPE for SAFEqx to receive ALL shell scripts
4051 sub RedirectShellScript # ('CommandString')
4053 my $CommandString = shift || undef;
4055 if($CommandString)
4057 $ShellScriptPIPE = "ShellScriptNamedPipe";
4058 open($ShellScriptPIPE, "|$CommandString")
4059 || main::dieHandler(30, "\'|$CommandString\' PIPE open failed: $!\n");
4061 else
4063 close($ShellScriptPIPE);
4064 $ShellScriptPIPE = undef;
4066 return $ShellScriptPIPE;
4069 # Print to redirected shell script pipe
4070 sub printSAFEqxPIPE # ("String") -> print return value
4072 my $String = shift || undef;
4074 select($ShellScriptPIPE); $| = 1;
4075 my $returnvalue = print $ShellScriptPIPE ($String);
4076 select(STDOUT); $| = 1;
4078 return $returnvalue;
4081 # a pointer to CGIexecute::SAFEqx
4082 sub SAFEqx # ('String') -> result of qx/"String"/
4084 my $CommandString = shift;
4085 return CGIexecute::SAFEqx($CommandString);
4089 # a pointer to CGIexecute::defineCGIvariable
4090 sub defineCGIvariable # ($name[, $default]) ->0/1
4092 my $name = shift;
4093 my $default = shift;
4094 return CGIexecute::defineCGIvariable($name, $default);
4098 # Decode URL encoded arguments
4099 sub URLdecode # (URL encoded input) -> string
4101 my $output = "";
4102 my $char;
4103 my $Value;
4104 foreach $Value (@_)
4106 my $EncodedValue = $Value; # Do not change the loop variable
4107 # Convert all "+" to " "
4108 $EncodedValue =~ s/\+/ /g;
4109 # Convert all hexadecimal codes (%FF) to their byte values
4110 while($EncodedValue =~ /\%([0-9A-F]{2})/i)
4112 $output .= $`.chr(hex($1));
4113 $EncodedValue = $';
4115 $output .= $EncodedValue; # The remaining part of $Value
4117 $output;
4120 # Encode arguments as URL codes.
4121 sub URLencode # (input) -> URL encoded string
4123 my $output = "";
4124 my $char;
4125 my $Value;
4126 foreach $Value (@_)
4128 my @CharList = split('', $Value);
4129 foreach $char (@CharList)
4131 if($char =~ /\s/)
4132 { $output .= "+";}
4133 elsif($char =~ /\w\-/)
4134 { $output .= $char;}
4135 else
4137 $output .= uc(sprintf("%%%2.2x", ord($char)));
4141 $output;
4144 # Extract the value of a CGI variable from the URL-encoded $string
4145 # Also extracts the data blocks from a multipart request. Does NOT
4146 # decode the multipart blocks
4147 sub CGIparseValue # (ValueName [, URL_encoded_QueryString [, \$QueryReturnReference]]) -> Decoded value
4149 my $ValueName = shift;
4150 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4151 my $ReturnReference = shift || undef;
4152 my $output = "";
4154 if($QueryString =~ /(^|\&)$ValueName\=([^\&]*)(\&|$)/)
4156 $output = URLdecode($2);
4157 $$ReturnReference = $' if ref($ReturnReference);
4159 # Get multipart POST or PUT methods
4160 elsif($main::ENV{'CONTENT_TYPE'} =~ m@(multipart/([\w\-]+)\;\s+boundary\=([\S]+))@i)
4162 my $MultipartType = $2;
4163 my $BoundaryString = $3;
4164 # Remove the boundary-string
4165 my $temp = $QueryString;
4166 $temp =~ /^\Q--$BoundaryString\E/m;
4167 $temp = $';
4169 # Identify the newline character(s), this is the first character in $temp
4170 my $NewLine = "\r\n"; # Actually, this IS the correct one
4171 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
4173 # Is this correct??? I have to check.
4174 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
4175 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
4176 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
4177 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
4180 # search through all data blocks
4181 while($temp =~ /^\Q--$BoundaryString\E/m)
4183 my $DataBlock = $`;
4184 $temp = $';
4185 # Get the empty line after the header
4186 $DataBlock =~ /$NewLine$NewLine/;
4187 $Header = $`;
4188 $output = $';
4189 my $Header = $`;
4190 $output = $';
4192 # Remove newlines from the header
4193 $Header =~ s/$NewLine/ /g;
4195 # Look whether this block is the one you are looking for
4196 # Require the quotes!
4197 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
4199 my $i;
4200 for($i=length($NewLine); $i; --$i)
4202 chop($output);
4204 # OK, get out
4205 last;
4207 # reinitialize the output
4208 $output = "";
4210 $$ReturnReference = $temp if ref($ReturnReference);
4212 elsif($QueryString !~ /(^|\&)$ValueName\=/) # The value simply isn't there
4214 return undef;
4215 $$ReturnReference = undef if ref($ReturnReference);
4217 else
4219 print "ERROR: $ValueName $main::ENV{'CONTENT_TYPE'}\n";
4221 return $output;
4225 # Get a list of values for the same ValueName. Uses CGIparseValue
4227 sub CGIparseValueList # (ValueName [, URL_encoded_QueryString]) -> List of decoded values
4229 my $ValueName = shift;
4230 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4231 my @output = ();
4232 my $RestQueryString;
4233 my $Value;
4234 while($QueryString &&
4235 (($Value = CGIparseValue($ValueName, $QueryString, \$RestQueryString))
4236 || defined($Value)))
4238 push(@output, $Value);
4239 $QueryString = $RestQueryString; # QueryString is consumed!
4241 # ready, return list with values
4242 return @output;
4245 sub CGIparseValueHash # (ValueName [, URL_encoded_QueryString]) -> Hash table of decoded values
4247 my $ValueName = shift;
4248 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4249 my $RestQueryString;
4250 my %output = ();
4251 while($QueryString && $QueryString =~ /(^|\&)$ValueName([\w]*)\=/)
4253 my $Key = $2;
4254 my $Value = CGIparseValue("$ValueName$Key", $QueryString, \$RestQueryString);
4255 $output{$Key} = $Value;
4256 $QueryString = $RestQueryString; # QueryString is consumed!
4258 # ready, return list with values
4259 return %output;
4262 sub CGIparseForm # ([URL_encoded_QueryString]) -> Decoded Form (NO multipart)
4264 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4265 my $output = "";
4267 $QueryString =~ s/\&/\n/g;
4268 $output = URLdecode($QueryString);
4270 $output;
4273 # Extract the header of a multipart CGI variable from the POST input
4274 sub CGIparseHeader # (ValueName [, URL_encoded_QueryString]) -> Decoded value
4276 my $ValueName = shift;
4277 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4278 my $output = "";
4280 if($main::ENV{'CONTENT_TYPE'} =~ m@(multipart/([\w\-]+)\;\s+boundary\=([\S]+))@i)
4282 my $MultipartType = $2;
4283 my $BoundaryString = $3;
4284 # Remove the boundary-string
4285 my $temp = $QueryString;
4286 $temp =~ /^\Q--$BoundaryString\E/m;
4287 $temp = $';
4289 # Identify the newline character(s), this is the first character in $temp
4290 my $NewLine = "\r\n"; # Actually, this IS the correct one
4291 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
4293 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
4294 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
4295 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
4296 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
4299 # search through all data blocks
4300 while($temp =~ /^\Q--$BoundaryString\E/m)
4302 my $DataBlock = $`;
4303 $temp = $';
4304 # Get the empty line after the header
4305 $DataBlock =~ /$NewLine$NewLine/;
4306 $Header = $`;
4307 my $Header = $`;
4309 # Remove newlines from the header
4310 $Header =~ s/$NewLine/ /g;
4312 # Look whether this block is the one you are looking for
4313 # Require the quotes!
4314 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
4316 $output = $Header;
4317 last;
4319 # reinitialize the output
4320 $output = "";
4323 return $output;
4327 # Checking variables for security (e.g., file names and email addresses)
4328 # File names are tested against the $::FileAllowedChars and $::BlockPathAccess variables
4329 sub CGIsafeFileName # FileName -> FileName or ""
4331 my $FileName = shift || "";
4332 return "" if $FileName =~ m?[^$::FileAllowedChars]?;
4333 return "" if $FileName =~ m!(^|/|\:)\-!;
4334 return "" if $FileName =~ m@\.\.\Q$::DirectorySeparator\E@; # Higher directory not allowed
4335 return "" if $FileName =~ m@\Q$::DirectorySeparator\E\.\.@; # Higher directory not allowed
4336 return "" if $::BlockPathAccess && $FileName =~ m@$::BlockPathAccess@; # Invisible (blocked) file
4338 return $FileName;
4341 sub CGIsafeEmailAddress # email -> email or ""
4343 my $Email = shift || "";
4344 return "" unless $Email =~ m/^[\w\.\-]+[\@][\w\.\-\:]+$/;
4345 return $Email;
4348 # Get a URL from the web. Needs main::GET_URL($URL) function
4349 # (i.e., curl, snarf, or wget)
4350 sub read_url # ($URL) -> page/file
4352 my $URL = shift || return "";
4354 # Get the commands to read the URL, do NOT add a print command
4355 my $URL_command = main::GET_URL($URL, 1);
4356 # execute the commands, i.e., actually read it
4357 my $URLcontent = CGIexecute->evaluate($URL_command);
4359 # Ready, return the content.
4360 return $URLcontent;
4363 ################################################>>>>>>>>>>Start Remove
4365 # BrowseDirs(RootDirectory [, Pattern, Start])
4367 # usage:
4368 # <SCRIPT TYPE='text/ssperl'>
4369 # CGIscriptor::BrowseDirs('Sounds', '\.aifc$', 'Speech', 'DIRECTORY')
4370 # </SCRIPT>
4372 # Allows to browse subdirectories. Start should be relative to the RootDirectory,
4373 # e.g., the full path of the directory 'Speech' is '~/Sounds/Speech'.
4374 # Only files which fit /$Pattern/ and directories are displayed.
4375 # Directories down or up the directory tree are supplied with a
4376 # GET request with the name of the CGI variable in the fourth argument (default
4377 # is 'BROWSEDIRS'). So the correct call for a subdirectory could be:
4378 # CGIscriptor::BrowseDirs('Sounds', '\.aifc$', $DIRECTORY, 'DIRECTORY')
4380 sub BrowseDirs # (RootDirectory [, Pattern, Start, CGIvariable, HTTPserver]) -> Print HTML code
4382 my $RootDirectory = shift; # || return 0;
4383 my $Pattern = shift || '\S';
4384 my $Start = shift || "";
4385 my $CGIvariable = shift || "BROWSEDIRS";
4386 my $HTTPserver = shift || '';
4388 $Start = CGIscriptor::URLdecode($Start); # Sometimes, too much has been encoded
4389 $Start =~ s@//+@/@g;
4390 $Start =~ s@[^/]+/\.\.@@ig;
4391 $Start =~ s@^\.\.@@ig;
4392 $Start =~ s@/\.$@@ig;
4393 $Start =~ s!/+$!!g;
4394 $Start .= "/" if $Start;
4396 my @Directory = glob("$::CGI_HOME/$RootDirectory/$Start");
4397 $CurrentDirectory = shift(@Directory);
4398 $CurrentDirectory = $' if $CurrentDirectory =~ m@(/\.\./)+@;
4399 $CurrentDirectory =~ s@^$::CGI_HOME@@g;
4400 print "<h1>";
4401 print "$CurrentDirectory" if $CurrentDirectory;
4402 print "</h1>\n";
4403 opendir(BROWSE, "$::CGI_HOME/$RootDirectory/$Start") || main::dieHandler(31, "$::CGI_HOME/$RootDirectory/$Start $!");
4404 my @AllFiles = sort grep(!/^([\.]+[^\.]|\~)/, readdir(BROWSE));
4406 # Print directories
4407 my $file;
4408 print "<pre><ul TYPE='NONE'>\n";
4409 foreach $file (@AllFiles)
4411 next unless -d "$::CGI_HOME/$RootDirectory/$Start$file";
4412 # Check whether this file should be visible
4413 next if $::BlockPathAccess &&
4414 "/$RootDirectory/$Start$file/" =~ m@$::BlockPathAccess@;
4416 my $NewURL = $Start ? "$Start$file" : $file;
4417 $NewURL = CGIscriptor::URLencode($NewURL);
4418 print "<dt><a href='";
4419 print "$ENV{SCRIPT_NAME}" if $ENV{SCRIPT_NAME} !~ m@[^\w+\-/]@;
4420 print "$ENV{PATH_INFO}?$CGIvariable=$NewURL'>$file</a></dt>\n";
4422 print "</ul></pre>\n";
4424 # Print files
4425 print "<pre><ul TYPE='CIRCLE'>\n";
4426 my $TotalSize = 0;
4427 foreach $file (@AllFiles)
4429 next if $file =~ /^\./;
4430 next if -d "$::CGI_HOME/$RootDirectory/$Start$file";
4431 next if -l "$::CGI_HOME/$RootDirectory/$Start$file";
4432 # Check whether this file should be visible
4433 next if $::BlockPathAccess &&
4434 "$::CGI_HOME/$RootDirectory/$Start$file" =~ m@$::BlockPathAccess@;
4436 if($file =~ m@$Pattern@)
4438 my $Date = localtime($^T - (-M "$::CGI_HOME/$RootDirectory/$Start$file")*3600*24);
4439 my $Size = -s "$::CGI_HOME/$RootDirectory/$Start$file";
4440 $Size = sprintf("%6.0F kB", $Size/1024);
4441 my $Type = `file $::CGI_HOME/$RootDirectory/$Start$file`;
4442 $Type =~ s@\s*$::CGI_HOME/$RootDirectory/$Start$file\s*\:\s*@@ig;
4443 chomp($Type);
4445 print "<li>";
4446 if($HTTPserver =~ /^\s*[\.\~]\s*$/)
4448 print "<a href='$Start$file'>";
4450 elsif($HTTPserver)
4452 print "<a href='$HTTPserver/$RootDirectory/$Start$file'>";
4454 printf("%-40s", "$file</a>") if $HTTPserver;
4455 printf("%-40s", "$file") unless $HTTPserver;
4456 print "\t$Size\t$Date\t$Type";
4457 print "</li>\n";
4460 print "</ul></pre>";
4462 return 1;
4466 # ListDocs(Pattern [,ListType])
4468 # usage:
4469 # <SCRIPT TYPE=text/ssperl>
4470 # CGIscriptor::ListDocs("/*", "dl");
4471 # </SCRIPT>
4473 # This subroutine is very usefull to manage collections of independent
4474 # documents. The resulting list will display the tree-like directory
4475 # structure. If this routine is too slow for online use, you can
4476 # store the result and use a link to that stored file.
4478 # List HTML and Text files with title and first header (HTML)
4479 # or filename and first meaningfull line (general text files).
4480 # The listing starts at the ServerRoot directory. Directories are
4481 # listed recursively.
4483 # You can change the list type (default is dl).
4484 # e.g.,
4485 # <dt><a href=<file.html>>title</a>
4486 # <dd>First Header
4487 # <dt><a href=<file.txt>>file.txt</a>
4488 # <dd>First meaningfull line of text
4490 sub ListDocs # ($Pattern [, prefix]) e.g., ("/Books/*", [, "dl"])
4492 my $Pattern = shift;
4493 $Pattern =~ /\*/;
4494 my $ListType = shift || "dl";
4495 my $Prefix = lc($ListType) eq "dl" ? "dt" : "li";
4496 my $URL_root = "http://$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}";
4497 my @FileList = glob("$::CGI_HOME$Pattern");
4498 my ($FileName, $Path, $Link);
4500 # Print List markers
4501 print "<$ListType>\n";
4503 # Glob all files
4504 File: foreach $FileName (@FileList)
4506 # Check whether this file should be visible
4507 next if $::BlockPathAccess && $FileName =~ m@$::BlockPathAccess@;
4509 # Recursively list files in all directories
4510 if(-d $FileName)
4512 $FileName =~ m@([^/]*)$@;
4513 my $DirName = $1;
4514 print "<$Prefix>$DirName\n";
4515 $Pattern =~ m@([^/]*)$@;
4516 &ListDocs("$`$DirName/$1", $ListType);
4517 next;
4519 # Use textfiles
4520 elsif(-T "$FileName")
4522 open(TextFile, $FileName) || next;
4524 # Ignore all other file types
4525 else
4526 { next;};
4528 # Get file path for link
4529 $FileName =~ /$::CGI_HOME/;
4530 print "<$Prefix><a href=$URL_root$'>";
4531 # Initialize all variables
4532 my $Line = "";
4533 my $TitleFound = 0;
4534 my $Caption = "";
4535 my $Title = "";
4536 # Read file and step through
4537 while(<TextFile>)
4539 chop $_;
4540 $Line = $_;
4541 # HTML files
4542 if($FileName =~ /\.ht[a-zA-Z]*$/i)
4544 # Catch Title
4545 while(!$Title)
4547 if($Line =~ m@<title>([^<]*)</title>@i)
4549 $Title = $1;
4550 $Line = $';
4552 else
4554 $Line .= <TextFile> || goto Print;
4555 chop $Line;
4558 # Catch First Header
4559 while(!$Caption)
4561 if($Line =~ m@</h1>@i)
4563 $Caption = $`;
4564 $Line = $';
4565 $Caption =~ m@<h1>@i;
4566 $Caption = $';
4567 $Line = $`.$Caption.$Line;
4569 else
4571 $Line .= <TextFile> || goto Print;
4572 chop $Line;
4576 # Other text files
4577 else
4579 # Title equals file name
4580 $FileName =~ /([^\/]+)$/;
4581 $Title = $1;
4582 # Catch equals First Meaningfull line
4583 while(!$Caption)
4585 if($Line =~ /[A-Z]/ &&
4586 ($Line =~ /subject|title/i || $Line =~ /^[\w,\.\s\?\:]+$/)
4587 && $Line !~ /Newsgroup/ && $Line !~ /\:\s*$/)
4589 $Line =~ s/\<[^\>]+\>//g;
4590 $Caption = $Line;
4592 else
4594 $Line = <TextFile> || goto Print;
4598 Print: # Print title and subject
4599 print "$Title</a>\n";
4600 print "<dd>$Caption\n" if $ListType eq "dl";
4601 $TitleFound = 0;
4602 $Caption = "";
4603 close TextFile;
4604 next File;
4607 # Print Closing List Marker
4608 print "</$ListType>\n";
4609 ""; # Empty return value
4613 # HTMLdocTree(Pattern [,ListType])
4615 # usage:
4616 # <SCRIPT TYPE=text/ssperl>
4617 # CGIscriptor::HTMLdocTree("/Welcome.html", "dl");
4618 # </SCRIPT>
4620 # The following subroutine is very usefull for checking large document
4621 # trees. Starting from the root (s), it reads all files and prints out
4622 # a nested list of links to all attached files. Non-existing or misplaced
4623 # files are flagged. This is quite a file-i/o intensive routine
4624 # so you would not like it to be accessible to everyone. If you want to
4625 # use the result, save the whole resulting page to disk and use a link
4626 # to this file.
4628 # HTMLdocTree takes an HTML file or file pattern and constructs nested lists
4629 # with links to *local* files (i.e., only links to the local server are
4630 # followed). The list entries are the document titles.
4631 # If the list type is <dl>, the first <H1> header is used too.
4632 # For each file matching the pattern, a list is made recursively of all
4633 # HTML documents that are linked from it and are stored in the same directory
4634 # or a sub-directory. Warnings are given for missing files.
4635 # The listing starts for the ServerRoot directory.
4636 # You can change the default list type <dl> (<dl>, <ul>, <ol>).
4638 %LinkUsed = ();
4640 sub HTMLdocTree # ($Pattern [, listtype])
4641 # e.g., ("/Welcome.html", [, "ul"])
4643 my $Pattern = shift;
4644 my $ListType = shift || "dl";
4645 my $Prefix = lc($ListType) eq "dl" ? "dt" : "li";
4646 my $URL_root = "http://$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}";
4647 my ($Filename, $Path, $Link);
4648 my %LocalLinks = {};
4650 # Read files (glob them for expansion of wildcards)
4651 my @FileList = glob("$::CGI_HOME$Pattern");
4652 foreach $Path (@FileList)
4654 # Get URL_path
4655 $Path =~ /$::CGI_HOME/;
4656 my $URL_path = $';
4657 # Check whether this file should be visible
4658 next if $::BlockPathAccess && $URL_path =~ m@$::BlockPathAccess@;
4660 my $Title = $URL_path;
4661 my $Caption = "";
4662 # Current file should not be used again
4663 ++$LinkUsed{$URL_path};
4664 # Open HTML doc
4665 unless(open(TextFile, $Path))
4667 print "<$Prefix>$Title <blink>(not found)</blink><br>\n";
4668 next;
4670 while(<TextFile>)
4672 chop $_;
4673 $Line = $_;
4674 # Catch Title
4675 while($Line =~ m@<title>@i)
4677 if($Line =~ m@<title>([^<]*)</title>@i)
4679 $Title = $1;
4680 $Line = $';
4682 else
4684 $Line .= <TextFile>;
4685 chop $Line;
4688 # Catch First Header
4689 while(!$Caption && $Line =~ m@<h1>@i)
4691 if($Line =~ m@</h[1-9]>@i)
4693 $Caption = $`;
4694 $Line = $';
4695 $Caption =~ m@<h1>@i;
4696 $Caption = $';
4697 $Line = $`.$Caption.$Line;
4699 else
4701 $Line .= <TextFile>;
4702 chop $Line;
4705 # Catch and print Links
4706 while($Line =~ m@<a href\=([^>]*)>@i)
4708 $Link = $1;
4709 $Line = $';
4710 # Remove quotes
4711 $Link =~ s/\"//g;
4712 # Remove extras
4713 $Link =~ s/[\#\?].*$//g;
4714 # Remove Servername
4715 if($Link =~ m@(http://|^)@i)
4717 $Link = $';
4718 # Only build tree for current server
4719 next unless $Link =~ m@$::ENV{'SERVER_NAME'}|^/@;
4720 # Remove server name and port
4721 $Link =~ s@^[^\/]*@@g;
4723 # Store the current link
4724 next if $LinkUsed{$Link} || $Link eq $URL_path;
4725 ++$LinkUsed{$Link};
4726 ++$LocalLinks{$Link};
4730 close TextFile;
4731 print "<$Prefix>";
4732 print "<a href=http://";
4733 print "$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}$URL_path>";
4734 print "$Title</a>\n";
4735 print "<br>$Caption\n"
4736 if $Caption && $Caption ne $Title && $ListType =~ /dl/i;
4737 print "<$ListType>\n";
4738 foreach $Link (keys(%LocalLinks))
4740 &HTMLdocTree($Link, $ListType);
4742 print "</$ListType>\n";
4746 ###########################<<<<<<<<<<End Remove
4748 # Make require happy
4751 =head1 NAME
4753 CGIscriptor -
4755 =head1 DESCRIPTION
4757 A flexible HTML 4 compliant script/module for CGI-aware
4758 embeded Perl, shell-scripts, and other scripting languages,
4759 executed at the server side.
4761 =head1 README
4763 Executes embeded Perl code in HTML pages with easy
4764 access to CGI variables. Also processes embeded shell
4765 scripts and scripts in any other language with an
4766 interactive interpreter (e.g., in-line Python, Tcl,
4767 Ruby, Awk, Lisp, Xlispstat, Prolog, M4, R, REBOL, Praat,
4768 sh, bash, csh, ksh).
4770 CGIscriptor is very flexible and hides all the specifics
4771 and idiosyncrasies of correct output and CGI coding and naming.
4772 CGIscriptor complies with the W3C HTML 4.0 recommendations.
4774 This Perl program will run on any WWW server that runs
4775 Perl scripts, just add a line like the following to your
4776 srm.conf file (Apache example):
4778 ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
4780 URL's that refer to http://www.your.address/SHTML/... will
4781 now be handled by CGIscriptor.pl, which can use a private
4782 directory tree (default is the DOCUMENT_ROOT directory tree,
4783 but it can be anywhere).
4785 =head1 PREREQUISITES
4788 =head1 COREQUISITES
4791 =pod OSNAMES
4793 Linux, *BSD, *nix, MS WinXP
4795 =pod SCRIPT CATEGORIES
4797 Servers
4801 =cut