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. The solution would be
1948 # to add a hidden iFrame tag loading the untrusted page from the URL and
1949 # extract the needed ticket and salt values. Then run the stored, trusted,
1950 # code with these values. It is not (yet) possible to set the
1951 # required session storage inside the browser, so this method only works
1952 # for IPADDRESS sessions.
1954 # Humans tend to reuse passwords. A compromise of a site running
1955 # CGIscriptor.pl could therefore lead to a compromise of user accounts at
1956 # other sites. Therefore, plain text passwords are never stored, used, or
1957 # exchanged. Instead, the plain password and user name are "encrypted" with
1958 # a server site salt value. Actually, all are concatenated and hashed
1959 # with a one-way secure hash function (SHA256) into a single string.
1960 # Whenever the word "password" is used, this hash sum is meant. Note that
1961 # the salts are generated from /dev/urandom. You should check whether the
1962 # implementation of /dev/urandom on your platform is secure before
1963 # relying on it. This might be a problem when running CGIscriptor under
1964 # Cygwin on MS Windows.
1965 # Note: no attempt is made to slow down the password hash, so bad
1966 # passwords can be cracked by brute force
1968 # As the (hashed) passwords are all that is needed to identify at the site,
1969 # these should not be stored in this form. A site specific passphrase
1970 # can be entered as an environment variable ($ENV{'CGIMasterKey'}). This
1971 # phrase is hashed with the server site salt and the result is hashed with
1972 # the user name and then XORed with the password when it is stored. Also, to
1973 # detect changes to the account (PASSWORD) and session tickets, a
1974 # (HMAC) hash of some of the contents of the ticket with the server salt and
1975 # CGIMasterKey is stored in each ticket.
1977 # Creating a valid (hashed) password, encrypt it with the CGIMasterKey and
1978 # construct a signature of the ticket are non-trivial. This has to be redone
1979 # with every change of the ticket file or CGIMasterKey change. CGIscriptor
1980 # can do this from the command line with the command:
1982 # perl CGIscriptor.pl --managelogin salt=Private/.Passwords/SALT \
1983 # masterkey='Sherlock investigates oleander curry in Bath' \
1984 # password='There is no password like more password' \
1987 # CGIscriptor will exit after this command with the first option being
1988 # --managelogin. Options have the form:
1990 # salt=[file or string]
1991 # Server salt value to use io the value
1992 # stored in the ticket file. Will replace the stored value if a new
1993 # password is given. If you change the server salt, you have to
1994 # reset all the passwords. There is absolutely no procedure known
1995 # to recover plaintext passwords, except asking the account holders.
1996 # You are strongly adviced to make a backup before you apply such a change
1997 # masterkey=[file or string]
1998 # CGIMasterKey used to read and decrypt the ticket
1999 # newmasterkey=[file or string]
2000 # CGIMasterKey used to encrypt, sign,
2001 # and write the ticket. Defaults to the masterkey. If you change
2002 # the masterkey, you will have to reset all the accounts. You are strongly
2003 # adviced to make a backup before you apply such a change
2004 # password=[file or string]
2005 # New plaintext password
2007 # When the value of an option is a existing file path, the first line of
2008 # that file is used. Options are followed by one or more paths plus names
2009 # of existing ticket files. Each password option is only used for a single
2010 # ticket file. It is most definitely a bad idea to use a password that is
2011 # identical to an existing filepath, as the file will be read instead. Be
2012 # aware that the name of the file should be a cleaned up version of the
2013 # Username. This will not be checked.
2015 # For the authentication and a change of password, the (old) password
2016 # is used to "encrypt" a random one-time token or the new password,
2017 # respectively. For authentication, decryption is not needed, so a secure
2018 # hash function (SHA256) is used to create a one-way hash sum "encryption".
2019 # A new password must be decrypted. New passwords are encryped by XORing
2020 # them with the old password.
2022 # Strong Passwords: It is so easy
2023 # If you only could see what you are typing
2025 # Your password might be vulnerable to brute force guessing
2026 # (https://en.wikipedia.org/wiki/Brute_force_attack).
2027 # Protections against such attacks are costly in terms of code
2028 # complexity, bugs, and execution time. However, there is a very
2029 # simple and secure counter measure. See the XKCD comic
2030 # (http://xkcd.com/936/). The phrase, "There is no password like more
2031 # password" would be both much easier to remember, and still stronger
2032 # than "h4]D%@m:49", at least before this phrase was pasted as an
2033 # example on the Internet.
2035 # For the procedures used at this site, a basic computer setup can
2036 # check in the order of a billion passwords per second. You need a
2037 # password (or phrase) strength in the order of 56 bits to be a
2038 # little secure (one year on a single computer). Please be so kind
2039 # and add the name of your favorite flower, dish, fictional
2040 # character, or small town to your password. Say, Oleander, Curry,
2041 # Sherlock, or Bath, UK (each adds ~12 bits) or even the phrase "Sherlock
2042 # investigates oleander curry in Bath" (adds > 56 bits, note that
2043 # oleander is poisonous, so do not try this curry at home). That
2044 # would be more effective than adding a thousand rounds of encryption.
2045 # Typing long passwords without seeing what you are typing is
2046 # problematic. So a button should be included to make password
2052 # Client side JavaScript code definitions. Variable names starting with '$'
2053 # are CGIscriptor CGI variables. Some of the hashes could be strengthened
2054 # by switching to HMAC signatures. However, the security issues of
2055 # maintaining parallel functions for HMAC in both Perl and Javascript seem
2056 # to be more serious than the attack vectors against the hashes. But HMAC
2057 # is indeed used for the ticket signatures.
2060 # HashPlaintextPassword() {
2061 # var plaintextpassword = document.getElementById('PASSWORD');
2062 # var serversalt = document.getElementById('SERVERSALT');
2063 # var username = document.getElementById('CGIUSERNAME');
2064 # return hex_sha256(plaintextpassword.value+username.value.toLowerCase()+serversalt.value);
2066 # var randomsalt = $RANDOMSALT; // From CGIscriptor
2067 # var loginticket = $LOGINTICKET; // From CGIscriptor
2068 # // Hash plaintext password
2069 # var password = HashPlaintextPassword();
2070 # // Authorize login
2071 # var hashedpassword = hex_sha256(randomsalt+password);
2073 # var sessionticket = hex_sha256(loginticket+password);
2074 # sessionStorage.setItem("CGIscriptorPRIVATE", sessionticket);
2075 # // Secretkey for encrypting new passwords, acts like a one-time pad
2076 # // Is set anew with every login, ie, also whith password changes
2077 # // and for each create new user request
2078 # var secretkey = hex_sha256(password+loginticket+randomsalt);
2079 # sessionStorage.setItem("CGIscriptorSECRET", secretkey);
2081 # // For a SESSION type request
2082 # sessionticket = sessionStorage.getItem("CGIscriptorPRIVATE");
2083 # createCookie("CGIscriptorSESSION",sessionticket, 0, "");
2085 // For a CHALLENGE type request
2086 # var sessionset = "$CHALLENGETICKET"; // From CGIscriptor
2087 # var sessionkey = sessionStorage.getItem("CGIscriptorPRIVATE");
2088 # sessionticket = hex_sha256(sessionset+sessionkey);
2089 # createCookie("CGIscriptorCHALLENGE",sessionticket, 0, "");
2091 # // For transmitting a new password
2092 # HashPlaintextNewPassword() {
2093 # var plaintextpassword = document.getElementById('NEWPASSWORD');
2094 # var serversalt = document.getElementById('SERVERSALT');
2095 # var username = document.getElementById('NEWUSERNAME');
2096 # return hex_sha256(plaintextpassword.value+username.value.toLowerCase()+serversalt.value);
2099 # var newpassword = document.getElementById('NEWPASSWORD');
2100 # var newpasswordrep = document.getElementById('NEWPASSWORDREP');
2101 # // Hash plaintext password
2102 # newpassword.value = HashPlaintextNewPassword();
2103 # var secretkey = sessionStorage.getItem("CGIscriptorSECRET");
2105 # var encrypted = XOR_hex_strings(secretkey, newpassword.value);
2106 # newpassword.value = encrypted;
2107 # newpasswordrep.value = encrypted;
2109 # // XOR of hexadecimal strings of equal length
2110 # function XOR_hex_strings(hex1, hex2) {
2111 # var resultHex = "";
2112 # var maxlength = Math.max(hex1.length, hex2.length);
2114 # for(var i=0; i < maxlength; ++i) {
2115 # var h1 = hex1.charAt(i);
2117 # var h2 = hex2.charAt(i);
2119 # var d1 = parseInt(h1,16);
2120 # var d2 = parseInt(h2,16);
2121 # var resultD = d1^d2;
2122 # resultHex = resultHex+resultD.toString(16);
2127 # Password encryption based on $ENV{'CGIMasterKey'}.
2128 # Server side Perl code:
2130 # # Password encryption
2131 # my $masterkey = $ENV{'CGIMasterKey'}
2132 # my $hash1 = hash_string($masterkey.$serversalt);
2133 # my $CryptKey = hash_string($username.$hash1);
2134 # $password = XOR_hex_strings($CryptKey,$password);
2136 # # Key for HMAC signing
2137 # my $hash1 = hash_string($masterkey.$serversalt);
2138 # my $HMACKey = hash_string($username.$hash1);
2144 # A CGIscriptor package is attached to the bottom of this file. With
2145 # this package you can personalize your version of CGIscriptor by
2146 # including often used perl routines. These subroutines can be
2147 # accessed by prefixing their names with CGIscriptor::, e.g.,
2148 # <SCRIPT LANGUAGE=PERL TYPE=text/ssperl>
2149 # CGIscriptor::ListDocs("/Books/*") # List all documents in /Books
2151 # It already contains some useful subroutines for Document Management.
2152 # As it is a separate package, it has its own namespace, isolated from
2153 # both the evaluator and the main program. To access variables from
2154 # the document <SCRIPT></SCRIPT> blocks, use $CGIexecute::<var>.
2156 # Currently, the following functions are implemented
2157 # (precede them with CGIscriptor::, see below for more information)
2158 # - SAFEqx ('String') -> result of qx/"String"/ # Safe application of ``-quotes
2159 # Is used by text/osshell Shell scripts. Protects all CGI
2160 # (client-supplied) values with single quotes before executing the
2161 # commands (one of the few functions that also works WITHOUT CGIscriptor::
2163 # - defineCGIvariable ($name[, $default) -> 0/1 (i.e., failure/success)
2164 # Is used by the META tag to define and initialize CGI and ENV
2165 # name/value pairs. Tries to obtain an initializing value from (in order):
2168 # The default value given (if any)
2169 # (one of the few functions that also works WITHOUT CGIscriptor::
2171 # - CGIsafeFileName (FileName) -> FileName or ""
2172 # Check a string against the Allowed File Characters (and ../ /..).
2173 # Returns an empty string for unsafe filenames.
2174 # - CGIsafeEmailAddress (Email) -> Email or ""
2175 # Check a string against correct email address pattern.
2176 # Returns an empty string for unsafe addresses.
2177 # - RedirectShellScript ('CommandString') -> FILEHANDLER or undef
2178 # Open a named PIPE for SAFEqx to receive ALL shell scripts
2179 # - URLdecode (URL encoded string) -> plain string # Decode URL encoded argument
2180 # - URLencode (plain string) -> URL encoded string # Encode argument as URL code
2181 # - CGIparseValue (ValueName [, URL_encoded_QueryString]) -> Decoded value
2182 # Extract the value of a CGI variable from the global or a private
2183 # URL-encoded query (multipart POST raw, NOT decoded)
2184 # - CGIparseValueList (ValueName [, URL_encoded_QueryString])
2185 # -> List of decoded values
2186 # As CGIparseValue, but now assembles ALL values of ValueName into a list.
2187 # - CGIparseHeader (ValueName [, URL_encoded_QueryString]) -> Header
2188 # Extract the header of a multipart CGI variable from the global or a private
2189 # URL-encoded query ("" when not a multipart variable or absent)
2190 # - CGIparseForm ([URL_encoded_QueryString]) -> Decoded Form
2191 # Decode the complete global URL-encoded query or a private
2193 # - read_url(URL) # Returns the page from URL (with added base tag, both FTP and HTTP)
2194 # Uses main::GET_URL(URL, 1) to get at the command to read the URL.
2195 # - BrowseDirs(RootDirectory [, Pattern, Startdir, CGIname]) # print browsable directories
2196 # - ListDocs(Pattern [,ListType]) # Prints a nested HTML directory listing of
2197 # all documents, e.g., ListDocs("/*", "dl");.
2198 # - HTMLdocTree(Pattern [,ListType]) # Prints a nested HTML listing of all
2199 # local links starting from a given document, e.g.,
2200 # HTMLdocTree("/Welcome.html", "dl");
2203 # THE RESULTS STACK: @CGISCRIPTORRESULTS
2205 # If the pseudo-variable "$CGIscriptorResults" has been defined in a
2206 # META tag, all subsequent SCRIPT and META results are pushed
2207 # on the @CGIscriptorResults stack. This list is just another
2208 # Perl variable and can be used and manipulated like any other list.
2209 # $CGIscriptorResults[-1] is always the last result.
2210 # This is only of limited use, e.g., to use the results of an OS shell
2211 # script inside a Perl script. Will NOT contain the results of Pipes
2212 # or code from MIME-profiling.
2215 # USEFULL CGI PREDEFINED VARIABLES (DO NOT ASSIGN TO THESE)
2217 # $CGI_HOME - The DocumentRoot directory
2218 # $CGI_Decoded_QS - The complete decoded Query String
2219 # $CGI_Content_Length - The ACTUAL length of the Query String
2220 # $CGI_Date - Current date and time
2221 # $CGI_Year $CGI_Month $CGI_Day $CGI_WeekDay - Current Date
2222 # $CGI_Time - Current Time
2223 # $CGI_Hour $CGI_Minutes $CGI_Seconds - Current Time, split
2225 # $CGI_GMTYear $CGI_GMTMonth $CGI_GMTDay $CGI_GMTWeekDay $CGI_GMTYearDay
2226 # $CGI_GMTHour $CGI_GMTMinutes $CGI_GMTSeconds $CGI_GMTisdst
2229 # USEFULL CGI ENVIRONMENT VARIABLES
2231 # Variables accessible (in APACHE) as $ENV{<name>}
2232 # (see: "http://hoohoo.ncsa.uiuc.edu/cgi/env.html"):
2234 # QUERY_STRING - The query part of URL, that is, everything that follows the
2236 # PATH_INFO - Extra path information given after the script name
2237 # PATH_TRANSLATED - Extra pathinfo translated through the rule system.
2238 # (This doesn't always make sense.)
2239 # REMOTE_USER - If the server supports user authentication, and the script is
2240 # protected, this is the username they have authenticated as.
2241 # REMOTE_HOST - The hostname making the request. If the server does not have
2242 # this information, it should set REMOTE_ADDR and leave this unset
2243 # REMOTE_ADDR - The IP address of the remote host making the request.
2244 # REMOTE_IDENT - If the HTTP server supports RFC 931 identification, then this
2245 # variable will be set to the remote user name retrieved from
2246 # the server. Usage of this variable should be limited to logging
2248 # AUTH_TYPE - If the server supports user authentication, and the script
2249 # is protected, this is the protocol-specific authentication
2250 # method used to validate the user.
2251 # CONTENT_TYPE - For queries which have attached information, such as HTTP
2252 # POST and PUT, this is the content type of the data.
2253 # CONTENT_LENGTH - The length of the said content as given by the client.
2254 # SERVER_SOFTWARE - The name and version of the information server software
2255 # answering the request (and running the gateway).
2256 # Format: name/version
2257 # SERVER_NAME - The server's hostname, DNS alias, or IP address as it
2258 # would appear in self-referencing URLs
2259 # GATEWAY_INTERFACE - The revision of the CGI specification to which this
2260 # server complies. Format: CGI/revision
2261 # SERVER_PROTOCOL - The name and revision of the information protocol this
2262 # request came in with. Format: protocol/revision
2263 # SERVER_PORT - The port number to which the request was sent.
2264 # REQUEST_METHOD - The method with which the request was made. For HTTP,
2265 # this is "GET", "HEAD", "POST", etc.
2266 # SCRIPT_NAME - A virtual path to the script being executed, used for
2267 # self-referencing URLs.
2268 # HTTP_ACCEPT - The MIME types which the client will accept, as given by
2269 # HTTP headers. Other protocols may need to get this
2270 # information from elsewhere. Each item in this list should
2271 # be separated by commas as per the HTTP spec.
2272 # Format: type/subtype, type/subtype
2273 # HTTP_USER_AGENT - The browser the client is using to send the request.
2274 # General format: software/version library/version.
2277 # INSTRUCTIONS FOR RUNNING CGIscriptor ON UNIX
2279 # CGIscriptor.pl will run on any WWW server that runs Perl scripts, just add
2280 # a line like the following to your srm.conf file (Apache example):
2282 # ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
2284 # URL's that refer to http://www.your.address/SHTML/... will now be handled
2285 # by CGIscriptor.pl, which can use a private directory tree (default is the
2286 # DOCUMENT_ROOT directory tree, but it can be anywhere, see manual).
2288 # If your hosting ISP won't let you add ScriptAlias lines you can use
2289 # the following "rewrite"-based "scriptalias" in .htaccess
2290 # (from Gerd Franke)
2294 # RewriteCond %{REQUEST_FILENAME} .html$
2295 # RewriteCond %{SCRIPT_FILENAME} !cgiscriptor.pl$
2296 # RewriteCond %{REQUEST_FILENAME} -f
2297 # RewriteRule ^(.*)$ /cgi-bin/cgiscriptor.pl/$1?&%{QUERY_STRING}
2299 # Everthing with the extension ".html" and not including "cgiscriptor.pl"
2300 # in the url and where the file "path/filename.html" exists is redirected
2301 # to "/cgi.bin/cgiscriptor.pl/path/filename.html?query".
2302 # The user configuration should get the same path-level as the
2305 # # Just enter your own directory path here
2306 # $YOUR_HTML_FILES = "$ENV{'DOCUMENT_ROOT'}";
2307 # # use DOCUMENT_ROOT only, if .htaccess lies in the root-directory.
2309 # If this .htaccess goes in a specific directory, the path to this
2310 # directory must be added to $ENV{'DOCUMENT_ROOT'}.
2312 # The CGIscriptor file contains all documentation as comments. These
2313 # comments can be removed to speed up loading (e.g., `egrep -v '^#'
2314 # CGIscriptor.pl` > leanScriptor.pl). A bare bones version of
2315 # CGIscriptor.pl, lacking documentation, most comments, access control,
2316 # example functions etc. (but still with the copyright notice and some
2317 # minimal documentation) can be obtained by calling CGIscriptor.pl on the
2318 # command line with the '-slim' command line argument, e.g.,
2320 # >CGIscriptor.pl -slim > slimCGIscriptor.pl
2322 # CGIscriptor.pl can be run from the command line with <path> and <query> as
2323 # arguments, as `CGIscriptor.pl <path> <query>`, inside a perl script
2324 # with 'do CGIscriptor.pl' after setting $ENV{PATH_INFO}
2325 # and $ENV{QUERY_STRING}, or CGIscriptor.pl can be loaded with 'require
2326 # "/real-path/CGIscriptor.pl"'. In the latter case, requests are processed
2327 # by 'Handle_Request();' (again after setting $ENV{PATH_INFO} and
2328 # $ENV{QUERY_STRING}).
2330 # Using the command line execution option, CGIscriptor.pl can be used as a
2331 # document (meta-)preprocessor. If the first argument is '-', STDIN will be read.
2334 # > cat MyDynamicDocument.html | CGIscriptor.pl - '[QueryString]' > MyStaticFile.html
2336 # This command line will produce a STATIC file with the DYNAMIC content of
2337 # MyDocument.html "interpolated".
2339 # This option would be very dangerous when available over the internet.
2340 # If someone could sneak a 'http://www.your.domain/-' URL past your
2341 # server, CGIscriptor could EXECUTE any POSTED contend.
2342 # Therefore, for security reasons, STDIN will NOT be read
2343 # if ANY of the HTTP server environment variables is set (e.g.,
2344 # SERVER_PORT, SERVER_PROTOCOL, SERVER_NAME, SERVER_SOFTWARE,
2345 # HTTP_USER_AGENT, REMOTE_ADDR).
2346 # This block on processing STDIN on HTTP requests can be lifted by setting
2347 # $BLOCK_STDIN_HTTP_REQUEST = 0;
2348 # In the security configuration. Butbe carefull when doing this.
2349 # It can be very dangerous.
2351 # Running demo's and more information can be found at
2352 # http://www.fon.hum.uva.nl/~rob/OSS/OSS.html
2354 # A pocket-size HTTP daemon, CGIservlet.pl, is available from my web site or
2355 # CPAN that can use CGIscriptor.pl as the base of a µWWW server and
2356 # demonstrates its use.
2359 # PROCESSING NON-FILESYSTEM DATA
2361 # Normally, HTTP (WWW) requests map onto file that can be accessed
2362 # using the perl open() function. That is, the web server runs on top of
2363 # some directory structure. However, we can envission (and put to good
2364 # use) other systems that do not use a normal file system. The whole CGI
2365 # was developed to make dynamic document generation possible.
2367 # A special case is where we want to have it both: A normal web server
2368 # with normal "file data", but not a normal files system. For instance,
2369 # we want or normal Web Site to run directly from a RAM hash table or
2370 # other database, instead of from disk. But we do NOT want to code the
2371 # whole site structure in CGI.
2373 # CGIscriptor can do this. If the web server fills an environment variable
2374 # $ENV{'CGI_FILE_CONTENT'} with the content of the "file", then the content
2375 # of this variable is processed instead of opening a file. If this environment
2376 # variable has the value '-', the content of another environment variable,
2377 # $ENV{'CGI_DATA_ACCESS_CODE'} is executed as:
2378 # eval("\@_ = ($file_path); do {$ENV{'CGI_DATA_ACCESS_CODE'}};")
2379 # and the result is processed as if it was the content of the requested
2381 # (actually, the names of the environment variables are user configurable,
2382 # they are stored in the local variables $CGI_FILE_CONTENT and
2383 # $CGI_DATA_ACCESS_CODE)
2385 # When using this mechanism, the SRC attribute mechanism will only partially work.
2386 # Only the "recursive" calls to CGIscriptor (the ProcessFile() function)
2387 # will work, the automagical execution of SRC files won't. (In this case,
2388 # the SRC attribute won't work either for other scripting languages)
2391 # NON-UNIX PLATFORMS
2393 # CGIscriptor.pl was mainly developed and tested on UNIX. However, as I
2394 # coded part of the time on an Apple Macintosh under MacPerl, I made sure
2395 # CGIscriptor did run under MacPerl (with command line options). But only
2396 # as an independend script, not as part of a HTTP server. I have used it
2397 # under Apache in Windows XP.
2402 ###############################################################################
2404 # SECURITY CONFIGURATION
2406 # Special configurations related to SECURITY
2407 # (i.e., optional, see also environment variables below)
2410 # Log Clients and the requested paths (Redundant when loging Queries)
2412 $ClientLog = "./Client.log"; # (uncomment for use)
2414 # Format: Localtime | REMOTE_USER REMOTE_IDENT REMOTE_HOST REMOTE_ADDRESS \
2415 # PATH_INFO CONTENT_LENGTH (actually, the real query+post length)
2417 # Log Clients and the queries, the CGIQUERYDECODE is required if you want
2418 # to log queries. If you log Queries, the loging of Clients is redundant
2419 # (note that queries can be quite long, so this might not be a good idea)
2421 #$QueryLog = "./Query.log"; # (uncomment for use)
2424 # the Access files should contain Hostnames or IP addresses,
2425 # i.e. REMOTE_HOST or REMOTE_ADDR, each on a separate line
2426 # optionally followed by one ore more file patterns, e.g., "edu /DEMO".
2427 # Matching is done "domain first". For example ".edu" matches all
2428 # clients whose "name" ends in ".edu" or ".EDU". The file pattern
2429 # "/DEMO" matches all paths that contain the strings "/DEMO" or "/demo"
2430 # (both matchings are done case-insensitive).
2431 # The name special symbol "-" matches ALL clients who do not supply a
2432 # REMOTE_HOST name, "*" matches all clients.
2433 # Lines starting with '-e' are evaluated. A non-zero return value indicates
2434 # a match. You can use $REMOTE_HOST, $REMOTE_ADDR, and $PATH_INFO. These
2435 # lines are evaluated in the program's own name-space. So DO NOT assign to
2438 # Accept the following users (remove comment # and adapt filename)
2439 $CGI_Accept = -s
"$YOUR_SCRIPTS/ACCEPT.lis" ?
"$YOUR_SCRIPTS/ACCEPT.lis" : ''; # (uncomment for use)
2441 # Reject requests from the following users (remove comment # and
2442 # adapt filename, this is only of limited use)
2443 $CGI_Reject = -s
"$YOUR_SCRIPTS/REJECT.lis" ?
"$YOUR_SCRIPTS/REJECT.lis" : ''; # (uncomment for use)
2445 # Empty lines or comment lines starting with '#' are ignored in both
2446 # $CGI_Accept and $CGI_Reject.
2448 # Block STDIN (i.e., '-') requests when servicing an HTTP request
2449 # Comment this out if you realy want to use STDIN in an on-line web server
2450 $BLOCK_STDIN_HTTP_REQUEST = 1;
2453 # End of security configuration
2455 ##################################################<<<<<<<<<<End Remove
2457 # PARSING CGI VALUES FROM THE QUERY STRING (USER CONFIGURABLE)
2459 # The CGI parse commands. These commands extract the values of the
2460 # CGI variables from the URL encoded Query String.
2461 # If you want to use your own CGI decoders, you can call them here
2462 # instead, using your own PATH and commenting/uncommenting the
2465 # CGI parse command for individual values
2466 # (if $List > 0, returns a list value, if $List < 0, a hash table, this is optional)
2467 sub YOUR_CGIPARSE
# ($Name [, $List]) -> Decoded value
2470 my $List = shift || 0;
2471 # Use one of the following by uncommenting
2472 if(!$List) # Simple value
2474 return CGIscriptor
::CGIparseValue
($Name) ;
2476 elsif($List < 0) # Hash tables
2478 return CGIscriptor
::CGIparseValueHash
($Name); # Defined in CGIscriptor below
2482 return CGIscriptor
::CGIparseValueList
($Name); # Defined in CGIscriptor below
2485 # return `/PATH/cgiparse -value $Name`; # Shell commands
2486 # require "/PATH/cgiparse.pl"; return cgivalue($Name); # Library
2489 sub YOUR_CGIQUERYDECODE
2491 # Use one of the following by uncommenting
2492 return CGIscriptor
::CGIparseForm
(); # Defined in CGIscriptor below
2493 # return `/PATH/cgiparse -form`; # Shell commands
2494 # require "/PATH/cgiparse.pl"; return cgiform(); # Library
2497 # End of configuration
2499 #######################################################################
2501 # Translating input files.
2502 # Allows general and global conversions of files using Regular Expressions
2503 # Translations are applied in the order of definition.
2506 # my $TranslationPaths = 'pattern'; # Pattern matching PATH_INFO
2508 # push(@TranslationTable, ['pattern', 'replacement']);
2509 # e.g. (for Ruby Rails):
2510 # push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2511 # push(@TranslationTable, ['%>', '</SCRIPT>']);
2514 # my $currentRegExp;
2515 # foreach $currentRegExp (keys(%TranslationTable))
2517 # my $currentRegExp;
2518 # foreach $currentRegExp (@TranslationTable)
2520 # my ($pattern, $replacement) = @$currentRegExp;
2521 # $$text =~ s!$pattern!$replacement!msg;
2525 # Configuration section
2527 #######################################################################
2529 # The file paths on which to apply the translation
2530 my $TranslationPaths = ''; # NO files
2531 #$TranslationPaths = '.'; # ANY file
2532 # $TranslationPaths = '\.html'; # HTML files
2534 my @TranslationTable = ();
2536 push(@TranslationTable, ['\<\s*CGI\s+([^\>])*\>', '\<SCRIPT TYPE=\"text/ssperl\"\>$1\<\/SCRIPT>']);
2538 push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2539 push(@TranslationTable, ['%>', '</SCRIPT>']);
2541 sub performTranslation
# (\$text)
2543 my $text = shift || return;
2544 if(@TranslationTable && $TranslationPaths && $ENV{'PATH_INFO'} =~ m!$TranslationPaths!)
2547 foreach $currentRegExp (@TranslationTable)
2549 my ($pattern, $replacement) = @
$currentRegExp;
2550 $$text =~ s!$pattern!$replacement!msg;
2555 #######################################################################
2557 # Seamless access to other (Scripting) Languages
2558 # TYPE='text/ss<interpreter>'
2560 # Configuration section
2562 #######################################################################
2564 # OTHER SCRIPTING LANGUAGES AT THE SERVER SIDE (MIME => OScommand)
2565 # Yes, it realy is this simple! (unbelievable, isn't it)
2566 # NOTE: Some interpreters require some filtering to obtain "clean" output
2568 %ScriptingLanguages = (
2569 "text/testperl" => 'perl', # Perl for testing
2570 "text/sspython" => 'python', # Python
2571 "text/ssruby" => 'ruby', # Ruby
2572 "text/sstcl" => 'tcl', # TCL
2573 "text/ssawk" => 'awk -f-', # Awk
2574 "text/sslisp" => # lisp (rep, GNU)
2575 'rep | tail +4 '."| egrep -v '> |^rep. |^nil\\\$'",
2576 "text/xlispstat" => # xlispstat
2577 'xlispstat | tail +7 ' ."| egrep -v '> \\\$|^NIL'",
2578 "text/ssprolog" => # Prolog (GNU)
2579 "gprolog | tail +4 | sed 's/^| ?- //'",
2580 "text/ssm4" => 'm4', # M4 macro's
2581 "text/sh" => 'sh', # Born shell
2582 "text/bash" => 'bash', # Born again shell
2583 "text/csh" => 'csh', # C shell
2584 "text/ksh" => 'ksh', # Korn shell
2585 "text/sspraat" => # Praat (sound/speech analysis)
2586 "praat - | sed 's/Praat > //g'",
2588 "R --vanilla --slave | sed 's/^[\[0-9\]*] //'",
2589 "text/ssrebol" => # REBOL
2590 "rebol --quiet|egrep -v '^[> ]* == '|sed 's/^\\s*\[> \]* //'",
2591 "text/postgresql" => 'psql 2>/dev/null',
2593 # Not real scripting, but the use of other applications
2594 "text/ssmailto" => "awk 'NF||F{F=1;print \\\$0;}'|mailto >/dev/null", # Send mail from server
2595 "text/ssdisplay" => 'cat', # Display, (interpolation)
2596 "text/sslogfile" => # Log to file, (interpolation)
2597 "awk 'NF||L {if(!L){L=tolower(\\\$1)~/^file:\\\$/ ? \\\$2 : \\\$1;}else{print \\\$0 >> L;};}'",
2602 # To be able to access the CGI variables in your script, they
2603 # should be passed to the scripting language in a readable form
2604 # Here you can enter how they should be printed (the first %s
2605 # is replaced by the NAME of the CGI variable as it apears in the
2606 # META tag, the second by its VALUE).
2607 # For Perl this would be:
2608 # "text/testperl" => '$%s = "%s";',
2609 # which would be executed as
2610 # printf('$%s = "%s";', $CGI_NAME, $CGI_VALUE);
2612 # If the hash table value doesn't exist, nothing is done
2613 # (you have to parse the Environment variables yourself).
2614 # If it DOES exist but is empty (e.g., "text/sspraat" => '',)
2615 # Perl string interpolation of variables (i.e., $var, @array,
2616 # %hash) is performed. This means that $@%\ must be protected
2619 %ScriptingCGIvariables = (
2620 "text/testperl" => "\$\%s = '\%s';", # Perl $VAR = 'value'; (for testing)
2621 "text/sspython" => "\%s = '\%s'", # Python VAR = 'value'
2622 "text/ssruby" => '@%s = "%s"', # Ruby @VAR = 'value'
2623 "text/sstcl" => 'set %s "%s"', # TCL set VAR "value"
2624 "text/ssawk" => '%s = "%s";', # Awk VAR = 'value';
2625 "text/sslisp" => '(setq %s "%s")', # Gnu lisp (rep) (setq VAR "value")
2626 "text/xlispstat" => '(setq %s "%s")', # xlispstat (setq VAR "value")
2627 "text/ssprolog" => '', # Gnu prolog (interpolated)
2628 "text/ssm4" => "define(`\%s', `\%s')", # M4 macro's define(`VAR', `value')
2629 "text/sh" => "\%s='\%s'", # Born shell VAR='value'
2630 "text/bash" => "\%s='\%s'", # Born again shell VAR='value'
2631 "text/csh" => "\$\%s='\%s';", # C shell $VAR = 'value';
2632 "text/ksh" => "\$\%s='\%s';", # Korn shell $VAR = 'value';
2634 "text/ssrebol" => '%s: copy "%s"', # REBOL VAR: copy "value"
2635 "text/sspraat" => '', # Praat (interpolation)
2636 "text/ssr" => '%s <- "%s";', # R VAR <- "value";
2637 "text/postgresql" => '', # PostgreSQL (interpolation)
2639 # Not real scripting, but the use of other applications
2640 "text/ssmailto" => '', # MAILTO, (interpolation)
2641 "text/ssdisplay" => '', # Display, (interpolation)
2642 "text/sslogfile" => '', # Log to file, (interpolation)
2647 # If you want something added in front or at the back of each script
2648 # block as send to the interpreter add it here.
2649 # mime => "string", e.g., "text/sspython" => "python commands"
2650 %ScriptingPrefix = (
2651 "text/testperl" => "\# Prefix Code;", # Perl script testing
2652 "text/ssm4" => 'divert(0)', # M4 macro's (open STDOUT)
2656 # If you want something added at the end of each script block
2657 %ScriptingPostfix = (
2658 "text/testperl" => "\# Postfix Code;", # Perl script testing
2659 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2663 # If you need initialization code, directly after opening
2664 %ScriptingInitialization = (
2665 "text/testperl" => "\# Initialization Code;", # Perl script testing
2666 "text/ssawk" => 'BEGIN {', # Server Side awk scripts (VAR = "value")
2667 "text/sslisp" => '(prog1 nil ', # Lisp (rep)
2668 "text/xlispstat" => '(prog1 nil ', # xlispstat
2669 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2673 # If you need cleanup code before closing
2674 %ScriptingCleanup = (
2675 "text/testperl" => "\# Cleanup Code;", # Perl script testing
2676 "text/sspraat" => 'Quit',
2677 "text/ssawk" => '};', # Server Side awk scripts (VAR = "value")
2678 "text/sslisp" => '(princ "\n" standard-output)).', # Closing print to rep
2679 "text/xlispstat" => '(print ""))', # Closing print to xlispstat
2680 "text/postgresql" => '\q', # quit psql
2681 "text/ssdisplay" => "", # close cat
2686 # End of configuration for foreign scripting languages
2688 ###############################################################################
2690 # Initialization Code
2693 sub Initialize_Request
2695 ###############################################################################
2697 # ENVIRONMENT VARIABLES
2699 # Use environment variables to configure CGIscriptor on a temporary basis.
2700 # If you define any of the configurable variables as environment variables,
2701 # these are used instead of the "hard coded" values above.
2703 $SS_PUB = $ENV{'SS_PUB'} || $YOUR_HTML_FILES;
2704 $SS_SCRIPT = $ENV{'SS_SCRIPT'} || $YOUR_SCRIPTS;
2707 # Substitution strings, these are used internally to handle the
2708 # directory separator strings, e.g., '~/' -> 'SS_PUB:' (Mac)
2709 $HOME_SUB = $SS_PUB;
2710 $SCRIPT_SUB = $SS_SCRIPT;
2713 # Make sure all script are reliably loaded
2714 push(@INC, $SS_SCRIPT);
2717 # Add the directory separator to the "home" directories.
2718 # (This is required for ~/ and ./ substitution)
2719 $HOME_SUB .= '/' if $HOME_SUB;
2720 $SCRIPT_SUB .= '/' if $SCRIPT_SUB;
2722 $CGI_HOME = $ENV{'DOCUMENT_ROOT'};
2723 $ENV{'PATH_TRANSLATED'} =~ /$ENV{'PATH_INFO'}/is;
2724 $CGI_HOME = $` unless $ENV{'DOCUMENT_ROOT'}; # Get the DOCUMENT_ROOT directory
2725 $default_values{'CGI_HOME'} = $CGI_HOME;
2726 $ENV{'HOME'} = $CGI_HOME;
2727 # Set SS_PUB and SS_SCRIPT as Environment variables (make them available
2729 $ENV{'SS_PUB'} = $SS_PUB unless $ENV{'SS_PUB'};
2730 $ENV{'SS_SCRIPT'} = $SS_SCRIPT unless $ENV{'SS_SCRIPT'};
2732 $FilePattern = $ENV{'FilePattern'} || $FilePattern;
2733 $MaximumQuerySize = $ENV{'MaximumQuerySize'} || $MaximumQuerySize;
2734 $ClientLog = $ENV{'ClientLog'} || $ClientLog;
2735 $QueryLog = $ENV{'QueryLog'} || $QueryLog;
2736 $CGI_Accept = $ENV{'CGI_Accept'} || $CGI_Accept;
2737 $CGI_Reject = $ENV{'CGI_Reject'} || $CGI_Reject;
2740 $CGI_Accept =~ s@^\~/@$HOME_SUB@g if $CGI_Accept;
2741 $CGI_Reject =~ s@^\~/@$HOME_SUB@g if $CGI_Reject;
2742 $ClientLog =~ s@^\~/@$HOME_SUB@g if $ClientLog;
2743 $QueryLog =~ s@^\~/@$HOME_SUB@g if $QueryLog;
2745 $CGI_Accept =~ s@^\./@$SCRIPT_SUB@g if $CGI_Accept;
2746 $CGI_Reject =~ s@^\./@$SCRIPT_SUB@g if $CGI_Reject;
2747 $ClientLog =~ s@^\./@$SCRIPT_SUB@g if $ClientLog;
2748 $QueryLog =~ s@^\./@$SCRIPT_SUB@g if $QueryLog;
2750 @CGIscriptorResults = (); # A stack of results
2752 # end of Environment variables
2754 #############################################################################
2756 # Define and Store "standard" values
2758 # BEFORE doing ANYTHING check the size of Query String
2759 length($ENV{'QUERY_STRING'}) <= $MaximumQuerySize || dieHandler(2, "QUERY TOO LONG\n");
2761 # The Translated Query String and the Actual length of the (decoded)
2763 if($ENV{'QUERY_STRING'})
2765 # If this can contain '`"-quotes, be carefull to use it QUOTED
2766 $default_values{CGI_Decoded_QS} = YOUR_CGIQUERYDECODE();
2767 $default_values{CGI_Content_Length} = length($default_values{CGI_Decoded_QS});
2770 # Get the current Date and time and store them as default variables
2773 $LocalTime = localtime;
2775 # CGI_Year CGI_Month CGI_Day CGI_WeekDay CGI_Time
2776 # CGI_Hour CGI_Minutes CGI_Seconds
2778 $default_values{CGI_Date} = $LocalTime;
2779 ($default_values{CGI_WeekDay},
2780 $default_values{CGI_Month},
2781 $default_values{CGI_Day},
2782 $default_values{CGI_Time},
2783 $default_values{CGI_Year}) = split(' ', $LocalTime);
2784 ($default_values{CGI_Hour},
2785 $default_values{CGI_Minutes},
2786 $default_values{CGI_Seconds}) = split(':', $default_values{CGI_Time});
2789 # CGI_GMTYear CGI_GMTMonth CGI_GMTDay CGI_GMTWeekDay CGI_GMTYearDay
2790 # CGI_GMTHour CGI_GMTMinutes CGI_GMTSeconds CGI_GMTisdst
2792 ($default_values{CGI_GMTSeconds},
2793 $default_values{CGI_GMTMinutes},
2794 $default_values{CGI_GMTHour},
2795 $default_values{CGI_GMTDay},
2796 $default_values{CGI_GMTMonth},
2797 $default_values{CGI_GMTYear},
2798 $default_values{CGI_GMTWeekDay},
2799 $default_values{CGI_GMTYearDay},
2800 $default_values{CGI_GMTisdst}) = gmtime;
2804 # End of Initialize Request
2806 ###################################################################
2808 # SECURITY: ACCESS CONTROL
2810 # Check the credentials of each client (use pattern matching, domain first).
2811 # This subroutine will kill-off (die) the current process whenever access
2816 # >>>>>>>>>>Start Remove
2820 # Only accept clients which are authorized, reject all unnamed clients
2821 # if REMOTE_HOST is given.
2822 # If file patterns are given, check whether the user is authorized for
2826 # Use local variables, REMOTE_HOST becomes '-' if undefined
2827 my $REMOTE_HOST = $ENV{REMOTE_HOST} || '-';
2828 my $REMOTE_ADDR = $ENV{REMOTE_ADDR};
2829 my $PATH_INFO = $ENV{'PATH_INFO'};
2831 open(CGI_Accept, "<$CGI_Accept") || dieHandler(3, "$CGI_Accept: $!\n");
2835 next unless /\S/; # Skip empty lines
2836 next if /^\s*\#/; # Skip comments
2841 my $Accept = $'; # Get the expression
2842 $NoAccess &&= eval($Accept); # evaluate the expresion
2846 my ($Accept, @FilePatternList) = split;
2847 if($Accept eq '*' # Always match
2848 ||$REMOTE_HOST =~ /\Q$Accept\E$/is # REMOTE_HOST matches
2850 $Accept =~ /^[0-9\.]+$/
2851 && $REMOTE_ADDR =~ /^\Q$Accept\E/ # IP address matches
2855 if($FilePatternList[0])
2857 foreach $Pattern (@FilePatternList)
2859 # Check whether this patterns is accepted
2860 $NoAccess &&= ($PATH_INFO !~ m@\Q$Pattern\E@is);
2865 $NoAccess = 0; # No file patterns -> Accepted
2870 last unless $NoAccess;
2873 if($NoAccess){ dieHandler(4, "No Access
: $PATH_INFO\n");};
2879 # Reject named clients, accept all unnamed clients
2882 # Use local variables, REMOTE_HOST becomes '-' if undefined
2883 my $REMOTE_HOST = $ENV{'REMOTE_HOST'} || '-';
2884 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
2885 my $PATH_INFO = $ENV{'PATH_INFO'};
2887 open(CGI_Reject, "<$CGI_Reject") || dieHandler(5, "$CGI_Reject: $!\n");
2891 next unless /\S/; # Skip empty lines
2892 next if /^\s*\#/; # Skip comments
2897 my $Reject = $'; # Get the expression
2898 $NoAccess ||= eval($Reject); # evaluate the expresion
2902 my ($Reject, @FilePatternList) = split;
2903 if($Reject eq '*' # Always match
2904 ||$REMOTE_HOST =~ /\Q$Reject\E$/is # REMOTE_HOST matches
2905 ||($Reject =~ /^[0-9\.]+$/
2906 && $REMOTE_ADDR =~ /^\Q$Reject\E/is # IP address matches
2910 if($FilePatternList[0])
2912 foreach $Pattern (@FilePatternList)
2914 $NoAccess ||= ($PATH_INFO =~ m@\Q$Pattern\E@is);
2919 $NoAccess = 1; # No file patterns -> Rejected
2926 if($NoAccess){ dieHandler(6, "Request rejected
: $PATH_INFO\n");};
2929 ##########################################################<<<<<<<<<<End Remove
2934 # Does the filename contain any illegal characters (e.g., |, >, or <)
2935 dieHandler(7, "Illegal request
: $ENV{'PATH_INFO'}\n") if $ENV{'PATH_INFO'} =~ /[^$FileAllowedChars]/;
2936 # Does the pathname contain an illegal (blocked) "directory
"
2937 dieHandler(8, "Illegal request
: $ENV{'PATH_INFO'}\n") if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@; # Access is blocked
2938 # Does the pathname contain a direct referencer to BinaryMapFile
2939 dieHandler(9, "Illegal request
: $ENV{'PATH_INFO'}\n") if $BinaryMapFile && $ENV{'PATH_INFO'} =~ m@\Q$BinaryMapFile\E@; # Access is blocked
2941 # SECURITY: Is PATH_INFO allowed?
2942 if($FilePattern && $ENV{'PATH_INFO'} && $ENV{'PATH_INFO'} ne '-' &&
2943 ($ENV{'PATH_INFO'} !~ m@($FilePattern)$@is))
2945 # Unsupported file types can be processed by a special raw-file
2948 $ENV{'CGI_BINARY_FILE'} = $ENV{'PATH_INFO'};
2949 $ENV{'PATH_INFO'} = $BinaryMapFile;
2953 dieHandler(10, "Illegal file
\n");
2959 # End of Security Access Control
2962 ############################################################################
2964 # Get the POST part of the query and add it to the QUERY_STRING.
2967 sub Get_POST_part_of_query
2970 # If POST, Read data from stdin to QUERY_STRING
2971 if($ENV{'REQUEST_METHOD'} =~ /POST/is)
2973 # SECURITY: Check size of Query String
2974 $ENV{'CONTENT_LENGTH'} <= $MaximumQuerySize || dieHandler
(11, "Query too long: $ENV{'CONTENT_LENGTH'}\n"); # Query too long
2976 my $SystemRead = $ENV{'CONTENT_LENGTH'};
2977 $ENV{'QUERY_STRING'} .= '&' if length($ENV{'QUERY_STRING'}) > 0;
2978 while($SystemRead > 0)
2980 $QueryRead = sysread(STDIN
, $Post, $SystemRead); # Limit length
2981 $ENV{'QUERY_STRING'} .= $Post;
2982 $SystemRead -= $QueryRead;
2984 # Update decoded Query String
2985 $default_values{CGI_Decoded_QS
} = YOUR_CGIQUERYDECODE
();
2986 $default_values{CGI_Content_Length
} =
2987 length($default_values{CGI_Decoded_QS
});
2991 # End of getting POST part of query
2994 ############################################################################
2996 # Start (HTML) output and logging
2997 # (if there are irregularities, it can kill the current process)
3000 sub Initialize_output
3002 # Construct the REAL file path (except for STDIN on the command line)
3003 my $file_path = $ENV{'PATH_INFO'} ne '-' ?
$SS_PUB . $ENV{'PATH_INFO'} : '-';
3004 $file_path =~ s/\?.*$//; # Remove query
3005 # This is only necessary if your server does not catch ../ directives
3006 $file_path !~ m@\
.\
./@ || dieHandler(12, "Illegal ../ Construct
\n"); # SECURITY: Do not allow ../ constructs
3008 # Block STDIN use (-) if CGIscriptor is servicing a HTTP request
3009 if($file_path eq '-')
3011 dieHandler(13, "STDIN request
in On Line
system\n") if $BLOCK_STDIN_HTTP_REQUEST
3012 && ($ENV{'SERVER_SOFTWARE'}
3013 || $ENV{'SERVER_NAME'}
3014 || $ENV{'GATEWAY_INTERFACE'}
3015 || $ENV{'SERVER_PROTOCOL'}
3016 || $ENV{'SERVER_PORT'}
3017 || $ENV{'REMOTE_ADDR'}
3018 || $ENV{'HTTP_USER_AGENT'});
3025 open(ClientLog, ">>$ClientLog");
3026 print ClientLog "$LocalTime | ",
3027 ($ENV{REMOTE_USER} || "-"), " ",
3028 ($ENV{REMOTE_IDENT} || "-"), " ",
3029 ($ENV{REMOTE_HOST} || "-"), " ",
3030 $ENV{REMOTE_ADDR}, " ",
3031 $ENV{PATH_INFO}, " ",
3032 $ENV{'CGI_BINARY_FILE'}, " ",
3033 ($default_values{CGI_Content_Length} || "-"),
3039 open(QueryLog, ">>$QueryLog");
3040 print QueryLog "$LocalTime\n",
3041 ($ENV{REMOTE_USER} || "-"), " ",
3042 ($ENV{REMOTE_IDENT} || "-"), " ",
3043 ($ENV{REMOTE_HOST} || "-"), " ",
3044 $ENV{REMOTE_ADDR}, ": ",
3045 $ENV{PATH_INFO}, " ",
3046 $ENV{'CGI_BINARY_FILE'}, "\n";
3048 # Write Query to Log file
3049 print QueryLog $default_values{CGI_Decoded_QS}, "\n\n";
3053 # Return the file path
3057 # End of Initialize output
3060 ############################################################################
3062 # Handle login access
3064 # Access is based on a valid session ticket.
3065 # Session tickets should be dependend on user name
3066 # and IP address. The patterns of URLs for which a
3067 # session ticket is needed and the login URL are stored in
3068 # %TicketRequiredPatterns as:
3069 # 'RegEx pattern' -> 'SessionPath\tPasswordPath\tLogin URL\tExpiration'
3072 sub Log_In_Access # () -> 0 = Access Allowed, Login page if access is not allowed
3074 # No patterns, no login
3075 goto Return unless %TicketRequiredPatterns;
3077 # Get and initialize values (watch out for stuff processed by BinaryMap files)
3078 my ($SessionPath, $PasswordsPath, $Login, $valid_duration) = ("", "", "", 0);
3079 my $PATH_INFO = $ENV{'CGI_BINARY_FILE'} ? $ENV{'CGI_BINARY_FILE'} : $ENV{'PATH_INFO'};
3080 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
3081 goto Return if $REMOTE_ADDR =~ /[^0-9\.]/;
3082 # Extract TICKETs, starting with returned cookies
3083 CGIexecute::defineCGIvariable('LOGINTICKET', "");
3084 CGIexecute::defineCGIvariable('SESSIONTICKET', "");
3085 CGIexecute::defineCGIvariable('CHALLENGETICKET', "");
3086 if($ENV{'COOKIE_JAR'})
3088 my $CurrentCookieJar = $ENV{'COOKIE_JAR'};
3089 $CurrentCookieJar =~ s/\w+\=\-\s*(\;\s*|$)//isg;
3090 if($CurrentCookieJar =~ /\s*CGIscriptorLOGIN\=\s*([^\;]+)/)
3092 ${"CGIexecute
::LOGINTICKET
"} = $1;
3094 if($CurrentCookieJar =~ /\s*CGIscriptorCHALLENGE\=\s*([^\;]+)/ && $1 ne '-')
3096 ${"CGIexecute
::CHALLENGETICKET
"} = $1;
3098 if($CurrentCookieJar =~ /\s*CGIscriptorSESSION\=\s*([^\;]+)/ && $1 ne '-')
3100 ${"CGIexecute
::SESSIONTICKET
"} = $1;
3103 # Get and check the tickets. Tickets are restricted to word-characters (alphanumeric+_+.)
3104 my $LOGINTICKET = ${"CGIexecute
::LOGINTICKET
"};
3105 goto Return if ($LOGINTICKET && $LOGINTICKET =~ /[^\w\.]/isg);
3106 my $SESSIONTICKET = ${"CGIexecute
::SESSIONTICKET
"};
3107 goto Return if ($SESSIONTICKET && $SESSIONTICKET =~ /[^\w\.]/isg);
3108 my $CHALLENGETICKET = ${"CGIexecute
::CHALLENGETICKET
"};
3109 goto Return if ($CHALLENGETICKET && $CHALLENGETICKET =~ /[^\w\.]/isg);
3110 # Look for a LOGOUT message
3111 my $LOGOUT = $ENV{QUERY_STRING} =~ /(^|\&)LOGOUT([\=\&]|$)/;
3112 # Username and password
3113 CGIexecute::defineCGIvariable('CGIUSERNAME', "");
3114 my $username = lc(${"CGIexecute
::CGIUSERNAME
"});
3115 goto Return if $username =~ m!^[^\w]!isg || $username =~ m![^\w \-]!isg;
3116 my $userfile = lc($username);
3117 $userfile =~ s/[^\w]/_/isg;
3118 CGIexecute::defineCGIvariable('PASSWORD', "");
3119 my $password = ${"CGIexecute
::PASSWORD
"};
3120 CGIexecute::defineCGIvariable('NEWUSERNAME', "");
3121 my $newuser = lc(${"CGIexecute
::NEWUSERNAME
"});
3122 CGIexecute::defineCGIvariable('NEWPASSWORD', "");
3123 my $newpassword = ${"CGIexecute
::NEWPASSWORD
"};
3125 foreach my $pattern (keys(%TicketRequiredPatterns))
3127 # Check BOTH the real PATH_INFO and the CGI_BINARY_FILE variable
3128 if($ENV{'PATH_INFO'} =~ m#$pattern# || $ENV{'CGI_BINARY_FILE'} =~ m#$pattern#)
3130 # Fall through a sieve of requirements
3131 ($SessionPath, $PasswordsPath, $Login, $validtime) = split(/\t/, $TicketRequiredPatterns{$pattern});
3132 # If a LOGOUT is present, remove everything
3133 if($LOGOUT && !$LOGINTICKET)
3135 unlink "$SessionPath/$LOGINTICKET" if $LOGINTICKET && (-s "$SessionPath/$LOGINTICKET");
3137 unlink "$SessionPath/$SESSIONTICKET" if $SESSIONTICKET && (-s "$SessionPath/$SESSIONTICKET");
3138 $SESSIONTICKET = "";
3139 unlink "$SessionPath/$CHALLENGETICKET" if $CHALLENGETICKET && (-s "$SessionPath/$CHALLENGETICKET");
3140 $CHALLENGETICKET = "";
3141 unlink "$SessionPath/$REMOTE_ADDR" if (-s "$SessionPath/$REMOTE_ADDR");
3142 $CHALLENGETICKET = "";
3145 # Is there a change password request?
3146 if($newuser && $LOGINTICKET && $username)
3148 goto Login unless (-s "$SessionPath/$LOGINTICKET");
3149 goto Login unless (-s "$PasswordsPath/$userfile");
3150 my $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3151 goto Login unless $ticket_valid;
3152 $ticket_valid = check_ticket_validity("LOGIN
", "$SessionPath/$LOGINTICKET", $REMOTE_ADDR, ".", 1);
3153 goto Login unless $ticket_valid;
3155 my ($sessiontype, $currentticket) = ("", "");
3156 if($CHALLENGETICKET) {($sessiontype, $currentticket) = ("CHALLENGE
", $CHALLENGETICKET);}
3157 elsif($SESSIONTICKET) {($sessiontype, $currentticket) = ("SESSION
", $SESSIONTICKET);}
3158 elsif(-s "$SessionPath/$REMOTE_ADDR") {($sessiontype, $currentticket) = ("IPADDRESS
", $REMOTE_ADDR);
3162 goto Login unless (-s "$SessionPath/$currentticket");
3163 my $ticket_valid = check_ticket_validity($sessiontype, "$SessionPath/$currentticket", $REMOTE_ADDR, $PATH_INFO);
3164 goto Login unless $ticket_valid;
3167 my $TMPTICKET = authorize_login("$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $password, $SessionPath);
3168 goto Login unless $TMPTICKET;
3170 # Create a new user account
3171 CGIexecute::defineCGIvariable('NEWSESSION', "");
3172 my $newsession = ${"CGIexecute
::NEWSESSION
"};
3173 my $newaccount = create_newuser("$SessionPath/$LOGINTICKET", "$SessionPath/$currentticket",
3174 "$PasswordsPath/$userfile", $password, $newuser, $newpassword, $newsession);
3175 CGIexecute::defineCGIvariable('NEWACCOUNTTEXT', $newaccount);
3176 ${CGIexecute::NEWACCOUNTTEXT} = $newaccount;
3177 # NEWACCOUNTTEXT is NOT to be set by the query
3178 CGIexecute::ProtectCGIvariable('NEWACCOUNTTEXT');
3184 # Is there a change password request?
3185 elsif($newpassword && $LOGINTICKET && $username)
3187 goto Login unless (-s "$SessionPath/$LOGINTICKET");
3188 goto Login unless (-s "$PasswordsPath/$userfile");
3189 my $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3190 goto Login unless $ticket_valid;
3191 $ticket_valid = check_ticket_validity("LOGIN
", "$SessionPath/$LOGINTICKET", $REMOTE_ADDR, ".", 1);
3192 goto Login unless $ticket_valid;
3194 my ($sessiontype, $currentticket) = ("", "");
3195 if($CHALLENGETICKET) {($sessiontype, $currentticket) = ("CHALLENGE
", $CHALLENGETICKET);}
3196 elsif($SESSIONTICKET) {($sessiontype, $currentticket) = ("SESSION
", $SESSIONTICKET);}
3197 elsif(-s "$SessionPath/$REMOTE_ADDR") {($sessiontype, $currentticket) = ("IPADDRESS
", $REMOTE_ADDR);
3201 goto Login unless (-s "$SessionPath/$currentticket");
3202 my $ticket_valid = check_ticket_validity($sessiontype, "$SessionPath/$currentticket", $REMOTE_ADDR, $PATH_INFO);
3203 goto Login unless $ticket_valid;
3206 change_password("$SessionPath/$LOGINTICKET", "$SessionPath/$currentticket", "$PasswordsPath/$userfile", $password, $newpassword);
3207 # After a change of password, you have to login again for a CHALLENGE
3208 if($CHALLENGETICKET){$CHALLENGETICKET = "";};
3212 # Is there a login ticket of this name?
3215 my $tickets_removed = remove_expired_tickets($SessionPath);
3216 goto Login unless (-s "$SessionPath/$LOGINTICKET");
3217 goto Login unless (-s "$PasswordsPath/$userfile");
3218 my $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3219 goto Login unless $ticket_valid;
3220 $ticket_valid = check_ticket_validity("LOGIN
", "$SessionPath/$LOGINTICKET", $REMOTE_ADDR, ".");
3221 goto Login unless $ticket_valid;
3223 # Remove any lingering tickets
3224 unlink "$SessionPath/$SESSIONTICKET" if $SESSIONTICKET && (-s "$SessionPath/$SESSIONTICKET");
3225 $SESSIONTICKET = "";
3226 unlink "$SessionPath/$CHALLENGETICKET" if $CHALLENGETICKET && (-s "$SessionPath/$CHALLENGETICKET");
3227 $CHALLENGETICKET = "";
3231 my $TMPTICKET = authorize_login("$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $password, $SessionPath);
3234 my $authorization = read_ticket("$PasswordsPath/$userfile");
3235 goto Login unless $authorization;
3236 # Session type is read from the userfile
3237 if($authorization->{"Session
"} && $authorization->{"Session
"}->[0] eq "CHALLENGE
")
3239 # Create New Random CHALLENGETICKET
3240 $CHALLENGETICKET = $TMPTICKET;
3241 create_session_file("$SessionPath/$CHALLENGETICKET", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
3243 elsif($authorization->{"Session
"} && $authorization->{"Session
"}->[0] eq "IPADDRESS
")
3245 create_session_file("$SessionPath/$REMOTE_ADDR", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
3249 $SESSIONTICKET = $TMPTICKET;
3250 create_session_file("$SessionPath/$SESSIONTICKET", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
3251 $SETCOOKIELIST{"CGIscriptorSESSION
"} = "-";
3254 # Login ticket file has been used, remove it
3257 # Is there a session ticket of this name?
3259 if($CHALLENGETICKET)
3261 # Do not log into a CHALLENGE account if the SESSION cookie is present
3262 goto Login if $SESSIONTICKET =~ /\S/;
3263 goto Login unless (-s "$SessionPath/$CHALLENGETICKET");
3264 my $ticket_valid = check_ticket_validity("CHALLENGE
", "$SessionPath/$CHALLENGETICKET", $REMOTE_ADDR, $PATH_INFO);
3265 goto Login unless $ticket_valid;
3267 my $oldchallenge = read_ticket("$SessionPath/$CHALLENGETICKET");
3268 goto Login unless $oldchallenge;
3269 # Check whether the login still exists
3270 my $userfile = lc($oldchallenge->{"Username
"}->[0]);
3271 $userfile =~ s/[^\w]/_/isg;
3272 goto Login unless (-s "$PasswordsPath/$userfile");
3274 $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3275 goto Login unless $ticket_valid;
3277 my $NEWCHALLENGETICKET = "";
3278 $NEWCHALLENGETICKET = copy_challenge_file("$SessionPath/$CHALLENGETICKET", "$PasswordsPath/$userfile", $SessionPath);
3279 # Sessionticket is available to scripts, do NOT set the cookie
3280 $ENV{'CHALLENGETICKET'} = $NEWCHALLENGETICKET;
3284 elsif(-s "$SessionPath/$REMOTE_ADDR")
3286 my $ticket_valid = check_ticket_validity("IPADDRESS
", "$SessionPath/$REMOTE_ADDR", $REMOTE_ADDR, $PATH_INFO);
3287 goto Login unless $ticket_valid;
3288 # Check whether the login still exists
3289 my $currentsessionticket = read_ticket("$SessionPath/$REMOTE_ADDR");
3290 my $userfile = lc($currentsessionticket->{"Username
"}->[0]);
3291 $userfile =~ s/[^\w]/_/isg;
3292 goto Login unless (-s "$PasswordsPath/$userfile");
3294 $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3295 goto Login unless $ticket_valid;
3300 elsif($SESSIONTICKET)
3302 goto Login unless (-s "$SessionPath/$SESSIONTICKET");
3303 my $ticket_valid = check_ticket_validity("SESSION
", "$SessionPath/$SESSIONTICKET", $REMOTE_ADDR, $PATH_INFO);
3304 goto Login unless $ticket_valid;
3306 # Check whether the login still exists
3307 my $currentsessionticket = read_ticket("$SessionPath/$SESSIONTICKET");
3308 my $userfile = lc($currentsessionticket->{"Username
"}->[0]);
3309 $userfile =~ s/[^\w]/_/isg;
3310 goto Login unless (-s "$PasswordsPath/$userfile");
3312 $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3313 goto Login unless $ticket_valid;
3315 # Sessionticket is available to scripts
3316 $ENV{'SESSIONTICKET'} = $SESSIONTICKET;
3325 # The Masterkey should NOT be accessible by the parsed files
3326 $ENV{'CGIMasterKey'} = "" if $ENV{'CGIMasterKey'};
3330 create_login_file($PasswordsPath, $SessionPath, $REMOTE_ADDR);
3331 # Note, cookies are set only ONCE
3332 $SETCOOKIELIST{"CGIscriptorLOGIN
"} = "-";
3333 # The Masterkey should NOT be accessible by the parsed files
3334 $ENV{'CGIMasterKey'} = "" if $ENV{'CGIMasterKey'};
3335 return "$YOUR_HTML_FILES/$Login";
3338 sub authorize_login # ($loginfile, $authorizationfile, $password, $SessionPath) => SESSIONTICKET First two arguments are file paths
3340 my $loginfile = shift || "";
3341 my $authorizationfile = shift || "";
3342 my $password = shift || "";
3343 my $SessionPath = shift || "";
3345 # Get Login session ticket
3346 my $loginticket = read_ticket($loginfile);
3347 return 0 unless $loginticket;
3348 # Get User credentials for authorization
3349 my $authorization = read_ticket($authorizationfile);
3350 return 0 unless $authorization;
3353 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
3354 return "" unless $Randomsalt;
3356 my $storedpassword = $authorization->{'Password'}->[0];
3357 return "" unless $storedpassword;
3358 my $Hashedpassword = hash_string($storedpassword.$Randomsalt);
3359 return "" unless $password eq $Hashedpassword;
3361 # Extract Session Ticket
3362 my $loginsession = $loginticket->{'Session'}->[0];
3363 my $sessionticket = hash_string($storedpassword.$loginsession);
3364 chomp($sessionticket);
3365 $sessionticket = "" if -x "$SessionPath/$sessionticket";
3367 return $sessionticket;
3370 sub change_password # ($loginfile, $sessionfile, $authorizationfile, $password, $newpassword) First three arguments are file paths
3372 my $loginfile = shift || "";
3373 my $sessionfile = shift || "";
3374 my $authorizationfile = shift || "";
3375 my $password = shift || "";
3376 my $newpassword = shift || "";
3377 # Get Login session ticket
3378 my $loginticket = read_ticket($loginfile);
3379 return "" unless $loginticket;
3380 # Login ticket file has been used, remove it
3383 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
3384 return "" unless $Randomsalt;
3385 my $LoginID = $loginticket->{'Session'}->[0];
3386 return "" unless $LoginID;
3388 # Get session ticket
3389 my $sessionticket = read_ticket($sessionfile);
3390 return "" unless $sessionticket;
3392 # Get User credentials for authorization
3393 my $authorization = read_ticket($authorizationfile);
3394 return "" unless $authorization && lc($authorization->{'Username'}->[0]) eq lc($sessionticket->{'Username'}->[0]);
3396 my $storedpassword = $authorization->{'Password'}->[0];
3397 my $Hashedpassword = hash_string($storedpassword.$Randomsalt);
3398 return "" unless $password eq $Hashedpassword;
3399 my $secretkey = hash_string($storedpassword.$LoginID.$Randomsalt);
3401 # Decrypt the $newpassword
3402 my $decryptedPassword = XOR_hex_strings($secretkey, $newpassword);
3403 return "" unless $decryptedPassword;
3404 # Authorization succeeded, change password
3405 $authorization->{'Password'}->[0] = $decryptedPassword;
3407 write_ticket($authorizationfile, $authorization, $authorization->{'Salt'}->[0]);
3409 return $newpassword;
3411 # First three arguments are file paths
3412 sub create_newuser # ($loginfile, $sessionfile, $authorizationfile, $password, $newuser, $newpassword, $newsession) -> account text
3414 my $loginfile = shift || "";
3415 my $sessionfile = shift || "";
3416 my $authorizationfile = shift || "";
3417 my $password = shift || "";
3418 my $newuser = shift || "";
3419 my $newpassword = shift || "";
3420 my $newsession = shift || "";
3422 # Get Login session ticket
3423 my $loginticket = read_ticket($loginfile);
3424 return "" unless $loginticket;
3425 # Login ticket file has been used, remove it
3428 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
3429 return "" unless $Randomsalt;
3430 my $LoginID = $loginticket->{'Session'}->[0];
3431 return "" unless $LoginID;
3433 # Get session ticket
3434 my $sessionticket = read_ticket($sessionfile);
3435 return "" unless $sessionticket;
3436 # Get User credentials for authorization
3437 my $authorization = read_ticket($authorizationfile);
3438 return "" unless $authorization && lc($authorization->{'Username'}->[0]) eq lc($sessionticket->{'Username'}->[0]);
3439 my $sessionkey = $sessionticket->{'Key'}->[0];
3440 my $serversalt = $authorization->{'Salt'}->[0];
3441 return "" unless $serversalt;
3443 my $storedpassword = $authorization->{'Password'}->[0];
3444 my $Hashedpassword = hash_string($storedpassword.$Randomsalt);
3445 return "" unless $password eq $Hashedpassword;
3446 my $secretkey = hash_string($storedpassword.$LoginID.$Randomsalt);
3448 # Decrypt the $newpassword
3449 my $decryptedPassword = XOR_hex_strings($secretkey, $newpassword);
3450 return "" unless $decryptedPassword;
3452 # Authorization succeeded, create new account
3453 my $newaccount = {};
3454 $newaccount->{'Type'} = ['PASSWORD'];
3455 $newaccount->{'Username'} = [$newuser];
3456 $newaccount->{'Password'} = [$decryptedPassword];
3457 $newaccount->{'Salt'} = [$serversalt];
3458 $newaccount->{'Session'} = ['SESSION'];
3459 if($newsession eq 'IPADDRESS'){$newaccount->{'Session'} = ['IPADDRESS'];};
3460 if($newsession eq 'CHALLENGE'){$newaccount->{'Session'} = ['CHALLENGE'];};
3461 my $timesec = time();
3462 my $gmt_date = gmtime();
3463 $newaccount->{'Time'} = [$timesec];
3464 $newaccount->{'Date'} = [$gmt_date];
3467 my $NewAllowedPaths = "";
3468 my $PATH_INFO = $ENV{'CGI_BINARY_FILE'} ? $ENV{'CGI_BINARY_FILE'} : $ENV{'PATH_INFO'};
3469 my $currentRoot = "";
3470 $currentRoot = $1 if $PATH_INFO =~ m!^([\w\-\. /]+)!isg;
3471 $currentRoot =~ s![^/]+$!!isg;
3474 $currentRoot .= '/' unless $currentRoot =~ m!/$!;
3475 my $newpath = "^".${currentRoot}.'[\w\-]+\.html?';
3476 $NewAllowedPaths .= 'AllowedPaths: ^'.${currentRoot}.'[\w\-]+\.html?'."\n";
3477 $newaccount->{'AllowedPaths'} = [$newpath];
3481 # Tricky PATH_INFO, deny all
3482 $NewAllowedPaths .= "DeniedPaths
: ^/\n";
3483 $newaccount->{'DeniedPaths'} = ["DeniedPaths
: ^/\n"];
3486 # Construct home directory path
3487 my $FullHomeDirectoryPath = "";
3488 my $currentHome = lc($newuser);
3489 if($currentHome && $currentHome !~ /^\s*\#/)
3491 $currentHome =~ s![^\w]!_!isg;
3492 my $newpath = "^${currentRoot
}$currentHome/";
3493 push(@{$newaccount->{'AllowedPaths'}}, $newpath);
3494 # Create home directory
3495 $FullHomeDirectoryPath = $ENV{'HOME'}.${currentRoot}.$currentHome;
3499 CGIexecute::defineCGIvariable('ALLOWEDPATHS', "");
3500 my $allowedpaths = ${"CGIexecute
::ALLOWEDPATHS
"};
3501 if($allowedpaths && $allowedpaths !~ /^\s*\#/)
3503 $allowedpaths =~ s![^\^\w\./\;\+\*\?\[\]\$]!!isg;
3504 my @pathlist = split(/\;/, $allowedpaths);
3505 foreach my $entry (@pathlist)
3507 push(@{$newaccount->{'AllowedPaths'}}, "^".${currentRoot}.$entry);
3511 # Allowed IP addresses
3512 CGIexecute::defineCGIvariable('IPADDRESS', "");
3513 my $ipaddress = ${"CGIexecute
::IPADDRESS
"};
3514 if($ipaddress && $ipaddress !~ /^\s*\#/)
3516 $ipaddress =~ s![^\d\.\;]!!isg;
3517 my @iplist = split(/\;/, $ipaddress);
3518 foreach my $entry (@iplist)
3520 next unless $entry =~ /\d/;
3521 next if $entry =~ /^\s*\#/;
3522 $entry =~ s/\./\\./g;
3523 push(@{$newaccount->{'IPaddress'}}, $entry);
3527 # Sign the new ticket
3528 my $Signature = SignTicketWithMasterkey($newaccount, $newaccount->{'Salt'}->[0]);
3531 my $datetime = gmtime();
3532 my $passwordline = "<span id
='newaccount'>".($newaccount->{'Password'}->[0])."</span
>";
3533 my $newuserfile = "";
3534 if(grep(/^CreateUser$/, @{$authorization->{'Capabilities'}}))
3536 my $newuserfilename = lc($newuser);
3537 $newuserfilename =~ s/[^\w]/_/isg;
3538 $newuserfile = $authorizationfile;
3539 $newuserfile =~ s![^/]*$!!isg;
3540 $newuserfile .= $newuserfilename;
3545 elsif($FullHomeDirectoryPath && !(-d $FullHomeDirectoryPath || -s $FullHomeDirectoryPath))
3547 if(-d "$ENV{'HOME'}${currentRoot
}.SkeletonDir
")
3549 `cp -r '$ENV{'HOME'}${currentRoot}.SkeletonDir' '$FullHomeDirectoryPath'`;
3551 elsif(-d "$ENV{'HOME'}${currentRoot
}SkeletonDir
")
3553 `cp -r '$ENV{'HOME'}${currentRoot}SkeletonDir' '$FullHomeDirectoryPath'`;
3555 elsif(-s "$ENV{'HOME'}${currentRoot
}UserIndex
.html
")
3557 mkdir $FullHomeDirectoryPath;
3558 `cp '$ENV{'HOME'}${currentRoot}UserIndex.html' '$FullHomeDirectoryPath/index.html'`;
3560 elsif(-s "$ENV{'HOME'}${currentRoot
}index.html
")
3562 mkdir $FullHomeDirectoryPath;
3563 `cp '$ENV{'HOME'}${currentRoot}index.html' '$FullHomeDirectoryPath/index.html'`;
3569 my $newaccounttext = write_ticket($newuserfile, $newaccount, $serversalt);
3571 # Re-encrypt the new password for transmission
3572 if($newaccounttext =~ /^(Password\:\s+)(\S+)\s*$/)
3574 my $passwordvalue = $1;
3575 my $reencryptedpassword = XOR_hex_strings($secretkey, $passwordvalue);
3576 my $encryptedpasswordline = "<span id
='newaccount'>$reencryptedpassword</span
>";
3577 $newaccounttext =~ s/^(Password\:\s+)(\S+)\s*$/\1$encryptedpasswordline/gim;
3579 return $newaccounttext;
3582 # Copy a Challenge ticket file to a new name which is the hash of the new $CHALLENGETICKET and the password
3583 sub copy_challenge_file #($oldchallengefile, $authorizationfile, $sessionpath) -> $CHALLENGETICKET
3585 my $oldchallengefile = shift || "";
3586 my $authorizationfile = shift || "";
3587 my $sessionpath = shift || "";
3588 $sessionpath =~ s!/+$!!g;
3590 # Get Login session ticket
3591 my $oldchallenge = read_ticket($oldchallengefile);
3592 return "" unless $oldchallenge;
3594 # Get Authorization (user) session file
3595 my $authorization = read_ticket($authorizationfile);
3596 return "" unless $authorization;
3597 my $storedpassword = $authorization->{'Password'}->[0];
3598 return "" unless $storedpassword;
3599 my $challengekey = $oldchallenge->{'Key'}->[0];
3600 return "" unless $challengekey;
3602 # Create Random Hash Salt
3603 my $NEWCHALLENGETICKET = get_random_hex();;
3604 my $newchallengefile = hash_string($challengekey.$NEWCHALLENGETICKET);
3605 return "" unless $newchallengefile;
3607 $ENV{'CHALLENGETICKET'} = $NEWCHALLENGETICKET;
3608 CGIexecute::defineCGIvariable('CHALLENGETICKET', "");
3609 ${"CGIexecute
::CHALLENGETICKET
"} = $NEWCHALLENGETICKET;
3611 # Write Session Ticket
3612 open(OLDCHALLENGE, "<$oldchallengefile") || die "<$oldchallengefile: $!\n";
3613 my @OldChallengeLines = <OLDCHALLENGE>;
3614 close(OLDCHALLENGE);
3615 # Old file should now be removed
3616 unlink($oldchallengefile);
3618 open(SESSION, ">$sessionpath/$newchallengefile") || die "$sessionpath/$newchallengefile: $!\n";
3619 foreach $line (@OldChallengeLines)
3621 print SESSION $line;
3625 return $NEWCHALLENGETICKET;
3628 sub create_login_file #($PasswordDir, $SessionDir, $IPaddress)
3630 my $PasswordDir = shift || "";
3631 my $SessionDir = shift || "";
3632 my $IPaddress = shift || "";
3634 # Create Login Ticket
3635 my $LOGINTICKET= get_random_hex ();
3637 # Create Random Hash Salt
3638 my $RANDOMSALT= get_random_hex();
3640 # Create SALT file if it does not exist
3641 # Remove this, including test account for life system
3642 unless(-d "$SessionDir")
3644 `mkdir -p "$SessionDir"`;
3646 unless(-d "$PasswordDir")
3648 `mkdir -p "$PasswordDir"`;
3650 # Create SERVERSALT and default test account
3651 my $SERVERSALT = "";
3652 unless(-s "$PasswordDir/SALT
")
3654 $SERVERSALT= get_random_hex();
3655 open(SALTFILE, ">$PasswordDir/SALT") || die ">$PasswordDir/SALT
: $!\n";
3656 print SALTFILE "$SERVERSALT\n";
3659 # Update test account (should be removed in live system)
3660 my @alltestusers = ("test
", "testip
", "testchallenge
", "admin
");
3661 foreach my $testuser (@alltestusers)
3663 if(-s "$PasswordDir/$testuser")
3665 my $plainpassword = $testuser eq 'admin' ? "There is
no password like more password
" : "testing
";
3667 my $storedpassword = hash_string(${plainpassword}.${testuser}.${SERVERSALT});
3668 # Encrypt the new password with the MasterKey
3669 my $authorization = read_ticket("$PasswordDir/$testuser") || return "";
3670 $authorization->{'Salt'} = [$SERVERSALT];
3671 $authorization->{'Type'} = ['INACTIVE PASSWORD'] if $testuser eq 'admin';
3672 set_password($authorization, $SERVERSALT, $plainpassword);
3673 write_ticket("$PasswordDir/$testuser", $authorization, $SERVERSALT);
3679 open(SALTFILE, "<$PasswordDir/SALT") || die "$PasswordDir/SALT
: $!\n";
3680 $SERVERSALT=<SALTFILE>;
3684 # Create login session ticket
3685 my $datetime = gmtime();
3686 my $timesec = time();
3687 my $loginticket = {};
3688 $loginticket->{Type} = ['LOGIN'];
3689 $loginticket->{IPaddress} = [$IPaddress];
3690 $loginticket->{Salt} = [$SERVERSALT];
3691 $loginticket->{Session} = [$LOGINTICKET];
3692 $loginticket->{Randomsalt} = [$RANDOMSALT];
3693 $loginticket->{Expires} = ['+600s'];
3694 $loginticket->{Date} = ["$datetime UTC
"];
3695 $loginticket->{Time} = [$timesec];
3696 write_ticket("$SessionDir/$LOGINTICKET", $loginticket, $SERVERSALT);
3698 # Set global variables
3700 $ENV{'SERVERSALT'} = $SERVERSALT;
3701 CGIexecute::defineCGIvariable('SERVERSALT', "");
3702 ${"CGIexecute
::SERVERSALT
"} = $SERVERSALT;
3705 $ENV{'SESSIONTICKET'} = $SESSIONTICKET;
3706 CGIexecute::defineCGIvariable('SESSIONTICKET', "");
3707 ${"CGIexecute
::SESSIONTICKET
"} = $SESSIONTICKET;
3710 $ENV{'RANDOMSALT'} = $RANDOMSALT;
3711 CGIexecute::defineCGIvariable('RANDOMSALT', "");
3712 ${"CGIexecute
::RANDOMSALT
"} = $RANDOMSALT;
3715 $ENV{'LOGINTICKET'} = $LOGINTICKET;
3716 CGIexecute::defineCGIvariable('LOGINTICKET', "");
3717 ${"CGIexecute
::LOGINTICKET
"} = $LOGINTICKET;
3719 return $ENV{'LOGINTICKET'};
3722 sub create_session_file #($sessionfile, $loginfile, $authorizationfile, $path) -> Is $loginfile deleted? 0/1
3724 my $sessionfile = shift || "";
3725 my $loginfile = shift || "";
3726 my $authorizationfile = shift || "";
3727 my $path = shift || "";
3729 # Get Login session ticket
3730 my $loginticket = read_ticket($loginfile);
3731 return unlink($loginfile) unless $loginticket;
3733 # Get Authorization (user) session file
3734 my $authorization = read_ticket($authorizationfile);
3735 return unlink($loginfile) unless $authorization;
3737 # For a Session or a Challenge, we need a stored key
3738 my $sessionkey = "";
3740 if($authorization->{'Session'} && $authorization->{'Session'}->[0] ne 'IPADDRESS')
3742 my $storedpassword = $authorization->{'Password'}->[0];
3743 my $loginticketid = $loginticket->{'Session'}->[0];
3744 my $randomsalt = $loginticket->{'Randomsalt'}->[0];
3745 $sessionkey = hash_string($storedpassword.$loginticketid);
3746 $secretkey = hash_string($storedpassword.$loginticketid.$randomsalt);
3750 if($sessionfile =~ m!([^/]+)$!)
3755 # Convert Authorization content to Session content
3756 my $sessionContent = {};
3757 my $SessionType = $authorization->{'Session'}->[0] ? $authorization->{'Session'}->[0] : "SESSION
";
3758 $sessionContent->{Type} = [$SessionType];
3759 $sessionContent->{Username} = [lc($authorization->{'Username'}->[0])];
3760 $sessionContent->{Session} = [$sessionid];
3761 $sessionContent->{Time} = [time];
3762 # Limit communication to the login IP address, except for Tor like situations with VariableREMOTE_ADDR
3763 $sessionContent->{IPaddress} = ['.'];
3764 if($sessionContent->{Type}->[0] eq 'CHALLENGE' && grep(/^VariableREMOTE_ADDR$/, @{$authorization->{'Capabilities'}}))
3766 $sessionContent->{IPaddress} = $authorization->{'IPaddress'} if $authorization->{'IPaddress'};
3770 $sessionContent->{IPaddress} = $loginticket->{'IPaddress'};
3772 $sessionContent->{Salt} = $authorization->{'Salt'};
3773 $sessionContent->{Randomsalt} = $loginticket->{'Randomsalt'};
3774 $sessionContent->{AllowedPaths} = $authorization->{'AllowedPaths'};
3775 $sessionContent->{DeniedPaths} = $authorization->{'DeniedPaths'};
3776 $sessionContent->{Expires} = $authorization->{'MaxLifetime'};
3777 $sessionContent->{Capabilities} = $authorization->{'Capabilities'};
3778 foreach my $pattern (keys(%TicketRequiredPatterns))
3780 if($path =~ m#$pattern#)
3782 my ($SessionPath, $PasswordsPath, $Login, $validtime) = split(/\t/, $TicketRequiredPatterns{$pattern});
3783 push(@{$sessionContent->{Expires}}, $validtime);
3786 $sessionContent->{Key} = [$sessionkey] if $sessionkey;
3787 $sessionContent->{Secretkey} = [$secretkey] if $secretkey;
3788 $sessionContent->{Date} = [gmtime()." UTC
"];
3790 # Write Session Ticket
3791 write_ticket($sessionfile, $sessionContent, $authorization->{'Salt'}->[0]);
3793 # Login file should now be removed
3794 return unlink($loginfile);
3797 sub check_ticket_validity # ($type, $ticketfile, $address, $path [, $unsigned])
3799 my $type = shift || "SESSION
";
3800 my $ticketfile = shift || "";
3801 my $address = shift || "";
3802 my $path = shift || "";
3803 my $unsigned = shift || 0;
3805 # Is there a session ticket of this name?
3806 return 0 unless -s "$ticketfile";
3808 # There is a session ticket, is it linked to this IP address?
3809 my $ticket = read_ticket($ticketfile);
3812 print STDERR "Ticket expired
or empty
: $ticketfile\n";
3816 # Is this the right type of ticket
3817 unless($ticket && $ticket->{'Type'}->[0] eq $type)
3819 print STDERR "Wrong ticket type
: $ticket->{'Type'}->[0] eq $type\n";
3823 # Does the IP address match?
3824 my $IPmatches = @{$ticket->{"IPaddress
"}} ? 0 : 1;
3825 for $IPpattern (@{$ticket->{"IPaddress
"}})
3827 ++$IPmatches if $address =~ m#^$IPpattern#ig;
3829 if($address && ! $IPmatches)
3831 print STDERR "Wrong REMOTE ADDR
for $ticket->{'Username'}->[0]: $ticket->{'IPaddress'}->[0] vs
$address\n";
3835 # Is the path denied
3836 my $Pathmatches = 0;
3837 foreach $Pathpattern (@{$ticket->{"DeniedPaths
"}})
3839 ++$Pathmatches if $path =~ m#$Pathpattern#ig;
3841 return 0 if @{$ticket->{"DeniedPaths
"}} && $Pathmatches;
3843 # Is the path allowed
3845 foreach $Pathpattern (@{$ticket->{"AllowedPaths
"}})
3847 ++$Pathmatches if $path =~ m#$Pathpattern#ig;
3849 return 0 unless !@{$ticket->{"AllowedPaths
"}} || $Pathmatches;
3851 # Check signature if not told to use an unsigned ticket (dangerous)
3852 my $Signature = TicketSignature($ticket, $ticket->{'Salt'}->[0]);
3853 if((! $unsigned) && $Signature && $Signature ne $ticket->{'Signature'}->[0])
3855 print STDERR "Invalid signature
for $ticket->{'Type'}: $ticket->{'Username'}\n$ticketfile\n";
3859 # Make login values available (will also protect against resetting by query)
3860 $ENV{"LOGINUSERNAME
"} = lc($ticket->{'Username'}->[0]);
3861 $ENV{"LOGINIPADDRESS
"} = $address;
3862 $ENV{"LOGINPATH
"} = $path;
3863 $ENV{"SESSIONTYPE
"} = $type unless $type eq "PASSWORD
";
3865 # Set Capabilities, if present
3866 if($ticket->{'Username'}->[0] && @{$ticket->{'Capabilities'}})
3868 $ENV{'CAPABILITIES'} = $ticket->{'Username'}->[0];
3869 CGIexecute::defineCGIvariableList('CAPABILITIES', "");
3870 @{"CGIexecute
::CAPABILITIES
"} = @{$ticket->{'Capabilities'}};
3871 # Capabilities should not be changed anymore by CGI query!
3873 # Capabilities are NOT to be set by the query
3874 CGIexecute::ProtectCGIvariable('CAPABILITIES');
3880 sub remove_expired_tickets # ($path) -> number of tickets removed
3882 my $path = shift || "";
3883 return 0 unless $path;
3885 my $removed_tickets = 0;
3886 my @ticketlist = glob("$path/*");
3887 foreach my $ticketfile (@ticketlist)
3889 my $ticket = read_ticket($ticketfile);
3896 return $removed_tickets;
3899 sub set_password # ($ticket, $salt, $plainpassword) -> $password
3901 my $ticket = shift || "";
3902 my $salt = shift || "";
3903 my $plainpassword = shift || "";
3905 my $user = lc($ticket->{'Username'}->[0]);
3906 return "" unless $user;
3907 $salt = $ticket->{'Salt'}->[0] unless $salt;
3909 my $storedpassword = hash_string(${plainpassword}.${user}.${salt});
3910 $ticket->{'Password'} = [$storedpassword];
3911 $ticket->{'Salt'} = [$salt];
3913 return $ticket->{'Password'}->[0];
3916 sub write_ticket # ($ticketfile, $ticket, $salt [, $masterkey]) -> &%ticket
3918 my $ticketfile = shift || "";
3919 my $ticket = shift || "";
3920 my $salt = shift || "";
3921 my $masterkey = shift || $ENV{'CGIMasterKey'};
3924 EncryptTicketWithMasterKey($ticket, $salt, $masterkey);
3926 # Sign the new ticket
3927 my $signature = SignTicketWithMasterkey($ticket, $salt, $masterkey);
3929 # Create ordered list with labels
3930 my @orderlist = ('Type', 'Username', 'Password', 'IPaddress', 'AllowedPaths', 'DeniedPaths',
3931 'Expires', 'Capabilities', 'Salt', 'Session', 'Randomsalt',
3932 'Date', 'Time', 'Signature', 'Key', 'Secretkey');
3933 my @labellist = keys(%{$ticket});
3934 foreach my $label (@orderlist)
3936 @labellist = grep(!/\b$label\b/, @labellist);
3939 # Create ticket in text
3940 my $TicketText = "";
3941 foreach my $label (@orderlist, @labellist)
3943 next unless exists($ticket->{$label}) && $ticket->{$label}->[0];
3944 foreach my $value (@{$ticket->{$label}})
3946 $TicketText .= "$label: $value\n";
3951 open(TICKET, ">$ticketfile") || die "$ticketfile: $!\n";
3952 print TICKET $TicketText;
3959 # Note, read_ticket will return 0 if the ticket has expired!
3960 sub read_ticket # ($ticketfile [, $salt, $masterkey]) -> &%ticket
3962 my $ticketfile = shift || "";
3963 my $serversalt = shift || "";
3964 my $masterkey = shift || $ENV{'CGIMasterKey'};
3967 if($ticketfile && -s $ticketfile)
3969 open(TICKETFILE, "<$ticketfile") || die "$ticketfile: $!\n";
3970 my @alllines = <TICKETFILE>;
3972 foreach my $currentline (@alllines)
3974 # Skip empty lines and comments
3975 next unless $currentline =~ /\S/;
3976 next if $currentline =~ /^\s*\#/;
3978 if($currentline =~ /^\s*(\S[^\:]+)\:\s+(.*)\s*$/)
3982 $ticket->{$Label} = () unless exists($ticket->{$Label});
3983 push(@{$ticket->{$Label}}, $Value);
3987 if($masterkey && exists($ticket->{'Password'}) && $ticket->{'Password'}->[0])
3989 # Use the ServerSalt stored in the ticket, if present
3990 if(!$serversalt && exists($ticket->{Salt}) && $ticket->{Salt}->[0])
3992 $serversalt = $ticket->{Salt}->[0];
3994 # Decrypt all passwords
3995 DecryptTicketWithMasterKey($ticket, $serversalt, $masterkey) ||
3996 die "Decryption failed
: DecryptTicketWithMasterKey
($ticket, $serversalt)\n";
3999 # Check whether the ticket has expired
4000 if(exists($ticket->{Expires}))
4003 if(exists($ticket->{Time}) && $ticket->{Time}->[0] > 0)
4005 $StartTime = [(sort(@{$ticket->{Time}}))]->[0];
4009 # Get SessionTicket file stats
4010 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)
4011 = stat($ticketfile);
4012 $StartTime = $ctime;
4014 foreach my $Value (@{$ticket->{'Expires'}})
4016 # Recalculate expire date from relative time
4019 if($Value =~ /^\+(\d+)\s*d(ays)?\s*$/)
4021 $ExpireTime = 24*3600*$1;
4023 elsif($Value =~ /^\+(\d+)\s*m(inutes)?\s*$/)
4025 $ExpireTime = 60*$1;
4027 elsif($Value =~ /^\+(\d+)\s*h(ours)?\s*$/)
4029 $ExpireTime = 3600*$1;
4031 elsif($Value =~ /^\+(\d+)\s*s(econds)?\s*$/)
4035 elsif($Value =~ /^\+(\d+)\s*$/)
4040 my $absoluteTime = $Value =~ /^\+/ ? $StartTime + $ExpireTime : $Value;
4041 return 0 unless $absoluteTime > time;
4043 @{$ticket->{Expires}} = sort(@{$ticket->{Expires}});
4048 # Set up a valid ticket from a given text file
4049 # Use from command line. DO NOT USE ONLINE
4050 # Watch out for passwords that get stored in the history file
4052 # perl CGIscriptor.pl --managelogin [options] [files]
4054 # salt={file or saltvalue}
4055 # masterkey={file or plaintext}
4056 # newmasterkey={file or plaintext}
4057 # password={file or palintext}
4059 # Followed by one or more file names.
4060 # Options can be interspersed between filenames,
4061 # e.g., password='plaintext'
4062 # Note that passwords are only used once!
4064 sub setup_ticket_file # (@ARGV)
4066 # Stop when run on-line
4067 return if $ENV{'PATH_INFO'} || $ENV{'QUERY_STRING'};
4070 foreach my $input (@_)
4072 if($input =~ /^([\w]+)\=/)
4078 if($value !~ m![^\w\.\~\/\:\-]! && $value !~ /^[\-\.]/ && -s "$value" && ! -d "$value")
4080 # Warn about reading a value from file
4081 print STDERR "Read
'$name' from
: '$value'\n";
4082 open(INPUTVALUE, "<$value") || die "$value: $!\n";
4083 $value = <INPUTVALUE>;
4087 $value =~ s/(^\'([^\']*)\'$)/\1/g;
4088 $value =~ s/(^\"([^\"]*)\"$)/\1/g;
4089 $Settings{$name} = $value;
4091 elsif($input !~ m![^\w\.\~\/\:\-]!i && $input !~ /^[\-\.]/i && -s $input)
4093 # We MUST have a salt
4094 $Settings{'salt'} = $ticket->{'Salt'}->[0] unless $Settings{'salt'};
4096 # Set the new masterkey to the old masterkey if there is no new masterkey
4097 $Settings{'newmasterkey'} = $Settings{'masterkey'} unless exists($Settings{'newmasterkey'});
4100 my $ticket = read_ticket($input, $Settings{'salt'}, $Settings{'masterkey'});
4102 # Set a new password from plaintext
4103 $ticket->{'Salt'}->[0] = $Settings{'salt'} if $Settings{'salt'} && $Settings{'password'};
4104 set_password ($ticket, $Settings{'salt'}, $Settings{'password'}) if $Settings{'password'};
4105 # Write the ticket back to file
4106 write_ticket($input, $ticket, $Settings{'salt'}, $Settings{'newmasterkey'});
4108 # A password is only used once
4109 $Settings{'password'} = "";
4114 # Add a signature from $masterkey to a ticket in the label $signlabel
4115 sub SignTicketWithMasterkey # ($ticket, $serversalt [, $masterkey, $signlabel]) -> $Signature
4117 my $ticket = shift || return 0;
4118 my $serversalt = shift || "";
4119 my $masterkey = shift || $ENV{'CGIMasterKey'};
4120 my $signlabel = shift || 'Signature';
4122 my $Signature = TicketSignature($ticket, $serversalt, $masterkey);
4124 $ticket->{$signlabel} = [$Signature] if $Signature;
4129 # Determine ticket signature
4130 sub TicketSignature # ($ticket, $serversalt [, $masterkey]) -> $Signature
4132 my $ticket = shift || return 0;
4133 my $serversalt = shift || "";
4134 my $masterkey = shift || $ENV{'CGIMasterKey'};
4139 # If the ServerSalt is not stored in the ticket, the SALT file has to be found
4140 if(!$serversalt && exists($ticket->{Salt}) && $ticket->{Salt}->[0])
4142 $serversalt = $ticket->{Salt}->[0];
4147 my $username = lc($ticket->{'Username'}->[0]);
4148 my $hash1 = hash_string(${masterkey}.${serversalt});
4149 my $CryptKey = hash_string($username.${'hash1'});
4150 my $SignText = "Type
: ".$ticket->{'Type'}->[0]."\n";
4151 my @tmp = sort(@{$ticket->{'Username'}});
4152 $SignText .= "Username
: @tmp\n";
4153 @tmp = sort(@{$ticket->{'IPaddress'}});
4154 $SignText .= "IPaddress
: @tmp\n";
4155 @tmp = sort(@{$ticket->{'AllowedPaths'}});
4156 $SignText .= "AllowedPaths
: @tmp\n";
4157 @tmp = sort(@{$ticket->{'DeniedPaths'}});
4158 $SignText .= "DeniedPaths
: @tmp\n";
4159 @tmp = sort(@{$ticket->{'Session'}});
4160 $SignText .= "Session
: @tmp\n";
4161 @tmp = sort(@{$ticket->{'Time'}});
4162 $SignText .= "Time
: @tmp\n";
4163 @tmp = sort(@{$ticket->{'Expires'}});
4164 $SignText .= "Expires
: @tmp\n";
4165 @tmp = sort(@{$ticket->{'Capabilities'}});
4166 $SignText .= "Capabilities
: @tmp\n";
4167 @tmp = sort(@{$ticket->{'MaxLifetime'}});
4168 $SignText .= "MaxLifetime
: @tmp\n";
4169 $Signature = HMAC_hex($CryptKey, $SignText);
4175 # Decrypts a password list IN PLACE
4176 sub DecryptTicketWithMasterKey # ($ticket, $serversalt [, $masterkey]) -> \@password_list
4178 my $ticket = shift || return 0;
4179 my $serversalt = shift || "";
4180 my $masterkey = shift || $ENV{'CGIMasterKey'};
4182 if($masterkey && exists($ticket->{Password}) && $ticket->{Password}->[0])
4184 # If the ServerSalt is not given, read it from the the ticket
4185 if(! $serversalt && exists($ticket->{Salt}) && $ticket->{Salt}->[0])
4187 $serversalt = $ticket->{Salt}->[0];
4189 # Decrypt password(s)
4192 my $hash1 = hash_string(${masterkey}.${serversalt});
4193 my $username = lc($ticket->{'Username'}->[0]);
4194 my $CryptKey = hash_string(${'hash1'}.$username);
4195 foreach my $password (@{$ticket->{Password}})
4197 $password = XOR_hex_strings($CryptKey,$password);
4201 return $ticket->{'Password'};
4203 sub EncryptTicketWithMasterKey # ($ticket, $serversalt [, $masterkey]) -> \@password_list
4205 DecryptTicketWithMasterKey(@_);
4208 # Implement HMAC signature hash.
4209 # Blocksize is length in HEX characters, NOT bytes
4210 sub HMAC_hex # ($key, $message [, $blocksizehex]) -> $hex
4212 my $key = shift || "";
4213 my $message = shift || "";
4214 my $blocksizehex = shift || length($key);
4215 $key = hash_string($key) if length($key) > $blocksizehex;
4217 my $innerkey = XOR_hex_byte ($key, "36");
4218 my $outerkey = XOR_hex_byte ($key, "5c
");
4219 my $innerhash = hash_string($innerkey.$message);
4220 my $outerhash = hash_string($outerkey.$innerhash);
4225 # XOR input with equally long string of repeated 2 hex character (byte)
4226 # string. Input must have even number of hex characters
4227 sub XOR_hex_byte # ($hex1, $hexbyte) -> $hex
4229 my $hex1 = shift || "";
4230 my $hexbyte = shift || "";
4231 my $bytelength = length($hexbyte);
4233 $hex2 =~ s/.{$bytelength}/$hexbyte/ig;
4234 return XOR_hex_strings($hex1, $hex2);
4237 sub XOR_hex_strings # ($hex1, $hex2) -> $hex
4239 my $hex1 = shift || "";
4240 my $hex2 = shift || "";
4241 my @hex1list = split('', $hex1);
4242 my @hex2list = split('', $hex2);
4243 my @hexresultlist = ();
4244 for(my $i; $i < scalar(@hex1list); ++$i)
4246 my $d1 = hex($hex1list[$i]);
4247 my $d2 = hex($hex2list[$i]);
4248 my $dresult = ($d1 ^ $d2);
4249 $hexresultlist[$i] = sprintf("%x", $dresult);
4251 $hexresult = join('', @hexresultlist);
4255 # End of Handle login access
4258 ############################################################################
4260 # Handle foreign interpreters (i.e., scripting languages)
4262 # Insert perl code to execute scripts in foreign scripting languages.
4263 # Actually, the scripts inside the <SCRIPT></SCRIPT> blocks are piped
4264 # into an interpreter.
4265 # The code presented here is fairly confusing because it
4266 # actually writes perl code code to the output.
4268 # A table with the file handles
4269 %SCRIPTINGINPUT = ();
4271 # A function to clean up Client delivered CGI parameter values
4272 # (i.e., quote all odd characters)
4282 sub shrubCGIparameter # ($String) -> Cleaned string
4284 my $String = shift || "";
4286 # Change all quotes [`'"] into HTML character entities
4287 my ($Char, $Transcript) = ('&', $SHRUBcharacterTR{'&'});
4290 $String =~ s/\Q$Char\E/$Transcript/isg if $Transcript;
4292 while( ($Char, $Transcript) = each %SHRUBcharacterTR)
4294 next if $Char eq '&';
4295 $String =~ s/\Q$Char\E/$Transcript/isg;
4299 $String =~ s/[\n]/\\n/g;
4300 # Replace control characters with their backslashed octal ordinal numbers
4301 $String =~ s/([^\S \t])/(sprintf("\\0%o", ord($1)))/eisg; #
4302 $String =~ s/([\x00-\x08\x0A-\x1F])/(sprintf("\\0%o", ord($1)))/eisg; #
4308 # The initial open statements: Open a pipe to the foreign script interpreter
4309 sub OpenForeignScript # ($ContentType) -> $DirectivePrefix
4311 my $ContentType = lc(shift) || return "";
4312 my $NewDirective = "";
4314 return $NewDirective if($SCRIPTINGINPUT{$ContentType});
4316 # Construct a unique file handle name
4317 $SCRIPTINGFILEHANDLE = uc($ContentType);
4318 $SCRIPTINGFILEHANDLE =~ s/\W/\_/isg;
4319 $SCRIPTINGINPUT{$ContentType} = $SCRIPTINGFILEHANDLE
4320 unless $SCRIPTINGINPUT{$ContentType};
4322 # Create the relevant script: Open the pipe to the interpreter
4323 $NewDirective .= <<"BLOCKCGISCRIPTOROPEN";
4324 # Open interpreter for '$ContentType'
4325 # Open pipe to interpreter (if it isn't
open already
)
4326 open($SCRIPTINGINPUT{$ContentType}, "|$ScriptingLanguages{$ContentType}") || main
::dieHandler
(14, "$ContentType: \$!\\n");
4327 BLOCKCGISCRIPTOROPEN
4329 # Insert Initialization code and CGI variables
4330 $NewDirective .= InitializeForeignScript
($ContentType);
4333 return $NewDirective;
4337 # The final closing code to stop the interpreter
4338 sub CloseForeignScript
# ($ContentType) -> $DirectivePrefix
4340 my $ContentType = lc(shift) || return "";
4341 my $NewDirective = "";
4343 # Do nothing unless the pipe realy IS open
4344 return "" unless $SCRIPTINGINPUT{$ContentType};
4347 $NewDirective .= "\# Close interpreter for '$ContentType'\n";
4350 # Write the Postfix code
4351 $NewDirective .= CleanupForeignScript
($ContentType);
4353 # Create the relevant script: Close the pipe to the interpreter
4354 $NewDirective .= <<"BLOCKCGISCRIPTORCLOSE";
4355 close($SCRIPTINGINPUT{$ContentType}) || main::dieHandler(15, \"$ContentType: \$!\\n\");
4356 select(STDOUT); \$|=1;
4358 BLOCKCGISCRIPTORCLOSE
4360 # Remove the file handler of the foreign script
4361 delete($SCRIPTINGINPUT{$ContentType});
4363 return $NewDirective;
4367 # The initialization code for the foreign script interpreter
4368 sub InitializeForeignScript
# ($ContentType) -> $DirectivePrefix
4370 my $ContentType = lc(shift) || return "";
4371 my $NewDirective = "";
4373 # Add initialization code
4374 if($ScriptingInitialization{$ContentType})
4376 $NewDirective .= <<"BLOCKCGISCRIPTORINIT";
4377 # Initialization Code for '$ContentType'
4378 # Select relevant output filehandle
4379 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4381 # The Initialization code (if any)
4382 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}INITIALIZATIONCODE';
4383 $ScriptingInitialization{$ContentType}
4384 ${ContentType}INITIALIZATIONCODE
4386 BLOCKCGISCRIPTORINIT
4389 # Add all CGI variables defined
4390 if(exists($ScriptingCGIvariables{$ContentType}))
4392 # Start writing variable definitions to the Interpreter
4393 if($ScriptingCGIvariables{$ContentType})
4395 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEF";
4396 # CGI variables (from the %default_values table)
4397 print $SCRIPTINGINPUT{$ContentType} << '${ContentType}CGIVARIABLES';
4398 BLOCKCGISCRIPTORVARDEF
4402 foreach $N (keys(%default_values))
4404 # Determine whether the parameter has been defined
4405 # (the eval is a workaround to get at the variable value)
4406 next unless eval("defined(\$CGIexecute::$N)");
4408 # Get the value from the EXECUTION environment
4409 $V = eval("\$CGIexecute::$N");
4410 # protect control characters (i.e., convert them to \0.. form)
4411 $V = shrubCGIparameter
($V);
4413 # Protect interpolated variables
4414 eval("\$CGIexecute::$N = '$V';") unless $ScriptingCGIvariables{$ContentType};
4416 # Print the actual declaration for this scripting language
4417 if($ScriptingCGIvariables{$ContentType})
4419 $NewDirective .= sprintf($ScriptingCGIvariables{$ContentType}, $N, $V);
4420 $NewDirective .= "\n";
4424 # Stop writing variable definitions to the Interpreter
4425 if($ScriptingCGIvariables{$ContentType})
4427 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEFEND";
4428 ${ContentType}CGIVARIABLES
4429 BLOCKCGISCRIPTORVARDEFEND
4434 $NewDirective .= << "BLOCKCGISCRIPTOREND";
4436 # Select STDOUT filehandle
4437 select(STDOUT
); \
$|=1;
4441 return $NewDirective;
4445 # The cleanup code for the foreign script interpreter
4446 sub CleanupForeignScript
# ($ContentType) -> $DirectivePrefix
4448 my $ContentType = lc(shift) || return "";
4449 my $NewDirective = "";
4451 # Return if not needed
4452 return $NewDirective unless $ScriptingCleanup{$ContentType};
4454 # Create the relevant script: Open the pipe to the interpreter
4455 $NewDirective .= <<"BLOCKCGISCRIPTORSTOP";
4456 # Cleanup Code for '$ContentType'
4457 # Select relevant output filehandle
4458 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4459 # Print Cleanup code to foreign script
4460 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}SCRIPTSTOP';
4461 $ScriptingCleanup{$ContentType}
4462 ${ContentType}SCRIPTSTOP
4464 # Select STDOUT filehandle
4465 select(STDOUT); \$|=1;
4466 BLOCKCGISCRIPTORSTOP
4468 return $NewDirective;
4472 # The prefix code for each <script></script> block
4473 sub PrefixForeignScript
# ($ContentType) -> $DirectivePrefix
4475 my $ContentType = lc(shift) || return "";
4476 my $NewDirective = "";
4478 # Return if not needed
4479 return $NewDirective unless $ScriptingPrefix{$ContentType};
4482 # If the CGIvariables parameter is defined, but empty, interpolate
4483 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
4484 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
4485 !$ScriptingCGIvariables{$ContentType};
4487 # Add initialization code
4488 $NewDirective .= <<"BLOCKCGISCRIPTORPREFIX";
4489 # Prefix Code for '$ContentType'
4490 # Select relevant output filehandle
4491 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4493 # The block Prefix code (if any)
4494 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}PREFIXCODE$Quote;
4495 $ScriptingPrefix{$ContentType}
4496 ${ContentType}PREFIXCODE
4497 # Select STDOUT filehandle
4498 select(STDOUT); \$|=1;
4499 BLOCKCGISCRIPTORPREFIX
4501 return $NewDirective;
4505 # The postfix code for each <script></script> block
4506 sub PostfixForeignScript
# ($ContentType) -> $DirectivePrefix
4508 my $ContentType = lc(shift) || return "";
4509 my $NewDirective = "";
4511 # Return if not needed
4512 return $NewDirective unless $ScriptingPostfix{$ContentType};
4515 # If the CGIvariables parameter is defined, but empty, interpolate
4516 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
4517 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
4518 !$ScriptingCGIvariables{$ContentType};
4520 # Create the relevant script: Open the pipe to the interpreter
4521 $NewDirective .= <<"BLOCKCGISCRIPTORPOSTFIX";
4522 # Postfix Code for '$ContentType'
4523 # Select filehandle to interpreter
4524 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4525 # Print postfix code to foreign script
4526 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SCRIPTPOSTFIX$Quote;
4527 $ScriptingPostfix{$ContentType}
4528 ${ContentType}SCRIPTPOSTFIX
4529 # Select STDOUT filehandle
4530 select(STDOUT); \$|=1;
4531 BLOCKCGISCRIPTORPOSTFIX
4533 return $NewDirective;
4536 sub InsertForeignScript
# ($ContentType, $directive, @SRCfile) -> $NewDirective
4538 my $ContentType = lc(shift) || return "";
4539 my $directive = shift || return "";
4541 my $NewDirective = "";
4544 # If the CGIvariables parameter is defined, but empty, interpolate
4545 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
4546 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
4547 !$ScriptingCGIvariables{$ContentType};
4549 # Create the relevant script
4550 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
4551 # Insert Code for '$ContentType'
4552 # Select filehandle to interpreter
4553 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4554 BLOCKCGISCRIPTORINSERT
4556 # Use SRC feature files
4558 while($ThisSRCfile = shift(@_))
4561 if($ThisSRCfile =~ /^\s*\{\s*/)
4564 $Block = $` if $Block =~ /\s*\}\s*$/;
4565 $NewDirective .= <<"BLOCKCGISCRIPTORSRCBLOCK";
4566 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SRCBLOCKCODE$Quote;
4568 ${ContentType}SRCBLOCKCODE
4569 BLOCKCGISCRIPTORSRCBLOCK
4575 $NewDirective .= <<"BLOCKCGISCRIPTORSRCFILES";
4577 open(SCRIPTINGSOURCE, "<$ThisSRCfile") || main::dieHandler(16, "$ThisSRCfILE: \$!");
4578 while(<SCRIPTINGSOURCE>)
4580 print $SCRIPTINGINPUT{$ContentType} \$_;
4582 close(SCRIPTINGSOURCE);
4584 BLOCKCGISCRIPTORSRCFILES
4591 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
4592 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}DIRECTIVECODE$Quote;
4594 ${ContentType}DIRECTIVECODE
4595 BLOCKCGISCRIPTORINSERT
4599 $NewDirective .= <<"BLOCKCGISCRIPTORSELECT";
4600 # Select STDOUT filehandle
4601 select(STDOUT); \$|=1;
4602 BLOCKCGISCRIPTORSELECT
4605 return $NewDirective;
4608 sub CloseAllForeignScripts
# Call CloseForeignScript on all open scripts
4611 foreach $ContentType (keys(%SCRIPTINGINPUT))
4613 my $directive = CloseForeignScript
($ContentType);
4614 print STDERR
"\nDirective $CGI_Date: ", $directive;
4615 CGIexecute
->evaluate($directive);
4620 # End of handling foreign (external) scripting languages.
4622 ############################################################################
4624 # A subroutine to handle "nested" quotes, it cuts off the leading
4625 # item or quoted substring
4627 # ' A_word and more words' -> @('A_word', ' and more words')
4628 # '"quoted string" The rest' -> @('quoted string', ' The rest')
4629 # (this is needed for parsing the <TAGS> and their attributes)
4630 my $SupportedQuotes = "\'\"\`\(\{\[";
4631 my %QuotePairs = ('('=>')','['=>']','{'=>'}'); # Brackets
4632 sub ExtractQuotedItem
# ($String) -> @($QuotedString, $RestOfString)
4635 my $String = shift || return @Result;
4637 if($String =~ /^\s*([\w\/\
-\
.]+)/is
)
4639 push(@Result, $1, $');
4641 elsif($String =~ /^\s*(\\?)([\Q$SupportedQuotes\E])/is)
4643 my $BackSlash = $1 || "";
4645 my $CloseQuote = $OpenQuote;
4646 $CloseQuote = $QuotePairs{$OpenQuote} if $QuotePairs{$OpenQuote};
4650 $String =~ /^\s*\\\Q$OpenQuote\E/i;
4652 $Onset =~ /\\\Q$CloseQuote\E/i;
4655 push(@Result, $Item, $Rest);
4660 $String =~ /^\s*\Q$OpenQuote\E([^\Q$CloseQuote\E]*)\Q$CloseQuote\E/i;
4661 push(@Result, $1, $');
4666 push(@Result, "", $String);
4671 # Now, start with the real work
4673 # Control the output of the Content-type: text/html\n\n message
4674 my $SupressContentType = 0;
4677 sub ProcessFile
# ($file_path)
4679 my $file_path = shift || return 0;
4682 # Generate a unique file handle (for recursions)
4684 my $FileHandle = "file";
4686 while(!eof($FileHandle.$n)) {++$n;};
4690 # Use the default Content-type if this is NOT a raw file
4691 unless(($RawFilePattern && $ENV{'PATH_INFO'} =~ m@
($RawFilePattern)$@i)
4692 || $SupressContentType)
4694 $ENV{'PATH_INFO'} =~ m@
($FilePattern)$@i;
4695 my $ContentType = $ContentTypeTable{$1};
4696 print "Content-type: $ContentType\n";
4697 if(%SETCOOKIELIST && keys(%SETCOOKIELIST))
4699 foreach my $name (keys(%SETCOOKIELIST))
4701 my $value = $SETCOOKIELIST{$name};
4702 print "Set-Cookie: $name=$value\n";
4704 # Cookies are set only ONCE
4705 %SETCOOKIELIST = ();
4708 $SupressContentType = 1; # Content type has been printed
4712 # Get access to the actual data. This can be from RAM (by way of an
4713 # environment variable) or by opening a file.
4715 # Handle the use of RAM images (file-data is stored in the
4716 # $CGI_FILE_CONTENTS environment variable)
4717 # Note that this environment variable will be cleared, i.e., it is strictly for
4719 if($ENV{$CGI_FILE_CONTENTS})
4721 # File has been read already
4722 $_ = $ENV{$CGI_FILE_CONTENTS};
4723 # Sorry, you have to do the reading yourself (dynamic document creation?)
4724 # NOTE: you must read the whole document at once
4727 $_ = eval("\@_=('$file_path'); do{$ENV{$CGI_DATA_ACCESS_CODE}}");
4729 else # Clear environment variable
4731 $ENV{$CGI_FILE_CONTENTS} = '-';
4734 # Open Only PLAIN TEXT files (or STDIN) and NO executable files (i.e., scripts).
4735 # THIS IS A SECURITY FEATURE!
4736 elsif($file_path eq '-' || (-e
"$file_path" && -r _
&& -T _
&& -f _
&& ! (-x _
|| -X _
) ))
4738 open($FileHandle, $file_path) || dieHandler
(17, "<h2>File not found</h2>\n");
4739 push(@OpenFiles, $file_path);
4740 $_ = <$FileHandle>; # Read first line
4744 print "<h2>File not found</h2>\n";
4745 dieHandler
(18, "$file_path\n");
4748 $| = 1; # Flush output buffers
4750 # Initialize variables
4751 my $METAarguments = ""; # The CGI arguments from the latest META tag
4752 my @METAvalues = (); # The ''-quoted CGI values from the latest META tag
4753 my $ClosedTag = 0; # <TAG> </TAG> versus <TAG/>
4756 # Send document to output
4757 # Process the requested document.
4758 # Do a loop BEFORE reading input again (this catches the RAM/Database
4759 # type of documents).
4763 # Handle translations if needed
4765 performTranslation
(\
$_) if $TranslationPaths;
4767 # Catch <SCRIPT LANGUAGE="PERL" TYPE="text/ssperl" > directives in $_
4768 # There can be more than 1 <SCRIPT> or META tags on a line
4769 while(/\<\s*(SCRIPT|META|DIV|INS)\s/is)
4772 # Store rest of line
4776 my $TagType = uc($1);
4777 # The before part can be send to the output
4780 # Read complete Tag from after and/or file
4781 until($After =~ /([^\\])\>/)
4783 $After .= <$FileHandle>;
4784 performTranslation(\$After) if $TranslationPaths;
4787 if($After =~ /([^\\])\>/)
4789 $ScriptTag .= $`.$&; # Keep the Script Tag intact
4794 dieHandler(19, "Closing > not found\n");
4797 # The tag could be closed by />, we handle this in the XML way
4798 # and don't process any content
(we ignore whitespace
)
4799 $ClosedTag = ($ScriptTag =~ m@
[^\\]/\s
*\
>\s
*$@
) ?
1 : 0;
4803 my $TypeName = ($TagType =~ /META/is) ?
"CONTENT" : "TYPE";
4804 $TypeName = "CLASS" if $TagType eq 'DIV' || $TagType eq 'INS';
4806 # Parse <SCRIPT> or <META> directive
4807 # If NOT (TYPE|CONTENT)="text/ssperl" (i.e., $ServerScriptContentType),
4808 # send the line to the output and go to the next loop
4809 my $CurrentContentType = "";
4810 if($ScriptTag =~ /(^|\s)$TypeName\s*=\s*/is)
4812 my ($Type) = ExtractQuotedItem
($');
4813 $Type =~ /^\s*([\w\/\-]+)\s*[\,\;]?/;
4814 $CurrentContentType = lc($1); # Note: mime-types are "case-less"
4815 # CSS classes are aliases of $ServerScriptContentType
4816 if($TypeName eq "CLASS" && $CurrentContentType eq $ServerScriptContentClass)
4818 $CurrentContentType = $ServerScriptContentType;
4823 # Not a known server-side content type, print and continue
4824 unless(($CurrentContentType =~
4825 /$ServerScriptContentType|$ShellScriptContentType/is) ||
4826 $ScriptingLanguages{$CurrentContentType})
4834 # A known server-side content type, evaluate
4836 # First, handle \> and \<
4837 $ScriptTag =~ s/\\\>/\>/isg;
4838 $ScriptTag =~ s/\\\</\</isg;
4840 # Extract the CGI, SRC, ID, IF and UNLESS attributes
4841 my %ScriptTagAttributes = ();
4842 while($ScriptTag =~ /(^|\s)(CGI|IF|UNLESS|SRC|ID)\s*=\s*/is)
4847 ($Value, $ScriptTag) = ExtractQuotedItem
($Rest);
4848 $ScriptTagAttributes{uc($Attribute)} = $Value;
4852 # The attribute used to define the CGI variables
4853 # Extract CGI-variables from
4854 # <META CONTENT="text/ssperl; CGI='' SRC=''">
4855 # <SCRIPT TYPE='text/ssperl' CGI='' SRC=''>
4856 # <DIV CLASS='ssperl' CGI='' SRC='' ID=""> tags
4857 # <INS CLASS='ssperl' CGI='' SRC='' ID=""> tags
4858 if($ScriptTagAttributes{'CGI'})
4860 @ARGV = (); # Reset ARGV
4862 $METAarguments = ""; # Reset the META CGI arguments
4864 my $Meta_CGI = $ScriptTagAttributes{'CGI'};
4866 # Process default values of variables ($<name> = 'default value')
4867 # Allowed quotes are '', "", ``, (), [], and {}
4868 while($Meta_CGI =~ /(^\s*|[^\\])([\$\@\%]?)([\w\-]+)\s*/is)
4870 my $varType = $2 || '$'; # Variable or list
4871 my $name = $3; # The Name
4875 if($Meta_CGI =~ /^\s*\=\s*/is)
4877 # Locate (any) default value
4878 ($default, $Meta_CGI) = ExtractQuotedItem($'); # Cut the parameter from the CGI
4880 $RemainingTag = $Meta_CGI;
4883 # Define CGI (or ENV) variable, initalize it from the
4884 # Query string or the default value
4886 # Also construct the @ARGV and @_ arrays. This allows other (SRC=) Perl
4887 # scripts to access the CGI arguments defined in the META tag
4888 # (Not for CGI inside <SCRIPT> tags)
4891 CGIexecute
::defineCGIvariable
($name, $default)
4892 || dieHandler
(20, "INVALID CGI name/value pair ($name, $default)\n");
4893 push(@METAvalues, "'".${"CGIexecute::$name"}."'");
4894 # Add value to the @ARGV list
4895 push(@ARGV, ${"CGIexecute::$name"});
4898 elsif($varType eq '@')
4900 CGIexecute
::defineCGIvariableList
($name, $default)
4901 || dieHandler
(21, "INVALID CGI name/value list pair ($name, $default)\n");
4902 push(@METAvalues, "'".join("'", @
{"CGIexecute::$name"})."'");
4903 # Add value to the @ARGV list
4904 push(@ARGV, @
{"CGIexecute::$name"});
4905 $ARGC = scalar(@CGIexecute::ARGV
);
4907 elsif($varType eq '%')
4909 CGIexecute
::defineCGIvariableHash
($name, $default)
4910 || dieHandler
(22, "INVALID CGI name/value hash pair ($name, $default)\n");
4911 my @PairList = map {"$_ => ".${"CGIexecute::$name"}{$_}} keys(%{"CGIexecute::$name"});
4912 push(@METAvalues, "'".join("'", @PairList)."'");
4913 # Add value to the @ARGV list
4914 push(@ARGV, %{"CGIexecute::$name"});
4915 $ARGC = scalar(@CGIexecute::ARGV
);
4918 # Store the values for internal and later use
4919 $METAarguments .= "$varType".$name.","; # A string of CGI variable names
4921 push(@METAvalues, "\'".eval("\"$varType\{CGIexecute::$name\}\"")."\'"); # ALWAYS add '-quotes around values
4926 # The IF (conditional execution) Attribute
4927 # Evaluate the condition and stop unless it evaluates to true
4928 if($ScriptTagAttributes{'IF'})
4930 my $IFcondition = $ScriptTagAttributes{'IF'};
4932 # Convert SCRIPT calls, ./<script>
4933 $IFcondition =~ s@
([\W
]|^)\
./([\S
])@
$1$SCRIPT_SUB$2@g;
4935 # Convert FILE calls, ~/<file>
4936 $IFcondition =~ s@
([\W
])\
~/([\S
])@
$1$HOME_SUB$2@g;
4938 # Block execution if necessary
4939 unless(CGIexecute
->evaluate($IFcondition))
4941 %ScriptTagAttributes = ();
4942 $CurrentContentType = "";
4946 # The UNLESS (conditional execution) Attribute
4947 # Evaluate the condition and stop if it evaluates to true
4948 if($ScriptTagAttributes{'UNLESS'})
4950 my $UNLESScondition = $ScriptTagAttributes{'UNLESS'};
4952 # Convert SCRIPT calls, ./<script>
4953 $UNLESScondition =~ s@
([\W
]|^)\
./([\S
])@
$1$SCRIPT_SUB$2@g;
4955 # Convert FILE calls, ~/<file>
4956 $UNLESScondition =~ s@
([\W
])\
~/([\S
])@
$1$HOME_SUB$2@g;
4958 # Block execution if necessary
4959 if(CGIexecute
->evaluate($UNLESScondition))
4961 %ScriptTagAttributes = ();
4962 $CurrentContentType = "";
4966 # The SRC (Source File) Attribute
4967 # Extract any source script files and add them in
4968 # front of the directive
4969 # The SRC list should be emptied
4973 my $PrefixDirective = "";
4974 my $PostfixDirective = "";
4975 # There is a SRC attribute
4976 if($ScriptTagAttributes{'SRC'})
4978 $SRCtag = $ScriptTagAttributes{'SRC'};
4979 # Remove "file://" prefixes
4980 $SRCtag =~ s@
([^\w\
/\\]|^)file\://([^\s\/\@\
=])@
$1$2@gis;
4981 # Expand script filenames "./Script"
4982 $SRCtag =~ s@
([^\w\
/\\]|^)\./([^\s\
/\@\=])@$1$SCRIPT_SUB/$2@gis;
4983 # Expand script filenames "~/Script"
4984 $SRCtag =~ s@
([^\w\
/\\]|^)\~/([^\s\
/\@\=])@$1$HOME_SUB/$2@gis;
4988 while($SRCtag =~ /\S/is)
4990 my $SRCdirective = "";
4992 # Pseudo file, just a switch to go from PREFIXING to POSTFIXING
4994 if($SRCtag =~ /^[\s\;\,]*(POSTFIX|PREFIX)([^$FileAllowedChars]|$)/is)
4996 my $InsertionPlace = $1;
4999 $Prefix = $InsertionPlace =~ /POSTFIX/i ? 0 : 1;
5003 # {}-blocks are just evaluated by "do"
5004 elsif($SRCtag =~ /^[\s\;\,]*\{/is)
5007 if($SRCblock =~ /\}[\s\;\,]*([^\}]*)$/is)
5011 # SAFEqx shell script blocks
5012 if($CurrentContentType =~ /$ShellScriptContentType/is)
5014 # Handle ''-quotes inside the script
5015 $SRCblock =~ s/[\']/\\$&/gis;
5017 $SRCblock = "print do { SAFEqx(\'".$SRCblock."\'); };'';";
5018 $SRCdirective .= $SRCblock."\n";
5021 elsif($CurrentContentType =~ /$ServerScriptContentType/is)
5023 $SRCblock = "print do { $SRCblock };'';";
5024 $SRCdirective .= $SRCblock."\n";
5026 else # The interpreter should handle this
5028 push(@SRClist, "{ $SRCblock }");
5033 { dieHandler(23, "Closing \} missing\n");};
5035 # Files are processed as Text or Executable files
5036 elsif($SRCtag =~ /[\s\;\,]*([$FileAllowedChars]+)[\;\,\s]*/is)
5041 # We are handling one of the external interpreters
5042 if($ScriptingLanguages{$CurrentContentType})
5044 push(@SRClist, $SrcFile);
5046 # We are at the start of a DIV tag, just load all SRC files and/or URL's
5047 elsif($TagType eq 'DIV' || $TagType eq 'INS') # All files are prepended in DIV's
5049 # $SrcFile is a URL pointing to an HTTP or FTP server
5050 if($SrcFile =~ m!^([a-z]+)\://!)
5052 my $URLoutput = CGIscriptor::read_url($SrcFile);
5053 $SRCdirective .= $URLoutput;
5055 # SRC file is an existing file
5056 elsif(-e "$SrcFile")
5058 open(DIVSOURCE, "<$SrcFile") || dieHandler(24, "<$SrcFile: $!\n");
5060 while(sysread(DIVSOURCE, $Content, 1024) > 0)
5062 $SRCdirective .= $Content;
5067 # Executable files are executed as
5068 # `$SrcFile 'ARGV[0]' 'ARGV[1]'`
5069 elsif(-x "$SrcFile")
5071 $SRCdirective .= "print \`$SrcFile @METAvalues\
`;'';\n";
5073 # Handle 'standard' files, using ProcessFile
5074 elsif((-T "$SrcFile" || $ENV{$CGI_FILE_CONTENTS})
5075 && $SrcFile =~ m@($FilePattern)$@) # A recursion
5078 # Do not process still open files because it can lead
5079 # to endless recursions
5080 if(grep(/^$SrcFile$/, @OpenFiles))
5081 { dieHandler(25, "$SrcFile allready opened (endless recursion)\n")};
5082 # Prepare meta arguments
5083 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
5085 $SRCdirective .= "main::ProcessFile(\'$SrcFile\');'';\n";
5087 elsif($SrcFile =~ m!^([a-z]+)\://!) # URL's are loaded and printed
5089 $SRCdirective .= GET_URL($SrcFile);
5091 elsif(-T "$SrcFile") # Textfiles are "do"-ed (Perl execution)
5093 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
5094 $SRCdirective .= "do \'$SrcFile\';'';\n";
5096 else # This one could not be resolved (should be handled by BinaryMapFile)
5098 $SRCdirective .= 'print "'.$SrcFile.' cannot be used"'."\n";
5106 $PrefixDirective .= $SRCdirective;
5110 $PostfixDirective .= $SRCdirective;
5113 # The prefix should be handled immediately
5114 $directive .= $PrefixDirective;
5115 $PrefixDirective = "";
5119 # Handle the content of the <SCRIPT></SCRIPT> tags
5120 # Do not process the content of <SCRIPT/>
5121 if($TagType =~ /SCRIPT/is && !$ClosedTag) # The <SCRIPT> TAG
5123 my $EndScriptTag = "";
5125 # Execute SHELL scripts with SAFEqx()
5126 if($CurrentContentType =~ /$ShellScriptContentType/is)
5128 $directive .= "SAFEqx(\'";
5132 while($After !~ /\<\s*\/SCRIPT[^\>]*\>/is && !eof($FileHandle))
5134 $After .= <$FileHandle>;
5135 performTranslation(\$After) if $TranslationPaths;
5138 if($After =~ /\<\s*\/SCRIPT[^\>]*\>/is)
5146 dieHandler(26, "Missing </SCRIPT> end tag in $ENV{'PATH_INFO
'}\n");
5149 # Process only when content should be executed
5150 if($CurrentContentType)
5153 # Remove all comments from Perl scripts
5154 # (NOT from OS shell scripts)
5155 $directive =~ s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/$1/g
5156 if $CurrentContentType =~ /$ServerScriptContentType/i;
5158 # Convert SCRIPT calls, ./<script>
5159 $directive =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
5161 # Convert FILE calls, ~/<file>
5162 $directive =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
5164 # Execute SHELL scripts with SAFEqx(), closing bracket
5165 if($CurrentContentType =~ /$ShellScriptContentType/i)
5167 # Handle ''-quotes inside the script
5168 $directive =~ /SAFEqx\(\'/;
5170 my $Executable = $';
5171 $Executable =~ s/[\']/\\$&/gs;
5173 $directive .= $Executable."\');"; # Closing bracket
5181 # Handle the content of the <DIV></DIV> tags
5182 # Do not process the content of <DIV/>
5183 elsif(($TagType eq 'DIV' || $TagType eq 'INS') && !$ClosedTag) # The <DIV> TAGs
5185 my $EndScriptTag = "";
5188 while($After !~ /\<\s*\/$TagType[^\
>]*\
>/is
&& !eof($FileHandle))
5190 $After .= <$FileHandle>;
5191 performTranslation
(\
$After) if $TranslationPaths;
5194 if($After =~ /\<\s*\/$TagType[^\
>]*\
>/is
)
5202 dieHandler(27, "Missing </$TagType> end tag in $ENV{'PATH_INFO'}\n");
5205 # Add the Postfixed directives (but only when it contains something printable)
5206 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
5207 $PostfixDirective = "";
5210 # Process only when content should be handled
5211 if($CurrentContentType)
5214 # Get the name (ID), and clean it (i.e., remove anything that is NOT part of
5215 # a valid Perl name). Names should not contain $, but we can handle it.
5216 my $name = $ScriptTagAttributes{'ID'};
5217 $name =~ /^\s*[\$\@\%]?([\w\-]+)/;
5220 # Assign DIV contents to $NAME value OUTSIDE the CGI values!
5221 CGIexecute::defineCGIexecuteVariable($name, $directive);
5225 # Nothing to execute
5230 # Handle Foreign scripting languages
5231 if($ScriptingLanguages{$CurrentContentType})
5233 my $newDirective = "";
5234 $newDirective .= OpenForeignScript($CurrentContentType); # Only if not already done
5235 $newDirective .= PrefixForeignScript($CurrentContentType);
5236 $newDirective .= InsertForeignScript($CurrentContentType, $directive, @SRClist);
5237 $newDirective .= PostfixForeignScript($CurrentContentType);
5238 $newDirective .= CloseForeignScript($CurrentContentType); # This shouldn't be necessary
5240 $newDirective .= '"";';
5242 $directive = $newDirective;
5246 # Add the Postfixed directives (but only when it contains something printable)
5247 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
5248 $PostfixDirective = "";
5251 # EXECUTE the script and print the results
5253 # Use this to debug the program
5254 # print STDERR "Directive $CGI_Date: \n", $directive, "\n\n";
5256 my $Result = CGIexecute->evaluate($directive) if $directive; # Evaluate as PERL code
5257 $Result =~ s/\n$//g; # Remove final newline
5259 # Print the Result of evaluating the directive
5260 # (this will handle LARGE, >64 kB output)
5261 my $BytesWritten = 1;
5262 while($Result && $BytesWritten)
5264 $BytesWritten = syswrite(STDOUT, $Result, 64);
5265 $Result = substr($Result, $BytesWritten);
5267 # print $Result; # Could be used instead of above code
5269 # Store result if wanted, i.e., if $CGIscriptorResults has been
5270 # defined in a <META> tag.
5271 push(@CGIexecute::CGIscriptorResults, $Result)
5272 if exists($default_values{'CGIscriptorResults'});
5274 # Process the rest of the input line (this could contain
5275 # another directive)
5279 } while(<$FileHandle>); # Read and Test AFTER first loop!
5281 close ($FileHandle);
5282 dieHandler(28, "Error in recursion\n") unless pop(@OpenFiles) == $file_path;
5286 ###############################################################################
5288 # Call the whole package
5294 # Initialization Code
5295 Initialize_Request();
5297 # SECURITY: ACCESS CONTROL
5300 # Read the POST part of the query, if there is one
5301 Get_POST_part_of_query();
5303 # Start (HTML) output and logging
5304 $file_path = Initialize_output();
5306 # Check login access or divert to login procedure
5307 $Use_Login = Log_In_Access();
5308 $file_path = $Use_Login if $Use_Login;
5310 # Record which files are still open (to avoid endless recursions)
5313 # Record whether the default HTML ContentType has already been printed
5314 # but only if the SERVER uses HTTP or some other protocol that might interpret
5315 # a content MIME type.
5317 $SupressContentType = !("$ENV{'SERVER_PROTOCOL'}" =~ /($ContentTypeServerProtocols)/i);
5319 # Process the specified file
5320 ProcessFile($file_path) if $file_path ne $SS_PUB;
5322 # Cleanup all open external (foreign) interpreters
5323 CloseAllForeignScripts();
5329 # Make a single call to handle an (empty) request
5333 # END OF PACKAGE MAIN
5336 ####################################################################################
5338 # The CGIEXECUTE PACKAGE
5340 ####################################################################################
5342 # Isolate the evaluation of directives as PERL code from the rest of the program.
5343 # Remember that each package has its own name space.
5344 # Note that only the FIRST argument of execute->evaluate is actually evaluated,
5345 # all other arguments are accessible inside the first argument as $_[0] to $_[$#_].
5352 my $directive = shift;
5353 $directive = eval($directive);
5354 warn $@ if $@; # Write an error message to STDERR
5355 $directive; # Return value of directive
5359 # defineCGIexecuteVariable($name [, $value]) -> 0/1
5361 # Define and intialize variables inside CGIexecute
5362 # Does no sanity checking, for internal use only
5364 sub defineCGIexecuteVariable # ($name [, $value]) -> 0/1
5366 my $name = shift || return 0; # The Name
5367 my $value = shift || ""; # The value
5374 # Protect certain CGI variables values when set internally
5375 # If not defined internally, there will be no variable set AT ALL
5376 my %CGIprotectedVariable = ();
5377 sub ProtectCGIvariable # ($name) -> 0/1
5379 my $name = shift || "";
5380 return 0 unless $name && $name =~ /\w/;
5382 ++$CGIprotectedVariable{$name};
5384 return $CGIprotectedVariable{$name};
5387 # defineCGIvariable($name [, $default]) -> 0/1
5389 # Define and intialize CGI variables
5390 # Tries (in order) $ENV{$name}, the Query string and the
5392 # Removes all '-quotes etc.
5394 sub defineCGIvariable # ($name [, $default]) -> 0/1
5396 my $name = shift || return 0; # The Name
5397 my $default = shift || ""; # The default value
5399 # Protect variables set internally
5400 return 1 if !$name || exists($CGIprotectedVariable{$name});
5402 # Remove \-quoted characters
5403 $default =~ s/\\(.)/$1/g;
5404 # Store default values
5405 $::default_values{$name} = $default if $default;
5409 # If there is a user supplied value, it replaces the
5412 # Environment values have precedence
5413 if(exists($ENV{$name}))
5415 $temp = $ENV{$name};
5417 # Get name and its value from the query string
5418 elsif($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
5420 $temp = ::YOUR_CGIPARSE($name);
5422 # Defined values must exist for security
5423 elsif(!exists($::default_values{$name}))
5425 $::default_values{$name} = undef;
5428 # SECURITY, do not allow '- and `-quotes
in
5430 # Remove all existing '-quotes
5431 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
5432 $temp =~ s/[\']/’/igs; # Remove all single quotes
5433 $temp =~ s/[\`]/‘/igs; # Remove all backtick quotes
5434 # If $temp is empty, use the default value (if it exists)
5435 unless($temp =~ /\S/ || length($temp) > 0) # I.e., $temp is empty
5437 $temp = $::default_values
{$name};
5438 # Remove all existing '-quotes
5439 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
5440 $temp =~ s/[\']/’/igs; # Remove all single quotes
5441 $temp =~ s/[\`]/‘/igs; # Remove all backtick quotes
5443 else # Store current CGI values and remove defaults
5445 $::default_values
{$name} = $temp;
5447 # Define the CGI variable and its value (in the execute package)
5454 sub defineCGIvariableList
# ($name [, $default]) -> 0/1)
5456 my $name = shift || return 0; # The Name
5457 my $default = shift || ""; # The default value
5459 # Protect variables set internally
5460 return 1 if !$name || exists($CGIprotectedVariable{$name});
5462 # Defined values must exist for security
5463 if(!exists($::default_values
{$name}))
5465 $::default_values
{$name} = $default;
5472 # Environment values have precedence
5473 if(exists($ENV{$name}))
5475 push(@temp, $ENV{$name});
5477 # Get name and its values from the query string
5478 elsif($ENV{QUERY_STRING
} =~ /$name/) # $name is in the query string
5480 push(@temp, ::YOUR_CGIPARSE
($name, 1)); # Extract LIST
5484 push(@temp, $::default_values
{$name});
5488 # SECURITY, do not allow '- and `-quotes in
5490 # Remove all existing '-quotes
5491 @temp = map {s/([\r\f]+\n)/\n/g; $_} @temp; # Only \n is allowed
5492 @temp = map {s/[\']/’/igs; $_} @temp; # Remove all single quotes
5493 @temp = map {s/[\`]/‘/igs; $_} @temp; # Remove all backtick quotes
5495 # Store current CGI values and remove defaults
5496 $::default_values
{$name} = $temp[0];
5498 # Define the CGI variable and its value (in the execute package)
5505 sub defineCGIvariableHash
# ($name [, $default]) -> 0/1) Note: '$name{""} = $default';
5507 my $name = shift || return 0; # The Name
5508 my $default = shift || ""; # The default value
5510 # Protect variables set internally
5511 return 1 if !$name || exists($CGIprotectedVariable{$name});
5513 # Defined values must exist for security
5514 if(!exists($::default_values
{$name}))
5516 $::default_values
{$name} = $default;
5523 # Environment values have precedence
5524 if(exists($ENV{$name}))
5526 $temp{""} = $ENV{$name};
5528 # Get name and its values from the query string
5529 elsif($ENV{QUERY_STRING
} =~ /$name/) # $name is in the query string
5531 %temp = ::YOUR_CGIPARSE
($name, -1); # Extract HASH table
5533 elsif($::default_values
{$name} ne "")
5535 $temp{""} = $::default_values
{$name};
5539 # SECURITY, do not allow '- and `-quotes in
5541 # Remove all existing '-quotes
5543 foreach $Key (keys(%temp))
5545 $temp{$Key} =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
5546 $temp{$Key} =~ s/[\']/’/igs; # Remove all single quotes
5547 $temp{$Key} =~ s/[\`]/‘/igs; # Remove all backtick quotes
5550 # Store current CGI values and remove defaults
5551 $::default_values
{$name} = $temp{""};
5553 # Define the CGI variable and its value (in the execute package)
5556 foreach $tempKey (keys(%temp))
5558 ${$name}{$tempKey} = $temp{$tempKey};
5566 # SAFEqx('CommandString')
5568 # A special function that is a safe alternative to backtick quotes (and qx//)
5569 # with client-supplied CGI values. All CGI variables are surrounded by
5570 # single ''-quotes (except between existing \'\'-quotes, don't try to be
5571 # too smart). All variables are then interpolated. Simple (@) lists are
5572 # expanded with join(' ', @List), and simple (%) hash tables expanded
5573 # as a list of "key=value" pairs. Complex variables, e.g., @$var, are
5574 # evaluated in a scalar context (e.g., as scalar(@$var)). All occurrences of
5575 # $@% that should NOT be interpolated must be preceeded by a "\".
5576 # If the first line of the String starts with "#! interpreter", the
5577 # remainder of the string is piped into interpreter (after interpolation), i.e.,
5578 # open(INTERPRETER, "|interpreter");print INTERPRETER remainder;
5579 # just like in UNIX. There are some problems with quotes. Be carefull in
5580 # using them. You do not have access to the output of any piped (#!)
5581 # process! If you want such access, execute
5582 # <SCRIPT TYPE="text/osshell">echo "script"|interpreter</SCRIPT> or
5583 # <SCRIPT TYPE="text/ssperl">$resultvar = SAFEqx('echo "script"|interpreter');
5586 # SAFEqx ONLY WORKS WHEN THE STRING ITSELF IS SURROUNDED BY SINGLE QUOTES
5587 # (SO THAT IT IS NOT INTERPOLATED BEFORE IT CAN BE PROTECTED)
5588 sub SAFEqx
# ('String') -> result of executing qx/"String"/
5590 my $CommandString = shift;
5591 my $NewCommandString = "";
5593 # Only interpolate when required (check the On/Off switch)
5594 unless($CGIscriptor::NoShellScriptInterpolation
)
5597 # Handle existing single quotes around CGI values
5598 while($CommandString =~ /\'[^\']+\'/s)
5600 my $CurrentQuotedString = $&;
5601 $NewCommandString .= $`;
5602 $CommandString = $'; # The remaining string
5603 # Interpolate CGI variables between quotes
5604 # (e.g., '$CGIscriptorResults[-1]')
5605 $CurrentQuotedString =~
5606 s/(^|[^\\])([\$\@])((\w*)([\{\[][\$\@\%]?[\:\w\-]+[\}\]])*)/if(exists($main::default_values{$4})){
5607 "$1".eval("$2$3")}else{"$&"}/egs;
5609 # Combine result with previous result
5610 $NewCommandString .= $CurrentQuotedString;
5612 $CommandString = $NewCommandString.$CommandString;
5614 # Select known CGI variables and surround them with single quotes,
5615 # then interpolate all variables
5617 s/(^|[^\\])([\$\@\%]+)((\w*)([\{\[][\w\:\$\"\-]+[\}\]])*)/
5618 if($2 eq '$' && exists($main::default_values{$4}))
5619 {"$1\'".eval("\$$3")."\'";}
5620 elsif($2 eq '@'){$1.join(' ', @{"$3"});}
5621 elsif($2 eq '%'){my $t=$1;map {$t.=" $_=".${"$3"}{$_}}
5623 else{$1.eval("${2}$3");
5626 # Remove backslashed [$@%]
5627 $CommandString =~ s/\\([\$\@\%])/$1/gs;
5631 # return $CommandString;
5633 # Handle UNIX style "#! shell command\n" constructs as
5634 # a pipe into the shell command. The output cannot be tapped.
5635 my $ReturnValue = "";
5636 if($CommandString =~ /^\s*\#\!([^\f\n\r]+)[\f\n\r]/is)
5638 my $ShellScripts = $';
5639 my $ShellCommand = $1;
5640 open(INTERPRETER, "|$ShellCommand") || dieHandler(29, "\'$ShellCommand\' PIPE not opened: &!\n");
5641 select(INTERPRETER);$| = 1;
5642 print INTERPRETER $ShellScripts;
5644 select(STDOUT);$| = 1;
5646 # Shell scripts which are redirected to an existing named pipe.
5647 # The output cannot be tapped.
5648 elsif($CGIscriptor::ShellScriptPIPE)
5650 CGIscriptor::printSAFEqxPIPE($CommandString);
5652 else # Plain ``-backtick execution
5654 # Execute the commands
5655 $ReturnValue = qx/$CommandString/;
5657 return $ReturnValue;
5660 ####################################################################################
5662 # The CGIscriptor PACKAGE
5664 ####################################################################################
5666 # Isolate the evaluation of CGIscriptor functions, i.e., those prefixed with
5669 package CGIscriptor;
5672 # The Interpolation On/Off switch
5673 my $NoShellScriptInterpolation = undef;
5674 # The ShellScript redirection pipe
5675 my $ShellScriptPIPE = undef;
5677 # Open a named PIPE for SAFEqx to receive ALL shell scripts
5678 sub RedirectShellScript # ('CommandString')
5680 my $CommandString = shift || undef;
5684 $ShellScriptPIPE = "ShellScriptNamedPipe";
5685 open($ShellScriptPIPE, "|$CommandString")
5686 || main::dieHandler(30, "\'|$CommandString\' PIPE open failed: $!\n");
5690 close($ShellScriptPIPE);
5691 $ShellScriptPIPE = undef;
5693 return $ShellScriptPIPE;
5696 # Print to redirected shell script pipe
5697 sub printSAFEqxPIPE # ("String") -> print return value
5699 my $String = shift || undef;
5701 select($ShellScriptPIPE); $| = 1;
5702 my $returnvalue = print $ShellScriptPIPE ($String);
5703 select(STDOUT); $| = 1;
5705 return $returnvalue;
5708 # a pointer to CGIexecute::SAFEqx
5709 sub SAFEqx # ('String') -> result of qx/"String"/
5711 my $CommandString = shift;
5712 return CGIexecute::SAFEqx($CommandString);
5716 # a pointer to CGIexecute::defineCGIvariable
5717 sub defineCGIvariable # ($name[, $default]) ->0/1
5720 my $default = shift;
5721 return CGIexecute::defineCGIvariable($name, $default);
5725 # a pointer to CGIexecute::defineCGIvariable
5726 sub defineCGIvariableList # ($name[, $default]) ->0/1
5729 my $default = shift;
5730 return CGIexecute::defineCGIvariableList($name, $default);
5734 # a pointer to CGIexecute::defineCGIvariable
5735 sub defineCGIvariableHash # ($name[, $default]) ->0/1
5738 my $default = shift;
5739 return CGIexecute::defineCGIvariableHash($name, $default);
5743 # Decode URL encoded arguments
5744 sub URLdecode # (URL encoded input) -> string
5751 my $EncodedValue = $Value; # Do not change the loop variable
5752 # Convert all "+" to " "
5753 $EncodedValue =~ s/\+/ /g;
5754 # Convert all hexadecimal codes (%FF) to their byte values
5755 while($EncodedValue =~ /\%([0-9A-F]{2})/i)
5757 $output .= $`.chr(hex($1));
5760 $output .= $EncodedValue; # The remaining part of $Value
5765 # Encode arguments as URL codes.
5766 sub URLencode # (input) -> URL encoded string
5773 my @CharList = split('', $Value);
5774 foreach $char (@CharList)
5778 elsif($char =~ /\w\-/)
5779 { $output .= $char;}
5782 $output .= uc(sprintf("%%%2.2x", ord($char)));
5789 # Extract the value of a CGI variable from the URL-encoded $string
5790 # Also extracts the data blocks from a multipart request. Does NOT
5791 # decode the multipart blocks
5792 sub CGIparseValue # (ValueName [, URL_encoded_QueryString [, \$QueryReturnReference]]) -> Decoded value
5794 my $ValueName = shift;
5795 my $QueryString = shift || $main::ENV{'QUERY_STRING
'};
5796 my $ReturnReference = shift || undef;
5799 if($QueryString =~ /(^|\&)$ValueName\=([^\&]*)(\&|$)/)
5801 $output = URLdecode($2);
5802 $$ReturnReference = $' if ref($ReturnReference);
5804 # Get multipart POST or PUT methods
5805 elsif($main::ENV
{'CONTENT_TYPE'} =~ m@
(multipart
/([\w\
-]+)\
;\s
+boundary\
=([\S
]+))@i)
5807 my $MultipartType = $2;
5808 my $BoundaryString = $3;
5809 # Remove the boundary-string
5810 my $temp = $QueryString;
5811 $temp =~ /^\Q--$BoundaryString\E/m;
5814 # Identify the newline character(s), this is the first character in $temp
5815 my $NewLine = "\r\n"; # Actually, this IS the correct one
5816 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
5818 # Is this correct??? I have to check.
5819 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
5820 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
5821 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
5822 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
5825 # search through all data blocks
5826 while($temp =~ /^\Q--$BoundaryString\E/m)
5830 # Get the empty line after the header
5831 $DataBlock =~ /$NewLine$NewLine/;
5837 # Remove newlines from the header
5838 $Header =~ s/$NewLine/ /g;
5840 # Look whether this block is the one you are looking for
5841 # Require the quotes!
5842 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
5845 for($i=length($NewLine); $i; --$i)
5852 # reinitialize the output
5855 $$ReturnReference = $temp if ref($ReturnReference);
5857 elsif($QueryString !~ /(^|\&)$ValueName\=/) # The value simply isn't there
5860 $$ReturnReference = undef if ref($ReturnReference);
5864 print "ERROR: $ValueName $main::ENV{'CONTENT_TYPE'}\n";
5870 # Get a list of values for the same ValueName. Uses CGIparseValue
5872 sub CGIparseValueList
# (ValueName [, URL_encoded_QueryString]) -> List of decoded values
5874 my $ValueName = shift;
5875 my $QueryString = shift || $main::ENV
{'QUERY_STRING'};
5877 my $RestQueryString;
5879 while($QueryString &&
5880 (($Value = CGIparseValue
($ValueName, $QueryString, \
$RestQueryString))
5881 || defined($Value)))
5883 push(@output, $Value);
5884 $QueryString = $RestQueryString; # QueryString is consumed!
5886 # ready, return list with values
5890 sub CGIparseValueHash
# (ValueName [, URL_encoded_QueryString]) -> Hash table of decoded values
5892 my $ValueName = shift;
5893 my $QueryString = shift || $main::ENV
{'QUERY_STRING'};
5894 my $RestQueryString;
5896 while($QueryString && $QueryString =~ /(^|\&)$ValueName([\w]*)\=/)
5899 my $Value = CGIparseValue
("$ValueName$Key", $QueryString, \
$RestQueryString);
5900 $output{$Key} = $Value;
5901 $QueryString = $RestQueryString; # QueryString is consumed!
5903 # ready, return list with values
5907 sub CGIparseForm
# ([URL_encoded_QueryString]) -> Decoded Form (NO multipart)
5909 my $QueryString = shift || $main::ENV
{'QUERY_STRING'};
5912 $QueryString =~ s/\&/\n/g;
5913 $output = URLdecode
($QueryString);
5918 # Extract the header of a multipart CGI variable from the POST input
5919 sub CGIparseHeader
# (ValueName [, URL_encoded_QueryString]) -> Decoded value
5921 my $ValueName = shift;
5922 my $QueryString = shift || $main::ENV
{'QUERY_STRING'};
5925 if($main::ENV
{'CONTENT_TYPE'} =~ m@
(multipart
/([\w\
-]+)\
;\s
+boundary\
=([\S
]+))@i)
5927 my $MultipartType = $2;
5928 my $BoundaryString = $3;
5929 # Remove the boundary-string
5930 my $temp = $QueryString;
5931 $temp =~ /^\Q--$BoundaryString\E/m;
5934 # Identify the newline character(s), this is the first character in $temp
5935 my $NewLine = "\r\n"; # Actually, this IS the correct one
5936 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
5938 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
5939 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
5940 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
5941 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
5944 # search through all data blocks
5945 while($temp =~ /^\Q--$BoundaryString\E/m)
5949 # Get the empty line after the header
5950 $DataBlock =~ /$NewLine$NewLine/;
5954 # Remove newlines from the header
5955 $Header =~ s/$NewLine/ /g;
5957 # Look whether this block is the one you are looking for
5958 # Require the quotes!
5959 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
5964 # reinitialize the output
5972 # Checking variables for security (e.g., file names and email addresses)
5973 # File names are tested against the $::FileAllowedChars and $::BlockPathAccess variables
5974 sub CGIsafeFileName
# FileName -> FileName or ""
5976 my $FileName = shift || "";
5977 return "" if $FileName =~ m?[^$::FileAllowedChars]?;
5978 return "" if $FileName =~ m!(^|/|\:)[\-\.]!;
5979 return "" if $FileName =~ m@\
.\
.\Q
$::DirectorySeparator\E@
; # Higher directory not allowed
5980 return "" if $FileName =~ m@\Q
$::DirectorySeparator\E\
.\
.@
; # Higher directory not allowed
5981 return "" if $::BlockPathAccess
&& $FileName =~ m@
$::BlockPathAccess@
; # Invisible (blocked) file
5986 sub CGIsafeEmailAddress
# email -> email or ""
5988 my $Email = shift || "";
5989 return "" unless $Email =~ m/^[\w\.\-]+[\@][\w\.\-\:]+$/;
5993 # Get a URL from the web. Needs main::GET_URL($URL) function
5994 # (i.e., curl, snarf, or wget)
5995 sub read_url
# ($URL) -> page/file
5997 my $URL = shift || return "";
5999 # Get the commands to read the URL, do NOT add a print command
6000 my $URL_command = main
::GET_URL
($URL, 1);
6001 # execute the commands, i.e., actually read it
6002 my $URLcontent = CGIexecute
->evaluate($URL_command);
6004 # Ready, return the content.
6008 ################################################>>>>>>>>>>Start Remove
6010 # BrowseAllDirs(Directory, indexfile)
6013 # <SCRIPT TYPE='text/ssperl'>
6014 # CGIscriptor::BrowseAllDirs('Sounds', 'index.html', '\.wav$')
6017 # Allows to browse all directories. Stops at '/'. If the directory contains
6018 # an indexfile, eg, index.html, that file will be used instead. Files must match
6019 # the $Pattern, if it is given. Default is
6020 # CGIscriptor::BrowseAllDirs('/', 'index.html', '')
6022 sub BrowseAllDirs
# (Directory, indexfile, $Pattern) -> Print HTML code
6024 my $Directory = shift || '/';
6025 my $indexfile = shift || 'index.html';
6026 my $Pattern = shift || '';
6027 $Directory =~ s!/$!!g;
6029 # If the index directory exists, use that one
6030 if(-s
"$::CGI_HOME$Directory/$indexfile")
6032 return main
::ProcessFile
("$::CGI_HOME$Directory/$indexfile");
6035 # No indexfile, continue
6036 my @DirectoryList = glob("$::CGI_HOME$Directory");
6037 $CurrentDirectory = shift(@DirectoryList);
6038 $CurrentDirectory = $' if $CurrentDirectory =~ m@(/\.\./)+@;
6039 $CurrentDirectory =~ s@^$::CGI_HOME@@g;
6041 print "$CurrentDirectory" if $CurrentDirectory;
6044 opendir(BROWSE, "$::CGI_HOME$Directory") || main::dieHandler(31, "$::CGI_HOME$Directory $!");
6045 my @AllFiles = sort grep(!/^([\.]+[^\.]|\~)/, readdir(BROWSE));
6049 print "<pre><ul TYPE='NONE
'>\n";
6050 foreach $file (@AllFiles)
6052 next unless -d "$::CGI_HOME$Directory/$file";
6053 # Check whether this file should be visible
6054 next if $::BlockPathAccess &&
6055 "$Directory/$file/" =~ m@$::BlockPathAccess@;
6056 print "<dt><a href='$Directory/$file'>$file</a></dt>\n";
6058 print "</ul></pre>\n";
6061 print "<pre><ul TYPE='CIRCLE
'>\n";
6063 foreach $file (@AllFiles)
6065 next if $file =~ /^\./;
6066 next if -d "$::CGI_HOME$Directory/$file";
6067 next if -l "$::CGI_HOME$Directory/$file";
6068 # Check whether this file should be visible
6069 next if $::BlockPathAccess &&
6070 "$Directory/$file" =~ m@$::BlockPathAccess@;
6072 if(!$Pattern || $file =~ m@$Pattern@)
6074 my $Date = localtime($^T - (-M "$::CGI_HOME$Directory/$file")*3600*24);
6075 my $Size = -s "$::CGI_HOME$Directory/$file";
6076 $Size = sprintf("%6.0F kB", $Size/1024);
6077 my $Type = `file $::CGI_HOME$Directory/$file`;
6078 $Type =~ s@\s*$::CGI_HOME$Directory/$file\s*\:\s*@@ig;
6082 print "<a href='$Directory/$file'>";
6083 printf("%-40s", "$file</a>");
6084 print "\t$Size\t$Date\t$Type";
6088 print "</ul></pre>";
6094 ################################################
6096 # BrowseDirs(RootDirectory [, Pattern, Start])
6099 # <SCRIPT TYPE='text
/ssperl
'>
6100 # CGIscriptor::BrowseDirs('Sounds
', '\
.aifc
$', 'Speech
', 'DIRECTORY
')
6103 # Allows to browse subdirectories. Start should be relative to the RootDirectory,
6104 # e.g., the full path of the directory 'Speech
' is '~/Sounds/Speech
'.
6105 # Only files which fit /$Pattern/ and directories are displayed.
6106 # Directories down or up the directory tree are supplied with a
6107 # GET request with the name of the CGI variable in the fourth argument (default
6108 # is 'BROWSEDIRS
'). So the correct call for a subdirectory could be:
6109 # CGIscriptor::BrowseDirs('Sounds
', '\
.aifc
$', $DIRECTORY, 'DIRECTORY
')
6111 sub BrowseDirs # (RootDirectory [, Pattern, Start, CGIvariable, HTTPserver]) -> Print HTML code
6113 my $RootDirectory = shift; # || return 0;
6114 my $Pattern = shift || '\S
';
6115 my $Start = shift || "";
6116 my $CGIvariable = shift || "BROWSEDIRS";
6117 my $HTTPserver = shift || '';
6119 $Start = CGIscriptor::URLdecode($Start); # Sometimes, too much has been encoded
6120 $Start =~ s@//+@/@g;
6121 $Start =~ s@[^/]+/\.\.@@ig;
6122 $Start =~ s@^\.\.@@ig;
6123 $Start =~ s@/\.$@@ig;
6125 $Start .= "/" if $Start;
6127 my @Directory = glob("$::CGI_HOME/$RootDirectory/$Start");
6128 $CurrentDirectory = shift(@Directory);
6129 $CurrentDirectory = $' if $CurrentDirectory =~ m@
(/\.\./)+@
;
6130 $CurrentDirectory =~ s@
^$::CGI_HOME@
@g;
6132 print "$CurrentDirectory" if $CurrentDirectory;
6134 opendir(BROWSE
, "$::CGI_HOME/$RootDirectory/$Start") || main
::dieHandler
(31, "$::CGI_HOME/$RootDirectory/$Start $!");
6135 my @AllFiles = sort grep(!/^([\.]+[^\.]|\~)/, readdir(BROWSE
));
6139 print "<pre><ul TYPE='NONE'>\n";
6140 foreach $file (@AllFiles)
6142 next unless -d
"$::CGI_HOME/$RootDirectory/$Start$file";
6143 # Check whether this file should be visible
6144 next if $::BlockPathAccess
&&
6145 "/$RootDirectory/$Start$file/" =~ m@
$::BlockPathAccess@
;
6147 my $NewURL = $Start ?
"$Start$file" : $file;
6148 $NewURL = CGIscriptor
::URLencode
($NewURL);
6149 print "<dt><a href='";
6150 print "$ENV{SCRIPT_NAME}" if $ENV{SCRIPT_NAME
} !~ m@
[^\w
+\
-/]@
;
6151 print "$ENV{PATH_INFO}?$CGIvariable=$NewURL'>$file</a></dt>\n";
6153 print "</ul></pre>\n";
6156 print "<pre><ul TYPE='CIRCLE'>\n";
6158 foreach $file (@AllFiles)
6160 next if $file =~ /^\./;
6161 next if -d
"$::CGI_HOME/$RootDirectory/$Start$file";
6162 next if -l
"$::CGI_HOME/$RootDirectory/$Start$file";
6163 # Check whether this file should be visible
6164 next if $::BlockPathAccess
&&
6165 "$::CGI_HOME/$RootDirectory/$Start$file" =~ m@
$::BlockPathAccess@
;
6167 if($file =~ m@
$Pattern@
)
6169 my $Date = localtime($^T
- (-M
"$::CGI_HOME/$RootDirectory/$Start$file")*3600*24);
6170 my $Size = -s
"$::CGI_HOME/$RootDirectory/$Start$file";
6171 $Size = sprintf("%6.0F kB", $Size/1024);
6172 my $Type = `file $::CGI_HOME/$RootDirectory/$Start$file`;
6173 $Type =~ s@\s
*$::CGI_HOME
/$RootDirectory/$Start$file\s
*\
:\s
*@
@ig;
6177 if($HTTPserver =~ /^\s*[\.\~]\s*$/)
6179 print "<a href='$RootDirectory/$Start$file'>";
6183 print "<a href='$HTTPserver/$RootDirectory/$Start$file'>";
6185 printf("%-40s", "$file</a>") if $HTTPserver;
6186 printf("%-40s", "$file") unless $HTTPserver;
6187 print "\t$Size\t$Date\t$Type";
6191 print "</ul></pre>";
6197 # ListDocs(Pattern [,ListType])
6200 # <SCRIPT TYPE=text/ssperl>
6201 # CGIscriptor::ListDocs("/*", "dl");
6204 # This subroutine is very usefull to manage collections of independent
6205 # documents. The resulting list will display the tree-like directory
6206 # structure. If this routine is too slow for online use, you can
6207 # store the result and use a link to that stored file.
6209 # List HTML and Text files with title and first header (HTML)
6210 # or filename and first meaningfull line (general text files).
6211 # The listing starts at the ServerRoot directory. Directories are
6212 # listed recursively.
6214 # You can change the list type (default is dl).
6216 # <dt><a href=<file.html>>title</a>
6218 # <dt><a href=<file.txt>>file.txt</a>
6219 # <dd>First meaningfull line of text
6221 sub ListDocs
# ($Pattern [, prefix]) e.g., ("/Books/*", [, "dl"])
6223 my $Pattern = shift;
6225 my $ListType = shift || "dl";
6226 my $Prefix = lc($ListType) eq "dl" ?
"dt" : "li";
6227 my $URL_root = "http://$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}";
6228 my @FileList = glob("$::CGI_HOME$Pattern");
6229 my ($FileName, $Path, $Link);
6231 # Print List markers
6232 print "<$ListType>\n";
6235 File
: foreach $FileName (@FileList)
6237 # Check whether this file should be visible
6238 next if $::BlockPathAccess
&& $FileName =~ m@
$::BlockPathAccess@
;
6240 # Recursively list files in all directories
6243 $FileName =~ m@
([^/]*)$@
;
6245 print "<$Prefix>$DirName\n";
6246 $Pattern =~ m@
([^/]*)$@
;
6247 &ListDocs
("$`$DirName/$1", $ListType);
6251 elsif(-T
"$FileName")
6253 open(TextFile
, $FileName) || next;
6255 # Ignore all other file types
6259 # Get file path for link
6260 $FileName =~ /$::CGI_HOME/;
6261 print "<$Prefix><a href=$URL_root$'>";
6262 # Initialize all variables
6267 # Read file and step through
6273 if($FileName =~ /\.ht[a-zA-Z]*$/i)
6278 if($Line =~ m@
<title
>([^<]*)</title
>@i)
6285 $Line .= <TextFile> || goto Print;
6289 # Catch First Header
6292 if($Line =~ m@</h1>@i)
6296 $Caption =~ m@
<h1
>@i;
6298 $Line = $`.$Caption.$Line;
6302 $Line .= <TextFile> || goto Print;
6310 # Title equals file name
6311 $FileName =~ /([^\/]+)$/;
6313 # Catch equals First Meaningfull line
6316 if($Line =~ /[A-Z]/ &&
6317 ($Line =~ /subject|title/i || $Line =~ /^[\w,\.\s\?\:]+$/)
6318 && $Line !~ /Newsgroup/ && $Line !~ /\:\s*$/)
6320 $Line =~ s/\<[^\>]+\>//g;
6325 $Line = <TextFile> || goto Print;
6329 Print: # Print title and subject
6330 print "$Title</a>\n";
6331 print "<dd>$Caption\n" if $ListType eq "dl";
6338 # Print Closing List Marker
6339 print "</$ListType>\n";
6340 ""; # Empty return value
6344 # HTMLdocTree(Pattern [,ListType])
6347 # <SCRIPT TYPE=text/ssperl>
6348 # CGIscriptor::HTMLdocTree("/Welcome.html", "dl");
6351 # The following subroutine is very usefull for checking large document
6352 # trees. Starting from the root (s), it reads all files and prints out
6353 # a nested list of links to all attached files. Non-existing or misplaced
6354 # files are flagged. This is quite a file-i/o intensive routine
6355 # so you would not like it to be accessible to everyone. If you want to
6356 # use the result, save the whole resulting page to disk and use a link
6359 # HTMLdocTree takes an HTML file or file pattern and constructs nested lists
6360 # with links to *local* files (i.e., only links to the local server are
6361 # followed). The list entries are the document titles.
6362 # If the list type is <dl>, the first <H1> header is used too.
6363 # For each file matching the pattern, a list is made recursively of all
6364 # HTML documents that are linked from it and are stored in the same directory
6365 # or a sub-directory. Warnings are given for missing files.
6366 # The listing starts for the ServerRoot directory.
6367 # You can change the default list type <dl> (<dl>, <ul>, <ol>).
6371 sub HTMLdocTree # ($Pattern [, listtype])
6372 # e.g., ("/Welcome.html", [, "ul"])
6374 my $Pattern = shift;
6375 my $ListType = shift || "dl";
6376 my $Prefix = lc($ListType) eq "dl" ? "dt" : "li";
6377 my $URL_root = "http://$::ENV{'SERVER_NAME
'}\:$::ENV{'SERVER_PORT
'}";
6378 my ($Filename, $Path, $Link);
6379 my %LocalLinks = {};
6381 # Read files (glob them for expansion of wildcards)
6382 my @FileList = glob("$::CGI_HOME$Pattern");
6383 foreach $Path (@FileList)
6386 $Path =~ /$::CGI_HOME/;
6388 # Check whether this file should be visible
6389 next if $::BlockPathAccess
&& $URL_path =~ m@
$::BlockPathAccess@
;
6391 my $Title = $URL_path;
6393 # Current file should not be used again
6394 ++$LinkUsed{$URL_path};
6396 unless(open(TextFile
, $Path))
6398 print "<$Prefix>$Title <blink>(not found)</blink><br>\n";
6406 while($Line =~ m@
<title
>@i)
6408 if($Line =~ m@
<title
>([^<]*)</title
>@i)
6415 $Line .= <TextFile>;
6419 # Catch First Header
6420 while(!$Caption && $Line =~ m@<h1>@i)
6422 if($Line =~ m@</h[1-9]>@i)
6426 $Caption =~ m@
<h1
>@i;
6428 $Line = $`.$Caption.$Line;
6432 $Line .= <TextFile>;
6436 # Catch and print Links
6437 while($Line =~ m@<a href\=([^>]*)>@i)
6444 $Link =~ s/[\#\?].*$//g;
6446 if($Link =~ m@
(http
://|^)@i)
6449 # Only build tree for current server
6450 next unless $Link =~ m@$::ENV{'SERVER_NAME
'}|^/@;
6451 # Remove server name and port
6452 $Link =~ s@^[^\/]*@@g;
6454 # Store the current link
6455 next if $LinkUsed{$Link} || $Link eq $URL_path;
6457 ++$LocalLinks{$Link};
6463 print "<a href=http://";
6464 print "$::ENV{'SERVER_NAME
'}\:$::ENV{'SERVER_PORT
'}$URL_path>";
6465 print "$Title</a>\n";
6466 print "<br>$Caption\n"
6467 if $Caption && $Caption ne $Title && $ListType =~ /dl/i;
6468 print "<$ListType>\n";
6469 foreach $Link (keys(%LocalLinks))
6471 &HTMLdocTree($Link, $ListType);
6473 print "</$ListType>\n";
6477 ###########################<<<<<<<<<<End Remove
6479 # Make require happy
6488 A flexible HTML 4 compliant script/module for CGI-aware
6489 embeded Perl, shell-scripts, and other scripting languages,
6490 executed at the server side.
6494 Executes embeded Perl code in HTML pages with easy
6495 access to CGI variables. Also processes embeded shell
6496 scripts and scripts in any other language with an
6497 interactive interpreter (e.g., in-line Python, Tcl,
6498 Ruby, Awk, Lisp, Xlispstat, Prolog, M4, R, REBOL, Praat,
6499 sh, bash, csh, ksh).
6501 CGIscriptor is very flexible and hides all the specifics
6502 and idiosyncrasies of correct output and CGI coding and naming.
6503 CGIscriptor complies with the W3C HTML 4.0 recommendations.
6505 This Perl program will run on any WWW server that runs
6506 Perl scripts, just add a line like the following to your
6507 srm.conf file (Apache example):
6509 ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
6511 URL's that refer to http
://www
.your
.address
/SHTML/... will
6512 now be handled by CGIscriptor
.pl
, which can
use a private
6513 directory tree
(default is the DOCUMENT_ROOT directory tree
,
6514 but it can be anywhere
).
6516 =head1 PREREQUISITES
6524 Linux, *BSD, *nix, MS WinXP
6526 =pod SCRIPT CATEGORIES