comments: Fix XSS security hole due to missing validation of page name.
[ikiwiki.git] / IkiWiki / Plugin / aggregate.pm
blob59185e97ffdd43eb283fbbf2d454cbbb40b3d894
1 #!/usr/bin/perl
2 # Feed aggregation plugin.
3 package IkiWiki::Plugin::aggregate;
5 use warnings;
6 use strict;
7 use IkiWiki 3.00;
8 use HTML::Parser;
9 use HTML::Tagset;
10 use HTML::Entities;
11 use open qw{:utf8 :std};
13 my %feeds;
14 my %guids;
16 sub import {
17 hook(type => "getopt", id => "aggregate", call => \&getopt);
18 hook(type => "getsetup", id => "aggregate", call => \&getsetup);
19 hook(type => "checkconfig", id => "aggregate", call => \&checkconfig);
20 hook(type => "needsbuild", id => "aggregate", call => \&needsbuild);
21 hook(type => "preprocess", id => "aggregate", call => \&preprocess);
22 hook(type => "delete", id => "aggregate", call => \&delete);
23 hook(type => "savestate", id => "aggregate", call => \&savestate);
24 hook(type => "htmlize", id => "_aggregated", call => \&htmlize);
25 if (exists $config{aggregate_webtrigger} && $config{aggregate_webtrigger}) {
26 hook(type => "cgi", id => "aggregate", call => \&cgi);
30 sub getopt () {
31 eval q{use Getopt::Long};
32 error($@) if $@;
33 Getopt::Long::Configure('pass_through');
34 GetOptions(
35 "aggregate" => \$config{aggregate},
36 "aggregateinternal!" => \$config{aggregateinternal},
40 sub getsetup () {
41 return
42 plugin => {
43 safe => 1,
44 rebuild => undef,
46 aggregateinternal => {
47 type => "boolean",
48 example => 1,
49 description => "enable aggregation to internal pages?",
50 safe => 0, # enabling needs manual transition
51 rebuild => 0,
53 aggregate_webtrigger => {
54 type => "boolean",
55 example => 0,
56 description => "allow aggregation to be triggered via the web?",
57 safe => 1,
58 rebuild => 0,
62 sub checkconfig () {
63 if (! defined $config{aggregateinternal}) {
64 $config{aggregateinternal}=1;
67 if ($config{aggregate} && ! ($config{post_commit} &&
68 IkiWiki::commit_hook_enabled())) {
69 launchaggregation();
73 sub cgi ($) {
74 my $cgi=shift;
76 if (defined $cgi->param('do') &&
77 $cgi->param("do") eq "aggregate_webtrigger") {
78 $|=1;
79 print "Content-Type: text/plain\n\n";
80 $config{cgi}=0;
81 $config{verbose}=1;
82 $config{syslog}=0;
83 print gettext("Aggregation triggered via web.")."\n\n";
84 if (launchaggregation()) {
85 IkiWiki::lockwiki();
86 IkiWiki::loadindex();
87 require IkiWiki::Render;
88 IkiWiki::refresh();
89 IkiWiki::saveindex();
91 else {
92 print gettext("Nothing to do right now, all feeds are up-to-date!")."\n";
94 exit 0;
98 sub launchaggregation () {
99 # See if any feeds need aggregation.
100 loadstate();
101 my @feeds=needsaggregate();
102 return unless @feeds;
103 if (! lockaggregate()) {
104 debug("an aggregation process is already running");
105 return;
107 # force a later rebuild of source pages
108 $IkiWiki::forcerebuild{$_->{sourcepage}}=1
109 foreach @feeds;
111 # Fork a child process to handle the aggregation.
112 # The parent process will then handle building the
113 # result. This avoids messy code to clear state
114 # accumulated while aggregating.
115 defined(my $pid = fork) or error("Can't fork: $!");
116 if (! $pid) {
117 IkiWiki::loadindex();
118 # Aggregation happens without the main wiki lock
119 # being held. This allows editing pages etc while
120 # aggregation is running.
121 aggregate(@feeds);
123 IkiWiki::lockwiki;
124 # Merge changes, since aggregation state may have
125 # changed on disk while the aggregation was happening.
126 mergestate();
127 expire();
128 savestate();
129 IkiWiki::unlockwiki;
130 exit 0;
132 waitpid($pid,0);
133 if ($?) {
134 error "aggregation failed with code $?";
137 clearstate();
138 unlockaggregate();
140 return 1;
143 # Pages with extension _aggregated have plain html markup, pass through.
144 sub htmlize (@) {
145 my %params=@_;
146 return $params{content};
149 # Used by ikiwiki-transition aggregateinternal.
150 sub migrate_to_internal {
151 if (! lockaggregate()) {
152 error("an aggregation process is currently running");
155 IkiWiki::lockwiki();
156 loadstate();
157 $config{verbose}=1;
159 foreach my $data (values %guids) {
160 next unless $data->{page};
161 next if $data->{expired};
163 $config{aggregateinternal} = 0;
164 my $oldname = "$config{srcdir}/".htmlfn($data->{page});
165 my $oldoutput = $config{destdir}."/".IkiWiki::htmlpage($data->{page});
167 $config{aggregateinternal} = 1;
168 my $newname = "$config{srcdir}/".htmlfn($data->{page});
170 debug "moving $oldname -> $newname";
171 if (-e $newname) {
172 if (-e $oldname) {
173 error("$newname already exists");
175 else {
176 debug("already renamed to $newname?");
179 elsif (-e $oldname) {
180 rename($oldname, $newname) || error("$!");
182 else {
183 debug("$oldname not found");
185 if (-e $oldoutput) {
186 require IkiWiki::Render;
187 debug("removing output file $oldoutput");
188 IkiWiki::prune($oldoutput);
192 savestate();
193 IkiWiki::unlockwiki;
195 unlockaggregate();
198 sub needsbuild (@) {
199 my $needsbuild=shift;
201 loadstate();
203 foreach my $feed (values %feeds) {
204 if (exists $pagesources{$feed->{sourcepage}} &&
205 grep { $_ eq $pagesources{$feed->{sourcepage}} } @$needsbuild) {
206 # Mark all feeds originating on this page as
207 # not yet seen; preprocess will unmark those that
208 # still exist.
209 markunseen($feed->{sourcepage});
213 return $needsbuild;
216 sub preprocess (@) {
217 my %params=@_;
219 foreach my $required (qw{name url}) {
220 if (! exists $params{$required}) {
221 error sprintf(gettext("missing %s parameter"), $required)
225 my $feed={};
226 my $name=$params{name};
227 if (exists $feeds{$name}) {
228 $feed=$feeds{$name};
230 else {
231 $feeds{$name}=$feed;
233 $feed->{name}=$name;
234 $feed->{sourcepage}=$params{page};
235 $feed->{url}=$params{url};
236 my $dir=exists $params{dir} ? $params{dir} : $params{page}."/".titlepage($params{name});
237 $dir=~s/^\/+//;
238 ($dir)=$dir=~/$config{wiki_file_regexp}/;
239 $feed->{dir}=$dir;
240 $feed->{feedurl}=defined $params{feedurl} ? $params{feedurl} : "";
241 $feed->{updateinterval}=defined $params{updateinterval} ? $params{updateinterval} * 60 : 15 * 60;
242 $feed->{expireage}=defined $params{expireage} ? $params{expireage} : 0;
243 $feed->{expirecount}=defined $params{expirecount} ? $params{expirecount} : 0;
244 if (exists $params{template}) {
245 $params{template}=~s/[^-_a-zA-Z0-9]+//g;
247 else {
248 $params{template} = "aggregatepost"
250 $feed->{template}=$params{template} . ".tmpl";
251 delete $feed->{unseen};
252 $feed->{lastupdate}=0 unless defined $feed->{lastupdate};
253 $feed->{lasttry}=$feed->{lastupdate} unless defined $feed->{lasttry};
254 $feed->{numposts}=0 unless defined $feed->{numposts};
255 $feed->{newposts}=0 unless defined $feed->{newposts};
256 $feed->{message}=gettext("new feed") unless defined $feed->{message};
257 $feed->{error}=0 unless defined $feed->{error};
258 $feed->{tags}=[];
259 while (@_) {
260 my $key=shift;
261 my $value=shift;
262 if ($key eq 'tag') {
263 push @{$feed->{tags}}, $value;
267 return "<a href=\"".$feed->{url}."\">".$feed->{name}."</a>: ".
268 ($feed->{error} ? "<em>" : "").$feed->{message}.
269 ($feed->{error} ? "</em>" : "").
270 " (".$feed->{numposts}." ".gettext("posts").
271 ($feed->{newposts} ? "; ".$feed->{newposts}.
272 " ".gettext("new") : "").
273 ")";
276 sub delete (@) {
277 my @files=@_;
279 # Remove feed data for removed pages.
280 foreach my $file (@files) {
281 my $page=pagename($file);
282 markunseen($page);
286 sub markunseen ($) {
287 my $page=shift;
289 foreach my $id (keys %feeds) {
290 if ($feeds{$id}->{sourcepage} eq $page) {
291 $feeds{$id}->{unseen}=1;
296 my $state_loaded=0;
298 sub loadstate () {
299 return if $state_loaded;
300 $state_loaded=1;
301 if (-e "$config{wikistatedir}/aggregate") {
302 open(IN, "<", "$config{wikistatedir}/aggregate") ||
303 die "$config{wikistatedir}/aggregate: $!";
304 while (<IN>) {
305 $_=IkiWiki::possibly_foolish_untaint($_);
306 chomp;
307 my $data={};
308 foreach my $i (split(/ /, $_)) {
309 my ($field, $val)=split(/=/, $i, 2);
310 if ($field eq "name" || $field eq "feed" ||
311 $field eq "guid" || $field eq "message") {
312 $data->{$field}=decode_entities($val, " \t\n");
314 elsif ($field eq "tag") {
315 push @{$data->{tags}}, $val;
317 else {
318 $data->{$field}=$val;
322 if (exists $data->{name}) {
323 $feeds{$data->{name}}=$data;
325 elsif (exists $data->{guid}) {
326 $guids{$data->{guid}}=$data;
330 close IN;
334 sub savestate () {
335 return unless $state_loaded;
336 garbage_collect();
337 my $newfile="$config{wikistatedir}/aggregate.new";
338 my $cleanup = sub { unlink($newfile) };
339 open (OUT, ">", $newfile) || error("open $newfile: $!", $cleanup);
340 foreach my $data (values %feeds, values %guids) {
341 my @line;
342 foreach my $field (keys %$data) {
343 if ($field eq "name" || $field eq "feed" ||
344 $field eq "guid" || $field eq "message") {
345 push @line, "$field=".encode_entities($data->{$field}, " \t\n");
347 elsif ($field eq "tags") {
348 push @line, "tag=$_" foreach @{$data->{tags}};
350 else {
351 push @line, "$field=".$data->{$field}
352 if defined $data->{$field};
355 print OUT join(" ", @line)."\n" || error("write $newfile: $!", $cleanup);
357 close OUT || error("save $newfile: $!", $cleanup);
358 rename($newfile, "$config{wikistatedir}/aggregate") ||
359 error("rename $newfile: $!", $cleanup);
361 my $timestamp=undef;
362 foreach my $feed (keys %feeds) {
363 my $t=$feeds{$feed}->{lastupdate}+$feeds{$feed}->{updateinterval};
364 if (! defined $timestamp || $timestamp > $t) {
365 $timestamp=$t;
368 $newfile=~s/\.new$/time/;
369 open (OUT, ">", $newfile) || error("open $newfile: $!", $cleanup);
370 if (defined $timestamp) {
371 print OUT $timestamp."\n";
373 close OUT || error("save $newfile: $!", $cleanup);
376 sub garbage_collect () {
377 foreach my $name (keys %feeds) {
378 # remove any feeds that were not seen while building the pages
379 # that used to contain them
380 if ($feeds{$name}->{unseen}) {
381 delete $feeds{$name};
385 foreach my $guid (values %guids) {
386 # any guid whose feed is gone should be removed
387 if (! exists $feeds{$guid->{feed}}) {
388 unlink "$config{srcdir}/".htmlfn($guid->{page})
389 if exists $guid->{page};
390 delete $guids{$guid->{guid}};
392 # handle expired guids
393 elsif ($guid->{expired} && exists $guid->{page}) {
394 unlink "$config{srcdir}/".htmlfn($guid->{page});
395 delete $guid->{page};
396 delete $guid->{md5};
401 sub mergestate () {
402 # Load the current state in from disk, and merge into it
403 # values from the state in memory that might have changed
404 # during aggregation.
405 my %myfeeds=%feeds;
406 my %myguids=%guids;
407 clearstate();
408 loadstate();
410 # All that can change in feed state during aggregation is a few
411 # fields.
412 foreach my $name (keys %myfeeds) {
413 if (exists $feeds{$name}) {
414 foreach my $field (qw{message lastupdate lasttry
415 numposts newposts error}) {
416 $feeds{$name}->{$field}=$myfeeds{$name}->{$field};
421 # New guids can be created during aggregation.
422 # Guids have a few fields that may be updated during aggregation.
423 # It's also possible that guids were removed from the on-disk state
424 # while the aggregation was in process. That would only happen if
425 # their feed was also removed, so any removed guids added back here
426 # will be garbage collected later.
427 foreach my $guid (keys %myguids) {
428 if (! exists $guids{$guid}) {
429 $guids{$guid}=$myguids{$guid};
431 else {
432 foreach my $field (qw{md5}) {
433 $guids{$guid}->{$field}=$myguids{$guid}->{$field};
439 sub clearstate () {
440 %feeds=();
441 %guids=();
442 $state_loaded=0;
445 sub expire () {
446 foreach my $feed (values %feeds) {
447 next unless $feed->{expireage} || $feed->{expirecount};
448 my $count=0;
449 my %seen;
450 foreach my $item (sort { ($IkiWiki::pagectime{$b->{page}} || 0) <=> ($IkiWiki::pagectime{$a->{page}} || 0) }
451 grep { exists $_->{page} && $_->{feed} eq $feed->{name} }
452 values %guids) {
453 if ($feed->{expireage}) {
454 my $days_old = (time - ($IkiWiki::pagectime{$item->{page}} || 0)) / 60 / 60 / 24;
455 if ($days_old > $feed->{expireage}) {
456 debug(sprintf(gettext("expiring %s (%s days old)"),
457 $item->{page}, int($days_old)));
458 $item->{expired}=1;
461 elsif ($feed->{expirecount} &&
462 $count >= $feed->{expirecount}) {
463 debug(sprintf(gettext("expiring %s"), $item->{page}));
464 $item->{expired}=1;
466 else {
467 if (! $seen{$item->{page}}) {
468 $seen{$item->{page}}=1;
469 $count++;
476 sub needsaggregate () {
477 return values %feeds if $config{rebuild};
478 return grep { time - $_->{lastupdate} >= $_->{updateinterval} } values %feeds;
481 sub aggregate (@) {
482 eval q{use XML::Feed};
483 error($@) if $@;
484 eval q{use URI::Fetch};
485 error($@) if $@;
487 foreach my $feed (@_) {
488 $feed->{lasttry}=time;
489 $feed->{newposts}=0;
490 $feed->{message}=sprintf(gettext("last checked %s"),
491 displaytime($feed->{lasttry}));
492 $feed->{error}=0;
494 debug(sprintf(gettext("checking feed %s ..."), $feed->{name}));
496 if (! length $feed->{feedurl}) {
497 my @urls=XML::Feed->find_feeds($feed->{url});
498 if (! @urls) {
499 $feed->{message}=sprintf(gettext("could not find feed at %s"), $feed->{url});
500 $feed->{error}=1;
501 debug($feed->{message});
502 next;
504 $feed->{feedurl}=pop @urls;
506 my $res=URI::Fetch->fetch($feed->{feedurl});
507 if (! $res) {
508 $feed->{message}=URI::Fetch->errstr;
509 $feed->{error}=1;
510 debug($feed->{message});
511 next;
514 # lastupdate is only set if we were able to contact the server
515 $feed->{lastupdate}=$feed->{lasttry};
517 if ($res->status == URI::Fetch::URI_GONE()) {
518 $feed->{message}=gettext("feed not found");
519 $feed->{error}=1;
520 debug($feed->{message});
521 next;
523 my $content=$res->content;
524 my $f=eval{XML::Feed->parse(\$content)};
525 if ($@) {
526 # One common cause of XML::Feed crashing is a feed
527 # that contains invalid UTF-8 sequences. Convert
528 # feed to ascii to try to work around.
529 $feed->{message}.=" ".sprintf(gettext("(invalid UTF-8 stripped from feed)"));
530 $f=eval {
531 $content=Encode::decode_utf8($content, 0);
532 XML::Feed->parse(\$content)
535 if ($@) {
536 # Another possibility is badly escaped entities.
537 $feed->{message}.=" ".sprintf(gettext("(feed entities escaped)"));
538 $content=~s/\&(?!amp)(\w+);/&amp;$1;/g;
539 $f=eval {
540 $content=Encode::decode_utf8($content, 0);
541 XML::Feed->parse(\$content)
544 if ($@) {
545 $feed->{message}=gettext("feed crashed XML::Feed!")." ($@)";
546 $feed->{error}=1;
547 debug($feed->{message});
548 next;
550 if (! $f) {
551 $feed->{message}=XML::Feed->errstr;
552 $feed->{error}=1;
553 debug($feed->{message});
554 next;
557 foreach my $entry ($f->entries) {
558 # XML::Feed doesn't work around XML::Atom's bizarre
559 # API, so we will. Real unicode strings? Yes please.
560 # See [[bugs/Aggregated_Atom_feeds_are_double-encoded]]
561 local $XML::Atom::ForceUnicode = 1;
563 my $c=$entry->content;
564 # atom feeds may have no content, only a summary
565 if (! defined $c && ref $entry->summary) {
566 $c=$entry->summary;
569 add_page(
570 feed => $feed,
571 copyright => $f->copyright,
572 title => defined $entry->title ? decode_entities($entry->title) : "untitled",
573 link => $entry->link,
574 content => (defined $c && defined $c->body) ? $c->body : "",
575 guid => defined $entry->id ? $entry->id : time."_".$feed->{name},
576 ctime => $entry->issued ? ($entry->issued->epoch || time) : time,
577 base => (defined $c && $c->can("base")) ? $c->base : undef,
583 sub add_page (@) {
584 my %params=@_;
586 my $feed=$params{feed};
587 my $guid={};
588 my $mtime;
589 if (exists $guids{$params{guid}}) {
590 # updating an existing post
591 $guid=$guids{$params{guid}};
592 return if $guid->{expired};
594 else {
595 # new post
596 $guid->{guid}=$params{guid};
597 $guids{$params{guid}}=$guid;
598 $mtime=$params{ctime};
599 $feed->{numposts}++;
600 $feed->{newposts}++;
602 # assign it an unused page
603 my $page=titlepage($params{title});
604 # escape slashes and periods in title so it doesn't specify
605 # directory name or trigger ".." disallowing code.
606 $page=~s!([/.])!"__".ord($1)."__"!eg;
607 $page=$feed->{dir}."/".$page;
608 ($page)=$page=~/$config{wiki_file_regexp}/;
609 if (! defined $page || ! length $page) {
610 $page=$feed->{dir}."/item";
612 my $c="";
613 while (exists $IkiWiki::pagecase{lc $page.$c} ||
614 -e "$config{srcdir}/".htmlfn($page.$c)) {
615 $c++
618 # Make sure that the file name isn't too long.
619 # NB: This doesn't check for path length limits.
620 my $max=POSIX::pathconf($config{srcdir}, &POSIX::_PC_NAME_MAX);
621 if (defined $max && length(htmlfn($page)) >= $max) {
622 $c="";
623 $page=$feed->{dir}."/item";
624 while (exists $IkiWiki::pagecase{lc $page.$c} ||
625 -e "$config{srcdir}/".htmlfn($page.$c)) {
626 $c++
630 $guid->{page}=$page;
631 debug(sprintf(gettext("creating new page %s"), $page));
633 $guid->{feed}=$feed->{name};
635 # To write or not to write? Need to avoid writing unchanged pages
636 # to avoid unneccessary rebuilding. The mtime from rss cannot be
637 # trusted; let's use a digest.
638 eval q{use Digest::MD5 'md5_hex'};
639 error($@) if $@;
640 require Encode;
641 my $digest=md5_hex(Encode::encode_utf8($params{content}));
642 return unless ! exists $guid->{md5} || $guid->{md5} ne $digest || $config{rebuild};
643 $guid->{md5}=$digest;
645 # Create the page.
646 my $template;
647 eval {
648 $template=template($feed->{template}, blind_cache => 1);
650 if ($@) {
651 print STDERR gettext("failed to process template:")." $@";
652 return;
654 $template->param(title => $params{title})
655 if defined $params{title} && length($params{title});
656 $template->param(content => wikiescape(htmlabs($params{content},
657 defined $params{base} ? $params{base} : $feed->{feedurl})));
658 $template->param(name => $feed->{name});
659 $template->param(url => $feed->{url});
660 $template->param(copyright => $params{copyright})
661 if defined $params{copyright} && length $params{copyright};
662 $template->param(permalink => IkiWiki::urlabs($params{link}, $feed->{feedurl}))
663 if defined $params{link};
664 if (ref $feed->{tags}) {
665 $template->param(tags => [map { tag => $_ }, @{$feed->{tags}}]);
667 writefile(htmlfn($guid->{page}), $config{srcdir},
668 $template->output);
670 if (defined $mtime && $mtime <= time) {
671 # Set the mtime, this lets the build process get the right
672 # creation time on record for the new page.
673 utime $mtime, $mtime, "$config{srcdir}/".htmlfn($guid->{page});
674 # Store it in pagectime for expiry code to use also.
675 $IkiWiki::pagectime{$guid->{page}}=$mtime
676 unless exists $IkiWiki::pagectime{$guid->{page}};
678 else {
679 # Dummy value for expiry code.
680 $IkiWiki::pagectime{$guid->{page}}=time
681 unless exists $IkiWiki::pagectime{$guid->{page}};
685 sub wikiescape ($) {
686 # escape accidental wikilinks and preprocessor stuff
687 return encode_entities(shift, '\[\]');
690 sub htmlabs ($$) {
691 # Convert links in html from relative to absolute.
692 # Note that this is a heuristic, which is not specified by the rss
693 # spec and may not be right for all feeds. Also, see Debian
694 # bug #381359.
695 my $html=shift;
696 my $urlbase=shift;
698 my $ret="";
699 my $p = HTML::Parser->new(api_version => 3);
700 $p->handler(default => sub { $ret.=join("", @_) }, "text");
701 $p->handler(start => sub {
702 my ($tagname, $pos, $text) = @_;
703 if (ref $HTML::Tagset::linkElements{$tagname}) {
704 while (4 <= @$pos) {
705 # use attribute sets from right to left
706 # to avoid invalidating the offsets
707 # when replacing the values
708 my($k_offset, $k_len, $v_offset, $v_len) =
709 splice(@$pos, -4);
710 my $attrname = lc(substr($text, $k_offset, $k_len));
711 next unless grep { $_ eq $attrname } @{$HTML::Tagset::linkElements{$tagname}};
712 next unless $v_offset; # 0 v_offset means no value
713 my $v = substr($text, $v_offset, $v_len);
714 $v =~ s/^([\'\"])(.*)\1$/$2/;
715 my $new_v=IkiWiki::urlabs($v, $urlbase);
716 $new_v =~ s/\"/&quot;/g; # since we quote with ""
717 substr($text, $v_offset, $v_len) = qq("$new_v");
720 $ret.=$text;
721 }, "tagname, tokenpos, text");
722 $p->parse($html);
723 $p->eof;
725 return $ret;
728 sub htmlfn ($) {
729 return shift().".".($config{aggregateinternal} ? "_aggregated" : $config{htmlext});
732 my $aggregatelock;
734 sub lockaggregate () {
735 # Take an exclusive lock to prevent multiple concurrent aggregators.
736 # Returns true if the lock was aquired.
737 if (! -d $config{wikistatedir}) {
738 mkdir($config{wikistatedir});
740 open($aggregatelock, '>', "$config{wikistatedir}/aggregatelock") ||
741 error ("cannot open to $config{wikistatedir}/aggregatelock: $!");
742 if (! flock($aggregatelock, 2 | 4)) { # LOCK_EX | LOCK_NB
743 close($aggregatelock) || error("failed closing aggregatelock: $!");
744 return 0;
746 return 1;
749 sub unlockaggregate () {
750 return close($aggregatelock) if $aggregatelock;
751 return;