]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki/Plugin/attachment.pm
CGI, attachment, passwordauth: harden against repeated parameters
[git.ikiwiki.info.git] / IkiWiki / Plugin / attachment.pm
1 #!/usr/bin/perl
2 package IkiWiki::Plugin::attachment;
4 use warnings;
5 use strict;
6 use IkiWiki 3.00;
8 sub import {
9         add_underlay("attachment");
10         add_underlay("javascript");
11         add_underlay("jquery");
12         hook(type => "getsetup", id => "attachment", call => \&getsetup);
13         hook(type => "checkconfig", id => "attachment", call => \&checkconfig);
14         hook(type => "formbuilder_setup", id => "attachment", call => \&formbuilder_setup);
15         hook(type => "formbuilder", id => "attachment", call => \&formbuilder, last => 1);
16         IkiWiki::loadplugin("filecheck");
17 }
19 sub getsetup () {
20         return
21                 plugin => {
22                         safe => 1,
23                         rebuild => 0,
24                         section => "web",
25                 },
26                 allowed_attachments => {
27                         type => "pagespec",
28                         example => "virusfree() and mimetype(image/*) and maxsize(50kb)",
29                         description => "enhanced PageSpec specifying what attachments are allowed",
30                         link => "ikiwiki/PageSpec/attachment",
31                         safe => 1,
32                         rebuild => 0,
33                 },
34                 virus_checker => {
35                         type => "string",
36                         example => "clamdscan -",
37                         description => "virus checker program (reads STDIN, returns nonzero if virus found)",
38                         safe => 0, # executed
39                         rebuild => 0,
40                 },
41 }
43 sub check_canattach ($$;$) {
44         my $session=shift;
45         my $dest=shift; # where it's going to be put, under the srcdir
46         my $file=shift; # the path to the attachment currently
48         # Don't allow an attachment to be uploaded with the same name as an
49         # existing page.
50         if (exists $IkiWiki::pagesources{$dest} &&
51             $IkiWiki::pagesources{$dest} ne $dest) {
52                 error(sprintf(gettext("there is already a page named %s"), $dest));
53         }
55         # Use a special pagespec to test that the attachment is valid.
56         my $allowed=1;
57         if (defined $config{allowed_attachments} &&
58             length $config{allowed_attachments}) {
59                 $allowed=pagespec_match($dest,
60                         $config{allowed_attachments},
61                         file => $file,
62                         user => $session->param("name"),
63                         ip => $session->remote_addr(),
64                 );
65         }
67         if (! $allowed) {
68                 error(gettext("prohibited by allowed_attachments")." ($allowed)");
69         }
70         else {
71                 return 1;
72         }
73 }
75 sub checkconfig () {
76         $config{cgi_disable_uploads}=0;
77 }
79 sub formbuilder_setup (@) {
80         my %params=@_;
81         my $form=$params{form};
82         my $q=$params{cgi};
84         if (defined $form->field("do") && ($form->field("do") eq "edit" ||
85             $form->field("do") eq "create")) {
86                 # Add attachment field, set type to multipart.
87                 $form->enctype(&CGI::MULTIPART);
88                 $form->field(name => 'attachment', type => 'file');
89                 # These buttons are not put in the usual place, so
90                 # are not added to the normal formbuilder button list.
91                 $form->tmpl_param("field-upload" => '<input name="_submit" type="submit" value="Upload Attachment" />');
92                 $form->tmpl_param("field-link" => '<input name="_submit" type="submit" value="Insert Links" />');
94                 # Add all the javascript used by the attachments interface.
95                 require IkiWiki::Plugin::toggle;
96                 my $js=IkiWiki::Plugin::toggle::include_javascript($params{page});
97                 $js.='<link rel="stylesheet" href="'.urlto("ikiwiki/jquery-ui.min.css", $params{page}).'" id="theme">'."\n";
98                 my @jsfiles=qw{jquery.min jquery-ui.min
99                         jquery.tmpl.min jquery.iframe-transport
100                         jquery.fileupload jquery.fileupload-ui
101                 };
102                 foreach my $file (@jsfiles) {
103                         $js.='<script src="'.urlto("ikiwiki/$file.js", $params{page}).
104                              '" type="text/javascript" charset="utf-8"></script>'."\n";
105                 }
106                 $form->tmpl_param("javascript" => $js);
108                 # Start with the attachments interface toggled invisible,
109                 # but if it was used, keep it open.
110                 if ($form->submitted ne "Upload Attachment" &&
111                     (! defined $q->param("attachment_select") ||
112                     ! length $q->param("attachment_select"))) {
113                         $form->tmpl_param("attachments-class" => "toggleable");
114                 }
115                 else {
116                         $form->tmpl_param("attachments-class" => "toggleable-open");
117                 }
118                 
119                 # Save attachments in holding area before previewing and
120                 # saving.
121                 if ($form->submitted eq "Preview" ||
122                     $form->submitted eq "Save Page") {
123                         attachments_save($form, $params{session});
124                 }
125         }
128 sub formbuilder (@) {
129         my %params=@_;
130         my $form=$params{form};
131         my $q=$params{cgi};
133         return if ! defined $form->field("do") || ($form->field("do") ne "edit" && $form->field("do") ne "create") ;
135         my $filename=Encode::decode_utf8(scalar $q->param('attachment'));
136         if (defined $filename && length $filename) {
137                 attachment_store($filename, $form, $q, $params{session});
138         }
140         if ($form->submitted eq "Save Page") {
141                 attachments_save($form, $params{session});
142         }
144         if ($form->submitted eq "Insert Links") {
145                 my $page=quotemeta(Encode::decode_utf8(scalar $q->param("page")));
146                 my $add="";
147                 foreach my $f (@{$q->param_fetch("attachment_select")}) {
148                         $f=Encode::decode_utf8($f);
149                         $f=~s/^$page\///;
150                         if (IkiWiki::isinlinableimage($f) &&
151                             IkiWiki::Plugin::img->can("import")) {
152                                 $add.='[[!img '.$f.' align="right" size="" alt=""]]';
153                         }
154                         else {
155                                 $add.="[[$f]]";
156                         }
157                         $add.="\n";
158                 }
159                 my $content = $form->field('editcontent');
160                 $form->field(name => 'editcontent',
161                         value => $content."\n\n".$add,
162                         force => 1) if length $add;
163         }
164         
165         # Generate the attachment list only after having added any new
166         # attachments.
167         $form->tmpl_param("attachment_list" => [attachment_list(scalar $form->field('page'))]);
170 sub attachment_holding_location {
171         my $page=attachment_location(shift);
173         my $dir=$config{wikistatedir}."/attachments/".
174                 IkiWiki::possibly_foolish_untaint(linkpage($page));
175         $dir=~s/\/$//;
176         return $dir;
179 sub is_held_attachment {
180         my $attachment=shift;
182         my $f=attachment_holding_location($attachment);
183         if (-f $f) {
184                 return $f
185         }
186         else {
187                 return undef;
188         }
191 # Stores the attachment in a holding area, not yet in the wiki proper.
192 sub attachment_store {
193         my $filename=shift;
194         my $form=shift;
195         my $q=shift;
196         my $session=shift;
197         
198         # This is an (apparently undocumented) way to get the name
199         # of the temp file that CGI writes the upload to.
200         my $tempfile=$q->tmpFileName($filename);
201         if (! defined $tempfile || ! length $tempfile) {
202                 # perl 5.8 needs an alternative, awful method
203                 if ($q =~ /HASH/ && exists $q->{'.tmpfiles'}) {
204                         foreach my $key (keys(%{$q->{'.tmpfiles'}})) {
205                                 $tempfile=$q->tmpFileName(\$key);
206                                 last if defined $tempfile && length $tempfile;
207                         }
208                 }
209                 if (! defined $tempfile || ! length $tempfile) {
210                         error("CGI::tmpFileName failed to return the uploaded file name");
211                 }
212         }
214         $filename=IkiWiki::basename($filename);
215         $filename=~s/.*\\+(.+)/$1/; # hello, windows
216         $filename=IkiWiki::possibly_foolish_untaint(linkpage($filename));
217         my $dest=attachment_holding_location(scalar $form->field('page'));
218         
219         # Check that the user is allowed to edit the attachment.
220         my $final_filename=
221                 linkpage(IkiWiki::possibly_foolish_untaint(
222                         attachment_location(scalar $form->field('page')))).
223                 $filename;
224         eval {
225                 if (IkiWiki::file_pruned($final_filename)) {
226                         error(gettext("bad attachment filename"));
227                 }
228                 IkiWiki::check_canedit($final_filename, $q, $session);
229                 # And that the attachment itself is acceptable.
230                 check_canattach($session, $final_filename, $tempfile);
231         };
232         if ($@) {
233                 # save error in case called functions clobber $@
234                 my $error = $@;
235                 json_response($q, $form, $dest."/".$filename, $error);
236                 error $error;
237         }
239         # Move the attachment into holding directory.
240         # Try to use a fast rename; fall back to copying.
241         IkiWiki::prep_writefile($filename, $dest);
242         unlink($dest."/".$filename);
243         if (rename($tempfile, $dest."/".$filename)) {
244                 # The temp file has tight permissions; loosen up.
245                 chmod(0666 & ~umask, $dest."/".$filename);
246         }
247         else {
248                 my $fh=$q->upload('attachment');
249                 if (! defined $fh || ! ref $fh) {
250                         # needed by old CGI versions
251                         $fh=$q->param('attachment');
252                         if (! defined $fh || ! ref $fh) {
253                                 # even that doesn't always work,
254                                 # fall back to opening the tempfile
255                                 $fh=undef;
256                                 open($fh, "<", $tempfile) || error("failed to open \"$tempfile\": $!");
257                         }
258                 }
259                 binmode($fh);
260                 require IkiWiki::Render; 
261                 writefile($filename, $dest, undef, 1, sub {
262                         IkiWiki::fast_file_copy($tempfile, $filename, $fh, @_);
263                 });
264         }
266         json_response($q, $form, $dest."/".$filename, stored_msg());
269 # Save all stored attachments for a page.
270 sub attachments_save {
271         my $form=shift;
272         my $session=shift;
274         # Move attachments out of holding directory.
275         my @attachments;
276         my $dir=attachment_holding_location(scalar $form->field('page'));
277         foreach my $filename (glob("$dir/*")) {
278                 $filename=Encode::decode_utf8($filename);
279                 next unless -f $filename;
280                 my $destdir=linkpage(IkiWiki::possibly_foolish_untaint(
281                         attachment_location(scalar $form->field('page'))));
282                 my $absdestdir=$config{srcdir}."/".$destdir;
283                 my $destfile=IkiWiki::basename($filename);
284                 my $dest=$absdestdir.$destfile;
285                 unlink($dest);
286                 IkiWiki::prep_writefile($destfile, $absdestdir);
287                 rename($filename, $dest);
288                 push @attachments, $destdir.$destfile;
289         }
290         return unless @attachments;
291         require IkiWiki::Render;
292         IkiWiki::prune($dir, $config{wikistatedir}."/attachments");
294         # Check the attachments in and trigger a wiki refresh.
295         if ($config{rcs}) {
296                 IkiWiki::rcs_add($_) foreach @attachments;
297                 IkiWiki::disable_commit_hook();
298                 IkiWiki::rcs_commit_staged(
299                         message => gettext("attachment upload"),
300                         session => $session,
301                 );
302                 IkiWiki::enable_commit_hook();
303                 IkiWiki::rcs_update();
304         }
305         IkiWiki::refresh();
306         IkiWiki::saveindex();
309 sub attachment_location ($) {
310         my $page=shift;
311         
312         # Put the attachment in a subdir of the page it's attached
313         # to, unless that page is the "index" page.
314         return "" if $page eq 'index';
315         $page.="/" if length $page;
316         
317         return $page;
320 sub attachment_list ($) {
321         my $page=shift;
322         my $loc=attachment_location($page);
324         my $std=sub {
325                 my $file=shift;
326                 my $mtime=shift;
327                 my $date=shift;
328                 my $size=shift;
330                 name => $file,
331                 size => IkiWiki::Plugin::filecheck::humansize($size),
332                 mtime => $date,
333                 mtime_raw => $mtime,
334         };
336         # attachments already in the wiki
337         my %attachments;
338         foreach my $f (values %pagesources) {
339                 if (! defined pagetype($f) &&
340                     $f=~m/^\Q$loc\E[^\/]+$/) {
341                         $attachments{$f}={
342                                 $std->($f, $IkiWiki::pagemtime{$f}, displaytime($IkiWiki::pagemtime{$f}), (stat($f))[7]),
343                                 link => htmllink($page, $page, $f, noimageinline => 1),
344                         };
345                 }
346         }
347         
348         # attachments in holding directory
349         my $dir=attachment_holding_location($page);
350         my $heldmsg=gettext("this attachment is not yet saved");
351         foreach my $file (glob("$dir/*")) {
352                 $file=Encode::decode_utf8($file);
353                 next unless -f $file;
354                 my $base=IkiWiki::basename($file);
355                 my $f=$loc.$base;
356                 $attachments{$f}={
357                         $std->($f, (stat($file))[9]*2, stored_msg(), (stat(_))[7]),
358                         link => $base,
359                 }
360         }
362         # Sort newer attachments to the end of the list.
363         return sort { $a->{mtime_raw} <=> $b->{mtime_raw} || $a->{link} cmp $b->{link} }
364                 values %attachments;
367 sub stored_msg {
368         gettext("just uploaded");
371 sub json_response ($$$$) {
372         my $q=shift;
373         my $form=shift;
374         my $filename=shift;
375         my $stored_msg=shift;
377         if (! defined $form->submitted ||
378             $form->submitted ne "Upload Attachment") {
379                 eval q{use JSON};
380                 error $@ if $@;
381                 print "Content-type: text/html\n\n";
382                 my $size=-s $filename;
383                 print to_json([
384                         {
385                                 name => IkiWiki::basename($filename),
386                                 size => $size,
387                                 humansize => IkiWiki::Plugin::filecheck::humansize($size),
388                                 stored_msg => $stored_msg,
389                                 
390                         }
391                 ]);
392                 exit 0;
393         }