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