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