]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/CGI.pm
mention that the CVE-2016-4561 fix was backported
[git.ikiwiki.info.git] / IkiWiki / CGI.pm
1 #!/usr/bin/perl
3 package IkiWiki;
5 use warnings;
6 use strict;
7 use IkiWiki;
8 use IkiWiki::UserInfo;
9 use open qw{:utf8 :std};
10 use Encode;
12 sub printheader ($) {
13         my $session=shift;
14         
15         if (($ENV{HTTPS} && lc $ENV{HTTPS} ne "off") || $config{sslcookie}) {
16                 print $session->header(-charset => 'utf-8',
17                         -cookie => $session->cookie(-httponly => 1, -secure => 1));
18         }
19         else {
20                 print $session->header(-charset => 'utf-8',
21                         -cookie => $session->cookie(-httponly => 1));
22         }
23 }
25 sub prepform {
26         my $form=shift;
27         my $buttons=shift;
28         my $session=shift;
29         my $cgi=shift;
31         if (exists $hooks{formbuilder}) {
32                 run_hooks(formbuilder => sub {
33                         shift->(form => $form, cgi => $cgi, session => $session,
34                                 buttons => $buttons);
35                 });
36         }
38         return $form;
39 }
41 sub showform ($$$$;@) {
42         my $form=prepform(@_);
43         shift;
44         my $buttons=shift;
45         my $session=shift;
46         my $cgi=shift;
48         printheader($session);
49         print cgitemplate($cgi, $form->title,
50                 $form->render(submit => $buttons), @_);
51 }
53 sub cgitemplate ($$$;@) {
54         my $cgi=shift;
55         my $title=shift;
56         my $content=shift;
57         my %params=@_;
58         
59         my $template=template("page.tmpl");
61         my $topurl = $config{url};
62         if (defined $cgi && ! $config{w3mmode} && ! $config{reverse_proxy}) {
63                 $topurl = $cgi->url;
64         }
66         my $page="";
67         if (exists $params{page}) {
68                 $page=delete $params{page};
69                 $params{forcebaseurl}=urlto($page);
70         }
71         run_hooks(pagetemplate => sub {
72                 shift->(
73                         page => $page,
74                         destpage => $page,
75                         template => $template,
76                 );
77         });
78         templateactions($template, "");
80         my $baseurl = baseurl();
82         $template->param(
83                 dynamic => 1,
84                 title => $title,
85                 wikiname => $config{wikiname},
86                 content => $content,
87                 baseurl => $baseurl,
88                 html5 => $config{html5},
89                 %params,
90         );
91         
92         return $template->output;
93 }
95 sub redirect ($$) {
96         my $q=shift;
97         eval q{use URI};
99         my $topurl;
100         if (defined $q && ! $config{w3mmode} && ! $config{reverse_proxy}) {
101                 $topurl = $q->url;
102         }
104         my $url=URI->new(urlabs(shift, $topurl));
105         if (! $config{w3mmode}) {
106                 print $q->redirect($url);
107         }
108         else {
109                 print "Content-type: text/plain\n";
110                 print "W3m-control: GOTO $url\n\n";
111         }
114 sub decode_cgi_utf8 ($) {
115         # decode_form_utf8 method is needed for 5.01
116         if ($] < 5.01) {
117                 my $cgi = shift;
118                 foreach my $f ($cgi->param) {
119                         $cgi->param($f, map { decode_utf8 $_ }
120                                 @{$cgi->param_fetch($f)});
121                 }
122         }
125 sub safe_decode_utf8 ($) {
126     my $octets = shift;
127     if (!Encode::is_utf8($octets)) {
128         return decode_utf8($octets);
129     }
130     else {
131         return $octets;
132     }
135 sub decode_form_utf8 ($) {
136         if ($] >= 5.01) {
137                 my $form = shift;
138                 foreach my $f ($form->field) {
139                         my @value=map { safe_decode_utf8($_) } $form->field($f);
140                         $form->field(name  => $f,
141                                      value => \@value,
142                                      force => 1,
143                         );
144                 }
145         }
148 # Check if the user is signed in. If not, redirect to the signin form and
149 # save their place to return to later.
150 sub needsignin ($$) {
151         my $q=shift;
152         my $session=shift;
154         if (! defined $session->param("name") ||
155             ! userinfo_get($session->param("name"), "regdate")) {
156                 $session->param(postsignin => $q->query_string);
157                 cgi_signin($q, $session);
158                 cgi_savesession($session);
159                 exit;
160         }
163 sub cgi_signin ($$;$) {
164         my $q=shift;
165         my $session=shift;
166         my $returnhtml=shift;
168         decode_cgi_utf8($q);
169         eval q{use CGI::FormBuilder};
170         error($@) if $@;
171         my $form = CGI::FormBuilder->new(
172                 title => "signin",
173                 name => "signin",
174                 charset => "utf-8",
175                 method => 'POST',
176                 required => 'NONE',
177                 javascript => 0,
178                 params => $q,
179                 action => cgiurl(),
180                 header => 0,
181                 template => {type => 'div'},
182                 stylesheet => 1,
183         );
184         my $buttons=["Login"];
185         
186         $form->field(name => "do", type => "hidden", value => "signin",
187                 force => 1);
188         
189         decode_form_utf8($form);
190         run_hooks(formbuilder_setup => sub {
191                 shift->(form => $form, cgi => $q, session => $session,
192                         buttons => $buttons);
193         });
194         decode_form_utf8($form);
196         if ($form->submitted) {
197                 $form->validate;
198         }
200         if ($returnhtml) {
201                 $form=prepform($form, $buttons, $session, $q);
202                 return $form->render(submit => $buttons);
203         }
205         showform($form, $buttons, $session, $q);
208 sub cgi_postsignin ($$) {
209         my $q=shift;
210         my $session=shift;
211         
212         # Continue with whatever was being done before the signin process.
213         if (defined $session->param("postsignin")) {
214                 my $postsignin=CGI->new($session->param("postsignin"));
215                 $session->clear("postsignin");
216                 cgi($postsignin, $session);
217                 cgi_savesession($session);
218                 exit;
219         }
220         else {
221                 if ($config{sslcookie} && ! $q->https()) {
222                         error(gettext("probable misconfiguration: sslcookie is set, but you are attempting to login via http, not https"));
223                 }
224                 else {
225                         error(gettext("login failed, perhaps you need to turn on cookies?"));
226                 }
227         }
230 sub cgi_prefs ($$) {
231         my $q=shift;
232         my $session=shift;
234         needsignin($q, $session);
235         decode_cgi_utf8($q);
236         
237         # The session id is stored on the form and checked to
238         # guard against CSRF.
239         my $sid=$q->param('sid');
240         if (! defined $sid) {
241                 $q->delete_all;
242         }
243         elsif ($sid ne $session->id) {
244                 error(gettext("Your login session has expired."));
245         }
247         eval q{use CGI::FormBuilder};
248         error($@) if $@;
249         my $form = CGI::FormBuilder->new(
250                 title => "preferences",
251                 name => "preferences",
252                 header => 0,
253                 charset => "utf-8",
254                 method => 'POST',
255                 validate => {
256                         email => 'EMAIL',
257                 },
258                 required => 'NONE',
259                 javascript => 0,
260                 params => $q,
261                 action => cgiurl(),
262                 template => {type => 'div'},
263                 stylesheet => 1,
264                 fieldsets => [
265                         [login => gettext("Login")],
266                         [preferences => gettext("Preferences")],
267                         [admin => gettext("Admin")]
268                 ],
269         );
270         my $buttons=["Save Preferences", "Logout", "Cancel"];
271         
272         decode_form_utf8($form);
273         run_hooks(formbuilder_setup => sub {
274                 shift->(form => $form, cgi => $q, session => $session,
275                         buttons => $buttons);
276         });
277         decode_form_utf8($form);
278         
279         $form->field(name => "do", type => "hidden", value => "prefs",
280                 force => 1);
281         $form->field(name => "sid", type => "hidden", value => $session->id,
282                 force => 1);
283         $form->field(name => "email", size => 50, fieldset => "preferences");
284         
285         my $user_name=$session->param("name");
287         if (! $form->submitted) {
288                 $form->field(name => "email", force => 1,
289                         value => userinfo_get($user_name, "email"));
290         }
291         
292         if ($form->submitted eq 'Logout') {
293                 $session->delete();
294                 redirect($q, baseurl(undef));
295                 return;
296         }
297         elsif ($form->submitted eq 'Cancel') {
298                 redirect($q, baseurl(undef));
299                 return;
300         }
301         elsif ($form->submitted eq 'Save Preferences' && $form->validate) {
302                 if (defined $form->field('email')) {
303                         userinfo_set($user_name, 'email', $form->field('email')) ||
304                                 error("failed to set email");
305                 }
307                 $form->text(gettext("Preferences saved."));
308         }
309         
310         showform($form, $buttons, $session, $q,
311                 prefsurl => "", # avoid showing the preferences link
312         );
315 sub cgi_custom_failure ($$$) {
316         my $q=shift;
317         my $httpstatus=shift;
318         my $message=shift;
320         print $q->header(
321                 -status => $httpstatus,
322                 -charset => 'utf-8',
323         );
324         print $message;
326         # Internet Explod^Hrer won't show custom 404 responses
327         # unless they're >= 512 bytes
328         print ' ' x 512;
330         exit;
333 sub check_banned ($$) {
334         my $q=shift;
335         my $session=shift;
337         my $banned=0;
338         my $name=$session->param("name");
339         my $cloak=cloak($name) if defined $name;
340         if (defined $name && 
341             grep { $name eq $_ || $cloak eq $_ } @{$config{banned_users}}) {
342                 $banned=1;
343         }
345         foreach my $b (@{$config{banned_users}}) {
346                 if (pagespec_match("", $b,
347                         ip => $session->remote_addr(),
348                         name => defined $name ? $name : "")
349                    || pagespec_match("", $b,
350                         ip => cloak($session->remote_addr()),
351                         name => defined $cloak ? $cloak : "")) {
352                         $banned=1;
353                         last;
354                 }
355         }
357         if ($banned) {
358                 $session->delete();
359                 cgi_savesession($session);
360                 cgi_custom_failure(
361                         $q, "403 Forbidden",
362                         gettext("You are banned."));
363         }
366 sub cgi_getsession ($) {
367         my $q=shift;
369         eval q{use CGI::Session; use HTML::Entities};
370         error($@) if $@;
371         CGI::Session->name("ikiwiki_session_".encode_entities($config{wikiname}));
372         
373         my $oldmask=umask(077);
374         my $session = eval {
375                 CGI::Session->new("driver:DB_File", $q,
376                         { FileName => "$config{wikistatedir}/sessions.db" })
377         };
378         if (! $session || $@) {
379                 my $error = $@;
380                 error($error." ".CGI::Session->errstr());
381         }
382         
383         umask($oldmask);
385         return $session;
388 # To guard against CSRF, the user's session id (sid)
389 # can be stored on a form. This function will check
390 # (for logged in users) that the sid on the form matches
391 # the session id in the cookie.
392 sub checksessionexpiry ($$) {
393         my $q=shift;
394         my $session = shift;
396         if (defined $session->param("name")) {
397                 my $sid=$q->param('sid');
398                 if (! defined $sid || $sid ne $session->id) {
399                         error(gettext("Your login session has expired."));
400                 }
401         }
404 sub cgi_savesession ($) {
405         my $session=shift;
407         # Force session flush with safe umask.
408         my $oldmask=umask(077);
409         $session->flush;
410         umask($oldmask);
413 sub cgi (;$$) {
414         my $q=shift;
415         my $session=shift;
417         eval q{use CGI};
418         error($@) if $@;
419         no warnings "once";
420         $CGI::DISABLE_UPLOADS=$config{cgi_disable_uploads};
421         use warnings;
423         if (! $q) {
424                 binmode(STDIN);
425                 $q=CGI->new;
426                 binmode(STDIN, ":utf8");
427         
428                 run_hooks(cgi => sub { shift->($q) });
429         }
431         my $do=$q->param('do');
432         if (! defined $do || ! length $do) {
433                 my $error = $q->cgi_error;
434                 if ($error) {
435                         error("Request not processed: $error");
436                 }
437                 else {
438                         error("\"do\" parameter missing");
439                 }
440         }
442         # Need to lock the wiki before getting a session.
443         lockwiki();
444         loadindex();
445         
446         if (! $session) {
447                 $session=cgi_getsession($q);
448         }
449         
450         # Auth hooks can sign a user in.
451         if ($do ne 'signin' && ! defined $session->param("name")) {
452                 run_hooks(auth => sub {
453                         shift->($q, $session)
454                 });
455                 if (defined $session->param("name")) {
456                         # Make sure whatever user was authed is in the
457                         # userinfo db.
458                         if (! userinfo_get($session->param("name"), "regdate")) {
459                                 userinfo_setall($session->param("name"), {
460                                         email => defined $session->param("email") ? $session->param("email") : "",
461                                         password => "",
462                                         regdate => time,
463                                 }) || error("failed adding user");
464                         }
465                 }
466         }
467         
468         check_banned($q, $session);
469         
470         run_hooks(sessioncgi => sub { shift->($q, $session) });
472         if ($do eq 'signin') {
473                 cgi_signin($q, $session);
474                 cgi_savesession($session);
475         }
476         elsif ($do eq 'prefs') {
477                 cgi_prefs($q, $session);
478         }
479         elsif (defined $session->param("postsignin") || $do eq 'postsignin') {
480                 cgi_postsignin($q, $session);
481         }
482         else {
483                 error("unknown do parameter");
484         }
487 # Does not need to be called directly; all errors will go through here.
488 sub cgierror ($) {
489         my $message=shift;
491         eval q{use HTML::Entities};
492         $message = encode_entities($message);
494         print "Content-type: text/html\n\n";
495         print cgitemplate(undef, gettext("Error"),
496                 "<p class=\"error\">".gettext("Error").": $message</p>");
497         die $@;