]> mj.ucw.cz Git - libucw.git/blob - ucw/perl/UCW/CGI.pm
99ab83a9ffc2eb7705b892e7fb5791feeeb5cb48
[libucw.git] / ucw / perl / UCW / CGI.pm
1 #       Poor Man's CGI Module for Perl
2 #
3 #       (c) 2002--2007 Martin Mares <mj@ucw.cz>
4 #       Slightly modified by Tomas Valla <tom@ucw.cz>
5 #
6 #       This software may be freely distributed and used according to the terms
7 #       of the GNU Lesser General Public License.
8
9 # FIXME:
10 # - respond with proper HTTP error codes
11 # - if we get invalid parameters, generate HTTP error or redirect
12
13 package UCW::CGI;
14
15 # First of all, set up error handling, so that even errors during parsing
16 # will be reported properly.
17
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
22
23 my $error_reported;
24 my $exit_code;
25 my $debug = 0;
26
27 sub report_bug($)
28 {
29         if (!defined $error_reported) {
30                 $error_reported = 1;
31                 print STDERR $_[0];
32                 if (defined($UCW::CGI::error_hook)) {
33                         &$UCW::CGI::error_hook($_[0]);
34                 } else {
35                         print "Content-type: text/plain\n\n";
36                         print "Internal bug:\n";
37                         print $_[0], "\n";
38                         print "Please notify $UCW::CGI::error_mail\n" if defined $UCW::CGI::error_mail;
39                 }
40         }
41         die;
42 }
43
44 BEGIN {
45         $SIG{__DIE__} = sub { report_bug($_[0]); };
46         $SIG{__WARN__} = sub { report_bug("WARNING: " . $_[0]); };
47         $exit_code = 0;
48 }
49
50 END {
51         $? = $exit_code;
52 }
53
54 use strict;
55 use warnings;
56
57 require Exporter;
58 our $VERSION = 1.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();
62
63 ### Escaping ###
64
65 sub url_escape($) {
66         my $x = shift @_;
67         $x =~ s/([^-\$_.!*'(),0-9A-Za-z\x80-\xff])/"%".unpack('H2',$1)/ge;
68         return $x;
69 }
70
71 sub url_deescape($) {
72         my $x = shift @_;
73         $x =~ s/%(..)/pack("H2",$1)/ge;
74         return $x;
75 }
76
77 sub url_param_escape($) {
78         my $x = shift @_;
79         $x = url_escape($x);
80         $x =~ s/%20/+/g;
81         return $x;
82 }
83
84 sub url_param_deescape($) {
85         my $x = shift @_;
86         $x =~ s/\+/ /g;
87         return url_deescape($x);
88 }
89
90 sub html_escape($) {
91         my $x = shift @_;
92         $x =~ s/&/&amp;/g;
93         $x =~ s/</&lt;/g;
94         $x =~ s/>/&gt;/g;
95         $x =~ s/"/&quot;/g;
96         return $x;
97 }
98
99 ### Analysing RFC 822 Style Headers ###
100
101 sub rfc822_prepare($) {
102         my $x = shift @_;
103         # Convert all %'s and backslash escapes to %xx escapes
104         $x =~ s/%/%25/g;
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.
112         $x =~ s/\s+/ /g;
113         $x =~ s/(^ | $)//g;
114         $x =~ s{\s*([()<>@,;:\\"/\[\]?=])\s*}{$1}g;
115         return $x;
116 }
117
118 sub rfc822_deescape($) {
119         my $x = shift @_;
120         return url_deescape($x);
121 }
122
123 ### Reading of HTTP headers ###
124
125 sub http_get($) {
126         my $h = shift @_;
127         $h =~ tr/a-z-/A-Z_/;
128         return $ENV{"HTTP_$h"} || $ENV{"$h"};
129 }
130
131 ### Parsing of Arguments ###
132
133 my $arg_table;
134
135 sub parse_arg_string($) {
136         my ($s) = @_;
137         $s =~ s/\s+//;
138         foreach $_ (split /[&:]/,$s) {
139                 (/^([^=]+)=(.*)$/) or next;
140                 my $arg = $arg_table->{$1} or next;
141                 $_ = $2;
142                 s/\+/ /g;
143                 s/%(..)/pack("H2",$1)/eg;
144                 s/\r\n/\n/g;
145                 s/\r/\n/g;
146                 $arg->{'multiline'} || s/(\n|\t)/ /g;
147                 s/^\s+//;
148                 s/\s+$//;
149                 if (my $rx = $arg->{'check'}) {
150                         if (!/^$rx$/) { $_ = $arg->{'default'}; }
151                 }
152
153                 my $r = ref($arg->{'var'});
154                 if ($r eq 'SCALAR') {
155                         ${$arg->{'var'}} = $_;
156                 } elsif ($r eq 'ARRAY') {
157                         push @{$arg->{'var'}}, $_;
158                 }
159         }
160 }
161
162 sub parse_multipart_form_data();
163
164 sub parse_args($) {
165         $arg_table = shift @_;
166         if (!defined $ENV{"GATEWAY_INTERFACE"}) {
167                 print STDERR "Must be called as a CGI script.\n";
168                 $exit_code = 1;
169                 exit;
170         }
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') {
177                         @{$a->{'var'}} = ();
178                 }
179         }
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) {
186                         while (<STDIN>) {
187                                 chomp;
188                                 parse_arg_string($_);
189                         }
190                 } elsif ($ENV{"CONTENT_TYPE"} =~ /^multipart\/form-data\b/i) {
191                         parse_multipart_form_data();
192                 } else {
193                         die "Unknown content type for POST data";
194                 }
195         } else {
196                 die "Unknown request method";
197         }
198 }
199
200 ### Parsing Multipart Form Data ###
201
202 my $boundary;
203 my $boundary_len;
204 my $mp_buffer;
205 my $mp_buffer_i;
206 my $mp_buffer_boundary;
207 my $mp_eof;
208
209 sub refill_mp_data($) {
210         my ($more) = @_;
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) {
214                 return $more;
215         } else {
216                 if ($mp_buffer_i) {
217                         $mp_buffer = substr($mp_buffer, $mp_buffer_i);
218                         $mp_buffer_i = 0;
219                 }
220                 while ($mp_buffer_i + $more > length($mp_buffer) - $boundary_len) {
221                         last if $mp_eof;
222                         my $data;
223                         my $n = read(STDIN, $data, 2048);
224                         if ($n > 0) {
225                                 $mp_buffer .= $data;
226                         } else {
227                                 $mp_eof = 1;
228                         }
229                 }
230                 $mp_buffer_boundary = index($mp_buffer, $boundary, $mp_buffer_i);
231                 if ($mp_buffer_boundary >= 0) {
232                         return $mp_buffer_boundary;
233                 } elsif ($mp_eof) {
234                         return length($mp_buffer);
235                 } else {
236                         return length($mp_buffer) - $boundary_len;
237                 }
238         }
239 }
240
241 sub get_mp_line($) {
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;
248                 return $s;
249         } elsif ($allow_empty) {
250                 if ($n) {                                                       # An incomplete line
251                         my $s = substr($mp_buffer, $mp_buffer_i, $n);
252                         $mp_buffer_i += $n;
253                         return $s;
254                 } else {                                                        # No more lines
255                         return undef;
256                 }
257         } else {
258                 die "Premature end of multipart POST data";
259         }
260 }
261
262 sub skip_mp_boundary() {
263         if ($mp_buffer_boundary != $mp_buffer_i) {
264                 die "Premature end of multipart POST data";
265         }
266         $mp_buffer_boundary = -1;
267         $mp_buffer_i += 2;
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--/) {
272                 return 0;
273         } else {
274                 return 1;
275         }
276 }
277
278 sub parse_mp_header() {
279         my $h = {};
280         my $last;
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;
286                         $last = $name;
287                 } elsif ($l =~ /^\s+/ && $last) {
288                         $h->{$last} .= $l;
289                 } else {
290                         $last = undef;
291                 }
292         }
293         foreach my $n (keys %$h) {
294                 $h->{$n} = rfc822_prepare($h->{$n});
295                 print STDERR "H $n: $h->{$n}\n" if $debug;
296         }
297         return (keys %$h) ? $h : undef;
298 }
299
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";
305         }
306         $boundary = rfc822_deescape($boundary);
307         print STDERR "BOUNDARY IS $boundary\n" if $debug;
308
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;
315
316         # Check upload size in advance
317         if (my $size = http_get("Content-Length")) {
318                 my $max_allowed = 0;
319                 foreach my $a (values %$arg_table) {
320                         $max_allowed += $a->{"maxsize"} || 65536;
321                 }
322                 if ($size > $max_allowed) {
323                         die "Maximum form data length exceeded";
324                 }
325         }
326
327         # Initialize our buffering mechanism and part splitter
328         $mp_buffer = "\r\n";
329         $mp_buffer_i = 0;
330         $mp_buffer_boundary = -1;
331         $mp_eof = 0;
332
333         # Skip garbage before the 1st part
334         while (my $i = refill_mp_data(256)) { $mp_buffer_i += $i; }
335         skip_mp_boundary() || return;
336
337         # Process individual parts
338         do { PART: {
339                 print STDERR "NEXT PART\n" if $debug;
340                 my $h = parse_mp_header();
341                 my ($field, $cdisp, $a);
342                 if ($h &&
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");
353                                 }
354                                 next PART;
355                         } elsif (defined $a->{"file"}) {
356                                 require File::Temp;
357                                 require IO::Handle;
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"};
365                                 my $total_size = 0;
366                                 while (my $i = refill_mp_data(4096)) {
367                                         print $fh substr($mp_buffer, $mp_buffer_i, $i);
368                                         $mp_buffer_i += $i;
369                                         $total_size += $i;
370                                         if ($total_size > $max_size) { die "Uploaded file too long"; }
371                                 }
372                                 $fh->flush();   # Don't close the handle, the file would disappear otherwise
373                                 next PART;
374                         }
375                 }
376                 print STDERR "SKIPPING\n" if $debug;
377                 while (my $i = refill_mp_data(256)) { $mp_buffer_i += $i; }
378         } } while (skip_mp_boundary());
379 }
380
381 ### Generating Self-ref URL's ###
382
383 sub make_out_args($) {
384         my ($overrides) = @_;
385         my $out = {};
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;
390                 my $value;
391                 if (!defined($value = $overrides->{$name})) {
392                         if (exists $overrides->{$name}) {
393                                 $value = $arg->{'default'};
394                         } else {
395                                 $value = ${$arg->{'var'}};
396                         }
397                 }
398                 if ($value ne $arg->{'default'}) {
399                         $out->{$name} = $value;
400                 }
401         }
402         return $out;
403 }
404
405 sub self_ref(@) {
406         my %h = @_;
407         my $out = make_out_args(\%h);
408         return "?" . join(':', map { "$_=" . url_param_escape($out->{$_}) } sort keys %$out);
409 }
410
411 sub self_form(@) {
412         my %h = @_;
413         my $out = make_out_args(\%h);
414         return join('', map { "<input type=hidden name=$_ value='" . html_escape($out->{$_}) . "'>\n" } sort keys %$out);
415 }
416
417 ### Cookies
418
419 sub set_cookie($$@) {
420         #
421         # Unfortunately, the support for the new cookie standard (RFC 2965) among
422         # web browsers is still very scarce, so we are still using the old Netscape
423         # specification.
424         #
425         # Usage: set_cookie(name, value, option => value...), where options are:
426         #
427         #       max-age         maximal age in seconds
428         #       domain          domain name scope
429         #       path            path name scope
430         #       secure          if present, cookie applies only to SSL connections
431         #                       (in this case, the value should be undefined)
432         #       discard         if present with any value, the cookie is discarded
433         #
434
435         my $key = shift @_;
436         my $value = shift @_;
437         my %other = @_;
438         if (exists $other{'discard'}) {
439                 delete $other{'discard'};
440                 $other{'max-age'} = 0;
441         }
442         if (defined(my $age = $other{'max-age'})) {
443                 delete $other{'max-age'};
444                 my $exp = ($age ? (time + $age) : 0);
445                 # Avoid problems with locales
446                 my ($S,$M,$H,$d,$m,$y,$wd) = gmtime $exp;
447                 my @wdays = ( 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' );
448                 my @mons = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' );
449                 $other{'expires'} = sprintf("%s, %02d-%s-%d %02d:%02d:%02d GMT",
450                         $wdays[$wd], $d, $mons[$m], $y+1900, $H, $M, $S);
451         }
452
453         print "Set-Cookie: $key=", url_escape($value);
454         foreach my $k (keys %other) {
455                 print "; $k";
456                 print "=", $other{$k} if defined $other{$k};
457         }
458         print "\n";
459 }
460
461 sub parse_cookies() {
462         my $h = http_get("Cookie") or return ();
463         my @cook = ();
464         foreach my $x (split /;\s*/, $h) {
465                 my ($k,$v) = split /=/, $x;
466                 $v = url_deescape($v) if defined $v;
467                 push @cook, $k => $v;
468         }
469         return @cook;
470 }
471
472 1;  # OK