Shasum adaption
[CGIscriptor.git] / CGIscriptor.pl
blobaad83d5e787f7b62ef477cbb81730467be7aa400
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 # 31 May 2012 - Session ticket system added for handling login sessions.
64 # 29 May 2012 - CGIsafeFileName does not accept filenames starting with '.'
65 # 29 May 2012 - Added CGIscriptor::BrowseAllDirs to handle browsing directories
66 # correctly.
67 # 22 May 2012 - Added Access control with Session Tickets linked to
68 # IP Address and PATH_INFO.
69 # 21 May 2012 - Corrected the links generated by CGIscriptor::BrowseDirs
70 # Will link to current base URL when the HTTP server is '.' or '~'
71 # 29 Oct 2009 - Adapted David A. Wheeler's suggestion about filenames:
72 # CGIsafeFileName does not accept filenames starting with '-'
73 # (http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html)
74 # 08 Oct 2009 - Some corrections in the README.txt file, eg, new email address
75 # 28 Jan 2005 - Added a file selector to performTranslation.
76 # Changed %TranslationTable to @TranslationTable
77 # and patterns to lists.
78 # 27 Jan 2005 - Added a %TranslationTable with associated
79 # performTranslation(\$text) function to allow
80 # run changes in the web pages. Say, to translate
81 # legacy pages with <%=...%> delimiters to the new
82 # <SCRIPT TYPE=..></SCRIPT> format.
83 # 27 Jan 2005 - Small bug of extra '\n' in output removed from the
84 # Other Languages Code.
85 # 10 May 2004 - Belated upload of latest version (2.3) to CPAN
86 # 07 Oct 2003 - Corrected error '\s' -> '\\s' in rebol scripting
87 # language call
88 # 07 Oct 2003 - Corrected omitted INS tags in <DIV><INS> handling
89 # 20 May 2003 - Added a --help switch to print the manual.
90 # 06 Mar 2003 - Adapted the blurb at the end of the file.
91 # 03 Mar 2003 - Added a user definable dieHandler function to catch all
92 # "die" calls. Also "enhanced" the STDERR printout.
93 # 10 Feb 2003 - Split off the reading of the POST part of a query
94 # from Initialize_output. This was suggested by Gerd Franke
95 # to allow for the catching of the file_path using a
96 # POST based lookup. That is, he needed the POST part
97 # to change the file_path.
98 # 03 Feb 2003 - %{$name}; => %{$name} = (); in defineCGIvariableHash.
99 # 03 Feb 2003 - \1 better written as $1 in
100 # $directive =~ s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/$1/g
101 # 29 Jan 2003 - This makes "CLASS="ssperl" CSS-compatible Gerd Franke
102 # added:
103 # $ServerScriptContentClass = "ssperl";
104 # changed in ProcessFile():
105 # unless(($CurrentContentType =~
106 # 28 Jan 2003 - Added 'INS' Tag! Gerd Franke
107 # 20 Dec 2002 - Removed useless $Directoryseparator variable.
108 # Update comments and documentation.
109 # 18 Dec 2002 - Corrected bug in Accept/Reject processing.
110 # Files didn't work.
111 # 24 Jul 2002 - Added .htaccess documentation (from Gerd Franke)
112 # Also added a note that RawFilePattern can be a
113 # complete file name.
114 # 19 Mar 2002 - Added SRC pseudo-files PREFIX and POSTFIX. These
115 # switch to prepending or to appending the content
116 # of the SRC attribute. Default is prefixing. You
117 # can add as many of these switches as you like.
118 # 13 Mar 2002 - Do not search for tag content if a tag closes with
119 # />, i.e., <DIV ... /> will be handled the XML/XHTML way.
120 # 25 Jan 2002 - Added 'curl' and 'snarf' to SRC attribute URL handling
121 # (replaces wget).
122 # 25 Jan 2002 - Found a bug in SAFEqx, now executes qx() in a scalar context
123 # (i.o. a list context). This is necessary for binary results.
124 # 24 Jan 2002 - Disambiguated -T $SRCfile to -T "$SRCfile" (and -e) and
125 # changed the order of if/elsif to allow removing these
126 # conditions in systems with broken -T functions.
127 # (I also removed a spurious ')' bracket)
128 # 17 Jan 2002 - Changed DIV tag SRC from <SOURCE> to sysread(SOURCE,...)
129 # to support binary files.
130 # 17 Jan 2002 - Removed WhiteSpace from $FileAllowedCharacters.
131 # 17 Jan 2002 - Allow "file://" prefix in SRC attribute. It is simply
132 # stipped from the path.
133 # 15 Jan 2002 - Version 2.2
134 # 15 Jan 2002 - Debugged and completed URL support (including
135 # CGIscriptor::read_url() function)
136 # 07 Jan 2002 - Added automatic (magic) URL support to the SRC attribute
137 # with the main::GET_URL function. Uses wget -O underlying.
138 # 04 Jan 2002 - Added initialization of $NewDirective in InsertForeignScript
139 # (i.e., my $NewDirective = "";) to clear old output
140 # (this was a realy anoying bug).
141 # 03 Jan 2002 - Added a <DIV CLASS='text/ssperl' ID='varname'></DIV>
142 # tags that assign the body text as-is (literally)
143 # to $varname. Allows standard HTML-tools to handle
144 # Cascading Style Sheet templates. This implements a
145 # design by Gerd Franke (franke@roo.de).
146 # 03 Jan 2002 - I finaly gave in and allowed SRC files to expand ~/.
147 # 12 Oct 2001 - Normalized spelling of "CGIsafFileName" in documentation.
148 # 09 Oct 2001 - Added $ENV{'CGI_BINARY_FILE'} to log files to
149 # detect unwanted indexing of TAR files by webcrawlers.
150 # 10 Sep 2001 - Added $YOUR_SCRIPTS directory to @INC for 'require'.
151 # 22 Aug 2001 - Added .txt (Content-type: text/plain) as a default
152 # processed file type. Was processed via BinaryMapFile.
153 # 31 May 2001 - Changed =~ inside CGIsafeEmailAddress that was buggy.
154 # 29 May 2001 - Updated $CGI_HOME to point to $ENV{DOCUMENT_ROOT} io
155 # the root of PATH_TRANSLATED. DOCUMENT_ROOT can now
156 # be manipulated to achieve a "Sub Root".
157 # NOTE: you can have $YOUR_HTML_FILES != DOCUMENT_ROOT
158 # 28 May 2001 - Changed CGIscriptor::BrowsDirs function for security
159 # and debugging (it now works).
160 # 21 May 2001 - defineCGIvariableHash will ADD values to existing
161 # hashes,instead of replacing existing hashes.
162 # 17 May 2001 - Interjected a '&' when pasting POST to GET data
163 # 24 Apr 2001 - Blocked direct requests for BinaryMapFile.
164 # 16 Aug 2000 - Added hash table extraction for CGI parameters with
165 # CGIparseValueHash (used with structured parameters).
166 # Use: CGI='%<CGI-partial-name>' (fill in your name in <>)
167 # Will collect all <CGI-partial-name><key>=value pairs in
168 # $<CGI-partial-name>{<key>} = value;
169 # 16 Aug 2000 - Adapted SAFEqx to protect @PARAMETER values.
170 # 09 Aug 2000 - Added support for non-filesystem input by way of
171 # the CGI_FILE_CONTENTS and CGI_DATA_ACCESS_CODE
172 # environment variables.
173 # 26 Jul 2000 - On the command-line, file-path '-' indicates STDIN.
174 # This allows CGIscriptor to be used in pipes.
175 # Default, $BLOCK_STDIN_HTTP_REQUEST=1 will block this
176 # in an HTTP request (i.e., in a web server).
177 # 26 Jul 2000 - Blocked 'Content-type: text/html' if the SERVER_PROTOCOL
178 # is not HTTP or another protocol. Changed the default
179 # source directory to DOCUMENT_ROOT (i.o. the incorrect
180 # SERVER_ROOT).
181 # 24 Jul 2000 - -slim Command-line argument added to remove all
182 # comments, security, etc.. Updated documentation.
183 # 05 Jul 2000 - Added IF and UNLESS attributes to make the
184 # execution of all <META> and <SCRIPT> code
185 # conditional.
186 # 05 Jul 2000 - Rewrote and isolated the code for extracting
187 # quoted items from CGI and SRC attributes.
188 # Now all attributes expect the same set of
189 # quotes: '', "", ``, (), {}, [] and the same
190 # preceded by a \, e.g., "\((aap)\)" will be
191 # extracted as "(aap)".
192 # 17 Jun 2000 - Construct @ARGV list directly in CGIexecute
193 # name-space (i.o. by evaluation) from
194 # CGI attributes to prevent interference with
195 # the processing for non perl scripts.
196 # Changed CGIparseValueList to prevent runaway
197 # loops.
198 # 16 Jun 2000 - Added a direct (interpolated) display mode
199 # (text/ssdisplay) and a user log mode
200 # (text/sslogfile).
201 # 06 Jun 2000 - Replace "print $Result" with a syswrite loop to
202 # allow large string output.
203 # 02 Jun 2000 - Corrected shrubCGIparameter($CGI_VALUE) to realy
204 # remove all control characters. Changed Interpreter
205 # initialization to shrub interpolated CGI parameters.
206 # Added 'text/ssmailto' interpreter script.
207 # 22 May 2000 - Changed some of the comments
208 # 09 May 2000 - Added list extraction for CGI parameters with
209 # CGIparseValueList (used with multiple selections).
210 # Use: CGI='@<CGI-parameter>' (fill in your name in <>)
211 # 09 May 2000 - Added a 'Not Present' condition to CGIparseValue.
212 # 27 Apr 2000 - Updated documentation to reflect changes.
213 # 27 Apr 2000 - SRC attribute "cleaned". Supported for external
214 # interpreters.
215 # 27 Apr 2000 - CGI attribute can be used in <SCRIPT> tag.
216 # 27 Apr 2000 - Gprolog, M4 support added.
217 # 26 Apr 2000 - Lisp (rep) support added.
218 # 20 Apr 2000 - Use of external interpreters now functional.
219 # 20 Apr 2000 - Removed bug from extracting Content types (RegExp)
220 # 10 Mar 2000 - Qualified unconditional removal of '#' that preclude
221 # the use of $#foo, i.e., I changed
222 # s/[^\\]\#[^\n\f\r]*([\n\f\r])/\1/g
223 # to
224 # s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/\1/g
225 # 03 Mar 2000 - Added a '$BlockPathAccess' variable to "hide"
226 # things like, e.g., CVS information in CVS subtrees
227 # 10 Feb 2000 - URLencode/URLdecode have been made case-insensitive
228 # 10 Feb 2000 - Added a BrowseDirs function (CGIscriptor package)
229 # 01 Feb 2000 - A BinaryMapFile in the ~/ directory has precedence
230 # over a "burried" BinaryMapFile.
231 # 04 Oct 1999 - Added two functions to check file names and email addresses
232 # (CGIscriptor::CGIsafeFileName and
233 # CGIscriptor::CGIsafeEmailAddress)
234 # 28 Sept 1999 - Corrected bug in sysread call for reading POST method
235 # to allow LONG posts.
236 # 28 Sept 1999 - Changed CGIparseValue to handle multipart/form-data.
237 # 29 July 1999 - Refer to BinaryMapFile from CGIscriptor directory, if
238 # this directory exists.
239 # 07 June 1999 - Limit file-pattern matching to LAST extension
240 # 04 June 1999 - Default text/html content type is printed only once.
241 # 18 May 1999 - Bug in replacement of ~/ and ./ removed.
242 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
243 # 15 May 1999 - Changed the name of the execute package to CGIexecute.
244 # Changed the processing of the Accept and Reject file.
245 # Added a full expression evaluation to Access Control.
246 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
247 # 27 Apr 1999 - Brought CGIscriptor under the GNU GPL. Made CGIscriptor
248 # Version 1.1 a module that can be called with 'require "CGIscriptor.pl"'.
249 # Requests are serviced by "Handle_Request()". CGIscriptor
250 # can still be called as a isolated perl script and a shell
251 # command.
252 # Changed the "factory default setting" so that it will run
253 # from the DOCUMENT_ROOT directory.
254 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
255 # 29 Mar 1999 - Remove second debugging STDERR switch. Moved most code
256 # to subroutines to change CGIscriptor into a module.
257 # Added mapping to process unsupported file types (e.g., binary
258 # pictures). See $BinaryMapFile.
259 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
260 # 24 Sept 1998 - Changed text of license (Rob van Son, R.J.J.H.vanSon@uva.nl)
261 # Removed a double setting of filepatterns and maximum query
262 # size. Changed email address. Removed some typos from the
263 # comments.
264 # 02 June 1998 - Bug fixed in URLdecode. Changing the foreach loop variable
265 # caused quiting CGIscriptor.(Rob van Son, R.J.J.H.vanSon@uva.nl)
266 # 02 June 1998 - $SS_PUB and $SS_SCRIPT inserted an extra /, removed.
267 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
270 # Known Bugs:
272 # 23 Mar 2000
273 # It is not possible to use operators or variables to construct variable names,
274 # e.g., $bar = \@{$foo}; won't work. However, eval('$bar = \@{'.$foo.'};');
275 # will indeed work. If someone could tell me why, I would be obliged.
278 ############################################################################
280 # OBLIGATORY USER CONFIGURATION
282 # Configure the directories where all user files can be found (this
283 # is the equivalent of the server root directory of a WWW-server).
284 # These directories can be located ANYWHERE. For security reasons, it is
285 # better to locate them outside the WWW-tree of your HTTP server, unless
286 # CGIscripter handles ALL requests.
288 # For convenience, the defaults are set to the root of the WWW server.
289 # However, this might not be safe!
291 # ~/ text files
292 # $YOUR_HTML_FILES = "/usr/pub/WWW/SHTML"; # or SS_PUB as environment var
293 # (patch to use the parent directory of CGIscriptor as document root, should be removed)
294 if($ENV{'SCRIPT_FILENAME'}) # && $ENV{'SCRIPT_FILENAME'} !~ /\Q$ENV{'DOCUMENT_ROOT'}\E/)
296 $ENV{'DOCUMENT_ROOT'} = $ENV{'SCRIPT_FILENAME'};
297 $ENV{'DOCUMENT_ROOT'} =~ s@/CGIscriptor.*$@@ig;
300 # Just enter your own directory path here
301 $YOUR_HTML_FILES = $ENV{'DOCUMENT_ROOT'}; # default is the DOCUMENT_ROOT
303 # ./ script files (recommended to be different from the previous)
304 # $YOUR_SCRIPTS = "/usr/pub/WWW/scripts"; # or SS_SCRIPT as environment var
305 $YOUR_SCRIPTS = $YOUR_HTML_FILES; # This might be a SECURITY RISK
307 # End of obligatory user configuration
308 # (note: there is more non-essential user configuration below)
310 ############################################################################
312 # OPTIONAL USER CONFIGURATION (all values are used CASE INSENSITIVE)
314 # Script content-types: TYPE="Content-type" (user defined mime-type)
315 $ServerScriptContentType = "text/ssperl"; # Server Side Perl scripts
316 # CSS require a simple class
317 $ServerScriptContentClass = $ServerScriptContentType =~ m!/! ?
318 $' : "ssperl"; # Server Side Perl CSS classes
320 $ShellScriptContentType = "text/osshell"; # OS shell scripts
321 # # (Server Side perl ``-execution)
323 # Accessible file patterns, block any request that doesn't match.
324 # Matches any file with the extension .(s)htm(l), .txt, or .xmr
325 # (\. is used in regexp)
326 # Note: die unless $PATH_INFO =~ m@($FilePattern)$@is;
327 $FilePattern = ".shtml|.htm|.html|.xml|.xmr|.txt";
329 # The table with the content type MIME types
330 # (allows to differentiate MIME types, if needed)
331 %ContentTypeTable =
333 '.html' => 'text/html',
334 '.shtml' => 'text/html',
335 '.htm' => 'text/html',
336 '.xml' => 'text/xml',
337 '.txt' => 'text/plain'
341 # File pattern post-processing
342 $FilePattern =~ s/([@.])/\\$1/g; # Convert . and @ to \. and \@
344 # SHAsum command needed for Authorization and Login
345 # (note, these have to be accessible in the HTML pages, ie, the CGIexecute environment)
346 my $shasum = qx{uname} =~ /Darwin/ ? "shasum-5.12" : "shasum";
347 $ENV{"SHASUMCMD"} = $shasum.' |cut -f 1 -d" "';
348 $ENV{"RANDOMHASHCMD"} = 'dd count=1 if=/dev/urandom 2>/dev/null | '.$shasum.' -b |cut -f 1 -d" "';
350 # File patterns of files which are handled by session tickets.
351 %TicketRequiredPatterns = (
352 '^/Private(/|$)' => "Private/.Sessions\tPrivate/.Passwords\t/Private/Login.html\t+36000"
354 # Session Ticket Directory: Private/.Sessions
355 # Password Directory: Private/.Password
356 # Login page (url path): /Private/Login.html
357 # Expiration time (s): +3600
358 # +<seconds> = relative time <seconds> is absolute date-time
360 # Raw files must contain their own Content-type (xmr <- x-multipart-replace).
361 # THIS IS A SUBSET OF THE FILES DEFINED IN $FilePattern
362 $RawFilePattern = ".xmr";
363 # (In principle, this could contain a full file specification, e.g.,
364 # ".xmr|relocated.html")
366 # Raw File pattern post-processing
367 $RawFilePattern =~ s/([@.])/\\$1/g; # Convert . and @ to \. and \@
369 # Server protocols for which "Content-type: text/html\n\n" should be printed
370 # (you should not bother with these, except for HTTP, they are mostly imaginary)
371 $ContentTypeServerProtocols = 'HTTP|MAIL|MIME';
373 # Block access to all (sub-) paths and directories that match the
374 # following (URL) path (is used as:
375 # 'die if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@;' )
376 $BlockPathAccess = '/(CVS|\.git)/'; # Protect CVS and .git information
378 # All (blocked) other file-types can be mapped to a single "binary-file"
379 # processor (a kind of pseudo-file path). This can either be an error
380 # message (e.g., "illegal file") or contain a script that serves binary
381 # files.
382 # Note: the real file path wil be stored in $ENV{CGI_BINARY_FILE}.
383 $BinaryMapFile = "/BinaryMapFile.xmr";
384 # Allow for the addition of a CGIscriptor directory
385 # Note that a BinaryMapFile in the root "~/" directory has precedence
386 $BinaryMapFile = "/CGIscriptor".$BinaryMapFile
387 if ! -e "$YOUR_HTML_FILES".$BinaryMapFile
388 && -e "$YOUR_HTML_FILES/CGIscriptor".$BinaryMapFile;
391 # List of all characters that are allowed in file names and paths.
392 # All requests containing illegal characters are blocked. This
393 # blocks most tricks (e.g., adding "\000", "\n", or other control
394 # characters, also blocks URI's using %FF)
395 # THIS IS A SECURITY FEATURE
396 # (this is also used to parse filenames in SRC= features, note the
397 # '-quotes, they are essential)
398 $FileAllowedChars = '\w\.\~\/\:\*\?\-'; # Covers Unix and Mac, but NO spaces
400 # Maximum size of the Query (number of characters clients can send
401 # covers both GET & POST combined)
402 $MaximumQuerySize = 2**20 - 1; # = 2**14 - 1
405 # Embeded URL get function used in SRC attributes and CGIscriptor::read_url
406 # (returns a string with the PERL code to transfer the URL contents, e.g.,
407 # "SAFEqx(\'curl \"http://www.fon.hum.uva.nl\"\')")
408 # "SAFEqx(\'wget --quiet --output-document=- \"http://www.fon.hum.uva.nl\"\')")
409 # Be sure to handle <BASE HREF='URL'> and allow BOTH
410 # direct printing GET_URL($URL [, 0]) and extracting the content of
411 # the $URL for post-processing GET_URL($URL, 1).
412 # You get the WHOLE file, including HTML header.
413 # The shell command Use $URL where the URL should go
414 # ('wget', 'snarf' or 'curl', uncomment the one you would like to use)
415 my $GET_URL_shell_command = 'wget --quiet --output-document=- $URL';
416 #my $GET_URL_shell_command = 'snarf $URL -';
417 #my $GET_URL_shell_command = 'curl $URL';
419 sub GET_URL # ($URL, $ValueNotPrint) -> content_of_url
421 my $URL = shift || return;
422 my $ValueNotPrint = shift || 0;
424 # Check URL for illegal characters
425 return "print '<h1>Illegal URL<h1>'\"\n\";" if $URL =~ /[^$FileAllowedChars\%]/;
427 # Include URL in final command
428 my $CurrentCommand = $GET_URL_shell_command;
429 $CurrentCommand =~ s/\$URL/$URL/g;
431 # Print to STDOUT or return a value
432 my $BlockPrint = "print STDOUT ";
433 $BlockPrint = "" if $ValueNotPrint;
435 my $Commands = <<"GETURLCODE";
436 # Get URL
438 my \$Page = "";
440 # Simple, using shell command
441 \$Page = SAFEqx('$CurrentCommand');
443 # Add a BASE tage to the header
444 \$Page =~ s!\\</head!\\<base href='$URL'\\>\\</head!ig unless \$Page =~ m!\\<base!;
446 # Print the URL value, or return it as a value
447 $BlockPrint\$Page;
449 GETURLCODE
450 return $Commands;
453 # As files can get rather large (and binary), you might want to use
454 # some more intelligent reading procedure, e.g.,
455 # Direct Perl
456 # # open(URLHANDLE, '/usr/bin/wget --quiet --output-document=- "$URL"|') || die "wget: \$!";
457 # #open(URLHANDLE, '/usr/bin/snarf "$URL" -|') || die "snarf: \$!";
458 # open(URLHANDLE, '/usr/bin/curl "$URL"|') || die "curl: \$!";
459 # my \$text = "";
460 # while(sysread(URLHANDLE,\$text, 1024) > 0)
462 # \$Page .= \$text;
463 # };
464 # close(URLHANDLE) || die "\$!";
465 # However, this doesn't work with the CGIexecute->evaluate() function.
466 # You get an error: 'No child processes at (eval 16) line 15, <file0> line 8.'
468 # You can forget the next two variables, they are only needed when
469 # you don't want to use a regular file system (i.e., with open)
470 # but use some kind of database/RAM image for accessing (generating)
471 # the data.
473 # Name of the environment variable that contains the file contents
474 # when reading directly from Database/RAM. When this environment variable,
475 # $ENV{$CGI_FILE_CONTENTS}, is not false, no real file will be read.
476 $CGI_FILE_CONTENTS = 'CGI_FILE_CONTENTS';
477 # Uncomment the following if you want to force the use of the data access code
478 # $ENV{$CGI_FILE_CONTENTS} = '-'; # Force use of $ENV{$CGI_DATA_ACCESS_CODE}
480 # Name of the environment variable that contains the RAM access perl
481 # code needed to read additional "files", i.e.,
482 # $ENV{$CGI_FILE_CONTENTS} = eval("\@_=('$file_path'); do{$ENV{$CGI_DATA_ACCESS_CODE}}");
483 # When $ENV{$CGI_FILE_CONTENTS} eq '-', this code is executed to generate the data.
484 $CGI_DATA_ACCESS_CODE = 'CGI_DATA_ACCESS_CODE';
486 # You can, of course, fill this yourself, e.g.,
487 # $ENV{$CGI_DATA_ACCESS_CODE} =
488 # 'open(INPUT, "<$_[0]"); while(<INPUT>){print;};close(INPUT);'
491 # DEBUGGING
493 # Suppress error messages, this can be changed for debugging or error-logging
494 #open(STDERR, "/dev/null"); # (comment out for use in debugging)
496 # SPECIAL: Remove Comments, security, etc. if the command line is
497 # '>CGIscriptor.pl -slim >slimCGIscriptor.pl'
498 $TrimDownCGIscriptor = 1 if $ARGV[0] =~ /^\-slim/i;
500 # If CGIscriptor is used from the command line, the command line
501 # arguments are interpreted as the file (1st) and the Query String (rest).
502 # Get the arguments
503 $ENV{'PATH_INFO'} = shift(@ARGV) unless exists($ENV{'PATH_INFO'}) || grep(/\-\-help/i, @ARGV);
504 $ENV{'QUERY_STRING'} = join("&", @ARGV) unless exists($ENV{'QUERY_STRING'});
507 # Handle bail-outs in a user definable way.
508 # Catch Die and replace it with your own function.
509 # Ends with a call to "die $_[0];"
511 sub dieHandler # ($ErrorCode, "Message", @_) -> DEAD
513 my $ErrorCode = shift;
514 my $ErrorMessage = shift;
516 # Place your own reporting functions here
518 # Now, kill everything (default)
519 print STDERR "$ErrorCode: $ErrorMessage\n";
520 die $ErrorMessage;
524 # End of optional user configuration
525 # (note: there is more non-essential user configuration below)
527 if(grep(/\-\-help/i, @ARGV))
529 print << 'ENDOFPREHELPTEXT2';
531 ###############################################################################
533 # Author and Copyright (c):
534 # Rob van Son, © 1995,1996,1997,1998,1999,2000,2001,2002-2012
535 # NKI-AVL Amsterdam
536 # r.v.son@nki.nl
537 # Institute of Phonetic Sciences & IFOTT/ACLS
538 # University of Amsterdam
539 # Email: R.J.J.H.vanSon@gmail.com
540 # Email: R.J.J.H.vanSon@uva.nl
541 # WWW : http://www.fon.hum.uva.nl/rob/
543 # License for use and disclaimers
545 # CGIscriptor merges plain ASCII HTML files transparantly
546 # with CGI variables, in-line PERL code, shell commands,
547 # and executable scripts in other scripting languages.
549 # This program is free software; you can redistribute it and/or
550 # modify it under the terms of the GNU General Public License
551 # as published by the Free Software Foundation; either version 2
552 # of the License, or (at your option) any later version.
554 # This program is distributed in the hope that it will be useful,
555 # but WITHOUT ANY WARRANTY; without even the implied warranty of
556 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
557 # GNU General Public License for more details.
559 # You should have received a copy of the GNU General Public License
560 # along with this program; if not, write to the Free Software
561 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
564 # Contributors:
565 # Rob van Son (R.J.J.H.vanSon@uva.nl)
566 # Gerd Franke franke@roo.de (designed the <DIV> behaviour)
568 #######################################################
569 ENDOFPREHELPTEXT2
571 #######################################################>>>>>>>>>>Start Remove
573 # You can skip the following code, it is an auto-splice
574 # procedure.
576 # Construct a slimmed down version of CGIscriptor
577 # (i.e., CGIscriptor.pl -slim > slimCGIscriptor.pl)
579 if($TrimDownCGIscriptor)
581 open(CGISCRIPTOR, "<CGIscriptor.pl")
582 || dieHandler(1, "<CGIscriptor.pl not slimmed down: $!\n");
583 my $SKIPtext = 0;
584 my $SKIPComments = 0;
586 while(<CGISCRIPTOR>)
588 my $SKIPline = 0;
590 ++$LineCount;
592 # Start of SKIP text
593 $SKIPtext = 1 if /[\>]{10}Start Remove/;
594 $SKIPComments = 1 if $SKIPtext == 1;
596 # Skip this line?
597 $SKIPline = 1 if $SKIPtext || ($SKIPComments && /^\s*\#/);
599 ++$PrintCount unless $SKIPline;
601 print STDOUT $_ unless $SKIPline;
603 # End of SKIP text ?
604 $SKIPtext = 0 if /[\<]{10}End Remove/;
606 # Ready!
607 print STDERR "\# Printed $PrintCount out of $LineCount lines\n";
608 exit;
611 #######################################################
613 if(grep(/\-\-help/i, @ARGV))
615 print << 'ENDOFHELPTEXT';
617 # HYPE
619 # CGIscriptor merges plain ASCII HTML files transparantly and safely
620 # with CGI variables, in-line PERL code, shell commands, and executable
621 # scripts in many languages (on-line and real-time). It combines the
622 # "ease of use" of HTML files with the versatillity of specialized
623 # scripts and PERL programs. It hides all the specifics and
624 # idiosyncrasies of correct output and CGI coding and naming. Scripts
625 # do not have to be aware of HTML, HTTP, or CGI conventions just as HTML
626 # files can be ignorant of scripts and the associated values. CGIscriptor
627 # complies with the W3C HTML 4.0 recommendations.
628 # In addition to its use as a WWW embeded CGI processor, it can
629 # be used as a command-line document preprocessor (text-filter).
631 # THIS IS HOW IT WORKS
633 # The aim of CGIscriptor is to execute "plain" scripts inside a text file
634 # using any required CGIparameters and environment variables. It
635 # is optimized to transparantly process HTML files inside a WWW server.
636 # The native language is Perl, but many other scripting languages
637 # can be used.
639 # CGIscriptor reads text files from the requested input file (i.e., from
640 # $YOUR_HTML_FILES$PATH_INFO) and writes them to <STDOUT> (i.e., the
641 # client requesting the service) preceded by the obligatory
642 # "Content-type: text/html\n\n" or "Content-type: text/plain\n\n" string
643 # (except for "raw" files which supply their own Content-type message
644 # and only if the SERVER_PROTOCOL supports HTTP, MAIL, or MIME).
646 # When CGIscriptor encounters an embedded script, indicated by an HTML4 tag
648 # <SCRIPT TYPE="text/ssperl" [CGI="$VAR='default value'"] [SRC="ScriptSource"]>
649 # PERL script
650 # </SCRIPT>
652 # or
654 # <SCRIPT TYPE="text/osshell" [CGI="$name='default value'"] [SRC="ScriptSource"]>
655 # OS Shell script
656 # </SCRIPT>
658 # construct (anything between []-brackets is optional, other MIME-types
659 # and scripting languages are supported), the embedded script is removed
660 # and both the contents of the source file (i.e., "do 'ScriptSource'")
661 # AND the script are evaluated as a PERL program (i.e., by eval()),
662 # shell script (i.e., by a "safe" version of `Command`, qx) or an external
663 # interpreter. The output of the eval() function takes the place of the
664 # original <SCRIPT></SCRIPT> construct in the output string. Any CGI
665 # parameters declared by the CGI attribute are available as simple perl
666 # variables, and can subsequently be made available as variables to other
667 # scripting languages (e.g., bash, python, or lisp).
669 # Example: printing "Hello World"
670 # <HTML><HEAD><TITLE>Hello World</TITLE>
671 # <BODY>
672 # <H1><SCRIPT TYPE="text/ssperl">"Hello World"</SCRIPT></H1>
673 # </BODY></HTML>
675 # Save this in a file, hello.html, in the directory you indicated with
676 # $YOUR_HTML_FILES and access http://your_server/SHTML/hello.html
677 # (or to whatever name you use as an alias for CGIscriptor.pl).
678 # This is realy ALL you need to do to get going.
680 # You can use any values that are delivered in CGI-compliant form (i.e.,
681 # the "?name=value" type URL additions) transparently as "$name" variables
682 # in your scripts IFF you have declared them in the CGI attribute of
683 # a META or SCRIPT tag before e.g.:
684 # <META CONTENT="text/ssperl; CGI='$name = `default value`'
685 # [SRC='ScriptSource']">
686 # or
687 # <SCRIPT TYPE="text/ssperl" CGI="$name = 'default value'"
688 # [SRC='ScriptSource']>
689 # After such a 'CGI' attribute, you can use $name as an ordinary PERL variable
690 # (the ScriptSource file is immediately evaluated with "do 'ScriptSource'").
691 # The CGIscriptor script allows you to write ordinary HTML files which will
692 # include dynamic CGI aware (run time) features, such as on-line answers
693 # to specific CGI requests, queries, or the results of calculations.
695 # For example, if you wanted to answer questions of clients, you could write
696 # a Perl program called "Answer.pl" with a function "AnswerQuestion()"
697 # that prints out the answer to requests given as arguments. You then write
698 # an HTML page "Respond.html" containing the following fragment:
700 # <center>
701 # The Answer to your question
702 # <META CONTENT="text/ssperl; CGI='$Question'">
703 # <h3><SCRIPT TYPE="text/ssperl">$Question</SCRIPT></h3>
704 # is
705 # <h3><SCRIPT TYPE="text/ssperl" SRC="./PATH/Answer.pl">
706 # AnswerQuestion($Question);
707 # </SCRIPT></h3>
708 # </center>
709 # <FORM ACTION=Respond.html METHOD=GET>
710 # Next question: <INPUT NAME="Question" TYPE=TEXT SIZE=40><br>
711 # <INPUT TYPE=SUBMIT VALUE="Ask">
712 # </FORM>
714 # The output could look like the following (in HTML-speak):
716 # <CENTER>
717 # The Answer to your question
718 # <h3>What is the capital of the Netherlands?</h3>
719 # is
720 # <h3>Amsterdam</h3>
721 # </CENTER>
722 # <FORM ACTION=Respond.html METHOD=GET>
723 # Next question: <INPUT NAME="Question" TYPE=TEXT SIZE=40><br>
724 # <INPUT TYPE=SUBMIT VALUE="Ask">
726 # Note that the function "Answer.pl" does know nothing about CGI or HTML,
727 # it just prints out answers to arguments. Likewise, the text has no
728 # provisions for scripts or CGI like constructs. Also, it is completely
729 # trivial to extend this "program" to use the "Answer" later in the page
730 # to call up other information or pictures/sounds. The final text never
731 # shows any cue as to what the original "source" looked like, i.e.,
732 # where you store your scripts and how they are called.
734 # There are some extra's. The argument of the files called in a SRC= tag
735 # can access the CGI variables declared in the preceding META tag from
736 # the @ARGV array. Executable files are called as:
737 # `file '$ARGV[0]' ... ` (e.g., `Answer.pl \'$Question\'`;)
738 # The files called from SRC can even be (CGIscriptor) html files which are
739 # processed in-line. Furthermore, the SRC= tag can contain a perl block
740 # that is evaluated. That is,
741 # <META CONTENT="text/ssperl; CGI='$Question' SRC='{$Question}'">
742 # will result in the evaluation of "print do {$Question};" and the VALUE
743 # of $Question will be printed. Note that these "SRC-blocks" can be
744 # preceded and followed by other file names, but only a single block is
745 # allowed in a SRC= tag.
747 # One of the major hassles of dynamic WWW pages is the fact that several
748 # mutually incompatible browsers and platforms must be supported. For example,
749 # the way sound is played automatically is different for Netscape and
750 # Internet Explorer, and for each browser it is different again on
751 # Unix, MacOS, and Windows. Realy dangerous is processing user-supplied
752 # (form-) values to construct email addresses, file names, or database
753 # queries. All Apache WWW-server exploits reported in the media are
754 # based on faulty CGI-scripts that didn't check their user-data properly.
756 # There is no panacee for these problems, but a lot of work and problems
757 # can be saved by allowing easy and transparent control over which
758 # <SCRIPT></SCRIPT> blocks are executed on what CGI-data. CGIscriptor
759 # supplies such a method in the form of a pair of attributes:
760 # IF='...condition..' and UNLESS='...condition...'. When added to a
761 # script tag, the whole block (including the SRC attribute) will be
762 # ignored if the condition is false (IF) or true (UNLESS).
763 # For example, the following block will NOT be evaluated if the value
764 # of the CGI variable FILENAME is NOT a valid filename:
766 # <SCRIPT TYPE='text/ssperl' CGI='$FILENAME'
767 # IF='CGIscriptor::CGIsafeFileName($FILENAME)'>
768 # .....
769 # </SCRIPT>
771 # (the function CGIsafeFileName(String) returns an empty string ("")
772 # if the String argument is not a valid filename).
773 # The UNLESS attribute is the mirror image of IF.
775 # A user manual follows the HTML 4 and security paragraphs below.
777 ##########################################################################
779 # HTML 4 compliance
781 # In general, CGIscriptor.pl complies with the HTML 4 recommendations of
782 # the W3C. This means that any software to manage Web sites will be able
783 # to handle CGIscriptor files, as will web agents.
785 # All script code should be placed between <SCRIPT></SCRIPT> tags, the
786 # script type is indicated with TYPE="mime-type", the LANGUAGE
787 # feature is ignored, and a SRC feature is implemented. All CGI specific
788 # features are delegated to the CGI attribute.
790 # However, the behavior deviates from the W3C recommendations at some
791 # points. Most notably:
792 # 0- The scripts are executed at the server side, invissible to the
793 # client (i.e., the browser)
794 # 1- The mime-types are personal and idiosyncratic, but can be adapted.
795 # 2- Code in the body of a <SCRIPT></SCRIPT> tag-pair is still evaluated
796 # when a SRC feature is present.
797 # 3- The SRC attribute reads a list of files.
798 # 4- The files in a SRC attribute are processed according to file type.
799 # 5- The SRC attribute evaluates inline Perl code.
800 # 6- Processed META, DIV, INS tags are removed from the output
801 # document.
802 # 7- All attributes of the processed META tags, except CONTENT, are ignored
803 # (i.e., deleted from the output).
804 # 8- META tags can be placed ANYWHERE in the document.
805 # 9- Through the SRC feature, META tags can have visible output in the
806 # document.
807 # 10- The CGI attribute that declares CGI parameters, can be used
808 # inside the <SCRIPT> tag.
809 # 11- Use of an extended quote set, i.e., '', "", ``, (), {}, []
810 # and their \-slashed combinations: \'\', \"\", \`\`, \(\),
811 # \{\}, \[\].
812 # 12- IF and UNLESS attributes to <SCRIPT>, <META>, <DIV>, <INS> tags.
813 # 13- <DIV> tags cannot be nested, DIV tags are not
814 # rendered with new-lines.
815 # 14- The XML style <TAG .... /> is recognized and handled correctly.
816 # (i.e., no content is processed)
818 # The reasons for these choices are:
819 # You can still write completely HTML4 compliant documents. CGIscriptor
820 # will not force you to write "deviant" code. However, it allows you to
821 # do so (which is, in fact, just as bad). The prime design principle
822 # was to allow users to include plain Perl code. The code itself should
823 # be "enhancement free". Therefore, extra features were needed to
824 # supply easy access to CGI and Web site components. For security
825 # reasons these have to be declared explicitly. The SRC feature
826 # transparently manages access to external files, especially the safe
827 # use of executable files.
828 # The CGI attribute handles the declarations of external (CGI) variables
829 # in the SCRIPT and META tag's.
830 # EVERYTHING THE CGI ATTRIBUTE AND THE META TAG DO CAN BE DONE INSIDE
831 # A <SCRIPT></SCRIPT> TAG CONSTRUCT.
833 # The reason for the IF, UNLESS, and SRC attributes (and their Perl code
834 # evaluation) were build into the META and SCRIPT tags is part laziness,
835 # part security. The SRC blocks allows more compact documents and easier
836 # debugging. The values of the CGI variables can be immediately screened
837 # for security by IF or UNLESS conditions, and even SRC attributes (e.g.,
838 # email addresses and file names), and a few commands can be called
839 # without having to add another Perl TAG pair. This is especially important
840 # for documents that require the use of other (more restricted) "scripting"
841 # languages and facilities that lag transparent control structures.
843 ##########################################################################
845 # SECURITY
847 # Your WWW site is a few keystrokes away from a few hundred million internet
848 # users. A fair percentage of these users knows more about your computer
849 # than you do. And some of these just might have bad intentions.
851 # To ensure uncompromized operation of your server and platform, several
852 # features are incorporated in CGIscriptor.pl to enhance security.
853 # First of all, you should check the source of this program. No security
854 # measures will help you when you download programs from anonymous sources.
855 # If you want to use THIS file, please make sure that it is uncompromized.
856 # The best way to do this is to contact the source and try to determine
857 # whether s/he is reliable (and accountable).
859 # BE AWARE THAT ANY PROGRAMMER CAN CHANGE THIS PROGRAM IN SUCH A WAY THAT
860 # IT WILL SET THE DOORS TO YOUR SYSTEM WIDE OPEN
862 # I would like to ask any user who finds bugs that could compromise
863 # security to report them to me (and any other bug too,
864 # Email: R.J.J.H.vanSon@uva.nl or ifa@hum.uva.nl).
866 # Security features
868 # 1 Invisibility
869 # The inner workings of the HTML source files are completely hidden
870 # from the client. Only the HTTP header and the ever changing content
871 # of the output distinguish it from the output of a plain, fixed HTML
872 # file. Names, structures, and arguments of the "embedded" scripts
873 # are invisible to the client. Error output is suppressed except
874 # during debugging (user configurable).
876 # 2 Separate directory trees
877 # Directories containing Inline text and script files can reside on
878 # separate trees, distinct from those of the HTTP server. This means
879 # that NEITHER the text files, NOR the script files can be read by
880 # clients other than through CGIscriptor.pl, UNLESS they are
881 # EXPLICITELY made available.
883 # 3 Requests are NEVER "evaluated"
884 # All client supplied values are used as literal values (''-quoted).
885 # Client supplied ''-quotes are ALWAYS removed. Therefore, as long as the
886 # embedded scripts do NOT themselves evaluate these values, clients CANNOT
887 # supply executable commands. Be sure to AVOID scripts like:
889 # <META CONTENT="text/ssperl; CGI='$UserValue'">
890 # <SCRIPT TYPE="text/ssperl">$dir = `ls -1 $UserValue`;</SCRIPT>
892 # These are a recipe for disaster. However, the following quoted
893 # form should be save (but is still not adviced):
895 # <SCRIPT TYPE="text/ssperl">$dir = `ls -1 \'$UserValue\'`;</SCRIPT>
897 # A special function, SAFEqx(), will automatically do exactly this,
898 # e.g., SAFEqx('ls -1 $UserValue') will execute `ls -1 \'$UserValue\'`
899 # with $UserValue interpolated. I recommend to use SAFEqx() instead
900 # of backticks whenever you can. The OS shell scripts inside
902 # <SCRIPT TYPE="text/osshell">ls -1 $UserValue</SCRIPT>
904 # are handeld by SAFEqx and automatically ''-quoted.
906 # 4 Logging of requests
907 # All requests can be logged separate from the Host server. The level of
908 # detail is user configurable: Including or excluding the actual queries.
909 # This allows for the inspection of (im-) proper use.
911 # 5 Access control: Clients
912 # The Remote addresses can be checked against a list of authorized
913 # (i.e., accepted) or non-authorized (i.e., rejected) clients. Both
914 # REMOTE_HOST and REMOTE_ADDR are tested so clients without a proper
915 # HOST name can be (in-) excluded by their IP-address. Client patterns
916 # containing all numbers and dots are considered IP-addresses, all others
917 # domain names. No wild-cards or regexp's are allowed, only partial
918 # addresses.
919 # Matching of names is done from the back to the front (domain first,
920 # i.e., $REMOTE_HOST =~ /\Q$pattern\E$/is), so including ".edu" will
921 # accept or reject all clients from the domain EDU. Matching of
922 # IP-addresses is done from the front to the back (domain first, i.e.,
923 # $REMOTE_ADDR =~ /^\Q$pattern\E/is), so including "128." will (in-)
924 # exclude all clients whose IP-address starts with 128.
925 # There are two special symbols: "-" matches HOSTs with no name and "*"
926 # matches ALL HOSTS/clients.
927 # For those needing more expressional power, lines starting with
928 # "-e" are evaluated by the perl eval() function. E.g.,
929 # '-e $REMOTE_HOST =~ /\.edu$/is;' will accept/reject clients from the
930 # domain '.edu'.
932 # 6 Access control: Files
933 # In principle, CGIscriptor could read ANY file in the directory
934 # tree as discussed in 1. However, for security reasons this is
935 # restricted to text files. It can be made more restricted by entering
936 # a global file pattern (e.g., ".html"). This is done by default.
937 # For each client requesting access, the file pattern(s) can be made
938 # more restrictive than the global pattern by entering client specific
939 # file patterns in the Access Control files (see 5).
940 # For example: if the ACCEPT file contained the lines
941 # * DEMO
942 # .hum.uva.nl LET
943 # 145.18.230.
944 # Then all clients could request paths containing "DEMO" or "demo", e.g.
945 # "/my/demo/file.html" ($PATH_INFO =~ /\Q$pattern\E/), Clients from
946 # *.hum.uva.nl could also request paths containing "LET or "let", e.g.
947 # "/my/let/file.html", and clients from the local cluster
948 # 145.18.230.[0-9]+ could access ALL files.
949 # Again, for those needing more expressional power, lines starting with
950 # "-e" are evaluated. For instance:
951 # '-e $REMOTE_HOST =~ /\.edu$/is && $PATH_INFO =~ m@/DEMO/@is;'
952 # will accept/reject requests for files from the directory "/demo/" from
953 # clients from the domain '.edu'.
955 # 7 Access control: Server side session tickets
956 # Specific paths can be controlled by Session Tickets which must be
957 # present as a SESSIONTICKET=<value> CGI variable in the request. These paths
958 # are defined in %TicketRequiredPatterns as pairs of:
959 # ('regexp' => 'SessionPath\tPasswordPath\tLogin.html\tExpiration').
960 # Session Tickets are stored in a separate directory (SessionPath, e.g.,
961 # "Private/.Session") as files with the exact same name of the SESSIONTICKET
962 # CGI. The following is an example:
963 # Type: SESSION
964 # IPaddress: 127.0.0.1
965 # AllowedPaths: ^/Private/Name/
966 # Expires: 3600
967 # Username: test
968 # ...
969 # Other content can follow.
971 # It is adviced that Session Tickets should be deleted
972 # after some (idle) time. The IP address should be the IP number at login, and
973 # the SESSIONTICKET will be rejected if it is presented from another IP address.
974 # AllowedPaths is a perl regexp. Be careful how they match. Make sure to delimit
975 # the names to prevent access to overlapping names, eg, "^/Private/Rob" will also
976 # match "^/Private/Robert", however, "^/Private/Rob/" will not. Expires is the
977 # time the ticket will remain valid after creation (file ctime). Time can be given
978 # in s[econds] (default), m[inutes], h[hours], or d[ays], eg, "24h" means 24 hours.
979 # None of these need be present, but the Ticket must have a non-zero size.
981 # Next to Session Tickets, there are two other type of ticket files:
982 # - LOGIN tickets store information about a current login request
983 # - PASSWORD ticket store account information to authorize login requests
985 # 8 Query length limiting
986 # The length of the Query string can be limited. If CONTENT_LENGTH is larger
987 # than this limit, the request is rejected. The combined length of the
988 # Query string and the POST input is checked before any processing is done.
989 # This will prevent clients from overloading the scripts.
990 # The actual, combined, Query Size is accessible as a variable through
991 # $CGI_Content_Length.
993 # 9 Illegal filenames, paths, and protected directories
994 # One of the primary security concerns in handling CGI-scripts is the
995 # use of "funny" characters in the requests that con scripts in executing
996 # malicious commands. Examples are inserting ';', null bytes, or <newline>
997 # characters in URL's and filenames, followed by executable commands. A
998 # special variable $FileAllowedChars stores a string of all allowed
999 # characters. Any request that translates to a filename with a character
1000 # OUTSIDE this set will be rejected.
1001 # In general, all (readable files) in the DocumentRoot tree are accessible.
1002 # This might not be what you want. For instance, your DocumentRoot directory
1003 # might be the working directory of a CVS project and contain sensitive
1004 # information (e.g., the password to get to the repository). You can block
1005 # access to these subdirectories by adding the corresponding patterns to
1006 # the $BlockPathAccess variable. For instance, $BlockPathAccess = '/CVS/'
1007 # will block any request that contains '/CVS/' or:
1008 # die if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@;
1010 #10 The execution of code blocks can be controlled in a transparent way
1011 # by adding IF or UNLESS conditions in the tags themselves. That is,
1012 # a simple check of the validity of filenames or email addresses can
1013 # be done before any code is executed.
1015 ###############################################################################
1017 # USER MANUAL (sort of)
1019 # CGIscriptor removes embedded scripts, indicated by an HTML 4 type
1020 # <SCRIPT TYPE='text/ssperl'> </SCRIPT> or <SCRIPT TYPE='text/osshell'>
1021 # </SCRIPT> constructs. CGIscriptor also recognizes XML-type
1022 # <SCRIPT TYPE='text/ssperl'/> constructs. These are usefull when
1023 # the necessary code is already available in the TAG itself (e.g.,
1024 # using external files). The contents of the directive are executed by
1025 # the PERL eval() and `` functions (in a separate name space). The
1026 # result of the eval() function replaces the <SCRIPT> </SCRIPT> construct
1027 # in the output file. You can use the values that are delivered in
1028 # CGI-compliant form (i.e., the "?name=value&.." type URL additions)
1029 # transparently as "$name" variables in your directives after they are
1030 # defined in a <META> or <SCRIPT> tag.
1031 # If you define the variable "$CGIscriptorResults" in a CGI attribute, all
1032 # subsequent <SCRIPT> and <META> results (including the defining
1033 # tag) will also be pushed onto a stack: @CGIscriptorResults. This list
1034 # behaves like any other, ordinary list and can be manipulated.
1036 # Both GET and POST requests are accepted. These two methods are treated
1037 # equal. Variables, i.e., those values that are determined when a file is
1038 # processed, are indicated in the CGI attribute by $<name> or $<name>=<default>
1039 # in which <name> is the name of the variable and <default> is the value
1040 # used when there is NO current CGI value for <name> (you can use
1041 # white-spaces in $<name>=<default> but really DO make sure that the
1042 # default value is followed by white space or is quoted). Names can contain
1043 # any alphanumeric characters and _ (i.e., names match /[\w]+/).
1044 # If the Content-type: is 'multipart/*', the input is treated as a
1045 # MIME multipart message and automatically delimited. CGI variables get
1046 # the "raw" (i.e., undecoded) body of the corresponding message part.
1048 # Variables can be CGI variables, i.e., those from the QUERY_STRING,
1049 # environment variables, e.g., REMOTE_USER, REMOTE_HOST, or REMOTE_ADDR,
1050 # or predefined values, e.g., CGI_Decoded_QS (The complete, decoded,
1051 # query string), CGI_Content_Length (the length of the decoded query
1052 # string), CGI_Year, CGI_Month, CGI_Time, and CGI_Hour (the current
1053 # date and time).
1055 # All these are available when defined in a CGI attribute. All environment
1056 # variables are accessible as $ENV{'name'}. So, to access the REMOTE_HOST
1057 # and the REMOTE_USER, use, e.g.:
1059 # <SCRIPT TYPE='text/ssperl'>
1060 # ($ENV{'REMOTE_HOST'}||"-")." $ENV{'REMOTE_USER'}"
1061 # </SCRIPT>
1063 # (This will print a "-" if REMOTE_HOST is not known)
1064 # Another way to do this is:
1066 # <META CONTENT="text/ssperl; CGI='$REMOTE_HOST = - $REMOTE_USER'">
1067 # <SCRIPT TYPE='text/ssperl'>"$REMOTE_HOST $REMOTE_USER"</SCRIPT>
1068 # or
1069 # <META CONTENT='text/ssperl; CGI="$REMOTE_HOST = - $REMOTE_USER"
1070 # SRC={"$REMOTE_HOST $REMOTE_USER\n"}'>
1072 # This is possible because ALL environment variables are available as
1073 # CGI variables. The environment variables take precedence over CGI
1074 # names in case of a "name clash". For instance:
1075 # <META CONTENT="text/ssperl; CGI='$HOME' SRC={$HOME}">
1076 # Will print the current HOME directory (environment) irrespective whether
1077 # there is a CGI variable from the query
1078 # (e.g., Where do you live? <INPUT TYPE="TEXT" NAME="HOME">)
1079 # THIS IS A SECURITY FEATURE. It prevents clients from changing
1080 # the values of defined environment variables (e.g., by supplying
1081 # a bogus $REMOTE_ADDR). Although $ENV{} is not changed by the META tags,
1082 # it would make the use of declared variables insecure. You can still
1083 # access CGI variables after a name clash with
1084 # CGIscriptor::CGIparseValue(<name>).
1086 # Some CGI variables are present several times in the query string
1087 # (e.g., from multiple selections). These should be defined as
1088 # @VARIABLENAME=default in the CGI attribute. The list @VARIABLENAME
1089 # will contain ALL VARIABLENAME values from the query, or a single
1090 # default value. If there is an ENVIRONMENT variable of the
1091 # same name, it will be used instead of the default AND the query
1092 # values. The corresponding function is
1093 # CGIscriptor::CGIparseValueList(<name>)
1095 # CGI variables collected in a @VARIABLENAME list are unordered.
1096 # When more structured variables are needed, a hash table can be used.
1097 # A variable defined as %VARIABLE=default will collect all
1098 # CGI-parameters whose name start with 'VARIABLE' in a hash table with
1099 # the remainder of the name as a key. For instance, %PERSON will
1100 # collect PERSONname='John Doe', PERSONbirthdate='01 Jan 00', and
1101 # PERSONspouse='Alice' into a hash table %PERSON such that $PERSON{'spouse'}
1102 # equals 'Alice'. Any default value or environment value will be stored
1103 # under the "" key. If there is an ENVIRONMENT variable of the same name,
1104 # it will be used instead of the default AND the query values. The
1105 # corresponding function is CGIscriptor::CGIparseValueHash(<name>)
1107 # This method of first declaring your environment and CGI variables
1108 # before being able to use them in the scripts might seem somewhat
1109 # clumsy, but it protects you from inadvertedly printing out the values of
1110 # system environment variables when their names coincide with those used
1111 # in the CGI forms. It also prevents "clients" from supplying CGI
1112 # parameter values for your private variables.
1113 # THIS IS A SECURITY FEATURE!
1116 # NON-HTML CONTENT TYPES
1118 # Normally, CGIscriptor prints the standard "Content-type: text/html\n\n"
1119 # message before anything is printed. This has been extended to include
1120 # plain text (.txt) files, for which the Content-type (MIME type)
1121 # 'text/plain' is printed. In all other respects, text files are treated
1122 # as HTML files (this can be switched off by removing '.txt' from the
1123 # $FilePattern variable) . When the content type should be something else,
1124 # e.g., with multipart files, use the $RawFilePattern (.xmr, see also next
1125 # item). CGIscriptor will not print a Content-type message for this file
1126 # type (which must supply its OWN Content-type message). Raw files must
1127 # still conform to the <SCRIPT></SCRIPT> and <META> tag specifications.
1130 # NON-HTML FILES
1132 # CGIscriptor is intended to process HTML and text files only. You can
1133 # create documents of any mime-type on-the-fly using "raw" text files,
1134 # e.g., with the .xmr extension. However, CGIscriptor will not process
1135 # binary files of any type, e.g., pictures or sounds. Given the sheer
1136 # number of formats, I do not have any intention to do so. However,
1137 # an escape route has been provided. You can construct a genuine raw
1138 # (.xmr) text file that contains the perl code to service any file type
1139 # you want. If the global $BinaryMapFile variable contains the path to
1140 # this file (e.g., /BinaryMapFile.xmr), this file will be called
1141 # whenever an unsupported (non-HTML) file type is requested. The path
1142 # to the requested binary file is stored in $ENV('CGI_BINARY_FILE')
1143 # and can be used like any other CGI-variable. Servicing binary files
1144 # then becomes supplying the correct Content-type (e.g., print
1145 # "Content-type: image/jpeg\n\n";) and reading the file and writing it
1146 # to STDOUT (e.g., using sysread() and syswrite()).
1149 # THE META TAG
1151 # All attributes of a META tag are ignored, except the
1152 # CONTENT='text/ssperl; CGI=" ... " [SRC=" ... "]' attribute. The string
1153 # inside the quotes following the CONTENT= indication (white-space is
1154 # ignored, "" '' `` (){}[]-quote pairs are allowed, plus their \ versions)
1155 # MUST start with any of the CGIscriptor mime-types (e.g.: text/ssperl or
1156 # text/osshell) and a comma or semicolon.
1157 # The quoted string following CGI= contains a white-space separated list
1158 # of declarations of the CGI (and Environment) values and default values
1159 # used when no CGI values are supplied by the query string.
1161 # If the default value is a longer string containing special characters,
1162 # possibly spanning several lines, the string must be enclosed in quotes.
1163 # You may use any pair of quotes or brackets from the list '', "", ``, (),
1164 # [], or {} to distinguish default values (or preceded by \, e.g., \(...\)
1165 # is different from (...)). The outermost pair will always be used and any
1166 # other quotes inside the string are considered to be part of the string
1167 # value, e.g.,
1169 # $Value = {['this'
1170 # "and" (this)]}
1171 # will result in $Value getting the default value: ['this'
1172 # "and" (this)]
1173 # (NOTE that the newline is part of the default value!).
1175 # Internally, for defining and initializing CGI (ENV) values, the META
1176 # and SCRIPT tags use the functions "defineCGIvariable($name, $default)"
1177 # (scalars) and "defineCGIvariableList($name, $default)" (lists).
1178 # These functions can be used inside scripts as
1179 # "CGIscriptor::defineCGIvariable($name, $default)" and
1180 # "CGIscriptor::defineCGIvariableList($name, $default)".
1181 # "CGIscriptor::defineCGIvariableHash($name, $default)".
1183 # The CGI attribute will be processed exactly identical when used inside
1184 # the <SCRIPT> tag. However, this use is not according to the
1185 # HTML 4.0 specifications of the W3C.
1188 # THE DIV/INS TAGS
1190 # There is a problem when constructing html files containing
1191 # server-side perl scripts with standard HTML tools. These
1192 # tools will refuse to process any text between <SCRIPT></SCRIPT>
1193 # tags. This is quite annoying when you want to use large
1194 # HTML templates where you will fill in values.
1196 # For this purpose, CGIscriptor will read the neutral
1197 # <DIV CLASS="ssperl" ID="varname"></DIV> or
1198 # <INS CLASS="ssperl" ID="varname"></INS>
1199 # tag (in Cascading Style Sheet manner) Note that
1200 # "varname" has NO '$' before it, it is a bare name.
1201 # Any text between these <DIV ...></DIV> or
1202 # <INS ...></INS>tags will be assigned to '$varname'
1203 # as is (e.g., as a literal).
1204 # No processing or interpolation will be performed.
1205 # There is also NO nesting possible. Do NOT nest a
1206 # </DIV> inside a <DIV></DIV>! Moreover, neither INS nor
1207 # DIV tags do ensure a block structure in the final
1208 # rendering (i.e., no empty lines).
1210 # Note that <DIV CLASS="ssperl" ID="varname"/>
1211 # is handled the XML way. No content is processed,
1212 # but varname is defined, and any SRC directives are
1213 # processed.
1215 # You can use $varname like any other variable name.
1216 # However, $varname is NOT a CGI variable and will be
1217 # completely internal to your script. There is NO
1218 # interaction between $varname and the outside world.
1220 # To interpolate a DIV derived text, you can use:
1221 # $varname =~ s/([\]])/\\\1/g; # Mark ']'-quotes
1222 # $varname = eval("qq[$varname]"); # Interpolate all values
1224 # The DIV tags will process IF, UNLESS, CGI and
1225 # SRC attributes. The SRC files will be pre-pended to the
1226 # body text of the tag. SRC blocks are NOT executed.
1228 # CONDITIONAL PROCESSING: THE 'IF' AND 'UNLESS' ATTRIBUTES
1230 # It is often necessary to include code-blocks that should be executed
1231 # conditionally, e.g., only for certain browsers or operating system.
1232 # Furthermore, quite often sanity and security checks are necessary
1233 # before user (form) data can be processed, e.g., with respect to
1234 # email addresses and filenames.
1236 # Checks added to the code are often difficult to find, interpret or
1237 # maintain and in general mess up the code flow. This kind of confussion
1238 # is dangerous.
1239 # Also, for many of the supported "foreign" scripting languages, adding
1240 # these checks is cumbersome or even impossible.
1242 # As a uniform method for asserting the correctness of "context", two
1243 # attributes are added to all supported tags: IF and UNLESS.
1244 # They both evaluate their value and block execution when the
1245 # result is <FALSE> (IF) or <TRUE> (UNLESS) in Perl, e.g.,
1246 # UNLESS='$NUMBER \> 100;' blocks execution if $NUMBER <= 100. Note that
1247 # the backslash in the '\>' is removed and only used to differentiate
1248 # this conditional '>' from the tag-closing '>'. For symmetry, the
1249 # backslash in '\<' is also removed. Inside these conditionals,
1250 # ~/ and ./ are expanded to their respective directory root paths.
1252 # For example, the following tag will be ignored when the filename is
1253 # invalid:
1255 # <SCRIPT TYPE='text/ssperl' CGI='$FILENAME'
1256 # IF='CGIscriptor::CGIsafeFileName($FILENAME);'>
1257 # ...
1258 # </SCRIPT>
1260 # The IF and UNLESS values must be quoted. The same quotes are supported
1261 # as with the other attributes. The SRC attribute is ignored when IF and
1262 # UNLESS block execution.
1264 # NOTE: 'IF' and 'UNLESS' always evaluate perl code.
1267 # THE MAGIC SOURCE ATTRIBUTE (SRC=)
1269 # The SRC attribute inside tags accepts a list of filenames and URL's
1270 # separated by "," comma's (or ";" semicolons).
1271 # ALL the variable values defined in the CGI attribute are available
1272 # in @ARGV as if the file or block was executed from the command line,
1273 # in the exact order in which they were declared in the preceding CGI
1274 # attribute.
1276 # First, a SRC={}-block will be evaluated as if the code inside the
1277 # block was part of a <SCRIPT></SCRIPT> construct, i.e.,
1278 # "print do { code };'';" or `code` (i.e., SAFEqx('code)).
1279 # Only a single block is evaluated. Note that this is processed less
1280 # efficiently than <SCRIPT> </SCRIPT> blocks. Type of evaluation
1281 # depends on the content-type: Perl for text/ssperl and OS shell for
1282 # text/osshell. For other mime types (scripting languages), anything in
1283 # the source block is put in front of the code block "inside" the tag.
1285 # Second, executable files (i.e., -x filename != 0) are evaluated as:
1286 # print `filename \'$ARGV[0]\' \'$ARGV[1]\' ...`
1287 # That is, you can actually call executables savely from the SRC tag.
1289 # Third, text files that match the file pattern, used by CGIscriptor to
1290 # check whether files should be processed ($FilePattern), are
1291 # processed in-line (i.e., recursively) by CGIscriptor as if the code
1292 # was inserted in the original source file. Recursions, i.e., calling
1293 # a file inside itself, are blocked. If you need them, you have to code
1294 # them explicitely using "main::ProcessFile($file_path)".
1296 # Fourth, Perl text files (i.e., -T filename != 0) are evaluated as:
1297 # "do FileName;'';".
1299 # Last, URL's (i.e., starting with 'HTTP://', 'FTP://', 'GOPHER://',
1300 # 'TELNET://', 'WHOIS://' etc.) are loaded
1301 # and printed. The loading and handling of <BASE> and document header
1302 # is done by a command generated by main::GET_URL($URL [, 0]). You can enter your
1303 # own code (default is curl, wget, or snarf and some post-processing to add a <BASE> tag).
1305 # There are two pseudo-file names: PREFIX and POSTFIX. These implement
1306 # a switch from prefixing the SRC code/files (PREFIX, default) before the
1307 # content of the tag to appending the code after the content of the tag
1308 # (POSTFIX). The switches are done in the order in which the PREFIX and
1309 # POSTFIX labels are encountered. You can mix PREFIX and POSTFIX labels
1310 # in any order with the SRC files. Note that the ORDER of file execution
1311 # is determined for prefixed and postfixed files seperately.
1313 # File paths can be preceded by the URL protocol prefix "file://". This
1314 # is simply STRIPPED from the name.
1316 # Example:
1317 # The request
1318 # "http://cgi-bin/Action_Forms.pl/Statistics/Sign_Test.html?positive=8&negative=22
1319 # will result in printing "${SS_PUB}/Statistics/Sign_Test.html"
1320 # With QUERY_STRING = "positive=8&negative=22"
1322 # on encountering the lines:
1323 # <META CONTENT="text/osshell; CGI='$positive=11 $negative=3'">
1324 # <b><SCRIPT LANGUAGE=PERL TYPE="text/ssperl" SRC="./Statistics/SignTest.pl">
1325 # </SCRIPT></b><p>"
1327 # This line will be processed as:
1328 # "<b>`${SS_SCRIPT}/Statistics/SignTest.pl '8' '22'`</b><p>"
1330 # In which "${SS_SCRIPT}/Statistics/SignTest.pl" is an executable script,
1331 # This line will end up printed as:
1332 # "<b>p <= 0.0161</b><p>"
1334 # Note that the META tag itself will never be printed, and is invisible to
1335 # the outside world.
1337 # The SRC files in a DIV or INS tag will be added (pre-pended) to the body
1338 # of the <DIV></DIV> tag. Blocks are NOT executed! If you do not
1339 # need any content, you can use the <DIV...../> format.
1342 # THE CGISCRIPTOR ROOT DIRECTORIES ~/ AND ./
1344 # Inside <SCRIPT></SCRIPT> tags, filepaths starting
1345 # with "~/" are replaced by "$YOUR_HTML_FILES/", this way files in the
1346 # public directories can be accessed without direct reference to the
1347 # actual paths. Filepaths starting with "./" are replaced by
1348 # "$YOUR_SCRIPTS/" and this should only be used for scripts.
1350 # Note: this replacement can seriously affect Perl scripts. Watch
1351 # out for constructs like $a =~ s/aap\./noot./g, use
1352 # $a =~ s@aap\.@noot.@g instead.
1354 # CGIscriptor.pl will assign the values of $SS_PUB and $SS_SCRIPT
1355 # (i.e., $YOUR_HTML_FILES and $YOUR_SCRIPTS) to the environment variables
1356 # $SS_PUB and $SS_SCRIPT. These can be accessed by the scripts that are
1357 # executed.
1358 # Values not preceded by $, ~/, or ./ are used as literals
1361 # OS SHELL SCRIPT EVALUATION (CONTENT-TYPE=TEXT/OSSHELL)
1363 # OS scripts are executed by a "safe" version of the `` operator (i.e.,
1364 # SAFEqx(), see also below) and any output is printed. CGIscriptor will
1365 # interpolate the script and replace all user-supplied CGI-variables by
1366 # their ''-quoted values (actually, all variables defined in CGI attributes
1367 # are quoted). Other Perl variables are interpolated in a simple fasion,
1368 # i.e., $scalar by their value, @list by join(' ', @list), and %hash by
1369 # their name=value pairs. Complex references, e.g., @$variable, are all
1370 # evaluated in a scalar context. Quotes should be used with care.
1371 # NOTE: the results of the shell script evaluation will appear in the
1372 # @CGIscriptorResults stack just as any other result.
1373 # All occurrences of $@% that should NOT be interpolated must be
1374 # preceeded by a "\". Interpolation can be switched off completely by
1375 # setting $CGIscriptor::NoShellScriptInterpolation = 1
1376 # (set to 0 or undef to switch interpolation on again)
1377 # i.e.,
1378 # <SCRIPT TYPE="text/ssperl">
1379 # $CGIscriptor::NoShellScriptInterpolation = 1;
1380 # </SCRIPT>
1383 # RUN TIME TRANSLATION OF INPUT FILES
1385 # Allows general and global conversions of files using Regular Expressions.
1386 # Very handy (but costly) to rewrite legacy pages to a new format.
1387 # Select files to use it on with
1388 # my $TranslationPaths = 'filepattern';
1389 # This is costly. For efficiency, define:
1390 # $TranslationPaths = ''; when not using translations.
1391 # Accepts general regular expressions: [$pattern, $replacement]
1393 # Define:
1394 # my $TranslationPaths = 'filepattern'; # Pattern matching PATH_INFO
1396 # push(@TranslationTable, ['pattern', 'replacement']);
1397 # e.g. (for Ruby Rails):
1398 # push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
1399 # push(@TranslationTable, ['%>', '</SCRIPT>']);
1401 # Runs:
1402 # my $currentRegExp;
1403 # foreach $currentRegExp (@TranslationTable)
1405 # my ($pattern, $replacement) = @$currentRegExp;
1406 # $$text =~ s!$pattern!$replacement!msg;
1407 # };
1410 # EVALUATION OF OTHER SCRIPTING LANGUAGES
1412 # Adding a MIME-type and an interpreter command to
1413 # %ScriptingLanguages automatically will catch any other
1414 # scripting language in the standard
1415 # <SCRIPT TYPE="[mime]"></SCRIPT> manner.
1416 # E.g., adding: $ScriptingLanguages{'text/sspython'} = 'python';
1417 # will actually execute the folowing code in an HTML page
1418 # (ignore 'REMOTE_HOST' for the moment):
1419 # <SCRIPT TYPE="text/sspython">
1420 # # A Python script
1421 # x = ["A","real","python","script","Hello","World","and", REMOTE_HOST]
1422 # print x[4:8] # Prints the list ["Hello","World","and", REMOTE_HOST]
1423 # </SCRIPT>
1425 # The script code is NOT interpolated by perl, EXCEPT for those
1426 # interpreters that cannot handle variables themselves.
1427 # Currently, several interpreters are pre-installed:
1429 # Perl test - "text/testperl" => 'perl',
1430 # Python - "text/sspython" => 'python',
1431 # Ruby - "text/ssruby" => 'ruby',
1432 # Tcl - "text/sstcl" => 'tcl',
1433 # Awk - "text/ssawk" => 'awk -f-',
1434 # Gnu Lisp - "text/sslisp" => 'rep | tail +5 '.
1435 # "| egrep -v '> |^rep. |^nil\\\$'",
1436 # XLispstat - "text/xlispstat" => 'xlispstat | tail +7 '.
1437 # "| egrep -v '> \\\$|^NIL'",
1438 # Gnu Prolog- "text/ssprolog" => 'gprolog',
1439 # M4 macro's- "text/ssm4" => 'm4',
1440 # Born shell- "text/sh" => 'sh',
1441 # Bash - "text/bash" => 'bash',
1442 # C-shell - "text/csh" => 'csh',
1443 # Korn shell- "text/ksh" => 'ksh',
1444 # Praat - "text/sspraat" => "praat - | sed 's/Praat > //g'",
1445 # R - "text/ssr" => "R --vanilla --slave | sed 's/^[\[0-9\]*] //g'",
1446 # REBOL - "text/ssrebol" =>
1447 # "rebol --quiet|egrep -v '^[> ]* == '|sed 's/^\s*\[> \]* //g'",
1448 # PostgreSQL- "text/postgresql" => 'psql 2>/dev/null',
1449 # (psql)
1451 # Note that the "value" of $ScriptingLanguages{mime} must be a command
1452 # that reads Standard Input and writes to standard output. Any extra
1453 # output of interactive interpreters (banners, echo's, prompts)
1454 # should be removed by piping the output through 'tail', 'grep',
1455 # 'sed', or even 'awk' or 'perl'.
1457 # For access to CGI variables there is a special hashtable:
1458 # %ScriptingCGIvariables.
1459 # CGI variables can be accessed in three ways.
1460 # 1. If the mime type is not present in %ScriptingCGIvariables,
1461 # nothing is done and the script itself should parse the relevant
1462 # environment variables.
1463 # 2. If the mime type IS present in %ScriptingCGIvariables, but it's
1464 # value is empty, e.g., $ScriptingCGIvariables{"text/sspraat"} = '';,
1465 # the script text is interpolated by perl. That is, all $var, @array,
1466 # %hash, and \-slashes are replaced by their respective values.
1467 # 3. In all other cases, the CGI and environment variables are added
1468 # in front of the script according to the format stored in
1469 # %ScriptingCGIvariables. That is, the following (pseudo-)code is
1470 # executed for each CGI- or Environment variable defined in the CGI-tag:
1471 # printf(INTERPRETER, $ScriptingCGIvariables{$mime}, $CGI_NAME, $CGI_VALUE);
1473 # For instance, "text/testperl" => '$%s = "%s";' defines variable
1474 # definitions for Perl, and "text/sspython" => '%s = "%s"' for Python
1475 # (note that these definitions are not save, the real ones contain '-quotes).
1477 # THIS WILL NOT WORK FOR @VARIABLES, the (empty) $VARIABLES will be used
1478 # instead.
1480 # The $CGI_VALUE parameters are "shrubed" of all control characters
1481 # and quotes (by &shrubCGIparameter($CGI_VALUE)) for the options 2 and 3.
1482 # Control characters are replaced by \0<octal ascii value> (the exception
1483 # is \015, the newline, which is replaced by \n) and quotes
1484 # and backslashes by their HTML character
1485 # value (' -> &#39; ` -> &#96; " -> &quot; \ -> &#92; & -> &amper;).
1486 # For example:
1487 # if a client would supply the string value (in standard perl, e.g.,
1488 # \n means <newline>)
1489 # "/dev/null';\nrm -rf *;\necho '"
1490 # it would be processed as
1491 # '/dev/null&#39;;\nrm -rf *;\necho &#39;'
1492 # (e.g., sh or bash would process the latter more according to your
1493 # intentions).
1494 # If your intepreter requires different protection measures, you will
1495 # have to supply these in %main::SHRUBcharacterTR (string => translation),
1496 # e.g., $SHRUBcharacterTR{"\'"} = "&#39;";
1498 # Currently, the following definitions are used:
1499 # %ScriptingCGIvariables = (
1500 # "text/testperl" => "\$\%s = '\%s';", # Perl $VAR = 'value' (for testing)
1501 # "text/sspython" => "\%s = '\%s'", # Python VAR = 'value'
1502 # "text/ssruby" => '@%s = "%s"', # Ruby @VAR = "value"
1503 # "text/sstcl" => 'set %s "%s"', # TCL set VAR "value"
1504 # "text/ssawk" => '%s = "%s";', # Awk VAR = "value";
1505 # "text/sslisp" => '(setq %s "%s")', # Gnu lisp (rep) (setq VAR "value")
1506 # "text/xlispstat" => '(setq %s "%s")', # Xlispstat (setq VAR "value")
1507 # "text/ssprolog" => '', # Gnu prolog (interpolated)
1508 # "text/ssm4" => "define(`\%s', `\%s')", # M4 macro's define(`VAR', `value')
1509 # "text/sh" => "\%s='\%s';", # Born shell VAR='value';
1510 # "text/bash" => "\%s='\%s';", # Born again shell VAR='value';
1511 # "text/csh" => "\$\%s = '\%s';", # C shell $VAR = 'value';
1512 # "text/ksh" => "\$\%s = '\%s';", # Korn shell $VAR = 'value';
1513 # "text/sspraat" => '', # Praat (interpolation)
1514 # "text/ssr" => '%s <- "%s";', # R VAR <- "value";
1515 # "text/ssrebol" => '%s: copy "%s"', # REBOL VAR: copy "value"
1516 # "text/postgresql" => '', # PostgreSQL (interpolation)
1517 # "" => ""
1518 # );
1520 # Four tables allow fine-tuning of interpreter with code that should be
1521 # added before and after each code block:
1523 # Code added before each script block
1524 # %ScriptingPrefix = (
1525 # "text/testperl" => "\# Prefix Code;", # Perl script testing
1526 # "text/ssm4" => 'divert(0)' # M4 macro's (open STDOUT)
1527 # );
1528 # Code added at the end of each script block
1529 # %ScriptingPostfix = (
1530 # "text/testperl" => "\# Postfix Code;", # Perl script testing
1531 # "text/ssm4" => 'divert(-1)' # M4 macro's (block STDOUT)
1532 # );
1533 # Initialization code, inserted directly after opening (NEVER interpolated)
1534 # %ScriptingInitialization = (
1535 # "text/testperl" => "\# Initialization Code;", # Perl script testing
1536 # "text/ssawk" => 'BEGIN {', # Server Side awk scripts
1537 # "text/sslisp" => '(prog1 nil ', # Lisp (rep)
1538 # "text/xlispstat" => '(prog1 nil ', # xlispstat
1539 # "text/ssm4" => 'divert(-1)' # M4 macro's (block STDOUT)
1540 # );
1541 # Cleanup code, inserted before closing (NEVER interpolated)
1542 # %ScriptingCleanup = (
1543 # "text/testperl" => "\# Cleanup Code;", # Perl script testing
1544 # "text/sspraat" => 'Quit',
1545 # "text/ssawk" => '};', # Server Side awk scripts
1546 # "text/sslisp" => '(princ "\n" standard-output)).' # Closing print to rep
1547 # "text/xlispstat" => '(print "" *standard-output*)).' # Closing print to xlispstat
1548 # "text/postgresql" => '\q',
1549 # );
1552 # The SRC attribute is NOT magical for these interpreters. In short,
1553 # all code inside a source file or {} block is written verbattim
1554 # to the interpreter. No (pre-)processing or executional magic is done.
1556 # A serious shortcomming of the described mechanism for handling other
1557 # (scripting) languages, with respect to standard perl scripts
1558 # (i.e., 'text/ssperl'), is that the code is only executed when
1559 # the pipe to the interpreter is closed. So the pipe has to be
1560 # closed at the end of each block. This means that the state of the
1561 # interpreter (e.g., all variable values) is lost after the closing of
1562 # the next </SCRIPT> tag. The standard 'text/ssperl' scripts retain
1563 # all values and definitions.
1565 # APPLICATION MIME TYPES
1567 # To ease some important auxilliary functions from within the
1568 # html pages I have added them as MIME types. This uses
1569 # the mechanism that is also used for the evaluation of
1570 # other scripting languages, with interpolation of CGI
1571 # parameters (and perl-variables). Actually, these are
1572 # defined exactly like any other "scripting language".
1574 # text/ssdisplay: display some (HTML) text with interpolated
1575 # variables (uses `cat`).
1576 # text/sslogfile: write (append) the interpolated block to the file
1577 # mentioned on the first, non-empty line
1578 # (the filename can be preceded by 'File: ',
1579 # note the space after the ':',
1580 # uses `awk .... >> <filename>`).
1581 # text/ssmailto: send email directly from within the script block.
1582 # The first line of the body must contain
1583 # To:Name@Valid.Email.Address
1584 # (note: NO space between 'To:' and the email adres)
1585 # For other options see the mailto man pages.
1586 # It works by directly sending the (interpolated)
1587 # content of the text block to a pipe into the
1588 # Linux program 'mailto'.
1590 # In these script blocks, all Perl variables will be
1591 # replaced by their values. All CGI variables are cleaned before
1592 # they are used. These CGI variables must be redefined with a
1593 # CGI attribute to restore their original values.
1594 # In general, this will be more secure than constructing
1595 # e.g., your own email command lines. For instance, Mailto will
1596 # not execute any odd (forged) email addres, but just stops
1597 # when the email address is invalid and awk will construct
1598 # any filename you give it (e.g. '<File;rm\\\040-f' would end up
1599 # as a "valid" UNIX filename). Note that it will also gladly
1600 # store this file anywhere (/../../../etc/passwd will work!).
1601 # Use the CGIscriptor::CGIsafeFileName() function to clean the
1602 # filename.
1604 # SHELL SCRIPT PIPING
1606 # If a shell script starts with the UNIX style "#! <shell command> \n"
1607 # line, the rest of the shell script is piped into the indicated command,
1608 # i.e.,
1609 # open(COMMAND, "| command");print COMMAND $RestOfScript;
1611 # In many ways this is equivalent to the MIME-type profiling for
1612 # evaluating other scripting languages as discussed above. The
1613 # difference breaks down to convenience. Shell script piping is a
1614 # "raw" implementation. It allows you to control all aspects of
1615 # execution. Using the MIME-type profiling is easier, but has a
1616 # lot of defaults built in that might get in the way. Another
1617 # difference is that shell script piping uses the SAFEqx() function,
1618 # and MIME-type profiling does not.
1620 # Execution of shell scripts is under the control of the Perl Script blocks
1621 # in the document. The MIME-type triggered execution of <SCRIPT></SCRIPT>
1622 # blocks can be simulated easily. You can switch to a different shell,
1623 # e.g. tcl, completely by executing the following Perl commands inside
1624 # your document:
1626 # <SCRIPT TYPE="text/ssperl">
1627 # $main::ShellScriptContentType = "text/ssTcl"; # Yes, you can do this
1628 # CGIscriptor::RedirectShellScript('/usr/bin/tcl'); # Pipe to Tcl
1629 # $CGIscriptor::NoShellScriptInterpolation = 1;
1630 # </SCRIPT>
1632 # After this script is executed, CGIscriptor will parse scripts of
1633 # TYPE="text/ssTcl" and pipe their contents into '|/usr/bin/tcl'
1634 # WITHOUT interpolation (i.e., NO substitution of Perl variables).
1635 # The crucial function is :
1636 # CGIscriptor::RedirectShellScript('/usr/bin/tcl')
1637 # After executing this function, all shell scripts AND all
1638 # calls to SAFEqx()) are piped into '|/usr/bin/tcl'. If the argument
1639 # of RedirectShellScript is empty, e.g., '', the original (default)
1640 # value is reset.
1642 # The standard output, STDOUT, of any pipe is send to the client.
1643 # Currently, you should be carefull with quotes in such a piped script.
1644 # The results of a pipe is NOT put on the @CGIscriptorResults stack.
1645 # As a result, you do not have access to the output of any piped (#!)
1646 # process! If you want such access, execute
1647 # <SCRIPT TYPE="text/osshell">echo "script"|command</SCRIPT>
1648 # or
1649 # <SCRIPT TYPE="text/ssperl">
1650 # $resultvar = SAFEqx('echo "script"|command');
1651 # </SCRIPT>.
1653 # Safety is never complete. Although SAFEqx() prevents some of the
1654 # most obvious forms of attacks and security slips, it cannot prevent
1655 # them all. Especially, complex combinations of quotes and intricate
1656 # variable references cannot be handled safely by SAFEqx. So be on
1657 # guard.
1660 # PERL CODE EVALUATION (CONTENT-TYPE=TEXT/SSPERL)
1662 # All PERL scripts are evaluated inside a PERL package. This package
1663 # has a separate name space. This isolated name space protects the
1664 # CGIscriptor.pl program against interference from user code. However,
1665 # some variables, e.g., $_, are global and cannot be protected. You are
1666 # advised NOT to use such global variable names. You CAN write
1667 # directives that directly access the variables in the main program.
1668 # You do so at your own risk (there is definitely enough rope available
1669 # to hang yourself). The behavior of CGIscriptor becomes undefined if
1670 # you change its private variables during run time. The PERL code
1671 # directives are used as in:
1672 # $Result = eval($directive); print $Result;'';
1673 # ($directive contains all text between <SCRIPT></SCRIPT>).
1674 # That is, the <directive> is treated as ''-quoted string and
1675 # the result is treated as a scalar. To prevent the VALUE of the code
1676 # block from appearing on the client's screen, end the directive with
1677 # ';""</SCRIPT>'. Evaluated directives return the last value, just as
1678 # eval(), blocks, and subroutines, but only as a scalar.
1680 # IMPORTANT: All PERL variables defined are persistent. Each <SCRIPT>
1681 # </SCRIPT> construct is evaluated as a {}-block with associated scope
1682 # (e.g., for "my $var;" declarations). This means that values assigned
1683 # to a PERL variable can be used throughout the document unless they
1684 # were declared with "my". The following will actually work as intended
1685 # (note that the ``-quotes in this example are NOT evaluated, but used
1686 # as simple quotes):
1688 # <META CONTENT="text/ssperl; CGI=`$String='abcdefg'`">
1689 # anything ...
1690 # <SCRIPT TYPE=text/ssperl>@List = split('', $String);</SCRIPT>
1691 # anything ...
1692 # <SCRIPT TYPE=text/ssperl>join(", ", @List[1..$#List]);</SCRIPT>
1694 # The first <SCRIPT TYPE=text/ssperl></SCRIPT> construct will return the
1695 # value scalar(@List), the second <SCRIPT TYPE=text/ssperl></SCRIPT>
1696 # construct will print the elements of $String separated by commas, leaving
1697 # out the first element, i.e., $List[0].
1699 # Another warning: './' and '~/' are ALWAYS replaced by the values of
1700 # $YOUR_SCRIPTS and $YOUR_HTML_FILES, respectively . This can interfere
1701 # with pattern matching, e.g., $a =~ s/aap\./noot\./g will result in the
1702 # evaluations of $a =~ s/aap\\${YOUR_SCRIPTS}noot\\${YOUR_SCRIPTS}g. Use
1703 # s@<regexp>.@<replacement>.@g instead.
1706 # SERVER SIDE SESSIONS AND ACCESS CONTROL (LOGIN)
1708 # An infrastructure for user acount authorization and file access control
1709 # is available. Each request is matched against a list of URL path patterns.
1710 # If the request matches, a Session Ticket is required to access the URL.
1711 # This Session Ticket should be present as a CGI parameter:
1712 # SESSIONTICKET=<value>
1713 # The example implementation stores Session Tickets as files in a local
1714 # directory. To create Session Tickets, a Login request must be given
1715 # with a LOGIN=<value> CGI parameter, a user name and a (doubly hashed)
1716 # password. The user name and (singly hashed) password are stored in a
1717 # PASSWORD ticket with the same name as the user account (name cleaned up
1718 # for security).
1720 # A Login page should create a LOGIN ticket file localy and send a
1721 # server specific SALT, a Random salt, and both the LOGIN and SESSION ticket
1722 # identifiers. The server side compares the username and hashed password,
1723 # actually hashed(Random salt+hashed(SALT+password)) from the client with
1724 # the values it calculates from the stored Random salt from the LOGIN
1725 # ticket and the hashed(SALT+password) from the PASSWORD ticket. If
1726 # successful, a new SESSION ticket is generated. The SESSION ticket
1727 # identifier is available as $SESSIONTICKET, the Username, IP address
1728 # and Path as $LoginUsername, $LoginIPaddress, and $LoginPath, respectively.
1730 # In the current example implementation, all random values are created as
1731 # a full SHA1 hash (Hex) of a 512 byte block read from /dev/urandom.
1733 # The example session model implements 3 functions:
1734 # 1 Login
1735 # The password is hashed with the server side salt, and then hashed with
1736 # a Random salt. The server side only stores the password hashed with the
1737 # server side salt. Neither the plain password, nor the hashed password is
1738 # ever exchanged. Only values hashed with the one-time salt are exchanged.
1739 # 2 Session
1740 # For every access to a restricted URL, the Session Ticket is checked
1741 # before access is granted.
1742 # 3 Password Change
1743 # A new password is hashed with the server side salt, and then XORed
1744 # with the old password hashed with the salt. That value is exchanged
1745 # and XORed with the stored old hashed(salt+password). Again, the
1746 # stored password value is never exchanged unencrypted.
1748 # USER EXTENSIONS
1750 # A CGIscriptor package is attached to the bottom of this file. With
1751 # this package you can personalize your version of CGIscriptor by
1752 # including often used perl routines. These subroutines can be
1753 # accessed by prefixing their names with CGIscriptor::, e.g.,
1754 # <SCRIPT LANGUAGE=PERL TYPE=text/ssperl>
1755 # CGIscriptor::ListDocs("/Books/*") # List all documents in /Books
1756 # </SCRIPT>
1757 # It already contains some useful subroutines for Document Management.
1758 # As it is a separate package, it has its own namespace, isolated from
1759 # both the evaluator and the main program. To access variables from
1760 # the document <SCRIPT></SCRIPT> blocks, use $CGIexecute::<var>.
1762 # Currently, the following functions are implemented
1763 # (precede them with CGIscriptor::, see below for more information)
1764 # - SAFEqx ('String') -> result of qx/"String"/ # Safe application of ``-quotes
1765 # Is used by text/osshell Shell scripts. Protects all CGI
1766 # (client-supplied) values with single quotes before executing the
1767 # commands (one of the few functions that also works WITHOUT CGIscriptor::
1768 # in front)
1769 # - defineCGIvariable ($name[, $default) -> 0/1 (i.e., failure/success)
1770 # Is used by the META tag to define and initialize CGI and ENV
1771 # name/value pairs. Tries to obtain an initializing value from (in order):
1772 # $ENV{$name}
1773 # The Query string
1774 # The default value given (if any)
1775 # (one of the few functions that also works WITHOUT CGIscriptor::
1776 # in front)
1777 # - CGIsafeFileName (FileName) -> FileName or ""
1778 # Check a string against the Allowed File Characters (and ../ /..).
1779 # Returns an empty string for unsafe filenames.
1780 # - CGIsafeEmailAddress (Email) -> Email or ""
1781 # Check a string against correct email address pattern.
1782 # Returns an empty string for unsafe addresses.
1783 # - RedirectShellScript ('CommandString') -> FILEHANDLER or undef
1784 # Open a named PIPE for SAFEqx to receive ALL shell scripts
1785 # - URLdecode (URL encoded string) -> plain string # Decode URL encoded argument
1786 # - URLencode (plain string) -> URL encoded string # Encode argument as URL code
1787 # - CGIparseValue (ValueName [, URL_encoded_QueryString]) -> Decoded value
1788 # Extract the value of a CGI variable from the global or a private
1789 # URL-encoded query (multipart POST raw, NOT decoded)
1790 # - CGIparseValueList (ValueName [, URL_encoded_QueryString])
1791 # -> List of decoded values
1792 # As CGIparseValue, but now assembles ALL values of ValueName into a list.
1793 # - CGIparseHeader (ValueName [, URL_encoded_QueryString]) -> Header
1794 # Extract the header of a multipart CGI variable from the global or a private
1795 # URL-encoded query ("" when not a multipart variable or absent)
1796 # - CGIparseForm ([URL_encoded_QueryString]) -> Decoded Form
1797 # Decode the complete global URL-encoded query or a private
1798 # URL-encoded query
1799 # - read_url(URL) # Returns the page from URL (with added base tag, both FTP and HTTP)
1800 # Uses main::GET_URL(URL, 1) to get at the command to read the URL.
1801 # - BrowseDirs(RootDirectory [, Pattern, Startdir, CGIname]) # print browsable directories
1802 # - ListDocs(Pattern [,ListType]) # Prints a nested HTML directory listing of
1803 # all documents, e.g., ListDocs("/*", "dl");.
1804 # - HTMLdocTree(Pattern [,ListType]) # Prints a nested HTML listing of all
1805 # local links starting from a given document, e.g.,
1806 # HTMLdocTree("/Welcome.html", "dl");
1809 # THE RESULTS STACK: @CGISCRIPTORRESULTS
1811 # If the pseudo-variable "$CGIscriptorResults" has been defined in a
1812 # META tag, all subsequent SCRIPT and META results are pushed
1813 # on the @CGIscriptorResults stack. This list is just another
1814 # Perl variable and can be used and manipulated like any other list.
1815 # $CGIscriptorResults[-1] is always the last result.
1816 # This is only of limited use, e.g., to use the results of an OS shell
1817 # script inside a Perl script. Will NOT contain the results of Pipes
1818 # or code from MIME-profiling.
1821 # USEFULL CGI PREDEFINED VARIABLES (DO NOT ASSIGN TO THESE)
1823 # $CGI_HOME - The DocumentRoot directory
1824 # $CGI_Decoded_QS - The complete decoded Query String
1825 # $CGI_Content_Length - The ACTUAL length of the Query String
1826 # $CGI_Date - Current date and time
1827 # $CGI_Year $CGI_Month $CGI_Day $CGI_WeekDay - Current Date
1828 # $CGI_Time - Current Time
1829 # $CGI_Hour $CGI_Minutes $CGI_Seconds - Current Time, split
1830 # GMT Date/Time:
1831 # $CGI_GMTYear $CGI_GMTMonth $CGI_GMTDay $CGI_GMTWeekDay $CGI_GMTYearDay
1832 # $CGI_GMTHour $CGI_GMTMinutes $CGI_GMTSeconds $CGI_GMTisdst
1835 # USEFULL CGI ENVIRONMENT VARIABLES
1837 # Variables accessible (in APACHE) as $ENV{<name>}
1838 # (see: "http://hoohoo.ncsa.uiuc.edu/cgi/env.html"):
1840 # QUERY_STRING - The query part of URL, that is, everything that follows the
1841 # question mark.
1842 # PATH_INFO - Extra path information given after the script name
1843 # PATH_TRANSLATED - Extra pathinfo translated through the rule system.
1844 # (This doesn't always make sense.)
1845 # REMOTE_USER - If the server supports user authentication, and the script is
1846 # protected, this is the username they have authenticated as.
1847 # REMOTE_HOST - The hostname making the request. If the server does not have
1848 # this information, it should set REMOTE_ADDR and leave this unset
1849 # REMOTE_ADDR - The IP address of the remote host making the request.
1850 # REMOTE_IDENT - If the HTTP server supports RFC 931 identification, then this
1851 # variable will be set to the remote user name retrieved from
1852 # the server. Usage of this variable should be limited to logging
1853 # only.
1854 # AUTH_TYPE - If the server supports user authentication, and the script
1855 # is protected, this is the protocol-specific authentication
1856 # method used to validate the user.
1857 # CONTENT_TYPE - For queries which have attached information, such as HTTP
1858 # POST and PUT, this is the content type of the data.
1859 # CONTENT_LENGTH - The length of the said content as given by the client.
1860 # SERVER_SOFTWARE - The name and version of the information server software
1861 # answering the request (and running the gateway).
1862 # Format: name/version
1863 # SERVER_NAME - The server's hostname, DNS alias, or IP address as it
1864 # would appear in self-referencing URLs
1865 # GATEWAY_INTERFACE - The revision of the CGI specification to which this
1866 # server complies. Format: CGI/revision
1867 # SERVER_PROTOCOL - The name and revision of the information protocol this
1868 # request came in with. Format: protocol/revision
1869 # SERVER_PORT - The port number to which the request was sent.
1870 # REQUEST_METHOD - The method with which the request was made. For HTTP,
1871 # this is "GET", "HEAD", "POST", etc.
1872 # SCRIPT_NAME - A virtual path to the script being executed, used for
1873 # self-referencing URLs.
1874 # HTTP_ACCEPT - The MIME types which the client will accept, as given by
1875 # HTTP headers. Other protocols may need to get this
1876 # information from elsewhere. Each item in this list should
1877 # be separated by commas as per the HTTP spec.
1878 # Format: type/subtype, type/subtype
1879 # HTTP_USER_AGENT - The browser the client is using to send the request.
1880 # General format: software/version library/version.
1883 # INSTRUCTIONS FOR RUNNING CGIscriptor ON UNIX
1885 # CGIscriptor.pl will run on any WWW server that runs Perl scripts, just add
1886 # a line like the following to your srm.conf file (Apache example):
1888 # ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
1890 # URL's that refer to http://www.your.address/SHTML/... will now be handled
1891 # by CGIscriptor.pl, which can use a private directory tree (default is the
1892 # DOCUMENT_ROOT directory tree, but it can be anywhere, see manual).
1894 # If your hosting ISP won't let you add ScriptAlias lines you can use
1895 # the following "rewrite"-based "scriptalias" in .htaccess
1896 # (from Gerd Franke)
1898 # RewriteEngine On
1899 # RewriteBase /
1900 # RewriteCond %{REQUEST_FILENAME} .html$
1901 # RewriteCond %{SCRIPT_FILENAME} !cgiscriptor.pl$
1902 # RewriteCond %{REQUEST_FILENAME} -f
1903 # RewriteRule ^(.*)$ /cgi-bin/cgiscriptor.pl/$1?&%{QUERY_STRING}
1905 # Everthing with the extension ".html" and not including "cgiscriptor.pl"
1906 # in the url and where the file "path/filename.html" exists is redirected
1907 # to "/cgi.bin/cgiscriptor.pl/path/filename.html?query".
1908 # The user configuration should get the same path-level as the
1909 # .htaccess-file:
1911 # # Just enter your own directory path here
1912 # $YOUR_HTML_FILES = "$ENV{'DOCUMENT_ROOT'}";
1913 # # use DOCUMENT_ROOT only, if .htaccess lies in the root-directory.
1915 # If this .htaccess goes in a specific directory, the path to this
1916 # directory must be added to $ENV{'DOCUMENT_ROOT'}.
1918 # The CGIscriptor file contains all documentation as comments. These
1919 # comments can be removed to speed up loading (e.g., `egrep -v '^#'
1920 # CGIscriptor.pl` > leanScriptor.pl). A bare bones version of
1921 # CGIscriptor.pl, lacking documentation, most comments, access control,
1922 # example functions etc. (but still with the copyright notice and some
1923 # minimal documentation) can be obtained by calling CGIscriptor.pl on the
1924 # command line with the '-slim' command line argument, e.g.,
1926 # >CGIscriptor.pl -slim > slimCGIscriptor.pl
1928 # CGIscriptor.pl can be run from the command line with <path> and <query> as
1929 # arguments, as `CGIscriptor.pl <path> <query>`, inside a perl script
1930 # with 'do CGIscriptor.pl' after setting $ENV{PATH_INFO}
1931 # and $ENV{QUERY_STRING}, or CGIscriptor.pl can be loaded with 'require
1932 # "/real-path/CGIscriptor.pl"'. In the latter case, requests are processed
1933 # by 'Handle_Request();' (again after setting $ENV{PATH_INFO} and
1934 # $ENV{QUERY_STRING}).
1936 # Using the command line execution option, CGIscriptor.pl can be used as a
1937 # document (meta-)preprocessor. If the first argument is '-', STDIN will be read.
1938 # For example:
1940 # > cat MyDynamicDocument.html | CGIscriptor.pl - '[QueryString]' > MyStaticFile.html
1942 # This command line will produce a STATIC file with the DYNAMIC content of
1943 # MyDocument.html "interpolated".
1945 # This option would be very dangerous when available over the internet.
1946 # If someone could sneak a 'http://www.your.domain/-' URL past your
1947 # server, CGIscriptor could EXECUTE any POSTED contend.
1948 # Therefore, for security reasons, STDIN will NOT be read
1949 # if ANY of the HTTP server environment variables is set (e.g.,
1950 # SERVER_PORT, SERVER_PROTOCOL, SERVER_NAME, SERVER_SOFTWARE,
1951 # HTTP_USER_AGENT, REMOTE_ADDR).
1952 # This block on processing STDIN on HTTP requests can be lifted by setting
1953 # $BLOCK_STDIN_HTTP_REQUEST = 0;
1954 # In the security configuration. Butbe carefull when doing this.
1955 # It can be very dangerous.
1957 # Running demo's and more information can be found at
1958 # http://www.fon.hum.uva.nl/~rob/OSS/OSS.html
1960 # A pocket-size HTTP daemon, CGIservlet.pl, is available from my web site or
1961 # CPAN that can use CGIscriptor.pl as the base of a µWWW server and
1962 # demonstrates its use.
1965 # PROCESSING NON-FILESYSTEM DATA
1967 # Normally, HTTP (WWW) requests map onto file that can be accessed
1968 # using the perl open() function. That is, the web server runs on top of
1969 # some directory structure. However, we can envission (and put to good
1970 # use) other systems that do not use a normal file system. The whole CGI
1971 # was developed to make dynamic document generation possible.
1973 # A special case is where we want to have it both: A normal web server
1974 # with normal "file data", but not a normal files system. For instance,
1975 # we want or normal Web Site to run directly from a RAM hash table or
1976 # other database, instead of from disk. But we do NOT want to code the
1977 # whole site structure in CGI.
1979 # CGIscriptor can do this. If the web server fills an environment variable
1980 # $ENV{'CGI_FILE_CONTENT'} with the content of the "file", then the content
1981 # of this variable is processed instead of opening a file. If this environment
1982 # variable has the value '-', the content of another environment variable,
1983 # $ENV{'CGI_DATA_ACCESS_CODE'} is executed as:
1984 # eval("\@_ = ($file_path); do {$ENV{'CGI_DATA_ACCESS_CODE'}};")
1985 # and the result is processed as if it was the content of the requested
1986 # file.
1987 # (actually, the names of the environment variables are user configurable,
1988 # they are stored in the local variables $CGI_FILE_CONTENT and
1989 # $CGI_DATA_ACCESS_CODE)
1991 # When using this mechanism, the SRC attribute mechanism will only partially work.
1992 # Only the "recursive" calls to CGIscriptor (the ProcessFile() function)
1993 # will work, the automagical execution of SRC files won't. (In this case,
1994 # the SRC attribute won't work either for other scripting languages)
1997 # NON-UNIX PLATFORMS
1999 # CGIscriptor.pl was mainly developed and tested on UNIX. However, as I
2000 # coded part of the time on an Apple Macintosh under MacPerl, I made sure
2001 # CGIscriptor did run under MacPerl (with command line options). But only
2002 # as an independend script, not as part of a HTTP server. I have used it
2003 # under Apache in Windows XP.
2005 ENDOFHELPTEXT
2006 exit;
2008 ###############################################################################
2010 # SECURITY CONFIGURATION
2012 # Special configurations related to SECURITY
2013 # (i.e., optional, see also environment variables below)
2015 # LOGGING
2016 # Log Clients and the requested paths (Redundant when loging Queries)
2018 $ClientLog = "./Client.log"; # (uncomment for use)
2020 # Format: Localtime | REMOTE_USER REMOTE_IDENT REMOTE_HOST REMOTE_ADDRESS \
2021 # PATH_INFO CONTENT_LENGTH (actually, the real query+post length)
2023 # Log Clients and the queries, the CGIQUERYDECODE is required if you want
2024 # to log queries. If you log Queries, the loging of Clients is redundant
2025 # (note that queries can be quite long, so this might not be a good idea)
2027 #$QueryLog = "./Query.log"; # (uncomment for use)
2029 # ACCESS CONTROL
2030 # the Access files should contain Hostnames or IP addresses,
2031 # i.e. REMOTE_HOST or REMOTE_ADDR, each on a separate line
2032 # optionally followed by one ore more file patterns, e.g., "edu /DEMO".
2033 # Matching is done "domain first". For example ".edu" matches all
2034 # clients whose "name" ends in ".edu" or ".EDU". The file pattern
2035 # "/DEMO" matches all paths that contain the strings "/DEMO" or "/demo"
2036 # (both matchings are done case-insensitive).
2037 # The name special symbol "-" matches ALL clients who do not supply a
2038 # REMOTE_HOST name, "*" matches all clients.
2039 # Lines starting with '-e' are evaluated. A non-zero return value indicates
2040 # a match. You can use $REMOTE_HOST, $REMOTE_ADDR, and $PATH_INFO. These
2041 # lines are evaluated in the program's own name-space. So DO NOT assign to
2042 # variables.
2044 # Accept the following users (remove comment # and adapt filename)
2045 $CGI_Accept = -s "$YOUR_SCRIPTS/ACCEPT.lis" ? "$YOUR_SCRIPTS/ACCEPT.lis" : ''; # (uncomment for use)
2047 # Reject requests from the following users (remove comment # and
2048 # adapt filename, this is only of limited use)
2049 $CGI_Reject = -s "$YOUR_SCRIPTS/REJECT.lis" ? "$YOUR_SCRIPTS/REJECT.lis" : ''; # (uncomment for use)
2051 # Empty lines or comment lines starting with '#' are ignored in both
2052 # $CGI_Accept and $CGI_Reject.
2054 # Block STDIN (i.e., '-') requests when servicing an HTTP request
2055 # Comment this out if you realy want to use STDIN in an on-line web server
2056 $BLOCK_STDIN_HTTP_REQUEST = 1;
2059 # End of security configuration
2061 ##################################################<<<<<<<<<<End Remove
2063 # PARSING CGI VALUES FROM THE QUERY STRING (USER CONFIGURABLE)
2065 # The CGI parse commands. These commands extract the values of the
2066 # CGI variables from the URL encoded Query String.
2067 # If you want to use your own CGI decoders, you can call them here
2068 # instead, using your own PATH and commenting/uncommenting the
2069 # appropriate lines
2071 # CGI parse command for individual values
2072 # (if $List > 0, returns a list value, if $List < 0, a hash table, this is optional)
2073 sub YOUR_CGIPARSE # ($Name [, $List]) -> Decoded value
2075 my $Name = shift;
2076 my $List = shift || 0;
2077 # Use one of the following by uncommenting
2078 if(!$List) # Simple value
2080 return CGIscriptor::CGIparseValue($Name) ;
2082 elsif($List < 0) # Hash tables
2084 return CGIscriptor::CGIparseValueHash($Name); # Defined in CGIscriptor below
2086 else # Lists
2088 return CGIscriptor::CGIparseValueList($Name); # Defined in CGIscriptor below
2091 # return `/PATH/cgiparse -value $Name`; # Shell commands
2092 # require "/PATH/cgiparse.pl"; return cgivalue($Name); # Library
2094 # Complete queries
2095 sub YOUR_CGIQUERYDECODE
2097 # Use one of the following by uncommenting
2098 return CGIscriptor::CGIparseForm(); # Defined in CGIscriptor below
2099 # return `/PATH/cgiparse -form`; # Shell commands
2100 # require "/PATH/cgiparse.pl"; return cgiform(); # Library
2103 # End of configuration
2105 #######################################################################
2107 # Translating input files.
2108 # Allows general and global conversions of files using Regular Expressions
2109 # Translations are applied in the order of definition.
2111 # Define:
2112 # my $TranslationPaths = 'pattern'; # Pattern matching PATH_INFO
2114 # push(@TranslationTable, ['pattern', 'replacement']);
2115 # e.g. (for Ruby Rails):
2116 # push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2117 # push(@TranslationTable, ['%>', '</SCRIPT>']);
2119 # Runs:
2120 # my $currentRegExp;
2121 # foreach $currentRegExp (keys(%TranslationTable))
2123 # my $currentRegExp;
2124 # foreach $currentRegExp (@TranslationTable)
2126 # my ($pattern, $replacement) = @$currentRegExp;
2127 # $$text =~ s!$pattern!$replacement!msg;
2128 # };
2129 # };
2131 # Configuration section
2133 #######################################################################
2135 # The file paths on which to apply the translation
2136 my $TranslationPaths = ''; # NO files
2137 #$TranslationPaths = '.'; # ANY file
2138 # $TranslationPaths = '\.html'; # HTML files
2140 my @TranslationTable = ();
2141 # Some legacy code
2142 push(@TranslationTable, ['\<\s*CGI\s+([^\>])*\>', '\<SCRIPT TYPE=\"text/ssperl\"\>$1\<\/SCRIPT>']);
2143 # Ruby Rails?
2144 push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2145 push(@TranslationTable, ['%>', '</SCRIPT>']);
2147 sub performTranslation # (\$text)
2149 my $text = shift || return;
2150 if(@TranslationTable && $TranslationPaths && $ENV{'PATH_INFO'} =~ m!$TranslationPaths!)
2152 my $currentRegExp;
2153 foreach $currentRegExp (@TranslationTable)
2155 my ($pattern, $replacement) = @$currentRegExp;
2156 $$text =~ s!$pattern!$replacement!msg;
2161 #######################################################################
2163 # Seamless access to other (Scripting) Languages
2164 # TYPE='text/ss<interpreter>'
2166 # Configuration section
2168 #######################################################################
2170 # OTHER SCRIPTING LANGUAGES AT THE SERVER SIDE (MIME => OScommand)
2171 # Yes, it realy is this simple! (unbelievable, isn't it)
2172 # NOTE: Some interpreters require some filtering to obtain "clean" output
2174 %ScriptingLanguages = (
2175 "text/testperl" => 'perl', # Perl for testing
2176 "text/sspython" => 'python', # Python
2177 "text/ssruby" => 'ruby', # Ruby
2178 "text/sstcl" => 'tcl', # TCL
2179 "text/ssawk" => 'awk -f-', # Awk
2180 "text/sslisp" => # lisp (rep, GNU)
2181 'rep | tail +4 '."| egrep -v '> |^rep. |^nil\\\$'",
2182 "text/xlispstat" => # xlispstat
2183 'xlispstat | tail +7 ' ."| egrep -v '> \\\$|^NIL'",
2184 "text/ssprolog" => # Prolog (GNU)
2185 "gprolog | tail +4 | sed 's/^| ?- //'",
2186 "text/ssm4" => 'm4', # M4 macro's
2187 "text/sh" => 'sh', # Born shell
2188 "text/bash" => 'bash', # Born again shell
2189 "text/csh" => 'csh', # C shell
2190 "text/ksh" => 'ksh', # Korn shell
2191 "text/sspraat" => # Praat (sound/speech analysis)
2192 "praat - | sed 's/Praat > //g'",
2193 "text/ssr" => # R
2194 "R --vanilla --slave | sed 's/^[\[0-9\]*] //'",
2195 "text/ssrebol" => # REBOL
2196 "rebol --quiet|egrep -v '^[> ]* == '|sed 's/^\\s*\[> \]* //'",
2197 "text/postgresql" => 'psql 2>/dev/null',
2199 # Not real scripting, but the use of other applications
2200 "text/ssmailto" => "awk 'NF||F{F=1;print \\\$0;}'|mailto >/dev/null", # Send mail from server
2201 "text/ssdisplay" => 'cat', # Display, (interpolation)
2202 "text/sslogfile" => # Log to file, (interpolation)
2203 "awk 'NF||L {if(!L){L=tolower(\\\$1)~/^file:\\\$/ ? \\\$2 : \\\$1;}else{print \\\$0 >> L;};}'",
2205 "" => ""
2208 # To be able to access the CGI variables in your script, they
2209 # should be passed to the scripting language in a readable form
2210 # Here you can enter how they should be printed (the first %s
2211 # is replaced by the NAME of the CGI variable as it apears in the
2212 # META tag, the second by its VALUE).
2213 # For Perl this would be:
2214 # "text/testperl" => '$%s = "%s";',
2215 # which would be executed as
2216 # printf('$%s = "%s";', $CGI_NAME, $CGI_VALUE);
2218 # If the hash table value doesn't exist, nothing is done
2219 # (you have to parse the Environment variables yourself).
2220 # If it DOES exist but is empty (e.g., "text/sspraat" => '',)
2221 # Perl string interpolation of variables (i.e., $var, @array,
2222 # %hash) is performed. This means that $@%\ must be protected
2223 # with a \.
2225 %ScriptingCGIvariables = (
2226 "text/testperl" => "\$\%s = '\%s';", # Perl $VAR = 'value'; (for testing)
2227 "text/sspython" => "\%s = '\%s'", # Python VAR = 'value'
2228 "text/ssruby" => '@%s = "%s"', # Ruby @VAR = 'value'
2229 "text/sstcl" => 'set %s "%s"', # TCL set VAR "value"
2230 "text/ssawk" => '%s = "%s";', # Awk VAR = 'value';
2231 "text/sslisp" => '(setq %s "%s")', # Gnu lisp (rep) (setq VAR "value")
2232 "text/xlispstat" => '(setq %s "%s")', # xlispstat (setq VAR "value")
2233 "text/ssprolog" => '', # Gnu prolog (interpolated)
2234 "text/ssm4" => "define(`\%s', `\%s')", # M4 macro's define(`VAR', `value')
2235 "text/sh" => "\%s='\%s'", # Born shell VAR='value'
2236 "text/bash" => "\%s='\%s'", # Born again shell VAR='value'
2237 "text/csh" => "\$\%s='\%s';", # C shell $VAR = 'value';
2238 "text/ksh" => "\$\%s='\%s';", # Korn shell $VAR = 'value';
2240 "text/ssrebol" => '%s: copy "%s"', # REBOL VAR: copy "value"
2241 "text/sspraat" => '', # Praat (interpolation)
2242 "text/ssr" => '%s <- "%s";', # R VAR <- "value";
2243 "text/postgresql" => '', # PostgreSQL (interpolation)
2245 # Not real scripting, but the use of other applications
2246 "text/ssmailto" => '', # MAILTO, (interpolation)
2247 "text/ssdisplay" => '', # Display, (interpolation)
2248 "text/sslogfile" => '', # Log to file, (interpolation)
2250 "" => ""
2253 # If you want something added in front or at the back of each script
2254 # block as send to the interpreter add it here.
2255 # mime => "string", e.g., "text/sspython" => "python commands"
2256 %ScriptingPrefix = (
2257 "text/testperl" => "\# Prefix Code;", # Perl script testing
2258 "text/ssm4" => 'divert(0)', # M4 macro's (open STDOUT)
2260 "" => ""
2262 # If you want something added at the end of each script block
2263 %ScriptingPostfix = (
2264 "text/testperl" => "\# Postfix Code;", # Perl script testing
2265 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2267 "" => ""
2269 # If you need initialization code, directly after opening
2270 %ScriptingInitialization = (
2271 "text/testperl" => "\# Initialization Code;", # Perl script testing
2272 "text/ssawk" => 'BEGIN {', # Server Side awk scripts (VAR = "value")
2273 "text/sslisp" => '(prog1 nil ', # Lisp (rep)
2274 "text/xlispstat" => '(prog1 nil ', # xlispstat
2275 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2277 "" => ""
2279 # If you need cleanup code before closing
2280 %ScriptingCleanup = (
2281 "text/testperl" => "\# Cleanup Code;", # Perl script testing
2282 "text/sspraat" => 'Quit',
2283 "text/ssawk" => '};', # Server Side awk scripts (VAR = "value")
2284 "text/sslisp" => '(princ "\n" standard-output)).', # Closing print to rep
2285 "text/xlispstat" => '(print ""))', # Closing print to xlispstat
2286 "text/postgresql" => '\q', # quit psql
2287 "text/ssdisplay" => "", # close cat
2289 "" => ""
2292 # End of configuration for foreign scripting languages
2294 ###############################################################################
2296 # Initialization Code
2299 sub Initialize_Request
2301 ###############################################################################
2303 # ENVIRONMENT VARIABLES
2305 # Use environment variables to configure CGIscriptor on a temporary basis.
2306 # If you define any of the configurable variables as environment variables,
2307 # these are used instead of the "hard coded" values above.
2309 $SS_PUB = $ENV{'SS_PUB'} || $YOUR_HTML_FILES;
2310 $SS_SCRIPT = $ENV{'SS_SCRIPT'} || $YOUR_SCRIPTS;
2313 # Substitution strings, these are used internally to handle the
2314 # directory separator strings, e.g., '~/' -> 'SS_PUB:' (Mac)
2315 $HOME_SUB = $SS_PUB;
2316 $SCRIPT_SUB = $SS_SCRIPT;
2319 # Make sure all script are reliably loaded
2320 push(@INC, $SS_SCRIPT);
2323 # Add the directory separator to the "home" directories.
2324 # (This is required for ~/ and ./ substitution)
2325 $HOME_SUB .= '/' if $HOME_SUB;
2326 $SCRIPT_SUB .= '/' if $SCRIPT_SUB;
2328 $CGI_HOME = $ENV{'DOCUMENT_ROOT'};
2329 $ENV{'PATH_TRANSLATED'} =~ /$ENV{'PATH_INFO'}/is;
2330 $CGI_HOME = $` unless $ENV{'DOCUMENT_ROOT'}; # Get the DOCUMENT_ROOT directory
2331 $default_values{'CGI_HOME'} = $CGI_HOME;
2332 $ENV{'HOME'} = $CGI_HOME;
2333 # Set SS_PUB and SS_SCRIPT as Environment variables (make them available
2334 # to the scripts)
2335 $ENV{'SS_PUB'} = $SS_PUB unless $ENV{'SS_PUB'};
2336 $ENV{'SS_SCRIPT'} = $SS_SCRIPT unless $ENV{'SS_SCRIPT'};
2338 $FilePattern = $ENV{'FilePattern'} || $FilePattern;
2339 $MaximumQuerySize = $ENV{'MaximumQuerySize'} || $MaximumQuerySize;
2340 $ClientLog = $ENV{'ClientLog'} || $ClientLog;
2341 $QueryLog = $ENV{'QueryLog'} || $QueryLog;
2342 $CGI_Accept = $ENV{'CGI_Accept'} || $CGI_Accept;
2343 $CGI_Reject = $ENV{'CGI_Reject'} || $CGI_Reject;
2345 # Parse file names
2346 $CGI_Accept =~ s@^\~/@$HOME_SUB@g if $CGI_Accept;
2347 $CGI_Reject =~ s@^\~/@$HOME_SUB@g if $CGI_Reject;
2348 $ClientLog =~ s@^\~/@$HOME_SUB@g if $ClientLog;
2349 $QueryLog =~ s@^\~/@$HOME_SUB@g if $QueryLog;
2351 $CGI_Accept =~ s@^\./@$SCRIPT_SUB@g if $CGI_Accept;
2352 $CGI_Reject =~ s@^\./@$SCRIPT_SUB@g if $CGI_Reject;
2353 $ClientLog =~ s@^\./@$SCRIPT_SUB@g if $ClientLog;
2354 $QueryLog =~ s@^\./@$SCRIPT_SUB@g if $QueryLog;
2356 @CGIscriptorResults = (); # A stack of results
2358 # end of Environment variables
2360 #############################################################################
2362 # Define and Store "standard" values
2364 # BEFORE doing ANYTHING check the size of Query String
2365 length($ENV{'QUERY_STRING'}) <= $MaximumQuerySize || dieHandler(2, "QUERY TOO LONG\n");
2367 # The Translated Query String and the Actual length of the (decoded)
2368 # Query String
2369 if($ENV{'QUERY_STRING'})
2371 # If this can contain '`"-quotes, be carefull to use it QUOTED
2372 $default_values{CGI_Decoded_QS} = YOUR_CGIQUERYDECODE();
2373 $default_values{CGI_Content_Length} = length($default_values{CGI_Decoded_QS});
2376 # Get the current Date and time and store them as default variables
2378 # Get Local Time
2379 $LocalTime = localtime;
2381 # CGI_Year CGI_Month CGI_Day CGI_WeekDay CGI_Time
2382 # CGI_Hour CGI_Minutes CGI_Seconds
2384 $default_values{CGI_Date} = $LocalTime;
2385 ($default_values{CGI_WeekDay},
2386 $default_values{CGI_Month},
2387 $default_values{CGI_Day},
2388 $default_values{CGI_Time},
2389 $default_values{CGI_Year}) = split(' ', $LocalTime);
2390 ($default_values{CGI_Hour},
2391 $default_values{CGI_Minutes},
2392 $default_values{CGI_Seconds}) = split(':', $default_values{CGI_Time});
2394 # GMT:
2395 # CGI_GMTYear CGI_GMTMonth CGI_GMTDay CGI_GMTWeekDay CGI_GMTYearDay
2396 # CGI_GMTHour CGI_GMTMinutes CGI_GMTSeconds CGI_GMTisdst
2398 ($default_values{CGI_GMTSeconds},
2399 $default_values{CGI_GMTMinutes},
2400 $default_values{CGI_GMTHour},
2401 $default_values{CGI_GMTDay},
2402 $default_values{CGI_GMTMonth},
2403 $default_values{CGI_GMTYear},
2404 $default_values{CGI_GMTWeekDay},
2405 $default_values{CGI_GMTYearDay},
2406 $default_values{CGI_GMTisdst}) = gmtime;
2410 # End of Initialize Request
2412 ###################################################################
2414 # SECURITY: ACCESS CONTROL
2416 # Check the credentials of each client (use pattern matching, domain first).
2417 # This subroutine will kill-off (die) the current process whenever access
2418 # is denied.
2420 sub Access_Control
2422 # >>>>>>>>>>Start Remove
2424 # ACCEPTED CLIENTS
2426 # Only accept clients which are authorized, reject all unnamed clients
2427 # if REMOTE_HOST is given.
2428 # If file patterns are given, check whether the user is authorized for
2429 # THIS file.
2430 if($CGI_Accept)
2432 # Use local variables, REMOTE_HOST becomes '-' if undefined
2433 my $REMOTE_HOST = $ENV{REMOTE_HOST} || '-';
2434 my $REMOTE_ADDR = $ENV{REMOTE_ADDR};
2435 my $PATH_INFO = $ENV{'PATH_INFO'};
2437 open(CGI_Accept, "<$CGI_Accept") || dieHandler(3, "$CGI_Accept: $!\n");
2438 $NoAccess = 1;
2439 while(<CGI_Accept>)
2441 next unless /\S/; # Skip empty lines
2442 next if /^\s*\#/; # Skip comments
2444 # Full expressions
2445 if(/^\s*-e\s/is)
2447 my $Accept = $'; # Get the expression
2448 $NoAccess &&= eval($Accept); # evaluate the expresion
2450 else
2452 my ($Accept, @FilePatternList) = split;
2453 if($Accept eq '*' # Always match
2454 ||$REMOTE_HOST =~ /\Q$Accept\E$/is # REMOTE_HOST matches
2455 || (
2456 $Accept =~ /^[0-9\.]+$/
2457 && $REMOTE_ADDR =~ /^\Q$Accept\E/ # IP address matches
2461 if($FilePatternList[0])
2463 foreach $Pattern (@FilePatternList)
2465 # Check whether this patterns is accepted
2466 $NoAccess &&= ($PATH_INFO !~ m@\Q$Pattern\E@is);
2469 else
2471 $NoAccess = 0; # No file patterns -> Accepted
2475 # Blocked
2476 last unless $NoAccess;
2478 close(CGI_Accept);
2479 if($NoAccess){ dieHandler(4, "No Access: $PATH_INFO\n");};
2483 # REJECTED CLIENTS
2485 # Reject named clients, accept all unnamed clients
2486 if($CGI_Reject)
2488 # Use local variables, REMOTE_HOST becomes '-' if undefined
2489 my $REMOTE_HOST = $ENV{'REMOTE_HOST'} || '-';
2490 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
2491 my $PATH_INFO = $ENV{'PATH_INFO'};
2493 open(CGI_Reject, "<$CGI_Reject") || dieHandler(5, "$CGI_Reject: $!\n");
2494 $NoAccess = 0;
2495 while(<CGI_Reject>)
2497 next unless /\S/; # Skip empty lines
2498 next if /^\s*\#/; # Skip comments
2500 # Full expressions
2501 if(/^-e\s/is)
2503 my $Reject = $'; # Get the expression
2504 $NoAccess ||= eval($Reject); # evaluate the expresion
2506 else
2508 my ($Reject, @FilePatternList) = split;
2509 if($Reject eq '*' # Always match
2510 ||$REMOTE_HOST =~ /\Q$Reject\E$/is # REMOTE_HOST matches
2511 ||($Reject =~ /^[0-9\.]+$/
2512 && $REMOTE_ADDR =~ /^\Q$Reject\E/is # IP address matches
2516 if($FilePatternList[0])
2518 foreach $Pattern (@FilePatternList)
2520 $NoAccess ||= ($PATH_INFO =~ m@\Q$Pattern\E@is);
2523 else
2525 $NoAccess = 1; # No file patterns -> Rejected
2529 last if $NoAccess;
2531 close(CGI_Reject);
2532 if($NoAccess){ dieHandler(6, "Request rejected: $PATH_INFO\n");};
2535 ##########################################################<<<<<<<<<<End Remove
2538 # Get the filename
2540 # Does the filename contain any illegal characters (e.g., |, >, or <)
2541 dieHandler(7, "Illegal request: $ENV{'PATH_INFO'}\n") if $ENV{'PATH_INFO'} =~ /[^$FileAllowedChars]/;
2542 # Does the pathname contain an illegal (blocked) "directory"
2543 dieHandler(8, "Illegal request: $ENV{'PATH_INFO'}\n") if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@; # Access is blocked
2544 # Does the pathname contain a direct referencer to BinaryMapFile
2545 dieHandler(9, "Illegal request: $ENV{'PATH_INFO'}\n") if $BinaryMapFile && $ENV{'PATH_INFO'} =~ m@\Q$BinaryMapFile\E@; # Access is blocked
2547 # SECURITY: Is PATH_INFO allowed?
2548 if($FilePattern && $ENV{'PATH_INFO'} && $ENV{'PATH_INFO'} ne '-' &&
2549 ($ENV{'PATH_INFO'} !~ m@($FilePattern)$@is))
2551 # Unsupported file types can be processed by a special raw-file
2552 if($BinaryMapFile)
2554 $ENV{'CGI_BINARY_FILE'} = $ENV{'PATH_INFO'};
2555 $ENV{'PATH_INFO'} = $BinaryMapFile;
2557 else
2559 dieHandler(10, "Illegal file\n");
2565 # End of Security Access Control
2568 ############################################################################
2570 # Get the POST part of the query and add it to the QUERY_STRING.
2573 sub Get_POST_part_of_query
2576 # If POST, Read data from stdin to QUERY_STRING
2577 if($ENV{'REQUEST_METHOD'} =~ /POST/is)
2579 # SECURITY: Check size of Query String
2580 $ENV{'CONTENT_LENGTH'} <= $MaximumQuerySize || dieHandler(11, "Query too long: $ENV{'CONTENT_LENGTH'}\n"); # Query too long
2581 my $QueryRead = 0;
2582 my $SystemRead = $ENV{'CONTENT_LENGTH'};
2583 $ENV{'QUERY_STRING'} .= '&' if length($ENV{'QUERY_STRING'}) > 0;
2584 while($SystemRead > 0)
2586 $QueryRead = sysread(STDIN, $Post, $SystemRead); # Limit length
2587 $ENV{'QUERY_STRING'} .= $Post;
2588 $SystemRead -= $QueryRead;
2590 # Update decoded Query String
2591 $default_values{CGI_Decoded_QS} = YOUR_CGIQUERYDECODE();
2592 $default_values{CGI_Content_Length} =
2593 length($default_values{CGI_Decoded_QS});
2597 # End of getting POST part of query
2600 ############################################################################
2602 # Start (HTML) output and logging
2603 # (if there are irregularities, it can kill the current process)
2606 sub Initialize_output
2608 # Construct the REAL file path (except for STDIN on the command line)
2609 my $file_path = $ENV{'PATH_INFO'} ne '-' ? $SS_PUB . $ENV{'PATH_INFO'} : '-';
2610 $file_path =~ s/\?.*$//; # Remove query
2611 # This is only necessary if your server does not catch ../ directives
2612 $file_path !~ m@\.\./@ || dieHandler(12, "Illegal ../ Construct\n"); # SECURITY: Do not allow ../ constructs
2614 # Block STDIN use (-) if CGIscriptor is servicing a HTTP request
2615 if($file_path eq '-')
2617 dieHandler(13, "STDIN request in On Line system\n") if $BLOCK_STDIN_HTTP_REQUEST
2618 && ($ENV{'SERVER_SOFTWARE'}
2619 || $ENV{'SERVER_NAME'}
2620 || $ENV{'GATEWAY_INTERFACE'}
2621 || $ENV{'SERVER_PROTOCOL'}
2622 || $ENV{'SERVER_PORT'}
2623 || $ENV{'REMOTE_ADDR'}
2624 || $ENV{'HTTP_USER_AGENT'});
2629 if($ClientLog)
2631 open(ClientLog, ">>$ClientLog");
2632 print ClientLog "$LocalTime | ",
2633 ($ENV{REMOTE_USER} || "-"), " ",
2634 ($ENV{REMOTE_IDENT} || "-"), " ",
2635 ($ENV{REMOTE_HOST} || "-"), " ",
2636 $ENV{REMOTE_ADDR}, " ",
2637 $ENV{PATH_INFO}, " ",
2638 $ENV{'CGI_BINARY_FILE'}, " ",
2639 ($default_values{CGI_Content_Length} || "-"),
2640 "\n";
2641 close(ClientLog);
2643 if($QueryLog)
2645 open(QueryLog, ">>$QueryLog");
2646 print QueryLog "$LocalTime\n",
2647 ($ENV{REMOTE_USER} || "-"), " ",
2648 ($ENV{REMOTE_IDENT} || "-"), " ",
2649 ($ENV{REMOTE_HOST} || "-"), " ",
2650 $ENV{REMOTE_ADDR}, ": ",
2651 $ENV{PATH_INFO}, " ",
2652 $ENV{'CGI_BINARY_FILE'}, "\n";
2654 # Write Query to Log file
2655 print QueryLog $default_values{CGI_Decoded_QS}, "\n\n";
2656 close(QueryLog);
2659 # Return the file path
2660 return $file_path;
2663 # End of Initialize output
2666 ############################################################################
2668 # Handle login access
2670 # Access is based on a valid session ticket.
2671 # Session tickets should be dependend on user name
2672 # and IP address. The patterns of URLs for which a
2673 # session ticket is needed and the login URL are stored in
2674 # %TicketRequiredPatterns as:
2675 # 'RegEx pattern' -> 'SessionPath\tPasswordPath\tLogin URL\tExpiration'
2678 sub Log_In_Access # () -> 0 = Access Allowed, Login page if access is not allowed
2680 # No patterns, no login
2681 return 0 unless %TicketRequiredPatterns;
2683 # Get and initialize values (watch out for stuff processed by BinaryMap files)
2684 my ($SessionPath, $PasswordsPath, $Login, $valid_duration) = ("", "", "", 0);
2685 my $PATH_INFO = $ENV{'CGI_BINARY_FILE'} ? $ENV{'CGI_BINARY_FILE'} : $ENV{'PATH_INFO'};
2686 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
2688 # Get and check the tickets. Tickets are restricted to word-characters (alphanumeric+_)
2689 CGIexecute::defineCGIvariable('LOGINTICKET', "");
2690 my $LOGINTICKET = ${"CGIexecute::LOGINTICKET"};
2691 return 0 if ($LOGINTICKET && $LOGINTICKET =~ /[^\w]/isg);
2692 CGIexecute::defineCGIvariable('SESSIONTICKET', "");
2693 my $SESSIONTICKET = ${"CGIexecute::SESSIONTICKET"};
2694 return 0 if ($SESSIONTICKET && $SESSIONTICKET =~ /[^\w]/isg);
2695 # Look for a LOGOUT message
2696 my $LOGOUT = $ENV{QUERY_STRING} =~ /(^|\&)LOGOUT([\=\&]|$)/;
2698 # Username and password
2699 CGIexecute::defineCGIvariable('USERNAME', "");
2700 my $username = ${"CGIexecute::USERNAME"};
2701 return 0 if $username =~ m!^[^\w]!isg || $username =~ m![^\w \-]!isg;
2702 my $userfile = lc($username);
2703 $userfile =~ s/[^\w]/_/isg;
2704 CGIexecute::defineCGIvariable('PASSWORD', "");
2705 my $password = ${"CGIexecute::PASSWORD"};
2706 CGIexecute::defineCGIvariable('NEWPASSWORD', "");
2707 my $newpassword = ${"CGIexecute::NEWPASSWORD"};
2710 foreach my $pattern (keys(%TicketRequiredPatterns))
2712 # Check BOTH the real PATH_INFO and the CGI_BINARY_FILE variable
2713 if($ENV{'PATH_INFO'} =~ m#$pattern# || $ENV{'CGI_BINARY_FILE'} =~ m#$pattern#)
2715 # Fall through a sieve of requirements
2716 ($SessionPath, $PasswordsPath, $Login, $validtime) = split(/\t/, $TicketRequiredPatterns{$pattern});
2718 # Is there a change password request?
2719 if($newpassword && $LOGINTICKET && $SESSIONTICKET)
2721 my $tickets_removed = remove_expired_tickets($SessionPath);
2722 goto Login unless (-s "$SessionPath/$LOGINTICKET");
2723 goto Login unless (-s "$PasswordsPath/$userfile");
2724 goto Login unless (-s "$SessionPath/$SESSIONTICKET");
2725 my $ticket_valid = check_ticket_validity("SESSION", "$SessionPath/$SESSIONTICKET", $REMOTE_ADDR, $PATH_INFO);
2726 goto Login unless $ticket_valid;
2727 # Sessionticket is available to scripts
2728 $ENV{'SESSIONTICKET'} = $SESSIONTICKET;
2729 # Authorize
2730 change_password("$SessionPath/$LOGINTICKET", "$SessionPath/$SESSIONTICKET", "$PasswordsPath/$userfile", $password, $newpassword);
2731 # Ready
2732 return 0;
2734 # Is there a login ticket of this name?
2735 elsif($LOGINTICKET)
2737 my $tickets_removed = remove_expired_tickets($SessionPath);
2738 goto Login unless (-s "$SessionPath/$LOGINTICKET");
2739 goto Login unless (-s "$PasswordsPath/$userfile");
2740 my $ticket_valid = check_ticket_validity("LOGIN", "$SessionPath/$LOGINTICKET", $REMOTE_ADDR, ".");
2741 goto Login unless $ticket_valid;
2743 # Authorize
2744 $SESSIONTICKET = authorize_login("$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $password);
2745 if($SESSIONTICKET)
2747 create_session_file("$SessionPath/$SESSIONTICKET", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
2748 # Sessionticket is available to scripts
2749 $ENV{'SESSIONTICKET'} = $SESSIONTICKET;
2752 # Is there a session ticket of this name?
2753 if($SESSIONTICKET)
2755 goto Login unless (-s "$SessionPath/$SESSIONTICKET");
2756 my $ticket_valid = check_ticket_validity("SESSION", "$SessionPath/$SESSIONTICKET", $REMOTE_ADDR, $PATH_INFO);
2757 goto Login unless $ticket_valid;
2758 if(!$LOGINTICKET && $LOGOUT)
2760 unlink "$SessionPath/$SESSIONTICKET";
2761 goto Login;
2763 # Sessionticket is available to scripts
2764 $ENV{'SESSIONTICKET'} = $SESSIONTICKET;
2765 return 0;
2768 goto Login;
2769 return 0;
2772 return 0;
2774 Login:
2776 return "$YOUR_HTML_FILES/$Login";
2779 sub authorize_login # ($loginfile, $authorizationfile, $password, $SessionPath) => SESSIONTICKET First two arguments are file paths
2781 my $loginfile = shift || "";
2782 my $authorizationfile = shift || "";
2783 my $password = shift || "";
2784 my $SessionPath = shift || "";
2786 # Get Login session ticket
2787 my $loginticket = read_ticket($loginfile);
2788 # Get User credentials for authorization
2789 my $authorization = read_ticket($authorizationfile);
2791 # Get Randomsalt
2792 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
2794 return "" unless $Randomsalt;
2796 my $storedpassword = $authorization->{'Password'}->[0];
2797 return "" unless $storedpassword;
2798 # Without the "bash -c", the 'echo -n' could use sh, which does not recognize the -n option
2799 my $Hashedpassword = `bash -c 'echo -n $Randomsalt$storedpassword| $ENV{"SHASUMCMD"}'`;
2800 chomp($Hashedpassword);
2801 return "" unless $password eq $Hashedpassword;
2803 # Extract Session Ticket
2804 my $sessionticket = $loginticket->{'Session'}->[0];
2805 $sessionticket = "" if -x "$SessionPath/$sessionticket";
2807 return $sessionticket;
2810 sub change_password # ($loginfile, $sessionfile, $authorizationfile, $password, $newpassword) First two arguments are file paths
2812 my $loginfile = shift || "";
2813 my $sessionfile = shift || "";
2814 my $authorizationfile = shift || "";
2815 my $password = shift || "";
2816 my $newpassword = shift || "";
2818 # Get Login session ticket
2819 my $loginticket = read_ticket($loginfile);
2820 # Get Randomsalt
2821 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
2822 # Login ticket file has been used, remove it
2823 unlink($loginfile);
2825 return "" unless $Randomsalt;
2827 # Get session ticket
2828 my $sessionticket = read_ticket($sessionfile);
2829 # Get User credentials for authorization
2830 my $authorization = read_ticket($authorizationfile);
2831 return "" unless $authorization->{'Username'}->[0] eq $sessionticket->{'Username'}->[0];
2833 my $storedpassword = $authorization->{'Password'}->[0];
2834 # Without the "bash -c", the 'echo -n' could use sh, which does not recognize the -n option
2835 my $Hashedpassword = `bash -c 'echo -n $Randomsalt$storedpassword| $ENV{"SHASUMCMD"}'`;
2836 chomp($Hashedpassword);
2838 return "" unless $password eq $Hashedpassword;
2840 # Decrypt the $newpassword
2841 my $decryptedPassword = XOR_hex_strings($storedpassword, $newpassword);
2842 print STDERR "$decryptedPassword = XOR_hex_strings($storedpassword, $newpassword)\n";
2844 # Authorization succeeded, change password
2845 $authorization->{'Password'}->[0] = $decryptedPassword;
2847 open(USERFILE, "<$authorizationfile") || die "<$authorizationfile: $!\n";
2848 my @USERlines = <USERFILE>;
2849 close(USERFILE);
2850 # Change
2851 open(USERFILE, ">$authorizationfile") || die ">$authorizationfile: $!\n";
2852 foreach my $line (@USERlines)
2854 $line =~ s/^Password: ($storedpassword)$/Password: $decryptedPassword/ig;
2855 print USERFILE $line;
2857 close(USERFILE);
2859 return $newpassword;
2862 sub XOR_hex_strings # (hex1, hex2) -> hex
2864 my $hex1 = shift || "";
2865 my $hex2 = shift || "";
2866 my @hex1list = split('', $hex1);
2867 my @hex2list = split('', $hex2);
2868 my @hexresultlist = ();
2869 for(my $i; $i < scalar(@hex1list); ++$i)
2871 my $d1 = hex($hex1list[$i]);
2872 my $d2 = hex($hex2list[$i]);
2873 my $dresult = ($d1 ^ $d2);
2874 $hexresultlist[$i] = sprintf("%x", $dresult);
2876 $hexresult = join('', @hexresultlist);
2877 return $hexresult;
2880 sub create_session_file #($sessionfile, $loginfile, $authorizationfile, $path) -> Is $loginfile deleted? 0/1
2882 my $sessionfile = shift || "";
2883 my $loginfile = shift || "";
2884 my $authorizationfile = shift || "";
2885 my $path = shift || "";
2887 # Get Login session ticket
2888 my $loginticket = read_ticket($loginfile);
2889 # Get Authorization (user) session file
2890 my $authorization = read_ticket($authorizationfile);
2892 my @IPaddress = @{$loginticket->{'IPaddress'}};
2893 my @AllowedPaths = @{$authorization->{'AllowedPaths'}};;
2894 my @Expires = ();
2895 foreach my $pattern (keys(%TicketRequiredPatterns))
2897 if($path =~ m#$pattern#)
2899 my ($SessionPath, $PasswordsPath, $Login, $validtime) = split(/\t/, $TicketRequiredPatterns{$pattern});
2900 push(@Expires, $validtime);
2903 # Write Session Ticket
2904 open(SESSION, ">$sessionfile") || die "$sessionfile: $!\n";
2905 print SESSION "Type: SESSION\n";
2906 foreach my $address (@IPaddress)
2908 print SESSION "IPaddress: $address\n";
2910 foreach my $path (@AllowedPaths)
2912 print SESSION "AllowedPaths: $path\n";
2914 foreach my $validtime (@Expires)
2916 print SESSION "Expires: $validtime\n";
2918 print SESSION "Username: ", $authorization->{'Username'}->[0], "\n";
2919 close(SESSION);
2921 # Login file should now be removed
2922 return unlink($loginfile);
2925 sub check_ticket_validity # ($type, $ticketfile, $address, $path)
2927 my $type = shift || "SESSION";
2928 my $ticketfile = shift || "";
2929 my $address = shift || "";
2930 my $path = shift || "";
2932 # Is there a session ticket of this name?
2933 return 0 unless -s "$ticketfile";
2935 # There is a session ticket, is it linked to this IP address?
2936 my $ticket = read_ticket($ticketfile);
2938 # Is this the right type of ticket
2939 return unless $ticket->{"Type"}->[0] eq $type;
2941 # Does the IP address match?
2942 $IPmatches = 0;
2943 for my $IPpattern (@{$ticket->{"IPaddress"}})
2945 ++$IPmatches if $address =~ m#^$IPpattern#ig;
2947 return 0 unless !$ticket->{"IPaddress"} || $IPmatches;
2949 # Is the path allowed
2950 my $Pathmatches = 0;
2951 foreach my $Pathpattern (@{$ticket->{"AllowedPaths"}})
2953 ++$Pathmatches if $path =~ m#$Pathpattern#ig;
2955 return 0 unless !@{$ticket->{"AllowedPaths"}} || $Pathmatches;
2957 # Is the ticket expired?
2958 my $Expired = 0;
2959 if($ticket->{"Expires"} && @{$ticket->{"Expires"}})
2961 my $CurrentTime = time();
2962 ++$Expired if($CurrentTime > $ticket->{"Expires"}->[0]);
2964 return 0 if $Expired;
2966 # Make login values available
2967 $ENV{"LoginUsername"} = $ticket->{'Username'}->[0];
2968 $ENV{"LoginIPaddress"} = $address;
2969 $ENV{"LoginPath"} = $path;
2971 return 1;
2975 sub remove_expired_tickets # ($path) -> number of tickets removed
2977 my $path = shift || "";
2978 return 0 unless $path;
2979 $path =~ s!/+$!!g;
2980 my $removed_tickets = 0;
2981 my @ticketlist = glob("$path/*");
2982 foreach my $ticketfile (@ticketlist)
2984 my $ticket = read_ticket($ticketfile);
2985 if(@{$ticket->{'Expires'}} && $ticket->{'Expires'}->[0] < time)
2987 unlink $ticketfile;
2988 ++$removed_tickets;
2991 return $removed_tickets;
2994 sub read_ticket # ($ticketfile) -> &%ticket
2996 my $ticketfile = shift || "";
2997 my $ticket = {};
2998 if($ticketfile && -s $ticketfile)
3000 open(TICKETFILE, "<$ticketfile") || die "$ticketfile: $!\n";
3001 my @alllines = <TICKETFILE>;
3002 close(TICKETFILE);
3003 foreach my $currentline (@alllines)
3005 if($currentline =~ /^\s*(\S[^\:]+)\:\s+(.*)\s*$/)
3007 my $Label = $1;
3008 my $Value = $2;
3009 # Recalculate expire date from relative time
3010 if($Label =~ /^Expires$/ig && $Value =~ /^\+/)
3012 # Get SessionTicket file stats
3013 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)
3014 = stat("$ticketfile");
3015 if($Value =~ /^\+(\d+)\s*d(ays)?\s*$/)
3017 $ExpireTime = 24*3600*$1;
3019 elsif($Value =~ /^\+(\d+)\s*m(inutes)?\s*$/)
3021 $ExpireTime = 60*$1;
3023 elsif($Value =~ /^\+(\d+)\s*h(ours)?\s*$/)
3025 $ExpireTime = 3600*$1;
3027 elsif($Value =~ /^\+(\d+)\s*s(econds)?\s*$/)
3029 $ExpireTime = $1;
3031 elsif($Value =~ /^\+(\d+)\s*$/)
3033 $ExpireTime = $1;
3036 my $ActualExpireTime = $ExpireTime + $ctime;
3037 $Value = $ActualExpireTime;
3039 $ticket->{$Label} = () unless exists($ticket->{$Label});
3040 push(@{$ticket->{$Label}}, $Value);
3044 if(exists($ticket->{Expires}))
3046 @{$ticket->{Expires}} = sort(@{$ticket->{Expires}});
3048 return $ticket;
3051 # End of Handle login access
3054 ############################################################################
3056 # Handle foreign interpreters (i.e., scripting languages)
3058 # Insert perl code to execute scripts in foreign scripting languages.
3059 # Actually, the scripts inside the <SCRIPT></SCRIPT> blocks are piped
3060 # into an interpreter.
3061 # The code presented here is fairly confusing because it
3062 # actually writes perl code code to the output.
3064 # A table with the file handles
3065 %SCRIPTINGINPUT = ();
3067 # A function to clean up Client delivered CGI parameter values
3068 # (i.e., quote all odd characters)
3069 %SHRUBcharacterTR =
3071 "\'" => '&#39;',
3072 "\`" => '&#96;',
3073 "\"" => '&quot;',
3074 '&' => '&amper;',
3075 "\\" => '&#92;'
3078 sub shrubCGIparameter # ($String) -> Cleaned string
3080 my $String = shift || "";
3082 # Change all quotes [`'"] into HTML character entities
3083 my ($Char, $Transcript) = ('&', $SHRUBcharacterTR{'&'});
3085 # Protect &
3086 $String =~ s/\Q$Char\E/$Transcript/isg if $Transcript;
3088 while( ($Char, $Transcript) = each %SHRUBcharacterTR)
3090 next if $Char eq '&';
3091 $String =~ s/\Q$Char\E/$Transcript/isg;
3094 # Replace newlines
3095 $String =~ s/[\n]/\\n/g;
3096 # Replace control characters with their backslashed octal ordinal numbers
3097 $String =~ s/([^\S \t])/(sprintf("\\0%o", ord($1)))/eisg; #
3098 $String =~ s/([\x00-\x08\x0A-\x1F])/(sprintf("\\0%o", ord($1)))/eisg; #
3100 return $String;
3104 # The initial open statements: Open a pipe to the foreign script interpreter
3105 sub OpenForeignScript # ($ContentType) -> $DirectivePrefix
3107 my $ContentType = lc(shift) || return "";
3108 my $NewDirective = "";
3110 return $NewDirective if($SCRIPTINGINPUT{$ContentType});
3112 # Construct a unique file handle name
3113 $SCRIPTINGFILEHANDLE = uc($ContentType);
3114 $SCRIPTINGFILEHANDLE =~ s/\W/\_/isg;
3115 $SCRIPTINGINPUT{$ContentType} = $SCRIPTINGFILEHANDLE
3116 unless $SCRIPTINGINPUT{$ContentType};
3118 # Create the relevant script: Open the pipe to the interpreter
3119 $NewDirective .= <<"BLOCKCGISCRIPTOROPEN";
3120 # Open interpreter for '$ContentType'
3121 # Open pipe to interpreter (if it isn't open already)
3122 open($SCRIPTINGINPUT{$ContentType}, "|$ScriptingLanguages{$ContentType}") || main::dieHandler(14, "$ContentType: \$!\\n");
3123 BLOCKCGISCRIPTOROPEN
3125 # Insert Initialization code and CGI variables
3126 $NewDirective .= InitializeForeignScript($ContentType);
3128 # Ready
3129 return $NewDirective;
3133 # The final closing code to stop the interpreter
3134 sub CloseForeignScript # ($ContentType) -> $DirectivePrefix
3136 my $ContentType = lc(shift) || return "";
3137 my $NewDirective = "";
3139 # Do nothing unless the pipe realy IS open
3140 return "" unless $SCRIPTINGINPUT{$ContentType};
3142 # Initial comment
3143 $NewDirective .= "\# Close interpreter for '$ContentType'\n";
3146 # Write the Postfix code
3147 $NewDirective .= CleanupForeignScript($ContentType);
3149 # Create the relevant script: Close the pipe to the interpreter
3150 $NewDirective .= <<"BLOCKCGISCRIPTORCLOSE";
3151 close($SCRIPTINGINPUT{$ContentType}) || main::dieHandler(15, \"$ContentType: \$!\\n\");
3152 select(STDOUT); \$|=1;
3154 BLOCKCGISCRIPTORCLOSE
3156 # Remove the file handler of the foreign script
3157 delete($SCRIPTINGINPUT{$ContentType});
3159 return $NewDirective;
3163 # The initialization code for the foreign script interpreter
3164 sub InitializeForeignScript # ($ContentType) -> $DirectivePrefix
3166 my $ContentType = lc(shift) || return "";
3167 my $NewDirective = "";
3169 # Add initialization code
3170 if($ScriptingInitialization{$ContentType})
3172 $NewDirective .= <<"BLOCKCGISCRIPTORINIT";
3173 # Initialization Code for '$ContentType'
3174 # Select relevant output filehandle
3175 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
3177 # The Initialization code (if any)
3178 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}INITIALIZATIONCODE';
3179 $ScriptingInitialization{$ContentType}
3180 ${ContentType}INITIALIZATIONCODE
3182 BLOCKCGISCRIPTORINIT
3185 # Add all CGI variables defined
3186 if(exists($ScriptingCGIvariables{$ContentType}))
3188 # Start writing variable definitions to the Interpreter
3189 if($ScriptingCGIvariables{$ContentType})
3191 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEF";
3192 # CGI variables (from the %default_values table)
3193 print $SCRIPTINGINPUT{$ContentType} << '${ContentType}CGIVARIABLES';
3194 BLOCKCGISCRIPTORVARDEF
3197 my ($N, $V);
3198 foreach $N (keys(%default_values))
3200 # Determine whether the parameter has been defined
3201 # (the eval is a workaround to get at the variable value)
3202 next unless eval("defined(\$CGIexecute::$N)");
3204 # Get the value from the EXECUTION environment
3205 $V = eval("\$CGIexecute::$N");
3206 # protect control characters (i.e., convert them to \0.. form)
3207 $V = shrubCGIparameter($V);
3209 # Protect interpolated variables
3210 eval("\$CGIexecute::$N = '$V';") unless $ScriptingCGIvariables{$ContentType};
3212 # Print the actual declaration for this scripting language
3213 if($ScriptingCGIvariables{$ContentType})
3215 $NewDirective .= sprintf($ScriptingCGIvariables{$ContentType}, $N, $V);
3216 $NewDirective .= "\n";
3220 # Stop writing variable definitions to the Interpreter
3221 if($ScriptingCGIvariables{$ContentType})
3223 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEFEND";
3224 ${ContentType}CGIVARIABLES
3225 BLOCKCGISCRIPTORVARDEFEND
3230 $NewDirective .= << "BLOCKCGISCRIPTOREND";
3232 # Select STDOUT filehandle
3233 select(STDOUT); \$|=1;
3235 BLOCKCGISCRIPTOREND
3237 return $NewDirective;
3241 # The cleanup code for the foreign script interpreter
3242 sub CleanupForeignScript # ($ContentType) -> $DirectivePrefix
3244 my $ContentType = lc(shift) || return "";
3245 my $NewDirective = "";
3247 # Return if not needed
3248 return $NewDirective unless $ScriptingCleanup{$ContentType};
3250 # Create the relevant script: Open the pipe to the interpreter
3251 $NewDirective .= <<"BLOCKCGISCRIPTORSTOP";
3252 # Cleanup Code for '$ContentType'
3253 # Select relevant output filehandle
3254 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
3255 # Print Cleanup code to foreign script
3256 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}SCRIPTSTOP';
3257 $ScriptingCleanup{$ContentType}
3258 ${ContentType}SCRIPTSTOP
3260 # Select STDOUT filehandle
3261 select(STDOUT); \$|=1;
3262 BLOCKCGISCRIPTORSTOP
3264 return $NewDirective;
3268 # The prefix code for each <script></script> block
3269 sub PrefixForeignScript # ($ContentType) -> $DirectivePrefix
3271 my $ContentType = lc(shift) || return "";
3272 my $NewDirective = "";
3274 # Return if not needed
3275 return $NewDirective unless $ScriptingPrefix{$ContentType};
3277 my $Quote = "\'";
3278 # If the CGIvariables parameter is defined, but empty, interpolate
3279 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
3280 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
3281 !$ScriptingCGIvariables{$ContentType};
3283 # Add initialization code
3284 $NewDirective .= <<"BLOCKCGISCRIPTORPREFIX";
3285 # Prefix Code for '$ContentType'
3286 # Select relevant output filehandle
3287 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
3289 # The block Prefix code (if any)
3290 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}PREFIXCODE$Quote;
3291 $ScriptingPrefix{$ContentType}
3292 ${ContentType}PREFIXCODE
3293 # Select STDOUT filehandle
3294 select(STDOUT); \$|=1;
3295 BLOCKCGISCRIPTORPREFIX
3297 return $NewDirective;
3301 # The postfix code for each <script></script> block
3302 sub PostfixForeignScript # ($ContentType) -> $DirectivePrefix
3304 my $ContentType = lc(shift) || return "";
3305 my $NewDirective = "";
3307 # Return if not needed
3308 return $NewDirective unless $ScriptingPostfix{$ContentType};
3310 my $Quote = "\'";
3311 # If the CGIvariables parameter is defined, but empty, interpolate
3312 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
3313 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
3314 !$ScriptingCGIvariables{$ContentType};
3316 # Create the relevant script: Open the pipe to the interpreter
3317 $NewDirective .= <<"BLOCKCGISCRIPTORPOSTFIX";
3318 # Postfix Code for '$ContentType'
3319 # Select filehandle to interpreter
3320 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
3321 # Print postfix code to foreign script
3322 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SCRIPTPOSTFIX$Quote;
3323 $ScriptingPostfix{$ContentType}
3324 ${ContentType}SCRIPTPOSTFIX
3325 # Select STDOUT filehandle
3326 select(STDOUT); \$|=1;
3327 BLOCKCGISCRIPTORPOSTFIX
3329 return $NewDirective;
3332 sub InsertForeignScript # ($ContentType, $directive, @SRCfile) -> $NewDirective
3334 my $ContentType = lc(shift) || return "";
3335 my $directive = shift || return "";
3336 my @SRCfile = @_;
3337 my $NewDirective = "";
3339 my $Quote = "\'";
3340 # If the CGIvariables parameter is defined, but empty, interpolate
3341 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
3342 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
3343 !$ScriptingCGIvariables{$ContentType};
3345 # Create the relevant script
3346 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
3347 # Insert Code for '$ContentType'
3348 # Select filehandle to interpreter
3349 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
3350 BLOCKCGISCRIPTORINSERT
3352 # Use SRC feature files
3353 my $ThisSRCfile;
3354 while($ThisSRCfile = shift(@_))
3356 # Handle blocks
3357 if($ThisSRCfile =~ /^\s*\{\s*/)
3359 my $Block = $';
3360 $Block = $` if $Block =~ /\s*\}\s*$/;
3361 $NewDirective .= <<"BLOCKCGISCRIPTORSRCBLOCK";
3362 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SRCBLOCKCODE$Quote;
3363 $Block
3364 ${ContentType}SRCBLOCKCODE
3365 BLOCKCGISCRIPTORSRCBLOCK
3367 next;
3370 # Handle files
3371 $NewDirective .= <<"BLOCKCGISCRIPTORSRCFILES";
3372 # Read $ThisSRCfile
3373 open(SCRIPTINGSOURCE, "<$ThisSRCfile") || main::dieHandler(16, "$ThisSRCfILE: \$!");
3374 while(<SCRIPTINGSOURCE>)
3376 print $SCRIPTINGINPUT{$ContentType} \$_;
3378 close(SCRIPTINGSOURCE);
3380 BLOCKCGISCRIPTORSRCFILES
3384 # Add the directive
3385 if($directive)
3387 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
3388 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}DIRECTIVECODE$Quote;
3389 $directive
3390 ${ContentType}DIRECTIVECODE
3391 BLOCKCGISCRIPTORINSERT
3395 $NewDirective .= <<"BLOCKCGISCRIPTORSELECT";
3396 # Select STDOUT filehandle
3397 select(STDOUT); \$|=1;
3398 BLOCKCGISCRIPTORSELECT
3400 # Ready
3401 return $NewDirective;
3404 sub CloseAllForeignScripts # Call CloseForeignScript on all open scripts
3406 my $ContentType;
3407 foreach $ContentType (keys(%SCRIPTINGINPUT))
3409 my $directive = CloseForeignScript($ContentType);
3410 print STDERR "\nDirective $CGI_Date: ", $directive;
3411 CGIexecute->evaluate($directive);
3416 # End of handling foreign (external) scripting languages.
3418 ############################################################################
3420 # A subroutine to handle "nested" quotes, it cuts off the leading
3421 # item or quoted substring
3422 # E.g.,
3423 # ' A_word and more words' -> @('A_word', ' and more words')
3424 # '"quoted string" The rest' -> @('quoted string', ' The rest')
3425 # (this is needed for parsing the <TAGS> and their attributes)
3426 my $SupportedQuotes = "\'\"\`\(\{\[";
3427 my %QuotePairs = ('('=>')','['=>']','{'=>'}'); # Brackets
3428 sub ExtractQuotedItem # ($String) -> @($QuotedString, $RestOfString)
3430 my @Result = ();
3431 my $String = shift || return @Result;
3433 if($String =~ /^\s*([\w\/\-\.]+)/is)
3435 push(@Result, $1, $');
3437 elsif($String =~ /^\s*(\\?)([\Q$SupportedQuotes\E])/is)
3439 my $BackSlash = $1 || "";
3440 my $OpenQuote = $2;
3441 my $CloseQuote = $OpenQuote;
3442 $CloseQuote = $QuotePairs{$OpenQuote} if $QuotePairs{$OpenQuote};
3444 if($BackSlash)
3446 $String =~ /^\s*\\\Q$OpenQuote\E/i;
3447 my $Onset = $';
3448 $Onset =~ /\\\Q$CloseQuote\E/i;
3449 my $Rest = $';
3450 my $Item = $`;
3451 push(@Result, $Item, $Rest);
3454 else
3456 $String =~ /^\s*\Q$OpenQuote\E([^\Q$CloseQuote\E]*)\Q$CloseQuote\E/i;
3457 push(@Result, $1, $');
3460 else
3462 push(@Result, "", $String);
3464 return @Result;
3467 # Now, start with the real work
3469 # Control the output of the Content-type: text/html\n\n message
3470 my $SupressContentType = 0;
3472 # Process a file
3473 sub ProcessFile # ($file_path)
3475 my $file_path = shift || return 0;
3478 # Generate a unique file handle (for recursions)
3479 my @SRClist = ();
3480 my $FileHandle = "file";
3481 my $n = 0;
3482 while(!eof($FileHandle.$n)) {++$n;};
3483 $FileHandle .= $n;
3485 # Start HTML output
3486 # Use the default Content-type if this is NOT a raw file
3487 unless(($RawFilePattern && $ENV{'PATH_INFO'} =~ m@($RawFilePattern)$@i)
3488 || $SupressContentType)
3490 $ENV{'PATH_INFO'} =~ m@($FilePattern)$@i;
3491 my $ContentType = $ContentTypeTable{$1};
3492 print "Content-type: $ContentType\n";
3493 print "\n";
3494 $SupressContentType = 1; # Content type has been printed
3498 # Get access to the actual data. This can be from RAM (by way of an
3499 # environment variable) or by opening a file.
3501 # Handle the use of RAM images (file-data is stored in the
3502 # $CGI_FILE_CONTENTS environment variable)
3503 # Note that this environment variable will be cleared, i.e., it is strictly for
3504 # single-use only!
3505 if($ENV{$CGI_FILE_CONTENTS})
3507 # File has been read already
3508 $_ = $ENV{$CGI_FILE_CONTENTS};
3509 # Sorry, you have to do the reading yourself (dynamic document creation?)
3510 # NOTE: you must read the whole document at once
3511 if($_ eq '-')
3513 $_ = eval("\@_=('$file_path'); do{$ENV{$CGI_DATA_ACCESS_CODE}}");
3515 else # Clear environment variable
3517 $ENV{$CGI_FILE_CONTENTS} = '-';
3520 # Open Only PLAIN TEXT files (or STDIN) and NO executable files (i.e., scripts).
3521 # THIS IS A SECURITY FEATURE!
3522 elsif($file_path eq '-' || (-e "$file_path" && -r _ && -T _ && -f _ && ! (-x _ || -X _) ))
3524 open($FileHandle, $file_path) || dieHandler(17, "<h2>File not found</h2>\n");
3525 push(@OpenFiles, $file_path);
3526 $_ = <$FileHandle>; # Read first line
3528 else
3530 print "<h2>File not found</h2>\n";
3531 dieHandler(18, "$file_path\n");
3534 $| = 1; # Flush output buffers
3536 # Initialize variables
3537 my $METAarguments = ""; # The CGI arguments from the latest META tag
3538 my @METAvalues = (); # The ''-quoted CGI values from the latest META tag
3539 my $ClosedTag = 0; # <TAG> </TAG> versus <TAG/>
3542 # Send document to output
3543 # Process the requested document.
3544 # Do a loop BEFORE reading input again (this catches the RAM/Database
3545 # type of documents).
3546 do {
3549 # Handle translations if needed
3551 performTranslation(\$_) if $TranslationPaths;
3553 # Catch <SCRIPT LANGUAGE="PERL" TYPE="text/ssperl" > directives in $_
3554 # There can be more than 1 <SCRIPT> or META tags on a line
3555 while(/\<\s*(SCRIPT|META|DIV|INS)\s/is)
3557 my $directive = "";
3558 # Store rest of line
3559 my $Before = $`;
3560 my $ScriptTag = $&;
3561 my $After = $';
3562 my $TagType = uc($1);
3563 # The before part can be send to the output
3564 print $Before;
3566 # Read complete Tag from after and/or file
3567 until($After =~ /([^\\])\>/)
3569 $After .= <$FileHandle>;
3570 performTranslation(\$After) if $TranslationPaths;
3573 if($After =~ /([^\\])\>/)
3575 $ScriptTag .= $`.$&; # Keep the Script Tag intact
3576 $After = $';
3578 else
3580 dieHandler(19, "Closing > not found\n");
3583 # The tag could be closed by />, we handle this in the XML way
3584 # and don't process any content (we ignore whitespace)
3585 $ClosedTag = ($ScriptTag =~ m@[^\\]/\s*\>\s*$@) ? 1 : 0;
3588 # TYPE or CLASS?
3589 my $TypeName = ($TagType =~ /META/is) ? "CONTENT" : "TYPE";
3590 $TypeName = "CLASS" if $TagType eq 'DIV' || $TagType eq 'INS';
3592 # Parse <SCRIPT> or <META> directive
3593 # If NOT (TYPE|CONTENT)="text/ssperl" (i.e., $ServerScriptContentType),
3594 # send the line to the output and go to the next loop
3595 my $CurrentContentType = "";
3596 if($ScriptTag =~ /(^|\s)$TypeName\s*=\s*/is)
3598 my ($Type) = ExtractQuotedItem($');
3599 $Type =~ /^\s*([\w\/\-]+)\s*[\,\;]?/;
3600 $CurrentContentType = lc($1); # Note: mime-types are "case-less"
3601 # CSS classes are aliases of $ServerScriptContentType
3602 if($TypeName eq "CLASS" && $CurrentContentType eq $ServerScriptContentClass)
3604 $CurrentContentType = $ServerScriptContentType;
3609 # Not a known server-side content type, print and continue
3610 unless(($CurrentContentType =~
3611 /$ServerScriptContentType|$ShellScriptContentType/is) ||
3612 $ScriptingLanguages{$CurrentContentType})
3614 print $ScriptTag;
3615 $_ = $After;
3616 next;
3620 # A known server-side content type, evaluate
3622 # First, handle \> and \<
3623 $ScriptTag =~ s/\\\>/\>/isg;
3624 $ScriptTag =~ s/\\\</\</isg;
3626 # Extract the CGI, SRC, ID, IF and UNLESS attributes
3627 my %ScriptTagAttributes = ();
3628 while($ScriptTag =~ /(^|\s)(CGI|IF|UNLESS|SRC|ID)\s*=\s*/is)
3630 my $Attribute = $2;
3631 my $Rest = $';
3632 my $Value = "";
3633 ($Value, $ScriptTag) = ExtractQuotedItem($Rest);
3634 $ScriptTagAttributes{uc($Attribute)} = $Value;
3638 # The attribute used to define the CGI variables
3639 # Extract CGI-variables from
3640 # <META CONTENT="text/ssperl; CGI='' SRC=''">
3641 # <SCRIPT TYPE='text/ssperl' CGI='' SRC=''>
3642 # <DIV CLASS='ssperl' CGI='' SRC='' ID=""> tags
3643 # <INS CLASS='ssperl' CGI='' SRC='' ID=""> tags
3644 if($ScriptTagAttributes{'CGI'})
3646 @ARGV = (); # Reset ARGV
3647 $ARGC = 0;
3648 $METAarguments = ""; # Reset the META CGI arguments
3649 @METAvalues = ();
3650 my $Meta_CGI = $ScriptTagAttributes{'CGI'};
3652 # Process default values of variables ($<name> = 'default value')
3653 # Allowed quotes are '', "", ``, (), [], and {}
3654 while($Meta_CGI =~ /(^\s*|[^\\])([\$\@\%]?)([\w\-]+)\s*/is)
3656 my $varType = $2 || '$'; # Variable or list
3657 my $name = $3; # The Name
3658 my $default = "";
3659 $Meta_CGI = $';
3661 if($Meta_CGI =~ /^\s*\=\s*/is)
3663 # Locate (any) default value
3664 ($default, $Meta_CGI) = ExtractQuotedItem($'); # Cut the parameter from the CGI
3666 $RemainingTag = $Meta_CGI;
3669 # Define CGI (or ENV) variable, initalize it from the
3670 # Query string or the default value
3672 # Also construct the @ARGV and @_ arrays. This allows other (SRC=) Perl
3673 # scripts to access the CGI arguments defined in the META tag
3674 # (Not for CGI inside <SCRIPT> tags)
3675 if($varType eq '$')
3677 CGIexecute::defineCGIvariable($name, $default)
3678 || dieHandler(20, "INVALID CGI name/value pair ($name, $default)\n");
3679 push(@METAvalues, "'".${"CGIexecute::$name"}."'");
3680 # Add value to the @ARGV list
3681 push(@ARGV, ${"CGIexecute::$name"});
3682 ++$ARGC;
3684 elsif($varType eq '@')
3686 CGIexecute::defineCGIvariableList($name, $default)
3687 || dieHandler(21, "INVALID CGI name/value list pair ($name, $default)\n");
3688 push(@METAvalues, "'".join("'", @{"CGIexecute::$name"})."'");
3689 # Add value to the @ARGV list
3690 push(@ARGV, @{"CGIexecute::$name"});
3691 $ARGC = scalar(@CGIexecute::ARGV);
3693 elsif($varType eq '%')
3695 CGIexecute::defineCGIvariableHash($name, $default)
3696 || dieHandler(22, "INVALID CGI name/value hash pair ($name, $default)\n");
3697 my @PairList = map {"$_ => ".${"CGIexecute::$name"}{$_}} keys(%{"CGIexecute::$name"});
3698 push(@METAvalues, "'".join("'", @PairList)."'");
3699 # Add value to the @ARGV list
3700 push(@ARGV, %{"CGIexecute::$name"});
3701 $ARGC = scalar(@CGIexecute::ARGV);
3704 # Store the values for internal and later use
3705 $METAarguments .= "$varType".$name.","; # A string of CGI variable names
3707 push(@METAvalues, "\'".eval("\"$varType\{CGIexecute::$name\}\"")."\'"); # ALWAYS add '-quotes around values
3712 # The IF (conditional execution) Attribute
3713 # Evaluate the condition and stop unless it evaluates to true
3714 if($ScriptTagAttributes{'IF'})
3716 my $IFcondition = $ScriptTagAttributes{'IF'};
3718 # Convert SCRIPT calls, ./<script>
3719 $IFcondition =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
3721 # Convert FILE calls, ~/<file>
3722 $IFcondition =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
3724 # Block execution if necessary
3725 unless(CGIexecute->evaluate($IFcondition))
3727 %ScriptTagAttributes = ();
3728 $CurrentContentType = "";
3732 # The UNLESS (conditional execution) Attribute
3733 # Evaluate the condition and stop if it evaluates to true
3734 if($ScriptTagAttributes{'UNLESS'})
3736 my $UNLESScondition = $ScriptTagAttributes{'UNLESS'};
3738 # Convert SCRIPT calls, ./<script>
3739 $UNLESScondition =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
3741 # Convert FILE calls, ~/<file>
3742 $UNLESScondition =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
3744 # Block execution if necessary
3745 if(CGIexecute->evaluate($UNLESScondition))
3747 %ScriptTagAttributes = ();
3748 $CurrentContentType = "";
3752 # The SRC (Source File) Attribute
3753 # Extract any source script files and add them in
3754 # front of the directive
3755 # The SRC list should be emptied
3756 @SRClist = ();
3757 my $SRCtag = "";
3758 my $Prefix = 1;
3759 my $PrefixDirective = "";
3760 my $PostfixDirective = "";
3761 # There is a SRC attribute
3762 if($ScriptTagAttributes{'SRC'})
3764 $SRCtag = $ScriptTagAttributes{'SRC'};
3765 # Remove "file://" prefixes
3766 $SRCtag =~ s@([^\w\/\\]|^)file\://([^\s\/\@\=])@$1$2@gis;
3767 # Expand script filenames "./Script"
3768 $SRCtag =~ s@([^\w\/\\]|^)\./([^\s\/\@\=])@$1$SCRIPT_SUB/$2@gis;
3769 # Expand script filenames "~/Script"
3770 $SRCtag =~ s@([^\w\/\\]|^)\~/([^\s\/\@\=])@$1$HOME_SUB/$2@gis;
3773 # File source tags
3774 while($SRCtag =~ /\S/is)
3776 my $SRCdirective = "";
3778 # Pseudo file, just a switch to go from PREFIXING to POSTFIXING
3779 # SRC files
3780 if($SRCtag =~ /^[\s\;\,]*(POSTFIX|PREFIX)([^$FileAllowedChars]|$)/is)
3782 my $InsertionPlace = $1;
3783 $SRCtag = $2.$';
3785 $Prefix = $InsertionPlace =~ /POSTFIX/i ? 0 : 1;
3786 # Go to next round
3787 next;
3789 # {}-blocks are just evaluated by "do"
3790 elsif($SRCtag =~ /^[\s\;\,]*\{/is)
3792 my $SRCblock = $';
3793 if($SRCblock =~ /\}[\s\;\,]*([^\}]*)$/is)
3795 $SRCblock = $`;
3796 $SRCtag = $1.$';
3797 # SAFEqx shell script blocks
3798 if($CurrentContentType =~ /$ShellScriptContentType/is)
3800 # Handle ''-quotes inside the script
3801 $SRCblock =~ s/[\']/\\$&/gis;
3803 $SRCblock = "print do { SAFEqx(\'".$SRCblock."\'); };'';";
3804 $SRCdirective .= $SRCblock."\n";
3806 # do { SRCblocks }
3807 elsif($CurrentContentType =~ /$ServerScriptContentType/is)
3809 $SRCblock = "print do { $SRCblock };'';";
3810 $SRCdirective .= $SRCblock."\n";
3812 else # The interpreter should handle this
3814 push(@SRClist, "{ $SRCblock }");
3818 else
3819 { dieHandler(23, "Closing \} missing\n");};
3821 # Files are processed as Text or Executable files
3822 elsif($SRCtag =~ /[\s\;\,]*([$FileAllowedChars]+)[\;\,\s]*/is)
3824 my $SrcFile = $1;
3825 $SRCtag = $';
3827 # We are handling one of the external interpreters
3828 if($ScriptingLanguages{$CurrentContentType})
3830 push(@SRClist, $SrcFile);
3832 # We are at the start of a DIV tag, just load all SRC files and/or URL's
3833 elsif($TagType eq 'DIV' || $TagType eq 'INS') # All files are prepended in DIV's
3835 # $SrcFile is a URL pointing to an HTTP or FTP server
3836 if($SrcFile =~ m!^([a-z]+)\://!)
3838 my $URLoutput = CGIscriptor::read_url($SrcFile);
3839 $SRCdirective .= $URLoutput;
3841 # SRC file is an existing file
3842 elsif(-e "$SrcFile")
3844 open(DIVSOURCE, "<$SrcFile") || dieHandler(24, "<$SrcFile: $!\n");
3845 my $Content;
3846 while(sysread(DIVSOURCE, $Content, 1024) > 0)
3848 $SRCdirective .= $Content;
3850 close(DIVSOURCE);
3853 # Executable files are executed as
3854 # `$SrcFile 'ARGV[0]' 'ARGV[1]'`
3855 elsif(-x "$SrcFile")
3857 $SRCdirective .= "print \`$SrcFile @METAvalues\`;'';\n";
3859 # Handle 'standard' files, using ProcessFile
3860 elsif((-T "$SrcFile" || $ENV{$CGI_FILE_CONTENTS})
3861 && $SrcFile =~ m@($FilePattern)$@) # A recursion
3864 # Do not process still open files because it can lead
3865 # to endless recursions
3866 if(grep(/^$SrcFile$/, @OpenFiles))
3867 { dieHandler(25, "$SrcFile allready opened (endless recursion)\n")};
3868 # Prepare meta arguments
3869 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
3870 # Process the file
3871 $SRCdirective .= "main::ProcessFile(\'$SrcFile\');'';\n";
3873 elsif($SrcFile =~ m!^([a-z]+)\://!) # URL's are loaded and printed
3875 $SRCdirective .= GET_URL($SrcFile);
3877 elsif(-T "$SrcFile") # Textfiles are "do"-ed (Perl execution)
3879 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
3880 $SRCdirective .= "do \'$SrcFile\';'';\n";
3882 else # This one could not be resolved (should be handled by BinaryMapFile)
3884 $SRCdirective .= 'print "'.$SrcFile.' cannot be used"'."\n";
3889 # Postfix or Prefix
3890 if($Prefix)
3892 $PrefixDirective .= $SRCdirective;
3894 else
3896 $PostfixDirective .= $SRCdirective;
3899 # The prefix should be handled immediately
3900 $directive .= $PrefixDirective;
3901 $PrefixDirective = "";
3905 # Handle the content of the <SCRIPT></SCRIPT> tags
3906 # Do not process the content of <SCRIPT/>
3907 if($TagType =~ /SCRIPT/is && !$ClosedTag) # The <SCRIPT> TAG
3909 my $EndScriptTag = "";
3911 # Execute SHELL scripts with SAFEqx()
3912 if($CurrentContentType =~ /$ShellScriptContentType/is)
3914 $directive .= "SAFEqx(\'";
3917 # Extract Program
3918 while($After !~ /\<\s*\/SCRIPT[^\>]*\>/is && !eof($FileHandle))
3920 $After .= <$FileHandle>;
3921 performTranslation(\$After) if $TranslationPaths;
3924 if($After =~ /\<\s*\/SCRIPT[^\>]*\>/is)
3926 $directive .= $`;
3927 $EndScriptTag = $&;
3928 $After = $';
3930 else
3932 dieHandler(26, "Missing </SCRIPT> end tag in $ENV{'PATH_INFO'}\n");
3935 # Process only when content should be executed
3936 if($CurrentContentType)
3939 # Remove all comments from Perl scripts
3940 # (NOT from OS shell scripts)
3941 $directive =~ s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/$1/g
3942 if $CurrentContentType =~ /$ServerScriptContentType/i;
3944 # Convert SCRIPT calls, ./<script>
3945 $directive =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
3947 # Convert FILE calls, ~/<file>
3948 $directive =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
3950 # Execute SHELL scripts with SAFEqx(), closing bracket
3951 if($CurrentContentType =~ /$ShellScriptContentType/i)
3953 # Handle ''-quotes inside the script
3954 $directive =~ /SAFEqx\(\'/;
3955 $directive = $`.$&;
3956 my $Executable = $';
3957 $Executable =~ s/[\']/\\$&/gs;
3959 $directive .= $Executable."\');"; # Closing bracket
3962 else
3964 $directive = "";
3967 # Handle the content of the <DIV></DIV> tags
3968 # Do not process the content of <DIV/>
3969 elsif(($TagType eq 'DIV' || $TagType eq 'INS') && !$ClosedTag) # The <DIV> TAGs
3971 my $EndScriptTag = "";
3973 # Extract Text
3974 while($After !~ /\<\s*\/$TagType[^\>]*\>/is && !eof($FileHandle))
3976 $After .= <$FileHandle>;
3977 performTranslation(\$After) if $TranslationPaths;
3980 if($After =~ /\<\s*\/$TagType[^\>]*\>/is)
3982 $directive .= $`;
3983 $EndScriptTag = $&;
3984 $After = $';
3986 else
3988 dieHandler(27, "Missing </$TagType> end tag in $ENV{'PATH_INFO'}\n");
3991 # Add the Postfixed directives (but only when it contains something printable)
3992 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
3993 $PostfixDirective = "";
3996 # Process only when content should be handled
3997 if($CurrentContentType)
4000 # Get the name (ID), and clean it (i.e., remove anything that is NOT part of
4001 # a valid Perl name). Names should not contain $, but we can handle it.
4002 my $name = $ScriptTagAttributes{'ID'};
4003 $name =~ /^\s*[\$\@\%]?([\w\-]+)/;
4004 $name = $1;
4006 # Assign DIV contents to $NAME value OUTSIDE the CGI values!
4007 CGIexecute::defineCGIexecuteVariable($name, $directive);
4008 $directive = "";
4011 # Nothing to execute
4012 $directive = "";
4016 # Handle Foreign scripting languages
4017 if($ScriptingLanguages{$CurrentContentType})
4019 my $newDirective = "";
4020 $newDirective .= OpenForeignScript($CurrentContentType); # Only if not already done
4021 $newDirective .= PrefixForeignScript($CurrentContentType);
4022 $newDirective .= InsertForeignScript($CurrentContentType, $directive, @SRClist);
4023 $newDirective .= PostfixForeignScript($CurrentContentType);
4024 $newDirective .= CloseForeignScript($CurrentContentType); # This shouldn't be necessary
4026 $newDirective .= '"";';
4028 $directive = $newDirective;
4032 # Add the Postfixed directives (but only when it contains something printable)
4033 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
4034 $PostfixDirective = "";
4037 # EXECUTE the script and print the results
4039 # Use this to debug the program
4040 # print STDERR "Directive $CGI_Date: \n", $directive, "\n\n";
4042 my $Result = CGIexecute->evaluate($directive) if $directive; # Evaluate as PERL code
4043 $Result =~ s/\n$//g; # Remove final newline
4045 # Print the Result of evaluating the directive
4046 # (this will handle LARGE, >64 kB output)
4047 my $BytesWritten = 1;
4048 while($Result && $BytesWritten)
4050 $BytesWritten = syswrite(STDOUT, $Result, 64);
4051 $Result = substr($Result, $BytesWritten);
4053 # print $Result; # Could be used instead of above code
4055 # Store result if wanted, i.e., if $CGIscriptorResults has been
4056 # defined in a <META> tag.
4057 push(@CGIexecute::CGIscriptorResults, $Result)
4058 if exists($default_values{'CGIscriptorResults'});
4060 # Process the rest of the input line (this could contain
4061 # another directive)
4062 $_ = $After;
4064 print $_;
4065 } while(<$FileHandle>); # Read and Test AFTER first loop!
4067 close ($FileHandle);
4068 dieHandler(28, "Error in recursion\n") unless pop(@OpenFiles) == $file_path;
4072 ###############################################################################
4074 # Call the whole package
4076 sub Handle_Request
4078 my $file_path = "";
4080 # Initialization Code
4081 Initialize_Request();
4083 # SECURITY: ACCESS CONTROL
4084 Access_Control();
4086 # Read the POST part of the query, if there is one
4087 Get_POST_part_of_query();
4089 # Start (HTML) output and logging
4090 $file_path = Initialize_output();
4092 # Check login access or divert to login procedure
4093 $Use_Login = Log_In_Access();
4094 $file_path = $Use_Login if $Use_Login;
4096 # Record which files are still open (to avoid endless recursions)
4097 my @OpenFiles = ();
4099 # Record whether the default HTML ContentType has already been printed
4100 # but only if the SERVER uses HTTP or some other protocol that might interpret
4101 # a content MIME type.
4103 $SupressContentType = !("$ENV{'SERVER_PROTOCOL'}" =~ /($ContentTypeServerProtocols)/i);
4105 # Process the specified file
4106 ProcessFile($file_path) if $file_path ne $SS_PUB;
4108 # Cleanup all open external (foreign) interpreters
4109 CloseAllForeignScripts();
4112 "" # SUCCESS
4115 # Make a single call to handle an (empty) request
4116 Handle_Request();
4119 # END OF PACKAGE MAIN
4122 ####################################################################################
4124 # The CGIEXECUTE PACKAGE
4126 ####################################################################################
4128 # Isolate the evaluation of directives as PERL code from the rest of the program.
4129 # Remember that each package has its own name space.
4130 # Note that only the FIRST argument of execute->evaluate is actually evaluated,
4131 # all other arguments are accessible inside the first argument as $_[0] to $_[$#_].
4133 package CGIexecute;
4135 sub evaluate
4137 my $self = shift;
4138 my $directive = shift;
4139 $directive = eval($directive);
4140 warn $@ if $@; # Write an error message to STDERR
4141 $directive; # Return value of directive
4145 # defineCGIexecuteVariable($name [, $value]) -> 0/1
4147 # Define and intialize variables inside CGIexecute
4148 # Does no sanity checking, for internal use only
4150 sub defineCGIexecuteVariable # ($name [, $value]) -> 0/1
4152 my $name = shift || return 0; # The Name
4153 my $value = shift || ""; # The value
4155 ${$name} = $value;
4157 return 1;
4160 # defineCGIvariable($name [, $default]) -> 0/1
4162 # Define and intialize CGI variables
4163 # Tries (in order) $ENV{$name}, the Query string and the
4164 # default value.
4165 # Removes all '-quotes etc.
4167 sub defineCGIvariable # ($name [, $default]) -> 0/1
4169 my $name = shift || return 0; # The Name
4170 my $default = shift || ""; # The default value
4172 # Remove \-quoted characters
4173 $default =~ s/\\(.)/$1/g;
4174 # Store default values
4175 $::default_values{$name} = $default if $default;
4177 # Process variables
4178 my $temp = undef;
4179 # If there is a user supplied value, it replaces the
4180 # default value.
4182 # Environment values have precedence
4183 if(exists($ENV{$name}))
4185 $temp = $ENV{$name};
4187 # Get name and its value from the query string
4188 elsif($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
4190 $temp = ::YOUR_CGIPARSE($name);
4192 # Defined values must exist for security
4193 elsif(!exists($::default_values{$name}))
4195 $::default_values{$name} = undef;
4198 # SECURITY, do not allow '- and `-quotes in
4199 # client values.
4200 # Remove all existing '-quotes
4201 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
4202 $temp =~ s/[\']/&#8217;/igs; # Remove all single quotes
4203 $temp =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
4204 # If $temp is empty, use the default value (if it exists)
4205 unless($temp =~ /\S/ || length($temp) > 0) # I.e., $temp is empty
4207 $temp = $::default_values{$name};
4208 # Remove all existing '-quotes
4209 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
4210 $temp =~ s/[\']/&#8217;/igs; # Remove all single quotes
4211 $temp =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
4213 else # Store current CGI values and remove defaults
4215 $::default_values{$name} = $temp;
4217 # Define the CGI variable and its value (in the execute package)
4218 ${$name} = $temp;
4220 # return SUCCES
4221 return 1;
4224 sub defineCGIvariableList # ($name [, $default]) -> 0/1)
4226 my $name = shift || return 0; # The Name
4227 my $default = shift || ""; # The default value
4229 # Defined values must exist for security
4230 if(!exists($::default_values{$name}))
4232 $::default_values{$name} = $default;
4235 my @temp = ();
4238 # For security:
4239 # Environment values have precedence
4240 if(exists($ENV{$name}))
4242 push(@temp, $ENV{$name});
4244 # Get name and its values from the query string
4245 if($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
4247 push(@temp, ::YOUR_CGIPARSE($name, 1)); # Extract LIST
4249 else
4251 push(@temp, $::default_values{$name});
4255 # SECURITY, do not allow '- and `-quotes in
4256 # client values.
4257 # Remove all existing '-quotes
4258 @temp = map {s/([\r\f]+\n)/\n/g; $_} @temp; # Only \n is allowed
4259 @temp = map {s/[\']/&#8217;/igs; $_} @temp; # Remove all single quotes
4260 @temp = map {s/[\`]/&#8216;/igs; $_} @temp; # Remove all backtick quotes
4262 # Store current CGI values and remove defaults
4263 $::default_values{$name} = $temp[0];
4265 # Define the CGI variable and its value (in the execute package)
4266 @{$name} = @temp;
4268 # return SUCCES
4269 return 1;
4272 sub defineCGIvariableHash # ($name [, $default]) -> 0/1) Note: '$name{""} = $default';
4274 my $name = shift || return 0; # The Name
4275 my $default = shift || ""; # The default value
4277 # Defined values must exist for security
4278 if(!exists($::default_values{$name}))
4280 $::default_values{$name} = $default;
4283 my %temp = ();
4286 # For security:
4287 # Environment values have precedence
4288 if(exists($ENV{$name}))
4290 $temp{""} = $ENV{$name};
4292 # Get name and its values from the query string
4293 if($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
4295 %temp = ::YOUR_CGIPARSE($name, -1); # Extract HASH table
4297 elsif($::default_values{$name} ne "")
4299 $temp{""} = $::default_values{$name};
4303 # SECURITY, do not allow '- and `-quotes in
4304 # client values.
4305 # Remove all existing '-quotes
4306 my $Key;
4307 foreach $Key (keys(%temp))
4309 $temp{$Key} =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
4310 $temp{$Key} =~ s/[\']/&#8217;/igs; # Remove all single quotes
4311 $temp{$Key} =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
4314 # Store current CGI values and remove defaults
4315 $::default_values{$name} = $temp{""};
4317 # Define the CGI variable and its value (in the execute package)
4318 %{$name} = ();
4319 my $tempKey;
4320 foreach $tempKey (keys(%temp))
4322 ${$name}{$tempKey} = $temp{$tempKey};
4325 # return SUCCES
4326 return 1;
4330 # SAFEqx('CommandString')
4332 # A special function that is a safe alternative to backtick quotes (and qx//)
4333 # with client-supplied CGI values. All CGI variables are surrounded by
4334 # single ''-quotes (except between existing \'\'-quotes, don't try to be
4335 # too smart). All variables are then interpolated. Simple (@) lists are
4336 # expanded with join(' ', @List), and simple (%) hash tables expanded
4337 # as a list of "key=value" pairs. Complex variables, e.g., @$var, are
4338 # evaluated in a scalar context (e.g., as scalar(@$var)). All occurrences of
4339 # $@% that should NOT be interpolated must be preceeded by a "\".
4340 # If the first line of the String starts with "#! interpreter", the
4341 # remainder of the string is piped into interpreter (after interpolation), i.e.,
4342 # open(INTERPRETER, "|interpreter");print INTERPRETER remainder;
4343 # just like in UNIX. There are some problems with quotes. Be carefull in
4344 # using them. You do not have access to the output of any piped (#!)
4345 # process! If you want such access, execute
4346 # <SCRIPT TYPE="text/osshell">echo "script"|interpreter</SCRIPT> or
4347 # <SCRIPT TYPE="text/ssperl">$resultvar = SAFEqx('echo "script"|interpreter');
4348 # </SCRIPT>.
4350 # SAFEqx ONLY WORKS WHEN THE STRING ITSELF IS SURROUNDED BY SINGLE QUOTES
4351 # (SO THAT IT IS NOT INTERPOLATED BEFORE IT CAN BE PROTECTED)
4352 sub SAFEqx # ('String') -> result of executing qx/"String"/
4354 my $CommandString = shift;
4355 my $NewCommandString = "";
4357 # Only interpolate when required (check the On/Off switch)
4358 unless($CGIscriptor::NoShellScriptInterpolation)
4361 # Handle existing single quotes around CGI values
4362 while($CommandString =~ /\'[^\']+\'/s)
4364 my $CurrentQuotedString = $&;
4365 $NewCommandString .= $`;
4366 $CommandString = $'; # The remaining string
4367 # Interpolate CGI variables between quotes
4368 # (e.g., '$CGIscriptorResults[-1]')
4369 $CurrentQuotedString =~
4370 s/(^|[^\\])([\$\@])((\w*)([\{\[][\$\@\%]?[\:\w\-]+[\}\]])*)/if(exists($main::default_values{$4})){
4371 "$1".eval("$2$3")}else{"$&"}/egs;
4373 # Combine result with previous result
4374 $NewCommandString .= $CurrentQuotedString;
4376 $CommandString = $NewCommandString.$CommandString;
4378 # Select known CGI variables and surround them with single quotes,
4379 # then interpolate all variables
4380 $CommandString =~
4381 s/(^|[^\\])([\$\@\%]+)((\w*)([\{\[][\w\:\$\"\-]+[\}\]])*)/
4382 if($2 eq '$' && exists($main::default_values{$4}))
4383 {"$1\'".eval("\$$3")."\'";}
4384 elsif($2 eq '@'){$1.join(' ', @{"$3"});}
4385 elsif($2 eq '%'){my $t=$1;map {$t.=" $_=".${"$3"}{$_}}
4386 keys(%{"$3"});$t}
4387 else{$1.eval("${2}$3");
4388 }/egs;
4390 # Remove backslashed [$@%]
4391 $CommandString =~ s/\\([\$\@\%])/$1/gs;
4394 # Debugging
4395 # return $CommandString;
4397 # Handle UNIX style "#! shell command\n" constructs as
4398 # a pipe into the shell command. The output cannot be tapped.
4399 my $ReturnValue = "";
4400 if($CommandString =~ /^\s*\#\!([^\f\n\r]+)[\f\n\r]/is)
4402 my $ShellScripts = $';
4403 my $ShellCommand = $1;
4404 open(INTERPRETER, "|$ShellCommand") || dieHandler(29, "\'$ShellCommand\' PIPE not opened: &!\n");
4405 select(INTERPRETER);$| = 1;
4406 print INTERPRETER $ShellScripts;
4407 close(INTERPRETER);
4408 select(STDOUT);$| = 1;
4410 # Shell scripts which are redirected to an existing named pipe.
4411 # The output cannot be tapped.
4412 elsif($CGIscriptor::ShellScriptPIPE)
4414 CGIscriptor::printSAFEqxPIPE($CommandString);
4416 else # Plain ``-backtick execution
4418 # Execute the commands
4419 $ReturnValue = qx/$CommandString/;
4421 return $ReturnValue;
4424 ####################################################################################
4426 # The CGIscriptor PACKAGE
4428 ####################################################################################
4430 # Isolate the evaluation of CGIscriptor functions, i.e., those prefixed with
4431 # "CGIscriptor::"
4433 package CGIscriptor;
4436 # The Interpolation On/Off switch
4437 my $NoShellScriptInterpolation = undef;
4438 # The ShellScript redirection pipe
4439 my $ShellScriptPIPE = undef;
4441 # Open a named PIPE for SAFEqx to receive ALL shell scripts
4442 sub RedirectShellScript # ('CommandString')
4444 my $CommandString = shift || undef;
4446 if($CommandString)
4448 $ShellScriptPIPE = "ShellScriptNamedPipe";
4449 open($ShellScriptPIPE, "|$CommandString")
4450 || main::dieHandler(30, "\'|$CommandString\' PIPE open failed: $!\n");
4452 else
4454 close($ShellScriptPIPE);
4455 $ShellScriptPIPE = undef;
4457 return $ShellScriptPIPE;
4460 # Print to redirected shell script pipe
4461 sub printSAFEqxPIPE # ("String") -> print return value
4463 my $String = shift || undef;
4465 select($ShellScriptPIPE); $| = 1;
4466 my $returnvalue = print $ShellScriptPIPE ($String);
4467 select(STDOUT); $| = 1;
4469 return $returnvalue;
4472 # a pointer to CGIexecute::SAFEqx
4473 sub SAFEqx # ('String') -> result of qx/"String"/
4475 my $CommandString = shift;
4476 return CGIexecute::SAFEqx($CommandString);
4480 # a pointer to CGIexecute::defineCGIvariable
4481 sub defineCGIvariable # ($name[, $default]) ->0/1
4483 my $name = shift;
4484 my $default = shift;
4485 return CGIexecute::defineCGIvariable($name, $default);
4489 # Decode URL encoded arguments
4490 sub URLdecode # (URL encoded input) -> string
4492 my $output = "";
4493 my $char;
4494 my $Value;
4495 foreach $Value (@_)
4497 my $EncodedValue = $Value; # Do not change the loop variable
4498 # Convert all "+" to " "
4499 $EncodedValue =~ s/\+/ /g;
4500 # Convert all hexadecimal codes (%FF) to their byte values
4501 while($EncodedValue =~ /\%([0-9A-F]{2})/i)
4503 $output .= $`.chr(hex($1));
4504 $EncodedValue = $';
4506 $output .= $EncodedValue; # The remaining part of $Value
4508 $output;
4511 # Encode arguments as URL codes.
4512 sub URLencode # (input) -> URL encoded string
4514 my $output = "";
4515 my $char;
4516 my $Value;
4517 foreach $Value (@_)
4519 my @CharList = split('', $Value);
4520 foreach $char (@CharList)
4522 if($char =~ /\s/)
4523 { $output .= "+";}
4524 elsif($char =~ /\w\-/)
4525 { $output .= $char;}
4526 else
4528 $output .= uc(sprintf("%%%2.2x", ord($char)));
4532 $output;
4535 # Extract the value of a CGI variable from the URL-encoded $string
4536 # Also extracts the data blocks from a multipart request. Does NOT
4537 # decode the multipart blocks
4538 sub CGIparseValue # (ValueName [, URL_encoded_QueryString [, \$QueryReturnReference]]) -> Decoded value
4540 my $ValueName = shift;
4541 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4542 my $ReturnReference = shift || undef;
4543 my $output = "";
4545 if($QueryString =~ /(^|\&)$ValueName\=([^\&]*)(\&|$)/)
4547 $output = URLdecode($2);
4548 $$ReturnReference = $' if ref($ReturnReference);
4550 # Get multipart POST or PUT methods
4551 elsif($main::ENV{'CONTENT_TYPE'} =~ m@(multipart/([\w\-]+)\;\s+boundary\=([\S]+))@i)
4553 my $MultipartType = $2;
4554 my $BoundaryString = $3;
4555 # Remove the boundary-string
4556 my $temp = $QueryString;
4557 $temp =~ /^\Q--$BoundaryString\E/m;
4558 $temp = $';
4560 # Identify the newline character(s), this is the first character in $temp
4561 my $NewLine = "\r\n"; # Actually, this IS the correct one
4562 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
4564 # Is this correct??? I have to check.
4565 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
4566 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
4567 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
4568 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
4571 # search through all data blocks
4572 while($temp =~ /^\Q--$BoundaryString\E/m)
4574 my $DataBlock = $`;
4575 $temp = $';
4576 # Get the empty line after the header
4577 $DataBlock =~ /$NewLine$NewLine/;
4578 $Header = $`;
4579 $output = $';
4580 my $Header = $`;
4581 $output = $';
4583 # Remove newlines from the header
4584 $Header =~ s/$NewLine/ /g;
4586 # Look whether this block is the one you are looking for
4587 # Require the quotes!
4588 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
4590 my $i;
4591 for($i=length($NewLine); $i; --$i)
4593 chop($output);
4595 # OK, get out
4596 last;
4598 # reinitialize the output
4599 $output = "";
4601 $$ReturnReference = $temp if ref($ReturnReference);
4603 elsif($QueryString !~ /(^|\&)$ValueName\=/) # The value simply isn't there
4605 return undef;
4606 $$ReturnReference = undef if ref($ReturnReference);
4608 else
4610 print "ERROR: $ValueName $main::ENV{'CONTENT_TYPE'}\n";
4612 return $output;
4616 # Get a list of values for the same ValueName. Uses CGIparseValue
4618 sub CGIparseValueList # (ValueName [, URL_encoded_QueryString]) -> List of decoded values
4620 my $ValueName = shift;
4621 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4622 my @output = ();
4623 my $RestQueryString;
4624 my $Value;
4625 while($QueryString &&
4626 (($Value = CGIparseValue($ValueName, $QueryString, \$RestQueryString))
4627 || defined($Value)))
4629 push(@output, $Value);
4630 $QueryString = $RestQueryString; # QueryString is consumed!
4632 # ready, return list with values
4633 return @output;
4636 sub CGIparseValueHash # (ValueName [, URL_encoded_QueryString]) -> Hash table of decoded values
4638 my $ValueName = shift;
4639 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4640 my $RestQueryString;
4641 my %output = ();
4642 while($QueryString && $QueryString =~ /(^|\&)$ValueName([\w]*)\=/)
4644 my $Key = $2;
4645 my $Value = CGIparseValue("$ValueName$Key", $QueryString, \$RestQueryString);
4646 $output{$Key} = $Value;
4647 $QueryString = $RestQueryString; # QueryString is consumed!
4649 # ready, return list with values
4650 return %output;
4653 sub CGIparseForm # ([URL_encoded_QueryString]) -> Decoded Form (NO multipart)
4655 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4656 my $output = "";
4658 $QueryString =~ s/\&/\n/g;
4659 $output = URLdecode($QueryString);
4661 $output;
4664 # Extract the header of a multipart CGI variable from the POST input
4665 sub CGIparseHeader # (ValueName [, URL_encoded_QueryString]) -> Decoded value
4667 my $ValueName = shift;
4668 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4669 my $output = "";
4671 if($main::ENV{'CONTENT_TYPE'} =~ m@(multipart/([\w\-]+)\;\s+boundary\=([\S]+))@i)
4673 my $MultipartType = $2;
4674 my $BoundaryString = $3;
4675 # Remove the boundary-string
4676 my $temp = $QueryString;
4677 $temp =~ /^\Q--$BoundaryString\E/m;
4678 $temp = $';
4680 # Identify the newline character(s), this is the first character in $temp
4681 my $NewLine = "\r\n"; # Actually, this IS the correct one
4682 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
4684 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
4685 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
4686 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
4687 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
4690 # search through all data blocks
4691 while($temp =~ /^\Q--$BoundaryString\E/m)
4693 my $DataBlock = $`;
4694 $temp = $';
4695 # Get the empty line after the header
4696 $DataBlock =~ /$NewLine$NewLine/;
4697 $Header = $`;
4698 my $Header = $`;
4700 # Remove newlines from the header
4701 $Header =~ s/$NewLine/ /g;
4703 # Look whether this block is the one you are looking for
4704 # Require the quotes!
4705 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
4707 $output = $Header;
4708 last;
4710 # reinitialize the output
4711 $output = "";
4714 return $output;
4718 # Checking variables for security (e.g., file names and email addresses)
4719 # File names are tested against the $::FileAllowedChars and $::BlockPathAccess variables
4720 sub CGIsafeFileName # FileName -> FileName or ""
4722 my $FileName = shift || "";
4723 return "" if $FileName =~ m?[^$::FileAllowedChars]?;
4724 return "" if $FileName =~ m!(^|/|\:)[\-\.]!;
4725 return "" if $FileName =~ m@\.\.\Q$::DirectorySeparator\E@; # Higher directory not allowed
4726 return "" if $FileName =~ m@\Q$::DirectorySeparator\E\.\.@; # Higher directory not allowed
4727 return "" if $::BlockPathAccess && $FileName =~ m@$::BlockPathAccess@; # Invisible (blocked) file
4729 return $FileName;
4732 sub CGIsafeEmailAddress # email -> email or ""
4734 my $Email = shift || "";
4735 return "" unless $Email =~ m/^[\w\.\-]+[\@][\w\.\-\:]+$/;
4736 return $Email;
4739 # Get a URL from the web. Needs main::GET_URL($URL) function
4740 # (i.e., curl, snarf, or wget)
4741 sub read_url # ($URL) -> page/file
4743 my $URL = shift || return "";
4745 # Get the commands to read the URL, do NOT add a print command
4746 my $URL_command = main::GET_URL($URL, 1);
4747 # execute the commands, i.e., actually read it
4748 my $URLcontent = CGIexecute->evaluate($URL_command);
4750 # Ready, return the content.
4751 return $URLcontent;
4754 ################################################>>>>>>>>>>Start Remove
4756 # BrowseAllDirs(Directory, indexfile)
4758 # usage:
4759 # <SCRIPT TYPE='text/ssperl'>
4760 # CGIscriptor::BrowseAllDirs('Sounds', 'index.html', '\.wav$')
4761 # </SCRIPT>
4763 # Allows to browse all directories. Stops at '/'. If the directory contains
4764 # an indexfile, eg, index.html, that file will be used instead. Files must match
4765 # the $Pattern, if it is given. Default is
4766 # CGIscriptor::BrowseAllDirs('/', 'index.html', '')
4768 sub BrowseAllDirs # (Directory, indexfile, $Pattern) -> Print HTML code
4770 my $Directory = shift || '/';
4771 my $indexfile = shift || 'index.html';
4772 my $Pattern = shift || '';
4773 $Directory =~ s!/$!!g;
4775 # If the index directory exists, use that one
4776 if(-s "$::CGI_HOME$Directory/$indexfile")
4778 return main::ProcessFile("$::CGI_HOME$Directory/$indexfile");
4781 # No indexfile, continue
4782 my @DirectoryList = glob("$::CGI_HOME$Directory");
4783 $CurrentDirectory = shift(@DirectoryList);
4784 $CurrentDirectory = $' if $CurrentDirectory =~ m@(/\.\./)+@;
4785 $CurrentDirectory =~ s@^$::CGI_HOME@@g;
4786 print "<h1>";
4787 print "$CurrentDirectory" if $CurrentDirectory;
4788 print "</h1>\n";
4790 opendir(BROWSE, "$::CGI_HOME$Directory") || main::dieHandler(31, "$::CGI_HOME$Directory $!");
4791 my @AllFiles = sort grep(!/^([\.]+[^\.]|\~)/, readdir(BROWSE));
4793 # Print directories
4794 my $file;
4795 print "<pre><ul TYPE='NONE'>\n";
4796 foreach $file (@AllFiles)
4798 next unless -d "$::CGI_HOME$Directory/$file";
4799 # Check whether this file should be visible
4800 next if $::BlockPathAccess &&
4801 "$Directory/$file/" =~ m@$::BlockPathAccess@;
4802 print "<dt><a href='$Directory/$file'>$file</a></dt>\n";
4804 print "</ul></pre>\n";
4806 # Print files
4807 print "<pre><ul TYPE='CIRCLE'>\n";
4808 my $TotalSize = 0;
4809 foreach $file (@AllFiles)
4811 next if $file =~ /^\./;
4812 next if -d "$::CGI_HOME$Directory/$file";
4813 next if -l "$::CGI_HOME$Directory/$file";
4814 # Check whether this file should be visible
4815 next if $::BlockPathAccess &&
4816 "$Directory/$file" =~ m@$::BlockPathAccess@;
4818 if(!$Pattern || $file =~ m@$Pattern@)
4820 my $Date = localtime($^T - (-M "$::CGI_HOME$Directory/$file")*3600*24);
4821 my $Size = -s "$::CGI_HOME$Directory/$file";
4822 $Size = sprintf("%6.0F kB", $Size/1024);
4823 my $Type = `file $::CGI_HOME$Directory/$file`;
4824 $Type =~ s@\s*$::CGI_HOME$Directory/$file\s*\:\s*@@ig;
4825 chomp($Type);
4827 print "<li>";
4828 print "<a href='$Directory/$file'>";
4829 printf("%-40s", "$file</a>");
4830 print "\t$Size\t$Date\t$Type";
4831 print "</li>\n";
4834 print "</ul></pre>";
4836 return 1;
4840 ################################################
4842 # BrowseDirs(RootDirectory [, Pattern, Start])
4844 # usage:
4845 # <SCRIPT TYPE='text/ssperl'>
4846 # CGIscriptor::BrowseDirs('Sounds', '\.aifc$', 'Speech', 'DIRECTORY')
4847 # </SCRIPT>
4849 # Allows to browse subdirectories. Start should be relative to the RootDirectory,
4850 # e.g., the full path of the directory 'Speech' is '~/Sounds/Speech'.
4851 # Only files which fit /$Pattern/ and directories are displayed.
4852 # Directories down or up the directory tree are supplied with a
4853 # GET request with the name of the CGI variable in the fourth argument (default
4854 # is 'BROWSEDIRS'). So the correct call for a subdirectory could be:
4855 # CGIscriptor::BrowseDirs('Sounds', '\.aifc$', $DIRECTORY, 'DIRECTORY')
4857 sub BrowseDirs # (RootDirectory [, Pattern, Start, CGIvariable, HTTPserver]) -> Print HTML code
4859 my $RootDirectory = shift; # || return 0;
4860 my $Pattern = shift || '\S';
4861 my $Start = shift || "";
4862 my $CGIvariable = shift || "BROWSEDIRS";
4863 my $HTTPserver = shift || '';
4865 $Start = CGIscriptor::URLdecode($Start); # Sometimes, too much has been encoded
4866 $Start =~ s@//+@/@g;
4867 $Start =~ s@[^/]+/\.\.@@ig;
4868 $Start =~ s@^\.\.@@ig;
4869 $Start =~ s@/\.$@@ig;
4870 $Start =~ s!/+$!!g;
4871 $Start .= "/" if $Start;
4873 my @Directory = glob("$::CGI_HOME/$RootDirectory/$Start");
4874 $CurrentDirectory = shift(@Directory);
4875 $CurrentDirectory = $' if $CurrentDirectory =~ m@(/\.\./)+@;
4876 $CurrentDirectory =~ s@^$::CGI_HOME@@g;
4877 print "<h1>";
4878 print "$CurrentDirectory" if $CurrentDirectory;
4879 print "</h1>\n";
4880 opendir(BROWSE, "$::CGI_HOME/$RootDirectory/$Start") || main::dieHandler(31, "$::CGI_HOME/$RootDirectory/$Start $!");
4881 my @AllFiles = sort grep(!/^([\.]+[^\.]|\~)/, readdir(BROWSE));
4883 # Print directories
4884 my $file;
4885 print "<pre><ul TYPE='NONE'>\n";
4886 foreach $file (@AllFiles)
4888 next unless -d "$::CGI_HOME/$RootDirectory/$Start$file";
4889 # Check whether this file should be visible
4890 next if $::BlockPathAccess &&
4891 "/$RootDirectory/$Start$file/" =~ m@$::BlockPathAccess@;
4893 my $NewURL = $Start ? "$Start$file" : $file;
4894 $NewURL = CGIscriptor::URLencode($NewURL);
4895 print "<dt><a href='";
4896 print "$ENV{SCRIPT_NAME}" if $ENV{SCRIPT_NAME} !~ m@[^\w+\-/]@;
4897 print "$ENV{PATH_INFO}?$CGIvariable=$NewURL'>$file</a></dt>\n";
4899 print "</ul></pre>\n";
4901 # Print files
4902 print "<pre><ul TYPE='CIRCLE'>\n";
4903 my $TotalSize = 0;
4904 foreach $file (@AllFiles)
4906 next if $file =~ /^\./;
4907 next if -d "$::CGI_HOME/$RootDirectory/$Start$file";
4908 next if -l "$::CGI_HOME/$RootDirectory/$Start$file";
4909 # Check whether this file should be visible
4910 next if $::BlockPathAccess &&
4911 "$::CGI_HOME/$RootDirectory/$Start$file" =~ m@$::BlockPathAccess@;
4913 if($file =~ m@$Pattern@)
4915 my $Date = localtime($^T - (-M "$::CGI_HOME/$RootDirectory/$Start$file")*3600*24);
4916 my $Size = -s "$::CGI_HOME/$RootDirectory/$Start$file";
4917 $Size = sprintf("%6.0F kB", $Size/1024);
4918 my $Type = `file $::CGI_HOME/$RootDirectory/$Start$file`;
4919 $Type =~ s@\s*$::CGI_HOME/$RootDirectory/$Start$file\s*\:\s*@@ig;
4920 chomp($Type);
4922 print "<li>";
4923 if($HTTPserver =~ /^\s*[\.\~]\s*$/)
4925 print "<a href='$RootDirectory/$Start$file'>";
4927 elsif($HTTPserver)
4929 print "<a href='$HTTPserver/$RootDirectory/$Start$file'>";
4931 printf("%-40s", "$file</a>") if $HTTPserver;
4932 printf("%-40s", "$file") unless $HTTPserver;
4933 print "\t$Size\t$Date\t$Type";
4934 print "</li>\n";
4937 print "</ul></pre>";
4939 return 1;
4943 # ListDocs(Pattern [,ListType])
4945 # usage:
4946 # <SCRIPT TYPE=text/ssperl>
4947 # CGIscriptor::ListDocs("/*", "dl");
4948 # </SCRIPT>
4950 # This subroutine is very usefull to manage collections of independent
4951 # documents. The resulting list will display the tree-like directory
4952 # structure. If this routine is too slow for online use, you can
4953 # store the result and use a link to that stored file.
4955 # List HTML and Text files with title and first header (HTML)
4956 # or filename and first meaningfull line (general text files).
4957 # The listing starts at the ServerRoot directory. Directories are
4958 # listed recursively.
4960 # You can change the list type (default is dl).
4961 # e.g.,
4962 # <dt><a href=<file.html>>title</a>
4963 # <dd>First Header
4964 # <dt><a href=<file.txt>>file.txt</a>
4965 # <dd>First meaningfull line of text
4967 sub ListDocs # ($Pattern [, prefix]) e.g., ("/Books/*", [, "dl"])
4969 my $Pattern = shift;
4970 $Pattern =~ /\*/;
4971 my $ListType = shift || "dl";
4972 my $Prefix = lc($ListType) eq "dl" ? "dt" : "li";
4973 my $URL_root = "http://$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}";
4974 my @FileList = glob("$::CGI_HOME$Pattern");
4975 my ($FileName, $Path, $Link);
4977 # Print List markers
4978 print "<$ListType>\n";
4980 # Glob all files
4981 File: foreach $FileName (@FileList)
4983 # Check whether this file should be visible
4984 next if $::BlockPathAccess && $FileName =~ m@$::BlockPathAccess@;
4986 # Recursively list files in all directories
4987 if(-d $FileName)
4989 $FileName =~ m@([^/]*)$@;
4990 my $DirName = $1;
4991 print "<$Prefix>$DirName\n";
4992 $Pattern =~ m@([^/]*)$@;
4993 &ListDocs("$`$DirName/$1", $ListType);
4994 next;
4996 # Use textfiles
4997 elsif(-T "$FileName")
4999 open(TextFile, $FileName) || next;
5001 # Ignore all other file types
5002 else
5003 { next;};
5005 # Get file path for link
5006 $FileName =~ /$::CGI_HOME/;
5007 print "<$Prefix><a href=$URL_root$'>";
5008 # Initialize all variables
5009 my $Line = "";
5010 my $TitleFound = 0;
5011 my $Caption = "";
5012 my $Title = "";
5013 # Read file and step through
5014 while(<TextFile>)
5016 chop $_;
5017 $Line = $_;
5018 # HTML files
5019 if($FileName =~ /\.ht[a-zA-Z]*$/i)
5021 # Catch Title
5022 while(!$Title)
5024 if($Line =~ m@<title>([^<]*)</title>@i)
5026 $Title = $1;
5027 $Line = $';
5029 else
5031 $Line .= <TextFile> || goto Print;
5032 chop $Line;
5035 # Catch First Header
5036 while(!$Caption)
5038 if($Line =~ m@</h1>@i)
5040 $Caption = $`;
5041 $Line = $';
5042 $Caption =~ m@<h1>@i;
5043 $Caption = $';
5044 $Line = $`.$Caption.$Line;
5046 else
5048 $Line .= <TextFile> || goto Print;
5049 chop $Line;
5053 # Other text files
5054 else
5056 # Title equals file name
5057 $FileName =~ /([^\/]+)$/;
5058 $Title = $1;
5059 # Catch equals First Meaningfull line
5060 while(!$Caption)
5062 if($Line =~ /[A-Z]/ &&
5063 ($Line =~ /subject|title/i || $Line =~ /^[\w,\.\s\?\:]+$/)
5064 && $Line !~ /Newsgroup/ && $Line !~ /\:\s*$/)
5066 $Line =~ s/\<[^\>]+\>//g;
5067 $Caption = $Line;
5069 else
5071 $Line = <TextFile> || goto Print;
5075 Print: # Print title and subject
5076 print "$Title</a>\n";
5077 print "<dd>$Caption\n" if $ListType eq "dl";
5078 $TitleFound = 0;
5079 $Caption = "";
5080 close TextFile;
5081 next File;
5084 # Print Closing List Marker
5085 print "</$ListType>\n";
5086 ""; # Empty return value
5090 # HTMLdocTree(Pattern [,ListType])
5092 # usage:
5093 # <SCRIPT TYPE=text/ssperl>
5094 # CGIscriptor::HTMLdocTree("/Welcome.html", "dl");
5095 # </SCRIPT>
5097 # The following subroutine is very usefull for checking large document
5098 # trees. Starting from the root (s), it reads all files and prints out
5099 # a nested list of links to all attached files. Non-existing or misplaced
5100 # files are flagged. This is quite a file-i/o intensive routine
5101 # so you would not like it to be accessible to everyone. If you want to
5102 # use the result, save the whole resulting page to disk and use a link
5103 # to this file.
5105 # HTMLdocTree takes an HTML file or file pattern and constructs nested lists
5106 # with links to *local* files (i.e., only links to the local server are
5107 # followed). The list entries are the document titles.
5108 # If the list type is <dl>, the first <H1> header is used too.
5109 # For each file matching the pattern, a list is made recursively of all
5110 # HTML documents that are linked from it and are stored in the same directory
5111 # or a sub-directory. Warnings are given for missing files.
5112 # The listing starts for the ServerRoot directory.
5113 # You can change the default list type <dl> (<dl>, <ul>, <ol>).
5115 %LinkUsed = ();
5117 sub HTMLdocTree # ($Pattern [, listtype])
5118 # e.g., ("/Welcome.html", [, "ul"])
5120 my $Pattern = shift;
5121 my $ListType = shift || "dl";
5122 my $Prefix = lc($ListType) eq "dl" ? "dt" : "li";
5123 my $URL_root = "http://$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}";
5124 my ($Filename, $Path, $Link);
5125 my %LocalLinks = {};
5127 # Read files (glob them for expansion of wildcards)
5128 my @FileList = glob("$::CGI_HOME$Pattern");
5129 foreach $Path (@FileList)
5131 # Get URL_path
5132 $Path =~ /$::CGI_HOME/;
5133 my $URL_path = $';
5134 # Check whether this file should be visible
5135 next if $::BlockPathAccess && $URL_path =~ m@$::BlockPathAccess@;
5137 my $Title = $URL_path;
5138 my $Caption = "";
5139 # Current file should not be used again
5140 ++$LinkUsed{$URL_path};
5141 # Open HTML doc
5142 unless(open(TextFile, $Path))
5144 print "<$Prefix>$Title <blink>(not found)</blink><br>\n";
5145 next;
5147 while(<TextFile>)
5149 chop $_;
5150 $Line = $_;
5151 # Catch Title
5152 while($Line =~ m@<title>@i)
5154 if($Line =~ m@<title>([^<]*)</title>@i)
5156 $Title = $1;
5157 $Line = $';
5159 else
5161 $Line .= <TextFile>;
5162 chop $Line;
5165 # Catch First Header
5166 while(!$Caption && $Line =~ m@<h1>@i)
5168 if($Line =~ m@</h[1-9]>@i)
5170 $Caption = $`;
5171 $Line = $';
5172 $Caption =~ m@<h1>@i;
5173 $Caption = $';
5174 $Line = $`.$Caption.$Line;
5176 else
5178 $Line .= <TextFile>;
5179 chop $Line;
5182 # Catch and print Links
5183 while($Line =~ m@<a href\=([^>]*)>@i)
5185 $Link = $1;
5186 $Line = $';
5187 # Remove quotes
5188 $Link =~ s/\"//g;
5189 # Remove extras
5190 $Link =~ s/[\#\?].*$//g;
5191 # Remove Servername
5192 if($Link =~ m@(http://|^)@i)
5194 $Link = $';
5195 # Only build tree for current server
5196 next unless $Link =~ m@$::ENV{'SERVER_NAME'}|^/@;
5197 # Remove server name and port
5198 $Link =~ s@^[^\/]*@@g;
5200 # Store the current link
5201 next if $LinkUsed{$Link} || $Link eq $URL_path;
5202 ++$LinkUsed{$Link};
5203 ++$LocalLinks{$Link};
5207 close TextFile;
5208 print "<$Prefix>";
5209 print "<a href=http://";
5210 print "$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}$URL_path>";
5211 print "$Title</a>\n";
5212 print "<br>$Caption\n"
5213 if $Caption && $Caption ne $Title && $ListType =~ /dl/i;
5214 print "<$ListType>\n";
5215 foreach $Link (keys(%LocalLinks))
5217 &HTMLdocTree($Link, $ListType);
5219 print "</$ListType>\n";
5223 ###########################<<<<<<<<<<End Remove
5225 # Make require happy
5228 =head1 NAME
5230 CGIscriptor -
5232 =head1 DESCRIPTION
5234 A flexible HTML 4 compliant script/module for CGI-aware
5235 embeded Perl, shell-scripts, and other scripting languages,
5236 executed at the server side.
5238 =head1 README
5240 Executes embeded Perl code in HTML pages with easy
5241 access to CGI variables. Also processes embeded shell
5242 scripts and scripts in any other language with an
5243 interactive interpreter (e.g., in-line Python, Tcl,
5244 Ruby, Awk, Lisp, Xlispstat, Prolog, M4, R, REBOL, Praat,
5245 sh, bash, csh, ksh).
5247 CGIscriptor is very flexible and hides all the specifics
5248 and idiosyncrasies of correct output and CGI coding and naming.
5249 CGIscriptor complies with the W3C HTML 4.0 recommendations.
5251 This Perl program will run on any WWW server that runs
5252 Perl scripts, just add a line like the following to your
5253 srm.conf file (Apache example):
5255 ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
5257 URL's that refer to http://www.your.address/SHTML/... will
5258 now be handled by CGIscriptor.pl, which can use a private
5259 directory tree (default is the DOCUMENT_ROOT directory tree,
5260 but it can be anywhere).
5262 =head1 PREREQUISITES
5265 =head1 COREQUISITES
5268 =pod OSNAMES
5270 Linux, *BSD, *nix, MS WinXP
5272 =pod SCRIPT CATEGORIES
5274 Servers
5278 =cut