]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/attach.c
Use pthread_atfork() to unlock mutexes after fork()
[mirror_lxc.git] / src / lxc / attach.c
1 /*
2 * lxc: linux Container library
3 *
4 * (C) Copyright IBM Corp. 2007, 2008
5 *
6 * Authors:
7 * Daniel Lezcano <daniel.lezcano at free.fr>
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23
24 #define _GNU_SOURCE
25 #include <unistd.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <sys/param.h>
32 #include <sys/prctl.h>
33 #include <sys/mount.h>
34 #include <sys/socket.h>
35 #include <sys/syscall.h>
36 #include <sys/wait.h>
37 #include <linux/unistd.h>
38 #include <pwd.h>
39
40 #if !HAVE_DECL_PR_CAPBSET_DROP
41 #define PR_CAPBSET_DROP 24
42 #endif
43
44 #include "namespace.h"
45 #include "log.h"
46 #include "attach.h"
47 #include "caps.h"
48 #include "config.h"
49 #include "utils.h"
50 #include "commands.h"
51 #include "cgroup.h"
52 #include "lxclock.h"
53 #include "lsm/lsm.h"
54
55 #if HAVE_SYS_PERSONALITY_H
56 #include <sys/personality.h>
57 #endif
58
59 #ifndef SOCK_CLOEXEC
60 # define SOCK_CLOEXEC 02000000
61 #endif
62
63 lxc_log_define(lxc_attach, lxc);
64
65 struct lxc_proc_context_info *lxc_proc_get_context_info(pid_t pid)
66 {
67 struct lxc_proc_context_info *info = calloc(1, sizeof(*info));
68 FILE *proc_file;
69 char proc_fn[MAXPATHLEN];
70 char *line = NULL;
71 size_t line_bufsz = 0;
72 int ret, found;
73
74 if (!info) {
75 SYSERROR("Could not allocate memory.");
76 return NULL;
77 }
78
79 /* read capabilities */
80 snprintf(proc_fn, MAXPATHLEN, "/proc/%d/status", pid);
81
82 proc_file = fopen(proc_fn, "r");
83 if (!proc_file) {
84 SYSERROR("Could not open %s", proc_fn);
85 goto out_error;
86 }
87
88 found = 0;
89 while (getline(&line, &line_bufsz, proc_file) != -1) {
90 ret = sscanf(line, "CapBnd: %llx", &info->capability_mask);
91 if (ret != EOF && ret > 0) {
92 found = 1;
93 break;
94 }
95 }
96
97 if (line)
98 free(line);
99 fclose(proc_file);
100
101 if (!found) {
102 SYSERROR("Could not read capability bounding set from %s", proc_fn);
103 errno = ENOENT;
104 goto out_error;
105 }
106
107 /* read personality */
108 snprintf(proc_fn, MAXPATHLEN, "/proc/%d/personality", pid);
109
110 proc_file = fopen(proc_fn, "r");
111 if (!proc_file) {
112 SYSERROR("Could not open %s", proc_fn);
113 goto out_error;
114 }
115
116 ret = fscanf(proc_file, "%lx", &info->personality);
117 fclose(proc_file);
118
119 if (ret == EOF || ret == 0) {
120 SYSERROR("Could not read personality from %s", proc_fn);
121 errno = ENOENT;
122 goto out_error;
123 }
124 info->lsm_label = lsm_process_label_get(pid);
125
126 return info;
127
128 out_error:
129 free(info);
130 return NULL;
131 }
132
133 static void lxc_proc_put_context_info(struct lxc_proc_context_info *ctx)
134 {
135 if (ctx->lsm_label)
136 free(ctx->lsm_label);
137 free(ctx);
138 }
139
140 int lxc_attach_to_ns(pid_t pid, int which)
141 {
142 char path[MAXPATHLEN];
143 /* according to <http://article.gmane.org/gmane.linux.kernel.containers.lxc.devel/1429>,
144 * the file for user namepsaces in /proc/$pid/ns will be called
145 * 'user' once the kernel supports it
146 */
147 static char *ns[] = { "mnt", "pid", "uts", "ipc", "user", "net" };
148 static int flags[] = {
149 CLONE_NEWNS, CLONE_NEWPID, CLONE_NEWUTS, CLONE_NEWIPC,
150 CLONE_NEWUSER, CLONE_NEWNET
151 };
152 static const int size = sizeof(ns) / sizeof(char *);
153 int fd[size];
154 int i, j, saved_errno;
155
156
157 snprintf(path, MAXPATHLEN, "/proc/%d/ns", pid);
158 if (access(path, X_OK)) {
159 ERROR("Does this kernel version support 'attach' ?");
160 return -1;
161 }
162
163 for (i = 0; i < size; i++) {
164 /* ignore if we are not supposed to attach to that
165 * namespace
166 */
167 if (which != -1 && !(which & flags[i])) {
168 fd[i] = -1;
169 continue;
170 }
171
172 snprintf(path, MAXPATHLEN, "/proc/%d/ns/%s", pid, ns[i]);
173 fd[i] = open(path, O_RDONLY | O_CLOEXEC);
174 if (fd[i] < 0) {
175 saved_errno = errno;
176
177 /* close all already opened file descriptors before
178 * we return an error, so we don't leak them
179 */
180 for (j = 0; j < i; j++)
181 close(fd[j]);
182
183 errno = saved_errno;
184 SYSERROR("failed to open '%s'", path);
185 return -1;
186 }
187 }
188
189 for (i = 0; i < size; i++) {
190 if (fd[i] >= 0 && setns(fd[i], 0) != 0) {
191 saved_errno = errno;
192
193 for (j = i; j < size; j++)
194 close(fd[j]);
195
196 errno = saved_errno;
197 SYSERROR("failed to set namespace '%s'", ns[i]);
198 return -1;
199 }
200
201 close(fd[i]);
202 }
203
204 return 0;
205 }
206
207 int lxc_attach_remount_sys_proc()
208 {
209 int ret;
210
211 ret = unshare(CLONE_NEWNS);
212 if (ret < 0) {
213 SYSERROR("failed to unshare mount namespace");
214 return -1;
215 }
216
217 /* assume /proc is always mounted, so remount it */
218 ret = umount2("/proc", MNT_DETACH);
219 if (ret < 0) {
220 SYSERROR("failed to unmount /proc");
221 return -1;
222 }
223
224 ret = mount("none", "/proc", "proc", 0, NULL);
225 if (ret < 0) {
226 SYSERROR("failed to remount /proc");
227 return -1;
228 }
229
230 /* try to umount /sys - if it's not a mount point,
231 * we'll get EINVAL, then we ignore it because it
232 * may not have been mounted in the first place
233 */
234 ret = umount2("/sys", MNT_DETACH);
235 if (ret < 0 && errno != EINVAL) {
236 SYSERROR("failed to unmount /sys");
237 return -1;
238 } else if (ret == 0) {
239 /* remount it */
240 ret = mount("none", "/sys", "sysfs", 0, NULL);
241 if (ret < 0) {
242 SYSERROR("failed to remount /sys");
243 return -1;
244 }
245 }
246
247 return 0;
248 }
249
250 int lxc_attach_drop_privs(struct lxc_proc_context_info *ctx)
251 {
252 int last_cap = lxc_caps_last_cap();
253 int cap;
254
255 for (cap = 0; cap <= last_cap; cap++) {
256 if (ctx->capability_mask & (1LL << cap))
257 continue;
258
259 if (prctl(PR_CAPBSET_DROP, cap, 0, 0, 0)) {
260 SYSERROR("failed to remove capability id %d", cap);
261 return -1;
262 }
263 }
264
265 return 0;
266 }
267
268 int lxc_attach_set_environment(enum lxc_attach_env_policy_t policy, char** extra_env, char** extra_keep)
269 {
270 if (policy == LXC_ATTACH_CLEAR_ENV) {
271 char **extra_keep_store = NULL;
272 int path_kept = 0;
273
274 if (extra_keep) {
275 size_t count, i;
276
277 for (count = 0; extra_keep[count]; count++);
278
279 extra_keep_store = calloc(count, sizeof(char *));
280 if (!extra_keep_store) {
281 SYSERROR("failed to allocate memory for storing current "
282 "environment variable values that will be kept");
283 return -1;
284 }
285 for (i = 0; i < count; i++) {
286 char *v = getenv(extra_keep[i]);
287 if (v) {
288 extra_keep_store[i] = strdup(v);
289 if (!extra_keep_store[i]) {
290 SYSERROR("failed to allocate memory for storing current "
291 "environment variable values that will be kept");
292 while (i > 0)
293 free(extra_keep_store[--i]);
294 free(extra_keep_store);
295 return -1;
296 }
297 if (strcmp(extra_keep[i], "PATH") == 0)
298 path_kept = 1;
299 }
300 /* calloc sets entire array to zero, so we don't
301 * need an else */
302 }
303 }
304
305 if (clearenv()) {
306 char **p;
307 SYSERROR("failed to clear environment");
308 if (extra_keep_store) {
309 for (p = extra_keep_store; *p; p++)
310 free(*p);
311 free(extra_keep_store);
312 }
313 return -1;
314 }
315
316 if (extra_keep_store) {
317 size_t i;
318 for (i = 0; extra_keep[i]; i++) {
319 if (extra_keep_store[i])
320 setenv(extra_keep[i], extra_keep_store[i], 1);
321 free(extra_keep_store[i]);
322 }
323 free(extra_keep_store);
324 }
325
326 /* always set a default path; shells and execlp tend
327 * to be fine without it, but there is a disturbing
328 * number of C programs out there that just assume
329 * that getenv("PATH") is never NULL and then die a
330 * painful segfault death. */
331 if (!path_kept) {
332 #ifdef HAVE_CONFSTR
333 size_t n;
334 char *path_env;
335
336 n = confstr(_CS_PATH, NULL, 0);
337 path_env = malloc(n);
338 if (path_env) {
339 confstr(_CS_PATH, path_env, n);
340 setenv("PATH", path_env, 1);
341 free(path_env);
342 }
343 /* don't error out, this is just an extra service */
344 #else
345 setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1);
346 #endif
347 }
348 }
349
350 if (putenv("container=lxc")) {
351 SYSERROR("failed to set environment variable");
352 return -1;
353 }
354
355 /* set extra environment variables */
356 if (extra_env) {
357 for (; *extra_env; extra_env++) {
358 /* duplicate the string, just to be on
359 * the safe side, because putenv does not
360 * do it for us */
361 char *p = strdup(*extra_env);
362 /* we just assume the user knows what they
363 * are doing, so we don't do any checks */
364 if (!p) {
365 SYSERROR("failed to allocate memory for additional environment "
366 "variables");
367 return -1;
368 }
369 putenv(p);
370 }
371 }
372
373 return 0;
374 }
375
376 char *lxc_attach_getpwshell(uid_t uid)
377 {
378 /* local variables */
379 pid_t pid;
380 int pipes[2];
381 int ret;
382 int fd;
383 char *result = NULL;
384
385 /* we need to fork off a process that runs the
386 * getent program, and we need to capture its
387 * output, so we use a pipe for that purpose
388 */
389 ret = pipe(pipes);
390 if (ret < 0)
391 return NULL;
392
393 pid = fork();
394 if (pid < 0) {
395 close(pipes[0]);
396 close(pipes[1]);
397 return NULL;
398 }
399
400 if (pid) {
401 /* parent process */
402 FILE *pipe_f;
403 char *line = NULL;
404 size_t line_bufsz = 0;
405 int found = 0;
406 int status;
407
408 close(pipes[1]);
409
410 pipe_f = fdopen(pipes[0], "r");
411 while (getline(&line, &line_bufsz, pipe_f) != -1) {
412 char *token;
413 char *saveptr = NULL;
414 long value;
415 char *endptr = NULL;
416 int i;
417
418 /* if we already found something, just continue
419 * to read until the pipe doesn't deliver any more
420 * data, but don't modify the existing data
421 * structure
422 */
423 if (found)
424 continue;
425
426 /* trim line on the right hand side */
427 for (i = strlen(line); i > 0 && (line[i - 1] == '\n' || line[i - 1] == '\r'); --i)
428 line[i - 1] = '\0';
429
430 /* split into tokens: first user name */
431 token = strtok_r(line, ":", &saveptr);
432 if (!token)
433 continue;
434 /* next: dummy password field */
435 token = strtok_r(NULL, ":", &saveptr);
436 if (!token)
437 continue;
438 /* next: user id */
439 token = strtok_r(NULL, ":", &saveptr);
440 value = token ? strtol(token, &endptr, 10) : 0;
441 if (!token || !endptr || *endptr || value == LONG_MIN || value == LONG_MAX)
442 continue;
443 /* dummy sanity check: user id matches */
444 if ((uid_t) value != uid)
445 continue;
446 /* skip fields: gid, gecos, dir, go to next field 'shell' */
447 for (i = 0; i < 4; i++) {
448 token = strtok_r(NULL, ":", &saveptr);
449 if (!token)
450 break;
451 }
452 if (!token)
453 continue;
454 if (result)
455 free(result);
456 result = strdup(token);
457
458 /* sanity check that there are no fields after that */
459 token = strtok_r(NULL, ":", &saveptr);
460 if (token)
461 continue;
462
463 found = 1;
464 }
465
466 free(line);
467 fclose(pipe_f);
468 again:
469 if (waitpid(pid, &status, 0) < 0) {
470 if (errno == EINTR)
471 goto again;
472 return NULL;
473 }
474
475 /* some sanity checks: if anything even hinted at going
476 * wrong: we can't be sure we have a valid result, so
477 * we assume we don't
478 */
479
480 if (!WIFEXITED(status))
481 return NULL;
482
483 if (WEXITSTATUS(status) != 0)
484 return NULL;
485
486 if (!found)
487 return NULL;
488
489 return result;
490 } else {
491 /* child process */
492 char uid_buf[32];
493 char *arguments[] = {
494 "getent",
495 "passwd",
496 uid_buf,
497 NULL
498 };
499
500 close(pipes[0]);
501
502 /* we want to capture stdout */
503 dup2(pipes[1], 1);
504 close(pipes[1]);
505
506 /* get rid of stdin/stderr, so we try to associate it
507 * with /dev/null
508 */
509 fd = open("/dev/null", O_RDWR);
510 if (fd < 0) {
511 close(0);
512 close(2);
513 } else {
514 dup2(fd, 0);
515 dup2(fd, 2);
516 close(fd);
517 }
518
519 /* finish argument list */
520 ret = snprintf(uid_buf, sizeof(uid_buf), "%ld", (long) uid);
521 if (ret <= 0)
522 exit(-1);
523
524 /* try to run getent program */
525 (void) execvp("getent", arguments);
526 exit(-1);
527 }
528 }
529
530 void lxc_attach_get_init_uidgid(uid_t* init_uid, gid_t* init_gid)
531 {
532 FILE *proc_file;
533 char proc_fn[MAXPATHLEN];
534 char *line = NULL;
535 size_t line_bufsz = 0;
536 int ret;
537 long value = -1;
538 uid_t uid = (uid_t)-1;
539 gid_t gid = (gid_t)-1;
540
541 /* read capabilities */
542 snprintf(proc_fn, MAXPATHLEN, "/proc/%d/status", 1);
543
544 proc_file = fopen(proc_fn, "r");
545 if (!proc_file)
546 return;
547
548 while (getline(&line, &line_bufsz, proc_file) != -1) {
549 /* format is: real, effective, saved set user, fs
550 * we only care about real uid
551 */
552 ret = sscanf(line, "Uid: %ld", &value);
553 if (ret != EOF && ret > 0) {
554 uid = (uid_t) value;
555 } else {
556 ret = sscanf(line, "Gid: %ld", &value);
557 if (ret != EOF && ret > 0)
558 gid = (gid_t) value;
559 }
560 if (uid != (uid_t)-1 && gid != (gid_t)-1)
561 break;
562 }
563
564 fclose(proc_file);
565 free(line);
566
567 /* only override arguments if we found something */
568 if (uid != (uid_t)-1)
569 *init_uid = uid;
570 if (gid != (gid_t)-1)
571 *init_gid = gid;
572
573 /* TODO: we should also parse supplementary groups and use
574 * setgroups() to set them */
575 }
576
577 struct attach_clone_payload {
578 int ipc_socket;
579 lxc_attach_options_t* options;
580 struct lxc_proc_context_info* init_ctx;
581 lxc_attach_exec_t exec_function;
582 void* exec_payload;
583 };
584
585 static int attach_child_main(void* data);
586
587 /* help the optimizer along if it doesn't know that exit always exits */
588 #define rexit(c) do { int __c = (c); exit(__c); return __c; } while(0)
589
590 /* define default options if no options are supplied by the user */
591 static lxc_attach_options_t attach_static_default_options = LXC_ATTACH_OPTIONS_DEFAULT;
592
593 int lxc_attach(const char* name, const char* lxcpath, lxc_attach_exec_t exec_function, void* exec_payload, lxc_attach_options_t* options, pid_t* attached_process)
594 {
595 int ret, status;
596 pid_t init_pid, pid, attached_pid;
597 struct lxc_proc_context_info *init_ctx;
598 char* cwd;
599 char* new_cwd;
600 int ipc_sockets[2];
601
602 if (!options)
603 options = &attach_static_default_options;
604
605 init_pid = lxc_cmd_get_init_pid(name, lxcpath);
606 if (init_pid < 0) {
607 ERROR("failed to get the init pid");
608 return -1;
609 }
610
611 init_ctx = lxc_proc_get_context_info(init_pid);
612 if (!init_ctx) {
613 ERROR("failed to get context of the init process, pid = %ld", (long)init_pid);
614 return -1;
615 }
616
617 cwd = getcwd(NULL, 0);
618
619 /* determine which namespaces the container was created with
620 * by asking lxc-start, if necessary
621 */
622 if (options->namespaces == -1) {
623 options->namespaces = lxc_cmd_get_clone_flags(name, lxcpath);
624 /* call failed */
625 if (options->namespaces == -1) {
626 ERROR("failed to automatically determine the "
627 "namespaces which the container unshared");
628 free(cwd);
629 lxc_proc_put_context_info(init_ctx);
630 return -1;
631 }
632 }
633
634 /* create a socket pair for IPC communication; set SOCK_CLOEXEC in order
635 * to make sure we don't irritate other threads that want to fork+exec away
636 *
637 * IMPORTANT: if the initial process is multithreaded and another call
638 * just fork()s away without exec'ing directly after, the socket fd will
639 * exist in the forked process from the other thread and any close() in
640 * our own child process will not really cause the socket to close properly,
641 * potentiall causing the parent to hang.
642 *
643 * For this reason, while IPC is still active, we have to use shutdown()
644 * if the child exits prematurely in order to signal that the socket
645 * is closed and cannot assume that the child exiting will automatically
646 * do that.
647 *
648 * IPC mechanism: (X is receiver)
649 * initial process intermediate attached
650 * X <--- send pid of
651 * attached proc,
652 * then exit
653 * send 0 ------------------------------------> X
654 * [do initialization]
655 * X <------------------------------------ send 1
656 * [add to cgroup, ...]
657 * send 2 ------------------------------------> X
658 * close socket close socket
659 * run program
660 */
661 ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, ipc_sockets);
662 if (ret < 0) {
663 SYSERROR("could not set up required IPC mechanism for attaching");
664 free(cwd);
665 lxc_proc_put_context_info(init_ctx);
666 return -1;
667 }
668
669 /* create intermediate subprocess, three reasons:
670 * 1. runs all pthread_atfork handlers and the
671 * child will no longer be threaded
672 * (we can't properly setns() in a threaded process)
673 * 2. we can't setns() in the child itself, since
674 * we want to make sure we are properly attached to
675 * the pidns
676 * 3. also, the initial thread has to put the attached
677 * process into the cgroup, which we can only do if
678 * we didn't already setns() (otherwise, user
679 * namespaces will hate us)
680 */
681 pid = fork();
682
683 if (pid < 0) {
684 SYSERROR("failed to create first subprocess");
685 free(cwd);
686 lxc_proc_put_context_info(init_ctx);
687 return -1;
688 }
689
690 if (pid) {
691 pid_t to_cleanup_pid = pid;
692 int expected = 0;
693
694 /* inital thread, we close the socket that is for the
695 * subprocesses
696 */
697 close(ipc_sockets[1]);
698 free(cwd);
699
700 /* get pid from intermediate process */
701 ret = lxc_read_nointr_expect(ipc_sockets[0], &attached_pid, sizeof(attached_pid), NULL);
702 if (ret <= 0) {
703 if (ret != 0)
704 ERROR("error using IPC to receive pid of attached process");
705 goto cleanup_error;
706 }
707
708 /* reap intermediate process */
709 ret = wait_for_pid(pid);
710 if (ret < 0)
711 goto cleanup_error;
712
713 /* we will always have to reap the grandchild now */
714 to_cleanup_pid = attached_pid;
715
716 /* tell attached process it may start initializing */
717 status = 0;
718 ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));
719 if (ret <= 0) {
720 ERROR("error using IPC to notify attached process for initialization (0)");
721 goto cleanup_error;
722 }
723
724 /* wait for the attached process to finish initializing */
725 expected = 1;
726 ret = lxc_read_nointr_expect(ipc_sockets[0], &status, sizeof(status), &expected);
727 if (ret <= 0) {
728 if (ret != 0)
729 ERROR("error using IPC to receive notification from attached process (1)");
730 goto cleanup_error;
731 }
732
733 /* attach to cgroup, if requested */
734 if (options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) {
735 struct cgroup_meta_data *meta_data;
736 struct cgroup_process_info *container_info;
737
738 meta_data = lxc_cgroup_load_meta();
739 if (!meta_data) {
740 ERROR("could not move attached process %ld to cgroup of container", (long)attached_pid);
741 goto cleanup_error;
742 }
743
744 container_info = lxc_cgroup_get_container_info(name, lxcpath, meta_data);
745 lxc_cgroup_put_meta(meta_data);
746 if (!container_info) {
747 ERROR("could not move attached process %ld to cgroup of container", (long)attached_pid);
748 goto cleanup_error;
749 }
750
751 ret = lxc_cgroup_enter(container_info, attached_pid, false);
752 lxc_cgroup_process_info_free(container_info);
753 if (ret < 0) {
754 ERROR("could not move attached process %ld to cgroup of container", (long)attached_pid);
755 goto cleanup_error;
756 }
757 }
758
759 /* tell attached process we're done */
760 status = 2;
761 ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status));
762 if (ret <= 0) {
763 ERROR("error using IPC to notify attached process for initialization (2)");
764 goto cleanup_error;
765 }
766
767 /* now shut down communication with child, we're done */
768 shutdown(ipc_sockets[0], SHUT_RDWR);
769 close(ipc_sockets[0]);
770 lxc_proc_put_context_info(init_ctx);
771
772 /* we're done, the child process should now execute whatever
773 * it is that the user requested. The parent can now track it
774 * with waitpid() or similar.
775 */
776
777 *attached_process = attached_pid;
778 return 0;
779
780 cleanup_error:
781 /* first shut down the socket, then wait for the pid,
782 * otherwise the pid we're waiting for may never exit
783 */
784 shutdown(ipc_sockets[0], SHUT_RDWR);
785 close(ipc_sockets[0]);
786 if (to_cleanup_pid)
787 (void) wait_for_pid(to_cleanup_pid);
788 lxc_proc_put_context_info(init_ctx);
789 return -1;
790 }
791
792 /* first subprocess begins here, we close the socket that is for the
793 * initial thread
794 */
795 close(ipc_sockets[0]);
796
797 /* attach now, create another subprocess later, since pid namespaces
798 * only really affect the children of the current process
799 */
800 ret = lxc_attach_to_ns(init_pid, options->namespaces);
801 if (ret < 0) {
802 ERROR("failed to enter the namespace");
803 shutdown(ipc_sockets[1], SHUT_RDWR);
804 rexit(-1);
805 }
806
807 /* attach succeeded, try to cwd */
808 if (options->initial_cwd)
809 new_cwd = options->initial_cwd;
810 else
811 new_cwd = cwd;
812 ret = chdir(new_cwd);
813 if (ret < 0)
814 WARN("could not change directory to '%s'", new_cwd);
815 free(cwd);
816
817 /* now create the real child process */
818 {
819 struct attach_clone_payload payload = {
820 .ipc_socket = ipc_sockets[1],
821 .options = options,
822 .init_ctx = init_ctx,
823 .exec_function = exec_function,
824 .exec_payload = exec_payload
825 };
826 /* We use clone_parent here to make this subprocess a direct child of
827 * the initial process. Then this intermediate process can exit and
828 * the parent can directly track the attached process.
829 */
830 pid = lxc_clone(attach_child_main, &payload, CLONE_PARENT);
831 }
832
833 /* shouldn't happen, clone() should always return positive pid */
834 if (pid <= 0) {
835 SYSERROR("failed to create subprocess");
836 shutdown(ipc_sockets[1], SHUT_RDWR);
837 rexit(-1);
838 }
839
840 /* tell grandparent the pid of the pid of the newly created child */
841 ret = lxc_write_nointr(ipc_sockets[1], &pid, sizeof(pid));
842 if (ret != sizeof(pid)) {
843 /* if this really happens here, this is very unfortunate, since the
844 * parent will not know the pid of the attached process and will
845 * not be able to wait for it (and we won't either due to CLONE_PARENT)
846 * so the parent won't be able to reap it and the attached process
847 * will remain a zombie
848 */
849 ERROR("error using IPC to notify main process of pid of the attached process");
850 shutdown(ipc_sockets[1], SHUT_RDWR);
851 rexit(-1);
852 }
853
854 /* the rest is in the hands of the initial and the attached process */
855 rexit(0);
856 }
857
858 int attach_child_main(void* data)
859 {
860 struct attach_clone_payload* payload = (struct attach_clone_payload*)data;
861 int ipc_socket = payload->ipc_socket;
862 lxc_attach_options_t* options = payload->options;
863 struct lxc_proc_context_info* init_ctx = payload->init_ctx;
864 #if HAVE_SYS_PERSONALITY_H
865 long new_personality;
866 #endif
867 int ret;
868 int status;
869 int expected;
870 long flags;
871 int fd;
872 uid_t new_uid;
873 gid_t new_gid;
874
875 /* wait for the initial thread to signal us that it's ready
876 * for us to start initializing
877 */
878 expected = 0;
879 status = -1;
880 ret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected);
881 if (ret <= 0) {
882 ERROR("error using IPC to receive notification from initial process (0)");
883 shutdown(ipc_socket, SHUT_RDWR);
884 rexit(-1);
885 }
886
887 /* A description of the purpose of this functionality is
888 * provided in the lxc-attach(1) manual page. We have to
889 * remount here and not in the parent process, otherwise
890 * /proc may not properly reflect the new pid namespace.
891 */
892 if (!(options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_REMOUNT_PROC_SYS)) {
893 ret = lxc_attach_remount_sys_proc();
894 if (ret < 0) {
895 shutdown(ipc_socket, SHUT_RDWR);
896 rexit(-1);
897 }
898 }
899
900 /* now perform additional attachments*/
901 #if HAVE_SYS_PERSONALITY_H
902 if (options->personality < 0)
903 new_personality = init_ctx->personality;
904 else
905 new_personality = options->personality;
906
907 if (options->attach_flags & LXC_ATTACH_SET_PERSONALITY) {
908 ret = personality(new_personality);
909 if (ret < 0) {
910 SYSERROR("could not ensure correct architecture");
911 shutdown(ipc_socket, SHUT_RDWR);
912 rexit(-1);
913 }
914 }
915 #endif
916
917 if (options->attach_flags & LXC_ATTACH_DROP_CAPABILITIES) {
918 ret = lxc_attach_drop_privs(init_ctx);
919 if (ret < 0) {
920 ERROR("could not drop privileges");
921 shutdown(ipc_socket, SHUT_RDWR);
922 rexit(-1);
923 }
924 }
925
926 /* always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL) if you want this to be a no-op) */
927 ret = lxc_attach_set_environment(options->env_policy, options->extra_env_vars, options->extra_keep_env);
928 if (ret < 0) {
929 ERROR("could not set initial environment for attached process");
930 shutdown(ipc_socket, SHUT_RDWR);
931 rexit(-1);
932 }
933
934 /* set user / group id */
935 new_uid = 0;
936 new_gid = 0;
937 /* ignore errors, we will fall back to root in that case
938 * (/proc was not mounted etc.)
939 */
940 if (options->namespaces & CLONE_NEWUSER)
941 lxc_attach_get_init_uidgid(&new_uid, &new_gid);
942
943 if (options->uid != (uid_t)-1)
944 new_uid = options->uid;
945 if (options->gid != (gid_t)-1)
946 new_gid = options->gid;
947
948 /* try to set the uid/gid combination */
949 if ((new_gid != 0 || options->namespaces & CLONE_NEWUSER) && setgid(new_gid)) {
950 SYSERROR("switching to container gid");
951 shutdown(ipc_socket, SHUT_RDWR);
952 rexit(-1);
953 }
954 if ((new_uid != 0 || options->namespaces & CLONE_NEWUSER) && setuid(new_uid)) {
955 SYSERROR("switching to container uid");
956 shutdown(ipc_socket, SHUT_RDWR);
957 rexit(-1);
958 }
959
960 /* tell initial process it may now put us into the cgroups */
961 status = 1;
962 ret = lxc_write_nointr(ipc_socket, &status, sizeof(status));
963 if (ret != sizeof(status)) {
964 ERROR("error using IPC to notify initial process for initialization (1)");
965 shutdown(ipc_socket, SHUT_RDWR);
966 rexit(-1);
967 }
968
969 /* wait for the initial thread to signal us that it has done
970 * everything for us when it comes to cgroups etc.
971 */
972 expected = 2;
973 status = -1;
974 ret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected);
975 if (ret <= 0) {
976 ERROR("error using IPC to receive final notification from initial process (2)");
977 shutdown(ipc_socket, SHUT_RDWR);
978 rexit(-1);
979 }
980
981 shutdown(ipc_socket, SHUT_RDWR);
982 close(ipc_socket);
983
984 /* set new apparmor profile/selinux context */
985 if ((options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_LSM)) {
986 int on_exec;
987
988 on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? 1 : 0;
989 ret = lsm_process_label_set(init_ctx->lsm_label, 0, on_exec);
990 if (ret < 0) {
991 rexit(-1);
992 }
993 }
994 lxc_proc_put_context_info(init_ctx);
995
996 /* The following is done after the communication socket is
997 * shut down. That way, all errors that might (though
998 * unlikely) occur up until this point will have their messages
999 * printed to the original stderr (if logging is so configured)
1000 * and not the fd the user supplied, if any.
1001 */
1002
1003 /* fd handling for stdin, stdout and stderr;
1004 * ignore errors here, user may want to make sure
1005 * the fds are closed, for example */
1006 if (options->stdin_fd >= 0 && options->stdin_fd != 0)
1007 dup2(options->stdin_fd, 0);
1008 if (options->stdout_fd >= 0 && options->stdout_fd != 1)
1009 dup2(options->stdout_fd, 1);
1010 if (options->stderr_fd >= 0 && options->stderr_fd != 2)
1011 dup2(options->stderr_fd, 2);
1012
1013 /* close the old fds */
1014 if (options->stdin_fd > 2)
1015 close(options->stdin_fd);
1016 if (options->stdout_fd > 2)
1017 close(options->stdout_fd);
1018 if (options->stderr_fd > 2)
1019 close(options->stderr_fd);
1020
1021 /* try to remove CLOEXEC flag from stdin/stdout/stderr,
1022 * but also here, ignore errors */
1023 for (fd = 0; fd <= 2; fd++) {
1024 flags = fcntl(fd, F_GETFL);
1025 if (flags < 0)
1026 continue;
1027 if (flags & FD_CLOEXEC)
1028 fcntl(fd, F_SETFL, flags & ~FD_CLOEXEC);
1029 }
1030
1031 /* we're done, so we can now do whatever the user intended us to do */
1032 rexit(payload->exec_function(payload->exec_payload));
1033 }
1034
1035 int lxc_attach_run_command(void* payload)
1036 {
1037 lxc_attach_command_t* cmd = (lxc_attach_command_t*)payload;
1038
1039 execvp(cmd->program, cmd->argv);
1040 SYSERROR("failed to exec '%s'", cmd->program);
1041 return -1;
1042 }
1043
1044 int lxc_attach_run_shell(void* payload)
1045 {
1046 uid_t uid;
1047 struct passwd *passwd;
1048 char *user_shell;
1049
1050 /* ignore payload parameter */
1051 (void)payload;
1052
1053 uid = getuid();
1054 passwd = getpwuid(uid);
1055
1056 /* this probably happens because of incompatible nss
1057 * implementations in host and container (remember, this
1058 * code is still using the host's glibc but our mount
1059 * namespace is in the container)
1060 * we may try to get the information by spawning a
1061 * [getent passwd uid] process and parsing the result
1062 */
1063 if (!passwd)
1064 user_shell = lxc_attach_getpwshell(uid);
1065 else
1066 user_shell = passwd->pw_shell;
1067
1068 if (user_shell)
1069 execlp(user_shell, user_shell, NULL);
1070
1071 /* executed if either no passwd entry or execvp fails,
1072 * we will fall back on /bin/sh as a default shell
1073 */
1074 execlp("/bin/sh", "/bin/sh", NULL);
1075 SYSERROR("failed to exec shell");
1076 return -1;
1077 }