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