chiark / gitweb /
some packaging and makefile fixes (found in a working tree)
[userv.git] / servexec.c
1 /*
2  * userv - execserv.c
3  * daemon code which executes actual service (ie child process)
4  *
5  * Copyright (C)1996-1997,1999-2001,2003 Ian Jackson
6  *
7  * This is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with userv; if not, write to the Free Software
19  * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
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 "; copyright (C)1996-2000 Ian Jackson.\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          PIPEFORMAT, PIPEMAXLEN);
98   serv_checkstdoutexit();
99 }
100
101 static void NONRETURNING dumpconfig(const char *string) {
102   int nspaces, c, lnl;
103   
104   nspaces= 0;
105   lnl= 1;
106   while ((c= *string++)) {
107     switch (c) {
108     case ' ': nspaces++; break;
109     case '\n':
110       if (!lnl) putchar('\n');
111       nspaces= 0; lnl= 1;
112       break;
113     default:
114       while (nspaces>0) { putchar(' '); nspaces--; }
115       putchar(c);
116       lnl= 0;
117       break;
118     }
119   }
120   assert(lnl);
121   serv_checkstdoutexit();
122 }
123
124 void bisexec_toplevel(const char *const *argv) {
125   dumpconfig(TOPLEVEL_CONFIGURATION);
126 }
127
128 void bisexec_override(const char *const *argv) {
129   dumpconfig(TOPLEVEL_OVERRIDDEN_CONFIGURATION);
130 }
131
132 void bisexec_reset(const char *const *argv) {
133   dumpconfig(RESET_CONFIGURATION);
134 }
135
136 void bisexec_execute(const char *const *argv) {
137   always_dumpexecsettings();
138   serv_checkstdoutexit();
139 }
140
141 void bisexec_shutdown(const char *const *argv) {
142   /* This is only reached if the serviceuser_uid test in
143    * process.c:servicerequest() fails (we have to handle the
144    * shutdown request there, unfortunately).
145    */
146   fputs("uservd: builtin service shutdown: permission denied\n",stderr);
147   _exit(-1);
148 }
149
150 static void serv_resetsignal(int signo) {
151   struct sigaction sig;
152   
153   sig.sa_handler= SIG_DFL;
154   sigemptyset(&sig.sa_mask);
155   sig.sa_flags= 0;
156   if (sigaction(signo,&sig,0)) serv_syscallfail("reset signal handler");
157 }
158
159 static const char *see_loginname(void) { return serviceuser; }
160 static const char *see_home(void) { return serviceuser_dir; }
161 static const char *see_shell(void) { return serviceuser_shell; }
162
163 static const char *see_service(void) { return service; }
164 static const char *see_c_cwd(void) { return cwd; }
165 static const char *see_c_loginname(void) { return loginname; }
166 static const char *see_c_uid(void) {
167   static char buf[CHAR_BIT*sizeof(uid_t)/3+4];
168   snyprintf(buf,sizeof(buf),"%lu",(unsigned long)request_mbuf.callinguid);
169   return buf;
170 }
171
172 static const char *see_c_list(int n, const char *(*fn)(int i)) {
173   int l, i;
174   char *r;
175   
176   for (i=0, l=1; i<n; i++) l+= strlen(fn(i))+1;
177   r= xmalloc(l); r[l-1]= '*';
178   for (i=0, *r=0; i<n; i++) snytprintfcat(r,l,"%s ",fn(i));
179   assert(!r[l-1] && r[l-2]==' ');
180   r[l-2]= 0;
181   return r;
182 }
183
184 static const char *seei_group(int i) {
185   return calling_groups[i];
186 }
187 static const char *see_c_group(void) {
188   return see_c_list(request_mbuf.ngids,seei_group);
189 }
190
191 static const char *seei_gid(int i) {
192   static char buf[CHAR_BIT*sizeof(gid_t)/3+4];
193   
194   snyprintf(buf,sizeof(buf),"%ld",(long)calling_gids[i]);
195   return buf;
196 }
197 static const char *see_c_gid(void) {
198   return see_c_list(request_mbuf.ngids,seei_gid);
199 }
200
201 static const struct serv_envinfo {
202   const char *name;
203   const char *(*fn)(void);
204 } serv_envinfos[]= {
205   { "USER",           see_loginname   },
206   { "LOGNAME",        see_loginname   },
207   { "HOME",           see_home        },
208   { "SHELL",          see_shell       },
209   { "PATH",           defaultpath     },
210   { "USERV_SERVICE",  see_service     },
211   { "USERV_CWD",      see_c_cwd       },
212   { "USERV_USER",     see_c_loginname },
213   { "USERV_UID",      see_c_uid       },
214   { "USERV_GROUP",    see_c_group     },
215   { "USERV_GID",      see_c_gid       },
216   {  0                                }
217 };
218
219 void execservice(const int synchsocket[], int clientfd) {
220   static const char *const setenvpfargs[]= {
221     "/bin/sh",
222     "-c",
223     ". " SETENVIRONMENTPATH "; exec \"$@\"",
224     "-",
225     0
226   };
227   int fd, realfd, holdfd, newfd, r, envvarbufsize=0, targ, nargs, i, l, fdflags;
228   char *envvarbuf=0;
229   const char **args, *const *cpp;
230   char *const *pp;
231   char synchmsg;
232   const struct serv_envinfo *sei;
233
234   if (dup2(fdarray[2].realfd,2)<0) {
235     static const char duperrmsg[]= "uservd(service): cannot dup2 for stderr\n";
236     write(fdarray[2].realfd,duperrmsg,sizeof(duperrmsg)-1);
237     _exit(-1);
238   }
239   serv_resetsignal(SIGPIPE);
240   serv_resetsignal(SIGCHLD);
241
242   if (close(synchsocket[0])) serv_syscallfail("close parent synch socket");
243
244   if (setpgid(0,0)) serv_syscallfail("set process group");
245   synchmsg= 'y';
246   r= write(synchsocket[1],&synchmsg,1);
247   if (r!=1) serv_syscallfail("write synch byte to parent");
248   r= synchread(synchsocket[1],'g');
249   if (r) serv_syscallfail("reach synch byte from parent");
250
251   if (close(clientfd)) serv_syscallfail("close client socket fd");
252
253   /* First we need to close the holding writing ends of the pipes
254    * inherited from our parent: */
255   for (fd=0; fd<fdarrayused; fd++) {
256     if (fdarray[fd].holdfd == -1) continue;
257     if (close(fdarray[fd].holdfd)) serv_syscallfail("close pipe hold fd");
258     fdarray[fd].holdfd= -1;
259   }
260   /* Now we can reuse the .holdfd member of the fdarray entries. */
261
262   /* We have to make all the fd's work.  It's rather a complicated
263    * algorithm, unfortunately.  We remember in holdfd[fd] whether fd
264    * is being used to hold a file descriptor we actually want for some
265    * other real fd in the service program; holdfd[fd] contains the fd
266    * we eventually want fd to be dup'd into, so that realfd[holdfd[fd]]==fd.
267    * After setting up the holdfds we go through the fds in order of
268    * eventual fd making sure that fd is the one we want it to be.  If the
269    * holdfd tells us we're currently storing some other fd in there we
270    * move it out of the way with dup and record its new location.
271    */
272   for (fd=0; fd<fdarrayused; fd++) {
273     if (fdarray[fd].realfd < fdarrayused && fdarray[fd].realfd >= 0)
274       fdarray[fdarray[fd].realfd].holdfd= fd;
275   }
276   for (fd=0; fd<fdarrayused; fd++) {
277     realfd= fdarray[fd].realfd;
278     if (realfd == -1) continue;
279     holdfd= fdarray[fd].holdfd;
280     if (holdfd == fd) {
281       assert(realfd == fd);
282       fdarray[fd].holdfd= -1;
283       continue;
284     } else if (holdfd != -1) {
285       assert(fdarray[holdfd].realfd == fd);
286       newfd= dup(fd); if (newfd<0) serv_syscallfail("dup out of the way");
287       fdarray[holdfd].realfd= newfd;
288       if (newfd<fdarrayused) fdarray[newfd].holdfd= holdfd;
289       fdarray[fd].holdfd= -1;
290     }
291     if (dup2(fdarray[fd].realfd,fd)<0) serv_syscallfail("dup2 set up fd");
292     if (close(fdarray[fd].realfd)) serv_syscallfail("close old fd");
293     fdflags= fcntl(fd,F_GETFD); if (fdflags<0) serv_syscallfail("get fd flags");
294     if (fcntl(fd,F_SETFD,fdflags&~FD_CLOEXEC)==-1) serv_syscallfail("set no-close-on-exec on fd");
295     fdarray[fd].realfd= fd;
296   }
297
298   for (sei= serv_envinfos; sei->name; sei++)
299     if (setenv(sei->name,sei->fn(),1)) serv_syscallfail("setenv standard");
300   for (i=0; i<request_mbuf.nvars; i++) {
301     l= strlen(defvararray[i].key)+9;
302     if (l>envvarbufsize) { envvarbufsize= l; envvarbuf= xrealloc(envvarbuf,l); }
303     snyprintf(envvarbuf,l,"USERV_U_%s",defvararray[i].key);
304     if (setenv(envvarbuf,defvararray[i].value,1)) serv_syscallfail("setenv defvar");
305   }
306
307   nargs= 0;
308   if (setenvironment) for (cpp= setenvpfargs; *cpp; cpp++) nargs++;
309   nargs++;
310   if (execargs) for (pp= execargs; *pp; pp++) nargs++;
311   if (!suppressargs) nargs+= request_mbuf.nargs;
312   args= xmalloc(sizeof(char*)*(nargs+1));
313   targ= 0;
314   if (setenvironment) for (cpp= setenvpfargs; *cpp; cpp++) args[targ++]= *cpp;
315   args[targ++]= execpath;
316   if (execargs) for (pp= execargs; *pp; pp++) args[targ++]= *pp;
317   if (!suppressargs) for (i=0; i<request_mbuf.nargs; i++) args[targ++]= argarray[i];
318   args[targ]= 0;
319
320   if (execbuiltin)
321     execbuiltin(args);
322   else
323     execv(args[0],(char* const*)args);
324
325   serv_syscallfail("exec service program");
326   _exit(-1);
327 }