minor optimizations
[util-vserver.git] / util-vserver / src / vcontext.c
1 // $Id$    --*- c -*--
2
3 // Copyright (C) 2004 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 "util.h"
24 #include "lib/internal.h"
25 #include "lib_internal/jail.h"
26
27 #include "linuxcaps.h"
28
29 #include <vserver.h>
30 #include <getopt.h>
31 #include <fcntl.h>
32 #include <errno.h>
33 #include <sys/socket.h>
34 #include <sys/un.h>
35 #include <assert.h>
36 #include <signal.h>
37
38 #define ENSC_WRAPPERS_PREFIX    "vcontext: "
39 #define ENSC_WRAPPERS_UNISTD    1
40 #define ENSC_WRAPPERS_VSERVER   1
41 #define ENSC_WRAPPERS_FCNTL     1
42 #define ENSC_WRAPPERS_SOCKET    1
43 #define ENSC_WRAPPERS_IOSOCK    1
44 #include <wrappers.h>
45
46 #define CMD_HELP                0x1000
47 #define CMD_VERSION             0x1001
48 #define CMD_XID                 0x4000
49 #define CMD_CREATE              0x4001
50 #define CMD_MIGRATE             0x4003
51 #define CMD_INITPID             0x4002
52 #define CMD_DISCONNECT          0x4004
53 #define CMD_UID                 0x4005
54 #define CMD_CHROOT              0x4006
55 #define CMD_SILENT              0x4007
56 #define CMD_SYNCSOCK            0x4008
57 #define CMD_SYNCMSG             0x4009
58 #define CMD_MIGRATESELF         0x400a
59 #define CMD_ENDSETUP            0x400b
60 #define CMD_SILENTEXIST         0x400c
61
62
63 struct option const
64 CMDLINE_OPTIONS[] = {
65   { "help",       no_argument,       0, CMD_HELP },
66   { "version",    no_argument,       0, CMD_VERSION },
67   { "ctx",        required_argument, 0, CMD_XID },
68   { "xid",        required_argument, 0, CMD_XID },
69   { "create",     no_argument,       0, CMD_CREATE },
70   { "migrate",    no_argument,       0, CMD_MIGRATE },
71   { "migrate-self", no_argument,        0, CMD_MIGRATESELF },
72   { "initpid",      no_argument,        0, CMD_INITPID },
73   { "endsetup",     no_argument,        0, CMD_ENDSETUP },
74   { "disconnect",   no_argument,        0, CMD_DISCONNECT },
75   { "silent",       no_argument,        0, CMD_SILENT },
76   { "silentexist",  no_argument,        0, CMD_SILENTEXIST },
77   { "uid",          required_argument,  0, CMD_UID },
78   { "chroot",       no_argument,        0, CMD_CHROOT },
79   { "syncsock",     required_argument,  0, CMD_SYNCSOCK },
80   { "syncmsg",      required_argument,  0, CMD_SYNCMSG },
81 #if 1  
82   { "fakeinit",     no_argument,        0, CMD_INITPID },       // compatibility
83 #endif  
84   { 0,0,0,0 },
85 };
86
87 struct Arguments {
88     bool                do_create;
89     bool                do_migrate;
90     bool                do_migrateself;
91     bool                do_disconnect;
92     bool                do_endsetup;
93     bool                is_initpid;
94     bool                is_silentexist;
95     int                 verbosity;
96     bool                do_chroot;
97     uid_t               uid;
98     xid_t               xid;
99     char const *        sync_sock;
100     char const *        sync_msg;
101 };
102
103 int             wrapper_exit_code = 255;
104
105 static void
106 showHelp(int fd, char const *cmd, int res)
107 {
108   WRITE_MSG(fd, "Usage:\n    ");
109   WRITE_STR(fd, cmd);
110   WRITE_MSG(fd,
111             " --create [--xid <xid>] <opts>* [--] <program> <args>*\n    ");
112   WRITE_STR(fd, cmd);
113   WRITE_MSG(fd,
114             " [(--migrate --xid <xid>)|--migrate-self]  <opts>* [--] <program> <args>*\n"
115             "\n"
116             "<opts> can be:\n"
117             "    --chroot        ...  chroot into current directory\n"
118             "    --uid <uid>     ...  change uid\n"
119             "    --initpid       ...  set current process as general process reaper\n"
120             "                         for ctx (possible for --migrate only)\n"
121             "    --endsetup      ...  clear the setup flag; usefully for migrate only\n"
122             "    --disconnect    ...  start program in background\n"
123             "    --silent        ...  be silent\n"
124             "    --silentexist   ...  be silent when context exists already; usefully\n"
125             "                         for '--create' only\n"
126             "    --syncsock <file-name>\n"
127             "                    ...  before executing the program, send a message\n"
128             "                         to the socket and wait until it closes.\n"
129             "                         <file-name> must be a SOCK_STREAM unix socket\n"
130             "    --syncmsg <message>\n"
131             "                    ...  use <message> as synchronization message; by\n"
132             "                         default, 'ok' will be used\n"
133             "\n"
134             "'vcontext --create' exits with code 254 iff the context exists already.\n"
135             "\n"
136             "Please report bugs to " PACKAGE_BUGREPORT "\n");
137
138   exit(res);
139 }
140
141 static void
142 showVersion()
143 {
144   WRITE_MSG(1,
145             "vcontext " VERSION " -- manages the creation of security contexts\n"
146             "This program is part of " PACKAGE_STRING "\n\n"
147             "Copyright (C) 2004 Enrico Scholz\n"
148             VERSION_COPYRIGHT_DISCLAIMER);
149   exit(0);
150 }
151
152 #include "context-sync.hc"
153
154 static inline ALWAYSINLINE void
155 tellContext(xid_t ctx, bool do_it)
156 {
157   char          buf[sizeof(xid_t)*3+2];
158   size_t        l;
159
160   if (!do_it) return;
161
162   l = utilvserver_fmt_long(buf,ctx);
163
164   WRITE_MSG(1, "New security context is ");
165   write(1, buf, l);
166   WRITE_MSG(1, "\n");
167 }
168
169 static int
170 connectExternalSync(char const *filename)
171 {
172   int                   fd;
173   struct sockaddr_un    addr;
174   
175   if (filename==0) return -1;
176
177   ENSC_INIT_UNIX_SOCK(addr, filename);
178
179   fd = Esocket(PF_UNIX, SOCK_STREAM, 0);
180   Econnect(fd, &addr, sizeof(addr));
181
182   return fd;
183 }
184
185 static void
186 setFlags(struct Arguments const *args, xid_t xid)
187 {
188   struct vc_ctx_flags   flags = { 0,0 };
189
190   if (args->is_initpid)
191     flags.mask |=  VC_VXF_STATE_INIT;
192
193   if (args->do_endsetup)
194     flags.mask |=  VC_VXF_STATE_SETUP;
195
196   if (flags.mask!=0) {
197     DPRINTF("set_flags: mask=%08llx, flag=%08llx\n", flags.mask, flags.flagword);
198     Evc_set_cflags(xid, &flags);
199   }
200 }
201
202 static void
203 doExternalSync(int fd, char const *msg)
204 {
205   char          c;
206   
207   if (fd==-1) return;
208
209   if (msg) EsendAll(fd, msg, strlen(msg));
210   Eshutdown(fd, SHUT_WR);
211
212   if (TEMP_FAILURE_RETRY(recv(fd, &c, 1, MSG_NOSIGNAL))!=0) {
213     WRITE_MSG(2, ENSC_WRAPPERS_PREFIX "unexpected external synchronization event\n");
214     exit(255);
215   }
216
217   Eclose(fd);
218 }
219
220 static inline ALWAYSINLINE int
221 doit(struct Arguments const *args, char *argv[])
222 {
223   int                   p[2][2];
224   pid_t                 pid = initSync(p, args->do_disconnect);
225   
226   if (pid==0) {
227     xid_t                       xid;
228     int                         ext_sync_fd = connectExternalSync(args->sync_sock);
229
230     doSyncStage0(p, args->do_disconnect);
231     
232     if (args->do_create) {
233       xid = vc_ctx_create(args->xid);
234       if (xid==VC_NOCTX) {
235         switch (errno) {
236           case EEXIST   :
237             if (!args->is_silentexist)
238               perror(ENSC_WRAPPERS_PREFIX "vc_create_context()");
239             return 254;
240           default       :
241             perror(ENSC_WRAPPERS_PREFIX "vc_create_context()");
242             return wrapper_exit_code;
243         }
244       }
245       tellContext(xid, args->verbosity>=1);
246     }
247     else
248       xid = args->xid;
249
250     if (args->do_chroot)
251       Echroot(".");
252
253     setFlags(args, xid);
254
255     if (args->do_migrate && !args->do_migrateself)
256       Evc_ctx_migrate(xid);
257
258     if (args->uid!=(uid_t)(-1) && getuid()!=args->uid) {
259       Esetuid(args->uid);
260       if (getuid()!=args->uid) {
261         WRITE_MSG(2, ENSC_WRAPPERS_PREFIX "Something went wrong while changing the UID\n");
262         exit(255);
263       }
264     }
265     
266     doExternalSync(ext_sync_fd, args->sync_msg);
267     doSyncStage1(p, args->do_disconnect);
268     DPRINTF("doit: pid=%u, ppid=%u\n", getpid(), getppid());
269     execvp (argv[optind],argv+optind);
270     doSyncStage2(p, args->do_disconnect);
271
272     PERROR_Q(ENSC_WRAPPERS_PREFIX "execvp", argv[optind]);
273     exit(255);
274   }
275
276   assert(args->do_disconnect);
277     
278   waitOnSync(pid, p, args->xid!=VC_DYNAMIC_XID && args->do_migrate);
279   return EXIT_SUCCESS;
280 }
281
282 int main (int argc, char *argv[])
283 {
284   struct Arguments              args = {
285     .do_create      = false,
286     .do_migrate     = false,
287     .do_migrateself = false,
288     .do_disconnect  = false,
289     .do_endsetup    = false,
290     .is_initpid     = false,
291     .is_silentexist = false,
292     .verbosity      = 1,
293     .uid            = -1,
294     .xid            = VC_DYNAMIC_XID,
295     .sync_msg       = "ok",
296   };
297   
298   while (1) {
299     int         c = getopt_long(argc, argv, "+", CMDLINE_OPTIONS, 0);
300     if (c==-1) break;
301     
302     switch (c) {
303       case CMD_HELP             :  showHelp(1, argv[0], 0);
304       case CMD_VERSION          :  showVersion();
305       case CMD_CREATE           :  args.do_create      = true;   break;
306       case CMD_MIGRATE          :  args.do_migrate     = true;   break;
307       case CMD_DISCONNECT       :  args.do_disconnect  = true;   break;
308       case CMD_ENDSETUP         :  args.do_endsetup    = true;   break;
309       case CMD_INITPID          :  args.is_initpid     = true;   break;
310       case CMD_CHROOT           :  args.do_chroot      = true;   break;
311       case CMD_SILENTEXIST      :  args.is_silentexist = true;   break;
312       case CMD_SYNCSOCK         :  args.sync_sock      = optarg; break;
313       case CMD_SYNCMSG          :  args.sync_msg       = optarg; break;
314       case CMD_UID              :  args.uid = atol(optarg);      break;
315       case CMD_XID              :  args.xid = Evc_xidopt2xid(optarg,true); break;
316       case CMD_SILENT           :  --args.verbosity; break;
317       case CMD_MIGRATESELF      :
318         args.do_migrate     = true;
319         args.do_migrateself = true;
320         break;
321
322       default           :
323         WRITE_MSG(2, "Try '");
324         WRITE_STR(2, argv[0]);
325         WRITE_MSG(2, " --help\" for more information.\n");
326         return 255;
327         break;
328     }
329   }
330
331   signal(SIGCHLD, SIG_DFL);
332   
333   if (args.do_migrateself)
334     args.xid = Evc_get_task_xid(0);
335   
336   if (!args.do_create && !args.do_migrate)
337     WRITE_MSG(2, "Neither '--create' nor '--migrate specified; try '--help' for more information\n");
338   else if (args.do_create  &&  args.do_migrate)
339     WRITE_MSG(2, "Can not specify '--create' and '--migrate' at the same time; try '--help' for more information\n");
340   else if (!args.do_migrate && args.is_initpid)
341     WRITE_MSG(2, "'--initpid' is possible in combination with '--migrate' only\n");
342   else if (!args.do_create && args.xid==VC_DYNAMIC_XID)
343     WRITE_MSG(2, ENSC_WRAPPERS_PREFIX "Can not migrate to an unknown context\n");
344   else if (optind>=argc)
345     WRITE_MSG(2, "No command given; use '--help' for more information.\n");
346   else
347     return doit(&args, argv);
348
349   return 255;
350 }