chiark / gitweb /
debian/control: Add missing build-dependency on flex. Fixes FTBFS. Report from Aurel...
[userv.git] / servexec.c
1 /*
2  * userv - execserv.c
3  * daemon code which executes actual service (ie child process)
4  *
5  * userv is copyright Ian Jackson and other contributors.
6  * See README for full authorship information.
7  *
8  * This is free software; you can redistribute it and/or modify it
9  * under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with userv; if not, see <http://www.gnu.org/licenses/>.
20  */
21
22 #include <stdio.h>
23 #include <limits.h>
24 #include <errno.h>
25 #include <assert.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <stdarg.h>
29 #include <stdlib.h>
30 #include <sys/types.h>
31 #include <fcntl.h>
32 #include <signal.h>
33
34 #include "config.h"
35 #include "common.h"
36 #include "daemon.h"
37 #include "lib.h"
38 #include "both.h"
39 #include "version.h"
40
41 static void NONRETURNING serv_syscallfail(const char *msg) {
42   fputs("uservd(service): ",stderr);
43   perror(msg);
44   _exit(-1);
45 }
46
47 static void NONRETURNING serv_checkstdoutexit(void) {
48   if (ferror(stdout) || fclose(stdout)) serv_syscallfail("write stdout");
49   _exit(0);
50 }
51
52 void bisexec_environment(const char *const *argv) {
53   execlp("env","env",(char*)0);
54   serv_syscallfail("execute `env'");
55 }
56
57 void bisexec_parameter(const char *const *argv) {
58   always_dumpparameter(execargs[0],execargs+1);
59   serv_checkstdoutexit();
60 }
61   
62 void bisexec_help(const char *const *argv) {
63   const char *const *pp;
64   
65   fputs("recognised builtin services:\n",stdout);
66   for (pp= builtinservicehelpstrings; *pp; pp++) printf("  %s\n",*pp);
67   serv_checkstdoutexit();
68 }
69   
70 void bisexec_version(const char *const *argv) {
71   const unsigned char *p;
72   int i;
73   
74   printf("uservd version " VERSION VEREXT "\n"
75 #ifdef DEBUG
76          "DEBUGGING VERSION"
77 #else
78          "production version"
79 #endif
80          " - protocol magic number %08lx\n"
81          "maximums:    fd %-10d                general string %d\n"
82          "             gids %-10d              override length %d\n"
83          "             args or variables %-10d error message %d\n"
84          "             nested inclusion %-10d  errno string reserve %d\n"
85          "protocol checksum: ",
86          BASE_MAGIC,
87          MAX_ALLOW_FD, MAX_GENERAL_STRING,
88          MAX_GIDS, MAX_OVERRIDE_LEN,
89          MAX_ARGSDEFVAR, MAX_ERRMSG_LEN,
90          MAX_INCLUDE_NEST, ERRMSG_RESERVE_ERRNO);
91   for (i=0, p=protocolchecksumversion; i<sizeof(protocolchecksumversion); i++, p++)
92     printf("%02x",*p);
93   printf("\n"
94          "rendezvous socket: `" RENDEZVOUSPATH "'\n"
95          "system config dir: `" SYSTEMCONFIGDIR "'\n"
96          "pipe filename format: `%s' (max length %d)\n"
97          COPYRIGHT("","\n"),
98          PIPEFORMAT, PIPEMAXLEN);
99   serv_checkstdoutexit();
100 }
101
102 static void NONRETURNING dumpconfig(const char *string) {
103   int nspaces, c, lnl;
104   
105   nspaces= 0;
106   lnl= 1;
107   while ((c= *string++)) {
108     switch (c) {
109     case ' ': nspaces++; break;
110     case '\n':
111       if (!lnl) putchar('\n');
112       nspaces= 0; lnl= 1;
113       break;
114     default:
115       while (nspaces>0) { putchar(' '); nspaces--; }
116       putchar(c);
117       lnl= 0;
118       break;
119     }
120   }
121   assert(lnl);
122   serv_checkstdoutexit();
123 }
124
125 void bisexec_toplevel(const char *const *argv) {
126   dumpconfig(TOPLEVEL_CONFIGURATION);
127 }
128
129 void bisexec_override(const char *const *argv) {
130   dumpconfig(TOPLEVEL_OVERRIDDEN_CONFIGURATION);
131 }
132
133 void bisexec_reset(const char *const *argv) {
134   dumpconfig(RESET_CONFIGURATION);
135 }
136
137 void bisexec_execute(const char *const *argv) {
138   always_dumpexecsettings();
139   serv_checkstdoutexit();
140 }
141
142 void bisexec_shutdown(const char *const *argv) {
143   /* This is only reached if the serviceuser_uid test in
144    * process.c:servicerequest() fails (we have to handle the
145    * shutdown request there, unfortunately).
146    */
147   fputs("uservd: builtin service shutdown: permission denied\n",stderr);
148   _exit(-1);
149 }
150
151 static void serv_resetsignal(int signo) {
152   struct sigaction sig;
153   
154   sig.sa_handler= SIG_DFL;
155   sigemptyset(&sig.sa_mask);
156   sig.sa_flags= 0;
157   if (sigaction(signo,&sig,0)) serv_syscallfail("reset signal handler");
158 }
159
160 static const char *see_loginname(void) { return serviceuser; }
161 static const char *see_home(void) { return serviceuser_dir; }
162 static const char *see_shell(void) { return serviceuser_shell; }
163
164 static const char *see_service(void) { return service; }
165 static const char *see_c_cwd(void) { return cwd; }
166 static const char *see_c_loginname(void) { return loginname; }
167 static const char *see_c_uid(void) {
168   static char buf[CHAR_BIT*sizeof(uid_t)/3+4];
169   snyprintf(buf,sizeof(buf),"%lu",(unsigned long)request_mbuf.callinguid);
170   return buf;
171 }
172
173 static const char *see_c_list(int n, const char *(*fn)(int i)) {
174   int l, i;
175   char *r;
176   
177   for (i=0, l=1; i<n; i++) l+= strlen(fn(i))+1;
178   r= xmalloc(l); r[l-1]= '*';
179   for (i=0, *r=0; i<n; i++) snytprintfcat(r,l,"%s ",fn(i));
180   assert(!r[l-1] && r[l-2]==' ');
181   r[l-2]= 0;
182   return r;
183 }
184
185 static const char *seei_group(int i) {
186   return calling_groups[i];
187 }
188 static const char *see_c_group(void) {
189   return see_c_list(request_mbuf.ngids,seei_group);
190 }
191
192 static const char *seei_gid(int i) {
193   static char buf[CHAR_BIT*sizeof(gid_t)/3+4];
194   
195   snyprintf(buf,sizeof(buf),"%ld",(long)calling_gids[i]);
196   return buf;
197 }
198 static const char *see_c_gid(void) {
199   return see_c_list(request_mbuf.ngids,seei_gid);
200 }
201
202 static const struct serv_envinfo {
203   const char *name;
204   const char *(*fn)(void);
205 } serv_envinfos[]= {
206   { "USER",           see_loginname   },
207   { "LOGNAME",        see_loginname   },
208   { "HOME",           see_home        },
209   { "SHELL",          see_shell       },
210   { "PATH",           defaultpath     },
211   { "USERV_SERVICE",  see_service     },
212   { "USERV_CWD",      see_c_cwd       },
213   { "USERV_USER",     see_c_loginname },
214   { "USERV_UID",      see_c_uid       },
215   { "USERV_GROUP",    see_c_group     },
216   { "USERV_GID",      see_c_gid       },
217   {  0                                }
218 };
219
220 void execservice(const int synchsocket[], int clientfd) {
221   static const char *const setenvpfargs[]= {
222     "/bin/sh",
223     "-c",
224     ". " SETENVIRONMENTPATH "; exec \"$@\"",
225     "-",
226     0
227   };
228   int fd, realfd, holdfd, newfd, r, envvarbufsize=0, targ, nargs, i, l, fdflags;
229   int unused;
230   char *envvarbuf=0;
231   const char **args, *const *cpp;
232   char *const *pp;
233   char synchmsg;
234   const struct serv_envinfo *sei;
235
236   if (dup2(fdarray[2].realfd,2)<0) {
237     static const char duperrmsg[]= "uservd(service): cannot dup2 for stderr\n";
238     unused= write(fdarray[2].realfd,duperrmsg,sizeof(duperrmsg)-1);
239     (void)unused;
240     _exit(-1);
241   }
242   serv_resetsignal(SIGPIPE);
243   serv_resetsignal(SIGCHLD);
244
245   if (close(synchsocket[0])) serv_syscallfail("close parent synch socket");
246
247   if (setpgid(0,0)) serv_syscallfail("set process group");
248   synchmsg= 'y';
249   r= write(synchsocket[1],&synchmsg,1);
250   if (r!=1) serv_syscallfail("write synch byte to parent");
251   r= synchread(synchsocket[1],'g');
252   if (r) serv_syscallfail("reach synch byte from parent");
253   if (close(synchsocket[1])) serv_syscallfail("close our synch socket");
254
255   if (close(clientfd)) serv_syscallfail("close client socket fd");
256
257   /* First we need to close the holding writing ends of the pipes
258    * inherited from our parent: */
259   for (fd=0; fd<fdarrayused; fd++) {
260     if (fdarray[fd].holdfd == -1) continue;
261     if (close(fdarray[fd].holdfd)) serv_syscallfail("close pipe hold fd");
262     fdarray[fd].holdfd= -1;
263   }
264   /* Now we can reuse the .holdfd member of the fdarray entries. */
265
266   /* We have to make all the fd's work.  It's rather a complicated
267    * algorithm, unfortunately.  We remember in holdfd[fd] whether fd
268    * is being used to hold a file descriptor we actually want for some
269    * other real fd in the service program; holdfd[fd] contains the fd
270    * we eventually want fd to be dup'd into, so that realfd[holdfd[fd]]==fd.
271    * After setting up the holdfds we go through the fds in order of
272    * eventual fd making sure that fd is the one we want it to be.  If the
273    * holdfd tells us we're currently storing some other fd in there we
274    * move it out of the way with dup and record its new location.
275    */
276   for (fd=0; fd<fdarrayused; fd++) {
277     if (fdarray[fd].realfd < fdarrayused && fdarray[fd].realfd >= 0)
278       fdarray[fdarray[fd].realfd].holdfd= fd;
279   }
280   for (fd=0; fd<fdarrayused; fd++) {
281     realfd= fdarray[fd].realfd;
282     if (realfd == -1) continue;
283     holdfd= fdarray[fd].holdfd;
284     if (holdfd == fd) {
285       assert(realfd == fd);
286       fdarray[fd].holdfd= -1;
287       continue;
288     } else if (holdfd != -1) {
289       assert(fdarray[holdfd].realfd == fd);
290       newfd= dup(fd); if (newfd<0) serv_syscallfail("dup out of the way");
291       fdarray[holdfd].realfd= newfd;
292       if (newfd<fdarrayused) fdarray[newfd].holdfd= holdfd;
293       fdarray[fd].holdfd= -1;
294     }
295     if (dup2(fdarray[fd].realfd,fd)<0) serv_syscallfail("dup2 set up fd");
296     if (close(fdarray[fd].realfd)) serv_syscallfail("close old fd");
297     fdflags= fcntl(fd,F_GETFD); if (fdflags<0) serv_syscallfail("get fd flags");
298     if (fcntl(fd,F_SETFD,fdflags&~FD_CLOEXEC)==-1) serv_syscallfail("set no-close-on-exec on fd");
299     fdarray[fd].realfd= fd;
300   }
301
302   for (sei= serv_envinfos; sei->name; sei++)
303     if (setenv(sei->name,sei->fn(),1)) serv_syscallfail("setenv standard");
304   for (i=0; i<request_mbuf.nvars; i++) {
305     l= strlen(defvararray[i].key)+9;
306     if (l>envvarbufsize) { envvarbufsize= l; envvarbuf= xrealloc(envvarbuf,l); }
307     snyprintf(envvarbuf,l,"USERV_U_%s",defvararray[i].key);
308     if (setenv(envvarbuf,defvararray[i].value,1)) serv_syscallfail("setenv defvar");
309   }
310
311   nargs= 0;
312   if (setenvironment) for (cpp= setenvpfargs; *cpp; cpp++) nargs++;
313   nargs++;
314   if (execargs) for (pp= execargs; *pp; pp++) nargs++;
315   if (!suppressargs) nargs+= request_mbuf.nargs;
316   args= xmalloc(sizeof(char*)*(nargs+1));
317   targ= 0;
318   if (setenvironment) for (cpp= setenvpfargs; *cpp; cpp++) args[targ++]= *cpp;
319   args[targ++]= execpath;
320   if (execargs) for (pp= execargs; *pp; pp++) args[targ++]= *pp;
321   if (!suppressargs) for (i=0; i<request_mbuf.nargs; i++) args[targ++]= argarray[i];
322   args[targ]= 0;
323
324   if (execbuiltin)
325     execbuiltin(args);
326   else
327     execv(args[0],(char* const*)args);
328
329   serv_syscallfail("exec service program");
330   _exit(-1);
331 }