1 # Poor Man's CGI Module for Perl
3 # (c) 2002--2011 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.
16 our @ISA = qw(Exporter);
17 our @EXPORT = qw(&html_escape &url_escape &url_deescape &url_param_escape &url_param_deescape &self_ref &self_form &http_get);
18 our @EXPORT_OK = qw();
20 # Configuration settings
26 print join("\n", "Status: $err", "Content-Type: text/plain", @_, "", $err, "");
35 utf8::encode($x) if $utf8_mode;
36 $x =~ s/([^-\$_.!*'(),0-9A-Za-z\x80-\xff])/"%".unpack('H2',$1)/ge;
37 utf8::decode($x) if $utf8_mode;
44 utf8::encode($x) if $utf8_mode;
45 $x =~ s/%(..)/pack("H2",$1)/ge;
46 utf8::decode($x) if $utf8_mode;
50 sub url_param_escape($) {
58 sub url_param_deescape($) {
62 return url_deescape($x);
76 ### Analysing RFC 822 Style Headers ###
78 sub rfc822_prepare($) {
80 # Convert all %'s and backslash escapes to %xx escapes
82 $x =~ s/\\(.)/"%".unpack("H2",$1)/ge;
83 # Remove all comments, beware, they can be nested (unterminated comments are closed at EOL automatically)
84 while ($x =~ s/^(("[^"]*"|[^"(])*(\([^)]*)*)(\([^()]*(\)|$))/$1 /) { }
85 # Remove quotes and escape dangerous characters inside (again closing at the end automatically)
86 $x =~ s{"([^"]*)("|$)}{my $z=$1; $z =~ s/([^0-9a-zA-Z%_-])/"%".unpack("H2",$1)/ge; $z;}ge;
87 # All control characters are properly escaped, tokens are clearly visible.
88 # Finally remove all unnecessary spaces.
91 $x =~ s{\s*([()<>@,;:\\"/\[\]?=])\s*}{$1}g;
95 sub rfc822_deescape($) {
97 return url_deescape($x);
100 ### Reading of HTTP headers ###
105 return $ENV{"HTTP_$h"} // $ENV{"$h"};
108 ### Parsing of Arguments ###
113 sub parse_raw_args_ll($$) {
117 utf8::decode($s) if $utf8_mode;
118 push @{$raw_args{$arg}}, $s;
121 sub parse_raw_args($) {
124 for $_ (split /[&:]/, $s) {
125 (/^([^=]+)=(.*)$/) or next;
129 s/%(..)/pack("H2",$1)/eg;
130 parse_raw_args_ll($arg, $_);
134 sub parse_multipart_form_data();
137 if (!defined $ENV{"GATEWAY_INTERFACE"}) {
138 print STDERR "Must be called as a CGI script.\n";
139 $UCW::CGI::ErrorHandler::exit_code = 1;
143 my $method = $ENV{"REQUEST_METHOD"};
144 if (my $qs = $ENV{"QUERY_STRING"}) {
147 if ($method eq "GET" || $method eq "HEAD") {
148 } elsif ($method eq "POST") {
149 my $content_type = $ENV{"CONTENT_TYPE"} // "";
150 if ($content_type =~ /^application\/x-www-form-urlencoded\b/i) {
155 } elsif ($content_type =~ /^multipart\/form-data\b/i) {
156 parse_multipart_form_data();
158 http_error "415 Unsupported Media Type";
162 http_error "405 Method Not Allowed", "Allow: GET, HEAD, POST";
166 sub parse_args($) { # CAVEAT: attached files must be defined in the main arg table
168 if (!$main_arg_table) {
169 $main_arg_table = $args;
173 for my $a (values %$args) {
174 my $r = ref($a->{'var'});
175 $a->{'default'} //= '';
176 if ($r eq 'SCALAR') {
177 ${$a->{'var'}} = $a->{'default'};
178 } elsif ($r eq 'ARRAY') {
183 for my $arg (keys %$args) {
184 my $a = $args->{$arg};
185 defined($raw_args{$arg}) or next;
186 for (@{$raw_args{$arg}}) {
187 $a->{'multiline'} or s/(\n|\t)/ /g;
190 if (my $rx = $a->{'check'}) {
191 if (!/^$rx$/) { $_ = $a->{'default'}; }
196 if ($r eq 'SCALAR') {
198 } elsif ($r eq 'ARRAY') {
205 ### Parsing Multipart Form Data ###
211 my $mp_buffer_boundary;
214 sub refill_mp_data($) {
216 if ($mp_buffer_boundary >= $mp_buffer_i) {
217 return $mp_buffer_boundary - $mp_buffer_i;
218 } elsif ($mp_buffer_i + $more <= length($mp_buffer) - $boundary_len) {
222 $mp_buffer = substr($mp_buffer, $mp_buffer_i);
225 while ($mp_buffer_i + $more > length($mp_buffer) - $boundary_len) {
228 my $n = read(STDIN, $data, 2048);
235 $mp_buffer_boundary = index($mp_buffer, $boundary, $mp_buffer_i);
236 if ($mp_buffer_boundary >= 0) {
237 return $mp_buffer_boundary;
239 return length($mp_buffer);
241 return length($mp_buffer) - $boundary_len;
247 my ($allow_empty) = @_;
248 my $n = refill_mp_data(1024);
249 my $i = index($mp_buffer, "\r\n", $mp_buffer_i);
250 if ($i >= $mp_buffer_i && $i < $mp_buffer_i + $n - 1) {
251 my $s = substr($mp_buffer, $mp_buffer_i, $i - $mp_buffer_i);
252 $mp_buffer_i = $i + 2;
254 } elsif ($allow_empty) {
255 if ($n) { # An incomplete line
256 my $s = substr($mp_buffer, $mp_buffer_i, $n);
259 } else { # No more lines
263 http_error "400 Bad Request: Premature end of multipart POST data";
267 sub skip_mp_boundary() {
268 if ($mp_buffer_boundary != $mp_buffer_i) {
269 http_error "400 Bad Request: Premature end of multipart POST data";
271 $mp_buffer_boundary = -1;
273 my $b = get_mp_line(0);
274 print STDERR "SEP $b\n" if $debug;
275 $mp_buffer_boundary = index($mp_buffer, $boundary, $mp_buffer_i);
276 if (substr("\r\n$b", 0, $boundary_len) eq "$boundary--") {
283 sub parse_mp_header() {
286 while ((my $l = get_mp_line(0)) ne "") {
287 print STDERR "HH $l\n" if $debug;
288 if (my ($name, $value) = ($l =~ /([A-Za-z0-9-]+)\s*:\s*(.*)/)) {
289 $name =~ tr/A-Z/a-z/;
290 $h->{$name} = $value;
292 } elsif ($l =~ /^\s+/ && $last) {
298 foreach my $n (keys %$h) {
299 $h->{$n} = rfc822_prepare($h->{$n});
300 print STDERR "H $n: $h->{$n}\n" if $debug;
302 return (keys %$h) ? $h : undef;
305 sub parse_multipart_form_data() {
306 # First of all, find the boundary string
307 my $ct = rfc822_prepare($ENV{"CONTENT_TYPE"});
308 if (!(($boundary) = ($ct =~ /^.*;\s*boundary=([^; ]+)/))) {
309 http_error "400 Bad Request: Multipart content with no boundary string received";
311 $boundary = rfc822_deescape($boundary);
312 print STDERR "BOUNDARY IS $boundary\n" if $debug;
314 # BUG: IE 3.01 on Macintosh forgets to add the "--" at the start of the boundary string
315 # as the MIME specs preach. Workaround borrowed from CGI.pm in Perl distribution.
316 my $agent = http_get("User-Agent") // "";
317 $boundary = "--$boundary" unless $agent =~ /MSIE\s+3\.0[12];\s*Mac/;
318 $boundary = "\r\n$boundary";
319 $boundary_len = length($boundary) + 2;
321 # Check upload size in advance
322 if (my $size = http_get("Content-Length")) {
324 foreach my $a (values %$main_arg_table) {
325 $max_allowed += $a->{"maxsize"} || 65536;
327 if ($size > $max_allowed) {
328 http_error "413 Request Entity Too Large";
332 # Initialize our buffering mechanism and part splitter
335 $mp_buffer_boundary = -1;
338 # Skip garbage before the 1st part
339 while (my $i = refill_mp_data(256)) { $mp_buffer_i += $i; }
340 skip_mp_boundary() || return;
342 # Process individual parts
344 print STDERR "NEXT PART\n" if $debug;
345 my $h = parse_mp_header();
346 my ($field, $cdisp, $a);
348 ($cdisp = $h->{"content-disposition"}) &&
349 $cdisp =~ /^form-data/ &&
350 (($field) = ($cdisp =~ /;name=([^;]+)/)) &&
351 ($a = $main_arg_table->{"$field"})) {
352 print STDERR "FIELD $field\n" if $debug;
353 if (defined $h->{"content-transfer-encoding"}) {
354 http_error "400 Bad Request: Unexpected Content-Transfer-Encoding";
356 if (defined $a->{"var"}) {
357 while (defined (my $l = get_mp_line(1))) {
358 print STDERR "VALUE $l\n" if $debug;
359 parse_raw_args_ll($field, $l);
362 } elsif (defined $a->{"file"}) {
365 my $max_size = $a->{"maxsize"} || 1048576;
366 my @tmpargs = (undef, UNLINK => 1);
367 push @tmpargs, DIR => $a->{"tmpdir"} if defined $a->{"tmpdir"};
368 my ($fh, $fn) = File::Temp::tempfile(@tmpargs);
369 print STDERR "FILE UPLOAD to $fn\n" if $debug;
370 ${$a->{"file"}} = $fn;
371 ${$a->{"fh"}} = $fh if defined $a->{"fh"};
373 while (my $i = refill_mp_data(4096)) {
374 print $fh substr($mp_buffer, $mp_buffer_i, $i);
377 if ($total_size > $max_size) { http_error "413 Request Entity Too Large"; }
379 $fh->flush(); # Don't close the handle, the file would disappear otherwise
383 print STDERR "SKIPPING\n" if $debug;
384 while (my $i = refill_mp_data(256)) { $mp_buffer_i += $i; }
385 } } while (skip_mp_boundary());
388 ### Generating Self-ref URL's ###
390 sub make_out_args(@) { # Usage: make_out_args([arg_table, ...] name => value, ...)
391 my @arg_tables = ( $main_arg_table );
392 while (@_ && ref($_[0]) eq 'HASH') {
393 push @arg_tables, shift @_;
397 for my $table (@arg_tables) {
398 for my $name (keys %$table) {
399 my $arg = $table->{$name};
400 defined($arg->{'var'}) || next;
401 defined($arg->{'pass'}) && !$arg->{'pass'} && !exists $overrides{$name} && next;
402 defined $arg->{'default'} or $arg->{'default'} = "";
404 if (!defined($value = $overrides{$name})) {
405 if (exists $overrides{$name}) {
406 $value = $arg->{'default'};
408 $value = ${$arg->{'var'}};
409 defined $value or $value = $arg->{'default'};
412 if ($value ne $arg->{'default'}) {
413 $out->{$name} = $value;
421 my $out = make_out_args(@_);
422 return "?" . join(':', map { "$_=" . url_param_escape($out->{$_}) } sort keys %$out);
426 my $out = make_out_args(@_);
427 return join('', map { "<input type=hidden name=$_ value='" . html_escape($out->{$_}) . "'>\n" } sort keys %$out);
432 sub set_cookie($$@) {
434 # Unfortunately, the support for the new cookie standard (RFC 2965) among
435 # web browsers is still very scarce, so we are still using the old Netscape
438 # Usage: set_cookie(name, value, option => value...), where options are:
440 # max-age maximal age in seconds
441 # domain domain name scope
442 # path path name scope
443 # secure if present, cookie applies only to SSL connections
444 # (in this case, the value should be undefined)
445 # discard if present with any value, the cookie is discarded
449 my $value = shift @_;
451 if (exists $other{'discard'}) {
452 delete $other{'discard'};
453 $other{'max-age'} = 0;
455 if (defined(my $age = $other{'max-age'})) {
456 delete $other{'max-age'};
457 my $exp = ($age ? (time + $age) : 0);
458 # Avoid problems with locales
459 my ($S,$M,$H,$d,$m,$y,$wd) = gmtime $exp;
460 my @wdays = ( 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' );
461 my @mons = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' );
462 $other{'expires'} = sprintf("%s, %02d-%s-%d %02d:%02d:%02d GMT",
463 $wdays[$wd], $d, $mons[$m], $y+1900, $H, $M, $S);
466 print "Set-Cookie: $key=", url_escape($value);
467 foreach my $k (keys %other) {
469 print "=", $other{$k} if defined $other{$k};
474 sub parse_cookies() {
475 my $h = http_get("Cookie") or return ();
477 foreach my $x (split /;\s*/, $h) {
478 my ($k,$v) = split /=/, $x;
479 $v = url_deescape($v) if defined $v;
480 push @cook, $k => $v;