1 # Poor Man's CGI Module for Perl
3 # (c) 2002--2010 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);
100 ### Analysing RFC 822 Style Headers ###
102 sub rfc822_prepare($) {
104 # Convert all %'s and backslash escapes to %xx escapes
106 $x =~ s/\\(.)/"%".unpack("H2",$1)/ge;
107 # Remove all comments, beware, they can be nested (unterminated comments are closed at EOL automatically)
108 while ($x =~ s/^(("[^"]*"|[^"(])*(\([^)]*)*)(\([^()]*(\)|$))/$1 /) { }
109 # Remove quotes and escape dangerous characters inside (again closing at the end automatically)
110 $x =~ s{"([^"]*)("|$)}{my $z=$1; $z =~ s/([^0-9a-zA-Z%_-])/"%".unpack("H2",$1)/ge; $z;}ge;
111 # All control characters are properly escaped, tokens are clearly visible.
112 # Finally remove all unnecessary spaces.
115 $x =~ s{\s*([()<>@,;:\\"/\[\]?=])\s*}{$1}g;
119 sub rfc822_deescape($) {
121 return url_deescape($x);
124 ### Reading of HTTP headers ###
129 return $ENV{"HTTP_$h"} || $ENV{"$h"};
132 ### Parsing of Arguments ###
137 sub parse_raw_args($) {
140 for $_ (split /[&:]/, $s) {
141 (/^([^=]+)=(.*)$/) or next;
145 s/%(..)/pack("H2",$1)/eg;
148 $raw_args{$arg} = $_;
152 sub parse_multipart_form_data();
155 if (!defined $ENV{"GATEWAY_INTERFACE"}) {
156 print STDERR "Must be called as a CGI script.\n";
161 my $method = $ENV{"REQUEST_METHOD"};
162 if (my $qs = $ENV{"QUERY_STRING"}) {
165 if ($method eq "GET") {
166 } elsif ($method eq "POST") {
167 if ($ENV{"CONTENT_TYPE"} =~ /^application\/x-www-form-urlencoded\b/i) {
172 } elsif ($ENV{"CONTENT_TYPE"} =~ /^multipart\/form-data\b/i) {
173 parse_multipart_form_data();
175 die "Unknown content type for POST data";
178 die "Unknown request method";
182 sub parse_args($) { # CAVEAT: attached files must be defined in the main arg table
184 if (!$main_arg_table) {
185 $main_arg_table = $args;
189 for my $a (values %$args) {
190 my $r = ref($a->{'var'});
191 defined($a->{'default'}) or $a->{'default'}="";
192 if ($r eq 'SCALAR') {
193 ${$a->{'var'}} = $a->{'default'};
194 } elsif ($r eq 'ARRAY') {
199 for my $a (values %$args) {
200 defined($raw_args{$a}) or next;
202 $a->{'multiline'} or s/(\n|\t)/ /g;
205 if (my $rx = $a->{'check'}) {
206 if (!/^$rx$/) { $_ = $a->{'default'}; }
211 if ($r eq 'SCALAR') {
213 } elsif ($r eq 'ARRAY') {
219 ### Parsing Multipart Form Data ###
225 my $mp_buffer_boundary;
228 sub refill_mp_data($) {
230 if ($mp_buffer_boundary >= $mp_buffer_i) {
231 return $mp_buffer_boundary - $mp_buffer_i;
232 } elsif ($mp_buffer_i + $more <= length($mp_buffer) - $boundary_len) {
236 $mp_buffer = substr($mp_buffer, $mp_buffer_i);
239 while ($mp_buffer_i + $more > length($mp_buffer) - $boundary_len) {
242 my $n = read(STDIN, $data, 2048);
249 $mp_buffer_boundary = index($mp_buffer, $boundary, $mp_buffer_i);
250 if ($mp_buffer_boundary >= 0) {
251 return $mp_buffer_boundary;
253 return length($mp_buffer);
255 return length($mp_buffer) - $boundary_len;
261 my ($allow_empty) = @_;
262 my $n = refill_mp_data(1024);
263 my $i = index($mp_buffer, "\r\n", $mp_buffer_i);
264 if ($i >= $mp_buffer_i && $i < $mp_buffer_i + $n - 1) {
265 my $s = substr($mp_buffer, $mp_buffer_i, $i - $mp_buffer_i);
266 $mp_buffer_i = $i + 2;
268 } elsif ($allow_empty) {
269 if ($n) { # An incomplete line
270 my $s = substr($mp_buffer, $mp_buffer_i, $n);
273 } else { # No more lines
277 die "Premature end of multipart POST data";
281 sub skip_mp_boundary() {
282 if ($mp_buffer_boundary != $mp_buffer_i) {
283 die "Premature end of multipart POST data";
285 $mp_buffer_boundary = -1;
287 my $b = get_mp_line(0);
288 print STDERR "SEP $b\n" if $debug;
289 $mp_buffer_boundary = index($mp_buffer, $boundary, $mp_buffer_i);
290 if (substr("\r\n$b", 0, $boundary_len) eq "$boundary--") {
297 sub parse_mp_header() {
300 while ((my $l = get_mp_line(0)) ne "") {
301 print STDERR "HH $l\n" if $debug;
302 if (my ($name, $value) = ($l =~ /([A-Za-z0-9-]+)\s*:\s*(.*)/)) {
303 $name =~ tr/A-Z/a-z/;
304 $h->{$name} = $value;
306 } elsif ($l =~ /^\s+/ && $last) {
312 foreach my $n (keys %$h) {
313 $h->{$n} = rfc822_prepare($h->{$n});
314 print STDERR "H $n: $h->{$n}\n" if $debug;
316 return (keys %$h) ? $h : undef;
319 sub parse_multipart_form_data() {
320 # First of all, find the boundary string
321 my $ct = rfc822_prepare($ENV{"CONTENT_TYPE"});
322 if (!(($boundary) = ($ct =~ /^.*;boundary=([^; ]+)/))) {
323 die "Multipart content with no boundary string received";
325 $boundary = rfc822_deescape($boundary);
326 print STDERR "BOUNDARY IS $boundary\n" if $debug;
328 # BUG: IE 3.01 on Macintosh forgets to add the "--" at the start of the boundary string
329 # as the MIME specs preach. Workaround borrowed from CGI.pm in Perl distribution.
330 my $agent = http_get("User-agent") || "";
331 $boundary = "--$boundary" unless $agent =~ /MSIE\s+3\.0[12];\s*Mac/;
332 $boundary = "\r\n$boundary";
333 $boundary_len = length($boundary) + 2;
335 # Check upload size in advance
336 if (my $size = http_get("Content-Length")) {
338 foreach my $a (values %$main_arg_table) {
339 $max_allowed += $a->{"maxsize"} || 65536;
341 if ($size > $max_allowed) {
342 die "Maximum form data length exceeded";
346 # Initialize our buffering mechanism and part splitter
349 $mp_buffer_boundary = -1;
352 # Skip garbage before the 1st part
353 while (my $i = refill_mp_data(256)) { $mp_buffer_i += $i; }
354 skip_mp_boundary() || return;
356 # Process individual parts
358 print STDERR "NEXT PART\n" if $debug;
359 my $h = parse_mp_header();
360 my ($field, $cdisp, $a);
362 ($cdisp = $h->{"content-disposition"}) &&
363 $cdisp =~ /^form-data/ &&
364 (($field) = ($cdisp =~ /;name=([^;]+)/)) &&
365 ($a = $main_arg_table->{"$field"})) {
366 print STDERR "FIELD $field\n" if $debug;
367 if (defined $h->{"content-transfer-encoding"}) { die "Unexpected Content-Transfer-Encoding"; }
368 if (defined $a->{"var"}) {
369 while (defined (my $l = get_mp_line(1))) {
370 print STDERR "VALUE $l\n" if $debug;
371 parse_raw_args("$field=$l");
374 } elsif (defined $a->{"file"}) {
377 my $max_size = $a->{"maxsize"} || 1048576;
378 my @tmpargs = (undef, UNLINK => 1);
379 push @tmpargs, DIR => $a->{"tmpdir"} if defined $a->{"tmpdir"};
380 my ($fh, $fn) = File::Temp::tempfile(@tmpargs);
381 print STDERR "FILE UPLOAD to $fn\n" if $debug;
382 ${$a->{"file"}} = $fn;
383 ${$a->{"fh"}} = $fh if defined $a->{"fh"};
385 while (my $i = refill_mp_data(4096)) {
386 print $fh substr($mp_buffer, $mp_buffer_i, $i);
389 if ($total_size > $max_size) { die "Uploaded file too long"; }
391 $fh->flush(); # Don't close the handle, the file would disappear otherwise
395 print STDERR "SKIPPING\n" if $debug;
396 while (my $i = refill_mp_data(256)) { $mp_buffer_i += $i; }
397 } } while (skip_mp_boundary());
400 ### Generating Self-ref URL's ###
402 sub make_out_args(@) { # Usage: make_out_args([arg_table, ...] name => value, ...)
403 my @arg_tables = ( $main_arg_table );
404 while (@_ && ref(@_) eq 'HASH') {
405 push @arg_tables, shift @_;
409 for my $table (@arg_tables) {
410 for my $name (keys %$table) {
411 my $arg = $table->{$name};
412 defined($arg->{'var'}) || next;
413 defined($arg->{'pass'}) && !$arg->{'pass'} && !exists $overrides{$name} && next;
415 if (!defined($value = $overrides{$name})) {
416 if (exists $overrides{$name}) {
417 $value = $arg->{'default'};
419 $value = ${$arg->{'var'}};
422 if ($value ne $arg->{'default'}) {
423 $out->{$name} = $value;
431 my $out = make_out_args(@_);
432 return "?" . join(':', map { "$_=" . url_param_escape($out->{$_}) } sort keys %$out);
436 my $out = make_out_args(@_);
437 return join('', map { "<input type=hidden name=$_ value='" . html_escape($out->{$_}) . "'>\n" } sort keys %$out);
442 sub set_cookie($$@) {
444 # Unfortunately, the support for the new cookie standard (RFC 2965) among
445 # web browsers is still very scarce, so we are still using the old Netscape
448 # Usage: set_cookie(name, value, option => value...), where options are:
450 # max-age maximal age in seconds
451 # domain domain name scope
452 # path path name scope
453 # secure if present, cookie applies only to SSL connections
454 # (in this case, the value should be undefined)
455 # discard if present with any value, the cookie is discarded
459 my $value = shift @_;
461 if (exists $other{'discard'}) {
462 delete $other{'discard'};
463 $other{'max-age'} = 0;
465 if (defined(my $age = $other{'max-age'})) {
466 delete $other{'max-age'};
467 my $exp = ($age ? (time + $age) : 0);
468 # Avoid problems with locales
469 my ($S,$M,$H,$d,$m,$y,$wd) = gmtime $exp;
470 my @wdays = ( 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' );
471 my @mons = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' );
472 $other{'expires'} = sprintf("%s, %02d-%s-%d %02d:%02d:%02d GMT",
473 $wdays[$wd], $d, $mons[$m], $y+1900, $H, $M, $S);
476 print "Set-Cookie: $key=", url_escape($value);
477 foreach my $k (keys %other) {
479 print "=", $other{$k} if defined $other{$k};
484 sub parse_cookies() {
485 my $h = http_get("Cookie") or return ();
487 foreach my $x (split /;\s*/, $h) {
488 my ($k,$v) = split /=/, $x;
489 $v = url_deescape($v) if defined $v;
490 push @cook, $k => $v;