]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/namespace.c
fix setns parameter
[mirror_lxc.git] / src / lxc / namespace.c
1 /*
2 * lxc: linux Container library
3 *
4 * (C) Copyright IBM Corp. 2007, 2009
5 *
6 * Authors:
7 * Daniel Lezcano <dlezcano at fr.ibm.com>
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 */
23
24 #include <unistd.h>
25 #include <alloca.h>
26 #include <errno.h>
27 #include <signal.h>
28 #include <syscall.h>
29 #include <sys/param.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33
34 #include "namespace.h"
35 #include "log.h"
36
37 #include "setns.h"
38
39 lxc_log_define(lxc_namespace, lxc);
40
41 struct clone_arg {
42 int (*fn)(void *);
43 void *arg;
44 };
45
46 int setns(int fd, int nstype)
47 {
48 #ifndef __NR_setns
49 errno = ENOSYS;
50 return -1;
51 #else
52 return syscall(__NR_setns, fd, nstype);
53 #endif
54 }
55
56 static int do_clone(void *arg)
57 {
58 struct clone_arg *clone_arg = arg;
59 return clone_arg->fn(clone_arg->arg);
60 }
61
62 pid_t lxc_clone(int (*fn)(void *), void *arg, int flags)
63 {
64 struct clone_arg clone_arg = {
65 .fn = fn,
66 .arg = arg,
67 };
68
69 long stack_size = sysconf(_SC_PAGESIZE);
70 void *stack = alloca(stack_size) + stack_size;
71 pid_t ret;
72
73 #ifdef __ia64__
74 ret = __clone2(do_clone, stack,
75 stack_size, flags | SIGCHLD, &clone_arg);
76 #else
77 ret = clone(do_clone, stack, flags | SIGCHLD, &clone_arg);
78 #endif
79 if (ret < 0)
80 ERROR("failed to clone(0x%x): %s", flags, strerror(errno));
81
82 return ret;
83 }
84
85 int lxc_attach(pid_t pid)
86 {
87 char path[MAXPATHLEN];
88 char *ns[] = { "pid", "mnt", "net", "ipc", "uts" };
89 const int size = sizeof(ns) / sizeof(char *);
90 int fd[size];
91 int i;
92
93 sprintf(path, "/proc/%d/ns", pid);
94 if (access(path, X_OK)) {
95 ERROR("Does this kernel version support 'attach' ?");
96 return -1;
97 }
98
99 for (i = 0; i < size; i++) {
100 sprintf(path, "/proc/%d/ns/%s", pid, ns[i]);
101 fd[i] = open(path, O_RDONLY);
102 if (fd[i] < 0) {
103 SYSERROR("failed to open '%s'", path);
104 return -1;
105 }
106 }
107
108 for (i = 0; i < size; i++) {
109 if (setns(fd[i], 0)) {
110 SYSERROR("failed to set namespace '%s'", ns[i]);
111 return -1;
112 }
113
114 close(fd[i]);
115 }
116
117 return 0;
118 }