Debian Codegraph @

ikisite

raw ◀ ▶
2 Debian patches touch this file
1 #!/usr/bin/perl
2 package IkiWiki::Hosting;
3
4 no lib '.';
5 use warnings;
6 use strict;
7 use IkiWiki;
8 use IkiWiki::Hosting;
9
10 my $apache_before_2_4=undef;
11
12 sub apache_before_2_4 {
13 return $apache_before_2_4 if defined $apache_before_2_4;
14 my $query_result = getshell('dpkg-query', '-W', 'apache2.2-common');
15 if ($query_result =~ m/^apache2.2-common\s+2\.[012]\./) {
16 $apache_before_2_4=1;
17 }
18 else {
19 $apache_before_2_4=0;
20 }
21 return $apache_before_2_4;
22 }
23
24 sub meta_create {
25 required => [qw{hostname}],
26 options => [qw{type=s vcs=s wikiname=s owner=s admin=s adminemail=s createnonce!}],
27 description => "create new site",
28 section => "primary",
29 }
30 sub create {
31 my $hostname=lc(shift);
32 my %options=(%config, @_);
33
34 assert_root();
35 my $nonce=$ENV{IKISITE_NONCE}; # stash for later
36 assert_wrapper_unsafe();
37
38 # All inputs are verified, so that ikisite create can be run
39 # from a suid wrapper.
40 if (! exists $options{admin}) {
41 error "must specify --admin=username";
42 }
43 if (! defined IkiWiki::openiduser($options{admin}) && ! defined IkiWiki::emailuser($options{admin})) {
44 error "$options{admin} is not a valid openid or email";
45 }
46 my $owner=exists $options{owner} ? $options{owner} : $options{admin};
47 if (! defined IkiWiki::openiduser($owner) && ! defined IkiWiki::emailuser($owner)) {
48 error "$owner is not a valid openid or email";
49 }
50 if ($options{vcs} !~ /^(git)$/) {
51 error "unsupported vcs $options{vcs}";
52 }
53
54 # This will also fail if the hostname is invalid.
55 locksite($hostname);
56 assert_siteexists($hostname, 0);
57
58 # Avoid path traversal etc when looking up autosetup file.
59 $options{type}=~s/[^-a-zA-Z0-9]//g if defined $options{type};
60
61 if (! isemail($options{adminemail})) {
62 $options{adminemail}=$config{adminemail};
63 }
64 if (! defined $options{wikiname} || ! length $options{wikiname}) {
65 $options{wikiname}=wikiname($hostname);
66 }
67
68 # Create user
69 usercreate($hostname);
70 my $home = homedir($hostname);
71
72 # Enable DNS early, to help give it time to propigate.
73 enabledns($hostname);
74
75 # Setup ikiwiki. It creates the VCS repository, and builds
76 # the site. Configuration is passed in via the environment.
77 $ENV{IKIWIKI_WIKINAME}=$options{wikiname};
78 $ENV{IKIWIKI_HOSTNAME}=$hostname;
79 $ENV{IKIWIKI_VCS}=$options{vcs};
80 $ENV{IKIWIKI_REPOSITORY}=$home."/source.$options{vcs}";
81 $ENV{IKIWIKI_ADMIN}=$options{admin};
82 $ENV{IKIWIKI_OWNER}=$owner;
83 $ENV{IKIWIKI_CREATED}=time;
84 $ENV{IKIWIKI_ADMINEMAIL}=$options{adminemail};
85 $ENV{IKIWIKI_SRCDIR}=srcdir($hostname);
86 $ENV{IKIWIKI_DESTDIR}=destdir($hostname);
87 $ENV{IKIWIKI_CGIDIR}=cgidir($hostname);
88 $ENV{IKIWIKI_LOGDIR}=logdir($hostname);
89 $ENV{IKIWIKI_OPENID_REALM}=$config{openid_realm};
90 $ENV{IKIWIKI_GITDAEMONUSER}=$config{gitdaemonuser};
91 # This is normally 06755, but for new users (with suexec) we can't use
92 # suid/sgid
93 $ENV{IKIWIKI_CGI_WRAPPERMODE}="0755";
94 $ENV{IKIWIKI_GIT_WRAPPERMODE}="6755";
95 my $autosetup=defined $options{type} ? "$config{autosetupdir}/auto-$options{type}.setup" : undef;
96 if (! defined $autosetup || ! -e $autosetup) {
97 $autosetup="$config{autosetupdir}/auto.setup";
98 }
99 add_wikilist($hostname);
100 eval q{use Cwd q{abs_path}};
101 $autosetup=abs_path($autosetup);
102 runas(username($hostname), sub {
103 chdir($home) || error "chdir $home: $!";
104 shell("ikiwiki", "-setup", $autosetup);
105 chmod(0600, "$home/ikiwiki.setup") || error "chmod $home/ikiwiki.setup: $!";
106 chmod(0700, "$home/source") || error "chmod $home/source: $!";
107 });
108
109 if ($options{vcs} eq "git") {
110 githooks($ENV{IKIWIKI_REPOSITORY});
111 }
112
113 createsetupbranch($hostname);
114
115 calendar($hostname);
116
117 enable($hostname);
118
119 accountinglog("create", $hostname, $owner);
120
121 if ($options{createnonce}) {
122 # If IKISITE_NONCE was set to a non-dummy nonce
123 # initially, create a nonce with that value.
124 if (defined $nonce && $nonce ne 'dummy') {
125 return createnonce($hostname, value => $nonce);
126 }
127 else {
128 return createnonce($hostname);
129 }
130 }
131 else {
132 return 1;
133 }
134 }
135
136 sub meta_delete {
137 required => [qw{hostname}],
138 options => [qw{}],
139 description => "delete a site",
140 section => "primary",
141 }
142 sub delete {
143 my $hostname=lc(shift);
144
145 assert_root();
146 locksite($hostname);
147 assert_siteexists($hostname, 1);
148 assert_wrapper_safe($hostname);
149
150 accountinglog("delete", $hostname);
151
152 disable($hostname);
153 ikiwikiclean($hostname);
154 if ($config{morguedir}) {
155 backup($hostname, morgue => 1);
156 }
157 remove_letsencrypt_config($hostname);
158 userdelete($hostname);
159 }
160
161 sub meta_backup {
162 required => [qw{hostname}],
163 options => [qw{filename=s morgue stdout srconly}],
164 description => "back up a site to the specified output",
165 section => "primary",
166 }
167 sub backup {
168 my $hostname=lc(shift);
169 my %options=@_;
170
171 assert_root();
172 locksite($hostname);
173 assert_siteexists($hostname, 1);
174 assert_wrapper_denied();
175
176 my $file;
177 if ($options{stdout}) {
178 $file="/dev/stdout";
179 }
180 elsif ($options{morgue}) {
181 if (! $config{morguedir}) {
182 error "morguedir not set (configure in $config{ikisite_conffile})";
183 }
184 shell("mkdir", "-p", $config{morguedir});
185 $file=$config{morguedir}."/$hostname.backup";
186 }
187 elsif (defined $options{filename}) {
188 eval q{use Cwd q{abs_path}};
189 error $@ if $@;
190 $file=abs_path($options{filename});
191 }
192 else {
193 error "must specify --filename=value or --morgue or --stdout"
194 }
195
196 # Ensure setup and wiki state are committed to the setup branch.
197 # Note that since this pushes into the repo, it triggers ikiwiki
198 # to run, and thus it must come before lockwiki, to avoid a
199 # deadlock.
200 commitsetup($hostname);
201
202 # Generate VCS dump.
203 my $vcs=getsetup($hostname, "rcs");
204 my $dump=homedir($hostname)."/$vcs.dump";
205 my @tobackup="$vcs.dump";
206 if (-e $dump) {
207 unlink($dump) || error("unlink $dump: $!");
208 }
209 if ($vcs eq "git") {
210 chdir(repository($hostname)) || error "chdir repository: $!";
211 # The wiki is not locked while this is run to the git repo
212 # could be changed; this assumes that git is reasonably
213 # atomic in its updating of eg, refs, so that the bundle
214 # will either see the new or old refs, and not no refs.
215 # Also, this relies on git writing objects before
216 # updating the refs to point to them.
217 runas(username($hostname), sub {
218 shell("git", "bundle", "create", $dump, "--all");
219 });
220 # git bundle does not preserve git's config file,
221 # so that will be backed up separately.
222 push @tobackup, repository($hostname)."/config";
223 }
224 else {
225 error "backup not implemented for $vcs";
226 }
227
228 foreach my $extrafile (glob(homedir($hostname)."/.ssh/id_*"),
229 homedir($hostname)."/.ssh/known_hosts",
230 glob(homedir($hostname)."/apache/*"),) {
231 push @tobackup, $extrafile if -e $extrafile;
232 }
233
234 # Copy rootconfig into home directory so it can be included
235 # in backup. Nuke ~/rootconfig if it already exists;
236 # the user should not be allowed to add files to rootconfig!
237 my $tmprootconfig=homedir($hostname)."/rootconfig/";
238 my @rootconfigs=glob(rootconfig($hostname)."/*");
239 if (@rootconfigs) {
240 if (! mkdir($tmprootconfig)) {
241 system("rm", "-rf", $tmprootconfig);
242 if (! mkdir("rootconfig")) {
243 error "failed to create $tmprootconfig directory: $!";
244 }
245 }
246
247 foreach my $config (@rootconfigs) {
248 shell("cp", "-a", $config, $tmprootconfig."/");
249 }
250 push @tobackup, $tmprootconfig;
251 }
252
253 # Prepare for running tar
254 chdir(homedir($hostname)) || error "chdir HOME: $!";
255 my $umask=umask(0277); # owner read-only backup file
256 my $homedir=homedir($hostname);
257 my $runtar=sub {
258 my $l=shift;
259 shell("tar", @_, $file,
260 map {
261 # avoid full paths to home directory in tarball
262 my $f=$_;
263 $f=~s/\Q$homedir\E\///;
264 $f;
265 } @$l,
266 "--owner=root", "--group=root");
267 };
268
269 # Back up the wiki's state files.
270 # The wiki is locked while doing this, to avoid any files being
271 # in an inconsistent state during backup. To keep it locked
272 # for a minimum time, the backup tarball is created here,
273 # containing only the state files, and the other files in @tobackup
274 # will be appended later once the lock is released.
275 $config{wikistatedir}=srcdir($hostname)."/.ikiwiki";
276 IkiWiki::lockwiki();
277 my @tobackupfirst;
278 if (! $options{srconly}) {
279 # sessions.db is not included. The file can get quite large
280 # and the worst that will happen if it's lost is users
281 # have to log back in earlier than usuual.
282 foreach my $ikifile (qw{indexdb userdb transient}) {
283 my $f=srcdir($hostname)."/.ikiwiki/$ikifile";
284 push @tobackupfirst, $f if -e $f;
285 }
286 $runtar->(\@tobackupfirst, "cf")
287 if @tobackupfirst;
288 }
289 IkiWiki::unlockwiki();
290
291 # Back up everything else.
292 if (@tobackupfirst) {
293 $runtar->(\@tobackup, "--append", "-f");
294 }
295 else {
296 $runtar->(\@tobackup, "cf");
297 }
298
299 # Cleanup.
300 umask($umask);
301 unlink($dump);
302 shell("rm", "-rf", $tmprootconfig);
303
304 return; # avoid writing status to stdout
305 }
306
307 sub meta_restore {
308 required => [qw{hostname}],
309 options => [qw{filename=s morgue! stdin! no-setup! no-sshkeys!}],
310 description => "restore a site from the specified input",
311 section => "primary",
312 }
313 sub restore {
314 my $hostname=lc(shift);
315 my %options=@_;
316
317 assert_root();
318 locksite($hostname);
319 assert_siteexists($hostname, 0);
320 assert_wrapper_denied();
321
322 my $file;
323 if ($options{stdin}) {
324 $file="/dev/stdin";
325 }
326 elsif ($options{morgue}) {
327 if (! $config{morguedir}) {
328 error "morguedir not set (configure in $config{ikisite_conffile})";
329 }
330 $file=$config{morguedir}."/$hostname.backup";
331 }
332 elsif (defined $options{filename}) {
333 eval q{use Cwd q{abs_path}};
334 error $@ if $@;
335 $file=abs_path($options{filename});
336 }
337 else {
338 error "must specify --filename=value or --morgue or --stdin"
339 }
340
341 if (! -e $file) {
342 error "$file does not exist";
343 }
344
345 usercreate($hostname);
346
347 # Enable DNS early, to help give it time to propigate.
348 enabledns($hostname) unless $options{"no-setup"};
349
350 # Extract the VCS dump from the backup tarball.
351 chdir(homedir($hostname)) || error "chdir HOME: $!";
352 shell("tar", "xf", $file, "--wildcards", "*.dump");
353 my $dump=glob("*.dump");
354 my ($vcs)=$dump=~/(.*)\.dump/;
355 my $repository="source.$vcs";
356
357 # Extract repository from VCS dump and then check out the source
358 # and setup branches from VCS. Since VCS typically have issues
359 # around checking out directly into an existing home directory,
360 # setup is extracted into a home-tmp.
361 if ($vcs eq "git") {
362 shell("git", "clone", $dump, $repository, "--bare");
363 # denyNonFastforwards and sharedrepository are normally
364 # set by git init --shared; replicate that in our bare clone.
365 chdir($repository) || error "chdir repository: $!";
366 shell("git", "config", "core.sharedrepository", 1);
367 shell("git", "config", "receive.denyNonFastforwards", "true");
368 chdir(homedir($hostname)) || error "chdir HOME: $!";
369
370 githooks($repository);
371
372 shell("git", "clone", $repository, "source");
373 shell("git", "clone", $repository, "home-tmp",
374 "--branch", "setup");
375
376 chmod(0700, "source") || error "chmod source: $!";
377 chmod(0700, "home-tmp/.git") || error "chmod home-tmp/.git: $!";
378 chmod(0600, "home-tmp/ikiwiki.setup") || error "chmod home-tmp/ikiwiki.setup: $!";
379 chmod(0600, "home-tmp/.gitignore") || error "chmod home-tmp/.gitignore: $!"
380 if -e "home-tmp/.gitignore";
381 }
382 else {
383 error "restore not implemented for $vcs";
384 }
385 unlink($dump) || error "unlink: $!";
386
387 # XXX Using rsync to merge the tree in means more disk IO
388 # than strictly necessary. But is easy.
389 shell("rsync", "-a", "--exclude=.ssh/", "home-tmp/", ".");
390
391 # Extract remainder of backup tarball.
392 shell("tar", "xf", $file, "--exclude", $dump);
393
394 # Move rootconfig into place.
395 if (-d "rootconfig") {
396 shell("rm", "-rf", rootconfig($hostname));
397 shell("mv", "rootconfig", rootconfig($hostname));
398 }
399
400 # Make all extracted files be owned by the user.
401 my $username=username($hostname);
402 shell("chown", "$username:$username", "-R", ".");
403
404 # apache/ should be readable by www-data.
405 if (-d "apache") {
406 shell("chgrp", "www-data", "apache");
407 chmod(0750, "apache") || error "chmod apache: $!";
408 }
409
410 if (! $options{'no-sshkeys'}) {
411 # Restore ssh last, to ensure the git repo is set up
412 # before any attempt is made to push changes into it.
413 foreach my $file (glob("home-tmp/.ssh/*")) {
414 if (-f $file) {
415 shell("mv", "-f", $file,
416 ".ssh/".IkiWiki::basename($file));
417 }
418
419 }
420 # ssh requires this file be mode 400, and most
421 # VCS do not preserve the mode.
422 shell("chmod", "400", ".ssh/authorized_keys")
423 if -e ".ssh/authorized_keys";
424 }
425 else {
426 # record that the ssh keys were dropped
427 commitsetup($hostname);
428 }
429
430 shell("rm", "-rf", "home-tmp");
431
432 if (! $options{"no-setup"}) {
433 ikiwikisetup($hostname);
434 enable($hostname);
435 accountinglog("create", $hostname, getsetup($hostname, "owner"));
436 }
437
438 # This is the same as IkiWiki::Setup::Automator does when
439 # creating a new site.
440 runas($username, sub {
441 mkdir(homedir($hostname)."/.ikiwiki");
442 open (WIKILIST, ">", homedir($hostname)."/.ikiwiki/wikilist") || die "wikilist: $!";
443 print WIKILIST $username." ".homedir($hostname)."/ikiwiki.setup\n";
444 close WIKILIST;
445 });
446 add_wikilist($hostname);
447
448 return 1;
449 }
450
451 sub meta_branch {
452 required => [qw{oldhostname newhostname}],
453 options => [qw{owner=s admin=s ... adminemail=s wikiname=s createnonce!}],
454 description => "generate a branch of a site with a new hostname,
455 optionally with a different admin",
456 section => "primary",
457 }
458 sub branch {
459 my $oldhostname=lc(shift);
460 my $newhostname=lc(shift);
461 my %options=@_;
462
463 assert_root();
464 my $nonce=$ENV{IKISITE_NONCE}; # stash for later
465 assert_wrapper_unsafe();
466
467 # All inputs are verified, so that ikisite create can be run
468 # from a suid wrapper.
469 my $adminchanged=0;
470 my %oldadmin=map { $_ => 1 } @{getsetup($oldhostname, "adminuser")};
471 my $owner=$options{owner};
472 if (exists $options{admin}) {
473 foreach my $admin (@{$options{admin}}) {
474 if (! defined IkiWiki::openiduser($admin) && ! defined IkiWiki::emailuser($admin)) {
475 error "$admin is not a valid openid or email";
476 }
477 if (! exists $oldadmin{$admin}) {
478 $adminchanged=1;
479 }
480 $owner=$admin unless defined $owner;
481 }
482 }
483 if (defined $owner && ! defined IkiWiki::openiduser($owner) && ! defined IkiWiki::emailuser($owner)) {
484 error "$owner is not a valid openid or email";
485 }
486
487 # These will also fail if the hostnames are invalid.
488 locksite($oldhostname);
489 assert_siteexists($oldhostname, 1);
490 locksite($newhostname);
491 assert_siteexists($newhostname, 0);
492
493 # The adminemail must be changed when the admin is changed.
494 # If it's not valid, use the default value.
495 if (exists $options{adminemail} && ! isemail($options{adminemail})) {
496 $options{adminemail}=$config{adminemail};
497 }
498 if (! exists $options{adminemail} && $adminchanged) {
499 $options{adminemail}=$config{adminemail};
500 }
501
502 eval q{use File::Temp};
503 my ($tempfh, $tempfile) = File::Temp::tempfile(UNLINK => 1);
504 backup($oldhostname, filename => $tempfile);
505 restore($newhostname, filename => $tempfile, "no-setup" => 1,
506 # don't include database files in branch
507 # (no email subscriptions, etc)
508 srconly => 1,
509 # when admin is changed, do not copy ssh keys from
510 # oldhostname
511 "no-sshkeys" => ($adminchanged ? 1 : 0));
512
513 # Enable DNS early, to help give it time to propigate.
514 enabledns($newhostname);
515
516 my $vcs=getsetup($oldhostname, "rcs");
517 my $vcswrapper;
518 # XXX this duplicates code from IkiWiki::Setup::Automator
519 if ($vcs eq 'git') {
520 $vcswrapper=repository($newhostname)."/hooks/post-update";
521 }
522 else {
523 error "branch not implemented for $vcs";
524 }
525
526 # The srcdir may be inside a subdirectory of the
527 # repo. If so, this should be preserved when branching.
528 my $oldsrcdir=srcdir($oldhostname);
529 my $oldhomedir=homedir($oldhostname);
530 $oldsrcdir=~s/^\Q$oldhomedir\E\//\//;
531 my $srcdir=homedir($newhostname).$oldsrcdir;
532
533 my $historyurl=getsetup($oldhostname, "historyurl");
534 $historyurl=~s/source\.\Q$oldhostname\E/source.$newhostname/i
535 if defined $historyurl;
536 my $diffurl=getsetup($oldhostname, "diffurl");
537 $diffurl=~s/source\.\Q$oldhostname\E/source.$newhostname/i
538 if defined $diffurl;
539
540 my @settings;
541 push @settings, set => [
542 "wikiname" ."=". (exists $options{wikiname} ? $options{wikiname} : wikiname($newhostname)),
543 "srcdir" ."=". $srcdir,
544 "destdir" ."=". destdir($newhostname),
545 "url" ."=". "http://$newhostname",
546 "cgiurl" ."=". "http://$newhostname/ikiwiki.cgi",
547 "openid_cgiurl" ."=". "http://$newhostname/ikiwiki.cgi",
548 "cgi_wrapper" ."=". cgidir($newhostname)."/ikiwiki.cgi",
549 "libdir" ."=". homedir($newhostname)."/.ikiwiki",
550 $vcs."_wrapper" ."=". $vcswrapper,
551 (defined $historyurl ? "historyurl" ."=". $historyurl : ()),
552 (defined $diffurl ? "diffurl" ."=". $diffurl : ()),
553 (exists $options{adminemail} ? "adminemail=$options{adminemail}" : ()),
554 (defined $owner ? "owner=$owner" : ()),
555 "created" ."=". time,
556 "hostname" ."=". $newhostname,
557 "parent" ."=". $oldhostname,
558 ];
559
560 eval q{use YAML::Syck};
561 die $@ if $@;
562 push @settings, 'set-yaml' => [
563 "urlalias=".Dump([]),
564 ($options{admin} ? "adminuser=".Dump($options{admin}) : ()),
565 "ENV=".Dump({TMPDIR => homedir($newhostname)."/tmp"}),
566 ];
567
568 # avoid git pushes from branch unless explicitly turned back on
569 push @settings, 'disable-plugin' => ['gitpush'];
570
571 changesetup($newhostname,
572 rebuild => 1,
573 commit => 1,
574 message => "branched $newhostname from $oldhostname",
575 @settings,
576 );
577
578 if ($options{admin}) {
579 # TODO modify .ikiwiki/userdb to add new admin, if not an openid or email?
580 }
581
582 enable($newhostname);
583
584 accountinglog("create", $newhostname,
585 defined $owner ? $owner : getsetup($newhostname, "owner"));
586
587 if ($options{createnonce}) {
588 # If IKISITE_NONCE was set to a non-dummy nonce
589 # initially, create a nonce with that value.
590 if (defined $nonce && $nonce ne 'dummy') {
591 return createnonce($newhostname, value => $nonce);
592 }
593 else {
594 return createnonce($newhostname);
595 }
596 }
597 else {
598 return 1;
599 }
600 }
601
602 sub meta_rename {
603 required => [qw{oldhostname newhostname}],
604 options => [qw{}],
605 description => "rename a site to use a different hostname",
606 section => "primary",
607 }
608 sub rename {
609 my $oldhostname=lc(shift);
610 my $newhostname=lc(shift);
611
612 assert_root();
613 locksite($oldhostname);
614 assert_siteexists($oldhostname, 1);
615 locksite($newhostname);
616 assert_siteexists($newhostname, 0);
617 assert_wrapper_denied();
618
619 branch($oldhostname, $newhostname);
620 IkiWiki::Hosting::delete($oldhostname); # silly perl, not the builtin delete..
621
622 return 1;
623 }
624
625 sub meta_compact {
626 required => [qw{hostname}],
627 options => [qw{aggressive!}],
628 description => "log rotation and vcs cleanup for a site",
629 section => "primary",
630 }
631 sub compact {
632 my $hostname=lc(shift);
633 my %options=@_;
634
635 assert_root();
636 locksite($hostname);
637 assert_siteexists($hostname, 1);
638 assert_wrapper_denied();
639
640 # log rotation
641 my $log_period=getsetup($hostname, "log_period") || 7;
642 $log_period = 2 if $log_period < 2; # savelog does not support 0 or 1
643 chdir(logdir($hostname)) || error "chdir logs: $!";
644 shell("savelog", "-p", "-n", "-t", "-c", $log_period,
645 "ikisite.log", "error.log", "access.log");
646 # Note that apache still has logs open, but this is ok since
647 # the logs are only renamed to .0, so it can still write to them.
648 # So, apache is not HUP'd -- but it would be a good idea to
649 # HUP apache after running a compact cron job.
650
651 # VCS optimisations
652 if (getsetup($hostname, "rcs") eq "git") {
653 runas(username($hostname), sub {
654 foreach my $repo (repository($hostname), srcdir($hostname)) {
655 chdir($repo) || error "chdir $repo: $!";
656 shell("git", "gc",
657 $options{aggressive} ? "--aggressive" : ());
658 }
659 });
660 }
661
662 return 1;
663 }
664
665 sub meta_list {
666 required => [qw{}],
667 options => [qw{admin=s ... owner=s ... extended! aggregatedue!}],
668 description => "lists all sites that exist on the current host, or match a condition",
669 section => "query",
670 }
671 sub list {
672 my %options=@_;
673
674 # Root is needed to read setup files in some circumstances.
675 assert_root();
676
677 # All inputs (and outputs) are safe, so this can be run from
678 # a suid wrapper.
679 assert_wrapper_unsafe();
680
681 my @list;
682 my %seen;
683 setpwent();
684 while (my $user=(getpwent())[0]) {
685 my $hostname=userlookup(user => $user);
686 next unless defined $hostname && length $hostname;
687
688 $seen{$hostname}=1 if $options{extended};
689
690 my $owner;
691 my %admins;
692 if ($options{extended} || $options{owner} || $options{admin}) {
693 # avoid list crashing if setup file is broken
694 eval { $owner=getsetup($hostname, "owner") };
695 next if $@;
696 %admins=map { $_ => 1 } @{getsetup($hostname, "adminuser")};
697 }
698
699 my $isowner=defined $options{owner} && grep { $_ eq $owner } @{$options{owner}};
700 next if defined $options{owner} && ! $isowner && ! defined $options{admin};
701 my $isadmin=defined $options{admin} && grep { $admins{$_} } @{$options{admin}};
702 next if defined $options{admin} && ! $isowner && ! $isadmin;
703
704 if ($options{aggregatedue}) {
705 my $timestamp=eval { readfile(srcdir($hostname)."/.ikiwiki/aggregatetime") };
706 next unless defined $timestamp && length $timestamp && $timestamp <= time();
707 }
708
709 if (! $options{extended}) {
710 push @list, $hostname;
711 }
712 else {
713 # Extended mode includes the information the
714 # controlpanel module needs, as well as some
715 # information needed by other programs.
716 my @admins=@{getsetup($hostname, "adminuser")};
717 my $unfinished=0; # unfinished site will have dummy admin
718 if (@admins && ! grep { $_ ne "http://none/" } @admins) {
719 $unfinished=1;
720 }
721 push @list, {
722 isowner => $isowner,
723 isadmin => $isadmin,
724 site_owner => $owner,
725 site_hostname => $hostname,
726 site_url => getsetup($hostname, "url"),
727 site_cgiurl => getsetup($hostname, "cgiurl"),
728 site_wikiname => getsetup($hostname, "wikiname"),
729 site_created => getsetup($hostname, "created"),
730 site_parent => getsetup($hostname, "parent"),
731 use_letsencrypt => getsetup($hostname, "use_letsencrypt"),
732 isunfinished => $unfinished,
733 };
734 }
735 }
736
737 return @list unless $options{extended};
738
739 # Filter no longer existing parents.
740 foreach my $siteinfo (@list) {
741 my $parent=$siteinfo->{site_parent};
742 if (defined $parent && ! $seen{$parent}) {
743 $siteinfo->{site_parent} = undef;
744 }
745 }
746
747 return \@list; # complex data structure
748 }
749
750 sub meta_userlookup {
751 required => [qw{}],
752 options => [qw{user=s}],
753 description => "returns the internal hostname corresponding to a unix username",
754 section => "query",
755 }
756 {
757 my %prefixes;
758 sub userlookup {
759 my %options=@_;
760
761 assert_wrapper_unsafe();
762
763 if (! exists $options{user} || ! length $options{user}) {
764 error "specify user to lookup with --user";
765 }
766
767 if (! keys %prefixes) {
768 foreach my $key (keys %config) {
769 if ($key =~ /^prefix_(.*)/) {
770 $prefixes{$1}=$config{$key};
771 }
772 }
773 }
774
775 foreach my $prefix (keys %prefixes) {
776 if ($options{user}=~/^\Q$prefix\E-(.*)/) {
777 return "$1.$prefixes{$prefix}";
778 }
779 elsif ($options{user}=~/^\Q$prefix\E5-(.*)/) {
780 # md5'd username; look up real hostname
781 # in setup file, and ensure it md5sums
782 # to the same username.
783 my $homedir=(getpwnam($options{user}))[7];
784 if (defined $homedir && -e "$homedir/ikiwiki.setup") {
785 foreach my $url (urllist($options{user})) {
786 my $host=$url->host;
787 if ($host=~/^(([a-z0-9][-a-z0-9]+)\.)\Q$prefixes{$prefix}\E$/ &&
788 $options{user} eq username($host)) {
789 return $url->host;
790 }
791 }
792 }
793 print STDERR "cannot determine hostname for user $options{user}\n";
794 }
795 }
796 return "";
797 }
798 }
799
800
801 sub meta_sitelookup {
802 required => [qw{}],
803 options => [qw{site=s}],
804 description => "returns the internal hostname for an url or external hostname",
805 section => "query",
806 }
807 sub sitelookup {
808 my %options=@_;
809
810 # Root is needed to read setup files in some circumstances.
811 assert_root();
812 assert_wrapper_unsafe();
813
814 if (! exists $options{site} || ! length $options{site}) {
815 error "specify site to lookup with --site";
816 }
817
818 eval q{use URI};
819 my $url=URI->new($options{site});
820 my $host=$url->can("host") ? $url->host : $options{site};
821
822 if (eval { sitexists($host) } && ! $@) {
823 return $host;
824 }
825
826 foreach my $hostname (list()) {
827 foreach my $url (urllist(username($hostname))) {
828 if (lc $url->host eq lc $host) {
829 return $hostname;
830 }
831 }
832 }
833
834 error "$host not found";
835 }
836
837
838 sub meta_siteexists {
839 required => [qw{hostname}],
840 options => [qw{}],
841 description => "returns true if the hostname already exists",
842 section => "query",
843 }
844 sub siteexists {
845 my $hostname=lc(shift);
846
847 my $user=username($hostname);
848
849 # TODO Assumes one server. To handle multiple servers, will need to
850 # query DNS or a database of sites.
851 my $uid=getpwnam($user);
852 return defined $uid ? IkiWiki::SuccessReason->new("$hostname exists")
853 : IkiWiki::FailReason->new("$hostname does not exist (user $user not found)");
854 }
855
856 sub meta_username {
857 required => [qw{hostname}],
858 options => [qw{}],
859 description => "returns the unix username for a site",
860 section => "query",
861 }
862 sub username {
863 my $hostname=lc(shift);
864
865 # paranoia: make sure the hostname looks like a FQDN
866 if ($hostname !~ /^([a-z0-9][-a-z0-9]*)\.\w+(\.\w+)+$/) {
867 error "illegal hostname \"$hostname\"";
868 }
869 if (length $hostname > 252) { # why not 253? Trailing dot..
870 error "hostname too long \"$hostname\"";
871 }
872
873 # since unix usernames are limited to 32 characters (see utmp(5))
874 # chop off the subdomain of the hostname, and use that as the
875 # username
876 my ($subdomain, $topdomain)=$hostname=~/^([a-z0-9][-a-z0-9]*)\.(.*)/;
877
878 # add unique prefix to avoid collisions with system users and
879 # other top domains
880 my $prefix;
881 foreach my $key (keys %config) {
882 next unless $key =~ m/^prefix_/;
883 next unless defined $config{$key};
884 next unless $config{$key} eq $topdomain;
885 $prefix=$key;
886 $prefix=~s/^prefix_//;
887 last;
888 }
889 if (! $prefix) {
890 error "unknown prefix for $topdomain (configure in $config{ikisite_conffile})";
891 }
892 my $username=$prefix.'-'.$subdomain;
893
894 if (length($username) > 32) {
895 # Fall back to using a hash for longer subdomains.
896 eval q{use Digest::MD5};
897 die $@ if $@;
898
899 my $md5=Digest::MD5::md5_hex($subdomain);
900 $username=$prefix.'5-'.substr($md5, 0, 16).'-'.
901 substr($subdomain, 0, 12);
902 }
903
904 return $username;
905 }
906
907 sub meta_homedir {
908 required => [qw{hostname}],
909 options => [qw{}],
910 description => "returns the home directory for a site",
911 section => "query",
912 }
913 sub homedir {
914 my $hostname=lc(shift);
915
916 return (getpwnam(username($hostname)))[7];
917 }
918
919 sub meta_srcdir {
920 required => [qw{hostname}],
921 options => [qw{}],
922 description => "returns the ikiwiki srcdir for a site",
923 section => "query",
924 }
925 sub srcdir {
926 my $hostname=shift;
927
928 # Normally it is ~/srcdir, but the setup file can be modified
929 # to only use a subdirectory of that.
930 if (-e homedir($hostname)."/ikiwiki.setup") {
931 return getsetup($hostname, "srcdir");
932 }
933 else {
934 return homedir($hostname)."/source";
935 }
936 }
937
938 sub meta_destdir {
939 required => [qw{hostname}],
940 options => [qw{}],
941 description => "returns the ikiwiki destdir for a site",
942 section => "query",
943 }
944 sub destdir {
945 my $hostname=shift;
946
947 return homedir($hostname)."/public_html";
948 }
949
950 sub meta_cgidir {
951 required => [qw{hostname}],
952 options => [qw{}],
953 description => "returns the CGI directory for a site",
954 section => "query",
955 }
956 sub cgidir {
957 my $hostname=shift;
958 my $newly_created=shift;
959 my $dir = "/var/www/".username($hostname);
960
961 if ($newly_created || -d $dir) {
962 return $dir;
963 }
964
965 return homedir($hostname)."/public_html";
966 }
967
968 sub meta_logdir {
969 required => [qw{hostname}],
970 options => [qw{}],
971 description => "returns the server log directory for a site",
972 section => "query",
973 }
974 sub logdir {
975 my $hostname=shift;
976 my $newly_created=shift;
977 my $dir = userlogdir(username($hostname));
978
979 if ($newly_created || -d $dir) {
980 return $dir;
981 }
982
983 my $home=homedir($hostname);
984 return unless defined $home;
985 return $home."/logs";
986 }
987
988 sub userlogdir {
989 my $username=shift;
990 return "/var/log/ikiwiki-hosting/".$username;
991 }
992
993 sub meta_rootconfig {
994 required => [qw{hostname}],
995 options => [qw{}],
996 description => "returns the root configuration directory of the site",
997 section => "query",
998 }
999 sub rootconfig {
1000 my $hostname=lc(shift);
1001
1002 return $config{ikisite_rootconfigdir}."/".username($hostname);
1003 }
1004
1005 sub ssl_file {
1006 my $ext=shift;
1007 my $hostname=shift;
1008 my $domain=shift;
1009 my $no_fallback=shift;
1010
1011 my $perdomain=rootconfig($hostname)."/".$domain.".".$ext;
1012 if ($no_fallback || -e $perdomain) {
1013 return $perdomain;
1014 }
1015 else {
1016 return rootconfig($hostname)."/ssl.".$ext;
1017 }
1018 }
1019
1020 sub ssl_cert_file { ssl_file("crt", @_) }
1021 sub ssl_key_file { ssl_file("key", @_) }
1022 sub ssl_chain_file { ssl_file("chain", @_) }
1023 sub ssl_fullchain_file { ssl_file("fullchain", @_) }
1024
1025 sub is_letsencrypt_link {
1026 my $file=shift;
1027 my $link=readlink($file);
1028 return (defined $link && $link=~m!/etc/letsencrypt/live!);
1029 }
1030
1031 sub meta_wikiname {
1032 required => [qw{hostname}],
1033 options => [qw{}],
1034 description => "calculates the default wikiname to use for a site",
1035 section => "query",
1036 }
1037 sub wikiname {
1038 my $hostname=shift;
1039
1040 my ($wikiname)=$hostname=~/^([a-zA-Z0-9][-a-zA-Z0-9_]*)\./;
1041 return $wikiname;
1042 }
1043
1044 sub meta_repository {
1045 required => [qw{hostname}],
1046 options => [qw{}],
1047 description => "returns the vcs repository for a site",
1048 section => "query",
1049 }
1050 sub repository {
1051 my $hostname=lc(shift);
1052
1053 return homedir($hostname)."/source.".getsetup($hostname, "rcs");
1054 }
1055
1056 sub meta_getsetup {
1057 required => [qw{hostname key}],
1058 options => [qw{}],
1059 description => "returns a value from the site's ikiwiki.setup",
1060 section => "query",
1061 }
1062
1063 my ($getsetup_cache_setup, $getsetup_homedir_old); # memoized for speed
1064 sub getsetup {
1065 my $hostname=shift;
1066 my $key=shift;
1067 my %options=@_;
1068
1069 # The suid wrapper can only be used to access a few values.
1070 if ($key eq 'branchable' || $key eq 'adminuser') {
1071 assert_wrapper_unsafe();
1072 }
1073 else {
1074 assert_wrapper_denied();
1075 }
1076
1077 my $homedir;
1078 # this option is used internally, when the hostname is not known
1079 if (exists $options{user}) {
1080 $homedir=(getpwnam($options{user}))[7];
1081 }
1082 else {
1083 $hostname=lc($hostname);
1084 assert_siteexists($hostname, 1);
1085 $homedir=homedir($hostname);
1086 }
1087
1088 if (! defined $getsetup_homedir_old ||
1089 $homedir ne $getsetup_homedir_old) {
1090 $getsetup_cache_setup=loadsetup_safe($homedir."/ikiwiki.setup");
1091 # Only keep cache if setup was successfully loaded.
1092 if (keys %$getsetup_cache_setup) {
1093 $getsetup_homedir_old=$homedir;
1094 }
1095 }
1096
1097 return $getsetup_cache_setup->{$key};
1098 }
1099
1100 sub meta_changesetup {
1101 required => [qw{hostname}],
1102 options => [qw{set=key=value ... set-yaml=key=value ... enable-plugin=s ... disable-plugin=s ... rebuild! commit! message=s}],
1103 description => "changes settings in the site's ikiwiki.setup",
1104 section => "utility",
1105 }
1106 sub changesetup {
1107 my $hostname=lc(shift);
1108 my %options=@_;
1109
1110 locksite($hostname);
1111 assert_siteexists($hostname, 1);
1112 assert_wrapper_safe($hostname);
1113
1114 runas(username($hostname), sub {
1115 my $home=homedir($hostname);
1116 chdir($home) || error "chdir $home: $!";
1117 my $cgi_wrapper=getsetup($hostname, "cgi_wrapper");
1118 my $srcdir=srcdir($hostname);
1119
1120 my @settings;
1121 my $changedesc="changed ";
1122 foreach my $type (qw{set set-yaml}) {
1123 next unless $options{$type};
1124 while (@{$options{$type}}) {
1125 my ($key, $value)=split("=", shift @{$options{$type}}, 2);
1126 if (! length $key) {
1127 error "no key specified";
1128 }
1129 if (! defined $value) {
1130 error "no value specified for $key";
1131 }
1132 $changedesc.="$key to '$value' ;";
1133 if ($key eq "cgi_wrapper") {
1134 $cgi_wrapper=$value;
1135 }
1136 elsif ($key eq "srcdir") {
1137 $srcdir=$value;
1138 }
1139 push @settings, "--$type", "$key=$value";
1140 }
1141 }
1142
1143 if ($options{"enable-plugin"} || $options{"disable-plugin"}) {
1144 my @add_plugins=@{getsetup($hostname, "add_plugins")};
1145 my @disable_plugins=@{getsetup($hostname, "disable_plugins")};
1146 foreach my $plugin (@{$options{"enable-plugin"}}) {
1147 $changedesc.="$plugin (enabled) ;";
1148 @disable_plugins=grep { $_ ne $plugin } @disable_plugins;
1149 push @add_plugins, $plugin unless grep { $_ eq $plugin } @add_plugins;
1150 }
1151 foreach my $plugin (@{$options{"disable-plugin"}}) {
1152 $changedesc.="$plugin (disabled) ;";
1153 @add_plugins=grep { $_ ne $plugin } @add_plugins;
1154 push @disable_plugins, $plugin unless grep { $_ eq $plugin } @disable_plugins;
1155 }
1156 eval q{use YAML::Syck};
1157 die $@ if $@;
1158
1159 push @settings, "--set-yaml", "add_plugins=".
1160 Dump(\@add_plugins);
1161 push @settings, "--set-yaml", "disable_plugins=".
1162 Dump(\@disable_plugins);
1163 }
1164
1165 $changedesc=~s/ ;$//;
1166 $changedesc=$options{message} if exists $options{message};
1167
1168 # There's a potential race with websetup; if a websetup
1169 # change is taking place at the same time, ikiwiki will
1170 # be running with the old configuration, and will write
1171 # a version of that back out to the setup file, overwriting
1172 # our changes.
1173 #
1174 # Simply calling lockwiki() will not help, because ikiwiki
1175 # could still start up, with the old configuration.
1176 # Instead, we need to prevent the ikiwiki cgi from running
1177 # (at least for websetup) while the setup file is being
1178 # changed.
1179 #
1180 # To accomplish that, let's first take the cgilock,
1181 # to ensure no cgi is currently running. Note that this assumes
1182 # that perl flock() really calls flock(2), which is currently
1183 # the case in Debian, but not guaranteed of all perls.
1184 $config{wikistatedir}="$srcdir/.ikiwiki";
1185 if (-d $config{wikistatedir}) {
1186 open(CGILOCK, ">", "$config{wikistatedir}/cgilock") ||
1187 error("$config{wikistatedir}/cgilock: $!");
1188 flock(CGILOCK, 2) || error("flock: $!");
1189 }
1190
1191 # Now, replace the cgi wrapper with a program that waits
1192 # for the cgilock to free up, and then re-execs the cgi
1193 # wrapper, loading the new wrapper we will generate,
1194 # with the changed configuration.
1195 if (-e $cgi_wrapper) {
1196 link($cgi_wrapper, $cgi_wrapper.".old") || error("$cgi_wrapper.old: $!");
1197 open(OUT, ">", $cgi_wrapper.".tmp") || error("$cgi_wrapper.tmp: $!");
1198 print OUT qq{#!/usr/bin/perl
1199 # Temporary wrapper inserted by ikisite changesetup.
1200 open(LOCK, ">", "$config{wikistatedir}/cgilock") ||
1201 die "error opening $config{wikistatedir}/cgilock";
1202 flock(LOCK, 2) || die "flock error";
1203 close LOCK;
1204 # When this is reached, the new wrapper has
1205 # replaced this program.
1206 exec(\$0, \@ARGV);
1207 die "exec: \$!";
1208 };
1209 close OUT || error("close: $!");
1210 shell("chmod", "755", $cgi_wrapper.".tmp");
1211 my $user=username($hostname);
1212 shell("chown", "$user:$user", $cgi_wrapper.".tmp");
1213 CORE::rename($cgi_wrapper.".tmp", $cgi_wrapper) || error("rename: $!");
1214 }
1215
1216 my $setupfile=homedir($hostname)."/ikiwiki.setup";
1217 my $oldsetup=readfile($setupfile);
1218 eval {
1219 shell("ikiwiki", "-setup", $setupfile,
1220 "-dumpsetup", $setupfile,
1221 @settings);
1222 ikiwikisetup($hostname, refresh => 1, wrappers => 1);
1223 };
1224 if ($@) {
1225 # error unwind
1226 if (-e $cgi_wrapper.".old") {
1227 CORE::rename($cgi_wrapper.".old", $cgi_wrapper) || error("rename: $!");
1228 }
1229 writefile($setupfile, "", $oldsetup);
1230 error $@;
1231 }
1232 unlink $cgi_wrapper.".old";
1233
1234 close CGILOCK; # Now any CGIs that were waiting to start up can run.
1235
1236 if ($options{rebuild}) {
1237 ikiwikisetup($hostname);
1238 }
1239
1240 if ($options{commit}) {
1241 commitsetup($hostname, message => $changedesc);
1242 }
1243 });
1244
1245 $getsetup_homedir_old=undef; # memoized setup values no longer valid
1246
1247 return 1;
1248 }
1249
1250 sub meta_domains {
1251 required => [qw{hostname}],
1252 options => [qw{external=s alias=s ...}],
1253 description => "configure a site's external domain name and aliases",
1254 section => "utility",
1255 }
1256 sub domains {
1257 my $hostname=lc(shift);
1258 my %options=@_;
1259
1260 assert_root();
1261 locksite($hostname);
1262 assert_siteexists($hostname, 1);
1263 assert_wrapper_safe($hostname);
1264
1265 # This subcommand can be run from a suid wrapper so inputs
1266 # cannot be trusted; check and sanitize.
1267 my @newdomains;
1268 my @urlalias;
1269 my @settings;
1270 my $rebuild=0;
1271 if (defined $options{external}) {
1272 push @newdomains, $options{external};
1273
1274 if (isinternaldomain($options{external})) {
1275 error "$options{external} is a reserved hostname";
1276 }
1277
1278 # The external domain name does need to be configured
1279 # correctly in the DNS.
1280 my $address=host_address_or_cname($options{external}, $hostname);
1281 if (! defined $address) {
1282 print STDERR "DNS not correctly configured for $options{external}. (Should point to $hostname)\n";
1283 exit 2; # special code
1284 }
1285 if ($address ne $hostname) {
1286 if (! grep { defined $_ && $_ eq $address } site_addresses()) {
1287 print STDERR "DNS not configured correctly for $options{external} - $address\n";
1288 exit 3; # special code
1289 }
1290 else {
1291 print STDERR "warning: DNS for $options{external} hardcodes IP $address\n";
1292 }
1293 }
1294
1295 # It can't be a name used by another site.
1296 my $exists=eval{ sitelookup(site => $options{external}) };
1297 if (! $@ && defined $exists && $exists ne $hostname) {
1298 error "$options{external} is in use by $exists";
1299 }
1300
1301 if (getsetup($hostname, "url") ne "http://$options{external}/") {
1302 push @settings, 'set' => [
1303 "url=http://$options{external}",
1304 "cgiurl=http://$options{external}/ikiwiki.cgi",
1305 ];
1306 $rebuild=1;
1307 }
1308
1309 # When using an external domain, the internal hostname
1310 # must be listed as one of the urlaliases.
1311 push @urlalias, "http://$hostname/";
1312 }
1313 else {
1314 push @settings, 'set' => [
1315 "url=http://$hostname",
1316 "cgiurl=http://$hostname/ikiwiki.cgi",
1317 ];
1318 push @newdomains, $hostname;
1319 }
1320 my %seen;
1321 foreach my $alias (@{$options{alias}}) {
1322 $alias=lc($alias);
1323
1324 # Sanitize aliases to avoid path traversal, etc.
1325 if ($alias !~ /^[-.a-zA-Z0-9]+$/) {
1326 error "bad alias \"$alias\": illegal hostname";
1327 }
1328 # Prevent aliases being set to (possibly unused) internal
1329 # site names.
1330 if ($alias ne $hostname && isinternaldomain($alias)) {
1331 error "bad alias \"$alias\": reserved hostname";
1332 }
1333 # Aliases should not be in use by other sites.
1334 my $site=eval{ sitelookup(site => $alias) };
1335 if (defined $site && !$@ && $site ne $hostname) {
1336 error "alias \"$alias\": already in use by $site";
1337 }
1338 # Note that aliases do not have to be set in the DNS.
1339 # Eg, www.foo.com may be an alias but not set up yet,
1340 # and should still be accepted.
1341 push @urlalias, "http://$alias/" unless $seen{$alias};
1342 $seen{$alias}=1;
1343 }
1344
1345 eval q{use YAML::Syck};
1346 die $@ if $@;
1347 push @settings, 'set-yaml' => [
1348 "urlalias=".Dump(\@urlalias),
1349 ];
1350
1351 push @newdomains, @urlalias;
1352 my @olddomains;
1353 foreach my $url (urllist(username($hostname))) {
1354 push @olddomains, $url->host;
1355 }
1356
1357 disable($hostname, temporary => 1);
1358 changesetup($hostname,
1359 rebuild => 0, # not yet; slow
1360 commit => 1,
1361 message => "configured domains",
1362 @settings,
1363 );
1364 enable($hostname);
1365
1366 # When there was a change to the set of domains used for a site,
1367 # need to either get a new cert from letsencrypt, or temporarily
1368 # disable using the old cert. This has to come after the site is
1369 # enabled using the new domains, so that letsencrypt can get certs
1370 # for them.
1371 if (getsetup($hostname, "use_letsencrypt")) {
1372 eval q{use Data::Compare};
1373 error $@ if $@;
1374 my $domainschanged = ! Compare([sort @olddomains], [sort @newdomains]);
1375 if ($domainschanged &&
1376 ! letsencrypt($hostname)) {
1377 letsnotencrypt($hostname, temporary => 1);
1378 }
1379 }
1380
1381 if ($rebuild) {
1382 # A full site rebuild can take a long time for
1383 # large sites, so is postponed until after the site's
1384 # changed domain has been configured.
1385 #
1386 # Unfortunatly, a long rebuild also blocks other ikiwiki
1387 # cgis from running. That needs to be dealt with in
1388 # ikiwiki, not here.
1389 ikiwikisetup($hostname);
1390 }
1391 }
1392
1393 sub meta_usercreate {
1394 required => [qw{hostname}],
1395 options => [qw{}],
1396 description => "creates the unix user for a site",
1397 section => "utility",
1398 }
1399 sub usercreate {
1400 my $hostname=lc(shift);
1401
1402 assert_root();
1403 my $lockfile=locksite($hostname);
1404 assert_wrapper_denied();
1405
1406 my $user=username($hostname);
1407 my @useradd_opts = ( "--base-dir", $config{useradd_basedir} )
1408 if ($config{useradd_basedir}) ;
1409 shell("useradd", $user,
1410 "--create-home",
1411 "--skel", "/dev/null", # disable /etc/skel files
1412 @useradd_opts,
1413 );
1414
1415 mkdir(rootconfig($hostname));
1416
1417 my $uid=int getpwnam($user);
1418 my $gid=int getgrnam($user);
1419
1420 # The user needs to own the site lock file, so ikisite
1421 # processes running as it can do locking.
1422 chown($uid, $gid, $lockfile)
1423 || error "chown $lockfile: $!";
1424
1425 # create skeleton
1426 my $home=homedir($hostname);
•1427 # useradd in Debian 13 defaults to 0700 permissions on new $HOME
1428 chmod(0755, $home);
1429 mkdir("$home/.ssh") || error "mkdir $home/.ssh: $!";
1430 mkdir("$home/tmp") || error "mkdir $home/tmp: $!";
1431 foreach my $file (".ssh", "tmp") {
1432 chown($uid, $gid, "$home/$file")
1433 || error "chown $home/$file: $!";
1434 }
1435 chmod(0700, "$home/tmp") || error "chmod $home/tmp: $!";
1436
1437 my $logdir=logdir($hostname, 1);
1438 mkdir($logdir) || error "mkdir $logdir: $!";
1439 writefile("ikisite.log", $logdir, "");
1440 foreach my $file (".", "ikisite.log") {
1441 chown(0, $gid, "$logdir/$file")
1442 || error "chown $logdir/$file: $!";
1443 }
1444 chmod(0750, "$logdir") || error "chmod $logdir: $!";
1445
1446 my $cgidir=cgidir($hostname, 1);
1447 mkdir($cgidir) || error "mkdir $cgidir: $!";
1448 chown($uid, $gid, "$cgidir") || error "chown $cgidir: $!";
1449 chmod(0755, "$cgidir") || error "chmod $cgidir: $!";
1450
1451 # configure default username and email for git commits
1452 runas(username($hostname), sub {
1453 # we need to move to a directory we can edit
1454 chdir($home) || error "chdir $home: $!";
1455 shell(qw{git config --global user.name admin});
1456 shell(qw{git config --global user.email}, $config{adminemail});
1457 chmod(0600, "$home/.gitconfig") || error "chmod $home/.gitconfig: $!";
1458 });
1459 }
1460
1461 sub meta_userdelete {
1462 required => [qw{hostname}],
1463 options => [qw{}],
1464 description => "removes the unix user for a site",
1465 section => "utility",
1466 }
1467 sub userdelete {
1468 my $hostname=lc(shift);
1469
1470 assert_root();
1471 my $lockfile=locksite($hostname);
1472 assert_wrapper_denied();
1473
1474 shell("rm", "-rf", logdir($hostname));
1475 shell("rm", "-rf", cgidir($hostname));
1476
1477 my $user=username($hostname);
1478 my $status=shell_exitcode("userdel", "-rf", $user);
1479 # userdel -f returns exit code 12 if it cannot delete the mail
1480 # spool, which typically will not exist. Work around this bug.
1481 if ($status != 0 && ($status >> 8) != 12) {
1482 error("userdel failed");
1483 }
1484
1485 shell("rm", "-rf", rootconfig($hostname));
1486 unlink($lockfile);
1487 }
1488
1489 sub get_apache_conf_tmpl {
1490 my $hostname = shift;
1491 my $suffix = shift;
1492 my $apache_template_vars = shift;
1493
1494 if (-f rootconfig($hostname)."/apache$suffix.conf.tmpl") {
1495 my @bits=stat(_);
1496 if ($bits[4] == 0 && $bits[5] == 0) {
1497 require HTML::Template;
1498 my $template=HTML::Template->new(
1499 filename => rootconfig($hostname)."/apache$suffix.conf.tmpl",
1500 die_on_bad_params => 0,
1501 );
1502 $template->param(@$apache_template_vars);
1503 return $template->output;
1504 }
1505 else {
1506 print STDERR "warning: ignoring apache$suffix.conf.tmpl; not owned by root\n";
1507 }
1508 }
1509
1510 return "";
1511 }
1512
1513 sub meta_enable {
1514 required => [qw{hostname}],
1515 options => [qw{}],
1516 description => "enables user access to a site",
1517 section => "utility",
1518 }
1519 sub enable {
1520 my $hostname=lc(shift);
1521
1522 assert_root();
1523 locksite($hostname);
1524 # Allow the wrapper to enable a site. The CGI for a site uses
1525 # this when its configuration is changed; the site is necessarily
1526 # already enabled for the CGI to run so this should not let
1527 # disabled sites be enabled via the CGI.
1528 assert_wrapper_unsafe();
1529
1530 my $user=username($hostname);
1531 my $home=homedir($hostname);
1532
1533 my @hostnames=map { $_->host } urllist($user);
1534
1535 # Lock down the public_html directory so only the site user and
1536 # www-data can access it.
1537 my $uid=int getpwnam($user);
1538 my $www_data_gid=int getgrnam("www-data");
1539 chown($uid, $www_data_gid, "$home/public_html") || error "chown $home/public_html: $!";
1540 chmod(0750, "$home/public_html") || error "chmod $home/public_html: $!";
1541
1542 my $vcs=getsetup($hostname, "rcs");
1543 if ($vcs eq "git") {
1544 # Setup git-daemon.
1545 foreach my $h (@hostnames) {
1546 my $dest="$config{gitdaemondir}/$h.git";
1547 unlink($dest);
1548 # The symlink is always made, but git-daemon will only
1549 # serve the site if its repository contains
1550 # git-daemon-export-ok.
1551 symlink(repository($hostname), $dest);
1552 }
1553
1554 # Create file if site currently allows branching.
1555 # The branchable plugin will also create/remove it
1556 # as needed when the setting is changed.
1557 my $branchable=getsetup($hostname, "branchable");
1558 my $flagfile=repository($hostname)."/git-daemon-export-ok";
1559 if ($branchable) {
1560 open(FLAG, ">", $flagfile);
1561 close FLAG;
1562 shell("chown", "$user:$user", $flagfile);
1563 chmod(02755, "$home/source.git") || error "chmod $home/source.git: $!";
1564 }
1565 else {
1566 unlink($flagfile);
1567 chmod(02750, "$home/source.git") || error "chmod $home/source.git: $!";
1568 }
1569
1570 # Allow git-daemon to read and write to the repo via ACL.
1571 # This has to come after any chmod of the source.git
1572 # directory, as such chmods will mess up the ACL this sets
1573 # up.
1574 readconfig();
1575 eval { shell("setfacl", "-R", "-m", "d:g:$config{gitdaemonuser}:rwX,d:g:$user:rwX,g:$config{gitdaemonuser}:rwX,g:$user:rwX", "$home/source.git") };
1576 if ($@) {
1577 print STDERR "warning: setfacl failed, anonpush will not work (perhaps the filesystem is not mounted with option 'acl'?)\n";
1578 }
1579
1580 # Setup gitweb.
1581 # An environment variable to points gitweb to
1582 # this file. We make it a symlink pointing at the real
1583 # file, and only enable the link for branchable sites.
1584 my $gitweb_conf_file=srcdir($hostname)."/.ikiwiki/gitweb.conf";
1585
1586 # To avoid privilege escalation via gitweb.conf, we run gitweb
1587 # via a suexec'able CGI script.
1588 my $cgidir=cgidir($hostname);
1589 my $gitweb = "$cgidir/gitweb.cgi";
1590 my $uid=int getpwnam($user);
1591 my $gid=int getgrnam($user);
1592 open(GITWEB, ">", "$gitweb") || die "open $gitweb: $!";
1593 print GITWEB "#!/bin/sh\n";
1594 print GITWEB "GITWEB_CONFIG=$gitweb_conf_file\n";
1595 print GITWEB "export GITWEB_CONFIG\n";
1596 print GITWEB "exec /usr/lib/cgi-bin/gitweb.cgi \"\$@\"\n";
1597 close GITWEB;
1598 chown($uid, $gid, $gitweb) || error "chown $gitweb: $!";
1599 chmod(0755, $gitweb) || error "chmod $gitweb: $!";
1600
1601 my $gitweb_projectslist=srcdir($hostname)."/.ikiwiki/gitweb-projectslist";
1602 my $git_description=repository($hostname)."/description";
1603 outtemplate("$gitweb_conf_file.real", "gitweb.conf.tmpl",
1604 user => $user,
1605 home => $home,
1606 destdir => destdir($hostname),
1607 cgidir => cgidir($hostname),
1608 logdir => logdir($hostname),
1609 hostname => $hostname,
1610 projectslist => $gitweb_projectslist,
1611 );
1612 shell("chown", "$user:$user", "$gitweb_conf_file.real");
1613 if ($branchable) {
1614 unlink($gitweb_conf_file); # force refresh symlink
1615 symlink("$gitweb_conf_file.real", $gitweb_conf_file);
1616 }
1617 else {
1618 unlink($gitweb_conf_file);
1619 }
1620 open(DESC, ">", $git_description) || die "$git_description: $!";
1621 print DESC "source repository for $hostname\n";
1622 close DESC;
1623 shell("chown", "$user:$user", $git_description);
1624 open(PLIST, ">", $gitweb_projectslist) || die "$gitweb_projectslist: $!";
1625 print PLIST "source.git source\n";
1626 close PLIST;
1627 shell("chown", "$user:$user", $gitweb_projectslist);
1628 }
1629
1630 # Get the url from the setup file. The hostname in this url
1631 # may be different from the internal site hostname; configure
1632 # apache to serve the url's hostname.
1633 eval q{use URI};
1634 error $@ if $@;
1635 # ensure url has a trailing slash (apache requires it)
1636 my $u=getsetup($hostname, "url")."/";
1637 $u=~s://$:/:;
1638 my $url=URI->new($u);
1639
1640 # write and enable apache config file
1641 my $apache_site="ikisite-".$url->host;
1642 my $apache_conf_file="/etc/apache2/sites-available/$apache_site.conf";
1643 my @apache_template_vars=(
1644 suexec => (cgidir($hostname) =~ m!^/var/www!),
1645 user => $user,
1646 hostname => $url->host,
1647 home => homedir($hostname),
1648 destdir => destdir($hostname),
1649 cgidir => cgidir($hostname),
1650 logdir => logdir($hostname),
1651 source_hostname => "source.$hostname",
1652 domain_template_vars($hostname, $url->host, $url)
1653 );
1654 outtemplate($apache_conf_file, "apache-site.tmpl",
1655 @apache_template_vars,
1656 # If an apache.conf.tmpl is available,
1657 # it will be added into the apache config file in the default
1658 # and SSL vhosts.
1659 apache_conf_tmpl => get_apache_conf_tmpl($hostname, "", [@apache_template_vars]),
1660 # Similarly, apache-source.conf.tmpl will be added to the
1661 # source.foo.example.com vhost, and apache-ssl.conf.tmpl
1662 # to the SSL vhost (only).
1663 apache_source_conf_tmpl => get_apache_conf_tmpl($hostname, '-source', [@apache_template_vars]),
1664 apache_ssl_conf_tmpl => get_apache_conf_tmpl($hostname, '-ssl', [@apache_template_vars]),
1665 );
1666 my %setup;
1667 $setup{$url->host}=1;
1668 if (apache_before_2_4()) {
1669 shell("a2ensite", "$apache_site.conf");
1670 }
1671 else {
1672 shell("a2ensite", $apache_site);
1673 }
1674
1675 # generate apache config files for alias urls, that redirect to the
1676 # main url
1677 foreach my $alias (@hostnames) {
1678 next if $setup{$alias};
1679 $setup{$alias}=1;
1680 $apache_site="ikisite-$alias";
1681 $apache_conf_file="/etc/apache2/sites-available/$apache_site.conf";
1682 outtemplate($apache_conf_file, "apache-sitealias.tmpl",
1683 suexec => (cgidir($hostname) =~ m!^/var/www!),
1684 user => $user,
1685 hostname => $url->host,
1686 home => homedir($hostname),
1687 destdir => destdir($hostname),
1688 cgidir => cgidir($hostname),
1689 logdir => logdir($hostname),
1690 alias => $alias,
1691 domain_template_vars($hostname, $alias, $url)
1692 );
1693 if (apache_before_2_4()) {
1694 shell("a2ensite", "$apache_site.conf");
1695 }
1696 else {
1697 shell("a2ensite", $apache_site);
1698 }
1699 }
1700
1701 # reload apache config
1702 if (! apache_reload_graceful()) {
1703 # avoid leaving apache in a broken state
1704 foreach my $site (keys %setup) {
1705 if (apache_before_2_4()) {
1706 shell("a2dissite", "$site.conf");
1707 }
1708 else {
1709 shell("a2dissite", $site);
1710 }
1711 }
1712 }
1713
1714 enabledns($hostname);
1715
1716 return 1;
1717 }
1718
1719 sub domain_template_vars {
1720 my $hostname=shift; # ikisite hostname
1721 my $domain=shift; # domain to generate template for
1722 my $mainurl=shift; # main url of the site
1723
1724 my $ssl_cert_file=ssl_cert_file($hostname, $domain);
1725 my $ssl_key_file=ssl_key_file($hostname, $domain);
1726 my $ssl_chain_file=ssl_chain_file($hostname, $domain);
1727 my $ssl_fullchain_file=ssl_fullchain_file($hostname, $domain);
1728 # Check that any user provided key file is not password protected,
1729 # as that makes apache startup hang. (Also checks that it's valid.)
•1730 local *openssl_can_read_ssl_key_file = sub {
1731 foreach my $key_type (qw(ec rsa)) {
1732 if (shell_exitcode("openssl", "$key_type",
1733 "-in" => $ssl_key_file,
1734 "-out" => $ssl_key_file,
1735 "-passin" => "pass:dummy",
1736 "-passout" => "pass:dummy") == 0) {
1737 return 1;
1738 }
1739 }
1740 return 0;
1741 };
1742
1743 if (-e $ssl_key_file) {
•1744 unless (openssl_can_read_ssl_key_file()) {
1745 printf STDERR "warning: invalid or password-protected ssl_key_file (%s) will be ignored.\n", $ssl_key_file;
1746 $ssl_key_file='';
1747 $ssl_cert_file='';
1748 $ssl_chain_file='';
1749 $ssl_fullchain_file='';
1750 }
1751 }
1752
1753 # Use wildcard cert if there is no site specific one.
1754 if (! -e $ssl_cert_file && ! -e $ssl_key_file) {
1755 my $wilddir=find_wildcard_ssl_cert_dir($domain);
1756 if (length $wilddir) {
1757 $ssl_cert_file="$wilddir/cert.pem";
1758 $ssl_key_file="$wilddir/privkey.pem";
1759 if (-e "$wilddir/fullchain.pem") {
1760 $ssl_fullchain_file="$wilddir/fullchain.pem";
1761 }
1762 else {
1763 $ssl_fullchain_file='';
1764 }
1765 if (-e "$wilddir/chain.pem") {
1766 $ssl_chain_file="$wilddir/chain.pem";
1767 }
1768 else {
1769 $ssl_chain_file='';
1770 }
1771 }
1772 }
1773
1774 my $ssl_enabled=-e $ssl_key_file && -e $ssl_cert_file;
1775 my @ssl_template_vars=(
1776 ssl_cert_file => $ssl_cert_file,
1777 ssl_key_file => $ssl_key_file,
1778 ssl_enabled => $ssl_enabled,
1779 );
1780 if (-e $ssl_chain_file) {
1781 push @ssl_template_vars, (
1782 ssl_chain_file => $ssl_chain_file,
1783 ssl_chain => 1,
1784 );
1785 }
1786 if (-e $ssl_fullchain_file) {
1787 push @ssl_template_vars, (
1788 ssl_fullchain_file => $ssl_fullchain_file,
1789 ssl_fullchain => 1,
1790 );
1791 }
1792
1793 # This is the url that alias urls redirect to.
1794 my $redirurl=$mainurl->clone;
1795 my $httpsredirurl=$mainurl->clone;
1796 if ($ssl_enabled) {
1797 $httpsredirurl->scheme("https");
1798 if (getsetup($hostname, 'redirect_to_https')) {
1799 $redirurl->scheme("https");
1800 push @ssl_template_vars, (redirect_to_https => 1);
1801 }
1802 }
1803
1804 return (
1805 # Value escaped to prevent leakage
1806 # into RewriteEngine regexp.
1807 url_escaped => quotemeta($redirurl),
1808 https_url_escaped => quotemeta($httpsredirurl),
1809 @ssl_template_vars
1810 );
1811 }
1812
1813 sub find_wildcard_ssl_cert_dir {
1814 my $domain=shift;
1815
1816 if (defined $config{wildcard_ssl_cert_dir}
1817 && length $config{wildcard_ssl_cert_dir}) {
1818 foreach my $wilddir (glob("$config{wildcard_ssl_cert_dir}/*")) {
1819 my $wilddomain=IkiWiki::basename($wilddir);
1820 if (($domain =~ /^.+\.\Q$wilddomain\E$/i || lc $domain eq lc $wilddomain) &&
1821 -e "$wilddir/cert.pem" && -e "$wilddir/privkey.pem") {
1822 return $wilddir;
1823 }
1824 }
1825 }
1826 return "";
1827 }
1828
1829 sub meta_disable {
1830 required => [qw{hostname}],
1831 options => [qw{temporary!}],
1832 description => "disables user access to a site, without removing it",
1833 section => "utility",
1834 }
1835 sub disable {
1836 my $hostname=lc(shift);
1837 my %options=@_;
1838
1839 assert_root();
1840 locksite($hostname);
1841 assert_wrapper_denied();
1842
1843 disabledns($hostname) unless $options{temporary};
1844
1845 my @urls=urllist(username($hostname));
1846
1847 my $vcs=getsetup($hostname, "rcs");
1848 if ($vcs eq "git") {
1849 foreach my $h (map { $_->host } @urls) {
1850 unlink("$config{gitdaemondir}/$h.git");
1851 }
1852 }
1853
1854 # remove apache config file(s)
1855 my $reload=0;
1856 foreach my $url (@urls) {
1857 my $apache_site="ikisite-".$url->host;
1858 my $apache_conf_file="/etc/apache2/sites-available/$apache_site.conf";
1859 if (-e $apache_conf_file) {
1860 # inside guard because a2dissite fails if the config
1861 # file does not exist, and this needs to be idempotent
1862 if (apache_before_2_4()) {
1863 shell("a2dissite", "$apache_site.conf");
1864 }
1865 else {
1866 shell("a2dissite", $apache_site);
1867 }
1868 unlink($apache_conf_file);
1869 $reload=1;
1870 }
1871 # If we're now using Apache 2.4, there might be old versions
1872 # from Apache 2.2 still lying around
1873 foreach my $detritus (
1874 "/etc/apache2/sites-enabled/$apache_site",
1875 "/etc/apache2/sites-available/$apache_site") {
1876 unlink $detritus || error("unlink $detritus: $!");
1877 $reload=1;
1878 }
1879 }
1880 apache_reload_graceful() if $reload && ! $options{temporary};
1881
1882 return 1;
1883 }
1884
1885 sub meta_letsencrypt {
1886 required => [qw{hostname}],
1887 options => [qw{}],
1888 description => "use Lets Encrypt to get https certificate",
1889 section => "utility",
1890 }
1891 sub letsencrypt {
1892 my $hostname=lc(shift);
1893
1894 assert_root();
1895 my $lockfile=locksite($hostname);
1896 assert_wrapper_denied();
1897
1898 changesetup($hostname,
1899 rebuild => 0,
1900 commit => 1,
1901 message => "letsencrypt enabled",
1902 set => [
1903 "use_letsencrypt=1",
1904 ],
1905 ) unless getsetup($hostname, "use_letsencrypt");
1906
1907 my $allsuccess=1;
1908 my $madechange=0;
1909 foreach my $url (urllist(username($hostname))) {
1910 my $host=$url->host;
1911
1912 my $livedir="/etc/letsencrypt/live/$host";
1913 my $certexists=sub {
1914 -e "$livedir/cert.pem" &&
1915 -e "$livedir/privkey.pem" &&
1916 -e "$livedir/fullchain.pem"
1917 };
1918
1919 # If there's a wildcard cert, don't get a per-domain cert.
1920 #
1921 # If we already got a per-domain cert using letsencrypt,
1922 # that cert is no longer necessary thanks to the wildcard,
1923 # and could be deleted. But deleting certs is too
1924 # dangerous, so the cert will continue to be used.
1925 if (length find_wildcard_ssl_cert_dir($host)) {
1926 next;
1927 }
1928
1929 # Some of the domains in the urllist may not have DNS set
1930 # up for them. Rather than trying and failing for those,
1931 # which would make maintaincerts noisy in cron,
1932 # just skip them.
1933 next unless defined host_address_or_cname($host, $hostname);
1934 shell_exitcode("certbot", "certonly",
1935 "--text", "--noninteractive", "--quiet", "--keep-until-expiring",
1936 "--agree-tos", "--email=$config{adminemail}",
1937 "--webroot", "--webroot-path", destdir($hostname),
1938 "--domain=".$host) unless $certexists->();
1939 if ($certexists->()) {
1940 my $cert=ssl_cert_file($hostname, $host, 1);
1941 if (! is_letsencrypt_link($cert)) {
1942 $madechange=1;
1943 shell("ln", "-sf", "$livedir/cert.pem", $cert);
1944 }
1945 my $key=ssl_key_file($hostname, $host, 1);
1946 if (! is_letsencrypt_link($key)) {
1947 $madechange=1;
1948 shell("ln", "-sf", "$livedir/privkey.pem", $key);
1949 }
1950 my $chain=ssl_chain_file($hostname, $host, 1);
1951 if (! is_letsencrypt_link($chain)) {
1952 $madechange=1;
1953 shell("ln", "-sf", "$livedir/chain.pem", $chain);
1954 }
1955 my $fullchain=ssl_fullchain_file($hostname, $host, 1);
1956 if (! is_letsencrypt_link($fullchain)) {
1957 $madechange=1;
1958 shell("ln", "-sf", "$livedir/fullchain.pem", $fullchain);
1959 }
1960 }
1961 else {
1962 print STDERR "warning: Unable to get letsencrypt certificate for $host at this time; will retry later.\n";
1963 $allsuccess=0;
1964 }
1965 }
1966
1967 if ($madechange) {
1968 return enable($hostname);
1969 }
1970
1971 return $allsuccess;
1972 }
1973
1974 sub meta_letsnotencrypt {
1975 required => [qw{hostname}],
1976 options => [qw{temporary!}],
1977 description => "disable use of Lets Encrypt and delete ssl certificate",
1978 section => "utility",
1979 }
1980 sub letsnotencrypt {
1981 my $hostname=lc(shift);
1982 my %options=@_;
1983
1984 assert_root();
1985 my $lockfile=locksite($hostname);
1986 assert_wrapper_denied();
1987
1988 changesetup($hostname,
1989 rebuild => 0,
1990 commit => 1,
1991 message => "letsencrypt disabled",
1992 set => [
1993 "use_letsencrypt=0",
1994 ],
1995 ) unless $options{temporary};
1996 remove_letsencrypt_cert($hostname);
1997 remove_letsencrypt_config($hostname);
1998 enable($hostname);
1999 }
2000
2001 sub remove_letsencrypt_cert {
2002 my $hostname=shift;
2003 foreach my $url (urllist(username($hostname))) {
2004 foreach my $f (ssl_cert_file($hostname, $url->host), ssl_key_file($hostname, $url->host), ssl_chain_file($hostname, $url->host), ssl_fullchain_file($hostname, $url->host)) {
2005 if (is_letsencrypt_link($f)) {
2006 unlink($f);
2007 }
2008 }
2009 }
2010
2011 }
2012
2013 sub remove_letsencrypt_config {
2014 my $hostname=shift;
2015 foreach my $f ("/etc/letsencrypt/renewal/$hostname.conf") {
2016 unlink($f) || 1;
2017 }
2018 }
2019
2020 sub meta_maintaincerts {
2021 required => [],
2022 options => [qw{}],
2023 description => "request and renew Lets Encrypt certificates as needed",
2024 section => "utility",
2025 }
2026 sub maintaincerts {
2027 assert_root();
2028 assert_wrapper_denied();
2029
2030 my $inuse=0;
2031 foreach my $site (@{list(extended => 1)}) {
2032 next if $site->{isunfinished};
2033 next unless $site->{use_letsencrypt};
2034 $inuse=1;
2035 letsencrypt($site->{site_hostname});
2036 }
2037
2038 # Debian installs a cron.d script that runs certbot renew,
2039 # so assume that if it's present, we don't need to renew on our
2040 # own.
2041 if ($inuse && ! -e "/etc/cron.d/certbot") {
2042 eval { shell("certbot", "renew", "--non-interactive", "--quiet") };
2043 apache_reload_graceful();
2044 }
2045
2046 return 1;
2047 }
2048
2049 sub meta_enabledns {
2050 required => [qw{hostname}],
2051 options => [qw{}],
2052 description => "adds a hostname to DNS",
2053 section => "utility",
2054 }
2055 sub enabledns {
2056 my $hostname=lc(shift);
2057
2058 assert_root();
2059 # Enabling dns is a fairly safe operation, and sites need to be
2060 # able to call it when ipv6_disabled is changed.
2061 assert_wrapper_unsafe();
2062
2063 locksite($hostname);
2064
2065 if ($config{allow_ipv4} || $config{allow_ipv6}) {
2066 my @commands;
2067 # A site's setup file can be used to disable ipv6.
2068 # But, the setup file may not yet exist, if an early dns
2069 # setup is being done. In that case, ipv6 is assumed not
2070 # to be disabled, and enabledns is expected to be run
2071 # a second time once the setup file is in place, and
2072 # can disable it then.
2073 my $ipv6_disabled = eval { getsetup($hostname, "ipv6_disabled") };
2074
2075 my ($ipv4, $ipv6)=site_addresses();
2076 foreach my $h ($hostname, "source.$hostname") {
2077 if ($ipv6_disabled || ! defined $ipv6 || ! $config{allow_ipv6}) {
2078 push @commands, "update delete $h AAAA";
2079 }
2080 else {
2081 push @commands, "update add $h $config{ttl} IN AAAA $ipv6";
2082 }
2083 push @commands, "update add $h $config{ttl} IN A $ipv4"
2084 if defined $ipv4 && $config{allow_ipv4};
2085 }
2086 if (! @commands) {
2087 error("failed to determine IP address");
2088 }
2089 nsupdate(@commands);
2090 }
2091 }
2092
2093 sub meta_disabledns {
2094 required => [qw{hostname}],
2095 options => [qw{}],
2096 description => "removes a hostname from DNS",
2097 section => "utility",
2098 }
2099 sub disabledns {
2100 my $hostname=lc(shift);
2101
2102 assert_root();
2103 locksite($hostname);
2104 assert_wrapper_denied();
2105
2106 if ($config{allow_ipv4} || $config{allow_ipv6}) {
2107 nsupdate(
2108 "update delete $hostname",
2109 "update delete source.$hostname",
2110 );
2111 }
2112 }
2113
2114 sub meta_ikiwikisetup {
2115 required => [qw{hostname}],
2116 options => [qw{refresh! wrappers!}],
2117 description => "calls ikiwiki to setup a site",
2118 section => "utility",
2119 }
2120 sub ikiwikisetup {
2121 my $hostname=lc(shift);
2122 my %options=@_;
2123
2124 locksite($hostname);
2125 assert_wrapper_denied();
2126
2127 runas(username($hostname), sub {
2128 my $home=homedir($hostname);
2129 chdir($home) || error "chdir $home: $!";
2130 my $setupfile="$home/ikiwiki.setup";
2131 shell("ikiwiki", "-setup", $setupfile,
2132 ($options{refresh} ? "-refresh" : ()),
2133 ($options{wrappers} ? "-wrappers" : ()));
2134 });
2135 }
2136
2137 sub meta_ikiwikiclean {
2138 required => [qw{hostname}],
2139 options => [qw{}],
2140 description => "removes ikiwiki generated files",
2141 section => "utility",
2142 }
2143 sub ikiwikiclean {
2144 my $hostname=lc(shift);
2145
2146 locksite($hostname);
2147 assert_wrapper_denied();
2148
2149 remove_wikilist($hostname);
2150 runas(username($hostname), sub {
2151 my $home=homedir($hostname);
2152 chdir($home) || error "chdir $home: $!";
2153 my $setupfile="$home/ikiwiki.setup";
2154 shell("ikiwiki", "-setup", $setupfile, "-clean");
2155
2156 return 1;
2157 });
2158 }
2159
2160 sub meta_createsetupbranch {
2161 required => [qw{hostname}],
2162 options => [qw{}],
2163 description => "creates \"setup\" branch in VCS",
2164 section => "utility",
2165 }
2166 sub createsetupbranch {
2167 my $hostname=lc(shift);
2168
2169 locksite($hostname);
2170 assert_wrapper_denied();
2171
2172 runas(username($hostname), sub {
2173 chdir(homedir($hostname)) || error "chdir HOME: $!";
2174
2175 my $vcs=getsetup($hostname, "rcs");
2176
2177 my @ignores=(
2178 ".ikiwiki",
2179 "public_html",
2180 "source",
2181 "source.".$vcs,
2182 "logs",
2183 ".ikisite-nonce",
2184 );
2185
2186 if ($vcs eq "git") {
2187 push @ignores, ".gitconfig";
2188 if (-d ".git") {
2189 error ".git directory already exists";
2190 }
2191 shell("git", "init");
2192 chmod(0700, ".git") || error "chmod .git: $!";
2193 # convince git to start committing to setup branch
2194 writefile(".git/HEAD", ".", "ref: refs/heads/setup\n");
2195 writefile(".gitignore", ".", join("\n", @ignores)."\n");
2196 chmod(0600, ".gitignore") || error "chmod .gitignore: $!";
2197 shell("git", "remote", "add", "origin", repository($hostname));
2198
2199 commitsetup($hostname, message => "initial commit of setup files");
2200
2201 }
2202 else {
2203 error "createsetupbranch not implemented for $vcs";
2204 }
2205
2206 return 1;
2207 });
2208 }
2209
2210 sub meta_commitsetup {
2211 required => [qw{hostname}],
2212 options => [qw{message=s}],
2213 description => "commits to \"setup\" branch in VCS",
2214 section => "utility",
2215 }
2216 sub commitsetup {
2217 my $hostname=lc(shift);
2218 my %options=@_;
2219
2220 locksite($hostname);
2221 assert_wrapper_denied();
2222
2223 runas(username($hostname), sub {
2224 chdir(homedir($hostname)) || error "chdir HOME: $!";
2225
2226 my $vcs=getsetup($hostname, "rcs");
2227
2228 my @files=(
2229 "ikiwiki.setup",
2230 ".ssh/authorized_keys",
2231 "apache.conf.tmpl",
2232 );
2233
2234 my $message=$options{message} ? $options{message} : "commit of setup files";
2235
2236 if ($vcs eq "git") {
2237 push @files, ".gitignore";
2238
2239 foreach my $file (@files) {
2240 if (-e $file) {
2241 shell("git", "add", $file);
2242 }
2243 else {
2244 # the file may have never been added,
2245 # so --ignore-unmatch
2246 shell("git", "rm", "--ignore-unmatch", $file);
2247 }
2248 }
2249 my $changed=`git status --porcelain | grep -v '^\?\?'`;
2250 if (length $changed) {
2251 shell("git", "commit", "-m", $message);
2252 shell("git", "push", "origin", "setup");
2253 }
2254 }
2255 else {
2256 error "commitsetup not implemented for $vcs";
2257 }
2258
2259 return 1;
2260 });
2261 }
2262
2263 sub meta_observe {
2264 required => [qw{hostname}],
2265 options => [qw{force!}],
2266 description => "informs observersites about site creation or removal",
2267 section => "utility",
2268 }
2269 sub observe {
2270 my $hostname=lc(shift);
2271 my %options=@_;
2272
2273 assert_wrapper_denied();
2274
2275 readconfig();
2276 return unless defined $config{observersites};
2277 my $exists=siteexists($hostname);
2278 foreach my $observer (split(' ', $config{observersites})) {
2279 next if $observer eq $hostname;
2280 next unless siteexists($observer);
2281
2282 runas(username($observer), sub {
2283 # Load observer site's ikiwiki setup file,
2284 # and plugins, so rcs_* functions can be used.
2285 require IkiWiki::Setup;
2286 %config=(%config, IkiWiki::defaultconfig());
2287 # Note use of safe mode to avoid running perl
2288 # format setup files.
2289 IkiWiki::Setup::load(homedir($observer)."/ikiwiki.setup", 1);
2290 IkiWiki::loadplugins();
2291 IkiWiki::checkconfig();
2292
2293 chdir(srcdir($observer));
2294 my $templatefile="templates/observersite.tmpl";
2295 return unless -e $templatefile;
2296
2297 my $e="existing/$hostname";
2298 my $r="removed/$hostname";
2299 my $page=$exists ? $e : $r;
2300 my $other=$exists ? $r : $e;
2301 my $staged=0;
2302
2303 # Handle moving page if it already existed.
2304 if (-e $other.".mdwn") {
2305 IkiWiki::rcs_rename($other.".mdwn", $page.".mdwn");
2306 $staged=1;
2307 # reset timestamp
2308 system("touch", $page.".mdwn");
2309 # just in case $other was not checked into
2310 # git, remove it
2311 unlink($other.".mdwn");
2312 }
2313 # Handle moving any subpages.
2314 if (-d $other) {
2315 IkiWiki::rcs_rename($other, $page);
2316 $staged=1;
2317 }
2318
2319 # Ensure page exists, but avoid destructive
2320 # overwrites, unless in force mode.
2321 if (! -e $page.".mdwn" || $options{force}) {
2322 eval q{use HTML::Template};
2323 error $@ if $@;
2324 my $template=HTML::Template->new(
2325 filename => $templatefile,
2326 );
2327 $template->param(hostname => $hostname);
2328 writefile($page.".mdwn", srcdir($observer), $template->output);
2329 IkiWiki::rcs_add($page.".mdwn");
2330 $staged=1;
2331 }
2332
2333 if ($staged) {
2334 IkiWiki::rcs_commit_staged(
2335 message => "automatic update",
2336 );
2337 }
2338 });
2339 }
2340 }
2341
2342 sub meta_updatecustomersite {
2343 required => [qw{hostname}],
2344 options => [],
2345 description => "updates customersite checkout",
2346 section => "utility",
2347 }
2348 sub updatecustomersite {
2349 my $hostname=lc(shift);
2350
2351 locksite($hostname);
2352 assert_wrapper_unsafe();
2353
2354 runas(username($hostname), sub {
2355 eval q{use IkiWiki::Customer};
2356 if (! defined IkiWiki::Customer::basedir(1)) {
2357 error "no customersite checked out; cannot update";
2358 }
2359 if (! IkiWiki::Customer::update()) {
2360 error "update failed";
2361 }
2362 return 1;
2363 });
2364 }
2365
2366 sub meta_add_wikilist {
2367 required => [qw{hostname}],
2368 options => [],
2369 description => "adds hostname's user to /etc/ikiwiki/wikilist",
2370 section => "utility",
2371 }
2372 sub add_wikilist {
2373 my $hostname=lc(shift);
2374 ikiwiki_update_wikilist($hostname, 0);
2375 }
2376
2377 sub meta_remove_wikilist {
2378 required => [qw{hostname}],
2379 options => [],
2380 description => "removes hostname's user to /etc/ikiwiki/wikilist",
2381 section => "utility",
2382 }
2383 sub remove_wikilist {
2384 my $hostname=lc(shift);
2385 ikiwiki_update_wikilist($hostname, 1);
2386 }
2387
2388 sub ikiwiki_update_wikilist {
2389 my $hostname=lc(shift);
2390 my $remove=shift;
2391
2392 assert_root();
2393 assert_siteexists($hostname, 1);
2394
2395 my $username=username($hostname);
2396
2397 my $wikilist="/etc/ikiwiki/wikilist";
2398 if (! -e $wikilist) {
2399 print "$wikilist does not exist\n";
2400 return;
2401 }
2402
2403 my $changed=0;
2404 my $seen=0;
2405 my @lines;
2406 open (my $list, "<$wikilist") || die "read $wikilist: $!";
2407 while (<$list>) {
2408 chomp;
2409 if (/^\s*([^\s]+)\s*$/) {
2410 my $user=$1;
2411 if ($user eq $username) {
2412 if (! $remove) {
2413 $seen=1;
2414 push @lines, $_;
2415 }
2416 else {
2417 $changed=1;
2418 }
2419 }
2420 else {
2421 push @lines, $_;
2422 }
2423 }
2424 else {
2425 push @lines, $_;
2426 }
2427 }
2428 if (! $seen && ! $remove) {
2429 push @lines, $username;
2430 $changed=1;
2431 }
2432 if ($changed) {
2433 close $list || die "error reading $list: $!\n";
2434 open ($list, ">$wikilist") || die "cannot write to $wikilist\n";
2435 foreach (@lines) {
2436 print $list "$_\n";
2437 }
2438 close $list || die "error writing $wikilist: $!\n";
2439 }
2440
2441 return 1;
2442 }
2443
2444 sub meta_sshkeys {
2445 required => [qw{hostname}],
2446 options => [qw{}],
2447 description => "lists enabled ssh keys",
2448 section => "query",
2449 }
2450 sub sshkeys {
2451 my $hostname=lc(shift);
2452
2453 assert_siteexists($hostname, 1);
2454 assert_wrapper_denied();
2455
2456 my @ret;
2457 my $user=username($hostname);
2458 my $sshdir=homedir($hostname)."/.ssh";
2459 my $authorized_keys=$sshdir."/authorized_keys";
2460 if (! -e $authorized_keys) {
2461 return ();
2462 }
2463 open(IN, "<", $authorized_keys) || error("open $authorized_keys: $!");
2464 while (<IN>) {
2465 chomp;
2466 my $k=parse_sshkey($_);
2467 if (defined $k) {
2468 push @ret, $k;
2469 }
2470 }
2471 close IN;
2472
2473 return @ret;
2474 }
2475
2476 sub meta_enablesshkey {
2477 required => [qw{hostname}],
2478 options => [qw{key=s}],
2479 description => "adds the specified ssh key to .ssh/authorized_keys",
2480 section => "utility",
2481 }
2482 sub enablesshkey {
2483 my $hostname=lc(shift);
2484 my %options=@_;
2485
2486 locksite($hostname);
2487 assert_siteexists($hostname, 1);
2488 assert_wrapper_denied();
2489
2490 if (! exists $options{key}) {
2491 error("must specify a key with --key=");
2492 }
2493 my $key=parse_sshkey($options{key});
2494 if (! defined $key) {
2495 error "invalid or unsupported ssh key";
2496 }
2497
2498 my $user=username($hostname);
2499 my $sshdir=homedir($hostname)."/.ssh";
2500 my $authorized_keys=$sshdir."/authorized_keys";
2501 if (! -d $sshdir) {
2502 shell("mkdir", "-p", $sshdir);
2503 shell("chown", "$user:$user", $sshdir);
2504 }
2505
2506 # regenerate file, adding key if it is not already present
2507 my %seen;
2508 $seen{$key}=1;
2509 if (-e $authorized_keys) {
2510 open(IN, "<", $authorized_keys) || error("open $authorized_keys: $!");
2511 while (<IN>) {
2512 chomp;
2513 my $k=parse_sshkey($_);
2514 $seen{$k}=1 if defined $k;
2515 }
2516 close IN;
2517 }
2518 my $vcs=getsetup($hostname, "rcs");
2519 open(OUT, ">", $authorized_keys.".tmp") || error("open: $authorized_keys.tmp: $!");
2520 foreach my $key (sort keys %seen) {
2521 print OUT sshkey_line($key, $vcs);
2522 }
2523 close OUT || error("close: $!");
2524 shell("chmod", "400", $authorized_keys.".tmp");
2525 shell("chown", "$user:$user", $authorized_keys.".tmp");
2526 CORE::rename($authorized_keys.".tmp", $authorized_keys) || error("rename; $!");
2527
2528 return 1;
2529 }
2530
2531 sub meta_disablesshkey {
2532 required => [qw{hostname}],
2533 options => [qw{key=s all}],
2534 description => "removes the specified ssh key (or all keys)",
2535 section => "utility",
2536 }
2537 sub disablesshkey {
2538 my $hostname=lc(shift);
2539 my %options=@_;
2540
2541 locksite($hostname);
2542 assert_siteexists($hostname, 1);
2543 assert_wrapper_denied();
2544
2545 my $key;
2546 if (exists $options{all}) {
2547 $key=undef;
2548 }
2549 elsif (exists $options{key}) {
2550 $key=parse_sshkey($options{key});
2551 }
2552 else {
2553 error("must specify --all or a key with --key=");
2554 }
2555
2556 my $user=username($hostname);
2557 my $sshdir=homedir($hostname)."/.ssh";
2558 my $authorized_keys=$sshdir."/authorized_keys";
2559
2560 return 1 if ! -e $authorized_keys;
2561
2562 if (! -d $sshdir) {
2563 shell("mkdir", "-p", $sshdir);
2564 shell("chown", "$user:$user", $sshdir);
2565 }
2566
2567 # regenerate file, removing matching keys
2568 open(IN, "<", $authorized_keys) || error("open $authorized_keys: $!");
2569 open(OUT, ">", $authorized_keys.".tmp") || error("open: $authorized_keys.tmp: $!");
2570 my $vcs=getsetup($hostname, "rcs");
2571 while (<IN>) {
2572 chomp;
2573 my $k=parse_sshkey($_);
2574 if (defined $k && defined $key && $k ne $key) {
2575 print OUT sshkey_line($k, $vcs);
2576 }
2577 }
2578 close IN;
2579 close OUT || error("close: $!");
2580 shell("chmod", "400", $authorized_keys.".tmp");
2581 shell("chown", "$user:$user", $authorized_keys.".tmp");
2582 CORE::rename($authorized_keys.".tmp", $authorized_keys) || error("rename; $!");
2583
2584 return 1;
2585 }
2586
2587 sub meta_calendar {
2588 required => [qw{hostname}],
2589 options => [qw{force! startyear=s endyear=s}],
2590 description => "runs ikiwiki-calendar if the site has the calendar plugin enabled",
2591 section => "utility",
2592 }
2593 sub calendar {
2594 my $hostname=lc(shift);
2595 my %options=@_;
2596
2597 locksite($hostname);
2598 assert_siteexists($hostname, 1);
2599 assert_wrapper_denied();
2600
2601 if ($options{endyear} && ! $options{startyear}) {
2602 error "cannot specify endyear without startyear";
2603 }
2604
2605 if (plugin_enabled($hostname, "calendar") &&
2606 defined getsetup($hostname, "archivebase") &&
2607 length getsetup($hostname, "archivebase")) {
2608 runas(username($hostname), sub {
2609 shell("ikiwiki-calendar",
2610 ($options{force} ? "-f" : ()),
2611 homedir($hostname)."/ikiwiki.setup",
2612 ($options{startyear} ? $options{startyear} : ()),
2613 ($options{endyear} ? $options{endyear} : ()),
2614 );
2615 });
2616 }
2617 }
2618
2619 sub meta_checksetup {
2620 required => [qw{setupref}],
2621 options => [qw{}],
2622 description => "checks that the specified ref contains only safe changes to the setup branch",
2623 section => "utility",
2624 }
2625 sub checksetup {
2626 my $setupref=shift;
2627
2628 my $hostname=userlookup(user => getpwuid($<));
2629 if (! defined $hostname) {
2630 error "unable to determine internal hostname";
2631 }
2632
2633 # Make a temporary checkout of the ref.
2634 my $homedir=homedir($hostname);
2635 eval q{use File::Temp};
2636 error $@ if $@;
2637 my $tmpcheckout=File::Temp::tempdir(CLEANUP => 1, DIR => "$homedir/tmp");
2638 my $newsetup="$tmpcheckout/ikiwiki.setup";
2639 my $vcs=getsetup($hostname, "rcs");
2640 if ($vcs eq "git") {
2641 # doing a shared clone makes the setupref, which has
2642 # not landed on any branch, be available for checkout
2643 shell("git", "clone", "--quiet", "--shared",
2644 "--no-checkout", repository($hostname), $tmpcheckout);
2645 chdir($tmpcheckout) || error "chdir $tmpcheckout: $!";
2646 shell("git", "checkout", "--quiet", $setupref, "-b", "setup");
2647 }
2648 else {
2649 error "checksetup not implemented for $vcs";
2650 }
2651
2652 # Only allow changes to ikiwiki.setup.
2653 my @files=map { chomp; $_ } `git diff --name-only remotes/origin/setup...`;
2654 chdir($homedir) || error "chdir $tmpcheckout: $!";
2655 if (grep { $_ ne "ikiwiki.setup" } @files) {
2656 error "rejecting change to setup branch: modification of files other than ikiwiki.setup is not allowed";
2657 }
2658
2659 # Make sure that ikiwiki.setup didn't turn into a symlink or other
2660 # special file, and was not removed.
2661 if (-l $newsetup || ! -f $newsetup || ! -e $newsetup) {
2662 error "rejecting change to setup branch: ikiwiki.setup must remain a regular file";
2663 }
2664 # paranoia
2665 if (-x $newsetup || -X $newsetup) {
2666 error "rejecting change to setup branch: ikiwiki.setup cannot be executable";
2667 }
2668
2669 # Load new and current setup file into temporary hashes.
2670 my $config_new=eval { loadsetup_safe($newsetup) };
2671 if ($@ || ! defined $config_new) {
2672 error "rejecting change to setup branch: failed to parse ikiwiki.setup as YAML formatted file (check syntax)\n$@";
2673 }
2674 my $config_old=loadsetup_safe($homedir."/ikiwiki.setup");
2675 # Compare to see which settings changed.
2676 eval q{use Data::Compare};
2677 error $@ if $@;
2678 my %changed;
2679 my %changed_plugins;
2680 foreach my $key (keys %$config_new, keys %$config_old) {
2681 if (! Compare($config_new->{$key}, $config_old->{$key})) {
2682 if ($key eq 'add_plugins' || $key eq 'disable_plugins') {
2683 my %old=map { $_ => 1 } @{$config_old->{$key}};
2684 my %new=map { $_ => 1 } @{$config_new->{$key}};
2685 foreach my $k (keys %new, keys %old) {
2686 if (! Compare($new{$k}, $old{$k})) {
2687 $changed_plugins{$k}=1;
2688 }
2689 }
2690 }
2691 else {
2692 $changed{$key}=1;
2693 }
2694 }
2695 }
2696
2697 # Check that each setting that changed is one that ikiwiki
2698 # considers safe. Take into account any overrides configured
2699 # into the websetup plugin.
2700 # Also, see if a full rebuild is called for by the changes made.
2701 my $rebuild_needed=0;
2702 eval q{use IkiWiki::Setup};
2703 error $@ if $@;
2704 # bootstrap enough of ikiwiki to load plugins
2705 my %oldconfig=%config;
2706 %config=(%config,IkiWiki::defaultconfig(), %$config_old);
2707 IkiWiki::checkconfig();
2708 my @setup=([main => [IkiWiki::getsetup()]], IkiWiki::Setup::getsetup());
2709 %config=%oldconfig;
2710
2711 my @unsafe_changes;
2712 my $websetup_unsafe=getsetup($hostname, "websetup_unsafe");
2713 CHANGE: foreach my $setting (keys %changed) {
2714 if (! ref $websetup_unsafe ||
2715 ! grep { $_ eq $setting } @$websetup_unsafe) {
2716 foreach my $pair (@setup) {
2717 my %setup=@{$pair->[1]};
2718
2719 foreach my $key (keys %setup) {
2720 if ($key eq $setting) {
2721 $rebuild_needed=1 unless Compare($setup{$key}->{rebuild}, 0);
2722 next CHANGE if $setup{$key}->{safe};
2723 }
2724 }
2725 }
2726 }
2727
2728 push @unsafe_changes, $setting;
2729 }
2730 if (@unsafe_changes) {
2731 print STDERR "the following settings cannot be changed:\n";
2732 print STDERR "\t$_\n" foreach @unsafe_changes;
2733 }
2734
2735 my @unsafe_plugin_changes;
2736 my $websetup_force_plugins=getsetup($hostname, "websetup_force_plugins");
2737 PCHANGE:
2738 foreach my $p (keys %changed_plugins) {
2739 if (! ref $websetup_force_plugins ||
2740 ! grep { $_ eq $p } @$websetup_force_plugins) {
2741 foreach my $pair (@setup) {
2742 next if $pair->[0] ne $p;
2743 my %setup=@{$pair->[1]};
2744 $rebuild_needed=1 unless Compare($setup{plugin}->{rebuild}, 0);
2745 next PCHANGE if $setup{plugin}->{safe};
2746 }
2747 }
2748
2749 push @unsafe_plugin_changes, $p;
2750 }
2751 if (@unsafe_plugin_changes) {
2752 print STDERR "the following plugins cannot be enabled/disabled:\n";
2753 print STDERR "\t$_\n" foreach @unsafe_plugin_changes;
2754 }
2755
2756 error "rejecting change to setup branch"
2757 if @unsafe_changes || @unsafe_plugin_changes;
2758
2759 if (%changed || %changed_plugins) {
2760 # Check out setup file in toplevel. This is slightly tricky
2761 # as the commit has not landed in the bare git repo yet --
2762 # but it is available in the tmpcheckout.
2763 shell("git", "pull", "-q", $tmpcheckout, "setup");
2764
2765 # Refresh or rebuild site to reflect setup changes.
2766 print STDERR "Updating site to reflect setup changes...\n";
2767 shell("ikiwiki", "-setup", "ikiwiki.setup", "-v",
2768 ($rebuild_needed ? ("-rebuild") : ("-refresh", "-wrappers"))
2769 );
2770 }
2771
2772 exit 0;
2773 }
2774
2775 sub meta_sudo {
2776 required => [qw{hostname ...}],
2777 options => [],
2778 description => "runs sudo as site user (example: ikisite sudo \$SITE -- ls -l)",
2779 section => "utility",
2780 }
2781 sub sudo {
2782 my $hostname=lc(shift);
2783
2784 assert_root();
2785 # note: no locksite, as commands that themselves lock may be run inside the sudo
2786 assert_siteexists($hostname, 1);
2787 assert_wrapper_denied();
2788
2789 $ENV{HOME}=homedir($hostname);
2790 chdir($ENV{HOME}) || error "chdir: $!";
2791 shell("sudo", "-u", username($hostname), (@_ ? @_ : ($ENV{SHELL} || "/bin/sh")));
2792 return undef; # don't print return code
2793 }
2794
2795 sub meta_analog {
2796 required => [qw{hostname ...}],
2797 options => [],
2798 description => "runs analog, generates report to stdout",
2799 section => "utility",
2800 }
2801 sub analog {
2802 my $hostname=lc(shift);
2803
2804 assert_siteexists($hostname, 1);
2805 assert_wrapper_unsafe();
2806 if (! $config{allow_analog_reports}) {
2807 assert_root();
2808 }
2809
2810 chdir(logdir($hostname)) || die "chdir: $!";
2811 system("analog", "+CREFREPEXCLUDE http://${hostname}/*", "+a", "+f", "+D", glob("access.log*"), @_);
2812 return undef; # don't print return code
2813 }
2814
2815 sub meta_logview {
2816 required => [qw{hostname ...}],
2817 options => [],
2818 description => "tail -f of all log files",
2819 section => "utility",
2820 }
2821 sub logview {
2822 my $hostname=lc(shift);
2823
2824 assert_root();
2825 assert_siteexists($hostname, 1);
2826 assert_wrapper_unsafe();
2827
2828 chdir(logdir($hostname)) || die "chdir: $!";
2829 system("tail", "-f", glob("*.log"), @_);
2830 return undef; # don't print return code
2831 }
2832
2833 # Run by iki-git-shell, don't trust inputs or stdio.
2834 sub meta_logs {
2835 required => [qw{}],
2836 options => [qw{dump tail}],
2837 description => "tails or dumps apache access.log for current user's site",
2838 section => "utility",
2839 }
2840 sub logs {
2841 my %options=@_;
2842
2843 assert_wrapper_unsafe();
2844
2845 my $username=(getpwuid($<))[0];
2846 if (! defined $username || ! length $username) {
2847 error "unable to determine username";
2848 }
2849 chdir(userlogdir($username)) || die "chdir: $!";
2850 if ($options{dump}) {
2851 foreach my $n (reverse(1..9)) {
2852 if (-e "access.log.$n.gz") {
2853 system("zcat", "access.log.$n.gz");
2854 }
2855 }
2856 foreach my $l ("access.log.0", "access.log") {
2857 if (-e $l) {
2858 system("cat", $l);
2859 }
2860 }
2861 }
2862 else {
2863 print "Viewing logs.. press ctrl-c to exit.\n\n";
2864 system("tail", "-f", "access.log");
2865 }
2866 return undef; # don't print return code
2867 }
2868
2869 sub meta_createnonce {
2870 required => [qw{hostname}],
2871 options => [qw{value=s}],
2872 description => "returns a nonce for ikisite-wrapper",
2873 section => "utility",
2874 }
2875 sub createnonce {
2876 my $hostname=shift;
2877 my %options=@_;
2878
2879 locksite($hostname);
2880 assert_siteexists($hostname, 1);
2881 assert_wrapper_denied();
2882
2883 my $nonce=defined $options{value} ? $options{value} : time().':'.`uuid -v4`;
2884 chomp $nonce;
2885 my $noncefile=homedir($hostname)."/.ikisite-nonce";
2886 open(NONCE, ">>", $noncefile) || die "$noncefile: $!";
2887 my $username=username($hostname);
2888 shell("chown", "$username:$username", $noncefile);
2889 shell("chmod", "600", $noncefile);
2890 print NONCE "$nonce\n";
2891 close NONCE;
2892 return $nonce;
2893 }
2894
2895 sub meta_deletenonce {
2896 required => [qw{hostname}],
2897 options => [qw{nonce=s}],
2898 description => "invalidates the specified nonce",
2899 section => "utility",
2900 }
2901 sub deletenonce {
2902 my $hostname=lc(shift);
2903 my %options=@_;
2904
2905 assert_root();
2906 locksite($hostname);
2907 assert_siteexists($hostname, 1);
2908 assert_wrapper_safe($hostname);
2909
2910 if (! defined $options{nonce}) {
2911 error "--nonce required";
2912 }
2913
2914 my $noncefile=homedir($hostname)."/.ikisite-nonce";
2915 open(NONCE, "<", $noncefile) || die "$noncefile: $!";
2916 my %nonces;
2917 while (<NONCE>) {
2918 chomp;
2919 $nonces{$_}=1;
2920 }
2921 close NONCE;
2922 delete $nonces{$options{nonce}};
2923 open(NONCE, ">", $noncefile) || die "$noncefile: $!";
2924 my $username=username($hostname);
2925 shell("chown", "$username:$username", $noncefile);
2926 shell("chmod", "600", $noncefile);
2927 print NONCE "$_\n" foreach keys %nonces;
2928 close NONCE;
2929
2930 return 1;
2931 }
2932
2933 sub meta_checksite {
2934 required => [qw{hostname}],
2935 options => [qw{wait hasnonce}],
2936 description => "checks if site is done being created",
2937 section => "query",
2938 }
2939 sub checksite {
2940 my $hostname=lc(shift);
2941 my %options=@_;
2942
2943 assert_root();
2944 assert_siteexists($hostname, 1);
2945 assert_wrapper_unsafe();
2946
2947 my $checknonce = sub {
2948 if ($options{hasnonce}) {
2949 my $noncefile=homedir($hostname)."/.ikisite-nonce";
2950 if (! -e $noncefile) {
2951 return IkiWiki::SuccessReason->new("$hostname lacks nonce");
2952 }
2953 }
2954 return IkiWiki::SuccessReason->new("$hostname is ready");
2955 };
2956
2957 if ($options{wait}) {
2958 # blocking wait
2959 locksite($hostname);
2960 return $checknonce->();
2961 }
2962 else {
2963 # nonblocking lock test
2964 my $lockfile="$config{lockdir}/".username($hostname);
2965 open(CHECKLOCK, '>', $lockfile) ||
2966 error ("cannot write to $lockfile: $!");
2967 if (! flock(CHECKLOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
2968 close CHECKLOCK;
2969 return IkiWiki::FailReason->new("$hostname is locked");
2970 }
2971 else {
2972 close CHECKLOCK;
2973 return $checknonce->();
2974 }
2975 }
2976 }
2977
2978 sub meta_upgrade {
2979 required => [qw{hostname}],
2980 options => [],
2981 description => "upgrade a site to new layout",
2982 section => "primary",
2983 }
2984 sub upgrade {
2985 my $hostname=lc(shift);
2986
2987 assert_root();
2988 assert_siteexists($hostname, 1);
2989 assert_wrapper_denied();
2990
2991 my $home=homedir($hostname);
2992
2993 my @cleanup;
2994
2995 my $user=username($hostname);
2996 my $uid=int getpwnam($user);
2997 my $gid=int getgrnam($user);
2998
2999 # logs moved
3000 if (-d "$home/logs") {
3001 my $newlogdir=logdir($hostname, 1);
3002 if (! -d $newlogdir) {
3003 mkdir($newlogdir) || error "mkdir $newlogdir: $!";
3004 chmod(0750, "$newlogdir") || error "chmod $newlogdir: $!";
3005 }
3006 foreach my $file (<$home/logs/*>) {
3007 my $basefile=IkiWiki::basename($file);
3008 my $dest="$newlogdir/$basefile";
3009 if (! -e $dest) {
3010 shell("mv", "-f", $file, $dest);
3011 }
3012 else {
3013 print STDERR "warning: $file not moved to $basefile, which already exists\n";
3014 }
3015 }
3016 rmdir("$home/logs");
3017
3018 # Only ikisite log is writable by the site user's gid.
3019 foreach my $file (".", "ikisite.log") {
3020 chown(0, $gid, "$newlogdir/$file")
3021 || error "chown $newlogdir/$file: $!";
3022 }
3023 }
3024
3025 # cgi moved, and is no longer suid, as suidexec is used.
3026 my $oldcgi=$home."/public_html/ikiwiki.cgi";
3027 if (-e $oldcgi) {
3028 push @cleanup, $oldcgi;
3029
3030 my $cgidir=cgidir($hostname, 1);
3031 mkdir($cgidir) || error "mkdir $cgidir: $!";
3032 chown($uid, $gid, "$cgidir") || error "chown $cgidir: $!";
3033 chmod(0755, "$cgidir") || error "chmod $cgidir: $!";
3034
3035 eval q{use YAML::Syck};
3036 die $@ if $@;
3037 readconfig();
3038
3039 changesetup($hostname,
3040 rebuild => 0,
3041 commit => 1,
3042 message => "ikisite upgrade",
3043 set => [
3044 "cgi_wrapper" ."=". $cgidir."/ikiwiki.cgi",
3045 "cgi_wrappermode" ."=". "0755",
3046 ],
3047 # gitdaemonuser became an untrusted committer
3048 'set-yaml' => [
3049 "untrusted_committers=".Dump([$config{gitdaemonuser}]),
3050 ],
3051 );
3052
3053 changesetup($hostname,
3054 rebuild => 0,
3055 commit => 1,
3056 message => "ikisite upgrade",
3057 set => [
3058 "cgi_wrapper" ."=". $cgidir."/ikiwiki.cgi",
3059 "cgi_wrappermode" ."=". "0755",
3060 ],
3061 );
3062 }
3063
3064 # File perms were locked down.
3065 foreach my $file ("ikiwiki.setup", ".gitconfig", ".gitignore") {
3066 if (-e "$home/$file") {
3067 chmod(0600, "$home/$file") || error "chmod $home/$file: $!";
3068 }
3069 }
3070 # Dir perms were locked down.
3071 foreach my $dir (".git", "source") {
3072 if (-e "$home/$dir") {
3073 chmod(0700, "$home/$dir") || error "chmod $home/$dir: $!";
3074 }
3075 }
3076 foreach my $dir ("apache") {
3077 if (-e "$home/$dir") {
3078 shell("chown", "$user:www-data", "$home/$dir");
3079 chmod(0750, "$home/$dir") || error "chmod $home/$dir: $!";
3080 }
3081 }
3082
3083 # New rootconfig directory created.
3084 my $rootconfig=rootconfig($hostname);
3085 if (! -d $rootconfig) {
3086 mkdir($rootconfig) || error "mkdir $rootconfig: $!";
3087 my $old=homedir($hostname)."/apache.conf.tmpl";
3088 if (-e $old &&
3089 ! -e "$rootconfig/apache.conf.tmpl") {
3090 # Safe because the file will only be used if owned
3091 # by root.
3092 shell("mv", "-f", $old, $rootconfig);
3093 }
3094 }
3095
3096 # Disable and re-enable to write new apache configs, etc.
3097 disable($hostname, temporary => 1);
3098 enable($hostname);
3099
3100 foreach my $file (@cleanup) {
3101 unlink($file) || error "unlink $file: $!";
3102 }
3103 }
3104
3105 ############################################################################
3106
3107 my %locks;
3108 sub locksite {
3109 my $hostname=shift;
3110
3111 my $lockfile="$config{lockdir}/".username($hostname);
3112
3113 if (! exists $locks{$hostname}) {
3114 open($locks{$hostname}, '>', $lockfile) ||
3115 error ("cannot write to $lockfile: $!");
3116 if (! flock($locks{$hostname}, 2)) { # LOCK_EX
3117 error("flock: $!");
3118 }
3119 }
3120
3121 return $lockfile;
3122 }
3123
3124 sub urllist {
3125 my $username=shift;
3126
3127 my @urls;
3128 my $urlalias=getsetup(undef, "urlalias", user => $username);
3129 if (ref $urlalias) {
3130 push @urls, @$urlalias;
3131 }
3132 push @urls, getsetup(undef, "url", user => $username);
3133 eval q{use URI};
3134 error $@ if $@;
3135 return grep { $_->can("host") } map { URI->new($_) } @urls;
3136 }
3137
3138 sub githooks {
3139 my $repository=shift;
3140
3141 unlink("$repository/hooks/update");
3142 symlink("/usr/bin/iki-git-hook-update", "$repository/hooks/update") || error("symlink: $!");
3143 }
3144
3145 sub parse_sshkey {
3146 my $line=shift;
3147
3148 return undef if $line=~/^\s*#/;
3149
3150 # Parse key out of line, which may be just the key,
3151 # or may be an authorized_keys line, and may have surrounding whitespace.
3152 # Retain one word of optional comment part.
3153 if ($line =~ /^(?:.* )?\s*(ssh-\w+\s+[A-Za-z0-9+\/=]+(?:\s+[^\s]*)?)\s*.*$/) {
3154 return $1;
3155 }
3156 else {
3157 return undef;
3158 }
3159 }
3160
3161 sub sshkey_line {
3162 my $key=shift;
3163 my $vcs=shift;
3164
3165 if ($vcs eq 'git') {
3166 return "command=\"iki-git-shell\",no-agent-forwarding,no-port-forwarding,no-X11-forwarding,no-pty,no-user-rc $key\n";
3167 }
3168 else {
3169 error("unsupported vcs $vcs");
3170 }
3171 }
3172
3173 sub assert_siteexists {
3174 my $hostname=shift;
3175 my $should=shift;
3176
3177 my $exists=siteexists($hostname);
3178 if ($exists != $should) {
3179 if ($exists) {
3180 error "$hostname already exists";
3181 }
3182 else {
3183 if (ref($exists) eq 'IkiWiki::FailReason') {
3184 error "$exists";
3185 }
3186 else {
3187 error "$hostname does not exist";
3188 }
3189 }
3190 }
3191
3192 }
3193
3194 sub assert_wrapper_denied {
3195 if (exists $ENV{IKISITE_NONCE}) {
3196 error "subcommand cannot be run via wrapper";
3197 }
3198 }
3199
3200 sub assert_wrapper_unsafe {
3201 my $hostname=shift;
3202
3203 delete $ENV{IKISITE_NONCE};
3204 }
3205
3206 sub assert_wrapper_safe {
3207 my $hostname=shift;
3208
3209 # IKISITE_NONCE, if set, must be equal to a line from the
3210 # .ikisite-nonce file. This allows suid wrappers to pass the
3211 # variable through to check that their caller knows a valid nonce
3212 # for the site.
3213 if (exists $ENV{IKISITE_NONCE}) {
3214 my $noncefile=homedir($hostname)."/.ikisite-nonce";
3215 open(NONCE, "<", $noncefile) || die "$noncefile: $!";
3216 while (<NONCE>) {
3217 chomp;
3218 if ($_ eq $ENV{IKISITE_NONCE}) {
3219 close NONCE;
3220 delete $ENV{IKISITE_NONCE};
3221 return 1;
3222 }
3223 }
3224 close NONCE;
3225
3226 error "nonce check failure";
3227 }
3228 }
3229
3230 sub isemail {
3231 my $email=shift;
3232
3233 return unless defined $email && length $email;
3234
3235 # This is not intended to be a complete RFC compliant email address
3236 # check. It only makes sure the email contains only legal
3237 # characters.
3238 return $email =~ /[^-+@_.a-zA-Z0-9]/;
3239 }
3240
3241 sub isinternaldomain {
3242 my $domain=shift;
3243
3244 while (length $domain) {
3245 if (defined eval { username($domain) } && !$@) {
3246 return 1;
3247 }
3248 $domain=~s/^[^.]+(\.|$)//; # strip subdomains
3249 }
3250
3251 return 0;
3252 }
3253
3254 sub plugin_enabled {
3255 my $hostname=shift;
3256 my $plugin=shift;
3257
3258 my @add_plugins=@{getsetup($hostname, "add_plugins")};
3259 my @disable_plugins=@{getsetup($hostname, "disable_plugins")};
3260
3261 return 0 if grep { $_ eq $plugin } @disable_plugins;
3262 return 1 if grep { $_ eq $plugin } @add_plugins;
3263 return undef; # might be enabled by default or pulled in via plugin bundle
3264 }
3265
3266 sub actionlog {
3267 my $message=shift;
3268 my $subcommand=shift;
3269 my $hostname=shift; # hostname is always the first required parameter
3270 return unless defined $hostname && length $hostname;
3271
3272 my $username=eval { username($hostname) };
3273 return unless defined $username;
3274
3275 my $logdir=eval { logdir($hostname) };
3276 return unless defined $logdir;
3277
3278 my $localhost=eval q{use Sys::Hostname; hostname()} || "somehost";
3279
3280 open(LOG, ">>", "$logdir/ikisite.log") || return;
3281 print LOG gmtime()." $localhost: $subcommand: $message\n";
3282 close LOG;
3283 }
3284
3285 # used only for recording a few specific actions:
3286 # site creation and deletion
3287 sub accountinglog ($$;$) {
3288 my $action=shift; # "create" or "delete"
3289 my $hostname=shift;
3290 my $username=shift; # only for create
3291
3292 readconfig();
3293 open(ACCOUNTING_LOG, ">>", $config{accountinglog}) || error "$config{accountinglog}: $!";
3294 if ($action eq "create") {
3295 print ACCOUNTING_LOG gmtime(time)." create $hostname $username\n";
3296 }
3297 elsif ($action eq "delete") {
3298 print ACCOUNTING_LOG gmtime(time)." delete $hostname\n";
3299 }
3300 else {
3301 error "accountinglog: unsupported action $action";
3302 }
3303 close ACCOUNTING_LOG;
3304
3305 # Inform observers as background job to avoid delaying eg,
3306 # site creation.
3307 my $pid=IkiWiki::Hosting::daemonize();
3308 if ($pid) {
3309 return;
3310 }
3311 # Avoid keeping sites locked while daemonized.
3312 foreach my $site (keys %locks) {
3313 close($locks{$site});
3314 }
3315 # Wait a minute to let anything that is being done settle.
3316 sleep(60);
3317 observe($hostname);
3318 exit;
3319 }
3320
3321 sub nsupdate {
3322 # chdir done here because nsupdate expects the other key in the pwd
3323 chdir "$config{keydir}/dns" || error "chdir $config{keydir}/dns: $!";
3324
3325 my @privkey=glob("K**.private");
3326 if (! @privkey) {
3327 error("cannot find private key in $config{keydir}/dns");
3328 }
3329
3330 # Any key in the directory is assumed to work, so just take the first.
3331 debug("nsupdate -k $privkey[0] <<EOF");
3332 open(NSUPDATE, "|-", "nsupdate", "-k", $privkey[0]) || error("nsupdate: $!");
3333 print NSUPDATE join("\n", @_)."\n\n";
3334 debug($_) foreach @_;
3335 debug("EOF");
3336 if (! close NSUPDATE) {
3337 error("nsupdate failed")
3338 }
3339
3340 chdir "/";
3341 }
3342
3343 # checks apache config, only reloading apache if the config is legal to
3344 # prevent a bad config leaving it not running
3345 #
3346 # returns false if the config is bad; the caller should then revert
3347 # whatever changes it made
3348 sub apache_reload_graceful {
3349 if (shell_exitcode("sh", "-c", "apache2ctl configtest >/dev/null 2>/dev/null") == 0) {
3350 # Use service rather than letting apache2ctl graceful
3351 # reload apache, because the latter has been observed
3352 # sometimes stopping apache and starting it again under a
3353 # different cgroup than the one systemd keeps apache in.
3354 eval { shell("service", "apache2", "reload") };
3355 if ($@) {
3356 return 0;
3357 }
3358 else {
3359 return 1;
3360 }
3361 }
3362 else {
3363 return 0;
3364 }
3365 }
3366
3367
3368 sub loadsetup_safe {
3369 my $setupfile=shift;
3370
3371 require IkiWiki::Setup;
3372 # Avoid polluting our %config with site setup.
3373 my %ret;
3374 no warnings;
3375 my $overridden=\&IkiWiki::Setup::merge;
3376 *IkiWiki::Setup::merge=sub { %ret=%{shift()} };
3377 # This can fail with error; catch to clean up.
3378 eval {
3379 # Note that safe mode is enabled, to avoid this
3380 # executing IkiWiki::Setup::Standard setup files.
3381 IkiWiki::Setup::load($setupfile, 1);
3382 };
3383 *IkiWiki::Setup::merge=$overridden;
3384 use warnings;
3385 die $@ if $@;
3386
3387 return \%ret;
3388 }
3389
3390 main(\&actionlog);