added Esetsid()
[util-vserver.git] / util-vserver / src / rpm-fake.c
1 // $Id$    --*- c++ -*--
2
3 // Copyright (C) 2003 Enrico Scholz <enrico.scholz@informatik.tu-chemnitz.de>
4 //  
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; version 2 of the License.
8 //  
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //  
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17 //  
18
19 #ifdef HAVE_CONFIG_H
20 #  include <config.h>
21 #endif
22
23 #include "pathconfig.h"
24 #include "util.h"
25
26 #include <vserver.h>
27
28 #include <dlfcn.h>
29 #include <stdlib.h>
30 #include <stdint.h>
31 #include <stdio.h>
32 #include <unistd.h>
33 #include <asm/unistd.h>
34 #include <string.h>
35 #include <stdbool.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <stdarg.h>
39 #include <sys/mount.h>
40 #include <linux/fs.h>
41 #include <sched.h>
42 #include <signal.h>
43 #include <sys/types.h>
44 #include <sys/wait.h>
45 #include <sys/socket.h>
46 #include <sys/un.h>
47 #include <fcntl.h>
48 #include <pwd.h>
49 #include <grp.h>
50
51 #ifndef CLONE_NEWNS
52 #  define CLONE_NEWNS   0x00020000
53 #endif
54
55 #define LIBNAME         "rpm-fake.so"
56 #define PLATFORM_FILE   "/etc/rpm/platform"
57
58 #define INIT(FILE,FUNC) FUNC##_func = ((__typeof__(FUNC) *) (xdlsym(FILE, #FUNC)))
59 #define DECLARE(FUNC)   static __typeof__(FUNC) *       FUNC##_func = 0
60
61
62 #define DBG_INIT        0x0001
63 #define DBG_VARIABLES   0x0002
64 #define DBG_RESOLVER    0x0004
65 #define DBG_EXECV       0x0008
66 #define DBG_VERBOSE0    0x8000
67 #define DBG_VERBOSE1    (0x4000 | DBG_VERBOSE0)
68 #define DBG_VERBOSE2    (0x2000 | DBG_VERBOSE1)
69
70 static char const *     ctx_s = 0;
71 static xid_t            ctx   = VC_NOCTX;
72 static uint32_t         caps  = ~0;
73 static int              flags = 0;
74 static char const *     mnts  = 0;
75 static char const *     root  = 0;
76 static int              pw_sock   = -1;
77 static int              sync_sock = -1;
78 static unsigned int     debug_level = 0;
79
80 static bool             is_initialized = false;
81
82 DECLARE(execv);
83 DECLARE(getpwnam);
84 DECLARE(getgrnam);
85 DECLARE(endpwent);
86 DECLARE(endgrent);
87
88 static void             initRPMFake() __attribute__((__constructor__));
89 static void             exitRPMFake() __attribute__((__destructor__));
90
91 static inline bool
92 isDbgLevel(unsigned int level)
93 {
94   return ((debug_level&level)==level);
95 }
96
97 static void *
98 xdlsym(void *handle, const char *symbol)
99 {
100   void  *res = dlsym(handle, symbol);
101   if (res==0) {
102     char const  *error = dlerror();
103     write(2, symbol, strlen(symbol));
104     write(2, ": ", 2);
105     write(2, error, strlen(error));
106     write(2, "\n", 2);
107
108     _exit(255);
109   }
110
111   return res;
112 }
113
114 static void
115 showHelp()
116 {
117   WRITE_MSG(1,
118             "Usage: LD_PRELOAD=" LIBNAME " <executable> <args>*\n\n"
119             LIBNAME " unterstands the following environment variables:\n"
120             "  $RPM_FAKE_RESOLVER     ...  program which does the NSS resolving (defaults\n"
121             "                              to " RESOLVER_PROG ")\n"
122             "  $RPM_FAKE_RESOLVER_UID ...  uid of the resolver program\n"
123             "  $RPM_FAKE_RESOLVER_GID ...  gid of the resolver program\n"
124             "  $RPM_FAKE_CTX          ...  vserver context which shall be used for resolver\n"
125             "                              and scriptlets\n"
126             "  $RPM_FAKE_CAP          ...  linux capability remove-mask for the context\n"
127             "  $RPM_FAKE_FLAGS        ...  vserver flags of the context\n"
128             "  $RPM_FAKE_CHROOT       ...  directory of the chroot environment\n"
129             "  $RPM_FAKE_NAMESPACE_MOUNTS\n"
130             "                          ... colon separated list of directories which will\n"
131             "                              umounted before scriptlet execution\n\n"
132             "  $RPM_FAKE_HELP          ... shows this message\n"
133             "  $RPM_FAKE_VERSION       ... shows the version of this program\n\n"
134             "  $RPM_FAKE_DEBUG         ... sets the debuglevel bitmask\n\n"
135             "Please report bugs to " PACKAGE_BUGREPORT "\n");
136   exit(0);
137 }
138
139 static void
140 showVersion()
141 {
142   WRITE_MSG(1,
143             LIBNAME " " VERSION " -- wrapper around rpm\n"
144             "This program is part of " PACKAGE_STRING "\n\n"
145             "Copyright (C) 2003 Enrico Scholz\n"
146             VERSION_COPYRIGHT_DISCLAIMER);
147   exit(0);
148 }
149
150 static int
151 getAndClearEnv(char const *key, int dflt)
152 {
153   char          *env = getenv(key);
154   int           res;
155
156   if (env==0 || env[0]=='\0') res = dflt;
157   else {
158     res = atoi(env);
159     unsetenv(key);
160   }
161
162   return res;
163 }
164
165 #if 0
166 static void
167 initPwSocket()
168 {
169   char const *  sock_name = getenv("RPM_FAKE_PWSOCKET");
170   if (sock_name!=0) {
171     int flag;
172     struct sockaddr_un  addr = {
173       .sun_family = AF_UNIX,
174     };
175
176     strncpy(addr.sun_path, sock_name, sizeof(addr.sun_path)-1);
177     addr.sun_path[sizeof(addr.sun_path)-1]='\0';
178     
179     if ((pw_sock=socket(AF_UNIX, SOCK_STREAM, 0))==-1 ||
180         connect(pw_sock, (struct sockaddr *)(&addr), sizeof addr)==-1 ||
181         (flag=fcntl(pw_sock, F_GETFD))==-1 ||
182         fcntl(pw_sock, F_SETFD, flag | FD_CLOEXEC)==-1) {
183       perror("error while initializing pw-socket");
184       exit(255);
185     }
186   }
187   unsetenv("RPM_FAKE_PWSOCKET");
188 }
189 #else
190 static void
191 initPwSocket()
192 {
193   char const *  resolver = getenv("RPM_FAKE_RESOLVER");
194   if (resolver==0) resolver=RESOLVER_PROG;
195   
196   if (resolver!=0 && *resolver!='\0') {
197     int                 res_sock[2];
198     int                 sync_pipe[2];
199     pid_t               pid;
200     char const *        uid=0;
201     char const *        gid=0;
202
203     uid=getenv("RPM_FAKE_RESOLVER_UID");
204     gid=getenv("RPM_FAKE_RESOLVER_GID");
205
206     if (socketpair(AF_UNIX, SOCK_STREAM, 0, res_sock)==-1 ||
207         pipe(sync_pipe)==-1 ||
208         fcntl(res_sock[0],  F_SETFD, FD_CLOEXEC)==-1 ||
209         fcntl(sync_pipe[0], F_SETFD, FD_CLOEXEC)==-1) {
210       perror("rpm-fake.so: failed to create/initialize resolver-socket or pipe");
211       exit(255);
212     }
213
214     pid = fork();
215     if (pid==-1) {
216       perror("rpm-fake.so: fork()");
217       exit(255);
218     }
219
220     if (pid==0) {
221       char const        *args[10];
222       char const        **ptr  = args;
223       char const        *env[] = { "HOME=/", "PATH=/bin:/usr/bin", 0 };
224       
225       setsid();
226       dup2(res_sock[1],  0);
227       dup2(res_sock[1],  1);
228       if (sync_pipe[1]!=3) {
229         close(3);
230         dup2(sync_pipe[1], 3);
231         close(sync_pipe[1]);
232       }
233       close(res_sock[1]);
234         /* ... *socket[0] are marked as close-on-exec ...*/
235
236       *ptr++ = resolver;
237       if (root)  { *ptr++ = "-r"; *ptr++ = root;  }
238       if (uid)   { *ptr++ = "-u"; *ptr++ = uid;   }
239       if (gid)   { *ptr++ = "-g"; *ptr++ = gid;   }
240       if (ctx_s) { *ptr++ = "-c"; *ptr++ = ctx_s; }
241       *ptr++ = 0;
242       
243       execve(resolver, (char **)args, (char **)env);
244       perror("rpm-fake.so: failed to exec resolver");
245       exit(255);
246     }
247     else {
248       uint8_t           c;
249
250       close(res_sock[1]);
251       close(sync_pipe[1]);
252       pw_sock   = res_sock[0];
253       sync_sock = sync_pipe[0];
254
255       if (read(sync_sock, &c, 1)!=1 ||
256           write(pw_sock, ".", 1)!=1 ||
257           read(pw_sock, &c,   1)!=1 ||
258           c!='.') {
259         WRITE_MSG(2, "rpm-fake.so: failed to initialize communication with resolver\n");
260         exit(255);
261       }
262
263       if (wait4(pid, 0, WNOHANG,0)==-1) {
264         WRITE_MSG(2, "rpm-fake.so: unexpected initialization-error of resolver\n");
265         exit(255);
266       }
267     }
268
269     free((char *)ctx_s);
270     unsetenv("RPM_FAKE_RESOLVER_GID");
271     unsetenv("RPM_FAKE_RESOLVER_UID");
272     unsetenv("RPM_FAKE_RESOLVER");    
273   }
274 }
275 #endif
276
277 static void
278 initEnvironment()
279 {
280   int           syscall_rev;
281   int           syscall_nr;
282   
283   if (is_initialized) return;
284
285   syscall_rev = getAndClearEnv("RPM_FAKE_S_CONTEXT_REV", 0);
286   syscall_nr  = getAndClearEnv("RPM_FAKE_S_CONTEXT_NR",  273);
287   
288 #ifdef VC_ENABLE_API_LEGACY
289   {
290     extern void vc_init_internal_legacy(int ctx_rev, int ctx_number,
291                                         int ipv4_rev, int ipv4_number);
292   
293     vc_init_internal_legacy(syscall_rev, syscall_nr, 3, 274);
294   }
295 #endif
296
297   ctx_s = getenv("RPM_FAKE_CTX");
298   if (ctx_s && *ctx_s) ctx_s = strdup(ctx_s);
299   else                 ctx_s = 0;
300
301   ctx       = getAndClearEnv("RPM_FAKE_CTX",  VC_RANDCTX);
302   caps      = getAndClearEnv("RPM_FAKE_CAP",  ~0x3404040f);
303   flags     = getAndClearEnv("RPM_FAKE_FLAGS", 0);
304   root      = getenv("RPM_FAKE_CHROOT");
305   mnts      = getenv("RPM_FAKE_NAMESPACE_MOUNTS");
306   if (mnts && *mnts) mnts = strdup(mnts);
307   else               mnts = 0;
308
309   unsetenv("RPM_FAKE_CHROOT");
310   unsetenv("RPM_FAKE_NAMESPACE_MOUNTS");
311
312   
313   is_initialized = true;
314 }
315
316 static void
317 initSymbols()
318 {
319   INIT(RTLD_NEXT, execv);
320   INIT(RTLD_NEXT, getgrnam);
321   INIT(RTLD_NEXT, getpwnam);
322   INIT(RTLD_NEXT, endpwent);
323   INIT(RTLD_NEXT, endgrent);
324 }
325
326 static void
327 fixPreloadEnv()
328 {
329   char                  *env = getenv("LD_PRELOAD");
330   char                  *pos;
331
332     // the const <-> non-const assignment is not an issue since the following
333     // modifying operations will not be executed in the const-case
334   env = env ? env : "";
335   pos = strstr(env, LIBNAME);
336
337   if (pos!=0) {
338     char        *end_pos = pos + sizeof(LIBNAME);
339     bool        is_end = (end_pos[-1]=='\0');
340     char        *start_pos;
341
342     end_pos[-1] = '\0';
343     start_pos   = strrchr(env, ':');
344     if (start_pos==0) start_pos = env;
345     else if (!is_end) ++start_pos;
346
347     if (is_end) *start_pos = '\0';
348     else        memmove(start_pos, end_pos, strlen(end_pos)+1);
349   }
350
351 #ifdef DEBUG
352   if (isDbgLevel(DBG_VERBOSE1|DBG_VARIABLES)) {
353     WRITE_MSG(2, "env='");
354     WRITE_STR(2, env);
355     WRITE_MSG(2, "'\n");
356   }
357 #endif
358
359   if (*env=='\0') unsetenv("LD_PRELOAD");
360 }
361
362 void
363 initRPMFake()
364 {
365   if (getenv("RPM_FAKE_VERSION")) showVersion();
366   if (getenv("RPM_FAKE_HELP"))    showHelp();
367   
368   debug_level = getAndClearEnv("RPM_FAKE_DEBUG", 0);
369
370   if (isDbgLevel(DBG_INIT)) WRITE_MSG(2, ">>>>> initRPMFake <<<<<\n");
371   
372   fixPreloadEnv();
373   initSymbols();
374   initEnvironment();
375   initPwSocket();
376
377 #if 0
378   if (isDbgLevel(DBG_VARIABLES|DBG_VERBOSE2)) {
379     
380   }
381 #endif
382 }
383
384 void
385 exitRPMFake()
386
387   if (isDbgLevel(DBG_INIT)) WRITE_MSG(2, ">>>>> exitRPMFake <<<<<\n");
388   if (pw_sock!=-1) {
389     uint8_t     c;
390     read(sync_sock, &c, 1);
391     write(pw_sock, "Q", 1);
392   }
393 }
394
395
396   //============   the worker part   ===========
397
398
399 static bool
400 doPwStringRequest(uint32_t *result, char style, char const *name)
401 {
402   uint32_t      len = strlen(name);
403   uint8_t       code;
404   uint8_t       c;
405
406     // read the token...
407   read(sync_sock, &c, 1);
408
409   write(pw_sock, &style, 1);
410   write(pw_sock, &len,   sizeof len);
411   write(pw_sock, name,   len);
412   read (pw_sock, &code,  sizeof code);
413   read (pw_sock, result, sizeof *result);
414
415   return code!=0;
416 }
417
418 struct passwd *
419 getpwnam(const char * name)
420 {
421   if (pw_sock==-1) return getpwnam_func(name);
422   else {
423     static struct passwd        res = {
424       .pw_passwd = "*",
425       .pw_gid    = -1,
426       .pw_gecos  = "",
427       .pw_dir    = "/",
428       .pw_shell  = "/bin/false"
429     };
430
431     res.pw_name = (char *)(name);
432     if (!doPwStringRequest(&res.pw_uid, 'P', name)) return 0;
433     
434     return &res;
435   }
436 }
437
438 struct group *
439 getgrnam(const char * name)
440 {
441   if (pw_sock==-1) return getgrnam_func(name);
442   else {
443     static struct group         res = {
444       .gr_passwd = "*",
445       .gr_mem    = 0
446     };
447
448     res.gr_name = (char *)(name);
449     if (!doPwStringRequest(&res.gr_gid, 'G', name)) return 0;
450
451     return &res;
452   }
453 }
454
455 void
456 endgrent()
457 {
458   if (pw_sock==-1) endgrent_func();
459 }
460
461 void
462 endpwent()
463 {
464   if (pw_sock==-1) endpwent_func();
465 }
466
467
468 static int
469 execvWorker(char const *path, char * const argv[])
470 {
471   int           res;
472
473   if ((res=vc_new_s_context(ctx,caps,flags))!=-1 &&
474       (res=execv_func(path, argv)!=-1) ) {}
475
476   return res;
477 }
478
479 struct ExecvParams
480 {
481     char const *        path;
482     char * const *      argv;
483     char const *        mnts;
484 };
485
486 static int
487 removeNamespaceMountsChild(struct ExecvParams const *params)
488 {
489   char                  buf[strlen(params->mnts)+1], *ptr;
490
491   strcpy(buf, params->mnts);
492   ptr = strtok(buf, ":");
493   while (ptr) {
494     if (umount2(ptr, 0)==-1) {
495         // FIXME: What is the semantic for CLONE_NEWNS? Is it ok that mounts in
496         // chroots are visible only, when chroot is on /dev/root?
497         //
498         // For now, ignore any errors, but future versions should handle them.
499
500         //return -1;
501     }
502     ptr = strtok(0, ":");
503   }
504
505   return execvWorker(params->path, params->argv);
506 }
507
508 static int
509 removeNamespaceMounts(char const *path, char * const argv[])
510 {
511   if (mnts==0) return execvWorker(path, argv);
512
513   {
514     int                         status;
515     pid_t                       p, pid;
516     struct ExecvParams          params;
517
518     params.path = path;
519     params.argv = argv;
520     params.mnts = mnts;
521
522       // the rpmlib signal-handler is still active; use the default one to
523       // make wait4() working...
524     signal(SIGCHLD, SIG_DFL);
525
526 #ifdef NDEBUG    
527     pid = syscall(__NR_clone, CLONE_NEWNS|SIGCHLD|CLONE_VFORK, 0);
528 #else
529     pid = syscall(__NR_clone, CLONE_NEWNS|SIGCHLD, 0);
530 #endif
531
532     switch (pid) {
533       case -1   :  return -1;
534       case 0    :  _exit(removeNamespaceMountsChild(&params));
535       default   :  break;
536     }
537         
538     while ((p=wait4(pid, &status, 0,0))==-1 &&
539            (errno==EINTR || errno==EAGAIN)) ;
540
541     if (p==-1)   return -1;
542
543     if (WIFEXITED(status))   _exit(WEXITSTATUS(status));
544     if (WIFSIGNALED(status)) kill(getpid(), WTERMSIG(status));
545
546     return -1;
547   }
548 }
549
550
551 int
552 execv(char const *path, char * const argv[]) __THROW
553 {
554   return removeNamespaceMounts(path, argv);
555 }