Updated documentation for switch to SHA256
[CGIscriptor.git] / CGIscriptor.pl
blobedca6e704830d22b28f672528ed8aa864b9f69c0
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 # 06 Jun 2012 - Added IP only session types after login.
64 # 31 May 2012 - Session ticket system added for handling login sessions.
65 # 29 May 2012 - CGIsafeFileName does not accept filenames starting with '.'
66 # 29 May 2012 - Added CGIscriptor::BrowseAllDirs to handle browsing directories
67 # correctly.
68 # 22 May 2012 - Added Access control with Session Tickets linked to
69 # IP Address and PATH_INFO.
70 # 21 May 2012 - Corrected the links generated by CGIscriptor::BrowseDirs
71 # Will link to current base URL when the HTTP server is '.' or '~'
72 # 29 Oct 2009 - Adapted David A. Wheeler's suggestion about filenames:
73 # CGIsafeFileName does not accept filenames starting with '-'
74 # (http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html)
75 # 08 Oct 2009 - Some corrections in the README.txt file, eg, new email address
76 # 28 Jan 2005 - Added a file selector to performTranslation.
77 # Changed %TranslationTable to @TranslationTable
78 # and patterns to lists.
79 # 27 Jan 2005 - Added a %TranslationTable with associated
80 # performTranslation(\$text) function to allow
81 # run changes in the web pages. Say, to translate
82 # legacy pages with <%=...%> delimiters to the new
83 # <SCRIPT TYPE=..></SCRIPT> format.
84 # 27 Jan 2005 - Small bug of extra '\n' in output removed from the
85 # Other Languages Code.
86 # 10 May 2004 - Belated upload of latest version (2.3) to CPAN
87 # 07 Oct 2003 - Corrected error '\s' -> '\\s' in rebol scripting
88 # language call
89 # 07 Oct 2003 - Corrected omitted INS tags in <DIV><INS> handling
90 # 20 May 2003 - Added a --help switch to print the manual.
91 # 06 Mar 2003 - Adapted the blurb at the end of the file.
92 # 03 Mar 2003 - Added a user definable dieHandler function to catch all
93 # "die" calls. Also "enhanced" the STDERR printout.
94 # 10 Feb 2003 - Split off the reading of the POST part of a query
95 # from Initialize_output. This was suggested by Gerd Franke
96 # to allow for the catching of the file_path using a
97 # POST based lookup. That is, he needed the POST part
98 # to change the file_path.
99 # 03 Feb 2003 - %{$name}; => %{$name} = (); in defineCGIvariableHash.
100 # 03 Feb 2003 - \1 better written as $1 in
101 # $directive =~ s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/$1/g
102 # 29 Jan 2003 - This makes "CLASS="ssperl" CSS-compatible Gerd Franke
103 # added:
104 # $ServerScriptContentClass = "ssperl";
105 # changed in ProcessFile():
106 # unless(($CurrentContentType =~
107 # 28 Jan 2003 - Added 'INS' Tag! Gerd Franke
108 # 20 Dec 2002 - Removed useless $Directoryseparator variable.
109 # Update comments and documentation.
110 # 18 Dec 2002 - Corrected bug in Accept/Reject processing.
111 # Files didn't work.
112 # 24 Jul 2002 - Added .htaccess documentation (from Gerd Franke)
113 # Also added a note that RawFilePattern can be a
114 # complete file name.
115 # 19 Mar 2002 - Added SRC pseudo-files PREFIX and POSTFIX. These
116 # switch to prepending or to appending the content
117 # of the SRC attribute. Default is prefixing. You
118 # can add as many of these switches as you like.
119 # 13 Mar 2002 - Do not search for tag content if a tag closes with
120 # />, i.e., <DIV ... /> will be handled the XML/XHTML way.
121 # 25 Jan 2002 - Added 'curl' and 'snarf' to SRC attribute URL handling
122 # (replaces wget).
123 # 25 Jan 2002 - Found a bug in SAFEqx, now executes qx() in a scalar context
124 # (i.o. a list context). This is necessary for binary results.
125 # 24 Jan 2002 - Disambiguated -T $SRCfile to -T "$SRCfile" (and -e) and
126 # changed the order of if/elsif to allow removing these
127 # conditions in systems with broken -T functions.
128 # (I also removed a spurious ')' bracket)
129 # 17 Jan 2002 - Changed DIV tag SRC from <SOURCE> to sysread(SOURCE,...)
130 # to support binary files.
131 # 17 Jan 2002 - Removed WhiteSpace from $FileAllowedCharacters.
132 # 17 Jan 2002 - Allow "file://" prefix in SRC attribute. It is simply
133 # stipped from the path.
134 # 15 Jan 2002 - Version 2.2
135 # 15 Jan 2002 - Debugged and completed URL support (including
136 # CGIscriptor::read_url() function)
137 # 07 Jan 2002 - Added automatic (magic) URL support to the SRC attribute
138 # with the main::GET_URL function. Uses wget -O underlying.
139 # 04 Jan 2002 - Added initialization of $NewDirective in InsertForeignScript
140 # (i.e., my $NewDirective = "";) to clear old output
141 # (this was a realy anoying bug).
142 # 03 Jan 2002 - Added a <DIV CLASS='text/ssperl' ID='varname'></DIV>
143 # tags that assign the body text as-is (literally)
144 # to $varname. Allows standard HTML-tools to handle
145 # Cascading Style Sheet templates. This implements a
146 # design by Gerd Franke (franke@roo.de).
147 # 03 Jan 2002 - I finaly gave in and allowed SRC files to expand ~/.
148 # 12 Oct 2001 - Normalized spelling of "CGIsafFileName" in documentation.
149 # 09 Oct 2001 - Added $ENV{'CGI_BINARY_FILE'} to log files to
150 # detect unwanted indexing of TAR files by webcrawlers.
151 # 10 Sep 2001 - Added $YOUR_SCRIPTS directory to @INC for 'require'.
152 # 22 Aug 2001 - Added .txt (Content-type: text/plain) as a default
153 # processed file type. Was processed via BinaryMapFile.
154 # 31 May 2001 - Changed =~ inside CGIsafeEmailAddress that was buggy.
155 # 29 May 2001 - Updated $CGI_HOME to point to $ENV{DOCUMENT_ROOT} io
156 # the root of PATH_TRANSLATED. DOCUMENT_ROOT can now
157 # be manipulated to achieve a "Sub Root".
158 # NOTE: you can have $YOUR_HTML_FILES != DOCUMENT_ROOT
159 # 28 May 2001 - Changed CGIscriptor::BrowsDirs function for security
160 # and debugging (it now works).
161 # 21 May 2001 - defineCGIvariableHash will ADD values to existing
162 # hashes,instead of replacing existing hashes.
163 # 17 May 2001 - Interjected a '&' when pasting POST to GET data
164 # 24 Apr 2001 - Blocked direct requests for BinaryMapFile.
165 # 16 Aug 2000 - Added hash table extraction for CGI parameters with
166 # CGIparseValueHash (used with structured parameters).
167 # Use: CGI='%<CGI-partial-name>' (fill in your name in <>)
168 # Will collect all <CGI-partial-name><key>=value pairs in
169 # $<CGI-partial-name>{<key>} = value;
170 # 16 Aug 2000 - Adapted SAFEqx to protect @PARAMETER values.
171 # 09 Aug 2000 - Added support for non-filesystem input by way of
172 # the CGI_FILE_CONTENTS and CGI_DATA_ACCESS_CODE
173 # environment variables.
174 # 26 Jul 2000 - On the command-line, file-path '-' indicates STDIN.
175 # This allows CGIscriptor to be used in pipes.
176 # Default, $BLOCK_STDIN_HTTP_REQUEST=1 will block this
177 # in an HTTP request (i.e., in a web server).
178 # 26 Jul 2000 - Blocked 'Content-type: text/html' if the SERVER_PROTOCOL
179 # is not HTTP or another protocol. Changed the default
180 # source directory to DOCUMENT_ROOT (i.o. the incorrect
181 # SERVER_ROOT).
182 # 24 Jul 2000 - -slim Command-line argument added to remove all
183 # comments, security, etc.. Updated documentation.
184 # 05 Jul 2000 - Added IF and UNLESS attributes to make the
185 # execution of all <META> and <SCRIPT> code
186 # conditional.
187 # 05 Jul 2000 - Rewrote and isolated the code for extracting
188 # quoted items from CGI and SRC attributes.
189 # Now all attributes expect the same set of
190 # quotes: '', "", ``, (), {}, [] and the same
191 # preceded by a \, e.g., "\((aap)\)" will be
192 # extracted as "(aap)".
193 # 17 Jun 2000 - Construct @ARGV list directly in CGIexecute
194 # name-space (i.o. by evaluation) from
195 # CGI attributes to prevent interference with
196 # the processing for non perl scripts.
197 # Changed CGIparseValueList to prevent runaway
198 # loops.
199 # 16 Jun 2000 - Added a direct (interpolated) display mode
200 # (text/ssdisplay) and a user log mode
201 # (text/sslogfile).
202 # 06 Jun 2000 - Replace "print $Result" with a syswrite loop to
203 # allow large string output.
204 # 02 Jun 2000 - Corrected shrubCGIparameter($CGI_VALUE) to realy
205 # remove all control characters. Changed Interpreter
206 # initialization to shrub interpolated CGI parameters.
207 # Added 'text/ssmailto' interpreter script.
208 # 22 May 2000 - Changed some of the comments
209 # 09 May 2000 - Added list extraction for CGI parameters with
210 # CGIparseValueList (used with multiple selections).
211 # Use: CGI='@<CGI-parameter>' (fill in your name in <>)
212 # 09 May 2000 - Added a 'Not Present' condition to CGIparseValue.
213 # 27 Apr 2000 - Updated documentation to reflect changes.
214 # 27 Apr 2000 - SRC attribute "cleaned". Supported for external
215 # interpreters.
216 # 27 Apr 2000 - CGI attribute can be used in <SCRIPT> tag.
217 # 27 Apr 2000 - Gprolog, M4 support added.
218 # 26 Apr 2000 - Lisp (rep) support added.
219 # 20 Apr 2000 - Use of external interpreters now functional.
220 # 20 Apr 2000 - Removed bug from extracting Content types (RegExp)
221 # 10 Mar 2000 - Qualified unconditional removal of '#' that preclude
222 # the use of $#foo, i.e., I changed
223 # s/[^\\]\#[^\n\f\r]*([\n\f\r])/\1/g
224 # to
225 # s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/\1/g
226 # 03 Mar 2000 - Added a '$BlockPathAccess' variable to "hide"
227 # things like, e.g., CVS information in CVS subtrees
228 # 10 Feb 2000 - URLencode/URLdecode have been made case-insensitive
229 # 10 Feb 2000 - Added a BrowseDirs function (CGIscriptor package)
230 # 01 Feb 2000 - A BinaryMapFile in the ~/ directory has precedence
231 # over a "burried" BinaryMapFile.
232 # 04 Oct 1999 - Added two functions to check file names and email addresses
233 # (CGIscriptor::CGIsafeFileName and
234 # CGIscriptor::CGIsafeEmailAddress)
235 # 28 Sept 1999 - Corrected bug in sysread call for reading POST method
236 # to allow LONG posts.
237 # 28 Sept 1999 - Changed CGIparseValue to handle multipart/form-data.
238 # 29 July 1999 - Refer to BinaryMapFile from CGIscriptor directory, if
239 # this directory exists.
240 # 07 June 1999 - Limit file-pattern matching to LAST extension
241 # 04 June 1999 - Default text/html content type is printed only once.
242 # 18 May 1999 - Bug in replacement of ~/ and ./ removed.
243 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
244 # 15 May 1999 - Changed the name of the execute package to CGIexecute.
245 # Changed the processing of the Accept and Reject file.
246 # Added a full expression evaluation to Access Control.
247 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
248 # 27 Apr 1999 - Brought CGIscriptor under the GNU GPL. Made CGIscriptor
249 # Version 1.1 a module that can be called with 'require "CGIscriptor.pl"'.
250 # Requests are serviced by "Handle_Request()". CGIscriptor
251 # can still be called as a isolated perl script and a shell
252 # command.
253 # Changed the "factory default setting" so that it will run
254 # from the DOCUMENT_ROOT directory.
255 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
256 # 29 Mar 1999 - Remove second debugging STDERR switch. Moved most code
257 # to subroutines to change CGIscriptor into a module.
258 # Added mapping to process unsupported file types (e.g., binary
259 # pictures). See $BinaryMapFile.
260 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
261 # 24 Sept 1998 - Changed text of license (Rob van Son, R.J.J.H.vanSon@uva.nl)
262 # Removed a double setting of filepatterns and maximum query
263 # size. Changed email address. Removed some typos from the
264 # comments.
265 # 02 June 1998 - Bug fixed in URLdecode. Changing the foreach loop variable
266 # caused quiting CGIscriptor.(Rob van Son, R.J.J.H.vanSon@uva.nl)
267 # 02 June 1998 - $SS_PUB and $SS_SCRIPT inserted an extra /, removed.
268 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
271 # Known Bugs:
273 # 23 Mar 2000
274 # It is not possible to use operators or variables to construct variable names,
275 # e.g., $bar = \@{$foo}; won't work. However, eval('$bar = \@{'.$foo.'};');
276 # will indeed work. If someone could tell me why, I would be obliged.
279 ############################################################################
281 # OBLIGATORY USER CONFIGURATION
283 # Configure the directories where all user files can be found (this
284 # is the equivalent of the server root directory of a WWW-server).
285 # These directories can be located ANYWHERE. For security reasons, it is
286 # better to locate them outside the WWW-tree of your HTTP server, unless
287 # CGIscripter handles ALL requests.
289 # For convenience, the defaults are set to the root of the WWW server.
290 # However, this might not be safe!
292 # ~/ text files
293 # $YOUR_HTML_FILES = "/usr/pub/WWW/SHTML"; # or SS_PUB as environment var
294 # (patch to use the parent directory of CGIscriptor as document root, should be removed)
295 if($ENV{'SCRIPT_FILENAME'}) # && $ENV{'SCRIPT_FILENAME'} !~ /\Q$ENV{'DOCUMENT_ROOT'}\E/)
297 $ENV{'DOCUMENT_ROOT'} = $ENV{'SCRIPT_FILENAME'};
298 $ENV{'DOCUMENT_ROOT'} =~ s@/CGIscriptor.*$@@ig;
301 # Just enter your own directory path here
302 $YOUR_HTML_FILES = $ENV{'DOCUMENT_ROOT'}; # default is the DOCUMENT_ROOT
304 # ./ script files (recommended to be different from the previous)
305 # $YOUR_SCRIPTS = "/usr/pub/WWW/scripts"; # or SS_SCRIPT as environment var
306 $YOUR_SCRIPTS = $YOUR_HTML_FILES; # This might be a SECURITY RISK
308 # End of obligatory user configuration
309 # (note: there is more non-essential user configuration below)
311 ############################################################################
313 # OPTIONAL USER CONFIGURATION (all values are used CASE INSENSITIVE)
315 # Script content-types: TYPE="Content-type" (user defined mime-type)
316 $ServerScriptContentType = "text/ssperl"; # Server Side Perl scripts
317 # CSS require a simple class
318 $ServerScriptContentClass = $ServerScriptContentType =~ m!/! ?
319 $' : "ssperl"; # Server Side Perl CSS classes
321 $ShellScriptContentType = "text/osshell"; # OS shell scripts
322 # # (Server Side perl ``-execution)
324 # Accessible file patterns, block any request that doesn't match.
325 # Matches any file with the extension .(s)htm(l), .txt, or .xmr
326 # (\. is used in regexp)
327 # Note: die unless $PATH_INFO =~ m@($FilePattern)$@is;
328 $FilePattern = ".shtml|.htm|.html|.xml|.xmr|.txt|.js";
330 # The table with the content type MIME types
331 # (allows to differentiate MIME types, if needed)
332 %ContentTypeTable =
334 '.html' => 'text/html',
335 '.shtml' => 'text/html',
336 '.htm' => 'text/html',
337 '.xml' => 'text/xml',
338 '.txt' => 'text/plain',
339 '.js' => 'text/plain'
343 # File pattern post-processing
344 $FilePattern =~ s/([@.])/\\$1/g; # Convert . and @ to \. and \@
346 # SHAsum command needed for Authorization and Login
347 # (note, these have to be accessible in the HTML pages, ie, the CGIexecute environment)
348 my $shasum = "shasum -a 256";
349 if(qx{uname} =~ /Darwin/)
351 $shasum = "shasum-5.12 -a 256" unless `which shasum`;
353 my $SHASUMCMD = $shasum.' |cut -f 1 -d" "';
354 $ENV{"SHASUMCMD"} = $SHASUMCMD;
355 my $RANDOMHASHCMD = 'dd bs=1 count=64 if=/dev/urandom 2>/dev/null | '.$shasum.' -b |cut -f 1 -d" "';
356 $ENV{"RANDOMHASHCMD"} = $RANDOMHASHCMD;
358 # File patterns of files which are handled by session tickets.
359 %TicketRequiredPatterns = (
360 '^/Private(/|$)' => "Private/.Sessions\tPrivate/.Passwords\t/Private/Login.html\t+36000"
362 # Used to set cookies, only session cookies supported
363 my %SETCOOKIELIST = ();
364 # Session Ticket Directory: Private/.Sessions
365 # Password Directory: Private/.Passwords
366 # Login page (url path): /Private/Login.html
367 # Expiration time (s): +3600
368 # +<seconds> = relative time <seconds> is absolute date-time
370 # Raw files must contain their own Content-type (xmr <- x-multipart-replace).
371 # THIS IS A SUBSET OF THE FILES DEFINED IN $FilePattern
372 $RawFilePattern = ".xmr";
373 # (In principle, this could contain a full file specification, e.g.,
374 # ".xmr|relocated.html")
376 # Raw File pattern post-processing
377 $RawFilePattern =~ s/([@.])/\\$1/g; # Convert . and @ to \. and \@
379 # Server protocols for which "Content-type: text/html\n\n" should be printed
380 # (you should not bother with these, except for HTTP, they are mostly imaginary)
381 $ContentTypeServerProtocols = 'HTTP|MAIL|MIME';
383 # Block access to all (sub-) paths and directories that match the
384 # following (URL) path (is used as:
385 # 'die if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@;' )
386 $BlockPathAccess = '/(CVS|\.git)/'; # Protect CVS and .git information
388 # All (blocked) other file-types can be mapped to a single "binary-file"
389 # processor (a kind of pseudo-file path). This can either be an error
390 # message (e.g., "illegal file") or contain a script that serves binary
391 # files.
392 # Note: the real file path wil be stored in $ENV{CGI_BINARY_FILE}.
393 $BinaryMapFile = "/BinaryMapFile.xmr";
394 # Allow for the addition of a CGIscriptor directory
395 # Note that a BinaryMapFile in the root "~/" directory has precedence
396 $BinaryMapFile = "/CGIscriptor".$BinaryMapFile
397 if ! -e "$YOUR_HTML_FILES".$BinaryMapFile
398 && -e "$YOUR_HTML_FILES/CGIscriptor".$BinaryMapFile;
401 # List of all characters that are allowed in file names and paths.
402 # All requests containing illegal characters are blocked. This
403 # blocks most tricks (e.g., adding "\000", "\n", or other control
404 # characters, also blocks URI's using %FF)
405 # THIS IS A SECURITY FEATURE
406 # (this is also used to parse filenames in SRC= features, note the
407 # '-quotes, they are essential)
408 $FileAllowedChars = '\w\.\~\/\:\*\?\-'; # Covers Unix and Mac, but NO spaces
410 # Maximum size of the Query (number of characters clients can send
411 # covers both GET & POST combined)
412 $MaximumQuerySize = 2**20 - 1; # = 2**14 - 1
415 # Embeded URL get function used in SRC attributes and CGIscriptor::read_url
416 # (returns a string with the PERL code to transfer the URL contents, e.g.,
417 # "SAFEqx(\'curl \"http://www.fon.hum.uva.nl\"\')")
418 # "SAFEqx(\'wget --quiet --output-document=- \"http://www.fon.hum.uva.nl\"\')")
419 # Be sure to handle <BASE HREF='URL'> and allow BOTH
420 # direct printing GET_URL($URL [, 0]) and extracting the content of
421 # the $URL for post-processing GET_URL($URL, 1).
422 # You get the WHOLE file, including HTML header.
423 # The shell command Use $URL where the URL should go
424 # ('wget', 'snarf' or 'curl', uncomment the one you would like to use)
425 my $GET_URL_shell_command = 'wget --quiet --output-document=- $URL';
426 #my $GET_URL_shell_command = 'snarf $URL -';
427 #my $GET_URL_shell_command = 'curl $URL';
429 sub GET_URL # ($URL, $ValueNotPrint) -> content_of_url
431 my $URL = shift || return;
432 my $ValueNotPrint = shift || 0;
434 # Check URL for illegal characters
435 return "print '<h1>Illegal URL<h1>'\"\n\";" if $URL =~ /[^$FileAllowedChars\%]/;
437 # Include URL in final command
438 my $CurrentCommand = $GET_URL_shell_command;
439 $CurrentCommand =~ s/\$URL/$URL/g;
441 # Print to STDOUT or return a value
442 my $BlockPrint = "print STDOUT ";
443 $BlockPrint = "" if $ValueNotPrint;
445 my $Commands = <<"GETURLCODE";
446 # Get URL
448 my \$Page = "";
450 # Simple, using shell command
451 \$Page = SAFEqx('$CurrentCommand');
453 # Add a BASE tage to the header
454 \$Page =~ s!\\</head!\\<base href='$URL'\\>\\</head!ig unless \$Page =~ m!\\<base!;
456 # Print the URL value, or return it as a value
457 $BlockPrint\$Page;
459 GETURLCODE
460 return $Commands;
463 # As files can get rather large (and binary), you might want to use
464 # some more intelligent reading procedure, e.g.,
465 # Direct Perl
466 # # open(URLHANDLE, '/usr/bin/wget --quiet --output-document=- "$URL"|') || die "wget: \$!";
467 # #open(URLHANDLE, '/usr/bin/snarf "$URL" -|') || die "snarf: \$!";
468 # open(URLHANDLE, '/usr/bin/curl "$URL"|') || die "curl: \$!";
469 # my \$text = "";
470 # while(sysread(URLHANDLE,\$text, 1024) > 0)
472 # \$Page .= \$text;
473 # };
474 # close(URLHANDLE) || die "\$!";
475 # However, this doesn't work with the CGIexecute->evaluate() function.
476 # You get an error: 'No child processes at (eval 16) line 15, <file0> line 8.'
478 # You can forget the next two variables, they are only needed when
479 # you don't want to use a regular file system (i.e., with open)
480 # but use some kind of database/RAM image for accessing (generating)
481 # the data.
483 # Name of the environment variable that contains the file contents
484 # when reading directly from Database/RAM. When this environment variable,
485 # $ENV{$CGI_FILE_CONTENTS}, is not false, no real file will be read.
486 $CGI_FILE_CONTENTS = 'CGI_FILE_CONTENTS';
487 # Uncomment the following if you want to force the use of the data access code
488 # $ENV{$CGI_FILE_CONTENTS} = '-'; # Force use of $ENV{$CGI_DATA_ACCESS_CODE}
490 # Name of the environment variable that contains the RAM access perl
491 # code needed to read additional "files", i.e.,
492 # $ENV{$CGI_FILE_CONTENTS} = eval("\@_=('$file_path'); do{$ENV{$CGI_DATA_ACCESS_CODE}}");
493 # When $ENV{$CGI_FILE_CONTENTS} eq '-', this code is executed to generate the data.
494 $CGI_DATA_ACCESS_CODE = 'CGI_DATA_ACCESS_CODE';
496 # You can, of course, fill this yourself, e.g.,
497 # $ENV{$CGI_DATA_ACCESS_CODE} =
498 # 'open(INPUT, "<$_[0]"); while(<INPUT>){print;};close(INPUT);'
501 # DEBUGGING
503 # Suppress error messages, this can be changed for debugging or error-logging
504 #open(STDERR, "/dev/null"); # (comment out for use in debugging)
506 # SPECIAL: Remove Comments, security, etc. if the command line is
507 # '>CGIscriptor.pl -slim >slimCGIscriptor.pl'
508 $TrimDownCGIscriptor = 1 if $ARGV[0] =~ /^\-slim/i;
510 # If CGIscriptor is used from the command line, the command line
511 # arguments are interpreted as the file (1st) and the Query String (rest).
512 # Get the arguments
513 $ENV{'PATH_INFO'} = shift(@ARGV) unless exists($ENV{'PATH_INFO'}) || grep(/\-\-help/i, @ARGV);
514 $ENV{'QUERY_STRING'} = join("&", @ARGV) unless exists($ENV{'QUERY_STRING'});
517 # Handle bail-outs in a user definable way.
518 # Catch Die and replace it with your own function.
519 # Ends with a call to "die $_[0];"
521 sub dieHandler # ($ErrorCode, "Message", @_) -> DEAD
523 my $ErrorCode = shift;
524 my $ErrorMessage = shift;
526 # Place your own reporting functions here
528 # Now, kill everything (default)
529 print STDERR "$ErrorCode: $ErrorMessage\n";
530 die $ErrorMessage;
534 # End of optional user configuration
535 # (note: there is more non-essential user configuration below)
537 if(grep(/\-\-help/i, @ARGV))
539 print << 'ENDOFPREHELPTEXT2';
541 ###############################################################################
543 # Author and Copyright (c):
544 # Rob van Son, © 1995,1996,1997,1998,1999,2000,2001,2002-2012
545 # NKI-AVL Amsterdam
546 # r.v.son@nki.nl
547 # Institute of Phonetic Sciences & IFOTT/ACLS
548 # University of Amsterdam
549 # Email: R.J.J.H.vanSon@gmail.com
550 # Email: R.J.J.H.vanSon@uva.nl
551 # WWW : http://www.fon.hum.uva.nl/rob/
553 # License for use and disclaimers
555 # CGIscriptor merges plain ASCII HTML files transparantly
556 # with CGI variables, in-line PERL code, shell commands,
557 # and executable scripts in other scripting languages.
559 # This program is free software; you can redistribute it and/or
560 # modify it under the terms of the GNU General Public License
561 # as published by the Free Software Foundation; either version 2
562 # of the License, or (at your option) any later version.
564 # This program is distributed in the hope that it will be useful,
565 # but WITHOUT ANY WARRANTY; without even the implied warranty of
566 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
567 # GNU General Public License for more details.
569 # You should have received a copy of the GNU General Public License
570 # along with this program; if not, write to the Free Software
571 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
574 # Contributors:
575 # Rob van Son (R.J.J.H.vanSon@uva.nl)
576 # Gerd Franke franke@roo.de (designed the <DIV> behaviour)
578 #######################################################
579 ENDOFPREHELPTEXT2
581 #######################################################>>>>>>>>>>Start Remove
583 # You can skip the following code, it is an auto-splice
584 # procedure.
586 # Construct a slimmed down version of CGIscriptor
587 # (i.e., CGIscriptor.pl -slim > slimCGIscriptor.pl)
589 if($TrimDownCGIscriptor)
591 open(CGISCRIPTOR, "<CGIscriptor.pl")
592 || dieHandler(1, "<CGIscriptor.pl not slimmed down: $!\n");
593 my $SKIPtext = 0;
594 my $SKIPComments = 0;
596 while(<CGISCRIPTOR>)
598 my $SKIPline = 0;
600 ++$LineCount;
602 # Start of SKIP text
603 $SKIPtext = 1 if /[\>]{10}Start Remove/;
604 $SKIPComments = 1 if $SKIPtext == 1;
606 # Skip this line?
607 $SKIPline = 1 if $SKIPtext || ($SKIPComments && /^\s*\#/);
609 ++$PrintCount unless $SKIPline;
611 print STDOUT $_ unless $SKIPline;
613 # End of SKIP text ?
614 $SKIPtext = 0 if /[\<]{10}End Remove/;
616 # Ready!
617 print STDERR "\# Printed $PrintCount out of $LineCount lines\n";
618 exit;
621 #######################################################
623 if(grep(/\-\-help/i, @ARGV))
625 print << 'ENDOFHELPTEXT';
627 # HYPE
629 # CGIscriptor merges plain ASCII HTML files transparantly and safely
630 # with CGI variables, in-line PERL code, shell commands, and executable
631 # scripts in many languages (on-line and real-time). It combines the
632 # "ease of use" of HTML files with the versatillity of specialized
633 # scripts and PERL programs. It hides all the specifics and
634 # idiosyncrasies of correct output and CGI coding and naming. Scripts
635 # do not have to be aware of HTML, HTTP, or CGI conventions just as HTML
636 # files can be ignorant of scripts and the associated values. CGIscriptor
637 # complies with the W3C HTML 4.0 recommendations.
638 # In addition to its use as a WWW embeded CGI processor, it can
639 # be used as a command-line document preprocessor (text-filter).
641 # THIS IS HOW IT WORKS
643 # The aim of CGIscriptor is to execute "plain" scripts inside a text file
644 # using any required CGIparameters and environment variables. It
645 # is optimized to transparantly process HTML files inside a WWW server.
646 # The native language is Perl, but many other scripting languages
647 # can be used.
649 # CGIscriptor reads text files from the requested input file (i.e., from
650 # $YOUR_HTML_FILES$PATH_INFO) and writes them to <STDOUT> (i.e., the
651 # client requesting the service) preceded by the obligatory
652 # "Content-type: text/html\n\n" or "Content-type: text/plain\n\n" string
653 # (except for "raw" files which supply their own Content-type message
654 # and only if the SERVER_PROTOCOL supports HTTP, MAIL, or MIME).
656 # When CGIscriptor encounters an embedded script, indicated by an HTML4 tag
658 # <SCRIPT TYPE="text/ssperl" [CGI="$VAR='default value'"] [SRC="ScriptSource"]>
659 # PERL script
660 # </SCRIPT>
662 # or
664 # <SCRIPT TYPE="text/osshell" [CGI="$name='default value'"] [SRC="ScriptSource"]>
665 # OS Shell script
666 # </SCRIPT>
668 # construct (anything between []-brackets is optional, other MIME-types
669 # and scripting languages are supported), the embedded script is removed
670 # and both the contents of the source file (i.e., "do 'ScriptSource'")
671 # AND the script are evaluated as a PERL program (i.e., by eval()),
672 # shell script (i.e., by a "safe" version of `Command`, qx) or an external
673 # interpreter. The output of the eval() function takes the place of the
674 # original <SCRIPT></SCRIPT> construct in the output string. Any CGI
675 # parameters declared by the CGI attribute are available as simple perl
676 # variables, and can subsequently be made available as variables to other
677 # scripting languages (e.g., bash, python, or lisp).
679 # Example: printing "Hello World"
680 # <HTML><HEAD><TITLE>Hello World</TITLE>
681 # <BODY>
682 # <H1><SCRIPT TYPE="text/ssperl">"Hello World"</SCRIPT></H1>
683 # </BODY></HTML>
685 # Save this in a file, hello.html, in the directory you indicated with
686 # $YOUR_HTML_FILES and access http://your_server/SHTML/hello.html
687 # (or to whatever name you use as an alias for CGIscriptor.pl).
688 # This is realy ALL you need to do to get going.
690 # You can use any values that are delivered in CGI-compliant form (i.e.,
691 # the "?name=value" type URL additions) transparently as "$name" variables
692 # in your scripts IFF you have declared them in the CGI attribute of
693 # a META or SCRIPT tag before e.g.:
694 # <META CONTENT="text/ssperl; CGI='$name = `default value`'
695 # [SRC='ScriptSource']">
696 # or
697 # <SCRIPT TYPE="text/ssperl" CGI="$name = 'default value'"
698 # [SRC='ScriptSource']>
699 # After such a 'CGI' attribute, you can use $name as an ordinary PERL variable
700 # (the ScriptSource file is immediately evaluated with "do 'ScriptSource'").
701 # The CGIscriptor script allows you to write ordinary HTML files which will
702 # include dynamic CGI aware (run time) features, such as on-line answers
703 # to specific CGI requests, queries, or the results of calculations.
705 # For example, if you wanted to answer questions of clients, you could write
706 # a Perl program called "Answer.pl" with a function "AnswerQuestion()"
707 # that prints out the answer to requests given as arguments. You then write
708 # an HTML page "Respond.html" containing the following fragment:
710 # <center>
711 # The Answer to your question
712 # <META CONTENT="text/ssperl; CGI='$Question'">
713 # <h3><SCRIPT TYPE="text/ssperl">$Question</SCRIPT></h3>
714 # is
715 # <h3><SCRIPT TYPE="text/ssperl" SRC="./PATH/Answer.pl">
716 # AnswerQuestion($Question);
717 # </SCRIPT></h3>
718 # </center>
719 # <FORM ACTION=Respond.html METHOD=GET>
720 # Next question: <INPUT NAME="Question" TYPE=TEXT SIZE=40><br>
721 # <INPUT TYPE=SUBMIT VALUE="Ask">
722 # </FORM>
724 # The output could look like the following (in HTML-speak):
726 # <CENTER>
727 # The Answer to your question
728 # <h3>What is the capital of the Netherlands?</h3>
729 # is
730 # <h3>Amsterdam</h3>
731 # </CENTER>
732 # <FORM ACTION=Respond.html METHOD=GET>
733 # Next question: <INPUT NAME="Question" TYPE=TEXT SIZE=40><br>
734 # <INPUT TYPE=SUBMIT VALUE="Ask">
736 # Note that the function "Answer.pl" does know nothing about CGI or HTML,
737 # it just prints out answers to arguments. Likewise, the text has no
738 # provisions for scripts or CGI like constructs. Also, it is completely
739 # trivial to extend this "program" to use the "Answer" later in the page
740 # to call up other information or pictures/sounds. The final text never
741 # shows any cue as to what the original "source" looked like, i.e.,
742 # where you store your scripts and how they are called.
744 # There are some extra's. The argument of the files called in a SRC= tag
745 # can access the CGI variables declared in the preceding META tag from
746 # the @ARGV array. Executable files are called as:
747 # `file '$ARGV[0]' ... ` (e.g., `Answer.pl \'$Question\'`;)
748 # The files called from SRC can even be (CGIscriptor) html files which are
749 # processed in-line. Furthermore, the SRC= tag can contain a perl block
750 # that is evaluated. That is,
751 # <META CONTENT="text/ssperl; CGI='$Question' SRC='{$Question}'">
752 # will result in the evaluation of "print do {$Question};" and the VALUE
753 # of $Question will be printed. Note that these "SRC-blocks" can be
754 # preceded and followed by other file names, but only a single block is
755 # allowed in a SRC= tag.
757 # One of the major hassles of dynamic WWW pages is the fact that several
758 # mutually incompatible browsers and platforms must be supported. For example,
759 # the way sound is played automatically is different for Netscape and
760 # Internet Explorer, and for each browser it is different again on
761 # Unix, MacOS, and Windows. Realy dangerous is processing user-supplied
762 # (form-) values to construct email addresses, file names, or database
763 # queries. All Apache WWW-server exploits reported in the media are
764 # based on faulty CGI-scripts that didn't check their user-data properly.
766 # There is no panacee for these problems, but a lot of work and problems
767 # can be saved by allowing easy and transparent control over which
768 # <SCRIPT></SCRIPT> blocks are executed on what CGI-data. CGIscriptor
769 # supplies such a method in the form of a pair of attributes:
770 # IF='...condition..' and UNLESS='...condition...'. When added to a
771 # script tag, the whole block (including the SRC attribute) will be
772 # ignored if the condition is false (IF) or true (UNLESS).
773 # For example, the following block will NOT be evaluated if the value
774 # of the CGI variable FILENAME is NOT a valid filename:
776 # <SCRIPT TYPE='text/ssperl' CGI='$FILENAME'
777 # IF='CGIscriptor::CGIsafeFileName($FILENAME)'>
778 # .....
779 # </SCRIPT>
781 # (the function CGIsafeFileName(String) returns an empty string ("")
782 # if the String argument is not a valid filename).
783 # The UNLESS attribute is the mirror image of IF.
785 # A user manual follows the HTML 4 and security paragraphs below.
787 ##########################################################################
789 # HTML 4 compliance
791 # In general, CGIscriptor.pl complies with the HTML 4 recommendations of
792 # the W3C. This means that any software to manage Web sites will be able
793 # to handle CGIscriptor files, as will web agents.
795 # All script code should be placed between <SCRIPT></SCRIPT> tags, the
796 # script type is indicated with TYPE="mime-type", the LANGUAGE
797 # feature is ignored, and a SRC feature is implemented. All CGI specific
798 # features are delegated to the CGI attribute.
800 # However, the behavior deviates from the W3C recommendations at some
801 # points. Most notably:
802 # 0- The scripts are executed at the server side, invissible to the
803 # client (i.e., the browser)
804 # 1- The mime-types are personal and idiosyncratic, but can be adapted.
805 # 2- Code in the body of a <SCRIPT></SCRIPT> tag-pair is still evaluated
806 # when a SRC feature is present.
807 # 3- The SRC attribute reads a list of files.
808 # 4- The files in a SRC attribute are processed according to file type.
809 # 5- The SRC attribute evaluates inline Perl code.
810 # 6- Processed META, DIV, INS tags are removed from the output
811 # document.
812 # 7- All attributes of the processed META tags, except CONTENT, are ignored
813 # (i.e., deleted from the output).
814 # 8- META tags can be placed ANYWHERE in the document.
815 # 9- Through the SRC feature, META tags can have visible output in the
816 # document.
817 # 10- The CGI attribute that declares CGI parameters, can be used
818 # inside the <SCRIPT> tag.
819 # 11- Use of an extended quote set, i.e., '', "", ``, (), {}, []
820 # and their \-slashed combinations: \'\', \"\", \`\`, \(\),
821 # \{\}, \[\].
822 # 12- IF and UNLESS attributes to <SCRIPT>, <META>, <DIV>, <INS> tags.
823 # 13- <DIV> tags cannot be nested, DIV tags are not
824 # rendered with new-lines.
825 # 14- The XML style <TAG .... /> is recognized and handled correctly.
826 # (i.e., no content is processed)
828 # The reasons for these choices are:
829 # You can still write completely HTML4 compliant documents. CGIscriptor
830 # will not force you to write "deviant" code. However, it allows you to
831 # do so (which is, in fact, just as bad). The prime design principle
832 # was to allow users to include plain Perl code. The code itself should
833 # be "enhancement free". Therefore, extra features were needed to
834 # supply easy access to CGI and Web site components. For security
835 # reasons these have to be declared explicitly. The SRC feature
836 # transparently manages access to external files, especially the safe
837 # use of executable files.
838 # The CGI attribute handles the declarations of external (CGI) variables
839 # in the SCRIPT and META tag's.
840 # EVERYTHING THE CGI ATTRIBUTE AND THE META TAG DO CAN BE DONE INSIDE
841 # A <SCRIPT></SCRIPT> TAG CONSTRUCT.
843 # The reason for the IF, UNLESS, and SRC attributes (and their Perl code
844 # evaluation) were build into the META and SCRIPT tags is part laziness,
845 # part security. The SRC blocks allows more compact documents and easier
846 # debugging. The values of the CGI variables can be immediately screened
847 # for security by IF or UNLESS conditions, and even SRC attributes (e.g.,
848 # email addresses and file names), and a few commands can be called
849 # without having to add another Perl TAG pair. This is especially important
850 # for documents that require the use of other (more restricted) "scripting"
851 # languages and facilities that lag transparent control structures.
853 ##########################################################################
855 # SECURITY
857 # Your WWW site is a few keystrokes away from a few hundred million internet
858 # users. A fair percentage of these users knows more about your computer
859 # than you do. And some of these just might have bad intentions.
861 # To ensure uncompromized operation of your server and platform, several
862 # features are incorporated in CGIscriptor.pl to enhance security.
863 # First of all, you should check the source of this program. No security
864 # measures will help you when you download programs from anonymous sources.
865 # If you want to use THIS file, please make sure that it is uncompromized.
866 # The best way to do this is to contact the source and try to determine
867 # whether s/he is reliable (and accountable).
869 # BE AWARE THAT ANY PROGRAMMER CAN CHANGE THIS PROGRAM IN SUCH A WAY THAT
870 # IT WILL SET THE DOORS TO YOUR SYSTEM WIDE OPEN
872 # I would like to ask any user who finds bugs that could compromise
873 # security to report them to me (and any other bug too,
874 # Email: R.J.J.H.vanSon@uva.nl or ifa@hum.uva.nl).
876 # Security features
878 # 1 Invisibility
879 # The inner workings of the HTML source files are completely hidden
880 # from the client. Only the HTTP header and the ever changing content
881 # of the output distinguish it from the output of a plain, fixed HTML
882 # file. Names, structures, and arguments of the "embedded" scripts
883 # are invisible to the client. Error output is suppressed except
884 # during debugging (user configurable).
886 # 2 Separate directory trees
887 # Directories containing Inline text and script files can reside on
888 # separate trees, distinct from those of the HTTP server. This means
889 # that NEITHER the text files, NOR the script files can be read by
890 # clients other than through CGIscriptor.pl, UNLESS they are
891 # EXPLICITELY made available.
893 # 3 Requests are NEVER "evaluated"
894 # All client supplied values are used as literal values (''-quoted).
895 # Client supplied ''-quotes are ALWAYS removed. Therefore, as long as the
896 # embedded scripts do NOT themselves evaluate these values, clients CANNOT
897 # supply executable commands. Be sure to AVOID scripts like:
899 # <META CONTENT="text/ssperl; CGI='$UserValue'">
900 # <SCRIPT TYPE="text/ssperl">$dir = `ls -1 $UserValue`;</SCRIPT>
902 # These are a recipe for disaster. However, the following quoted
903 # form should be save (but is still not adviced):
905 # <SCRIPT TYPE="text/ssperl">$dir = `ls -1 \'$UserValue\'`;</SCRIPT>
907 # A special function, SAFEqx(), will automatically do exactly this,
908 # e.g., SAFEqx('ls -1 $UserValue') will execute `ls -1 \'$UserValue\'`
909 # with $UserValue interpolated. I recommend to use SAFEqx() instead
910 # of backticks whenever you can. The OS shell scripts inside
912 # <SCRIPT TYPE="text/osshell">ls -1 $UserValue</SCRIPT>
914 # are handeld by SAFEqx and automatically ''-quoted.
916 # 4 Logging of requests
917 # All requests can be logged separate from the Host server. The level of
918 # detail is user configurable: Including or excluding the actual queries.
919 # This allows for the inspection of (im-) proper use.
921 # 5 Access control: Clients
922 # The Remote addresses can be checked against a list of authorized
923 # (i.e., accepted) or non-authorized (i.e., rejected) clients. Both
924 # REMOTE_HOST and REMOTE_ADDR are tested so clients without a proper
925 # HOST name can be (in-) excluded by their IP-address. Client patterns
926 # containing all numbers and dots are considered IP-addresses, all others
927 # domain names. No wild-cards or regexp's are allowed, only partial
928 # addresses.
929 # Matching of names is done from the back to the front (domain first,
930 # i.e., $REMOTE_HOST =~ /\Q$pattern\E$/is), so including ".edu" will
931 # accept or reject all clients from the domain EDU. Matching of
932 # IP-addresses is done from the front to the back (domain first, i.e.,
933 # $REMOTE_ADDR =~ /^\Q$pattern\E/is), so including "128." will (in-)
934 # exclude all clients whose IP-address starts with 128.
935 # There are two special symbols: "-" matches HOSTs with no name and "*"
936 # matches ALL HOSTS/clients.
937 # For those needing more expressional power, lines starting with
938 # "-e" are evaluated by the perl eval() function. E.g.,
939 # '-e $REMOTE_HOST =~ /\.edu$/is;' will accept/reject clients from the
940 # domain '.edu'.
942 # 6 Access control: Files
943 # In principle, CGIscriptor could read ANY file in the directory
944 # tree as discussed in 1. However, for security reasons this is
945 # restricted to text files. It can be made more restricted by entering
946 # a global file pattern (e.g., ".html"). This is done by default.
947 # For each client requesting access, the file pattern(s) can be made
948 # more restrictive than the global pattern by entering client specific
949 # file patterns in the Access Control files (see 5).
950 # For example: if the ACCEPT file contained the lines
951 # * DEMO
952 # .hum.uva.nl LET
953 # 145.18.230.
954 # Then all clients could request paths containing "DEMO" or "demo", e.g.
955 # "/my/demo/file.html" ($PATH_INFO =~ /\Q$pattern\E/), Clients from
956 # *.hum.uva.nl could also request paths containing "LET or "let", e.g.
957 # "/my/let/file.html", and clients from the local cluster
958 # 145.18.230.[0-9]+ could access ALL files.
959 # Again, for those needing more expressional power, lines starting with
960 # "-e" are evaluated. For instance:
961 # '-e $REMOTE_HOST =~ /\.edu$/is && $PATH_INFO =~ m@/DEMO/@is;'
962 # will accept/reject requests for files from the directory "/demo/" from
963 # clients from the domain '.edu'.
965 # 7 Access control: Server side session tickets
966 # Specific paths can be controlled by Session Tickets which must be
967 # present as a SESSIONTICKET=<value> CGI variable in the request. These paths
968 # are defined in %TicketRequiredPatterns as pairs of:
969 # ('regexp' => 'SessionPath\tPasswordPath\tLogin.html\tExpiration').
970 # Session Tickets are stored in a separate directory (SessionPath, e.g.,
971 # "Private/.Session") as files with the exact same name of the SESSIONTICKET
972 # CGI. The following is an example:
973 # Type: SESSION
974 # IPaddress: 127.0.0.1
975 # AllowedPaths: ^/Private/Name/
976 # Expires: 3600
977 # Username: test
978 # ...
979 # Other content can follow.
981 # It is adviced that Session Tickets should be deleted
982 # after some (idle) time. The IP address should be the IP number at login, and
983 # the SESSIONTICKET will be rejected if it is presented from another IP address.
984 # AllowedPaths is a perl regexp. Be careful how they match. Make sure to delimit
985 # the names to prevent access to overlapping names, eg, "^/Private/Rob" will also
986 # match "^/Private/Robert", however, "^/Private/Rob/" will not. Expires is the
987 # time the ticket will remain valid after creation (file ctime). Time can be given
988 # in s[econds] (default), m[inutes], h[hours], or d[ays], eg, "24h" means 24 hours.
989 # None of these need be present, but the Ticket must have a non-zero size.
991 # Next to Session Tickets, there are two other type of ticket files:
992 # - LOGIN tickets store information about a current login request
993 # - PASSWORD ticket store account information to authorize login requests
995 # 8 Query length limiting
996 # The length of the Query string can be limited. If CONTENT_LENGTH is larger
997 # than this limit, the request is rejected. The combined length of the
998 # Query string and the POST input is checked before any processing is done.
999 # This will prevent clients from overloading the scripts.
1000 # The actual, combined, Query Size is accessible as a variable through
1001 # $CGI_Content_Length.
1003 # 9 Illegal filenames, paths, and protected directories
1004 # One of the primary security concerns in handling CGI-scripts is the
1005 # use of "funny" characters in the requests that con scripts in executing
1006 # malicious commands. Examples are inserting ';', null bytes, or <newline>
1007 # characters in URL's and filenames, followed by executable commands. A
1008 # special variable $FileAllowedChars stores a string of all allowed
1009 # characters. Any request that translates to a filename with a character
1010 # OUTSIDE this set will be rejected.
1011 # In general, all (readable files) in the DocumentRoot tree are accessible.
1012 # This might not be what you want. For instance, your DocumentRoot directory
1013 # might be the working directory of a CVS project and contain sensitive
1014 # information (e.g., the password to get to the repository). You can block
1015 # access to these subdirectories by adding the corresponding patterns to
1016 # the $BlockPathAccess variable. For instance, $BlockPathAccess = '/CVS/'
1017 # will block any request that contains '/CVS/' or:
1018 # die if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@;
1020 #10 The execution of code blocks can be controlled in a transparent way
1021 # by adding IF or UNLESS conditions in the tags themselves. That is,
1022 # a simple check of the validity of filenames or email addresses can
1023 # be done before any code is executed.
1025 ###############################################################################
1027 # USER MANUAL (sort of)
1029 # CGIscriptor removes embedded scripts, indicated by an HTML 4 type
1030 # <SCRIPT TYPE='text/ssperl'> </SCRIPT> or <SCRIPT TYPE='text/osshell'>
1031 # </SCRIPT> constructs. CGIscriptor also recognizes XML-type
1032 # <SCRIPT TYPE='text/ssperl'/> constructs. These are usefull when
1033 # the necessary code is already available in the TAG itself (e.g.,
1034 # using external files). The contents of the directive are executed by
1035 # the PERL eval() and `` functions (in a separate name space). The
1036 # result of the eval() function replaces the <SCRIPT> </SCRIPT> construct
1037 # in the output file. You can use the values that are delivered in
1038 # CGI-compliant form (i.e., the "?name=value&.." type URL additions)
1039 # transparently as "$name" variables in your directives after they are
1040 # defined in a <META> or <SCRIPT> tag.
1041 # If you define the variable "$CGIscriptorResults" in a CGI attribute, all
1042 # subsequent <SCRIPT> and <META> results (including the defining
1043 # tag) will also be pushed onto a stack: @CGIscriptorResults. This list
1044 # behaves like any other, ordinary list and can be manipulated.
1046 # Both GET and POST requests are accepted. These two methods are treated
1047 # equal. Variables, i.e., those values that are determined when a file is
1048 # processed, are indicated in the CGI attribute by $<name> or $<name>=<default>
1049 # in which <name> is the name of the variable and <default> is the value
1050 # used when there is NO current CGI value for <name> (you can use
1051 # white-spaces in $<name>=<default> but really DO make sure that the
1052 # default value is followed by white space or is quoted). Names can contain
1053 # any alphanumeric characters and _ (i.e., names match /[\w]+/).
1054 # If the Content-type: is 'multipart/*', the input is treated as a
1055 # MIME multipart message and automatically delimited. CGI variables get
1056 # the "raw" (i.e., undecoded) body of the corresponding message part.
1058 # Variables can be CGI variables, i.e., those from the QUERY_STRING,
1059 # environment variables, e.g., REMOTE_USER, REMOTE_HOST, or REMOTE_ADDR,
1060 # or predefined values, e.g., CGI_Decoded_QS (The complete, decoded,
1061 # query string), CGI_Content_Length (the length of the decoded query
1062 # string), CGI_Year, CGI_Month, CGI_Time, and CGI_Hour (the current
1063 # date and time).
1065 # All these are available when defined in a CGI attribute. All environment
1066 # variables are accessible as $ENV{'name'}. So, to access the REMOTE_HOST
1067 # and the REMOTE_USER, use, e.g.:
1069 # <SCRIPT TYPE='text/ssperl'>
1070 # ($ENV{'REMOTE_HOST'}||"-")." $ENV{'REMOTE_USER'}"
1071 # </SCRIPT>
1073 # (This will print a "-" if REMOTE_HOST is not known)
1074 # Another way to do this is:
1076 # <META CONTENT="text/ssperl; CGI='$REMOTE_HOST = - $REMOTE_USER'">
1077 # <SCRIPT TYPE='text/ssperl'>"$REMOTE_HOST $REMOTE_USER"</SCRIPT>
1078 # or
1079 # <META CONTENT='text/ssperl; CGI="$REMOTE_HOST = - $REMOTE_USER"
1080 # SRC={"$REMOTE_HOST $REMOTE_USER\n"}'>
1082 # This is possible because ALL environment variables are available as
1083 # CGI variables. The environment variables take precedence over CGI
1084 # names in case of a "name clash". For instance:
1085 # <META CONTENT="text/ssperl; CGI='$HOME' SRC={$HOME}">
1086 # Will print the current HOME directory (environment) irrespective whether
1087 # there is a CGI variable from the query
1088 # (e.g., Where do you live? <INPUT TYPE="TEXT" NAME="HOME">)
1089 # THIS IS A SECURITY FEATURE. It prevents clients from changing
1090 # the values of defined environment variables (e.g., by supplying
1091 # a bogus $REMOTE_ADDR). Although $ENV{} is not changed by the META tags,
1092 # it would make the use of declared variables insecure. You can still
1093 # access CGI variables after a name clash with
1094 # CGIscriptor::CGIparseValue(<name>).
1096 # Some CGI variables are present several times in the query string
1097 # (e.g., from multiple selections). These should be defined as
1098 # @VARIABLENAME=default in the CGI attribute. The list @VARIABLENAME
1099 # will contain ALL VARIABLENAME values from the query, or a single
1100 # default value. If there is an ENVIRONMENT variable of the
1101 # same name, it will be used instead of the default AND the query
1102 # values. The corresponding function is
1103 # CGIscriptor::CGIparseValueList(<name>)
1105 # CGI variables collected in a @VARIABLENAME list are unordered.
1106 # When more structured variables are needed, a hash table can be used.
1107 # A variable defined as %VARIABLE=default will collect all
1108 # CGI-parameters whose name start with 'VARIABLE' in a hash table with
1109 # the remainder of the name as a key. For instance, %PERSON will
1110 # collect PERSONname='John Doe', PERSONbirthdate='01 Jan 00', and
1111 # PERSONspouse='Alice' into a hash table %PERSON such that $PERSON{'spouse'}
1112 # equals 'Alice'. Any default value or environment value will be stored
1113 # under the "" key. If there is an ENVIRONMENT variable of the same name,
1114 # it will be used instead of the default AND the query values. The
1115 # corresponding function is CGIscriptor::CGIparseValueHash(<name>)
1117 # This method of first declaring your environment and CGI variables
1118 # before being able to use them in the scripts might seem somewhat
1119 # clumsy, but it protects you from inadvertedly printing out the values of
1120 # system environment variables when their names coincide with those used
1121 # in the CGI forms. It also prevents "clients" from supplying CGI
1122 # parameter values for your private variables.
1123 # THIS IS A SECURITY FEATURE!
1126 # NON-HTML CONTENT TYPES
1128 # Normally, CGIscriptor prints the standard "Content-type: text/html\n\n"
1129 # message before anything is printed. This has been extended to include
1130 # plain text (.txt) files, for which the Content-type (MIME type)
1131 # 'text/plain' is printed. In all other respects, text files are treated
1132 # as HTML files (this can be switched off by removing '.txt' from the
1133 # $FilePattern variable) . When the content type should be something else,
1134 # e.g., with multipart files, use the $RawFilePattern (.xmr, see also next
1135 # item). CGIscriptor will not print a Content-type message for this file
1136 # type (which must supply its OWN Content-type message). Raw files must
1137 # still conform to the <SCRIPT></SCRIPT> and <META> tag specifications.
1140 # NON-HTML FILES
1142 # CGIscriptor is intended to process HTML and text files only. You can
1143 # create documents of any mime-type on-the-fly using "raw" text files,
1144 # e.g., with the .xmr extension. However, CGIscriptor will not process
1145 # binary files of any type, e.g., pictures or sounds. Given the sheer
1146 # number of formats, I do not have any intention to do so. However,
1147 # an escape route has been provided. You can construct a genuine raw
1148 # (.xmr) text file that contains the perl code to service any file type
1149 # you want. If the global $BinaryMapFile variable contains the path to
1150 # this file (e.g., /BinaryMapFile.xmr), this file will be called
1151 # whenever an unsupported (non-HTML) file type is requested. The path
1152 # to the requested binary file is stored in $ENV('CGI_BINARY_FILE')
1153 # and can be used like any other CGI-variable. Servicing binary files
1154 # then becomes supplying the correct Content-type (e.g., print
1155 # "Content-type: image/jpeg\n\n";) and reading the file and writing it
1156 # to STDOUT (e.g., using sysread() and syswrite()).
1159 # THE META TAG
1161 # All attributes of a META tag are ignored, except the
1162 # CONTENT='text/ssperl; CGI=" ... " [SRC=" ... "]' attribute. The string
1163 # inside the quotes following the CONTENT= indication (white-space is
1164 # ignored, "" '' `` (){}[]-quote pairs are allowed, plus their \ versions)
1165 # MUST start with any of the CGIscriptor mime-types (e.g.: text/ssperl or
1166 # text/osshell) and a comma or semicolon.
1167 # The quoted string following CGI= contains a white-space separated list
1168 # of declarations of the CGI (and Environment) values and default values
1169 # used when no CGI values are supplied by the query string.
1171 # If the default value is a longer string containing special characters,
1172 # possibly spanning several lines, the string must be enclosed in quotes.
1173 # You may use any pair of quotes or brackets from the list '', "", ``, (),
1174 # [], or {} to distinguish default values (or preceded by \, e.g., \(...\)
1175 # is different from (...)). The outermost pair will always be used and any
1176 # other quotes inside the string are considered to be part of the string
1177 # value, e.g.,
1179 # $Value = {['this'
1180 # "and" (this)]}
1181 # will result in $Value getting the default value: ['this'
1182 # "and" (this)]
1183 # (NOTE that the newline is part of the default value!).
1185 # Internally, for defining and initializing CGI (ENV) values, the META
1186 # and SCRIPT tags use the functions "defineCGIvariable($name, $default)"
1187 # (scalars) and "defineCGIvariableList($name, $default)" (lists).
1188 # These functions can be used inside scripts as
1189 # "CGIscriptor::defineCGIvariable($name, $default)" and
1190 # "CGIscriptor::defineCGIvariableList($name, $default)".
1191 # "CGIscriptor::defineCGIvariableHash($name, $default)".
1193 # The CGI attribute will be processed exactly identical when used inside
1194 # the <SCRIPT> tag. However, this use is not according to the
1195 # HTML 4.0 specifications of the W3C.
1198 # THE DIV/INS TAGS
1200 # There is a problem when constructing html files containing
1201 # server-side perl scripts with standard HTML tools. These
1202 # tools will refuse to process any text between <SCRIPT></SCRIPT>
1203 # tags. This is quite annoying when you want to use large
1204 # HTML templates where you will fill in values.
1206 # For this purpose, CGIscriptor will read the neutral
1207 # <DIV CLASS="ssperl" ID="varname"></DIV> or
1208 # <INS CLASS="ssperl" ID="varname"></INS>
1209 # tag (in Cascading Style Sheet manner) Note that
1210 # "varname" has NO '$' before it, it is a bare name.
1211 # Any text between these <DIV ...></DIV> or
1212 # <INS ...></INS>tags will be assigned to '$varname'
1213 # as is (e.g., as a literal).
1214 # No processing or interpolation will be performed.
1215 # There is also NO nesting possible. Do NOT nest a
1216 # </DIV> inside a <DIV></DIV>! Moreover, neither INS nor
1217 # DIV tags do ensure a block structure in the final
1218 # rendering (i.e., no empty lines).
1220 # Note that <DIV CLASS="ssperl" ID="varname"/>
1221 # is handled the XML way. No content is processed,
1222 # but varname is defined, and any SRC directives are
1223 # processed.
1225 # You can use $varname like any other variable name.
1226 # However, $varname is NOT a CGI variable and will be
1227 # completely internal to your script. There is NO
1228 # interaction between $varname and the outside world.
1230 # To interpolate a DIV derived text, you can use:
1231 # $varname =~ s/([\]])/\\\1/g; # Mark ']'-quotes
1232 # $varname = eval("qq[$varname]"); # Interpolate all values
1234 # The DIV tags will process IF, UNLESS, CGI and
1235 # SRC attributes. The SRC files will be pre-pended to the
1236 # body text of the tag. SRC blocks are NOT executed.
1238 # CONDITIONAL PROCESSING: THE 'IF' AND 'UNLESS' ATTRIBUTES
1240 # It is often necessary to include code-blocks that should be executed
1241 # conditionally, e.g., only for certain browsers or operating system.
1242 # Furthermore, quite often sanity and security checks are necessary
1243 # before user (form) data can be processed, e.g., with respect to
1244 # email addresses and filenames.
1246 # Checks added to the code are often difficult to find, interpret or
1247 # maintain and in general mess up the code flow. This kind of confussion
1248 # is dangerous.
1249 # Also, for many of the supported "foreign" scripting languages, adding
1250 # these checks is cumbersome or even impossible.
1252 # As a uniform method for asserting the correctness of "context", two
1253 # attributes are added to all supported tags: IF and UNLESS.
1254 # They both evaluate their value and block execution when the
1255 # result is <FALSE> (IF) or <TRUE> (UNLESS) in Perl, e.g.,
1256 # UNLESS='$NUMBER \> 100;' blocks execution if $NUMBER <= 100. Note that
1257 # the backslash in the '\>' is removed and only used to differentiate
1258 # this conditional '>' from the tag-closing '>'. For symmetry, the
1259 # backslash in '\<' is also removed. Inside these conditionals,
1260 # ~/ and ./ are expanded to their respective directory root paths.
1262 # For example, the following tag will be ignored when the filename is
1263 # invalid:
1265 # <SCRIPT TYPE='text/ssperl' CGI='$FILENAME'
1266 # IF='CGIscriptor::CGIsafeFileName($FILENAME);'>
1267 # ...
1268 # </SCRIPT>
1270 # The IF and UNLESS values must be quoted. The same quotes are supported
1271 # as with the other attributes. The SRC attribute is ignored when IF and
1272 # UNLESS block execution.
1274 # NOTE: 'IF' and 'UNLESS' always evaluate perl code.
1277 # THE MAGIC SOURCE ATTRIBUTE (SRC=)
1279 # The SRC attribute inside tags accepts a list of filenames and URL's
1280 # separated by "," comma's (or ";" semicolons).
1281 # ALL the variable values defined in the CGI attribute are available
1282 # in @ARGV as if the file or block was executed from the command line,
1283 # in the exact order in which they were declared in the preceding CGI
1284 # attribute.
1286 # First, a SRC={}-block will be evaluated as if the code inside the
1287 # block was part of a <SCRIPT></SCRIPT> construct, i.e.,
1288 # "print do { code };'';" or `code` (i.e., SAFEqx('code)).
1289 # Only a single block is evaluated. Note that this is processed less
1290 # efficiently than <SCRIPT> </SCRIPT> blocks. Type of evaluation
1291 # depends on the content-type: Perl for text/ssperl and OS shell for
1292 # text/osshell. For other mime types (scripting languages), anything in
1293 # the source block is put in front of the code block "inside" the tag.
1295 # Second, executable files (i.e., -x filename != 0) are evaluated as:
1296 # print `filename \'$ARGV[0]\' \'$ARGV[1]\' ...`
1297 # That is, you can actually call executables savely from the SRC tag.
1299 # Third, text files that match the file pattern, used by CGIscriptor to
1300 # check whether files should be processed ($FilePattern), are
1301 # processed in-line (i.e., recursively) by CGIscriptor as if the code
1302 # was inserted in the original source file. Recursions, i.e., calling
1303 # a file inside itself, are blocked. If you need them, you have to code
1304 # them explicitely using "main::ProcessFile($file_path)".
1306 # Fourth, Perl text files (i.e., -T filename != 0) are evaluated as:
1307 # "do FileName;'';".
1309 # Last, URL's (i.e., starting with 'HTTP://', 'FTP://', 'GOPHER://',
1310 # 'TELNET://', 'WHOIS://' etc.) are loaded
1311 # and printed. The loading and handling of <BASE> and document header
1312 # is done by a command generated by main::GET_URL($URL [, 0]). You can enter your
1313 # own code (default is curl, wget, or snarf and some post-processing to add a <BASE> tag).
1315 # There are two pseudo-file names: PREFIX and POSTFIX. These implement
1316 # a switch from prefixing the SRC code/files (PREFIX, default) before the
1317 # content of the tag to appending the code after the content of the tag
1318 # (POSTFIX). The switches are done in the order in which the PREFIX and
1319 # POSTFIX labels are encountered. You can mix PREFIX and POSTFIX labels
1320 # in any order with the SRC files. Note that the ORDER of file execution
1321 # is determined for prefixed and postfixed files seperately.
1323 # File paths can be preceded by the URL protocol prefix "file://". This
1324 # is simply STRIPPED from the name.
1326 # Example:
1327 # The request
1328 # "http://cgi-bin/Action_Forms.pl/Statistics/Sign_Test.html?positive=8&negative=22
1329 # will result in printing "${SS_PUB}/Statistics/Sign_Test.html"
1330 # With QUERY_STRING = "positive=8&negative=22"
1332 # on encountering the lines:
1333 # <META CONTENT="text/osshell; CGI='$positive=11 $negative=3'">
1334 # <b><SCRIPT LANGUAGE=PERL TYPE="text/ssperl" SRC="./Statistics/SignTest.pl">
1335 # </SCRIPT></b><p>"
1337 # This line will be processed as:
1338 # "<b>`${SS_SCRIPT}/Statistics/SignTest.pl '8' '22'`</b><p>"
1340 # In which "${SS_SCRIPT}/Statistics/SignTest.pl" is an executable script,
1341 # This line will end up printed as:
1342 # "<b>p <= 0.0161</b><p>"
1344 # Note that the META tag itself will never be printed, and is invisible to
1345 # the outside world.
1347 # The SRC files in a DIV or INS tag will be added (pre-pended) to the body
1348 # of the <DIV></DIV> tag. Blocks are NOT executed! If you do not
1349 # need any content, you can use the <DIV...../> format.
1352 # THE CGISCRIPTOR ROOT DIRECTORIES ~/ AND ./
1354 # Inside <SCRIPT></SCRIPT> tags, filepaths starting
1355 # with "~/" are replaced by "$YOUR_HTML_FILES/", this way files in the
1356 # public directories can be accessed without direct reference to the
1357 # actual paths. Filepaths starting with "./" are replaced by
1358 # "$YOUR_SCRIPTS/" and this should only be used for scripts.
1360 # Note: this replacement can seriously affect Perl scripts. Watch
1361 # out for constructs like $a =~ s/aap\./noot./g, use
1362 # $a =~ s@aap\.@noot.@g instead.
1364 # CGIscriptor.pl will assign the values of $SS_PUB and $SS_SCRIPT
1365 # (i.e., $YOUR_HTML_FILES and $YOUR_SCRIPTS) to the environment variables
1366 # $SS_PUB and $SS_SCRIPT. These can be accessed by the scripts that are
1367 # executed.
1368 # Values not preceded by $, ~/, or ./ are used as literals
1371 # OS SHELL SCRIPT EVALUATION (CONTENT-TYPE=TEXT/OSSHELL)
1373 # OS scripts are executed by a "safe" version of the `` operator (i.e.,
1374 # SAFEqx(), see also below) and any output is printed. CGIscriptor will
1375 # interpolate the script and replace all user-supplied CGI-variables by
1376 # their ''-quoted values (actually, all variables defined in CGI attributes
1377 # are quoted). Other Perl variables are interpolated in a simple fasion,
1378 # i.e., $scalar by their value, @list by join(' ', @list), and %hash by
1379 # their name=value pairs. Complex references, e.g., @$variable, are all
1380 # evaluated in a scalar context. Quotes should be used with care.
1381 # NOTE: the results of the shell script evaluation will appear in the
1382 # @CGIscriptorResults stack just as any other result.
1383 # All occurrences of $@% that should NOT be interpolated must be
1384 # preceeded by a "\". Interpolation can be switched off completely by
1385 # setting $CGIscriptor::NoShellScriptInterpolation = 1
1386 # (set to 0 or undef to switch interpolation on again)
1387 # i.e.,
1388 # <SCRIPT TYPE="text/ssperl">
1389 # $CGIscriptor::NoShellScriptInterpolation = 1;
1390 # </SCRIPT>
1393 # RUN TIME TRANSLATION OF INPUT FILES
1395 # Allows general and global conversions of files using Regular Expressions.
1396 # Very handy (but costly) to rewrite legacy pages to a new format.
1397 # Select files to use it on with
1398 # my $TranslationPaths = 'filepattern';
1399 # This is costly. For efficiency, define:
1400 # $TranslationPaths = ''; when not using translations.
1401 # Accepts general regular expressions: [$pattern, $replacement]
1403 # Define:
1404 # my $TranslationPaths = 'filepattern'; # Pattern matching PATH_INFO
1406 # push(@TranslationTable, ['pattern', 'replacement']);
1407 # e.g. (for Ruby Rails):
1408 # push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
1409 # push(@TranslationTable, ['%>', '</SCRIPT>']);
1411 # Runs:
1412 # my $currentRegExp;
1413 # foreach $currentRegExp (@TranslationTable)
1415 # my ($pattern, $replacement) = @$currentRegExp;
1416 # $$text =~ s!$pattern!$replacement!msg;
1417 # };
1420 # EVALUATION OF OTHER SCRIPTING LANGUAGES
1422 # Adding a MIME-type and an interpreter command to
1423 # %ScriptingLanguages automatically will catch any other
1424 # scripting language in the standard
1425 # <SCRIPT TYPE="[mime]"></SCRIPT> manner.
1426 # E.g., adding: $ScriptingLanguages{'text/sspython'} = 'python';
1427 # will actually execute the folowing code in an HTML page
1428 # (ignore 'REMOTE_HOST' for the moment):
1429 # <SCRIPT TYPE="text/sspython">
1430 # # A Python script
1431 # x = ["A","real","python","script","Hello","World","and", REMOTE_HOST]
1432 # print x[4:8] # Prints the list ["Hello","World","and", REMOTE_HOST]
1433 # </SCRIPT>
1435 # The script code is NOT interpolated by perl, EXCEPT for those
1436 # interpreters that cannot handle variables themselves.
1437 # Currently, several interpreters are pre-installed:
1439 # Perl test - "text/testperl" => 'perl',
1440 # Python - "text/sspython" => 'python',
1441 # Ruby - "text/ssruby" => 'ruby',
1442 # Tcl - "text/sstcl" => 'tcl',
1443 # Awk - "text/ssawk" => 'awk -f-',
1444 # Gnu Lisp - "text/sslisp" => 'rep | tail +5 '.
1445 # "| egrep -v '> |^rep. |^nil\\\$'",
1446 # XLispstat - "text/xlispstat" => 'xlispstat | tail +7 '.
1447 # "| egrep -v '> \\\$|^NIL'",
1448 # Gnu Prolog- "text/ssprolog" => 'gprolog',
1449 # M4 macro's- "text/ssm4" => 'm4',
1450 # Born shell- "text/sh" => 'sh',
1451 # Bash - "text/bash" => 'bash',
1452 # C-shell - "text/csh" => 'csh',
1453 # Korn shell- "text/ksh" => 'ksh',
1454 # Praat - "text/sspraat" => "praat - | sed 's/Praat > //g'",
1455 # R - "text/ssr" => "R --vanilla --slave | sed 's/^[\[0-9\]*] //g'",
1456 # REBOL - "text/ssrebol" =>
1457 # "rebol --quiet|egrep -v '^[> ]* == '|sed 's/^\s*\[> \]* //g'",
1458 # PostgreSQL- "text/postgresql" => 'psql 2>/dev/null',
1459 # (psql)
1461 # Note that the "value" of $ScriptingLanguages{mime} must be a command
1462 # that reads Standard Input and writes to standard output. Any extra
1463 # output of interactive interpreters (banners, echo's, prompts)
1464 # should be removed by piping the output through 'tail', 'grep',
1465 # 'sed', or even 'awk' or 'perl'.
1467 # For access to CGI variables there is a special hashtable:
1468 # %ScriptingCGIvariables.
1469 # CGI variables can be accessed in three ways.
1470 # 1. If the mime type is not present in %ScriptingCGIvariables,
1471 # nothing is done and the script itself should parse the relevant
1472 # environment variables.
1473 # 2. If the mime type IS present in %ScriptingCGIvariables, but it's
1474 # value is empty, e.g., $ScriptingCGIvariables{"text/sspraat"} = '';,
1475 # the script text is interpolated by perl. That is, all $var, @array,
1476 # %hash, and \-slashes are replaced by their respective values.
1477 # 3. In all other cases, the CGI and environment variables are added
1478 # in front of the script according to the format stored in
1479 # %ScriptingCGIvariables. That is, the following (pseudo-)code is
1480 # executed for each CGI- or Environment variable defined in the CGI-tag:
1481 # printf(INTERPRETER, $ScriptingCGIvariables{$mime}, $CGI_NAME, $CGI_VALUE);
1483 # For instance, "text/testperl" => '$%s = "%s";' defines variable
1484 # definitions for Perl, and "text/sspython" => '%s = "%s"' for Python
1485 # (note that these definitions are not save, the real ones contain '-quotes).
1487 # THIS WILL NOT WORK FOR @VARIABLES, the (empty) $VARIABLES will be used
1488 # instead.
1490 # The $CGI_VALUE parameters are "shrubed" of all control characters
1491 # and quotes (by &shrubCGIparameter($CGI_VALUE)) for the options 2 and 3.
1492 # Control characters are replaced by \0<octal ascii value> (the exception
1493 # is \015, the newline, which is replaced by \n) and quotes
1494 # and backslashes by their HTML character
1495 # value (' -> &#39; ` -> &#96; " -> &quot; \ -> &#92; & -> &amper;).
1496 # For example:
1497 # if a client would supply the string value (in standard perl, e.g.,
1498 # \n means <newline>)
1499 # "/dev/null';\nrm -rf *;\necho '"
1500 # it would be processed as
1501 # '/dev/null&#39;;\nrm -rf *;\necho &#39;'
1502 # (e.g., sh or bash would process the latter more according to your
1503 # intentions).
1504 # If your intepreter requires different protection measures, you will
1505 # have to supply these in %main::SHRUBcharacterTR (string => translation),
1506 # e.g., $SHRUBcharacterTR{"\'"} = "&#39;";
1508 # Currently, the following definitions are used:
1509 # %ScriptingCGIvariables = (
1510 # "text/testperl" => "\$\%s = '\%s';", # Perl $VAR = 'value' (for testing)
1511 # "text/sspython" => "\%s = '\%s'", # Python VAR = 'value'
1512 # "text/ssruby" => '@%s = "%s"', # Ruby @VAR = "value"
1513 # "text/sstcl" => 'set %s "%s"', # TCL set VAR "value"
1514 # "text/ssawk" => '%s = "%s";', # Awk VAR = "value";
1515 # "text/sslisp" => '(setq %s "%s")', # Gnu lisp (rep) (setq VAR "value")
1516 # "text/xlispstat" => '(setq %s "%s")', # Xlispstat (setq VAR "value")
1517 # "text/ssprolog" => '', # Gnu prolog (interpolated)
1518 # "text/ssm4" => "define(`\%s', `\%s')", # M4 macro's define(`VAR', `value')
1519 # "text/sh" => "\%s='\%s';", # Born shell VAR='value';
1520 # "text/bash" => "\%s='\%s';", # Born again shell VAR='value';
1521 # "text/csh" => "\$\%s = '\%s';", # C shell $VAR = 'value';
1522 # "text/ksh" => "\$\%s = '\%s';", # Korn shell $VAR = 'value';
1523 # "text/sspraat" => '', # Praat (interpolation)
1524 # "text/ssr" => '%s <- "%s";', # R VAR <- "value";
1525 # "text/ssrebol" => '%s: copy "%s"', # REBOL VAR: copy "value"
1526 # "text/postgresql" => '', # PostgreSQL (interpolation)
1527 # "" => ""
1528 # );
1530 # Four tables allow fine-tuning of interpreter with code that should be
1531 # added before and after each code block:
1533 # Code added before each script block
1534 # %ScriptingPrefix = (
1535 # "text/testperl" => "\# Prefix Code;", # Perl script testing
1536 # "text/ssm4" => 'divert(0)' # M4 macro's (open STDOUT)
1537 # );
1538 # Code added at the end of each script block
1539 # %ScriptingPostfix = (
1540 # "text/testperl" => "\# Postfix Code;", # Perl script testing
1541 # "text/ssm4" => 'divert(-1)' # M4 macro's (block STDOUT)
1542 # );
1543 # Initialization code, inserted directly after opening (NEVER interpolated)
1544 # %ScriptingInitialization = (
1545 # "text/testperl" => "\# Initialization Code;", # Perl script testing
1546 # "text/ssawk" => 'BEGIN {', # Server Side awk scripts
1547 # "text/sslisp" => '(prog1 nil ', # Lisp (rep)
1548 # "text/xlispstat" => '(prog1 nil ', # xlispstat
1549 # "text/ssm4" => 'divert(-1)' # M4 macro's (block STDOUT)
1550 # );
1551 # Cleanup code, inserted before closing (NEVER interpolated)
1552 # %ScriptingCleanup = (
1553 # "text/testperl" => "\# Cleanup Code;", # Perl script testing
1554 # "text/sspraat" => 'Quit',
1555 # "text/ssawk" => '};', # Server Side awk scripts
1556 # "text/sslisp" => '(princ "\n" standard-output)).' # Closing print to rep
1557 # "text/xlispstat" => '(print "" *standard-output*)).' # Closing print to xlispstat
1558 # "text/postgresql" => '\q',
1559 # );
1562 # The SRC attribute is NOT magical for these interpreters. In short,
1563 # all code inside a source file or {} block is written verbattim
1564 # to the interpreter. No (pre-)processing or executional magic is done.
1566 # A serious shortcomming of the described mechanism for handling other
1567 # (scripting) languages, with respect to standard perl scripts
1568 # (i.e., 'text/ssperl'), is that the code is only executed when
1569 # the pipe to the interpreter is closed. So the pipe has to be
1570 # closed at the end of each block. This means that the state of the
1571 # interpreter (e.g., all variable values) is lost after the closing of
1572 # the next </SCRIPT> tag. The standard 'text/ssperl' scripts retain
1573 # all values and definitions.
1575 # APPLICATION MIME TYPES
1577 # To ease some important auxilliary functions from within the
1578 # html pages I have added them as MIME types. This uses
1579 # the mechanism that is also used for the evaluation of
1580 # other scripting languages, with interpolation of CGI
1581 # parameters (and perl-variables). Actually, these are
1582 # defined exactly like any other "scripting language".
1584 # text/ssdisplay: display some (HTML) text with interpolated
1585 # variables (uses `cat`).
1586 # text/sslogfile: write (append) the interpolated block to the file
1587 # mentioned on the first, non-empty line
1588 # (the filename can be preceded by 'File: ',
1589 # note the space after the ':',
1590 # uses `awk .... >> <filename>`).
1591 # text/ssmailto: send email directly from within the script block.
1592 # The first line of the body must contain
1593 # To:Name@Valid.Email.Address
1594 # (note: NO space between 'To:' and the email adres)
1595 # For other options see the mailto man pages.
1596 # It works by directly sending the (interpolated)
1597 # content of the text block to a pipe into the
1598 # Linux program 'mailto'.
1600 # In these script blocks, all Perl variables will be
1601 # replaced by their values. All CGI variables are cleaned before
1602 # they are used. These CGI variables must be redefined with a
1603 # CGI attribute to restore their original values.
1604 # In general, this will be more secure than constructing
1605 # e.g., your own email command lines. For instance, Mailto will
1606 # not execute any odd (forged) email addres, but just stops
1607 # when the email address is invalid and awk will construct
1608 # any filename you give it (e.g. '<File;rm\\\040-f' would end up
1609 # as a "valid" UNIX filename). Note that it will also gladly
1610 # store this file anywhere (/../../../etc/passwd will work!).
1611 # Use the CGIscriptor::CGIsafeFileName() function to clean the
1612 # filename.
1614 # SHELL SCRIPT PIPING
1616 # If a shell script starts with the UNIX style "#! <shell command> \n"
1617 # line, the rest of the shell script is piped into the indicated command,
1618 # i.e.,
1619 # open(COMMAND, "| command");print COMMAND $RestOfScript;
1621 # In many ways this is equivalent to the MIME-type profiling for
1622 # evaluating other scripting languages as discussed above. The
1623 # difference breaks down to convenience. Shell script piping is a
1624 # "raw" implementation. It allows you to control all aspects of
1625 # execution. Using the MIME-type profiling is easier, but has a
1626 # lot of defaults built in that might get in the way. Another
1627 # difference is that shell script piping uses the SAFEqx() function,
1628 # and MIME-type profiling does not.
1630 # Execution of shell scripts is under the control of the Perl Script blocks
1631 # in the document. The MIME-type triggered execution of <SCRIPT></SCRIPT>
1632 # blocks can be simulated easily. You can switch to a different shell,
1633 # e.g. tcl, completely by executing the following Perl commands inside
1634 # your document:
1636 # <SCRIPT TYPE="text/ssperl">
1637 # $main::ShellScriptContentType = "text/ssTcl"; # Yes, you can do this
1638 # CGIscriptor::RedirectShellScript('/usr/bin/tcl'); # Pipe to Tcl
1639 # $CGIscriptor::NoShellScriptInterpolation = 1;
1640 # </SCRIPT>
1642 # After this script is executed, CGIscriptor will parse scripts of
1643 # TYPE="text/ssTcl" and pipe their contents into '|/usr/bin/tcl'
1644 # WITHOUT interpolation (i.e., NO substitution of Perl variables).
1645 # The crucial function is :
1646 # CGIscriptor::RedirectShellScript('/usr/bin/tcl')
1647 # After executing this function, all shell scripts AND all
1648 # calls to SAFEqx()) are piped into '|/usr/bin/tcl'. If the argument
1649 # of RedirectShellScript is empty, e.g., '', the original (default)
1650 # value is reset.
1652 # The standard output, STDOUT, of any pipe is send to the client.
1653 # Currently, you should be carefull with quotes in such a piped script.
1654 # The results of a pipe is NOT put on the @CGIscriptorResults stack.
1655 # As a result, you do not have access to the output of any piped (#!)
1656 # process! If you want such access, execute
1657 # <SCRIPT TYPE="text/osshell">echo "script"|command</SCRIPT>
1658 # or
1659 # <SCRIPT TYPE="text/ssperl">
1660 # $resultvar = SAFEqx('echo "script"|command');
1661 # </SCRIPT>.
1663 # Safety is never complete. Although SAFEqx() prevents some of the
1664 # most obvious forms of attacks and security slips, it cannot prevent
1665 # them all. Especially, complex combinations of quotes and intricate
1666 # variable references cannot be handled safely by SAFEqx. So be on
1667 # guard.
1670 # PERL CODE EVALUATION (CONTENT-TYPE=TEXT/SSPERL)
1672 # All PERL scripts are evaluated inside a PERL package. This package
1673 # has a separate name space. This isolated name space protects the
1674 # CGIscriptor.pl program against interference from user code. However,
1675 # some variables, e.g., $_, are global and cannot be protected. You are
1676 # advised NOT to use such global variable names. You CAN write
1677 # directives that directly access the variables in the main program.
1678 # You do so at your own risk (there is definitely enough rope available
1679 # to hang yourself). The behavior of CGIscriptor becomes undefined if
1680 # you change its private variables during run time. The PERL code
1681 # directives are used as in:
1682 # $Result = eval($directive); print $Result;'';
1683 # ($directive contains all text between <SCRIPT></SCRIPT>).
1684 # That is, the <directive> is treated as ''-quoted string and
1685 # the result is treated as a scalar. To prevent the VALUE of the code
1686 # block from appearing on the client's screen, end the directive with
1687 # ';""</SCRIPT>'. Evaluated directives return the last value, just as
1688 # eval(), blocks, and subroutines, but only as a scalar.
1690 # IMPORTANT: All PERL variables defined are persistent. Each <SCRIPT>
1691 # </SCRIPT> construct is evaluated as a {}-block with associated scope
1692 # (e.g., for "my $var;" declarations). This means that values assigned
1693 # to a PERL variable can be used throughout the document unless they
1694 # were declared with "my". The following will actually work as intended
1695 # (note that the ``-quotes in this example are NOT evaluated, but used
1696 # as simple quotes):
1698 # <META CONTENT="text/ssperl; CGI=`$String='abcdefg'`">
1699 # anything ...
1700 # <SCRIPT TYPE=text/ssperl>@List = split('', $String);</SCRIPT>
1701 # anything ...
1702 # <SCRIPT TYPE=text/ssperl>join(", ", @List[1..$#List]);</SCRIPT>
1704 # The first <SCRIPT TYPE=text/ssperl></SCRIPT> construct will return the
1705 # value scalar(@List), the second <SCRIPT TYPE=text/ssperl></SCRIPT>
1706 # construct will print the elements of $String separated by commas, leaving
1707 # out the first element, i.e., $List[0].
1709 # Another warning: './' and '~/' are ALWAYS replaced by the values of
1710 # $YOUR_SCRIPTS and $YOUR_HTML_FILES, respectively . This can interfere
1711 # with pattern matching, e.g., $a =~ s/aap\./noot\./g will result in the
1712 # evaluations of $a =~ s/aap\\${YOUR_SCRIPTS}noot\\${YOUR_SCRIPTS}g. Use
1713 # s@<regexp>.@<replacement>.@g instead.
1716 # SERVER SIDE SESSIONS AND ACCESS CONTROL (LOGIN)
1718 # An infrastructure for user acount authorization and file access control
1719 # is available. Each request is matched against a list of URL path patterns.
1720 # If the request matches, a Session Ticket is required to access the URL.
1721 # This Session Ticket should be present as a CGI parameter:
1722 # SESSIONTICKET=<value>
1723 # The example implementation stores Session Tickets as files in a local
1724 # directory. To create Session Tickets, a Login request must be given
1725 # with a LOGIN=<value> CGI parameter, a user name and a (doubly hashed)
1726 # password. The user name and (singly hashed) password are stored in a
1727 # PASSWORD ticket with the same name as the user account (name cleaned up
1728 # for security).
1730 # A Login page should create a LOGIN ticket file localy and send a
1731 # server specific SALT, a Random salt, and both the LOGIN and SESSION ticket
1732 # identifiers. The server side compares the username and hashed password,
1733 # actually hashed(Random salt+hashed(SALT+password)) from the client with
1734 # the values it calculates from the stored Random salt from the LOGIN
1735 # ticket and the hashed(SALT+password) from the PASSWORD ticket. If
1736 # successful, a new SESSION ticket is generated. The SESSION ticket
1737 # identifier is available as $SESSIONTICKET, the Username, IP address
1738 # and Path as $LOGINUSERNAME, $LOGINIPADDRESS, and $LOGINPATH, respectively.
1740 # In the current example implementation, all random values are created as
1741 # a full SHA256 hash (Hex) of a 64 byte block read from /dev/urandom.
1743 # The example session model implements 3 functions:
1744 # 1 Login
1745 # The password is hashed with the server side salt, and then hashed with
1746 # a Random salt. The server side only stores the password hashed with the
1747 # server side salt. Neither the plain password, nor the hashed password is
1748 # ever exchanged. Only values hashed with the one-time salt are exchanged.
1749 # 2 Session
1750 # For every access to a restricted URL, the Session Ticket is checked
1751 # before access is granted.
1752 # 3 Password Change
1753 # A new password is hashed with the server side salt, and then XORed
1754 # with the old password hashed with the salt. That value is exchanged
1755 # and XORed with the stored old hashed(salt+password). Again, the
1756 # stored password value is never exchanged unencrypted.
1758 # USER EXTENSIONS
1760 # A CGIscriptor package is attached to the bottom of this file. With
1761 # this package you can personalize your version of CGIscriptor by
1762 # including often used perl routines. These subroutines can be
1763 # accessed by prefixing their names with CGIscriptor::, e.g.,
1764 # <SCRIPT LANGUAGE=PERL TYPE=text/ssperl>
1765 # CGIscriptor::ListDocs("/Books/*") # List all documents in /Books
1766 # </SCRIPT>
1767 # It already contains some useful subroutines for Document Management.
1768 # As it is a separate package, it has its own namespace, isolated from
1769 # both the evaluator and the main program. To access variables from
1770 # the document <SCRIPT></SCRIPT> blocks, use $CGIexecute::<var>.
1772 # Currently, the following functions are implemented
1773 # (precede them with CGIscriptor::, see below for more information)
1774 # - SAFEqx ('String') -> result of qx/"String"/ # Safe application of ``-quotes
1775 # Is used by text/osshell Shell scripts. Protects all CGI
1776 # (client-supplied) values with single quotes before executing the
1777 # commands (one of the few functions that also works WITHOUT CGIscriptor::
1778 # in front)
1779 # - defineCGIvariable ($name[, $default) -> 0/1 (i.e., failure/success)
1780 # Is used by the META tag to define and initialize CGI and ENV
1781 # name/value pairs. Tries to obtain an initializing value from (in order):
1782 # $ENV{$name}
1783 # The Query string
1784 # The default value given (if any)
1785 # (one of the few functions that also works WITHOUT CGIscriptor::
1786 # in front)
1787 # - CGIsafeFileName (FileName) -> FileName or ""
1788 # Check a string against the Allowed File Characters (and ../ /..).
1789 # Returns an empty string for unsafe filenames.
1790 # - CGIsafeEmailAddress (Email) -> Email or ""
1791 # Check a string against correct email address pattern.
1792 # Returns an empty string for unsafe addresses.
1793 # - RedirectShellScript ('CommandString') -> FILEHANDLER or undef
1794 # Open a named PIPE for SAFEqx to receive ALL shell scripts
1795 # - URLdecode (URL encoded string) -> plain string # Decode URL encoded argument
1796 # - URLencode (plain string) -> URL encoded string # Encode argument as URL code
1797 # - CGIparseValue (ValueName [, URL_encoded_QueryString]) -> Decoded value
1798 # Extract the value of a CGI variable from the global or a private
1799 # URL-encoded query (multipart POST raw, NOT decoded)
1800 # - CGIparseValueList (ValueName [, URL_encoded_QueryString])
1801 # -> List of decoded values
1802 # As CGIparseValue, but now assembles ALL values of ValueName into a list.
1803 # - CGIparseHeader (ValueName [, URL_encoded_QueryString]) -> Header
1804 # Extract the header of a multipart CGI variable from the global or a private
1805 # URL-encoded query ("" when not a multipart variable or absent)
1806 # - CGIparseForm ([URL_encoded_QueryString]) -> Decoded Form
1807 # Decode the complete global URL-encoded query or a private
1808 # URL-encoded query
1809 # - read_url(URL) # Returns the page from URL (with added base tag, both FTP and HTTP)
1810 # Uses main::GET_URL(URL, 1) to get at the command to read the URL.
1811 # - BrowseDirs(RootDirectory [, Pattern, Startdir, CGIname]) # print browsable directories
1812 # - ListDocs(Pattern [,ListType]) # Prints a nested HTML directory listing of
1813 # all documents, e.g., ListDocs("/*", "dl");.
1814 # - HTMLdocTree(Pattern [,ListType]) # Prints a nested HTML listing of all
1815 # local links starting from a given document, e.g.,
1816 # HTMLdocTree("/Welcome.html", "dl");
1819 # THE RESULTS STACK: @CGISCRIPTORRESULTS
1821 # If the pseudo-variable "$CGIscriptorResults" has been defined in a
1822 # META tag, all subsequent SCRIPT and META results are pushed
1823 # on the @CGIscriptorResults stack. This list is just another
1824 # Perl variable and can be used and manipulated like any other list.
1825 # $CGIscriptorResults[-1] is always the last result.
1826 # This is only of limited use, e.g., to use the results of an OS shell
1827 # script inside a Perl script. Will NOT contain the results of Pipes
1828 # or code from MIME-profiling.
1831 # USEFULL CGI PREDEFINED VARIABLES (DO NOT ASSIGN TO THESE)
1833 # $CGI_HOME - The DocumentRoot directory
1834 # $CGI_Decoded_QS - The complete decoded Query String
1835 # $CGI_Content_Length - The ACTUAL length of the Query String
1836 # $CGI_Date - Current date and time
1837 # $CGI_Year $CGI_Month $CGI_Day $CGI_WeekDay - Current Date
1838 # $CGI_Time - Current Time
1839 # $CGI_Hour $CGI_Minutes $CGI_Seconds - Current Time, split
1840 # GMT Date/Time:
1841 # $CGI_GMTYear $CGI_GMTMonth $CGI_GMTDay $CGI_GMTWeekDay $CGI_GMTYearDay
1842 # $CGI_GMTHour $CGI_GMTMinutes $CGI_GMTSeconds $CGI_GMTisdst
1845 # USEFULL CGI ENVIRONMENT VARIABLES
1847 # Variables accessible (in APACHE) as $ENV{<name>}
1848 # (see: "http://hoohoo.ncsa.uiuc.edu/cgi/env.html"):
1850 # QUERY_STRING - The query part of URL, that is, everything that follows the
1851 # question mark.
1852 # PATH_INFO - Extra path information given after the script name
1853 # PATH_TRANSLATED - Extra pathinfo translated through the rule system.
1854 # (This doesn't always make sense.)
1855 # REMOTE_USER - If the server supports user authentication, and the script is
1856 # protected, this is the username they have authenticated as.
1857 # REMOTE_HOST - The hostname making the request. If the server does not have
1858 # this information, it should set REMOTE_ADDR and leave this unset
1859 # REMOTE_ADDR - The IP address of the remote host making the request.
1860 # REMOTE_IDENT - If the HTTP server supports RFC 931 identification, then this
1861 # variable will be set to the remote user name retrieved from
1862 # the server. Usage of this variable should be limited to logging
1863 # only.
1864 # AUTH_TYPE - If the server supports user authentication, and the script
1865 # is protected, this is the protocol-specific authentication
1866 # method used to validate the user.
1867 # CONTENT_TYPE - For queries which have attached information, such as HTTP
1868 # POST and PUT, this is the content type of the data.
1869 # CONTENT_LENGTH - The length of the said content as given by the client.
1870 # SERVER_SOFTWARE - The name and version of the information server software
1871 # answering the request (and running the gateway).
1872 # Format: name/version
1873 # SERVER_NAME - The server's hostname, DNS alias, or IP address as it
1874 # would appear in self-referencing URLs
1875 # GATEWAY_INTERFACE - The revision of the CGI specification to which this
1876 # server complies. Format: CGI/revision
1877 # SERVER_PROTOCOL - The name and revision of the information protocol this
1878 # request came in with. Format: protocol/revision
1879 # SERVER_PORT - The port number to which the request was sent.
1880 # REQUEST_METHOD - The method with which the request was made. For HTTP,
1881 # this is "GET", "HEAD", "POST", etc.
1882 # SCRIPT_NAME - A virtual path to the script being executed, used for
1883 # self-referencing URLs.
1884 # HTTP_ACCEPT - The MIME types which the client will accept, as given by
1885 # HTTP headers. Other protocols may need to get this
1886 # information from elsewhere. Each item in this list should
1887 # be separated by commas as per the HTTP spec.
1888 # Format: type/subtype, type/subtype
1889 # HTTP_USER_AGENT - The browser the client is using to send the request.
1890 # General format: software/version library/version.
1893 # INSTRUCTIONS FOR RUNNING CGIscriptor ON UNIX
1895 # CGIscriptor.pl will run on any WWW server that runs Perl scripts, just add
1896 # a line like the following to your srm.conf file (Apache example):
1898 # ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
1900 # URL's that refer to http://www.your.address/SHTML/... will now be handled
1901 # by CGIscriptor.pl, which can use a private directory tree (default is the
1902 # DOCUMENT_ROOT directory tree, but it can be anywhere, see manual).
1904 # If your hosting ISP won't let you add ScriptAlias lines you can use
1905 # the following "rewrite"-based "scriptalias" in .htaccess
1906 # (from Gerd Franke)
1908 # RewriteEngine On
1909 # RewriteBase /
1910 # RewriteCond %{REQUEST_FILENAME} .html$
1911 # RewriteCond %{SCRIPT_FILENAME} !cgiscriptor.pl$
1912 # RewriteCond %{REQUEST_FILENAME} -f
1913 # RewriteRule ^(.*)$ /cgi-bin/cgiscriptor.pl/$1?&%{QUERY_STRING}
1915 # Everthing with the extension ".html" and not including "cgiscriptor.pl"
1916 # in the url and where the file "path/filename.html" exists is redirected
1917 # to "/cgi.bin/cgiscriptor.pl/path/filename.html?query".
1918 # The user configuration should get the same path-level as the
1919 # .htaccess-file:
1921 # # Just enter your own directory path here
1922 # $YOUR_HTML_FILES = "$ENV{'DOCUMENT_ROOT'}";
1923 # # use DOCUMENT_ROOT only, if .htaccess lies in the root-directory.
1925 # If this .htaccess goes in a specific directory, the path to this
1926 # directory must be added to $ENV{'DOCUMENT_ROOT'}.
1928 # The CGIscriptor file contains all documentation as comments. These
1929 # comments can be removed to speed up loading (e.g., `egrep -v '^#'
1930 # CGIscriptor.pl` > leanScriptor.pl). A bare bones version of
1931 # CGIscriptor.pl, lacking documentation, most comments, access control,
1932 # example functions etc. (but still with the copyright notice and some
1933 # minimal documentation) can be obtained by calling CGIscriptor.pl on the
1934 # command line with the '-slim' command line argument, e.g.,
1936 # >CGIscriptor.pl -slim > slimCGIscriptor.pl
1938 # CGIscriptor.pl can be run from the command line with <path> and <query> as
1939 # arguments, as `CGIscriptor.pl <path> <query>`, inside a perl script
1940 # with 'do CGIscriptor.pl' after setting $ENV{PATH_INFO}
1941 # and $ENV{QUERY_STRING}, or CGIscriptor.pl can be loaded with 'require
1942 # "/real-path/CGIscriptor.pl"'. In the latter case, requests are processed
1943 # by 'Handle_Request();' (again after setting $ENV{PATH_INFO} and
1944 # $ENV{QUERY_STRING}).
1946 # Using the command line execution option, CGIscriptor.pl can be used as a
1947 # document (meta-)preprocessor. If the first argument is '-', STDIN will be read.
1948 # For example:
1950 # > cat MyDynamicDocument.html | CGIscriptor.pl - '[QueryString]' > MyStaticFile.html
1952 # This command line will produce a STATIC file with the DYNAMIC content of
1953 # MyDocument.html "interpolated".
1955 # This option would be very dangerous when available over the internet.
1956 # If someone could sneak a 'http://www.your.domain/-' URL past your
1957 # server, CGIscriptor could EXECUTE any POSTED contend.
1958 # Therefore, for security reasons, STDIN will NOT be read
1959 # if ANY of the HTTP server environment variables is set (e.g.,
1960 # SERVER_PORT, SERVER_PROTOCOL, SERVER_NAME, SERVER_SOFTWARE,
1961 # HTTP_USER_AGENT, REMOTE_ADDR).
1962 # This block on processing STDIN on HTTP requests can be lifted by setting
1963 # $BLOCK_STDIN_HTTP_REQUEST = 0;
1964 # In the security configuration. Butbe carefull when doing this.
1965 # It can be very dangerous.
1967 # Running demo's and more information can be found at
1968 # http://www.fon.hum.uva.nl/~rob/OSS/OSS.html
1970 # A pocket-size HTTP daemon, CGIservlet.pl, is available from my web site or
1971 # CPAN that can use CGIscriptor.pl as the base of a µWWW server and
1972 # demonstrates its use.
1975 # PROCESSING NON-FILESYSTEM DATA
1977 # Normally, HTTP (WWW) requests map onto file that can be accessed
1978 # using the perl open() function. That is, the web server runs on top of
1979 # some directory structure. However, we can envission (and put to good
1980 # use) other systems that do not use a normal file system. The whole CGI
1981 # was developed to make dynamic document generation possible.
1983 # A special case is where we want to have it both: A normal web server
1984 # with normal "file data", but not a normal files system. For instance,
1985 # we want or normal Web Site to run directly from a RAM hash table or
1986 # other database, instead of from disk. But we do NOT want to code the
1987 # whole site structure in CGI.
1989 # CGIscriptor can do this. If the web server fills an environment variable
1990 # $ENV{'CGI_FILE_CONTENT'} with the content of the "file", then the content
1991 # of this variable is processed instead of opening a file. If this environment
1992 # variable has the value '-', the content of another environment variable,
1993 # $ENV{'CGI_DATA_ACCESS_CODE'} is executed as:
1994 # eval("\@_ = ($file_path); do {$ENV{'CGI_DATA_ACCESS_CODE'}};")
1995 # and the result is processed as if it was the content of the requested
1996 # file.
1997 # (actually, the names of the environment variables are user configurable,
1998 # they are stored in the local variables $CGI_FILE_CONTENT and
1999 # $CGI_DATA_ACCESS_CODE)
2001 # When using this mechanism, the SRC attribute mechanism will only partially work.
2002 # Only the "recursive" calls to CGIscriptor (the ProcessFile() function)
2003 # will work, the automagical execution of SRC files won't. (In this case,
2004 # the SRC attribute won't work either for other scripting languages)
2007 # NON-UNIX PLATFORMS
2009 # CGIscriptor.pl was mainly developed and tested on UNIX. However, as I
2010 # coded part of the time on an Apple Macintosh under MacPerl, I made sure
2011 # CGIscriptor did run under MacPerl (with command line options). But only
2012 # as an independend script, not as part of a HTTP server. I have used it
2013 # under Apache in Windows XP.
2015 ENDOFHELPTEXT
2016 exit;
2018 ###############################################################################
2020 # SECURITY CONFIGURATION
2022 # Special configurations related to SECURITY
2023 # (i.e., optional, see also environment variables below)
2025 # LOGGING
2026 # Log Clients and the requested paths (Redundant when loging Queries)
2028 $ClientLog = "./Client.log"; # (uncomment for use)
2030 # Format: Localtime | REMOTE_USER REMOTE_IDENT REMOTE_HOST REMOTE_ADDRESS \
2031 # PATH_INFO CONTENT_LENGTH (actually, the real query+post length)
2033 # Log Clients and the queries, the CGIQUERYDECODE is required if you want
2034 # to log queries. If you log Queries, the loging of Clients is redundant
2035 # (note that queries can be quite long, so this might not be a good idea)
2037 #$QueryLog = "./Query.log"; # (uncomment for use)
2039 # ACCESS CONTROL
2040 # the Access files should contain Hostnames or IP addresses,
2041 # i.e. REMOTE_HOST or REMOTE_ADDR, each on a separate line
2042 # optionally followed by one ore more file patterns, e.g., "edu /DEMO".
2043 # Matching is done "domain first". For example ".edu" matches all
2044 # clients whose "name" ends in ".edu" or ".EDU". The file pattern
2045 # "/DEMO" matches all paths that contain the strings "/DEMO" or "/demo"
2046 # (both matchings are done case-insensitive).
2047 # The name special symbol "-" matches ALL clients who do not supply a
2048 # REMOTE_HOST name, "*" matches all clients.
2049 # Lines starting with '-e' are evaluated. A non-zero return value indicates
2050 # a match. You can use $REMOTE_HOST, $REMOTE_ADDR, and $PATH_INFO. These
2051 # lines are evaluated in the program's own name-space. So DO NOT assign to
2052 # variables.
2054 # Accept the following users (remove comment # and adapt filename)
2055 $CGI_Accept = -s "$YOUR_SCRIPTS/ACCEPT.lis" ? "$YOUR_SCRIPTS/ACCEPT.lis" : ''; # (uncomment for use)
2057 # Reject requests from the following users (remove comment # and
2058 # adapt filename, this is only of limited use)
2059 $CGI_Reject = -s "$YOUR_SCRIPTS/REJECT.lis" ? "$YOUR_SCRIPTS/REJECT.lis" : ''; # (uncomment for use)
2061 # Empty lines or comment lines starting with '#' are ignored in both
2062 # $CGI_Accept and $CGI_Reject.
2064 # Block STDIN (i.e., '-') requests when servicing an HTTP request
2065 # Comment this out if you realy want to use STDIN in an on-line web server
2066 $BLOCK_STDIN_HTTP_REQUEST = 1;
2069 # End of security configuration
2071 ##################################################<<<<<<<<<<End Remove
2073 # PARSING CGI VALUES FROM THE QUERY STRING (USER CONFIGURABLE)
2075 # The CGI parse commands. These commands extract the values of the
2076 # CGI variables from the URL encoded Query String.
2077 # If you want to use your own CGI decoders, you can call them here
2078 # instead, using your own PATH and commenting/uncommenting the
2079 # appropriate lines
2081 # CGI parse command for individual values
2082 # (if $List > 0, returns a list value, if $List < 0, a hash table, this is optional)
2083 sub YOUR_CGIPARSE # ($Name [, $List]) -> Decoded value
2085 my $Name = shift;
2086 my $List = shift || 0;
2087 # Use one of the following by uncommenting
2088 if(!$List) # Simple value
2090 return CGIscriptor::CGIparseValue($Name) ;
2092 elsif($List < 0) # Hash tables
2094 return CGIscriptor::CGIparseValueHash($Name); # Defined in CGIscriptor below
2096 else # Lists
2098 return CGIscriptor::CGIparseValueList($Name); # Defined in CGIscriptor below
2101 # return `/PATH/cgiparse -value $Name`; # Shell commands
2102 # require "/PATH/cgiparse.pl"; return cgivalue($Name); # Library
2104 # Complete queries
2105 sub YOUR_CGIQUERYDECODE
2107 # Use one of the following by uncommenting
2108 return CGIscriptor::CGIparseForm(); # Defined in CGIscriptor below
2109 # return `/PATH/cgiparse -form`; # Shell commands
2110 # require "/PATH/cgiparse.pl"; return cgiform(); # Library
2113 # End of configuration
2115 #######################################################################
2117 # Translating input files.
2118 # Allows general and global conversions of files using Regular Expressions
2119 # Translations are applied in the order of definition.
2121 # Define:
2122 # my $TranslationPaths = 'pattern'; # Pattern matching PATH_INFO
2124 # push(@TranslationTable, ['pattern', 'replacement']);
2125 # e.g. (for Ruby Rails):
2126 # push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2127 # push(@TranslationTable, ['%>', '</SCRIPT>']);
2129 # Runs:
2130 # my $currentRegExp;
2131 # foreach $currentRegExp (keys(%TranslationTable))
2133 # my $currentRegExp;
2134 # foreach $currentRegExp (@TranslationTable)
2136 # my ($pattern, $replacement) = @$currentRegExp;
2137 # $$text =~ s!$pattern!$replacement!msg;
2138 # };
2139 # };
2141 # Configuration section
2143 #######################################################################
2145 # The file paths on which to apply the translation
2146 my $TranslationPaths = ''; # NO files
2147 #$TranslationPaths = '.'; # ANY file
2148 # $TranslationPaths = '\.html'; # HTML files
2150 my @TranslationTable = ();
2151 # Some legacy code
2152 push(@TranslationTable, ['\<\s*CGI\s+([^\>])*\>', '\<SCRIPT TYPE=\"text/ssperl\"\>$1\<\/SCRIPT>']);
2153 # Ruby Rails?
2154 push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2155 push(@TranslationTable, ['%>', '</SCRIPT>']);
2157 sub performTranslation # (\$text)
2159 my $text = shift || return;
2160 if(@TranslationTable && $TranslationPaths && $ENV{'PATH_INFO'} =~ m!$TranslationPaths!)
2162 my $currentRegExp;
2163 foreach $currentRegExp (@TranslationTable)
2165 my ($pattern, $replacement) = @$currentRegExp;
2166 $$text =~ s!$pattern!$replacement!msg;
2171 #######################################################################
2173 # Seamless access to other (Scripting) Languages
2174 # TYPE='text/ss<interpreter>'
2176 # Configuration section
2178 #######################################################################
2180 # OTHER SCRIPTING LANGUAGES AT THE SERVER SIDE (MIME => OScommand)
2181 # Yes, it realy is this simple! (unbelievable, isn't it)
2182 # NOTE: Some interpreters require some filtering to obtain "clean" output
2184 %ScriptingLanguages = (
2185 "text/testperl" => 'perl', # Perl for testing
2186 "text/sspython" => 'python', # Python
2187 "text/ssruby" => 'ruby', # Ruby
2188 "text/sstcl" => 'tcl', # TCL
2189 "text/ssawk" => 'awk -f-', # Awk
2190 "text/sslisp" => # lisp (rep, GNU)
2191 'rep | tail +4 '."| egrep -v '> |^rep. |^nil\\\$'",
2192 "text/xlispstat" => # xlispstat
2193 'xlispstat | tail +7 ' ."| egrep -v '> \\\$|^NIL'",
2194 "text/ssprolog" => # Prolog (GNU)
2195 "gprolog | tail +4 | sed 's/^| ?- //'",
2196 "text/ssm4" => 'm4', # M4 macro's
2197 "text/sh" => 'sh', # Born shell
2198 "text/bash" => 'bash', # Born again shell
2199 "text/csh" => 'csh', # C shell
2200 "text/ksh" => 'ksh', # Korn shell
2201 "text/sspraat" => # Praat (sound/speech analysis)
2202 "praat - | sed 's/Praat > //g'",
2203 "text/ssr" => # R
2204 "R --vanilla --slave | sed 's/^[\[0-9\]*] //'",
2205 "text/ssrebol" => # REBOL
2206 "rebol --quiet|egrep -v '^[> ]* == '|sed 's/^\\s*\[> \]* //'",
2207 "text/postgresql" => 'psql 2>/dev/null',
2209 # Not real scripting, but the use of other applications
2210 "text/ssmailto" => "awk 'NF||F{F=1;print \\\$0;}'|mailto >/dev/null", # Send mail from server
2211 "text/ssdisplay" => 'cat', # Display, (interpolation)
2212 "text/sslogfile" => # Log to file, (interpolation)
2213 "awk 'NF||L {if(!L){L=tolower(\\\$1)~/^file:\\\$/ ? \\\$2 : \\\$1;}else{print \\\$0 >> L;};}'",
2215 "" => ""
2218 # To be able to access the CGI variables in your script, they
2219 # should be passed to the scripting language in a readable form
2220 # Here you can enter how they should be printed (the first %s
2221 # is replaced by the NAME of the CGI variable as it apears in the
2222 # META tag, the second by its VALUE).
2223 # For Perl this would be:
2224 # "text/testperl" => '$%s = "%s";',
2225 # which would be executed as
2226 # printf('$%s = "%s";', $CGI_NAME, $CGI_VALUE);
2228 # If the hash table value doesn't exist, nothing is done
2229 # (you have to parse the Environment variables yourself).
2230 # If it DOES exist but is empty (e.g., "text/sspraat" => '',)
2231 # Perl string interpolation of variables (i.e., $var, @array,
2232 # %hash) is performed. This means that $@%\ must be protected
2233 # with a \.
2235 %ScriptingCGIvariables = (
2236 "text/testperl" => "\$\%s = '\%s';", # Perl $VAR = 'value'; (for testing)
2237 "text/sspython" => "\%s = '\%s'", # Python VAR = 'value'
2238 "text/ssruby" => '@%s = "%s"', # Ruby @VAR = 'value'
2239 "text/sstcl" => 'set %s "%s"', # TCL set VAR "value"
2240 "text/ssawk" => '%s = "%s";', # Awk VAR = 'value';
2241 "text/sslisp" => '(setq %s "%s")', # Gnu lisp (rep) (setq VAR "value")
2242 "text/xlispstat" => '(setq %s "%s")', # xlispstat (setq VAR "value")
2243 "text/ssprolog" => '', # Gnu prolog (interpolated)
2244 "text/ssm4" => "define(`\%s', `\%s')", # M4 macro's define(`VAR', `value')
2245 "text/sh" => "\%s='\%s'", # Born shell VAR='value'
2246 "text/bash" => "\%s='\%s'", # Born again shell VAR='value'
2247 "text/csh" => "\$\%s='\%s';", # C shell $VAR = 'value';
2248 "text/ksh" => "\$\%s='\%s';", # Korn shell $VAR = 'value';
2250 "text/ssrebol" => '%s: copy "%s"', # REBOL VAR: copy "value"
2251 "text/sspraat" => '', # Praat (interpolation)
2252 "text/ssr" => '%s <- "%s";', # R VAR <- "value";
2253 "text/postgresql" => '', # PostgreSQL (interpolation)
2255 # Not real scripting, but the use of other applications
2256 "text/ssmailto" => '', # MAILTO, (interpolation)
2257 "text/ssdisplay" => '', # Display, (interpolation)
2258 "text/sslogfile" => '', # Log to file, (interpolation)
2260 "" => ""
2263 # If you want something added in front or at the back of each script
2264 # block as send to the interpreter add it here.
2265 # mime => "string", e.g., "text/sspython" => "python commands"
2266 %ScriptingPrefix = (
2267 "text/testperl" => "\# Prefix Code;", # Perl script testing
2268 "text/ssm4" => 'divert(0)', # M4 macro's (open STDOUT)
2270 "" => ""
2272 # If you want something added at the end of each script block
2273 %ScriptingPostfix = (
2274 "text/testperl" => "\# Postfix Code;", # Perl script testing
2275 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2277 "" => ""
2279 # If you need initialization code, directly after opening
2280 %ScriptingInitialization = (
2281 "text/testperl" => "\# Initialization Code;", # Perl script testing
2282 "text/ssawk" => 'BEGIN {', # Server Side awk scripts (VAR = "value")
2283 "text/sslisp" => '(prog1 nil ', # Lisp (rep)
2284 "text/xlispstat" => '(prog1 nil ', # xlispstat
2285 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2287 "" => ""
2289 # If you need cleanup code before closing
2290 %ScriptingCleanup = (
2291 "text/testperl" => "\# Cleanup Code;", # Perl script testing
2292 "text/sspraat" => 'Quit',
2293 "text/ssawk" => '};', # Server Side awk scripts (VAR = "value")
2294 "text/sslisp" => '(princ "\n" standard-output)).', # Closing print to rep
2295 "text/xlispstat" => '(print ""))', # Closing print to xlispstat
2296 "text/postgresql" => '\q', # quit psql
2297 "text/ssdisplay" => "", # close cat
2299 "" => ""
2302 # End of configuration for foreign scripting languages
2304 ###############################################################################
2306 # Initialization Code
2309 sub Initialize_Request
2311 ###############################################################################
2313 # ENVIRONMENT VARIABLES
2315 # Use environment variables to configure CGIscriptor on a temporary basis.
2316 # If you define any of the configurable variables as environment variables,
2317 # these are used instead of the "hard coded" values above.
2319 $SS_PUB = $ENV{'SS_PUB'} || $YOUR_HTML_FILES;
2320 $SS_SCRIPT = $ENV{'SS_SCRIPT'} || $YOUR_SCRIPTS;
2323 # Substitution strings, these are used internally to handle the
2324 # directory separator strings, e.g., '~/' -> 'SS_PUB:' (Mac)
2325 $HOME_SUB = $SS_PUB;
2326 $SCRIPT_SUB = $SS_SCRIPT;
2329 # Make sure all script are reliably loaded
2330 push(@INC, $SS_SCRIPT);
2333 # Add the directory separator to the "home" directories.
2334 # (This is required for ~/ and ./ substitution)
2335 $HOME_SUB .= '/' if $HOME_SUB;
2336 $SCRIPT_SUB .= '/' if $SCRIPT_SUB;
2338 $CGI_HOME = $ENV{'DOCUMENT_ROOT'};
2339 $ENV{'PATH_TRANSLATED'} =~ /$ENV{'PATH_INFO'}/is;
2340 $CGI_HOME = $` unless $ENV{'DOCUMENT_ROOT'}; # Get the DOCUMENT_ROOT directory
2341 $default_values{'CGI_HOME'} = $CGI_HOME;
2342 $ENV{'HOME'} = $CGI_HOME;
2343 # Set SS_PUB and SS_SCRIPT as Environment variables (make them available
2344 # to the scripts)
2345 $ENV{'SS_PUB'} = $SS_PUB unless $ENV{'SS_PUB'};
2346 $ENV{'SS_SCRIPT'} = $SS_SCRIPT unless $ENV{'SS_SCRIPT'};
2348 $FilePattern = $ENV{'FilePattern'} || $FilePattern;
2349 $MaximumQuerySize = $ENV{'MaximumQuerySize'} || $MaximumQuerySize;
2350 $ClientLog = $ENV{'ClientLog'} || $ClientLog;
2351 $QueryLog = $ENV{'QueryLog'} || $QueryLog;
2352 $CGI_Accept = $ENV{'CGI_Accept'} || $CGI_Accept;
2353 $CGI_Reject = $ENV{'CGI_Reject'} || $CGI_Reject;
2355 # Parse file names
2356 $CGI_Accept =~ s@^\~/@$HOME_SUB@g if $CGI_Accept;
2357 $CGI_Reject =~ s@^\~/@$HOME_SUB@g if $CGI_Reject;
2358 $ClientLog =~ s@^\~/@$HOME_SUB@g if $ClientLog;
2359 $QueryLog =~ s@^\~/@$HOME_SUB@g if $QueryLog;
2361 $CGI_Accept =~ s@^\./@$SCRIPT_SUB@g if $CGI_Accept;
2362 $CGI_Reject =~ s@^\./@$SCRIPT_SUB@g if $CGI_Reject;
2363 $ClientLog =~ s@^\./@$SCRIPT_SUB@g if $ClientLog;
2364 $QueryLog =~ s@^\./@$SCRIPT_SUB@g if $QueryLog;
2366 @CGIscriptorResults = (); # A stack of results
2368 # end of Environment variables
2370 #############################################################################
2372 # Define and Store "standard" values
2374 # BEFORE doing ANYTHING check the size of Query String
2375 length($ENV{'QUERY_STRING'}) <= $MaximumQuerySize || dieHandler(2, "QUERY TOO LONG\n");
2377 # The Translated Query String and the Actual length of the (decoded)
2378 # Query String
2379 if($ENV{'QUERY_STRING'})
2381 # If this can contain '`"-quotes, be carefull to use it QUOTED
2382 $default_values{CGI_Decoded_QS} = YOUR_CGIQUERYDECODE();
2383 $default_values{CGI_Content_Length} = length($default_values{CGI_Decoded_QS});
2386 # Get the current Date and time and store them as default variables
2388 # Get Local Time
2389 $LocalTime = localtime;
2391 # CGI_Year CGI_Month CGI_Day CGI_WeekDay CGI_Time
2392 # CGI_Hour CGI_Minutes CGI_Seconds
2394 $default_values{CGI_Date} = $LocalTime;
2395 ($default_values{CGI_WeekDay},
2396 $default_values{CGI_Month},
2397 $default_values{CGI_Day},
2398 $default_values{CGI_Time},
2399 $default_values{CGI_Year}) = split(' ', $LocalTime);
2400 ($default_values{CGI_Hour},
2401 $default_values{CGI_Minutes},
2402 $default_values{CGI_Seconds}) = split(':', $default_values{CGI_Time});
2404 # GMT:
2405 # CGI_GMTYear CGI_GMTMonth CGI_GMTDay CGI_GMTWeekDay CGI_GMTYearDay
2406 # CGI_GMTHour CGI_GMTMinutes CGI_GMTSeconds CGI_GMTisdst
2408 ($default_values{CGI_GMTSeconds},
2409 $default_values{CGI_GMTMinutes},
2410 $default_values{CGI_GMTHour},
2411 $default_values{CGI_GMTDay},
2412 $default_values{CGI_GMTMonth},
2413 $default_values{CGI_GMTYear},
2414 $default_values{CGI_GMTWeekDay},
2415 $default_values{CGI_GMTYearDay},
2416 $default_values{CGI_GMTisdst}) = gmtime;
2420 # End of Initialize Request
2422 ###################################################################
2424 # SECURITY: ACCESS CONTROL
2426 # Check the credentials of each client (use pattern matching, domain first).
2427 # This subroutine will kill-off (die) the current process whenever access
2428 # is denied.
2430 sub Access_Control
2432 # >>>>>>>>>>Start Remove
2434 # ACCEPTED CLIENTS
2436 # Only accept clients which are authorized, reject all unnamed clients
2437 # if REMOTE_HOST is given.
2438 # If file patterns are given, check whether the user is authorized for
2439 # THIS file.
2440 if($CGI_Accept)
2442 # Use local variables, REMOTE_HOST becomes '-' if undefined
2443 my $REMOTE_HOST = $ENV{REMOTE_HOST} || '-';
2444 my $REMOTE_ADDR = $ENV{REMOTE_ADDR};
2445 my $PATH_INFO = $ENV{'PATH_INFO'};
2447 open(CGI_Accept, "<$CGI_Accept") || dieHandler(3, "$CGI_Accept: $!\n");
2448 $NoAccess = 1;
2449 while(<CGI_Accept>)
2451 next unless /\S/; # Skip empty lines
2452 next if /^\s*\#/; # Skip comments
2454 # Full expressions
2455 if(/^\s*-e\s/is)
2457 my $Accept = $'; # Get the expression
2458 $NoAccess &&= eval($Accept); # evaluate the expresion
2460 else
2462 my ($Accept, @FilePatternList) = split;
2463 if($Accept eq '*' # Always match
2464 ||$REMOTE_HOST =~ /\Q$Accept\E$/is # REMOTE_HOST matches
2465 || (
2466 $Accept =~ /^[0-9\.]+$/
2467 && $REMOTE_ADDR =~ /^\Q$Accept\E/ # IP address matches
2471 if($FilePatternList[0])
2473 foreach $Pattern (@FilePatternList)
2475 # Check whether this patterns is accepted
2476 $NoAccess &&= ($PATH_INFO !~ m@\Q$Pattern\E@is);
2479 else
2481 $NoAccess = 0; # No file patterns -> Accepted
2485 # Blocked
2486 last unless $NoAccess;
2488 close(CGI_Accept);
2489 if($NoAccess){ dieHandler(4, "No Access: $PATH_INFO\n");};
2493 # REJECTED CLIENTS
2495 # Reject named clients, accept all unnamed clients
2496 if($CGI_Reject)
2498 # Use local variables, REMOTE_HOST becomes '-' if undefined
2499 my $REMOTE_HOST = $ENV{'REMOTE_HOST'} || '-';
2500 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
2501 my $PATH_INFO = $ENV{'PATH_INFO'};
2503 open(CGI_Reject, "<$CGI_Reject") || dieHandler(5, "$CGI_Reject: $!\n");
2504 $NoAccess = 0;
2505 while(<CGI_Reject>)
2507 next unless /\S/; # Skip empty lines
2508 next if /^\s*\#/; # Skip comments
2510 # Full expressions
2511 if(/^-e\s/is)
2513 my $Reject = $'; # Get the expression
2514 $NoAccess ||= eval($Reject); # evaluate the expresion
2516 else
2518 my ($Reject, @FilePatternList) = split;
2519 if($Reject eq '*' # Always match
2520 ||$REMOTE_HOST =~ /\Q$Reject\E$/is # REMOTE_HOST matches
2521 ||($Reject =~ /^[0-9\.]+$/
2522 && $REMOTE_ADDR =~ /^\Q$Reject\E/is # IP address matches
2526 if($FilePatternList[0])
2528 foreach $Pattern (@FilePatternList)
2530 $NoAccess ||= ($PATH_INFO =~ m@\Q$Pattern\E@is);
2533 else
2535 $NoAccess = 1; # No file patterns -> Rejected
2539 last if $NoAccess;
2541 close(CGI_Reject);
2542 if($NoAccess){ dieHandler(6, "Request rejected: $PATH_INFO\n");};
2545 ##########################################################<<<<<<<<<<End Remove
2548 # Get the filename
2550 # Does the filename contain any illegal characters (e.g., |, >, or <)
2551 dieHandler(7, "Illegal request: $ENV{'PATH_INFO'}\n") if $ENV{'PATH_INFO'} =~ /[^$FileAllowedChars]/;
2552 # Does the pathname contain an illegal (blocked) "directory"
2553 dieHandler(8, "Illegal request: $ENV{'PATH_INFO'}\n") if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@; # Access is blocked
2554 # Does the pathname contain a direct referencer to BinaryMapFile
2555 dieHandler(9, "Illegal request: $ENV{'PATH_INFO'}\n") if $BinaryMapFile && $ENV{'PATH_INFO'} =~ m@\Q$BinaryMapFile\E@; # Access is blocked
2557 # SECURITY: Is PATH_INFO allowed?
2558 if($FilePattern && $ENV{'PATH_INFO'} && $ENV{'PATH_INFO'} ne '-' &&
2559 ($ENV{'PATH_INFO'} !~ m@($FilePattern)$@is))
2561 # Unsupported file types can be processed by a special raw-file
2562 if($BinaryMapFile)
2564 $ENV{'CGI_BINARY_FILE'} = $ENV{'PATH_INFO'};
2565 $ENV{'PATH_INFO'} = $BinaryMapFile;
2567 else
2569 dieHandler(10, "Illegal file\n");
2575 # End of Security Access Control
2578 ############################################################################
2580 # Get the POST part of the query and add it to the QUERY_STRING.
2583 sub Get_POST_part_of_query
2586 # If POST, Read data from stdin to QUERY_STRING
2587 if($ENV{'REQUEST_METHOD'} =~ /POST/is)
2589 # SECURITY: Check size of Query String
2590 $ENV{'CONTENT_LENGTH'} <= $MaximumQuerySize || dieHandler(11, "Query too long: $ENV{'CONTENT_LENGTH'}\n"); # Query too long
2591 my $QueryRead = 0;
2592 my $SystemRead = $ENV{'CONTENT_LENGTH'};
2593 $ENV{'QUERY_STRING'} .= '&' if length($ENV{'QUERY_STRING'}) > 0;
2594 while($SystemRead > 0)
2596 $QueryRead = sysread(STDIN, $Post, $SystemRead); # Limit length
2597 $ENV{'QUERY_STRING'} .= $Post;
2598 $SystemRead -= $QueryRead;
2600 # Update decoded Query String
2601 $default_values{CGI_Decoded_QS} = YOUR_CGIQUERYDECODE();
2602 $default_values{CGI_Content_Length} =
2603 length($default_values{CGI_Decoded_QS});
2607 # End of getting POST part of query
2610 ############################################################################
2612 # Start (HTML) output and logging
2613 # (if there are irregularities, it can kill the current process)
2616 sub Initialize_output
2618 # Construct the REAL file path (except for STDIN on the command line)
2619 my $file_path = $ENV{'PATH_INFO'} ne '-' ? $SS_PUB . $ENV{'PATH_INFO'} : '-';
2620 $file_path =~ s/\?.*$//; # Remove query
2621 # This is only necessary if your server does not catch ../ directives
2622 $file_path !~ m@\.\./@ || dieHandler(12, "Illegal ../ Construct\n"); # SECURITY: Do not allow ../ constructs
2624 # Block STDIN use (-) if CGIscriptor is servicing a HTTP request
2625 if($file_path eq '-')
2627 dieHandler(13, "STDIN request in On Line system\n") if $BLOCK_STDIN_HTTP_REQUEST
2628 && ($ENV{'SERVER_SOFTWARE'}
2629 || $ENV{'SERVER_NAME'}
2630 || $ENV{'GATEWAY_INTERFACE'}
2631 || $ENV{'SERVER_PROTOCOL'}
2632 || $ENV{'SERVER_PORT'}
2633 || $ENV{'REMOTE_ADDR'}
2634 || $ENV{'HTTP_USER_AGENT'});
2639 if($ClientLog)
2641 open(ClientLog, ">>$ClientLog");
2642 print ClientLog "$LocalTime | ",
2643 ($ENV{REMOTE_USER} || "-"), " ",
2644 ($ENV{REMOTE_IDENT} || "-"), " ",
2645 ($ENV{REMOTE_HOST} || "-"), " ",
2646 $ENV{REMOTE_ADDR}, " ",
2647 $ENV{PATH_INFO}, " ",
2648 $ENV{'CGI_BINARY_FILE'}, " ",
2649 ($default_values{CGI_Content_Length} || "-"),
2650 "\n";
2651 close(ClientLog);
2653 if($QueryLog)
2655 open(QueryLog, ">>$QueryLog");
2656 print QueryLog "$LocalTime\n",
2657 ($ENV{REMOTE_USER} || "-"), " ",
2658 ($ENV{REMOTE_IDENT} || "-"), " ",
2659 ($ENV{REMOTE_HOST} || "-"), " ",
2660 $ENV{REMOTE_ADDR}, ": ",
2661 $ENV{PATH_INFO}, " ",
2662 $ENV{'CGI_BINARY_FILE'}, "\n";
2664 # Write Query to Log file
2665 print QueryLog $default_values{CGI_Decoded_QS}, "\n\n";
2666 close(QueryLog);
2669 # Return the file path
2670 return $file_path;
2673 # End of Initialize output
2676 ############################################################################
2678 # Handle login access
2680 # Access is based on a valid session ticket.
2681 # Session tickets should be dependend on user name
2682 # and IP address. The patterns of URLs for which a
2683 # session ticket is needed and the login URL are stored in
2684 # %TicketRequiredPatterns as:
2685 # 'RegEx pattern' -> 'SessionPath\tPasswordPath\tLogin URL\tExpiration'
2688 sub Log_In_Access # () -> 0 = Access Allowed, Login page if access is not allowed
2690 # No patterns, no login
2691 return 0 unless %TicketRequiredPatterns;
2693 # Get and initialize values (watch out for stuff processed by BinaryMap files)
2694 my ($SessionPath, $PasswordsPath, $Login, $valid_duration) = ("", "", "", 0);
2695 my $PATH_INFO = $ENV{'CGI_BINARY_FILE'} ? $ENV{'CGI_BINARY_FILE'} : $ENV{'PATH_INFO'};
2696 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
2697 return 0 if $REMOTE_ADDR =~ /[^0-9\.]/;
2699 # Extract TICKETs, starting with returned cookies
2700 CGIexecute::defineCGIvariable('LOGINTICKET', "");
2701 CGIexecute::defineCGIvariable('SESSIONTICKET', "");
2702 CGIexecute::defineCGIvariable('CHALLENGETICKET', "");
2703 if($ENV{'COOKIE_JAR'})
2705 my $CurrentCookieJar = $ENV{'COOKIE_JAR'};
2706 $CurrentCookieJar =~ s/\w+\=\-\s*(\;\s*|$)//isg;
2707 if($CurrentCookieJar =~ /\s*CGIscriptorLOGIN\=\s*([^\;]+)/)
2709 ${"CGIexecute::LOGINTICKET"} = $1;
2711 if($CurrentCookieJar =~ /\s*CGIscriptorCHALLENGE\=\s*([^\;]+)/ && $1 ne '-')
2713 ${"CGIexecute::CHALLENGETICKET"} = $1;
2715 if($CurrentCookieJar =~ /\s*CGIscriptorSESSION\=\s*([^\;]+)/ && $1 ne '-')
2717 ${"CGIexecute::SESSIONTICKET"} = $1;
2720 # Get and check the tickets. Tickets are restricted to word-characters (alphanumeric+_+.)
2721 my $LOGINTICKET = ${"CGIexecute::LOGINTICKET"};
2722 return 0 if ($LOGINTICKET && $LOGINTICKET =~ /[^\w\.]/isg);
2723 my $SESSIONTICKET = ${"CGIexecute::SESSIONTICKET"};
2724 return 0 if ($SESSIONTICKET && $SESSIONTICKET =~ /[^\w\.]/isg);
2725 my $CHALLENGETICKET = ${"CGIexecute::CHALLENGETICKET"};
2726 return 0 if ($SESSIONTICKET && $SESSIONTICKET =~ /[^\w\.]/isg);
2727 # Look for a LOGOUT message
2728 my $LOGOUT = $ENV{QUERY_STRING} =~ /(^|\&)LOGOUT([\=\&]|$)/;
2729 # Username and password
2730 CGIexecute::defineCGIvariable('USERNAME', "");
2731 my $username = lc(${"CGIexecute::USERNAME"});
2732 return 0 if $username =~ m!^[^\w]!isg || $username =~ m![^\w \-]!isg;
2733 my $userfile = lc($username);
2734 $userfile =~ s/[^\w]/_/isg;
2735 CGIexecute::defineCGIvariable('PASSWORD', "");
2736 my $password = ${"CGIexecute::PASSWORD"};
2737 CGIexecute::defineCGIvariable('NEWPASSWORD', "");
2738 my $newpassword = ${"CGIexecute::NEWPASSWORD"};
2740 foreach my $pattern (keys(%TicketRequiredPatterns))
2742 # Check BOTH the real PATH_INFO and the CGI_BINARY_FILE variable
2743 if($ENV{'PATH_INFO'} =~ m#$pattern# || $ENV{'CGI_BINARY_FILE'} =~ m#$pattern#)
2745 # Fall through a sieve of requirements
2746 ($SessionPath, $PasswordsPath, $Login, $validtime) = split(/\t/, $TicketRequiredPatterns{$pattern});
2747 # If a LOGOUT is present, remove everything
2748 if($LOGOUT && !$LOGINTICKET)
2750 unlink "$SessionPath/$LOGINTICKET" if $LOGINTICKET && (-s "$SessionPath/$LOGINTICKET");
2751 $LOGINTICKET = "";
2752 unlink "$SessionPath/$SESSIONTICKET" if $SESSIONTICKET && (-s "$SessionPath/$SESSIONTICKET");
2753 $SESSIONTICKET = "";
2754 unlink "$SessionPath/$CHALLENGETICKET" if $CHALLENGETICKET && (-s "$SessionPath/$CHALLENGETICKET");
2755 $CHALLENGETICKET = "";
2756 unlink "$SessionPath/$REMOTE_ADDR" if (-s "$SessionPath/$$REMOTE_ADDR");
2757 $CHALLENGETICKET = "";
2758 goto Login;
2760 # Is there a change password request?
2761 if($newpassword && $LOGINTICKET && $username)
2763 my $tickets_removed = remove_expired_tickets($SessionPath);
2764 goto Login unless (-s "$SessionPath/$LOGINTICKET");
2765 goto Login unless (-s "$PasswordsPath/$userfile");
2766 my ($sessiontype, $currentticket) = ("", "");
2767 if($CHALLENGETICKET) {($sessiontype, $currentticket) = ("CHALLENGE", $CHALLENGETICKET);}
2768 elsif($SESSIONTICKET) {($sessiontype, $currentticket) = ("SESSION", $SESSIONTICKET);}
2769 elsif(-s "$SessionPath/$REMOTE_ADDR") {($sessiontype, $currentticket) = ("IPADDRESS", $REMOTE_ADDR);
2771 if($sessiontype)
2773 goto Login unless (-s "$SessionPath/$currentticket");
2774 my $ticket_valid = check_ticket_validity($sessiontype, "$SessionPath/$currentticket", $REMOTE_ADDR, $PATH_INFO);
2775 goto Login unless $ticket_valid;
2777 # Authorize
2778 change_password("$SessionPath/$LOGINTICKET", "$SessionPath/$currentticket", "$PasswordsPath/$userfile", $password, $newpassword);
2779 # After a change of password, you have to login again for a CHALLENGE
2780 if($CHALLENGETICKET){$CHALLENGETICKET = "";};
2781 # Ready
2782 return 0;
2784 # Is there a login ticket of this name?
2785 elsif($LOGINTICKET)
2787 my $tickets_removed = remove_expired_tickets($SessionPath);
2788 goto Login unless (-s "$SessionPath/$LOGINTICKET");
2789 goto Login unless (-s "$PasswordsPath/$userfile");
2790 my $ticket_valid = check_ticket_validity("LOGIN", "$SessionPath/$LOGINTICKET", $REMOTE_ADDR, ".");
2791 goto Login unless $ticket_valid;
2793 # Remove any lingering tickets
2794 unlink "$SessionPath/$SESSIONTICKET" if $SESSIONTICKET && (-s "$SessionPath/$SESSIONTICKET");
2795 $SESSIONTICKET = "";
2796 unlink "$SessionPath/$CHALLENGETICKET" if $CHALLENGETICKET && (-s "$SessionPath/$CHALLENGETICKET");
2797 $CHALLENGETICKET = "";
2800 # Authorize
2801 my $TMPTICKET = authorize_login("$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $password, $SessionPath);
2802 if($TMPTICKET)
2804 my $authorization = read_ticket("$PasswordsPath/$userfile");
2805 # Session type is read from the userfile
2806 if($authorization->{"Session"} && $authorization->{"Session"}->[0] eq "CHALLENGE")
2808 # Create New Random CHALLENGETICKET
2809 $CHALLENGETICKET = $TMPTICKET;
2810 create_session_file("$SessionPath/$CHALLENGETICKET", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
2812 elsif($authorization->{"Session"} && $authorization->{"Session"}->[0] eq "IPADDRESS")
2814 create_session_file("$SessionPath/$REMOTE_ADDR", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
2816 else
2818 $SESSIONTICKET = $TMPTICKET;
2819 create_session_file("$SessionPath/$SESSIONTICKET", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
2820 $SETCOOKIELIST{"CGIscriptorSESSION"} = "-";
2823 # Login ticket file has been used, remove it
2824 unlink($loginfile);
2826 # Is there a session ticket of this name?
2827 # CHALLENGE
2828 if($CHALLENGETICKET)
2830 goto Login unless (-s "$SessionPath/$CHALLENGETICKET");
2831 my $ticket_valid = check_ticket_validity("CHALLENGE", "$SessionPath/$CHALLENGETICKET", $REMOTE_ADDR, $PATH_INFO);
2832 goto Login unless $ticket_valid;
2833 my $oldchallenge = read_ticket("$SessionPath/$CHALLENGETICKET");
2834 my $userfile = lc($oldchallenge->{"Username"}->[0]);
2835 $userfile =~ s/[^\w]/_/isg;
2836 my $NEWCHALLENGETICKET = "";
2837 $NEWCHALLENGETICKET = copy_challenge_file("$SessionPath/$CHALLENGETICKET", "$PasswordsPath/$userfile", $SessionPath);
2838 # Sessionticket is available to scripts, do NOT set the cookie
2839 $ENV{'CHALLENGETICKET'} = $NEWCHALLENGETICKET;
2840 return 0;
2842 # IPADDRESS
2843 elsif(-s "$SessionPath/$REMOTE_ADDR")
2845 my $ticket_valid = check_ticket_validity("IPADDRESS", "$SessionPath/$REMOTE_ADDR", $REMOTE_ADDR, $PATH_INFO);
2846 goto Login unless $ticket_valid;
2847 return 0;
2849 # SESSION
2850 elsif($SESSIONTICKET)
2852 goto Login unless (-s "$SessionPath/$SESSIONTICKET");
2853 my $ticket_valid = check_ticket_validity("SESSION", "$SessionPath/$SESSIONTICKET", $REMOTE_ADDR, $PATH_INFO);
2854 goto Login unless $ticket_valid;
2855 # Sessionticket is available to scripts
2856 $ENV{'SESSIONTICKET'} = $SESSIONTICKET;
2857 return 0;
2860 goto Login;
2861 return 0;
2864 return 0;
2866 Login:
2867 create_login_file($PasswordsPath, $SessionPath, $REMOTE_ADDR);
2868 # Note, cookies are set only ONCE
2869 $SETCOOKIELIST{"CGIscriptorLOGIN"} = "-";
2870 return "$YOUR_HTML_FILES/$Login";
2873 sub authorize_login # ($loginfile, $authorizationfile, $password, $SessionPath) => SESSIONTICKET First two arguments are file paths
2875 my $loginfile = shift || "";
2876 my $authorizationfile = shift || "";
2877 my $password = shift || "";
2878 my $SessionPath = shift || "";
2880 # Get Login session ticket
2881 my $loginticket = read_ticket($loginfile);
2882 # Get User credentials for authorization
2883 my $authorization = read_ticket($authorizationfile);
2885 # Get Randomsalt
2886 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
2887 return "" unless $Randomsalt;
2889 my $storedpassword = $authorization->{'Password'}->[0];
2890 return "" unless $storedpassword;
2891 # Without the "bash -c", the 'echo -n' could use sh, which does not recognize the -n option
2892 my $Hashedpassword = `bash -c 'echo -n $Randomsalt$storedpassword| $ENV{"SHASUMCMD"}'`;
2893 chomp($Hashedpassword);
2894 return "" unless $password eq $Hashedpassword;
2896 # Extract Session Ticket
2897 my $loginsession = $loginticket->{'Session'}->[0];
2898 my $sessionticket = `bash -c 'echo -n $loginsession$storedpassword| $ENV{"SHASUMCMD"}'`;
2899 chomp($sessionticket);
2900 $sessionticket = "" if -x "$SessionPath/$sessionticket";
2902 return $sessionticket;
2905 sub change_password # ($loginfile, $sessionfile, $authorizationfile, $password, $newpassword) First two arguments are file paths
2907 my $loginfile = shift || "";
2908 my $sessionfile = shift || "";
2909 my $authorizationfile = shift || "";
2910 my $password = shift || "";
2911 my $newpassword = shift || "";
2912 # Get Login session ticket
2913 my $loginticket = read_ticket($loginfile);
2914 # Login ticket file has been used, remove it
2915 unlink($loginfile);
2916 # Get Randomsalt
2917 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
2919 return "" unless $Randomsalt;
2921 # Get session ticket
2922 my $sessionticket = read_ticket($sessionfile);
2923 # Get User credentials for authorization
2924 my $authorization = read_ticket($authorizationfile);
2925 return "" unless lc($authorization->{'Username'}->[0]) eq lc($sessionticket->{'Username'}->[0]);
2927 my $storedpassword = $authorization->{'Password'}->[0];
2928 # Without the "bash -c", the 'echo -n' could use sh, which does not recognize the -n option
2929 my $Hashedpassword = `bash -c 'echo -n $Randomsalt$storedpassword| $ENV{"SHASUMCMD"}'`;
2930 chomp($Hashedpassword);
2931 return "" unless $password eq $Hashedpassword;
2933 # Decrypt the $newpassword
2934 my $loginticketid = $loginticket->{'Session'}->[0];
2935 my $passwordkey = `bash -c 'echo -n $loginticketid$storedpassword| $ENV{"SHASUMCMD"}'`;
2936 chomp($passwordkey);
2937 my $decryptedPassword = XOR_hex_strings($passwordkey, $newpassword);
2938 return "" unless $decryptedPassword;
2939 # Authorization succeeded, change password
2940 $authorization->{'Password'}->[0] = $decryptedPassword;
2942 open(USERFILE, "<$authorizationfile") || die "<$authorizationfile: $!\n";
2943 my @USERlines = <USERFILE>;
2944 close(USERFILE);
2945 # Change
2946 open(USERFILE, ">$authorizationfile") || die ">$authorizationfile: $!\n";
2947 foreach my $line (@USERlines)
2949 $line =~ s/^Password: ($storedpassword)$/Password: $decryptedPassword/ig;
2950 print USERFILE $line;
2952 close(USERFILE);
2954 return $newpassword;
2957 sub XOR_hex_strings # (hex1, hex2) -> hex
2959 my $hex1 = shift || "";
2960 my $hex2 = shift || "";
2961 my @hex1list = split('', $hex1);
2962 my @hex2list = split('', $hex2);
2963 my @hexresultlist = ();
2964 for(my $i; $i < scalar(@hex1list); ++$i)
2966 my $d1 = hex($hex1list[$i]);
2967 my $d2 = hex($hex2list[$i]);
2968 my $dresult = ($d1 ^ $d2);
2969 $hexresultlist[$i] = sprintf("%x", $dresult);
2971 $hexresult = join('', @hexresultlist);
2972 return $hexresult;
2975 # Copy a Challenge ticket file to a new name which is the hash of the new $CHALLENGETICKET and the password
2976 sub copy_challenge_file #($oldchallengefile, $authorizationfile, $sessionpath) -> $CHALLENGETICKET
2978 my $oldchallengefile = shift || "";
2979 my $authorizationfile = shift || "";
2980 my $sessionpath = shift || "";
2981 $sessionpath =~ s!/+$!!g;
2983 # Get Login session ticket
2984 my $oldchallenge = read_ticket($oldchallengefile);
2986 # Get Authorization (user) session file
2987 my $authorization = read_ticket($authorizationfile);
2988 my $storedpassword = $authorization->{'Password'}->[0];
2989 return "" unless $storedpassword;
2990 my $challengekey = $oldchallenge->{'Key'}->[0];
2991 return "" unless $challengekey;
2993 # Create Random Hash Salt
2994 open(URANDOM, "$RANDOMHASHCMD |") || die "URANDOM; $RANDOMHASHCMD | $!\n";
2995 my $NEWCHALLENGETICKET = <URANDOM>;
2996 close(URANDOM);
2997 chomp($NEWCHALLENGETICKET);
2998 my $newchallengefile = `bash -c 'echo -n $NEWCHALLENGETICKET$challengekey| $ENV{"SHASUMCMD"}'`;
2999 chomp($newchallengefile);
3000 return "" unless $newchallengefile;
3002 $ENV{'CHALLENGETICKET'} = $NEWCHALLENGETICKET;
3003 CGIexecute::defineCGIvariable('CHALLENGETICKET', "");
3004 ${"CGIexecute::CHALLENGETICKET"} = $NEWCHALLENGETICKET;
3006 # Write Session Ticket
3007 open(OLDCHALLENGE, "<$oldchallengefile") || die "<$oldchallengefile: $!\n";
3008 my @OldChallengeLines = <OLDCHALLENGE>;
3009 close(OLDCHALLENGE);
3010 # Old file should now be removed
3011 unlink($oldchallengefile);
3013 open(SESSION, ">$sessionpath/$newchallengefile") || die "$sessionpath/$newchallengefile: $!\n";
3014 foreach $line (@OldChallengeLines)
3016 print SESSION $line;
3018 close(SESSION);
3020 return $NEWCHALLENGETICKET;
3023 sub create_login_file #($PasswordDir, $SessionDir, $IPaddress)
3025 my $PasswordDir = shift || "";
3026 my $SessionDir = shift || "";
3027 my $IPaddress = shift || "";
3029 # Create Login Ticket
3030 open(URANDOM, "$RANDOMHASHCMD |") || die "URANDOM; $!\n";
3031 my $LOGINTICKET= <URANDOM>;
3032 close(URANDOM);
3033 chomp($LOGINTICKET);
3035 # Create Random Hash Salt
3036 open(URANDOM, "$RANDOMHASHCMD |") || die "URANDOM; $RANDOMHASHCMD | $!\n";
3037 my $RANDOMSALT= <URANDOM>;
3038 close(URANDOM);
3039 chomp($RANDOMSALT);
3041 # Create SALT file if it does not exist
3042 # Remove this, including test account for life system
3043 unless(-d "$SessionDir")
3045 `mkdir -p "$SessionDir"`;
3047 unless(-d "$PasswordDir")
3049 `mkdir -p "$PasswordDir"`;
3051 # Create SERVERSALT and default test account
3052 my $SERVERSALT = "";
3053 unless(-s "$PasswordDir/SALT")
3055 open(URANDOM, "$RANDOMHASHCMD |") || die "URANDOM; $!\n";
3056 $SERVERSALT= <URANDOM>;
3057 chomp($SERVERSALT);
3058 close(URANDOM);
3059 open(SALTFILE, ">$PasswordDir/SALT") || die ">$PasswordDir/SALT: $!\n";
3060 print SALTFILE "$SERVERSALT\n";
3061 close(SALTFILE);
3063 # Update test account (should be removed in live system)
3064 my @alltestusers = ("test", "testip", "testchallenge");
3065 foreach my $testuser (@alltestusers)
3067 if(-s "$PasswordDir/$testuser")
3069 my $storedpassword = `bash -c 'echo -n ${SERVERSALT}test${testuser} | $ENV{"SHASUMCMD"}'`;
3070 chomp($storedpassword);
3071 open(USERFILE, "<$PasswordDir/$testuser") || die "</Private/.Passwords/$testuser: $!\n";
3072 @USERlines = <USERFILE>;
3073 close(USERFILE);
3075 open(USERFILE, ">$PasswordDir/$testuser") || die ">/Private/.Passwords/$testuser: $!\n";
3076 # Add Password and Salt
3077 foreach my $line (@USERlines)
3079 $line =~ s/^Password: (.*)$/Password: $storedpassword/ig;
3080 $line =~ s/^Salt: (.*)$/Salt: $SERVERSALT/ig;
3082 print USERFILE $line;
3084 close(USERFILE);
3090 # Read in site Salt
3091 open(SALTFILE, "<$PasswordDir/SALT") || die "$PasswordDir/SALT: $!\n";
3092 $SERVERSALT=<SALTFILE>;
3093 close(SALTFILE);
3094 chomp($SERVERSALT);
3096 # Create login session ticket
3097 open(LOGINTICKET, ">$SessionDir/$LOGINTICKET") || die "$SessionDir/$LOGINTICKET: $!\n";
3098 print LOGINTICKET << "ENDOFLOGINTICKET";
3099 Type: LOGIN
3100 IPaddress: $IPaddress
3101 Salt: $SERVERSALT
3102 Session: $LOGINTICKET
3103 Randomsalt: $RANDOMSALT
3104 Expires: +600s
3105 ENDOFLOGINTICKET
3106 close(LOGINTICKET);
3108 # Set global variables
3109 # $SERVERSALT
3110 $ENV{'SERVERSALT'} = $SERVERSALT;
3111 CGIexecute::defineCGIvariable('SERVERSALT', "");
3112 ${"CGIexecute::SERVERSALT"} = $SERVERSALT;
3114 # $SESSIONTICKET
3115 $ENV{'SESSIONTICKET'} = $SESSIONTICKET;
3116 CGIexecute::defineCGIvariable('SESSIONTICKET', "");
3117 ${"CGIexecute::SESSIONTICKET"} = $SESSIONTICKET;
3119 # $RANDOMSALT
3120 $ENV{'RANDOMSALT'} = $RANDOMSALT;
3121 CGIexecute::defineCGIvariable('RANDOMSALT', "");
3122 ${"CGIexecute::RANDOMSALT"} = $RANDOMSALT;
3124 # $LOGINTICKET
3125 $ENV{'LOGINTICKET'} = $LOGINTICKET;
3126 CGIexecute::defineCGIvariable('LOGINTICKET', "");
3127 ${"CGIexecute::LOGINTICKET"} = $LOGINTICKET;
3129 return $ENV{'LOGINTICKET'};
3132 sub create_session_file #($sessionfile, $loginfile, $authorizationfile, $path) -> Is $loginfile deleted? 0/1
3134 my $sessionfile = shift || "";
3135 my $loginfile = shift || "";
3136 my $authorizationfile = shift || "";
3137 my $path = shift || "";
3139 # Get Login session ticket
3140 my $loginticket = read_ticket($loginfile);
3142 # Get Authorization (user) session file
3143 my $authorization = read_ticket($authorizationfile);
3144 # For a Session or a Challenge, we need a stored key
3145 my $sessionkey = "";
3146 if($authorization->{'Session'} && $authorization->{'Session'}->[0] ne 'IPADDRESS')
3148 my $storedpassword = $authorization->{'Password'}->[0];
3149 my $loginticketid = $loginticket->{'Session'}->[0];
3150 $sessionkey = `bash -c 'echo -n $loginticketid$storedpassword| $ENV{"SHASUMCMD"}'`;
3151 chomp($sessionkey);
3154 my @IPaddress = @{$loginticket->{'IPaddress'}};
3155 my @AllowedPaths = @{$authorization->{'AllowedPaths'}};;
3156 my @Expires = ();
3157 foreach my $pattern (keys(%TicketRequiredPatterns))
3159 if($path =~ m#$pattern#)
3161 my ($SessionPath, $PasswordsPath, $Login, $validtime) = split(/\t/, $TicketRequiredPatterns{$pattern});
3162 push(@Expires, $validtime);
3166 # Write Session Ticket
3167 open(SESSION, ">$sessionfile") || die "$sessionfile: $!\n";
3168 if($authorization->{'Session'} && $authorization->{'Session'}->[0])
3170 print SESSION "Type: ", $authorization->{'Session'}->[0], "\n";
3172 else
3174 print SESSION "Type: SESSION\n";
3176 foreach my $address (@IPaddress)
3178 print SESSION "IPaddress: $address\n";
3180 foreach my $path (@AllowedPaths)
3182 print SESSION "AllowedPaths: $path\n";
3184 foreach my $validtime (@Expires)
3186 print SESSION "Expires: $validtime\n";
3188 print SESSION "Username: ", lc($authorization->{'Username'}->[0]), "\n";
3189 print SESSION "Key: $sessionkey\n" if $sessionkey;
3190 close(SESSION);
3192 # Login file should now be removed
3193 return unlink($loginfile);
3196 sub check_ticket_validity # ($type, $ticketfile, $address, $path)
3198 my $type = shift || "SESSION";
3199 my $ticketfile = shift || "";
3200 my $address = shift || "";
3201 my $path = shift || "";
3203 # Is there a session ticket of this name?
3204 return 0 unless -s "$ticketfile";
3206 # There is a session ticket, is it linked to this IP address?
3207 my $ticket = read_ticket($ticketfile);
3209 # Is this the right type of ticket
3210 return unless $ticket->{"Type"}->[0] eq $type;
3212 # Does the IP address match?
3213 $IPmatches = 0;
3214 for my $IPpattern (@{$ticket->{"IPaddress"}})
3216 ++$IPmatches if $address =~ m#^$IPpattern#ig;
3218 return 0 unless !$ticket->{"IPaddress"} || $IPmatches;
3220 # Is the path allowed
3221 my $Pathmatches = 0;
3222 foreach my $Pathpattern (@{$ticket->{"AllowedPaths"}})
3224 ++$Pathmatches if $path =~ m#$Pathpattern#ig;
3226 return 0 unless !@{$ticket->{"AllowedPaths"}} || $Pathmatches;
3228 # Is the ticket expired?
3229 my $Expired = 0;
3230 if($ticket->{"Expires"} && @{$ticket->{"Expires"}})
3232 my $CurrentTime = time();
3233 ++$Expired if($CurrentTime > $ticket->{"Expires"}->[0]);
3235 return 0 if $Expired;
3237 # Make login values available
3238 $ENV{"LOGINUSERNAME"} = lc($ticket->{'Username'}->[0]);
3239 $ENV{"LOGINIPADDRESS"} = $address;
3240 $ENV{"LOGINPATH"} = $path;
3241 $ENV{"SESSIONTYPE"} = $type;
3243 return 1;
3247 sub remove_expired_tickets # ($path) -> number of tickets removed
3249 my $path = shift || "";
3250 return 0 unless $path;
3251 $path =~ s!/+$!!g;
3252 my $removed_tickets = 0;
3253 my @ticketlist = glob("$path/*");
3254 foreach my $ticketfile (@ticketlist)
3256 my $ticket = read_ticket($ticketfile);
3257 if(@{$ticket->{'Expires'}} && $ticket->{'Expires'}->[0] < time)
3259 unlink $ticketfile;
3260 ++$removed_tickets;
3263 return $removed_tickets;
3266 sub read_ticket # ($ticketfile) -> &%ticket
3268 my $ticketfile = shift || "";
3269 my $ticket = {};
3270 if($ticketfile && -s $ticketfile)
3272 open(TICKETFILE, "<$ticketfile") || die "$ticketfile: $!\n";
3273 my @alllines = <TICKETFILE>;
3274 close(TICKETFILE);
3275 foreach my $currentline (@alllines)
3277 if($currentline =~ /^\s*(\S[^\:]+)\:\s+(.*)\s*$/)
3279 my $Label = $1;
3280 my $Value = $2;
3281 # Recalculate expire date from relative time
3282 if($Label =~ /^Expires$/ig && $Value =~ /^\+/)
3284 # Get SessionTicket file stats
3285 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)
3286 = stat("$ticketfile");
3287 if($Value =~ /^\+(\d+)\s*d(ays)?\s*$/)
3289 $ExpireTime = 24*3600*$1;
3291 elsif($Value =~ /^\+(\d+)\s*m(inutes)?\s*$/)
3293 $ExpireTime = 60*$1;
3295 elsif($Value =~ /^\+(\d+)\s*h(ours)?\s*$/)
3297 $ExpireTime = 3600*$1;
3299 elsif($Value =~ /^\+(\d+)\s*s(econds)?\s*$/)
3301 $ExpireTime = $1;
3303 elsif($Value =~ /^\+(\d+)\s*$/)
3305 $ExpireTime = $1;
3308 my $ActualExpireTime = $ExpireTime + $ctime;
3309 $Value = $ActualExpireTime;
3311 $ticket->{$Label} = () unless exists($ticket->{$Label});
3312 push(@{$ticket->{$Label}}, $Value);
3316 if(exists($ticket->{Expires}))
3318 @{$ticket->{Expires}} = sort(@{$ticket->{Expires}});
3320 return $ticket;
3323 # End of Handle login access
3326 ############################################################################
3328 # Handle foreign interpreters (i.e., scripting languages)
3330 # Insert perl code to execute scripts in foreign scripting languages.
3331 # Actually, the scripts inside the <SCRIPT></SCRIPT> blocks are piped
3332 # into an interpreter.
3333 # The code presented here is fairly confusing because it
3334 # actually writes perl code code to the output.
3336 # A table with the file handles
3337 %SCRIPTINGINPUT = ();
3339 # A function to clean up Client delivered CGI parameter values
3340 # (i.e., quote all odd characters)
3341 %SHRUBcharacterTR =
3343 "\'" => '&#39;',
3344 "\`" => '&#96;',
3345 "\"" => '&quot;',
3346 '&' => '&amper;',
3347 "\\" => '&#92;'
3350 sub shrubCGIparameter # ($String) -> Cleaned string
3352 my $String = shift || "";
3354 # Change all quotes [`'"] into HTML character entities
3355 my ($Char, $Transcript) = ('&', $SHRUBcharacterTR{'&'});
3357 # Protect &
3358 $String =~ s/\Q$Char\E/$Transcript/isg if $Transcript;
3360 while( ($Char, $Transcript) = each %SHRUBcharacterTR)
3362 next if $Char eq '&';
3363 $String =~ s/\Q$Char\E/$Transcript/isg;
3366 # Replace newlines
3367 $String =~ s/[\n]/\\n/g;
3368 # Replace control characters with their backslashed octal ordinal numbers
3369 $String =~ s/([^\S \t])/(sprintf("\\0%o", ord($1)))/eisg; #
3370 $String =~ s/([\x00-\x08\x0A-\x1F])/(sprintf("\\0%o", ord($1)))/eisg; #
3372 return $String;
3376 # The initial open statements: Open a pipe to the foreign script interpreter
3377 sub OpenForeignScript # ($ContentType) -> $DirectivePrefix
3379 my $ContentType = lc(shift) || return "";
3380 my $NewDirective = "";
3382 return $NewDirective if($SCRIPTINGINPUT{$ContentType});
3384 # Construct a unique file handle name
3385 $SCRIPTINGFILEHANDLE = uc($ContentType);
3386 $SCRIPTINGFILEHANDLE =~ s/\W/\_/isg;
3387 $SCRIPTINGINPUT{$ContentType} = $SCRIPTINGFILEHANDLE
3388 unless $SCRIPTINGINPUT{$ContentType};
3390 # Create the relevant script: Open the pipe to the interpreter
3391 $NewDirective .= <<"BLOCKCGISCRIPTOROPEN";
3392 # Open interpreter for '$ContentType'
3393 # Open pipe to interpreter (if it isn't open already)
3394 open($SCRIPTINGINPUT{$ContentType}, "|$ScriptingLanguages{$ContentType}") || main::dieHandler(14, "$ContentType: \$!\\n");
3395 BLOCKCGISCRIPTOROPEN
3397 # Insert Initialization code and CGI variables
3398 $NewDirective .= InitializeForeignScript($ContentType);
3400 # Ready
3401 return $NewDirective;
3405 # The final closing code to stop the interpreter
3406 sub CloseForeignScript # ($ContentType) -> $DirectivePrefix
3408 my $ContentType = lc(shift) || return "";
3409 my $NewDirective = "";
3411 # Do nothing unless the pipe realy IS open
3412 return "" unless $SCRIPTINGINPUT{$ContentType};
3414 # Initial comment
3415 $NewDirective .= "\# Close interpreter for '$ContentType'\n";
3418 # Write the Postfix code
3419 $NewDirective .= CleanupForeignScript($ContentType);
3421 # Create the relevant script: Close the pipe to the interpreter
3422 $NewDirective .= <<"BLOCKCGISCRIPTORCLOSE";
3423 close($SCRIPTINGINPUT{$ContentType}) || main::dieHandler(15, \"$ContentType: \$!\\n\");
3424 select(STDOUT); \$|=1;
3426 BLOCKCGISCRIPTORCLOSE
3428 # Remove the file handler of the foreign script
3429 delete($SCRIPTINGINPUT{$ContentType});
3431 return $NewDirective;
3435 # The initialization code for the foreign script interpreter
3436 sub InitializeForeignScript # ($ContentType) -> $DirectivePrefix
3438 my $ContentType = lc(shift) || return "";
3439 my $NewDirective = "";
3441 # Add initialization code
3442 if($ScriptingInitialization{$ContentType})
3444 $NewDirective .= <<"BLOCKCGISCRIPTORINIT";
3445 # Initialization Code for '$ContentType'
3446 # Select relevant output filehandle
3447 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
3449 # The Initialization code (if any)
3450 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}INITIALIZATIONCODE';
3451 $ScriptingInitialization{$ContentType}
3452 ${ContentType}INITIALIZATIONCODE
3454 BLOCKCGISCRIPTORINIT
3457 # Add all CGI variables defined
3458 if(exists($ScriptingCGIvariables{$ContentType}))
3460 # Start writing variable definitions to the Interpreter
3461 if($ScriptingCGIvariables{$ContentType})
3463 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEF";
3464 # CGI variables (from the %default_values table)
3465 print $SCRIPTINGINPUT{$ContentType} << '${ContentType}CGIVARIABLES';
3466 BLOCKCGISCRIPTORVARDEF
3469 my ($N, $V);
3470 foreach $N (keys(%default_values))
3472 # Determine whether the parameter has been defined
3473 # (the eval is a workaround to get at the variable value)
3474 next unless eval("defined(\$CGIexecute::$N)");
3476 # Get the value from the EXECUTION environment
3477 $V = eval("\$CGIexecute::$N");
3478 # protect control characters (i.e., convert them to \0.. form)
3479 $V = shrubCGIparameter($V);
3481 # Protect interpolated variables
3482 eval("\$CGIexecute::$N = '$V';") unless $ScriptingCGIvariables{$ContentType};
3484 # Print the actual declaration for this scripting language
3485 if($ScriptingCGIvariables{$ContentType})
3487 $NewDirective .= sprintf($ScriptingCGIvariables{$ContentType}, $N, $V);
3488 $NewDirective .= "\n";
3492 # Stop writing variable definitions to the Interpreter
3493 if($ScriptingCGIvariables{$ContentType})
3495 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEFEND";
3496 ${ContentType}CGIVARIABLES
3497 BLOCKCGISCRIPTORVARDEFEND
3502 $NewDirective .= << "BLOCKCGISCRIPTOREND";
3504 # Select STDOUT filehandle
3505 select(STDOUT); \$|=1;
3507 BLOCKCGISCRIPTOREND
3509 return $NewDirective;
3513 # The cleanup code for the foreign script interpreter
3514 sub CleanupForeignScript # ($ContentType) -> $DirectivePrefix
3516 my $ContentType = lc(shift) || return "";
3517 my $NewDirective = "";
3519 # Return if not needed
3520 return $NewDirective unless $ScriptingCleanup{$ContentType};
3522 # Create the relevant script: Open the pipe to the interpreter
3523 $NewDirective .= <<"BLOCKCGISCRIPTORSTOP";
3524 # Cleanup Code for '$ContentType'
3525 # Select relevant output filehandle
3526 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
3527 # Print Cleanup code to foreign script
3528 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}SCRIPTSTOP';
3529 $ScriptingCleanup{$ContentType}
3530 ${ContentType}SCRIPTSTOP
3532 # Select STDOUT filehandle
3533 select(STDOUT); \$|=1;
3534 BLOCKCGISCRIPTORSTOP
3536 return $NewDirective;
3540 # The prefix code for each <script></script> block
3541 sub PrefixForeignScript # ($ContentType) -> $DirectivePrefix
3543 my $ContentType = lc(shift) || return "";
3544 my $NewDirective = "";
3546 # Return if not needed
3547 return $NewDirective unless $ScriptingPrefix{$ContentType};
3549 my $Quote = "\'";
3550 # If the CGIvariables parameter is defined, but empty, interpolate
3551 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
3552 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
3553 !$ScriptingCGIvariables{$ContentType};
3555 # Add initialization code
3556 $NewDirective .= <<"BLOCKCGISCRIPTORPREFIX";
3557 # Prefix Code for '$ContentType'
3558 # Select relevant output filehandle
3559 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
3561 # The block Prefix code (if any)
3562 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}PREFIXCODE$Quote;
3563 $ScriptingPrefix{$ContentType}
3564 ${ContentType}PREFIXCODE
3565 # Select STDOUT filehandle
3566 select(STDOUT); \$|=1;
3567 BLOCKCGISCRIPTORPREFIX
3569 return $NewDirective;
3573 # The postfix code for each <script></script> block
3574 sub PostfixForeignScript # ($ContentType) -> $DirectivePrefix
3576 my $ContentType = lc(shift) || return "";
3577 my $NewDirective = "";
3579 # Return if not needed
3580 return $NewDirective unless $ScriptingPostfix{$ContentType};
3582 my $Quote = "\'";
3583 # If the CGIvariables parameter is defined, but empty, interpolate
3584 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
3585 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
3586 !$ScriptingCGIvariables{$ContentType};
3588 # Create the relevant script: Open the pipe to the interpreter
3589 $NewDirective .= <<"BLOCKCGISCRIPTORPOSTFIX";
3590 # Postfix Code for '$ContentType'
3591 # Select filehandle to interpreter
3592 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
3593 # Print postfix code to foreign script
3594 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SCRIPTPOSTFIX$Quote;
3595 $ScriptingPostfix{$ContentType}
3596 ${ContentType}SCRIPTPOSTFIX
3597 # Select STDOUT filehandle
3598 select(STDOUT); \$|=1;
3599 BLOCKCGISCRIPTORPOSTFIX
3601 return $NewDirective;
3604 sub InsertForeignScript # ($ContentType, $directive, @SRCfile) -> $NewDirective
3606 my $ContentType = lc(shift) || return "";
3607 my $directive = shift || return "";
3608 my @SRCfile = @_;
3609 my $NewDirective = "";
3611 my $Quote = "\'";
3612 # If the CGIvariables parameter is defined, but empty, interpolate
3613 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
3614 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
3615 !$ScriptingCGIvariables{$ContentType};
3617 # Create the relevant script
3618 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
3619 # Insert Code for '$ContentType'
3620 # Select filehandle to interpreter
3621 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
3622 BLOCKCGISCRIPTORINSERT
3624 # Use SRC feature files
3625 my $ThisSRCfile;
3626 while($ThisSRCfile = shift(@_))
3628 # Handle blocks
3629 if($ThisSRCfile =~ /^\s*\{\s*/)
3631 my $Block = $';
3632 $Block = $` if $Block =~ /\s*\}\s*$/;
3633 $NewDirective .= <<"BLOCKCGISCRIPTORSRCBLOCK";
3634 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SRCBLOCKCODE$Quote;
3635 $Block
3636 ${ContentType}SRCBLOCKCODE
3637 BLOCKCGISCRIPTORSRCBLOCK
3639 next;
3642 # Handle files
3643 $NewDirective .= <<"BLOCKCGISCRIPTORSRCFILES";
3644 # Read $ThisSRCfile
3645 open(SCRIPTINGSOURCE, "<$ThisSRCfile") || main::dieHandler(16, "$ThisSRCfILE: \$!");
3646 while(<SCRIPTINGSOURCE>)
3648 print $SCRIPTINGINPUT{$ContentType} \$_;
3650 close(SCRIPTINGSOURCE);
3652 BLOCKCGISCRIPTORSRCFILES
3656 # Add the directive
3657 if($directive)
3659 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
3660 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}DIRECTIVECODE$Quote;
3661 $directive
3662 ${ContentType}DIRECTIVECODE
3663 BLOCKCGISCRIPTORINSERT
3667 $NewDirective .= <<"BLOCKCGISCRIPTORSELECT";
3668 # Select STDOUT filehandle
3669 select(STDOUT); \$|=1;
3670 BLOCKCGISCRIPTORSELECT
3672 # Ready
3673 return $NewDirective;
3676 sub CloseAllForeignScripts # Call CloseForeignScript on all open scripts
3678 my $ContentType;
3679 foreach $ContentType (keys(%SCRIPTINGINPUT))
3681 my $directive = CloseForeignScript($ContentType);
3682 print STDERR "\nDirective $CGI_Date: ", $directive;
3683 CGIexecute->evaluate($directive);
3688 # End of handling foreign (external) scripting languages.
3690 ############################################################################
3692 # A subroutine to handle "nested" quotes, it cuts off the leading
3693 # item or quoted substring
3694 # E.g.,
3695 # ' A_word and more words' -> @('A_word', ' and more words')
3696 # '"quoted string" The rest' -> @('quoted string', ' The rest')
3697 # (this is needed for parsing the <TAGS> and their attributes)
3698 my $SupportedQuotes = "\'\"\`\(\{\[";
3699 my %QuotePairs = ('('=>')','['=>']','{'=>'}'); # Brackets
3700 sub ExtractQuotedItem # ($String) -> @($QuotedString, $RestOfString)
3702 my @Result = ();
3703 my $String = shift || return @Result;
3705 if($String =~ /^\s*([\w\/\-\.]+)/is)
3707 push(@Result, $1, $');
3709 elsif($String =~ /^\s*(\\?)([\Q$SupportedQuotes\E])/is)
3711 my $BackSlash = $1 || "";
3712 my $OpenQuote = $2;
3713 my $CloseQuote = $OpenQuote;
3714 $CloseQuote = $QuotePairs{$OpenQuote} if $QuotePairs{$OpenQuote};
3716 if($BackSlash)
3718 $String =~ /^\s*\\\Q$OpenQuote\E/i;
3719 my $Onset = $';
3720 $Onset =~ /\\\Q$CloseQuote\E/i;
3721 my $Rest = $';
3722 my $Item = $`;
3723 push(@Result, $Item, $Rest);
3726 else
3728 $String =~ /^\s*\Q$OpenQuote\E([^\Q$CloseQuote\E]*)\Q$CloseQuote\E/i;
3729 push(@Result, $1, $');
3732 else
3734 push(@Result, "", $String);
3736 return @Result;
3739 # Now, start with the real work
3741 # Control the output of the Content-type: text/html\n\n message
3742 my $SupressContentType = 0;
3744 # Process a file
3745 sub ProcessFile # ($file_path)
3747 my $file_path = shift || return 0;
3750 # Generate a unique file handle (for recursions)
3751 my @SRClist = ();
3752 my $FileHandle = "file";
3753 my $n = 0;
3754 while(!eof($FileHandle.$n)) {++$n;};
3755 $FileHandle .= $n;
3757 # Start HTML output
3758 # Use the default Content-type if this is NOT a raw file
3759 unless(($RawFilePattern && $ENV{'PATH_INFO'} =~ m@($RawFilePattern)$@i)
3760 || $SupressContentType)
3762 $ENV{'PATH_INFO'} =~ m@($FilePattern)$@i;
3763 my $ContentType = $ContentTypeTable{$1};
3764 print "Content-type: $ContentType\n";
3765 if(%SETCOOKIELIST && keys(%SETCOOKIELIST))
3767 foreach my $name (keys(%SETCOOKIELIST))
3769 my $value = $SETCOOKIELIST{$name};
3770 print "Set-Cookie: $name=$value\n";
3772 # Cookies are set only ONCE
3773 %SETCOOKIELIST = ();
3775 print "\n";
3776 $SupressContentType = 1; # Content type has been printed
3780 # Get access to the actual data. This can be from RAM (by way of an
3781 # environment variable) or by opening a file.
3783 # Handle the use of RAM images (file-data is stored in the
3784 # $CGI_FILE_CONTENTS environment variable)
3785 # Note that this environment variable will be cleared, i.e., it is strictly for
3786 # single-use only!
3787 if($ENV{$CGI_FILE_CONTENTS})
3789 # File has been read already
3790 $_ = $ENV{$CGI_FILE_CONTENTS};
3791 # Sorry, you have to do the reading yourself (dynamic document creation?)
3792 # NOTE: you must read the whole document at once
3793 if($_ eq '-')
3795 $_ = eval("\@_=('$file_path'); do{$ENV{$CGI_DATA_ACCESS_CODE}}");
3797 else # Clear environment variable
3799 $ENV{$CGI_FILE_CONTENTS} = '-';
3802 # Open Only PLAIN TEXT files (or STDIN) and NO executable files (i.e., scripts).
3803 # THIS IS A SECURITY FEATURE!
3804 elsif($file_path eq '-' || (-e "$file_path" && -r _ && -T _ && -f _ && ! (-x _ || -X _) ))
3806 open($FileHandle, $file_path) || dieHandler(17, "<h2>File not found</h2>\n");
3807 push(@OpenFiles, $file_path);
3808 $_ = <$FileHandle>; # Read first line
3810 else
3812 print "<h2>File not found</h2>\n";
3813 dieHandler(18, "$file_path\n");
3816 $| = 1; # Flush output buffers
3818 # Initialize variables
3819 my $METAarguments = ""; # The CGI arguments from the latest META tag
3820 my @METAvalues = (); # The ''-quoted CGI values from the latest META tag
3821 my $ClosedTag = 0; # <TAG> </TAG> versus <TAG/>
3824 # Send document to output
3825 # Process the requested document.
3826 # Do a loop BEFORE reading input again (this catches the RAM/Database
3827 # type of documents).
3828 do {
3831 # Handle translations if needed
3833 performTranslation(\$_) if $TranslationPaths;
3835 # Catch <SCRIPT LANGUAGE="PERL" TYPE="text/ssperl" > directives in $_
3836 # There can be more than 1 <SCRIPT> or META tags on a line
3837 while(/\<\s*(SCRIPT|META|DIV|INS)\s/is)
3839 my $directive = "";
3840 # Store rest of line
3841 my $Before = $`;
3842 my $ScriptTag = $&;
3843 my $After = $';
3844 my $TagType = uc($1);
3845 # The before part can be send to the output
3846 print $Before;
3848 # Read complete Tag from after and/or file
3849 until($After =~ /([^\\])\>/)
3851 $After .= <$FileHandle>;
3852 performTranslation(\$After) if $TranslationPaths;
3855 if($After =~ /([^\\])\>/)
3857 $ScriptTag .= $`.$&; # Keep the Script Tag intact
3858 $After = $';
3860 else
3862 dieHandler(19, "Closing > not found\n");
3865 # The tag could be closed by />, we handle this in the XML way
3866 # and don't process any content (we ignore whitespace)
3867 $ClosedTag = ($ScriptTag =~ m@[^\\]/\s*\>\s*$@) ? 1 : 0;
3870 # TYPE or CLASS?
3871 my $TypeName = ($TagType =~ /META/is) ? "CONTENT" : "TYPE";
3872 $TypeName = "CLASS" if $TagType eq 'DIV' || $TagType eq 'INS';
3874 # Parse <SCRIPT> or <META> directive
3875 # If NOT (TYPE|CONTENT)="text/ssperl" (i.e., $ServerScriptContentType),
3876 # send the line to the output and go to the next loop
3877 my $CurrentContentType = "";
3878 if($ScriptTag =~ /(^|\s)$TypeName\s*=\s*/is)
3880 my ($Type) = ExtractQuotedItem($');
3881 $Type =~ /^\s*([\w\/\-]+)\s*[\,\;]?/;
3882 $CurrentContentType = lc($1); # Note: mime-types are "case-less"
3883 # CSS classes are aliases of $ServerScriptContentType
3884 if($TypeName eq "CLASS" && $CurrentContentType eq $ServerScriptContentClass)
3886 $CurrentContentType = $ServerScriptContentType;
3891 # Not a known server-side content type, print and continue
3892 unless(($CurrentContentType =~
3893 /$ServerScriptContentType|$ShellScriptContentType/is) ||
3894 $ScriptingLanguages{$CurrentContentType})
3896 print $ScriptTag;
3897 $_ = $After;
3898 next;
3902 # A known server-side content type, evaluate
3904 # First, handle \> and \<
3905 $ScriptTag =~ s/\\\>/\>/isg;
3906 $ScriptTag =~ s/\\\</\</isg;
3908 # Extract the CGI, SRC, ID, IF and UNLESS attributes
3909 my %ScriptTagAttributes = ();
3910 while($ScriptTag =~ /(^|\s)(CGI|IF|UNLESS|SRC|ID)\s*=\s*/is)
3912 my $Attribute = $2;
3913 my $Rest = $';
3914 my $Value = "";
3915 ($Value, $ScriptTag) = ExtractQuotedItem($Rest);
3916 $ScriptTagAttributes{uc($Attribute)} = $Value;
3920 # The attribute used to define the CGI variables
3921 # Extract CGI-variables from
3922 # <META CONTENT="text/ssperl; CGI='' SRC=''">
3923 # <SCRIPT TYPE='text/ssperl' CGI='' SRC=''>
3924 # <DIV CLASS='ssperl' CGI='' SRC='' ID=""> tags
3925 # <INS CLASS='ssperl' CGI='' SRC='' ID=""> tags
3926 if($ScriptTagAttributes{'CGI'})
3928 @ARGV = (); # Reset ARGV
3929 $ARGC = 0;
3930 $METAarguments = ""; # Reset the META CGI arguments
3931 @METAvalues = ();
3932 my $Meta_CGI = $ScriptTagAttributes{'CGI'};
3934 # Process default values of variables ($<name> = 'default value')
3935 # Allowed quotes are '', "", ``, (), [], and {}
3936 while($Meta_CGI =~ /(^\s*|[^\\])([\$\@\%]?)([\w\-]+)\s*/is)
3938 my $varType = $2 || '$'; # Variable or list
3939 my $name = $3; # The Name
3940 my $default = "";
3941 $Meta_CGI = $';
3943 if($Meta_CGI =~ /^\s*\=\s*/is)
3945 # Locate (any) default value
3946 ($default, $Meta_CGI) = ExtractQuotedItem($'); # Cut the parameter from the CGI
3948 $RemainingTag = $Meta_CGI;
3951 # Define CGI (or ENV) variable, initalize it from the
3952 # Query string or the default value
3954 # Also construct the @ARGV and @_ arrays. This allows other (SRC=) Perl
3955 # scripts to access the CGI arguments defined in the META tag
3956 # (Not for CGI inside <SCRIPT> tags)
3957 if($varType eq '$')
3959 CGIexecute::defineCGIvariable($name, $default)
3960 || dieHandler(20, "INVALID CGI name/value pair ($name, $default)\n");
3961 push(@METAvalues, "'".${"CGIexecute::$name"}."'");
3962 # Add value to the @ARGV list
3963 push(@ARGV, ${"CGIexecute::$name"});
3964 ++$ARGC;
3966 elsif($varType eq '@')
3968 CGIexecute::defineCGIvariableList($name, $default)
3969 || dieHandler(21, "INVALID CGI name/value list pair ($name, $default)\n");
3970 push(@METAvalues, "'".join("'", @{"CGIexecute::$name"})."'");
3971 # Add value to the @ARGV list
3972 push(@ARGV, @{"CGIexecute::$name"});
3973 $ARGC = scalar(@CGIexecute::ARGV);
3975 elsif($varType eq '%')
3977 CGIexecute::defineCGIvariableHash($name, $default)
3978 || dieHandler(22, "INVALID CGI name/value hash pair ($name, $default)\n");
3979 my @PairList = map {"$_ => ".${"CGIexecute::$name"}{$_}} keys(%{"CGIexecute::$name"});
3980 push(@METAvalues, "'".join("'", @PairList)."'");
3981 # Add value to the @ARGV list
3982 push(@ARGV, %{"CGIexecute::$name"});
3983 $ARGC = scalar(@CGIexecute::ARGV);
3986 # Store the values for internal and later use
3987 $METAarguments .= "$varType".$name.","; # A string of CGI variable names
3989 push(@METAvalues, "\'".eval("\"$varType\{CGIexecute::$name\}\"")."\'"); # ALWAYS add '-quotes around values
3994 # The IF (conditional execution) Attribute
3995 # Evaluate the condition and stop unless it evaluates to true
3996 if($ScriptTagAttributes{'IF'})
3998 my $IFcondition = $ScriptTagAttributes{'IF'};
4000 # Convert SCRIPT calls, ./<script>
4001 $IFcondition =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
4003 # Convert FILE calls, ~/<file>
4004 $IFcondition =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
4006 # Block execution if necessary
4007 unless(CGIexecute->evaluate($IFcondition))
4009 %ScriptTagAttributes = ();
4010 $CurrentContentType = "";
4014 # The UNLESS (conditional execution) Attribute
4015 # Evaluate the condition and stop if it evaluates to true
4016 if($ScriptTagAttributes{'UNLESS'})
4018 my $UNLESScondition = $ScriptTagAttributes{'UNLESS'};
4020 # Convert SCRIPT calls, ./<script>
4021 $UNLESScondition =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
4023 # Convert FILE calls, ~/<file>
4024 $UNLESScondition =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
4026 # Block execution if necessary
4027 if(CGIexecute->evaluate($UNLESScondition))
4029 %ScriptTagAttributes = ();
4030 $CurrentContentType = "";
4034 # The SRC (Source File) Attribute
4035 # Extract any source script files and add them in
4036 # front of the directive
4037 # The SRC list should be emptied
4038 @SRClist = ();
4039 my $SRCtag = "";
4040 my $Prefix = 1;
4041 my $PrefixDirective = "";
4042 my $PostfixDirective = "";
4043 # There is a SRC attribute
4044 if($ScriptTagAttributes{'SRC'})
4046 $SRCtag = $ScriptTagAttributes{'SRC'};
4047 # Remove "file://" prefixes
4048 $SRCtag =~ s@([^\w\/\\]|^)file\://([^\s\/\@\=])@$1$2@gis;
4049 # Expand script filenames "./Script"
4050 $SRCtag =~ s@([^\w\/\\]|^)\./([^\s\/\@\=])@$1$SCRIPT_SUB/$2@gis;
4051 # Expand script filenames "~/Script"
4052 $SRCtag =~ s@([^\w\/\\]|^)\~/([^\s\/\@\=])@$1$HOME_SUB/$2@gis;
4055 # File source tags
4056 while($SRCtag =~ /\S/is)
4058 my $SRCdirective = "";
4060 # Pseudo file, just a switch to go from PREFIXING to POSTFIXING
4061 # SRC files
4062 if($SRCtag =~ /^[\s\;\,]*(POSTFIX|PREFIX)([^$FileAllowedChars]|$)/is)
4064 my $InsertionPlace = $1;
4065 $SRCtag = $2.$';
4067 $Prefix = $InsertionPlace =~ /POSTFIX/i ? 0 : 1;
4068 # Go to next round
4069 next;
4071 # {}-blocks are just evaluated by "do"
4072 elsif($SRCtag =~ /^[\s\;\,]*\{/is)
4074 my $SRCblock = $';
4075 if($SRCblock =~ /\}[\s\;\,]*([^\}]*)$/is)
4077 $SRCblock = $`;
4078 $SRCtag = $1.$';
4079 # SAFEqx shell script blocks
4080 if($CurrentContentType =~ /$ShellScriptContentType/is)
4082 # Handle ''-quotes inside the script
4083 $SRCblock =~ s/[\']/\\$&/gis;
4085 $SRCblock = "print do { SAFEqx(\'".$SRCblock."\'); };'';";
4086 $SRCdirective .= $SRCblock."\n";
4088 # do { SRCblocks }
4089 elsif($CurrentContentType =~ /$ServerScriptContentType/is)
4091 $SRCblock = "print do { $SRCblock };'';";
4092 $SRCdirective .= $SRCblock."\n";
4094 else # The interpreter should handle this
4096 push(@SRClist, "{ $SRCblock }");
4100 else
4101 { dieHandler(23, "Closing \} missing\n");};
4103 # Files are processed as Text or Executable files
4104 elsif($SRCtag =~ /[\s\;\,]*([$FileAllowedChars]+)[\;\,\s]*/is)
4106 my $SrcFile = $1;
4107 $SRCtag = $';
4109 # We are handling one of the external interpreters
4110 if($ScriptingLanguages{$CurrentContentType})
4112 push(@SRClist, $SrcFile);
4114 # We are at the start of a DIV tag, just load all SRC files and/or URL's
4115 elsif($TagType eq 'DIV' || $TagType eq 'INS') # All files are prepended in DIV's
4117 # $SrcFile is a URL pointing to an HTTP or FTP server
4118 if($SrcFile =~ m!^([a-z]+)\://!)
4120 my $URLoutput = CGIscriptor::read_url($SrcFile);
4121 $SRCdirective .= $URLoutput;
4123 # SRC file is an existing file
4124 elsif(-e "$SrcFile")
4126 open(DIVSOURCE, "<$SrcFile") || dieHandler(24, "<$SrcFile: $!\n");
4127 my $Content;
4128 while(sysread(DIVSOURCE, $Content, 1024) > 0)
4130 $SRCdirective .= $Content;
4132 close(DIVSOURCE);
4135 # Executable files are executed as
4136 # `$SrcFile 'ARGV[0]' 'ARGV[1]'`
4137 elsif(-x "$SrcFile")
4139 $SRCdirective .= "print \`$SrcFile @METAvalues\`;'';\n";
4141 # Handle 'standard' files, using ProcessFile
4142 elsif((-T "$SrcFile" || $ENV{$CGI_FILE_CONTENTS})
4143 && $SrcFile =~ m@($FilePattern)$@) # A recursion
4146 # Do not process still open files because it can lead
4147 # to endless recursions
4148 if(grep(/^$SrcFile$/, @OpenFiles))
4149 { dieHandler(25, "$SrcFile allready opened (endless recursion)\n")};
4150 # Prepare meta arguments
4151 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
4152 # Process the file
4153 $SRCdirective .= "main::ProcessFile(\'$SrcFile\');'';\n";
4155 elsif($SrcFile =~ m!^([a-z]+)\://!) # URL's are loaded and printed
4157 $SRCdirective .= GET_URL($SrcFile);
4159 elsif(-T "$SrcFile") # Textfiles are "do"-ed (Perl execution)
4161 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
4162 $SRCdirective .= "do \'$SrcFile\';'';\n";
4164 else # This one could not be resolved (should be handled by BinaryMapFile)
4166 $SRCdirective .= 'print "'.$SrcFile.' cannot be used"'."\n";
4171 # Postfix or Prefix
4172 if($Prefix)
4174 $PrefixDirective .= $SRCdirective;
4176 else
4178 $PostfixDirective .= $SRCdirective;
4181 # The prefix should be handled immediately
4182 $directive .= $PrefixDirective;
4183 $PrefixDirective = "";
4187 # Handle the content of the <SCRIPT></SCRIPT> tags
4188 # Do not process the content of <SCRIPT/>
4189 if($TagType =~ /SCRIPT/is && !$ClosedTag) # The <SCRIPT> TAG
4191 my $EndScriptTag = "";
4193 # Execute SHELL scripts with SAFEqx()
4194 if($CurrentContentType =~ /$ShellScriptContentType/is)
4196 $directive .= "SAFEqx(\'";
4199 # Extract Program
4200 while($After !~ /\<\s*\/SCRIPT[^\>]*\>/is && !eof($FileHandle))
4202 $After .= <$FileHandle>;
4203 performTranslation(\$After) if $TranslationPaths;
4206 if($After =~ /\<\s*\/SCRIPT[^\>]*\>/is)
4208 $directive .= $`;
4209 $EndScriptTag = $&;
4210 $After = $';
4212 else
4214 dieHandler(26, "Missing </SCRIPT> end tag in $ENV{'PATH_INFO'}\n");
4217 # Process only when content should be executed
4218 if($CurrentContentType)
4221 # Remove all comments from Perl scripts
4222 # (NOT from OS shell scripts)
4223 $directive =~ s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/$1/g
4224 if $CurrentContentType =~ /$ServerScriptContentType/i;
4226 # Convert SCRIPT calls, ./<script>
4227 $directive =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
4229 # Convert FILE calls, ~/<file>
4230 $directive =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
4232 # Execute SHELL scripts with SAFEqx(), closing bracket
4233 if($CurrentContentType =~ /$ShellScriptContentType/i)
4235 # Handle ''-quotes inside the script
4236 $directive =~ /SAFEqx\(\'/;
4237 $directive = $`.$&;
4238 my $Executable = $';
4239 $Executable =~ s/[\']/\\$&/gs;
4241 $directive .= $Executable."\');"; # Closing bracket
4244 else
4246 $directive = "";
4249 # Handle the content of the <DIV></DIV> tags
4250 # Do not process the content of <DIV/>
4251 elsif(($TagType eq 'DIV' || $TagType eq 'INS') && !$ClosedTag) # The <DIV> TAGs
4253 my $EndScriptTag = "";
4255 # Extract Text
4256 while($After !~ /\<\s*\/$TagType[^\>]*\>/is && !eof($FileHandle))
4258 $After .= <$FileHandle>;
4259 performTranslation(\$After) if $TranslationPaths;
4262 if($After =~ /\<\s*\/$TagType[^\>]*\>/is)
4264 $directive .= $`;
4265 $EndScriptTag = $&;
4266 $After = $';
4268 else
4270 dieHandler(27, "Missing </$TagType> end tag in $ENV{'PATH_INFO'}\n");
4273 # Add the Postfixed directives (but only when it contains something printable)
4274 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
4275 $PostfixDirective = "";
4278 # Process only when content should be handled
4279 if($CurrentContentType)
4282 # Get the name (ID), and clean it (i.e., remove anything that is NOT part of
4283 # a valid Perl name). Names should not contain $, but we can handle it.
4284 my $name = $ScriptTagAttributes{'ID'};
4285 $name =~ /^\s*[\$\@\%]?([\w\-]+)/;
4286 $name = $1;
4288 # Assign DIV contents to $NAME value OUTSIDE the CGI values!
4289 CGIexecute::defineCGIexecuteVariable($name, $directive);
4290 $directive = "";
4293 # Nothing to execute
4294 $directive = "";
4298 # Handle Foreign scripting languages
4299 if($ScriptingLanguages{$CurrentContentType})
4301 my $newDirective = "";
4302 $newDirective .= OpenForeignScript($CurrentContentType); # Only if not already done
4303 $newDirective .= PrefixForeignScript($CurrentContentType);
4304 $newDirective .= InsertForeignScript($CurrentContentType, $directive, @SRClist);
4305 $newDirective .= PostfixForeignScript($CurrentContentType);
4306 $newDirective .= CloseForeignScript($CurrentContentType); # This shouldn't be necessary
4308 $newDirective .= '"";';
4310 $directive = $newDirective;
4314 # Add the Postfixed directives (but only when it contains something printable)
4315 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
4316 $PostfixDirective = "";
4319 # EXECUTE the script and print the results
4321 # Use this to debug the program
4322 # print STDERR "Directive $CGI_Date: \n", $directive, "\n\n";
4324 my $Result = CGIexecute->evaluate($directive) if $directive; # Evaluate as PERL code
4325 $Result =~ s/\n$//g; # Remove final newline
4327 # Print the Result of evaluating the directive
4328 # (this will handle LARGE, >64 kB output)
4329 my $BytesWritten = 1;
4330 while($Result && $BytesWritten)
4332 $BytesWritten = syswrite(STDOUT, $Result, 64);
4333 $Result = substr($Result, $BytesWritten);
4335 # print $Result; # Could be used instead of above code
4337 # Store result if wanted, i.e., if $CGIscriptorResults has been
4338 # defined in a <META> tag.
4339 push(@CGIexecute::CGIscriptorResults, $Result)
4340 if exists($default_values{'CGIscriptorResults'});
4342 # Process the rest of the input line (this could contain
4343 # another directive)
4344 $_ = $After;
4346 print $_;
4347 } while(<$FileHandle>); # Read and Test AFTER first loop!
4349 close ($FileHandle);
4350 dieHandler(28, "Error in recursion\n") unless pop(@OpenFiles) == $file_path;
4354 ###############################################################################
4356 # Call the whole package
4358 sub Handle_Request
4360 my $file_path = "";
4362 # Initialization Code
4363 Initialize_Request();
4365 # SECURITY: ACCESS CONTROL
4366 Access_Control();
4368 # Read the POST part of the query, if there is one
4369 Get_POST_part_of_query();
4371 # Start (HTML) output and logging
4372 $file_path = Initialize_output();
4374 # Check login access or divert to login procedure
4375 $Use_Login = Log_In_Access();
4376 $file_path = $Use_Login if $Use_Login;
4378 # Record which files are still open (to avoid endless recursions)
4379 my @OpenFiles = ();
4381 # Record whether the default HTML ContentType has already been printed
4382 # but only if the SERVER uses HTTP or some other protocol that might interpret
4383 # a content MIME type.
4385 $SupressContentType = !("$ENV{'SERVER_PROTOCOL'}" =~ /($ContentTypeServerProtocols)/i);
4387 # Process the specified file
4388 ProcessFile($file_path) if $file_path ne $SS_PUB;
4390 # Cleanup all open external (foreign) interpreters
4391 CloseAllForeignScripts();
4394 "" # SUCCESS
4397 # Make a single call to handle an (empty) request
4398 Handle_Request();
4401 # END OF PACKAGE MAIN
4404 ####################################################################################
4406 # The CGIEXECUTE PACKAGE
4408 ####################################################################################
4410 # Isolate the evaluation of directives as PERL code from the rest of the program.
4411 # Remember that each package has its own name space.
4412 # Note that only the FIRST argument of execute->evaluate is actually evaluated,
4413 # all other arguments are accessible inside the first argument as $_[0] to $_[$#_].
4415 package CGIexecute;
4417 sub evaluate
4419 my $self = shift;
4420 my $directive = shift;
4421 $directive = eval($directive);
4422 warn $@ if $@; # Write an error message to STDERR
4423 $directive; # Return value of directive
4427 # defineCGIexecuteVariable($name [, $value]) -> 0/1
4429 # Define and intialize variables inside CGIexecute
4430 # Does no sanity checking, for internal use only
4432 sub defineCGIexecuteVariable # ($name [, $value]) -> 0/1
4434 my $name = shift || return 0; # The Name
4435 my $value = shift || ""; # The value
4437 ${$name} = $value;
4439 return 1;
4442 # defineCGIvariable($name [, $default]) -> 0/1
4444 # Define and intialize CGI variables
4445 # Tries (in order) $ENV{$name}, the Query string and the
4446 # default value.
4447 # Removes all '-quotes etc.
4449 sub defineCGIvariable # ($name [, $default]) -> 0/1
4451 my $name = shift || return 0; # The Name
4452 my $default = shift || ""; # The default value
4454 # Remove \-quoted characters
4455 $default =~ s/\\(.)/$1/g;
4456 # Store default values
4457 $::default_values{$name} = $default if $default;
4459 # Process variables
4460 my $temp = undef;
4461 # If there is a user supplied value, it replaces the
4462 # default value.
4464 # Environment values have precedence
4465 if(exists($ENV{$name}))
4467 $temp = $ENV{$name};
4469 # Get name and its value from the query string
4470 elsif($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
4472 $temp = ::YOUR_CGIPARSE($name);
4474 # Defined values must exist for security
4475 elsif(!exists($::default_values{$name}))
4477 $::default_values{$name} = undef;
4480 # SECURITY, do not allow '- and `-quotes in
4481 # client values.
4482 # Remove all existing '-quotes
4483 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
4484 $temp =~ s/[\']/&#8217;/igs; # Remove all single quotes
4485 $temp =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
4486 # If $temp is empty, use the default value (if it exists)
4487 unless($temp =~ /\S/ || length($temp) > 0) # I.e., $temp is empty
4489 $temp = $::default_values{$name};
4490 # Remove all existing '-quotes
4491 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
4492 $temp =~ s/[\']/&#8217;/igs; # Remove all single quotes
4493 $temp =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
4495 else # Store current CGI values and remove defaults
4497 $::default_values{$name} = $temp;
4499 # Define the CGI variable and its value (in the execute package)
4500 ${$name} = $temp;
4502 # return SUCCES
4503 return 1;
4506 sub defineCGIvariableList # ($name [, $default]) -> 0/1)
4508 my $name = shift || return 0; # The Name
4509 my $default = shift || ""; # The default value
4511 # Defined values must exist for security
4512 if(!exists($::default_values{$name}))
4514 $::default_values{$name} = $default;
4517 my @temp = ();
4520 # For security:
4521 # Environment values have precedence
4522 if(exists($ENV{$name}))
4524 push(@temp, $ENV{$name});
4526 # Get name and its values from the query string
4527 if($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
4529 push(@temp, ::YOUR_CGIPARSE($name, 1)); # Extract LIST
4531 else
4533 push(@temp, $::default_values{$name});
4537 # SECURITY, do not allow '- and `-quotes in
4538 # client values.
4539 # Remove all existing '-quotes
4540 @temp = map {s/([\r\f]+\n)/\n/g; $_} @temp; # Only \n is allowed
4541 @temp = map {s/[\']/&#8217;/igs; $_} @temp; # Remove all single quotes
4542 @temp = map {s/[\`]/&#8216;/igs; $_} @temp; # Remove all backtick quotes
4544 # Store current CGI values and remove defaults
4545 $::default_values{$name} = $temp[0];
4547 # Define the CGI variable and its value (in the execute package)
4548 @{$name} = @temp;
4550 # return SUCCES
4551 return 1;
4554 sub defineCGIvariableHash # ($name [, $default]) -> 0/1) Note: '$name{""} = $default';
4556 my $name = shift || return 0; # The Name
4557 my $default = shift || ""; # The default value
4559 # Defined values must exist for security
4560 if(!exists($::default_values{$name}))
4562 $::default_values{$name} = $default;
4565 my %temp = ();
4568 # For security:
4569 # Environment values have precedence
4570 if(exists($ENV{$name}))
4572 $temp{""} = $ENV{$name};
4574 # Get name and its values from the query string
4575 if($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
4577 %temp = ::YOUR_CGIPARSE($name, -1); # Extract HASH table
4579 elsif($::default_values{$name} ne "")
4581 $temp{""} = $::default_values{$name};
4585 # SECURITY, do not allow '- and `-quotes in
4586 # client values.
4587 # Remove all existing '-quotes
4588 my $Key;
4589 foreach $Key (keys(%temp))
4591 $temp{$Key} =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
4592 $temp{$Key} =~ s/[\']/&#8217;/igs; # Remove all single quotes
4593 $temp{$Key} =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
4596 # Store current CGI values and remove defaults
4597 $::default_values{$name} = $temp{""};
4599 # Define the CGI variable and its value (in the execute package)
4600 %{$name} = ();
4601 my $tempKey;
4602 foreach $tempKey (keys(%temp))
4604 ${$name}{$tempKey} = $temp{$tempKey};
4607 # return SUCCES
4608 return 1;
4612 # SAFEqx('CommandString')
4614 # A special function that is a safe alternative to backtick quotes (and qx//)
4615 # with client-supplied CGI values. All CGI variables are surrounded by
4616 # single ''-quotes (except between existing \'\'-quotes, don't try to be
4617 # too smart). All variables are then interpolated. Simple (@) lists are
4618 # expanded with join(' ', @List), and simple (%) hash tables expanded
4619 # as a list of "key=value" pairs. Complex variables, e.g., @$var, are
4620 # evaluated in a scalar context (e.g., as scalar(@$var)). All occurrences of
4621 # $@% that should NOT be interpolated must be preceeded by a "\".
4622 # If the first line of the String starts with "#! interpreter", the
4623 # remainder of the string is piped into interpreter (after interpolation), i.e.,
4624 # open(INTERPRETER, "|interpreter");print INTERPRETER remainder;
4625 # just like in UNIX. There are some problems with quotes. Be carefull in
4626 # using them. You do not have access to the output of any piped (#!)
4627 # process! If you want such access, execute
4628 # <SCRIPT TYPE="text/osshell">echo "script"|interpreter</SCRIPT> or
4629 # <SCRIPT TYPE="text/ssperl">$resultvar = SAFEqx('echo "script"|interpreter');
4630 # </SCRIPT>.
4632 # SAFEqx ONLY WORKS WHEN THE STRING ITSELF IS SURROUNDED BY SINGLE QUOTES
4633 # (SO THAT IT IS NOT INTERPOLATED BEFORE IT CAN BE PROTECTED)
4634 sub SAFEqx # ('String') -> result of executing qx/"String"/
4636 my $CommandString = shift;
4637 my $NewCommandString = "";
4639 # Only interpolate when required (check the On/Off switch)
4640 unless($CGIscriptor::NoShellScriptInterpolation)
4643 # Handle existing single quotes around CGI values
4644 while($CommandString =~ /\'[^\']+\'/s)
4646 my $CurrentQuotedString = $&;
4647 $NewCommandString .= $`;
4648 $CommandString = $'; # The remaining string
4649 # Interpolate CGI variables between quotes
4650 # (e.g., '$CGIscriptorResults[-1]')
4651 $CurrentQuotedString =~
4652 s/(^|[^\\])([\$\@])((\w*)([\{\[][\$\@\%]?[\:\w\-]+[\}\]])*)/if(exists($main::default_values{$4})){
4653 "$1".eval("$2$3")}else{"$&"}/egs;
4655 # Combine result with previous result
4656 $NewCommandString .= $CurrentQuotedString;
4658 $CommandString = $NewCommandString.$CommandString;
4660 # Select known CGI variables and surround them with single quotes,
4661 # then interpolate all variables
4662 $CommandString =~
4663 s/(^|[^\\])([\$\@\%]+)((\w*)([\{\[][\w\:\$\"\-]+[\}\]])*)/
4664 if($2 eq '$' && exists($main::default_values{$4}))
4665 {"$1\'".eval("\$$3")."\'";}
4666 elsif($2 eq '@'){$1.join(' ', @{"$3"});}
4667 elsif($2 eq '%'){my $t=$1;map {$t.=" $_=".${"$3"}{$_}}
4668 keys(%{"$3"});$t}
4669 else{$1.eval("${2}$3");
4670 }/egs;
4672 # Remove backslashed [$@%]
4673 $CommandString =~ s/\\([\$\@\%])/$1/gs;
4676 # Debugging
4677 # return $CommandString;
4679 # Handle UNIX style "#! shell command\n" constructs as
4680 # a pipe into the shell command. The output cannot be tapped.
4681 my $ReturnValue = "";
4682 if($CommandString =~ /^\s*\#\!([^\f\n\r]+)[\f\n\r]/is)
4684 my $ShellScripts = $';
4685 my $ShellCommand = $1;
4686 open(INTERPRETER, "|$ShellCommand") || dieHandler(29, "\'$ShellCommand\' PIPE not opened: &!\n");
4687 select(INTERPRETER);$| = 1;
4688 print INTERPRETER $ShellScripts;
4689 close(INTERPRETER);
4690 select(STDOUT);$| = 1;
4692 # Shell scripts which are redirected to an existing named pipe.
4693 # The output cannot be tapped.
4694 elsif($CGIscriptor::ShellScriptPIPE)
4696 CGIscriptor::printSAFEqxPIPE($CommandString);
4698 else # Plain ``-backtick execution
4700 # Execute the commands
4701 $ReturnValue = qx/$CommandString/;
4703 return $ReturnValue;
4706 ####################################################################################
4708 # The CGIscriptor PACKAGE
4710 ####################################################################################
4712 # Isolate the evaluation of CGIscriptor functions, i.e., those prefixed with
4713 # "CGIscriptor::"
4715 package CGIscriptor;
4718 # The Interpolation On/Off switch
4719 my $NoShellScriptInterpolation = undef;
4720 # The ShellScript redirection pipe
4721 my $ShellScriptPIPE = undef;
4723 # Open a named PIPE for SAFEqx to receive ALL shell scripts
4724 sub RedirectShellScript # ('CommandString')
4726 my $CommandString = shift || undef;
4728 if($CommandString)
4730 $ShellScriptPIPE = "ShellScriptNamedPipe";
4731 open($ShellScriptPIPE, "|$CommandString")
4732 || main::dieHandler(30, "\'|$CommandString\' PIPE open failed: $!\n");
4734 else
4736 close($ShellScriptPIPE);
4737 $ShellScriptPIPE = undef;
4739 return $ShellScriptPIPE;
4742 # Print to redirected shell script pipe
4743 sub printSAFEqxPIPE # ("String") -> print return value
4745 my $String = shift || undef;
4747 select($ShellScriptPIPE); $| = 1;
4748 my $returnvalue = print $ShellScriptPIPE ($String);
4749 select(STDOUT); $| = 1;
4751 return $returnvalue;
4754 # a pointer to CGIexecute::SAFEqx
4755 sub SAFEqx # ('String') -> result of qx/"String"/
4757 my $CommandString = shift;
4758 return CGIexecute::SAFEqx($CommandString);
4762 # a pointer to CGIexecute::defineCGIvariable
4763 sub defineCGIvariable # ($name[, $default]) ->0/1
4765 my $name = shift;
4766 my $default = shift;
4767 return CGIexecute::defineCGIvariable($name, $default);
4771 # Decode URL encoded arguments
4772 sub URLdecode # (URL encoded input) -> string
4774 my $output = "";
4775 my $char;
4776 my $Value;
4777 foreach $Value (@_)
4779 my $EncodedValue = $Value; # Do not change the loop variable
4780 # Convert all "+" to " "
4781 $EncodedValue =~ s/\+/ /g;
4782 # Convert all hexadecimal codes (%FF) to their byte values
4783 while($EncodedValue =~ /\%([0-9A-F]{2})/i)
4785 $output .= $`.chr(hex($1));
4786 $EncodedValue = $';
4788 $output .= $EncodedValue; # The remaining part of $Value
4790 $output;
4793 # Encode arguments as URL codes.
4794 sub URLencode # (input) -> URL encoded string
4796 my $output = "";
4797 my $char;
4798 my $Value;
4799 foreach $Value (@_)
4801 my @CharList = split('', $Value);
4802 foreach $char (@CharList)
4804 if($char =~ /\s/)
4805 { $output .= "+";}
4806 elsif($char =~ /\w\-/)
4807 { $output .= $char;}
4808 else
4810 $output .= uc(sprintf("%%%2.2x", ord($char)));
4814 $output;
4817 # Extract the value of a CGI variable from the URL-encoded $string
4818 # Also extracts the data blocks from a multipart request. Does NOT
4819 # decode the multipart blocks
4820 sub CGIparseValue # (ValueName [, URL_encoded_QueryString [, \$QueryReturnReference]]) -> Decoded value
4822 my $ValueName = shift;
4823 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4824 my $ReturnReference = shift || undef;
4825 my $output = "";
4827 if($QueryString =~ /(^|\&)$ValueName\=([^\&]*)(\&|$)/)
4829 $output = URLdecode($2);
4830 $$ReturnReference = $' if ref($ReturnReference);
4832 # Get multipart POST or PUT methods
4833 elsif($main::ENV{'CONTENT_TYPE'} =~ m@(multipart/([\w\-]+)\;\s+boundary\=([\S]+))@i)
4835 my $MultipartType = $2;
4836 my $BoundaryString = $3;
4837 # Remove the boundary-string
4838 my $temp = $QueryString;
4839 $temp =~ /^\Q--$BoundaryString\E/m;
4840 $temp = $';
4842 # Identify the newline character(s), this is the first character in $temp
4843 my $NewLine = "\r\n"; # Actually, this IS the correct one
4844 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
4846 # Is this correct??? I have to check.
4847 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
4848 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
4849 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
4850 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
4853 # search through all data blocks
4854 while($temp =~ /^\Q--$BoundaryString\E/m)
4856 my $DataBlock = $`;
4857 $temp = $';
4858 # Get the empty line after the header
4859 $DataBlock =~ /$NewLine$NewLine/;
4860 $Header = $`;
4861 $output = $';
4862 my $Header = $`;
4863 $output = $';
4865 # Remove newlines from the header
4866 $Header =~ s/$NewLine/ /g;
4868 # Look whether this block is the one you are looking for
4869 # Require the quotes!
4870 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
4872 my $i;
4873 for($i=length($NewLine); $i; --$i)
4875 chop($output);
4877 # OK, get out
4878 last;
4880 # reinitialize the output
4881 $output = "";
4883 $$ReturnReference = $temp if ref($ReturnReference);
4885 elsif($QueryString !~ /(^|\&)$ValueName\=/) # The value simply isn't there
4887 return undef;
4888 $$ReturnReference = undef if ref($ReturnReference);
4890 else
4892 print "ERROR: $ValueName $main::ENV{'CONTENT_TYPE'}\n";
4894 return $output;
4898 # Get a list of values for the same ValueName. Uses CGIparseValue
4900 sub CGIparseValueList # (ValueName [, URL_encoded_QueryString]) -> List of decoded values
4902 my $ValueName = shift;
4903 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4904 my @output = ();
4905 my $RestQueryString;
4906 my $Value;
4907 while($QueryString &&
4908 (($Value = CGIparseValue($ValueName, $QueryString, \$RestQueryString))
4909 || defined($Value)))
4911 push(@output, $Value);
4912 $QueryString = $RestQueryString; # QueryString is consumed!
4914 # ready, return list with values
4915 return @output;
4918 sub CGIparseValueHash # (ValueName [, URL_encoded_QueryString]) -> Hash table of decoded values
4920 my $ValueName = shift;
4921 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4922 my $RestQueryString;
4923 my %output = ();
4924 while($QueryString && $QueryString =~ /(^|\&)$ValueName([\w]*)\=/)
4926 my $Key = $2;
4927 my $Value = CGIparseValue("$ValueName$Key", $QueryString, \$RestQueryString);
4928 $output{$Key} = $Value;
4929 $QueryString = $RestQueryString; # QueryString is consumed!
4931 # ready, return list with values
4932 return %output;
4935 sub CGIparseForm # ([URL_encoded_QueryString]) -> Decoded Form (NO multipart)
4937 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4938 my $output = "";
4940 $QueryString =~ s/\&/\n/g;
4941 $output = URLdecode($QueryString);
4943 $output;
4946 # Extract the header of a multipart CGI variable from the POST input
4947 sub CGIparseHeader # (ValueName [, URL_encoded_QueryString]) -> Decoded value
4949 my $ValueName = shift;
4950 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
4951 my $output = "";
4953 if($main::ENV{'CONTENT_TYPE'} =~ m@(multipart/([\w\-]+)\;\s+boundary\=([\S]+))@i)
4955 my $MultipartType = $2;
4956 my $BoundaryString = $3;
4957 # Remove the boundary-string
4958 my $temp = $QueryString;
4959 $temp =~ /^\Q--$BoundaryString\E/m;
4960 $temp = $';
4962 # Identify the newline character(s), this is the first character in $temp
4963 my $NewLine = "\r\n"; # Actually, this IS the correct one
4964 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
4966 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
4967 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
4968 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
4969 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
4972 # search through all data blocks
4973 while($temp =~ /^\Q--$BoundaryString\E/m)
4975 my $DataBlock = $`;
4976 $temp = $';
4977 # Get the empty line after the header
4978 $DataBlock =~ /$NewLine$NewLine/;
4979 $Header = $`;
4980 my $Header = $`;
4982 # Remove newlines from the header
4983 $Header =~ s/$NewLine/ /g;
4985 # Look whether this block is the one you are looking for
4986 # Require the quotes!
4987 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
4989 $output = $Header;
4990 last;
4992 # reinitialize the output
4993 $output = "";
4996 return $output;
5000 # Checking variables for security (e.g., file names and email addresses)
5001 # File names are tested against the $::FileAllowedChars and $::BlockPathAccess variables
5002 sub CGIsafeFileName # FileName -> FileName or ""
5004 my $FileName = shift || "";
5005 return "" if $FileName =~ m?[^$::FileAllowedChars]?;
5006 return "" if $FileName =~ m!(^|/|\:)[\-\.]!;
5007 return "" if $FileName =~ m@\.\.\Q$::DirectorySeparator\E@; # Higher directory not allowed
5008 return "" if $FileName =~ m@\Q$::DirectorySeparator\E\.\.@; # Higher directory not allowed
5009 return "" if $::BlockPathAccess && $FileName =~ m@$::BlockPathAccess@; # Invisible (blocked) file
5011 return $FileName;
5014 sub CGIsafeEmailAddress # email -> email or ""
5016 my $Email = shift || "";
5017 return "" unless $Email =~ m/^[\w\.\-]+[\@][\w\.\-\:]+$/;
5018 return $Email;
5021 # Get a URL from the web. Needs main::GET_URL($URL) function
5022 # (i.e., curl, snarf, or wget)
5023 sub read_url # ($URL) -> page/file
5025 my $URL = shift || return "";
5027 # Get the commands to read the URL, do NOT add a print command
5028 my $URL_command = main::GET_URL($URL, 1);
5029 # execute the commands, i.e., actually read it
5030 my $URLcontent = CGIexecute->evaluate($URL_command);
5032 # Ready, return the content.
5033 return $URLcontent;
5036 ################################################>>>>>>>>>>Start Remove
5038 # BrowseAllDirs(Directory, indexfile)
5040 # usage:
5041 # <SCRIPT TYPE='text/ssperl'>
5042 # CGIscriptor::BrowseAllDirs('Sounds', 'index.html', '\.wav$')
5043 # </SCRIPT>
5045 # Allows to browse all directories. Stops at '/'. If the directory contains
5046 # an indexfile, eg, index.html, that file will be used instead. Files must match
5047 # the $Pattern, if it is given. Default is
5048 # CGIscriptor::BrowseAllDirs('/', 'index.html', '')
5050 sub BrowseAllDirs # (Directory, indexfile, $Pattern) -> Print HTML code
5052 my $Directory = shift || '/';
5053 my $indexfile = shift || 'index.html';
5054 my $Pattern = shift || '';
5055 $Directory =~ s!/$!!g;
5057 # If the index directory exists, use that one
5058 if(-s "$::CGI_HOME$Directory/$indexfile")
5060 return main::ProcessFile("$::CGI_HOME$Directory/$indexfile");
5063 # No indexfile, continue
5064 my @DirectoryList = glob("$::CGI_HOME$Directory");
5065 $CurrentDirectory = shift(@DirectoryList);
5066 $CurrentDirectory = $' if $CurrentDirectory =~ m@(/\.\./)+@;
5067 $CurrentDirectory =~ s@^$::CGI_HOME@@g;
5068 print "<h1>";
5069 print "$CurrentDirectory" if $CurrentDirectory;
5070 print "</h1>\n";
5072 opendir(BROWSE, "$::CGI_HOME$Directory") || main::dieHandler(31, "$::CGI_HOME$Directory $!");
5073 my @AllFiles = sort grep(!/^([\.]+[^\.]|\~)/, readdir(BROWSE));
5075 # Print directories
5076 my $file;
5077 print "<pre><ul TYPE='NONE'>\n";
5078 foreach $file (@AllFiles)
5080 next unless -d "$::CGI_HOME$Directory/$file";
5081 # Check whether this file should be visible
5082 next if $::BlockPathAccess &&
5083 "$Directory/$file/" =~ m@$::BlockPathAccess@;
5084 print "<dt><a href='$Directory/$file'>$file</a></dt>\n";
5086 print "</ul></pre>\n";
5088 # Print files
5089 print "<pre><ul TYPE='CIRCLE'>\n";
5090 my $TotalSize = 0;
5091 foreach $file (@AllFiles)
5093 next if $file =~ /^\./;
5094 next if -d "$::CGI_HOME$Directory/$file";
5095 next if -l "$::CGI_HOME$Directory/$file";
5096 # Check whether this file should be visible
5097 next if $::BlockPathAccess &&
5098 "$Directory/$file" =~ m@$::BlockPathAccess@;
5100 if(!$Pattern || $file =~ m@$Pattern@)
5102 my $Date = localtime($^T - (-M "$::CGI_HOME$Directory/$file")*3600*24);
5103 my $Size = -s "$::CGI_HOME$Directory/$file";
5104 $Size = sprintf("%6.0F kB", $Size/1024);
5105 my $Type = `file $::CGI_HOME$Directory/$file`;
5106 $Type =~ s@\s*$::CGI_HOME$Directory/$file\s*\:\s*@@ig;
5107 chomp($Type);
5109 print "<li>";
5110 print "<a href='$Directory/$file'>";
5111 printf("%-40s", "$file</a>");
5112 print "\t$Size\t$Date\t$Type";
5113 print "</li>\n";
5116 print "</ul></pre>";
5118 return 1;
5122 ################################################
5124 # BrowseDirs(RootDirectory [, Pattern, Start])
5126 # usage:
5127 # <SCRIPT TYPE='text/ssperl'>
5128 # CGIscriptor::BrowseDirs('Sounds', '\.aifc$', 'Speech', 'DIRECTORY')
5129 # </SCRIPT>
5131 # Allows to browse subdirectories. Start should be relative to the RootDirectory,
5132 # e.g., the full path of the directory 'Speech' is '~/Sounds/Speech'.
5133 # Only files which fit /$Pattern/ and directories are displayed.
5134 # Directories down or up the directory tree are supplied with a
5135 # GET request with the name of the CGI variable in the fourth argument (default
5136 # is 'BROWSEDIRS'). So the correct call for a subdirectory could be:
5137 # CGIscriptor::BrowseDirs('Sounds', '\.aifc$', $DIRECTORY, 'DIRECTORY')
5139 sub BrowseDirs # (RootDirectory [, Pattern, Start, CGIvariable, HTTPserver]) -> Print HTML code
5141 my $RootDirectory = shift; # || return 0;
5142 my $Pattern = shift || '\S';
5143 my $Start = shift || "";
5144 my $CGIvariable = shift || "BROWSEDIRS";
5145 my $HTTPserver = shift || '';
5147 $Start = CGIscriptor::URLdecode($Start); # Sometimes, too much has been encoded
5148 $Start =~ s@//+@/@g;
5149 $Start =~ s@[^/]+/\.\.@@ig;
5150 $Start =~ s@^\.\.@@ig;
5151 $Start =~ s@/\.$@@ig;
5152 $Start =~ s!/+$!!g;
5153 $Start .= "/" if $Start;
5155 my @Directory = glob("$::CGI_HOME/$RootDirectory/$Start");
5156 $CurrentDirectory = shift(@Directory);
5157 $CurrentDirectory = $' if $CurrentDirectory =~ m@(/\.\./)+@;
5158 $CurrentDirectory =~ s@^$::CGI_HOME@@g;
5159 print "<h1>";
5160 print "$CurrentDirectory" if $CurrentDirectory;
5161 print "</h1>\n";
5162 opendir(BROWSE, "$::CGI_HOME/$RootDirectory/$Start") || main::dieHandler(31, "$::CGI_HOME/$RootDirectory/$Start $!");
5163 my @AllFiles = sort grep(!/^([\.]+[^\.]|\~)/, readdir(BROWSE));
5165 # Print directories
5166 my $file;
5167 print "<pre><ul TYPE='NONE'>\n";
5168 foreach $file (@AllFiles)
5170 next unless -d "$::CGI_HOME/$RootDirectory/$Start$file";
5171 # Check whether this file should be visible
5172 next if $::BlockPathAccess &&
5173 "/$RootDirectory/$Start$file/" =~ m@$::BlockPathAccess@;
5175 my $NewURL = $Start ? "$Start$file" : $file;
5176 $NewURL = CGIscriptor::URLencode($NewURL);
5177 print "<dt><a href='";
5178 print "$ENV{SCRIPT_NAME}" if $ENV{SCRIPT_NAME} !~ m@[^\w+\-/]@;
5179 print "$ENV{PATH_INFO}?$CGIvariable=$NewURL'>$file</a></dt>\n";
5181 print "</ul></pre>\n";
5183 # Print files
5184 print "<pre><ul TYPE='CIRCLE'>\n";
5185 my $TotalSize = 0;
5186 foreach $file (@AllFiles)
5188 next if $file =~ /^\./;
5189 next if -d "$::CGI_HOME/$RootDirectory/$Start$file";
5190 next if -l "$::CGI_HOME/$RootDirectory/$Start$file";
5191 # Check whether this file should be visible
5192 next if $::BlockPathAccess &&
5193 "$::CGI_HOME/$RootDirectory/$Start$file" =~ m@$::BlockPathAccess@;
5195 if($file =~ m@$Pattern@)
5197 my $Date = localtime($^T - (-M "$::CGI_HOME/$RootDirectory/$Start$file")*3600*24);
5198 my $Size = -s "$::CGI_HOME/$RootDirectory/$Start$file";
5199 $Size = sprintf("%6.0F kB", $Size/1024);
5200 my $Type = `file $::CGI_HOME/$RootDirectory/$Start$file`;
5201 $Type =~ s@\s*$::CGI_HOME/$RootDirectory/$Start$file\s*\:\s*@@ig;
5202 chomp($Type);
5204 print "<li>";
5205 if($HTTPserver =~ /^\s*[\.\~]\s*$/)
5207 print "<a href='$RootDirectory/$Start$file'>";
5209 elsif($HTTPserver)
5211 print "<a href='$HTTPserver/$RootDirectory/$Start$file'>";
5213 printf("%-40s", "$file</a>") if $HTTPserver;
5214 printf("%-40s", "$file") unless $HTTPserver;
5215 print "\t$Size\t$Date\t$Type";
5216 print "</li>\n";
5219 print "</ul></pre>";
5221 return 1;
5225 # ListDocs(Pattern [,ListType])
5227 # usage:
5228 # <SCRIPT TYPE=text/ssperl>
5229 # CGIscriptor::ListDocs("/*", "dl");
5230 # </SCRIPT>
5232 # This subroutine is very usefull to manage collections of independent
5233 # documents. The resulting list will display the tree-like directory
5234 # structure. If this routine is too slow for online use, you can
5235 # store the result and use a link to that stored file.
5237 # List HTML and Text files with title and first header (HTML)
5238 # or filename and first meaningfull line (general text files).
5239 # The listing starts at the ServerRoot directory. Directories are
5240 # listed recursively.
5242 # You can change the list type (default is dl).
5243 # e.g.,
5244 # <dt><a href=<file.html>>title</a>
5245 # <dd>First Header
5246 # <dt><a href=<file.txt>>file.txt</a>
5247 # <dd>First meaningfull line of text
5249 sub ListDocs # ($Pattern [, prefix]) e.g., ("/Books/*", [, "dl"])
5251 my $Pattern = shift;
5252 $Pattern =~ /\*/;
5253 my $ListType = shift || "dl";
5254 my $Prefix = lc($ListType) eq "dl" ? "dt" : "li";
5255 my $URL_root = "http://$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}";
5256 my @FileList = glob("$::CGI_HOME$Pattern");
5257 my ($FileName, $Path, $Link);
5259 # Print List markers
5260 print "<$ListType>\n";
5262 # Glob all files
5263 File: foreach $FileName (@FileList)
5265 # Check whether this file should be visible
5266 next if $::BlockPathAccess && $FileName =~ m@$::BlockPathAccess@;
5268 # Recursively list files in all directories
5269 if(-d $FileName)
5271 $FileName =~ m@([^/]*)$@;
5272 my $DirName = $1;
5273 print "<$Prefix>$DirName\n";
5274 $Pattern =~ m@([^/]*)$@;
5275 &ListDocs("$`$DirName/$1", $ListType);
5276 next;
5278 # Use textfiles
5279 elsif(-T "$FileName")
5281 open(TextFile, $FileName) || next;
5283 # Ignore all other file types
5284 else
5285 { next;};
5287 # Get file path for link
5288 $FileName =~ /$::CGI_HOME/;
5289 print "<$Prefix><a href=$URL_root$'>";
5290 # Initialize all variables
5291 my $Line = "";
5292 my $TitleFound = 0;
5293 my $Caption = "";
5294 my $Title = "";
5295 # Read file and step through
5296 while(<TextFile>)
5298 chop $_;
5299 $Line = $_;
5300 # HTML files
5301 if($FileName =~ /\.ht[a-zA-Z]*$/i)
5303 # Catch Title
5304 while(!$Title)
5306 if($Line =~ m@<title>([^<]*)</title>@i)
5308 $Title = $1;
5309 $Line = $';
5311 else
5313 $Line .= <TextFile> || goto Print;
5314 chop $Line;
5317 # Catch First Header
5318 while(!$Caption)
5320 if($Line =~ m@</h1>@i)
5322 $Caption = $`;
5323 $Line = $';
5324 $Caption =~ m@<h1>@i;
5325 $Caption = $';
5326 $Line = $`.$Caption.$Line;
5328 else
5330 $Line .= <TextFile> || goto Print;
5331 chop $Line;
5335 # Other text files
5336 else
5338 # Title equals file name
5339 $FileName =~ /([^\/]+)$/;
5340 $Title = $1;
5341 # Catch equals First Meaningfull line
5342 while(!$Caption)
5344 if($Line =~ /[A-Z]/ &&
5345 ($Line =~ /subject|title/i || $Line =~ /^[\w,\.\s\?\:]+$/)
5346 && $Line !~ /Newsgroup/ && $Line !~ /\:\s*$/)
5348 $Line =~ s/\<[^\>]+\>//g;
5349 $Caption = $Line;
5351 else
5353 $Line = <TextFile> || goto Print;
5357 Print: # Print title and subject
5358 print "$Title</a>\n";
5359 print "<dd>$Caption\n" if $ListType eq "dl";
5360 $TitleFound = 0;
5361 $Caption = "";
5362 close TextFile;
5363 next File;
5366 # Print Closing List Marker
5367 print "</$ListType>\n";
5368 ""; # Empty return value
5372 # HTMLdocTree(Pattern [,ListType])
5374 # usage:
5375 # <SCRIPT TYPE=text/ssperl>
5376 # CGIscriptor::HTMLdocTree("/Welcome.html", "dl");
5377 # </SCRIPT>
5379 # The following subroutine is very usefull for checking large document
5380 # trees. Starting from the root (s), it reads all files and prints out
5381 # a nested list of links to all attached files. Non-existing or misplaced
5382 # files are flagged. This is quite a file-i/o intensive routine
5383 # so you would not like it to be accessible to everyone. If you want to
5384 # use the result, save the whole resulting page to disk and use a link
5385 # to this file.
5387 # HTMLdocTree takes an HTML file or file pattern and constructs nested lists
5388 # with links to *local* files (i.e., only links to the local server are
5389 # followed). The list entries are the document titles.
5390 # If the list type is <dl>, the first <H1> header is used too.
5391 # For each file matching the pattern, a list is made recursively of all
5392 # HTML documents that are linked from it and are stored in the same directory
5393 # or a sub-directory. Warnings are given for missing files.
5394 # The listing starts for the ServerRoot directory.
5395 # You can change the default list type <dl> (<dl>, <ul>, <ol>).
5397 %LinkUsed = ();
5399 sub HTMLdocTree # ($Pattern [, listtype])
5400 # e.g., ("/Welcome.html", [, "ul"])
5402 my $Pattern = shift;
5403 my $ListType = shift || "dl";
5404 my $Prefix = lc($ListType) eq "dl" ? "dt" : "li";
5405 my $URL_root = "http://$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}";
5406 my ($Filename, $Path, $Link);
5407 my %LocalLinks = {};
5409 # Read files (glob them for expansion of wildcards)
5410 my @FileList = glob("$::CGI_HOME$Pattern");
5411 foreach $Path (@FileList)
5413 # Get URL_path
5414 $Path =~ /$::CGI_HOME/;
5415 my $URL_path = $';
5416 # Check whether this file should be visible
5417 next if $::BlockPathAccess && $URL_path =~ m@$::BlockPathAccess@;
5419 my $Title = $URL_path;
5420 my $Caption = "";
5421 # Current file should not be used again
5422 ++$LinkUsed{$URL_path};
5423 # Open HTML doc
5424 unless(open(TextFile, $Path))
5426 print "<$Prefix>$Title <blink>(not found)</blink><br>\n";
5427 next;
5429 while(<TextFile>)
5431 chop $_;
5432 $Line = $_;
5433 # Catch Title
5434 while($Line =~ m@<title>@i)
5436 if($Line =~ m@<title>([^<]*)</title>@i)
5438 $Title = $1;
5439 $Line = $';
5441 else
5443 $Line .= <TextFile>;
5444 chop $Line;
5447 # Catch First Header
5448 while(!$Caption && $Line =~ m@<h1>@i)
5450 if($Line =~ m@</h[1-9]>@i)
5452 $Caption = $`;
5453 $Line = $';
5454 $Caption =~ m@<h1>@i;
5455 $Caption = $';
5456 $Line = $`.$Caption.$Line;
5458 else
5460 $Line .= <TextFile>;
5461 chop $Line;
5464 # Catch and print Links
5465 while($Line =~ m@<a href\=([^>]*)>@i)
5467 $Link = $1;
5468 $Line = $';
5469 # Remove quotes
5470 $Link =~ s/\"//g;
5471 # Remove extras
5472 $Link =~ s/[\#\?].*$//g;
5473 # Remove Servername
5474 if($Link =~ m@(http://|^)@i)
5476 $Link = $';
5477 # Only build tree for current server
5478 next unless $Link =~ m@$::ENV{'SERVER_NAME'}|^/@;
5479 # Remove server name and port
5480 $Link =~ s@^[^\/]*@@g;
5482 # Store the current link
5483 next if $LinkUsed{$Link} || $Link eq $URL_path;
5484 ++$LinkUsed{$Link};
5485 ++$LocalLinks{$Link};
5489 close TextFile;
5490 print "<$Prefix>";
5491 print "<a href=http://";
5492 print "$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}$URL_path>";
5493 print "$Title</a>\n";
5494 print "<br>$Caption\n"
5495 if $Caption && $Caption ne $Title && $ListType =~ /dl/i;
5496 print "<$ListType>\n";
5497 foreach $Link (keys(%LocalLinks))
5499 &HTMLdocTree($Link, $ListType);
5501 print "</$ListType>\n";
5505 ###########################<<<<<<<<<<End Remove
5507 # Make require happy
5510 =head1 NAME
5512 CGIscriptor -
5514 =head1 DESCRIPTION
5516 A flexible HTML 4 compliant script/module for CGI-aware
5517 embeded Perl, shell-scripts, and other scripting languages,
5518 executed at the server side.
5520 =head1 README
5522 Executes embeded Perl code in HTML pages with easy
5523 access to CGI variables. Also processes embeded shell
5524 scripts and scripts in any other language with an
5525 interactive interpreter (e.g., in-line Python, Tcl,
5526 Ruby, Awk, Lisp, Xlispstat, Prolog, M4, R, REBOL, Praat,
5527 sh, bash, csh, ksh).
5529 CGIscriptor is very flexible and hides all the specifics
5530 and idiosyncrasies of correct output and CGI coding and naming.
5531 CGIscriptor complies with the W3C HTML 4.0 recommendations.
5533 This Perl program will run on any WWW server that runs
5534 Perl scripts, just add a line like the following to your
5535 srm.conf file (Apache example):
5537 ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
5539 URL's that refer to http://www.your.address/SHTML/... will
5540 now be handled by CGIscriptor.pl, which can use a private
5541 directory tree (default is the DOCUMENT_ROOT directory tree,
5542 but it can be anywhere).
5544 =head1 PREREQUISITES
5547 =head1 COREQUISITES
5550 =pod OSNAMES
5552 Linux, *BSD, *nix, MS WinXP
5554 =pod SCRIPT CATEGORIES
5556 Servers
5560 =cut