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