ffbaf99086cfc80d93140acca579812c56c21300
[ikiwiki.git] / IkiWiki / Wrapper.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4
5 use warnings;
6 use strict;
7 use File::Spec;
8 use Data::Dumper;
9 use IkiWiki;
10
11 sub gen_wrappers () {
12         debug(gettext("generating wrappers.."));
13         my %origconfig=(%config);
14         foreach my $wrapper (@{$config{wrappers}}) {
15                 %config=(%origconfig, %{$wrapper});
16                 $config{verbose}=$config{setupverbose}
17                         if exists $config{setupverbose};
18                 $config{syslog}=$config{setupsyslog}
19                         if exists $config{setupsyslog};
20                 delete @config{qw(setupsyslog setupverbose wrappers genwrappers rebuild)};
21                 checkconfig();
22                 if (! $config{cgi} && ! $config{post_commit} &&
23                     ! $config{test_receive}) {
24                         $config{post_commit}=1;
25                 }
26                 gen_wrapper();
27         }
28         %config=(%origconfig);
29 }
30
31 our $program_to_wrap = $0;
32 sub gen_wrapper () {
33         $config{srcdir}=File::Spec->rel2abs($config{srcdir});
34         $config{destdir}=File::Spec->rel2abs($config{destdir});
35         my $this=File::Spec->rel2abs($program_to_wrap);
36         if (! -x $this) {
37                 error(sprintf(gettext("%s doesn't seem to be executable"), $this));
38         }
39
40         if ($config{setup}) {
41                 error(gettext("cannot create a wrapper that uses a setup file"));
42         }
43         my $wrapper=possibly_foolish_untaint($config{wrapper});
44         if (! defined $wrapper || ! length $wrapper) {
45                 error(gettext("wrapper filename not specified"));
46         }
47         delete $config{wrapper};
48         
49         my @envsave;
50         push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
51                        CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
52                        HTTP_COOKIE REMOTE_USER HTTPS REDIRECT_STATUS
53                        HTTP_HOST SERVER_PORT HTTPS HTTP_ACCEPT
54                        REDIRECT_URL} if $config{cgi};
55         my $envsize=$#envsave;
56         my $envsave="";
57         foreach my $var (@envsave) {
58                 $envsave.=<<"EOF";
59         if ((s=getenv("$var")))
60                 addenv("$var", s);
61 EOF
62         }
63         if (ref $config{ENV} eq 'HASH') {
64                 foreach my $key (keys %{$config{ENV}}) {
65                         my $val=$config{ENV}{$key};
66                         $val =~ s/([\\"])/\\$1/g;
67                         $envsize += 1;
68                         $envsave.=<<"EOF";
69         addenv("$key", "$val");
70 EOF
71                 }
72                 delete $config{ENV};
73         }
74         
75         my @wrapper_hooks;
76         run_hooks(genwrapper => sub { push @wrapper_hooks, shift->() });
77
78         my $check_commit_hook="";
79         my $pre_exec="";
80         if ($config{post_commit}) {
81                 # Optimise checking !commit_hook_enabled() , 
82                 # so that ikiwiki does not have to be started if the
83                 # hook is disabled.
84                 #
85                 # Note that perl's flock may be implemented using fcntl
86                 # or lockf on some systems. If so, and if there is no
87                 # interop between the locking systems, the true C flock will
88                 # always succeed, and this optimisation won't work.
89                 # The perl code will later correctly check the lock,
90                 # so the right thing will still happen, though without
91                 # the benefit of this optimisation.
92                 $check_commit_hook=<<"EOF";
93         {
94                 int fd=open("$config{wikistatedir}/commitlock", O_CREAT | O_RDWR, 0666);
95                 if (fd != -1) {
96                         if (flock(fd, LOCK_SH | LOCK_NB) != 0)
97                                 exit(0);
98                         close(fd);
99                 }
100         }
101 EOF
102         }
103         elsif ($config{cgi}) {
104                 # Avoid more than one ikiwiki cgi running at a time by
105                 # taking a cgi lock. Since ikiwiki uses several MB of
106                 # memory, a pile up of processes could cause thrashing
107                 # otherwise. The fd of the lock is stored in
108                 # IKIWIKI_CGILOCK_FD so unlockwiki can close it.
109                 #
110                 # A lot of cgi wrapper processes can potentially build
111                 # up and clog an otherwise unloaded web server. To
112                 # partially avoid this, when a GET comes in and the lock
113                 # is already held, rather than blocking a html page is
114                 # constructed that retries. This is enabled by setting
115                 # cgi_overload_delay.
116                 if (defined $config{cgi_overload_delay} &&
117                     $config{cgi_overload_delay} =~/^[0-9]+/) {
118                         my $i=int($config{cgi_overload_delay});
119                         $pre_exec.="#define CGI_OVERLOAD_DELAY $i\n"
120                                 if $i > 0;
121                         my $msg=gettext("Please wait");
122                         $msg=~s/"/\\"/g;
123                         $pre_exec.='#define CGI_PLEASE_WAIT_TITLE "'.$msg."\"\n";
124                         if (defined $config{cgi_overload_message} && length $config{cgi_overload_message}) {
125                                 $msg=$config{cgi_overload_message};
126                                 $msg=~s/"/\\"/g;
127                         }
128                         $pre_exec.='#define CGI_PLEASE_WAIT_BODY "'.$msg."\"\n";
129                 }
130                 $pre_exec.=<<"EOF";
131         lockfd=open("$config{wikistatedir}/cgilock", O_CREAT | O_RDWR, 0666);
132         if (lockfd != -1) {
133 #ifdef CGI_OVERLOAD_DELAY
134                 char *request_method = getenv("REQUEST_METHOD");
135                 if (request_method && strcmp(request_method, "GET") == 0) {
136                         if (lockf(lockfd, F_TLOCK, 0) == 0) {
137                                 set_cgilock_fd(lockfd);
138                         }
139                         else {
140                                 printf("Content-Type: text/html\\nRefresh: %i; URL=%s\\n\\n<html><head><title>%s</title><head><body><p>%s</p></body></html>",
141                                         CGI_OVERLOAD_DELAY,
142                                         getenv("REQUEST_URI"),
143                                         CGI_PLEASE_WAIT_TITLE,
144                                         CGI_PLEASE_WAIT_BODY);
145                                 exit(0);
146                         }
147                 }
148                 else if (lockf(lockfd, F_LOCK, 0) == 0) {
149                         set_cgilock_fd(lockfd);
150                 }
151 #else
152                 if (lockf(lockfd, F_LOCK, 0) == 0) {
153                         set_cgilock_fd(lockfd);
154                 }
155 #endif
156         }
157 EOF
158         }
159
160         my $set_background_command='';
161         if (defined $config{wrapper_background_command} &&
162             length $config{wrapper_background_command}) {
163                 my $background_command=delete $config{wrapper_background_command};
164                 $set_background_command=~s/"/\\"/g;
165                 $set_background_command='#define BACKGROUND_COMMAND "'.$background_command.'"';
166         }
167
168         $Data::Dumper::Indent=0; # no newlines
169         my $configstring=Data::Dumper->Dump([\%config], ['*config']);
170         $configstring=~s/\\/\\\\/g;
171         $configstring=~s/"/\\"/g;
172         $configstring=~s/\n/\\n/g;
173         
174         writefile(basename("$wrapper.c"), dirname($wrapper), <<"EOF");
175 /* A wrapper for ikiwiki, can be safely made suid. */
176 #include <stdio.h>
177 #include <sys/types.h>
178 #include <sys/stat.h>
179 #include <fcntl.h>
180 #include <unistd.h>
181 #include <stdlib.h>
182 #include <string.h>
183 #include <sys/file.h>
184
185 extern char **environ;
186 char *newenviron[$envsize+7];
187 int i=0;
188
189 void addenv(char *var, char *val) {
190         char *s=malloc(strlen(var)+1+strlen(val)+1);
191         if (!s)
192                 perror("malloc");
193         sprintf(s, "%s=%s", var, val);
194         newenviron[i++]=s;
195 }
196
197 void set_cgilock_fd (int lockfd) {
198         char *fd_s=malloc(8);
199         sprintf(fd_s, "%i", lockfd);
200         setenv("IKIWIKI_CGILOCK_FD", fd_s, 1);
201 }
202
203 int main (int argc, char **argv) {
204         int lockfd=-1;
205         char *s;
206
207 $check_commit_hook
208 @wrapper_hooks
209 $envsave
210         newenviron[i++]="HOME=$ENV{HOME}";
211         newenviron[i++]="PATH=$ENV{PATH}";
212         newenviron[i++]="WRAPPED_OPTIONS=$configstring";
213
214 #ifdef __TINYC__
215         /* old tcc versions do not support modifying environ directly */
216         if (clearenv() != 0) {
217                 perror("clearenv");
218                 exit(1);
219         }
220         for (; i>0; i--)
221                 putenv(newenviron[i-1]);
222 #else
223         newenviron[i]=NULL;
224         environ=newenviron;
225 #endif
226
227         if (setregid(getegid(), -1) != 0 &&
228             setregid(getegid(), -1) != 0) {
229                 perror("failed to drop real gid");
230                 exit(1);
231         }
232         if (setreuid(geteuid(), -1) != 0 &&
233             setreuid(geteuid(), -1) != 0) {
234                 perror("failed to drop real uid");
235                 exit(1);
236         }
237
238 $pre_exec
239
240 $set_background_command
241 #ifdef BACKGROUND_COMMAND
242         if (lockfd != -1) {
243                 close(lockfd);
244         }
245
246         pid_t pid=fork();
247         if (pid == -1) {
248                 perror("fork");
249                 exit(1);
250         }
251         else if (pid == 0) {
252                 execl("$this", "$this", NULL);
253                 perror("exec $this");
254                 exit(1);                
255         }
256         else {
257                 waitpid(pid, NULL, 0);
258
259                 if (daemon(1, 0) == 0) {
260                         system(BACKGROUND_COMMAND);
261                         exit(0);
262                 }
263                 else {
264                         perror("daemon");
265                         exit(1);
266                 }
267         }
268 #else
269         execl("$this", "$this", NULL);
270         perror("exec $this");
271         exit(1);
272 #endif
273 }
274 EOF
275
276         my @cc=exists $ENV{CC} ? possibly_foolish_untaint($ENV{CC}) : 'cc';
277         push @cc, split(' ', possibly_foolish_untaint($ENV{CFLAGS})) if exists $ENV{CFLAGS};
278         if (system(@cc, "$wrapper.c", "-o", "$wrapper.new") != 0) {
279                 #translators: The parameter is a C filename.
280                 error(sprintf(gettext("failed to compile %s"), "$wrapper.c"));
281         }
282         unlink("$wrapper.c");
283         if (defined $config{wrappergroup}) {
284                 my $gid=(getgrnam($config{wrappergroup}))[2];
285                 if (! defined $gid) {
286                         error(sprintf("bad wrappergroup"));
287                 }
288                 if (! chown(-1, $gid, "$wrapper.new")) {
289                         error("chown $wrapper.new: $!");
290                 }
291         }
292         if (defined $config{wrappermode} &&
293             ! chmod(oct($config{wrappermode}), "$wrapper.new")) {
294                 error("chmod $wrapper.new: $!");
295         }
296         if (! rename("$wrapper.new", $wrapper)) {
297                 error("rename $wrapper.new $wrapper: $!");
298         }
299         #translators: The parameter is a filename.
300         debug(sprintf(gettext("successfully generated %s"), $wrapper));
301 }
302
303 1