/
lxc_init.c
518 lines (435 loc) · 11 KB
/
lxc_init.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
/* SPDX-License-Identifier: LGPL-2.1+ */
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <libgen.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <lxc/lxccontainer.h>
#include <lxc/version.h>
#include "compiler.h"
#include "config.h"
#include "error.h"
#include "initutils.h"
#include "memory_utils.h"
#include "parse.h"
#include "process_utils.h"
#include "string_utils.h"
/* option keys for long only options */
#define OPT_USAGE 0x1000
#define OPT_VERSION (OPT_USAGE - 1)
#define QUOTE(macro) #macro
#define QUOTEVAL(macro) QUOTE(macro)
static sig_atomic_t was_interrupted;
static void interrupt_handler(int sig)
{
if (!was_interrupted)
was_interrupted = sig;
}
static struct option long_options[] = {
{ "name", required_argument, 0, 'n' },
{ "help", no_argument, 0, 'h' },
{ "usage", no_argument, 0, OPT_USAGE },
{ "version", no_argument, 0, OPT_VERSION },
{ "quiet", no_argument, 0, 'q' },
{ "lxcpath", required_argument, 0, 'P' },
{ 0, 0, 0, 0 }
};
static const char short_options[] = "n:hqo:l:P:";
struct arguments {
const struct option *options;
const char *shortopts;
const char *name;
bool quiet;
const char *lxcpath;
/* remaining arguments */
char *const *argv;
int argc;
};
static struct arguments my_args = {
.options = long_options,
.shortopts = short_options
};
static void prevent_forking(void)
{
__do_free char *line = NULL;
__do_fclose FILE *f = NULL;
char path[PATH_MAX];
size_t len = 0;
f = fopen("/proc/self/cgroup", "re");
if (!f)
return;
while (getline(&line, &len, f) != -1) {
__do_close int fd = -EBADF;
int ret;
char *p, *p2;
p = strchr(line, ':');
if (!p)
continue;
p++;
p2 = strchr(p, ':');
if (!p2)
continue;
*p2 = '\0';
/* This is a cgroup v2 entry. Skip it. */
if ((p2 - p) == 0)
continue;
if (strcmp(p, "pids") != 0)
continue;
p2++;
p2 += lxc_char_left_gc(p2, strlen(p2));
p2[lxc_char_right_gc(p2, strlen(p2))] = '\0';
ret = snprintf(path, sizeof(path),
"/sys/fs/cgroup/pids/%s/pids.max", p2);
if (ret < 0 || (size_t)ret >= sizeof(path)) {
if (my_args.quiet)
fprintf(stderr, "Failed to create string\n");
return;
}
fd = open(path, O_WRONLY | O_CLOEXEC);
if (fd < 0) {
if (my_args.quiet)
fprintf(stderr, "Failed to open \"%s\"\n", path);
return;
}
ret = write(fd, "1", 1);
if (ret != 1 && !my_args.quiet)
fprintf(stderr, "Failed to write to \"%s\"\n", path);
return;
}
}
static void kill_children(pid_t pid)
{
__do_fclose FILE *f = NULL;
char path[PATH_MAX];
int ret;
ret = snprintf(path, sizeof(path), "/proc/%d/task/%d/children", pid, pid);
if (ret < 0 || (size_t)ret >= sizeof(path)) {
if (my_args.quiet)
fprintf(stderr, "Failed to create string\n");
return;
}
f = fopen(path, "re");
if (!f) {
if (my_args.quiet)
fprintf(stderr, "Failed to open %s\n", path);
return;
}
while (!feof(f)) {
pid_t find_pid;
if (fscanf(f, "%d ", &find_pid) != 1) {
if (my_args.quiet)
fprintf(stderr, "Failed to retrieve pid\n");
return;
}
(void)kill_children(find_pid);
(void)kill(find_pid, SIGKILL);
}
}
static void remove_self(void)
{
int ret;
ssize_t n;
char path[PATH_MAX] = {0};
n = readlink("/proc/self/exe", path, sizeof(path));
if (n < 0 || n >= PATH_MAX)
return;
path[n] = '\0';
ret = umount2(path, MNT_DETACH);
if (ret < 0)
return;
ret = unlink(path);
if (ret < 0)
return;
}
__noreturn static void print_usage_exit(const struct option longopts[])
{
fprintf(stderr, "Usage: lxc-init [-n|--name=NAME] [-h|--help] [--usage] [--version]\n\
[-q|--quiet] [-P|--lxcpath=LXCPATH]\n");
exit(EXIT_SUCCESS);
}
__noreturn static void print_version_exit(void)
{
printf("%s\n", LXC_VERSION);
exit(EXIT_SUCCESS);
}
static void print_help(void)
{
fprintf(stderr, "\
Usage: lxc-init --name=NAME -- COMMAND\n\
\n\
lxc-init start a COMMAND as PID 2 inside a container\n\
\n\
Options :\n\
-n, --name=NAME NAME of the container\n\
-q, --quiet Don't produce any output\n\
-P, --lxcpath=PATH Use specified container path\n\
-?, --help Give this help list\n\
--usage Give a short usage message\n\
--version Print the version number\n\
\n\
Mandatory or optional arguments to long options are also mandatory or optional\n\
for any corresponding short options.\n\
\n\
See the lxc-init man page for further information.\n\n");
}
static int arguments_parse(struct arguments *args, int argc,
char *const argv[])
{
for (;;) {
int c;
int index = 0;
c = getopt_long(argc, argv, args->shortopts, args->options, &index);
if (c == -1)
break;
switch (c) {
case 'n':
args->name = optarg;
break;
case 'o':
break;
case 'l':
break;
case 'q':
args->quiet = true;
break;
case 'P':
remove_trailing_slashes(optarg);
args->lxcpath = optarg;
break;
case OPT_USAGE:
print_usage_exit(args->options);
case OPT_VERSION:
print_version_exit();
case '?':
print_help();
exit(EXIT_FAILURE);
case 'h':
print_help();
exit(EXIT_SUCCESS);
}
}
/*
* Reclaim the remaining command arguments
*/
args->argv = &argv[optind];
args->argc = argc - optind;
/* If no lxcpath was given, use default */
if (!args->lxcpath)
args->lxcpath = lxc_global_config_value("lxc.lxcpath");
/* Check the command options */
if (!args->name) {
if (!args->quiet)
fprintf(stderr, "lxc-init: missing container name, use --name option\n");
return -1;
}
return 0;
}
int main(int argc, char *argv[])
{
int i, logfd, ret;
pid_t pid;
struct sigaction act;
sigset_t mask, omask;
int have_status = 0, exit_with = 1, shutdown = 0;
if (arguments_parse(&my_args, argc, argv))
exit(EXIT_FAILURE);
if (!my_args.argc) {
if (my_args.quiet)
fprintf(stderr, "Please specify a command to execute\n");
exit(EXIT_FAILURE);
}
/* Mask all the signals so we are safe to install a signal handler and
* to fork.
*/
ret = sigfillset(&mask);
if (ret < 0)
exit(EXIT_FAILURE);
ret = sigdelset(&mask, SIGILL);
if (ret < 0)
exit(EXIT_FAILURE);
ret = sigdelset(&mask, SIGSEGV);
if (ret < 0)
exit(EXIT_FAILURE);
ret = sigdelset(&mask, SIGBUS);
if (ret < 0)
exit(EXIT_FAILURE);
ret = pthread_sigmask(SIG_SETMASK, &mask, &omask);
if (ret < 0)
exit(EXIT_FAILURE);
ret = sigfillset(&act.sa_mask);
if (ret < 0)
exit(EXIT_FAILURE);
ret = sigdelset(&act.sa_mask, SIGILL);
if (ret < 0)
exit(EXIT_FAILURE);
ret = sigdelset(&act.sa_mask, SIGSEGV);
if (ret < 0)
exit(EXIT_FAILURE);
ret = sigdelset(&act.sa_mask, SIGBUS);
if (ret < 0)
exit(EXIT_FAILURE);
ret = sigdelset(&act.sa_mask, SIGSTOP);
if (ret < 0)
exit(EXIT_FAILURE);
ret = sigdelset(&act.sa_mask, SIGKILL);
if (ret < 0)
exit(EXIT_FAILURE);
act.sa_flags = 0;
act.sa_handler = interrupt_handler;
for (i = 1; i < NSIG; i++) {
/* Exclude some signals: ILL, SEGV and BUS are likely to reveal
* a bug and we want a core. STOP and KILL cannot be handled
* anyway: they're here for documentation. 32 and 33 are not
* defined.
*/
if (i == SIGILL || i == SIGSEGV || i == SIGBUS ||
i == SIGSTOP || i == SIGKILL || i == 32 || i == 33)
continue;
ret = sigaction(i, &act, NULL);
if (ret < 0) {
if (errno == EINVAL)
continue;
if (my_args.quiet)
fprintf(stderr, "Failed to change signal action\n");
exit(EXIT_FAILURE);
}
}
remove_self();
pid = fork();
if (pid < 0)
exit(EXIT_FAILURE);
if (!pid) {
/* restore default signal handlers */
for (i = 1; i < NSIG; i++) {
sighandler_t sigerr;
if (i == SIGILL || i == SIGSEGV || i == SIGBUS ||
i == SIGSTOP || i == SIGKILL || i == 32 || i == 33)
continue;
sigerr = signal(i, SIG_DFL);
if (sigerr == SIG_ERR && !my_args.quiet)
fprintf(stderr, "Failed to reset to default action for signal \"%d\": %d\n", i, pid);
}
ret = pthread_sigmask(SIG_SETMASK, &omask, NULL);
if (ret < 0) {
if (my_args.quiet)
fprintf(stderr, "Failed to set signal mask\n");
exit(EXIT_FAILURE);
}
(void)setsid();
(void)ioctl(STDIN_FILENO, TIOCSCTTY, 0);
ret = execvp(my_args.argv[0], my_args.argv);
if (my_args.quiet)
fprintf(stderr, "Failed to exec \"%s\"\n", my_args.argv[0]);
exit(ret);
}
logfd = open("/dev/console", O_WRONLY | O_NOCTTY | O_CLOEXEC);
if (logfd >= 0) {
ret = dup3(logfd, STDERR_FILENO, O_CLOEXEC);
if (ret < 0)
exit(EXIT_FAILURE);
}
(void)setproctitle("init");
/* Let's process the signals now. */
ret = sigdelset(&omask, SIGALRM);
if (ret < 0)
exit(EXIT_FAILURE);
ret = pthread_sigmask(SIG_SETMASK, &omask, NULL);
if (ret < 0) {
if (my_args.quiet)
fprintf(stderr, "Failed to set signal mask\n");
exit(EXIT_FAILURE);
}
/* No need of other inherited fds but stderr. */
close(STDIN_FILENO);
close(STDOUT_FILENO);
for (;;) {
int status;
pid_t waited_pid;
switch (was_interrupted) {
case 0:
/* Some applications send SIGHUP in order to get init to reload
* its configuration. We don't want to forward this onto the
* application itself, because it probably isn't expecting this
* signal since it was expecting init to do something with it.
*
* Instead, let's explicitly ignore it here. The actual
* terminal case is handled in the monitor's handler, which
* sends this task a SIGTERM in the case of a SIGHUP, which is
* what we want.
*/
case SIGHUP:
break;
case SIGPWR:
case SIGTERM:
if (!shutdown) {
pid_t mypid = lxc_raw_getpid();
shutdown = 1;
prevent_forking();
if (mypid != 1) {
kill_children(mypid);
} else {
ret = kill(-1, SIGTERM);
if (ret < 0 && !my_args.quiet)
fprintf(stderr, "Failed to send SIGTERM to all children\n");
}
alarm(1);
}
break;
case SIGALRM: {
pid_t mypid = lxc_raw_getpid();
prevent_forking();
if (mypid != 1) {
kill_children(mypid);
} else {
ret = kill(-1, SIGKILL);
if (ret < 0 && !my_args.quiet)
fprintf(stderr, "Failed to send SIGTERM to all children\n");
}
break;
}
default:
kill(pid, was_interrupted);
break;
}
ret = EXIT_SUCCESS;
was_interrupted = 0;
waited_pid = wait(&status);
if (waited_pid < 0) {
if (errno == ECHILD)
goto out;
if (errno == EINTR)
continue;
if (my_args.quiet)
fprintf(stderr, "Failed to wait on child %d\n", pid);
ret = -1;
goto out;
}
/* Reset timer each time a process exited. */
if (shutdown)
alarm(1);
/* Keep the exit code of the started application (not wrapped
* pid) and continue to wait for the end of the orphan group.
*/
if (waited_pid == pid && !have_status) {
exit_with = lxc_error_set_and_log(waited_pid, status);
have_status = 1;
}
}
out:
if (ret < 0)
exit(EXIT_FAILURE);
exit(exit_with);
}