do not call vc_new_s_context() when COMPAT API is not available
[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 = ~0ull;
199       caps.cmask = ~0ull;
200       caps.bcaps = ~vc_get_insecurecaps();
201       caps.bmask = ~0ull;
202       Evc_set_ccaps(rc, &caps);
203       
204         // context will be activated later...
205
206       xid = rc;
207       res = true;
208     }
209   }
210
211   if (xid==VC_DYNAMIC_XID)
212     *xid_str = 0;
213   else {
214     char                buf[sizeof(xid_t)*3 + 2];
215     size_t              l;
216     
217     l        = utilvserver_fmt_uint(buf, xid); buf[l] = '\0';
218     *xid_str = strdup(buf);
219   }
220  
221   Ewrite(3, &xid, sizeof xid);
222   return res;
223 }
224
225 #if 0
226 static void
227 initPwSocket()
228 {
229   char const *  sock_name = getenv("RPM_FAKE_PWSOCKET");
230   if (sock_name!=0) {
231     int flag;
232     struct sockaddr_un  addr = {
233       .sun_family = AF_UNIX,
234     };
235
236     strncpy(addr.sun_path, sock_name, sizeof(addr.sun_path)-1);
237     addr.sun_path[sizeof(addr.sun_path)-1]='\0';
238     
239     if ((pw_sock=socket(AF_UNIX, SOCK_STREAM, 0))==-1 ||
240         connect(pw_sock, (struct sockaddr *)(&addr), sizeof addr)==-1 ||
241         (flag=fcntl(pw_sock, F_GETFD))==-1 ||
242         fcntl(pw_sock, F_SETFD, flag | FD_CLOEXEC)==-1) {
243       perror(ENSC_WRAPPERS_PREFIX "error while initializing pw-socket");
244       exit(255);
245     }
246   }
247   unsetenv("RPM_FAKE_PWSOCKET");
248 }
249 #else
250 static void
251 initPwSocket()
252 {
253   char const *  resolver = getenv("RPM_FAKE_RESOLVER");
254   if (resolver==0) resolver=RESOLVER_PROG;
255   
256   if (resolver!=0 && *resolver!='\0') {
257     int                 res_sock[2];
258     int                 sync_pipe[2];
259     pid_t               pid;
260     char const *        uid=0;
261     char const *        gid=0;
262
263     uid=getenv("RPM_FAKE_RESOLVER_UID");
264     gid=getenv("RPM_FAKE_RESOLVER_GID");
265
266     if (socketpair(AF_UNIX, SOCK_STREAM, 0, res_sock)==-1 ||
267         pipe(sync_pipe)==-1 ||
268         fcntl(res_sock[0],  F_SETFD, FD_CLOEXEC)==-1 ||
269         fcntl(sync_pipe[0], F_SETFD, FD_CLOEXEC)==-1) {
270       perror(ENSC_WRAPPERS_PREFIX "failed to create/initialize resolver-socket or pipe");
271       exit(255);
272     }
273
274     pid = fork();
275     if (pid==-1) {
276       perror(ENSC_WRAPPERS_PREFIX "fork()");
277       exit(255);
278     }
279
280     if (pid==0) {
281       char const        *args[15];
282       char const        **ptr  = args;
283       char const        *env[] = { "HOME=/", "PATH=/bin:/usr/bin", 0 };
284       char const        *xid_str;
285       
286       setsid();
287       dup2(res_sock[1],  0);
288       dup2(res_sock[1],  1);
289       if (sync_pipe[1]!=3) {
290         close(3);
291         dup2(sync_pipe[1], 3);
292         close(sync_pipe[1]);
293       }
294       close(res_sock[1]);
295         /* ... *socket[0] are marked as close-on-exec ...*/
296
297       *ptr++ = resolver;
298       if (root)  { *ptr++ = "-r"; *ptr++ = root;  }
299       if (uid)   { *ptr++ = "-u"; *ptr++ = uid;   }
300       if (gid)   { *ptr++ = "-g"; *ptr++ = gid;   }
301
302       if (setupContext(ctx, &xid_str)) { *ptr++ = "-s"; }
303       else if (xid_str)                { *ptr++ = "-c"; *ptr++ = xid_str; }
304       
305       *ptr++ = 0;
306       execve(resolver, (char **)args, (char **)env);
307       perror(ENSC_WRAPPERS_PREFIX "failed to exec resolver");
308       exit(255);
309     }
310     else {
311       uint8_t           c;
312
313       close(res_sock[1]);
314       close(sync_pipe[1]);
315       pw_sock   = res_sock[0];
316       sync_sock = sync_pipe[0];
317
318       if (read(sync_sock, &ctx, sizeof ctx)!=sizeof(ctx) ||
319           read(sync_sock, &c, 1)!=1 ||
320           write(pw_sock, ".", 1)!=1 ||
321           read(pw_sock, &c,   1)!=1 ||
322           c!='.') {
323         WRITE_MSG(2, ENSC_WRAPPERS_PREFIX "failed to initialize communication with resolver\n");
324         exit(255);
325       }
326
327       if (wait4(pid, 0, WNOHANG,0)==-1) {
328         WRITE_MSG(2, ENSC_WRAPPERS_PREFIX" unexpected initialization-error of resolver\n");
329         exit(255);
330       }
331     }
332
333     unsetenv("RPM_FAKE_RESOLVER_GID");
334     unsetenv("RPM_FAKE_RESOLVER_UID");
335     unsetenv("RPM_FAKE_RESOLVER");    
336   }
337 }
338 #endif
339
340 static void
341 initEnvironment()
342 {
343   int           syscall_rev;
344   int           syscall_nr;
345   
346   if (is_initialized) return;
347
348   syscall_rev = getAndClearEnv("RPM_FAKE_S_CONTEXT_REV", 0);
349   syscall_nr  = getAndClearEnv("RPM_FAKE_S_CONTEXT_NR",  273);
350   
351 #ifdef VC_ENABLE_API_LEGACY
352   {
353     extern void vc_init_internal_legacy(int ctx_rev, int ctx_number,
354                                         int ipv4_rev, int ipv4_number);
355   
356     vc_init_internal_legacy(syscall_rev, syscall_nr, 3, 274);
357   }
358 #endif
359
360   ctx       = getAndClearEnv("RPM_FAKE_CTX",  VC_DYNAMIC_XID);
361   caps      = getAndClearEnv("RPM_FAKE_CAP",  ~0x3404040f);
362   flags     = getAndClearEnv("RPM_FAKE_FLAGS", 0);
363   root      = getenv("RPM_FAKE_CHROOT");
364   mnts      = getenv("RPM_FAKE_NAMESPACE_MOUNTS");
365   if (mnts && *mnts) mnts = strdup(mnts);
366   else               mnts = 0;
367
368   unsetenv("RPM_FAKE_CHROOT");
369   unsetenv("RPM_FAKE_NAMESPACE_MOUNTS");
370
371   
372   is_initialized = true;
373 }
374
375 static void
376 initSymbols()
377 {
378   INIT(RTLD_NEXT, execv);
379   INIT(RTLD_NEXT, getgrnam);
380   INIT(RTLD_NEXT, getpwnam);
381   INIT(RTLD_NEXT, endpwent);
382   INIT(RTLD_NEXT, endgrent);
383 }
384
385 static void
386 fixPreloadEnv()
387 {
388   char                  *env = getenv("LD_PRELOAD");
389   char                  *pos;
390
391     // the const <-> non-const assignment is not an issue since the following
392     // modifying operations will not be executed in the const-case
393   env = env ? env : "";
394   pos = strstr(env, LIBNAME);
395
396   if (pos!=0) {
397     char        *end_pos = pos + sizeof(LIBNAME);
398     bool        is_end = (end_pos[-1]=='\0');
399     char        *start_pos;
400
401     end_pos[-1] = '\0';
402     start_pos   = strrchr(env, ':');
403     if (start_pos==0) start_pos = env;
404     else if (!is_end) ++start_pos;
405
406     if (is_end) *start_pos = '\0';
407     else        memmove(start_pos, end_pos, strlen(end_pos)+1);
408   }
409
410 #ifdef DEBUG
411   if (isDbgLevel(DBG_VERBOSE1|DBG_VARIABLES)) {
412     WRITE_MSG(2, "env='");
413     WRITE_STR(2, env);
414     WRITE_MSG(2, "'\n");
415   }
416 #endif
417
418   if (*env=='\0') unsetenv("LD_PRELOAD");
419 }
420
421 void
422 initRPMFake()
423 {
424   if (getenv("RPM_FAKE_VERSION")) showVersion();
425   if (getenv("RPM_FAKE_HELP"))    showHelp();
426   
427   debug_level = getAndClearEnv("RPM_FAKE_DEBUG", 0);
428
429   if (isDbgLevel(DBG_INIT)) WRITE_MSG(2, ">>>>> initRPMFake <<<<<\n");
430   
431   fixPreloadEnv();
432   initSymbols();
433   initEnvironment();
434   initPwSocket();
435
436 #if 0
437   if (isDbgLevel(DBG_VARIABLES|DBG_VERBOSE2)) {
438     
439   }
440 #endif
441 }
442
443 void
444 exitRPMFake()
445
446   if (isDbgLevel(DBG_INIT)) WRITE_MSG(2, ">>>>> exitRPMFake <<<<<\n");
447   if (pw_sock!=-1) {
448     uint8_t     c;
449     read(sync_sock, &c, 1);
450     write(pw_sock, "Q", 1);
451   }
452 }
453
454
455   //============   the worker part   ===========
456
457
458 static bool
459 doPwStringRequest(uint32_t *result, char style, char const *name)
460 {
461   uint32_t      len = strlen(name);
462   uint8_t       code;
463   uint8_t       c;
464
465     // read the token...
466   read(sync_sock, &c, 1);
467
468   write(pw_sock, &style, 1);
469   write(pw_sock, &len,   sizeof len);
470   write(pw_sock, name,   len);
471   read (pw_sock, &code,  sizeof code);
472   read (pw_sock, result, sizeof *result);
473
474   return code!=0;
475 }
476
477 struct passwd *
478 getpwnam(const char * name)
479 {
480   if (pw_sock==-1) return getpwnam_func(name);
481   else {
482     static struct passwd        res = {
483       .pw_passwd = "*",
484       .pw_gid    = -1,
485       .pw_gecos  = "",
486       .pw_dir    = "/",
487       .pw_shell  = "/bin/false"
488     };
489
490     res.pw_name = (char *)(name);
491     if (!doPwStringRequest(&res.pw_uid, 'P', name)) return 0;
492     
493     return &res;
494   }
495 }
496
497 struct group *
498 getgrnam(const char * name)
499 {
500   if (pw_sock==-1) return getgrnam_func(name);
501   else {
502     static struct group         res = {
503       .gr_passwd = "*",
504       .gr_mem    = 0
505     };
506
507     res.gr_name = (char *)(name);
508     if (!doPwStringRequest(&res.gr_gid, 'G', name)) return 0;
509
510     return &res;
511   }
512 }
513
514 void
515 endgrent()
516 {
517   if (pw_sock==-1) endgrent_func();
518 }
519
520 void
521 endpwent()
522 {
523   if (pw_sock==-1) endpwent_func();
524 }
525
526
527 static int
528 execvWorker(char const *path, char * const argv[])
529 {
530   int           res = -1;
531
532   if (vc_isSupported(vcFEATURE_MIGRATE))
533     res = vc_migrate_context(ctx);
534   else
535 #ifdef VC_ENABLE_API_COMPAT  
536     res = vc_new_s_context(ctx,caps,flags);
537 #else
538     WRITE_MSG(2, ENSC_WRAPPERS_PREFIX "can not change context: migrate kernel feature missing and 'compat' API disabled\n");
539 #endif
540     
541   if (res!=-1)
542     res=execv_func(path, argv);
543
544   return res;
545 }
546
547 struct ExecvParams
548 {
549     char const *        path;
550     char * const *      argv;
551     char const *        mnts;
552 };
553
554 static int
555 removeNamespaceMountsChild(struct ExecvParams const *params)
556 {
557   char                  buf[strlen(params->mnts)+1], *ptr;
558
559   strcpy(buf, params->mnts);
560   ptr = strtok(buf, ":");
561   while (ptr) {
562     if (umount2(ptr, 0)==-1) {
563         // FIXME: What is the semantic for CLONE_NEWNS? Is it ok that mounts in
564         // chroots are visible only, when chroot is on /dev/root?
565         //
566         // For now, ignore any errors, but future versions should handle them.
567
568         //return -1;
569     }
570     ptr = strtok(0, ":");
571   }
572
573   return execvWorker(params->path, params->argv);
574 }
575
576 static int
577 removeNamespaceMounts(char const *path, char * const argv[])
578 {
579   if (mnts==0) return execvWorker(path, argv);
580
581   {
582     int                         status;
583     pid_t                       p, pid;
584     struct ExecvParams          params;
585
586     params.path = path;
587     params.argv = argv;
588     params.mnts = mnts;
589
590       // the rpmlib signal-handler is still active; use the default one to
591       // make wait4() working...
592     signal(SIGCHLD, SIG_DFL);
593
594 #ifdef NDEBUG
595     pid = sys_clone(CLONE_NEWNS|SIGCHLD|CLONE_VFORK, 0);
596 #else
597     pid = sys_clone(CLONE_NEWNS|SIGCHLD, 0);
598 #endif
599
600     switch (pid) {
601       case -1   :  return -1;
602       case 0    :  _exit(removeNamespaceMountsChild(&params));
603       default   :  break;
604     }
605         
606     while ((p=wait4(pid, &status, 0,0))==-1 &&
607            (errno==EINTR || errno==EAGAIN)) ;
608
609     if (p==-1)   return -1;
610
611     if (WIFEXITED(status))   _exit(WEXITSTATUS(status));
612     if (WIFSIGNALED(status)) kill(getpid(), WTERMSIG(status));
613
614     return -1;
615   }
616 }
617
618
619 int
620 execv(char const *path, char * const argv[]) __THROW
621 {
622   return removeNamespaceMounts(path, argv);
623 }