]> mj.ucw.cz Git - libucw.git/blob - ucw/perl/UCW/CGI.pm
UCW::CGI: Bug fixes
[libucw.git] / ucw / perl / UCW / CGI.pm
1 #       Poor Man's CGI Module for Perl
2 #
3 #       (c) 2002--2010 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         $x =~ s/'/&#39;/g;
97         return $x;
98 }
99
100 ### Analysing RFC 822 Style Headers ###
101
102 sub rfc822_prepare($) {
103         my $x = shift @_;
104         # Convert all %'s and backslash escapes to %xx escapes
105         $x =~ s/%/%25/g;
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.
113         $x =~ s/\s+/ /g;
114         $x =~ s/(^ | $)//g;
115         $x =~ s{\s*([()<>@,;:\\"/\[\]?=])\s*}{$1}g;
116         return $x;
117 }
118
119 sub rfc822_deescape($) {
120         my $x = shift @_;
121         return url_deescape($x);
122 }
123
124 ### Reading of HTTP headers ###
125
126 sub http_get($) {
127         my $h = shift @_;
128         $h =~ tr/a-z-/A-Z_/;
129         return $ENV{"HTTP_$h"} || $ENV{"$h"};
130 }
131
132 ### Parsing of Arguments ###
133
134 my $main_arg_table;
135 my %raw_args;
136
137 sub parse_raw_args($) {
138         my ($s) = @_;
139         $s =~ s/\s+//;
140         for $_ (split /[&:]/, $s) {
141                 (/^([^=]+)=(.*)$/) or next;
142                 my $arg = $1;
143                 $_ = $2;
144                 s/\+/ /g;
145                 s/%(..)/pack("H2",$1)/eg;
146                 s/\r\n/\n/g;
147                 s/\r/\n/g;
148                 $raw_args{$arg} = $_;
149         }
150 }
151
152 sub parse_multipart_form_data();
153
154 sub init_args() {
155         if (!defined $ENV{"GATEWAY_INTERFACE"}) {
156                 print STDERR "Must be called as a CGI script.\n";
157                 $exit_code = 1;
158                 exit;
159         }
160
161         my $method = $ENV{"REQUEST_METHOD"};
162         if (my $qs = $ENV{"QUERY_STRING"}) {
163                 parse_raw_args($qs);
164         }
165         if ($method eq "GET") {
166         } elsif ($method eq "POST") {
167                 if ($ENV{"CONTENT_TYPE"} =~ /^application\/x-www-form-urlencoded\b/i) {
168                         while (<STDIN>) {
169                                 chomp;
170                                 parse_raw_args($_);
171                         }
172                 } elsif ($ENV{"CONTENT_TYPE"} =~ /^multipart\/form-data\b/i) {
173                         parse_multipart_form_data();
174                 } else {
175                         die "Unknown content type for POST data";
176                 }
177         } else {
178                 die "Unknown request method";
179         }
180 }
181
182 sub parse_args($) {                     # CAVEAT: attached files must be defined in the main arg table
183         my $args = shift @_;
184         if (!$main_arg_table) {
185                 $main_arg_table = $args;
186                 init_args();
187         }
188
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') {
195                         @{$a->{'var'}} = ();
196                 }
197         }
198
199         for my $arg (keys %$args) {
200                 my $a = $args->{$arg};
201                 defined($raw_args{$arg}) or next;
202                 $_ = $raw_args{$arg};
203                 $a->{'multiline'} or s/(\n|\t)/ /g;
204                 s/^\s+//;
205                 s/\s+$//;
206                 if (my $rx = $a->{'check'}) {
207                         if (!/^$rx$/) { $_ = $a->{'default'}; }
208                 }
209
210                 my $v = $a->{'var'};
211                 my $r = ref($v);
212                 if ($r eq 'SCALAR') {
213                         $$v = $_;
214                 } elsif ($r eq 'ARRAY') {
215                         push @$v, $_;
216                 }
217         }
218 }
219
220 ### Parsing Multipart Form Data ###
221
222 my $boundary;
223 my $boundary_len;
224 my $mp_buffer;
225 my $mp_buffer_i;
226 my $mp_buffer_boundary;
227 my $mp_eof;
228
229 sub refill_mp_data($) {
230         my ($more) = @_;
231         if ($mp_buffer_boundary >= $mp_buffer_i) {
232                 return $mp_buffer_boundary - $mp_buffer_i;
233         } elsif ($mp_buffer_i + $more <= length($mp_buffer) - $boundary_len) {
234                 return $more;
235         } else {
236                 if ($mp_buffer_i) {
237                         $mp_buffer = substr($mp_buffer, $mp_buffer_i);
238                         $mp_buffer_i = 0;
239                 }
240                 while ($mp_buffer_i + $more > length($mp_buffer) - $boundary_len) {
241                         last if $mp_eof;
242                         my $data;
243                         my $n = read(STDIN, $data, 2048);
244                         if ($n > 0) {
245                                 $mp_buffer .= $data;
246                         } else {
247                                 $mp_eof = 1;
248                         }
249                 }
250                 $mp_buffer_boundary = index($mp_buffer, $boundary, $mp_buffer_i);
251                 if ($mp_buffer_boundary >= 0) {
252                         return $mp_buffer_boundary;
253                 } elsif ($mp_eof) {
254                         return length($mp_buffer);
255                 } else {
256                         return length($mp_buffer) - $boundary_len;
257                 }
258         }
259 }
260
261 sub get_mp_line($) {
262         my ($allow_empty) = @_;
263         my $n = refill_mp_data(1024);
264         my $i = index($mp_buffer, "\r\n", $mp_buffer_i);
265         if ($i >= $mp_buffer_i && $i < $mp_buffer_i + $n - 1) {
266                 my $s = substr($mp_buffer, $mp_buffer_i, $i - $mp_buffer_i);
267                 $mp_buffer_i = $i + 2;
268                 return $s;
269         } elsif ($allow_empty) {
270                 if ($n) {                                                       # An incomplete line
271                         my $s = substr($mp_buffer, $mp_buffer_i, $n);
272                         $mp_buffer_i += $n;
273                         return $s;
274                 } else {                                                        # No more lines
275                         return undef;
276                 }
277         } else {
278                 die "Premature end of multipart POST data";
279         }
280 }
281
282 sub skip_mp_boundary() {
283         if ($mp_buffer_boundary != $mp_buffer_i) {
284                 die "Premature end of multipart POST data";
285         }
286         $mp_buffer_boundary = -1;
287         $mp_buffer_i += 2;
288         my $b = get_mp_line(0);
289         print STDERR "SEP $b\n" if $debug;
290         $mp_buffer_boundary = index($mp_buffer, $boundary, $mp_buffer_i);
291         if (substr("\r\n$b", 0, $boundary_len) eq "$boundary--") {
292                 return 0;
293         } else {
294                 return 1;
295         }
296 }
297
298 sub parse_mp_header() {
299         my $h = {};
300         my $last;
301         while ((my $l = get_mp_line(0)) ne "") {
302                 print STDERR "HH $l\n" if $debug;
303                 if (my ($name, $value) = ($l =~ /([A-Za-z0-9-]+)\s*:\s*(.*)/)) {
304                         $name =~ tr/A-Z/a-z/;
305                         $h->{$name} = $value;
306                         $last = $name;
307                 } elsif ($l =~ /^\s+/ && $last) {
308                         $h->{$last} .= $l;
309                 } else {
310                         $last = undef;
311                 }
312         }
313         foreach my $n (keys %$h) {
314                 $h->{$n} = rfc822_prepare($h->{$n});
315                 print STDERR "H $n: $h->{$n}\n" if $debug;
316         }
317         return (keys %$h) ? $h : undef;
318 }
319
320 sub parse_multipart_form_data() {
321         # First of all, find the boundary string
322         my $ct = rfc822_prepare($ENV{"CONTENT_TYPE"});
323         if (!(($boundary) = ($ct =~ /^.*;boundary=([^; ]+)/))) {
324                 die "Multipart content with no boundary string received";
325         }
326         $boundary = rfc822_deescape($boundary);
327         print STDERR "BOUNDARY IS $boundary\n" if $debug;
328
329         # BUG: IE 3.01 on Macintosh forgets to add the "--" at the start of the boundary string
330         # as the MIME specs preach. Workaround borrowed from CGI.pm in Perl distribution.
331         my $agent = http_get("User-agent") || "";
332         $boundary = "--$boundary" unless $agent =~ /MSIE\s+3\.0[12];\s*Mac/;
333         $boundary = "\r\n$boundary";
334         $boundary_len = length($boundary) + 2;
335
336         # Check upload size in advance
337         if (my $size = http_get("Content-Length")) {
338                 my $max_allowed = 0;
339                 foreach my $a (values %$main_arg_table) {
340                         $max_allowed += $a->{"maxsize"} || 65536;
341                 }
342                 if ($size > $max_allowed) {
343                         die "Maximum form data length exceeded";
344                 }
345         }
346
347         # Initialize our buffering mechanism and part splitter
348         $mp_buffer = "\r\n";
349         $mp_buffer_i = 0;
350         $mp_buffer_boundary = -1;
351         $mp_eof = 0;
352
353         # Skip garbage before the 1st part
354         while (my $i = refill_mp_data(256)) { $mp_buffer_i += $i; }
355         skip_mp_boundary() || return;
356
357         # Process individual parts
358         do { PART: {
359                 print STDERR "NEXT PART\n" if $debug;
360                 my $h = parse_mp_header();
361                 my ($field, $cdisp, $a);
362                 if ($h &&
363                     ($cdisp = $h->{"content-disposition"}) &&
364                     $cdisp =~ /^form-data/ &&
365                     (($field) = ($cdisp =~ /;name=([^;]+)/)) &&
366                     ($a = $main_arg_table->{"$field"})) {
367                         print STDERR "FIELD $field\n" if $debug;
368                         if (defined $h->{"content-transfer-encoding"}) { die "Unexpected Content-Transfer-Encoding"; }
369                         if (defined $a->{"var"}) {
370                                 while (defined (my $l = get_mp_line(1))) {
371                                         print STDERR "VALUE $l\n" if $debug;
372                                         parse_raw_args("$field=$l");
373                                 }
374                                 next PART;
375                         } elsif (defined $a->{"file"}) {
376                                 require File::Temp;
377                                 require IO::Handle;
378                                 my $max_size = $a->{"maxsize"} || 1048576;
379                                 my @tmpargs = (undef, UNLINK => 1);
380                                 push @tmpargs, DIR => $a->{"tmpdir"} if defined $a->{"tmpdir"};
381                                 my ($fh, $fn) = File::Temp::tempfile(@tmpargs);
382                                 print STDERR "FILE UPLOAD to $fn\n" if $debug;
383                                 ${$a->{"file"}} = $fn;
384                                 ${$a->{"fh"}} = $fh if defined $a->{"fh"};
385                                 my $total_size = 0;
386                                 while (my $i = refill_mp_data(4096)) {
387                                         print $fh substr($mp_buffer, $mp_buffer_i, $i);
388                                         $mp_buffer_i += $i;
389                                         $total_size += $i;
390                                         if ($total_size > $max_size) { die "Uploaded file too long"; }
391                                 }
392                                 $fh->flush();   # Don't close the handle, the file would disappear otherwise
393                                 next PART;
394                         }
395                 }
396                 print STDERR "SKIPPING\n" if $debug;
397                 while (my $i = refill_mp_data(256)) { $mp_buffer_i += $i; }
398         } } while (skip_mp_boundary());
399 }
400
401 ### Generating Self-ref URL's ###
402
403 sub make_out_args(@) {          # Usage: make_out_args([arg_table, ...] name => value, ...)
404         my @arg_tables = ( $main_arg_table );
405         while (@_ && ref($_[0]) eq 'HASH') {
406                 push @arg_tables, shift @_;
407         }
408         my %overrides = @_;
409         my $out = {};
410         for my $table (@arg_tables) {
411                 for my $name (keys %$table) {
412                         my $arg = $table->{$name};
413                         defined($arg->{'var'}) || next;
414                         defined($arg->{'pass'}) && !$arg->{'pass'} && !exists $overrides{$name} && next;
415                         defined $arg->{'default'} or $arg->{'default'} = "";
416                         my $value;
417                         if (!defined($value = $overrides{$name})) {
418                                 if (exists $overrides{$name}) {
419                                         $value = $arg->{'default'};
420                                 } else {
421                                         $value = ${$arg->{'var'}};
422                                         defined $value or $value = $arg->{'default'};
423                                 }
424                         }
425                         if ($value ne $arg->{'default'}) {
426                                 $out->{$name} = $value;
427                         }
428                 }
429         }
430         return $out;
431 }
432
433 sub self_ref(@) {
434         my $out = make_out_args(@_);
435         return "?" . join(':', map { "$_=" . url_param_escape($out->{$_}) } sort keys %$out);
436 }
437
438 sub self_form(@) {
439         my $out = make_out_args(@_);
440         return join('', map { "<input type=hidden name=$_ value='" . html_escape($out->{$_}) . "'>\n" } sort keys %$out);
441 }
442
443 ### Cookies
444
445 sub set_cookie($$@) {
446         #
447         # Unfortunately, the support for the new cookie standard (RFC 2965) among
448         # web browsers is still very scarce, so we are still using the old Netscape
449         # specification.
450         #
451         # Usage: set_cookie(name, value, option => value...), where options are:
452         #
453         #       max-age         maximal age in seconds
454         #       domain          domain name scope
455         #       path            path name scope
456         #       secure          if present, cookie applies only to SSL connections
457         #                       (in this case, the value should be undefined)
458         #       discard         if present with any value, the cookie is discarded
459         #
460
461         my $key = shift @_;
462         my $value = shift @_;
463         my %other = @_;
464         if (exists $other{'discard'}) {
465                 delete $other{'discard'};
466                 $other{'max-age'} = 0;
467         }
468         if (defined(my $age = $other{'max-age'})) {
469                 delete $other{'max-age'};
470                 my $exp = ($age ? (time + $age) : 0);
471                 # Avoid problems with locales
472                 my ($S,$M,$H,$d,$m,$y,$wd) = gmtime $exp;
473                 my @wdays = ( 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' );
474                 my @mons = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' );
475                 $other{'expires'} = sprintf("%s, %02d-%s-%d %02d:%02d:%02d GMT",
476                         $wdays[$wd], $d, $mons[$m], $y+1900, $H, $M, $S);
477         }
478
479         print "Set-Cookie: $key=", url_escape($value);
480         foreach my $k (keys %other) {
481                 print "; $k";
482                 print "=", $other{$k} if defined $other{$k};
483         }
484         print "\n";
485 }
486
487 sub parse_cookies() {
488         my $h = http_get("Cookie") or return ();
489         my @cook = ();
490         foreach my $x (split /;\s*/, $h) {
491                 my ($k,$v) = split /=/, $x;
492                 $v = url_deescape($v) if defined $v;
493                 push @cook, $k => $v;
494         }
495         return @cook;
496 }
497
498 1;  # OK