chiark / gitweb /
fa8b8ac033d4d6e65a179e1e893184469e2af571
[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 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 "version.h"
39
40 static void NONRETURNING serv_syscallfail(const char *msg) {
41   fputs("uservd(service): ",stderr);
42   perror(msg);
43   _exit(-1);
44 }
45
46 static void NONRETURNING serv_checkstdoutexit(void) {
47   if (ferror(stdout) || fclose(stdout)) serv_syscallfail("write stdout");
48   _exit(0);
49 }
50
51 void bisexec_environment(const char *const *argv) {
52   execlp("env","env",(char*)0);
53   serv_syscallfail("execute `env'");
54 }
55
56 void bisexec_parameter(const char *const *argv) {
57   always_dumpparameter(execargs[0],execargs+1);
58   serv_checkstdoutexit();
59 }
60   
61 void bisexec_help(const char *const *argv) {
62   const char *const *pp;
63   
64   fputs("recognised builtin services:\n",stdout);
65   for (pp= builtinservicehelpstrings; *pp; pp++) printf("  %s\n",*pp);
66   serv_checkstdoutexit();
67 }
68   
69 void bisexec_version(const char *const *argv) {
70   const unsigned char *p;
71   int i;
72   
73   printf("uservd version " VERSION VEREXT "; copyright (C)1996-1997 Ian Jackson.\n"
74 #ifdef DEBUG
75          "DEBUGGING VERSION"
76 #else
77          "production version"
78 #endif
79          " - protocol magic number %08lx\n"
80          "maximums:    fd %-10d                general string %d\n"
81          "             gids %-10d              override length %d\n"
82          "             args or variables %-10d error message %d\n"
83          "             nested inclusion %-10d  errno string reserve %d\n"
84          "protocol checksum: ",
85          BASE_MAGIC,
86          MAX_ALLOW_FD, MAX_GENERAL_STRING,
87          MAX_GIDS, MAX_OVERRIDE_LEN,
88          MAX_ARGSDEFVAR, MAX_ERRMSG_LEN,
89          MAX_INCLUDE_NEST, ERRMSG_RESERVE_ERRNO);
90   for (i=0, p=protocolchecksumversion; i<sizeof(protocolchecksumversion); i++, p++)
91     printf("%02x",*p);
92   printf("\n"
93          "rendezvous socket: `" RENDEZVOUSPATH "'\n"
94          "system config dir: `" SYSTEMCONFIGDIR "'\n"
95          "pipe filename format: `%s' (max length %d)\n",
96          PIPEFORMAT, PIPEMAXLEN);
97   serv_checkstdoutexit();
98 }
99
100 static void NONRETURNING dumpconfig(const char *string) {
101   int nspaces, c, lnl;
102   
103   nspaces= 0;
104   lnl= 1;
105   while ((c= *string++)) {
106     switch (c) {
107     case ' ': nspaces++; break;
108     case '\n':
109       if (!lnl) putchar('\n');
110       nspaces= 0; lnl= 1;
111       break;
112     default:
113       while (nspaces>0) { putchar(' '); nspaces--; }
114       putchar(c);
115       lnl= 0;
116       break;
117     }
118   }
119   assert(lnl);
120   serv_checkstdoutexit();
121 }
122
123 void bisexec_toplevel(const char *const *argv) {
124   dumpconfig(TOPLEVEL_CONFIGURATION);
125 }
126
127 void bisexec_override(const char *const *argv) {
128   dumpconfig(TOPLEVEL_OVERRIDDEN_CONFIGURATION);
129 }
130
131 void bisexec_reset(const char *const *argv) {
132   dumpconfig(RESET_CONFIGURATION);
133 }
134
135 void bisexec_execute(const char *const *argv) {
136   always_dumpexecsettings();
137   serv_checkstdoutexit();
138 }
139
140 void bisexec_shutdown(const char *const *argv) {
141   /* This is only reached if the serviceuser_uid test in
142    * process.c:servicerequest() fails (we have to handle the
143    * shutdown request there, unfortunately).
144    */
145   fputs("uservd: builtin service shutdown: permission denied\n",stderr);
146   _exit(-1);
147 }
148
149 static void serv_resetsignal(int signo) {
150   struct sigaction sig;
151   
152   sig.sa_handler= SIG_DFL;
153   sigemptyset(&sig.sa_mask);
154   sig.sa_flags= 0;
155   if (sigaction(signo,&sig,0)) serv_syscallfail("reset signal handler");
156 }
157
158 static const char *see_loginname(void) { return serviceuser; }
159 static const char *see_home(void) { return serviceuser_dir; }
160 static const char *see_shell(void) { return serviceuser_shell; }
161
162 static const char *see_service(void) { return service; }
163 static const char *see_c_cwd(void) { return cwd; }
164 static const char *see_c_loginname(void) { return loginname; }
165 static const char *see_c_uid(void) {
166   static char buf[CHAR_BIT*sizeof(uid_t)/3+4];
167   snyprintf(buf,sizeof(buf),"%lu",(unsigned long)request_mbuf.callinguid);
168   return buf;
169 }
170
171 static const char *see_c_list(int n, const char *(*fn)(int i)) {
172   int l, i;
173   char *r;
174   
175   for (i=0, l=1; i<n; i++) l+= strlen(fn(i))+1;
176   r= xmalloc(l); r[l-1]= '*';
177   for (i=0, *r=0; i<n; i++) snytprintfcat(r,l,"%s ",fn(i));
178   assert(!r[l-1] && r[l-2]==' ');
179   r[l-2]= 0;
180   return r;
181 }
182
183 static const char *seei_group(int i) {
184   return calling_groups[i];
185 }
186 static const char *see_c_group(void) {
187   return see_c_list(request_mbuf.ngids,seei_group);
188 }
189
190 static const char *seei_gid(int i) {
191   static char buf[CHAR_BIT*sizeof(gid_t)/3+4];
192   
193   snyprintf(buf,sizeof(buf),"%d",calling_gids[i]);
194   return buf;
195 }
196 static const char *see_c_gid(void) {
197   return see_c_list(request_mbuf.ngids,seei_gid);
198 }
199
200 static const struct serv_envinfo {
201   const char *name;
202   const char *(*fn)(void);
203 } serv_envinfos[]= {
204   { "USER",           see_loginname   },
205   { "LOGNAME",        see_loginname   },
206   { "HOME",           see_home        },
207   { "SHELL",          see_shell       },
208   { "PATH",           defaultpath     },
209   { "USERV_SERVICE",  see_service     },
210   { "USERV_CWD",      see_c_cwd       },
211   { "USERV_USER",     see_c_loginname },
212   { "USERV_UID",      see_c_uid       },
213   { "USERV_GROUP",    see_c_group     },
214   { "USERV_GID",      see_c_gid       },
215   {  0                                }
216 };
217
218 void execservice(const int synchsocket[], int clientfd) {
219   static const char *const setenvpfargs[]= {
220     "/bin/sh",
221     "-c",
222     ". " SETENVIRONMENTPATH "; exec \"$@\"",
223     "-",
224     0
225   };
226   int fd, realfd, holdfd, newfd, r, envvarbufsize=0, targ, nargs, i, l;
227   char *envvarbuf=0;
228   const char **args, *const *cpp;
229   char *const *pp;
230   char synchmsg;
231   const struct serv_envinfo *sei;
232
233   if (dup2(fdarray[2].realfd,2)<0) {
234     static const char duperrmsg[]= "uservd(service): cannot dup2 for stderr\n";
235     write(fdarray[2].realfd,duperrmsg,sizeof(duperrmsg)-1);
236     _exit(-1);
237   }
238   serv_resetsignal(SIGPIPE);
239   serv_resetsignal(SIGCHLD);
240
241   if (close(synchsocket[0])) serv_syscallfail("close parent synch socket");
242
243   if (setpgid(0,0)) serv_syscallfail("set process group");
244   synchmsg= 'y';
245   r= write(synchsocket[1],&synchmsg,1);
246   if (r!=1) serv_syscallfail("write synch byte to parent");
247   r= synchread(synchsocket[1],'g');
248   if (r) serv_syscallfail("reach synch byte from parent");
249
250   if (close(clientfd)) serv_syscallfail("close client socket fd");
251
252   /* Now we have to make all the fd's work.  It's rather a complicated
253    * algorithm, unfortunately.  We remember in holdfd[fd] whether fd
254    * is being used to hold a file descriptor we actually want for some
255    * other real fd in the service program; holdfd[fd] contains the fd
256    * we eventually want fd to be dup'd into, so that realfd[holdfd[fd]]==fd.
257    * After setting up the holdfds we go through the fds in order of
258    * eventual fd making sure that fd is the one we want it to be.  If the
259    * holdfd tells us we're currently storing some other fd in there we
260    * move it out of the way with dup and record its new location.
261    */
262   for (fd=0; fd<fdarrayused; fd++) {
263     if (fdarray[fd].holdfd == -1) continue;
264     if (close(fdarray[fd].holdfd)) serv_syscallfail("close pipe hold fd");
265     fdarray[fd].holdfd= -1;
266   }
267   for (fd=0; fd<fdarrayused; fd++) {
268     if (fdarray[fd].realfd < fdarrayused) fdarray[fdarray[fd].realfd].holdfd= fd;
269   }
270   for (fd=0; fd<fdarrayused; fd++) {
271     realfd= fdarray[fd].realfd;
272     if (realfd == -1) continue;
273     holdfd= fdarray[fd].holdfd;
274     if (holdfd == fd) {
275       assert(realfd == fd);
276       fdarray[fd].holdfd= -1;
277       continue;
278     } else if (holdfd != -1) {
279       assert(fdarray[holdfd].realfd == fd);
280       newfd= dup(fd); if (newfd<0) serv_syscallfail("dup out of the way");
281       fdarray[holdfd].realfd= newfd;
282       if (newfd<fdarrayused) fdarray[newfd].holdfd= holdfd;
283       fdarray[fd].holdfd= -1;
284     }
285     if (dup2(fdarray[fd].realfd,fd)<0) serv_syscallfail("dup2 set up fd");
286     if (close(fdarray[fd].realfd)) serv_syscallfail("close old fd");
287     if (fcntl(fd,F_SETFD,0)<0) serv_syscallfail("set no-close-on-exec on fd");
288     fdarray[fd].realfd= fd;
289   }
290
291   for (sei= serv_envinfos; sei->name; sei++)
292     if (setenv(sei->name,sei->fn(),1)) serv_syscallfail("setenv standard");
293   for (i=0; i<request_mbuf.nvars; i++) {
294     l= strlen(defvararray[i].key)+9;
295     if (l>envvarbufsize) { envvarbufsize= l; envvarbuf= xrealloc(envvarbuf,l); }
296     snyprintf(envvarbuf,l,"USERV_U_%s",defvararray[i].key);
297     if (setenv(envvarbuf,defvararray[i].value,1)) serv_syscallfail("setenv defvar");
298   }
299
300   nargs= 0;
301   if (setenvironment) for (cpp= setenvpfargs; *cpp; cpp++) nargs++;
302   nargs++;
303   if (execargs) for (pp= execargs; *pp; pp++) nargs++;
304   if (!suppressargs) nargs+= request_mbuf.nargs;
305   args= xmalloc(sizeof(char*)*(nargs+1));
306   targ= 0;
307   if (setenvironment) for (cpp= setenvpfargs; *cpp; cpp++) args[targ++]= *cpp;
308   args[targ++]= execpath;
309   if (execargs) for (pp= execargs; *pp; pp++) args[targ++]= *pp;
310   if (!suppressargs) for (i=0; i<request_mbuf.nargs; i++) args[targ++]= argarray[i];
311   args[targ]= 0;
312
313   if (execbuiltin)
314     execbuiltin(args);
315   else
316     execv(args[0],(char* const*)args);
317
318   serv_syscallfail("exec service program");
319   _exit(-1);
320 }