3 # (configure the first line to contain YOUR path to perl 5.000+)
11 # perl 5.0 or higher (see: "http://www.perl.org/")
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
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.
58 # Configuration, copyright notice, and user manual follow the next
61 ############################################################################
63 # Changes (document ALL changes with date, name and email here):
64 # 13 Mar 2013 - Changed password hash
65 # 10 Jul 2012 - Version 2.4
66 # 11 Jun 2012 - Securing CGIvariable setting. Made
67 # 'if($ENV{QUERY_STRING} =~ /$name/)' into elsif in
68 # defineCGIvariable/List/Hash to give precedence to ENV{$name}
69 # This was a very old security bug. Added ProtectCGIvariable($name).
70 # 06 Jun 2012 - Added IP only session types after login.
71 # 31 May 2012 - Session ticket system added for handling login sessions.
72 # 29 May 2012 - CGIsafeFileName does not accept filenames starting with '.'
73 # 29 May 2012 - Added CGIscriptor::BrowseAllDirs to handle browsing directories
75 # 22 May 2012 - Added Access control with Session Tickets linked to
76 # IP Address and PATH_INFO.
77 # 21 May 2012 - Corrected the links generated by CGIscriptor::BrowseDirs
78 # Will link to current base URL when the HTTP server is '.' or '~'
79 # 29 Oct 2009 - Adapted David A. Wheeler's suggestion about filenames:
80 # CGIsafeFileName does not accept filenames starting with '-'
81 # (http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html)
82 # 08 Oct 2009 - Some corrections in the README.txt file, eg, new email address
83 # 28 Jan 2005 - Added a file selector to performTranslation.
84 # Changed %TranslationTable to @TranslationTable
85 # and patterns to lists.
86 # 27 Jan 2005 - Added a %TranslationTable with associated
87 # performTranslation(\$text) function to allow
88 # run changes in the web pages. Say, to translate
89 # legacy pages with <%=...%> delimiters to the new
90 # <SCRIPT TYPE=..></SCRIPT> format.
91 # 27 Jan 2005 - Small bug of extra '\n' in output removed from the
92 # Other Languages Code.
93 # 10 May 2004 - Belated upload of latest version (2.3) to CPAN
94 # 07 Oct 2003 - Corrected error '\s' -> '\\s' in rebol scripting
96 # 07 Oct 2003 - Corrected omitted INS tags in <DIV><INS> handling
97 # 20 May 2003 - Added a --help switch to print the manual.
98 # 06 Mar 2003 - Adapted the blurb at the end of the file.
99 # 03 Mar 2003 - Added a user definable dieHandler function to catch all
100 # "die" calls. Also "enhanced" the STDERR printout.
101 # 10 Feb 2003 - Split off the reading of the POST part of a query
102 # from Initialize_output. This was suggested by Gerd Franke
103 # to allow for the catching of the file_path using a
104 # POST based lookup. That is, he needed the POST part
105 # to change the file_path.
106 # 03 Feb 2003 - %{$name}; => %{$name} = (); in defineCGIvariableHash.
107 # 03 Feb 2003 - \1 better written as $1 in
108 # $directive =~ s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/$1/g
109 # 29 Jan 2003 - This makes "CLASS="ssperl" CSS-compatible Gerd Franke
111 # $ServerScriptContentClass = "ssperl";
112 # changed in ProcessFile():
113 # unless(($CurrentContentType =~
114 # 28 Jan 2003 - Added 'INS' Tag! Gerd Franke
115 # 20 Dec 2002 - Removed useless $Directoryseparator variable.
116 # Update comments and documentation.
117 # 18 Dec 2002 - Corrected bug in Accept/Reject processing.
119 # 24 Jul 2002 - Added .htaccess documentation (from Gerd Franke)
120 # Also added a note that RawFilePattern can be a
121 # complete file name.
122 # 19 Mar 2002 - Added SRC pseudo-files PREFIX and POSTFIX. These
123 # switch to prepending or to appending the content
124 # of the SRC attribute. Default is prefixing. You
125 # can add as many of these switches as you like.
126 # 13 Mar 2002 - Do not search for tag content if a tag closes with
127 # />, i.e., <DIV ... /> will be handled the XML/XHTML way.
128 # 25 Jan 2002 - Added 'curl' and 'snarf' to SRC attribute URL handling
130 # 25 Jan 2002 - Found a bug in SAFEqx, now executes qx() in a scalar context
131 # (i.o. a list context). This is necessary for binary results.
132 # 24 Jan 2002 - Disambiguated -T $SRCfile to -T "$SRCfile" (and -e) and
133 # changed the order of if/elsif to allow removing these
134 # conditions in systems with broken -T functions.
135 # (I also removed a spurious ')' bracket)
136 # 17 Jan 2002 - Changed DIV tag SRC from <SOURCE> to sysread(SOURCE,...)
137 # to support binary files.
138 # 17 Jan 2002 - Removed WhiteSpace from $FileAllowedCharacters.
139 # 17 Jan 2002 - Allow "file://" prefix in SRC attribute. It is simply
140 # stipped from the path.
141 # 15 Jan 2002 - Version 2.2
142 # 15 Jan 2002 - Debugged and completed URL support (including
143 # CGIscriptor::read_url() function)
144 # 07 Jan 2002 - Added automatic (magic) URL support to the SRC attribute
145 # with the main::GET_URL function. Uses wget -O underlying.
146 # 04 Jan 2002 - Added initialization of $NewDirective in InsertForeignScript
147 # (i.e., my $NewDirective = "";) to clear old output
148 # (this was a realy anoying bug).
149 # 03 Jan 2002 - Added a <DIV CLASS='text/ssperl' ID='varname'></DIV>
150 # tags that assign the body text as-is (literally)
151 # to $varname. Allows standard HTML-tools to handle
152 # Cascading Style Sheet templates. This implements a
153 # design by Gerd Franke (franke@roo.de).
154 # 03 Jan 2002 - I finaly gave in and allowed SRC files to expand ~/.
155 # 12 Oct 2001 - Normalized spelling of "CGIsafFileName" in documentation.
156 # 09 Oct 2001 - Added $ENV{'CGI_BINARY_FILE'} to log files to
157 # detect unwanted indexing of TAR files by webcrawlers.
158 # 10 Sep 2001 - Added $YOUR_SCRIPTS directory to @INC for 'require'.
159 # 22 Aug 2001 - Added .txt (Content-type: text/plain) as a default
160 # processed file type. Was processed via BinaryMapFile.
161 # 31 May 2001 - Changed =~ inside CGIsafeEmailAddress that was buggy.
162 # 29 May 2001 - Updated $CGI_HOME to point to $ENV{DOCUMENT_ROOT} io
163 # the root of PATH_TRANSLATED. DOCUMENT_ROOT can now
164 # be manipulated to achieve a "Sub Root".
165 # NOTE: you can have $YOUR_HTML_FILES != DOCUMENT_ROOT
166 # 28 May 2001 - Changed CGIscriptor::BrowsDirs function for security
167 # and debugging (it now works).
168 # 21 May 2001 - defineCGIvariableHash will ADD values to existing
169 # hashes,instead of replacing existing hashes.
170 # 17 May 2001 - Interjected a '&' when pasting POST to GET data
171 # 24 Apr 2001 - Blocked direct requests for BinaryMapFile.
172 # 16 Aug 2000 - Added hash table extraction for CGI parameters with
173 # CGIparseValueHash (used with structured parameters).
174 # Use: CGI='%<CGI-partial-name>' (fill in your name in <>)
175 # Will collect all <CGI-partial-name><key>=value pairs in
176 # $<CGI-partial-name>{<key>} = value;
177 # 16 Aug 2000 - Adapted SAFEqx to protect @PARAMETER values.
178 # 09 Aug 2000 - Added support for non-filesystem input by way of
179 # the CGI_FILE_CONTENTS and CGI_DATA_ACCESS_CODE
180 # environment variables.
181 # 26 Jul 2000 - On the command-line, file-path '-' indicates STDIN.
182 # This allows CGIscriptor to be used in pipes.
183 # Default, $BLOCK_STDIN_HTTP_REQUEST=1 will block this
184 # in an HTTP request (i.e., in a web server).
185 # 26 Jul 2000 - Blocked 'Content-type: text/html' if the SERVER_PROTOCOL
186 # is not HTTP or another protocol. Changed the default
187 # source directory to DOCUMENT_ROOT (i.o. the incorrect
189 # 24 Jul 2000 - -slim Command-line argument added to remove all
190 # comments, security, etc.. Updated documentation.
191 # 05 Jul 2000 - Added IF and UNLESS attributes to make the
192 # execution of all <META> and <SCRIPT> code
194 # 05 Jul 2000 - Rewrote and isolated the code for extracting
195 # quoted items from CGI and SRC attributes.
196 # Now all attributes expect the same set of
197 # quotes: '', "", ``, (), {}, [] and the same
198 # preceded by a \, e.g., "\((aap)\)" will be
199 # extracted as "(aap)".
200 # 17 Jun 2000 - Construct @ARGV list directly in CGIexecute
201 # name-space (i.o. by evaluation) from
202 # CGI attributes to prevent interference with
203 # the processing for non perl scripts.
204 # Changed CGIparseValueList to prevent runaway
206 # 16 Jun 2000 - Added a direct (interpolated) display mode
207 # (text/ssdisplay) and a user log mode
209 # 06 Jun 2000 - Replace "print $Result" with a syswrite loop to
210 # allow large string output.
211 # 02 Jun 2000 - Corrected shrubCGIparameter($CGI_VALUE) to realy
212 # remove all control characters. Changed Interpreter
213 # initialization to shrub interpolated CGI parameters.
214 # Added 'text/ssmailto' interpreter script.
215 # 22 May 2000 - Changed some of the comments
216 # 09 May 2000 - Added list extraction for CGI parameters with
217 # CGIparseValueList (used with multiple selections).
218 # Use: CGI='@<CGI-parameter>' (fill in your name in <>)
219 # 09 May 2000 - Added a 'Not Present' condition to CGIparseValue.
220 # 27 Apr 2000 - Updated documentation to reflect changes.
221 # 27 Apr 2000 - SRC attribute "cleaned". Supported for external
223 # 27 Apr 2000 - CGI attribute can be used in <SCRIPT> tag.
224 # 27 Apr 2000 - Gprolog, M4 support added.
225 # 26 Apr 2000 - Lisp (rep) support added.
226 # 20 Apr 2000 - Use of external interpreters now functional.
227 # 20 Apr 2000 - Removed bug from extracting Content types (RegExp)
228 # 10 Mar 2000 - Qualified unconditional removal of '#' that preclude
229 # the use of $#foo, i.e., I changed
230 # s/[^\\]\#[^\n\f\r]*([\n\f\r])/\1/g
232 # s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/\1/g
233 # 03 Mar 2000 - Added a '$BlockPathAccess' variable to "hide"
234 # things like, e.g., CVS information in CVS subtrees
235 # 10 Feb 2000 - URLencode/URLdecode have been made case-insensitive
236 # 10 Feb 2000 - Added a BrowseDirs function (CGIscriptor package)
237 # 01 Feb 2000 - A BinaryMapFile in the ~/ directory has precedence
238 # over a "burried" BinaryMapFile.
239 # 04 Oct 1999 - Added two functions to check file names and email addresses
240 # (CGIscriptor::CGIsafeFileName and
241 # CGIscriptor::CGIsafeEmailAddress)
242 # 28 Sept 1999 - Corrected bug in sysread call for reading POST method
243 # to allow LONG posts.
244 # 28 Sept 1999 - Changed CGIparseValue to handle multipart/form-data.
245 # 29 July 1999 - Refer to BinaryMapFile from CGIscriptor directory, if
246 # this directory exists.
247 # 07 June 1999 - Limit file-pattern matching to LAST extension
248 # 04 June 1999 - Default text/html content type is printed only once.
249 # 18 May 1999 - Bug in replacement of ~/ and ./ removed.
250 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
251 # 15 May 1999 - Changed the name of the execute package to CGIexecute.
252 # Changed the processing of the Accept and Reject file.
253 # Added a full expression evaluation to Access Control.
254 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
255 # 27 Apr 1999 - Brought CGIscriptor under the GNU GPL. Made CGIscriptor
256 # Version 1.1 a module that can be called with 'require "CGIscriptor.pl"'.
257 # Requests are serviced by "Handle_Request()". CGIscriptor
258 # can still be called as a isolated perl script and a shell
260 # Changed the "factory default setting" so that it will run
261 # from the DOCUMENT_ROOT directory.
262 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
263 # 29 Mar 1999 - Remove second debugging STDERR switch. Moved most code
264 # to subroutines to change CGIscriptor into a module.
265 # Added mapping to process unsupported file types (e.g., binary
266 # pictures). See $BinaryMapFile.
267 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
268 # 24 Sept 1998 - Changed text of license (Rob van Son, R.J.J.H.vanSon@uva.nl)
269 # Removed a double setting of filepatterns and maximum query
270 # size. Changed email address. Removed some typos from the
272 # 02 June 1998 - Bug fixed in URLdecode. Changing the foreach loop variable
273 # caused quiting CGIscriptor.(Rob van Son, R.J.J.H.vanSon@uva.nl)
274 # 02 June 1998 - $SS_PUB and $SS_SCRIPT inserted an extra /, removed.
275 # (Rob van Son, R.J.J.H.vanSon@uva.nl)
281 # It is not possible to use operators or variables to construct variable names,
282 # e.g., $bar = \@{$foo}; won't work. However, eval('$bar = \@{'.$foo.'};');
283 # will indeed work. If someone could tell me why, I would be obliged.
286 ############################################################################
288 # OBLIGATORY USER CONFIGURATION
290 # Configure the directories where all user files can be found (this
291 # is the equivalent of the server root directory of a WWW-server).
292 # These directories can be located ANYWHERE. For security reasons, it is
293 # better to locate them outside the WWW-tree of your HTTP server, unless
294 # CGIscripter handles ALL requests.
296 # For convenience, the defaults are set to the root of the WWW server.
297 # However, this might not be safe!
300 # $YOUR_HTML_FILES = "/usr/pub/WWW/SHTML"; # or SS_PUB as environment var
301 # (patch to use the parent directory of CGIscriptor as document root, should be removed)
302 if($ENV{'SCRIPT_FILENAME'}) # && $ENV{'SCRIPT_FILENAME'} !~ /\Q$ENV{'DOCUMENT_ROOT'}\E/)
304 $ENV{'DOCUMENT_ROOT'} = $ENV{'SCRIPT_FILENAME'};
305 $ENV{'DOCUMENT_ROOT'} =~ s@
/CGIscriptor
.*$@
@ig;
308 # Just enter your own directory path here
309 $YOUR_HTML_FILES = $ENV{'DOCUMENT_ROOT'}; # default is the DOCUMENT_ROOT
311 # ./ script files (recommended to be different from the previous)
312 # $YOUR_SCRIPTS = "/usr/pub/WWW/scripts"; # or SS_SCRIPT as environment var
313 $YOUR_SCRIPTS = $YOUR_HTML_FILES; # This might be a SECURITY RISK
315 # End of obligatory user configuration
316 # (note: there is more non-essential user configuration below)
318 ############################################################################
320 # OPTIONAL USER CONFIGURATION (all values are used CASE INSENSITIVE)
322 # Script content-types: TYPE="Content-type" (user defined mime-type)
323 $ServerScriptContentType = "text/ssperl"; # Server Side Perl scripts
324 # CSS require a simple class
325 $ServerScriptContentClass = $ServerScriptContentType =~ m!/! ?
326 $' : "ssperl"; # Server Side Perl CSS classes
328 $ShellScriptContentType = "text/osshell"; # OS shell scripts
329 # # (Server Side perl ``-execution)
331 # Accessible file patterns, block any request that doesn't match
.
332 # Matches any file with the extension .(s)htm(l), .txt, or .xmr
333 # (\. is used in regexp)
334 # Note: die unless $PATH_INFO =~ m@($FilePattern)$@is;
335 $FilePattern = ".shtml|.htm|.html|.xml|.xmr|.txt|.js|.css";
337 # The table with the content type MIME types
338 # (allows to differentiate MIME types, if needed)
341 '.html' => 'text/html',
342 '.shtml' => 'text/html',
343 '.htm' => 'text/html',
344 '.xml' => 'text/xml',
345 '.txt' => 'text/plain',
346 '.js' => 'text/plain',
347 '.css' => 'text/plain'
351 # File pattern post-processing
352 $FilePattern =~ s/([@.])/\\$1/g; # Convert . and @ to \. and \@
354 # SHAsum command needed for Authorization and Login
355 # (note, these have to be accessible in the HTML pages, ie, the CGIexecute environment)
356 my $shasum = "shasum -a 256";
357 if(qx{uname
} =~ /Darwin/)
359 $shasum = "shasum-5.12 -a 256" unless `which shasum`;
361 my $SHASUMCMD = $shasum.' |cut -f 1 -d" "';
362 $ENV{"SHASUMCMD"} = $SHASUMCMD;
363 my $RANDOMHASHCMD = 'dd bs=1 count=64 if=/dev/urandom 2>/dev/null | '.$shasum.' -b |cut -f 1 -d" "';
364 $ENV{"RANDOMHASHCMD"} = $RANDOMHASHCMD;
366 # Hash a string, return hex of hash
367 sub hash_string
# ($string) -> hex_hash
369 my $string = shift || "";
370 # Catch nasty \'-quotes, embed them in '..'"'"'..'
371 $string =~ s/\'/\'\"\'\"\'/isg;
372 my $hash = `printf '%s' '$string'| $ENV{"SHASUMCMD"}`;
377 # Generate random hex hash
378 sub get_random_hex
# () -> hex
380 # Create Random Hash Salt
381 open(URANDOM
, "$RANDOMHASHCMD |") || die "URANDOM; $RANDOMHASHCMD | $!\n";
382 my $RANDOMSALT= <URANDOM
>;
390 # File patterns of files which are handled by session tickets.
391 %TicketRequiredPatterns = (
392 '^/Private(/|$)' => "Private/.Sessions\tPrivate/.Passwords\t/Private/Login.html\t+36000"
394 # Used to set cookies, only session cookies supported
395 my %SETCOOKIELIST = ();
397 # Session Ticket Directory: Private/.Sessions
398 # Password Directory: Private/.Passwords
399 # Login page (url path): /Private/Login.html
400 # Expiration time (s): +3600
401 # +<seconds> = relative time <seconds> is absolute date-time
404 # Set up a valid ticket from a given text file
405 # Use from command line. DO NOT USE ONLINE
406 # Watch out for passwords that get stored in the history file
408 # perl CGIscriptor.pl --managelogin [options] [files]
410 # salt={file or saltvalue}
411 # masterkey={file or plaintext}
412 # newmasterkey={file or plaintext}
413 # password={file or palintext}
415 # Followed by one or more file names.
416 # Options can be interspersed between filenames,
417 # e.g., password='plaintext'
418 # Note that passwords are only used once!
420 if($ARGV[0] =~ /^\-\-managelogin/i)
422 my @arguments = @ARGV;
424 setup_ticket_file
(@arguments);
425 # Should be run on the command line
431 # Raw files must contain their own Content-type (xmr <- x-multipart-replace).
432 # THIS IS A SUBSET OF THE FILES DEFINED IN $FilePattern
433 $RawFilePattern = ".xmr";
434 # (In principle, this could contain a full file specification, e.g.,
435 # ".xmr|relocated.html")
437 # Raw File pattern post-processing
438 $RawFilePattern =~ s/([@.])/\\$1/g; # Convert . and @ to \. and \@
440 # Server protocols for which "Content-type: text/html\n\n" should be printed
441 # (you should not bother with these, except for HTTP, they are mostly imaginary)
442 $ContentTypeServerProtocols = 'HTTP|MAIL|MIME';
444 # Block access to all (sub-) paths and directories that match the
445 # following (URL) path (is used as:
446 # 'die if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@;' )
447 $BlockPathAccess = '/(CVS|\.git)/'; # Protect CVS and .git information
449 # All (blocked) other file-types can be mapped to a single "binary-file"
450 # processor (a kind of pseudo-file path). This can either be an error
451 # message (e.g., "illegal file") or contain a script that serves binary
453 # Note: the real file path wil be stored in $ENV{CGI_BINARY_FILE}.
454 $BinaryMapFile = "/BinaryMapFile.xmr";
455 # Allow for the addition of a CGIscriptor directory
456 # Note that a BinaryMapFile in the root "~/" directory has precedence
457 $BinaryMapFile = "/CGIscriptor".$BinaryMapFile
458 if ! -e
"$YOUR_HTML_FILES".$BinaryMapFile
459 && -e
"$YOUR_HTML_FILES/CGIscriptor".$BinaryMapFile;
462 # List of all characters that are allowed in file names and paths.
463 # All requests containing illegal characters are blocked. This
464 # blocks most tricks (e.g., adding "\000", "\n", or other control
465 # characters, also blocks URI's using %FF)
466 # THIS IS A SECURITY FEATURE
467 # (this is also used to parse filenames in SRC= features, note the
468 # '-quotes, they are essential)
469 $FileAllowedChars = '\w\.\~\/\:\*\?\-'; # Covers Unix and Mac, but NO spaces
471 # Maximum size of the Query (number of characters clients can send
472 # covers both GET & POST combined)
473 $MaximumQuerySize = 2**20 - 1; # = 2**14 - 1
476 # Embeded URL get function used in SRC attributes and CGIscriptor::read_url
477 # (returns a string with the PERL code to transfer the URL contents, e.g.,
478 # "SAFEqx(\'curl \"http://www.fon.hum.uva.nl\"\')")
479 # "SAFEqx(\'wget --quiet --output-document=- \"http://www.fon.hum.uva.nl\"\')")
480 # Be sure to handle <BASE HREF='URL'> and allow BOTH
481 # direct printing GET_URL($URL [, 0]) and extracting the content of
482 # the $URL for post-processing GET_URL($URL, 1).
483 # You get the WHOLE file, including HTML header.
484 # The shell command Use $URL where the URL should go
485 # ('wget', 'snarf' or 'curl', uncomment the one you would like to use)
486 my $GET_URL_shell_command = 'wget --quiet --output-document=- $URL';
487 #my $GET_URL_shell_command = 'snarf $URL -';
488 #my $GET_URL_shell_command = 'curl $URL';
490 sub GET_URL
# ($URL, $ValueNotPrint) -> content_of_url
492 my $URL = shift || return;
493 my $ValueNotPrint = shift || 0;
495 # Check URL for illegal characters
496 return "print '<h1>Illegal URL<h1>'\"\n\";" if $URL =~ /[^$FileAllowedChars\%]/;
498 # Include URL in final command
499 my $CurrentCommand = $GET_URL_shell_command;
500 $CurrentCommand =~ s/\$URL/$URL/g;
502 # Print to STDOUT or return a value
503 my $BlockPrint = "print STDOUT ";
504 $BlockPrint = "" if $ValueNotPrint;
506 my $Commands = <<"GETURLCODE";
511 # Simple, using shell command
512 \$Page = SAFEqx('$CurrentCommand');
514 # Add a BASE tage to the header
515 \$Page =~ s!\\</head!\\<base href='$URL'\\>\\</head!ig unless \$Page =~ m!\\<base!;
517 # Print the URL value, or return it as a value
524 # As files can get rather large (and binary), you might want to use
525 # some more intelligent reading procedure, e.g.,
527 # # open(URLHANDLE, '/usr/bin/wget --quiet --output-document=- "$URL"|') || die "wget: \$!";
528 # #open(URLHANDLE, '/usr/bin/snarf "$URL" -|') || die "snarf: \$!";
529 # open(URLHANDLE, '/usr/bin/curl "$URL"|') || die "curl: \$!";
531 # while(sysread(URLHANDLE,\$text, 1024) > 0)
535 # close(URLHANDLE) || die "\$!";
536 # However, this doesn't work with the CGIexecute->evaluate() function.
537 # You get an error: 'No child processes at (eval 16) line 15, <file0> line 8.'
539 # You can forget the next two variables, they are only needed when
540 # you don't want to use a regular file system (i.e., with open)
541 # but use some kind of database/RAM image for accessing (generating)
544 # Name of the environment variable that contains the file contents
545 # when reading directly from Database/RAM. When this environment variable,
546 # $ENV{$CGI_FILE_CONTENTS}, is not false, no real file will be read.
547 $CGI_FILE_CONTENTS = 'CGI_FILE_CONTENTS';
548 # Uncomment the following if you want to force the use of the data access code
549 # $ENV{$CGI_FILE_CONTENTS} = '-'; # Force use of $ENV{$CGI_DATA_ACCESS_CODE}
551 # Name of the environment variable that contains the RAM access perl
552 # code needed to read additional "files", i.e.,
553 # $ENV{$CGI_FILE_CONTENTS} = eval("\@_=('$file_path'); do{$ENV{$CGI_DATA_ACCESS_CODE}}");
554 # When $ENV{$CGI_FILE_CONTENTS} eq '-', this code is executed to generate the data.
555 $CGI_DATA_ACCESS_CODE = 'CGI_DATA_ACCESS_CODE';
557 # You can, of course, fill this yourself, e.g.,
558 # $ENV{$CGI_DATA_ACCESS_CODE} =
559 # 'open(INPUT, "<$_[0]"); while(<INPUT>){print;};close(INPUT);'
564 # Suppress error messages, this can be changed for debugging or error-logging
565 #open(STDERR, "/dev/null"); # (comment out for use in debugging)
567 # SPECIAL: Remove Comments, security, etc. if the command line is
568 # '>CGIscriptor.pl -slim >slimCGIscriptor.pl'
569 $TrimDownCGIscriptor = 1 if $ARGV[0] =~ /^\-slim/i;
571 # If CGIscriptor is used from the command line, the command line
572 # arguments are interpreted as the file (1st) and the Query String (rest).
574 $ENV{'PATH_INFO'} = shift(@ARGV) unless exists($ENV{'PATH_INFO'}) || grep(/\-\-help/i, @ARGV);
575 $ENV{'QUERY_STRING'} = join("&", @ARGV) unless exists($ENV{'QUERY_STRING'});
578 # Handle bail-outs in a user definable way.
579 # Catch Die and replace it with your own function.
580 # Ends with a call to "die $_[0];"
582 sub dieHandler
# ($ErrorCode, "Message", @_) -> DEAD
584 my $ErrorCode = shift;
585 my $ErrorMessage = shift;
587 # Place your own reporting functions here
589 # Now, kill everything (default)
590 print STDERR
"$ErrorCode: $ErrorMessage\n";
595 # End of optional user configuration
596 # (note: there is more non-essential user configuration below)
598 if(grep(/\-\-help/i, @ARGV))
600 print << 'ENDOFPREHELPTEXT2';
602 ###############################################################################
604 # Author and Copyright (c):
605 # Rob van Son, © 1995,1996,1997,1998,1999,2000,2001,2002-2012
608 # Institute of Phonetic Sciences & IFOTT/ACLS
609 # University of Amsterdam
610 # Email: R.J.J.H.vanSon@gmail.com
611 # Email: R.J.J.H.vanSon@uva.nl
612 # WWW : http://www.fon.hum.uva.nl/rob/
614 # License for use and disclaimers
616 # CGIscriptor merges plain ASCII HTML files transparantly
617 # with CGI variables, in-line PERL code, shell commands,
618 # and executable scripts in other scripting languages.
620 # This program is free software; you can redistribute it and/or
621 # modify it under the terms of the GNU General Public License
622 # as published by the Free Software Foundation; either version 2
623 # of the License, or (at your option) any later version.
625 # This program is distributed in the hope that it will be useful,
626 # but WITHOUT ANY WARRANTY; without even the implied warranty of
627 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
628 # GNU General Public License for more details.
630 # You should have received a copy of the GNU General Public License
631 # along with this program; if not, write to the Free Software
632 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
636 # Rob van Son (R.J.J.H.vanSon@uva.nl)
637 # Gerd Franke franke@roo.de (designed the <DIV> behaviour)
639 #######################################################
642 #######################################################>>>>>>>>>>Start Remove
644 # You can skip the following code, it is an auto-splice
647 # Construct a slimmed down version of CGIscriptor
648 # (i.e., CGIscriptor.pl -slim > slimCGIscriptor.pl)
650 if($TrimDownCGIscriptor)
652 open(CGISCRIPTOR
, "<CGIscriptor.pl")
653 || dieHandler
(1, "<CGIscriptor.pl not slimmed down: $!\n");
655 my $SKIPComments = 0;
664 $SKIPtext = 1 if /[\>]{10}Start Remove/;
665 $SKIPComments = 1 if $SKIPtext == 1;
668 $SKIPline = 1 if $SKIPtext || ($SKIPComments && /^\s*\#/);
670 ++$PrintCount unless $SKIPline;
672 print STDOUT
$_ unless $SKIPline;
675 $SKIPtext = 0 if /[\<]{10}End Remove/;
678 print STDERR
"\# Printed $PrintCount out of $LineCount lines\n";
682 #######################################################
684 if(grep(/\-\-help/i, @ARGV))
686 print << 'ENDOFHELPTEXT';
690 # CGIscriptor merges plain ASCII HTML files transparantly and safely
691 # with CGI variables, in-line PERL code, shell commands, and executable
692 # scripts in many languages (on-line and real-time). It combines the
693 # "ease of use" of HTML files with the versatillity of specialized
694 # scripts and PERL programs. It hides all the specifics and
695 # idiosyncrasies of correct output and CGI coding and naming. Scripts
696 # do not have to be aware of HTML, HTTP, or CGI conventions just as HTML
697 # files can be ignorant of scripts and the associated values. CGIscriptor
698 # complies with the W3C HTML 4.0 recommendations.
699 # In addition to its use as a WWW embeded CGI processor, it can
700 # be used as a command-line document preprocessor (text-filter).
702 # THIS IS HOW IT WORKS
704 # The aim of CGIscriptor is to execute "plain" scripts inside a text file
705 # using any required CGIparameters and environment variables. It
706 # is optimized to transparantly process HTML files inside a WWW server.
707 # The native language is Perl, but many other scripting languages
710 # CGIscriptor reads text files from the requested input file (i.e., from
711 # $YOUR_HTML_FILES$PATH_INFO) and writes them to <STDOUT> (i.e., the
712 # client requesting the service) preceded by the obligatory
713 # "Content-type: text/html\n\n" or "Content-type: text/plain\n\n" string
714 # (except for "raw" files which supply their own Content-type message
715 # and only if the SERVER_PROTOCOL supports HTTP, MAIL, or MIME).
717 # When CGIscriptor encounters an embedded script, indicated by an HTML4 tag
719 # <SCRIPT TYPE="text/ssperl" [CGI="$VAR='default value'"] [SRC="ScriptSource"]>
725 # <SCRIPT TYPE="text/osshell" [CGI="$name='default value'"] [SRC="ScriptSource"]>
729 # construct (anything between []-brackets is optional, other MIME-types
730 # and scripting languages are supported), the embedded script is removed
731 # and both the contents of the source file (i.e., "do 'ScriptSource'")
732 # AND the script are evaluated as a PERL program (i.e., by eval()),
733 # shell script (i.e., by a "safe" version of `Command`, qx) or an external
734 # interpreter. The output of the eval() function takes the place of the
735 # original <SCRIPT></SCRIPT> construct in the output string. Any CGI
736 # parameters declared by the CGI attribute are available as simple perl
737 # variables, and can subsequently be made available as variables to other
738 # scripting languages (e.g., bash, python, or lisp).
740 # Example: printing "Hello World"
741 # <HTML><HEAD><TITLE>Hello World</TITLE>
743 # <H1><SCRIPT TYPE="text/ssperl">"Hello World"</SCRIPT></H1>
746 # Save this in a file, hello.html, in the directory you indicated with
747 # $YOUR_HTML_FILES and access http://your_server/SHTML/hello.html
748 # (or to whatever name you use as an alias for CGIscriptor.pl).
749 # This is realy ALL you need to do to get going.
751 # You can use any values that are delivered in CGI-compliant form (i.e.,
752 # the "?name=value" type URL additions) transparently as "$name" variables
753 # in your scripts IFF you have declared them in the CGI attribute of
754 # a META or SCRIPT tag before e.g.:
755 # <META CONTENT="text/ssperl; CGI='$name = `default value`'
756 # [SRC='ScriptSource']">
758 # <SCRIPT TYPE="text/ssperl" CGI="$name = 'default value'"
759 # [SRC='ScriptSource']>
760 # After such a 'CGI' attribute, you can use $name as an ordinary PERL variable
761 # (the ScriptSource file is immediately evaluated with "do 'ScriptSource'").
762 # The CGIscriptor script allows you to write ordinary HTML files which will
763 # include dynamic CGI aware (run time) features, such as on-line answers
764 # to specific CGI requests, queries, or the results of calculations.
766 # For example, if you wanted to answer questions of clients, you could write
767 # a Perl program called "Answer.pl" with a function "AnswerQuestion()"
768 # that prints out the answer to requests given as arguments. You then write
769 # an HTML page "Respond.html" containing the following fragment:
772 # The Answer to your question
773 # <META CONTENT="text/ssperl; CGI='$Question'">
774 # <h3><SCRIPT TYPE="text/ssperl">$Question</SCRIPT></h3>
776 # <h3><SCRIPT TYPE="text/ssperl" SRC="./PATH/Answer.pl">
777 # AnswerQuestion($Question);
780 # <FORM ACTION=Respond.html METHOD=GET>
781 # Next question: <INPUT NAME="Question" TYPE=TEXT SIZE=40><br>
782 # <INPUT TYPE=SUBMIT VALUE="Ask">
785 # The output could look like the following (in HTML-speak):
788 # The Answer to your question
789 # <h3>What is the capital of the Netherlands?</h3>
793 # <FORM ACTION=Respond.html METHOD=GET>
794 # Next question: <INPUT NAME="Question" TYPE=TEXT SIZE=40><br>
795 # <INPUT TYPE=SUBMIT VALUE="Ask">
797 # Note that the function "Answer.pl" does know nothing about CGI or HTML,
798 # it just prints out answers to arguments. Likewise, the text has no
799 # provisions for scripts or CGI like constructs. Also, it is completely
800 # trivial to extend this "program" to use the "Answer" later in the page
801 # to call up other information or pictures/sounds. The final text never
802 # shows any cue as to what the original "source" looked like, i.e.,
803 # where you store your scripts and how they are called.
805 # There are some extra's. The argument of the files called in a SRC= tag
806 # can access the CGI variables declared in the preceding META tag from
807 # the @ARGV array. Executable files are called as:
808 # `file '$ARGV[0]' ... ` (e.g., `Answer.pl \'$Question\'`;)
809 # The files called from SRC can even be (CGIscriptor) html files which are
810 # processed in-line. Furthermore, the SRC= tag can contain a perl block
811 # that is evaluated. That is,
812 # <META CONTENT="text/ssperl; CGI='$Question' SRC='{$Question}'">
813 # will result in the evaluation of "print do {$Question};" and the VALUE
814 # of $Question will be printed. Note that these "SRC-blocks" can be
815 # preceded and followed by other file names, but only a single block is
816 # allowed in a SRC= tag.
818 # One of the major hassles of dynamic WWW pages is the fact that several
819 # mutually incompatible browsers and platforms must be supported. For example,
820 # the way sound is played automatically is different for Netscape and
821 # Internet Explorer, and for each browser it is different again on
822 # Unix, MacOS, and Windows. Realy dangerous is processing user-supplied
823 # (form-) values to construct email addresses, file names, or database
824 # queries. All Apache WWW-server exploits reported in the media are
825 # based on faulty CGI-scripts that didn't check their user-data properly.
827 # There is no panacee for these problems, but a lot of work and problems
828 # can be saved by allowing easy and transparent control over which
829 # <SCRIPT></SCRIPT> blocks are executed on what CGI-data. CGIscriptor
830 # supplies such a method in the form of a pair of attributes:
831 # IF='...condition..' and UNLESS='...condition...'. When added to a
832 # script tag, the whole block (including the SRC attribute) will be
833 # ignored if the condition is false (IF) or true (UNLESS).
834 # For example, the following block will NOT be evaluated if the value
835 # of the CGI variable FILENAME is NOT a valid filename:
837 # <SCRIPT TYPE='text/ssperl' CGI='$FILENAME'
838 # IF='CGIscriptor::CGIsafeFileName($FILENAME)'>
842 # (the function CGIsafeFileName(String) returns an empty string ("")
843 # if the String argument is not a valid filename).
844 # The UNLESS attribute is the mirror image of IF.
846 # A user manual follows the HTML 4 and security paragraphs below.
848 ##########################################################################
852 # In general, CGIscriptor.pl complies with the HTML 4 recommendations of
853 # the W3C. This means that any software to manage Web sites will be able
854 # to handle CGIscriptor files, as will web agents.
856 # All script code should be placed between <SCRIPT></SCRIPT> tags, the
857 # script type is indicated with TYPE="mime-type", the LANGUAGE
858 # feature is ignored, and a SRC feature is implemented. All CGI specific
859 # features are delegated to the CGI attribute.
861 # However, the behavior deviates from the W3C recommendations at some
862 # points. Most notably:
863 # 0- The scripts are executed at the server side, invissible to the
864 # client (i.e., the browser)
865 # 1- The mime-types are personal and idiosyncratic, but can be adapted.
866 # 2- Code in the body of a <SCRIPT></SCRIPT> tag-pair is still evaluated
867 # when a SRC feature is present.
868 # 3- The SRC attribute reads a list of files.
869 # 4- The files in a SRC attribute are processed according to file type.
870 # 5- The SRC attribute evaluates inline Perl code.
871 # 6- Processed META, DIV, INS tags are removed from the output
873 # 7- All attributes of the processed META tags, except CONTENT, are ignored
874 # (i.e., deleted from the output).
875 # 8- META tags can be placed ANYWHERE in the document.
876 # 9- Through the SRC feature, META tags can have visible output in the
878 # 10- The CGI attribute that declares CGI parameters, can be used
879 # inside the <SCRIPT> tag.
880 # 11- Use of an extended quote set, i.e., '', "", ``, (), {}, []
881 # and their \-slashed combinations: \'\', \"\", \`\`, \(\),
883 # 12- IF and UNLESS attributes to <SCRIPT>, <META>, <DIV>, <INS> tags.
884 # 13- <DIV> tags cannot be nested, DIV tags are not
885 # rendered with new-lines.
886 # 14- The XML style <TAG .... /> is recognized and handled correctly.
887 # (i.e., no content is processed)
889 # The reasons for these choices are:
890 # You can still write completely HTML4 compliant documents. CGIscriptor
891 # will not force you to write "deviant" code. However, it allows you to
892 # do so (which is, in fact, just as bad). The prime design principle
893 # was to allow users to include plain Perl code. The code itself should
894 # be "enhancement free". Therefore, extra features were needed to
895 # supply easy access to CGI and Web site components. For security
896 # reasons these have to be declared explicitly. The SRC feature
897 # transparently manages access to external files, especially the safe
898 # use of executable files.
899 # The CGI attribute handles the declarations of external (CGI) variables
900 # in the SCRIPT and META tag's.
901 # EVERYTHING THE CGI ATTRIBUTE AND THE META TAG DO CAN BE DONE INSIDE
902 # A <SCRIPT></SCRIPT> TAG CONSTRUCT.
904 # The reason for the IF, UNLESS, and SRC attributes (and their Perl code
905 # evaluation) were build into the META and SCRIPT tags is part laziness,
906 # part security. The SRC blocks allows more compact documents and easier
907 # debugging. The values of the CGI variables can be immediately screened
908 # for security by IF or UNLESS conditions, and even SRC attributes (e.g.,
909 # email addresses and file names), and a few commands can be called
910 # without having to add another Perl TAG pair. This is especially important
911 # for documents that require the use of other (more restricted) "scripting"
912 # languages and facilities that lag transparent control structures.
914 ##########################################################################
918 # Your WWW site is a few keystrokes away from a few hundred million internet
919 # users. A fair percentage of these users knows more about your computer
920 # than you do. And some of these just might have bad intentions.
922 # To ensure uncompromized operation of your server and platform, several
923 # features are incorporated in CGIscriptor.pl to enhance security.
924 # First of all, you should check the source of this program. No security
925 # measures will help you when you download programs from anonymous sources.
926 # If you want to use THIS file, please make sure that it is uncompromized.
927 # The best way to do this is to contact the source and try to determine
928 # whether s/he is reliable (and accountable).
930 # BE AWARE THAT ANY PROGRAMMER CAN CHANGE THIS PROGRAM IN SUCH A WAY THAT
931 # IT WILL SET THE DOORS TO YOUR SYSTEM WIDE OPEN
933 # I would like to ask any user who finds bugs that could compromise
934 # security to report them to me (and any other bug too,
935 # Email: R.J.J.H.vanSon@uva.nl or ifa@hum.uva.nl).
940 # The inner workings of the HTML source files are completely hidden
941 # from the client. Only the HTTP header and the ever changing content
942 # of the output distinguish it from the output of a plain, fixed HTML
943 # file. Names, structures, and arguments of the "embedded" scripts
944 # are invisible to the client. Error output is suppressed except
945 # during debugging (user configurable).
947 # 2 Separate directory trees
948 # Directories containing Inline text and script files can reside on
949 # separate trees, distinct from those of the HTTP server. This means
950 # that NEITHER the text files, NOR the script files can be read by
951 # clients other than through CGIscriptor.pl, UNLESS they are
952 # EXPLICITELY made available.
954 # 3 Requests are NEVER "evaluated"
955 # All client supplied values are used as literal values (''-quoted).
956 # Client supplied ''-quotes are ALWAYS removed. Therefore, as long as the
957 # embedded scripts do NOT themselves evaluate these values, clients CANNOT
958 # supply executable commands. Be sure to AVOID scripts like:
960 # <META CONTENT="text/ssperl; CGI='$UserValue'">
961 # <SCRIPT TYPE="text/ssperl">$dir = `ls -1 $UserValue`;</SCRIPT>
963 # These are a recipe for disaster. However, the following quoted
964 # form should be save (but is still not adviced):
966 # <SCRIPT TYPE="text/ssperl">$dir = `ls -1 \'$UserValue\'`;</SCRIPT>
968 # A special function, SAFEqx(), will automatically do exactly this,
969 # e.g., SAFEqx('ls -1 $UserValue') will execute `ls -1 \'$UserValue\'`
970 # with $UserValue interpolated. I recommend to use SAFEqx() instead
971 # of backticks whenever you can. The OS shell scripts inside
973 # <SCRIPT TYPE="text/osshell">ls -1 $UserValue</SCRIPT>
975 # are handeld by SAFEqx and automatically ''-quoted.
977 # 4 Logging of requests
978 # All requests can be logged separate from the Host server. The level of
979 # detail is user configurable: Including or excluding the actual queries.
980 # This allows for the inspection of (im-) proper use.
982 # 5 Access control: Clients
983 # The Remote addresses can be checked against a list of authorized
984 # (i.e., accepted) or non-authorized (i.e., rejected) clients. Both
985 # REMOTE_HOST and REMOTE_ADDR are tested so clients without a proper
986 # HOST name can be (in-) excluded by their IP-address. Client patterns
987 # containing all numbers and dots are considered IP-addresses, all others
988 # domain names. No wild-cards or regexp's are allowed, only partial
990 # Matching of names is done from the back to the front (domain first,
991 # i.e., $REMOTE_HOST =~ /\Q$pattern\E$/is), so including ".edu" will
992 # accept or reject all clients from the domain EDU. Matching of
993 # IP-addresses is done from the front to the back (domain first, i.e.,
994 # $REMOTE_ADDR =~ /^\Q$pattern\E/is), so including "128." will (in-)
995 # exclude all clients whose IP-address starts with 128.
996 # There are two special symbols: "-" matches HOSTs with no name and "*"
997 # matches ALL HOSTS/clients.
998 # For those needing more expressional power, lines starting with
999 # "-e" are evaluated by the perl eval() function. E.g.,
1000 # '-e $REMOTE_HOST =~ /\.edu$/is;' will accept/reject clients from the
1003 # 6 Access control: Files
1004 # In principle, CGIscriptor could read ANY file in the directory
1005 # tree as discussed in 1. However, for security reasons this is
1006 # restricted to text files. It can be made more restricted by entering
1007 # a global file pattern (e.g., ".html"). This is done by default.
1008 # For each client requesting access, the file pattern(s) can be made
1009 # more restrictive than the global pattern by entering client specific
1010 # file patterns in the Access Control files (see 5).
1011 # For example: if the ACCEPT file contained the lines
1015 # Then all clients could request paths containing "DEMO" or "demo", e.g.
1016 # "/my/demo/file.html" ($PATH_INFO =~ /\Q$pattern\E/), Clients from
1017 # *.hum.uva.nl could also request paths containing "LET or "let", e.g.
1018 # "/my/let/file.html", and clients from the local cluster
1019 # 145.18.230.[0-9]+ could access ALL files.
1020 # Again, for those needing more expressional power, lines starting with
1021 # "-e" are evaluated. For instance:
1022 # '-e $REMOTE_HOST =~ /\.edu$/is && $PATH_INFO =~ m@/DEMO/@is;'
1023 # will accept/reject requests for files from the directory "/demo/" from
1024 # clients from the domain '.edu'.
1026 # 7 Access control: Server side session tickets
1027 # Specific paths can be controlled by Session Tickets which must be
1028 # present as a SESSIONTICKET=<value> CGI variable in the request. These paths
1029 # are defined in %TicketRequiredPatterns as pairs of:
1030 # ('regexp' => 'SessionPath\tPasswordPath\tLogin.html\tExpiration').
1031 # Session Tickets are stored in a separate directory (SessionPath, e.g.,
1032 # "Private/.Session") as files with the exact same name of the SESSIONTICKET
1033 # CGI. The following is an example:
1035 # IPaddress: 127.0.0.1
1036 # AllowedPaths: ^/Private/Name/
1040 # Other content can follow.
1042 # It is adviced that Session Tickets should be deleted
1043 # after some (idle) time. The IP address should be the IP number at login, and
1044 # the SESSIONTICKET will be rejected if it is presented from another IP address.
1045 # AllowedPaths and DeniedPaths are perl regexps. Be careful how they match. Make sure to delimit
1046 # the names to prevent access to overlapping names, eg, "^/Private/Rob" will also
1047 # match "^/Private/Robert", however, "^/Private/Rob/" will not. Expires is the
1048 # time the ticket will remain valid after creation (file ctime). Time can be given
1049 # in s[econds] (default), m[inutes], h[hours], or d[ays], eg, "24h" means 24 hours.
1050 # None of these need be present, but the Ticket must have a non-zero size.
1052 # Next to Session Tickets, there are two other type of ticket files:
1053 # - LOGIN tickets store information about a current login request
1054 # - PASSWORD ticket store account information to authorize login requests
1056 # 8 Query length limiting
1057 # The length of the Query string can be limited. If CONTENT_LENGTH is larger
1058 # than this limit, the request is rejected. The combined length of the
1059 # Query string and the POST input is checked before any processing is done.
1060 # This will prevent clients from overloading the scripts.
1061 # The actual, combined, Query Size is accessible as a variable through
1062 # $CGI_Content_Length.
1064 # 9 Illegal filenames, paths, and protected directories
1065 # One of the primary security concerns in handling CGI-scripts is the
1066 # use of "funny" characters in the requests that con scripts in executing
1067 # malicious commands. Examples are inserting ';', null bytes, or <newline>
1068 # characters in URL's and filenames, followed by executable commands. A
1069 # special variable $FileAllowedChars stores a string of all allowed
1070 # characters. Any request that translates to a filename with a character
1071 # OUTSIDE this set will be rejected.
1072 # In general, all (readable files) in the DocumentRoot tree are accessible.
1073 # This might not be what you want. For instance, your DocumentRoot directory
1074 # might be the working directory of a CVS project and contain sensitive
1075 # information (e.g., the password to get to the repository). You can block
1076 # access to these subdirectories by adding the corresponding patterns to
1077 # the $BlockPathAccess variable. For instance, $BlockPathAccess = '/CVS/'
1078 # will block any request that contains '/CVS/' or:
1079 # die if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@;
1081 #10 The execution of code blocks can be controlled in a transparent way
1082 # by adding IF or UNLESS conditions in the tags themselves. That is,
1083 # a simple check of the validity of filenames or email addresses can
1084 # be done before any code is executed.
1086 ###############################################################################
1088 # USER MANUAL (sort of)
1090 # CGIscriptor removes embedded scripts, indicated by an HTML 4 type
1091 # <SCRIPT TYPE='text/ssperl'> </SCRIPT> or <SCRIPT TYPE='text/osshell'>
1092 # </SCRIPT> constructs. CGIscriptor also recognizes XML-type
1093 # <SCRIPT TYPE='text/ssperl'/> constructs. These are usefull when
1094 # the necessary code is already available in the TAG itself (e.g.,
1095 # using external files). The contents of the directive are executed by
1096 # the PERL eval() and `` functions (in a separate name space). The
1097 # result of the eval() function replaces the <SCRIPT> </SCRIPT> construct
1098 # in the output file. You can use the values that are delivered in
1099 # CGI-compliant form (i.e., the "?name=value&.." type URL additions)
1100 # transparently as "$name" variables in your directives after they are
1101 # defined in a <META> or <SCRIPT> tag.
1102 # If you define the variable "$CGIscriptorResults" in a CGI attribute, all
1103 # subsequent <SCRIPT> and <META> results (including the defining
1104 # tag) will also be pushed onto a stack: @CGIscriptorResults. This list
1105 # behaves like any other, ordinary list and can be manipulated.
1107 # Both GET and POST requests are accepted. These two methods are treated
1108 # equal. Variables, i.e., those values that are determined when a file is
1109 # processed, are indicated in the CGI attribute by $<name> or $<name>=<default>
1110 # in which <name> is the name of the variable and <default> is the value
1111 # used when there is NO current CGI value for <name> (you can use
1112 # white-spaces in $<name>=<default> but really DO make sure that the
1113 # default value is followed by white space or is quoted). Names can contain
1114 # any alphanumeric characters and _ (i.e., names match /[\w]+/).
1115 # If the Content-type: is 'multipart/*', the input is treated as a
1116 # MIME multipart message and automatically delimited. CGI variables get
1117 # the "raw" (i.e., undecoded) body of the corresponding message part.
1119 # Variables can be CGI variables, i.e., those from the QUERY_STRING,
1120 # environment variables, e.g., REMOTE_USER, REMOTE_HOST, or REMOTE_ADDR,
1121 # or predefined values, e.g., CGI_Decoded_QS (The complete, decoded,
1122 # query string), CGI_Content_Length (the length of the decoded query
1123 # string), CGI_Year, CGI_Month, CGI_Time, and CGI_Hour (the current
1126 # All these are available when defined in a CGI attribute. All environment
1127 # variables are accessible as $ENV{'name'}. So, to access the REMOTE_HOST
1128 # and the REMOTE_USER, use, e.g.:
1130 # <SCRIPT TYPE='text/ssperl'>
1131 # ($ENV{'REMOTE_HOST'}||"-")." $ENV{'REMOTE_USER'}"
1134 # (This will print a "-" if REMOTE_HOST is not known)
1135 # Another way to do this is:
1137 # <META CONTENT="text/ssperl; CGI='$REMOTE_HOST = - $REMOTE_USER'">
1138 # <SCRIPT TYPE='text/ssperl'>"$REMOTE_HOST $REMOTE_USER"</SCRIPT>
1140 # <META CONTENT='text/ssperl; CGI="$REMOTE_HOST = - $REMOTE_USER"
1141 # SRC={"$REMOTE_HOST $REMOTE_USER\n"}'>
1143 # This is possible because ALL environment variables are available as
1144 # CGI variables. The environment variables take precedence over CGI
1145 # names in case of a "name clash". For instance:
1146 # <META CONTENT="text/ssperl; CGI='$HOME' SRC={$HOME}">
1147 # Will print the current HOME directory (environment) irrespective whether
1148 # there is a CGI variable from the query
1149 # (e.g., Where do you live? <INPUT TYPE="TEXT" NAME="HOME">)
1150 # THIS IS A SECURITY FEATURE. It prevents clients from changing
1151 # the values of defined environment variables (e.g., by supplying
1152 # a bogus $REMOTE_ADDR). Although $ENV{} is not changed by the META tags,
1153 # it would make the use of declared variables insecure. You can still
1154 # access CGI variables after a name clash with
1155 # CGIscriptor::CGIparseValue(<name>).
1157 # Some CGI variables are present several times in the query string
1158 # (e.g., from multiple selections). These should be defined as
1159 # @VARIABLENAME=default in the CGI attribute. The list @VARIABLENAME
1160 # will contain ALL VARIABLENAME values from the query, or a single
1161 # default value. If there is an ENVIRONMENT variable of the
1162 # same name, it will be used instead of the default AND the query
1163 # values. The corresponding function is
1164 # CGIscriptor::CGIparseValueList(<name>)
1166 # CGI variables collected in a @VARIABLENAME list are unordered.
1167 # When more structured variables are needed, a hash table can be used.
1168 # A variable defined as %VARIABLE=default will collect all
1169 # CGI-parameters whose name start with 'VARIABLE' in a hash table with
1170 # the remainder of the name as a key. For instance, %PERSON will
1171 # collect PERSONname='John Doe', PERSONbirthdate='01 Jan 00', and
1172 # PERSONspouse='Alice' into a hash table %PERSON such that $PERSON{'spouse'}
1173 # equals 'Alice'. Any default value or environment value will be stored
1174 # under the "" key. If there is an ENVIRONMENT variable of the same name,
1175 # it will be used instead of the default AND the query values. The
1176 # corresponding function is CGIscriptor::CGIparseValueHash(<name>)
1178 # This method of first declaring your environment and CGI variables
1179 # before being able to use them in the scripts might seem somewhat
1180 # clumsy, but it protects you from inadvertedly printing out the values of
1181 # system environment variables when their names coincide with those used
1182 # in the CGI forms. It also prevents "clients" from supplying CGI
1183 # parameter values for your private variables.
1184 # THIS IS A SECURITY FEATURE!
1187 # NON-HTML CONTENT TYPES
1189 # Normally, CGIscriptor prints the standard "Content-type: text/html\n\n"
1190 # message before anything is printed. This has been extended to include
1191 # plain text (.txt) files, for which the Content-type (MIME type)
1192 # 'text/plain' is printed. In all other respects, text files are treated
1193 # as HTML files (this can be switched off by removing '.txt' from the
1194 # $FilePattern variable) . When the content type should be something else,
1195 # e.g., with multipart files, use the $RawFilePattern (.xmr, see also next
1196 # item). CGIscriptor will not print a Content-type message for this file
1197 # type (which must supply its OWN Content-type message). Raw files must
1198 # still conform to the <SCRIPT></SCRIPT> and <META> tag specifications.
1203 # CGIscriptor is intended to process HTML and text files only. You can
1204 # create documents of any mime-type on-the-fly using "raw" text files,
1205 # e.g., with the .xmr extension. However, CGIscriptor will not process
1206 # binary files of any type, e.g., pictures or sounds. Given the sheer
1207 # number of formats, I do not have any intention to do so. However,
1208 # an escape route has been provided. You can construct a genuine raw
1209 # (.xmr) text file that contains the perl code to service any file type
1210 # you want. If the global $BinaryMapFile variable contains the path to
1211 # this file (e.g., /BinaryMapFile.xmr), this file will be called
1212 # whenever an unsupported (non-HTML) file type is requested. The path
1213 # to the requested binary file is stored in $ENV('CGI_BINARY_FILE')
1214 # and can be used like any other CGI-variable. Servicing binary files
1215 # then becomes supplying the correct Content-type (e.g., print
1216 # "Content-type: image/jpeg\n\n";) and reading the file and writing it
1217 # to STDOUT (e.g., using sysread() and syswrite()).
1222 # All attributes of a META tag are ignored, except the
1223 # CONTENT='text/ssperl; CGI=" ... " [SRC=" ... "]' attribute. The string
1224 # inside the quotes following the CONTENT= indication (white-space is
1225 # ignored, "" '' `` (){}[]-quote pairs are allowed, plus their \ versions)
1226 # MUST start with any of the CGIscriptor mime-types (e.g.: text/ssperl or
1227 # text/osshell) and a comma or semicolon.
1228 # The quoted string following CGI= contains a white-space separated list
1229 # of declarations of the CGI (and Environment) values and default values
1230 # used when no CGI values are supplied by the query string.
1232 # If the default value is a longer string containing special characters,
1233 # possibly spanning several lines, the string must be enclosed in quotes.
1234 # You may use any pair of quotes or brackets from the list '', "", ``, (),
1235 # [], or {} to distinguish default values (or preceded by \, e.g., \(...\)
1236 # is different from (...)). The outermost pair will always be used and any
1237 # other quotes inside the string are considered to be part of the string
1242 # will result in $Value getting the default value: ['this'
1244 # (NOTE that the newline is part of the default value!).
1246 # Internally, for defining and initializing CGI (ENV) values, the META
1247 # and SCRIPT tags use the functions "defineCGIvariable($name, $default)"
1248 # (scalars) and "defineCGIvariableList($name, $default)" (lists).
1249 # These functions can be used inside scripts as
1250 # "CGIscriptor::defineCGIvariable($name, $default)" and
1251 # "CGIscriptor::defineCGIvariableList($name, $default)".
1252 # "CGIscriptor::defineCGIvariableHash($name, $default)".
1254 # The CGI attribute will be processed exactly identical when used inside
1255 # the <SCRIPT> tag. However, this use is not according to the
1256 # HTML 4.0 specifications of the W3C.
1261 # There is a problem when constructing html files containing
1262 # server-side perl scripts with standard HTML tools. These
1263 # tools will refuse to process any text between <SCRIPT></SCRIPT>
1264 # tags. This is quite annoying when you want to use large
1265 # HTML templates where you will fill in values.
1267 # For this purpose, CGIscriptor will read the neutral
1268 # <DIV CLASS="ssperl" ID="varname"></DIV> or
1269 # <INS CLASS="ssperl" ID="varname"></INS>
1270 # tag (in Cascading Style Sheet manner) Note that
1271 # "varname" has NO '$' before it, it is a bare name.
1272 # Any text between these <DIV ...></DIV> or
1273 # <INS ...></INS>tags will be assigned to '$varname'
1274 # as is (e.g., as a literal).
1275 # No processing or interpolation will be performed.
1276 # There is also NO nesting possible. Do NOT nest a
1277 # </DIV> inside a <DIV></DIV>! Moreover, neither INS nor
1278 # DIV tags do ensure a block structure in the final
1279 # rendering (i.e., no empty lines).
1281 # Note that <DIV CLASS="ssperl" ID="varname"/>
1282 # is handled the XML way. No content is processed,
1283 # but varname is defined, and any SRC directives are
1286 # You can use $varname like any other variable name.
1287 # However, $varname is NOT a CGI variable and will be
1288 # completely internal to your script. There is NO
1289 # interaction between $varname and the outside world.
1291 # To interpolate a DIV derived text, you can use:
1292 # $varname =~ s/([\]])/\\\1/g; # Mark ']'-quotes
1293 # $varname = eval("qq[$varname]"); # Interpolate all values
1295 # The DIV tags will process IF, UNLESS, CGI and
1296 # SRC attributes. The SRC files will be pre-pended to the
1297 # body text of the tag. SRC blocks are NOT executed.
1299 # CONDITIONAL PROCESSING: THE 'IF' AND 'UNLESS' ATTRIBUTES
1301 # It is often necessary to include code-blocks that should be executed
1302 # conditionally, e.g., only for certain browsers or operating system.
1303 # Furthermore, quite often sanity and security checks are necessary
1304 # before user (form) data can be processed, e.g., with respect to
1305 # email addresses and filenames.
1307 # Checks added to the code are often difficult to find, interpret or
1308 # maintain and in general mess up the code flow. This kind of confussion
1310 # Also, for many of the supported "foreign" scripting languages, adding
1311 # these checks is cumbersome or even impossible.
1313 # As a uniform method for asserting the correctness of "context", two
1314 # attributes are added to all supported tags: IF and UNLESS.
1315 # They both evaluate their value and block execution when the
1316 # result is <FALSE> (IF) or <TRUE> (UNLESS) in Perl, e.g.,
1317 # UNLESS='$NUMBER \> 100;' blocks execution if $NUMBER <= 100. Note that
1318 # the backslash in the '\>' is removed and only used to differentiate
1319 # this conditional '>' from the tag-closing '>'. For symmetry, the
1320 # backslash in '\<' is also removed. Inside these conditionals,
1321 # ~/ and ./ are expanded to their respective directory root paths.
1323 # For example, the following tag will be ignored when the filename is
1326 # <SCRIPT TYPE='text/ssperl' CGI='$FILENAME'
1327 # IF='CGIscriptor::CGIsafeFileName($FILENAME);'>
1331 # The IF and UNLESS values must be quoted. The same quotes are supported
1332 # as with the other attributes. The SRC attribute is ignored when IF and
1333 # UNLESS block execution.
1335 # NOTE: 'IF' and 'UNLESS' always evaluate perl code.
1338 # THE MAGIC SOURCE ATTRIBUTE (SRC=)
1340 # The SRC attribute inside tags accepts a list of filenames and URL's
1341 # separated by "," comma's (or ";" semicolons).
1342 # ALL the variable values defined in the CGI attribute are available
1343 # in @ARGV as if the file or block was executed from the command line,
1344 # in the exact order in which they were declared in the preceding CGI
1347 # First, a SRC={}-block will be evaluated as if the code inside the
1348 # block was part of a <SCRIPT></SCRIPT> construct, i.e.,
1349 # "print do { code };'';" or `code` (i.e., SAFEqx('code)).
1350 # Only a single block is evaluated. Note that this is processed less
1351 # efficiently than <SCRIPT> </SCRIPT> blocks. Type of evaluation
1352 # depends on the content-type: Perl for text/ssperl and OS shell for
1353 # text/osshell. For other mime types (scripting languages), anything in
1354 # the source block is put in front of the code block "inside" the tag.
1356 # Second, executable files (i.e., -x filename != 0) are evaluated as:
1357 # print `filename \'$ARGV[0]\' \'$ARGV[1]\' ...`
1358 # That is, you can actually call executables savely from the SRC tag.
1360 # Third, text files that match the file pattern, used by CGIscriptor to
1361 # check whether files should be processed ($FilePattern), are
1362 # processed in-line (i.e., recursively) by CGIscriptor as if the code
1363 # was inserted in the original source file. Recursions, i.e., calling
1364 # a file inside itself, are blocked. If you need them, you have to code
1365 # them explicitely using "main::ProcessFile($file_path)".
1367 # Fourth, Perl text files (i.e., -T filename != 0) are evaluated as:
1368 # "do FileName;'';".
1370 # Last, URL's (i.e., starting with 'HTTP://', 'FTP://', 'GOPHER://',
1371 # 'TELNET://', 'WHOIS://' etc.) are loaded
1372 # and printed. The loading and handling of <BASE> and document header
1373 # is done by a command generated by main::GET_URL($URL [, 0]). You can enter your
1374 # own code (default is curl, wget, or snarf and some post-processing to add a <BASE> tag).
1376 # There are two pseudo-file names: PREFIX and POSTFIX. These implement
1377 # a switch from prefixing the SRC code/files (PREFIX, default) before the
1378 # content of the tag to appending the code after the content of the tag
1379 # (POSTFIX). The switches are done in the order in which the PREFIX and
1380 # POSTFIX labels are encountered. You can mix PREFIX and POSTFIX labels
1381 # in any order with the SRC files. Note that the ORDER of file execution
1382 # is determined for prefixed and postfixed files seperately.
1384 # File paths can be preceded by the URL protocol prefix "file://". This
1385 # is simply STRIPPED from the name.
1389 # "http://cgi-bin/Action_Forms.pl/Statistics/Sign_Test.html?positive=8&negative=22
1390 # will result in printing "${SS_PUB}/Statistics/Sign_Test.html"
1391 # With QUERY_STRING = "positive=8&negative=22"
1393 # on encountering the lines:
1394 # <META CONTENT="text/osshell; CGI='$positive=11 $negative=3'">
1395 # <b><SCRIPT LANGUAGE=PERL TYPE="text/ssperl" SRC="./Statistics/SignTest.pl">
1398 # This line will be processed as:
1399 # "<b>`${SS_SCRIPT}/Statistics/SignTest.pl '8' '22'`</b><p>"
1401 # In which "${SS_SCRIPT}/Statistics/SignTest.pl" is an executable script,
1402 # This line will end up printed as:
1403 # "<b>p <= 0.0161</b><p>"
1405 # Note that the META tag itself will never be printed, and is invisible to
1406 # the outside world.
1408 # The SRC files in a DIV or INS tag will be added (pre-pended) to the body
1409 # of the <DIV></DIV> tag. Blocks are NOT executed! If you do not
1410 # need any content, you can use the <DIV...../> format.
1413 # THE CGISCRIPTOR ROOT DIRECTORIES ~/ AND ./
1415 # Inside <SCRIPT></SCRIPT> tags, filepaths starting
1416 # with "~/" are replaced by "$YOUR_HTML_FILES/", this way files in the
1417 # public directories can be accessed without direct reference to the
1418 # actual paths. Filepaths starting with "./" are replaced by
1419 # "$YOUR_SCRIPTS/" and this should only be used for scripts.
1421 # Note: this replacement can seriously affect Perl scripts. Watch
1422 # out for constructs like $a =~ s/aap\./noot./g, use
1423 # $a =~ s@aap\.@noot.@g instead.
1425 # CGIscriptor.pl will assign the values of $SS_PUB and $SS_SCRIPT
1426 # (i.e., $YOUR_HTML_FILES and $YOUR_SCRIPTS) to the environment variables
1427 # $SS_PUB and $SS_SCRIPT. These can be accessed by the scripts that are
1429 # Values not preceded by $, ~/, or ./ are used as literals
1432 # OS SHELL SCRIPT EVALUATION (CONTENT-TYPE=TEXT/OSSHELL)
1434 # OS scripts are executed by a "safe" version of the `` operator (i.e.,
1435 # SAFEqx(), see also below) and any output is printed. CGIscriptor will
1436 # interpolate the script and replace all user-supplied CGI-variables by
1437 # their ''-quoted values (actually, all variables defined in CGI attributes
1438 # are quoted). Other Perl variables are interpolated in a simple fasion,
1439 # i.e., $scalar by their value, @list by join(' ', @list), and %hash by
1440 # their name=value pairs. Complex references, e.g., @$variable, are all
1441 # evaluated in a scalar context. Quotes should be used with care.
1442 # NOTE: the results of the shell script evaluation will appear in the
1443 # @CGIscriptorResults stack just as any other result.
1444 # All occurrences of $@% that should NOT be interpolated must be
1445 # preceeded by a "\". Interpolation can be switched off completely by
1446 # setting $CGIscriptor::NoShellScriptInterpolation = 1
1447 # (set to 0 or undef to switch interpolation on again)
1449 # <SCRIPT TYPE="text/ssperl">
1450 # $CGIscriptor::NoShellScriptInterpolation = 1;
1454 # RUN TIME TRANSLATION OF INPUT FILES
1456 # Allows general and global conversions of files using Regular Expressions.
1457 # Very handy (but costly) to rewrite legacy pages to a new format.
1458 # Select files to use it on with
1459 # my $TranslationPaths = 'filepattern';
1460 # This is costly. For efficiency, define:
1461 # $TranslationPaths = ''; when not using translations.
1462 # Accepts general regular expressions: [$pattern, $replacement]
1465 # my $TranslationPaths = 'filepattern'; # Pattern matching PATH_INFO
1467 # push(@TranslationTable, ['pattern', 'replacement']);
1468 # e.g. (for Ruby Rails):
1469 # push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
1470 # push(@TranslationTable, ['%>', '</SCRIPT>']);
1473 # my $currentRegExp;
1474 # foreach $currentRegExp (@TranslationTable)
1476 # my ($pattern, $replacement) = @$currentRegExp;
1477 # $$text =~ s!$pattern!$replacement!msg;
1481 # EVALUATION OF OTHER SCRIPTING LANGUAGES
1483 # Adding a MIME-type and an interpreter command to
1484 # %ScriptingLanguages automatically will catch any other
1485 # scripting language in the standard
1486 # <SCRIPT TYPE="[mime]"></SCRIPT> manner.
1487 # E.g., adding: $ScriptingLanguages{'text/sspython'} = 'python';
1488 # will actually execute the folowing code in an HTML page
1489 # (ignore 'REMOTE_HOST' for the moment):
1490 # <SCRIPT TYPE="text/sspython">
1492 # x = ["A","real","python","script","Hello","World","and", REMOTE_HOST]
1493 # print x[4:8] # Prints the list ["Hello","World","and", REMOTE_HOST]
1496 # The script code is NOT interpolated by perl, EXCEPT for those
1497 # interpreters that cannot handle variables themselves.
1498 # Currently, several interpreters are pre-installed:
1500 # Perl test - "text/testperl" => 'perl',
1501 # Python - "text/sspython" => 'python',
1502 # Ruby - "text/ssruby" => 'ruby',
1503 # Tcl - "text/sstcl" => 'tcl',
1504 # Awk - "text/ssawk" => 'awk -f-',
1505 # Gnu Lisp - "text/sslisp" => 'rep | tail +5 '.
1506 # "| egrep -v '> |^rep. |^nil\\\$'",
1507 # XLispstat - "text/xlispstat" => 'xlispstat | tail +7 '.
1508 # "| egrep -v '> \\\$|^NIL'",
1509 # Gnu Prolog- "text/ssprolog" => 'gprolog',
1510 # M4 macro's- "text/ssm4" => 'm4',
1511 # Born shell- "text/sh" => 'sh',
1512 # Bash - "text/bash" => 'bash',
1513 # C-shell - "text/csh" => 'csh',
1514 # Korn shell- "text/ksh" => 'ksh',
1515 # Praat - "text/sspraat" => "praat - | sed 's/Praat > //g'",
1516 # R - "text/ssr" => "R --vanilla --slave | sed 's/^[\[0-9\]*] //g'",
1517 # REBOL - "text/ssrebol" =>
1518 # "rebol --quiet|egrep -v '^[> ]* == '|sed 's/^\s*\[> \]* //g'",
1519 # PostgreSQL- "text/postgresql" => 'psql 2>/dev/null',
1522 # Note that the "value" of $ScriptingLanguages{mime} must be a command
1523 # that reads Standard Input and writes to standard output. Any extra
1524 # output of interactive interpreters (banners, echo's, prompts)
1525 # should be removed by piping the output through 'tail', 'grep',
1526 # 'sed', or even 'awk' or 'perl'.
1528 # For access to CGI variables there is a special hashtable:
1529 # %ScriptingCGIvariables.
1530 # CGI variables can be accessed in three ways.
1531 # 1. If the mime type is not present in %ScriptingCGIvariables,
1532 # nothing is done and the script itself should parse the relevant
1533 # environment variables.
1534 # 2. If the mime type IS present in %ScriptingCGIvariables, but it's
1535 # value is empty, e.g., $ScriptingCGIvariables{"text/sspraat"} = '';,
1536 # the script text is interpolated by perl. That is, all $var, @array,
1537 # %hash, and \-slashes are replaced by their respective values.
1538 # 3. In all other cases, the CGI and environment variables are added
1539 # in front of the script according to the format stored in
1540 # %ScriptingCGIvariables. That is, the following (pseudo-)code is
1541 # executed for each CGI- or Environment variable defined in the CGI-tag:
1542 # printf(INTERPRETER, $ScriptingCGIvariables{$mime}, $CGI_NAME, $CGI_VALUE);
1544 # For instance, "text/testperl" => '$%s = "%s";' defines variable
1545 # definitions for Perl, and "text/sspython" => '%s = "%s"' for Python
1546 # (note that these definitions are not save, the real ones contain '-quotes).
1548 # THIS WILL NOT WORK FOR @VARIABLES, the (empty) $VARIABLES will be used
1551 # The $CGI_VALUE parameters are "shrubed" of all control characters
1552 # and quotes (by &shrubCGIparameter($CGI_VALUE)) for the options 2 and 3.
1553 # Control characters are replaced by \0<octal ascii value> (the exception
1554 # is \015, the newline, which is replaced by \n) and quotes
1555 # and backslashes by their HTML character
1556 # value (' -> ' ` -> ` " -> " \ -> \ & -> &er;).
1558 # if a client would supply the string value (in standard perl, e.g.,
1559 # \n means <newline>)
1560 # "/dev/null';\nrm -rf *;\necho '"
1561 # it would be processed as
1562 # '/dev/null';\nrm -rf *;\necho ''
1563 # (e.g., sh or bash would process the latter more according to your
1565 # If your intepreter requires different protection measures, you will
1566 # have to supply these in %main::SHRUBcharacterTR (string => translation),
1567 # e.g., $SHRUBcharacterTR{"\'"} = "'";
1569 # Currently, the following definitions are used:
1570 # %ScriptingCGIvariables = (
1571 # "text/testperl" => "\$\%s = '\%s';", # Perl $VAR = 'value' (for testing)
1572 # "text/sspython" => "\%s = '\%s'", # Python VAR = 'value'
1573 # "text/ssruby" => '@%s = "%s"', # Ruby @VAR = "value"
1574 # "text/sstcl" => 'set %s "%s"', # TCL set VAR "value"
1575 # "text/ssawk" => '%s = "%s";', # Awk VAR = "value";
1576 # "text/sslisp" => '(setq %s "%s")', # Gnu lisp (rep) (setq VAR "value")
1577 # "text/xlispstat" => '(setq %s "%s")', # Xlispstat (setq VAR "value")
1578 # "text/ssprolog" => '', # Gnu prolog (interpolated)
1579 # "text/ssm4" => "define(`\%s', `\%s')", # M4 macro's define(`VAR', `value')
1580 # "text/sh" => "\%s='\%s';", # Born shell VAR='value';
1581 # "text/bash" => "\%s='\%s';", # Born again shell VAR='value';
1582 # "text/csh" => "\$\%s = '\%s';", # C shell $VAR = 'value';
1583 # "text/ksh" => "\$\%s = '\%s';", # Korn shell $VAR = 'value';
1584 # "text/sspraat" => '', # Praat (interpolation)
1585 # "text/ssr" => '%s <- "%s";', # R VAR <- "value";
1586 # "text/ssrebol" => '%s: copy "%s"', # REBOL VAR: copy "value"
1587 # "text/postgresql" => '', # PostgreSQL (interpolation)
1591 # Four tables allow fine-tuning of interpreter with code that should be
1592 # added before and after each code block:
1594 # Code added before each script block
1595 # %ScriptingPrefix = (
1596 # "text/testperl" => "\# Prefix Code;", # Perl script testing
1597 # "text/ssm4" => 'divert(0)' # M4 macro's (open STDOUT)
1599 # Code added at the end of each script block
1600 # %ScriptingPostfix = (
1601 # "text/testperl" => "\# Postfix Code;", # Perl script testing
1602 # "text/ssm4" => 'divert(-1)' # M4 macro's (block STDOUT)
1604 # Initialization code, inserted directly after opening (NEVER interpolated)
1605 # %ScriptingInitialization = (
1606 # "text/testperl" => "\# Initialization Code;", # Perl script testing
1607 # "text/ssawk" => 'BEGIN {', # Server Side awk scripts
1608 # "text/sslisp" => '(prog1 nil ', # Lisp (rep)
1609 # "text/xlispstat" => '(prog1 nil ', # xlispstat
1610 # "text/ssm4" => 'divert(-1)' # M4 macro's (block STDOUT)
1612 # Cleanup code, inserted before closing (NEVER interpolated)
1613 # %ScriptingCleanup = (
1614 # "text/testperl" => "\# Cleanup Code;", # Perl script testing
1615 # "text/sspraat" => 'Quit',
1616 # "text/ssawk" => '};', # Server Side awk scripts
1617 # "text/sslisp" => '(princ "\n" standard-output)).' # Closing print to rep
1618 # "text/xlispstat" => '(print "" *standard-output*)).' # Closing print to xlispstat
1619 # "text/postgresql" => '\q',
1623 # The SRC attribute is NOT magical for these interpreters. In short,
1624 # all code inside a source file or {} block is written verbattim
1625 # to the interpreter. No (pre-)processing or executional magic is done.
1627 # A serious shortcomming of the described mechanism for handling other
1628 # (scripting) languages, with respect to standard perl scripts
1629 # (i.e., 'text/ssperl'), is that the code is only executed when
1630 # the pipe to the interpreter is closed. So the pipe has to be
1631 # closed at the end of each block. This means that the state of the
1632 # interpreter (e.g., all variable values) is lost after the closing of
1633 # the next </SCRIPT> tag. The standard 'text/ssperl' scripts retain
1634 # all values and definitions.
1636 # APPLICATION MIME TYPES
1638 # To ease some important auxilliary functions from within the
1639 # html pages I have added them as MIME types. This uses
1640 # the mechanism that is also used for the evaluation of
1641 # other scripting languages, with interpolation of CGI
1642 # parameters (and perl-variables). Actually, these are
1643 # defined exactly like any other "scripting language".
1645 # text/ssdisplay: display some (HTML) text with interpolated
1646 # variables (uses `cat`).
1647 # text/sslogfile: write (append) the interpolated block to the file
1648 # mentioned on the first, non-empty line
1649 # (the filename can be preceded by 'File: ',
1650 # note the space after the ':',
1651 # uses `awk .... >> <filename>`).
1652 # text/ssmailto: send email directly from within the script block.
1653 # The first line of the body must contain
1654 # To:Name@Valid.Email.Address
1655 # (note: NO space between 'To:' and the email adres)
1656 # For other options see the mailto man pages.
1657 # It works by directly sending the (interpolated)
1658 # content of the text block to a pipe into the
1659 # Linux program 'mailto'.
1661 # In these script blocks, all Perl variables will be
1662 # replaced by their values. All CGI variables are cleaned before
1663 # they are used. These CGI variables must be redefined with a
1664 # CGI attribute to restore their original values.
1665 # In general, this will be more secure than constructing
1666 # e.g., your own email command lines. For instance, Mailto will
1667 # not execute any odd (forged) email addres, but just stops
1668 # when the email address is invalid and awk will construct
1669 # any filename you give it (e.g. '<File;rm\\\040-f' would end up
1670 # as a "valid" UNIX filename). Note that it will also gladly
1671 # store this file anywhere (/../../../etc/passwd will work!).
1672 # Use the CGIscriptor::CGIsafeFileName() function to clean the
1675 # SHELL SCRIPT PIPING
1677 # If a shell script starts with the UNIX style "#! <shell command> \n"
1678 # line, the rest of the shell script is piped into the indicated command,
1680 # open(COMMAND, "| command");print COMMAND $RestOfScript;
1682 # In many ways this is equivalent to the MIME-type profiling for
1683 # evaluating other scripting languages as discussed above. The
1684 # difference breaks down to convenience. Shell script piping is a
1685 # "raw" implementation. It allows you to control all aspects of
1686 # execution. Using the MIME-type profiling is easier, but has a
1687 # lot of defaults built in that might get in the way. Another
1688 # difference is that shell script piping uses the SAFEqx() function,
1689 # and MIME-type profiling does not.
1691 # Execution of shell scripts is under the control of the Perl Script blocks
1692 # in the document. The MIME-type triggered execution of <SCRIPT></SCRIPT>
1693 # blocks can be simulated easily. You can switch to a different shell,
1694 # e.g. tcl, completely by executing the following Perl commands inside
1697 # <SCRIPT TYPE="text/ssperl">
1698 # $main::ShellScriptContentType = "text/ssTcl"; # Yes, you can do this
1699 # CGIscriptor::RedirectShellScript('/usr/bin/tcl'); # Pipe to Tcl
1700 # $CGIscriptor::NoShellScriptInterpolation = 1;
1703 # After this script is executed, CGIscriptor will parse scripts of
1704 # TYPE="text/ssTcl" and pipe their contents into '|/usr/bin/tcl'
1705 # WITHOUT interpolation (i.e., NO substitution of Perl variables).
1706 # The crucial function is :
1707 # CGIscriptor::RedirectShellScript('/usr/bin/tcl')
1708 # After executing this function, all shell scripts AND all
1709 # calls to SAFEqx()) are piped into '|/usr/bin/tcl'. If the argument
1710 # of RedirectShellScript is empty, e.g., '', the original (default)
1713 # The standard output, STDOUT, of any pipe is send to the client.
1714 # Currently, you should be carefull with quotes in such a piped script.
1715 # The results of a pipe is NOT put on the @CGIscriptorResults stack.
1716 # As a result, you do not have access to the output of any piped (#!)
1717 # process! If you want such access, execute
1718 # <SCRIPT TYPE="text/osshell">echo "script"|command</SCRIPT>
1720 # <SCRIPT TYPE="text/ssperl">
1721 # $resultvar = SAFEqx('echo "script"|command');
1724 # Safety is never complete. Although SAFEqx() prevents some of the
1725 # most obvious forms of attacks and security slips, it cannot prevent
1726 # them all. Especially, complex combinations of quotes and intricate
1727 # variable references cannot be handled safely by SAFEqx. So be on
1731 # PERL CODE EVALUATION (CONTENT-TYPE=TEXT/SSPERL)
1733 # All PERL scripts are evaluated inside a PERL package. This package
1734 # has a separate name space. This isolated name space protects the
1735 # CGIscriptor.pl program against interference from user code. However,
1736 # some variables, e.g., $_, are global and cannot be protected. You are
1737 # advised NOT to use such global variable names. You CAN write
1738 # directives that directly access the variables in the main program.
1739 # You do so at your own risk (there is definitely enough rope available
1740 # to hang yourself). The behavior of CGIscriptor becomes undefined if
1741 # you change its private variables during run time. The PERL code
1742 # directives are used as in:
1743 # $Result = eval($directive); print $Result;'';
1744 # ($directive contains all text between <SCRIPT></SCRIPT>).
1745 # That is, the <directive> is treated as ''-quoted string and
1746 # the result is treated as a scalar. To prevent the VALUE of the code
1747 # block from appearing on the client's screen, end the directive with
1748 # ';""</SCRIPT>'. Evaluated directives return the last value, just as
1749 # eval(), blocks, and subroutines, but only as a scalar.
1751 # IMPORTANT: All PERL variables defined are persistent. Each <SCRIPT>
1752 # </SCRIPT> construct is evaluated as a {}-block with associated scope
1753 # (e.g., for "my $var;" declarations). This means that values assigned
1754 # to a PERL variable can be used throughout the document unless they
1755 # were declared with "my". The following will actually work as intended
1756 # (note that the ``-quotes in this example are NOT evaluated, but used
1757 # as simple quotes):
1759 # <META CONTENT="text/ssperl; CGI=`$String='abcdefg'`">
1761 # <SCRIPT TYPE=text/ssperl>@List = split('', $String);</SCRIPT>
1763 # <SCRIPT TYPE=text/ssperl>join(", ", @List[1..$#List]);</SCRIPT>
1765 # The first <SCRIPT TYPE=text/ssperl></SCRIPT> construct will return the
1766 # value scalar(@List), the second <SCRIPT TYPE=text/ssperl></SCRIPT>
1767 # construct will print the elements of $String separated by commas, leaving
1768 # out the first element, i.e., $List[0].
1770 # Another warning: './' and '~/' are ALWAYS replaced by the values of
1771 # $YOUR_SCRIPTS and $YOUR_HTML_FILES, respectively . This can interfere
1772 # with pattern matching, e.g., $a =~ s/aap\./noot\./g will result in the
1773 # evaluations of $a =~ s/aap\\${YOUR_SCRIPTS}noot\\${YOUR_SCRIPTS}g. Use
1774 # s@<regexp>.@<replacement>.@g instead.
1777 # SERVER SIDE SESSIONS AND ACCESS CONTROL (LOGIN)
1779 # An infrastructure for user acount authorization and file access control
1780 # is available. Each request is matched against a list of URL path patterns.
1781 # If the request matches, a Session Ticket is required to access the URL.
1782 # This Session Ticket should be present as a CGI parameter or Cookie, eg:
1784 # CGI: SESSIONTICKET=<value>
1785 # Cookie: CGIscriptorSESSION=<value>
1787 # The example implementation stores Session Tickets as files in a local
1788 # directory. To create Session Tickets, a Login request must be given
1789 # with a LOGIN=<value> CGI parameter, a user name and a (doubly hashed)
1790 # password. The user name and (singly hashed) password are stored in a
1791 # PASSWORD ticket with the same name as the user account (name cleaned up
1794 # The example session model implements 4 functions:
1796 # The password is hashed with the user name and server side salt, and then
1797 # hashed with a random salt. Client and Server both perform these actions
1798 # and the Server only grants access if restults are the same. The server
1799 # side only stores the password hashed with the user name and
1800 # server side salt. Neither the plain password, nor the hashed password is
1801 # ever exchanged. Only values hashed with the one-time salt are exchanged.
1803 # For every access to a restricted URL, the Session Ticket is checked before
1804 # access is granted. There are three session modes. The first uses a fixed
1805 # Session Ticket that is stored as a cookie value in the browser (actually,
1806 # as a sessionStorage value). The second uses only the IP address at login
1807 # to authenticate requests. The third
1808 # is a Challenge mode, where the client has to calculate the value of the
1809 # next one-time Session Ticket from a value derived from the password and
1812 # A new password is hashed with the user name and server side salt, and
1813 # then encrypted (XORed)
1814 # with the old password hashed with the user name and salt. That value is
1815 # exchanged and XORed with the stored old hashed(password+username+salt).
1816 # Again, the stored password value is never exchanged unencrypted.
1818 # The text of a new account (Type: PASSWORD) file is constructed from
1819 # the new username (CGI: NEWUSERNAME, converted to lowercase) and
1820 # hashed new password (CGI: NEWPASSWORD). The same process is used to encrypt
1821 # the new password as is used for the Password Change function.
1822 # Again, the stored password value is never exchanged unencrypted.
1823 # Some default setting are encoded. For display in the browser, the new password
1824 # is reencrypted (XORed) with a special key, the old password hash
1825 # hashed with a session specific random hex value sent initially with the
1826 # session login ticket ($RANDOMSALT).
1827 # For example for user "NewUser" and password "NewPassword" with filename
1832 # Password: 19afeadfba8d5dcd252e157fafd3010859f8762b87682b6b6cdb3e565194fa91
1833 # IPaddress: 127\.0\.0\.1
1834 # AllowedPaths: ^/Private/[\w\-]+\.html?
1835 # AllowedPaths: ^/Private/newuser/
1836 # Salt: e93cf858a1d5626bf095ea5c25df990dfa969ff5a5dc908b22c9a5229b525f65
1838 # Date: Fri Jun 29 12:46:22 2012
1840 # Signature: 676c35d3aa63540293ea5442f12872bfb0a22665b504f58f804582493b6ef04e
1842 # The password is created with the commands:
1844 # printf '%s' 'NewPasswordnewuser970e68017413fb0ea84d7fe3c463077636dd6d53486910d4a53c693dd4109b1a'|shasum -a 256
1846 # However, the password account files are protected against unauthorized change.
1847 # To obtain a valid Password account, the following command should be given:
1849 # perl CGIscriptor.pl --managelogin salt=Private/.Passwords/SALT \
1850 # masterkey='Sherlock investigates oleander curry in Bath' \
1851 # password='NewPassword' \
1852 # Private/.Passwords/newuser
1857 # The session authentication mechanism is based on the exchange of ticket
1858 # identifiers. A ticket identifier is just a string of characters, a name
1859 # or a random 64 character hexadecimal string. Ticket identifiers should be
1860 # "safe" filenames (except user names). There are four types of tickets:
1861 # PASSWORD: User account descriptors, including a user name and password
1862 # LOGIN: Temporary anonymous tickets used during login
1863 # IPADDRESS: Authetication tokens that allow access based on the IP address of the request
1864 # SESSION: Reusable authetication tokens
1865 # CHALLENGE: One-time authetication tokens
1866 # All tickets can have an expiration date in the form of a time duration
1867 # from creation, in seconds, minutes, hours, or days (+duration[smhd]).
1868 # An absolute time can be given in seconds since the epoch of the server host.
1869 # Note that expiration times of CHALLENGE authetication tokens are calculated
1870 # from the last access time. Accounts can include a maximal lifetime
1871 # for session tickets (MaxLifetime).
1873 # A Login page should create a LOGIN ticket file locally and send a
1874 # server specific salt, a Random salt, and a LOGIN ticket
1875 # identifier. The server side compares the username and hashed password,
1876 # actually hashed(hashed(password+serversalt)+Random salt) from the client with
1877 # the values it calculates from the stored Random salt from the LOGIN
1878 # ticket and the hashed(password+serversalt) from the PASSWORD ticket. If
1879 # successful, a new SESSION ticket is generated as a hash sum of the stored
1880 # password and the LOGIN ticket. This SESSION ticket should also be
1881 # generated by the client and stored as sessionStorage and cookie values
1882 # as needed. The Username, IP address and Path are available as
1883 # $LoginUsername, $LoginIPaddress, and $LoginPath, respectively.
1885 # The CHALLENGE protocol stores the same value as the SESSION tickets.
1886 # However, this value is not exchanged, but kept secret in the JavaScript
1887 # sessionStorage object. Instead, every page returned from the
1888 # server will contain a one-time Challenge value ($CHALLENGETICKET) which
1889 # has to be hashed with the stored value to return the current ticket
1892 # In the current example implementation, all random values are created as
1893 # full, 256 bit SHA256 hash values (Hex strings) of 64 bytes read from
1899 # A limited level of authorization tuning is build into the login system.
1900 # Each account file (PASSWORD ticket file) can contain a number of
1901 # Capabilities lines. These control special priveliges. The
1902 # Capabilities can be checked inside the HTML pages as part of the
1903 # ticket information. Two privileges are handled internally:
1904 # CreateUser and VariableREMOTE_ADDR.
1905 # CreateUser allows the logged in user to create a new user account.
1906 # With VariableREMOTE_ADDR, the session of the logged in user is
1907 # not limited to the Remote IP address from which the inital log-in took
1908 # place. Sessions can hop from one apparant (proxy) IP address to another,
1909 # e.g., when using Tor. Any IPaddress patterns given in the PASSWORD
1910 # ticket file remain in effect during the session. For security reasons,
1911 # the VariableREMOTE_ADDR capability is only effective if the session
1912 # type is CHALLENGE.
1915 # Security considerations with Session tickets
1917 # For strong security, please use end-to-end encryption. This can be
1918 # achieved using a VPN (Virtual Private Network), SSH tunnel, or a HTTPS
1919 # capable server with OpenSSL. The session ticket system of CGIscriptor.pl
1920 # is intended to be used as a simple authentication mechanism WITHOUT
1921 # END-TO-END ENCRYPTION. The authenticating mechanism tries to use some
1922 # simple means to protect the authentication process from eavesdropping.
1923 # For this it uses a secure hash function, SHA256. For all practial purposes,
1924 # it is impossible to "decrypt" a SHA256 sum. But this login scheme is
1925 # only as secure as your browser. Which, in general, is not very secure.
1927 # One weakness of the implemented procedure is that the Client obtains
1928 # the code to encrypt the passwords from the server. It is the JavaScript
1929 # code in the HTML pages. An attacker who could place himself between Server
1930 # and Client, a man in the middle attack (MITM), could change the code to
1931 # reveal the plaintext password and other information. There is no real
1932 # protection against this attack without end-to-end encryption and
1933 # authentication. A simple, but rather cumbersome, way to check for such
1934 # attacks would be to store known good copys of the pages (downloaded
1935 # with a browser or automatically with curl or wget) and
1936 # then use other tools to download new pages at random intervals and compare
1937 # them to the old pages. For instance, the following line would remove
1938 # the variable ticket codes and give a fixed SHA256 sum for the original
1939 # Login.html page+code:
1940 # curl http://localhost:8080/Private/index.html | \
1941 # sed 's/=\"[a-z0-9]\{64\}\"/=""/g' | shasum -a 256
1942 # A simple diff command between old and new files should give only
1943 # differences in half a dozen lines, where only hexadecimal salt values
1944 # will actually differ.
1946 # A solution for the MITM attack problem would be to run a trusted web
1947 # page from local storage to handle password input. An example of such
1948 # a solution has been implemented for IPADDRESS sessions only. The
1949 # Login.html page has three comment lines saying:
1950 # "UNCOMMENT for use in a local version of the Private/Login.html web page."
1951 # If you save this page and follow the instructions in these comments, you
1952 # will be able to load the page from local storage in your browser and
1953 # log in at the designated web site. It is not (yet) possible to set the
1954 # required session storage inside the browser, so this method only works
1955 # for IPADDRESS sessions.
1957 # Humans tend to reuse passwords. A compromise of a site running
1958 # CGIscriptor.pl could therefore lead to a compromise of user accounts at
1959 # other sites. Therefore, plain text passwords are never stored, used, or
1960 # exchanged. Instead, the plain password and user name are "encrypted" with
1961 # a server site salt value. Actually, all are concatenated and hashed
1962 # with a one-way secure hash function (SHA256) into a single string.
1963 # Whenever the word "password" is used, this hash sum is meant. Note that
1964 # the salts are generated from /dev/urandom. You should check whether the
1965 # implementation of /dev/urandom on your platform is secure before
1966 # relying on it. This might be a problem when running CGIscriptor under
1967 # Cygwin on MS Windows.
1968 # Note: no attempt is made to slow down the password hash, so bad
1969 # passwords can be cracked by brute force
1971 # As the (hashed) passwords are all that is needed to identify at the site,
1972 # these should not be stored in this form. A site specific passphrase
1973 # can be entered as an environment variable ($ENV{'CGIMasterKey'}). This
1974 # phrase is hashed with the server site salt and the result is hashed with
1975 # the user name and then XORed with the password when it is stored. Also, to
1976 # detect changes to the account (PASSWORD) and session tickets, a
1977 # (HMAC) hash of some of the contents of the ticket with the server salt and
1978 # CGIMasterKey is stored in each ticket.
1980 # Creating a valid (hashed) password, encrypt it with the CGIMasterKey and
1981 # construct a signature of the ticket are non-trivial. This has to be redone
1982 # with every change of the ticket file or CGIMasterKey change. CGIscriptor
1983 # can do this from the command line with the command:
1985 # perl CGIscriptor.pl --managelogin salt=Private/.Passwords/SALT \
1986 # masterkey='Sherlock investigates oleander curry in Bath' \
1987 # password='There is no password like more password' \
1990 # CGIscriptor will exit after this command with the first option being
1991 # --managelogin. Options have the form:
1993 # salt=[file or string]
1994 # Server salt value to use io the value
1995 # stored in the ticket file. Will replace the stored value if a new
1996 # password is given. If you change the server salt, you have to
1997 # reset all the passwords. There is absolutely no procedure known
1998 # to recover plaintext passwords, except asking the account holders.
1999 # You are strongly adviced to make a backup before you apply such a change
2000 # masterkey=[file or string]
2001 # CGIMasterKey used to read and decrypt the ticket
2002 # newmasterkey=[file or string]
2003 # CGIMasterKey used to encrypt, sign,
2004 # and write the ticket. Defaults to the masterkey. If you change
2005 # the masterkey, you will have to reset all the accounts. You are strongly
2006 # adviced to make a backup before you apply such a change
2007 # password=[file or string]
2008 # New plaintext password
2010 # When the value of an option is a existing file path, the first line of
2011 # that file is used. Options are followed by one or more paths plus names
2012 # of existing ticket files. Each password option is only used for a single
2013 # ticket file. It is most definitely a bad idea to use a password that is
2014 # identical to an existing filepath, as the file will be read instead. Be
2015 # aware that the name of the file should be a cleaned up version of the
2016 # Username. This will not be checked.
2018 # For the authentication and a change of password, the (old) password
2019 # is used to "encrypt" a random one-time token or the new password,
2020 # respectively. For authentication, decryption is not needed, so a secure
2021 # hash function (SHA256) is used to create a one-way hash sum "encryption".
2022 # A new password must be decrypted. New passwords are encryped by XORing
2023 # them with the old password.
2025 # Strong Passwords: It is so easy
2026 # If you only could see what you are typing
2028 # Your password might be vulnerable to brute force guessing
2029 # (https://en.wikipedia.org/wiki/Brute_force_attack).
2030 # Protections against such attacks are costly in terms of code
2031 # complexity, bugs, and execution time. However, there is a very
2032 # simple and secure counter measure. See the XKCD comic
2033 # (http://xkcd.com/936/). The phrase, "There is no password like more
2034 # password" would be both much easier to remember, and still stronger
2035 # than "h4]D%@m:49", at least before this phrase was pasted as an
2036 # example on the Internet.
2038 # For the procedures used at this site, a basic computer setup can
2039 # check in the order of a billion passwords per second. You need a
2040 # password (or phrase) strength in the order of 56 bits to be a
2041 # little secure (one year on a single computer). Please be so kind
2042 # and add the name of your favorite flower, dish, fictional
2043 # character, or small town to your password. Say, Oleander, Curry,
2044 # Sherlock, or Bath, UK (each adds ~12 bits) or even the phrase "Sherlock
2045 # investigates oleander curry in Bath" (adds > 56 bits, note that
2046 # oleander is poisonous, so do not try this curry at home). That
2047 # would be more effective than adding a thousand rounds of encryption.
2048 # Typing long passwords without seeing what you are typing is
2049 # problematic. So a button should be included to make password
2055 # Client side JavaScript code definitions. Variable names starting with '$'
2056 # are CGIscriptor CGI variables. Some of the hashes could be strengthened
2057 # by switching to HMAC signatures. However, the security issues of
2058 # maintaining parallel functions for HMAC in both Perl and Javascript seem
2059 # to be more serious than the attack vectors against the hashes. But HMAC
2060 # is indeed used for the ticket signatures.
2063 # HashPlaintextPassword() {
2064 # var plaintextpassword = document.getElementById('PASSWORD');
2065 # var serversalt = document.getElementById('SERVERSALT');
2066 # var username = document.getElementById('CGIUSERNAME');
2067 # return hex_sha256(plaintextpassword.value+username.value.toLowerCase()+serversalt.value);
2069 # var randomsalt = $RANDOMSALT; // From CGIscriptor
2070 # var loginticket = $LOGINTICKET; // From CGIscriptor
2071 # // Hash plaintext password
2072 # var password = HashPlaintextPassword();
2073 # // Authorize login
2074 # var hashedpassword = hex_sha256(randomsalt+password);
2076 # var sessionticket = hex_sha256(loginticket+password);
2077 # sessionStorage.setItem("CGIscriptorPRIVATE", sessionticket);
2078 # // Secretkey for encrypting new passwords, acts like a one-time pad
2079 # // Is set anew with every login, ie, also whith password changes
2080 # // and for each create new user request
2081 # var secretkey = hex_sha256(password+loginticket+randomsalt);
2082 # sessionStorage.setItem("CGIscriptorSECRET", secretkey);
2084 # // For a SESSION type request
2085 # sessionticket = sessionStorage.getItem("CGIscriptorPRIVATE");
2086 # createCookie("CGIscriptorSESSION",sessionticket, 0, "");
2088 // For a CHALLENGE type request
2089 # var sessionset = "$CHALLENGETICKET"; // From CGIscriptor
2090 # var sessionkey = sessionStorage.getItem("CGIscriptorPRIVATE");
2091 # sessionticket = hex_sha256(sessionset+sessionkey);
2092 # createCookie("CGIscriptorCHALLENGE",sessionticket, 0, "");
2094 # // For transmitting a new password
2095 # HashPlaintextNewPassword() {
2096 # var plaintextpassword = document.getElementById('NEWPASSWORD');
2097 # var serversalt = document.getElementById('SERVERSALT');
2098 # var username = document.getElementById('NEWUSERNAME');
2099 # return hex_sha256(plaintextpassword.value+username.value.toLowerCase()+serversalt.value);
2102 # var newpassword = document.getElementById('NEWPASSWORD');
2103 # var newpasswordrep = document.getElementById('NEWPASSWORDREP');
2104 # // Hash plaintext password
2105 # newpassword.value = HashPlaintextNewPassword();
2106 # var secretkey = sessionStorage.getItem("CGIscriptorSECRET");
2108 # var encrypted = XOR_hex_strings(secretkey, newpassword.value);
2109 # newpassword.value = encrypted;
2110 # newpasswordrep.value = encrypted;
2112 # // XOR of hexadecimal strings of equal length
2113 # function XOR_hex_strings(hex1, hex2) {
2114 # var resultHex = "";
2115 # var maxlength = Math.max(hex1.length, hex2.length);
2117 # for(var i=0; i < maxlength; ++i) {
2118 # var h1 = hex1.charAt(i);
2120 # var h2 = hex2.charAt(i);
2122 # var d1 = parseInt(h1,16);
2123 # var d2 = parseInt(h2,16);
2124 # var resultD = d1^d2;
2125 # resultHex = resultHex+resultD.toString(16);
2130 # Password encryption based on $ENV{'CGIMasterKey'}.
2131 # Server side Perl code:
2133 # # Password encryption
2134 # my $masterkey = $ENV{'CGIMasterKey'}
2135 # my $hash1 = hash_string($masterkey.$serversalt);
2136 # my $CryptKey = hash_string($username.$hash1);
2137 # $password = XOR_hex_strings($CryptKey,$password);
2139 # # Key for HMAC signing
2140 # my $hash1 = hash_string($masterkey.$serversalt);
2141 # my $HMACKey = hash_string($username.$hash1);
2147 # A CGIscriptor package is attached to the bottom of this file. With
2148 # this package you can personalize your version of CGIscriptor by
2149 # including often used perl routines. These subroutines can be
2150 # accessed by prefixing their names with CGIscriptor::, e.g.,
2151 # <SCRIPT LANGUAGE=PERL TYPE=text/ssperl>
2152 # CGIscriptor::ListDocs("/Books/*") # List all documents in /Books
2154 # It already contains some useful subroutines for Document Management.
2155 # As it is a separate package, it has its own namespace, isolated from
2156 # both the evaluator and the main program. To access variables from
2157 # the document <SCRIPT></SCRIPT> blocks, use $CGIexecute::<var>.
2159 # Currently, the following functions are implemented
2160 # (precede them with CGIscriptor::, see below for more information)
2161 # - SAFEqx ('String') -> result of qx/"String"/ # Safe application of ``-quotes
2162 # Is used by text/osshell Shell scripts. Protects all CGI
2163 # (client-supplied) values with single quotes before executing the
2164 # commands (one of the few functions that also works WITHOUT CGIscriptor::
2166 # - defineCGIvariable ($name[, $default) -> 0/1 (i.e., failure/success)
2167 # Is used by the META tag to define and initialize CGI and ENV
2168 # name/value pairs. Tries to obtain an initializing value from (in order):
2171 # The default value given (if any)
2172 # (one of the few functions that also works WITHOUT CGIscriptor::
2174 # - CGIsafeFileName (FileName) -> FileName or ""
2175 # Check a string against the Allowed File Characters (and ../ /..).
2176 # Returns an empty string for unsafe filenames.
2177 # - CGIsafeEmailAddress (Email) -> Email or ""
2178 # Check a string against correct email address pattern.
2179 # Returns an empty string for unsafe addresses.
2180 # - RedirectShellScript ('CommandString') -> FILEHANDLER or undef
2181 # Open a named PIPE for SAFEqx to receive ALL shell scripts
2182 # - URLdecode (URL encoded string) -> plain string # Decode URL encoded argument
2183 # - URLencode (plain string) -> URL encoded string # Encode argument as URL code
2184 # - CGIparseValue (ValueName [, URL_encoded_QueryString]) -> Decoded value
2185 # Extract the value of a CGI variable from the global or a private
2186 # URL-encoded query (multipart POST raw, NOT decoded)
2187 # - CGIparseValueList (ValueName [, URL_encoded_QueryString])
2188 # -> List of decoded values
2189 # As CGIparseValue, but now assembles ALL values of ValueName into a list.
2190 # - CGIparseHeader (ValueName [, URL_encoded_QueryString]) -> Header
2191 # Extract the header of a multipart CGI variable from the global or a private
2192 # URL-encoded query ("" when not a multipart variable or absent)
2193 # - CGIparseForm ([URL_encoded_QueryString]) -> Decoded Form
2194 # Decode the complete global URL-encoded query or a private
2196 # - read_url(URL) # Returns the page from URL (with added base tag, both FTP and HTTP)
2197 # Uses main::GET_URL(URL, 1) to get at the command to read the URL.
2198 # - BrowseDirs(RootDirectory [, Pattern, Startdir, CGIname]) # print browsable directories
2199 # - ListDocs(Pattern [,ListType]) # Prints a nested HTML directory listing of
2200 # all documents, e.g., ListDocs("/*", "dl");.
2201 # - HTMLdocTree(Pattern [,ListType]) # Prints a nested HTML listing of all
2202 # local links starting from a given document, e.g.,
2203 # HTMLdocTree("/Welcome.html", "dl");
2206 # THE RESULTS STACK: @CGISCRIPTORRESULTS
2208 # If the pseudo-variable "$CGIscriptorResults" has been defined in a
2209 # META tag, all subsequent SCRIPT and META results are pushed
2210 # on the @CGIscriptorResults stack. This list is just another
2211 # Perl variable and can be used and manipulated like any other list.
2212 # $CGIscriptorResults[-1] is always the last result.
2213 # This is only of limited use, e.g., to use the results of an OS shell
2214 # script inside a Perl script. Will NOT contain the results of Pipes
2215 # or code from MIME-profiling.
2218 # USEFULL CGI PREDEFINED VARIABLES (DO NOT ASSIGN TO THESE)
2220 # $CGI_HOME - The DocumentRoot directory
2221 # $CGI_Decoded_QS - The complete decoded Query String
2222 # $CGI_Content_Length - The ACTUAL length of the Query String
2223 # $CGI_Date - Current date and time
2224 # $CGI_Year $CGI_Month $CGI_Day $CGI_WeekDay - Current Date
2225 # $CGI_Time - Current Time
2226 # $CGI_Hour $CGI_Minutes $CGI_Seconds - Current Time, split
2228 # $CGI_GMTYear $CGI_GMTMonth $CGI_GMTDay $CGI_GMTWeekDay $CGI_GMTYearDay
2229 # $CGI_GMTHour $CGI_GMTMinutes $CGI_GMTSeconds $CGI_GMTisdst
2232 # USEFULL CGI ENVIRONMENT VARIABLES
2234 # Variables accessible (in APACHE) as $ENV{<name>}
2235 # (see: "http://hoohoo.ncsa.uiuc.edu/cgi/env.html"):
2237 # QUERY_STRING - The query part of URL, that is, everything that follows the
2239 # PATH_INFO - Extra path information given after the script name
2240 # PATH_TRANSLATED - Extra pathinfo translated through the rule system.
2241 # (This doesn't always make sense.)
2242 # REMOTE_USER - If the server supports user authentication, and the script is
2243 # protected, this is the username they have authenticated as.
2244 # REMOTE_HOST - The hostname making the request. If the server does not have
2245 # this information, it should set REMOTE_ADDR and leave this unset
2246 # REMOTE_ADDR - The IP address of the remote host making the request.
2247 # REMOTE_IDENT - If the HTTP server supports RFC 931 identification, then this
2248 # variable will be set to the remote user name retrieved from
2249 # the server. Usage of this variable should be limited to logging
2251 # AUTH_TYPE - If the server supports user authentication, and the script
2252 # is protected, this is the protocol-specific authentication
2253 # method used to validate the user.
2254 # CONTENT_TYPE - For queries which have attached information, such as HTTP
2255 # POST and PUT, this is the content type of the data.
2256 # CONTENT_LENGTH - The length of the said content as given by the client.
2257 # SERVER_SOFTWARE - The name and version of the information server software
2258 # answering the request (and running the gateway).
2259 # Format: name/version
2260 # SERVER_NAME - The server's hostname, DNS alias, or IP address as it
2261 # would appear in self-referencing URLs
2262 # GATEWAY_INTERFACE - The revision of the CGI specification to which this
2263 # server complies. Format: CGI/revision
2264 # SERVER_PROTOCOL - The name and revision of the information protocol this
2265 # request came in with. Format: protocol/revision
2266 # SERVER_PORT - The port number to which the request was sent.
2267 # REQUEST_METHOD - The method with which the request was made. For HTTP,
2268 # this is "GET", "HEAD", "POST", etc.
2269 # SCRIPT_NAME - A virtual path to the script being executed, used for
2270 # self-referencing URLs.
2271 # HTTP_ACCEPT - The MIME types which the client will accept, as given by
2272 # HTTP headers. Other protocols may need to get this
2273 # information from elsewhere. Each item in this list should
2274 # be separated by commas as per the HTTP spec.
2275 # Format: type/subtype, type/subtype
2276 # HTTP_USER_AGENT - The browser the client is using to send the request.
2277 # General format: software/version library/version.
2280 # INSTRUCTIONS FOR RUNNING CGIscriptor ON UNIX
2282 # CGIscriptor.pl will run on any WWW server that runs Perl scripts, just add
2283 # a line like the following to your srm.conf file (Apache example):
2285 # ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
2287 # URL's that refer to http://www.your.address/SHTML/... will now be handled
2288 # by CGIscriptor.pl, which can use a private directory tree (default is the
2289 # DOCUMENT_ROOT directory tree, but it can be anywhere, see manual).
2291 # If your hosting ISP won't let you add ScriptAlias lines you can use
2292 # the following "rewrite"-based "scriptalias" in .htaccess
2293 # (from Gerd Franke)
2297 # RewriteCond %{REQUEST_FILENAME} .html$
2298 # RewriteCond %{SCRIPT_FILENAME} !cgiscriptor.pl$
2299 # RewriteCond %{REQUEST_FILENAME} -f
2300 # RewriteRule ^(.*)$ /cgi-bin/cgiscriptor.pl/$1?&%{QUERY_STRING}
2302 # Everthing with the extension ".html" and not including "cgiscriptor.pl"
2303 # in the url and where the file "path/filename.html" exists is redirected
2304 # to "/cgi.bin/cgiscriptor.pl/path/filename.html?query".
2305 # The user configuration should get the same path-level as the
2308 # # Just enter your own directory path here
2309 # $YOUR_HTML_FILES = "$ENV{'DOCUMENT_ROOT'}";
2310 # # use DOCUMENT_ROOT only, if .htaccess lies in the root-directory.
2312 # If this .htaccess goes in a specific directory, the path to this
2313 # directory must be added to $ENV{'DOCUMENT_ROOT'}.
2315 # The CGIscriptor file contains all documentation as comments. These
2316 # comments can be removed to speed up loading (e.g., `egrep -v '^#'
2317 # CGIscriptor.pl` > leanScriptor.pl). A bare bones version of
2318 # CGIscriptor.pl, lacking documentation, most comments, access control,
2319 # example functions etc. (but still with the copyright notice and some
2320 # minimal documentation) can be obtained by calling CGIscriptor.pl on the
2321 # command line with the '-slim' command line argument, e.g.,
2323 # >CGIscriptor.pl -slim > slimCGIscriptor.pl
2325 # CGIscriptor.pl can be run from the command line with <path> and <query> as
2326 # arguments, as `CGIscriptor.pl <path> <query>`, inside a perl script
2327 # with 'do CGIscriptor.pl' after setting $ENV{PATH_INFO}
2328 # and $ENV{QUERY_STRING}, or CGIscriptor.pl can be loaded with 'require
2329 # "/real-path/CGIscriptor.pl"'. In the latter case, requests are processed
2330 # by 'Handle_Request();' (again after setting $ENV{PATH_INFO} and
2331 # $ENV{QUERY_STRING}).
2333 # Using the command line execution option, CGIscriptor.pl can be used as a
2334 # document (meta-)preprocessor. If the first argument is '-', STDIN will be read.
2337 # > cat MyDynamicDocument.html | CGIscriptor.pl - '[QueryString]' > MyStaticFile.html
2339 # This command line will produce a STATIC file with the DYNAMIC content of
2340 # MyDocument.html "interpolated".
2342 # This option would be very dangerous when available over the internet.
2343 # If someone could sneak a 'http://www.your.domain/-' URL past your
2344 # server, CGIscriptor could EXECUTE any POSTED contend.
2345 # Therefore, for security reasons, STDIN will NOT be read
2346 # if ANY of the HTTP server environment variables is set (e.g.,
2347 # SERVER_PORT, SERVER_PROTOCOL, SERVER_NAME, SERVER_SOFTWARE,
2348 # HTTP_USER_AGENT, REMOTE_ADDR).
2349 # This block on processing STDIN on HTTP requests can be lifted by setting
2350 # $BLOCK_STDIN_HTTP_REQUEST = 0;
2351 # In the security configuration. Butbe carefull when doing this.
2352 # It can be very dangerous.
2354 # Running demo's and more information can be found at
2355 # http://www.fon.hum.uva.nl/~rob/OSS/OSS.html
2357 # A pocket-size HTTP daemon, CGIservlet.pl, is available from my web site or
2358 # CPAN that can use CGIscriptor.pl as the base of a µWWW server and
2359 # demonstrates its use.
2362 # PROCESSING NON-FILESYSTEM DATA
2364 # Normally, HTTP (WWW) requests map onto file that can be accessed
2365 # using the perl open() function. That is, the web server runs on top of
2366 # some directory structure. However, we can envission (and put to good
2367 # use) other systems that do not use a normal file system. The whole CGI
2368 # was developed to make dynamic document generation possible.
2370 # A special case is where we want to have it both: A normal web server
2371 # with normal "file data", but not a normal files system. For instance,
2372 # we want or normal Web Site to run directly from a RAM hash table or
2373 # other database, instead of from disk. But we do NOT want to code the
2374 # whole site structure in CGI.
2376 # CGIscriptor can do this. If the web server fills an environment variable
2377 # $ENV{'CGI_FILE_CONTENT'} with the content of the "file", then the content
2378 # of this variable is processed instead of opening a file. If this environment
2379 # variable has the value '-', the content of another environment variable,
2380 # $ENV{'CGI_DATA_ACCESS_CODE'} is executed as:
2381 # eval("\@_ = ($file_path); do {$ENV{'CGI_DATA_ACCESS_CODE'}};")
2382 # and the result is processed as if it was the content of the requested
2384 # (actually, the names of the environment variables are user configurable,
2385 # they are stored in the local variables $CGI_FILE_CONTENT and
2386 # $CGI_DATA_ACCESS_CODE)
2388 # When using this mechanism, the SRC attribute mechanism will only partially work.
2389 # Only the "recursive" calls to CGIscriptor (the ProcessFile() function)
2390 # will work, the automagical execution of SRC files won't. (In this case,
2391 # the SRC attribute won't work either for other scripting languages)
2394 # NON-UNIX PLATFORMS
2396 # CGIscriptor.pl was mainly developed and tested on UNIX. However, as I
2397 # coded part of the time on an Apple Macintosh under MacPerl, I made sure
2398 # CGIscriptor did run under MacPerl (with command line options). But only
2399 # as an independend script, not as part of a HTTP server. I have used it
2400 # under Apache in Windows XP.
2405 ###############################################################################
2407 # SECURITY CONFIGURATION
2409 # Special configurations related to SECURITY
2410 # (i.e., optional, see also environment variables below)
2413 # Log Clients and the requested paths (Redundant when loging Queries)
2415 $ClientLog = "./Client.log"; # (uncomment for use)
2417 # Format: Localtime | REMOTE_USER REMOTE_IDENT REMOTE_HOST REMOTE_ADDRESS \
2418 # PATH_INFO CONTENT_LENGTH (actually, the real query+post length)
2420 # Log Clients and the queries, the CGIQUERYDECODE is required if you want
2421 # to log queries. If you log Queries, the loging of Clients is redundant
2422 # (note that queries can be quite long, so this might not be a good idea)
2424 #$QueryLog = "./Query.log"; # (uncomment for use)
2427 # the Access files should contain Hostnames or IP addresses,
2428 # i.e. REMOTE_HOST or REMOTE_ADDR, each on a separate line
2429 # optionally followed by one ore more file patterns, e.g., "edu /DEMO".
2430 # Matching is done "domain first". For example ".edu" matches all
2431 # clients whose "name" ends in ".edu" or ".EDU". The file pattern
2432 # "/DEMO" matches all paths that contain the strings "/DEMO" or "/demo"
2433 # (both matchings are done case-insensitive).
2434 # The name special symbol "-" matches ALL clients who do not supply a
2435 # REMOTE_HOST name, "*" matches all clients.
2436 # Lines starting with '-e' are evaluated. A non-zero return value indicates
2437 # a match. You can use $REMOTE_HOST, $REMOTE_ADDR, and $PATH_INFO. These
2438 # lines are evaluated in the program's own name-space. So DO NOT assign to
2441 # Accept the following users (remove comment # and adapt filename)
2442 $CGI_Accept = -s
"$YOUR_SCRIPTS/ACCEPT.lis" ?
"$YOUR_SCRIPTS/ACCEPT.lis" : ''; # (uncomment for use)
2444 # Reject requests from the following users (remove comment # and
2445 # adapt filename, this is only of limited use)
2446 $CGI_Reject = -s
"$YOUR_SCRIPTS/REJECT.lis" ?
"$YOUR_SCRIPTS/REJECT.lis" : ''; # (uncomment for use)
2448 # Empty lines or comment lines starting with '#' are ignored in both
2449 # $CGI_Accept and $CGI_Reject.
2451 # Block STDIN (i.e., '-') requests when servicing an HTTP request
2452 # Comment this out if you realy want to use STDIN in an on-line web server
2453 $BLOCK_STDIN_HTTP_REQUEST = 1;
2456 # End of security configuration
2458 ##################################################<<<<<<<<<<End Remove
2460 # PARSING CGI VALUES FROM THE QUERY STRING (USER CONFIGURABLE)
2462 # The CGI parse commands. These commands extract the values of the
2463 # CGI variables from the URL encoded Query String.
2464 # If you want to use your own CGI decoders, you can call them here
2465 # instead, using your own PATH and commenting/uncommenting the
2468 # CGI parse command for individual values
2469 # (if $List > 0, returns a list value, if $List < 0, a hash table, this is optional)
2470 sub YOUR_CGIPARSE
# ($Name [, $List]) -> Decoded value
2473 my $List = shift || 0;
2474 # Use one of the following by uncommenting
2475 if(!$List) # Simple value
2477 return CGIscriptor
::CGIparseValue
($Name) ;
2479 elsif($List < 0) # Hash tables
2481 return CGIscriptor
::CGIparseValueHash
($Name); # Defined in CGIscriptor below
2485 return CGIscriptor
::CGIparseValueList
($Name); # Defined in CGIscriptor below
2488 # return `/PATH/cgiparse -value $Name`; # Shell commands
2489 # require "/PATH/cgiparse.pl"; return cgivalue($Name); # Library
2492 sub YOUR_CGIQUERYDECODE
2494 # Use one of the following by uncommenting
2495 return CGIscriptor
::CGIparseForm
(); # Defined in CGIscriptor below
2496 # return `/PATH/cgiparse -form`; # Shell commands
2497 # require "/PATH/cgiparse.pl"; return cgiform(); # Library
2500 # End of configuration
2502 #######################################################################
2504 # Translating input files.
2505 # Allows general and global conversions of files using Regular Expressions
2506 # Translations are applied in the order of definition.
2509 # my $TranslationPaths = 'pattern'; # Pattern matching PATH_INFO
2511 # push(@TranslationTable, ['pattern', 'replacement']);
2512 # e.g. (for Ruby Rails):
2513 # push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2514 # push(@TranslationTable, ['%>', '</SCRIPT>']);
2517 # my $currentRegExp;
2518 # foreach $currentRegExp (keys(%TranslationTable))
2520 # my $currentRegExp;
2521 # foreach $currentRegExp (@TranslationTable)
2523 # my ($pattern, $replacement) = @$currentRegExp;
2524 # $$text =~ s!$pattern!$replacement!msg;
2528 # Configuration section
2530 #######################################################################
2532 # The file paths on which to apply the translation
2533 my $TranslationPaths = ''; # NO files
2534 #$TranslationPaths = '.'; # ANY file
2535 # $TranslationPaths = '\.html'; # HTML files
2537 my @TranslationTable = ();
2539 push(@TranslationTable, ['\<\s*CGI\s+([^\>])*\>', '\<SCRIPT TYPE=\"text/ssperl\"\>$1\<\/SCRIPT>']);
2541 push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2542 push(@TranslationTable, ['%>', '</SCRIPT>']);
2544 sub performTranslation
# (\$text)
2546 my $text = shift || return;
2547 if(@TranslationTable && $TranslationPaths && $ENV{'PATH_INFO'} =~ m!$TranslationPaths!)
2550 foreach $currentRegExp (@TranslationTable)
2552 my ($pattern, $replacement) = @
$currentRegExp;
2553 $$text =~ s!$pattern!$replacement!msg;
2558 #######################################################################
2560 # Seamless access to other (Scripting) Languages
2561 # TYPE='text/ss<interpreter>'
2563 # Configuration section
2565 #######################################################################
2567 # OTHER SCRIPTING LANGUAGES AT THE SERVER SIDE (MIME => OScommand)
2568 # Yes, it realy is this simple! (unbelievable, isn't it)
2569 # NOTE: Some interpreters require some filtering to obtain "clean" output
2571 %ScriptingLanguages = (
2572 "text/testperl" => 'perl', # Perl for testing
2573 "text/sspython" => 'python', # Python
2574 "text/ssruby" => 'ruby', # Ruby
2575 "text/sstcl" => 'tcl', # TCL
2576 "text/ssawk" => 'awk -f-', # Awk
2577 "text/sslisp" => # lisp (rep, GNU)
2578 'rep | tail +4 '."| egrep -v '> |^rep. |^nil\\\$'",
2579 "text/xlispstat" => # xlispstat
2580 'xlispstat | tail +7 ' ."| egrep -v '> \\\$|^NIL'",
2581 "text/ssprolog" => # Prolog (GNU)
2582 "gprolog | tail +4 | sed 's/^| ?- //'",
2583 "text/ssm4" => 'm4', # M4 macro's
2584 "text/sh" => 'sh', # Born shell
2585 "text/bash" => 'bash', # Born again shell
2586 "text/csh" => 'csh', # C shell
2587 "text/ksh" => 'ksh', # Korn shell
2588 "text/sspraat" => # Praat (sound/speech analysis)
2589 "praat - | sed 's/Praat > //g'",
2591 "R --vanilla --slave | sed 's/^[\[0-9\]*] //'",
2592 "text/ssrebol" => # REBOL
2593 "rebol --quiet|egrep -v '^[> ]* == '|sed 's/^\\s*\[> \]* //'",
2594 "text/postgresql" => 'psql 2>/dev/null',
2596 # Not real scripting, but the use of other applications
2597 "text/ssmailto" => "awk 'NF||F{F=1;print \\\$0;}'|mailto >/dev/null", # Send mail from server
2598 "text/ssdisplay" => 'cat', # Display, (interpolation)
2599 "text/sslogfile" => # Log to file, (interpolation)
2600 "awk 'NF||L {if(!L){L=tolower(\\\$1)~/^file:\\\$/ ? \\\$2 : \\\$1;}else{print \\\$0 >> L;};}'",
2605 # To be able to access the CGI variables in your script, they
2606 # should be passed to the scripting language in a readable form
2607 # Here you can enter how they should be printed (the first %s
2608 # is replaced by the NAME of the CGI variable as it apears in the
2609 # META tag, the second by its VALUE).
2610 # For Perl this would be:
2611 # "text/testperl" => '$%s = "%s";',
2612 # which would be executed as
2613 # printf('$%s = "%s";', $CGI_NAME, $CGI_VALUE);
2615 # If the hash table value doesn't exist, nothing is done
2616 # (you have to parse the Environment variables yourself).
2617 # If it DOES exist but is empty (e.g., "text/sspraat" => '',)
2618 # Perl string interpolation of variables (i.e., $var, @array,
2619 # %hash) is performed. This means that $@%\ must be protected
2622 %ScriptingCGIvariables = (
2623 "text/testperl" => "\$\%s = '\%s';", # Perl $VAR = 'value'; (for testing)
2624 "text/sspython" => "\%s = '\%s'", # Python VAR = 'value'
2625 "text/ssruby" => '@%s = "%s"', # Ruby @VAR = 'value'
2626 "text/sstcl" => 'set %s "%s"', # TCL set VAR "value"
2627 "text/ssawk" => '%s = "%s";', # Awk VAR = 'value';
2628 "text/sslisp" => '(setq %s "%s")', # Gnu lisp (rep) (setq VAR "value")
2629 "text/xlispstat" => '(setq %s "%s")', # xlispstat (setq VAR "value")
2630 "text/ssprolog" => '', # Gnu prolog (interpolated)
2631 "text/ssm4" => "define(`\%s', `\%s')", # M4 macro's define(`VAR', `value')
2632 "text/sh" => "\%s='\%s'", # Born shell VAR='value'
2633 "text/bash" => "\%s='\%s'", # Born again shell VAR='value'
2634 "text/csh" => "\$\%s='\%s';", # C shell $VAR = 'value';
2635 "text/ksh" => "\$\%s='\%s';", # Korn shell $VAR = 'value';
2637 "text/ssrebol" => '%s: copy "%s"', # REBOL VAR: copy "value"
2638 "text/sspraat" => '', # Praat (interpolation)
2639 "text/ssr" => '%s <- "%s";', # R VAR <- "value";
2640 "text/postgresql" => '', # PostgreSQL (interpolation)
2642 # Not real scripting, but the use of other applications
2643 "text/ssmailto" => '', # MAILTO, (interpolation)
2644 "text/ssdisplay" => '', # Display, (interpolation)
2645 "text/sslogfile" => '', # Log to file, (interpolation)
2650 # If you want something added in front or at the back of each script
2651 # block as send to the interpreter add it here.
2652 # mime => "string", e.g., "text/sspython" => "python commands"
2653 %ScriptingPrefix = (
2654 "text/testperl" => "\# Prefix Code;", # Perl script testing
2655 "text/ssm4" => 'divert(0)', # M4 macro's (open STDOUT)
2659 # If you want something added at the end of each script block
2660 %ScriptingPostfix = (
2661 "text/testperl" => "\# Postfix Code;", # Perl script testing
2662 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2666 # If you need initialization code, directly after opening
2667 %ScriptingInitialization = (
2668 "text/testperl" => "\# Initialization Code;", # Perl script testing
2669 "text/ssawk" => 'BEGIN {', # Server Side awk scripts (VAR = "value")
2670 "text/sslisp" => '(prog1 nil ', # Lisp (rep)
2671 "text/xlispstat" => '(prog1 nil ', # xlispstat
2672 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2676 # If you need cleanup code before closing
2677 %ScriptingCleanup = (
2678 "text/testperl" => "\# Cleanup Code;", # Perl script testing
2679 "text/sspraat" => 'Quit',
2680 "text/ssawk" => '};', # Server Side awk scripts (VAR = "value")
2681 "text/sslisp" => '(princ "\n" standard-output)).', # Closing print to rep
2682 "text/xlispstat" => '(print ""))', # Closing print to xlispstat
2683 "text/postgresql" => '\q', # quit psql
2684 "text/ssdisplay" => "", # close cat
2689 # End of configuration for foreign scripting languages
2691 ###############################################################################
2693 # Initialization Code
2696 sub Initialize_Request
2698 ###############################################################################
2700 # ENVIRONMENT VARIABLES
2702 # Use environment variables to configure CGIscriptor on a temporary basis.
2703 # If you define any of the configurable variables as environment variables,
2704 # these are used instead of the "hard coded" values above.
2706 $SS_PUB = $ENV{'SS_PUB'} || $YOUR_HTML_FILES;
2707 $SS_SCRIPT = $ENV{'SS_SCRIPT'} || $YOUR_SCRIPTS;
2710 # Substitution strings, these are used internally to handle the
2711 # directory separator strings, e.g., '~/' -> 'SS_PUB:' (Mac)
2712 $HOME_SUB = $SS_PUB;
2713 $SCRIPT_SUB = $SS_SCRIPT;
2716 # Make sure all script are reliably loaded
2717 push(@INC, $SS_SCRIPT);
2720 # Add the directory separator to the "home" directories.
2721 # (This is required for ~/ and ./ substitution)
2722 $HOME_SUB .= '/' if $HOME_SUB;
2723 $SCRIPT_SUB .= '/' if $SCRIPT_SUB;
2725 $CGI_HOME = $ENV{'DOCUMENT_ROOT'};
2726 $ENV{'PATH_TRANSLATED'} =~ /$ENV{'PATH_INFO'}/is;
2727 $CGI_HOME = $` unless $ENV{'DOCUMENT_ROOT'}; # Get the DOCUMENT_ROOT directory
2728 $default_values{'CGI_HOME'} = $CGI_HOME;
2729 $ENV{'HOME'} = $CGI_HOME;
2730 # Set SS_PUB and SS_SCRIPT as Environment variables (make them available
2732 $ENV{'SS_PUB'} = $SS_PUB unless $ENV{'SS_PUB'};
2733 $ENV{'SS_SCRIPT'} = $SS_SCRIPT unless $ENV{'SS_SCRIPT'};
2735 $FilePattern = $ENV{'FilePattern'} || $FilePattern;
2736 $MaximumQuerySize = $ENV{'MaximumQuerySize'} || $MaximumQuerySize;
2737 $ClientLog = $ENV{'ClientLog'} || $ClientLog;
2738 $QueryLog = $ENV{'QueryLog'} || $QueryLog;
2739 $CGI_Accept = $ENV{'CGI_Accept'} || $CGI_Accept;
2740 $CGI_Reject = $ENV{'CGI_Reject'} || $CGI_Reject;
2743 $CGI_Accept =~ s@^\~/@$HOME_SUB@g if $CGI_Accept;
2744 $CGI_Reject =~ s@^\~/@$HOME_SUB@g if $CGI_Reject;
2745 $ClientLog =~ s@^\~/@$HOME_SUB@g if $ClientLog;
2746 $QueryLog =~ s@^\~/@$HOME_SUB@g if $QueryLog;
2748 $CGI_Accept =~ s@^\./@$SCRIPT_SUB@g if $CGI_Accept;
2749 $CGI_Reject =~ s@^\./@$SCRIPT_SUB@g if $CGI_Reject;
2750 $ClientLog =~ s@^\./@$SCRIPT_SUB@g if $ClientLog;
2751 $QueryLog =~ s@^\./@$SCRIPT_SUB@g if $QueryLog;
2753 @CGIscriptorResults = (); # A stack of results
2755 # end of Environment variables
2757 #############################################################################
2759 # Define and Store "standard" values
2761 # BEFORE doing ANYTHING check the size of Query String
2762 length($ENV{'QUERY_STRING'}) <= $MaximumQuerySize || dieHandler(2, "QUERY TOO LONG\n");
2764 # The Translated Query String and the Actual length of the (decoded)
2766 if($ENV{'QUERY_STRING'})
2768 # If this can contain '`"-quotes, be carefull to use it QUOTED
2769 $default_values{CGI_Decoded_QS} = YOUR_CGIQUERYDECODE();
2770 $default_values{CGI_Content_Length} = length($default_values{CGI_Decoded_QS});
2773 # Get the current Date and time and store them as default variables
2776 $LocalTime = localtime;
2778 # CGI_Year CGI_Month CGI_Day CGI_WeekDay CGI_Time
2779 # CGI_Hour CGI_Minutes CGI_Seconds
2781 $default_values{CGI_Date} = $LocalTime;
2782 ($default_values{CGI_WeekDay},
2783 $default_values{CGI_Month},
2784 $default_values{CGI_Day},
2785 $default_values{CGI_Time},
2786 $default_values{CGI_Year}) = split(' ', $LocalTime);
2787 ($default_values{CGI_Hour},
2788 $default_values{CGI_Minutes},
2789 $default_values{CGI_Seconds}) = split(':', $default_values{CGI_Time});
2792 # CGI_GMTYear CGI_GMTMonth CGI_GMTDay CGI_GMTWeekDay CGI_GMTYearDay
2793 # CGI_GMTHour CGI_GMTMinutes CGI_GMTSeconds CGI_GMTisdst
2795 ($default_values{CGI_GMTSeconds},
2796 $default_values{CGI_GMTMinutes},
2797 $default_values{CGI_GMTHour},
2798 $default_values{CGI_GMTDay},
2799 $default_values{CGI_GMTMonth},
2800 $default_values{CGI_GMTYear},
2801 $default_values{CGI_GMTWeekDay},
2802 $default_values{CGI_GMTYearDay},
2803 $default_values{CGI_GMTisdst}) = gmtime;
2807 # End of Initialize Request
2809 ###################################################################
2811 # SECURITY: ACCESS CONTROL
2813 # Check the credentials of each client (use pattern matching, domain first).
2814 # This subroutine will kill-off (die) the current process whenever access
2819 # >>>>>>>>>>Start Remove
2823 # Only accept clients which are authorized, reject all unnamed clients
2824 # if REMOTE_HOST is given.
2825 # If file patterns are given, check whether the user is authorized for
2829 # Use local variables, REMOTE_HOST becomes '-' if undefined
2830 my $REMOTE_HOST = $ENV{REMOTE_HOST} || '-';
2831 my $REMOTE_ADDR = $ENV{REMOTE_ADDR};
2832 my $PATH_INFO = $ENV{'PATH_INFO'};
2834 open(CGI_Accept, "<$CGI_Accept") || dieHandler(3, "$CGI_Accept: $!\n");
2838 next unless /\S/; # Skip empty lines
2839 next if /^\s*\#/; # Skip comments
2844 my $Accept = $'; # Get the expression
2845 $NoAccess &&= eval($Accept); # evaluate the expresion
2849 my ($Accept, @FilePatternList) = split;
2850 if($Accept eq '*' # Always match
2851 ||$REMOTE_HOST =~ /\Q$Accept\E$/is # REMOTE_HOST matches
2853 $Accept =~ /^[0-9\.]+$/
2854 && $REMOTE_ADDR =~ /^\Q$Accept\E/ # IP address matches
2858 if($FilePatternList[0])
2860 foreach $Pattern (@FilePatternList)
2862 # Check whether this patterns is accepted
2863 $NoAccess &&= ($PATH_INFO !~ m@\Q$Pattern\E@is);
2868 $NoAccess = 0; # No file patterns -> Accepted
2873 last unless $NoAccess;
2876 if($NoAccess){ dieHandler(4, "No Access
: $PATH_INFO\n");};
2882 # Reject named clients, accept all unnamed clients
2885 # Use local variables, REMOTE_HOST becomes '-' if undefined
2886 my $REMOTE_HOST = $ENV{'REMOTE_HOST'} || '-';
2887 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
2888 my $PATH_INFO = $ENV{'PATH_INFO'};
2890 open(CGI_Reject, "<$CGI_Reject") || dieHandler(5, "$CGI_Reject: $!\n");
2894 next unless /\S/; # Skip empty lines
2895 next if /^\s*\#/; # Skip comments
2900 my $Reject = $'; # Get the expression
2901 $NoAccess ||= eval($Reject); # evaluate the expresion
2905 my ($Reject, @FilePatternList) = split;
2906 if($Reject eq '*' # Always match
2907 ||$REMOTE_HOST =~ /\Q$Reject\E$/is # REMOTE_HOST matches
2908 ||($Reject =~ /^[0-9\.]+$/
2909 && $REMOTE_ADDR =~ /^\Q$Reject\E/is # IP address matches
2913 if($FilePatternList[0])
2915 foreach $Pattern (@FilePatternList)
2917 $NoAccess ||= ($PATH_INFO =~ m@\Q$Pattern\E@is);
2922 $NoAccess = 1; # No file patterns -> Rejected
2929 if($NoAccess){ dieHandler(6, "Request rejected
: $PATH_INFO\n");};
2932 ##########################################################<<<<<<<<<<End Remove
2937 # Does the filename contain any illegal characters (e.g., |, >, or <)
2938 dieHandler(7, "Illegal request
: $ENV{'PATH_INFO'}\n") if $ENV{'PATH_INFO'} =~ /[^$FileAllowedChars]/;
2939 # Does the pathname contain an illegal (blocked) "directory
"
2940 dieHandler(8, "Illegal request
: $ENV{'PATH_INFO'}\n") if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@; # Access is blocked
2941 # Does the pathname contain a direct referencer to BinaryMapFile
2942 dieHandler(9, "Illegal request
: $ENV{'PATH_INFO'}\n") if $BinaryMapFile && $ENV{'PATH_INFO'} =~ m@\Q$BinaryMapFile\E@; # Access is blocked
2944 # SECURITY: Is PATH_INFO allowed?
2945 if($FilePattern && $ENV{'PATH_INFO'} && $ENV{'PATH_INFO'} ne '-' &&
2946 ($ENV{'PATH_INFO'} !~ m@($FilePattern)$@is))
2948 # Unsupported file types can be processed by a special raw-file
2951 $ENV{'CGI_BINARY_FILE'} = $ENV{'PATH_INFO'};
2952 $ENV{'PATH_INFO'} = $BinaryMapFile;
2956 dieHandler(10, "Illegal file
\n");
2962 # End of Security Access Control
2965 ############################################################################
2967 # Get the POST part of the query and add it to the QUERY_STRING.
2970 sub Get_POST_part_of_query
2973 # If POST, Read data from stdin to QUERY_STRING
2974 if($ENV{'REQUEST_METHOD'} =~ /POST/is)
2976 # SECURITY: Check size of Query String
2977 $ENV{'CONTENT_LENGTH'} <= $MaximumQuerySize || dieHandler
(11, "Query too long: $ENV{'CONTENT_LENGTH'}\n"); # Query too long
2979 my $SystemRead = $ENV{'CONTENT_LENGTH'};
2980 $ENV{'QUERY_STRING'} .= '&' if length($ENV{'QUERY_STRING'}) > 0;
2981 while($SystemRead > 0)
2983 $QueryRead = sysread(STDIN
, $Post, $SystemRead); # Limit length
2984 $ENV{'QUERY_STRING'} .= $Post;
2985 $SystemRead -= $QueryRead;
2987 # Update decoded Query String
2988 $default_values{CGI_Decoded_QS
} = YOUR_CGIQUERYDECODE
();
2989 $default_values{CGI_Content_Length
} =
2990 length($default_values{CGI_Decoded_QS
});
2994 # End of getting POST part of query
2997 ############################################################################
2999 # Start (HTML) output and logging
3000 # (if there are irregularities, it can kill the current process)
3003 sub Initialize_output
3005 # Construct the REAL file path (except for STDIN on the command line)
3006 my $file_path = $ENV{'PATH_INFO'} ne '-' ?
$SS_PUB . $ENV{'PATH_INFO'} : '-';
3007 $file_path =~ s/\?.*$//; # Remove query
3008 # This is only necessary if your server does not catch ../ directives
3009 $file_path !~ m@\
.\
./@ || dieHandler(12, "Illegal ../ Construct
\n"); # SECURITY: Do not allow ../ constructs
3011 # Block STDIN use (-) if CGIscriptor is servicing a HTTP request
3012 if($file_path eq '-')
3014 dieHandler(13, "STDIN request
in On Line
system\n") if $BLOCK_STDIN_HTTP_REQUEST
3015 && ($ENV{'SERVER_SOFTWARE'}
3016 || $ENV{'SERVER_NAME'}
3017 || $ENV{'GATEWAY_INTERFACE'}
3018 || $ENV{'SERVER_PROTOCOL'}
3019 || $ENV{'SERVER_PORT'}
3020 || $ENV{'REMOTE_ADDR'}
3021 || $ENV{'HTTP_USER_AGENT'});
3028 open(ClientLog, ">>$ClientLog");
3029 print ClientLog "$LocalTime | ",
3030 ($ENV{REMOTE_USER} || "-"), " ",
3031 ($ENV{REMOTE_IDENT} || "-"), " ",
3032 ($ENV{REMOTE_HOST} || "-"), " ",
3033 $ENV{REMOTE_ADDR}, " ",
3034 $ENV{PATH_INFO}, " ",
3035 $ENV{'CGI_BINARY_FILE'}, " ",
3036 ($default_values{CGI_Content_Length} || "-"),
3042 open(QueryLog, ">>$QueryLog");
3043 print QueryLog "$LocalTime\n",
3044 ($ENV{REMOTE_USER} || "-"), " ",
3045 ($ENV{REMOTE_IDENT} || "-"), " ",
3046 ($ENV{REMOTE_HOST} || "-"), " ",
3047 $ENV{REMOTE_ADDR}, ": ",
3048 $ENV{PATH_INFO}, " ",
3049 $ENV{'CGI_BINARY_FILE'}, "\n";
3051 # Write Query to Log file
3052 print QueryLog $default_values{CGI_Decoded_QS}, "\n\n";
3056 # Return the file path
3060 # End of Initialize output
3063 ############################################################################
3065 # Handle login access
3067 # Access is based on a valid session ticket.
3068 # Session tickets should be dependend on user name
3069 # and IP address. The patterns of URLs for which a
3070 # session ticket is needed and the login URL are stored in
3071 # %TicketRequiredPatterns as:
3072 # 'RegEx pattern' -> 'SessionPath\tPasswordPath\tLogin URL\tExpiration'
3075 sub Log_In_Access # () -> 0 = Access Allowed, Login page if access is not allowed
3077 # No patterns, no login
3078 goto Return unless %TicketRequiredPatterns;
3080 # Get and initialize values (watch out for stuff processed by BinaryMap files)
3081 my ($SessionPath, $PasswordsPath, $Login, $valid_duration) = ("", "", "", 0);
3082 my $PATH_INFO = $ENV{'CGI_BINARY_FILE'} ? $ENV{'CGI_BINARY_FILE'} : $ENV{'PATH_INFO'};
3083 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
3084 goto Return if $REMOTE_ADDR =~ /[^0-9\.]/;
3085 # Extract TICKETs, starting with returned cookies
3086 CGIexecute::defineCGIvariable('LOGINTICKET', "");
3087 CGIexecute::defineCGIvariable('SESSIONTICKET', "");
3088 CGIexecute::defineCGIvariable('CHALLENGETICKET', "");
3089 if($ENV{'COOKIE_JAR'})
3091 my $CurrentCookieJar = $ENV{'COOKIE_JAR'};
3092 $CurrentCookieJar =~ s/\w+\=\-\s*(\;\s*|$)//isg;
3093 if($CurrentCookieJar =~ /\s*CGIscriptorLOGIN\=\s*([^\;]+)/)
3095 ${"CGIexecute
::LOGINTICKET
"} = $1;
3097 if($CurrentCookieJar =~ /\s*CGIscriptorCHALLENGE\=\s*([^\;]+)/ && $1 ne '-')
3099 ${"CGIexecute
::CHALLENGETICKET
"} = $1;
3101 if($CurrentCookieJar =~ /\s*CGIscriptorSESSION\=\s*([^\;]+)/ && $1 ne '-')
3103 ${"CGIexecute
::SESSIONTICKET
"} = $1;
3106 # Get and check the tickets. Tickets are restricted to word-characters (alphanumeric+_+.)
3107 my $LOGINTICKET = ${"CGIexecute
::LOGINTICKET
"};
3108 goto Return if ($LOGINTICKET && $LOGINTICKET =~ /[^\w\.]/isg);
3109 my $SESSIONTICKET = ${"CGIexecute
::SESSIONTICKET
"};
3110 goto Return if ($SESSIONTICKET && $SESSIONTICKET =~ /[^\w\.]/isg);
3111 my $CHALLENGETICKET = ${"CGIexecute
::CHALLENGETICKET
"};
3112 goto Return if ($CHALLENGETICKET && $CHALLENGETICKET =~ /[^\w\.]/isg);
3113 # Look for a LOGOUT message
3114 my $LOGOUT = $ENV{QUERY_STRING} =~ /(^|\&)LOGOUT([\=\&]|$)/;
3115 # Username and password
3116 CGIexecute::defineCGIvariable('CGIUSERNAME', "");
3117 my $username = lc(${"CGIexecute
::CGIUSERNAME
"});
3118 goto Return if $username =~ m!^[^\w]!isg || $username =~ m![^\w \-]!isg;
3119 my $userfile = lc($username);
3120 $userfile =~ s/[^\w]/_/isg;
3121 CGIexecute::defineCGIvariable('PASSWORD', "");
3122 my $password = ${"CGIexecute
::PASSWORD
"};
3123 CGIexecute::defineCGIvariable('NEWUSERNAME', "");
3124 my $newuser = lc(${"CGIexecute
::NEWUSERNAME
"});
3125 CGIexecute::defineCGIvariable('NEWPASSWORD', "");
3126 my $newpassword = ${"CGIexecute
::NEWPASSWORD
"};
3128 foreach my $pattern (keys(%TicketRequiredPatterns))
3130 # Check BOTH the real PATH_INFO and the CGI_BINARY_FILE variable
3131 if($ENV{'PATH_INFO'} =~ m#$pattern# || $ENV{'CGI_BINARY_FILE'} =~ m#$pattern#)
3133 # Fall through a sieve of requirements
3134 ($SessionPath, $PasswordsPath, $Login, $validtime) = split(/\t/, $TicketRequiredPatterns{$pattern});
3135 # If a LOGOUT is present, remove everything
3136 if($LOGOUT && !$LOGINTICKET)
3138 unlink "$SessionPath/$LOGINTICKET" if $LOGINTICKET && (-s "$SessionPath/$LOGINTICKET");
3140 unlink "$SessionPath/$SESSIONTICKET" if $SESSIONTICKET && (-s "$SessionPath/$SESSIONTICKET");
3141 $SESSIONTICKET = "";
3142 unlink "$SessionPath/$CHALLENGETICKET" if $CHALLENGETICKET && (-s "$SessionPath/$CHALLENGETICKET");
3143 $CHALLENGETICKET = "";
3144 unlink "$SessionPath/$REMOTE_ADDR" if (-s "$SessionPath/$REMOTE_ADDR");
3145 $CHALLENGETICKET = "";
3148 # Is there a change password request?
3149 if($newuser && $LOGINTICKET && $username)
3151 goto Login unless (-s "$SessionPath/$LOGINTICKET");
3152 goto Login unless (-s "$PasswordsPath/$userfile");
3153 my $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3154 goto Login unless $ticket_valid;
3155 $ticket_valid = check_ticket_validity("LOGIN
", "$SessionPath/$LOGINTICKET", $REMOTE_ADDR, ".", 1);
3156 goto Login unless $ticket_valid;
3158 my ($sessiontype, $currentticket) = ("", "");
3159 if($CHALLENGETICKET) {($sessiontype, $currentticket) = ("CHALLENGE
", $CHALLENGETICKET);}
3160 elsif($SESSIONTICKET) {($sessiontype, $currentticket) = ("SESSION
", $SESSIONTICKET);}
3161 elsif(-s "$SessionPath/$REMOTE_ADDR") {($sessiontype, $currentticket) = ("IPADDRESS
", $REMOTE_ADDR);
3165 goto Login unless (-s "$SessionPath/$currentticket");
3166 my $ticket_valid = check_ticket_validity($sessiontype, "$SessionPath/$currentticket", $REMOTE_ADDR, $PATH_INFO);
3167 goto Login unless $ticket_valid;
3170 my $TMPTICKET = authorize_login("$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $password, $SessionPath);
3171 goto Login unless $TMPTICKET;
3173 # Create a new user account
3174 CGIexecute::defineCGIvariable('NEWSESSION', "");
3175 my $newsession = ${"CGIexecute
::NEWSESSION
"};
3176 my $newaccount = create_newuser("$SessionPath/$LOGINTICKET", "$SessionPath/$currentticket",
3177 "$PasswordsPath/$userfile", $password, $newuser, $newpassword, $newsession);
3178 CGIexecute::defineCGIvariable('NEWACCOUNTTEXT', $newaccount);
3179 ${CGIexecute::NEWACCOUNTTEXT} = $newaccount;
3180 # NEWACCOUNTTEXT is NOT to be set by the query
3181 CGIexecute::ProtectCGIvariable('NEWACCOUNTTEXT');
3187 # Is there a change password request?
3188 elsif($newpassword && $LOGINTICKET && $username)
3190 goto Login unless (-s "$SessionPath/$LOGINTICKET");
3191 goto Login unless (-s "$PasswordsPath/$userfile");
3192 my $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3193 goto Login unless $ticket_valid;
3194 $ticket_valid = check_ticket_validity("LOGIN
", "$SessionPath/$LOGINTICKET", $REMOTE_ADDR, ".", 1);
3195 goto Login unless $ticket_valid;
3197 my ($sessiontype, $currentticket) = ("", "");
3198 if($CHALLENGETICKET) {($sessiontype, $currentticket) = ("CHALLENGE
", $CHALLENGETICKET);}
3199 elsif($SESSIONTICKET) {($sessiontype, $currentticket) = ("SESSION
", $SESSIONTICKET);}
3200 elsif(-s "$SessionPath/$REMOTE_ADDR") {($sessiontype, $currentticket) = ("IPADDRESS
", $REMOTE_ADDR);
3204 goto Login unless (-s "$SessionPath/$currentticket");
3205 my $ticket_valid = check_ticket_validity($sessiontype, "$SessionPath/$currentticket", $REMOTE_ADDR, $PATH_INFO);
3206 goto Login unless $ticket_valid;
3209 change_password("$SessionPath/$LOGINTICKET", "$SessionPath/$currentticket", "$PasswordsPath/$userfile", $password, $newpassword);
3210 # After a change of password, you have to login again for a CHALLENGE
3211 if($CHALLENGETICKET){$CHALLENGETICKET = "";};
3215 # Is there a login ticket of this name?
3218 my $tickets_removed = remove_expired_tickets($SessionPath);
3219 goto Login unless (-s "$SessionPath/$LOGINTICKET");
3220 goto Login unless (-s "$PasswordsPath/$userfile");
3221 my $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3222 goto Login unless $ticket_valid;
3223 $ticket_valid = check_ticket_validity("LOGIN
", "$SessionPath/$LOGINTICKET", $REMOTE_ADDR, ".");
3224 goto Login unless $ticket_valid;
3226 # Remove any lingering tickets
3227 unlink "$SessionPath/$SESSIONTICKET" if $SESSIONTICKET && (-s "$SessionPath/$SESSIONTICKET");
3228 $SESSIONTICKET = "";
3229 unlink "$SessionPath/$CHALLENGETICKET" if $CHALLENGETICKET && (-s "$SessionPath/$CHALLENGETICKET");
3230 $CHALLENGETICKET = "";
3234 my $TMPTICKET = authorize_login("$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $password, $SessionPath);
3237 my $authorization = read_ticket("$PasswordsPath/$userfile");
3238 goto Login unless $authorization;
3239 # Session type is read from the userfile
3240 if($authorization->{"Session
"} && $authorization->{"Session
"}->[0] eq "CHALLENGE
")
3242 # Create New Random CHALLENGETICKET
3243 $CHALLENGETICKET = $TMPTICKET;
3244 create_session_file("$SessionPath/$CHALLENGETICKET", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
3246 elsif($authorization->{"Session
"} && $authorization->{"Session
"}->[0] eq "IPADDRESS
")
3248 create_session_file("$SessionPath/$REMOTE_ADDR", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
3252 $SESSIONTICKET = $TMPTICKET;
3253 create_session_file("$SessionPath/$SESSIONTICKET", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
3254 $SETCOOKIELIST{"CGIscriptorSESSION
"} = "-";
3257 # Login ticket file has been used, remove it
3260 # Is there a session ticket of this name?
3262 if($CHALLENGETICKET)
3264 # Do not log into a CHALLENGE account if the SESSION cookie is present
3265 goto Login if $SESSIONTICKET =~ /\S/;
3266 goto Login unless (-s "$SessionPath/$CHALLENGETICKET");
3267 my $ticket_valid = check_ticket_validity("CHALLENGE
", "$SessionPath/$CHALLENGETICKET", $REMOTE_ADDR, $PATH_INFO);
3268 goto Login unless $ticket_valid;
3270 my $oldchallenge = read_ticket("$SessionPath/$CHALLENGETICKET");
3271 goto Login unless $oldchallenge;
3272 # Check whether the login still exists
3273 my $userfile = lc($oldchallenge->{"Username
"}->[0]);
3274 $userfile =~ s/[^\w]/_/isg;
3275 goto Login unless (-s "$PasswordsPath/$userfile");
3277 $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3278 goto Login unless $ticket_valid;
3280 my $NEWCHALLENGETICKET = "";
3281 $NEWCHALLENGETICKET = copy_challenge_file("$SessionPath/$CHALLENGETICKET", "$PasswordsPath/$userfile", $SessionPath);
3282 # Sessionticket is available to scripts, do NOT set the cookie
3283 $ENV{'CHALLENGETICKET'} = $NEWCHALLENGETICKET;
3287 elsif(-s "$SessionPath/$REMOTE_ADDR")
3289 my $ticket_valid = check_ticket_validity("IPADDRESS
", "$SessionPath/$REMOTE_ADDR", $REMOTE_ADDR, $PATH_INFO);
3290 goto Login unless $ticket_valid;
3291 # Check whether the login still exists
3292 my $currentsessionticket = read_ticket("$SessionPath/$REMOTE_ADDR");
3293 my $userfile = lc($currentsessionticket->{"Username
"}->[0]);
3294 $userfile =~ s/[^\w]/_/isg;
3295 goto Login unless (-s "$PasswordsPath/$userfile");
3297 $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3298 goto Login unless $ticket_valid;
3303 elsif($SESSIONTICKET)
3305 goto Login unless (-s "$SessionPath/$SESSIONTICKET");
3306 my $ticket_valid = check_ticket_validity("SESSION
", "$SessionPath/$SESSIONTICKET", $REMOTE_ADDR, $PATH_INFO);
3307 goto Login unless $ticket_valid;
3309 # Check whether the login still exists
3310 my $currentsessionticket = read_ticket("$SessionPath/$SESSIONTICKET");
3311 my $userfile = lc($currentsessionticket->{"Username
"}->[0]);
3312 $userfile =~ s/[^\w]/_/isg;
3313 goto Login unless (-s "$PasswordsPath/$userfile");
3315 $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3316 goto Login unless $ticket_valid;
3318 # Sessionticket is available to scripts
3319 $ENV{'SESSIONTICKET'} = $SESSIONTICKET;
3328 # The Masterkey should NOT be accessible by the parsed files
3329 $ENV{'CGIMasterKey'} = "" if $ENV{'CGIMasterKey'};
3333 create_login_file($PasswordsPath, $SessionPath, $REMOTE_ADDR);
3334 # Note, cookies are set only ONCE
3335 $SETCOOKIELIST{"CGIscriptorLOGIN
"} = "-";
3336 # The Masterkey should NOT be accessible by the parsed files
3337 $ENV{'CGIMasterKey'} = "" if $ENV{'CGIMasterKey'};
3338 return "$YOUR_HTML_FILES/$Login";
3341 sub authorize_login # ($loginfile, $authorizationfile, $password, $SessionPath) => SESSIONTICKET First two arguments are file paths
3343 my $loginfile = shift || "";
3344 my $authorizationfile = shift || "";
3345 my $password = shift || "";
3346 my $SessionPath = shift || "";
3348 # Get Login session ticket
3349 my $loginticket = read_ticket($loginfile);
3350 return 0 unless $loginticket;
3351 # Get User credentials for authorization
3352 my $authorization = read_ticket($authorizationfile);
3353 return 0 unless $authorization;
3356 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
3357 return "" unless $Randomsalt;
3359 my $storedpassword = $authorization->{'Password'}->[0];
3360 return "" unless $storedpassword;
3361 my $Hashedpassword = hash_string($storedpassword.$Randomsalt);
3362 return "" unless $password eq $Hashedpassword;
3364 # Extract Session Ticket
3365 my $loginsession = $loginticket->{'Session'}->[0];
3366 my $sessionticket = hash_string($storedpassword.$loginsession);
3367 chomp($sessionticket);
3368 $sessionticket = "" if -x "$SessionPath/$sessionticket";
3370 return $sessionticket;
3373 sub change_password # ($loginfile, $sessionfile, $authorizationfile, $password, $newpassword) First three arguments are file paths
3375 my $loginfile = shift || "";
3376 my $sessionfile = shift || "";
3377 my $authorizationfile = shift || "";
3378 my $password = shift || "";
3379 my $newpassword = shift || "";
3380 # Get Login session ticket
3381 my $loginticket = read_ticket($loginfile);
3382 return "" unless $loginticket;
3383 # Login ticket file has been used, remove it
3386 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
3387 return "" unless $Randomsalt;
3388 my $LoginID = $loginticket->{'Session'}->[0];
3389 return "" unless $LoginID;
3391 # Get session ticket
3392 my $sessionticket = read_ticket($sessionfile);
3393 return "" unless $sessionticket;
3395 # Get User credentials for authorization
3396 my $authorization = read_ticket($authorizationfile);
3397 return "" unless $authorization && lc($authorization->{'Username'}->[0]) eq lc($sessionticket->{'Username'}->[0]);
3399 my $storedpassword = $authorization->{'Password'}->[0];
3400 my $Hashedpassword = hash_string($storedpassword.$Randomsalt);
3401 return "" unless $password eq $Hashedpassword;
3402 my $secretkey = hash_string($storedpassword.$LoginID.$Randomsalt);
3404 # Decrypt the $newpassword
3405 my $decryptedPassword = XOR_hex_strings($secretkey, $newpassword);
3406 return "" unless $decryptedPassword;
3407 # Authorization succeeded, change password
3408 $authorization->{'Password'}->[0] = $decryptedPassword;
3410 write_ticket($authorizationfile, $authorization, $authorization->{'Salt'}->[0]);
3412 return $newpassword;
3414 # First three arguments are file paths
3415 sub create_newuser # ($loginfile, $sessionfile, $authorizationfile, $password, $newuser, $newpassword, $newsession) -> account text
3417 my $loginfile = shift || "";
3418 my $sessionfile = shift || "";
3419 my $authorizationfile = shift || "";
3420 my $password = shift || "";
3421 my $newuser = shift || "";
3422 my $newpassword = shift || "";
3423 my $newsession = shift || "";
3425 # Get Login session ticket
3426 my $loginticket = read_ticket($loginfile);
3427 return "" unless $loginticket;
3428 # Login ticket file has been used, remove it
3431 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
3432 return "" unless $Randomsalt;
3433 my $LoginID = $loginticket->{'Session'}->[0];
3434 return "" unless $LoginID;
3436 # Get session ticket
3437 my $sessionticket = read_ticket($sessionfile);
3438 return "" unless $sessionticket;
3439 # Get User credentials for authorization
3440 my $authorization = read_ticket($authorizationfile);
3441 return "" unless $authorization && lc($authorization->{'Username'}->[0]) eq lc($sessionticket->{'Username'}->[0]);
3442 my $sessionkey = $sessionticket->{'Key'}->[0];
3443 my $serversalt = $authorization->{'Salt'}->[0];
3444 return "" unless $serversalt;
3446 my $storedpassword = $authorization->{'Password'}->[0];
3447 my $Hashedpassword = hash_string($storedpassword.$Randomsalt);
3448 return "" unless $password eq $Hashedpassword;
3449 my $secretkey = hash_string($storedpassword.$LoginID.$Randomsalt);
3451 # Decrypt the $newpassword
3452 my $decryptedPassword = XOR_hex_strings($secretkey, $newpassword);
3453 return "" unless $decryptedPassword;
3455 # Authorization succeeded, create new account
3456 my $newaccount = {};
3457 $newaccount->{'Type'} = ['PASSWORD'];
3458 $newaccount->{'Username'} = [$newuser];
3459 $newaccount->{'Password'} = [$decryptedPassword];
3460 $newaccount->{'Salt'} = [$serversalt];
3461 $newaccount->{'Session'} = ['SESSION'];
3462 if($newsession eq 'IPADDRESS'){$newaccount->{'Session'} = ['IPADDRESS'];};
3463 if($newsession eq 'CHALLENGE'){$newaccount->{'Session'} = ['CHALLENGE'];};
3464 my $timesec = time();
3465 my $gmt_date = gmtime();
3466 $newaccount->{'Time'} = [$timesec];
3467 $newaccount->{'Date'} = [$gmt_date];
3470 my $NewAllowedPaths = "";
3471 my $PATH_INFO = $ENV{'CGI_BINARY_FILE'} ? $ENV{'CGI_BINARY_FILE'} : $ENV{'PATH_INFO'};
3472 my $currentRoot = "";
3473 $currentRoot = $1 if $PATH_INFO =~ m!^([\w\-\. /]+)!isg;
3474 $currentRoot =~ s![^/]+$!!isg;
3477 $currentRoot .= '/' unless $currentRoot =~ m!/$!;
3478 my $newpath = "^".${currentRoot}.'[\w\-]+\.html?';
3479 $NewAllowedPaths .= 'AllowedPaths: ^'.${currentRoot}.'[\w\-]+\.html?'."\n";
3480 $newaccount->{'AllowedPaths'} = [$newpath];
3484 # Tricky PATH_INFO, deny all
3485 $NewAllowedPaths .= "DeniedPaths
: ^/\n";
3486 $newaccount->{'DeniedPaths'} = ["DeniedPaths
: ^/\n"];
3489 # Construct home directory path
3490 my $FullHomeDirectoryPath = "";
3491 my $currentHome = lc($newuser);
3492 if($currentHome && $currentHome !~ /^\s*\#/)
3494 $currentHome =~ s![^\w]!_!isg;
3495 my $newpath = "^${currentRoot
}$currentHome/";
3496 push(@{$newaccount->{'AllowedPaths'}}, $newpath);
3497 # Create home directory
3498 $FullHomeDirectoryPath = $ENV{'HOME'}.${currentRoot}.$currentHome;
3502 CGIexecute::defineCGIvariable('ALLOWEDPATHS', "");
3503 my $allowedpaths = ${"CGIexecute
::ALLOWEDPATHS
"};
3504 if($allowedpaths && $allowedpaths !~ /^\s*\#/)
3506 $allowedpaths =~ s![^\^\w\./\;\+\*\?\[\]\$]!!isg;
3507 my @pathlist = split(/\;/, $allowedpaths);
3508 foreach my $entry (@pathlist)
3510 push(@{$newaccount->{'AllowedPaths'}}, "^".${currentRoot}.$entry);
3514 # Allowed IP addresses
3515 CGIexecute::defineCGIvariable('IPADDRESS', "");
3516 my $ipaddress = ${"CGIexecute
::IPADDRESS
"};
3517 if($ipaddress && $ipaddress !~ /^\s*\#/)
3519 $ipaddress =~ s![^\d\.\;]!!isg;
3520 my @iplist = split(/\;/, $ipaddress);
3521 foreach my $entry (@iplist)
3523 next unless $entry =~ /\d/;
3524 next if $entry =~ /^\s*\#/;
3525 $entry =~ s/\./\\./g;
3526 push(@{$newaccount->{'IPaddress'}}, $entry);
3530 # Sign the new ticket
3531 my $Signature = SignTicketWithMasterkey($newaccount, $newaccount->{'Salt'}->[0]);
3534 my $datetime = gmtime();
3535 my $passwordline = "<span id
='newaccount'>".($newaccount->{'Password'}->[0])."</span
>";
3536 my $newuserfile = "";
3537 if(grep(/^CreateUser$/, @{$authorization->{'Capabilities'}}))
3539 my $newuserfilename = lc($newuser);
3540 $newuserfilename =~ s/[^\w]/_/isg;
3541 $newuserfile = $authorizationfile;
3542 $newuserfile =~ s![^/]*$!!isg;
3543 $newuserfile .= $newuserfilename;
3548 elsif($FullHomeDirectoryPath && !(-d $FullHomeDirectoryPath || -s $FullHomeDirectoryPath))
3550 if(-d "$ENV{'HOME'}${currentRoot
}.SkeletonDir
")
3552 `cp -r '$ENV{'HOME'}${currentRoot}.SkeletonDir' '$FullHomeDirectoryPath'`;
3554 elsif(-d "$ENV{'HOME'}${currentRoot
}SkeletonDir
")
3556 `cp -r '$ENV{'HOME'}${currentRoot}SkeletonDir' '$FullHomeDirectoryPath'`;
3558 elsif(-s "$ENV{'HOME'}${currentRoot
}UserIndex
.html
")
3560 mkdir $FullHomeDirectoryPath;
3561 `cp '$ENV{'HOME'}${currentRoot}UserIndex.html' '$FullHomeDirectoryPath/index.html'`;
3563 elsif(-s "$ENV{'HOME'}${currentRoot
}index.html
")
3565 mkdir $FullHomeDirectoryPath;
3566 `cp '$ENV{'HOME'}${currentRoot}index.html' '$FullHomeDirectoryPath/index.html'`;
3572 my $newaccounttext = write_ticket($newuserfile, $newaccount, $serversalt);
3574 # Re-encrypt the new password for transmission
3575 if($newaccounttext =~ /^(Password\:\s+)(\S+)\s*$/)
3577 my $passwordvalue = $1;
3578 my $reencryptedpassword = XOR_hex_strings($secretkey, $passwordvalue);
3579 my $encryptedpasswordline = "<span id
='newaccount'>$reencryptedpassword</span
>";
3580 $newaccounttext =~ s/^(Password\:\s+)(\S+)\s*$/\1$encryptedpasswordline/gim;
3582 return $newaccounttext;
3585 # Copy a Challenge ticket file to a new name which is the hash of the new $CHALLENGETICKET and the password
3586 sub copy_challenge_file #($oldchallengefile, $authorizationfile, $sessionpath) -> $CHALLENGETICKET
3588 my $oldchallengefile = shift || "";
3589 my $authorizationfile = shift || "";
3590 my $sessionpath = shift || "";
3591 $sessionpath =~ s!/+$!!g;
3593 # Get Login session ticket
3594 my $oldchallenge = read_ticket($oldchallengefile);
3595 return "" unless $oldchallenge;
3597 # Get Authorization (user) session file
3598 my $authorization = read_ticket($authorizationfile);
3599 return "" unless $authorization;
3600 my $storedpassword = $authorization->{'Password'}->[0];
3601 return "" unless $storedpassword;
3602 my $challengekey = $oldchallenge->{'Key'}->[0];
3603 return "" unless $challengekey;
3605 # Create Random Hash Salt
3606 my $NEWCHALLENGETICKET = get_random_hex();;
3607 my $newchallengefile = hash_string($challengekey.$NEWCHALLENGETICKET);
3608 return "" unless $newchallengefile;
3610 $ENV{'CHALLENGETICKET'} = $NEWCHALLENGETICKET;
3611 CGIexecute::defineCGIvariable('CHALLENGETICKET', "");
3612 ${"CGIexecute
::CHALLENGETICKET
"} = $NEWCHALLENGETICKET;
3614 # Write Session Ticket
3615 open(OLDCHALLENGE, "<$oldchallengefile") || die "<$oldchallengefile: $!\n";
3616 my @OldChallengeLines = <OLDCHALLENGE>;
3617 close(OLDCHALLENGE);
3618 # Old file should now be removed
3619 unlink($oldchallengefile);
3621 open(SESSION, ">$sessionpath/$newchallengefile") || die "$sessionpath/$newchallengefile: $!\n";
3622 foreach $line (@OldChallengeLines)
3624 print SESSION $line;
3628 return $NEWCHALLENGETICKET;
3631 sub create_login_file #($PasswordDir, $SessionDir, $IPaddress)
3633 my $PasswordDir = shift || "";
3634 my $SessionDir = shift || "";
3635 my $IPaddress = shift || "";
3637 # Create Login Ticket
3638 my $LOGINTICKET= get_random_hex ();
3640 # Create Random Hash Salt
3641 my $RANDOMSALT= get_random_hex();
3643 # Create SALT file if it does not exist
3644 # Remove this, including test account for life system
3645 unless(-d "$SessionDir")
3647 `mkdir -p "$SessionDir"`;
3649 unless(-d "$PasswordDir")
3651 `mkdir -p "$PasswordDir"`;
3653 # Create SERVERSALT and default test account
3654 my $SERVERSALT = "";
3655 unless(-s "$PasswordDir/SALT
")
3657 $SERVERSALT= get_random_hex();
3658 open(SALTFILE, ">$PasswordDir/SALT") || die ">$PasswordDir/SALT
: $!\n";
3659 print SALTFILE "$SERVERSALT\n";
3662 # Update test account (should be removed in live system)
3663 my @alltestusers = ("test
", "testip
", "testchallenge
", "admin
");
3664 foreach my $testuser (@alltestusers)
3666 if(-s "$PasswordDir/$testuser")
3668 my $plainpassword = $testuser eq 'admin' ? "There is
no password like more password
" : "testing
";
3670 my $storedpassword = hash_string(${plainpassword}.${testuser}.${SERVERSALT});
3671 # Encrypt the new password with the MasterKey
3672 my $authorization = read_ticket("$PasswordDir/$testuser") || return "";
3673 $authorization->{'Salt'} = [$SERVERSALT];
3674 $authorization->{'Type'} = ['INACTIVE PASSWORD'] if $testuser eq 'admin';
3675 set_password($authorization, $SERVERSALT, $plainpassword);
3676 write_ticket("$PasswordDir/$testuser", $authorization, $SERVERSALT);
3682 open(SALTFILE, "<$PasswordDir/SALT") || die "$PasswordDir/SALT
: $!\n";
3683 $SERVERSALT=<SALTFILE>;
3687 # Create login session ticket
3688 my $datetime = gmtime();
3689 my $timesec = time();
3690 my $loginticket = {};
3691 $loginticket->{Type} = ['LOGIN'];
3692 $loginticket->{IPaddress} = [$IPaddress];
3693 $loginticket->{Salt} = [$SERVERSALT];
3694 $loginticket->{Session} = [$LOGINTICKET];
3695 $loginticket->{Randomsalt} = [$RANDOMSALT];
3696 $loginticket->{Expires} = ['+600s'];
3697 $loginticket->{Date} = ["$datetime UTC
"];
3698 $loginticket->{Time} = [$timesec];
3699 write_ticket("$SessionDir/$LOGINTICKET", $loginticket, $SERVERSALT);
3701 # Set global variables
3703 $ENV{'SERVERSALT'} = $SERVERSALT;
3704 CGIexecute::defineCGIvariable('SERVERSALT', "");
3705 ${"CGIexecute
::SERVERSALT
"} = $SERVERSALT;
3708 $ENV{'SESSIONTICKET'} = $SESSIONTICKET;
3709 CGIexecute::defineCGIvariable('SESSIONTICKET', "");
3710 ${"CGIexecute
::SESSIONTICKET
"} = $SESSIONTICKET;
3713 $ENV{'RANDOMSALT'} = $RANDOMSALT;
3714 CGIexecute::defineCGIvariable('RANDOMSALT', "");
3715 ${"CGIexecute
::RANDOMSALT
"} = $RANDOMSALT;
3718 $ENV{'LOGINTICKET'} = $LOGINTICKET;
3719 CGIexecute::defineCGIvariable('LOGINTICKET', "");
3720 ${"CGIexecute
::LOGINTICKET
"} = $LOGINTICKET;
3722 return $ENV{'LOGINTICKET'};
3725 sub create_session_file #($sessionfile, $loginfile, $authorizationfile, $path) -> Is $loginfile deleted? 0/1
3727 my $sessionfile = shift || "";
3728 my $loginfile = shift || "";
3729 my $authorizationfile = shift || "";
3730 my $path = shift || "";
3732 # Get Login session ticket
3733 my $loginticket = read_ticket($loginfile);
3734 return unlink($loginfile) unless $loginticket;
3736 # Get Authorization (user) session file
3737 my $authorization = read_ticket($authorizationfile);
3738 return unlink($loginfile) unless $authorization;
3740 # For a Session or a Challenge, we need a stored key
3741 my $sessionkey = "";
3743 if($authorization->{'Session'} && $authorization->{'Session'}->[0] ne 'IPADDRESS')
3745 my $storedpassword = $authorization->{'Password'}->[0];
3746 my $loginticketid = $loginticket->{'Session'}->[0];
3747 my $randomsalt = $loginticket->{'Randomsalt'}->[0];
3748 $sessionkey = hash_string($storedpassword.$loginticketid);
3749 $secretkey = hash_string($storedpassword.$loginticketid.$randomsalt);
3753 if($sessionfile =~ m!([^/]+)$!)
3758 # Convert Authorization content to Session content
3759 my $sessionContent = {};
3760 my $SessionType = $authorization->{'Session'}->[0] ? $authorization->{'Session'}->[0] : "SESSION
";
3761 $sessionContent->{Type} = [$SessionType];
3762 $sessionContent->{Username} = [lc($authorization->{'Username'}->[0])];
3763 $sessionContent->{Session} = [$sessionid];
3764 $sessionContent->{Time} = [time];
3765 # Limit communication to the login IP address, except for Tor like situations with VariableREMOTE_ADDR
3766 $sessionContent->{IPaddress} = ['.'];
3767 if($sessionContent->{Type}->[0] eq 'CHALLENGE' && grep(/^VariableREMOTE_ADDR$/, @{$authorization->{'Capabilities'}}))
3769 $sessionContent->{IPaddress} = $authorization->{'IPaddress'} if $authorization->{'IPaddress'};
3773 $sessionContent->{IPaddress} = $loginticket->{'IPaddress'};
3775 $sessionContent->{Salt} = $authorization->{'Salt'};
3776 $sessionContent->{Randomsalt} = $loginticket->{'Randomsalt'};
3777 $sessionContent->{AllowedPaths} = $authorization->{'AllowedPaths'};
3778 $sessionContent->{DeniedPaths} = $authorization->{'DeniedPaths'};
3779 $sessionContent->{Expires} = $authorization->{'MaxLifetime'};
3780 $sessionContent->{Capabilities} = $authorization->{'Capabilities'};
3781 foreach my $pattern (keys(%TicketRequiredPatterns))
3783 if($path =~ m#$pattern#)
3785 my ($SessionPath, $PasswordsPath, $Login, $validtime) = split(/\t/, $TicketRequiredPatterns{$pattern});
3786 push(@{$sessionContent->{Expires}}, $validtime);
3789 $sessionContent->{Key} = [$sessionkey] if $sessionkey;
3790 $sessionContent->{Secretkey} = [$secretkey] if $secretkey;
3791 $sessionContent->{Date} = [gmtime()." UTC
"];
3793 # Write Session Ticket
3794 write_ticket($sessionfile, $sessionContent, $authorization->{'Salt'}->[0]);
3796 # Login file should now be removed
3797 return unlink($loginfile);
3800 sub check_ticket_validity # ($type, $ticketfile, $address, $path [, $unsigned])
3802 my $type = shift || "SESSION
";
3803 my $ticketfile = shift || "";
3804 my $address = shift || "";
3805 my $path = shift || "";
3806 my $unsigned = shift || 0;
3808 # Is there a session ticket of this name?
3809 return 0 unless -s "$ticketfile";
3811 # There is a session ticket, is it linked to this IP address?
3812 my $ticket = read_ticket($ticketfile);
3815 print STDERR "Ticket expired
or empty
: $ticketfile\n";
3819 # Is this the right type of ticket
3820 unless($ticket && $ticket->{'Type'}->[0] eq $type)
3822 print STDERR "Wrong ticket type
: $ticket->{'Type'}->[0] eq $type\n";
3826 # Does the IP address match?
3827 my $IPmatches = @{$ticket->{"IPaddress
"}} ? 0 : 1;
3828 for $IPpattern (@{$ticket->{"IPaddress
"}})
3830 ++$IPmatches if $address =~ m#^$IPpattern#ig;
3832 if($address && ! $IPmatches)
3834 print STDERR "Wrong REMOTE ADDR
for $ticket->{'Username'}->[0]: $ticket->{'IPaddress'}->[0] vs
$address\n";
3838 # Is the path denied
3839 my $Pathmatches = 0;
3840 foreach $Pathpattern (@{$ticket->{"DeniedPaths
"}})
3842 ++$Pathmatches if $path =~ m#$Pathpattern#ig;
3844 return 0 if @{$ticket->{"DeniedPaths
"}} && $Pathmatches;
3846 # Is the path allowed
3848 foreach $Pathpattern (@{$ticket->{"AllowedPaths
"}})
3850 ++$Pathmatches if $path =~ m#$Pathpattern#ig;
3852 return 0 unless !@{$ticket->{"AllowedPaths
"}} || $Pathmatches;
3854 # Check signature if not told to use an unsigned ticket (dangerous)
3855 my $Signature = TicketSignature($ticket, $ticket->{'Salt'}->[0]);
3856 if((! $unsigned) && $Signature && $Signature ne $ticket->{'Signature'}->[0])
3858 print STDERR "Invalid signature
for $ticket->{'Type'}: $ticket->{'Username'}\n$ticketfile\n";
3862 # Make login values available (will also protect against resetting by query)
3863 $ENV{"LOGINUSERNAME
"} = lc($ticket->{'Username'}->[0]);
3864 $ENV{"LOGINIPADDRESS
"} = $address;
3865 $ENV{"LOGINPATH
"} = $path;
3866 $ENV{"SESSIONTYPE
"} = $type unless $type eq "PASSWORD
";
3868 # Set Capabilities, if present
3869 if($ticket->{'Username'}->[0] && @{$ticket->{'Capabilities'}})
3871 $ENV{'CAPABILITIES'} = $ticket->{'Username'}->[0];
3872 CGIexecute::defineCGIvariableList('CAPABILITIES', "");
3873 @{"CGIexecute
::CAPABILITIES
"} = @{$ticket->{'Capabilities'}};
3874 # Capabilities should not be changed anymore by CGI query!
3876 # Capabilities are NOT to be set by the query
3877 CGIexecute::ProtectCGIvariable('CAPABILITIES');
3883 sub remove_expired_tickets # ($path) -> number of tickets removed
3885 my $path = shift || "";
3886 return 0 unless $path;
3888 my $removed_tickets = 0;
3889 my @ticketlist = glob("$path/*");
3890 foreach my $ticketfile (@ticketlist)
3892 my $ticket = read_ticket($ticketfile);
3899 return $removed_tickets;
3902 sub set_password # ($ticket, $salt, $plainpassword) -> $password
3904 my $ticket = shift || "";
3905 my $salt = shift || "";
3906 my $plainpassword = shift || "";
3908 my $user = lc($ticket->{'Username'}->[0]);
3909 return "" unless $user;
3910 $salt = $ticket->{'Salt'}->[0] unless $salt;
3912 my $storedpassword = hash_string(${plainpassword}.${user}.${salt});
3913 $ticket->{'Password'} = [$storedpassword];
3914 $ticket->{'Salt'} = [$salt];
3916 return $ticket->{'Password'}->[0];
3919 sub write_ticket # ($ticketfile, $ticket, $salt [, $masterkey]) -> &%ticket
3921 my $ticketfile = shift || "";
3922 my $ticket = shift || "";
3923 my $salt = shift || "";
3924 my $masterkey = shift || $ENV{'CGIMasterKey'};
3927 EncryptTicketWithMasterKey($ticket, $salt, $masterkey);
3929 # Sign the new ticket
3930 my $signature = SignTicketWithMasterkey($ticket, $salt, $masterkey);
3932 # Create ordered list with labels
3933 my @orderlist = ('Type', 'Username', 'Password', 'IPaddress', 'AllowedPaths', 'DeniedPaths',
3934 'Expires', 'Capabilities', 'Salt', 'Session', 'Randomsalt',
3935 'Date', 'Time', 'Signature', 'Key', 'Secretkey');
3936 my @labellist = keys(%{$ticket});
3937 foreach my $label (@orderlist)
3939 @labellist = grep(!/\b$label\b/, @labellist);
3942 # Create ticket in text
3943 my $TicketText = "";
3944 foreach my $label (@orderlist, @labellist)
3946 next unless exists($ticket->{$label}) && $ticket->{$label}->[0];
3947 foreach my $value (@{$ticket->{$label}})
3949 $TicketText .= "$label: $value\n";
3954 open(TICKET, ">$ticketfile") || die "$ticketfile: $!\n";
3955 print TICKET $TicketText;
3962 # Note, read_ticket will return 0 if the ticket has expired!
3963 sub read_ticket # ($ticketfile [, $salt, $masterkey]) -> &%ticket
3965 my $ticketfile = shift || "";
3966 my $serversalt = shift || "";
3967 my $masterkey = shift || $ENV{'CGIMasterKey'};
3970 if($ticketfile && -s $ticketfile)
3972 open(TICKETFILE, "<$ticketfile") || die "$ticketfile: $!\n";
3973 my @alllines = <TICKETFILE>;
3975 foreach my $currentline (@alllines)
3977 # Skip empty lines and comments
3978 next unless $currentline =~ /\S/;
3979 next if $currentline =~ /^\s*\#/;
3981 if($currentline =~ /^\s*(\S[^\:]+)\:\s+(.*)\s*$/)
3985 $ticket->{$Label} = () unless exists($ticket->{$Label});
3986 push(@{$ticket->{$Label}}, $Value);
3990 if($masterkey && exists($ticket->{'Password'}) && $ticket->{'Password'}->[0])
3992 # Use the ServerSalt stored in the ticket, if present
3993 if(!$serversalt && exists($ticket->{Salt}) && $ticket->{Salt}->[0])
3995 $serversalt = $ticket->{Salt}->[0];
3997 # Decrypt all passwords
3998 DecryptTicketWithMasterKey($ticket, $serversalt, $masterkey) ||
3999 die "Decryption failed
: DecryptTicketWithMasterKey
($ticket, $serversalt)\n";
4002 # Check whether the ticket has expired
4003 if(exists($ticket->{Expires}))
4006 if(exists($ticket->{Time}) && $ticket->{Time}->[0] > 0)
4008 $StartTime = [(sort(@{$ticket->{Time}}))]->[0];
4012 # Get SessionTicket file stats
4013 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)
4014 = stat($ticketfile);
4015 $StartTime = $ctime;
4017 foreach my $Value (@{$ticket->{'Expires'}})
4019 # Recalculate expire date from relative time
4022 if($Value =~ /^\+(\d+)\s*d(ays)?\s*$/)
4024 $ExpireTime = 24*3600*$1;
4026 elsif($Value =~ /^\+(\d+)\s*m(inutes)?\s*$/)
4028 $ExpireTime = 60*$1;
4030 elsif($Value =~ /^\+(\d+)\s*h(ours)?\s*$/)
4032 $ExpireTime = 3600*$1;
4034 elsif($Value =~ /^\+(\d+)\s*s(econds)?\s*$/)
4038 elsif($Value =~ /^\+(\d+)\s*$/)
4043 my $absoluteTime = $Value =~ /^\+/ ? $StartTime + $ExpireTime : $Value;
4044 return 0 unless $absoluteTime > time;
4046 @{$ticket->{Expires}} = sort(@{$ticket->{Expires}});
4051 # Set up a valid ticket from a given text file
4052 # Use from command line. DO NOT USE ONLINE
4053 # Watch out for passwords that get stored in the history file
4055 # perl CGIscriptor.pl --managelogin [options] [files]
4057 # salt={file or saltvalue}
4058 # masterkey={file or plaintext}
4059 # newmasterkey={file or plaintext}
4060 # password={file or palintext}
4062 # Followed by one or more file names.
4063 # Options can be interspersed between filenames,
4064 # e.g., password='plaintext'
4065 # Note that passwords are only used once!
4067 sub setup_ticket_file # (@ARGV)
4069 # Stop when run on-line
4070 return if $ENV{'PATH_INFO'} || $ENV{'QUERY_STRING'};
4073 foreach my $input (@_)
4075 if($input =~ /^([\w]+)\=/)
4081 if($value !~ m![^\w\.\~\/\:\-]! && $value !~ /^[\-\.]/ && -s "$value" && ! -d "$value")
4083 # Warn about reading a value from file
4084 print STDERR "Read
'$name' from
: '$value'\n";
4085 open(INPUTVALUE, "<$value") || die "$value: $!\n";
4086 $value = <INPUTVALUE>;
4090 $value =~ s/(^\'([^\']*)\'$)/\1/g;
4091 $value =~ s/(^\"([^\"]*)\"$)/\1/g;
4092 $Settings{$name} = $value;
4094 elsif($input !~ m![^\w\.\~\/\:\-]!i && $input !~ /^[\-\.]/i && -s $input)
4096 # We MUST have a salt
4097 $Settings{'salt'} = $ticket->{'Salt'}->[0] unless $Settings{'salt'};
4099 # Set the new masterkey to the old masterkey if there is no new masterkey
4100 $Settings{'newmasterkey'} = $Settings{'masterkey'} unless exists($Settings{'newmasterkey'});
4103 my $ticket = read_ticket($input, $Settings{'salt'}, $Settings{'masterkey'});
4105 # Set a new password from plaintext
4106 $ticket->{'Salt'}->[0] = $Settings{'salt'} if $Settings{'salt'} && $Settings{'password'};
4107 set_password ($ticket, $Settings{'salt'}, $Settings{'password'}) if $Settings{'password'};
4108 # Write the ticket back to file
4109 write_ticket($input, $ticket, $Settings{'salt'}, $Settings{'newmasterkey'});
4111 # A password is only used once
4112 $Settings{'password'} = "";
4117 # Add a signature from $masterkey to a ticket in the label $signlabel
4118 sub SignTicketWithMasterkey # ($ticket, $serversalt [, $masterkey, $signlabel]) -> $Signature
4120 my $ticket = shift || return 0;
4121 my $serversalt = shift || "";
4122 my $masterkey = shift || $ENV{'CGIMasterKey'};
4123 my $signlabel = shift || 'Signature';
4125 my $Signature = TicketSignature($ticket, $serversalt, $masterkey);
4127 $ticket->{$signlabel} = [$Signature] if $Signature;
4132 # Determine ticket signature
4133 sub TicketSignature # ($ticket, $serversalt [, $masterkey]) -> $Signature
4135 my $ticket = shift || return 0;
4136 my $serversalt = shift || "";
4137 my $masterkey = shift || $ENV{'CGIMasterKey'};
4142 # If the ServerSalt is not stored in the ticket, the SALT file has to be found
4143 if(!$serversalt && exists($ticket->{Salt}) && $ticket->{Salt}->[0])
4145 $serversalt = $ticket->{Salt}->[0];
4150 my $username = lc($ticket->{'Username'}->[0]);
4151 my $hash1 = hash_string(${masterkey}.${serversalt});
4152 my $CryptKey = hash_string($username.${'hash1'});
4153 my $SignText = "Type
: ".$ticket->{'Type'}->[0]."\n";
4154 my @tmp = sort(@{$ticket->{'Username'}});
4155 $SignText .= "Username
: @tmp\n";
4156 @tmp = sort(@{$ticket->{'IPaddress'}});
4157 $SignText .= "IPaddress
: @tmp\n";
4158 @tmp = sort(@{$ticket->{'AllowedPaths'}});
4159 $SignText .= "AllowedPaths
: @tmp\n";
4160 @tmp = sort(@{$ticket->{'DeniedPaths'}});
4161 $SignText .= "DeniedPaths
: @tmp\n";
4162 @tmp = sort(@{$ticket->{'Session'}});
4163 $SignText .= "Session
: @tmp\n";
4164 @tmp = sort(@{$ticket->{'Time'}});
4165 $SignText .= "Time
: @tmp\n";
4166 @tmp = sort(@{$ticket->{'Expires'}});
4167 $SignText .= "Expires
: @tmp\n";
4168 @tmp = sort(@{$ticket->{'Capabilities'}});
4169 $SignText .= "Capabilities
: @tmp\n";
4170 @tmp = sort(@{$ticket->{'MaxLifetime'}});
4171 $SignText .= "MaxLifetime
: @tmp\n";
4172 $Signature = HMAC_hex($CryptKey, $SignText);
4178 # Decrypts a password list IN PLACE
4179 sub DecryptTicketWithMasterKey # ($ticket, $serversalt [, $masterkey]) -> \@password_list
4181 my $ticket = shift || return 0;
4182 my $serversalt = shift || "";
4183 my $masterkey = shift || $ENV{'CGIMasterKey'};
4185 if($masterkey && exists($ticket->{Password}) && $ticket->{Password}->[0])
4187 # If the ServerSalt is not given, read it from the the ticket
4188 if(! $serversalt && exists($ticket->{Salt}) && $ticket->{Salt}->[0])
4190 $serversalt = $ticket->{Salt}->[0];
4192 # Decrypt password(s)
4195 my $hash1 = hash_string(${masterkey}.${serversalt});
4196 my $username = lc($ticket->{'Username'}->[0]);
4197 my $CryptKey = hash_string(${'hash1'}.$username);
4198 foreach my $password (@{$ticket->{Password}})
4200 $password = XOR_hex_strings($CryptKey,$password);
4204 return $ticket->{'Password'};
4206 sub EncryptTicketWithMasterKey # ($ticket, $serversalt [, $masterkey]) -> \@password_list
4208 DecryptTicketWithMasterKey(@_);
4211 # Implement HMAC signature hash.
4212 # Blocksize is length in HEX characters, NOT bytes
4213 sub HMAC_hex # ($key, $message [, $blocksizehex]) -> $hex
4215 my $key = shift || "";
4216 my $message = shift || "";
4217 my $blocksizehex = shift || length($key);
4218 $key = hash_string($key) if length($key) > $blocksizehex;
4220 my $innerkey = XOR_hex_byte ($key, "36");
4221 my $outerkey = XOR_hex_byte ($key, "5c
");
4222 my $innerhash = hash_string($innerkey.$message);
4223 my $outerhash = hash_string($outerkey.$innerhash);
4228 # XOR input with equally long string of repeated 2 hex character (byte)
4229 # string. Input must have even number of hex characters
4230 sub XOR_hex_byte # ($hex1, $hexbyte) -> $hex
4232 my $hex1 = shift || "";
4233 my $hexbyte = shift || "";
4234 my $bytelength = length($hexbyte);
4236 $hex2 =~ s/.{$bytelength}/$hexbyte/ig;
4237 return XOR_hex_strings($hex1, $hex2);
4240 sub XOR_hex_strings # ($hex1, $hex2) -> $hex
4242 my $hex1 = shift || "";
4243 my $hex2 = shift || "";
4244 my @hex1list = split('', $hex1);
4245 my @hex2list = split('', $hex2);
4246 my @hexresultlist = ();
4247 for(my $i; $i < scalar(@hex1list); ++$i)
4249 my $d1 = hex($hex1list[$i]);
4250 my $d2 = hex($hex2list[$i]);
4251 my $dresult = ($d1 ^ $d2);
4252 $hexresultlist[$i] = sprintf("%x", $dresult);
4254 $hexresult = join('', @hexresultlist);
4258 # End of Handle login access
4261 ############################################################################
4263 # Handle foreign interpreters (i.e., scripting languages)
4265 # Insert perl code to execute scripts in foreign scripting languages.
4266 # Actually, the scripts inside the <SCRIPT></SCRIPT> blocks are piped
4267 # into an interpreter.
4268 # The code presented here is fairly confusing because it
4269 # actually writes perl code code to the output.
4271 # A table with the file handles
4272 %SCRIPTINGINPUT = ();
4274 # A function to clean up Client delivered CGI parameter values
4275 # (i.e., quote all odd characters)
4285 sub shrubCGIparameter # ($String) -> Cleaned string
4287 my $String = shift || "";
4289 # Change all quotes [`'"] into HTML character entities
4290 my ($Char, $Transcript) = ('&', $SHRUBcharacterTR{'&'});
4293 $String =~ s/\Q$Char\E/$Transcript/isg if $Transcript;
4295 while( ($Char, $Transcript) = each %SHRUBcharacterTR)
4297 next if $Char eq '&';
4298 $String =~ s/\Q$Char\E/$Transcript/isg;
4302 $String =~ s/[\n]/\\n/g;
4303 # Replace control characters with their backslashed octal ordinal numbers
4304 $String =~ s/([^\S \t])/(sprintf("\\0%o", ord($1)))/eisg; #
4305 $String =~ s/([\x00-\x08\x0A-\x1F])/(sprintf("\\0%o", ord($1)))/eisg; #
4311 # The initial open statements: Open a pipe to the foreign script interpreter
4312 sub OpenForeignScript # ($ContentType) -> $DirectivePrefix
4314 my $ContentType = lc(shift) || return "";
4315 my $NewDirective = "";
4317 return $NewDirective if($SCRIPTINGINPUT{$ContentType});
4319 # Construct a unique file handle name
4320 $SCRIPTINGFILEHANDLE = uc($ContentType);
4321 $SCRIPTINGFILEHANDLE =~ s/\W/\_/isg;
4322 $SCRIPTINGINPUT{$ContentType} = $SCRIPTINGFILEHANDLE
4323 unless $SCRIPTINGINPUT{$ContentType};
4325 # Create the relevant script: Open the pipe to the interpreter
4326 $NewDirective .= <<"BLOCKCGISCRIPTOROPEN";
4327 # Open interpreter for '$ContentType'
4328 # Open pipe to interpreter (if it isn't
open already
)
4329 open($SCRIPTINGINPUT{$ContentType}, "|$ScriptingLanguages{$ContentType}") || main
::dieHandler
(14, "$ContentType: \$!\\n");
4330 BLOCKCGISCRIPTOROPEN
4332 # Insert Initialization code and CGI variables
4333 $NewDirective .= InitializeForeignScript
($ContentType);
4336 return $NewDirective;
4340 # The final closing code to stop the interpreter
4341 sub CloseForeignScript
# ($ContentType) -> $DirectivePrefix
4343 my $ContentType = lc(shift) || return "";
4344 my $NewDirective = "";
4346 # Do nothing unless the pipe realy IS open
4347 return "" unless $SCRIPTINGINPUT{$ContentType};
4350 $NewDirective .= "\# Close interpreter for '$ContentType'\n";
4353 # Write the Postfix code
4354 $NewDirective .= CleanupForeignScript
($ContentType);
4356 # Create the relevant script: Close the pipe to the interpreter
4357 $NewDirective .= <<"BLOCKCGISCRIPTORCLOSE";
4358 close($SCRIPTINGINPUT{$ContentType}) || main::dieHandler(15, \"$ContentType: \$!\\n\");
4359 select(STDOUT); \$|=1;
4361 BLOCKCGISCRIPTORCLOSE
4363 # Remove the file handler of the foreign script
4364 delete($SCRIPTINGINPUT{$ContentType});
4366 return $NewDirective;
4370 # The initialization code for the foreign script interpreter
4371 sub InitializeForeignScript
# ($ContentType) -> $DirectivePrefix
4373 my $ContentType = lc(shift) || return "";
4374 my $NewDirective = "";
4376 # Add initialization code
4377 if($ScriptingInitialization{$ContentType})
4379 $NewDirective .= <<"BLOCKCGISCRIPTORINIT";
4380 # Initialization Code for '$ContentType'
4381 # Select relevant output filehandle
4382 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4384 # The Initialization code (if any)
4385 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}INITIALIZATIONCODE';
4386 $ScriptingInitialization{$ContentType}
4387 ${ContentType}INITIALIZATIONCODE
4389 BLOCKCGISCRIPTORINIT
4392 # Add all CGI variables defined
4393 if(exists($ScriptingCGIvariables{$ContentType}))
4395 # Start writing variable definitions to the Interpreter
4396 if($ScriptingCGIvariables{$ContentType})
4398 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEF";
4399 # CGI variables (from the %default_values table)
4400 print $SCRIPTINGINPUT{$ContentType} << '${ContentType}CGIVARIABLES';
4401 BLOCKCGISCRIPTORVARDEF
4405 foreach $N (keys(%default_values))
4407 # Determine whether the parameter has been defined
4408 # (the eval is a workaround to get at the variable value)
4409 next unless eval("defined(\$CGIexecute::$N)");
4411 # Get the value from the EXECUTION environment
4412 $V = eval("\$CGIexecute::$N");
4413 # protect control characters (i.e., convert them to \0.. form)
4414 $V = shrubCGIparameter
($V);
4416 # Protect interpolated variables
4417 eval("\$CGIexecute::$N = '$V';") unless $ScriptingCGIvariables{$ContentType};
4419 # Print the actual declaration for this scripting language
4420 if($ScriptingCGIvariables{$ContentType})
4422 $NewDirective .= sprintf($ScriptingCGIvariables{$ContentType}, $N, $V);
4423 $NewDirective .= "\n";
4427 # Stop writing variable definitions to the Interpreter
4428 if($ScriptingCGIvariables{$ContentType})
4430 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEFEND";
4431 ${ContentType}CGIVARIABLES
4432 BLOCKCGISCRIPTORVARDEFEND
4437 $NewDirective .= << "BLOCKCGISCRIPTOREND";
4439 # Select STDOUT filehandle
4440 select(STDOUT
); \
$|=1;
4444 return $NewDirective;
4448 # The cleanup code for the foreign script interpreter
4449 sub CleanupForeignScript
# ($ContentType) -> $DirectivePrefix
4451 my $ContentType = lc(shift) || return "";
4452 my $NewDirective = "";
4454 # Return if not needed
4455 return $NewDirective unless $ScriptingCleanup{$ContentType};
4457 # Create the relevant script: Open the pipe to the interpreter
4458 $NewDirective .= <<"BLOCKCGISCRIPTORSTOP";
4459 # Cleanup Code for '$ContentType'
4460 # Select relevant output filehandle
4461 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4462 # Print Cleanup code to foreign script
4463 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}SCRIPTSTOP';
4464 $ScriptingCleanup{$ContentType}
4465 ${ContentType}SCRIPTSTOP
4467 # Select STDOUT filehandle
4468 select(STDOUT); \$|=1;
4469 BLOCKCGISCRIPTORSTOP
4471 return $NewDirective;
4475 # The prefix code for each <script></script> block
4476 sub PrefixForeignScript
# ($ContentType) -> $DirectivePrefix
4478 my $ContentType = lc(shift) || return "";
4479 my $NewDirective = "";
4481 # Return if not needed
4482 return $NewDirective unless $ScriptingPrefix{$ContentType};
4485 # If the CGIvariables parameter is defined, but empty, interpolate
4486 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
4487 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
4488 !$ScriptingCGIvariables{$ContentType};
4490 # Add initialization code
4491 $NewDirective .= <<"BLOCKCGISCRIPTORPREFIX";
4492 # Prefix Code for '$ContentType'
4493 # Select relevant output filehandle
4494 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4496 # The block Prefix code (if any)
4497 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}PREFIXCODE$Quote;
4498 $ScriptingPrefix{$ContentType}
4499 ${ContentType}PREFIXCODE
4500 # Select STDOUT filehandle
4501 select(STDOUT); \$|=1;
4502 BLOCKCGISCRIPTORPREFIX
4504 return $NewDirective;
4508 # The postfix code for each <script></script> block
4509 sub PostfixForeignScript
# ($ContentType) -> $DirectivePrefix
4511 my $ContentType = lc(shift) || return "";
4512 my $NewDirective = "";
4514 # Return if not needed
4515 return $NewDirective unless $ScriptingPostfix{$ContentType};
4518 # If the CGIvariables parameter is defined, but empty, interpolate
4519 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
4520 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
4521 !$ScriptingCGIvariables{$ContentType};
4523 # Create the relevant script: Open the pipe to the interpreter
4524 $NewDirective .= <<"BLOCKCGISCRIPTORPOSTFIX";
4525 # Postfix Code for '$ContentType'
4526 # Select filehandle to interpreter
4527 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4528 # Print postfix code to foreign script
4529 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SCRIPTPOSTFIX$Quote;
4530 $ScriptingPostfix{$ContentType}
4531 ${ContentType}SCRIPTPOSTFIX
4532 # Select STDOUT filehandle
4533 select(STDOUT); \$|=1;
4534 BLOCKCGISCRIPTORPOSTFIX
4536 return $NewDirective;
4539 sub InsertForeignScript
# ($ContentType, $directive, @SRCfile) -> $NewDirective
4541 my $ContentType = lc(shift) || return "";
4542 my $directive = shift || return "";
4544 my $NewDirective = "";
4547 # If the CGIvariables parameter is defined, but empty, interpolate
4548 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
4549 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
4550 !$ScriptingCGIvariables{$ContentType};
4552 # Create the relevant script
4553 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
4554 # Insert Code for '$ContentType'
4555 # Select filehandle to interpreter
4556 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4557 BLOCKCGISCRIPTORINSERT
4559 # Use SRC feature files
4561 while($ThisSRCfile = shift(@_))
4564 if($ThisSRCfile =~ /^\s*\{\s*/)
4567 $Block = $` if $Block =~ /\s*\}\s*$/;
4568 $NewDirective .= <<"BLOCKCGISCRIPTORSRCBLOCK";
4569 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SRCBLOCKCODE$Quote;
4571 ${ContentType}SRCBLOCKCODE
4572 BLOCKCGISCRIPTORSRCBLOCK
4578 $NewDirective .= <<"BLOCKCGISCRIPTORSRCFILES";
4580 open(SCRIPTINGSOURCE, "<$ThisSRCfile") || main::dieHandler(16, "$ThisSRCfILE: \$!");
4581 while(<SCRIPTINGSOURCE>)
4583 print $SCRIPTINGINPUT{$ContentType} \$_;
4585 close(SCRIPTINGSOURCE);
4587 BLOCKCGISCRIPTORSRCFILES
4594 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
4595 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}DIRECTIVECODE$Quote;
4597 ${ContentType}DIRECTIVECODE
4598 BLOCKCGISCRIPTORINSERT
4602 $NewDirective .= <<"BLOCKCGISCRIPTORSELECT";
4603 # Select STDOUT filehandle
4604 select(STDOUT); \$|=1;
4605 BLOCKCGISCRIPTORSELECT
4608 return $NewDirective;
4611 sub CloseAllForeignScripts
# Call CloseForeignScript on all open scripts
4614 foreach $ContentType (keys(%SCRIPTINGINPUT))
4616 my $directive = CloseForeignScript
($ContentType);
4617 print STDERR
"\nDirective $CGI_Date: ", $directive;
4618 CGIexecute
->evaluate($directive);
4623 # End of handling foreign (external) scripting languages.
4625 ############################################################################
4627 # A subroutine to handle "nested" quotes, it cuts off the leading
4628 # item or quoted substring
4630 # ' A_word and more words' -> @('A_word', ' and more words')
4631 # '"quoted string" The rest' -> @('quoted string', ' The rest')
4632 # (this is needed for parsing the <TAGS> and their attributes)
4633 my $SupportedQuotes = "\'\"\`\(\{\[";
4634 my %QuotePairs = ('('=>')','['=>']','{'=>'}'); # Brackets
4635 sub ExtractQuotedItem
# ($String) -> @($QuotedString, $RestOfString)
4638 my $String = shift || return @Result;
4640 if($String =~ /^\s*([\w\/\
-\
.]+)/is
)
4642 push(@Result, $1, $');
4644 elsif($String =~ /^\s*(\\?)([\Q$SupportedQuotes\E])/is)
4646 my $BackSlash = $1 || "";
4648 my $CloseQuote = $OpenQuote;
4649 $CloseQuote = $QuotePairs{$OpenQuote} if $QuotePairs{$OpenQuote};
4653 $String =~ /^\s*\\\Q$OpenQuote\E/i;
4655 $Onset =~ /\\\Q$CloseQuote\E/i;
4658 push(@Result, $Item, $Rest);
4663 $String =~ /^\s*\Q$OpenQuote\E([^\Q$CloseQuote\E]*)\Q$CloseQuote\E/i;
4664 push(@Result, $1, $');
4669 push(@Result, "", $String);
4674 # Now, start with the real work
4676 # Control the output of the Content-type: text/html\n\n message
4677 my $SupressContentType = 0;
4680 sub ProcessFile
# ($file_path)
4682 my $file_path = shift || return 0;
4685 # Generate a unique file handle (for recursions)
4687 my $FileHandle = "file";
4689 while(!eof($FileHandle.$n)) {++$n;};
4693 # Use the default Content-type if this is NOT a raw file
4694 unless(($RawFilePattern && $ENV{'PATH_INFO'} =~ m@
($RawFilePattern)$@i)
4695 || $SupressContentType)
4697 $ENV{'PATH_INFO'} =~ m@
($FilePattern)$@i;
4698 my $ContentType = $ContentTypeTable{$1};
4699 print "Content-type: $ContentType\n";
4700 if(%SETCOOKIELIST && keys(%SETCOOKIELIST))
4702 foreach my $name (keys(%SETCOOKIELIST))
4704 my $value = $SETCOOKIELIST{$name};
4705 print "Set-Cookie: $name=$value\n";
4707 # Cookies are set only ONCE
4708 %SETCOOKIELIST = ();
4711 $SupressContentType = 1; # Content type has been printed
4715 # Get access to the actual data. This can be from RAM (by way of an
4716 # environment variable) or by opening a file.
4718 # Handle the use of RAM images (file-data is stored in the
4719 # $CGI_FILE_CONTENTS environment variable)
4720 # Note that this environment variable will be cleared, i.e., it is strictly for
4722 if($ENV{$CGI_FILE_CONTENTS})
4724 # File has been read already
4725 $_ = $ENV{$CGI_FILE_CONTENTS};
4726 # Sorry, you have to do the reading yourself (dynamic document creation?)
4727 # NOTE: you must read the whole document at once
4730 $_ = eval("\@_=('$file_path'); do{$ENV{$CGI_DATA_ACCESS_CODE}}");
4732 else # Clear environment variable
4734 $ENV{$CGI_FILE_CONTENTS} = '-';
4737 # Open Only PLAIN TEXT files (or STDIN) and NO executable files (i.e., scripts).
4738 # THIS IS A SECURITY FEATURE!
4739 elsif($file_path eq '-' || (-e
"$file_path" && -r _
&& -T _
&& -f _
&& ! (-x _
|| -X _
) ))
4741 open($FileHandle, $file_path) || dieHandler
(17, "<h2>File not found</h2>\n");
4742 push(@OpenFiles, $file_path);
4743 $_ = <$FileHandle>; # Read first line
4747 print "<h2>File not found</h2>\n";
4748 dieHandler
(18, "$file_path\n");
4751 $| = 1; # Flush output buffers
4753 # Initialize variables
4754 my $METAarguments = ""; # The CGI arguments from the latest META tag
4755 my @METAvalues = (); # The ''-quoted CGI values from the latest META tag
4756 my $ClosedTag = 0; # <TAG> </TAG> versus <TAG/>
4759 # Send document to output
4760 # Process the requested document.
4761 # Do a loop BEFORE reading input again (this catches the RAM/Database
4762 # type of documents).
4766 # Handle translations if needed
4768 performTranslation
(\
$_) if $TranslationPaths;
4770 # Catch <SCRIPT LANGUAGE="PERL" TYPE="text/ssperl" > directives in $_
4771 # There can be more than 1 <SCRIPT> or META tags on a line
4772 while(/\<\s*(SCRIPT|META|DIV|INS)\s/is)
4775 # Store rest of line
4779 my $TagType = uc($1);
4780 # The before part can be send to the output
4783 # Read complete Tag from after and/or file
4784 until($After =~ /([^\\])\>/)
4786 $After .= <$FileHandle>;
4787 performTranslation(\$After) if $TranslationPaths;
4790 if($After =~ /([^\\])\>/)
4792 $ScriptTag .= $`.$&; # Keep the Script Tag intact
4797 dieHandler(19, "Closing > not found\n");
4800 # The tag could be closed by />, we handle this in the XML way
4801 # and don't process any content
(we ignore whitespace
)
4802 $ClosedTag = ($ScriptTag =~ m@
[^\\]/\s
*\
>\s
*$@
) ?
1 : 0;
4806 my $TypeName = ($TagType =~ /META/is) ?
"CONTENT" : "TYPE";
4807 $TypeName = "CLASS" if $TagType eq 'DIV' || $TagType eq 'INS';
4809 # Parse <SCRIPT> or <META> directive
4810 # If NOT (TYPE|CONTENT)="text/ssperl" (i.e., $ServerScriptContentType),
4811 # send the line to the output and go to the next loop
4812 my $CurrentContentType = "";
4813 if($ScriptTag =~ /(^|\s)$TypeName\s*=\s*/is)
4815 my ($Type) = ExtractQuotedItem
($');
4816 $Type =~ /^\s*([\w\/\-]+)\s*[\,\;]?/;
4817 $CurrentContentType = lc($1); # Note: mime-types are "case-less"
4818 # CSS classes are aliases of $ServerScriptContentType
4819 if($TypeName eq "CLASS" && $CurrentContentType eq $ServerScriptContentClass)
4821 $CurrentContentType = $ServerScriptContentType;
4826 # Not a known server-side content type, print and continue
4827 unless(($CurrentContentType =~
4828 /$ServerScriptContentType|$ShellScriptContentType/is) ||
4829 $ScriptingLanguages{$CurrentContentType})
4837 # A known server-side content type, evaluate
4839 # First, handle \> and \<
4840 $ScriptTag =~ s/\\\>/\>/isg;
4841 $ScriptTag =~ s/\\\</\</isg;
4843 # Extract the CGI, SRC, ID, IF and UNLESS attributes
4844 my %ScriptTagAttributes = ();
4845 while($ScriptTag =~ /(^|\s)(CGI|IF|UNLESS|SRC|ID)\s*=\s*/is)
4850 ($Value, $ScriptTag) = ExtractQuotedItem
($Rest);
4851 $ScriptTagAttributes{uc($Attribute)} = $Value;
4855 # The attribute used to define the CGI variables
4856 # Extract CGI-variables from
4857 # <META CONTENT="text/ssperl; CGI='' SRC=''">
4858 # <SCRIPT TYPE='text/ssperl' CGI='' SRC=''>
4859 # <DIV CLASS='ssperl' CGI='' SRC='' ID=""> tags
4860 # <INS CLASS='ssperl' CGI='' SRC='' ID=""> tags
4861 if($ScriptTagAttributes{'CGI'})
4863 @ARGV = (); # Reset ARGV
4865 $METAarguments = ""; # Reset the META CGI arguments
4867 my $Meta_CGI = $ScriptTagAttributes{'CGI'};
4869 # Process default values of variables ($<name> = 'default value')
4870 # Allowed quotes are '', "", ``, (), [], and {}
4871 while($Meta_CGI =~ /(^\s*|[^\\])([\$\@\%]?)([\w\-]+)\s*/is)
4873 my $varType = $2 || '$'; # Variable or list
4874 my $name = $3; # The Name
4878 if($Meta_CGI =~ /^\s*\=\s*/is)
4880 # Locate (any) default value
4881 ($default, $Meta_CGI) = ExtractQuotedItem($'); # Cut the parameter from the CGI
4883 $RemainingTag = $Meta_CGI;
4886 # Define CGI (or ENV) variable, initalize it from the
4887 # Query string or the default value
4889 # Also construct the @ARGV and @_ arrays. This allows other (SRC=) Perl
4890 # scripts to access the CGI arguments defined in the META tag
4891 # (Not for CGI inside <SCRIPT> tags)
4894 CGIexecute
::defineCGIvariable
($name, $default)
4895 || dieHandler
(20, "INVALID CGI name/value pair ($name, $default)\n");
4896 push(@METAvalues, "'".${"CGIexecute::$name"}."'");
4897 # Add value to the @ARGV list
4898 push(@ARGV, ${"CGIexecute::$name"});
4901 elsif($varType eq '@')
4903 CGIexecute
::defineCGIvariableList
($name, $default)
4904 || dieHandler
(21, "INVALID CGI name/value list pair ($name, $default)\n");
4905 push(@METAvalues, "'".join("'", @
{"CGIexecute::$name"})."'");
4906 # Add value to the @ARGV list
4907 push(@ARGV, @
{"CGIexecute::$name"});
4908 $ARGC = scalar(@CGIexecute::ARGV
);
4910 elsif($varType eq '%')
4912 CGIexecute
::defineCGIvariableHash
($name, $default)
4913 || dieHandler
(22, "INVALID CGI name/value hash pair ($name, $default)\n");
4914 my @PairList = map {"$_ => ".${"CGIexecute::$name"}{$_}} keys(%{"CGIexecute::$name"});
4915 push(@METAvalues, "'".join("'", @PairList)."'");
4916 # Add value to the @ARGV list
4917 push(@ARGV, %{"CGIexecute::$name"});
4918 $ARGC = scalar(@CGIexecute::ARGV
);
4921 # Store the values for internal and later use
4922 $METAarguments .= "$varType".$name.","; # A string of CGI variable names
4924 push(@METAvalues, "\'".eval("\"$varType\{CGIexecute::$name\}\"")."\'"); # ALWAYS add '-quotes around values
4929 # The IF (conditional execution) Attribute
4930 # Evaluate the condition and stop unless it evaluates to true
4931 if($ScriptTagAttributes{'IF'})
4933 my $IFcondition = $ScriptTagAttributes{'IF'};
4935 # Convert SCRIPT calls, ./<script>
4936 $IFcondition =~ s@
([\W
]|^)\
./([\S
])@
$1$SCRIPT_SUB$2@g;
4938 # Convert FILE calls, ~/<file>
4939 $IFcondition =~ s@
([\W
])\
~/([\S
])@
$1$HOME_SUB$2@g;
4941 # Block execution if necessary
4942 unless(CGIexecute
->evaluate($IFcondition))
4944 %ScriptTagAttributes = ();
4945 $CurrentContentType = "";
4949 # The UNLESS (conditional execution) Attribute
4950 # Evaluate the condition and stop if it evaluates to true
4951 if($ScriptTagAttributes{'UNLESS'})
4953 my $UNLESScondition = $ScriptTagAttributes{'UNLESS'};
4955 # Convert SCRIPT calls, ./<script>
4956 $UNLESScondition =~ s@
([\W
]|^)\
./([\S
])@
$1$SCRIPT_SUB$2@g;
4958 # Convert FILE calls, ~/<file>
4959 $UNLESScondition =~ s@
([\W
])\
~/([\S
])@
$1$HOME_SUB$2@g;
4961 # Block execution if necessary
4962 if(CGIexecute
->evaluate($UNLESScondition))
4964 %ScriptTagAttributes = ();
4965 $CurrentContentType = "";
4969 # The SRC (Source File) Attribute
4970 # Extract any source script files and add them in
4971 # front of the directive
4972 # The SRC list should be emptied
4976 my $PrefixDirective = "";
4977 my $PostfixDirective = "";
4978 # There is a SRC attribute
4979 if($ScriptTagAttributes{'SRC'})
4981 $SRCtag = $ScriptTagAttributes{'SRC'};
4982 # Remove "file://" prefixes
4983 $SRCtag =~ s@
([^\w\
/\\]|^)file\://([^\s\/\@\
=])@
$1$2@gis;
4984 # Expand script filenames "./Script"
4985 $SRCtag =~ s@
([^\w\
/\\]|^)\./([^\s\
/\@\=])@$1$SCRIPT_SUB/$2@gis;
4986 # Expand script filenames "~/Script"
4987 $SRCtag =~ s@
([^\w\
/\\]|^)\~/([^\s\
/\@\=])@$1$HOME_SUB/$2@gis;
4991 while($SRCtag =~ /\S/is)
4993 my $SRCdirective = "";
4995 # Pseudo file, just a switch to go from PREFIXING to POSTFIXING
4997 if($SRCtag =~ /^[\s\;\,]*(POSTFIX|PREFIX)([^$FileAllowedChars]|$)/is)
4999 my $InsertionPlace = $1;
5002 $Prefix = $InsertionPlace =~ /POSTFIX/i ? 0 : 1;
5006 # {}-blocks are just evaluated by "do"
5007 elsif($SRCtag =~ /^[\s\;\,]*\{/is)
5010 if($SRCblock =~ /\}[\s\;\,]*([^\}]*)$/is)
5014 # SAFEqx shell script blocks
5015 if($CurrentContentType =~ /$ShellScriptContentType/is)
5017 # Handle ''-quotes inside the script
5018 $SRCblock =~ s/[\']/\\$&/gis;
5020 $SRCblock = "print do { SAFEqx(\'".$SRCblock."\'); };'';";
5021 $SRCdirective .= $SRCblock."\n";
5024 elsif($CurrentContentType =~ /$ServerScriptContentType/is)
5026 $SRCblock = "print do { $SRCblock };'';";
5027 $SRCdirective .= $SRCblock."\n";
5029 else # The interpreter should handle this
5031 push(@SRClist, "{ $SRCblock }");
5036 { dieHandler(23, "Closing \} missing\n");};
5038 # Files are processed as Text or Executable files
5039 elsif($SRCtag =~ /[\s\;\,]*([$FileAllowedChars]+)[\;\,\s]*/is)
5044 # We are handling one of the external interpreters
5045 if($ScriptingLanguages{$CurrentContentType})
5047 push(@SRClist, $SrcFile);
5049 # We are at the start of a DIV tag, just load all SRC files and/or URL's
5050 elsif($TagType eq 'DIV' || $TagType eq 'INS') # All files are prepended in DIV's
5052 # $SrcFile is a URL pointing to an HTTP or FTP server
5053 if($SrcFile =~ m!^([a-z]+)\://!)
5055 my $URLoutput = CGIscriptor::read_url($SrcFile);
5056 $SRCdirective .= $URLoutput;
5058 # SRC file is an existing file
5059 elsif(-e "$SrcFile")
5061 open(DIVSOURCE, "<$SrcFile") || dieHandler(24, "<$SrcFile: $!\n");
5063 while(sysread(DIVSOURCE, $Content, 1024) > 0)
5065 $SRCdirective .= $Content;
5070 # Executable files are executed as
5071 # `$SrcFile 'ARGV[0]' 'ARGV[1]'`
5072 elsif(-x "$SrcFile")
5074 $SRCdirective .= "print \`$SrcFile @METAvalues\
`;'';\n";
5076 # Handle 'standard' files, using ProcessFile
5077 elsif((-T "$SrcFile" || $ENV{$CGI_FILE_CONTENTS})
5078 && $SrcFile =~ m@($FilePattern)$@) # A recursion
5081 # Do not process still open files because it can lead
5082 # to endless recursions
5083 if(grep(/^$SrcFile$/, @OpenFiles))
5084 { dieHandler(25, "$SrcFile allready opened (endless recursion)\n")};
5085 # Prepare meta arguments
5086 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
5088 $SRCdirective .= "main::ProcessFile(\'$SrcFile\');'';\n";
5090 elsif($SrcFile =~ m!^([a-z]+)\://!) # URL's are loaded and printed
5092 $SRCdirective .= GET_URL($SrcFile);
5094 elsif(-T "$SrcFile") # Textfiles are "do"-ed (Perl execution)
5096 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
5097 $SRCdirective .= "do \'$SrcFile\';'';\n";
5099 else # This one could not be resolved (should be handled by BinaryMapFile)
5101 $SRCdirective .= 'print "'.$SrcFile.' cannot be used"'."\n";
5109 $PrefixDirective .= $SRCdirective;
5113 $PostfixDirective .= $SRCdirective;
5116 # The prefix should be handled immediately
5117 $directive .= $PrefixDirective;
5118 $PrefixDirective = "";
5122 # Handle the content of the <SCRIPT></SCRIPT> tags
5123 # Do not process the content of <SCRIPT/>
5124 if($TagType =~ /SCRIPT/is && !$ClosedTag) # The <SCRIPT> TAG
5126 my $EndScriptTag = "";
5128 # Execute SHELL scripts with SAFEqx()
5129 if($CurrentContentType =~ /$ShellScriptContentType/is)
5131 $directive .= "SAFEqx(\'";
5135 while($After !~ /\<\s*\/SCRIPT[^\>]*\>/is && !eof($FileHandle))
5137 $After .= <$FileHandle>;
5138 performTranslation(\$After) if $TranslationPaths;
5141 if($After =~ /\<\s*\/SCRIPT[^\>]*\>/is)
5149 dieHandler(26, "Missing </SCRIPT> end tag in $ENV{'PATH_INFO
'}\n");
5152 # Process only when content should be executed
5153 if($CurrentContentType)
5156 # Remove all comments from Perl scripts
5157 # (NOT from OS shell scripts)
5158 $directive =~ s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/$1/g
5159 if $CurrentContentType =~ /$ServerScriptContentType/i;
5161 # Convert SCRIPT calls, ./<script>
5162 $directive =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
5164 # Convert FILE calls, ~/<file>
5165 $directive =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
5167 # Execute SHELL scripts with SAFEqx(), closing bracket
5168 if($CurrentContentType =~ /$ShellScriptContentType/i)
5170 # Handle ''-quotes inside the script
5171 $directive =~ /SAFEqx\(\'/;
5173 my $Executable = $';
5174 $Executable =~ s/[\']/\\$&/gs;
5176 $directive .= $Executable."\');"; # Closing bracket
5184 # Handle the content of the <DIV></DIV> tags
5185 # Do not process the content of <DIV/>
5186 elsif(($TagType eq 'DIV' || $TagType eq 'INS') && !$ClosedTag) # The <DIV> TAGs
5188 my $EndScriptTag = "";
5191 while($After !~ /\<\s*\/$TagType[^\
>]*\
>/is
&& !eof($FileHandle))
5193 $After .= <$FileHandle>;
5194 performTranslation
(\
$After) if $TranslationPaths;
5197 if($After =~ /\<\s*\/$TagType[^\
>]*\
>/is
)
5205 dieHandler(27, "Missing </$TagType> end tag in $ENV{'PATH_INFO'}\n");
5208 # Add the Postfixed directives (but only when it contains something printable)
5209 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
5210 $PostfixDirective = "";
5213 # Process only when content should be handled
5214 if($CurrentContentType)
5217 # Get the name (ID), and clean it (i.e., remove anything that is NOT part of
5218 # a valid Perl name). Names should not contain $, but we can handle it.
5219 my $name = $ScriptTagAttributes{'ID'};
5220 $name =~ /^\s*[\$\@\%]?([\w\-]+)/;
5223 # Assign DIV contents to $NAME value OUTSIDE the CGI values!
5224 CGIexecute::defineCGIexecuteVariable($name, $directive);
5228 # Nothing to execute
5233 # Handle Foreign scripting languages
5234 if($ScriptingLanguages{$CurrentContentType})
5236 my $newDirective = "";
5237 $newDirective .= OpenForeignScript($CurrentContentType); # Only if not already done
5238 $newDirective .= PrefixForeignScript($CurrentContentType);
5239 $newDirective .= InsertForeignScript($CurrentContentType, $directive, @SRClist);
5240 $newDirective .= PostfixForeignScript($CurrentContentType);
5241 $newDirective .= CloseForeignScript($CurrentContentType); # This shouldn't be necessary
5243 $newDirective .= '"";';
5245 $directive = $newDirective;
5249 # Add the Postfixed directives (but only when it contains something printable)
5250 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
5251 $PostfixDirective = "";
5254 # EXECUTE the script and print the results
5256 # Use this to debug the program
5257 # print STDERR "Directive $CGI_Date: \n", $directive, "\n\n";
5259 my $Result = CGIexecute->evaluate($directive) if $directive; # Evaluate as PERL code
5260 $Result =~ s/\n$//g; # Remove final newline
5262 # Print the Result of evaluating the directive
5263 # (this will handle LARGE, >64 kB output)
5264 my $BytesWritten = 1;
5265 while($Result && $BytesWritten)
5267 $BytesWritten = syswrite(STDOUT, $Result, 64);
5268 $Result = substr($Result, $BytesWritten);
5270 # print $Result; # Could be used instead of above code
5272 # Store result if wanted, i.e., if $CGIscriptorResults has been
5273 # defined in a <META> tag.
5274 push(@CGIexecute::CGIscriptorResults, $Result)
5275 if exists($default_values{'CGIscriptorResults'});
5277 # Process the rest of the input line (this could contain
5278 # another directive)
5282 } while(<$FileHandle>); # Read and Test AFTER first loop!
5284 close ($FileHandle);
5285 dieHandler(28, "Error in recursion\n") unless pop(@OpenFiles) == $file_path;
5289 ###############################################################################
5291 # Call the whole package
5297 # Initialization Code
5298 Initialize_Request();
5300 # SECURITY: ACCESS CONTROL
5303 # Read the POST part of the query, if there is one
5304 Get_POST_part_of_query();
5306 # Start (HTML) output and logging
5307 $file_path = Initialize_output();
5309 # Check login access or divert to login procedure
5310 $Use_Login = Log_In_Access();
5311 $file_path = $Use_Login if $Use_Login;
5313 # Record which files are still open (to avoid endless recursions)
5316 # Record whether the default HTML ContentType has already been printed
5317 # but only if the SERVER uses HTTP or some other protocol that might interpret
5318 # a content MIME type.
5320 $SupressContentType = !("$ENV{'SERVER_PROTOCOL'}" =~ /($ContentTypeServerProtocols)/i);
5322 # Process the specified file
5323 ProcessFile($file_path) if $file_path ne $SS_PUB;
5325 # Cleanup all open external (foreign) interpreters
5326 CloseAllForeignScripts();
5332 # Make a single call to handle an (empty) request
5336 # END OF PACKAGE MAIN
5339 ####################################################################################
5341 # The CGIEXECUTE PACKAGE
5343 ####################################################################################
5345 # Isolate the evaluation of directives as PERL code from the rest of the program.
5346 # Remember that each package has its own name space.
5347 # Note that only the FIRST argument of execute->evaluate is actually evaluated,
5348 # all other arguments are accessible inside the first argument as $_[0] to $_[$#_].
5355 my $directive = shift;
5356 $directive = eval($directive);
5357 warn $@ if $@; # Write an error message to STDERR
5358 $directive; # Return value of directive
5362 # defineCGIexecuteVariable($name [, $value]) -> 0/1
5364 # Define and intialize variables inside CGIexecute
5365 # Does no sanity checking, for internal use only
5367 sub defineCGIexecuteVariable # ($name [, $value]) -> 0/1
5369 my $name = shift || return 0; # The Name
5370 my $value = shift || ""; # The value
5377 # Protect certain CGI variables values when set internally
5378 # If not defined internally, there will be no variable set AT ALL
5379 my %CGIprotectedVariable = ();
5380 sub ProtectCGIvariable # ($name) -> 0/1
5382 my $name = shift || "";
5383 return 0 unless $name && $name =~ /\w/;
5385 ++$CGIprotectedVariable{$name};
5387 return $CGIprotectedVariable{$name};
5390 # defineCGIvariable($name [, $default]) -> 0/1
5392 # Define and intialize CGI variables
5393 # Tries (in order) $ENV{$name}, the Query string and the
5395 # Removes all '-quotes etc.
5397 sub defineCGIvariable # ($name [, $default]) -> 0/1
5399 my $name = shift || return 0; # The Name
5400 my $default = shift || ""; # The default value
5402 # Protect variables set internally
5403 return 1 if !$name || exists($CGIprotectedVariable{$name});
5405 # Remove \-quoted characters
5406 $default =~ s/\\(.)/$1/g;
5407 # Store default values
5408 $::default_values{$name} = $default if $default;
5412 # If there is a user supplied value, it replaces the
5415 # Environment values have precedence
5416 if(exists($ENV{$name}))
5418 $temp = $ENV{$name};
5420 # Get name and its value from the query string
5421 elsif($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
5423 $temp = ::YOUR_CGIPARSE($name);
5425 # Defined values must exist for security
5426 elsif(!exists($::default_values{$name}))
5428 $::default_values{$name} = undef;
5431 # SECURITY, do not allow '- and `-quotes
in
5433 # Remove all existing '-quotes
5434 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
5435 $temp =~ s/[\']/’/igs; # Remove all single quotes
5436 $temp =~ s/[\`]/‘/igs; # Remove all backtick quotes
5437 # If $temp is empty, use the default value (if it exists)
5438 unless($temp =~ /\S/ || length($temp) > 0) # I.e., $temp is empty
5440 $temp = $::default_values
{$name};
5441 # Remove all existing '-quotes
5442 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
5443 $temp =~ s/[\']/’/igs; # Remove all single quotes
5444 $temp =~ s/[\`]/‘/igs; # Remove all backtick quotes
5446 else # Store current CGI values and remove defaults
5448 $::default_values
{$name} = $temp;
5450 # Define the CGI variable and its value (in the execute package)
5457 sub defineCGIvariableList
# ($name [, $default]) -> 0/1)
5459 my $name = shift || return 0; # The Name
5460 my $default = shift || ""; # The default value
5462 # Protect variables set internally
5463 return 1 if !$name || exists($CGIprotectedVariable{$name});
5465 # Defined values must exist for security
5466 if(!exists($::default_values
{$name}))
5468 $::default_values
{$name} = $default;
5475 # Environment values have precedence
5476 if(exists($ENV{$name}))
5478 push(@temp, $ENV{$name});
5480 # Get name and its values from the query string
5481 elsif($ENV{QUERY_STRING
} =~ /$name/) # $name is in the query string
5483 push(@temp, ::YOUR_CGIPARSE
($name, 1)); # Extract LIST
5487 push(@temp, $::default_values
{$name});
5491 # SECURITY, do not allow '- and `-quotes in
5493 # Remove all existing '-quotes
5494 @temp = map {s/([\r\f]+\n)/\n/g; $_} @temp; # Only \n is allowed
5495 @temp = map {s/[\']/’/igs; $_} @temp; # Remove all single quotes
5496 @temp = map {s/[\`]/‘/igs; $_} @temp; # Remove all backtick quotes
5498 # Store current CGI values and remove defaults
5499 $::default_values
{$name} = $temp[0];
5501 # Define the CGI variable and its value (in the execute package)
5508 sub defineCGIvariableHash
# ($name [, $default]) -> 0/1) Note: '$name{""} = $default';
5510 my $name = shift || return 0; # The Name
5511 my $default = shift || ""; # The default value
5513 # Protect variables set internally
5514 return 1 if !$name || exists($CGIprotectedVariable{$name});
5516 # Defined values must exist for security
5517 if(!exists($::default_values
{$name}))
5519 $::default_values
{$name} = $default;
5526 # Environment values have precedence
5527 if(exists($ENV{$name}))
5529 $temp{""} = $ENV{$name};
5531 # Get name and its values from the query string
5532 elsif($ENV{QUERY_STRING
} =~ /$name/) # $name is in the query string
5534 %temp = ::YOUR_CGIPARSE
($name, -1); # Extract HASH table
5536 elsif($::default_values
{$name} ne "")
5538 $temp{""} = $::default_values
{$name};
5542 # SECURITY, do not allow '- and `-quotes in
5544 # Remove all existing '-quotes
5546 foreach $Key (keys(%temp))
5548 $temp{$Key} =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
5549 $temp{$Key} =~ s/[\']/’/igs; # Remove all single quotes
5550 $temp{$Key} =~ s/[\`]/‘/igs; # Remove all backtick quotes
5553 # Store current CGI values and remove defaults
5554 $::default_values
{$name} = $temp{""};
5556 # Define the CGI variable and its value (in the execute package)
5559 foreach $tempKey (keys(%temp))
5561 ${$name}{$tempKey} = $temp{$tempKey};
5569 # SAFEqx('CommandString')
5571 # A special function that is a safe alternative to backtick quotes (and qx//)
5572 # with client-supplied CGI values. All CGI variables are surrounded by
5573 # single ''-quotes (except between existing \'\'-quotes, don't try to be
5574 # too smart). All variables are then interpolated. Simple (@) lists are
5575 # expanded with join(' ', @List), and simple (%) hash tables expanded
5576 # as a list of "key=value" pairs. Complex variables, e.g., @$var, are
5577 # evaluated in a scalar context (e.g., as scalar(@$var)). All occurrences of
5578 # $@% that should NOT be interpolated must be preceeded by a "\".
5579 # If the first line of the String starts with "#! interpreter", the
5580 # remainder of the string is piped into interpreter (after interpolation), i.e.,
5581 # open(INTERPRETER, "|interpreter");print INTERPRETER remainder;
5582 # just like in UNIX. There are some problems with quotes. Be carefull in
5583 # using them. You do not have access to the output of any piped (#!)
5584 # process! If you want such access, execute
5585 # <SCRIPT TYPE="text/osshell">echo "script"|interpreter</SCRIPT> or
5586 # <SCRIPT TYPE="text/ssperl">$resultvar = SAFEqx('echo "script"|interpreter');
5589 # SAFEqx ONLY WORKS WHEN THE STRING ITSELF IS SURROUNDED BY SINGLE QUOTES
5590 # (SO THAT IT IS NOT INTERPOLATED BEFORE IT CAN BE PROTECTED)
5591 sub SAFEqx
# ('String') -> result of executing qx/"String"/
5593 my $CommandString = shift;
5594 my $NewCommandString = "";
5596 # Only interpolate when required (check the On/Off switch)
5597 unless($CGIscriptor::NoShellScriptInterpolation
)
5600 # Handle existing single quotes around CGI values
5601 while($CommandString =~ /\'[^\']+\'/s)
5603 my $CurrentQuotedString = $&;
5604 $NewCommandString .= $`;
5605 $CommandString = $'; # The remaining string
5606 # Interpolate CGI variables between quotes
5607 # (e.g., '$CGIscriptorResults[-1]')
5608 $CurrentQuotedString =~
5609 s/(^|[^\\])([\$\@])((\w*)([\{\[][\$\@\%]?[\:\w\-]+[\}\]])*)/if(exists($main::default_values{$4})){
5610 "$1".eval("$2$3")}else{"$&"}/egs;
5612 # Combine result with previous result
5613 $NewCommandString .= $CurrentQuotedString;
5615 $CommandString = $NewCommandString.$CommandString;
5617 # Select known CGI variables and surround them with single quotes,
5618 # then interpolate all variables
5620 s/(^|[^\\])([\$\@\%]+)((\w*)([\{\[][\w\:\$\"\-]+[\}\]])*)/
5621 if($2 eq '$' && exists($main::default_values{$4}))
5622 {"$1\'".eval("\$$3")."\'";}
5623 elsif($2 eq '@'){$1.join(' ', @{"$3"});}
5624 elsif($2 eq '%'){my $t=$1;map {$t.=" $_=".${"$3"}{$_}}
5626 else{$1.eval("${2}$3");
5629 # Remove backslashed [$@%]
5630 $CommandString =~ s/\\([\$\@\%])/$1/gs;
5634 # return $CommandString;
5636 # Handle UNIX style "#! shell command\n" constructs as
5637 # a pipe into the shell command. The output cannot be tapped.
5638 my $ReturnValue = "";
5639 if($CommandString =~ /^\s*\#\!([^\f\n\r]+)[\f\n\r]/is)
5641 my $ShellScripts = $';
5642 my $ShellCommand = $1;
5643 open(INTERPRETER, "|$ShellCommand") || dieHandler(29, "\'$ShellCommand\' PIPE not opened: &!\n");
5644 select(INTERPRETER);$| = 1;
5645 print INTERPRETER $ShellScripts;
5647 select(STDOUT);$| = 1;
5649 # Shell scripts which are redirected to an existing named pipe.
5650 # The output cannot be tapped.
5651 elsif($CGIscriptor::ShellScriptPIPE)
5653 CGIscriptor::printSAFEqxPIPE($CommandString);
5655 else # Plain ``-backtick execution
5657 # Execute the commands
5658 $ReturnValue = qx/$CommandString/;
5660 return $ReturnValue;
5663 ####################################################################################
5665 # The CGIscriptor PACKAGE
5667 ####################################################################################
5669 # Isolate the evaluation of CGIscriptor functions, i.e., those prefixed with
5672 package CGIscriptor;
5675 # The Interpolation On/Off switch
5676 my $NoShellScriptInterpolation = undef;
5677 # The ShellScript redirection pipe
5678 my $ShellScriptPIPE = undef;
5680 # Open a named PIPE for SAFEqx to receive ALL shell scripts
5681 sub RedirectShellScript # ('CommandString')
5683 my $CommandString = shift || undef;
5687 $ShellScriptPIPE = "ShellScriptNamedPipe";
5688 open($ShellScriptPIPE, "|$CommandString")
5689 || main::dieHandler(30, "\'|$CommandString\' PIPE open failed: $!\n");
5693 close($ShellScriptPIPE);
5694 $ShellScriptPIPE = undef;
5696 return $ShellScriptPIPE;
5699 # Print to redirected shell script pipe
5700 sub printSAFEqxPIPE # ("String") -> print return value
5702 my $String = shift || undef;
5704 select($ShellScriptPIPE); $| = 1;
5705 my $returnvalue = print $ShellScriptPIPE ($String);
5706 select(STDOUT); $| = 1;
5708 return $returnvalue;
5711 # a pointer to CGIexecute::SAFEqx
5712 sub SAFEqx # ('String') -> result of qx/"String"/
5714 my $CommandString = shift;
5715 return CGIexecute::SAFEqx($CommandString);
5719 # a pointer to CGIexecute::defineCGIvariable
5720 sub defineCGIvariable # ($name[, $default]) ->0/1
5723 my $default = shift;
5724 return CGIexecute::defineCGIvariable($name, $default);
5728 # a pointer to CGIexecute::defineCGIvariable
5729 sub defineCGIvariableList # ($name[, $default]) ->0/1
5732 my $default = shift;
5733 return CGIexecute::defineCGIvariableList($name, $default);
5737 # a pointer to CGIexecute::defineCGIvariable
5738 sub defineCGIvariableHash # ($name[, $default]) ->0/1
5741 my $default = shift;
5742 return CGIexecute::defineCGIvariableHash($name, $default);
5746 # Decode URL encoded arguments
5747 sub URLdecode # (URL encoded input) -> string
5754 my $EncodedValue = $Value; # Do not change the loop variable
5755 # Convert all "+" to " "
5756 $EncodedValue =~ s/\+/ /g;
5757 # Convert all hexadecimal codes (%FF) to their byte values
5758 while($EncodedValue =~ /\%([0-9A-F]{2})/i)
5760 $output .= $`.chr(hex($1));
5763 $output .= $EncodedValue; # The remaining part of $Value
5768 # Encode arguments as URL codes.
5769 sub URLencode # (input) -> URL encoded string
5776 my @CharList = split('', $Value);
5777 foreach $char (@CharList)
5781 elsif($char =~ /\w\-/)
5782 { $output .= $char;}
5785 $output .= uc(sprintf("%%%2.2x", ord($char)));
5792 # Extract the value of a CGI variable from the URL-encoded $string
5793 # Also extracts the data blocks from a multipart request. Does NOT
5794 # decode the multipart blocks
5795 sub CGIparseValue # (ValueName [, URL_encoded_QueryString [, \$QueryReturnReference]]) -> Decoded value
5797 my $ValueName = shift;
5798 my $QueryString = shift || $main::ENV{'QUERY_STRING
'};
5799 my $ReturnReference = shift || undef;
5802 if($QueryString =~ /(^|\&)$ValueName\=([^\&]*)(\&|$)/)
5804 $output = URLdecode($2);
5805 $$ReturnReference = $' if ref($ReturnReference);
5807 # Get multipart POST or PUT methods
5808 elsif($main::ENV
{'CONTENT_TYPE'} =~ m@
(multipart
/([\w\
-]+)\
;\s
+boundary\
=([\S
]+))@i)
5810 my $MultipartType = $2;
5811 my $BoundaryString = $3;
5812 # Remove the boundary-string
5813 my $temp = $QueryString;
5814 $temp =~ /^\Q--$BoundaryString\E/m;
5817 # Identify the newline character(s), this is the first character in $temp
5818 my $NewLine = "\r\n"; # Actually, this IS the correct one
5819 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
5821 # Is this correct??? I have to check.
5822 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
5823 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
5824 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
5825 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
5828 # search through all data blocks
5829 while($temp =~ /^\Q--$BoundaryString\E/m)
5833 # Get the empty line after the header
5834 $DataBlock =~ /$NewLine$NewLine/;
5840 # Remove newlines from the header
5841 $Header =~ s/$NewLine/ /g;
5843 # Look whether this block is the one you are looking for
5844 # Require the quotes!
5845 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
5848 for($i=length($NewLine); $i; --$i)
5855 # reinitialize the output
5858 $$ReturnReference = $temp if ref($ReturnReference);
5860 elsif($QueryString !~ /(^|\&)$ValueName\=/) # The value simply isn't there
5863 $$ReturnReference = undef if ref($ReturnReference);
5867 print "ERROR: $ValueName $main::ENV{'CONTENT_TYPE'}\n";
5873 # Get a list of values for the same ValueName. Uses CGIparseValue
5875 sub CGIparseValueList
# (ValueName [, URL_encoded_QueryString]) -> List of decoded values
5877 my $ValueName = shift;
5878 my $QueryString = shift || $main::ENV
{'QUERY_STRING'};
5880 my $RestQueryString;
5882 while($QueryString &&
5883 (($Value = CGIparseValue
($ValueName, $QueryString, \
$RestQueryString))
5884 || defined($Value)))
5886 push(@output, $Value);
5887 $QueryString = $RestQueryString; # QueryString is consumed!
5889 # ready, return list with values
5893 sub CGIparseValueHash
# (ValueName [, URL_encoded_QueryString]) -> Hash table of decoded values
5895 my $ValueName = shift;
5896 my $QueryString = shift || $main::ENV
{'QUERY_STRING'};
5897 my $RestQueryString;
5899 while($QueryString && $QueryString =~ /(^|\&)$ValueName([\w]*)\=/)
5902 my $Value = CGIparseValue
("$ValueName$Key", $QueryString, \
$RestQueryString);
5903 $output{$Key} = $Value;
5904 $QueryString = $RestQueryString; # QueryString is consumed!
5906 # ready, return list with values
5910 sub CGIparseForm
# ([URL_encoded_QueryString]) -> Decoded Form (NO multipart)
5912 my $QueryString = shift || $main::ENV
{'QUERY_STRING'};
5915 $QueryString =~ s/\&/\n/g;
5916 $output = URLdecode
($QueryString);
5921 # Extract the header of a multipart CGI variable from the POST input
5922 sub CGIparseHeader
# (ValueName [, URL_encoded_QueryString]) -> Decoded value
5924 my $ValueName = shift;
5925 my $QueryString = shift || $main::ENV
{'QUERY_STRING'};
5928 if($main::ENV
{'CONTENT_TYPE'} =~ m@
(multipart
/([\w\
-]+)\
;\s
+boundary\
=([\S
]+))@i)
5930 my $MultipartType = $2;
5931 my $BoundaryString = $3;
5932 # Remove the boundary-string
5933 my $temp = $QueryString;
5934 $temp =~ /^\Q--$BoundaryString\E/m;
5937 # Identify the newline character(s), this is the first character in $temp
5938 my $NewLine = "\r\n"; # Actually, this IS the correct one
5939 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
5941 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
5942 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
5943 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
5944 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
5947 # search through all data blocks
5948 while($temp =~ /^\Q--$BoundaryString\E/m)
5952 # Get the empty line after the header
5953 $DataBlock =~ /$NewLine$NewLine/;
5957 # Remove newlines from the header
5958 $Header =~ s/$NewLine/ /g;
5960 # Look whether this block is the one you are looking for
5961 # Require the quotes!
5962 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
5967 # reinitialize the output
5975 # Checking variables for security (e.g., file names and email addresses)
5976 # File names are tested against the $::FileAllowedChars and $::BlockPathAccess variables
5977 sub CGIsafeFileName
# FileName -> FileName or ""
5979 my $FileName = shift || "";
5980 return "" if $FileName =~ m?[^$::FileAllowedChars]?;
5981 return "" if $FileName =~ m!(^|/|\:)[\-\.]!;
5982 return "" if $FileName =~ m@\
.\
.\Q
$::DirectorySeparator\E@
; # Higher directory not allowed
5983 return "" if $FileName =~ m@\Q
$::DirectorySeparator\E\
.\
.@
; # Higher directory not allowed
5984 return "" if $::BlockPathAccess
&& $FileName =~ m@
$::BlockPathAccess@
; # Invisible (blocked) file
5989 sub CGIsafeEmailAddress
# email -> email or ""
5991 my $Email = shift || "";
5992 return "" unless $Email =~ m/^[\w\.\-]+[\@][\w\.\-\:]+$/;
5996 # Get a URL from the web. Needs main::GET_URL($URL) function
5997 # (i.e., curl, snarf, or wget)
5998 sub read_url
# ($URL) -> page/file
6000 my $URL = shift || return "";
6002 # Get the commands to read the URL, do NOT add a print command
6003 my $URL_command = main
::GET_URL
($URL, 1);
6004 # execute the commands, i.e., actually read it
6005 my $URLcontent = CGIexecute
->evaluate($URL_command);
6007 # Ready, return the content.
6011 ################################################>>>>>>>>>>Start Remove
6013 # BrowseAllDirs(Directory, indexfile)
6016 # <SCRIPT TYPE='text/ssperl'>
6017 # CGIscriptor::BrowseAllDirs('Sounds', 'index.html', '\.wav$')
6020 # Allows to browse all directories. Stops at '/'. If the directory contains
6021 # an indexfile, eg, index.html, that file will be used instead. Files must match
6022 # the $Pattern, if it is given. Default is
6023 # CGIscriptor::BrowseAllDirs('/', 'index.html', '')
6025 sub BrowseAllDirs
# (Directory, indexfile, $Pattern) -> Print HTML code
6027 my $Directory = shift || '/';
6028 my $indexfile = shift || 'index.html';
6029 my $Pattern = shift || '';
6030 $Directory =~ s!/$!!g;
6032 # If the index directory exists, use that one
6033 if(-s
"$::CGI_HOME$Directory/$indexfile")
6035 return main
::ProcessFile
("$::CGI_HOME$Directory/$indexfile");
6038 # No indexfile, continue
6039 my @DirectoryList = glob("$::CGI_HOME$Directory");
6040 $CurrentDirectory = shift(@DirectoryList);
6041 $CurrentDirectory = $' if $CurrentDirectory =~ m@(/\.\./)+@;
6042 $CurrentDirectory =~ s@^$::CGI_HOME@@g;
6044 print "$CurrentDirectory" if $CurrentDirectory;
6047 opendir(BROWSE, "$::CGI_HOME$Directory") || main::dieHandler(31, "$::CGI_HOME$Directory $!");
6048 my @AllFiles = sort grep(!/^([\.]+[^\.]|\~)/, readdir(BROWSE));
6052 print "<pre><ul TYPE='NONE
'>\n";
6053 foreach $file (@AllFiles)
6055 next unless -d "$::CGI_HOME$Directory/$file";
6056 # Check whether this file should be visible
6057 next if $::BlockPathAccess &&
6058 "$Directory/$file/" =~ m@$::BlockPathAccess@;
6059 print "<dt><a href='$Directory/$file'>$file</a></dt>\n";
6061 print "</ul></pre>\n";
6064 print "<pre><ul TYPE='CIRCLE
'>\n";
6066 foreach $file (@AllFiles)
6068 next if $file =~ /^\./;
6069 next if -d "$::CGI_HOME$Directory/$file";
6070 next if -l "$::CGI_HOME$Directory/$file";
6071 # Check whether this file should be visible
6072 next if $::BlockPathAccess &&
6073 "$Directory/$file" =~ m@$::BlockPathAccess@;
6075 if(!$Pattern || $file =~ m@$Pattern@)
6077 my $Date = localtime($^T - (-M "$::CGI_HOME$Directory/$file")*3600*24);
6078 my $Size = -s "$::CGI_HOME$Directory/$file";
6079 $Size = sprintf("%6.0F kB", $Size/1024);
6080 my $Type = `file $::CGI_HOME$Directory/$file`;
6081 $Type =~ s@\s*$::CGI_HOME$Directory/$file\s*\:\s*@@ig;
6085 print "<a href='$Directory/$file'>";
6086 printf("%-40s", "$file</a>");
6087 print "\t$Size\t$Date\t$Type";
6091 print "</ul></pre>";
6097 ################################################
6099 # BrowseDirs(RootDirectory [, Pattern, Start])
6102 # <SCRIPT TYPE='text
/ssperl
'>
6103 # CGIscriptor::BrowseDirs('Sounds
', '\
.aifc
$', 'Speech
', 'DIRECTORY
')
6106 # Allows to browse subdirectories. Start should be relative to the RootDirectory,
6107 # e.g., the full path of the directory 'Speech
' is '~/Sounds/Speech
'.
6108 # Only files which fit /$Pattern/ and directories are displayed.
6109 # Directories down or up the directory tree are supplied with a
6110 # GET request with the name of the CGI variable in the fourth argument (default
6111 # is 'BROWSEDIRS
'). So the correct call for a subdirectory could be:
6112 # CGIscriptor::BrowseDirs('Sounds
', '\
.aifc
$', $DIRECTORY, 'DIRECTORY
')
6114 sub BrowseDirs # (RootDirectory [, Pattern, Start, CGIvariable, HTTPserver]) -> Print HTML code
6116 my $RootDirectory = shift; # || return 0;
6117 my $Pattern = shift || '\S
';
6118 my $Start = shift || "";
6119 my $CGIvariable = shift || "BROWSEDIRS";
6120 my $HTTPserver = shift || '';
6122 $Start = CGIscriptor::URLdecode($Start); # Sometimes, too much has been encoded
6123 $Start =~ s@//+@/@g;
6124 $Start =~ s@[^/]+/\.\.@@ig;
6125 $Start =~ s@^\.\.@@ig;
6126 $Start =~ s@/\.$@@ig;
6128 $Start .= "/" if $Start;
6130 my @Directory = glob("$::CGI_HOME/$RootDirectory/$Start");
6131 $CurrentDirectory = shift(@Directory);
6132 $CurrentDirectory = $' if $CurrentDirectory =~ m@
(/\.\./)+@
;
6133 $CurrentDirectory =~ s@
^$::CGI_HOME@
@g;
6135 print "$CurrentDirectory" if $CurrentDirectory;
6137 opendir(BROWSE
, "$::CGI_HOME/$RootDirectory/$Start") || main
::dieHandler
(31, "$::CGI_HOME/$RootDirectory/$Start $!");
6138 my @AllFiles = sort grep(!/^([\.]+[^\.]|\~)/, readdir(BROWSE
));
6142 print "<pre><ul TYPE='NONE'>\n";
6143 foreach $file (@AllFiles)
6145 next unless -d
"$::CGI_HOME/$RootDirectory/$Start$file";
6146 # Check whether this file should be visible
6147 next if $::BlockPathAccess
&&
6148 "/$RootDirectory/$Start$file/" =~ m@
$::BlockPathAccess@
;
6150 my $NewURL = $Start ?
"$Start$file" : $file;
6151 $NewURL = CGIscriptor
::URLencode
($NewURL);
6152 print "<dt><a href='";
6153 print "$ENV{SCRIPT_NAME}" if $ENV{SCRIPT_NAME
} !~ m@
[^\w
+\
-/]@
;
6154 print "$ENV{PATH_INFO}?$CGIvariable=$NewURL'>$file</a></dt>\n";
6156 print "</ul></pre>\n";
6159 print "<pre><ul TYPE='CIRCLE'>\n";
6161 foreach $file (@AllFiles)
6163 next if $file =~ /^\./;
6164 next if -d
"$::CGI_HOME/$RootDirectory/$Start$file";
6165 next if -l
"$::CGI_HOME/$RootDirectory/$Start$file";
6166 # Check whether this file should be visible
6167 next if $::BlockPathAccess
&&
6168 "$::CGI_HOME/$RootDirectory/$Start$file" =~ m@
$::BlockPathAccess@
;
6170 if($file =~ m@
$Pattern@
)
6172 my $Date = localtime($^T
- (-M
"$::CGI_HOME/$RootDirectory/$Start$file")*3600*24);
6173 my $Size = -s
"$::CGI_HOME/$RootDirectory/$Start$file";
6174 $Size = sprintf("%6.0F kB", $Size/1024);
6175 my $Type = `file $::CGI_HOME/$RootDirectory/$Start$file`;
6176 $Type =~ s@\s
*$::CGI_HOME
/$RootDirectory/$Start$file\s
*\
:\s
*@
@ig;
6180 if($HTTPserver =~ /^\s*[\.\~]\s*$/)
6182 print "<a href='$RootDirectory/$Start$file'>";
6186 print "<a href='$HTTPserver/$RootDirectory/$Start$file'>";
6188 printf("%-40s", "$file</a>") if $HTTPserver;
6189 printf("%-40s", "$file") unless $HTTPserver;
6190 print "\t$Size\t$Date\t$Type";
6194 print "</ul></pre>";
6200 # ListDocs(Pattern [,ListType])
6203 # <SCRIPT TYPE=text/ssperl>
6204 # CGIscriptor::ListDocs("/*", "dl");
6207 # This subroutine is very usefull to manage collections of independent
6208 # documents. The resulting list will display the tree-like directory
6209 # structure. If this routine is too slow for online use, you can
6210 # store the result and use a link to that stored file.
6212 # List HTML and Text files with title and first header (HTML)
6213 # or filename and first meaningfull line (general text files).
6214 # The listing starts at the ServerRoot directory. Directories are
6215 # listed recursively.
6217 # You can change the list type (default is dl).
6219 # <dt><a href=<file.html>>title</a>
6221 # <dt><a href=<file.txt>>file.txt</a>
6222 # <dd>First meaningfull line of text
6224 sub ListDocs
# ($Pattern [, prefix]) e.g., ("/Books/*", [, "dl"])
6226 my $Pattern = shift;
6228 my $ListType = shift || "dl";
6229 my $Prefix = lc($ListType) eq "dl" ?
"dt" : "li";
6230 my $URL_root = "http://$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}";
6231 my @FileList = glob("$::CGI_HOME$Pattern");
6232 my ($FileName, $Path, $Link);
6234 # Print List markers
6235 print "<$ListType>\n";
6238 File
: foreach $FileName (@FileList)
6240 # Check whether this file should be visible
6241 next if $::BlockPathAccess
&& $FileName =~ m@
$::BlockPathAccess@
;
6243 # Recursively list files in all directories
6246 $FileName =~ m@
([^/]*)$@
;
6248 print "<$Prefix>$DirName\n";
6249 $Pattern =~ m@
([^/]*)$@
;
6250 &ListDocs
("$`$DirName/$1", $ListType);
6254 elsif(-T
"$FileName")
6256 open(TextFile
, $FileName) || next;
6258 # Ignore all other file types
6262 # Get file path for link
6263 $FileName =~ /$::CGI_HOME/;
6264 print "<$Prefix><a href=$URL_root$'>";
6265 # Initialize all variables
6270 # Read file and step through
6276 if($FileName =~ /\.ht[a-zA-Z]*$/i)
6281 if($Line =~ m@
<title
>([^<]*)</title
>@i)
6288 $Line .= <TextFile> || goto Print;
6292 # Catch First Header
6295 if($Line =~ m@</h1>@i)
6299 $Caption =~ m@
<h1
>@i;
6301 $Line = $`.$Caption.$Line;
6305 $Line .= <TextFile> || goto Print;
6313 # Title equals file name
6314 $FileName =~ /([^\/]+)$/;
6316 # Catch equals First Meaningfull line
6319 if($Line =~ /[A-Z]/ &&
6320 ($Line =~ /subject|title/i || $Line =~ /^[\w,\.\s\?\:]+$/)
6321 && $Line !~ /Newsgroup/ && $Line !~ /\:\s*$/)
6323 $Line =~ s/\<[^\>]+\>//g;
6328 $Line = <TextFile> || goto Print;
6332 Print: # Print title and subject
6333 print "$Title</a>\n";
6334 print "<dd>$Caption\n" if $ListType eq "dl";
6341 # Print Closing List Marker
6342 print "</$ListType>\n";
6343 ""; # Empty return value
6347 # HTMLdocTree(Pattern [,ListType])
6350 # <SCRIPT TYPE=text/ssperl>
6351 # CGIscriptor::HTMLdocTree("/Welcome.html", "dl");
6354 # The following subroutine is very usefull for checking large document
6355 # trees. Starting from the root (s), it reads all files and prints out
6356 # a nested list of links to all attached files. Non-existing or misplaced
6357 # files are flagged. This is quite a file-i/o intensive routine
6358 # so you would not like it to be accessible to everyone. If you want to
6359 # use the result, save the whole resulting page to disk and use a link
6362 # HTMLdocTree takes an HTML file or file pattern and constructs nested lists
6363 # with links to *local* files (i.e., only links to the local server are
6364 # followed). The list entries are the document titles.
6365 # If the list type is <dl>, the first <H1> header is used too.
6366 # For each file matching the pattern, a list is made recursively of all
6367 # HTML documents that are linked from it and are stored in the same directory
6368 # or a sub-directory. Warnings are given for missing files.
6369 # The listing starts for the ServerRoot directory.
6370 # You can change the default list type <dl> (<dl>, <ul>, <ol>).
6374 sub HTMLdocTree # ($Pattern [, listtype])
6375 # e.g., ("/Welcome.html", [, "ul"])
6377 my $Pattern = shift;
6378 my $ListType = shift || "dl";
6379 my $Prefix = lc($ListType) eq "dl" ? "dt" : "li";
6380 my $URL_root = "http://$::ENV{'SERVER_NAME
'}\:$::ENV{'SERVER_PORT
'}";
6381 my ($Filename, $Path, $Link);
6382 my %LocalLinks = {};
6384 # Read files (glob them for expansion of wildcards)
6385 my @FileList = glob("$::CGI_HOME$Pattern");
6386 foreach $Path (@FileList)
6389 $Path =~ /$::CGI_HOME/;
6391 # Check whether this file should be visible
6392 next if $::BlockPathAccess
&& $URL_path =~ m@
$::BlockPathAccess@
;
6394 my $Title = $URL_path;
6396 # Current file should not be used again
6397 ++$LinkUsed{$URL_path};
6399 unless(open(TextFile
, $Path))
6401 print "<$Prefix>$Title <blink>(not found)</blink><br>\n";
6409 while($Line =~ m@
<title
>@i)
6411 if($Line =~ m@
<title
>([^<]*)</title
>@i)
6418 $Line .= <TextFile>;
6422 # Catch First Header
6423 while(!$Caption && $Line =~ m@<h1>@i)
6425 if($Line =~ m@</h[1-9]>@i)
6429 $Caption =~ m@
<h1
>@i;
6431 $Line = $`.$Caption.$Line;
6435 $Line .= <TextFile>;
6439 # Catch and print Links
6440 while($Line =~ m@<a href\=([^>]*)>@i)
6447 $Link =~ s/[\#\?].*$//g;
6449 if($Link =~ m@
(http
://|^)@i)
6452 # Only build tree for current server
6453 next unless $Link =~ m@$::ENV{'SERVER_NAME
'}|^/@;
6454 # Remove server name and port
6455 $Link =~ s@^[^\/]*@@g;
6457 # Store the current link
6458 next if $LinkUsed{$Link} || $Link eq $URL_path;
6460 ++$LocalLinks{$Link};
6466 print "<a href=http://";
6467 print "$::ENV{'SERVER_NAME
'}\:$::ENV{'SERVER_PORT
'}$URL_path>";
6468 print "$Title</a>\n";
6469 print "<br>$Caption\n"
6470 if $Caption && $Caption ne $Title && $ListType =~ /dl/i;
6471 print "<$ListType>\n";
6472 foreach $Link (keys(%LocalLinks))
6474 &HTMLdocTree($Link, $ListType);
6476 print "</$ListType>\n";
6480 ###########################<<<<<<<<<<End Remove
6482 # Make require happy
6491 A flexible HTML 4 compliant script/module for CGI-aware
6492 embeded Perl, shell-scripts, and other scripting languages,
6493 executed at the server side.
6497 Executes embeded Perl code in HTML pages with easy
6498 access to CGI variables. Also processes embeded shell
6499 scripts and scripts in any other language with an
6500 interactive interpreter (e.g., in-line Python, Tcl,
6501 Ruby, Awk, Lisp, Xlispstat, Prolog, M4, R, REBOL, Praat,
6502 sh, bash, csh, ksh).
6504 CGIscriptor is very flexible and hides all the specifics
6505 and idiosyncrasies of correct output and CGI coding and naming.
6506 CGIscriptor complies with the W3C HTML 4.0 recommendations.
6508 This Perl program will run on any WWW server that runs
6509 Perl scripts, just add a line like the following to your
6510 srm.conf file (Apache example):
6512 ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
6514 URL's that refer to http
://www
.your
.address
/SHTML/... will
6515 now be handled by CGIscriptor
.pl
, which can
use a private
6516 directory tree
(default is the DOCUMENT_ROOT directory tree
,
6517 but it can be anywhere
).
6519 =head1 PREREQUISITES
6527 Linux, *BSD, *nix, MS WinXP
6529 =pod SCRIPT CATEGORIES