Added documentation of USEFAT
[CGIscriptor.git] / CGIscriptor.pl
blob7d818bd360990b385886ae9d9d71c14ba5caec7c
1 #! /usr/bin/perl
3 # (configure the first line to contain YOUR path to perl 5.000+)
5 # CGIscriptor.pl
6 # Version 2.4
7 # 10 July 2012
9 # YOU NEED:
11 # perl 5.0 or higher (see: "http://www.perl.org/")
13 # Notes:
15 if(grep(/\-\-help/i, @ARGV))
17 print << 'ENDOFPREHELPTEXT1';
18 # CGIscriptor.pl is a Perl program will run on any WWW server that
19 # runs Perl scripts, just add a line like the following to your
20 # httpd.conf file (Apache example):
22 # ScriptAlias /SHTML/ "/real-path/CGIscriptor.pl/"
24 # URL's that refer to http://www.your.address/SHTML/... will now be handled
25 # by CGIscriptor.pl, which can use a private directory tree (default is the
26 # DOCUMENT_ROOT directory tree, but it can be anywhere, see below).
27 # NOTE: if you cannot use a ScriptAlias, there is a way to use .htaccess
28 # instead. See below.
30 # This file contains all documentation as comments. These comments
31 # can be removed to speed up loading (e.g., `egrep -v '^#' CGIscriptor.pl` >
32 # leanScriptor.pl). A bare bones version of CGIscriptor.pl, lacking
33 # documentation, most comments, access control, example functions etc.
34 # (but still with the copyright notice and some minimal documentation)
35 # can be obtained by calling CGIscriptor.pl with the '-slim'
36 # command line argument, e.g.,
37 # >CGIscriptor.pl -slim >slimCGIscriptor.pl
39 # CGIscriptor.pl can be run from the command line as
40 # `CGIscriptor.pl <path> <query>`, inside a perl script with
41 # 'do CGIscriptor.pl' after setting $ENV{PATH_INFO} and $ENV{QUERY_STRING},
42 # or CGIscriptor.pl can be loaded with 'require "/real-path/CGIscriptor.pl"'.
43 # In the latter case, requests are processed by 'Handle_Request();'
44 # (again after setting $ENV{PATH_INFO} and $ENV{QUERY_STRING}).
46 # The --help command line switch will print the manual.
48 # Running demo's and more information can be found at
49 # http://www.fon.hum.uva.nl/rob/OSS/OSS.html
51 # A pocket-size HTTP daemon, CGIservlet.pl, is available from my web site
52 # or CPAN that can use CGIscriptor.pl as the base of a µWWW server and
53 # demonstrates its use.
55 ENDOFPREHELPTEXT1
58 # Configuration, copyright notice, and user manual follow the next
59 # (Changes) section.
61 ############################################################################
63 # Changes (document ALL changes with date, name and email here):
64 # 10 Feb 2014 - Added use of FAT fs and spaces in filenames
65 # 06 Feb 2014 - Corrected behavior of ACCEPT.lis and REJECT.lis
66 # 05 Apr 2013 - Renamed COOKIE_JAR to HTTP_COOKIE, added support for
67 # CGI::Cookie in case $ENV{HTTP_COOKIE} is undefined (untested)
68 # 31 Mar 2013 - Added support for Digest::SHA
69 # 13 Mar 2013 - Changed password hash
70 # 10 Jul 2012 - Version 2.4
71 # 11 Jun 2012 - Securing CGIvariable setting. Made
72 # 'if($ENV{QUERY_STRING} =~ /$name/)' into elsif in
73 # defineCGIvariable/List/Hash to give precedence to ENV{$name}
74 # This was a very old security bug. Added ProtectCGIvariable($name).
75 # 06 Jun 2012 - Added IP only session types after login.
76 # 31 May 2012 - Session ticket system added for handling login sessions.
77 # 29 May 2012 - CGIsafeFileName does not accept filenames starting with '.'
78 # 29 May 2012 - Added CGIscriptor::BrowseAllDirs to handle browsing directories
79 # correctly.
80 # 22 May 2012 - Added Access control with Session Tickets linked to
81 # IP Address and PATH_INFO.
82 # 21 May 2012 - Corrected the links generated by CGIscriptor::BrowseDirs
83 # Will link to current base URL when the HTTP server is '.' or '~'
84 # 29 Oct 2009 - Adapted David A. Wheeler's suggestion about filenames:
85 # CGIsafeFileName does not accept filenames starting with '-'
86 # (http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html)
87 # 08 Oct 2009 - Some corrections in the README.txt file, eg, new email address
88 # 28 Jan 2005 - Added a file selector to performTranslation.
89 # Changed %TranslationTable to @TranslationTable
90 # and patterns to lists.
91 # 27 Jan 2005 - Added a %TranslationTable with associated
92 # performTranslation(\$text) function to allow
93 # run changes in the web pages. Say, to translate
94 # legacy pages with <%=...%> delimiters to the new
95 # <SCRIPT TYPE=..></SCRIPT> format.
96 # 27 Jan 2005 - Small bug of extra '\n' in output removed from the
97 # Other Languages Code.
98 # 10 May 2004 - Belated upload of latest version (2.3) to CPAN
99 # 07 Oct 2003 - Corrected error '\s' -> '\\s' in rebol scripting
100 # language call
101 # 07 Oct 2003 - Corrected omitted INS tags in <DIV><INS> handling
102 # 20 May 2003 - Added a --help switch to print the manual.
103 # 06 Mar 2003 - Adapted the blurb at the end of the file.
104 # 03 Mar 2003 - Added a user definable dieHandler function to catch all
105 # "die" calls. Also "enhanced" the STDERR printout.
106 # 10 Feb 2003 - Split off the reading of the POST part of a query
107 # from Initialize_output. This was suggested by Gerd Franke
108 # to allow for the catching of the file_path using a
109 # POST based lookup. That is, he needed the POST part
110 # to change the file_path.
111 # 03 Feb 2003 - %{$name}; => %{$name} = (); in defineCGIvariableHash.
112 # 03 Feb 2003 - \1 better written as $1 in
113 # $directive =~ s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/$1/g
114 # 29 Jan 2003 - This makes "CLASS="ssperl" CSS-compatible Gerd Franke
115 # added:
116 # $ServerScriptContentClass = "ssperl";
117 # changed in ProcessFile():
118 # unless(($CurrentContentType =~
119 # 28 Jan 2003 - Added 'INS' Tag! Gerd Franke
120 # 20 Dec 2002 - Removed useless $Directoryseparator variable.
121 # Update comments and documentation.
122 # 18 Dec 2002 - Corrected bug in Accept/Reject processing.
123 # Files didn't work.
124 # 24 Jul 2002 - Added .htaccess documentation (from Gerd Franke)
125 # Also added a note that RawFilePattern can be a
126 # complete file name.
127 # 19 Mar 2002 - Added SRC pseudo-files PREFIX and POSTFIX. These
128 # switch to prepending or to appending the content
129 # of the SRC attribute. Default is prefixing. You
130 # can add as many of these switches as you like.
131 # 13 Mar 2002 - Do not search for tag content if a tag closes with
132 # />, i.e., <DIV ... /> will be handled the XML/XHTML way.
133 # 25 Jan 2002 - Added 'curl' and 'snarf' to SRC attribute URL handling
134 # (replaces wget).
135 # 25 Jan 2002 - Found a bug in SAFEqx, now executes qx() in a scalar context
136 # (i.o. a list context). This is necessary for binary results.
137 # 24 Jan 2002 - Disambiguated -T $SRCfile to -T "$SRCfile" (and -e) and
138 # changed the order of if/elsif to allow removing these
139 # conditions in systems with broken -T functions.
140 # (I also removed a spurious ')' bracket)
141 # 17 Jan 2002 - Changed DIV tag SRC from <SOURCE> to sysread(SOURCE,...)
142 # to support binary files.
143 # 17 Jan 2002 - Removed WhiteSpace from $FileAllowedCharacters.
144 # 17 Jan 2002 - Allow "file://" prefix in SRC attribute. It is simply
145 # stipped from the path.
146 # 15 Jan 2002 - Version 2.2
147 # 15 Jan 2002 - Debugged and completed URL support (including
148 # CGIscriptor::read_url() function)
149 # 07 Jan 2002 - Added automatic (magic) URL support to the SRC attribute
150 # with the main::GET_URL function. Uses wget -O underlying.
151 # 04 Jan 2002 - Added initialization of $NewDirective in InsertForeignScript
152 # (i.e., my $NewDirective = "";) to clear old output
153 # (this was a realy anoying bug).
154 # 03 Jan 2002 - Added a <DIV CLASS='text/ssperl' ID='varname'></DIV>
155 # tags that assign the body text as-is (literally)
156 # to $varname. Allows standard HTML-tools to handle
157 # Cascading Style Sheet templates. This implements a
158 # design by Gerd Franke (franke@roo.de).
159 # 03 Jan 2002 - I finaly gave in and allowed SRC files to expand ~/.
160 # 12 Oct 2001 - Normalized spelling of "CGIsafFileName" in documentation.
161 # 09 Oct 2001 - Added $ENV{'CGI_BINARY_FILE'} to log files to
162 # detect unwanted indexing of TAR files by webcrawlers.
163 # 10 Sep 2001 - Added $YOUR_SCRIPTS directory to @INC for 'require'.
164 # 22 Aug 2001 - Added .txt (Content-type: text/plain) as a default
165 # processed file type. Was processed via BinaryMapFile.
166 # 31 May 2001 - Changed =~ inside CGIsafeEmailAddress that was buggy.
167 # 29 May 2001 - Updated $CGI_HOME to point to $ENV{DOCUMENT_ROOT} io
168 # the root of PATH_TRANSLATED. DOCUMENT_ROOT can now
169 # be manipulated to achieve a "Sub Root".
170 # NOTE: you can have $YOUR_HTML_FILES != DOCUMENT_ROOT
171 # 28 May 2001 - Changed CGIscriptor::BrowsDirs function for security
172 # and debugging (it now works).
173 # 21 May 2001 - defineCGIvariableHash will ADD values to existing
174 # hashes,instead of replacing existing hashes.
175 # 17 May 2001 - Interjected a '&' when pasting POST to GET data
176 # 24 Apr 2001 - Blocked direct requests for BinaryMapFile.
177 # 16 Aug 2000 - Added hash table extraction for CGI parameters with
178 # CGIparseValueHash (used with structured parameters).
179 # Use: CGI='%<CGI-partial-name>' (fill in your name in <>)
180 # Will collect all <CGI-partial-name><key>=value pairs in
181 # $<CGI-partial-name>{<key>} = value;
182 # 16 Aug 2000 - Adapted SAFEqx to protect @PARAMETER values.
183 # 09 Aug 2000 - Added support for non-filesystem input by way of
184 # the CGI_FILE_CONTENTS and CGI_DATA_ACCESS_CODE
185 # environment variables.
186 # 26 Jul 2000 - On the command-line, file-path '-' indicates STDIN.
187 # This allows CGIscriptor to be used in pipes.
188 # Default, $BLOCK_STDIN_HTTP_REQUEST=1 will block this
189 # in an HTTP request (i.e., in a web server).
190 # 26 Jul 2000 - Blocked 'Content-type: text/html' if the SERVER_PROTOCOL
191 # is not HTTP or another protocol. Changed the default
192 # source directory to DOCUMENT_ROOT (i.o. the incorrect
193 # SERVER_ROOT).
194 # 24 Jul 2000 - -slim Command-line argument added to remove all
195 # comments, security, etc.. Updated documentation.
196 # 05 Jul 2000 - Added IF and UNLESS attributes to make the
197 # execution of all <META> and <SCRIPT> code
198 # conditional.
199 # 05 Jul 2000 - Rewrote and isolated the code for extracting
200 # quoted items from CGI and SRC attributes.
201 # Now all attributes expect the same set of
202 # quotes: '', "", ``, (), {}, [] and the same
203 # preceded by a \, e.g., "\((aap)\)" will be
204 # extracted as "(aap)".
205 # 17 Jun 2000 - Construct @ARGV list directly in CGIexecute
206 # name-space (i.o. by evaluation) from
207 # CGI attributes to prevent interference with
208 # the processing for non perl scripts.
209 # Changed CGIparseValueList to prevent runaway
210 # loops.
211 # 16 Jun 2000 - Added a direct (interpolated) display mode
212 # (text/ssdisplay) and a user log mode
213 # (text/sslogfile).
214 # 06 Jun 2000 - Replace "print $Result" with a syswrite loop to
215 # allow large string output.
216 # 02 Jun 2000 - Corrected shrubCGIparameter($CGI_VALUE) to realy
217 # remove all control characters. Changed Interpreter
218 # initialization to shrub interpolated CGI parameters.
219 # Added 'text/ssmailto' interpreter script.
220 # 22 May 2000 - Changed some of the comments
221 # 09 May 2000 - Added list extraction for CGI parameters with
222 # CGIparseValueList (used with multiple selections).
223 # Use: CGI='@<CGI-parameter>' (fill in your name in <>)
224 # 09 May 2000 - Added a 'Not Present' condition to CGIparseValue.
225 # 27 Apr 2000 - Updated documentation to reflect changes.
226 # 27 Apr 2000 - SRC attribute "cleaned". Supported for external
227 # interpreters.
228 # 27 Apr 2000 - CGI attribute can be used in <SCRIPT> tag.
229 # 27 Apr 2000 - Gprolog, M4 support added.
230 # 26 Apr 2000 - Lisp (rep) support added.
231 # 20 Apr 2000 - Use of external interpreters now functional.
232 # 20 Apr 2000 - Removed bug from extracting Content types (RegExp)
233 # 10 Mar 2000 - Qualified unconditional removal of '#' that preclude
234 # the use of $#foo, i.e., I changed
235 # s/[^\\]\#[^\n\f\r]*([\n\f\r])/\1/g
236 # to
237 # s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/\1/g
238 # 03 Mar 2000 - Added a '$BlockPathAccess' variable to "hide"
239 # things like, e.g., CVS information in CVS subtrees
240 # 10 Feb 2000 - URLencode/URLdecode have been made case-insensitive
241 # 10 Feb 2000 - Added a BrowseDirs function (CGIscriptor package)
242 # 01 Feb 2000 - A BinaryMapFile in the ~/ directory has precedence
243 # over a "burried" BinaryMapFile.
244 # 04 Oct 1999 - Added two functions to check file names and email addresses
245 # (CGIscriptor::CGIsafeFileName and
246 # CGIscriptor::CGIsafeEmailAddress)
247 # 28 Sept 1999 - Corrected bug in sysread call for reading POST method
248 # to allow LONG posts.
249 # 28 Sept 1999 - Changed CGIparseValue to handle multipart/form-data.
250 # 29 July 1999 - Refer to BinaryMapFile from CGIscriptor directory, if
251 # this directory exists.
252 # 07 June 1999 - Limit file-pattern matching to LAST extension
253 # 04 June 1999 - Default text/html content type is printed only once.
254 # 18 May 1999 - Bug in replacement of ~/ and ./ removed.
255 # (Rob van Son, R.J.J.H.vanSon@gmail.com)
256 # 15 May 1999 - Changed the name of the execute package to CGIexecute.
257 # Changed the processing of the Accept and Reject file.
258 # Added a full expression evaluation to Access Control.
259 # (Rob van Son, R.J.J.H.vanSon@gmail.com)
260 # 27 Apr 1999 - Brought CGIscriptor under the GNU GPL. Made CGIscriptor
261 # Version 1.1 a module that can be called with 'require "CGIscriptor.pl"'.
262 # Requests are serviced by "Handle_Request()". CGIscriptor
263 # can still be called as a isolated perl script and a shell
264 # command.
265 # Changed the "factory default setting" so that it will run
266 # from the DOCUMENT_ROOT directory.
267 # (Rob van Son, R.J.J.H.vanSon@gmail.com)
268 # 29 Mar 1999 - Remove second debugging STDERR switch. Moved most code
269 # to subroutines to change CGIscriptor into a module.
270 # Added mapping to process unsupported file types (e.g., binary
271 # pictures). See $BinaryMapFile.
272 # (Rob van Son, R.J.J.H.vanSon@gmail.com)
273 # 24 Sept 1998 - Changed text of license (Rob van Son, R.J.J.H.vanSon@gmail.com)
274 # Removed a double setting of filepatterns and maximum query
275 # size. Changed email address. Removed some typos from the
276 # comments.
277 # 02 June 1998 - Bug fixed in URLdecode. Changing the foreach loop variable
278 # caused quiting CGIscriptor.(Rob van Son, R.J.J.H.vanSon@gmail.com)
279 # 02 June 1998 - $SS_PUB and $SS_SCRIPT inserted an extra /, removed.
280 # (Rob van Son, R.J.J.H.vanSon@gmail.com)
283 # Known Bugs:
285 # 23 Mar 2000
286 # It is not possible to use operators or variables to construct variable names,
287 # e.g., $bar = \@{$foo}; won't work. However, eval('$bar = \@{'.$foo.'};');
288 # will indeed work. If someone could tell me why, I would be obliged.
291 ############################################################################
293 # OBLIGATORY USER CONFIGURATION
295 # Configure the directories where all user files can be found (this
296 # is the equivalent of the server root directory of a WWW-server).
297 # These directories can be located ANYWHERE. For security reasons, it is
298 # better to locate them outside the WWW-tree of your HTTP server, unless
299 # CGIscripter handles ALL requests.
301 # For convenience, the defaults are set to the root of the WWW server.
302 # However, this might not be safe!
304 # ~/ text files
305 # $YOUR_HTML_FILES = "/usr/pub/WWW/SHTML"; # or SS_PUB as environment var
306 # (patch to use the parent directory of CGIscriptor as document root, should be removed)
307 if($ENV{'SCRIPT_FILENAME'}) # && $ENV{'SCRIPT_FILENAME'} !~ /\Q$ENV{'DOCUMENT_ROOT'}\E/)
309 $ENV{'DOCUMENT_ROOT'} = $ENV{'SCRIPT_FILENAME'};
310 $ENV{'DOCUMENT_ROOT'} =~ s@/CGIscriptor.*$@@ig;
313 # Just enter your own directory path here
314 $YOUR_HTML_FILES = $ENV{'DOCUMENT_ROOT'}; # default is the DOCUMENT_ROOT
316 # ./ script files (recommended to be different from the previous)
317 # $YOUR_SCRIPTS = "/usr/pub/WWW/scripts"; # or SS_SCRIPT as environment var
318 $YOUR_SCRIPTS = $YOUR_HTML_FILES; # This might be a SECURITY RISK
320 # End of obligatory user configuration
321 # (note: there is more non-essential user configuration below)
323 ############################################################################
325 # OPTIONAL USER CONFIGURATION (all values are used CASE INSENSITIVE)
327 # Script content-types: TYPE="Content-type" (user defined mime-type)
328 $ServerScriptContentType = "text/ssperl"; # Server Side Perl scripts
329 # CSS require a simple class
330 $ServerScriptContentClass = $ServerScriptContentType =~ m!/! ?
331 $' : "ssperl"; # Server Side Perl CSS classes
333 $ShellScriptContentType = "text/osshell"; # OS shell scripts
334 # # (Server Side perl ``-execution)
336 # Run from FAT file systems (Windows) based on environment variable
337 $useFAT = $ENV{'USEFAT'};
338 # Accessible file patterns, block any request that doesn't match.
339 # Matches any file with the extension .(s)htm(l), .txt, or .xmr
340 # (\. is used in regexp)
341 # Note: die unless $PATH_INFO =~ m@($FilePattern)$@is;
342 $FilePattern = ".shtml|.htm|.html|.xml|.xmr|.txt|.js|.css";
344 # The table with the content type MIME types
345 # (allows to differentiate MIME types, if needed)
346 %ContentTypeTable =
348 '.html' => 'text/html',
349 '.shtml' => 'text/html',
350 '.htm' => 'text/html',
351 '.xml' => 'text/xml',
352 '.txt' => 'text/plain',
353 '.js' => 'text/plain',
354 '.css' => 'text/plain'
358 # File pattern post-processing
359 $FilePattern =~ s/([@.])/\\$1/g; # Convert . and @ to \. and \@
361 # SHAsum command needed for Authorization and Login
362 # (note, these have to be accessible in the HTML pages, ie, the CGIexecute environment)
363 my $shasum = "shasum -a 256";
364 if(qx{uname} =~ /Darwin/)
366 $shasum = "shasum-5.12 -a 256" unless `which shasum`;
368 my $SHASUMCMD = $shasum.' |cut -f 1 -d" "';
369 $ENV{"SHASUMCMD"} = $SHASUMCMD;
370 my $RANDOMHASHCMD = 'dd bs=1 count=64 if=/dev/urandom 2>/dev/null | '.$shasum.' -b |cut -f 1 -d" "';
371 $ENV{"RANDOMHASHCMD"} = $RANDOMHASHCMD;
373 # Hash a string, return hex of hash
374 sub hash_string_cmd # ($string) -> hex_hash
376 my $string = shift || "";
377 # Catch nasty \'-quotes, embed them in '..'"'"'..'
378 $string =~ s/\'/\'\"\'\"\'/isg;
379 my $hash = `printf '%s' '$string'| $ENV{"SHASUMCMD"}`;
380 chomp($hash);
381 return $hash;
384 # Note that you CANNOT replace $RANDOMHASHCMD with a call using hash_string_cmd
385 # as the output of /dev/urandom breaks string handling in Perl.
386 # Generate random hex hash
387 sub get_random_hex_cmd # () -> hex
389 # Create Random Hash Salt
390 open(URANDOM, "$RANDOMHASHCMD |") || die "URANDOM; $RANDOMHASHCMD | $!\n";
391 my $RANDOMSALT= <URANDOM>;
392 close(URANDOM);
393 chomp($RANDOMSALT);
395 return $RANDOMSALT;
399 # You can use Digest::SHA (SHA.pm), you need sha256_hex
400 # See http://search.cpan.org/~mshelor/Digest-SHA-5.84/lib/Digest/SHA.pm
401 # > sudo CPAN -i Digest
403 # The following code will check whether Digest::SHA is available and then
404 # use the appropriate function calls.
406 $shaDigestLoaded = (eval("require Digest::SHA;1;") eq "1") ? 1 : 0;
408 sub hash_string_Digest # ($string) -> hex_hash
410 my $string = shift || "";
411 my $digest = Digest::SHA::sha256_hex($string);
412 $string = $digest;
413 return $digest;
416 sub get_random_hex_Digest # () -> hex
418 my $randomstring = "";
419 # Create Random Hash Salt
420 open(URANDOM, "</dev/urandom") || die "/dev/urandom: $!\n";
421 read URANDOM, $randomstring, 64 || die "No random bytes read: $!\n";
422 close(URANDOM);
423 my $RANDOMSALT= hash_string_Digest($randomstring);
425 return $RANDOMSALT;
428 # The final functions
429 sub hash_string # ($string) -> hex_hash
431 if($shaDigestLoaded)
432 { return hash_string_Digest (@_) }
433 else
434 { return hash_string_cmd(@_);};
437 sub get_random_hex # () -> hex
439 if($shaDigestLoaded)
440 { return get_random_hex_Digest () }
441 else
442 { return get_random_hex_cmd();};
445 ######################################################################
447 # File patterns of files which are handled by session tickets.
448 %TicketRequiredPatterns = (
449 '^/Private(/|$)' => "Private/.Sessions\tPrivate/.Passwords\t/Private/Login.html\t+36000"
451 # Used to set cookies, only session cookies supported
452 my %SETCOOKIELIST = ();
453 my %CGI_Cookies = ();
454 # Parse the cookies if $ENV{'HTTP_COOKIE'} is defined, else use CGI::Cookie
455 # if it is available
456 sub Get_All_Cookies
458 $ENV{'HTTP_COOKIE'} = $ENV{'Cookie'} if defined($ENV{'Cookie'}) && !defined($ENV{'HTTP_COOKIE'});
460 if(defined($ENV{'HTTP_COOKIE'}))
462 my @CookieList = split(/[\;\s]+/, $ENV{'HTTP_COOKIE'});
463 foreach my $CookieEntry (@CookieList)
465 my ($k, $v) = split(/\=/, $CookieEntry);
466 # Add new cookie only if it does not already exist
467 $CGI_Cookies{$k} = $v unless exists($CGI_Cookies{$k}) && ($v eq "" || $v eq "-");
468 ($k, $v, $CookieEntry) = (0, 0, 0);
470 @CookieList = ();
471 $ENV{'Cookie'} = "" if defined($ENV{'Cookie'})
473 else
475 my $cookiesLoaded = (eval("require CGI::Cookie;1;") eq "1") ? 1 : 0;
476 if($cookiesLoaded)
478 %CGI_Cookies = fetch CGI::Cookie;
484 # Session Ticket Directory: Private/.Sessions
485 # Password Directory: Private/.Passwords
486 # Login page (url path): /Private/Login.html
487 # Expiration time (s): +3600
488 # +<seconds> = relative time <seconds> is absolute date-time
490 # Manage login
491 # Set up a valid ticket from a given text file
492 # Use from command line. DO NOT USE ONLINE
493 # Watch out for passwords that get stored in the history file
495 # perl CGIscriptor.pl --managelogin [options] [files]
496 # Options:
497 # salt={file or saltvalue}
498 # masterkey={file or plaintext}
499 # newmasterkey={file or plaintext}
500 # password={file or palintext}
502 # Followed by one or more file names.
503 # Options can be interspersed between filenames,
504 # e.g., password='plaintext'
505 # Note that passwords are only used once!
507 if($ARGV[0] =~ /^\-\-managelogin/i)
509 my @arguments = @ARGV;
510 shift(@arguments);
511 setup_ticket_file(@arguments);
512 # Should be run on the command line
513 exit;
518 # Raw files must contain their own Content-type (xmr <- x-multipart-replace).
519 # THIS IS A SUBSET OF THE FILES DEFINED IN $FilePattern
520 $RawFilePattern = ".xmr";
521 # (In principle, this could contain a full file specification, e.g.,
522 # ".xmr|relocated.html")
524 # Raw File pattern post-processing
525 $RawFilePattern =~ s/([@.])/\\$1/g; # Convert . and @ to \. and \@
527 # Server protocols for which "Content-type: text/html\n\n" should be printed
528 # (you should not bother with these, except for HTTP, they are mostly imaginary)
529 $ContentTypeServerProtocols = 'HTTP|MAIL|MIME';
531 # Block access to all (sub-) paths and directories that match the
532 # following (URL) path (is used as:
533 # 'die if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@;' )
534 $BlockPathAccess = '/(CVS|\.git)/'; # Protect CVS and .git information
536 # All (blocked) other file-types can be mapped to a single "binary-file"
537 # processor (a kind of pseudo-file path). This can either be an error
538 # message (e.g., "illegal file") or contain a script that serves binary
539 # files.
540 # Note: the real file path wil be stored in $ENV{CGI_BINARY_FILE}.
541 $BinaryMapFile = "/BinaryMapFile.xmr";
542 # Allow for the addition of a CGIscriptor directory
543 # Note that a BinaryMapFile in the root "~/" directory has precedence
544 $BinaryMapFile = "/CGIscriptor".$BinaryMapFile
545 if ! -e "$YOUR_HTML_FILES".$BinaryMapFile
546 && -e "$YOUR_HTML_FILES/CGIscriptor".$BinaryMapFile;
549 # List of all characters that are allowed in file names and paths.
550 # All requests containing illegal characters are blocked. This
551 # blocks most tricks (e.g., adding "\000", "\n", or other control
552 # characters, also blocks URI's using %FF)
553 # THIS IS A SECURITY FEATURE
554 # (this is also used to parse filenames in SRC= features, note the
555 # '-quotes, they are essential)
556 $FileAllowedChars = '\w\.\~\/\:\*\?\-\ '; # Covers Unix and Mac, including spaces
558 # Maximum size of the Query (number of characters clients can send
559 # covers both GET & POST combined)
560 $MaximumQuerySize = 2**20 - 1; # = 2**14 - 1
563 # Embeded URL get function used in SRC attributes and CGIscriptor::read_url
564 # (returns a string with the PERL code to transfer the URL contents, e.g.,
565 # "SAFEqx(\'curl \"http://www.fon.hum.uva.nl\"\')")
566 # "SAFEqx(\'wget --quiet --output-document=- \"http://www.fon.hum.uva.nl\"\')")
567 # Be sure to handle <BASE HREF='URL'> and allow BOTH
568 # direct printing GET_URL($URL [, 0]) and extracting the content of
569 # the $URL for post-processing GET_URL($URL, 1).
570 # You get the WHOLE file, including HTML header.
571 # The shell command Use $URL where the URL should go
572 # ('wget', 'snarf' or 'curl', uncomment the one you would like to use)
573 my $GET_URL_shell_command = 'wget --quiet --output-document=- $URL';
574 #my $GET_URL_shell_command = 'snarf $URL -';
575 #my $GET_URL_shell_command = 'curl $URL';
577 sub GET_URL # ($URL, $ValueNotPrint) -> content_of_url
579 my $URL = shift || return;
580 my $ValueNotPrint = shift || 0;
582 # Check URL for illegal characters
583 return "print '<h1>Illegal URL<h1>'\"\n\";" if $URL =~ /[^$FileAllowedChars\%]/;
585 # Include URL in final command
586 my $CurrentCommand = $GET_URL_shell_command;
587 $CurrentCommand =~ s/\$URL/$URL/g;
589 # Print to STDOUT or return a value
590 my $BlockPrint = "print STDOUT ";
591 $BlockPrint = "" if $ValueNotPrint;
593 my $Commands = <<"GETURLCODE";
594 # Get URL
596 my \$Page = "";
598 # Simple, using shell command
599 \$Page = SAFEqx('$CurrentCommand');
601 # Add a BASE tage to the header
602 \$Page =~ s!\\</head!\\<base href='$URL'\\>\\</head!ig unless \$Page =~ m!\\<base!;
604 # Print the URL value, or return it as a value
605 $BlockPrint\$Page;
607 GETURLCODE
608 return $Commands;
611 # As files can get rather large (and binary), you might want to use
612 # some more intelligent reading procedure, e.g.,
613 # Direct Perl
614 # # open(URLHANDLE, '/usr/bin/wget --quiet --output-document=- "$URL"|') || die "wget: \$!";
615 # #open(URLHANDLE, '/usr/bin/snarf "$URL" -|') || die "snarf: \$!";
616 # open(URLHANDLE, '/usr/bin/curl "$URL"|') || die "curl: \$!";
617 # my \$text = "";
618 # while(sysread(URLHANDLE,\$text, 1024) > 0)
620 # \$Page .= \$text;
621 # };
622 # close(URLHANDLE) || die "\$!";
623 # However, this doesn't work with the CGIexecute->evaluate() function.
624 # You get an error: 'No child processes at (eval 16) line 15, <file0> line 8.'
626 # You can forget the next two variables, they are only needed when
627 # you don't want to use a regular file system (i.e., with open)
628 # but use some kind of database/RAM image for accessing (generating)
629 # the data.
631 # Name of the environment variable that contains the file contents
632 # when reading directly from Database/RAM. When this environment variable,
633 # $ENV{$CGI_FILE_CONTENTS}, is not false, no real file will be read.
634 $CGI_FILE_CONTENTS = 'CGI_FILE_CONTENTS';
635 # Uncomment the following if you want to force the use of the data access code
636 # $ENV{$CGI_FILE_CONTENTS} = '-'; # Force use of $ENV{$CGI_DATA_ACCESS_CODE}
638 # Name of the environment variable that contains the RAM access perl
639 # code needed to read additional "files", i.e.,
640 # $ENV{$CGI_FILE_CONTENTS} = eval("\@_=('$file_path'); do{$ENV{$CGI_DATA_ACCESS_CODE}}");
641 # When $ENV{$CGI_FILE_CONTENTS} eq '-', this code is executed to generate the data.
642 $CGI_DATA_ACCESS_CODE = 'CGI_DATA_ACCESS_CODE';
644 # You can, of course, fill this yourself, e.g.,
645 # $ENV{$CGI_DATA_ACCESS_CODE} =
646 # 'open(INPUT, "<$_[0]"); while(<INPUT>){print;};close(INPUT);'
649 # DEBUGGING
651 # Suppress error messages, this can be changed for debugging or error-logging
652 #open(STDERR, "/dev/null"); # (comment out for use in debugging)
654 # SPECIAL: Remove Comments, security, etc. if the command line is
655 # '>CGIscriptor.pl -slim >slimCGIscriptor.pl'
656 $TrimDownCGIscriptor = 1 if $ARGV[0] =~ /^\-slim/i;
658 # If CGIscriptor is used from the command line, the command line
659 # arguments are interpreted as the file (1st) and the Query String (rest).
660 # Get the arguments
661 $ENV{'PATH_INFO'} = shift(@ARGV) unless exists($ENV{'PATH_INFO'}) || grep(/\-\-help/i, @ARGV);
662 $ENV{'QUERY_STRING'} = join("&", @ARGV) unless exists($ENV{'QUERY_STRING'});
665 # Handle bail-outs in a user definable way.
666 # Catch Die and replace it with your own function.
667 # Ends with a call to "die $_[0];"
669 sub dieHandler # ($ErrorCode, "Message", @_) -> DEAD
671 my $ErrorCode = shift;
672 my $ErrorMessage = shift;
674 # Place your own reporting functions here
676 # Now, kill everything (default)
677 print STDERR "$ErrorCode: $ErrorMessage\n";
678 die $ErrorMessage;
682 # End of optional user configuration
683 # (note: there is more non-essential user configuration below)
685 if(grep(/\-\-help/i, @ARGV))
687 print << 'ENDOFPREHELPTEXT2';
689 ###############################################################################
691 # Author and Copyright (c):
692 # Rob van Son, © 1995,1996,1997,1998,1999,2000,2001,2002-2012
693 # NKI-AVL Amsterdam
694 # r.v.son@nki.nl
695 # Institute of Phonetic Sciences & IFOTT/ACLS
696 # University of Amsterdam
697 # Email: R.J.J.H.vanSon@gmail.com
698 # Email: R.J.J.H.vanSon@gmail.com
699 # WWW : http://www.fon.hum.uva.nl/rob/
701 # License for use and disclaimers
703 # CGIscriptor merges plain ASCII HTML files transparantly
704 # with CGI variables, in-line PERL code, shell commands,
705 # and executable scripts in other scripting languages.
707 # This program is free software; you can redistribute it and/or
708 # modify it under the terms of the GNU General Public License
709 # as published by the Free Software Foundation; either version 2
710 # of the License, or (at your option) any later version.
712 # This program is distributed in the hope that it will be useful,
713 # but WITHOUT ANY WARRANTY; without even the implied warranty of
714 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
715 # GNU General Public License for more details.
717 # You should have received a copy of the GNU General Public License
718 # along with this program; if not, write to the Free Software
719 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
722 # Contributors:
723 # Rob van Son (R.J.J.H.vanSon@gmail.com)
724 # Gerd Franke franke@roo.de (designed the <DIV> behaviour)
726 #######################################################
727 ENDOFPREHELPTEXT2
729 #######################################################>>>>>>>>>>Start Remove
731 # You can skip the following code, it is an auto-splice
732 # procedure.
734 # Construct a slimmed down version of CGIscriptor
735 # (i.e., CGIscriptor.pl -slim > slimCGIscriptor.pl)
737 if($TrimDownCGIscriptor)
739 open(CGISCRIPTOR, "<CGIscriptor.pl")
740 || dieHandler(1, "<CGIscriptor.pl not slimmed down: $!\n");
741 my $SKIPtext = 0;
742 my $SKIPComments = 0;
744 while(<CGISCRIPTOR>)
746 my $SKIPline = 0;
748 ++$LineCount;
750 # Start of SKIP text
751 $SKIPtext = 1 if /[\>]{10}Start Remove/;
752 $SKIPComments = 1 if $SKIPtext == 1;
754 # Skip this line?
755 $SKIPline = 1 if $SKIPtext || ($SKIPComments && /^\s*\#/);
757 ++$PrintCount unless $SKIPline;
759 print STDOUT $_ unless $SKIPline;
761 # End of SKIP text ?
762 $SKIPtext = 0 if /[\<]{10}End Remove/;
764 # Ready!
765 print STDERR "\# Printed $PrintCount out of $LineCount lines\n";
766 exit;
769 #######################################################
771 if(grep(/\-\-help/i, @ARGV))
773 print << 'ENDOFHELPTEXT';
775 # HYPE
777 # CGIscriptor merges plain ASCII HTML files transparantly and safely
778 # with CGI variables, in-line PERL code, shell commands, and executable
779 # scripts in many languages (on-line and real-time). It combines the
780 # "ease of use" of HTML files with the versatillity of specialized
781 # scripts and PERL programs. It hides all the specifics and
782 # idiosyncrasies of correct output and CGI coding and naming. Scripts
783 # do not have to be aware of HTML, HTTP, or CGI conventions just as HTML
784 # files can be ignorant of scripts and the associated values. CGIscriptor
785 # complies with the W3C HTML 4.0 recommendations.
786 # In addition to its use as a WWW embeded CGI processor, it can
787 # be used as a command-line document preprocessor (text-filter).
789 # THIS IS HOW IT WORKS
791 # The aim of CGIscriptor is to execute "plain" scripts inside a text file
792 # using any required CGIparameters and environment variables. It
793 # is optimized to transparantly process HTML files inside a WWW server.
794 # The native language is Perl, but many other scripting languages
795 # can be used.
797 # CGIscriptor reads text files from the requested input file (i.e., from
798 # $YOUR_HTML_FILES$PATH_INFO) and writes them to <STDOUT> (i.e., the
799 # client requesting the service) preceded by the obligatory
800 # "Content-type: text/html\n\n" or "Content-type: text/plain\n\n" string
801 # (except for "raw" files which supply their own Content-type message
802 # and only if the SERVER_PROTOCOL supports HTTP, MAIL, or MIME).
804 # When CGIscriptor encounters an embedded script, indicated by an HTML4 tag
806 # <SCRIPT TYPE="text/ssperl" [CGI="$VAR='default value'"] [SRC="ScriptSource"]>
807 # PERL script
808 # </SCRIPT>
810 # or
812 # <SCRIPT TYPE="text/osshell" [CGI="$name='default value'"] [SRC="ScriptSource"]>
813 # OS Shell script
814 # </SCRIPT>
816 # construct (anything between []-brackets is optional, other MIME-types
817 # and scripting languages are supported), the embedded script is removed
818 # and both the contents of the source file (i.e., "do 'ScriptSource'")
819 # AND the script are evaluated as a PERL program (i.e., by eval()),
820 # shell script (i.e., by a "safe" version of `Command`, qx) or an external
821 # interpreter. The output of the eval() function takes the place of the
822 # original <SCRIPT></SCRIPT> construct in the output string. Any CGI
823 # parameters declared by the CGI attribute are available as simple perl
824 # variables, and can subsequently be made available as variables to other
825 # scripting languages (e.g., bash, python, or lisp).
827 # Example: printing "Hello World"
828 # <HTML><HEAD><TITLE>Hello World</TITLE>
829 # <BODY>
830 # <H1><SCRIPT TYPE="text/ssperl">"Hello World"</SCRIPT></H1>
831 # </BODY></HTML>
833 # Save this in a file, hello.html, in the directory you indicated with
834 # $YOUR_HTML_FILES and access http://your_server/SHTML/hello.html
835 # (or to whatever name you use as an alias for CGIscriptor.pl).
836 # This is realy ALL you need to do to get going.
838 # You can use any values that are delivered in CGI-compliant form (i.e.,
839 # the "?name=value" type URL additions) transparently as "$name" variables
840 # in your scripts IFF you have declared them in the CGI attribute of
841 # a META or SCRIPT tag before e.g.:
842 # <META CONTENT="text/ssperl; CGI='$name = `default value`'
843 # [SRC='ScriptSource']">
844 # or
845 # <SCRIPT TYPE="text/ssperl" CGI="$name = 'default value'"
846 # [SRC='ScriptSource']>
847 # After such a 'CGI' attribute, you can use $name as an ordinary PERL variable
848 # (the ScriptSource file is immediately evaluated with "do 'ScriptSource'").
849 # The CGIscriptor script allows you to write ordinary HTML files which will
850 # include dynamic CGI aware (run time) features, such as on-line answers
851 # to specific CGI requests, queries, or the results of calculations.
853 # For example, if you wanted to answer questions of clients, you could write
854 # a Perl program called "Answer.pl" with a function "AnswerQuestion()"
855 # that prints out the answer to requests given as arguments. You then write
856 # an HTML page "Respond.html" containing the following fragment:
858 # <center>
859 # The Answer to your question
860 # <META CONTENT="text/ssperl; CGI='$Question'">
861 # <h3><SCRIPT TYPE="text/ssperl">$Question</SCRIPT></h3>
862 # is
863 # <h3><SCRIPT TYPE="text/ssperl" SRC="./PATH/Answer.pl">
864 # AnswerQuestion($Question);
865 # </SCRIPT></h3>
866 # </center>
867 # <FORM ACTION=Respond.html METHOD=GET>
868 # Next question: <INPUT NAME="Question" TYPE=TEXT SIZE=40><br>
869 # <INPUT TYPE=SUBMIT VALUE="Ask">
870 # </FORM>
872 # The output could look like the following (in HTML-speak):
874 # <CENTER>
875 # The Answer to your question
876 # <h3>What is the capital of the Netherlands?</h3>
877 # is
878 # <h3>Amsterdam</h3>
879 # </CENTER>
880 # <FORM ACTION=Respond.html METHOD=GET>
881 # Next question: <INPUT NAME="Question" TYPE=TEXT SIZE=40><br>
882 # <INPUT TYPE=SUBMIT VALUE="Ask">
884 # Note that the function "Answer.pl" does know nothing about CGI or HTML,
885 # it just prints out answers to arguments. Likewise, the text has no
886 # provisions for scripts or CGI like constructs. Also, it is completely
887 # trivial to extend this "program" to use the "Answer" later in the page
888 # to call up other information or pictures/sounds. The final text never
889 # shows any cue as to what the original "source" looked like, i.e.,
890 # where you store your scripts and how they are called.
892 # There are some extra's. The argument of the files called in a SRC= tag
893 # can access the CGI variables declared in the preceding META tag from
894 # the @ARGV array. Executable files are called as:
895 # `file '$ARGV[0]' ... ` (e.g., `Answer.pl \'$Question\'`;)
896 # The files called from SRC can even be (CGIscriptor) html files which are
897 # processed in-line. Furthermore, the SRC= tag can contain a perl block
898 # that is evaluated. That is,
899 # <META CONTENT="text/ssperl; CGI='$Question' SRC='{$Question}'">
900 # will result in the evaluation of "print do {$Question};" and the VALUE
901 # of $Question will be printed. Note that these "SRC-blocks" can be
902 # preceded and followed by other file names, but only a single block is
903 # allowed in a SRC= tag.
905 # One of the major hassles of dynamic WWW pages is the fact that several
906 # mutually incompatible browsers and platforms must be supported. For example,
907 # the way sound is played automatically is different for Netscape and
908 # Internet Explorer, and for each browser it is different again on
909 # Unix, MacOS, and Windows. Realy dangerous is processing user-supplied
910 # (form-) values to construct email addresses, file names, or database
911 # queries. All Apache WWW-server exploits reported in the media are
912 # based on faulty CGI-scripts that didn't check their user-data properly.
914 # There is no panacee for these problems, but a lot of work and problems
915 # can be saved by allowing easy and transparent control over which
916 # <SCRIPT></SCRIPT> blocks are executed on what CGI-data. CGIscriptor
917 # supplies such a method in the form of a pair of attributes:
918 # IF='...condition..' and UNLESS='...condition...'. When added to a
919 # script tag, the whole block (including the SRC attribute) will be
920 # ignored if the condition is false (IF) or true (UNLESS).
921 # For example, the following block will NOT be evaluated if the value
922 # of the CGI variable FILENAME is NOT a valid filename:
924 # <SCRIPT TYPE='text/ssperl' CGI='$FILENAME'
925 # IF='CGIscriptor::CGIsafeFileName($FILENAME)'>
926 # .....
927 # </SCRIPT>
929 # (the function CGIsafeFileName(String) returns an empty string ("")
930 # if the String argument is not a valid filename).
931 # The UNLESS attribute is the mirror image of IF.
933 # A user manual follows the HTML 4 and security paragraphs below.
935 ##########################################################################
937 # HTML 4 compliance
939 # In general, CGIscriptor.pl complies with the HTML 4 recommendations of
940 # the W3C. This means that any software to manage Web sites will be able
941 # to handle CGIscriptor files, as will web agents.
943 # All script code should be placed between <SCRIPT></SCRIPT> tags, the
944 # script type is indicated with TYPE="mime-type", the LANGUAGE
945 # feature is ignored, and a SRC feature is implemented. All CGI specific
946 # features are delegated to the CGI attribute.
948 # However, the behavior deviates from the W3C recommendations at some
949 # points. Most notably:
950 # 0- The scripts are executed at the server side, invissible to the
951 # client (i.e., the browser)
952 # 1- The mime-types are personal and idiosyncratic, but can be adapted.
953 # 2- Code in the body of a <SCRIPT></SCRIPT> tag-pair is still evaluated
954 # when a SRC feature is present.
955 # 3- The SRC attribute reads a list of files.
956 # 4- The files in a SRC attribute are processed according to file type.
957 # 5- The SRC attribute evaluates inline Perl code.
958 # 6- Processed META, DIV, INS tags are removed from the output
959 # document.
960 # 7- All attributes of the processed META tags, except CONTENT, are ignored
961 # (i.e., deleted from the output).
962 # 8- META tags can be placed ANYWHERE in the document.
963 # 9- Through the SRC feature, META tags can have visible output in the
964 # document.
965 # 10- The CGI attribute that declares CGI parameters, can be used
966 # inside the <SCRIPT> tag.
967 # 11- Use of an extended quote set, i.e., '', "", ``, (), {}, []
968 # and their \-slashed combinations: \'\', \"\", \`\`, \(\),
969 # \{\}, \[\].
970 # 12- IF and UNLESS attributes to <SCRIPT>, <META>, <DIV>, <INS> tags.
971 # 13- <DIV> tags cannot be nested, DIV tags are not
972 # rendered with new-lines.
973 # 14- The XML style <TAG .... /> is recognized and handled correctly.
974 # (i.e., no content is processed)
976 # The reasons for these choices are:
977 # You can still write completely HTML4 compliant documents. CGIscriptor
978 # will not force you to write "deviant" code. However, it allows you to
979 # do so (which is, in fact, just as bad). The prime design principle
980 # was to allow users to include plain Perl code. The code itself should
981 # be "enhancement free". Therefore, extra features were needed to
982 # supply easy access to CGI and Web site components. For security
983 # reasons these have to be declared explicitly. The SRC feature
984 # transparently manages access to external files, especially the safe
985 # use of executable files.
986 # The CGI attribute handles the declarations of external (CGI) variables
987 # in the SCRIPT and META tag's.
988 # EVERYTHING THE CGI ATTRIBUTE AND THE META TAG DO CAN BE DONE INSIDE
989 # A <SCRIPT></SCRIPT> TAG CONSTRUCT.
991 # The reason for the IF, UNLESS, and SRC attributes (and their Perl code
992 # evaluation) were build into the META and SCRIPT tags is part laziness,
993 # part security. The SRC blocks allows more compact documents and easier
994 # debugging. The values of the CGI variables can be immediately screened
995 # for security by IF or UNLESS conditions, and even SRC attributes (e.g.,
996 # email addresses and file names), and a few commands can be called
997 # without having to add another Perl TAG pair. This is especially important
998 # for documents that require the use of other (more restricted) "scripting"
999 # languages and facilities that lag transparent control structures.
1001 ##########################################################################
1003 # SECURITY
1005 # Your WWW site is a few keystrokes away from a few hundred million internet
1006 # users. A fair percentage of these users knows more about your computer
1007 # than you do. And some of these just might have bad intentions.
1009 # To ensure uncompromized operation of your server and platform, several
1010 # features are incorporated in CGIscriptor.pl to enhance security.
1011 # First of all, you should check the source of this program. No security
1012 # measures will help you when you download programs from anonymous sources.
1013 # If you want to use THIS file, please make sure that it is uncompromized.
1014 # The best way to do this is to contact the source and try to determine
1015 # whether s/he is reliable (and accountable).
1017 # BE AWARE THAT ANY PROGRAMMER CAN CHANGE THIS PROGRAM IN SUCH A WAY THAT
1018 # IT WILL SET THE DOORS TO YOUR SYSTEM WIDE OPEN
1020 # I would like to ask any user who finds bugs that could compromise
1021 # security to report them to me (and any other bug too,
1022 # Email: R.J.J.H.vanSon@gmail.com or ifa@hum.uva.nl).
1024 # Security features
1026 # 1 Invisibility
1027 # The inner workings of the HTML source files are completely hidden
1028 # from the client. Only the HTTP header and the ever changing content
1029 # of the output distinguish it from the output of a plain, fixed HTML
1030 # file. Names, structures, and arguments of the "embedded" scripts
1031 # are invisible to the client. Error output is suppressed except
1032 # during debugging (user configurable).
1034 # 2 Separate directory trees
1035 # Directories containing Inline text and script files can reside on
1036 # separate trees, distinct from those of the HTTP server. This means
1037 # that NEITHER the text files, NOR the script files can be read by
1038 # clients other than through CGIscriptor.pl, UNLESS they are
1039 # EXPLICITELY made available.
1041 # 3 Requests are NEVER "evaluated"
1042 # All client supplied values are used as literal values (''-quoted).
1043 # Client supplied ''-quotes are ALWAYS removed. Therefore, as long as the
1044 # embedded scripts do NOT themselves evaluate these values, clients CANNOT
1045 # supply executable commands. Be sure to AVOID scripts like:
1047 # <META CONTENT="text/ssperl; CGI='$UserValue'">
1048 # <SCRIPT TYPE="text/ssperl">$dir = `ls -1 $UserValue`;</SCRIPT>
1050 # These are a recipe for disaster. However, the following quoted
1051 # form should be save (but is still not adviced):
1053 # <SCRIPT TYPE="text/ssperl">$dir = `ls -1 \'$UserValue\'`;</SCRIPT>
1055 # A special function, SAFEqx(), will automatically do exactly this,
1056 # e.g., SAFEqx('ls -1 $UserValue') will execute `ls -1 \'$UserValue\'`
1057 # with $UserValue interpolated. I recommend to use SAFEqx() instead
1058 # of backticks whenever you can. The OS shell scripts inside
1060 # <SCRIPT TYPE="text/osshell">ls -1 $UserValue</SCRIPT>
1062 # are handeld by SAFEqx and automatically ''-quoted.
1064 # 4 Logging of requests
1065 # All requests can be logged separate from the Host server. The level of
1066 # detail is user configurable: Including or excluding the actual queries.
1067 # This allows for the inspection of (im-) proper use.
1069 # 5 Access control: Clients
1070 # The Remote addresses can be checked against a list of authorized
1071 # (i.e., accepted) or non-authorized (i.e., rejected) clients. Both
1072 # REMOTE_HOST and REMOTE_ADDR are tested so clients without a proper
1073 # HOST name can be (in-) excluded by their IP-address. Client patterns
1074 # containing all numbers and dots are considered IP-addresses, all others
1075 # domain names. No wild-cards or regexp's are allowed, only partial
1076 # addresses.
1077 # Matching of names is done from the back to the front (domain first,
1078 # i.e., $REMOTE_HOST =~ /\Q$pattern\E$/is), so including ".edu" will
1079 # accept or reject all clients from the domain EDU. Matching of
1080 # IP-addresses is done from the front to the back (domain first, i.e.,
1081 # $REMOTE_ADDR =~ /^\Q$pattern\E/is), so including "128." will (in-)
1082 # exclude all clients whose IP-address starts with 128.
1083 # There are two special symbols: "-" matches HOSTs with no name and "*"
1084 # matches ALL HOSTS/clients.
1085 # For those needing more expressional power, lines starting with
1086 # "-e" are evaluated by the perl eval() function. E.g.,
1087 # '-e $REMOTE_HOST =~ /\.edu$/is;' will accept/reject clients from the
1088 # domain '.edu'.
1090 # 6 Access control: Files
1091 # In principle, CGIscriptor could read ANY file in the directory
1092 # tree as discussed in 1. However, for security reasons this is
1093 # restricted to text files. It can be made more restricted by entering
1094 # a global file pattern (e.g., ".html"). This is done by default.
1095 # For each client requesting access, the file pattern(s) can be made
1096 # more restrictive than the global pattern by entering client specific
1097 # file patterns in the Access Control files (see 5).
1098 # For example: if the ACCEPT file contained the lines
1099 # * DEMO
1100 # .hum.uva.nl LET
1101 # 145.18.230.
1102 # Then all clients could request paths containing "DEMO" or "demo", e.g.
1103 # "/my/demo/file.html" ($PATH_INFO =~ /\Q$pattern\E/), Clients from
1104 # *.hum.uva.nl could also request paths containing "LET or "let", e.g.
1105 # "/my/let/file.html", and clients from the local cluster
1106 # 145.18.230.[0-9]+ could access ALL files.
1107 # Again, for those needing more expressional power, lines starting with
1108 # "-e" are evaluated. For instance:
1109 # '-e $REMOTE_HOST =~ /\.edu$/is && $PATH_INFO =~ m@/DEMO/@is;'
1110 # will accept/reject requests for files from the directory "/demo/" from
1111 # clients from the domain '.edu'.
1112 # Path selections starting with ! or 'not' will be inverted. That is:
1113 # * not .wav
1114 # Will match all file and path names that do NOT contain '.wav'
1116 # 7 Access control: Server side session tickets
1117 # Specific paths can be controlled by Session Tickets which must be
1118 # present as a SESSIONTICKET=<value> CGI variable in the request. These paths
1119 # are defined in %TicketRequiredPatterns as pairs of:
1120 # ('regexp' => 'SessionPath\tPasswordPath\tLogin.html\tExpiration').
1121 # Session Tickets are stored in a separate directory (SessionPath, e.g.,
1122 # "Private/.Session") as files with the exact same name of the SESSIONTICKET
1123 # CGI. The following is an example:
1124 # Type: SESSION
1125 # IPaddress: 127.0.0.1
1126 # AllowedPaths: ^/Private/Name/
1127 # Expires: 3600
1128 # Username: test
1129 # ...
1130 # Other content can follow.
1132 # It is adviced that Session Tickets should be deleted
1133 # after some (idle) time. The IP address should be the IP number at login, and
1134 # the SESSIONTICKET will be rejected if it is presented from another IP address.
1135 # AllowedPaths and DeniedPaths are perl regexps. Be careful how they match. Make sure to delimit
1136 # the names to prevent access to overlapping names, eg, "^/Private/Rob" will also
1137 # match "^/Private/Robert", however, "^/Private/Rob/" will not. Expires is the
1138 # time the ticket will remain valid after creation (file ctime). Time can be given
1139 # in s[econds] (default), m[inutes], h[hours], or d[ays], eg, "24h" means 24 hours.
1140 # None of these need be present, but the Ticket must have a non-zero size.
1142 # Next to Session Tickets, there are two other type of ticket files:
1143 # - LOGIN tickets store information about a current login request
1144 # - PASSWORD ticket store account information to authorize login requests
1146 # 8 Query length limiting
1147 # The length of the Query string can be limited. If CONTENT_LENGTH is larger
1148 # than this limit, the request is rejected. The combined length of the
1149 # Query string and the POST input is checked before any processing is done.
1150 # This will prevent clients from overloading the scripts.
1151 # The actual, combined, Query Size is accessible as a variable through
1152 # $CGI_Content_Length.
1154 # 9 Illegal filenames, paths, and protected directories
1155 # One of the primary security concerns in handling CGI-scripts is the
1156 # use of "funny" characters in the requests that con scripts in executing
1157 # malicious commands. Examples are inserting ';', null bytes, or <newline>
1158 # characters in URL's and filenames, followed by executable commands. A
1159 # special variable $FileAllowedChars stores a string of all allowed
1160 # characters. Any request that translates to a filename with a character
1161 # OUTSIDE this set will be rejected.
1162 # In general, all (readable text) files in the DocumentRoot tree are accessible.
1163 # Default, executable files are rejected, but this can be reversed by setting
1164 # the environment variable $ENV{USEFAT}=1 ($useFAT = 1). This allows using
1165 # CGIscriptor on MS FAT filesystems.
1166 # This might not be what you want. For instance, your DocumentRoot directory
1167 # might be the working directory of a CVS project and contain sensitive
1168 # information (e.g., the password to get to the repository). You can block
1169 # access to these subdirectories by adding the corresponding patterns to
1170 # the $BlockPathAccess variable. For instance, $BlockPathAccess = '/CVS/'
1171 # will block any request that contains '/CVS/' or:
1172 # die if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@;
1174 #10 The execution of code blocks can be controlled in a transparent way
1175 # by adding IF or UNLESS conditions in the tags themselves. That is,
1176 # a simple check of the validity of filenames or email addresses can
1177 # be done before any code is executed.
1179 ###############################################################################
1181 # USER MANUAL (sort of)
1183 # CGIscriptor removes embedded scripts, indicated by an HTML 4 type
1184 # <SCRIPT TYPE='text/ssperl'> </SCRIPT> or <SCRIPT TYPE='text/osshell'>
1185 # </SCRIPT> constructs. CGIscriptor also recognizes XML-type
1186 # <SCRIPT TYPE='text/ssperl'/> constructs. These are usefull when
1187 # the necessary code is already available in the TAG itself (e.g.,
1188 # using external files). The contents of the directive are executed by
1189 # the PERL eval() and `` functions (in a separate name space). The
1190 # result of the eval() function replaces the <SCRIPT> </SCRIPT> construct
1191 # in the output file. You can use the values that are delivered in
1192 # CGI-compliant form (i.e., the "?name=value&.." type URL additions)
1193 # transparently as "$name" variables in your directives after they are
1194 # defined in a <META> or <SCRIPT> tag.
1195 # If you define the variable "$CGIscriptorResults" in a CGI attribute, all
1196 # subsequent <SCRIPT> and <META> results (including the defining
1197 # tag) will also be pushed onto a stack: @CGIscriptorResults. This list
1198 # behaves like any other, ordinary list and can be manipulated.
1200 # Both GET and POST requests are accepted. These two methods are treated
1201 # equal. Variables, i.e., those values that are determined when a file is
1202 # processed, are indicated in the CGI attribute by $<name> or $<name>=<default>
1203 # in which <name> is the name of the variable and <default> is the value
1204 # used when there is NO current CGI value for <name> (you can use
1205 # white-spaces in $<name>=<default> but really DO make sure that the
1206 # default value is followed by white space or is quoted). Names can contain
1207 # any alphanumeric characters and _ (i.e., names match /[\w]+/).
1208 # If the Content-type: is 'multipart/*', the input is treated as a
1209 # MIME multipart message and automatically delimited. CGI variables get
1210 # the "raw" (i.e., undecoded) body of the corresponding message part.
1212 # Variables can be CGI variables, i.e., those from the QUERY_STRING,
1213 # environment variables, e.g., REMOTE_USER, REMOTE_HOST, or REMOTE_ADDR,
1214 # or predefined values, e.g., CGI_Decoded_QS (The complete, decoded,
1215 # query string), CGI_Content_Length (the length of the decoded query
1216 # string), CGI_Year, CGI_Month, CGI_Time, and CGI_Hour (the current
1217 # date and time).
1219 # All these are available when defined in a CGI attribute. All environment
1220 # variables are accessible as $ENV{'name'}. So, to access the REMOTE_HOST
1221 # and the REMOTE_USER, use, e.g.:
1223 # <SCRIPT TYPE='text/ssperl'>
1224 # ($ENV{'REMOTE_HOST'}||"-")." $ENV{'REMOTE_USER'}"
1225 # </SCRIPT>
1227 # (This will print a "-" if REMOTE_HOST is not known)
1228 # Another way to do this is:
1230 # <META CONTENT="text/ssperl; CGI='$REMOTE_HOST = - $REMOTE_USER'">
1231 # <SCRIPT TYPE='text/ssperl'>"$REMOTE_HOST $REMOTE_USER"</SCRIPT>
1232 # or
1233 # <META CONTENT='text/ssperl; CGI="$REMOTE_HOST = - $REMOTE_USER"
1234 # SRC={"$REMOTE_HOST $REMOTE_USER\n"}'>
1236 # This is possible because ALL environment variables are available as
1237 # CGI variables. The environment variables take precedence over CGI
1238 # names in case of a "name clash". For instance:
1239 # <META CONTENT="text/ssperl; CGI='$HOME' SRC={$HOME}">
1240 # Will print the current HOME directory (environment) irrespective whether
1241 # there is a CGI variable from the query
1242 # (e.g., Where do you live? <INPUT TYPE="TEXT" NAME="HOME">)
1243 # THIS IS A SECURITY FEATURE. It prevents clients from changing
1244 # the values of defined environment variables (e.g., by supplying
1245 # a bogus $REMOTE_ADDR). Although $ENV{} is not changed by the META tags,
1246 # it would make the use of declared variables insecure. You can still
1247 # access CGI variables after a name clash with
1248 # CGIscriptor::CGIparseValue(<name>).
1250 # Some CGI variables are present several times in the query string
1251 # (e.g., from multiple selections). These should be defined as
1252 # @VARIABLENAME=default in the CGI attribute. The list @VARIABLENAME
1253 # will contain ALL VARIABLENAME values from the query, or a single
1254 # default value. If there is an ENVIRONMENT variable of the
1255 # same name, it will be used instead of the default AND the query
1256 # values. The corresponding function is
1257 # CGIscriptor::CGIparseValueList(<name>)
1259 # CGI variables collected in a @VARIABLENAME list are unordered.
1260 # When more structured variables are needed, a hash table can be used.
1261 # A variable defined as %VARIABLE=default will collect all
1262 # CGI-parameters whose name start with 'VARIABLE' in a hash table with
1263 # the remainder of the name as a key. For instance, %PERSON will
1264 # collect PERSONname='John Doe', PERSONbirthdate='01 Jan 00', and
1265 # PERSONspouse='Alice' into a hash table %PERSON such that $PERSON{'spouse'}
1266 # equals 'Alice'. Any default value or environment value will be stored
1267 # under the "" key. If there is an ENVIRONMENT variable of the same name,
1268 # it will be used instead of the default AND the query values. The
1269 # corresponding function is CGIscriptor::CGIparseValueHash(<name>)
1271 # This method of first declaring your environment and CGI variables
1272 # before being able to use them in the scripts might seem somewhat
1273 # clumsy, but it protects you from inadvertedly printing out the values of
1274 # system environment variables when their names coincide with those used
1275 # in the CGI forms. It also prevents "clients" from supplying CGI
1276 # parameter values for your private variables.
1277 # THIS IS A SECURITY FEATURE!
1280 # NON-HTML CONTENT TYPES
1282 # Normally, CGIscriptor prints the standard "Content-type: text/html\n\n"
1283 # message before anything is printed. This has been extended to include
1284 # plain text (.txt) files, for which the Content-type (MIME type)
1285 # 'text/plain' is printed. In all other respects, text files are treated
1286 # as HTML files (this can be switched off by removing '.txt' from the
1287 # $FilePattern variable) . When the content type should be something else,
1288 # e.g., with multipart files, use the $RawFilePattern (.xmr, see also next
1289 # item). CGIscriptor will not print a Content-type message for this file
1290 # type (which must supply its OWN Content-type message). Raw files must
1291 # still conform to the <SCRIPT></SCRIPT> and <META> tag specifications.
1294 # NON-HTML FILES
1296 # CGIscriptor is intended to process HTML and text files only. You can
1297 # create documents of any mime-type on-the-fly using "raw" text files,
1298 # e.g., with the .xmr extension. However, CGIscriptor will not process
1299 # binary files of any type, e.g., pictures or sounds. Given the sheer
1300 # number of formats, I do not have any intention to do so. However,
1301 # an escape route has been provided. You can construct a genuine raw
1302 # (.xmr) text file that contains the perl code to service any file type
1303 # you want. If the global $BinaryMapFile variable contains the path to
1304 # this file (e.g., /BinaryMapFile.xmr), this file will be called
1305 # whenever an unsupported (non-HTML) file type is requested. The path
1306 # to the requested binary file is stored in $ENV('CGI_BINARY_FILE')
1307 # and can be used like any other CGI-variable. Servicing binary files
1308 # then becomes supplying the correct Content-type (e.g., print
1309 # "Content-type: image/jpeg\n\n";) and reading the file and writing it
1310 # to STDOUT (e.g., using sysread() and syswrite()).
1313 # THE META TAG
1315 # All attributes of a META tag are ignored, except the
1316 # CONTENT='text/ssperl; CGI=" ... " [SRC=" ... "]' attribute. The string
1317 # inside the quotes following the CONTENT= indication (white-space is
1318 # ignored, "" '' `` (){}[]-quote pairs are allowed, plus their \ versions)
1319 # MUST start with any of the CGIscriptor mime-types (e.g.: text/ssperl or
1320 # text/osshell) and a comma or semicolon.
1321 # The quoted string following CGI= contains a white-space separated list
1322 # of declarations of the CGI (and Environment) values and default values
1323 # used when no CGI values are supplied by the query string.
1325 # If the default value is a longer string containing special characters,
1326 # possibly spanning several lines, the string must be enclosed in quotes.
1327 # You may use any pair of quotes or brackets from the list '', "", ``, (),
1328 # [], or {} to distinguish default values (or preceded by \, e.g., \(...\)
1329 # is different from (...)). The outermost pair will always be used and any
1330 # other quotes inside the string are considered to be part of the string
1331 # value, e.g.,
1333 # $Value = {['this'
1334 # "and" (this)]}
1335 # will result in $Value getting the default value: ['this'
1336 # "and" (this)]
1337 # (NOTE that the newline is part of the default value!).
1339 # Internally, for defining and initializing CGI (ENV) values, the META
1340 # and SCRIPT tags use the functions "defineCGIvariable($name, $default)"
1341 # (scalars) and "defineCGIvariableList($name, $default)" (lists).
1342 # These functions can be used inside scripts as
1343 # "CGIscriptor::defineCGIvariable($name, $default)" and
1344 # "CGIscriptor::defineCGIvariableList($name, $default)".
1345 # "CGIscriptor::defineCGIvariableHash($name, $default)".
1347 # The CGI attribute will be processed exactly identical when used inside
1348 # the <SCRIPT> tag. However, this use is not according to the
1349 # HTML 4.0 specifications of the W3C.
1352 # THE DIV/INS TAGS
1354 # There is a problem when constructing html files containing
1355 # server-side perl scripts with standard HTML tools. These
1356 # tools will refuse to process any text between <SCRIPT></SCRIPT>
1357 # tags. This is quite annoying when you want to use large
1358 # HTML templates where you will fill in values.
1360 # For this purpose, CGIscriptor will read the neutral
1361 # <DIV CLASS="ssperl" ID="varname"></DIV> or
1362 # <INS CLASS="ssperl" ID="varname"></INS>
1363 # tag (in Cascading Style Sheet manner) Note that
1364 # "varname" has NO '$' before it, it is a bare name.
1365 # Any text between these <DIV ...></DIV> or
1366 # <INS ...></INS>tags will be assigned to '$varname'
1367 # as is (e.g., as a literal).
1368 # No processing or interpolation will be performed.
1369 # There is also NO nesting possible. Do NOT nest a
1370 # </DIV> inside a <DIV></DIV>! Moreover, neither INS nor
1371 # DIV tags do ensure a block structure in the final
1372 # rendering (i.e., no empty lines).
1374 # Note that <DIV CLASS="ssperl" ID="varname"/>
1375 # is handled the XML way. No content is processed,
1376 # but varname is defined, and any SRC directives are
1377 # processed.
1379 # You can use $varname like any other variable name.
1380 # However, $varname is NOT a CGI variable and will be
1381 # completely internal to your script. There is NO
1382 # interaction between $varname and the outside world.
1384 # To interpolate a DIV derived text, you can use:
1385 # $varname =~ s/([\]])/\\\1/g; # Mark ']'-quotes
1386 # $varname = eval("qq[$varname]"); # Interpolate all values
1388 # The DIV tags will process IF, UNLESS, CGI and
1389 # SRC attributes. The SRC files will be pre-pended to the
1390 # body text of the tag. SRC blocks are NOT executed.
1392 # CONDITIONAL PROCESSING: THE 'IF' AND 'UNLESS' ATTRIBUTES
1394 # It is often necessary to include code-blocks that should be executed
1395 # conditionally, e.g., only for certain browsers or operating system.
1396 # Furthermore, quite often sanity and security checks are necessary
1397 # before user (form) data can be processed, e.g., with respect to
1398 # email addresses and filenames.
1400 # Checks added to the code are often difficult to find, interpret or
1401 # maintain and in general mess up the code flow. This kind of confussion
1402 # is dangerous.
1403 # Also, for many of the supported "foreign" scripting languages, adding
1404 # these checks is cumbersome or even impossible.
1406 # As a uniform method for asserting the correctness of "context", two
1407 # attributes are added to all supported tags: IF and UNLESS.
1408 # They both evaluate their value and block execution when the
1409 # result is <FALSE> (IF) or <TRUE> (UNLESS) in Perl, e.g.,
1410 # UNLESS='$NUMBER \> 100;' blocks execution if $NUMBER <= 100. Note that
1411 # the backslash in the '\>' is removed and only used to differentiate
1412 # this conditional '>' from the tag-closing '>'. For symmetry, the
1413 # backslash in '\<' is also removed. Inside these conditionals,
1414 # ~/ and ./ are expanded to their respective directory root paths.
1416 # For example, the following tag will be ignored when the filename is
1417 # invalid:
1419 # <SCRIPT TYPE='text/ssperl' CGI='$FILENAME'
1420 # IF='CGIscriptor::CGIsafeFileName($FILENAME);'>
1421 # ...
1422 # </SCRIPT>
1424 # The IF and UNLESS values must be quoted. The same quotes are supported
1425 # as with the other attributes. The SRC attribute is ignored when IF and
1426 # UNLESS block execution.
1428 # NOTE: 'IF' and 'UNLESS' always evaluate perl code.
1431 # THE MAGIC SOURCE ATTRIBUTE (SRC=)
1433 # The SRC attribute inside tags accepts a list of filenames and URL's
1434 # separated by "," comma's (or ";" semicolons).
1435 # ALL the variable values defined in the CGI attribute are available
1436 # in @ARGV as if the file or block was executed from the command line,
1437 # in the exact order in which they were declared in the preceding CGI
1438 # attribute.
1440 # First, a SRC={}-block will be evaluated as if the code inside the
1441 # block was part of a <SCRIPT></SCRIPT> construct, i.e.,
1442 # "print do { code };'';" or `code` (i.e., SAFEqx('code)).
1443 # Only a single block is evaluated. Note that this is processed less
1444 # efficiently than <SCRIPT> </SCRIPT> blocks. Type of evaluation
1445 # depends on the content-type: Perl for text/ssperl and OS shell for
1446 # text/osshell. For other mime types (scripting languages), anything in
1447 # the source block is put in front of the code block "inside" the tag.
1449 # Second, executable files (i.e., -x filename != 0) are evaluated as:
1450 # print `filename \'$ARGV[0]\' \'$ARGV[1]\' ...`
1451 # That is, you can actually call executables savely from the SRC tag.
1453 # Third, text files that match the file pattern, used by CGIscriptor to
1454 # check whether files should be processed ($FilePattern), are
1455 # processed in-line (i.e., recursively) by CGIscriptor as if the code
1456 # was inserted in the original source file. Recursions, i.e., calling
1457 # a file inside itself, are blocked. If you need them, you have to code
1458 # them explicitely using "main::ProcessFile($file_path)".
1460 # Fourth, Perl text files (i.e., -T filename != 0) are evaluated as:
1461 # "do FileName;'';".
1463 # Last, URL's (i.e., starting with 'HTTP://', 'FTP://', 'GOPHER://',
1464 # 'TELNET://', 'WHOIS://' etc.) are loaded
1465 # and printed. The loading and handling of <BASE> and document header
1466 # is done by a command generated by main::GET_URL($URL [, 0]). You can enter your
1467 # own code (default is curl, wget, or snarf and some post-processing to add a <BASE> tag).
1469 # There are two pseudo-file names: PREFIX and POSTFIX. These implement
1470 # a switch from prefixing the SRC code/files (PREFIX, default) before the
1471 # content of the tag to appending the code after the content of the tag
1472 # (POSTFIX). The switches are done in the order in which the PREFIX and
1473 # POSTFIX labels are encountered. You can mix PREFIX and POSTFIX labels
1474 # in any order with the SRC files. Note that the ORDER of file execution
1475 # is determined for prefixed and postfixed files seperately.
1477 # File paths can be preceded by the URL protocol prefix "file://". This
1478 # is simply STRIPPED from the name.
1480 # Example:
1481 # The request
1482 # "http://cgi-bin/Action_Forms.pl/Statistics/Sign_Test.html?positive=8&negative=22
1483 # will result in printing "${SS_PUB}/Statistics/Sign_Test.html"
1484 # With QUERY_STRING = "positive=8&negative=22"
1486 # on encountering the lines:
1487 # <META CONTENT="text/osshell; CGI='$positive=11 $negative=3'">
1488 # <b><SCRIPT LANGUAGE=PERL TYPE="text/ssperl" SRC="./Statistics/SignTest.pl">
1489 # </SCRIPT></b><p>"
1491 # This line will be processed as:
1492 # "<b>`${SS_SCRIPT}/Statistics/SignTest.pl '8' '22'`</b><p>"
1494 # In which "${SS_SCRIPT}/Statistics/SignTest.pl" is an executable script,
1495 # This line will end up printed as:
1496 # "<b>p <= 0.0161</b><p>"
1498 # Note that the META tag itself will never be printed, and is invisible to
1499 # the outside world.
1501 # The SRC files in a DIV or INS tag will be added (pre-pended) to the body
1502 # of the <DIV></DIV> tag. Blocks are NOT executed! If you do not
1503 # need any content, you can use the <DIV...../> format.
1506 # THE CGISCRIPTOR ROOT DIRECTORIES ~/ AND ./
1508 # Inside <SCRIPT></SCRIPT> tags, filepaths starting
1509 # with "~/" are replaced by "$YOUR_HTML_FILES/", this way files in the
1510 # public directories can be accessed without direct reference to the
1511 # actual paths. Filepaths starting with "./" are replaced by
1512 # "$YOUR_SCRIPTS/" and this should only be used for scripts.
1514 # Note: this replacement can seriously affect Perl scripts. Watch
1515 # out for constructs like $a =~ s/aap\./noot./g, use
1516 # $a =~ s@aap\.@noot.@g instead.
1518 # CGIscriptor.pl will assign the values of $SS_PUB and $SS_SCRIPT
1519 # (i.e., $YOUR_HTML_FILES and $YOUR_SCRIPTS) to the environment variables
1520 # $SS_PUB and $SS_SCRIPT. These can be accessed by the scripts that are
1521 # executed.
1522 # Values not preceded by $, ~/, or ./ are used as literals
1525 # OS SHELL SCRIPT EVALUATION (CONTENT-TYPE=TEXT/OSSHELL)
1527 # OS scripts are executed by a "safe" version of the `` operator (i.e.,
1528 # SAFEqx(), see also below) and any output is printed. CGIscriptor will
1529 # interpolate the script and replace all user-supplied CGI-variables by
1530 # their ''-quoted values (actually, all variables defined in CGI attributes
1531 # are quoted). Other Perl variables are interpolated in a simple fasion,
1532 # i.e., $scalar by their value, @list by join(' ', @list), and %hash by
1533 # their name=value pairs. Complex references, e.g., @$variable, are all
1534 # evaluated in a scalar context. Quotes should be used with care.
1535 # NOTE: the results of the shell script evaluation will appear in the
1536 # @CGIscriptorResults stack just as any other result.
1537 # All occurrences of $@% that should NOT be interpolated must be
1538 # preceeded by a "\". Interpolation can be switched off completely by
1539 # setting $CGIscriptor::NoShellScriptInterpolation = 1
1540 # (set to 0 or undef to switch interpolation on again)
1541 # i.e.,
1542 # <SCRIPT TYPE="text/ssperl">
1543 # $CGIscriptor::NoShellScriptInterpolation = 1;
1544 # </SCRIPT>
1547 # RUN TIME TRANSLATION OF INPUT FILES
1549 # Allows general and global conversions of files using Regular Expressions.
1550 # Very handy (but costly) to rewrite legacy pages to a new format.
1551 # Select files to use it on with
1552 # my $TranslationPaths = 'filepattern';
1553 # This is costly. For efficiency, define:
1554 # $TranslationPaths = ''; when not using translations.
1555 # Accepts general regular expressions: [$pattern, $replacement]
1557 # Define:
1558 # my $TranslationPaths = 'filepattern'; # Pattern matching PATH_INFO
1560 # push(@TranslationTable, ['pattern', 'replacement']);
1561 # e.g. (for Ruby Rails):
1562 # push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
1563 # push(@TranslationTable, ['%>', '</SCRIPT>']);
1565 # Runs:
1566 # my $currentRegExp;
1567 # foreach $currentRegExp (@TranslationTable)
1569 # my ($pattern, $replacement) = @$currentRegExp;
1570 # $$text =~ s!$pattern!$replacement!msg;
1571 # };
1574 # EVALUATION OF OTHER SCRIPTING LANGUAGES
1576 # Adding a MIME-type and an interpreter command to
1577 # %ScriptingLanguages automatically will catch any other
1578 # scripting language in the standard
1579 # <SCRIPT TYPE="[mime]"></SCRIPT> manner.
1580 # E.g., adding: $ScriptingLanguages{'text/sspython'} = 'python';
1581 # will actually execute the folowing code in an HTML page
1582 # (ignore 'REMOTE_HOST' for the moment):
1583 # <SCRIPT TYPE="text/sspython">
1584 # # A Python script
1585 # x = ["A","real","python","script","Hello","World","and", REMOTE_HOST]
1586 # print x[4:8] # Prints the list ["Hello","World","and", REMOTE_HOST]
1587 # </SCRIPT>
1589 # The script code is NOT interpolated by perl, EXCEPT for those
1590 # interpreters that cannot handle variables themselves.
1591 # Currently, several interpreters are pre-installed:
1593 # Perl test - "text/testperl" => 'perl',
1594 # Python - "text/sspython" => 'python',
1595 # Ruby - "text/ssruby" => 'ruby',
1596 # Tcl - "text/sstcl" => 'tcl',
1597 # Awk - "text/ssawk" => 'awk -f-',
1598 # Gnu Lisp - "text/sslisp" => 'rep | tail +5 '.
1599 # "| egrep -v '> |^rep. |^nil\\\$'",
1600 # XLispstat - "text/xlispstat" => 'xlispstat | tail +7 '.
1601 # "| egrep -v '> \\\$|^NIL'",
1602 # Gnu Prolog- "text/ssprolog" => 'gprolog',
1603 # M4 macro's- "text/ssm4" => 'm4',
1604 # Born shell- "text/sh" => 'sh',
1605 # Bash - "text/bash" => 'bash',
1606 # C-shell - "text/csh" => 'csh',
1607 # Korn shell- "text/ksh" => 'ksh',
1608 # Praat - "text/sspraat" => "praat - | sed 's/Praat > //g'",
1609 # R - "text/ssr" => "R --vanilla --slave | sed 's/^[\[0-9\]*] //g'",
1610 # REBOL - "text/ssrebol" =>
1611 # "rebol --quiet|egrep -v '^[> ]* == '|sed 's/^\s*\[> \]* //g'",
1612 # PostgreSQL- "text/postgresql" => 'psql 2>/dev/null',
1613 # (psql)
1615 # Note that the "value" of $ScriptingLanguages{mime} must be a command
1616 # that reads Standard Input and writes to standard output. Any extra
1617 # output of interactive interpreters (banners, echo's, prompts)
1618 # should be removed by piping the output through 'tail', 'grep',
1619 # 'sed', or even 'awk' or 'perl'.
1621 # For access to CGI variables there is a special hashtable:
1622 # %ScriptingCGIvariables.
1623 # CGI variables can be accessed in three ways.
1624 # 1. If the mime type is not present in %ScriptingCGIvariables,
1625 # nothing is done and the script itself should parse the relevant
1626 # environment variables.
1627 # 2. If the mime type IS present in %ScriptingCGIvariables, but it's
1628 # value is empty, e.g., $ScriptingCGIvariables{"text/sspraat"} = '';,
1629 # the script text is interpolated by perl. That is, all $var, @array,
1630 # %hash, and \-slashes are replaced by their respective values.
1631 # 3. In all other cases, the CGI and environment variables are added
1632 # in front of the script according to the format stored in
1633 # %ScriptingCGIvariables. That is, the following (pseudo-)code is
1634 # executed for each CGI- or Environment variable defined in the CGI-tag:
1635 # printf(INTERPRETER, $ScriptingCGIvariables{$mime}, $CGI_NAME, $CGI_VALUE);
1637 # For instance, "text/testperl" => '$%s = "%s";' defines variable
1638 # definitions for Perl, and "text/sspython" => '%s = "%s"' for Python
1639 # (note that these definitions are not save, the real ones contain '-quotes).
1641 # THIS WILL NOT WORK FOR @VARIABLES, the (empty) $VARIABLES will be used
1642 # instead.
1644 # The $CGI_VALUE parameters are "shrubed" of all control characters
1645 # and quotes (by &shrubCGIparameter($CGI_VALUE)) for the options 2 and 3.
1646 # Control characters are replaced by \0<octal ascii value> (the exception
1647 # is \015, the newline, which is replaced by \n) and quotes
1648 # and backslashes by their HTML character
1649 # value (' -> &#39; ` -> &#96; " -> &quot; \ -> &#92; & -> &amper;).
1650 # For example:
1651 # if a client would supply the string value (in standard perl, e.g.,
1652 # \n means <newline>)
1653 # "/dev/null';\nrm -rf *;\necho '"
1654 # it would be processed as
1655 # '/dev/null&#39;;\nrm -rf *;\necho &#39;'
1656 # (e.g., sh or bash would process the latter more according to your
1657 # intentions).
1658 # If your intepreter requires different protection measures, you will
1659 # have to supply these in %main::SHRUBcharacterTR (string => translation),
1660 # e.g., $SHRUBcharacterTR{"\'"} = "&#39;";
1662 # Currently, the following definitions are used:
1663 # %ScriptingCGIvariables = (
1664 # "text/testperl" => "\$\%s = '\%s';", # Perl $VAR = 'value' (for testing)
1665 # "text/sspython" => "\%s = '\%s'", # Python VAR = 'value'
1666 # "text/ssruby" => '@%s = "%s"', # Ruby @VAR = "value"
1667 # "text/sstcl" => 'set %s "%s"', # TCL set VAR "value"
1668 # "text/ssawk" => '%s = "%s";', # Awk VAR = "value";
1669 # "text/sslisp" => '(setq %s "%s")', # Gnu lisp (rep) (setq VAR "value")
1670 # "text/xlispstat" => '(setq %s "%s")', # Xlispstat (setq VAR "value")
1671 # "text/ssprolog" => '', # Gnu prolog (interpolated)
1672 # "text/ssm4" => "define(`\%s', `\%s')", # M4 macro's define(`VAR', `value')
1673 # "text/sh" => "\%s='\%s';", # Born shell VAR='value';
1674 # "text/bash" => "\%s='\%s';", # Born again shell VAR='value';
1675 # "text/csh" => "\$\%s = '\%s';", # C shell $VAR = 'value';
1676 # "text/ksh" => "\$\%s = '\%s';", # Korn shell $VAR = 'value';
1677 # "text/sspraat" => '', # Praat (interpolation)
1678 # "text/ssr" => '%s <- "%s";', # R VAR <- "value";
1679 # "text/ssrebol" => '%s: copy "%s"', # REBOL VAR: copy "value"
1680 # "text/postgresql" => '', # PostgreSQL (interpolation)
1681 # "" => ""
1682 # );
1684 # Four tables allow fine-tuning of interpreter with code that should be
1685 # added before and after each code block:
1687 # Code added before each script block
1688 # %ScriptingPrefix = (
1689 # "text/testperl" => "\# Prefix Code;", # Perl script testing
1690 # "text/ssm4" => 'divert(0)' # M4 macro's (open STDOUT)
1691 # );
1692 # Code added at the end of each script block
1693 # %ScriptingPostfix = (
1694 # "text/testperl" => "\# Postfix Code;", # Perl script testing
1695 # "text/ssm4" => 'divert(-1)' # M4 macro's (block STDOUT)
1696 # );
1697 # Initialization code, inserted directly after opening (NEVER interpolated)
1698 # %ScriptingInitialization = (
1699 # "text/testperl" => "\# Initialization Code;", # Perl script testing
1700 # "text/ssawk" => 'BEGIN {', # Server Side awk scripts
1701 # "text/sslisp" => '(prog1 nil ', # Lisp (rep)
1702 # "text/xlispstat" => '(prog1 nil ', # xlispstat
1703 # "text/ssm4" => 'divert(-1)' # M4 macro's (block STDOUT)
1704 # );
1705 # Cleanup code, inserted before closing (NEVER interpolated)
1706 # %ScriptingCleanup = (
1707 # "text/testperl" => "\# Cleanup Code;", # Perl script testing
1708 # "text/sspraat" => 'Quit',
1709 # "text/ssawk" => '};', # Server Side awk scripts
1710 # "text/sslisp" => '(princ "\n" standard-output)).' # Closing print to rep
1711 # "text/xlispstat" => '(print "" *standard-output*)).' # Closing print to xlispstat
1712 # "text/postgresql" => '\q',
1713 # );
1716 # The SRC attribute is NOT magical for these interpreters. In short,
1717 # all code inside a source file or {} block is written verbattim
1718 # to the interpreter. No (pre-)processing or executional magic is done.
1720 # A serious shortcomming of the described mechanism for handling other
1721 # (scripting) languages, with respect to standard perl scripts
1722 # (i.e., 'text/ssperl'), is that the code is only executed when
1723 # the pipe to the interpreter is closed. So the pipe has to be
1724 # closed at the end of each block. This means that the state of the
1725 # interpreter (e.g., all variable values) is lost after the closing of
1726 # the next </SCRIPT> tag. The standard 'text/ssperl' scripts retain
1727 # all values and definitions.
1729 # APPLICATION MIME TYPES
1731 # To ease some important auxilliary functions from within the
1732 # html pages I have added them as MIME types. This uses
1733 # the mechanism that is also used for the evaluation of
1734 # other scripting languages, with interpolation of CGI
1735 # parameters (and perl-variables). Actually, these are
1736 # defined exactly like any other "scripting language".
1738 # text/ssdisplay: display some (HTML) text with interpolated
1739 # variables (uses `cat`).
1740 # text/sslogfile: write (append) the interpolated block to the file
1741 # mentioned on the first, non-empty line
1742 # (the filename can be preceded by 'File: ',
1743 # note the space after the ':',
1744 # uses `awk .... >> <filename>`).
1745 # text/ssmailto: send email directly from within the script block.
1746 # The first line of the body must contain
1747 # To:Name@Valid.Email.Address
1748 # (note: NO space between 'To:' and the email adres)
1749 # For other options see the mailto man pages.
1750 # It works by directly sending the (interpolated)
1751 # content of the text block to a pipe into the
1752 # Linux program 'mailto'.
1754 # In these script blocks, all Perl variables will be
1755 # replaced by their values. All CGI variables are cleaned before
1756 # they are used. These CGI variables must be redefined with a
1757 # CGI attribute to restore their original values.
1758 # In general, this will be more secure than constructing
1759 # e.g., your own email command lines. For instance, Mailto will
1760 # not execute any odd (forged) email addres, but just stops
1761 # when the email address is invalid and awk will construct
1762 # any filename you give it (e.g. '<File;rm\\\040-f' would end up
1763 # as a "valid" UNIX filename). Note that it will also gladly
1764 # store this file anywhere (/../../../etc/passwd will work!).
1765 # Use the CGIscriptor::CGIsafeFileName() function to clean the
1766 # filename.
1768 # SHELL SCRIPT PIPING
1770 # If a shell script starts with the UNIX style "#! <shell command> \n"
1771 # line, the rest of the shell script is piped into the indicated command,
1772 # i.e.,
1773 # open(COMMAND, "| command");print COMMAND $RestOfScript;
1775 # In many ways this is equivalent to the MIME-type profiling for
1776 # evaluating other scripting languages as discussed above. The
1777 # difference breaks down to convenience. Shell script piping is a
1778 # "raw" implementation. It allows you to control all aspects of
1779 # execution. Using the MIME-type profiling is easier, but has a
1780 # lot of defaults built in that might get in the way. Another
1781 # difference is that shell script piping uses the SAFEqx() function,
1782 # and MIME-type profiling does not.
1784 # Execution of shell scripts is under the control of the Perl Script blocks
1785 # in the document. The MIME-type triggered execution of <SCRIPT></SCRIPT>
1786 # blocks can be simulated easily. You can switch to a different shell,
1787 # e.g. tcl, completely by executing the following Perl commands inside
1788 # your document:
1790 # <SCRIPT TYPE="text/ssperl">
1791 # $main::ShellScriptContentType = "text/ssTcl"; # Yes, you can do this
1792 # CGIscriptor::RedirectShellScript('/usr/bin/tcl'); # Pipe to Tcl
1793 # $CGIscriptor::NoShellScriptInterpolation = 1;
1794 # </SCRIPT>
1796 # After this script is executed, CGIscriptor will parse scripts of
1797 # TYPE="text/ssTcl" and pipe their contents into '|/usr/bin/tcl'
1798 # WITHOUT interpolation (i.e., NO substitution of Perl variables).
1799 # The crucial function is :
1800 # CGIscriptor::RedirectShellScript('/usr/bin/tcl')
1801 # After executing this function, all shell scripts AND all
1802 # calls to SAFEqx()) are piped into '|/usr/bin/tcl'. If the argument
1803 # of RedirectShellScript is empty, e.g., '', the original (default)
1804 # value is reset.
1806 # The standard output, STDOUT, of any pipe is send to the client.
1807 # Currently, you should be carefull with quotes in such a piped script.
1808 # The results of a pipe is NOT put on the @CGIscriptorResults stack.
1809 # As a result, you do not have access to the output of any piped (#!)
1810 # process! If you want such access, execute
1811 # <SCRIPT TYPE="text/osshell">echo "script"|command</SCRIPT>
1812 # or
1813 # <SCRIPT TYPE="text/ssperl">
1814 # $resultvar = SAFEqx('echo "script"|command');
1815 # </SCRIPT>.
1817 # Safety is never complete. Although SAFEqx() prevents some of the
1818 # most obvious forms of attacks and security slips, it cannot prevent
1819 # them all. Especially, complex combinations of quotes and intricate
1820 # variable references cannot be handled safely by SAFEqx. So be on
1821 # guard.
1824 # PERL CODE EVALUATION (CONTENT-TYPE=TEXT/SSPERL)
1826 # All PERL scripts are evaluated inside a PERL package. This package
1827 # has a separate name space. This isolated name space protects the
1828 # CGIscriptor.pl program against interference from user code. However,
1829 # some variables, e.g., $_, are global and cannot be protected. You are
1830 # advised NOT to use such global variable names. You CAN write
1831 # directives that directly access the variables in the main program.
1832 # You do so at your own risk (there is definitely enough rope available
1833 # to hang yourself). The behavior of CGIscriptor becomes undefined if
1834 # you change its private variables during run time. The PERL code
1835 # directives are used as in:
1836 # $Result = eval($directive); print $Result;'';
1837 # ($directive contains all text between <SCRIPT></SCRIPT>).
1838 # That is, the <directive> is treated as ''-quoted string and
1839 # the result is treated as a scalar. To prevent the VALUE of the code
1840 # block from appearing on the client's screen, end the directive with
1841 # ';""</SCRIPT>'. Evaluated directives return the last value, just as
1842 # eval(), blocks, and subroutines, but only as a scalar.
1844 # IMPORTANT: All PERL variables defined are persistent. Each <SCRIPT>
1845 # </SCRIPT> construct is evaluated as a {}-block with associated scope
1846 # (e.g., for "my $var;" declarations). This means that values assigned
1847 # to a PERL variable can be used throughout the document unless they
1848 # were declared with "my". The following will actually work as intended
1849 # (note that the ``-quotes in this example are NOT evaluated, but used
1850 # as simple quotes):
1852 # <META CONTENT="text/ssperl; CGI=`$String='abcdefg'`">
1853 # anything ...
1854 # <SCRIPT TYPE=text/ssperl>@List = split('', $String);</SCRIPT>
1855 # anything ...
1856 # <SCRIPT TYPE=text/ssperl>join(", ", @List[1..$#List]);</SCRIPT>
1858 # The first <SCRIPT TYPE=text/ssperl></SCRIPT> construct will return the
1859 # value scalar(@List), the second <SCRIPT TYPE=text/ssperl></SCRIPT>
1860 # construct will print the elements of $String separated by commas, leaving
1861 # out the first element, i.e., $List[0].
1863 # Another warning: './' and '~/' are ALWAYS replaced by the values of
1864 # $YOUR_SCRIPTS and $YOUR_HTML_FILES, respectively . This can interfere
1865 # with pattern matching, e.g., $a =~ s/aap\./noot\./g will result in the
1866 # evaluations of $a =~ s/aap\\${YOUR_SCRIPTS}noot\\${YOUR_SCRIPTS}g. Use
1867 # s@<regexp>.@<replacement>.@g instead.
1870 # SERVER SIDE SESSIONS AND ACCESS CONTROL (LOGIN)
1872 # An infrastructure for user acount authorization and file access control
1873 # is available. Each request is matched against a list of URL path patterns.
1874 # If the request matches, a Session Ticket is required to access the URL.
1875 # This Session Ticket should be present as a CGI parameter or Cookie, eg:
1877 # CGI: SESSIONTICKET=&lt;value&gt;
1878 # Cookie: CGIscriptorSESSION=&lt;value&gt;
1880 # The example implementation stores Session Tickets as files in a local
1881 # directory. To create Session Tickets, a Login request must be given
1882 # with a LOGIN=&lt;value&gt; CGI parameter, a user name and a (doubly hashed)
1883 # password. The user name and (singly hashed) password are stored in a
1884 # PASSWORD ticket with the same name as the user account (name cleaned up
1885 # for security).
1887 # The example session model implements 4 functions:
1888 # - Login
1889 # The password is hashed with the user name and server side salt, and then
1890 # hashed with the REMOTE_HOST and a random salt. Client and Server both
1891 # perform these actions and the Server only grants access if restults are
1892 # the same. The server side only stores the password hashed with the user
1893 # name and server side salt. Neither the plain password, nor the hashed
1894 # password is ever exchanged. Only values hashed with the one-time salt
1895 # are exchanged.
1896 # - Session
1897 # For every access to a restricted URL, the Session Ticket is checked before
1898 # access is granted. There are three session modes. The first uses a fixed
1899 # Session Ticket that is stored as a cookie value in the browser (actually,
1900 # as a sessionStorage value). The second uses only the IP address at login
1901 # to authenticate requests. The third
1902 # is a Challenge mode, where the client has to calculate the value of the
1903 # next one-time Session Ticket from a value derived from the password and
1904 # a random string.
1905 # - Password Change
1906 # A new password is hashed with the user name and server side salt, and
1907 # then encrypted (XORed)
1908 # with the old password hashed with the user name and salt. That value is
1909 # exchanged and XORed with the stored old hashed(password+username+salt).
1910 # Again, the stored password value is never exchanged unencrypted.
1911 # - New Account
1912 # The text of a new account (Type: PASSWORD) file is constructed from
1913 # the new username (CGI: NEWUSERNAME, converted to lowercase) and
1914 # hashed new password (CGI: NEWPASSWORD). The same process is used to encrypt
1915 # the new password as is used for the Password Change function.
1916 # Again, the stored password value is never exchanged unencrypted.
1917 # Some default setting are encoded. For display in the browser, the new password
1918 # is reencrypted (XORed) with a special key, the old password hash
1919 # hashed with a session specific random hex value sent initially with the
1920 # session login ticket ($RANDOMSALT).
1921 # For example for user "NewUser" and password "NewPassword" with filename
1922 # "newuser":
1924 # Type: PASSWORD
1925 # Username: newuser
1926 # Password: 19afeadfba8d5dcd252e157fafd3010859f8762b87682b6b6cdb3e565194fa91
1927 # IPaddress: 127\.0\.0\.1
1928 # AllowedPaths: ^/Private/[\w\-]+\.html?
1929 # AllowedPaths: ^/Private/newuser/
1930 # Salt: e93cf858a1d5626bf095ea5c25df990dfa969ff5a5dc908b22c9a5229b525f65
1931 # Session: SESSION
1932 # Date: Fri Jun 29 12:46:22 2012
1933 # Time: 1340973982
1934 # Signature: 676c35d3aa63540293ea5442f12872bfb0a22665b504f58f804582493b6ef04e
1936 # The password is created with the commands:
1938 # printf '%s' 'NewPasswordnewuser970e68017413fb0ea84d7fe3c463077636dd6d53486910d4a53c693dd4109b1a'|shasum -a 256
1940 # If the CPAN mudule Digest is installed, it is used instead of the commands.
1941 # However, the password account files are protected against unauthorized change.
1942 # To obtain a valid Password account, the following command should be given:
1944 # perl CGIscriptor.pl --managelogin salt=Private/.Passwords/SALT \
1945 # masterkey='Sherlock investigates oleander curry in Bath' \
1946 # password='NewPassword' \
1947 # Private/.Passwords/newuser
1950 # Implementation
1952 # The session authentication mechanism is based on the exchange of ticket
1953 # identifiers. A ticket identifier is just a string of characters, a name
1954 # or a random 64 character hexadecimal string. Authentication is based
1955 # on a (password derived) shared secret and the ability to calculate ticket
1956 # identifiers from this shared secret. Ticket identifiers should be
1957 # "safe" filenames (except user names). There are four types of tickets:
1958 # PASSWORD: User account descriptors, including a user name and password
1959 # LOGIN: Temporary anonymous tickets used during login
1960 # IPADDRESS: Authentication tokens that allow access based on the IP address of the request
1961 # SESSION: Reusable authentication tokens
1962 # CHALLENGE: One-time authentication tokens
1963 # All tickets can have an expiration date in the form of a time duration
1964 # from creation, in seconds, minutes, hours, or days (+duration[smhd]).
1965 # An absolute time can be given in seconds since the epoch of the server host.
1966 # Note that expiration times of CHALLENGE authentication tokens are calculated
1967 # from the last access time. Accounts can include a maximal lifetime
1968 # for session tickets (MaxLifetime).
1970 # A Login page should create a LOGIN ticket file locally and send a
1971 # server specific salt, a Random salt, and a LOGIN ticket
1972 # identifier. The server side compares the username and hashed password,
1973 # actually hashed(hashed(password+serversalt)+Random salt) from the client with
1974 # the values it calculates from the stored Random salt from the LOGIN
1975 # ticket and the hashed(password+serversalt) from the PASSWORD ticket. If
1976 # successful, a new SESSION ticket is generated as a (double) hash sum of the stored
1977 # password and the LOGIN ticket, i.e.
1978 # LoginTicket = hashed(hashed(password+serversalt)+REMOTE_HOST + Random salt) and
1979 # SessionTicket = hashed(hashed(LoginTicket).LoginTicket). This SESSION
1980 # ticket should also be generated by the client and stored as
1981 # sessionStorage and cookie values as needed. The Username, IP address
1982 # and Path are available as $LoginUsername, $LoginIPaddress, and
1983 # $LoginPath, respectively.
1985 # The CHALLENGE protocol stores the single hashed version of the SESSION tickets.
1986 # However, this value is not exchanged, but kept secret in the JavaScript
1987 # sessionStorage object. Instead, every page returned from the
1988 # server will contain a one-time Challenge value ($CHALLENGETICKET) which
1989 # has to be hashed with the stored value to return the current ticket
1990 # id string.
1992 # In the current example implementation, all random values are created as
1993 # full, 256 bit SHA256 hash values (Hex strings) of 64 bytes read from
1994 # /dev/urandom.
1997 # Authorization
1999 # A limited level of authorization tuning is build into the login system.
2000 # Each account file (PASSWORD ticket file) can contain a number of
2001 # Capabilities lines. These control special priveliges. The
2002 # Capabilities can be checked inside the HTML pages as part of the
2003 # ticket information. Two privileges are handled internally:
2004 # CreateUser and VariableREMOTE_ADDR.
2005 # CreateUser allows the logged in user to create a new user account.
2006 # With VariableREMOTE_ADDR, the session of the logged in user is
2007 # not limited to the Remote IP address from which the inital log-in took
2008 # place. Sessions can hop from one apparant (proxy) IP address to another,
2009 # e.g., when using Tor. Any IPaddress patterns given in the PASSWORD
2010 # ticket file remain in effect during the session. For security reasons,
2011 # the VariableREMOTE_ADDR capability is only effective if the session
2012 # type is CHALLENGE.
2015 # Security considerations with Session tickets
2017 # For strong security, please use end-to-end encryption. This can be
2018 # achieved using a VPN (Virtual Private Network), SSH tunnel, or a HTTPS
2019 # capable server with OpenSSL. The session ticket system of CGIscriptor.pl
2020 # is intended to be used as a simple authentication mechanism WITHOUT
2021 # END-TO-END ENCRYPTION. The authenticating mechanism tries to use some
2022 # simple means to protect the authentication process from eavesdropping.
2023 # For this it uses a secure hash function, SHA256. For all practial purposes,
2024 # it is impossible to "decrypt" a SHA256 sum. But this login scheme is
2025 # only as secure as your browser. Which, in general, is not very secure.
2027 # One fundamental weakness of the implemented procedure is that the Client
2028 # obtains the code to encrypt the passwords from the server. It is the JavaScript
2029 # code in the HTML pages. An attacker who could place himself between Server
2030 # and Client, a man in the middle attack (MITM), could change the code to
2031 # reveal the plaintext password and other information. There is no
2032 # real protection against this attack without end-to-end encryption and
2033 # authentication. A simple, but rather cumbersome, way to check for such
2034 # attacks would be to store known good copys of the pages (downloaded
2035 # with a browser or automatically with curl or wget) and
2036 # then use other tools to download new pages at random intervals and compare
2037 # them to the old pages. For instance, the following line would remove
2038 # the variable ticket codes and give a fixed SHA256 sum for the original
2039 # Login.html page+code:
2040 # curl http://localhost:8080/Private/index.html | \
2041 # sed 's/=\"[a-z0-9]\{64\}\"/=""/g' | shasum -a 256
2042 # A simple diff command between old and new files should give only
2043 # differences in half a dozen lines, where only hexadecimal salt values
2044 # will actually differ.
2046 # A sort of solution for the MITM attack problem that might protect at
2047 # least the plaintext password would be to run a trusted web
2048 # page from local storage to handle password input. The solution would be
2049 # to add a hidden iFrame tag loading the untrusted page from the URL and
2050 # extract the needed ticket and salt values. Then run the stored, trusted,
2051 # code with these values. It is not (yet) possible to set the
2052 # required session storage inside the browser, so this method only works
2053 # for IPADDRESS sessions and plain SESSION tickets. There are many
2054 # security problems with this "solution".
2056 # If you are able to ascertain the integrity of the login page using any
2057 # of the above methods, you can check whether the IP address seen by the
2058 # login server is indeed the IP address of your computer. The IP address
2059 # of the REMOTE_HOST (your visible IP address) is part of the login
2060 # "password". It is stored in the login page as a CLIENTIPADDRESS. It can
2061 # can be inspected by clicking the "Check IP address" box. Provided the
2062 # MitM attacker cannot spoof your IP address, you can ensure that the login
2063 # server sees your IP address and not that of an attacker.
2065 # Humans tend to reuse passwords. A compromise of a site running
2066 # CGIscriptor.pl could therefore lead to a compromise of user accounts at
2067 # other sites. Therefore, plain text passwords are never stored, used, or
2068 # exchanged. Instead, the plain password and user name are "encrypted" with
2069 # a server site salt value. Actually, all are concatenated and hashed
2070 # with a one-way secure hash function (SHA256) into a single string.
2071 # Whenever the word "password" is used, this hash sum is meant. Note that
2072 # the salts are generated from /dev/urandom. You should check whether the
2073 # implementation of /dev/urandom on your platform is secure before
2074 # relying on it. This might be a problem when running CGIscriptor under
2075 # Cygwin on MS Windows.
2076 # Note: no attempt is made to slow down the password hash, so bad
2077 # passwords can be cracked by brute force
2079 # As the (hashed) passwords are all that is needed to identify at the site,
2080 # these should not be stored in this form. A site specific passphrase
2081 # can be entered as an environment variable ($ENV{'CGIMasterKey'}). This
2082 # phrase is hashed with the server site salt and the result is hashed with
2083 # the user name and then XORed with the password when it is stored. Also, to
2084 # detect changes to the account (PASSWORD) and session tickets, a
2085 # (HMAC) hash of some of the contents of the ticket with the server salt and
2086 # CGIMasterKey is stored in each ticket.
2088 # Creating a valid (hashed) password, encrypt it with the CGIMasterKey and
2089 # construct a signature of the ticket are non-trivial. This has to be redone
2090 # with every change of the ticket file or CGIMasterKey change. CGIscriptor
2091 # can do this from the command line with the command:
2093 # perl CGIscriptor.pl --managelogin salt=Private/.Passwords/SALT \
2094 # masterkey='Sherlock investigates oleander curry in Bath' \
2095 # password='There is no password like more password' \
2096 # admin
2098 # CGIscriptor will exit after this command with the first option being
2099 # --managelogin. Options have the form:
2101 # salt=[file or string]
2102 # Server salt value to use io the value
2103 # stored in the ticket file. Will replace the stored value if a new
2104 # password is given. If you change the server salt, you have to
2105 # reset all the passwords. There is absolutely no procedure known
2106 # to recover plaintext passwords, except asking the account holders.
2107 # You are strongly adviced to make a backup before you apply such a change
2108 # masterkey=[file or string]
2109 # CGIMasterKey used to read and decrypt the ticket
2110 # newmasterkey=[file or string]
2111 # CGIMasterKey used to encrypt, sign,
2112 # and write the ticket. Defaults to the masterkey. If you change
2113 # the masterkey, you will have to reset all the accounts. You are strongly
2114 # adviced to make a backup before you apply such a change
2115 # password=[file or string]
2116 # New plaintext password
2118 # When the value of an option is a existing file path, the first line of
2119 # that file is used. Options are followed by one or more paths plus names
2120 # of existing ticket files. Each password option is only used for a single
2121 # ticket file. It is most definitely a bad idea to use a password that is
2122 # identical to an existing filepath, as the file will be read instead. Be
2123 # aware that the name of the file should be a cleaned up version of the
2124 # Username. This will not be checked.
2126 # For the authentication and a change of password, the (old) password
2127 # is used to "encrypt" a random one-time token or the new password,
2128 # respectively. For authentication, decryption is not needed, so a secure
2129 # hash function (SHA256) is used to create a one-way hash sum "encryption".
2130 # A new password must be decrypted. New passwords are encryped by XORing
2131 # them with the old password.
2133 # Strong Passwords: It is so easy
2134 # If you only could see what you are typing
2136 # Your password might be vulnerable to brute force guessing
2137 # (https://en.wikipedia.org/wiki/Brute_force_attack).
2138 # Protections against such attacks are costly in terms of code
2139 # complexity, bugs, and execution time. However, there is a very
2140 # simple and secure counter measure. See the XKCD comic
2141 # (http://xkcd.com/936/). The phrase, "There is no password like more
2142 # password" would be both much easier to remember, and still stronger
2143 # than "h4]D%@m:49", at least before this phrase was pasted as an
2144 # example on the Internet.
2146 # For the procedures used at this site, a basic computer setup can
2147 # check in the order of a billion passwords per second. You need a
2148 # password (or phrase) strength in the order of 56 bits to be a
2149 # little secure (one year on a single computer). Please be so kind
2150 # and add the name of your favorite flower, dish, fictional
2151 # character, or small town to your password. Say, Oleander, Curry,
2152 # Sherlock, or Bath, UK (each adds ~12 bits) or even the phrase "Sherlock
2153 # investigates oleander curry in Bath" (adds > 56 bits, note that
2154 # oleander is poisonous, so do not try this curry at home). That
2155 # would be more effective than adding a thousand rounds of encryption.
2156 # Typing long passwords without seeing what you are typing is
2157 # problematic. So a button should be included to make password
2158 # visible.
2161 # Technical matters
2163 # Client side JavaScript code definitions. Variable names starting with '$'
2164 # are CGIscriptor CGI variables. Some of the hashes could be strengthened
2165 # by switching to HMAC signatures. However, the security issues of
2166 # maintaining parallel functions for HMAC in both Perl and Javascript seem
2167 # to be more serious than the attack vectors against the hashes. But HMAC
2168 # is indeed used for the ticket signatures.
2170 # // On Login
2171 # HashPlaintextPassword() {
2172 # var plaintextpassword = document.getElementById('PASSWORD');
2173 # var serversalt = document.getElementById('SERVERSALT');
2174 # var username = document.getElementById('CGIUSERNAME');
2175 # return hex_sha256(plaintextpassword.value+username.value.toLowerCase()+serversalt.value);
2177 # var randomsalt = $RANDOMSALT; // From CGIscriptor
2178 # var loginticket = $LOGINTICKET; // From CGIscriptor
2179 # // Hash plaintext password
2180 # var password = HashPlaintextPassword();
2181 # // Authorize login
2182 # var hashedpassword = hex_sha256(randomsalt+password);
2183 # // Sessionticket
2184 # var sessionticket = hex_sha256(loginticket+password);
2185 # sessionStorage.setItem("CGIscriptorPRIVATE", sessionticket);
2186 # // Secretkey for encrypting new passwords, acts like a one-time pad
2187 # // Is set anew with every login, ie, also whith password changes
2188 # // and for each create new user request
2189 # var secretkey = hex_sha256(password+loginticket+randomsalt);
2190 # sessionStorage.setItem("CGIscriptorSECRET", secretkey);
2192 # // For a SESSION type request
2193 # sessionticket = hex_sha256(sessionStorage.getItem("CGIscriptorPRIVATE"));
2194 # createCookie("CGIscriptorSESSION",sessionticket, 0, "");
2196 // For a CHALLENGE type request
2197 # var sessionset = "$CHALLENGETICKET"; // From CGIscriptor
2198 # var sessionkey = sessionStorage.getItem("CGIscriptorPRIVATE");
2199 # sessionticket = hex_sha256(sessionset+sessionkey);
2200 # createCookie("CGIscriptorCHALLENGE",sessionticket, 0, "");
2202 # // For transmitting a new password
2203 # HashPlaintextNewPassword() {
2204 # var plaintextpassword = document.getElementById('NEWPASSWORD');
2205 # var serversalt = document.getElementById('SERVERSALT');
2206 # var username = document.getElementById('NEWUSERNAME');
2207 # return hex_sha256(plaintextpassword.value+username.value.toLowerCase()+serversalt.value);
2210 # var newpassword = document.getElementById('NEWPASSWORD');
2211 # var newpasswordrep = document.getElementById('NEWPASSWORDREP');
2212 # // Hash plaintext password
2213 # newpassword.value = HashPlaintextNewPassword();
2214 # var secretkey = sessionStorage.getItem("CGIscriptorSECRET");
2216 # var encrypted = XOR_hex_strings(secretkey, newpassword.value);
2217 # newpassword.value = encrypted;
2218 # newpasswordrep.value = encrypted;
2220 # // XOR of hexadecimal strings of equal length
2221 # function XOR_hex_strings(hex1, hex2) {
2222 # var resultHex = "";
2223 # var maxlength = Math.max(hex1.length, hex2.length);
2225 # for(var i=0; i &lt; maxlength; ++i) {
2226 # var h1 = hex1.charAt(i);
2227 # if(! h1) h1='0';
2228 # var h2 = hex2.charAt(i);
2229 # if(! h2) h2 ='0';
2230 # var d1 = parseInt(h1,16);
2231 # var d2 = parseInt(h2,16);
2232 # var resultD = d1^d2;
2233 # resultHex = resultHex+resultD.toString(16);
2234 # };
2235 # return resultHex;
2236 # };
2238 # Password encryption based on $ENV{'CGIMasterKey'}.
2239 # Server side Perl code:
2241 # # Password encryption
2242 # my $masterkey = $ENV{'CGIMasterKey'}
2243 # my $hash1 = hash_string($masterkey.$serversalt);
2244 # my $CryptKey = hash_string($username.$hash1);
2245 # $password = XOR_hex_strings($CryptKey,$password);
2247 # # Key for HMAC signing
2248 # my $hash1 = hash_string($masterkey.$serversalt);
2249 # my $HMACKey = hash_string($username.$hash1);
2253 # USER EXTENSIONS
2255 # A CGIscriptor package is attached to the bottom of this file. With
2256 # this package you can personalize your version of CGIscriptor by
2257 # including often used perl routines. These subroutines can be
2258 # accessed by prefixing their names with CGIscriptor::, e.g.,
2259 # <SCRIPT LANGUAGE=PERL TYPE=text/ssperl>
2260 # CGIscriptor::ListDocs("/Books/*") # List all documents in /Books
2261 # </SCRIPT>
2262 # It already contains some useful subroutines for Document Management.
2263 # As it is a separate package, it has its own namespace, isolated from
2264 # both the evaluator and the main program. To access variables from
2265 # the document <SCRIPT></SCRIPT> blocks, use $CGIexecute::<var>.
2267 # Currently, the following functions are implemented
2268 # (precede them with CGIscriptor::, see below for more information)
2269 # - SAFEqx ('String') -> result of qx/"String"/ # Safe application of ``-quotes
2270 # Is used by text/osshell Shell scripts. Protects all CGI
2271 # (client-supplied) values with single quotes before executing the
2272 # commands (one of the few functions that also works WITHOUT CGIscriptor::
2273 # in front)
2274 # - defineCGIvariable ($name[, $default) -> 0/1 (i.e., failure/success)
2275 # Is used by the META tag to define and initialize CGI and ENV
2276 # name/value pairs. Tries to obtain an initializing value from (in order):
2277 # $ENV{$name}
2278 # The Query string
2279 # The default value given (if any)
2280 # (one of the few functions that also works WITHOUT CGIscriptor::
2281 # in front)
2282 # - CGIsafeFileName (FileName) -> FileName or ""
2283 # Check a string against the Allowed File Characters (and ../ /..).
2284 # Returns an empty string for unsafe filenames.
2285 # - CGIsafeEmailAddress (Email) -> Email or ""
2286 # Check a string against correct email address pattern.
2287 # Returns an empty string for unsafe addresses.
2288 # - RedirectShellScript ('CommandString') -> FILEHANDLER or undef
2289 # Open a named PIPE for SAFEqx to receive ALL shell scripts
2290 # - URLdecode (URL encoded string) -> plain string # Decode URL encoded argument
2291 # - URLencode (plain string) -> URL encoded string # Encode argument as URL code
2292 # - CGIparseValue (ValueName [, URL_encoded_QueryString]) -> Decoded value
2293 # Extract the value of a CGI variable from the global or a private
2294 # URL-encoded query (multipart POST raw, NOT decoded)
2295 # - CGIparseValueList (ValueName [, URL_encoded_QueryString])
2296 # -> List of decoded values
2297 # As CGIparseValue, but now assembles ALL values of ValueName into a list.
2298 # - CGIparseHeader (ValueName [, URL_encoded_QueryString]) -> Header
2299 # Extract the header of a multipart CGI variable from the global or a private
2300 # URL-encoded query ("" when not a multipart variable or absent)
2301 # - CGIparseForm ([URL_encoded_QueryString]) -> Decoded Form
2302 # Decode the complete global URL-encoded query or a private
2303 # URL-encoded query
2304 # - read_url(URL) # Returns the page from URL (with added base tag, both FTP and HTTP)
2305 # Uses main::GET_URL(URL, 1) to get at the command to read the URL.
2306 # - BrowseDirs(RootDirectory [, Pattern, Startdir, CGIname]) # print browsable directories
2307 # - ListDocs(Pattern [,ListType]) # Prints a nested HTML directory listing of
2308 # all documents, e.g., ListDocs("/*", "dl");.
2309 # - HTMLdocTree(Pattern [,ListType]) # Prints a nested HTML listing of all
2310 # local links starting from a given document, e.g.,
2311 # HTMLdocTree("/Welcome.html", "dl");
2314 # THE RESULTS STACK: @CGISCRIPTORRESULTS
2316 # If the pseudo-variable "$CGIscriptorResults" has been defined in a
2317 # META tag, all subsequent SCRIPT and META results are pushed
2318 # on the @CGIscriptorResults stack. This list is just another
2319 # Perl variable and can be used and manipulated like any other list.
2320 # $CGIscriptorResults[-1] is always the last result.
2321 # This is only of limited use, e.g., to use the results of an OS shell
2322 # script inside a Perl script. Will NOT contain the results of Pipes
2323 # or code from MIME-profiling.
2326 # USEFULL CGI PREDEFINED VARIABLES (DO NOT ASSIGN TO THESE)
2328 # $CGI_HOME - The DocumentRoot directory
2329 # $CGI_Decoded_QS - The complete decoded Query String
2330 # $CGI_Content_Length - The ACTUAL length of the Query String
2331 # $CGI_Date - Current date and time
2332 # $CGI_Year $CGI_Month $CGI_Day $CGI_WeekDay - Current Date
2333 # $CGI_Time - Current Time
2334 # $CGI_Hour $CGI_Minutes $CGI_Seconds - Current Time, split
2335 # GMT Date/Time:
2336 # $CGI_GMTYear $CGI_GMTMonth $CGI_GMTDay $CGI_GMTWeekDay $CGI_GMTYearDay
2337 # $CGI_GMTHour $CGI_GMTMinutes $CGI_GMTSeconds $CGI_GMTisdst
2340 # USEFULL CGI ENVIRONMENT VARIABLES
2342 # Variables accessible (in APACHE) as $ENV{<name>}
2343 # (see: "http://hoohoo.ncsa.uiuc.edu/cgi/env.html"):
2345 # QUERY_STRING - The query part of URL, that is, everything that follows the
2346 # question mark.
2347 # PATH_INFO - Extra path information given after the script name
2348 # PATH_TRANSLATED - Extra pathinfo translated through the rule system.
2349 # (This doesn't always make sense.)
2350 # REMOTE_USER - If the server supports user authentication, and the script is
2351 # protected, this is the username they have authenticated as.
2352 # REMOTE_HOST - The hostname making the request. If the server does not have
2353 # this information, it should set REMOTE_ADDR and leave this unset
2354 # REMOTE_ADDR - The IP address of the remote host making the request.
2355 # REMOTE_IDENT - If the HTTP server supports RFC 931 identification, then this
2356 # variable will be set to the remote user name retrieved from
2357 # the server. Usage of this variable should be limited to logging
2358 # only.
2359 # AUTH_TYPE - If the server supports user authentication, and the script
2360 # is protected, this is the protocol-specific authentication
2361 # method used to validate the user.
2362 # CONTENT_TYPE - For queries which have attached information, such as HTTP
2363 # POST and PUT, this is the content type of the data.
2364 # CONTENT_LENGTH - The length of the said content as given by the client.
2365 # SERVER_SOFTWARE - The name and version of the information server software
2366 # answering the request (and running the gateway).
2367 # Format: name/version
2368 # SERVER_NAME - The server's hostname, DNS alias, or IP address as it
2369 # would appear in self-referencing URLs
2370 # GATEWAY_INTERFACE - The revision of the CGI specification to which this
2371 # server complies. Format: CGI/revision
2372 # SERVER_PROTOCOL - The name and revision of the information protocol this
2373 # request came in with. Format: protocol/revision
2374 # SERVER_PORT - The port number to which the request was sent.
2375 # REQUEST_METHOD - The method with which the request was made. For HTTP,
2376 # this is "GET", "HEAD", "POST", etc.
2377 # SCRIPT_NAME - A virtual path to the script being executed, used for
2378 # self-referencing URLs.
2379 # HTTP_ACCEPT - The MIME types which the client will accept, as given by
2380 # HTTP headers. Other protocols may need to get this
2381 # information from elsewhere. Each item in this list should
2382 # be separated by commas as per the HTTP spec.
2383 # Format: type/subtype, type/subtype
2384 # HTTP_USER_AGENT - The browser the client is using to send the request.
2385 # General format: software/version library/version.
2388 # INSTRUCTIONS FOR RUNNING CGIscriptor ON UNIX
2390 # CGIscriptor.pl will run on any WWW server that runs Perl scripts, just add
2391 # a line like the following to your srm.conf file (Apache example):
2393 # ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
2395 # URL's that refer to http://www.your.address/SHTML/... will now be handled
2396 # by CGIscriptor.pl, which can use a private directory tree (default is the
2397 # DOCUMENT_ROOT directory tree, but it can be anywhere, see manual).
2399 # If your hosting ISP won't let you add ScriptAlias lines you can use
2400 # the following "rewrite"-based "scriptalias" in .htaccess
2401 # (from Gerd Franke)
2403 # RewriteEngine On
2404 # RewriteBase /
2405 # RewriteCond %{REQUEST_FILENAME} .html$
2406 # RewriteCond %{SCRIPT_FILENAME} !cgiscriptor.pl$
2407 # RewriteCond %{REQUEST_FILENAME} -f
2408 # RewriteRule ^(.*)$ /cgi-bin/cgiscriptor.pl/$1?&%{QUERY_STRING}
2410 # Everthing with the extension ".html" and not including "cgiscriptor.pl"
2411 # in the url and where the file "path/filename.html" exists is redirected
2412 # to "/cgi.bin/cgiscriptor.pl/path/filename.html?query".
2413 # The user configuration should get the same path-level as the
2414 # .htaccess-file:
2416 # # Just enter your own directory path here
2417 # $YOUR_HTML_FILES = "$ENV{'DOCUMENT_ROOT'}";
2418 # # use DOCUMENT_ROOT only, if .htaccess lies in the root-directory.
2420 # If this .htaccess goes in a specific directory, the path to this
2421 # directory must be added to $ENV{'DOCUMENT_ROOT'}.
2423 # The CGIscriptor file contains all documentation as comments. These
2424 # comments can be removed to speed up loading (e.g., `egrep -v '^#'
2425 # CGIscriptor.pl` > leanScriptor.pl). A bare bones version of
2426 # CGIscriptor.pl, lacking documentation, most comments, access control,
2427 # example functions etc. (but still with the copyright notice and some
2428 # minimal documentation) can be obtained by calling CGIscriptor.pl on the
2429 # command line with the '-slim' command line argument, e.g.,
2431 # >CGIscriptor.pl -slim > slimCGIscriptor.pl
2433 # CGIscriptor.pl can be run from the command line with <path> and <query> as
2434 # arguments, as `CGIscriptor.pl <path> <query>`, inside a perl script
2435 # with 'do CGIscriptor.pl' after setting $ENV{PATH_INFO}
2436 # and $ENV{QUERY_STRING}, or CGIscriptor.pl can be loaded with 'require
2437 # "/real-path/CGIscriptor.pl"'. In the latter case, requests are processed
2438 # by 'Handle_Request();' (again after setting $ENV{PATH_INFO} and
2439 # $ENV{QUERY_STRING}).
2441 # Using the command line execution option, CGIscriptor.pl can be used as a
2442 # document (meta-)preprocessor. If the first argument is '-', STDIN will be read.
2443 # For example:
2445 # > cat MyDynamicDocument.html | CGIscriptor.pl - '[QueryString]' > MyStaticFile.html
2447 # This command line will produce a STATIC file with the DYNAMIC content of
2448 # MyDocument.html "interpolated".
2450 # This option would be very dangerous when available over the internet.
2451 # If someone could sneak a 'http://www.your.domain/-' URL past your
2452 # server, CGIscriptor could EXECUTE any POSTED contend.
2453 # Therefore, for security reasons, STDIN will NOT be read
2454 # if ANY of the HTTP server environment variables is set (e.g.,
2455 # SERVER_PORT, SERVER_PROTOCOL, SERVER_NAME, SERVER_SOFTWARE,
2456 # HTTP_USER_AGENT, REMOTE_ADDR).
2457 # This block on processing STDIN on HTTP requests can be lifted by setting
2458 # $BLOCK_STDIN_HTTP_REQUEST = 0;
2459 # In the security configuration. Butbe carefull when doing this.
2460 # It can be very dangerous.
2462 # Running demo's and more information can be found at
2463 # http://www.fon.hum.uva.nl/~rob/OSS/OSS.html
2465 # A pocket-size HTTP daemon, CGIservlet.pl, is available from my web site or
2466 # CPAN that can use CGIscriptor.pl as the base of a µWWW server and
2467 # demonstrates its use.
2470 # PROCESSING NON-FILESYSTEM DATA
2472 # Normally, HTTP (WWW) requests map onto file that can be accessed
2473 # using the perl open() function. That is, the web server runs on top of
2474 # some directory structure. However, we can envission (and put to good
2475 # use) other systems that do not use a normal file system. The whole CGI
2476 # was developed to make dynamic document generation possible.
2478 # A special case is where we want to have it both: A normal web server
2479 # with normal "file data", but not a normal files system. For instance,
2480 # we want or normal Web Site to run directly from a RAM hash table or
2481 # other database, instead of from disk. But we do NOT want to code the
2482 # whole site structure in CGI.
2484 # CGIscriptor can do this. If the web server fills an environment variable
2485 # $ENV{'CGI_FILE_CONTENT'} with the content of the "file", then the content
2486 # of this variable is processed instead of opening a file. If this environment
2487 # variable has the value '-', the content of another environment variable,
2488 # $ENV{'CGI_DATA_ACCESS_CODE'} is executed as:
2489 # eval("\@_ = ($file_path); do {$ENV{'CGI_DATA_ACCESS_CODE'}};")
2490 # and the result is processed as if it was the content of the requested
2491 # file.
2492 # (actually, the names of the environment variables are user configurable,
2493 # they are stored in the local variables $CGI_FILE_CONTENT and
2494 # $CGI_DATA_ACCESS_CODE)
2496 # When using this mechanism, the SRC attribute mechanism will only partially work.
2497 # Only the "recursive" calls to CGIscriptor (the ProcessFile() function)
2498 # will work, the automagical execution of SRC files won't. (In this case,
2499 # the SRC attribute won't work either for other scripting languages)
2502 # NON-UNIX PLATFORMS
2504 # CGIscriptor.pl was mainly developed and tested on UNIX. However, as I
2505 # coded part of the time on an Apple Macintosh under MacPerl, I made sure
2506 # CGIscriptor did run under MacPerl (with command line options). But only
2507 # as an independend script, not as part of a HTTP server. I have used it
2508 # under Apache in Windows XP.
2510 ENDOFHELPTEXT
2511 exit;
2513 ###############################################################################
2515 # SECURITY CONFIGURATION
2517 # Special configurations related to SECURITY
2518 # (i.e., optional, see also environment variables below)
2520 # LOGGING
2521 # Log Clients and the requested paths (Redundant when loging Queries)
2523 $ClientLog = "./Client.log"; # (uncomment for use)
2525 # Format: Localtime | REMOTE_USER REMOTE_IDENT REMOTE_HOST REMOTE_ADDRESS \
2526 # PATH_INFO CONTENT_LENGTH (actually, the real query+post length)
2528 # Log Clients and the queries, the CGIQUERYDECODE is required if you want
2529 # to log queries. If you log Queries, the loging of Clients is redundant
2530 # (note that queries can be quite long, so this might not be a good idea)
2532 #$QueryLog = "./Query.log"; # (uncomment for use)
2534 # ACCESS CONTROL
2535 # the Access files should contain Hostnames or IP addresses,
2536 # i.e. REMOTE_HOST or REMOTE_ADDR, each on a separate line
2537 # optionally followed by one ore more file patterns, e.g., "edu /DEMO".
2538 # Matching is done "domain first". For example ".edu" matches all
2539 # clients whose "name" ends in ".edu" or ".EDU". The file pattern
2540 # "/DEMO" matches all paths that contain the strings "/DEMO" or "/demo"
2541 # (both matchings are done case-insensitive).
2542 # The name special symbol "-" matches ALL clients who do not supply a
2543 # REMOTE_HOST name, "*" matches all clients.
2544 # Lines starting with '-e' are evaluated. A non-zero return value indicates
2545 # a match. You can use $REMOTE_HOST, $REMOTE_ADDR, and $PATH_INFO. These
2546 # lines are evaluated in the program's own name-space. So DO NOT assign to
2547 # variables.
2549 # Accept the following users (remove comment # and adapt filename)
2550 $CGI_Accept = -s "$YOUR_SCRIPTS/ACCEPT.lis" ? "$YOUR_SCRIPTS/ACCEPT.lis" : ''; # (uncomment for use)
2552 # Reject requests from the following users (remove comment # and
2553 # adapt filename, this is only of limited use)
2554 $CGI_Reject = -s "$YOUR_SCRIPTS/REJECT.lis" ? "$YOUR_SCRIPTS/REJECT.lis" : ''; # (uncomment for use)
2556 # Empty lines or comment lines starting with '#' are ignored in both
2557 # $CGI_Accept and $CGI_Reject.
2559 # Block STDIN (i.e., '-') requests when servicing an HTTP request
2560 # Comment this out if you realy want to use STDIN in an on-line web server
2561 $BLOCK_STDIN_HTTP_REQUEST = 1;
2564 # End of security configuration
2566 ##################################################<<<<<<<<<<End Remove
2568 # PARSING CGI VALUES FROM THE QUERY STRING (USER CONFIGURABLE)
2570 # The CGI parse commands. These commands extract the values of the
2571 # CGI variables from the URL encoded Query String.
2572 # If you want to use your own CGI decoders, you can call them here
2573 # instead, using your own PATH and commenting/uncommenting the
2574 # appropriate lines
2576 # CGI parse command for individual values
2577 # (if $List > 0, returns a list value, if $List < 0, a hash table, this is optional)
2578 sub YOUR_CGIPARSE # ($Name [, $List]) -> Decoded value
2580 my $Name = shift;
2581 my $List = shift || 0;
2582 # Use one of the following by uncommenting
2583 if(!$List) # Simple value
2585 return CGIscriptor::CGIparseValue($Name) ;
2587 elsif($List < 0) # Hash tables
2589 return CGIscriptor::CGIparseValueHash($Name); # Defined in CGIscriptor below
2591 else # Lists
2593 return CGIscriptor::CGIparseValueList($Name); # Defined in CGIscriptor below
2596 # return `/PATH/cgiparse -value $Name`; # Shell commands
2597 # require "/PATH/cgiparse.pl"; return cgivalue($Name); # Library
2599 # Complete queries
2600 sub YOUR_CGIQUERYDECODE
2602 # Use one of the following by uncommenting
2603 return CGIscriptor::CGIparseForm(); # Defined in CGIscriptor below
2604 # return `/PATH/cgiparse -form`; # Shell commands
2605 # require "/PATH/cgiparse.pl"; return cgiform(); # Library
2608 # End of configuration
2610 #######################################################################
2612 # Translating input files.
2613 # Allows general and global conversions of files using Regular Expressions
2614 # Translations are applied in the order of definition.
2616 # Define:
2617 # my $TranslationPaths = 'pattern'; # Pattern matching PATH_INFO
2619 # push(@TranslationTable, ['pattern', 'replacement']);
2620 # e.g. (for Ruby Rails):
2621 # push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2622 # push(@TranslationTable, ['%>', '</SCRIPT>']);
2624 # Runs:
2625 # my $currentRegExp;
2626 # foreach $currentRegExp (keys(%TranslationTable))
2628 # my $currentRegExp;
2629 # foreach $currentRegExp (@TranslationTable)
2631 # my ($pattern, $replacement) = @$currentRegExp;
2632 # $$text =~ s!$pattern!$replacement!msg;
2633 # };
2634 # };
2636 # Configuration section
2638 #######################################################################
2640 # The file paths on which to apply the translation
2641 my $TranslationPaths = ''; # NO files
2642 #$TranslationPaths = '.'; # ANY file
2643 # $TranslationPaths = '\.html'; # HTML files
2645 my @TranslationTable = ();
2646 # Some legacy code
2647 push(@TranslationTable, ['\<\s*CGI\s+([^\>])*\>', '\<SCRIPT TYPE=\"text/ssperl\"\>$1\<\/SCRIPT>']);
2648 # Ruby Rails?
2649 push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2650 push(@TranslationTable, ['%>', '</SCRIPT>']);
2652 sub performTranslation # (\$text)
2654 my $text = shift || return;
2655 if(@TranslationTable && $TranslationPaths && $ENV{'PATH_INFO'} =~ m!$TranslationPaths!)
2657 my $currentRegExp;
2658 foreach $currentRegExp (@TranslationTable)
2660 my ($pattern, $replacement) = @$currentRegExp;
2661 $$text =~ s!$pattern!$replacement!msg;
2666 #######################################################################
2668 # Seamless access to other (Scripting) Languages
2669 # TYPE='text/ss<interpreter>'
2671 # Configuration section
2673 #######################################################################
2675 # OTHER SCRIPTING LANGUAGES AT THE SERVER SIDE (MIME => OScommand)
2676 # Yes, it realy is this simple! (unbelievable, isn't it)
2677 # NOTE: Some interpreters require some filtering to obtain "clean" output
2679 %ScriptingLanguages = (
2680 "text/testperl" => 'perl', # Perl for testing
2681 "text/sspython" => 'python', # Python
2682 "text/ssruby" => 'ruby', # Ruby
2683 "text/sstcl" => 'tcl', # TCL
2684 "text/ssawk" => 'awk -f-', # Awk
2685 "text/sslisp" => # lisp (rep, GNU)
2686 'rep | tail +4 '."| egrep -v '> |^rep. |^nil\\\$'",
2687 "text/xlispstat" => # xlispstat
2688 'xlispstat | tail +7 ' ."| egrep -v '> \\\$|^NIL'",
2689 "text/ssprolog" => # Prolog (GNU)
2690 "gprolog | tail +4 | sed 's/^| ?- //'",
2691 "text/ssm4" => 'm4', # M4 macro's
2692 "text/sh" => 'sh', # Born shell
2693 "text/bash" => 'bash', # Born again shell
2694 "text/csh" => 'csh', # C shell
2695 "text/ksh" => 'ksh', # Korn shell
2696 "text/sspraat" => # Praat (sound/speech analysis)
2697 "praat - | sed 's/Praat > //g'",
2698 "text/ssr" => # R
2699 "R --vanilla --slave | sed 's/^[\[0-9\]*] //'",
2700 "text/ssrebol" => # REBOL
2701 "rebol --quiet|egrep -v '^[> ]* == '|sed 's/^\\s*\[> \]* //'",
2702 "text/postgresql" => 'psql 2>/dev/null',
2704 # Not real scripting, but the use of other applications
2705 "text/ssmailto" => "awk 'NF||F{F=1;print \\\$0;}'|mailto >/dev/null", # Send mail from server
2706 "text/ssdisplay" => 'cat', # Display, (interpolation)
2707 "text/sslogfile" => # Log to file, (interpolation)
2708 "awk 'NF||L {if(!L){L=tolower(\\\$1)~/^file:\\\$/ ? \\\$2 : \\\$1;}else{print \\\$0 >> L;};}'",
2710 "" => ""
2713 # To be able to access the CGI variables in your script, they
2714 # should be passed to the scripting language in a readable form
2715 # Here you can enter how they should be printed (the first %s
2716 # is replaced by the NAME of the CGI variable as it apears in the
2717 # META tag, the second by its VALUE).
2718 # For Perl this would be:
2719 # "text/testperl" => '$%s = "%s";',
2720 # which would be executed as
2721 # printf('$%s = "%s";', $CGI_NAME, $CGI_VALUE);
2723 # If the hash table value doesn't exist, nothing is done
2724 # (you have to parse the Environment variables yourself).
2725 # If it DOES exist but is empty (e.g., "text/sspraat" => '',)
2726 # Perl string interpolation of variables (i.e., $var, @array,
2727 # %hash) is performed. This means that $@%\ must be protected
2728 # with a \.
2730 %ScriptingCGIvariables = (
2731 "text/testperl" => "\$\%s = '\%s';", # Perl $VAR = 'value'; (for testing)
2732 "text/sspython" => "\%s = '\%s'", # Python VAR = 'value'
2733 "text/ssruby" => '@%s = "%s"', # Ruby @VAR = 'value'
2734 "text/sstcl" => 'set %s "%s"', # TCL set VAR "value"
2735 "text/ssawk" => '%s = "%s";', # Awk VAR = 'value';
2736 "text/sslisp" => '(setq %s "%s")', # Gnu lisp (rep) (setq VAR "value")
2737 "text/xlispstat" => '(setq %s "%s")', # xlispstat (setq VAR "value")
2738 "text/ssprolog" => '', # Gnu prolog (interpolated)
2739 "text/ssm4" => "define(`\%s', `\%s')", # M4 macro's define(`VAR', `value')
2740 "text/sh" => "\%s='\%s'", # Born shell VAR='value'
2741 "text/bash" => "\%s='\%s'", # Born again shell VAR='value'
2742 "text/csh" => "\$\%s='\%s';", # C shell $VAR = 'value';
2743 "text/ksh" => "\$\%s='\%s';", # Korn shell $VAR = 'value';
2745 "text/ssrebol" => '%s: copy "%s"', # REBOL VAR: copy "value"
2746 "text/sspraat" => '', # Praat (interpolation)
2747 "text/ssr" => '%s <- "%s";', # R VAR <- "value";
2748 "text/postgresql" => '', # PostgreSQL (interpolation)
2750 # Not real scripting, but the use of other applications
2751 "text/ssmailto" => '', # MAILTO, (interpolation)
2752 "text/ssdisplay" => '', # Display, (interpolation)
2753 "text/sslogfile" => '', # Log to file, (interpolation)
2755 "" => ""
2758 # If you want something added in front or at the back of each script
2759 # block as send to the interpreter add it here.
2760 # mime => "string", e.g., "text/sspython" => "python commands"
2761 %ScriptingPrefix = (
2762 "text/testperl" => "\# Prefix Code;", # Perl script testing
2763 "text/ssm4" => 'divert(0)', # M4 macro's (open STDOUT)
2765 "" => ""
2767 # If you want something added at the end of each script block
2768 %ScriptingPostfix = (
2769 "text/testperl" => "\# Postfix Code;", # Perl script testing
2770 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2772 "" => ""
2774 # If you need initialization code, directly after opening
2775 %ScriptingInitialization = (
2776 "text/testperl" => "\# Initialization Code;", # Perl script testing
2777 "text/ssawk" => 'BEGIN {', # Server Side awk scripts (VAR = "value")
2778 "text/sslisp" => '(prog1 nil ', # Lisp (rep)
2779 "text/xlispstat" => '(prog1 nil ', # xlispstat
2780 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2782 "" => ""
2784 # If you need cleanup code before closing
2785 %ScriptingCleanup = (
2786 "text/testperl" => "\# Cleanup Code;", # Perl script testing
2787 "text/sspraat" => 'Quit',
2788 "text/ssawk" => '};', # Server Side awk scripts (VAR = "value")
2789 "text/sslisp" => '(princ "\n" standard-output)).', # Closing print to rep
2790 "text/xlispstat" => '(print ""))', # Closing print to xlispstat
2791 "text/postgresql" => '\q', # quit psql
2792 "text/ssdisplay" => "", # close cat
2794 "" => ""
2797 # End of configuration for foreign scripting languages
2799 ###############################################################################
2801 # Initialization Code
2804 sub Initialize_Request
2806 ###############################################################################
2808 # ENVIRONMENT VARIABLES
2810 # Use environment variables to configure CGIscriptor on a temporary basis.
2811 # If you define any of the configurable variables as environment variables,
2812 # these are used instead of the "hard coded" values above.
2814 $SS_PUB = $ENV{'SS_PUB'} || $YOUR_HTML_FILES;
2815 $SS_SCRIPT = $ENV{'SS_SCRIPT'} || $YOUR_SCRIPTS;
2818 # Substitution strings, these are used internally to handle the
2819 # directory separator strings, e.g., '~/' -> 'SS_PUB:' (Mac)
2820 $HOME_SUB = $SS_PUB;
2821 $SCRIPT_SUB = $SS_SCRIPT;
2824 # Make sure all script are reliably loaded
2825 push(@INC, $SS_SCRIPT);
2828 # Add the directory separator to the "home" directories.
2829 # (This is required for ~/ and ./ substitution)
2830 $HOME_SUB .= '/' if $HOME_SUB;
2831 $SCRIPT_SUB .= '/' if $SCRIPT_SUB;
2833 $CGI_HOME = $ENV{'DOCUMENT_ROOT'};
2834 $ENV{'PATH_TRANSLATED'} =~ /$ENV{'PATH_INFO'}/is;
2835 $CGI_HOME = $` unless $ENV{'DOCUMENT_ROOT'}; # Get the DOCUMENT_ROOT directory
2836 $default_values{'CGI_HOME'} = $CGI_HOME;
2837 $ENV{'HOME'} = $CGI_HOME;
2838 # Set SS_PUB and SS_SCRIPT as Environment variables (make them available
2839 # to the scripts)
2840 $ENV{'SS_PUB'} = $SS_PUB unless $ENV{'SS_PUB'};
2841 $ENV{'SS_SCRIPT'} = $SS_SCRIPT unless $ENV{'SS_SCRIPT'};
2843 $FilePattern = $ENV{'FilePattern'} || $FilePattern;
2844 $MaximumQuerySize = $ENV{'MaximumQuerySize'} || $MaximumQuerySize;
2845 $ClientLog = $ENV{'ClientLog'} || $ClientLog;
2846 $QueryLog = $ENV{'QueryLog'} || $QueryLog;
2847 $CGI_Accept = $ENV{'CGI_Accept'} || $CGI_Accept;
2848 $CGI_Reject = $ENV{'CGI_Reject'} || $CGI_Reject;
2850 # Parse file names
2851 $CGI_Accept =~ s@^\~/@$HOME_SUB@g if $CGI_Accept;
2852 $CGI_Reject =~ s@^\~/@$HOME_SUB@g if $CGI_Reject;
2853 $ClientLog =~ s@^\~/@$HOME_SUB@g if $ClientLog;
2854 $QueryLog =~ s@^\~/@$HOME_SUB@g if $QueryLog;
2856 $CGI_Accept =~ s@^\./@$SCRIPT_SUB@g if $CGI_Accept;
2857 $CGI_Reject =~ s@^\./@$SCRIPT_SUB@g if $CGI_Reject;
2858 $ClientLog =~ s@^\./@$SCRIPT_SUB@g if $ClientLog;
2859 $QueryLog =~ s@^\./@$SCRIPT_SUB@g if $QueryLog;
2861 @CGIscriptorResults = (); # A stack of results
2863 # end of Environment variables
2865 #############################################################################
2867 # Define and Store "standard" values
2869 # BEFORE doing ANYTHING check the size of Query String
2870 length($ENV{'QUERY_STRING'}) <= $MaximumQuerySize || dieHandler(2, "QUERY TOO LONG\n");
2872 # The Translated Query String and the Actual length of the (decoded)
2873 # Query String
2874 if($ENV{'QUERY_STRING'})
2876 # If this can contain '`"-quotes, be carefull to use it QUOTED
2877 $default_values{CGI_Decoded_QS} = YOUR_CGIQUERYDECODE();
2878 $default_values{CGI_Content_Length} = length($default_values{CGI_Decoded_QS});
2881 # Get the current Date and time and store them as default variables
2883 # Get Local Time
2884 $LocalTime = localtime;
2886 # CGI_Year CGI_Month CGI_Day CGI_WeekDay CGI_Time
2887 # CGI_Hour CGI_Minutes CGI_Seconds
2889 $default_values{CGI_Date} = $LocalTime;
2890 ($default_values{CGI_WeekDay},
2891 $default_values{CGI_Month},
2892 $default_values{CGI_Day},
2893 $default_values{CGI_Time},
2894 $default_values{CGI_Year}) = split(' ', $LocalTime);
2895 ($default_values{CGI_Hour},
2896 $default_values{CGI_Minutes},
2897 $default_values{CGI_Seconds}) = split(':', $default_values{CGI_Time});
2899 # GMT:
2900 # CGI_GMTYear CGI_GMTMonth CGI_GMTDay CGI_GMTWeekDay CGI_GMTYearDay
2901 # CGI_GMTHour CGI_GMTMinutes CGI_GMTSeconds CGI_GMTisdst
2903 ($default_values{CGI_GMTSeconds},
2904 $default_values{CGI_GMTMinutes},
2905 $default_values{CGI_GMTHour},
2906 $default_values{CGI_GMTDay},
2907 $default_values{CGI_GMTMonth},
2908 $default_values{CGI_GMTYear},
2909 $default_values{CGI_GMTWeekDay},
2910 $default_values{CGI_GMTYearDay},
2911 $default_values{CGI_GMTisdst}) = gmtime;
2915 # End of Initialize Request
2917 ###################################################################
2919 # SECURITY: ACCESS CONTROL
2921 # Check the credentials of each client (use pattern matching, domain first).
2922 # This subroutine will kill-off (die) the current process whenever access
2923 # is denied.
2925 sub Access_Control
2927 # >>>>>>>>>>Start Remove
2929 # ACCEPTED CLIENTS
2931 # Only accept clients which are authorized, reject all unnamed clients
2932 # if REMOTE_HOST is given.
2933 # If file patterns are given, check whether the user is authorized for
2934 # THIS file.
2935 if($CGI_Accept)
2937 # Use local variables, REMOTE_HOST becomes '-' if undefined
2938 my $REMOTE_HOST = $ENV{REMOTE_HOST} || '-';
2939 my $REMOTE_ADDR = $ENV{REMOTE_ADDR};
2940 my $PATH_INFO = $ENV{'PATH_INFO'};
2942 open(CGI_Accept, "<$CGI_Accept") || dieHandler(3, "$CGI_Accept: $!\n");
2943 $NoAccess = 1;
2944 while(<CGI_Accept>)
2946 next unless /\S/; # Skip empty lines
2947 next if /^\s*\#/; # Skip comments
2948 chomp;
2950 # Full expressions
2951 if(/^\s*-e\s/is)
2953 my $Accept = $'; # Get the expression
2954 $NoAccess &&= eval($Accept); # evaluate the expresion
2956 elsif($PATH_INFO ne "")
2958 my ($Accept, @FilePatternList) = split;
2959 if($Accept eq '*' # Always match
2960 ||$REMOTE_HOST =~ /\Q$Accept\E$/is # REMOTE_HOST matches
2961 || (
2962 $Accept =~ /^[0-9\.]+$/
2963 && $REMOTE_ADDR =~ /^\Q$Accept\E/ # IP address matches
2967 if($FilePatternList[0])
2969 my $invert = 0;
2970 if($FilePatternList[0] eq "!" or $FilePatternList[0] eq "not")
2972 $invert = 1;
2973 shift(@FilePatternList);
2975 foreach $Pattern (@FilePatternList)
2977 # Check whether this patterns is accepted
2978 my $value = ($PATH_INFO !~ m@\Q$Pattern\E@is);
2979 $value = not $value if $invert;
2980 $NoAccess &&= $value;
2983 else
2985 $NoAccess = 0; # No file patterns -> Accepted
2989 # Blocked
2990 last unless $NoAccess;
2992 close(CGI_Accept);
2993 if($NoAccess && $PATH_INFO ne "")
2995 dieHandler(4, "No Access: $PATH_INFO\n");
2996 $ENV{'PATH_INFO'} = "";
3001 # REJECTED CLIENTS
3003 # Reject named clients, accept all unnamed clients
3004 if($CGI_Reject)
3006 # Use local variables, REMOTE_HOST becomes '-' if undefined
3007 my $REMOTE_HOST = $ENV{'REMOTE_HOST'} || '-';
3008 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
3009 my $PATH_INFO = $ENV{'PATH_INFO'};
3011 open(CGI_Reject, "<$CGI_Reject") || dieHandler(5, "$CGI_Reject: $!\n");
3012 $NoAccess = 0;
3013 while(<CGI_Reject>)
3015 next unless /\S/; # Skip empty lines
3016 next if /^\s*\#/; # Skip comments
3017 chomp;
3019 # Full expressions
3020 if(/^-e\s/is)
3022 my $Reject = $'; # Get the expression
3023 $NoAccess ||= eval($Reject); # evaluate the expresion
3025 elsif($PATH_INFO ne "")
3027 my ($Reject, @FilePatternList) = split;
3028 if($Reject eq '*' # Always match
3029 ||$REMOTE_HOST =~ /\Q$Reject\E$/is # REMOTE_HOST matches
3030 ||($Reject =~ /^[0-9\.]+$/
3031 && $REMOTE_ADDR =~ /^\Q$Reject\E/is # IP address matches
3035 if($FilePatternList[0])
3037 my $invert = 0;
3038 if($FilePatternList[0] eq "!" or $FilePatternList[0] eq "not")
3040 $invert = 1;
3041 shift(@FilePatternList);
3043 foreach $Pattern (@FilePatternList)
3045 my $value = ($PATH_INFO =~ m@\Q$Pattern\E@is);
3046 $value = not $value if $invert;
3047 $NoAccess ||= $value;
3050 else
3052 $NoAccess = 1; # No file patterns -> Rejected
3056 last if $NoAccess;
3058 close(CGI_Reject);
3059 if($NoAccess && $PATH_INFO ne "")
3061 dieHandler(4, "Request rejected: $PATH_INFO\n");
3062 $ENV{'PATH_INFO'} = "";
3066 ##########################################################<<<<<<<<<<End Remove
3069 # Get the filename
3071 # Does the filename contain any illegal characters (e.g., |, >, or <)
3072 dieHandler(7, "Illegal request: $ENV{'PATH_INFO'}\n") if $ENV{'PATH_INFO'} =~ /[^$FileAllowedChars]/;
3073 # Does the pathname contain an illegal (blocked) "directory"
3074 dieHandler(8, "Illegal request: $ENV{'PATH_INFO'}\n") if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@; # Access is blocked
3075 # Does the pathname contain a direct referencer to BinaryMapFile
3076 dieHandler(9, "Illegal request: $ENV{'PATH_INFO'}\n") if $BinaryMapFile && $ENV{'PATH_INFO'} =~ m@\Q$BinaryMapFile\E@; # Access is blocked
3078 # SECURITY: Is PATH_INFO allowed?
3079 if($FilePattern && $ENV{'PATH_INFO'} && $ENV{'PATH_INFO'} ne '-' &&
3080 ($ENV{'PATH_INFO'} !~ m@($FilePattern)$@is))
3082 # Unsupported file types can be processed by a special raw-file
3083 if($BinaryMapFile)
3085 $ENV{'CGI_BINARY_FILE'} = $ENV{'PATH_INFO'};
3086 $ENV{'PATH_INFO'} = $BinaryMapFile;
3088 else
3090 dieHandler(10, "Illegal file\n");
3096 # End of Security Access Control
3099 ############################################################################
3101 # Get the POST part of the query and add it to the QUERY_STRING.
3104 sub Get_POST_part_of_query
3107 # If POST, Read data from stdin to QUERY_STRING
3108 if($ENV{'REQUEST_METHOD'} =~ /POST/is)
3110 # SECURITY: Check size of Query String
3111 $ENV{'CONTENT_LENGTH'} <= $MaximumQuerySize || dieHandler(11, "Query too long: $ENV{'CONTENT_LENGTH'}\n"); # Query too long
3112 my $QueryRead = 0;
3113 my $SystemRead = $ENV{'CONTENT_LENGTH'};
3114 $ENV{'QUERY_STRING'} .= '&' if length($ENV{'QUERY_STRING'}) > 0;
3115 while($SystemRead > 0)
3117 $QueryRead = sysread(STDIN, $Post, $SystemRead); # Limit length
3118 $ENV{'QUERY_STRING'} .= $Post;
3119 $SystemRead -= $QueryRead;
3121 # Update decoded Query String
3122 $default_values{CGI_Decoded_QS} = YOUR_CGIQUERYDECODE();
3123 $default_values{CGI_Content_Length} =
3124 length($default_values{CGI_Decoded_QS});
3128 # End of getting POST part of query
3131 ############################################################################
3133 # Start (HTML) output and logging
3134 # (if there are irregularities, it can kill the current process)
3137 sub Initialize_output
3139 # Construct the REAL file path (except for STDIN on the command line)
3140 my $file_path = $ENV{'PATH_INFO'} ne '-' ? $SS_PUB . $ENV{'PATH_INFO'} : '-';
3141 $file_path =~ s/\?.*$//; # Remove query
3142 # This is only necessary if your server does not catch ../ directives
3143 $file_path !~ m@\.\./@ || dieHandler(12, "Illegal ../ Construct\n"); # SECURITY: Do not allow ../ constructs
3145 # Block STDIN use (-) if CGIscriptor is servicing a HTTP request
3146 if($file_path eq '-')
3148 dieHandler(13, "STDIN request in On Line system\n") if $BLOCK_STDIN_HTTP_REQUEST
3149 && ($ENV{'SERVER_SOFTWARE'}
3150 || $ENV{'SERVER_NAME'}
3151 || $ENV{'GATEWAY_INTERFACE'}
3152 || $ENV{'SERVER_PROTOCOL'}
3153 || $ENV{'SERVER_PORT'}
3154 || $ENV{'REMOTE_ADDR'}
3155 || $ENV{'HTTP_USER_AGENT'});
3160 if($ClientLog)
3162 open(ClientLog, ">>$ClientLog");
3163 print ClientLog "$LocalTime | ",
3164 ($ENV{REMOTE_USER} || "-"), " ",
3165 ($ENV{REMOTE_IDENT} || "-"), " ",
3166 ($ENV{REMOTE_HOST} || "-"), " ",
3167 $ENV{REMOTE_ADDR}, " ",
3168 $ENV{PATH_INFO}, " ",
3169 $ENV{'CGI_BINARY_FILE'}, " ",
3170 ($default_values{CGI_Content_Length} || "-"),
3171 "\n";
3172 close(ClientLog);
3174 if($QueryLog)
3176 open(QueryLog, ">>$QueryLog");
3177 print QueryLog "$LocalTime\n",
3178 ($ENV{REMOTE_USER} || "-"), " ",
3179 ($ENV{REMOTE_IDENT} || "-"), " ",
3180 ($ENV{REMOTE_HOST} || "-"), " ",
3181 $ENV{REMOTE_ADDR}, ": ",
3182 $ENV{PATH_INFO}, " ",
3183 $ENV{'CGI_BINARY_FILE'}, "\n";
3185 # Write Query to Log file
3186 print QueryLog $default_values{CGI_Decoded_QS}, "\n\n";
3187 close(QueryLog);
3190 # Return the file path
3191 return $file_path;
3194 # End of Initialize output
3197 ############################################################################
3199 # Handle login access
3201 # Access is based on a valid session ticket.
3202 # Session tickets should be dependend on user name
3203 # and IP address. The patterns of URLs for which a
3204 # session ticket is needed and the login URL are stored in
3205 # %TicketRequiredPatterns as:
3206 # 'RegEx pattern' -> 'SessionPath\tPasswordPath\tLogin URL\tExpiration'
3209 sub Log_In_Access # () -> 0 = Access Allowed, Login page if access is not allowed
3211 # No patterns, no login
3212 goto Return unless %TicketRequiredPatterns;
3214 # Get and initialize values (watch out for stuff processed by BinaryMap files)
3215 my ($SessionPath, $PasswordsPath, $Login, $valid_duration) = ("", "", "", 0);
3216 my $PATH_INFO = $ENV{'CGI_BINARY_FILE'} ? $ENV{'CGI_BINARY_FILE'} : $ENV{'PATH_INFO'};
3217 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
3218 goto Return if $REMOTE_ADDR =~ /[^0-9\.]/;
3219 # Extract TICKETs, starting with returned cookies
3220 CGIexecute::defineCGIvariable('LOGINTICKET', "");
3221 CGIexecute::defineCGIvariable('SESSIONTICKET', "");
3222 CGIexecute::defineCGIvariable('CHALLENGETICKET', "");
3223 Get_All_Cookies();
3224 if(length(keys(%CGI_Cookies)) > 0)
3226 ${"CGIexecute::LOGINTICKET"} = $CGI_Cookies{'CGIscriptorLOGIN'}
3227 if $CGI_Cookies{'CGIscriptorLOGIN'} && $CGI_Cookies{'CGIscriptorLOGIN'} ne "-";
3228 $CGI_Cookies{'CGIscriptorLOGIN'} = "-";
3229 ${"CGIexecute::CHALLENGETICKET"} = $CGI_Cookies{'CGIscriptorCHALLENGE'}
3230 if $CGI_Cookies{'CGIscriptorCHALLENGE'} && $CGI_Cookies{'CGIscriptorCHALLENGE'} ne "-";
3231 $CGI_Cookies{'CGIscriptorCHALLENGE'} = "-";
3232 ${"CGIexecute::SESSIONTICKET"} = $CGI_Cookies{'CGIscriptorSESSION'}
3233 if $CGI_Cookies{'CGIscriptorSESSION'} && $CGI_Cookies{'CGIscriptorSESSION'} ne "-";
3234 $CGI_Cookies{'CGIscriptorSESSION'} = "-";
3236 # Get and check the tickets. Tickets are restricted to word-characters (alphanumeric+_+.)
3237 my $LOGINTICKET = ${"CGIexecute::LOGINTICKET"};
3238 goto Return if ($LOGINTICKET && $LOGINTICKET =~ /[^\w\.]/isg);
3239 my $SESSIONTICKET = ${"CGIexecute::SESSIONTICKET"};
3240 goto Return if ($SESSIONTICKET && $SESSIONTICKET =~ /[^\w\.]/isg);
3241 my $CHALLENGETICKET = ${"CGIexecute::CHALLENGETICKET"};
3242 goto Return if ($CHALLENGETICKET && $CHALLENGETICKET =~ /[^\w\.]/isg);
3243 # Look for a LOGOUT message
3244 my $LOGOUT = $ENV{QUERY_STRING} =~ /(^|\&)LOGOUT([\=\&]|$)/;
3245 # Username and password
3246 CGIexecute::defineCGIvariable('CGIUSERNAME', "");
3247 my $username = lc(${"CGIexecute::CGIUSERNAME"});
3248 goto Return if $username =~ m!^[^\w]!isg || $username =~ m![^\w \-]!isg;
3249 my $userfile = lc($username);
3250 $userfile =~ s/[^\w]/_/isg;
3251 CGIexecute::defineCGIvariable('PASSWORD', "");
3252 my $password = ${"CGIexecute::PASSWORD"};
3253 CGIexecute::defineCGIvariable('NEWUSERNAME', "");
3254 my $newuser = lc(${"CGIexecute::NEWUSERNAME"});
3255 CGIexecute::defineCGIvariable('NEWPASSWORD', "");
3256 my $newpassword = ${"CGIexecute::NEWPASSWORD"};
3258 foreach my $pattern (keys(%TicketRequiredPatterns))
3260 # Check BOTH the real PATH_INFO and the CGI_BINARY_FILE variable
3261 if($ENV{'PATH_INFO'} =~ m#$pattern# || $ENV{'CGI_BINARY_FILE'} =~ m#$pattern#)
3263 # Fall through a sieve of requirements
3264 ($SessionPath, $PasswordsPath, $Login, $validtime) = split(/\t/, $TicketRequiredPatterns{$pattern});
3266 # Is there a change password request?
3267 if($newuser && $LOGINTICKET && $username)
3269 goto Login unless (-s "$SessionPath/$LOGINTICKET");
3270 goto Login unless (-s "$PasswordsPath/$userfile");
3271 my $ticket_valid = check_ticket_validity("PASSWORD", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3272 goto Login unless $ticket_valid;
3273 $ticket_valid = check_ticket_validity("LOGIN", "$SessionPath/$LOGINTICKET", $REMOTE_ADDR, ".", 1);
3274 goto Login unless $ticket_valid;
3276 my ($sessiontype, $currentticket) = ("", "");
3277 if($CHALLENGETICKET) {($sessiontype, $currentticket) = ("CHALLENGE", $CHALLENGETICKET);}
3278 elsif($SESSIONTICKET) {($sessiontype, $currentticket) = ("SESSION", $SESSIONTICKET);}
3279 elsif(-s "$SessionPath/$REMOTE_ADDR") {($sessiontype, $currentticket) = ("IPADDRESS", $REMOTE_ADDR);
3281 if($sessiontype)
3283 goto Login unless (-s "$SessionPath/$currentticket");
3284 my $ticket_valid = check_ticket_validity($sessiontype, "$SessionPath/$currentticket", $REMOTE_ADDR, $PATH_INFO);
3285 goto Login unless $ticket_valid;
3287 # Authorize
3288 my $TMPTICKET = authorize_login("$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $password, $SessionPath, $REMOTE_ADDR);
3289 goto Login unless $TMPTICKET;
3291 # Create a new user account
3292 CGIexecute::defineCGIvariable('NEWSESSION', "");
3293 my $newsession = ${"CGIexecute::NEWSESSION"};
3294 my $newaccount = create_newuser("$SessionPath/$LOGINTICKET", "$SessionPath/$currentticket",
3295 "$PasswordsPath/$userfile", $password, $newuser, $newpassword, $newsession);
3296 CGIexecute::defineCGIvariable('NEWACCOUNTTEXT', $newaccount);
3297 ${CGIexecute::NEWACCOUNTTEXT} = $newaccount;
3298 # NEWACCOUNTTEXT is NOT to be set by the query
3299 CGIexecute::ProtectCGIvariable('NEWACCOUNTTEXT');
3302 # Ready
3303 goto Return;
3305 # Is there a change password request?
3306 elsif($newpassword && $LOGINTICKET && $username)
3308 goto Login unless (-s "$SessionPath/$LOGINTICKET");
3309 goto Login unless (-s "$PasswordsPath/$userfile");
3310 my $ticket_valid = check_ticket_validity("PASSWORD", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3311 goto Login unless $ticket_valid;
3312 $ticket_valid = check_ticket_validity("LOGIN", "$SessionPath/$LOGINTICKET", $REMOTE_ADDR, ".", 1);
3313 goto Login unless $ticket_valid;
3315 my ($sessiontype, $currentticket) = ("", "");
3316 if($CHALLENGETICKET) {($sessiontype, $currentticket) = ("CHALLENGE", $CHALLENGETICKET);}
3317 elsif($SESSIONTICKET) {($sessiontype, $currentticket) = ("SESSION", $SESSIONTICKET);}
3318 elsif(-s "$SessionPath/$REMOTE_ADDR") {($sessiontype, $currentticket) = ("IPADDRESS", $REMOTE_ADDR);
3320 if($sessiontype)
3322 goto Login unless (-s "$SessionPath/$currentticket");
3323 my $ticket_valid = check_ticket_validity($sessiontype, "$SessionPath/$currentticket", $REMOTE_ADDR, $PATH_INFO);
3324 goto Login unless $ticket_valid;
3326 # Authorize
3327 change_password("$SessionPath/$LOGINTICKET", "$SessionPath/$currentticket", "$PasswordsPath/$userfile", $password, $newpassword);
3328 # After a change of password, you have to login again for a CHALLENGE
3329 if($CHALLENGETICKET){$CHALLENGETICKET = "";};
3330 # Ready
3331 goto Return;
3333 # Is there a login ticket of this name?
3334 elsif($LOGINTICKET)
3336 goto Login unless (-s "$SessionPath/$LOGINTICKET");
3337 goto Login unless (-s "$PasswordsPath/$userfile");
3338 my $ticket_valid = check_ticket_validity("PASSWORD", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3339 goto Login unless $ticket_valid;
3340 $ticket_valid = check_ticket_validity("LOGIN", "$SessionPath/$LOGINTICKET", $REMOTE_ADDR, ".");
3341 goto Login unless $ticket_valid;
3343 # Authorize
3344 my $TMPTICKET = authorize_login("$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $password, $SessionPath, $REMOTE_ADDR);
3345 if($TMPTICKET)
3347 my $authorization = read_ticket("$PasswordsPath/$userfile");
3348 goto Login unless $authorization;
3349 # Session type is read from the userfile
3350 if($authorization->{"Session"} && $authorization->{"Session"}->[0] eq "CHALLENGE")
3352 # Create New Random CHALLENGETICKET
3353 $CHALLENGETICKET = $TMPTICKET;
3354 create_session_file("$SessionPath/$CHALLENGETICKET", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
3356 elsif($authorization->{"Session"} && $authorization->{"Session"}->[0] eq "IPADDRESS")
3358 create_session_file("$SessionPath/$REMOTE_ADDR", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
3360 else
3362 # Extra hash to protect CHALLENGETICKET use
3363 $SESSIONTICKET = hash_string($TMPTICKET);
3364 $SESSIONTICKET = hash_string($SESSIONTICKET.$TMPTICKET);
3365 create_session_file("$SessionPath/$SESSIONTICKET", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
3366 $SETCOOKIELIST{"CGIscriptorSESSION"} = "-";
3367 $TMPTICKET = $SESSIONTICKET;
3370 # Login ticket file has been used, remove it
3371 unlink($loginfile);
3373 # Is there a session ticket of this name?
3374 # CHALLENGE
3375 if($CHALLENGETICKET)
3377 # Do not log into a CHALLENGE account if the SESSION cookie is present
3378 # Uncomment when $SESSIONTICKET does not receive an extra hash
3379 #goto Login if $SESSIONTICKET =~ /\S/;
3380 goto Login unless (-s "$SessionPath/$CHALLENGETICKET");
3381 my $ticket_valid = check_ticket_validity("CHALLENGE", "$SessionPath/$CHALLENGETICKET", $REMOTE_ADDR, $PATH_INFO);
3382 goto Login unless $ticket_valid;
3384 my $oldchallenge = read_ticket("$SessionPath/$CHALLENGETICKET");
3385 goto Login unless $oldchallenge;
3386 # Check whether the login still exists
3387 my $userfile = lc($oldchallenge->{"Username"}->[0]);
3388 $userfile =~ s/[^\w]/_/isg;
3389 goto Login unless (-s "$PasswordsPath/$userfile");
3391 $ticket_valid = check_ticket_validity("PASSWORD", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3392 goto Login unless $ticket_valid;
3394 # This is a LOGOUT request, clean up (Access has already been validated)
3395 if($LOGOUT)
3397 unlink "$SessionPath/$CHALLENGETICKET" if $CHALLENGETICKET && (-s "$SessionPath/$CHALLENGETICKET");
3398 $CHALLENGETICKET = "";
3399 goto Login;
3402 my $NEWCHALLENGETICKET = "";
3403 $NEWCHALLENGETICKET = copy_challenge_file("$SessionPath/$CHALLENGETICKET", "$PasswordsPath/$userfile", $SessionPath);
3404 # Sessionticket is available to scripts, do NOT set the cookie
3405 $ENV{'CHALLENGETICKET'} = $NEWCHALLENGETICKET;
3406 goto Return;
3408 # IPADDRESS
3409 elsif(-s "$SessionPath/$REMOTE_ADDR")
3411 my $ticket_valid = check_ticket_validity("IPADDRESS", "$SessionPath/$REMOTE_ADDR", $REMOTE_ADDR, $PATH_INFO);
3412 goto Login unless $ticket_valid;
3413 # Check whether the login still exists
3414 my $currentsessionticket = read_ticket("$SessionPath/$REMOTE_ADDR");
3415 my $userfile = lc($currentsessionticket->{"Username"}->[0]);
3416 $userfile =~ s/[^\w]/_/isg;
3417 goto Login unless (-s "$PasswordsPath/$userfile");
3419 $ticket_valid = check_ticket_validity("PASSWORD", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3420 goto Login unless $ticket_valid;
3422 # This is a LOGOUT request, clean up (Access has already been validated)
3423 if($LOGOUT)
3425 unlink "$SessionPath/$REMOTE_ADDR" if (-s "$SessionPath/$REMOTE_ADDR");
3426 goto Login;
3429 goto Return;
3431 # SESSION
3432 elsif($SESSIONTICKET)
3434 goto Login unless (-s "$SessionPath/$SESSIONTICKET");
3435 my $ticket_valid = check_ticket_validity("SESSION", "$SessionPath/$SESSIONTICKET", $REMOTE_ADDR, $PATH_INFO);
3436 goto Login unless $ticket_valid;
3438 # Check whether the login still exists
3439 my $currentsessionticket = read_ticket("$SessionPath/$SESSIONTICKET");
3440 my $userfile = lc($currentsessionticket->{"Username"}->[0]);
3441 $userfile =~ s/[^\w]/_/isg;
3442 goto Login unless (-s "$PasswordsPath/$userfile");
3444 $ticket_valid = check_ticket_validity("PASSWORD", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3445 goto Login unless $ticket_valid;
3447 # This is a LOGOUT request, clean up (Access has already been validated)
3448 if($LOGOUT)
3450 unlink "$SessionPath/$SESSIONTICKET" if $SESSIONTICKET && (-s "$SessionPath/$SESSIONTICKET");
3451 $SESSIONTICKET = "";
3452 goto Login;
3455 # Sessionticket is available to scripts
3456 $ENV{'SESSIONTICKET'} = $SESSIONTICKET;
3457 goto Return;
3460 goto Login;
3461 goto Return;
3464 Return:
3465 # The Masterkey should NOT be accessible by the parsed files
3466 $ENV{'CGIMasterKey'} = "" if $ENV{'CGIMasterKey'};
3467 return 0;
3469 Login:
3470 # To deter DOS attacks, do not remove valid session tickets unless the
3471 # "owner" has accredited herself
3472 my $tickets_removed = remove_expired_tickets($SessionPath);
3473 create_login_file($PasswordsPath, $SessionPath, $REMOTE_ADDR);
3474 # Note, cookies are set only ONCE
3475 $SETCOOKIELIST{"CGIscriptorLOGIN"} = "-";
3476 # The Masterkey should NOT be accessible by the parsed files
3477 $ENV{'CGIMasterKey'} = "" if $ENV{'CGIMasterKey'};
3478 return "$YOUR_HTML_FILES/$Login";
3481 sub authorize_login # ($loginfile, $authorizationfile, $password, $SessionPath, $IPaddress) => SESSIONTICKET First two arguments are file paths
3483 my $loginfile = shift || "";
3484 my $authorizationfile = shift || "";
3485 my $password = shift || "";
3486 my $SessionPath = shift || "";
3487 my $RemoteIPaddress = shift || "";
3489 # Get Login session ticket
3490 my $loginticket = read_ticket($loginfile);
3491 return 0 unless $loginticket;
3492 # Get User credentials for authorization
3493 my $authorization = read_ticket($authorizationfile);
3494 return 0 unless $authorization;
3496 # Get Randomsalt
3497 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
3498 return "" unless $Randomsalt;
3500 my $storedpassword = $authorization->{'Password'}->[0];
3501 return "" unless $storedpassword;
3502 my $Hashedpassword = hash_string($storedpassword.$RemoteIPaddress.$Randomsalt);
3503 return "" unless $password eq $Hashedpassword;
3505 # Extract Session Ticket
3506 my $loginsession = $loginticket->{'Session'}->[0];
3507 my $sessionticket = hash_string($storedpassword.$loginsession);
3508 chomp($sessionticket);
3509 $sessionticket = "" if -x "$SessionPath/$sessionticket";
3511 # No lingering password variables
3512 $Hashedpassword = $Randomsalt;
3513 $password = $Randomsalt;
3514 $authorization->{'Password'}->[0] = $Randomsalt;
3516 return $sessionticket;
3519 sub change_password # ($loginfile, $sessionfile, $authorizationfile, $password, $newpassword) First three arguments are file paths
3521 my $loginfile = shift || "";
3522 my $sessionfile = shift || "";
3523 my $authorizationfile = shift || "";
3524 my $password = shift || "";
3525 my $newpassword = shift || "";
3526 # Get Login session ticket
3527 my $loginticket = read_ticket($loginfile);
3528 return "" unless $loginticket;
3529 # Login ticket file has been used, remove it
3530 unlink($loginfile);
3531 # Get Randomsalt
3532 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
3533 return "" unless $Randomsalt;
3534 my $LoginID = $loginticket->{'Session'}->[0];
3535 return "" unless $LoginID;
3537 # Get session ticket
3538 my $sessionticket = read_ticket($sessionfile);
3539 return "" unless $sessionticket;
3541 # Get User credentials for authorization
3542 my $authorization = read_ticket($authorizationfile);
3543 return "" unless $authorization && lc($authorization->{'Username'}->[0]) eq lc($sessionticket->{'Username'}->[0]);
3545 my $storedpassword = $authorization->{'Password'}->[0];
3546 my $Hashedpassword = hash_string($storedpassword.$Randomsalt);
3547 return "" unless $password eq $Hashedpassword;
3548 my $secretkey = hash_string($storedpassword.$LoginID.$Randomsalt);
3550 # Decrypt the $newpassword
3551 my $decryptedPassword = XOR_hex_strings($secretkey, $newpassword);
3552 return "" unless $decryptedPassword;
3553 # Authorization succeeded, change password
3554 $authorization->{'Password'}->[0] = $decryptedPassword;
3555 # Write out
3556 write_ticket($authorizationfile, $authorization, $authorization->{'Salt'}->[0]);
3558 # No lingering password variables
3559 $decryptedPassword = $Randomsalt;
3560 $secretkey = $Randomsalt;
3561 $storedpassword = $Randomsalt;
3562 $Hashedpassword = $Randomsalt;
3563 $authorization->{'Password'}->[0] = $Randomsalt;
3565 return $newpassword;
3567 # First three arguments are file paths
3568 sub create_newuser # ($loginfile, $sessionfile, $authorizationfile, $password, $newuser, $newpassword, $newsession) -> account text
3570 my $loginfile = shift || "";
3571 my $sessionfile = shift || "";
3572 my $authorizationfile = shift || "";
3573 my $password = shift || "";
3574 my $newuser = shift || "";
3575 my $newpassword = shift || "";
3576 my $newsession = shift || "";
3578 # Get Login session ticket
3579 my $loginticket = read_ticket($loginfile);
3580 return "" unless $loginticket;
3581 # Login ticket file has been used, remove it
3582 unlink($loginfile);
3583 # Get Randomsalt
3584 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
3585 return "" unless $Randomsalt;
3586 my $LoginID = $loginticket->{'Session'}->[0];
3587 return "" unless $LoginID;
3589 # Get session ticket
3590 my $sessionticket = read_ticket($sessionfile);
3591 return "" unless $sessionticket;
3592 # Get User credentials for authorization
3593 my $authorization = read_ticket($authorizationfile);
3594 return "" unless $authorization && lc($authorization->{'Username'}->[0]) eq lc($sessionticket->{'Username'}->[0]);
3595 my $sessionkey = $sessionticket->{'Key'}->[0];
3596 my $serversalt = $authorization->{'Salt'}->[0];
3597 return "" unless $serversalt;
3599 my $storedpassword = $authorization->{'Password'}->[0];
3600 my $Hashedpassword = hash_string($storedpassword.$Randomsalt);
3601 return "" unless $password eq $Hashedpassword;
3602 my $secretkey = hash_string($storedpassword.$LoginID.$Randomsalt);
3604 # Decrypt the $newpassword
3605 my $decryptedPassword = XOR_hex_strings($secretkey, $newpassword);
3606 return "" unless $decryptedPassword;
3608 # Authorization succeeded, create new account
3609 my $newaccount = {};
3610 $newaccount->{'Type'} = ['PASSWORD'];
3611 $newaccount->{'Username'} = [$newuser];
3612 $newaccount->{'Password'} = [$decryptedPassword];
3613 $newaccount->{'Salt'} = [$serversalt];
3614 $newaccount->{'Session'} = ['SESSION'];
3615 if($newsession eq 'IPADDRESS'){$newaccount->{'Session'} = ['IPADDRESS'];};
3616 if($newsession eq 'CHALLENGE'){$newaccount->{'Session'} = ['CHALLENGE'];};
3617 my $timesec = time();
3618 my $gmt_date = gmtime();
3619 $newaccount->{'Time'} = [$timesec];
3620 $newaccount->{'Date'} = [$gmt_date];
3622 # AllowedPaths
3623 my $NewAllowedPaths = "";
3624 my $PATH_INFO = $ENV{'CGI_BINARY_FILE'} ? $ENV{'CGI_BINARY_FILE'} : $ENV{'PATH_INFO'};
3625 my $currentRoot = "";
3626 $currentRoot = $1 if $PATH_INFO =~ m!^([\w\-\. /]+)!isg;
3627 $currentRoot =~ s![^/]+$!!isg;
3628 if($currentRoot)
3630 $currentRoot .= '/' unless $currentRoot =~ m!/$!;
3631 my $newpath = "^".${currentRoot}.'[\w\-]+\.html?';
3632 $NewAllowedPaths .= 'AllowedPaths: ^'.${currentRoot}.'[\w\-]+\.html?'."\n";
3633 $newaccount->{'AllowedPaths'} = [$newpath];
3635 else
3637 # Tricky PATH_INFO, deny all
3638 $NewAllowedPaths .= "DeniedPaths: ^/\n";
3639 $newaccount->{'DeniedPaths'} = ["DeniedPaths: ^/\n"];
3642 # Construct home directory path
3643 my $FullHomeDirectoryPath = "";
3644 my $currentHome = lc($newuser);
3645 if($currentHome && $currentHome !~ /^\s*\#/)
3647 $currentHome =~ s![^\w]!_!isg;
3648 my $newpath = "^${currentRoot}$currentHome/";
3649 push(@{$newaccount->{'AllowedPaths'}}, $newpath);
3650 # Create home directory
3651 $FullHomeDirectoryPath = $ENV{'HOME'}.${currentRoot}.$currentHome;
3654 # Allowed Paths
3655 CGIexecute::defineCGIvariable('ALLOWEDPATHS', "");
3656 my $allowedpaths = ${"CGIexecute::ALLOWEDPATHS"};
3657 if($allowedpaths && $allowedpaths !~ /^\s*\#/)
3659 $allowedpaths =~ s!\#.*$!!isg;
3660 $allowedpaths =~ s![^\^\w\./\;\+\*\?\[\]\$]!!isg;
3661 my @pathlist = split(/\;/, $allowedpaths);
3662 foreach my $entry (@pathlist)
3664 push(@{$newaccount->{'AllowedPaths'}}, "^".${currentRoot}.$entry);
3668 # Allowed IP addresses
3669 CGIexecute::defineCGIvariable('IPADDRESS', "");
3670 my $ipaddress = ${"CGIexecute::IPADDRESS"};
3671 if($ipaddress && $ipaddress !~ /^\s*\#/)
3673 $ipaddress =~ s!\#.*$!!isg;
3674 $ipaddress =~ s![^\d\.\;]!!isg;
3675 my @iplist = split(/\;/, $ipaddress);
3676 foreach my $entry (@iplist)
3678 next unless $entry =~ /\d/;
3679 next if $entry =~ /^\s*\#/;
3680 $entry =~ s/\./\\./g;
3681 push(@{$newaccount->{'IPaddress'}}, $entry);
3685 # Capabilities
3686 CGIexecute::defineCGIvariable('NEWCAPABILITIES', "");
3687 my $capabilities = ${"CGIexecute::NEWCAPABILITIES"};
3688 if($capabilities && $capabilities !~ /^\W*\#/)
3690 $capabilities =~ s!\#.*$!!isg;
3691 $capabilities =~ s![^\w\s]!!isg;
3692 my @caplist = split(/\s/, $capabilities);
3693 foreach my $entry (@caplist)
3695 next unless $entry =~ /\w/;
3696 next if $entry =~ /^\s*\#/;
3697 push(@{$newaccount->{'Capabilities'}}, $entry);
3701 # Sign the new ticket
3702 my $Signature = SignTicketWithMasterkey($newaccount, $newaccount->{'Salt'}->[0]);
3704 # Write
3705 my $datetime = gmtime();
3706 my $newuserfile = "";
3707 if(grep(/^CreateUser$/, @{$authorization->{'Capabilities'}}))
3709 my $newuserfilename = lc($newuser);
3710 $newuserfilename =~ s/[^\w]/_/isg;
3711 $newuserfile = $authorizationfile;
3712 $newuserfile =~ s![^/]*$!!isg;
3713 $newuserfile .= $newuserfilename;
3714 if(-s $newuserfile)
3716 $newuserfile = "";
3718 elsif($FullHomeDirectoryPath && !(-d $FullHomeDirectoryPath || -s $FullHomeDirectoryPath))
3720 if(-d "$ENV{'HOME'}${currentRoot}.SkeletonDir")
3722 `cp -r '$ENV{'HOME'}${currentRoot}.SkeletonDir' '$FullHomeDirectoryPath'`;
3724 elsif(-d "$ENV{'HOME'}${currentRoot}SkeletonDir")
3726 `cp -r '$ENV{'HOME'}${currentRoot}SkeletonDir' '$FullHomeDirectoryPath'`;
3728 elsif(-s "$ENV{'HOME'}${currentRoot}UserIndex.html")
3730 mkdir $FullHomeDirectoryPath;
3731 `cp '$ENV{'HOME'}${currentRoot}UserIndex.html' '$FullHomeDirectoryPath/index.html'`;
3733 elsif(-s "$ENV{'HOME'}${currentRoot}index.html")
3735 mkdir $FullHomeDirectoryPath;
3736 `cp '$ENV{'HOME'}${currentRoot}index.html' '$FullHomeDirectoryPath/index.html'`;
3742 my $newaccounttext = write_ticket($newuserfile, $newaccount, $serversalt);
3744 # Re-encrypt the new password for transmission
3745 if($newaccounttext =~ /^(Password\:\s+)(\S+)\s*$/)
3747 my $passwordvalue = $1;
3748 my $reencryptedpassword = XOR_hex_strings($secretkey, $passwordvalue);
3749 my $encryptedpasswordline = "<span id='newaccount'>$reencryptedpassword</span>";
3750 $newaccounttext =~ s/^(Password\:\s+)(\S+)\s*$/\1$encryptedpasswordline/gim;
3752 # No lingering passwords
3753 $passwordvalue = $serversalt;
3755 return $newaccounttext;
3758 # Copy a Challenge ticket file to a new name which is the hash of the new $CHALLENGETICKET and the password
3759 sub copy_challenge_file #($oldchallengefile, $authorizationfile, $sessionpath) -> $CHALLENGETICKET
3761 my $oldchallengefile = shift || "";
3762 my $authorizationfile = shift || "";
3763 my $sessionpath = shift || "";
3764 $sessionpath =~ s!/+$!!g;
3766 # Get Login session ticket
3767 my $oldchallenge = read_ticket($oldchallengefile);
3768 return "" unless $oldchallenge;
3770 # Get Authorization (user) session file
3771 my $authorization = read_ticket($authorizationfile);
3772 return "" unless $authorization;
3773 my $storedpassword = $authorization->{'Password'}->[0];
3774 return "" unless $storedpassword;
3775 my $challengekey = $oldchallenge->{'Key'}->[0];
3776 return "" unless $challengekey;
3778 # Create Random Hash Salt
3779 my $NEWCHALLENGETICKET = get_random_hex();;
3780 my $newchallengefile = hash_string($challengekey.$NEWCHALLENGETICKET);
3781 return "" unless $newchallengefile;
3783 $ENV{'CHALLENGETICKET'} = $NEWCHALLENGETICKET;
3784 CGIexecute::defineCGIvariable('CHALLENGETICKET', "");
3785 ${"CGIexecute::CHALLENGETICKET"} = $NEWCHALLENGETICKET;
3787 # Write Session Ticket
3788 open(OLDCHALLENGE, "<$oldchallengefile") || die "<$oldchallengefile: $!\n";
3789 my @OldChallengeLines = <OLDCHALLENGE>;
3790 close(OLDCHALLENGE);
3791 # Old file should now be removed
3792 unlink($oldchallengefile);
3794 open(SESSION, ">$sessionpath/$newchallengefile") || die "$sessionpath/$newchallengefile: $!\n";
3795 foreach $line (@OldChallengeLines)
3797 print SESSION $line;
3799 close(SESSION);
3801 # No lingering passwords
3802 $storedpassword = $oldchallenge;
3804 return $NEWCHALLENGETICKET;
3807 sub create_login_file #($PasswordDir, $SessionDir, $IPaddress)
3809 my $PasswordDir = shift || "";
3810 my $SessionDir = shift || "";
3811 my $IPaddress = shift || "";
3813 # Create Login Ticket
3814 my $LOGINTICKET= get_random_hex ();
3816 # Create Random Hash Salt
3817 my $RANDOMSALT= get_random_hex();
3819 # Create SALT file if it does not exist
3820 # Remove this, including test account for life system
3821 unless(-d "$SessionDir")
3823 `mkdir -p "$SessionDir"`;
3825 unless(-d "$PasswordDir")
3827 `mkdir -p "$PasswordDir"`;
3829 # Create SERVERSALT and default test account
3830 my $SERVERSALT = "";
3831 unless(-s "$PasswordDir/SALT")
3833 $SERVERSALT= get_random_hex();
3834 open(SALTFILE, ">$PasswordDir/SALT") || die ">$PasswordDir/SALT: $!\n";
3835 print SALTFILE "$SERVERSALT\n";
3836 close(SALTFILE);
3838 # Update test account (should be removed in live system)
3839 my @alltestusers = ("test", "testip", "testchallenge", "admin");
3840 foreach my $testuser (@alltestusers)
3842 if(-s "$PasswordDir/$testuser")
3844 my $plainpassword = $testuser eq 'admin' ? "There is no password like more password" : "testing";
3846 my $storedpassword = hash_string(${plainpassword}.${testuser}.${SERVERSALT});
3847 # Encrypt the new password with the MasterKey
3848 my $authorization = read_ticket("$PasswordDir/$testuser") || return "";
3849 $authorization->{'Salt'} = [$SERVERSALT];
3850 $authorization->{'Type'} = ['INACTIVE PASSWORD'] if $testuser eq 'admin';
3851 set_password($authorization, $SERVERSALT, $plainpassword);
3852 write_ticket("$PasswordDir/$testuser", $authorization, $SERVERSALT);
3853 # No lingering passwords
3854 $storedpassword = $SERVERSALT;
3855 $plainpassword = $SERVERSALT;
3860 # Read in site Salt
3861 open(SALTFILE, "<$PasswordDir/SALT") || die "$PasswordDir/SALT: $!\n";
3862 $SERVERSALT=<SALTFILE>;
3863 close(SALTFILE);
3864 chomp($SERVERSALT);
3866 # Create login session ticket
3867 my $datetime = gmtime();
3868 my $timesec = time();
3869 my $loginticket = {};
3870 $loginticket->{Type} = ['LOGIN'];
3871 $loginticket->{IPaddress} = [$IPaddress];
3872 $loginticket->{Salt} = [$SERVERSALT];
3873 $loginticket->{Session} = [$LOGINTICKET];
3874 $loginticket->{Randomsalt} = [$RANDOMSALT];
3875 $loginticket->{Expires} = ['+600s'];
3876 $loginticket->{Date} = ["$datetime UTC"];
3877 $loginticket->{Time} = [$timesec];
3878 write_ticket("$SessionDir/$LOGINTICKET", $loginticket, $SERVERSALT);
3880 # Set global variables
3881 # $SERVERSALT
3882 $ENV{'SERVERSALT'} = $SERVERSALT;
3883 CGIexecute::defineCGIvariable('SERVERSALT', "");
3884 ${"CGIexecute::SERVERSALT"} = $SERVERSALT;
3886 # $SESSIONTICKET
3887 $ENV{'SESSIONTICKET'} = $SESSIONTICKET;
3888 CGIexecute::defineCGIvariable('SESSIONTICKET', "");
3889 ${"CGIexecute::SESSIONTICKET"} = $SESSIONTICKET;
3891 # $RANDOMSALT
3892 $ENV{'RANDOMSALT'} = $RANDOMSALT;
3893 CGIexecute::defineCGIvariable('RANDOMSALT', "");
3894 ${"CGIexecute::RANDOMSALT"} = $RANDOMSALT;
3896 # $LOGINTICKET
3897 $ENV{'LOGINTICKET'} = $LOGINTICKET;
3898 CGIexecute::defineCGIvariable('LOGINTICKET', "");
3899 ${"CGIexecute::LOGINTICKET"} = $LOGINTICKET;
3901 return $ENV{'LOGINTICKET'};
3904 sub create_session_file #($sessionfile, $loginfile, $authorizationfile, $path) -> Is $loginfile deleted? 0/1
3906 my $sessionfile = shift || "";
3907 my $loginfile = shift || "";
3908 my $authorizationfile = shift || "";
3909 my $path = shift || "";
3911 # Get Login session ticket
3912 my $loginticket = read_ticket($loginfile);
3913 return unlink($loginfile) unless $loginticket;
3915 # Get Authorization (user) session file
3916 my $authorization = read_ticket($authorizationfile);
3917 return unlink($loginfile) unless $authorization;
3919 # For a Session or a Challenge, we need a stored key
3920 my $sessionkey = "";
3921 my $secretkey = "";
3922 if($authorization->{'Session'} && $authorization->{'Session'}->[0] ne 'IPADDRESS')
3924 my $storedpassword = $authorization->{'Password'}->[0];
3925 my $loginticketid = $loginticket->{'Session'}->[0];
3926 my $randomsalt = $loginticket->{'Randomsalt'}->[0];
3927 $sessionkey = hash_string($storedpassword.$loginticketid);
3928 $secretkey = hash_string($storedpassword.$loginticketid.$randomsalt);
3929 # No lingering passwords
3930 $storedpassword = $loginticketid;
3932 # Get Session id
3933 my $sessionid = "";
3934 if($sessionfile =~ m!([^/]+)$!)
3936 $sessionid = $1;
3939 # Convert Authorization content to Session content
3940 my $sessionContent = {};
3941 my $SessionType = $authorization->{'Session'}->[0] ? $authorization->{'Session'}->[0] : "SESSION";
3942 $sessionContent->{Type} = [$SessionType];
3943 $sessionContent->{Username} = [lc($authorization->{'Username'}->[0])];
3944 $sessionContent->{Session} = [$sessionid];
3945 $sessionContent->{Time} = [time];
3946 # Limit communication to the login IP address, except for Tor like situations with VariableREMOTE_ADDR
3947 $sessionContent->{IPaddress} = ['.'];
3948 if($sessionContent->{Type}->[0] eq 'CHALLENGE' && grep(/^VariableREMOTE_ADDR$/, @{$authorization->{'Capabilities'}}))
3950 $sessionContent->{IPaddress} = $authorization->{'IPaddress'} if $authorization->{'IPaddress'};
3952 else
3954 $sessionContent->{IPaddress} = $loginticket->{'IPaddress'};
3956 $sessionContent->{Salt} = $authorization->{'Salt'};
3957 $sessionContent->{Randomsalt} = $loginticket->{'Randomsalt'};
3958 $sessionContent->{AllowedPaths} = $authorization->{'AllowedPaths'};
3959 $sessionContent->{DeniedPaths} = $authorization->{'DeniedPaths'};
3960 $sessionContent->{Expires} = $authorization->{'MaxLifetime'};
3961 $sessionContent->{Capabilities} = $authorization->{'Capabilities'};
3962 foreach my $pattern (keys(%TicketRequiredPatterns))
3964 if($path =~ m#$pattern#)
3966 my ($SessionPath, $PasswordsPath, $Login, $validtime) = split(/\t/, $TicketRequiredPatterns{$pattern});
3967 push(@{$sessionContent->{Expires}}, $validtime);
3970 $sessionContent->{Key} = [$sessionkey] if $sessionkey;
3971 $sessionContent->{Secretkey} = [$secretkey] if $secretkey;
3972 $sessionContent->{Date} = [gmtime()." UTC"];
3974 # Write Session Ticket
3975 write_ticket($sessionfile, $sessionContent, $authorization->{'Salt'}->[0]);
3977 # Login file should now be removed
3978 return unlink($loginfile);
3981 sub check_ticket_validity # ($type, $ticketfile, $address, $path [, $unsigned])
3983 my $type = shift || "SESSION";
3984 my $ticketfile = shift || "";
3985 my $address = shift || "";
3986 my $path = shift || "";
3987 my $unsigned = shift || 0;
3989 # Is there a session ticket of this name?
3990 return 0 unless -s "$ticketfile";
3992 # There is a session ticket, is it linked to this IP address?
3993 my $ticket = read_ticket($ticketfile);
3994 unless($ticket)
3996 print STDERR "Ticket expired or empty: $ticketfile\n";
3997 return;
4000 # Is this the right type of ticket
4001 unless($ticket && $ticket->{'Type'}->[0] eq $type)
4003 print STDERR "Wrong ticket type: $ticket->{'Type'}->[0] eq $type\n";
4004 return;
4007 # Does the IP address match?
4008 my $IPmatches = @{$ticket->{"IPaddress"}} ? 0 : 1;
4009 for $IPpattern (@{$ticket->{"IPaddress"}})
4011 ++$IPmatches if $address =~ m#^$IPpattern#ig;
4013 if($address && ! $IPmatches)
4015 print STDERR "Wrong REMOTE ADDR for $ticket->{'Username'}->[0]: $ticket->{'IPaddress'}->[0] vs $address\n";
4016 return 0;
4019 # Is the path denied
4020 my $Pathmatches = 0;
4021 foreach $Pathpattern (@{$ticket->{"DeniedPaths"}})
4023 ++$Pathmatches if $path =~ m#$Pathpattern#ig;
4025 return 0 if @{$ticket->{"DeniedPaths"}} && $Pathmatches;
4027 # Is the path allowed
4028 $Pathmatches = 0;
4029 foreach $Pathpattern (@{$ticket->{"AllowedPaths"}})
4031 ++$Pathmatches if $path =~ m#$Pathpattern#ig;
4033 return 0 unless !@{$ticket->{"AllowedPaths"}} || $Pathmatches;
4035 # Check signature if not told to use an unsigned ticket (dangerous)
4036 my $Signature = TicketSignature($ticket, $ticket->{'Salt'}->[0]);
4037 if((! $unsigned) && $Signature && $Signature ne $ticket->{'Signature'}->[0])
4039 print STDERR "Invalid signature for $ticket->{'Type'}: $ticket->{'Username'}\n$ticketfile\n";
4040 return 0;
4043 # Make login values available (will also protect against resetting by query)
4044 $ENV{"LOGINUSERNAME"} = lc($ticket->{'Username'}->[0]);
4045 $ENV{"LOGINIPADDRESS"} = $address;
4046 $ENV{"LOGINPATH"} = $path;
4047 $ENV{"SESSIONTYPE"} = $type unless $type eq "PASSWORD";
4049 # Set Capabilities, if present
4050 if($ticket->{'Username'}->[0] && @{$ticket->{'Capabilities'}})
4052 $ENV{'CAPABILITIES'} = $ticket->{'Username'}->[0];
4053 CGIexecute::defineCGIvariableList('CAPABILITIES', "");
4054 @{"CGIexecute::CAPABILITIES"} = @{$ticket->{'Capabilities'}};
4055 # Capabilities should not be changed anymore by CGI query!
4057 # Capabilities are NOT to be set by the query
4058 CGIexecute::ProtectCGIvariable('CAPABILITIES');
4060 return 1;
4064 # This might be run in a fork()?
4065 sub remove_expired_tickets # ($path) -> number of tickets removed
4067 my $path = shift || "";
4068 return 0 unless $path;
4069 $path =~ s!/+$!!g;
4070 my $removed_tickets = 0;
4071 my @ticketlist = glob("$path/*");
4072 foreach my $ticketfile (@ticketlist)
4074 my $ticket = read_ticket($ticketfile);
4075 unless($ticket)
4077 unlink $ticketfile;
4078 ++$removed_tickets;
4081 return $removed_tickets;
4084 sub set_password # ($ticket, $salt, $plainpassword) -> $password
4086 my $ticket = shift || "";
4087 my $salt = shift || "";
4088 my $plainpassword = shift || "";
4090 my $user = lc($ticket->{'Username'}->[0]);
4091 return "" unless $user;
4092 $salt = $ticket->{'Salt'}->[0] unless $salt;
4094 my $storedpassword = hash_string(${plainpassword}.${user}.${salt});
4095 $ticket->{'Password'} = [$storedpassword];
4096 $ticket->{'Salt'} = [$salt];
4097 # No lingering passwords
4098 $storedpassword = $salt;
4099 $plainpassword = $salt;
4101 return $ticket->{'Password'}->[0];
4104 sub write_ticket # ($ticketfile, $ticket, $salt [, $masterkey]) -> &%ticket
4106 my $ticketfile = shift || "";
4107 my $ticket = shift || "";
4108 my $salt = shift || "";
4109 my $masterkey = shift || $ENV{'CGIMasterKey'};
4111 # Encrypt password
4112 EncryptTicketWithMasterKey($ticket, $salt, $masterkey);
4114 # Sign the new ticket
4115 my $signature = SignTicketWithMasterkey($ticket, $salt, $masterkey);
4117 # Create ordered list with labels
4118 my @orderlist = ('Type', 'Username', 'Password', 'IPaddress', 'AllowedPaths', 'DeniedPaths',
4119 'Expires', 'Capabilities', 'Salt', 'Session', 'Randomsalt',
4120 'Date', 'Time', 'Signature', 'Key', 'Secretkey');
4121 my @labellist = keys(%{$ticket});
4122 foreach my $label (@orderlist)
4124 @labellist = grep(!/\b$label\b/, @labellist);
4127 # Create ticket in text
4128 my $TicketText = "";
4129 foreach my $label (@orderlist, @labellist)
4131 next unless exists($ticket->{$label}) && $ticket->{$label}->[0];
4132 foreach my $value (@{$ticket->{$label}})
4134 $TicketText .= "$label: $value\n";
4137 if($ticketfile)
4139 open(TICKET, ">$ticketfile") || die "$ticketfile: $!\n";
4140 print TICKET $TicketText;
4141 close(TICKET);
4144 return $TicketText;
4147 # Note, read_ticket will return 0 if the ticket has expired!
4148 sub read_ticket # ($ticketfile [, $salt, $masterkey]) -> &%ticket
4150 my $ticketfile = shift || "";
4151 my $serversalt = shift || "";
4152 my $masterkey = shift || $ENV{'CGIMasterKey'};
4154 my $ticket = {};
4155 if($ticketfile && -s $ticketfile)
4157 open(TICKETFILE, "<$ticketfile") || die "$ticketfile: $!\n";
4158 my @alllines = <TICKETFILE>;
4159 close(TICKETFILE);
4160 foreach my $currentline (@alllines)
4162 # Skip empty lines and comments
4163 next unless $currentline =~ /\S/;
4164 next if $currentline =~ /^\s*\#/;
4166 if($currentline =~ /^\s*(\S[^\:]+)\:\s+(.*)\s*$/)
4168 my $Label = $1;
4169 my $Value = $2;
4170 $ticket->{$Label} = () unless exists($ticket->{$Label});
4171 push(@{$ticket->{$Label}}, $Value);
4175 elsif(-z $ticketfile)
4177 return 0;
4179 if($masterkey && exists($ticket->{'Password'}) && $ticket->{'Password'}->[0])
4181 # Use the ServerSalt stored in the ticket, if present
4182 if(!$serversalt && exists($ticket->{Salt}) && $ticket->{Salt}->[0])
4184 $serversalt = $ticket->{Salt}->[0];
4186 # Decrypt all passwords
4187 DecryptTicketWithMasterKey($ticket, $serversalt, $masterkey) ||
4188 die "Decryption failed: DecryptTicketWithMasterKey ($ticket, $serversalt)\n";
4191 # Check whether the ticket has expired
4192 if(exists($ticket->{Expires}))
4194 my $StartTime = 0;
4195 if(exists($ticket->{Time}) && $ticket->{Time}->[0] > 0)
4197 $StartTime = [(sort(@{$ticket->{Time}}))]->[0];
4199 else
4201 # Get SessionTicket file stats
4202 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)
4203 = stat($ticketfile);
4204 $StartTime = $ctime;
4206 foreach my $Value (@{$ticket->{'Expires'}})
4208 # Recalculate expire date from relative time
4209 if($Value =~ /^\+/)
4211 if($Value =~ /^\+(\d+)\s*d(ays)?\s*$/)
4213 $ExpireTime = 24*3600*$1;
4215 elsif($Value =~ /^\+(\d+)\s*m(inutes)?\s*$/)
4217 $ExpireTime = 60*$1;
4219 elsif($Value =~ /^\+(\d+)\s*h(ours)?\s*$/)
4221 $ExpireTime = 3600*$1;
4223 elsif($Value =~ /^\+(\d+)\s*s(econds)?\s*$/)
4225 $ExpireTime = $1;
4227 elsif($Value =~ /^\+(\d+)\s*$/)
4229 $ExpireTime = $1;
4232 my $absoluteTime = $Value =~ /^\+/ ? $StartTime + $ExpireTime : $Value;
4233 return 0 unless $absoluteTime > time;
4235 @{$ticket->{Expires}} = sort(@{$ticket->{Expires}});
4237 return $ticket;
4240 # Set up a valid ticket from a given text file
4241 # Use from command line. DO NOT USE ONLINE
4242 # Watch out for passwords that get stored in the history file
4244 # perl CGIscriptor.pl --managelogin [options] [files]
4245 # Options:
4246 # salt={file or saltvalue}
4247 # masterkey={file or plaintext}
4248 # newmasterkey={file or plaintext}
4249 # password={file or palintext}
4251 # Followed by one or more file names.
4252 # Options can be interspersed between filenames,
4253 # e.g., password='plaintext'
4254 # Note that passwords are only used once!
4256 sub setup_ticket_file # (@ARGV)
4258 # Stop when run on-line
4259 return if $ENV{'PATH_INFO'} || $ENV{'QUERY_STRING'};
4261 my %Settings = ();
4262 foreach my $input (@_)
4264 if($input =~ /^([\w]+)\=/)
4266 my $name = lc($1);
4267 my $value = $';
4268 chomp($value);
4270 if($value !~ m![^\w\.\~\/\:\-]! && $value !~ /^[\-\.]/ && -s "$value" && ! -d "$value")
4272 # Warn about reading a value from file
4273 print STDERR "Read '$name' from: '$value'\n";
4274 open(INPUTVALUE, "<$value") || die "$value: $!\n";
4275 $value = <INPUTVALUE>;
4276 chomp($value);
4279 $value =~ s/(^\'([^\']*)\'$)/\1/g;
4280 $value =~ s/(^\"([^\"]*)\"$)/\1/g;
4281 $Settings{$name} = $value;
4283 elsif($input !~ m![^\w\.\~\/\:\-]!i && $input !~ /^[\-\.]/i && -s $input)
4285 # We MUST have a salt
4286 $Settings{'salt'} = $ticket->{'Salt'}->[0] unless $Settings{'salt'};
4288 # Set the new masterkey to the old masterkey if there is no new masterkey
4289 $Settings{'newmasterkey'} = $Settings{'masterkey'} unless exists($Settings{'newmasterkey'});
4291 # Get the ticket
4292 my $ticket = read_ticket($input, $Settings{'salt'}, $Settings{'masterkey'});
4294 # Set a new password from plaintext
4295 $ticket->{'Salt'}->[0] = $Settings{'salt'} if $Settings{'salt'} && $Settings{'password'};
4296 set_password ($ticket, $Settings{'salt'}, $Settings{'password'}) if $Settings{'password'};
4297 # Write the ticket back to file
4298 write_ticket($input, $ticket, $Settings{'salt'}, $Settings{'newmasterkey'});
4300 # A password is only used once
4301 $Settings{'password'} = "";
4306 # Add a signature from $masterkey to a ticket in the label $signlabel
4307 sub SignTicketWithMasterkey # ($ticket, $serversalt [, $masterkey, $signlabel]) -> $Signature
4309 my $ticket = shift || return 0;
4310 my $serversalt = shift || "";
4311 my $masterkey = shift || $ENV{'CGIMasterKey'};
4312 my $signlabel = shift || 'Signature';
4314 my $Signature = TicketSignature($ticket, $serversalt, $masterkey);
4316 $ticket->{$signlabel} = [$Signature] if $Signature;
4318 return $Signature;
4321 # Determine ticket signature
4322 sub TicketSignature # ($ticket, $serversalt [, $masterkey]) -> $Signature
4324 my $ticket = shift || return 0;
4325 my $serversalt = shift || "";
4326 my $masterkey = shift || $ENV{'CGIMasterKey'};
4327 my $Signature = "";
4329 if($masterkey)
4331 # If the ServerSalt is not stored in the ticket, the SALT file has to be found
4332 if(!$serversalt && exists($ticket->{Salt}) && $ticket->{Salt}->[0])
4334 $serversalt = $ticket->{Salt}->[0];
4336 # Sign
4337 if($serversalt)
4339 my $username = lc($ticket->{'Username'}->[0]);
4340 my $hash1 = hash_string(${masterkey}.${serversalt});
4341 # The order of $username.$hash1 should be different than in DecryptTicketWithMasterKey
4342 my $CryptKey = hash_string($username.${'hash1'});
4343 my $SignText = "Type: ".$ticket->{'Type'}->[0]."\n";
4344 my @tmp = sort(@{$ticket->{'Username'}});
4345 $SignText .= "Username: @tmp\n";
4346 @tmp = sort(@{$ticket->{'IPaddress'}});
4347 $SignText .= "IPaddress: @tmp\n";
4348 @tmp = sort(@{$ticket->{'AllowedPaths'}});
4349 $SignText .= "AllowedPaths: @tmp\n";
4350 @tmp = sort(@{$ticket->{'DeniedPaths'}});
4351 $SignText .= "DeniedPaths: @tmp\n";
4352 @tmp = sort(@{$ticket->{'Session'}});
4353 $SignText .= "Session: @tmp\n";
4354 @tmp = sort(@{$ticket->{'Time'}});
4355 $SignText .= "Time: @tmp\n";
4356 @tmp = sort(@{$ticket->{'Expires'}});
4357 $SignText .= "Expires: @tmp\n";
4358 @tmp = sort(@{$ticket->{'Capabilities'}});
4359 $SignText .= "Capabilities: @tmp\n";
4360 @tmp = sort(@{$ticket->{'MaxLifetime'}});
4361 $SignText .= "MaxLifetime: @tmp\n";
4362 $Signature = HMAC_hex($CryptKey, $SignText);
4365 return $Signature;
4368 # Decrypts a password list IN PLACE
4369 sub DecryptTicketWithMasterKey # ($ticket, $serversalt [, $masterkey]) -> \@password_list
4371 my $ticket = shift || return 0;
4372 my $serversalt = shift || "";
4373 my $masterkey = shift || $ENV{'CGIMasterKey'};
4375 if($masterkey && exists($ticket->{Password}) && $ticket->{Password}->[0])
4377 # If the ServerSalt is not given, read it from the the ticket
4378 if(! $serversalt && exists($ticket->{Salt}) && $ticket->{Salt}->[0])
4380 $serversalt = $ticket->{Salt}->[0];
4382 # Decrypt password(s)
4383 if($serversalt)
4385 my $hash1 = hash_string(${masterkey}.${serversalt});
4386 my $username = lc($ticket->{'Username'}->[0]);
4387 # The order of $hash1.$username should be different than in TicketSignature
4388 my $CryptKey = hash_string(${'hash1'}.$username);
4389 foreach my $password (@{$ticket->{Password}})
4391 $password = XOR_hex_strings($CryptKey,$password);
4395 return $ticket->{'Password'};
4397 sub EncryptTicketWithMasterKey # ($ticket, $serversalt [, $masterkey]) -> \@password_list
4399 DecryptTicketWithMasterKey(@_);
4402 # Implement HMAC signature hash.
4403 # Blocksize is length in HEX characters, NOT bytes
4404 sub HMAC_hex # ($key, $message [, $blocksizehex]) -> $hex
4406 my $key = shift || "";
4407 my $message = shift || "";
4408 my $blocksizehex = shift || length($key);
4409 $key = hash_string($key) if length($key) > $blocksizehex;
4411 my $innerkey = XOR_hex_byte ($key, "36");
4412 my $outerkey = XOR_hex_byte ($key, "5c");
4413 my $innerhash = hash_string($innerkey.$message);
4414 my $outerhash = hash_string($outerkey.$innerhash);
4416 return $outerhash;
4419 # XOR input with equally long string of repeated 2 hex character (byte)
4420 # string. Input must have even number of hex characters
4421 sub XOR_hex_byte # ($hex1, $hexbyte) -> $hex
4423 my $hex1 = shift || "";
4424 my $hexbyte = shift || "";
4425 my $bytelength = length($hexbyte);
4426 my $hex2 = $hex1;
4427 $hex2 =~ s/.{$bytelength}/$hexbyte/ig;
4428 return XOR_hex_strings($hex1, $hex2);
4431 sub XOR_hex_strings # ($hex1, $hex2) -> $hex
4433 my $hex1 = shift || "";
4434 my $hex2 = shift || "";
4435 my @hex1list = split('', $hex1);
4436 my @hex2list = split('', $hex2);
4437 my @hexresultlist = ();
4438 for(my $i; $i < scalar(@hex1list); ++$i)
4440 my $d1 = hex($hex1list[$i]);
4441 my $d2 = hex($hex2list[$i]);
4442 my $dresult = ($d1 ^ $d2);
4443 $hexresultlist[$i] = sprintf("%x", $dresult);
4445 $hexresult = join('', @hexresultlist);
4446 return $hexresult;
4449 # End of Handle login access
4452 ############################################################################
4454 # Handle foreign interpreters (i.e., scripting languages)
4456 # Insert perl code to execute scripts in foreign scripting languages.
4457 # Actually, the scripts inside the <SCRIPT></SCRIPT> blocks are piped
4458 # into an interpreter.
4459 # The code presented here is fairly confusing because it
4460 # actually writes perl code code to the output.
4462 # A table with the file handles
4463 %SCRIPTINGINPUT = ();
4465 # A function to clean up Client delivered CGI parameter values
4466 # (i.e., quote all odd characters)
4467 %SHRUBcharacterTR =
4469 "\'" => '&#39;',
4470 "\`" => '&#96;',
4471 "\"" => '&quot;',
4472 '&' => '&amper;',
4473 "\\" => '&#92;'
4476 sub shrubCGIparameter # ($String) -> Cleaned string
4478 my $String = shift || "";
4480 # Change all quotes [`'"] into HTML character entities
4481 my ($Char, $Transcript) = ('&', $SHRUBcharacterTR{'&'});
4483 # Protect &
4484 $String =~ s/\Q$Char\E/$Transcript/isg if $Transcript;
4486 while( ($Char, $Transcript) = each %SHRUBcharacterTR)
4488 next if $Char eq '&';
4489 $String =~ s/\Q$Char\E/$Transcript/isg;
4492 # Replace newlines
4493 $String =~ s/[\n]/\\n/g;
4494 # Replace control characters with their backslashed octal ordinal numbers
4495 $String =~ s/([^\S \t])/(sprintf("\\0%o", ord($1)))/eisg; #
4496 $String =~ s/([\x00-\x08\x0A-\x1F])/(sprintf("\\0%o", ord($1)))/eisg; #
4498 return $String;
4502 # The initial open statements: Open a pipe to the foreign script interpreter
4503 sub OpenForeignScript # ($ContentType) -> $DirectivePrefix
4505 my $ContentType = lc(shift) || return "";
4506 my $NewDirective = "";
4508 return $NewDirective if($SCRIPTINGINPUT{$ContentType});
4510 # Construct a unique file handle name
4511 $SCRIPTINGFILEHANDLE = uc($ContentType);
4512 $SCRIPTINGFILEHANDLE =~ s/\W/\_/isg;
4513 $SCRIPTINGINPUT{$ContentType} = $SCRIPTINGFILEHANDLE
4514 unless $SCRIPTINGINPUT{$ContentType};
4516 # Create the relevant script: Open the pipe to the interpreter
4517 $NewDirective .= <<"BLOCKCGISCRIPTOROPEN";
4518 # Open interpreter for '$ContentType'
4519 # Open pipe to interpreter (if it isn't open already)
4520 open($SCRIPTINGINPUT{$ContentType}, "|$ScriptingLanguages{$ContentType}") || main::dieHandler(14, "$ContentType: \$!\\n");
4521 BLOCKCGISCRIPTOROPEN
4523 # Insert Initialization code and CGI variables
4524 $NewDirective .= InitializeForeignScript($ContentType);
4526 # Ready
4527 return $NewDirective;
4531 # The final closing code to stop the interpreter
4532 sub CloseForeignScript # ($ContentType) -> $DirectivePrefix
4534 my $ContentType = lc(shift) || return "";
4535 my $NewDirective = "";
4537 # Do nothing unless the pipe realy IS open
4538 return "" unless $SCRIPTINGINPUT{$ContentType};
4540 # Initial comment
4541 $NewDirective .= "\# Close interpreter for '$ContentType'\n";
4544 # Write the Postfix code
4545 $NewDirective .= CleanupForeignScript($ContentType);
4547 # Create the relevant script: Close the pipe to the interpreter
4548 $NewDirective .= <<"BLOCKCGISCRIPTORCLOSE";
4549 close($SCRIPTINGINPUT{$ContentType}) || main::dieHandler(15, \"$ContentType: \$!\\n\");
4550 select(STDOUT); \$|=1;
4552 BLOCKCGISCRIPTORCLOSE
4554 # Remove the file handler of the foreign script
4555 delete($SCRIPTINGINPUT{$ContentType});
4557 return $NewDirective;
4561 # The initialization code for the foreign script interpreter
4562 sub InitializeForeignScript # ($ContentType) -> $DirectivePrefix
4564 my $ContentType = lc(shift) || return "";
4565 my $NewDirective = "";
4567 # Add initialization code
4568 if($ScriptingInitialization{$ContentType})
4570 $NewDirective .= <<"BLOCKCGISCRIPTORINIT";
4571 # Initialization Code for '$ContentType'
4572 # Select relevant output filehandle
4573 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4575 # The Initialization code (if any)
4576 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}INITIALIZATIONCODE';
4577 $ScriptingInitialization{$ContentType}
4578 ${ContentType}INITIALIZATIONCODE
4580 BLOCKCGISCRIPTORINIT
4583 # Add all CGI variables defined
4584 if(exists($ScriptingCGIvariables{$ContentType}))
4586 # Start writing variable definitions to the Interpreter
4587 if($ScriptingCGIvariables{$ContentType})
4589 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEF";
4590 # CGI variables (from the %default_values table)
4591 print $SCRIPTINGINPUT{$ContentType} << '${ContentType}CGIVARIABLES';
4592 BLOCKCGISCRIPTORVARDEF
4595 my ($N, $V);
4596 foreach $N (keys(%default_values))
4598 # Determine whether the parameter has been defined
4599 # (the eval is a workaround to get at the variable value)
4600 next unless eval("defined(\$CGIexecute::$N)");
4602 # Get the value from the EXECUTION environment
4603 $V = eval("\$CGIexecute::$N");
4604 # protect control characters (i.e., convert them to \0.. form)
4605 $V = shrubCGIparameter($V);
4607 # Protect interpolated variables
4608 eval("\$CGIexecute::$N = '$V';") unless $ScriptingCGIvariables{$ContentType};
4610 # Print the actual declaration for this scripting language
4611 if($ScriptingCGIvariables{$ContentType})
4613 $NewDirective .= sprintf($ScriptingCGIvariables{$ContentType}, $N, $V);
4614 $NewDirective .= "\n";
4618 # Stop writing variable definitions to the Interpreter
4619 if($ScriptingCGIvariables{$ContentType})
4621 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEFEND";
4622 ${ContentType}CGIVARIABLES
4623 BLOCKCGISCRIPTORVARDEFEND
4628 $NewDirective .= << "BLOCKCGISCRIPTOREND";
4630 # Select STDOUT filehandle
4631 select(STDOUT); \$|=1;
4633 BLOCKCGISCRIPTOREND
4635 return $NewDirective;
4639 # The cleanup code for the foreign script interpreter
4640 sub CleanupForeignScript # ($ContentType) -> $DirectivePrefix
4642 my $ContentType = lc(shift) || return "";
4643 my $NewDirective = "";
4645 # Return if not needed
4646 return $NewDirective unless $ScriptingCleanup{$ContentType};
4648 # Create the relevant script: Open the pipe to the interpreter
4649 $NewDirective .= <<"BLOCKCGISCRIPTORSTOP";
4650 # Cleanup Code for '$ContentType'
4651 # Select relevant output filehandle
4652 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4653 # Print Cleanup code to foreign script
4654 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}SCRIPTSTOP';
4655 $ScriptingCleanup{$ContentType}
4656 ${ContentType}SCRIPTSTOP
4658 # Select STDOUT filehandle
4659 select(STDOUT); \$|=1;
4660 BLOCKCGISCRIPTORSTOP
4662 return $NewDirective;
4666 # The prefix code for each <script></script> block
4667 sub PrefixForeignScript # ($ContentType) -> $DirectivePrefix
4669 my $ContentType = lc(shift) || return "";
4670 my $NewDirective = "";
4672 # Return if not needed
4673 return $NewDirective unless $ScriptingPrefix{$ContentType};
4675 my $Quote = "\'";
4676 # If the CGIvariables parameter is defined, but empty, interpolate
4677 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
4678 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
4679 !$ScriptingCGIvariables{$ContentType};
4681 # Add initialization code
4682 $NewDirective .= <<"BLOCKCGISCRIPTORPREFIX";
4683 # Prefix Code for '$ContentType'
4684 # Select relevant output filehandle
4685 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4687 # The block Prefix code (if any)
4688 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}PREFIXCODE$Quote;
4689 $ScriptingPrefix{$ContentType}
4690 ${ContentType}PREFIXCODE
4691 # Select STDOUT filehandle
4692 select(STDOUT); \$|=1;
4693 BLOCKCGISCRIPTORPREFIX
4695 return $NewDirective;
4699 # The postfix code for each <script></script> block
4700 sub PostfixForeignScript # ($ContentType) -> $DirectivePrefix
4702 my $ContentType = lc(shift) || return "";
4703 my $NewDirective = "";
4705 # Return if not needed
4706 return $NewDirective unless $ScriptingPostfix{$ContentType};
4708 my $Quote = "\'";
4709 # If the CGIvariables parameter is defined, but empty, interpolate
4710 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
4711 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
4712 !$ScriptingCGIvariables{$ContentType};
4714 # Create the relevant script: Open the pipe to the interpreter
4715 $NewDirective .= <<"BLOCKCGISCRIPTORPOSTFIX";
4716 # Postfix Code for '$ContentType'
4717 # Select filehandle to interpreter
4718 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4719 # Print postfix code to foreign script
4720 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SCRIPTPOSTFIX$Quote;
4721 $ScriptingPostfix{$ContentType}
4722 ${ContentType}SCRIPTPOSTFIX
4723 # Select STDOUT filehandle
4724 select(STDOUT); \$|=1;
4725 BLOCKCGISCRIPTORPOSTFIX
4727 return $NewDirective;
4730 sub InsertForeignScript # ($ContentType, $directive, @SRCfile) -> $NewDirective
4732 my $ContentType = lc(shift) || return "";
4733 my $directive = shift || return "";
4734 my @SRCfile = @_;
4735 my $NewDirective = "";
4737 my $Quote = "\'";
4738 # If the CGIvariables parameter is defined, but empty, interpolate
4739 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
4740 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
4741 !$ScriptingCGIvariables{$ContentType};
4743 # Create the relevant script
4744 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
4745 # Insert Code for '$ContentType'
4746 # Select filehandle to interpreter
4747 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4748 BLOCKCGISCRIPTORINSERT
4750 # Use SRC feature files
4751 my $ThisSRCfile;
4752 while($ThisSRCfile = shift(@_))
4754 # Handle blocks
4755 if($ThisSRCfile =~ /^\s*\{\s*/)
4757 my $Block = $';
4758 $Block = $` if $Block =~ /\s*\}\s*$/;
4759 $NewDirective .= <<"BLOCKCGISCRIPTORSRCBLOCK";
4760 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SRCBLOCKCODE$Quote;
4761 $Block
4762 ${ContentType}SRCBLOCKCODE
4763 BLOCKCGISCRIPTORSRCBLOCK
4765 next;
4768 # Handle files
4769 $NewDirective .= <<"BLOCKCGISCRIPTORSRCFILES";
4770 # Read $ThisSRCfile
4771 open(SCRIPTINGSOURCE, "<$ThisSRCfile") || main::dieHandler(16, "$ThisSRCfILE: \$!");
4772 while(<SCRIPTINGSOURCE>)
4774 print $SCRIPTINGINPUT{$ContentType} \$_;
4776 close(SCRIPTINGSOURCE);
4778 BLOCKCGISCRIPTORSRCFILES
4782 # Add the directive
4783 if($directive)
4785 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
4786 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}DIRECTIVECODE$Quote;
4787 $directive
4788 ${ContentType}DIRECTIVECODE
4789 BLOCKCGISCRIPTORINSERT
4793 $NewDirective .= <<"BLOCKCGISCRIPTORSELECT";
4794 # Select STDOUT filehandle
4795 select(STDOUT); \$|=1;
4796 BLOCKCGISCRIPTORSELECT
4798 # Ready
4799 return $NewDirective;
4802 sub CloseAllForeignScripts # Call CloseForeignScript on all open scripts
4804 my $ContentType;
4805 foreach $ContentType (keys(%SCRIPTINGINPUT))
4807 my $directive = CloseForeignScript($ContentType);
4808 print STDERR "\nDirective $CGI_Date: ", $directive;
4809 CGIexecute->evaluate($directive);
4814 # End of handling foreign (external) scripting languages.
4816 ############################################################################
4818 # A subroutine to handle "nested" quotes, it cuts off the leading
4819 # item or quoted substring
4820 # E.g.,
4821 # ' A_word and more words' -> @('A_word', ' and more words')
4822 # '"quoted string" The rest' -> @('quoted string', ' The rest')
4823 # (this is needed for parsing the <TAGS> and their attributes)
4824 my $SupportedQuotes = "\'\"\`\(\{\[";
4825 my %QuotePairs = ('('=>')','['=>']','{'=>'}'); # Brackets
4826 sub ExtractQuotedItem # ($String) -> @($QuotedString, $RestOfString)
4828 my @Result = ();
4829 my $String = shift || return @Result;
4831 if($String =~ /^\s*([\w\/\-\.]+)/is)
4833 push(@Result, $1, $');
4835 elsif($String =~ /^\s*(\\?)([\Q$SupportedQuotes\E])/is)
4837 my $BackSlash = $1 || "";
4838 my $OpenQuote = $2;
4839 my $CloseQuote = $OpenQuote;
4840 $CloseQuote = $QuotePairs{$OpenQuote} if $QuotePairs{$OpenQuote};
4842 if($BackSlash)
4844 $String =~ /^\s*\\\Q$OpenQuote\E/i;
4845 my $Onset = $';
4846 $Onset =~ /\\\Q$CloseQuote\E/i;
4847 my $Rest = $';
4848 my $Item = $`;
4849 push(@Result, $Item, $Rest);
4852 else
4854 $String =~ /^\s*\Q$OpenQuote\E([^\Q$CloseQuote\E]*)\Q$CloseQuote\E/i;
4855 push(@Result, $1, $');
4858 else
4860 push(@Result, "", $String);
4862 return @Result;
4865 # Now, start with the real work
4867 # Control the output of the Content-type: text/html\n\n message
4868 my $SupressContentType = 0;
4870 # Process a file
4871 sub ProcessFile # ($file_path)
4873 my $file_path = shift || return 0;
4876 # Generate a unique file handle (for recursions)
4877 my @SRClist = ();
4878 my $FileHandle = "file";
4879 my $n = 0;
4880 while(!eof($FileHandle.$n)) {++$n;};
4881 $FileHandle .= $n;
4883 # Start HTML output
4884 # Use the default Content-type if this is NOT a raw file
4885 unless(($RawFilePattern && $ENV{'PATH_INFO'} =~ m@($RawFilePattern)$@i)
4886 || $SupressContentType)
4888 $ENV{'PATH_INFO'} =~ m@($FilePattern)$@i;
4889 my $ContentType = $ContentTypeTable{$1};
4890 print "Content-type: $ContentType\n";
4891 if(%SETCOOKIELIST && keys(%SETCOOKIELIST))
4893 foreach my $name (keys(%SETCOOKIELIST))
4895 my $value = $SETCOOKIELIST{$name};
4896 print "Set-Cookie: $name=$value\n";
4898 # Cookies are set only ONCE
4899 %SETCOOKIELIST = ();
4901 print "\n";
4902 $SupressContentType = 1; # Content type has been printed
4906 # Get access to the actual data. This can be from RAM (by way of an
4907 # environment variable) or by opening a file.
4909 # Handle the use of RAM images (file-data is stored in the
4910 # $CGI_FILE_CONTENTS environment variable)
4911 # Note that this environment variable will be cleared, i.e., it is strictly for
4912 # single-use only!
4913 if($ENV{$CGI_FILE_CONTENTS})
4915 # File has been read already
4916 $_ = $ENV{$CGI_FILE_CONTENTS};
4917 # Sorry, you have to do the reading yourself (dynamic document creation?)
4918 # NOTE: you must read the whole document at once
4919 if($_ eq '-')
4921 $_ = eval("\@_=('$file_path'); do{$ENV{$CGI_DATA_ACCESS_CODE}}");
4923 else # Clear environment variable
4925 $ENV{$CGI_FILE_CONTENTS} = '-';
4928 # Open Only PLAIN TEXT files (or STDIN) and NO executable files (i.e., scripts).
4929 # THIS IS A SECURITY FEATURE!
4930 elsif($file_path eq '-' || (-e "$file_path" && -r _ && -T _ && -f _ && ! (-x _ || -X _) ))
4932 open($FileHandle, $file_path) || dieHandler(17, "<h2>File not found</h2>\n");
4933 push(@OpenFiles, $file_path);
4934 $_ = <$FileHandle>; # Read first line
4936 elsif( -e "$file_path" && -r _ && -T _ && -f _ && $useFAT )
4938 open($FileHandle, $file_path) || dieHandler(17, "<h2>File not found</h2>\n");
4939 push(@OpenFiles, $file_path);
4940 $_ = <$FileHandle>; # Read first line
4942 else
4944 print "<h2>File not found</h2>\n";
4945 dieHandler(18, "$file_path\n");
4948 $| = 1; # Flush output buffers
4950 # Initialize variables
4951 my $METAarguments = ""; # The CGI arguments from the latest META tag
4952 my @METAvalues = (); # The ''-quoted CGI values from the latest META tag
4953 my $ClosedTag = 0; # <TAG> </TAG> versus <TAG/>
4956 # Send document to output
4957 # Process the requested document.
4958 # Do a loop BEFORE reading input again (this catches the RAM/Database
4959 # type of documents).
4960 do {
4963 # Handle translations if needed
4965 performTranslation(\$_) if $TranslationPaths;
4967 # Catch <SCRIPT LANGUAGE="PERL" TYPE="text/ssperl" > directives in $_
4968 # There can be more than 1 <SCRIPT> or META tags on a line
4969 while(/\<\s*(SCRIPT|META|DIV|INS)\s/is)
4971 my $directive = "";
4972 # Store rest of line
4973 my $Before = $`;
4974 my $ScriptTag = $&;
4975 my $After = $';
4976 my $TagType = uc($1);
4977 # The before part can be send to the output
4978 print $Before;
4980 # Read complete Tag from after and/or file
4981 until($After =~ /([^\\])\>/)
4983 $After .= <$FileHandle>;
4984 performTranslation(\$After) if $TranslationPaths;
4987 if($After =~ /([^\\])\>/)
4989 $ScriptTag .= $`.$&; # Keep the Script Tag intact
4990 $After = $';
4992 else
4994 dieHandler(19, "Closing > not found\n");
4997 # The tag could be closed by />, we handle this in the XML way
4998 # and don't process any content (we ignore whitespace)
4999 $ClosedTag = ($ScriptTag =~ m@[^\\]/\s*\>\s*$@) ? 1 : 0;
5002 # TYPE or CLASS?
5003 my $TypeName = ($TagType =~ /META/is) ? "CONTENT" : "TYPE";
5004 $TypeName = "CLASS" if $TagType eq 'DIV' || $TagType eq 'INS';
5006 # Parse <SCRIPT> or <META> directive
5007 # If NOT (TYPE|CONTENT)="text/ssperl" (i.e., $ServerScriptContentType),
5008 # send the line to the output and go to the next loop
5009 my $CurrentContentType = "";
5010 if($ScriptTag =~ /(^|\s)$TypeName\s*=\s*/is)
5012 my ($Type) = ExtractQuotedItem($');
5013 $Type =~ /^\s*([\w\/\-]+)\s*[\,\;]?/;
5014 $CurrentContentType = lc($1); # Note: mime-types are "case-less"
5015 # CSS classes are aliases of $ServerScriptContentType
5016 if($TypeName eq "CLASS" && $CurrentContentType eq $ServerScriptContentClass)
5018 $CurrentContentType = $ServerScriptContentType;
5023 # Not a known server-side content type, print and continue
5024 unless(($CurrentContentType =~
5025 /$ServerScriptContentType|$ShellScriptContentType/is) ||
5026 $ScriptingLanguages{$CurrentContentType})
5028 print $ScriptTag;
5029 $_ = $After;
5030 next;
5034 # A known server-side content type, evaluate
5036 # First, handle \> and \<
5037 $ScriptTag =~ s/\\\>/\>/isg;
5038 $ScriptTag =~ s/\\\</\</isg;
5040 # Extract the CGI, SRC, ID, IF and UNLESS attributes
5041 my %ScriptTagAttributes = ();
5042 while($ScriptTag =~ /(^|\s)(CGI|IF|UNLESS|SRC|ID)\s*=\s*/is)
5044 my $Attribute = $2;
5045 my $Rest = $';
5046 my $Value = "";
5047 ($Value, $ScriptTag) = ExtractQuotedItem($Rest);
5048 $ScriptTagAttributes{uc($Attribute)} = $Value;
5052 # The attribute used to define the CGI variables
5053 # Extract CGI-variables from
5054 # <META CONTENT="text/ssperl; CGI='' SRC=''">
5055 # <SCRIPT TYPE='text/ssperl' CGI='' SRC=''>
5056 # <DIV CLASS='ssperl' CGI='' SRC='' ID=""> tags
5057 # <INS CLASS='ssperl' CGI='' SRC='' ID=""> tags
5058 if($ScriptTagAttributes{'CGI'})
5060 @ARGV = (); # Reset ARGV
5061 $ARGC = 0;
5062 $METAarguments = ""; # Reset the META CGI arguments
5063 @METAvalues = ();
5064 my $Meta_CGI = $ScriptTagAttributes{'CGI'};
5066 # Process default values of variables ($<name> = 'default value')
5067 # Allowed quotes are '', "", ``, (), [], and {}
5068 while($Meta_CGI =~ /(^\s*|[^\\])([\$\@\%]?)([\w\-]+)\s*/is)
5070 my $varType = $2 || '$'; # Variable or list
5071 my $name = $3; # The Name
5072 my $default = "";
5073 $Meta_CGI = $';
5075 if($Meta_CGI =~ /^\s*\=\s*/is)
5077 # Locate (any) default value
5078 ($default, $Meta_CGI) = ExtractQuotedItem($'); # Cut the parameter from the CGI
5080 $RemainingTag = $Meta_CGI;
5083 # Define CGI (or ENV) variable, initalize it from the
5084 # Query string or the default value
5086 # Also construct the @ARGV and @_ arrays. This allows other (SRC=) Perl
5087 # scripts to access the CGI arguments defined in the META tag
5088 # (Not for CGI inside <SCRIPT> tags)
5089 if($varType eq '$')
5091 CGIexecute::defineCGIvariable($name, $default)
5092 || dieHandler(20, "INVALID CGI name/value pair ($name, $default)\n");
5093 push(@METAvalues, "'".${"CGIexecute::$name"}."'");
5094 # Add value to the @ARGV list
5095 push(@ARGV, ${"CGIexecute::$name"});
5096 ++$ARGC;
5098 elsif($varType eq '@')
5100 CGIexecute::defineCGIvariableList($name, $default)
5101 || dieHandler(21, "INVALID CGI name/value list pair ($name, $default)\n");
5102 push(@METAvalues, "'".join("'", @{"CGIexecute::$name"})."'");
5103 # Add value to the @ARGV list
5104 push(@ARGV, @{"CGIexecute::$name"});
5105 $ARGC = scalar(@CGIexecute::ARGV);
5107 elsif($varType eq '%')
5109 CGIexecute::defineCGIvariableHash($name, $default)
5110 || dieHandler(22, "INVALID CGI name/value hash pair ($name, $default)\n");
5111 my @PairList = map {"$_ => ".${"CGIexecute::$name"}{$_}} keys(%{"CGIexecute::$name"});
5112 push(@METAvalues, "'".join("'", @PairList)."'");
5113 # Add value to the @ARGV list
5114 push(@ARGV, %{"CGIexecute::$name"});
5115 $ARGC = scalar(@CGIexecute::ARGV);
5118 # Store the values for internal and later use
5119 $METAarguments .= "$varType".$name.","; # A string of CGI variable names
5121 push(@METAvalues, "\'".eval("\"$varType\{CGIexecute::$name\}\"")."\'"); # ALWAYS add '-quotes around values
5126 # The IF (conditional execution) Attribute
5127 # Evaluate the condition and stop unless it evaluates to true
5128 if($ScriptTagAttributes{'IF'})
5130 my $IFcondition = $ScriptTagAttributes{'IF'};
5132 # Convert SCRIPT calls, ./<script>
5133 $IFcondition =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
5135 # Convert FILE calls, ~/<file>
5136 $IFcondition =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
5138 # Block execution if necessary
5139 unless(CGIexecute->evaluate($IFcondition))
5141 %ScriptTagAttributes = ();
5142 $CurrentContentType = "";
5146 # The UNLESS (conditional execution) Attribute
5147 # Evaluate the condition and stop if it evaluates to true
5148 if($ScriptTagAttributes{'UNLESS'})
5150 my $UNLESScondition = $ScriptTagAttributes{'UNLESS'};
5152 # Convert SCRIPT calls, ./<script>
5153 $UNLESScondition =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
5155 # Convert FILE calls, ~/<file>
5156 $UNLESScondition =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
5158 # Block execution if necessary
5159 if(CGIexecute->evaluate($UNLESScondition))
5161 %ScriptTagAttributes = ();
5162 $CurrentContentType = "";
5166 # The SRC (Source File) Attribute
5167 # Extract any source script files and add them in
5168 # front of the directive
5169 # The SRC list should be emptied
5170 @SRClist = ();
5171 my $SRCtag = "";
5172 my $Prefix = 1;
5173 my $PrefixDirective = "";
5174 my $PostfixDirective = "";
5175 # There is a SRC attribute
5176 if($ScriptTagAttributes{'SRC'})
5178 $SRCtag = $ScriptTagAttributes{'SRC'};
5179 # Remove "file://" prefixes
5180 $SRCtag =~ s@([^\w\/\\]|^)file\://([^\s\/\@\=])@$1$2@gis;
5181 # Expand script filenames "./Script"
5182 $SRCtag =~ s@([^\w\/\\]|^)\./([^\s\/\@\=])@$1$SCRIPT_SUB/$2@gis;
5183 # Expand script filenames "~/Script"
5184 $SRCtag =~ s@([^\w\/\\]|^)\~/([^\s\/\@\=])@$1$HOME_SUB/$2@gis;
5187 # File source tags
5188 while($SRCtag =~ /\S/is)
5190 my $SRCdirective = "";
5192 # Pseudo file, just a switch to go from PREFIXING to POSTFIXING
5193 # SRC files
5194 if($SRCtag =~ /^[\s\;\,]*(POSTFIX|PREFIX)([^$FileAllowedChars]|$)/is)
5196 my $InsertionPlace = $1;
5197 $SRCtag = $2.$';
5199 $Prefix = $InsertionPlace =~ /POSTFIX/i ? 0 : 1;
5200 # Go to next round
5201 next;
5203 # {}-blocks are just evaluated by "do"
5204 elsif($SRCtag =~ /^[\s\;\,]*\{/is)
5206 my $SRCblock = $';
5207 if($SRCblock =~ /\}[\s\;\,]*([^\}]*)$/is)
5209 $SRCblock = $`;
5210 $SRCtag = $1.$';
5211 # SAFEqx shell script blocks
5212 if($CurrentContentType =~ /$ShellScriptContentType/is)
5214 # Handle ''-quotes inside the script
5215 $SRCblock =~ s/[\']/\\$&/gis;
5217 $SRCblock = "print do { SAFEqx(\'".$SRCblock."\'); };'';";
5218 $SRCdirective .= $SRCblock."\n";
5220 # do { SRCblocks }
5221 elsif($CurrentContentType =~ /$ServerScriptContentType/is)
5223 $SRCblock = "print do { $SRCblock };'';";
5224 $SRCdirective .= $SRCblock."\n";
5226 else # The interpreter should handle this
5228 push(@SRClist, "{ $SRCblock }");
5232 else
5233 { dieHandler(23, "Closing \} missing\n");};
5235 # Files are processed as Text or Executable files
5236 elsif($SRCtag =~ /[\s\;\,]*([$FileAllowedChars]+)[\;\,\s]*/is)
5238 my $SrcFile = $1;
5239 $SRCtag = $';
5241 # We are handling one of the external interpreters
5242 if($ScriptingLanguages{$CurrentContentType})
5244 push(@SRClist, $SrcFile);
5246 # We are at the start of a DIV tag, just load all SRC files and/or URL's
5247 elsif($TagType eq 'DIV' || $TagType eq 'INS') # All files are prepended in DIV's
5249 # $SrcFile is a URL pointing to an HTTP or FTP server
5250 if($SrcFile =~ m!^([a-z]+)\://!)
5252 my $URLoutput = CGIscriptor::read_url($SrcFile);
5253 $SRCdirective .= $URLoutput;
5255 # SRC file is an existing file
5256 elsif(-e "$SrcFile")
5258 open(DIVSOURCE, "<$SrcFile") || dieHandler(24, "<$SrcFile: $!\n");
5259 my $Content;
5260 while(sysread(DIVSOURCE, $Content, 1024) > 0)
5262 $SRCdirective .= $Content;
5264 close(DIVSOURCE);
5267 # Executable files are executed as
5268 # `$SrcFile 'ARGV[0]' 'ARGV[1]'`
5269 elsif(-x "$SrcFile")
5271 $SRCdirective .= "print \`$SrcFile @METAvalues\`;'';\n";
5273 # Handle 'standard' files, using ProcessFile
5274 elsif((-T "$SrcFile" || $ENV{$CGI_FILE_CONTENTS})
5275 && $SrcFile =~ m@($FilePattern)$@) # A recursion
5278 # Do not process still open files because it can lead
5279 # to endless recursions
5280 if(grep(/^$SrcFile$/, @OpenFiles))
5281 { dieHandler(25, "$SrcFile allready opened (endless recursion)\n")};
5282 # Prepare meta arguments
5283 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
5284 # Process the file
5285 $SRCdirective .= "main::ProcessFile(\'$SrcFile\');'';\n";
5287 elsif($SrcFile =~ m!^([a-z]+)\://!) # URL's are loaded and printed
5289 $SRCdirective .= GET_URL($SrcFile);
5291 elsif(-T "$SrcFile") # Textfiles are "do"-ed (Perl execution)
5293 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
5294 $SRCdirective .= "do \'$SrcFile\';'';\n";
5296 else # This one could not be resolved (should be handled by BinaryMapFile)
5298 $SRCdirective .= 'print "'.$SrcFile.' cannot be used"'."\n";
5303 # Postfix or Prefix
5304 if($Prefix)
5306 $PrefixDirective .= $SRCdirective;
5308 else
5310 $PostfixDirective .= $SRCdirective;
5313 # The prefix should be handled immediately
5314 $directive .= $PrefixDirective;
5315 $PrefixDirective = "";
5319 # Handle the content of the <SCRIPT></SCRIPT> tags
5320 # Do not process the content of <SCRIPT/>
5321 if($TagType =~ /SCRIPT/is && !$ClosedTag) # The <SCRIPT> TAG
5323 my $EndScriptTag = "";
5325 # Execute SHELL scripts with SAFEqx()
5326 if($CurrentContentType =~ /$ShellScriptContentType/is)
5328 $directive .= "SAFEqx(\'";
5331 # Extract Program
5332 while($After !~ /\<\s*\/SCRIPT[^\>]*\>/is && !eof($FileHandle))
5334 $After .= <$FileHandle>;
5335 performTranslation(\$After) if $TranslationPaths;
5338 if($After =~ /\<\s*\/SCRIPT[^\>]*\>/is)
5340 $directive .= $`;
5341 $EndScriptTag = $&;
5342 $After = $';
5344 else
5346 dieHandler(26, "Missing </SCRIPT> end tag in $ENV{'PATH_INFO'}\n");
5349 # Process only when content should be executed
5350 if($CurrentContentType)
5353 # Remove all comments from Perl scripts
5354 # (NOT from OS shell scripts)
5355 $directive =~ s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/$1/g
5356 if $CurrentContentType =~ /$ServerScriptContentType/i;
5358 # Convert SCRIPT calls, ./<script>
5359 $directive =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
5361 # Convert FILE calls, ~/<file>
5362 $directive =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
5364 # Execute SHELL scripts with SAFEqx(), closing bracket
5365 if($CurrentContentType =~ /$ShellScriptContentType/i)
5367 # Handle ''-quotes inside the script
5368 $directive =~ /SAFEqx\(\'/;
5369 $directive = $`.$&;
5370 my $Executable = $';
5371 $Executable =~ s/[\']/\\$&/gs;
5373 $directive .= $Executable."\');"; # Closing bracket
5376 else
5378 $directive = "";
5381 # Handle the content of the <DIV></DIV> tags
5382 # Do not process the content of <DIV/>
5383 elsif(($TagType eq 'DIV' || $TagType eq 'INS') && !$ClosedTag) # The <DIV> TAGs
5385 my $EndScriptTag = "";
5387 # Extract Text
5388 while($After !~ /\<\s*\/$TagType[^\>]*\>/is && !eof($FileHandle))
5390 $After .= <$FileHandle>;
5391 performTranslation(\$After) if $TranslationPaths;
5394 if($After =~ /\<\s*\/$TagType[^\>]*\>/is)
5396 $directive .= $`;
5397 $EndScriptTag = $&;
5398 $After = $';
5400 else
5402 dieHandler(27, "Missing </$TagType> end tag in $ENV{'PATH_INFO'}\n");
5405 # Add the Postfixed directives (but only when it contains something printable)
5406 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
5407 $PostfixDirective = "";
5410 # Process only when content should be handled
5411 if($CurrentContentType)
5414 # Get the name (ID), and clean it (i.e., remove anything that is NOT part of
5415 # a valid Perl name). Names should not contain $, but we can handle it.
5416 my $name = $ScriptTagAttributes{'ID'};
5417 $name =~ /^\s*[\$\@\%]?([\w\-]+)/;
5418 $name = $1;
5420 # Assign DIV contents to $NAME value OUTSIDE the CGI values!
5421 CGIexecute::defineCGIexecuteVariable($name, $directive);
5422 $directive = "";
5425 # Nothing to execute
5426 $directive = "";
5430 # Handle Foreign scripting languages
5431 if($ScriptingLanguages{$CurrentContentType})
5433 my $newDirective = "";
5434 $newDirective .= OpenForeignScript($CurrentContentType); # Only if not already done
5435 $newDirective .= PrefixForeignScript($CurrentContentType);
5436 $newDirective .= InsertForeignScript($CurrentContentType, $directive, @SRClist);
5437 $newDirective .= PostfixForeignScript($CurrentContentType);
5438 $newDirective .= CloseForeignScript($CurrentContentType); # This shouldn't be necessary
5440 $newDirective .= '"";';
5442 $directive = $newDirective;
5446 # Add the Postfixed directives (but only when it contains something printable)
5447 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
5448 $PostfixDirective = "";
5451 # EXECUTE the script and print the results
5453 # Use this to debug the program
5454 # print STDERR "Directive $CGI_Date: \n", $directive, "\n\n";
5456 my $Result = CGIexecute->evaluate($directive) if $directive; # Evaluate as PERL code
5457 $Result =~ s/\n$//g; # Remove final newline
5459 # Print the Result of evaluating the directive
5460 # (this will handle LARGE, >64 kB output)
5461 my $BytesWritten = 1;
5462 while($Result && $BytesWritten)
5464 $BytesWritten = syswrite(STDOUT, $Result, 64);
5465 $Result = substr($Result, $BytesWritten);
5467 # print $Result; # Could be used instead of above code
5469 # Store result if wanted, i.e., if $CGIscriptorResults has been
5470 # defined in a <META> tag.
5471 push(@CGIexecute::CGIscriptorResults, $Result)
5472 if exists($default_values{'CGIscriptorResults'});
5474 # Process the rest of the input line (this could contain
5475 # another directive)
5476 $_ = $After;
5478 print $_;
5479 } while(<$FileHandle>); # Read and Test AFTER first loop!
5481 close ($FileHandle);
5482 dieHandler(28, "Error in recursion\n") unless pop(@OpenFiles) == $file_path;
5486 ###############################################################################
5488 # Call the whole package
5490 sub Handle_Request
5492 my $file_path = "";
5494 # Initialization Code
5495 Initialize_Request();
5497 # SECURITY: ACCESS CONTROL
5498 Access_Control();
5500 # Read the POST part of the query, if there is one
5501 Get_POST_part_of_query();
5503 # Start (HTML) output and logging
5504 $file_path = Initialize_output();
5506 # Check login access or divert to login procedure
5507 $Use_Login = Log_In_Access();
5508 $file_path = $Use_Login if $Use_Login;
5510 # Record which files are still open (to avoid endless recursions)
5511 my @OpenFiles = ();
5513 # Record whether the default HTML ContentType has already been printed
5514 # but only if the SERVER uses HTTP or some other protocol that might interpret
5515 # a content MIME type.
5517 $SupressContentType = !("$ENV{'SERVER_PROTOCOL'}" =~ /($ContentTypeServerProtocols)/i);
5519 # Process the specified file
5520 ProcessFile($file_path) if $file_path ne $SS_PUB;
5522 # Cleanup all open external (foreign) interpreters
5523 CloseAllForeignScripts();
5526 "" # SUCCESS
5529 # Make a single call to handle an (empty) request
5530 Handle_Request();
5533 # END OF PACKAGE MAIN
5536 ####################################################################################
5538 # The CGIEXECUTE PACKAGE
5540 ####################################################################################
5542 # Isolate the evaluation of directives as PERL code from the rest of the program.
5543 # Remember that each package has its own name space.
5544 # Note that only the FIRST argument of execute->evaluate is actually evaluated,
5545 # all other arguments are accessible inside the first argument as $_[0] to $_[$#_].
5547 package CGIexecute;
5549 sub evaluate
5551 my $self = shift;
5552 my $directive = shift;
5553 $directive = eval($directive);
5554 warn $@ if $@; # Write an error message to STDERR
5555 $directive; # Return value of directive
5559 # defineCGIexecuteVariable($name [, $value]) -> 0/1
5561 # Define and intialize variables inside CGIexecute
5562 # Does no sanity checking, for internal use only
5564 sub defineCGIexecuteVariable # ($name [, $value]) -> 0/1
5566 my $name = shift || return 0; # The Name
5567 my $value = shift || ""; # The value
5569 ${$name} = $value;
5571 return 1;
5574 # Protect certain CGI variables values when set internally
5575 # If not defined internally, there will be no variable set AT ALL
5576 my %CGIprotectedVariable = ();
5577 sub ProtectCGIvariable # ($name) -> 0/1
5579 my $name = shift || "";
5580 return 0 unless $name && $name =~ /\w/;
5582 ++$CGIprotectedVariable{$name};
5584 return $CGIprotectedVariable{$name};
5587 # defineCGIvariable($name [, $default]) -> 0/1
5589 # Define and intialize CGI variables
5590 # Tries (in order) $ENV{$name}, the Query string and the
5591 # default value.
5592 # Removes all '-quotes etc.
5594 sub defineCGIvariable # ($name [, $default]) -> 0/1
5596 my $name = shift || return 0; # The Name
5597 my $default = shift || ""; # The default value
5599 # Protect variables set internally
5600 return 1 if !$name || exists($CGIprotectedVariable{$name});
5602 # Remove \-quoted characters
5603 $default =~ s/\\(.)/$1/g;
5604 # Store default values
5605 $::default_values{$name} = $default if $default;
5607 # Process variables
5608 my $temp = undef;
5609 # If there is a user supplied value, it replaces the
5610 # default value.
5612 # Environment values have precedence
5613 if(exists($ENV{$name}))
5615 $temp = $ENV{$name};
5617 # Get name and its value from the query string
5618 elsif($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
5620 $temp = ::YOUR_CGIPARSE($name);
5622 # Defined values must exist for security
5623 elsif(!exists($::default_values{$name}))
5625 $::default_values{$name} = undef;
5628 # SECURITY, do not allow '- and `-quotes in
5629 # client values.
5630 # Remove all existing '-quotes
5631 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
5632 $temp =~ s/[\']/&#8217;/igs; # Remove all single quotes
5633 $temp =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
5634 # If $temp is empty, use the default value (if it exists)
5635 unless($temp =~ /\S/ || length($temp) > 0) # I.e., $temp is empty
5637 $temp = $::default_values{$name};
5638 # Remove all existing '-quotes
5639 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
5640 $temp =~ s/[\']/&#8217;/igs; # Remove all single quotes
5641 $temp =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
5643 else # Store current CGI values and remove defaults
5645 $::default_values{$name} = $temp;
5647 # Define the CGI variable and its value (in the execute package)
5648 ${$name} = $temp;
5650 # return SUCCES
5651 return 1;
5654 sub defineCGIvariableList # ($name [, $default]) -> 0/1)
5656 my $name = shift || return 0; # The Name
5657 my $default = shift || ""; # The default value
5659 # Protect variables set internally
5660 return 1 if !$name || exists($CGIprotectedVariable{$name});
5662 # Defined values must exist for security
5663 if(!exists($::default_values{$name}))
5665 $::default_values{$name} = $default;
5668 my @temp = ();
5671 # For security:
5672 # Environment values have precedence
5673 if(exists($ENV{$name}))
5675 push(@temp, $ENV{$name});
5677 # Get name and its values from the query string
5678 elsif($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
5680 push(@temp, ::YOUR_CGIPARSE($name, 1)); # Extract LIST
5682 else
5684 push(@temp, $::default_values{$name});
5688 # SECURITY, do not allow '- and `-quotes in
5689 # client values.
5690 # Remove all existing '-quotes
5691 @temp = map {s/([\r\f]+\n)/\n/g; $_} @temp; # Only \n is allowed
5692 @temp = map {s/[\']/&#8217;/igs; $_} @temp; # Remove all single quotes
5693 @temp = map {s/[\`]/&#8216;/igs; $_} @temp; # Remove all backtick quotes
5695 # Store current CGI values and remove defaults
5696 $::default_values{$name} = $temp[0];
5698 # Define the CGI variable and its value (in the execute package)
5699 @{$name} = @temp;
5701 # return SUCCES
5702 return 1;
5705 sub defineCGIvariableHash # ($name [, $default]) -> 0/1) Note: '$name{""} = $default';
5707 my $name = shift || return 0; # The Name
5708 my $default = shift || ""; # The default value
5710 # Protect variables set internally
5711 return 1 if !$name || exists($CGIprotectedVariable{$name});
5713 # Defined values must exist for security
5714 if(!exists($::default_values{$name}))
5716 $::default_values{$name} = $default;
5719 my %temp = ();
5722 # For security:
5723 # Environment values have precedence
5724 if(exists($ENV{$name}))
5726 $temp{""} = $ENV{$name};
5728 # Get name and its values from the query string
5729 elsif($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
5731 %temp = ::YOUR_CGIPARSE($name, -1); # Extract HASH table
5733 elsif($::default_values{$name} ne "")
5735 $temp{""} = $::default_values{$name};
5739 # SECURITY, do not allow '- and `-quotes in
5740 # client values.
5741 # Remove all existing '-quotes
5742 my $Key;
5743 foreach $Key (keys(%temp))
5745 $temp{$Key} =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
5746 $temp{$Key} =~ s/[\']/&#8217;/igs; # Remove all single quotes
5747 $temp{$Key} =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
5750 # Store current CGI values and remove defaults
5751 $::default_values{$name} = $temp{""};
5753 # Define the CGI variable and its value (in the execute package)
5754 %{$name} = ();
5755 my $tempKey;
5756 foreach $tempKey (keys(%temp))
5758 ${$name}{$tempKey} = $temp{$tempKey};
5761 # return SUCCES
5762 return 1;
5766 # SAFEqx('CommandString')
5768 # A special function that is a safe alternative to backtick quotes (and qx//)
5769 # with client-supplied CGI values. All CGI variables are surrounded by
5770 # single ''-quotes (except between existing \'\'-quotes, don't try to be
5771 # too smart). All variables are then interpolated. Simple (@) lists are
5772 # expanded with join(' ', @List), and simple (%) hash tables expanded
5773 # as a list of "key=value" pairs. Complex variables, e.g., @$var, are
5774 # evaluated in a scalar context (e.g., as scalar(@$var)). All occurrences of
5775 # $@% that should NOT be interpolated must be preceeded by a "\".
5776 # If the first line of the String starts with "#! interpreter", the
5777 # remainder of the string is piped into interpreter (after interpolation), i.e.,
5778 # open(INTERPRETER, "|interpreter");print INTERPRETER remainder;
5779 # just like in UNIX. There are some problems with quotes. Be carefull in
5780 # using them. You do not have access to the output of any piped (#!)
5781 # process! If you want such access, execute
5782 # <SCRIPT TYPE="text/osshell">echo "script"|interpreter</SCRIPT> or
5783 # <SCRIPT TYPE="text/ssperl">$resultvar = SAFEqx('echo "script"|interpreter');
5784 # </SCRIPT>.
5786 # SAFEqx ONLY WORKS WHEN THE STRING ITSELF IS SURROUNDED BY SINGLE QUOTES
5787 # (SO THAT IT IS NOT INTERPOLATED BEFORE IT CAN BE PROTECTED)
5788 sub SAFEqx # ('String') -> result of executing qx/"String"/
5790 my $CommandString = shift;
5791 my $NewCommandString = "";
5793 # Only interpolate when required (check the On/Off switch)
5794 unless($CGIscriptor::NoShellScriptInterpolation)
5797 # Handle existing single quotes around CGI values
5798 while($CommandString =~ /\'[^\']+\'/s)
5800 my $CurrentQuotedString = $&;
5801 $NewCommandString .= $`;
5802 $CommandString = $'; # The remaining string
5803 # Interpolate CGI variables between quotes
5804 # (e.g., '$CGIscriptorResults[-1]')
5805 $CurrentQuotedString =~
5806 s/(^|[^\\])([\$\@])((\w*)([\{\[][\$\@\%]?[\:\w\-]+[\}\]])*)/if(exists($main::default_values{$4})){
5807 "$1".eval("$2$3")}else{"$&"}/egs;
5809 # Combine result with previous result
5810 $NewCommandString .= $CurrentQuotedString;
5812 $CommandString = $NewCommandString.$CommandString;
5814 # Select known CGI variables and surround them with single quotes,
5815 # then interpolate all variables
5816 $CommandString =~
5817 s/(^|[^\\])([\$\@\%]+)((\w*)([\{\[][\w\:\$\"\-]+[\}\]])*)/
5818 if($2 eq '$' && exists($main::default_values{$4}))
5819 {"$1\'".eval("\$$3")."\'";}
5820 elsif($2 eq '@'){$1.join(' ', @{"$3"});}
5821 elsif($2 eq '%'){my $t=$1;map {$t.=" $_=".${"$3"}{$_}}
5822 keys(%{"$3"});$t}
5823 else{$1.eval("${2}$3");
5824 }/egs;
5826 # Remove backslashed [$@%]
5827 $CommandString =~ s/\\([\$\@\%])/$1/gs;
5830 # Debugging
5831 # return $CommandString;
5833 # Handle UNIX style "#! shell command\n" constructs as
5834 # a pipe into the shell command. The output cannot be tapped.
5835 my $ReturnValue = "";
5836 if($CommandString =~ /^\s*\#\!([^\f\n\r]+)[\f\n\r]/is)
5838 my $ShellScripts = $';
5839 my $ShellCommand = $1;
5840 open(INTERPRETER, "|$ShellCommand") || dieHandler(29, "\'$ShellCommand\' PIPE not opened: &!\n");
5841 select(INTERPRETER);$| = 1;
5842 print INTERPRETER $ShellScripts;
5843 close(INTERPRETER);
5844 select(STDOUT);$| = 1;
5846 # Shell scripts which are redirected to an existing named pipe.
5847 # The output cannot be tapped.
5848 elsif($CGIscriptor::ShellScriptPIPE)
5850 CGIscriptor::printSAFEqxPIPE($CommandString);
5852 else # Plain ``-backtick execution
5854 # Execute the commands
5855 $ReturnValue = qx/$CommandString/;
5857 return $ReturnValue;
5860 ####################################################################################
5862 # The CGIscriptor PACKAGE
5864 ####################################################################################
5866 # Isolate the evaluation of CGIscriptor functions, i.e., those prefixed with
5867 # "CGIscriptor::"
5869 package CGIscriptor;
5872 # The Interpolation On/Off switch
5873 my $NoShellScriptInterpolation = undef;
5874 # The ShellScript redirection pipe
5875 my $ShellScriptPIPE = undef;
5877 # Open a named PIPE for SAFEqx to receive ALL shell scripts
5878 sub RedirectShellScript # ('CommandString')
5880 my $CommandString = shift || undef;
5882 if($CommandString)
5884 $ShellScriptPIPE = "ShellScriptNamedPipe";
5885 open($ShellScriptPIPE, "|$CommandString")
5886 || main::dieHandler(30, "\'|$CommandString\' PIPE open failed: $!\n");
5888 else
5890 close($ShellScriptPIPE);
5891 $ShellScriptPIPE = undef;
5893 return $ShellScriptPIPE;
5896 # Print to redirected shell script pipe
5897 sub printSAFEqxPIPE # ("String") -> print return value
5899 my $String = shift || undef;
5901 select($ShellScriptPIPE); $| = 1;
5902 my $returnvalue = print $ShellScriptPIPE ($String);
5903 select(STDOUT); $| = 1;
5905 return $returnvalue;
5908 # a pointer to CGIexecute::SAFEqx
5909 sub SAFEqx # ('String') -> result of qx/"String"/
5911 my $CommandString = shift;
5912 return CGIexecute::SAFEqx($CommandString);
5916 # a pointer to CGIexecute::defineCGIvariable
5917 sub defineCGIvariable # ($name[, $default]) ->0/1
5919 my $name = shift;
5920 my $default = shift;
5921 return CGIexecute::defineCGIvariable($name, $default);
5925 # a pointer to CGIexecute::defineCGIvariable
5926 sub defineCGIvariableList # ($name[, $default]) ->0/1
5928 my $name = shift;
5929 my $default = shift;
5930 return CGIexecute::defineCGIvariableList($name, $default);
5934 # a pointer to CGIexecute::defineCGIvariable
5935 sub defineCGIvariableHash # ($name[, $default]) ->0/1
5937 my $name = shift;
5938 my $default = shift;
5939 return CGIexecute::defineCGIvariableHash($name, $default);
5943 # Decode URL encoded arguments
5944 sub URLdecode # (URL encoded input) -> string
5946 my $output = "";
5947 my $char;
5948 my $Value;
5949 foreach $Value (@_)
5951 my $EncodedValue = $Value; # Do not change the loop variable
5952 # Convert all "+" to " "
5953 $EncodedValue =~ s/\+/ /g;
5954 # Convert all hexadecimal codes (%FF) to their byte values
5955 while($EncodedValue =~ /\%([0-9A-F]{2})/i)
5957 $output .= $`.chr(hex($1));
5958 $EncodedValue = $';
5960 $output .= $EncodedValue; # The remaining part of $Value
5962 $output;
5965 # Encode arguments as URL codes.
5966 sub URLencode # (input) -> URL encoded string
5968 my $output = "";
5969 my $char;
5970 my $Value;
5971 foreach $Value (@_)
5973 my @CharList = split('', $Value);
5974 foreach $char (@CharList)
5976 if($char =~ /\s/)
5977 { $output .= "+";}
5978 elsif($char =~ /\w\-/)
5979 { $output .= $char;}
5980 else
5982 $output .= uc(sprintf("%%%2.2x", ord($char)));
5986 $output;
5989 # Extract the value of a CGI variable from the URL-encoded $string
5990 # Also extracts the data blocks from a multipart request. Does NOT
5991 # decode the multipart blocks
5992 sub CGIparseValue # (ValueName [, URL_encoded_QueryString [, \$QueryReturnReference]]) -> Decoded value
5994 my $ValueName = shift;
5995 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
5996 my $ReturnReference = shift || undef;
5997 my $output = "";
5999 if($QueryString =~ /(^|\&)$ValueName\=([^\&]*)(\&|$)/)
6001 $output = URLdecode($2);
6002 $$ReturnReference = $' if ref($ReturnReference);
6004 # Get multipart POST or PUT methods
6005 elsif($main::ENV{'CONTENT_TYPE'} =~ m@(multipart/([\w\-]+)\;\s+boundary\=([\S]+))@i)
6007 my $MultipartType = $2;
6008 my $BoundaryString = $3;
6009 # Remove the boundary-string
6010 my $temp = $QueryString;
6011 $temp =~ /^\Q--$BoundaryString\E/m;
6012 $temp = $';
6014 # Identify the newline character(s), this is the first character in $temp
6015 my $NewLine = "\r\n"; # Actually, this IS the correct one
6016 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
6018 # Is this correct??? I have to check.
6019 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
6020 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
6021 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
6022 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
6025 # search through all data blocks
6026 while($temp =~ /^\Q--$BoundaryString\E/m)
6028 my $DataBlock = $`;
6029 $temp = $';
6030 # Get the empty line after the header
6031 $DataBlock =~ /$NewLine$NewLine/;
6032 $Header = $`;
6033 $output = $';
6034 my $Header = $`;
6035 $output = $';
6037 # Remove newlines from the header
6038 $Header =~ s/$NewLine/ /g;
6040 # Look whether this block is the one you are looking for
6041 # Require the quotes!
6042 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
6044 my $i;
6045 for($i=length($NewLine); $i; --$i)
6047 chop($output);
6049 # OK, get out
6050 last;
6052 # reinitialize the output
6053 $output = "";
6055 $$ReturnReference = $temp if ref($ReturnReference);
6057 elsif($QueryString !~ /(^|\&)$ValueName\=/) # The value simply isn't there
6059 return undef;
6060 $$ReturnReference = undef if ref($ReturnReference);
6062 else
6064 print "ERROR: $ValueName $main::ENV{'CONTENT_TYPE'}\n";
6066 return $output;
6070 # Get a list of values for the same ValueName. Uses CGIparseValue
6072 sub CGIparseValueList # (ValueName [, URL_encoded_QueryString]) -> List of decoded values
6074 my $ValueName = shift;
6075 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
6076 my @output = ();
6077 my $RestQueryString;
6078 my $Value;
6079 while($QueryString &&
6080 (($Value = CGIparseValue($ValueName, $QueryString, \$RestQueryString))
6081 || defined($Value)))
6083 push(@output, $Value);
6084 $QueryString = $RestQueryString; # QueryString is consumed!
6086 # ready, return list with values
6087 return @output;
6090 sub CGIparseValueHash # (ValueName [, URL_encoded_QueryString]) -> Hash table of decoded values
6092 my $ValueName = shift;
6093 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
6094 my $RestQueryString;
6095 my %output = ();
6096 while($QueryString && $QueryString =~ /(^|\&)$ValueName([\w]*)\=/)
6098 my $Key = $2;
6099 my $Value = CGIparseValue("$ValueName$Key", $QueryString, \$RestQueryString);
6100 $output{$Key} = $Value;
6101 $QueryString = $RestQueryString; # QueryString is consumed!
6103 # ready, return list with values
6104 return %output;
6107 sub CGIparseForm # ([URL_encoded_QueryString]) -> Decoded Form (NO multipart)
6109 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
6110 my $output = "";
6112 $QueryString =~ s/\&/\n/g;
6113 $output = URLdecode($QueryString);
6115 $output;
6118 # Extract the header of a multipart CGI variable from the POST input
6119 sub CGIparseHeader # (ValueName [, URL_encoded_QueryString]) -> Decoded value
6121 my $ValueName = shift;
6122 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
6123 my $output = "";
6125 if($main::ENV{'CONTENT_TYPE'} =~ m@(multipart/([\w\-]+)\;\s+boundary\=([\S]+))@i)
6127 my $MultipartType = $2;
6128 my $BoundaryString = $3;
6129 # Remove the boundary-string
6130 my $temp = $QueryString;
6131 $temp =~ /^\Q--$BoundaryString\E/m;
6132 $temp = $';
6134 # Identify the newline character(s), this is the first character in $temp
6135 my $NewLine = "\r\n"; # Actually, this IS the correct one
6136 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
6138 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
6139 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
6140 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
6141 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
6144 # search through all data blocks
6145 while($temp =~ /^\Q--$BoundaryString\E/m)
6147 my $DataBlock = $`;
6148 $temp = $';
6149 # Get the empty line after the header
6150 $DataBlock =~ /$NewLine$NewLine/;
6151 $Header = $`;
6152 my $Header = $`;
6154 # Remove newlines from the header
6155 $Header =~ s/$NewLine/ /g;
6157 # Look whether this block is the one you are looking for
6158 # Require the quotes!
6159 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
6161 $output = $Header;
6162 last;
6164 # reinitialize the output
6165 $output = "";
6168 return $output;
6172 # Checking variables for security (e.g., file names and email addresses)
6173 # File names are tested against the $::FileAllowedChars and $::BlockPathAccess variables
6174 sub CGIsafeFileName # FileName -> FileName or ""
6176 my $FileName = shift || "";
6177 return "" if $FileName =~ m?[^$::FileAllowedChars]?;
6178 return "" if $FileName =~ m!(^|/|\:)[\-\.]!;
6179 return "" if $FileName =~ m@\.\.\Q$::DirectorySeparator\E@; # Higher directory not allowed
6180 return "" if $FileName =~ m@\Q$::DirectorySeparator\E\.\.@; # Higher directory not allowed
6181 return "" if $::BlockPathAccess && $FileName =~ m@$::BlockPathAccess@; # Invisible (blocked) file
6183 return $FileName;
6186 sub CGIsafeEmailAddress # email -> email or ""
6188 my $Email = shift || "";
6189 return "" unless $Email =~ m/^[\w\.\-]+[\@][\w\.\-\:]+$/;
6190 return $Email;
6193 # Get a URL from the web. Needs main::GET_URL($URL) function
6194 # (i.e., curl, snarf, or wget)
6195 sub read_url # ($URL) -> page/file
6197 my $URL = shift || return "";
6199 # Get the commands to read the URL, do NOT add a print command
6200 my $URL_command = main::GET_URL($URL, 1);
6201 # execute the commands, i.e., actually read it
6202 my $URLcontent = CGIexecute->evaluate($URL_command);
6204 # Ready, return the content.
6205 return $URLcontent;
6208 ################################################>>>>>>>>>>Start Remove
6210 # BrowseAllDirs(Directory, indexfile)
6212 # usage:
6213 # <SCRIPT TYPE='text/ssperl'>
6214 # CGIscriptor::BrowseAllDirs('Sounds', 'index.html', '\.wav$')
6215 # </SCRIPT>
6217 # Allows to browse all directories. Stops at '/'. If the directory contains
6218 # an indexfile, eg, index.html, that file will be used instead. Files must match
6219 # the $Pattern, if it is given. Default is
6220 # CGIscriptor::BrowseAllDirs('/', 'index.html', '')
6222 sub BrowseAllDirs # (Directory, indexfile, $Pattern) -> Print HTML code
6224 my $Directory = shift || '/';
6225 my $indexfile = shift || 'index.html';
6226 my $Pattern = shift || '';
6227 $Directory =~ s!/$!!g;
6229 # If the index directory exists, use that one
6230 if(-s "$::CGI_HOME$Directory/$indexfile")
6232 return main::ProcessFile("$::CGI_HOME$Directory/$indexfile");
6235 # No indexfile, continue
6236 my @DirectoryList = glob("$::CGI_HOME$Directory");
6237 $CurrentDirectory = shift(@DirectoryList);
6238 $CurrentDirectory = $' if $CurrentDirectory =~ m@(/\.\./)+@;
6239 $CurrentDirectory =~ s@^$::CGI_HOME@@g;
6240 print "<h1>";
6241 print "$CurrentDirectory" if $CurrentDirectory;
6242 print "</h1>\n";
6244 opendir(BROWSE, "$::CGI_HOME$Directory") || main::dieHandler(31, "$::CGI_HOME$Directory $!");
6245 my @AllFiles = sort grep(!/^([\.]+[^\.]|\~)/, readdir(BROWSE));
6247 # Print directories
6248 my $file;
6249 print "<pre><ul TYPE='NONE'>\n";
6250 foreach $file (@AllFiles)
6252 next unless -d "$::CGI_HOME$Directory/$file";
6253 # Check whether this file should be visible
6254 next if $::BlockPathAccess &&
6255 "$Directory/$file/" =~ m@$::BlockPathAccess@;
6256 print "<dt><a href='$Directory/$file'>$file</a></dt>\n";
6258 print "</ul></pre>\n";
6260 # Print files
6261 print "<pre><ul TYPE='CIRCLE'>\n";
6262 my $TotalSize = 0;
6263 foreach $file (@AllFiles)
6265 next if $file =~ /^\./;
6266 next if -d "$::CGI_HOME$Directory/$file";
6267 next if -l "$::CGI_HOME$Directory/$file";
6268 # Check whether this file should be visible
6269 next if $::BlockPathAccess &&
6270 "$Directory/$file" =~ m@$::BlockPathAccess@;
6272 if(!$Pattern || $file =~ m@$Pattern@)
6274 my $Date = localtime($^T - (-M "$::CGI_HOME$Directory/$file")*3600*24);
6275 my $Size = -s "$::CGI_HOME$Directory/$file";
6276 $Size = sprintf("%6.0F kB", $Size/1024);
6277 my $Type = `file $::CGI_HOME$Directory/$file`;
6278 $Type =~ s@\s*$::CGI_HOME$Directory/$file\s*\:\s*@@ig;
6279 chomp($Type);
6281 print "<li>";
6282 print "<a href='$Directory/$file'>";
6283 printf("%-40s", "$file</a>");
6284 print "\t$Size\t$Date\t$Type";
6285 print "</li>\n";
6288 print "</ul></pre>";
6290 return 1;
6294 ################################################
6296 # BrowseDirs(RootDirectory [, Pattern, Start])
6298 # usage:
6299 # <SCRIPT TYPE='text/ssperl'>
6300 # CGIscriptor::BrowseDirs('Sounds', '\.aifc$', 'Speech', 'DIRECTORY')
6301 # </SCRIPT>
6303 # Allows to browse subdirectories. Start should be relative to the RootDirectory,
6304 # e.g., the full path of the directory 'Speech' is '~/Sounds/Speech'.
6305 # Only files which fit /$Pattern/ and directories are displayed.
6306 # Directories down or up the directory tree are supplied with a
6307 # GET request with the name of the CGI variable in the fourth argument (default
6308 # is 'BROWSEDIRS'). So the correct call for a subdirectory could be:
6309 # CGIscriptor::BrowseDirs('Sounds', '\.aifc$', $DIRECTORY, 'DIRECTORY')
6311 sub BrowseDirs # (RootDirectory [, Pattern, Start, CGIvariable, HTTPserver]) -> Print HTML code
6313 my $RootDirectory = shift; # || return 0;
6314 my $Pattern = shift || '\S';
6315 my $Start = shift || "";
6316 my $CGIvariable = shift || "BROWSEDIRS";
6317 my $HTTPserver = shift || '';
6319 $Start = CGIscriptor::URLdecode($Start); # Sometimes, too much has been encoded
6320 $Start =~ s@//+@/@g;
6321 $Start =~ s@[^/]+/\.\.@@ig;
6322 $Start =~ s@^\.\.@@ig;
6323 $Start =~ s@/\.$@@ig;
6324 $Start =~ s!/+$!!g;
6325 $Start .= "/" if $Start;
6327 my @Directory = glob("$::CGI_HOME/$RootDirectory/$Start");
6328 $CurrentDirectory = shift(@Directory);
6329 $CurrentDirectory = $' if $CurrentDirectory =~ m@(/\.\./)+@;
6330 $CurrentDirectory =~ s@^$::CGI_HOME@@g;
6331 print "<h1>";
6332 print "$CurrentDirectory" if $CurrentDirectory;
6333 print "</h1>\n";
6334 opendir(BROWSE, "$::CGI_HOME/$RootDirectory/$Start") || main::dieHandler(31, "$::CGI_HOME/$RootDirectory/$Start $!");
6335 my @AllFiles = sort grep(!/^([\.]+[^\.]|\~)/, readdir(BROWSE));
6337 # Print directories
6338 my $file;
6339 print "<pre><ul TYPE='NONE'>\n";
6340 foreach $file (@AllFiles)
6342 next unless -d "$::CGI_HOME/$RootDirectory/$Start$file";
6343 # Check whether this file should be visible
6344 next if $::BlockPathAccess &&
6345 "/$RootDirectory/$Start$file/" =~ m@$::BlockPathAccess@;
6347 my $NewURL = $Start ? "$Start$file" : $file;
6348 $NewURL = CGIscriptor::URLencode($NewURL);
6349 print "<dt><a href='";
6350 print "$ENV{SCRIPT_NAME}" if $ENV{SCRIPT_NAME} !~ m@[^\w+\-/]@;
6351 print "$ENV{PATH_INFO}?$CGIvariable=$NewURL'>$file</a></dt>\n";
6353 print "</ul></pre>\n";
6355 # Print files
6356 print "<pre><ul TYPE='CIRCLE'>\n";
6357 my $TotalSize = 0;
6358 foreach $file (@AllFiles)
6360 next if $file =~ /^\./;
6361 next if -d "$::CGI_HOME/$RootDirectory/$Start$file";
6362 next if -l "$::CGI_HOME/$RootDirectory/$Start$file";
6363 # Check whether this file should be visible
6364 next if $::BlockPathAccess &&
6365 "$::CGI_HOME/$RootDirectory/$Start$file" =~ m@$::BlockPathAccess@;
6367 if($file =~ m@$Pattern@)
6369 my $Date = localtime($^T - (-M "$::CGI_HOME/$RootDirectory/$Start$file")*3600*24);
6370 my $Size = -s "$::CGI_HOME/$RootDirectory/$Start$file";
6371 $Size = sprintf("%6.0F kB", $Size/1024);
6372 my $Type = `file $::CGI_HOME/$RootDirectory/$Start$file`;
6373 $Type =~ s@\s*$::CGI_HOME/$RootDirectory/$Start$file\s*\:\s*@@ig;
6374 chomp($Type);
6376 print "<li>";
6377 if($HTTPserver =~ /^\s*[\.\~]\s*$/)
6379 print "<a href='$RootDirectory/$Start$file'>";
6381 elsif($HTTPserver)
6383 print "<a href='$HTTPserver/$RootDirectory/$Start$file'>";
6385 printf("%-40s", "$file</a>") if $HTTPserver;
6386 printf("%-40s", "$file") unless $HTTPserver;
6387 print "\t$Size\t$Date\t$Type";
6388 print "</li>\n";
6391 print "</ul></pre>";
6393 return 1;
6397 # ListDocs(Pattern [,ListType])
6399 # usage:
6400 # <SCRIPT TYPE=text/ssperl>
6401 # CGIscriptor::ListDocs("/*", "dl");
6402 # </SCRIPT>
6404 # This subroutine is very usefull to manage collections of independent
6405 # documents. The resulting list will display the tree-like directory
6406 # structure. If this routine is too slow for online use, you can
6407 # store the result and use a link to that stored file.
6409 # List HTML and Text files with title and first header (HTML)
6410 # or filename and first meaningfull line (general text files).
6411 # The listing starts at the ServerRoot directory. Directories are
6412 # listed recursively.
6414 # You can change the list type (default is dl).
6415 # e.g.,
6416 # <dt><a href=<file.html>>title</a>
6417 # <dd>First Header
6418 # <dt><a href=<file.txt>>file.txt</a>
6419 # <dd>First meaningfull line of text
6421 sub ListDocs # ($Pattern [, prefix]) e.g., ("/Books/*", [, "dl"])
6423 my $Pattern = shift;
6424 $Pattern =~ /\*/;
6425 my $ListType = shift || "dl";
6426 my $Prefix = lc($ListType) eq "dl" ? "dt" : "li";
6427 my $URL_root = "http://$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}";
6428 my @FileList = glob("$::CGI_HOME$Pattern");
6429 my ($FileName, $Path, $Link);
6431 # Print List markers
6432 print "<$ListType>\n";
6434 # Glob all files
6435 File: foreach $FileName (@FileList)
6437 # Check whether this file should be visible
6438 next if $::BlockPathAccess && $FileName =~ m@$::BlockPathAccess@;
6440 # Recursively list files in all directories
6441 if(-d $FileName)
6443 $FileName =~ m@([^/]*)$@;
6444 my $DirName = $1;
6445 print "<$Prefix>$DirName\n";
6446 $Pattern =~ m@([^/]*)$@;
6447 &ListDocs("$`$DirName/$1", $ListType);
6448 next;
6450 # Use textfiles
6451 elsif(-T "$FileName")
6453 open(TextFile, $FileName) || next;
6455 # Ignore all other file types
6456 else
6457 { next;};
6459 # Get file path for link
6460 $FileName =~ /$::CGI_HOME/;
6461 print "<$Prefix><a href=$URL_root$'>";
6462 # Initialize all variables
6463 my $Line = "";
6464 my $TitleFound = 0;
6465 my $Caption = "";
6466 my $Title = "";
6467 # Read file and step through
6468 while(<TextFile>)
6470 chop $_;
6471 $Line = $_;
6472 # HTML files
6473 if($FileName =~ /\.ht[a-zA-Z]*$/i)
6475 # Catch Title
6476 while(!$Title)
6478 if($Line =~ m@<title>([^<]*)</title>@i)
6480 $Title = $1;
6481 $Line = $';
6483 else
6485 $Line .= <TextFile> || goto Print;
6486 chop $Line;
6489 # Catch First Header
6490 while(!$Caption)
6492 if($Line =~ m@</h1>@i)
6494 $Caption = $`;
6495 $Line = $';
6496 $Caption =~ m@<h1>@i;
6497 $Caption = $';
6498 $Line = $`.$Caption.$Line;
6500 else
6502 $Line .= <TextFile> || goto Print;
6503 chop $Line;
6507 # Other text files
6508 else
6510 # Title equals file name
6511 $FileName =~ /([^\/]+)$/;
6512 $Title = $1;
6513 # Catch equals First Meaningfull line
6514 while(!$Caption)
6516 if($Line =~ /[A-Z]/ &&
6517 ($Line =~ /subject|title/i || $Line =~ /^[\w,\.\s\?\:]+$/)
6518 && $Line !~ /Newsgroup/ && $Line !~ /\:\s*$/)
6520 $Line =~ s/\<[^\>]+\>//g;
6521 $Caption = $Line;
6523 else
6525 $Line = <TextFile> || goto Print;
6529 Print: # Print title and subject
6530 print "$Title</a>\n";
6531 print "<dd>$Caption\n" if $ListType eq "dl";
6532 $TitleFound = 0;
6533 $Caption = "";
6534 close TextFile;
6535 next File;
6538 # Print Closing List Marker
6539 print "</$ListType>\n";
6540 ""; # Empty return value
6544 # HTMLdocTree(Pattern [,ListType])
6546 # usage:
6547 # <SCRIPT TYPE=text/ssperl>
6548 # CGIscriptor::HTMLdocTree("/Welcome.html", "dl");
6549 # </SCRIPT>
6551 # The following subroutine is very usefull for checking large document
6552 # trees. Starting from the root (s), it reads all files and prints out
6553 # a nested list of links to all attached files. Non-existing or misplaced
6554 # files are flagged. This is quite a file-i/o intensive routine
6555 # so you would not like it to be accessible to everyone. If you want to
6556 # use the result, save the whole resulting page to disk and use a link
6557 # to this file.
6559 # HTMLdocTree takes an HTML file or file pattern and constructs nested lists
6560 # with links to *local* files (i.e., only links to the local server are
6561 # followed). The list entries are the document titles.
6562 # If the list type is <dl>, the first <H1> header is used too.
6563 # For each file matching the pattern, a list is made recursively of all
6564 # HTML documents that are linked from it and are stored in the same directory
6565 # or a sub-directory. Warnings are given for missing files.
6566 # The listing starts for the ServerRoot directory.
6567 # You can change the default list type <dl> (<dl>, <ul>, <ol>).
6569 %LinkUsed = ();
6571 sub HTMLdocTree # ($Pattern [, listtype])
6572 # e.g., ("/Welcome.html", [, "ul"])
6574 my $Pattern = shift;
6575 my $ListType = shift || "dl";
6576 my $Prefix = lc($ListType) eq "dl" ? "dt" : "li";
6577 my $URL_root = "http://$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}";
6578 my ($Filename, $Path, $Link);
6579 my %LocalLinks = {};
6581 # Read files (glob them for expansion of wildcards)
6582 my @FileList = glob("$::CGI_HOME$Pattern");
6583 foreach $Path (@FileList)
6585 # Get URL_path
6586 $Path =~ /$::CGI_HOME/;
6587 my $URL_path = $';
6588 # Check whether this file should be visible
6589 next if $::BlockPathAccess && $URL_path =~ m@$::BlockPathAccess@;
6591 my $Title = $URL_path;
6592 my $Caption = "";
6593 # Current file should not be used again
6594 ++$LinkUsed{$URL_path};
6595 # Open HTML doc
6596 unless(open(TextFile, $Path))
6598 print "<$Prefix>$Title <blink>(not found)</blink><br>\n";
6599 next;
6601 while(<TextFile>)
6603 chop $_;
6604 $Line = $_;
6605 # Catch Title
6606 while($Line =~ m@<title>@i)
6608 if($Line =~ m@<title>([^<]*)</title>@i)
6610 $Title = $1;
6611 $Line = $';
6613 else
6615 $Line .= <TextFile>;
6616 chop $Line;
6619 # Catch First Header
6620 while(!$Caption && $Line =~ m@<h1>@i)
6622 if($Line =~ m@</h[1-9]>@i)
6624 $Caption = $`;
6625 $Line = $';
6626 $Caption =~ m@<h1>@i;
6627 $Caption = $';
6628 $Line = $`.$Caption.$Line;
6630 else
6632 $Line .= <TextFile>;
6633 chop $Line;
6636 # Catch and print Links
6637 while($Line =~ m@<a href\=([^>]*)>@i)
6639 $Link = $1;
6640 $Line = $';
6641 # Remove quotes
6642 $Link =~ s/\"//g;
6643 # Remove extras
6644 $Link =~ s/[\#\?].*$//g;
6645 # Remove Servername
6646 if($Link =~ m@(http://|^)@i)
6648 $Link = $';
6649 # Only build tree for current server
6650 next unless $Link =~ m@$::ENV{'SERVER_NAME'}|^/@;
6651 # Remove server name and port
6652 $Link =~ s@^[^\/]*@@g;
6654 # Store the current link
6655 next if $LinkUsed{$Link} || $Link eq $URL_path;
6656 ++$LinkUsed{$Link};
6657 ++$LocalLinks{$Link};
6661 close TextFile;
6662 print "<$Prefix>";
6663 print "<a href=http://";
6664 print "$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}$URL_path>";
6665 print "$Title</a>\n";
6666 print "<br>$Caption\n"
6667 if $Caption && $Caption ne $Title && $ListType =~ /dl/i;
6668 print "<$ListType>\n";
6669 foreach $Link (keys(%LocalLinks))
6671 &HTMLdocTree($Link, $ListType);
6673 print "</$ListType>\n";
6677 ###########################<<<<<<<<<<End Remove
6679 # Make require happy
6682 =head1 NAME
6684 CGIscriptor -
6686 =head1 DESCRIPTION
6688 A flexible HTML 4 compliant script/module for CGI-aware
6689 embeded Perl, shell-scripts, and other scripting languages,
6690 executed at the server side.
6692 =head1 README
6694 Executes embeded Perl code in HTML pages with easy
6695 access to CGI variables. Also processes embeded shell
6696 scripts and scripts in any other language with an
6697 interactive interpreter (e.g., in-line Python, Tcl,
6698 Ruby, Awk, Lisp, Xlispstat, Prolog, M4, R, REBOL, Praat,
6699 sh, bash, csh, ksh).
6701 CGIscriptor is very flexible and hides all the specifics
6702 and idiosyncrasies of correct output and CGI coding and naming.
6703 CGIscriptor complies with the W3C HTML 4.0 recommendations.
6705 This Perl program will run on any WWW server that runs
6706 Perl scripts, just add a line like the following to your
6707 srm.conf file (Apache example):
6709 ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
6711 URL's that refer to http://www.your.address/SHTML/... will
6712 now be handled by CGIscriptor.pl, which can use a private
6713 directory tree (default is the DOCUMENT_ROOT directory tree,
6714 but it can be anywhere).
6716 =head1 PREREQUISITES
6719 =head1 COREQUISITES
6722 =pod OSNAMES
6724 Linux, *BSD, *nix, MS WinXP
6726 =pod SCRIPT CATEGORIES
6728 Servers
6732 =cut