1 # Poor Man's CGI Module for Perl
3 # (c) 2002--2007 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 ###
135 sub parse_arg_string($) {
138 foreach $_ (split /[&:]/,$s) {
139 (/^([^=]+)=(.*)$/) or next;
140 my $arg = $arg_table->{$1} or next;
143 s/%(..)/pack("H2",$1)/eg;
146 $arg->{'multiline'} || s/(\n|\t)/ /g;
149 if (my $rx = $arg->{'check'}) {
150 if (!/^$rx$/) { $_ = $arg->{'default'}; }
153 my $r = ref($arg->{'var'});
154 if ($r eq 'SCALAR') {
155 ${$arg->{'var'}} = $_;
156 } elsif ($r eq 'ARRAY') {
157 push @{$arg->{'var'}}, $_;
162 sub parse_multipart_form_data();
165 $arg_table = shift @_;
166 if (!defined $ENV{"GATEWAY_INTERFACE"}) {
167 print STDERR "Must be called as a CGI script.\n";
171 foreach my $a (values %$arg_table) {
172 my $r = ref($a->{'var'});
173 defined($a->{'default'}) or $a->{'default'}="";
174 if ($r eq 'SCALAR') {
175 ${$a->{'var'}} = $a->{'default'};
176 } elsif ($r eq 'ARRAY') {
180 my $method = $ENV{"REQUEST_METHOD"};
181 my $qs = $ENV{"QUERY_STRING"};
182 parse_arg_string($qs) if defined($qs);
183 if ($method eq "GET") {
184 } elsif ($method eq "POST") {
185 if ($ENV{"CONTENT_TYPE"} =~ /^application\/x-www-form-urlencoded\b/i) {
188 parse_arg_string($_);
190 } elsif ($ENV{"CONTENT_TYPE"} =~ /^multipart\/form-data\b/i) {
191 parse_multipart_form_data();
193 die "Unknown content type for POST data";
196 die "Unknown request method";
200 ### Parsing Multipart Form Data ###
206 my $mp_buffer_boundary;
209 sub refill_mp_data($) {
211 if ($mp_buffer_boundary >= $mp_buffer_i) {
212 return $mp_buffer_boundary - $mp_buffer_i;
213 } elsif ($mp_buffer_i + $more <= length($mp_buffer) - $boundary_len) {
217 $mp_buffer = substr($mp_buffer, $mp_buffer_i);
220 while ($mp_buffer_i + $more > length($mp_buffer) - $boundary_len) {
223 my $n = read(STDIN, $data, 2048);
230 $mp_buffer_boundary = index($mp_buffer, $boundary, $mp_buffer_i);
231 if ($mp_buffer_boundary >= 0) {
232 return $mp_buffer_boundary;
234 return length($mp_buffer);
236 return length($mp_buffer) - $boundary_len;
242 my ($allow_empty) = @_;
243 my $n = refill_mp_data(1024);
244 my $i = index($mp_buffer, "\r\n", $mp_buffer_i);
245 if ($i >= $mp_buffer_i && $i < $mp_buffer_i + $n - 1) {
246 my $s = substr($mp_buffer, $mp_buffer_i, $i - $mp_buffer_i);
247 $mp_buffer_i = $i + 2;
249 } elsif ($allow_empty) {
250 if ($n) { # An incomplete line
251 my $s = substr($mp_buffer, $mp_buffer_i, $n);
254 } else { # No more lines
258 die "Premature end of multipart POST data";
262 sub skip_mp_boundary() {
263 if ($mp_buffer_boundary != $mp_buffer_i) {
264 die "Premature end of multipart POST data";
266 $mp_buffer_boundary = -1;
268 my $b = get_mp_line(0);
269 print STDERR "SEP $b\n" if $debug;
270 $mp_buffer_boundary = index($mp_buffer, $boundary, $mp_buffer_i);
271 if ("\r\n$b" =~ /^$boundary--/) {
278 sub parse_mp_header() {
281 while ((my $l = get_mp_line(0)) ne "") {
282 print STDERR "HH $l\n" if $debug;
283 if (my ($name, $value) = ($l =~ /([A-Za-z0-9-]+)\s*:\s*(.*)/)) {
284 $name =~ tr/A-Z/a-z/;
285 $h->{$name} = $value;
287 } elsif ($l =~ /^\s+/ && $last) {
293 foreach my $n (keys %$h) {
294 $h->{$n} = rfc822_prepare($h->{$n});
295 print STDERR "H $n: $h->{$n}\n" if $debug;
297 return (keys %$h) ? $h : undef;
300 sub parse_multipart_form_data() {
301 # First of all, find the boundary string
302 my $ct = rfc822_prepare($ENV{"CONTENT_TYPE"});
303 if (!(($boundary) = ($ct =~ /^.*;boundary=([^; ]+)/))) {
304 die "Multipart content with no boundary string received";
306 $boundary = rfc822_deescape($boundary);
307 print STDERR "BOUNDARY IS $boundary\n" if $debug;
309 # BUG: IE 3.01 on Macintosh forgets to add the "--" at the start of the boundary string
310 # as the MIME specs preach. Workaround borrowed from CGI.pm in Perl distribution.
311 my $agent = http_get("User-agent") || "";
312 $boundary = "--$boundary" unless $agent =~ /MSIE\s+3\.0[12];\s*Mac/;
313 $boundary = "\r\n$boundary";
314 $boundary_len = length($boundary) + 2;
316 # Check upload size in advance
317 if (my $size = http_get("Content-Length")) {
319 foreach my $a (values %$arg_table) {
320 $max_allowed += $a->{"maxsize"} || 65536;
322 if ($size > $max_allowed) {
323 die "Maximum form data length exceeded";
327 # Initialize our buffering mechanism and part splitter
330 $mp_buffer_boundary = -1;
333 # Skip garbage before the 1st part
334 while (my $i = refill_mp_data(256)) { $mp_buffer_i += $i; }
335 skip_mp_boundary() || return;
337 # Process individual parts
339 print STDERR "NEXT PART\n" if $debug;
340 my $h = parse_mp_header();
341 my ($field, $cdisp, $a);
343 ($cdisp = $h->{"content-disposition"}) &&
344 $cdisp =~ /^form-data/ &&
345 (($field) = ($cdisp =~ /;name=([^;]+)/)) &&
346 ($a = $arg_table->{"$field"})) {
347 print STDERR "FIELD $field\n" if $debug;
348 if (defined $h->{"content-transfer-encoding"}) { die "Unexpected Content-Transfer-Encoding"; }
349 if (defined $a->{"var"}) {
350 while (defined (my $l = get_mp_line(1))) {
351 print STDERR "VALUE $l\n" if $debug;
352 parse_arg_string("$field=$l");
355 } elsif (defined $a->{"file"}) {
358 my $max_size = $a->{"maxsize"} || 1048576;
359 my @tmpargs = (undef, UNLINK => 1);
360 push @tmpargs, DIR => $a->{"tmpdir"} if defined $a->{"tmpdir"};
361 my ($fh, $fn) = File::Temp::tempfile(@tmpargs);
362 print STDERR "FILE UPLOAD to $fn\n" if $debug;
363 ${$a->{"file"}} = $fn;
364 ${$a->{"fh"}} = $fh if defined $a->{"fh"};
366 while (my $i = refill_mp_data(4096)) {
367 print $fh substr($mp_buffer, $mp_buffer_i, $i);
370 if ($total_size > $max_size) { die "Uploaded file too long"; }
372 $fh->flush(); # Don't close the handle, the file would disappear otherwise
376 print STDERR "SKIPPING\n" if $debug;
377 while (my $i = refill_mp_data(256)) { $mp_buffer_i += $i; }
378 } } while (skip_mp_boundary());
381 ### Generating Self-ref URL's ###
383 sub make_out_args($) {
384 my ($overrides) = @_;
386 foreach my $name (keys %$arg_table) {
387 my $arg = $arg_table->{$name};
388 defined($arg->{'var'}) || next;
389 defined($arg->{'pass'}) && !$arg->{'pass'} && !exists $overrides->{$name} && next;
391 if (!defined($value = $overrides->{$name})) {
392 if (exists $overrides->{$name}) {
393 $value = $arg->{'default'};
395 $value = ${$arg->{'var'}};
398 if ($value ne $arg->{'default'}) {
399 $out->{$name} = $value;
407 my $out = make_out_args(\%h);
408 return "?" . join(':', map { "$_=" . url_param_escape($out->{$_}) } sort keys %$out);
413 my $out = make_out_args(\%h);
414 return join('', map { "<input type=hidden name=$_ value='" . html_escape($out->{$_}) . "'>\n" } sort keys %$out);
421 if ($x !~ /^[a-zA-Z0-9%]+$/) {
422 $x =~ s/([\\\"])/\\$1/g;
428 sub set_cookie($$@) {
430 my $value = shift @_;
432 $other{'version'} = 1 unless defined $other{'version'};
433 print "Set-Cookie: $key=", cookie_esc($value);
434 foreach my $k (keys %other) {
435 print ";$k=", cookie_esc($other{$k});
440 sub parse_cookies() {
441 my $h = http_get("Cookie") or return ();
443 while (my ($padding,$name,$val,$xx,$rest) = ($h =~ /\s*([,;]\s*)*([^ =]+)=([^ =,;\"]*|\"([^\"\\]|\\.)*\")(\s.*|;.*|$)/)) {
447 $val =~ s/\\(.)/$1/g;
449 push @cook, $name, $val;