1 # Poor Man's CGI Module for Perl
3 # (c) 2002--2009 Martin Mares <mj@ucw.cz>
4 # Slightly modified by Tomas Valla <tom@ucw.cz>
6 # This software may be freely distributed and used according to the terms
7 # of the GNU Lesser General Public License.
10 # - respond with proper HTTP error codes
11 # - if we get invalid parameters, generate HTTP error or redirect
15 # First of all, set up error handling, so that even errors during parsing
16 # will be reported properly.
18 # Variables to be set by the calling module:
19 # $UCW::CGI::error_mail mail address of the script admin (optional)
20 # (this one has to be set in the BEGIN block!)
21 # $UCW::CGI::error_hook function to be called for reporting errors
29 if (!defined $error_reported) {
32 if (defined($UCW::CGI::error_hook)) {
33 &$UCW::CGI::error_hook($_[0]);
35 print "Content-type: text/plain\n\n";
36 print "Internal bug:\n";
38 print "Please notify $UCW::CGI::error_mail\n" if defined $UCW::CGI::error_mail;
45 $SIG{__DIE__} = sub { report_bug($_[0]); };
46 $SIG{__WARN__} = sub { report_bug("WARNING: " . $_[0]); };
59 our @ISA = qw(Exporter);
60 our @EXPORT = qw(&html_escape &url_escape &url_deescape &url_param_escape &url_param_deescape &self_ref &self_form &http_get);
61 our @EXPORT_OK = qw();
67 $x =~ s/([^-\$_.!*'(),0-9A-Za-z\x80-\xff])/"%".unpack('H2',$1)/ge;
73 $x =~ s/%(..)/pack("H2",$1)/ge;
77 sub url_param_escape($) {
84 sub url_param_deescape($) {
87 return url_deescape($x);
99 ### Analysing RFC 822 Style Headers ###
101 sub rfc822_prepare($) {
103 # Convert all %'s and backslash escapes to %xx escapes
105 $x =~ s/\\(.)/"%".unpack("H2",$1)/ge;
106 # Remove all comments, beware, they can be nested (unterminated comments are closed at EOL automatically)
107 while ($x =~ s/^(("[^"]*"|[^"(])*(\([^)]*)*)(\([^()]*(\)|$))/$1 /) { }
108 # Remove quotes and escape dangerous characters inside (again closing at the end automatically)
109 $x =~ s{"([^"]*)("|$)}{my $z=$1; $z =~ s/([^0-9a-zA-Z%_-])/"%".unpack("H2",$1)/ge; $z;}ge;
110 # All control characters are properly escaped, tokens are clearly visible.
111 # Finally remove all unnecessary spaces.
114 $x =~ s{\s*([()<>@,;:\\"/\[\]?=])\s*}{$1}g;
118 sub rfc822_deescape($) {
120 return url_deescape($x);
123 ### Reading of HTTP headers ###
128 return $ENV{"HTTP_$h"} || $ENV{"$h"};
131 ### Parsing of Arguments ###
136 sub parse_raw_args($) {
139 for $_ (split /[&:]/, $s) {
140 (/^([^=]+)=(.*)$/) or next;
144 s/%(..)/pack("H2",$1)/eg;
147 $raw_args{$arg} = $_;
151 sub parse_multipart_form_data();
154 if (!defined $ENV{"GATEWAY_INTERFACE"}) {
155 print STDERR "Must be called as a CGI script.\n";
160 my $method = $ENV{"REQUEST_METHOD"};
161 if (my $qs = $ENV{"QUERY_STRING"}) {
164 if ($method eq "GET") {
165 } elsif ($method eq "POST") {
166 if ($ENV{"CONTENT_TYPE"} =~ /^application\/x-www-form-urlencoded\b/i) {
171 } elsif ($ENV{"CONTENT_TYPE"} =~ /^multipart\/form-data\b/i) {
172 parse_multipart_form_data();
174 die "Unknown content type for POST data";
177 die "Unknown request method";
181 sub parse_args($) { # CAVEAT: attached files must be defined in the main arg table
183 if (!$main_arg_table) {
184 $main_arg_table = $args;
188 for my $a (values %$args) {
189 my $r = ref($a->{'var'});
190 defined($a->{'default'}) or $a->{'default'}="";
191 if ($r eq 'SCALAR') {
192 ${$a->{'var'}} = $a->{'default'};
193 } elsif ($r eq 'ARRAY') {
198 for my $a (values %$args) {
199 defined($raw_args{$a}) or next;
201 $a->{'multiline'} or s/(\n|\t)/ /g;
204 if (my $rx = $a->{'check'}) {
205 if (!/^$rx$/) { $_ = $a->{'default'}; }
210 if ($r eq 'SCALAR') {
212 } elsif ($r eq 'ARRAY') {
218 ### Parsing Multipart Form Data ###
224 my $mp_buffer_boundary;
227 sub refill_mp_data($) {
229 if ($mp_buffer_boundary >= $mp_buffer_i) {
230 return $mp_buffer_boundary - $mp_buffer_i;
231 } elsif ($mp_buffer_i + $more <= length($mp_buffer) - $boundary_len) {
235 $mp_buffer = substr($mp_buffer, $mp_buffer_i);
238 while ($mp_buffer_i + $more > length($mp_buffer) - $boundary_len) {
241 my $n = read(STDIN, $data, 2048);
248 $mp_buffer_boundary = index($mp_buffer, $boundary, $mp_buffer_i);
249 if ($mp_buffer_boundary >= 0) {
250 return $mp_buffer_boundary;
252 return length($mp_buffer);
254 return length($mp_buffer) - $boundary_len;
260 my ($allow_empty) = @_;
261 my $n = refill_mp_data(1024);
262 my $i = index($mp_buffer, "\r\n", $mp_buffer_i);
263 if ($i >= $mp_buffer_i && $i < $mp_buffer_i + $n - 1) {
264 my $s = substr($mp_buffer, $mp_buffer_i, $i - $mp_buffer_i);
265 $mp_buffer_i = $i + 2;
267 } elsif ($allow_empty) {
268 if ($n) { # An incomplete line
269 my $s = substr($mp_buffer, $mp_buffer_i, $n);
272 } else { # No more lines
276 die "Premature end of multipart POST data";
280 sub skip_mp_boundary() {
281 if ($mp_buffer_boundary != $mp_buffer_i) {
282 die "Premature end of multipart POST data";
284 $mp_buffer_boundary = -1;
286 my $b = get_mp_line(0);
287 print STDERR "SEP $b\n" if $debug;
288 $mp_buffer_boundary = index($mp_buffer, $boundary, $mp_buffer_i);
289 if (substr("\r\n$b", 0, $boundary_len) eq "$boundary--") {
296 sub parse_mp_header() {
299 while ((my $l = get_mp_line(0)) ne "") {
300 print STDERR "HH $l\n" if $debug;
301 if (my ($name, $value) = ($l =~ /([A-Za-z0-9-]+)\s*:\s*(.*)/)) {
302 $name =~ tr/A-Z/a-z/;
303 $h->{$name} = $value;
305 } elsif ($l =~ /^\s+/ && $last) {
311 foreach my $n (keys %$h) {
312 $h->{$n} = rfc822_prepare($h->{$n});
313 print STDERR "H $n: $h->{$n}\n" if $debug;
315 return (keys %$h) ? $h : undef;
318 sub parse_multipart_form_data() {
319 # First of all, find the boundary string
320 my $ct = rfc822_prepare($ENV{"CONTENT_TYPE"});
321 if (!(($boundary) = ($ct =~ /^.*;boundary=([^; ]+)/))) {
322 die "Multipart content with no boundary string received";
324 $boundary = rfc822_deescape($boundary);
325 print STDERR "BOUNDARY IS $boundary\n" if $debug;
327 # BUG: IE 3.01 on Macintosh forgets to add the "--" at the start of the boundary string
328 # as the MIME specs preach. Workaround borrowed from CGI.pm in Perl distribution.
329 my $agent = http_get("User-agent") || "";
330 $boundary = "--$boundary" unless $agent =~ /MSIE\s+3\.0[12];\s*Mac/;
331 $boundary = "\r\n$boundary";
332 $boundary_len = length($boundary) + 2;
334 # Check upload size in advance
335 if (my $size = http_get("Content-Length")) {
337 foreach my $a (values %$main_arg_table) {
338 $max_allowed += $a->{"maxsize"} || 65536;
340 if ($size > $max_allowed) {
341 die "Maximum form data length exceeded";
345 # Initialize our buffering mechanism and part splitter
348 $mp_buffer_boundary = -1;
351 # Skip garbage before the 1st part
352 while (my $i = refill_mp_data(256)) { $mp_buffer_i += $i; }
353 skip_mp_boundary() || return;
355 # Process individual parts
357 print STDERR "NEXT PART\n" if $debug;
358 my $h = parse_mp_header();
359 my ($field, $cdisp, $a);
361 ($cdisp = $h->{"content-disposition"}) &&
362 $cdisp =~ /^form-data/ &&
363 (($field) = ($cdisp =~ /;name=([^;]+)/)) &&
364 ($a = $main_arg_table->{"$field"})) {
365 print STDERR "FIELD $field\n" if $debug;
366 if (defined $h->{"content-transfer-encoding"}) { die "Unexpected Content-Transfer-Encoding"; }
367 if (defined $a->{"var"}) {
368 while (defined (my $l = get_mp_line(1))) {
369 print STDERR "VALUE $l\n" if $debug;
370 parse_raw_args("$field=$l");
373 } elsif (defined $a->{"file"}) {
376 my $max_size = $a->{"maxsize"} || 1048576;
377 my @tmpargs = (undef, UNLINK => 1);
378 push @tmpargs, DIR => $a->{"tmpdir"} if defined $a->{"tmpdir"};
379 my ($fh, $fn) = File::Temp::tempfile(@tmpargs);
380 print STDERR "FILE UPLOAD to $fn\n" if $debug;
381 ${$a->{"file"}} = $fn;
382 ${$a->{"fh"}} = $fh if defined $a->{"fh"};
384 while (my $i = refill_mp_data(4096)) {
385 print $fh substr($mp_buffer, $mp_buffer_i, $i);
388 if ($total_size > $max_size) { die "Uploaded file too long"; }
390 $fh->flush(); # Don't close the handle, the file would disappear otherwise
394 print STDERR "SKIPPING\n" if $debug;
395 while (my $i = refill_mp_data(256)) { $mp_buffer_i += $i; }
396 } } while (skip_mp_boundary());
399 ### Generating Self-ref URL's ###
401 sub make_out_args(@) { # Usage: make_out_args([arg_table, ...] name => value, ...)
402 my @arg_tables = ( $main_arg_table );
403 while (@_ && ref(@_) eq 'HASH') {
404 push @arg_tables, shift @_;
408 for my $table (@arg_tables) {
409 for my $name (keys %$table) {
410 my $arg = $table->{$name};
411 defined($arg->{'var'}) || next;
412 defined($arg->{'pass'}) && !$arg->{'pass'} && !exists $overrides{$name} && next;
414 if (!defined($value = $overrides{$name})) {
415 if (exists $overrides{$name}) {
416 $value = $arg->{'default'};
418 $value = ${$arg->{'var'}};
421 if ($value ne $arg->{'default'}) {
422 $out->{$name} = $value;
430 my $out = make_out_args(@_);
431 return "?" . join(':', map { "$_=" . url_param_escape($out->{$_}) } sort keys %$out);
435 my $out = make_out_args(@_);
436 return join('', map { "<input type=hidden name=$_ value='" . html_escape($out->{$_}) . "'>\n" } sort keys %$out);
441 sub set_cookie($$@) {
443 # Unfortunately, the support for the new cookie standard (RFC 2965) among
444 # web browsers is still very scarce, so we are still using the old Netscape
447 # Usage: set_cookie(name, value, option => value...), where options are:
449 # max-age maximal age in seconds
450 # domain domain name scope
451 # path path name scope
452 # secure if present, cookie applies only to SSL connections
453 # (in this case, the value should be undefined)
454 # discard if present with any value, the cookie is discarded
458 my $value = shift @_;
460 if (exists $other{'discard'}) {
461 delete $other{'discard'};
462 $other{'max-age'} = 0;
464 if (defined(my $age = $other{'max-age'})) {
465 delete $other{'max-age'};
466 my $exp = ($age ? (time + $age) : 0);
467 # Avoid problems with locales
468 my ($S,$M,$H,$d,$m,$y,$wd) = gmtime $exp;
469 my @wdays = ( 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' );
470 my @mons = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' );
471 $other{'expires'} = sprintf("%s, %02d-%s-%d %02d:%02d:%02d GMT",
472 $wdays[$wd], $d, $mons[$m], $y+1900, $H, $M, $S);
475 print "Set-Cookie: $key=", url_escape($value);
476 foreach my $k (keys %other) {
478 print "=", $other{$k} if defined $other{$k};
483 sub parse_cookies() {
484 my $h = http_get("Cookie") or return ();
486 foreach my $x (split /;\s*/, $h) {
487 my ($k,$v) = split /=/, $x;
488 $v = url_deescape($v) if defined $v;
489 push @cook, $k => $v;