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.
15 # The somewhat hairy Perl export mechanism
17 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
20 @EXPORT = qw(&html_escape &url_escape &url_param_escape &self_ref &self_form);
29 $x =~ s/([^-\$_.!*'(),0-9A-Za-z\x80-\xff])/"%".unpack('H2',$1)/ge;
33 sub url_param_escape($) {
49 ### Analysing RFC 822 Style Headers ###
51 sub rfc822_prepare($) {
53 # Convert all %'s and backslash escapes to %xx escapes
55 $x =~ s/\\(.)/"%".unpack("H2",$1)/ge;
56 # Remove all comments, beware, they can be nested (unterminated comments are closed at EOL automatically)
57 while ($x =~ s/^(("[^"]*"|[^"(])*(\([^)]*)*)(\([^()]*(\)|$))/$1 /) { }
58 # Remove quotes and escape dangerous characters inside (again closing at the end automatically)
59 $x =~ s{"([^"]*)("|$)}{my $z=$1; $z =~ s/([^0-9a-zA-Z%_-])/"%".unpack("H2",$1)/ge; $z;}ge;
60 # All control characters are properly escaped, tokens are clearly visible.
61 # Finally remove all unnecessary spaces.
64 $x =~ s{\s*([()<>@,;:\\"/\[\]?=])\s*}{$1}g;
68 sub rfc822_deescape($) {
70 $x =~ s/%(..)/pack("H2",$1)/ge;
74 ### Reading of HTTP headers ###
79 return $ENV{"HTTP_$h"} || $ENV{"$h"};
82 ### Parsing of Arguments ###
86 sub parse_arg_string($) {
89 foreach $_ (split /[&:]/,$s) {
90 (/^([^=]+)=(.*)$/) or next;
91 my $arg = $arg_table->{$1} or next;
94 s/%(..)/pack("H2",$1)/eg;
97 $arg->{'multiline'} || s/(\n|\t)/ /g;
100 if (my $rx = $arg->{'check'}) {
101 if (!/^$rx$/) { $_ = $arg->{'default'}; }
104 my $r = ref($arg->{'var'});
105 if ($r eq 'SCALAR') {
106 ${$arg->{'var'}} = $_;
107 } elsif ($r eq 'ARRAY') {
108 push @{$arg->{'var'}}, $_;
113 sub parse_multipart_form_data();
116 $arg_table = shift @_;
117 if (!defined $ENV{"GATEWAY_INTERFACE"}) {
118 print STDERR "Must be called as a CGI script.\n";
122 foreach my $a (values %$arg_table) {
123 my $r = ref($a->{'var'});
124 defined($a->{'default'}) or $a->{'default'}="";
125 if ($r eq 'SCALAR') {
126 ${$a->{'var'}} = $a->{'default'};
127 } elsif ($r eq 'ARRAY') {
131 my $method = $ENV{"REQUEST_METHOD"};
132 my $qs = $ENV{"QUERY_STRING"};
133 parse_arg_string($qs) if defined($qs);
134 if ($method eq "GET") {
135 } elsif ($method eq "POST") {
136 if ($ENV{"CONTENT_TYPE"} =~ /^application\/x-www-form-urlencoded\b/i) {
139 parse_arg_string($_);
141 } elsif ($ENV{"CONTENT_TYPE"} =~ /^multipart\/form-data\b/i) {
142 parse_multipart_form_data();
144 die "Unknown content type for POST data";
147 die "Unknown request method";
151 ### Parsing Multipart Form Data ###
157 my $mp_buffer_boundary;
160 sub refill_mp_data($) {
162 if ($mp_buffer_boundary >= $mp_buffer_i) {
163 return $mp_buffer_boundary - $mp_buffer_i;
164 } elsif ($mp_buffer_i + $more <= length($mp_buffer) - $boundary_len) {
168 $mp_buffer = substr($mp_buffer, $mp_buffer_i);
171 while ($mp_buffer_i + $more > length($mp_buffer) - $boundary_len) {
174 my $n = read(STDIN, $data, 2048);
181 $mp_buffer_boundary = index($mp_buffer, $boundary, $mp_buffer_i);
182 if ($mp_buffer_boundary >= 0) {
183 return $mp_buffer_boundary;
185 return length($mp_buffer);
187 return length($mp_buffer) - $boundary_len;
193 my ($allow_empty) = @_;
194 my $n = refill_mp_data(1024);
195 my $i = index($mp_buffer, "\r\n", $mp_buffer_i);
196 if ($i >= $mp_buffer_i && $i < $mp_buffer_i + $n - 1) {
197 my $s = substr($mp_buffer, $mp_buffer_i, $i - $mp_buffer_i);
198 $mp_buffer_i = $i + 2;
200 } elsif ($allow_empty) {
201 if ($n) { # An incomplete line
202 my $s = substr($mp_buffer, $mp_buffer_i, $n);
205 } else { # No more lines
209 die "Premature end of multipart POST data";
213 sub skip_mp_boundary() {
214 if ($mp_buffer_boundary != $mp_buffer_i) {
215 die "Premature end of multipart POST data";
217 $mp_buffer_boundary = -1;
219 my $b = get_mp_line(0);
220 print STDERR "SEP $b\n" if $debug;
221 $mp_buffer_boundary = index($mp_buffer, $boundary, $mp_buffer_i);
222 if ("\r\n$b" =~ /^$boundary--/) {
229 sub parse_mp_header() {
232 while ((my $l = get_mp_line(0)) ne "") {
233 print STDERR "HH $l\n" if $debug;
234 if (my ($name, $value) = ($l =~ /([A-Za-z0-9-]+)\s*:\s*(.*)/)) {
235 $name =~ tr/A-Z/a-z/;
236 $h->{$name} = $value;
238 } elsif ($l =~ /^\s+/ && $last) {
244 foreach my $n (keys %$h) {
245 $h->{$n} = rfc822_prepare($h->{$n});
246 print STDERR "H $n: $h->{$n}\n" if $debug;
248 return (keys %$h) ? $h : undef;
251 sub parse_multipart_form_data() {
252 # First of all, find the boundary string
253 my $ct = rfc822_prepare($ENV{"CONTENT_TYPE"});
254 if (!(($boundary) = ($ct =~ /^.*;boundary=([^; ]+)/))) {
255 die "Multipart content with no boundary string received";
257 $boundary = rfc822_deescape($boundary);
258 print STDERR "BOUNDARY IS $boundary\n" if $debug;
260 # BUG: IE 3.01 on Macintosh forgets to add the "--" at the start of the boundary string
261 # as the MIME specs preach. Workaround borrowed from CGI.pm in Perl distribution.
262 my $agent = http_get("User-agent") || "";
263 $boundary = "--$boundary" unless $agent =~ /MSIE\s+3\.0[12];\s*Mac/;
264 $boundary = "\r\n$boundary";
265 $boundary_len = length($boundary) + 2;
267 # Check upload size in advance
268 if (my $size = http_get("Content-Length")) {
270 foreach my $a (values %$arg_table) {
271 $max_allowed += $a->{"maxsize"} || 65536;
273 if ($size > $max_allowed) {
274 die "Maximum form data length exceeded";
278 # Initialize our buffering mechanism and part splitter
281 $mp_buffer_boundary = -1;
284 # Skip garbage before the 1st part
285 while (my $i = refill_mp_data(256)) { $mp_buffer_i += $i; }
286 skip_mp_boundary() || return;
288 # Process individual parts
290 print STDERR "NEXT PART\n" if $debug;
291 my $h = parse_mp_header();
292 my ($field, $cdisp, $a);
294 ($cdisp = $h->{"content-disposition"}) &&
295 $cdisp =~ /^form-data/ &&
296 (($field) = ($cdisp =~ /;name=([^;]+)/)) &&
297 ($a = $arg_table->{"$field"})) {
298 print STDERR "FIELD $field\n" if $debug;
299 if (defined $h->{"content-transfer-encoding"}) { die "Unexpected Content-Transfer-Encoding"; }
300 if (defined $a->{"var"}) {
301 while (defined (my $l = get_mp_line(1))) {
302 print STDERR "VALUE $l\n" if $debug;
303 parse_arg_string("$field=$l");
306 } elsif (defined $a->{"file"}) {
309 my $max_size = $a->{"maxsize"} || 1048576;
310 my @tmpargs = (undef, UNLINK => 1);
311 push @tmpargs, DIR => $a->{"tmpdir"} if defined $a->{"tmpdir"};
312 my ($fh, $fn) = File::Temp::tempfile(@tmpargs);
313 print STDERR "FILE UPLOAD to $fn\n" if $debug;
314 ${$a->{"file"}} = $fn;
315 ${$a->{"fh"}} = $fh if defined $a->{"fh"};
317 while (my $i = refill_mp_data(4096)) {
318 print $fh substr($mp_buffer, $mp_buffer_i, $i);
321 if ($total_size > $max_size) { die "Uploaded file too long"; }
323 $fh->flush(); # Don't close the handle, the file would disappear otherwise
327 print STDERR "SKIPPING\n" if $debug;
328 while (my $i = refill_mp_data(256)) { $mp_buffer_i += $i; }
329 } } while (skip_mp_boundary());
332 ### Generating Self-ref URL's ###
334 sub make_out_args($) {
335 my ($overrides) = @_;
337 foreach my $name (keys %$arg_table) {
338 my $arg = $arg_table->{$name};
339 defined($arg->{'var'}) || next;
340 defined($arg->{'pass'}) && !$arg->{'pass'} && !exists $overrides->{$name} && next;
342 if (!defined($value = $overrides->{$name})) {
343 if (exists $overrides->{$name}) {
344 $value = $arg->{'default'};
346 $value = ${$arg->{'var'}};
349 if ($value ne $arg->{'default'}) {
350 $out->{$name} = $value;
358 my $out = make_out_args(\%h);
359 return "?" . join(':', map { "$_=" . url_param_escape($out->{$_}) } sort keys %$out);
364 my $out = make_out_args(\%h);
365 return join('', map { "<input type=hidden name=$_ value='" . html_escape($out->{$_}) . "'>\n" } sort keys %$out);
372 if ($x !~ /^[a-zA-Z0-9%]+$/) {
373 $x =~ s/([\\\"])/\\$1/g;
379 sub set_cookie($$@) {
381 my $value = shift @_;
383 $other{'version'} = 1 unless defined $other{'version'};
384 print "Set-Cookie: $key=", cookie_esc($value);
385 foreach my $k (keys %other) {
386 print ";$k=", cookie_esc($other{$k});
391 sub parse_cookies() {
392 my $h = http_get("Cookie") or return ();
394 while (my ($padding,$name,$val,$xx,$rest) = ($h =~ /\s*([,;]\s*)*([^ =]+)=([^ =,;\"]*|\"([^\"\\]|\\.)*\")(\s.*|;.*|$)/)) {
398 $val =~ s/\\(.)/$1/g;
400 push @cook, $name, $val;