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