2 * lxc: linux Container library
4 * (C) Copyright IBM Corp. 2007, 2008
7 * Daniel Lezcano <daniel.lezcano at free.fr>
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.
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.
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
40 #include <arpa/inet.h>
41 #include <linux/loop.h>
43 #include <netinet/in.h>
45 #include <sys/mount.h>
46 #include <sys/param.h>
47 #include <sys/prctl.h>
49 #include <sys/socket.h>
50 #include <sys/sysmacros.h>
51 #include <sys/syscall.h>
52 #include <sys/types.h>
53 #include <sys/utsname.h>
58 # include <sys/mkdev.h>
62 #include <sys/statvfs.h>
68 #include <../include/openpty.h>
71 #ifdef HAVE_LINUX_MEMFD_H
72 #include <linux/memfd.h>
77 #include "caps.h" /* for lxc_caps_last_cap() */
80 #include "confile_utils.h"
85 #include "lxcoverlay.h"
86 #include "lxcseccomp.h"
87 #include "namespace.h"
94 #include <sys/capability.h>
97 #if HAVE_SYS_PERSONALITY_H
98 #include <sys/personality.h>
102 #include <../include/lxcmntent.h>
104 #include <../include/prlimit.h>
110 lxc_log_define(lxc_conf
, lxc
);
114 #define CAP_SETFCAP 31
117 #ifndef CAP_MAC_OVERRIDE
118 #define CAP_MAC_OVERRIDE 32
121 #ifndef CAP_MAC_ADMIN
122 #define CAP_MAC_ADMIN 33
126 #ifndef PR_CAPBSET_DROP
127 #define PR_CAPBSET_DROP 24
130 #ifndef LO_FLAGS_AUTOCLEAR
131 #define LO_FLAGS_AUTOCLEAR 4
142 /* needed for cgroup automount checks, regardless of whether we
143 * have included linux/capability.h or not */
144 #ifndef CAP_SYS_ADMIN
145 #define CAP_SYS_ADMIN 21
148 /* Define pivot_root() if missing from the C library */
149 #ifndef HAVE_PIVOT_ROOT
150 static int pivot_root(const char * new_root
, const char * put_old
)
152 #ifdef __NR_pivot_root
153 return syscall(__NR_pivot_root
, new_root
, put_old
);
160 extern int pivot_root(const char * new_root
, const char * put_old
);
163 /* Define sethostname() if missing from the C library */
164 #ifndef HAVE_SETHOSTNAME
165 static int sethostname(const char * name
, size_t len
)
167 #ifdef __NR_sethostname
168 return syscall(__NR_sethostname
, name
, len
);
177 #define MS_PRIVATE (1<<18)
181 #define MS_LAZYTIME (1<<25)
186 #define MFD_CLOEXEC 0x0001U
189 #ifndef MFD_ALLOW_SEALING
190 #define MFD_ALLOW_SEALING 0x0002U
193 #ifndef HAVE_MEMFD_CREATE
194 static int memfd_create(const char *name
, unsigned int flags
) {
195 #ifndef __NR_memfd_create
197 #define __NR_memfd_create 356
198 #elif defined __x86_64__
199 #define __NR_memfd_create 319
200 #elif defined __arm__
201 #define __NR_memfd_create 385
202 #elif defined __aarch64__
203 #define __NR_memfd_create 279
204 #elif defined __s390__
205 #define __NR_memfd_create 350
206 #elif defined __powerpc__
207 #define __NR_memfd_create 360
208 #elif defined __sparc__
209 #define __NR_memfd_create 348
210 #elif defined __blackfin__
211 #define __NR_memfd_create 390
212 #elif defined __ia64__
213 #define __NR_memfd_create 1340
214 #elif defined _MIPS_SIM
215 #if _MIPS_SIM == _MIPS_SIM_ABI32
216 #define __NR_memfd_create 4354
218 #if _MIPS_SIM == _MIPS_SIM_NABI32
219 #define __NR_memfd_create 6318
221 #if _MIPS_SIM == _MIPS_SIM_ABI64
222 #define __NR_memfd_create 5314
226 #ifdef __NR_memfd_create
227 return syscall(__NR_memfd_create
, name
, flags
);
234 extern int memfd_create(const char *name
, unsigned int flags
);
237 char *lxchook_names
[NUM_LXC_HOOKS
] = {
238 "pre-start", "pre-mount", "mount", "autodev", "start", "stop", "post-stop", "clone", "destroy" };
240 typedef int (*instantiate_cb
)(struct lxc_handler
*, struct lxc_netdev
*);
259 * The lxc_conf of the container currently being worked on in an
261 * This is used in the error calls
264 __thread
struct lxc_conf
*current_config
;
266 struct lxc_conf
*current_config
;
269 /* Declare this here, since we don't want to reshuffle the whole file. */
270 static int in_caplist(int cap
, struct lxc_list
*caps
);
272 static int instantiate_veth(struct lxc_handler
*, struct lxc_netdev
*);
273 static int instantiate_macvlan(struct lxc_handler
*, struct lxc_netdev
*);
274 static int instantiate_vlan(struct lxc_handler
*, struct lxc_netdev
*);
275 static int instantiate_phys(struct lxc_handler
*, struct lxc_netdev
*);
276 static int instantiate_empty(struct lxc_handler
*, struct lxc_netdev
*);
277 static int instantiate_none(struct lxc_handler
*, struct lxc_netdev
*);
279 static instantiate_cb netdev_conf
[LXC_NET_MAXCONFTYPE
+ 1] = {
280 [LXC_NET_VETH
] = instantiate_veth
,
281 [LXC_NET_MACVLAN
] = instantiate_macvlan
,
282 [LXC_NET_VLAN
] = instantiate_vlan
,
283 [LXC_NET_PHYS
] = instantiate_phys
,
284 [LXC_NET_EMPTY
] = instantiate_empty
,
285 [LXC_NET_NONE
] = instantiate_none
,
288 static int shutdown_veth(struct lxc_handler
*, struct lxc_netdev
*);
289 static int shutdown_macvlan(struct lxc_handler
*, struct lxc_netdev
*);
290 static int shutdown_vlan(struct lxc_handler
*, struct lxc_netdev
*);
291 static int shutdown_phys(struct lxc_handler
*, struct lxc_netdev
*);
292 static int shutdown_empty(struct lxc_handler
*, struct lxc_netdev
*);
293 static int shutdown_none(struct lxc_handler
*, struct lxc_netdev
*);
295 static instantiate_cb netdev_deconf
[LXC_NET_MAXCONFTYPE
+ 1] = {
296 [LXC_NET_VETH
] = shutdown_veth
,
297 [LXC_NET_MACVLAN
] = shutdown_macvlan
,
298 [LXC_NET_VLAN
] = shutdown_vlan
,
299 [LXC_NET_PHYS
] = shutdown_phys
,
300 [LXC_NET_EMPTY
] = shutdown_empty
,
301 [LXC_NET_NONE
] = shutdown_none
,
304 static struct mount_opt mount_opt
[] = {
305 { "async", 1, MS_SYNCHRONOUS
},
306 { "atime", 1, MS_NOATIME
},
307 { "bind", 0, MS_BIND
},
308 { "defaults", 0, 0 },
309 { "dev", 1, MS_NODEV
},
310 { "diratime", 1, MS_NODIRATIME
},
311 { "dirsync", 0, MS_DIRSYNC
},
312 { "exec", 1, MS_NOEXEC
},
313 { "lazytime", 0, MS_LAZYTIME
},
314 { "mand", 0, MS_MANDLOCK
},
315 { "noatime", 0, MS_NOATIME
},
316 { "nodev", 0, MS_NODEV
},
317 { "nodiratime", 0, MS_NODIRATIME
},
318 { "noexec", 0, MS_NOEXEC
},
319 { "nomand", 1, MS_MANDLOCK
},
320 { "norelatime", 1, MS_RELATIME
},
321 { "nostrictatime", 1, MS_STRICTATIME
},
322 { "nosuid", 0, MS_NOSUID
},
323 { "rbind", 0, MS_BIND
|MS_REC
},
324 { "relatime", 0, MS_RELATIME
},
325 { "remount", 0, MS_REMOUNT
},
326 { "ro", 0, MS_RDONLY
},
327 { "rw", 1, MS_RDONLY
},
328 { "strictatime", 0, MS_STRICTATIME
},
329 { "suid", 1, MS_NOSUID
},
330 { "sync", 0, MS_SYNCHRONOUS
},
335 static struct caps_opt caps_opt
[] = {
336 { "chown", CAP_CHOWN
},
337 { "dac_override", CAP_DAC_OVERRIDE
},
338 { "dac_read_search", CAP_DAC_READ_SEARCH
},
339 { "fowner", CAP_FOWNER
},
340 { "fsetid", CAP_FSETID
},
341 { "kill", CAP_KILL
},
342 { "setgid", CAP_SETGID
},
343 { "setuid", CAP_SETUID
},
344 { "setpcap", CAP_SETPCAP
},
345 { "linux_immutable", CAP_LINUX_IMMUTABLE
},
346 { "net_bind_service", CAP_NET_BIND_SERVICE
},
347 { "net_broadcast", CAP_NET_BROADCAST
},
348 { "net_admin", CAP_NET_ADMIN
},
349 { "net_raw", CAP_NET_RAW
},
350 { "ipc_lock", CAP_IPC_LOCK
},
351 { "ipc_owner", CAP_IPC_OWNER
},
352 { "sys_module", CAP_SYS_MODULE
},
353 { "sys_rawio", CAP_SYS_RAWIO
},
354 { "sys_chroot", CAP_SYS_CHROOT
},
355 { "sys_ptrace", CAP_SYS_PTRACE
},
356 { "sys_pacct", CAP_SYS_PACCT
},
357 { "sys_admin", CAP_SYS_ADMIN
},
358 { "sys_boot", CAP_SYS_BOOT
},
359 { "sys_nice", CAP_SYS_NICE
},
360 { "sys_resource", CAP_SYS_RESOURCE
},
361 { "sys_time", CAP_SYS_TIME
},
362 { "sys_tty_config", CAP_SYS_TTY_CONFIG
},
363 { "mknod", CAP_MKNOD
},
364 { "lease", CAP_LEASE
},
365 #ifdef CAP_AUDIT_READ
366 { "audit_read", CAP_AUDIT_READ
},
368 #ifdef CAP_AUDIT_WRITE
369 { "audit_write", CAP_AUDIT_WRITE
},
371 #ifdef CAP_AUDIT_CONTROL
372 { "audit_control", CAP_AUDIT_CONTROL
},
374 { "setfcap", CAP_SETFCAP
},
375 { "mac_override", CAP_MAC_OVERRIDE
},
376 { "mac_admin", CAP_MAC_ADMIN
},
378 { "syslog", CAP_SYSLOG
},
380 #ifdef CAP_WAKE_ALARM
381 { "wake_alarm", CAP_WAKE_ALARM
},
383 #ifdef CAP_BLOCK_SUSPEND
384 { "block_suspend", CAP_BLOCK_SUSPEND
},
388 static struct caps_opt caps_opt
[] = {};
391 static struct limit_opt limit_opt
[] = {
396 { "core", RLIMIT_CORE
},
399 { "cpu", RLIMIT_CPU
},
402 { "data", RLIMIT_DATA
},
405 { "fsize", RLIMIT_FSIZE
},
408 { "locks", RLIMIT_LOCKS
},
410 #ifdef RLIMIT_MEMLOCK
411 { "memlock", RLIMIT_MEMLOCK
},
413 #ifdef RLIMIT_MSGQUEUE
414 { "msgqueue", RLIMIT_MSGQUEUE
},
417 { "nice", RLIMIT_NICE
},
420 { "nofile", RLIMIT_NOFILE
},
423 { "nproc", RLIMIT_NPROC
},
426 { "rss", RLIMIT_RSS
},
429 { "rtprio", RLIMIT_RTPRIO
},
432 { "rttime", RLIMIT_RTTIME
},
434 #ifdef RLIMIT_SIGPENDING
435 { "sigpending", RLIMIT_SIGPENDING
},
438 { "stack", RLIMIT_STACK
},
442 static int run_buffer(char *buffer
)
444 struct lxc_popen_FILE
*f
;
448 f
= lxc_popen(buffer
);
450 SYSERROR("Failed to popen() %s.", buffer
);
454 output
= malloc(LXC_LOG_BUFFER_SIZE
);
456 ERROR("Failed to allocate memory for %s.", buffer
);
461 while (fgets(output
, LXC_LOG_BUFFER_SIZE
, f
->f
))
462 DEBUG("Script %s with output: %s.", buffer
, output
);
468 SYSERROR("Script exited with error.");
470 } else if (WIFEXITED(ret
) && WEXITSTATUS(ret
) != 0) {
471 ERROR("Script exited with status %d.", WEXITSTATUS(ret
));
473 } else if (WIFSIGNALED(ret
)) {
474 ERROR("Script terminated by signal %d.", WTERMSIG(ret
));
481 static int run_script_argv(const char *name
, const char *section
,
482 const char *script
, const char *hook
,
483 const char *lxcpath
, char **argsin
)
489 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\".",
490 script
, name
, section
);
492 for (i
= 0; argsin
&& argsin
[i
]; i
++)
493 size
+= strlen(argsin
[i
]) + 1;
495 size
+= strlen(hook
) + 1;
497 size
+= strlen(script
);
498 size
+= strlen(name
);
499 size
+= strlen(section
);
505 buffer
= alloca(size
);
507 ERROR("Failed to allocate memory.");
512 snprintf(buffer
, size
, "%s %s %s %s", script
, name
, section
, hook
);
513 if (ret
< 0 || (size_t)ret
>= size
) {
514 ERROR("Script name too long.");
518 for (i
= 0; argsin
&& argsin
[i
]; i
++) {
519 int len
= size
- ret
;
521 rc
= snprintf(buffer
+ ret
, len
, " %s", argsin
[i
]);
522 if (rc
< 0 || rc
>= len
) {
523 ERROR("Script args too long.");
529 return run_buffer(buffer
);
532 static int run_script(const char *name
, const char *section
, const char *script
,
540 INFO("Executing script \"%s\" for container \"%s\", config section \"%s\".",
541 script
, name
, section
);
543 va_start(ap
, script
);
544 while ((p
= va_arg(ap
, char *)))
545 size
+= strlen(p
) + 1;
548 size
+= strlen(script
);
549 size
+= strlen(name
);
550 size
+= strlen(section
);
556 buffer
= alloca(size
);
558 ERROR("Failed to allocate memory.");
562 ret
= snprintf(buffer
, size
, "%s %s %s", script
, name
, section
);
563 if (ret
< 0 || ret
>= size
) {
564 ERROR("Script name too long.");
568 va_start(ap
, script
);
569 while ((p
= va_arg(ap
, char *))) {
570 int len
= size
- ret
;
572 rc
= snprintf(buffer
+ ret
, len
, " %s", p
);
573 if (rc
< 0 || rc
>= len
) {
574 ERROR("Script args too long.");
581 return run_buffer(buffer
);
586 * if rootfs is a directory, then open ${rootfs}/lxc.hold for writing for
587 * the duration of the container run, to prevent the container from marking
588 * the underlying fs readonly on shutdown. unlink the file immediately so
589 * no name pollution is happens
590 * return -1 on error.
591 * return -2 if nothing needed to be pinned.
592 * return an open fd (>=0) if we pinned it.
594 int pin_rootfs(const char *rootfs
)
596 char absrootfs
[MAXPATHLEN
];
597 char absrootfspin
[MAXPATHLEN
];
601 if (rootfs
== NULL
|| strlen(rootfs
) == 0)
604 if (!realpath(rootfs
, absrootfs
))
607 if (access(absrootfs
, F_OK
))
610 if (stat(absrootfs
, &s
))
613 if (!S_ISDIR(s
.st_mode
))
616 ret
= snprintf(absrootfspin
, MAXPATHLEN
, "%s/lxc.hold", absrootfs
);
617 if (ret
>= MAXPATHLEN
)
620 fd
= open(absrootfspin
, O_CREAT
| O_RDWR
, S_IWUSR
|S_IRUSR
);
623 (void)unlink(absrootfspin
);
628 * If we are asking to remount something, make sure that any
629 * NOEXEC etc are honored.
631 static unsigned long add_required_remount_flags(const char *s
, const char *d
,
636 unsigned long required_flags
= 0;
638 if (!(flags
& MS_REMOUNT
))
646 if (statvfs(s
, &sb
) < 0)
649 if (sb
.f_flag
& MS_NOSUID
)
650 required_flags
|= MS_NOSUID
;
651 if (sb
.f_flag
& MS_NODEV
)
652 required_flags
|= MS_NODEV
;
653 if (sb
.f_flag
& MS_RDONLY
)
654 required_flags
|= MS_RDONLY
;
655 if (sb
.f_flag
& MS_NOEXEC
)
656 required_flags
|= MS_NOEXEC
;
658 return flags
| required_flags
;
664 static int lxc_mount_auto_mounts(struct lxc_conf
*conf
, int flags
, struct lxc_handler
*handler
)
672 const char *destination
;
676 } default_mounts
[] = {
677 /* Read-only bind-mounting... In older kernels, doing that required
678 * to do one MS_BIND mount and then MS_REMOUNT|MS_RDONLY the same
679 * one. According to mount(2) manpage, MS_BIND honors MS_RDONLY from
680 * kernel 2.6.26 onwards. However, this apparently does not work on
681 * kernel 3.8. Unfortunately, on that very same kernel, doing the
682 * same trick as above doesn't seem to work either, there one needs
683 * to ALSO specify MS_BIND for the remount, otherwise the entire
684 * fs is remounted read-only or the mount fails because it's busy...
685 * MS_REMOUNT|MS_BIND|MS_RDONLY seems to work for kernels as low as
688 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
689 /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */
690 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys/net", "%r/proc/tty", NULL
, MS_BIND
, NULL
},
691 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sys", "%r/proc/sys", NULL
, MS_BIND
, NULL
},
692 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
693 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/tty", "%r/proc/sys/net", NULL
, MS_MOVE
, NULL
},
694 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, "%r/proc/sysrq-trigger", "%r/proc/sysrq-trigger", NULL
, MS_BIND
, NULL
},
695 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_MIXED
, NULL
, "%r/proc/sysrq-trigger", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
696 { LXC_AUTO_PROC_MASK
, LXC_AUTO_PROC_RW
, "proc", "%r/proc", "proc", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
697 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RW
, "sysfs", "%r/sys", "sysfs", 0, NULL
},
698 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_RO
, "sysfs", "%r/sys", "sysfs", MS_RDONLY
, NULL
},
699 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys", "sysfs", MS_NODEV
|MS_NOEXEC
|MS_NOSUID
, NULL
},
700 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/sys", "%r/sys", NULL
, MS_BIND
, NULL
},
701 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys", NULL
, MS_REMOUNT
|MS_BIND
|MS_RDONLY
, NULL
},
702 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "sysfs", "%r/sys/devices/virtual/net", "sysfs", 0, NULL
},
703 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, "%r/sys/devices/virtual/net/devices/virtual/net", "%r/sys/devices/virtual/net", NULL
, MS_BIND
, NULL
},
704 { LXC_AUTO_SYS_MASK
, LXC_AUTO_SYS_MIXED
, NULL
, "%r/sys/devices/virtual/net", NULL
, MS_REMOUNT
|MS_BIND
|MS_NOSUID
|MS_NODEV
|MS_NOEXEC
, NULL
},
705 { 0, 0, NULL
, NULL
, NULL
, 0, NULL
}
708 for (i
= 0; default_mounts
[i
].match_mask
; i
++) {
709 if ((flags
& default_mounts
[i
].match_mask
) == default_mounts
[i
].match_flag
) {
711 char *destination
= NULL
;
713 unsigned long mflags
;
715 if (default_mounts
[i
].source
) {
716 /* will act like strdup if %r is not present */
717 source
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].source
);
719 SYSERROR("memory allocation error");
723 if (!default_mounts
[i
].destination
) {
724 ERROR("BUG: auto mounts destination %d was NULL", i
);
728 /* will act like strdup if %r is not present */
729 destination
= lxc_string_replace("%r", conf
->rootfs
.path
? conf
->rootfs
.mount
: "", default_mounts
[i
].destination
);
732 SYSERROR("memory allocation error");
737 mflags
= add_required_remount_flags(source
, destination
,
738 default_mounts
[i
].flags
);
739 r
= safe_mount(source
, destination
, default_mounts
[i
].fstype
, mflags
, default_mounts
[i
].options
, conf
->rootfs
.path
? conf
->rootfs
.mount
: NULL
);
741 if (r
< 0 && errno
== ENOENT
) {
742 INFO("Mount source or target for %s on %s doesn't exist. Skipping.", source
, destination
);
746 SYSERROR("error mounting %s on %s flags %lu", source
, destination
, mflags
);
757 if (flags
& LXC_AUTO_CGROUP_MASK
) {
760 cg_flags
= flags
& LXC_AUTO_CGROUP_MASK
;
761 /* If the type of cgroup mount was not specified, it depends on the
762 * container's capabilities as to what makes sense: if we have
763 * CAP_SYS_ADMIN, the read-only part can be remounted read-write
764 * anyway, so we may as well default to read-write; then the admin
765 * will not be given a false sense of security. (And if they really
766 * want mixed r/o r/w, then they can explicitly specify :mixed.)
767 * OTOH, if the container lacks CAP_SYS_ADMIN, do only default to
768 * :mixed, because then the container can't remount it read-write. */
769 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
|| cg_flags
== LXC_AUTO_CGROUP_FULL_NOSPEC
) {
770 int has_sys_admin
= 0;
772 if (!lxc_list_empty(&conf
->keepcaps
))
773 has_sys_admin
= in_caplist(CAP_SYS_ADMIN
, &conf
->keepcaps
);
775 has_sys_admin
= !in_caplist(CAP_SYS_ADMIN
, &conf
->caps
);
777 if (cg_flags
== LXC_AUTO_CGROUP_NOSPEC
)
778 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_RW
: LXC_AUTO_CGROUP_MIXED
;
780 cg_flags
= has_sys_admin
? LXC_AUTO_CGROUP_FULL_RW
: LXC_AUTO_CGROUP_FULL_MIXED
;
783 if (!cgroup_mount(conf
->rootfs
.path
? conf
->rootfs
.mount
: "", handler
, cg_flags
)) {
784 SYSERROR("error mounting /sys/fs/cgroup");
792 static int setup_utsname(struct utsname
*utsname
)
797 if (sethostname(utsname
->nodename
, strlen(utsname
->nodename
))) {
798 SYSERROR("failed to set the hostname to '%s'", utsname
->nodename
);
802 INFO("'%s' hostname has been setup", utsname
->nodename
);
807 struct dev_symlinks
{
812 static const struct dev_symlinks dev_symlinks
[] = {
813 {"/proc/self/fd", "fd"},
814 {"/proc/self/fd/0", "stdin"},
815 {"/proc/self/fd/1", "stdout"},
816 {"/proc/self/fd/2", "stderr"},
819 static int setup_dev_symlinks(const struct lxc_rootfs
*rootfs
)
821 char path
[MAXPATHLEN
];
826 for (i
= 0; i
< sizeof(dev_symlinks
) / sizeof(dev_symlinks
[0]); i
++) {
827 const struct dev_symlinks
*d
= &dev_symlinks
[i
];
828 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs
->path
? rootfs
->mount
: "", d
->name
);
829 if (ret
< 0 || ret
>= MAXPATHLEN
)
833 * Stat the path first. If we don't get an error
834 * accept it as is and don't try to create it
836 if (!stat(path
, &s
)) {
840 ret
= symlink(d
->oldpath
, path
);
842 if (ret
&& errno
!= EEXIST
) {
843 if ( errno
== EROFS
) {
844 WARN("Warning: Read Only file system while creating %s", path
);
846 SYSERROR("Error creating %s", path
);
855 * Build a space-separate list of ptys to pass to systemd.
857 static bool append_ptyname(char **pp
, char *name
)
862 *pp
= malloc(strlen(name
) + strlen("container_ttys=") + 1);
865 sprintf(*pp
, "container_ttys=%s", name
);
868 p
= realloc(*pp
, strlen(*pp
) + strlen(name
) + 2);
877 static int lxc_setup_tty(struct lxc_conf
*conf
)
880 const struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
881 char *ttydir
= conf
->ttydir
;
882 char path
[MAXPATHLEN
], lxcpath
[MAXPATHLEN
];
884 if (!conf
->rootfs
.path
)
887 for (i
= 0; i
< tty_info
->nbtty
; i
++) {
888 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
890 ret
= snprintf(path
, sizeof(path
), "/dev/tty%d", i
+ 1);
891 if (ret
< 0 || (size_t)ret
>= sizeof(path
)) {
892 ERROR("pathname too long for ttys");
897 /* create dev/lxc/tty%d" */
898 ret
= snprintf(lxcpath
, sizeof(lxcpath
),
899 "/dev/%s/tty%d", ttydir
, i
+ 1);
900 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
)) {
901 ERROR("pathname too long for ttys");
905 ret
= creat(lxcpath
, 0660);
906 if (ret
< 0 && errno
!= EEXIST
) {
907 SYSERROR("failed to create \"%s\"", lxcpath
);
914 if (ret
< 0 && errno
!= ENOENT
) {
915 SYSERROR("failed to unlink \"%s\"", path
);
919 ret
= mount(pty_info
->name
, lxcpath
, "none", MS_BIND
, 0);
921 WARN("failed to bind mount \"%s\" onto \"%s\"",
922 pty_info
->name
, path
);
925 DEBUG("bind mounted \"%s\" onto \"%s\"", pty_info
->name
,
928 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/tty%d",
930 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
)) {
931 ERROR("tty pathname too long");
935 ret
= symlink(lxcpath
, path
);
937 SYSERROR("failed to create symlink \"%s\" -> \"%s\"",
942 /* If we populated /dev, then we need to create
945 ret
= access(path
, F_OK
);
947 ret
= creat(path
, 0660);
949 SYSERROR("failed to create \"%s\"", path
);
950 /* this isn't fatal, continue */
956 ret
= mount(pty_info
->name
, path
, "none", MS_BIND
, 0);
958 SYSERROR("failed to mount '%s'->'%s'", pty_info
->name
, path
);
962 DEBUG("bind mounted \"%s\" onto \"%s\"", pty_info
->name
,
966 if (!append_ptyname(&conf
->pty_names
, pty_info
->name
)) {
967 ERROR("Error setting up container_ttys string");
972 INFO("finished setting up %d /dev/tty<N> device(s)", tty_info
->nbtty
);
976 static int setup_rootfs_pivot_root(const char *rootfs
)
978 int oldroot
= -1, newroot
= -1;
980 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
982 SYSERROR("Error opening old-/ for fchdir");
985 newroot
= open(rootfs
, O_DIRECTORY
| O_RDONLY
);
987 SYSERROR("Error opening new-/ for fchdir");
991 /* change into new root fs */
992 if (fchdir(newroot
)) {
993 SYSERROR("can't chdir to new rootfs '%s'", rootfs
);
997 /* pivot_root into our new root fs */
998 if (pivot_root(".", ".")) {
999 SYSERROR("pivot_root syscall failed");
1004 * at this point the old-root is mounted on top of our new-root
1005 * To unmounted it we must not be chdir'd into it, so escape back
1008 if (fchdir(oldroot
) < 0) {
1009 SYSERROR("Error entering oldroot");
1012 if (umount2(".", MNT_DETACH
) < 0) {
1013 SYSERROR("Error detaching old root");
1017 if (fchdir(newroot
) < 0) {
1018 SYSERROR("Error re-entering newroot");
1025 DEBUG("pivot_root syscall to '%s' successful", rootfs
);
1038 * Just create a path for /dev under $lxcpath/$name and in rootfs
1039 * If we hit an error, log it but don't fail yet.
1041 static int mount_autodev(const char *name
, const struct lxc_rootfs
*rootfs
, const char *lxcpath
)
1047 INFO("Mounting container /dev");
1049 /* $(rootfs->mount) + "/dev/pts" + '\0' */
1050 clen
= (rootfs
->path
? strlen(rootfs
->mount
) : 0) + 9;
1051 path
= alloca(clen
);
1053 ret
= snprintf(path
, clen
, "%s/dev", rootfs
->path
? rootfs
->mount
: "");
1054 if (ret
< 0 || ret
>= clen
)
1057 if (!dir_exists(path
)) {
1058 WARN("No /dev in container.");
1059 WARN("Proceeding without autodev setup");
1063 ret
= safe_mount("none", path
, "tmpfs", 0, "size=500000,mode=755",
1064 rootfs
->path
? rootfs
->mount
: NULL
);
1066 SYSERROR("Failed mounting tmpfs onto %s\n", path
);
1070 INFO("Mounted tmpfs onto %s", path
);
1072 ret
= snprintf(path
, clen
, "%s/dev/pts", rootfs
->path
? rootfs
->mount
: "");
1073 if (ret
< 0 || ret
>= clen
)
1077 * If we are running on a devtmpfs mapping, dev/pts may already exist.
1078 * If not, then create it and exit if that fails...
1080 if (!dir_exists(path
)) {
1081 ret
= mkdir(path
, S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
1083 SYSERROR("Failed to create /dev/pts in container");
1088 INFO("Mounted container /dev");
1099 static const struct lxc_devs lxc_devs
[] = {
1100 { "null", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 3 },
1101 { "zero", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 5 },
1102 { "full", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 7 },
1103 { "urandom", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 9 },
1104 { "random", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 1, 8 },
1105 { "tty", S_IFCHR
| S_IRWXU
| S_IRWXG
| S_IRWXO
, 5, 0 },
1108 static int lxc_fill_autodev(const struct lxc_rootfs
*rootfs
)
1111 char path
[MAXPATHLEN
];
1115 ret
= snprintf(path
, MAXPATHLEN
, "%s/dev", rootfs
->path
? rootfs
->mount
: "");
1116 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1117 ERROR("Error calculating container /dev location");
1121 /* ignore, just don't try to fill in */
1122 if (!dir_exists(path
))
1125 INFO("populating container /dev");
1126 cmask
= umask(S_IXUSR
| S_IXGRP
| S_IXOTH
);
1127 for (i
= 0; i
< sizeof(lxc_devs
) / sizeof(lxc_devs
[0]); i
++) {
1128 const struct lxc_devs
*d
= &lxc_devs
[i
];
1130 ret
= snprintf(path
, MAXPATHLEN
, "%s/dev/%s", rootfs
->path
? rootfs
->mount
: "", d
->name
);
1131 if (ret
< 0 || ret
>= MAXPATHLEN
)
1134 ret
= mknod(path
, d
->mode
, makedev(d
->maj
, d
->min
));
1136 char hostpath
[MAXPATHLEN
];
1139 if (errno
== EEXIST
) {
1140 DEBUG("\"%s\" device already existed", path
);
1144 /* Unprivileged containers cannot create devices, so
1145 * bind mount the device from the host.
1147 ret
= snprintf(hostpath
, MAXPATHLEN
, "/dev/%s", d
->name
);
1148 if (ret
< 0 || ret
>= MAXPATHLEN
)
1150 pathfile
= fopen(path
, "wb");
1152 SYSERROR("Failed to create device mount target '%s'", path
);
1156 if (safe_mount(hostpath
, path
, 0, MS_BIND
, NULL
, rootfs
->path
? rootfs
->mount
: NULL
) != 0) {
1157 SYSERROR("Failed bind mounting device %s from host into container", d
->name
);
1160 DEBUG("bind mounted \"%s\" onto \"%s\"", hostpath
, path
);
1162 DEBUG("created device node \"%s\"", path
);
1167 INFO("populated container /dev");
1171 static int lxc_setup_rootfs(struct lxc_conf
*conf
)
1175 const struct lxc_rootfs
*rootfs
;
1177 rootfs
= &conf
->rootfs
;
1178 if (!rootfs
->path
) {
1179 if (mount("", "/", NULL
, MS_SLAVE
| MS_REC
, 0)) {
1180 SYSERROR("Failed to make / rslave.");
1186 if (access(rootfs
->mount
, F_OK
)) {
1187 SYSERROR("Failed to access to \"%s\". Check it is present.",
1192 bdev
= bdev_init(conf
, rootfs
->path
, rootfs
->mount
, rootfs
->options
);
1194 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\".",
1195 rootfs
->path
, rootfs
->mount
,
1196 rootfs
->options
? rootfs
->options
: "(null)");
1200 ret
= bdev
->ops
->mount(bdev
);
1203 ERROR("Failed to mount rootfs \"%s\" onto \"%s\" with options \"%s\".",
1204 rootfs
->path
, rootfs
->mount
,
1205 rootfs
->options
? rootfs
->options
: "(null)");
1209 DEBUG("Mounted rootfs \"%s\" onto \"%s\" with options \"%s\".",
1210 rootfs
->path
, rootfs
->mount
,
1211 rootfs
->options
? rootfs
->options
: "(null)");
1216 int prepare_ramfs_root(char *root
)
1218 char buf
[LXC_LINELEN
], *p
;
1219 char nroot
[PATH_MAX
];
1224 if (realpath(root
, nroot
) == NULL
)
1227 if (chdir("/") == -1)
1231 * We could use here MS_MOVE, but in userns this mount is
1232 * locked and can't be moved.
1234 if (mount(root
, "/", NULL
, MS_REC
| MS_BIND
, NULL
) < 0) {
1235 SYSERROR("Failed to move %s into /", root
);
1239 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, NULL
) < 0) {
1240 SYSERROR("Failed to make . rprivate");
1245 * The following code cleans up inhereted mounts which are not
1248 * The mountinfo file shows not all mounts, if a few points have been
1249 * unmounted between read operations from the mountinfo. So we need to
1250 * read mountinfo a few times.
1252 * This loop can be skipped if a container uses unserns, because all
1253 * inherited mounts are locked and we should live with all this trash.
1258 f
= fopen("./proc/self/mountinfo", "r");
1260 SYSERROR("Unable to open /proc/self/mountinfo");
1263 while (fgets(buf
, LXC_LINELEN
, f
)) {
1264 for (p
= buf
, i
=0; p
&& i
< 4; i
++)
1265 p
= strchr(p
+1, ' ');
1268 p2
= strchr(p
+1, ' ');
1275 if (strcmp(p
+ 1, "/") == 0)
1277 if (strcmp(p
+ 1, "/proc") == 0)
1280 if (umount2(p
, MNT_DETACH
) == 0)
1288 /* This also can be skipped if a container uses unserns */
1289 umount2("./proc", MNT_DETACH
);
1291 /* It is weird, but chdir("..") moves us in a new root */
1292 if (chdir("..") == -1) {
1293 SYSERROR("Unable to change working directory");
1297 if (chroot(".") == -1) {
1298 SYSERROR("Unable to chroot");
1305 static int setup_pivot_root(const struct lxc_rootfs
*rootfs
)
1307 if (!rootfs
->path
) {
1308 DEBUG("container does not have a rootfs, so not doing pivot root");
1312 if (detect_ramfs_rootfs()) {
1313 DEBUG("detected that container is on ramfs");
1314 if (prepare_ramfs_root(rootfs
->mount
)) {
1315 ERROR("failed to prepare minimal ramfs root");
1319 DEBUG("prepared ramfs root for container");
1323 if (setup_rootfs_pivot_root(rootfs
->mount
) < 0) {
1324 ERROR("failed to pivot root");
1328 DEBUG("finished pivot root");
1332 static int lxc_setup_devpts(int num_pts
)
1335 const char *devpts_mntopts
= "newinstance,ptmxmode=0666,mode=0620,gid=5";
1338 DEBUG("no new devpts instance will be mounted since no pts "
1339 "devices are requested");
1343 /* Unmount old devpts instance. */
1344 ret
= access("/dev/pts/ptmx", F_OK
);
1346 ret
= umount("/dev/pts");
1348 SYSERROR("failed to unmount old devpts instance");
1351 DEBUG("unmounted old /dev/pts instance");
1354 /* Create mountpoint for devpts instance. */
1355 ret
= mkdir("/dev/pts", 0755);
1356 if (ret
< 0 && errno
!= EEXIST
) {
1357 SYSERROR("failed to create the \"/dev/pts\" directory");
1361 /* Mount new devpts instance. */
1362 ret
= mount("devpts", "/dev/pts", "devpts", MS_MGC_VAL
, devpts_mntopts
);
1364 SYSERROR("failed to mount new devpts instance");
1367 DEBUG("mount new devpts instance with options \"%s\"", devpts_mntopts
);
1369 /* Remove any pre-existing /dev/ptmx file. */
1370 ret
= access("/dev/ptmx", F_OK
);
1372 ret
= remove("/dev/ptmx");
1374 SYSERROR("failed to remove existing \"/dev/ptmx\"");
1377 DEBUG("removed existing \"/dev/ptmx\"");
1380 /* Create dummy /dev/ptmx file as bind mountpoint for /dev/pts/ptmx. */
1381 ret
= open("/dev/ptmx", O_CREAT
, 0666);
1383 SYSERROR("failed to create dummy \"/dev/ptmx\" file as bind mount target");
1387 DEBUG("created dummy \"/dev/ptmx\" file as bind mount target");
1389 /* Fallback option: create symlink /dev/ptmx -> /dev/pts/ptmx */
1390 ret
= mount("/dev/pts/ptmx", "/dev/ptmx", NULL
, MS_BIND
, NULL
);
1392 DEBUG("bind mounted \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1395 /* Fallthrough and try to create a symlink. */
1396 ERROR("failed to bind mount \"/dev/pts/ptmx\" to \"/dev/ptmx\"");
1399 /* Remove the dummy /dev/ptmx file we created above. */
1400 ret
= remove("/dev/ptmx");
1402 SYSERROR("failed to remove existing \"/dev/ptmx\"");
1406 /* Fallback option: Create symlink /dev/ptmx -> /dev/pts/ptmx. */
1407 ret
= symlink("/dev/pts/ptmx", "/dev/ptmx");
1409 SYSERROR("failed to create symlink \"/dev/ptmx\" -> \"/dev/pts/ptmx\"");
1412 DEBUG("created symlink \"/dev/ptmx\" -> \"/dev/pts/ptmx\"");
1417 static int setup_personality(int persona
)
1419 #if HAVE_SYS_PERSONALITY_H
1423 if (personality(persona
) < 0) {
1424 SYSERROR("failed to set personality to '0x%x'", persona
);
1428 INFO("set personality to '0x%x'", persona
);
1434 static int lxc_setup_dev_console(const struct lxc_rootfs
*rootfs
,
1435 const struct lxc_console
*console
)
1437 char path
[MAXPATHLEN
];
1440 if (console
->path
&& !strcmp(console
->path
, "none"))
1443 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs
->mount
);
1444 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1447 /* When we are asked to setup a console we remove any previous
1448 * /dev/console bind-mounts.
1450 if (file_exists(path
)) {
1451 ret
= lxc_unstack_mountpoint(path
, false);
1453 ERROR("failed to unmount \"%s\": %s", path
, strerror(errno
));
1456 DEBUG("cleared all (%d) mounts from \"%s\"", ret
, path
);
1460 SYSERROR("error unlinking %s", path
);
1465 /* For unprivileged containers autodev or automounts will already have
1466 * taken care of creating /dev/console.
1468 fd
= open(path
, O_CREAT
| O_EXCL
, S_IXUSR
| S_IXGRP
| S_IXOTH
);
1470 if (errno
!= EEXIST
) {
1471 SYSERROR("failed to create console");
1478 if (chmod(console
->name
, S_IXUSR
| S_IXGRP
| S_IXOTH
)) {
1479 SYSERROR("failed to set mode '0%o' to '%s'", S_IXUSR
| S_IXGRP
| S_IXOTH
, console
->name
);
1483 if (safe_mount(console
->name
, path
, "none", MS_BIND
, 0, rootfs
->mount
) < 0) {
1484 ERROR("failed to mount '%s' on '%s'", console
->name
, path
);
1488 DEBUG("mounted pts device \"%s\" onto \"%s\"", console
->name
, path
);
1492 static int lxc_setup_ttydir_console(const struct lxc_rootfs
*rootfs
,
1493 const struct lxc_console
*console
,
1497 char path
[MAXPATHLEN
], lxcpath
[MAXPATHLEN
];
1499 /* create rootfs/dev/<ttydir> directory */
1500 ret
= snprintf(path
, sizeof(path
), "%s/dev/%s", rootfs
->mount
, ttydir
);
1501 if (ret
< 0 || (size_t)ret
>= sizeof(path
))
1504 ret
= mkdir(path
, 0755);
1505 if (ret
&& errno
!= EEXIST
) {
1506 SYSERROR("failed with errno %d to create %s", errno
, path
);
1509 DEBUG("created directory for console and tty devices at \%s\"", path
);
1511 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/dev/%s/console", rootfs
->mount
, ttydir
);
1512 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1515 ret
= creat(lxcpath
, 0660);
1516 if (ret
== -1 && errno
!= EEXIST
) {
1517 SYSERROR("error %d creating %s", errno
, lxcpath
);
1523 ret
= snprintf(path
, sizeof(path
), "%s/dev/console", rootfs
->mount
);
1524 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1527 /* When we are asked to setup a console we remove any previous
1528 * /dev/console bind-mounts.
1530 if (console
->path
&& !strcmp(console
->path
, "none")) {
1532 ret
= stat(path
, &st
);
1534 if (errno
== ENOENT
)
1536 SYSERROR("failed stat() \"%s\"", path
);
1540 /* /dev/console must be character device with major number 5 and
1541 * minor number 1. If not, give benefit of the doubt and assume
1542 * the user has mounted something else right there on purpose.
1544 if (((st
.st_mode
& S_IFMT
) != S_IFCHR
) || major(st
.st_rdev
) != 5 || minor(st
.st_rdev
) != 1)
1547 /* In case the user requested a bind-mount for /dev/console and
1548 * requests a ttydir we move the mount to the
1549 * /dev/<ttydir/console.
1550 * Note, we only move the uppermost mount and clear all other
1551 * mounts underneath for safety.
1552 * If it is a character device created via mknod() we simply
1555 ret
= safe_mount(path
, lxcpath
, "none", MS_MOVE
, NULL
, rootfs
->mount
);
1557 if (errno
!= EINVAL
) {
1558 ERROR("failed to MS_MOVE \"%s\" to \"%s\": %s", path
, lxcpath
, strerror(errno
));
1561 /* path was not a mountpoint */
1562 ret
= rename(path
, lxcpath
);
1564 ERROR("failed to rename \"%s\" to \"%s\": %s", path
, lxcpath
, strerror(errno
));
1567 DEBUG("renamed \"%s\" to \"%s\"", path
, lxcpath
);
1569 DEBUG("moved mount \"%s\" to \"%s\"", path
, lxcpath
);
1572 /* Clear all remaining bind-mounts. */
1573 ret
= lxc_unstack_mountpoint(path
, false);
1575 ERROR("failed to unmount \"%s\": %s", path
, strerror(errno
));
1578 DEBUG("cleared all (%d) mounts from \"%s\"", ret
, path
);
1581 if (file_exists(path
)) {
1582 ret
= lxc_unstack_mountpoint(path
, false);
1584 ERROR("failed to unmount \"%s\": %s", path
, strerror(errno
));
1587 DEBUG("cleared all (%d) mounts from \"%s\"", ret
, path
);
1591 if (safe_mount(console
->name
, lxcpath
, "none", MS_BIND
, 0, rootfs
->mount
) < 0) {
1592 ERROR("failed to mount '%s' on '%s'", console
->name
, lxcpath
);
1595 DEBUG("mounted \"%s\" onto \"%s\"", console
->name
, lxcpath
);
1598 /* create symlink from rootfs /dev/console to '<ttydir>/console' */
1599 ret
= snprintf(lxcpath
, sizeof(lxcpath
), "%s/console", ttydir
);
1600 if (ret
< 0 || (size_t)ret
>= sizeof(lxcpath
))
1604 if (ret
&& errno
!= ENOENT
) {
1605 SYSERROR("error unlinking %s", path
);
1609 ret
= symlink(lxcpath
, path
);
1611 SYSERROR("failed to create symlink for console from \"%s\" to \"%s\"", lxcpath
, path
);
1615 DEBUG("console has been setup under \"%s\" and symlinked to \"%s\"", lxcpath
, path
);
1619 static int lxc_setup_console(const struct lxc_rootfs
*rootfs
,
1620 const struct lxc_console
*console
, char *ttydir
)
1622 /* We don't have a rootfs, /dev/console will be shared. */
1623 if (!rootfs
->path
) {
1624 DEBUG("/dev/console will be shared with the host");
1629 return lxc_setup_dev_console(rootfs
, console
);
1631 return lxc_setup_ttydir_console(rootfs
, console
, ttydir
);
1634 static int setup_kmsg(const struct lxc_rootfs
*rootfs
,
1635 const struct lxc_console
*console
)
1637 char kpath
[MAXPATHLEN
];
1642 ret
= snprintf(kpath
, sizeof(kpath
), "%s/dev/kmsg", rootfs
->mount
);
1643 if (ret
< 0 || ret
>= sizeof(kpath
))
1646 ret
= unlink(kpath
);
1647 if (ret
&& errno
!= ENOENT
) {
1648 SYSERROR("error unlinking %s", kpath
);
1652 ret
= symlink("console", kpath
);
1654 SYSERROR("failed to create symlink for kmsg");
1661 static void parse_mntopt(char *opt
, unsigned long *flags
, char **data
)
1663 struct mount_opt
*mo
;
1665 /* If opt is found in mount_opt, set or clear flags.
1666 * Otherwise append it to data. */
1668 for (mo
= &mount_opt
[0]; mo
->name
!= NULL
; mo
++) {
1669 if (!strncmp(opt
, mo
->name
, strlen(mo
->name
))) {
1671 *flags
&= ~mo
->flag
;
1683 int parse_mntopts(const char *mntopts
, unsigned long *mntflags
,
1687 char *p
, *saveptr
= NULL
;
1695 s
= strdup(mntopts
);
1697 SYSERROR("failed to allocate memory");
1701 data
= malloc(strlen(s
) + 1);
1703 SYSERROR("failed to allocate memory");
1709 for (p
= strtok_r(s
, ",", &saveptr
); p
!= NULL
;
1710 p
= strtok_r(NULL
, ",", &saveptr
))
1711 parse_mntopt(p
, mntflags
, &data
);
1722 static void null_endofword(char *word
)
1724 while (*word
&& *word
!= ' ' && *word
!= '\t')
1730 * skip @nfields spaces in @src
1732 static char *get_field(char *src
, int nfields
)
1737 for (i
= 0; i
< nfields
; i
++) {
1738 while (*p
&& *p
!= ' ' && *p
!= '\t')
1747 static int mount_entry(const char *fsname
, const char *target
,
1748 const char *fstype
, unsigned long mountflags
,
1749 const char *data
, int optional
, int dev
, const char *rootfs
)
1755 if (safe_mount(fsname
, target
, fstype
, mountflags
& ~MS_REMOUNT
, data
, rootfs
)) {
1757 INFO("failed to mount '%s' on '%s' (optional): %s", fsname
,
1758 target
, strerror(errno
));
1762 SYSERROR("failed to mount '%s' on '%s'", fsname
, target
);
1767 if ((mountflags
& MS_REMOUNT
) || (mountflags
& MS_BIND
)) {
1768 DEBUG("remounting %s on %s to respect bind or remount options",
1769 fsname
? fsname
: "(none)", target
? target
: "(none)");
1770 unsigned long rqd_flags
= 0;
1771 if (mountflags
& MS_RDONLY
)
1772 rqd_flags
|= MS_RDONLY
;
1774 if (statvfs(fsname
, &sb
) == 0) {
1775 unsigned long required_flags
= rqd_flags
;
1776 if (sb
.f_flag
& MS_NOSUID
)
1777 required_flags
|= MS_NOSUID
;
1778 if (sb
.f_flag
& MS_NODEV
&& !dev
)
1779 required_flags
|= MS_NODEV
;
1780 if (sb
.f_flag
& MS_RDONLY
)
1781 required_flags
|= MS_RDONLY
;
1782 if (sb
.f_flag
& MS_NOEXEC
)
1783 required_flags
|= MS_NOEXEC
;
1784 DEBUG("(at remount) flags for %s was %lu, required extra flags are %lu", fsname
, sb
.f_flag
, required_flags
);
1786 * If this was a bind mount request, and required_flags
1787 * does not have any flags which are not already in
1788 * mountflags, then skip the remount
1790 if (!(mountflags
& MS_REMOUNT
)) {
1791 if (!(required_flags
& ~mountflags
) && rqd_flags
== 0) {
1792 DEBUG("mountflags already was %lu, skipping remount",
1797 mountflags
|= required_flags
;
1801 if (mount(fsname
, target
, fstype
,
1802 mountflags
| MS_REMOUNT
, data
) < 0) {
1804 INFO("failed to mount '%s' on '%s' (optional): %s",
1805 fsname
, target
, strerror(errno
));
1809 SYSERROR("failed to mount '%s' on '%s'",
1819 DEBUG("mounted '%s' on '%s', type '%s'", fsname
, target
, fstype
);
1825 * Remove 'optional', 'create=dir', and 'create=file' from mntopt
1827 static void cull_mntent_opt(struct mntent
*mntent
)
1831 char *list
[] = {"create=dir",
1836 for (i
=0; list
[i
]; i
++) {
1837 if (!(p
= strstr(mntent
->mnt_opts
, list
[i
])))
1839 p2
= strchr(p
, ',');
1841 /* no more mntopts, so just chop it here */
1845 memmove(p
, p2
+1, strlen(p2
+1)+1);
1849 static int mount_entry_create_dir_file(const struct mntent
*mntent
,
1850 const char* path
, const struct lxc_rootfs
*rootfs
,
1851 const char *lxc_name
, const char *lxc_path
)
1853 char *pathdirname
= NULL
;
1855 FILE *pathfile
= NULL
;
1857 if (strncmp(mntent
->mnt_type
, "overlay", 7) == 0) {
1858 if (ovl_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
) < 0)
1860 } else if (strncmp(mntent
->mnt_type
, "aufs", 4) == 0) {
1861 if (aufs_mkdir(mntent
, rootfs
, lxc_name
, lxc_path
) < 0)
1865 if (hasmntopt(mntent
, "create=dir")) {
1866 if (mkdir_p(path
, 0755) < 0) {
1867 WARN("Failed to create mount target '%s'", path
);
1872 if (hasmntopt(mntent
, "create=file") && access(path
, F_OK
)) {
1873 pathdirname
= strdup(path
);
1874 pathdirname
= dirname(pathdirname
);
1875 if (mkdir_p(pathdirname
, 0755) < 0) {
1876 WARN("Failed to create target directory");
1878 pathfile
= fopen(path
, "wb");
1880 WARN("Failed to create mount target '%s'", path
);
1890 /* rootfs, lxc_name, and lxc_path can be NULL when the container is created
1891 * without a rootfs. */
1892 static inline int mount_entry_on_generic(struct mntent
*mntent
,
1893 const char* path
, const struct lxc_rootfs
*rootfs
,
1894 const char *lxc_name
, const char *lxc_path
)
1896 unsigned long mntflags
;
1899 bool optional
= hasmntopt(mntent
, "optional") != NULL
;
1900 bool dev
= hasmntopt(mntent
, "dev") != NULL
;
1902 char *rootfs_path
= NULL
;
1903 if (rootfs
&& rootfs
->path
)
1904 rootfs_path
= rootfs
->mount
;
1906 ret
= mount_entry_create_dir_file(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
1909 return optional
? 0 : -1;
1911 cull_mntent_opt(mntent
);
1913 if (parse_mntopts(mntent
->mnt_opts
, &mntflags
, &mntdata
) < 0) {
1918 ret
= mount_entry(mntent
->mnt_fsname
, path
, mntent
->mnt_type
, mntflags
,
1919 mntdata
, optional
, dev
, rootfs_path
);
1925 static inline int mount_entry_on_systemfs(struct mntent
*mntent
)
1927 char path
[MAXPATHLEN
];
1930 /* For containers created without a rootfs all mounts are treated as
1931 * absolute paths starting at / on the host. */
1932 if (mntent
->mnt_dir
[0] != '/')
1933 ret
= snprintf(path
, sizeof(path
), "/%s", mntent
->mnt_dir
);
1935 ret
= snprintf(path
, sizeof(path
), "%s", mntent
->mnt_dir
);
1937 if (ret
< 0 || ret
>= sizeof(path
)) {
1938 ERROR("path name too long");
1942 return mount_entry_on_generic(mntent
, path
, NULL
, NULL
, NULL
);
1945 static int mount_entry_on_absolute_rootfs(struct mntent
*mntent
,
1946 const struct lxc_rootfs
*rootfs
,
1947 const char *lxc_name
,
1948 const char *lxc_path
)
1951 char path
[MAXPATHLEN
];
1952 int r
, ret
= 0, offset
;
1953 const char *lxcpath
;
1955 lxcpath
= lxc_global_config_value("lxc.lxcpath");
1957 ERROR("Out of memory");
1961 /* if rootfs->path is a blockdev path, allow container fstab to
1962 * use $lxcpath/CN/rootfs as the target prefix */
1963 r
= snprintf(path
, MAXPATHLEN
, "%s/%s/rootfs", lxcpath
, lxc_name
);
1964 if (r
< 0 || r
>= MAXPATHLEN
)
1967 aux
= strstr(mntent
->mnt_dir
, path
);
1969 offset
= strlen(path
);
1974 aux
= strstr(mntent
->mnt_dir
, rootfs
->path
);
1976 WARN("ignoring mount point '%s'", mntent
->mnt_dir
);
1979 offset
= strlen(rootfs
->path
);
1983 r
= snprintf(path
, MAXPATHLEN
, "%s/%s", rootfs
->mount
,
1985 if (r
< 0 || r
>= MAXPATHLEN
) {
1986 WARN("pathnme too long for '%s'", mntent
->mnt_dir
);
1990 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
1993 static int mount_entry_on_relative_rootfs(struct mntent
*mntent
,
1994 const struct lxc_rootfs
*rootfs
,
1995 const char *lxc_name
,
1996 const char *lxc_path
)
1998 char path
[MAXPATHLEN
];
2001 /* relative to root mount point */
2002 ret
= snprintf(path
, sizeof(path
), "%s/%s", rootfs
->mount
, mntent
->mnt_dir
);
2003 if (ret
< 0 || ret
>= sizeof(path
)) {
2004 ERROR("path name too long");
2008 return mount_entry_on_generic(mntent
, path
, rootfs
, lxc_name
, lxc_path
);
2011 static int mount_file_entries(const struct lxc_rootfs
*rootfs
, FILE *file
,
2012 const char *lxc_name
, const char *lxc_path
)
2014 struct mntent mntent
;
2018 while (getmntent_r(file
, &mntent
, buf
, sizeof(buf
))) {
2020 if (!rootfs
->path
) {
2021 if (mount_entry_on_systemfs(&mntent
))
2026 /* We have a separate root, mounts are relative to it */
2027 if (mntent
.mnt_dir
[0] != '/') {
2028 if (mount_entry_on_relative_rootfs(&mntent
, rootfs
, lxc_name
, lxc_path
))
2033 if (mount_entry_on_absolute_rootfs(&mntent
, rootfs
, lxc_name
, lxc_path
))
2039 INFO("mount points have been setup");
2044 static int setup_mount(const struct lxc_rootfs
*rootfs
, const char *fstab
,
2045 const char *lxc_name
, const char *lxc_path
)
2053 file
= setmntent(fstab
, "r");
2055 SYSERROR("failed to use '%s'", fstab
);
2059 ret
= mount_file_entries(rootfs
, file
, lxc_name
, lxc_path
);
2065 FILE *make_anonymous_mount_file(struct lxc_list
*mount
)
2069 struct lxc_list
*iterator
;
2073 fd
= memfd_create("lxc_mount_file", MFD_CLOEXEC
);
2075 if (errno
!= ENOSYS
)
2079 file
= fdopen(fd
, "r+");
2083 int saved_errno
= errno
;
2086 ERROR("Could not create mount entry file: %s.", strerror(saved_errno
));
2090 lxc_list_for_each(iterator
, mount
) {
2091 mount_entry
= iterator
->elem
;
2092 ret
= fprintf(file
, "%s\n", mount_entry
);
2093 if (ret
< strlen(mount_entry
))
2094 WARN("Could not write mount entry to anonymous mount file.");
2097 if (fseek(file
, 0, SEEK_SET
) < 0) {
2105 static int setup_mount_entries(const struct lxc_rootfs
*rootfs
,
2106 struct lxc_list
*mount
, const char *lxc_name
,
2107 const char *lxc_path
)
2112 file
= make_anonymous_mount_file(mount
);
2116 ret
= mount_file_entries(rootfs
, file
, lxc_name
, lxc_path
);
2122 static int parse_cap(const char *cap
)
2128 if (!strcmp(cap
, "none"))
2131 for (i
= 0; i
< sizeof(caps_opt
)/sizeof(caps_opt
[0]); i
++) {
2133 if (strcmp(cap
, caps_opt
[i
].name
))
2136 capid
= caps_opt
[i
].value
;
2141 /* try to see if it's numeric, so the user may specify
2142 * capabilities that the running kernel knows about but
2145 capid
= strtol(cap
, &ptr
, 10);
2146 if (!ptr
|| *ptr
!= '\0' || errno
!= 0)
2147 /* not a valid number */
2149 else if (capid
> lxc_caps_last_cap())
2150 /* we have a number but it's not a valid
2158 int in_caplist(int cap
, struct lxc_list
*caps
)
2160 struct lxc_list
*iterator
;
2163 lxc_list_for_each(iterator
, caps
) {
2164 capid
= parse_cap(iterator
->elem
);
2172 static int setup_caps(struct lxc_list
*caps
)
2174 struct lxc_list
*iterator
;
2178 lxc_list_for_each(iterator
, caps
) {
2180 drop_entry
= iterator
->elem
;
2182 capid
= parse_cap(drop_entry
);
2185 ERROR("unknown capability %s", drop_entry
);
2189 DEBUG("drop capability '%s' (%d)", drop_entry
, capid
);
2191 if (prctl(PR_CAPBSET_DROP
, capid
, 0, 0, 0)) {
2192 SYSERROR("failed to remove %s capability", drop_entry
);
2198 DEBUG("capabilities have been setup");
2203 static int dropcaps_except(struct lxc_list
*caps
)
2205 struct lxc_list
*iterator
;
2208 int numcaps
= lxc_caps_last_cap() + 1;
2209 INFO("found %d capabilities", numcaps
);
2211 if (numcaps
<= 0 || numcaps
> 200)
2214 // caplist[i] is 1 if we keep capability i
2215 int *caplist
= alloca(numcaps
* sizeof(int));
2216 memset(caplist
, 0, numcaps
* sizeof(int));
2218 lxc_list_for_each(iterator
, caps
) {
2220 keep_entry
= iterator
->elem
;
2222 capid
= parse_cap(keep_entry
);
2228 ERROR("unknown capability %s", keep_entry
);
2232 DEBUG("keep capability '%s' (%d)", keep_entry
, capid
);
2236 for (i
=0; i
<numcaps
; i
++) {
2239 if (prctl(PR_CAPBSET_DROP
, i
, 0, 0, 0)) {
2240 SYSERROR("failed to remove capability %d", i
);
2245 DEBUG("capabilities have been setup");
2250 static int setup_hw_addr(char *hwaddr
, const char *ifname
)
2252 struct sockaddr sockaddr
;
2254 int ret
, fd
, saved_errno
;
2256 ret
= lxc_convert_mac(hwaddr
, &sockaddr
);
2258 ERROR("mac address '%s' conversion failed : %s",
2259 hwaddr
, strerror(-ret
));
2263 memcpy(ifr
.ifr_name
, ifname
, IFNAMSIZ
);
2264 ifr
.ifr_name
[IFNAMSIZ
-1] = '\0';
2265 memcpy((char *) &ifr
.ifr_hwaddr
, (char *) &sockaddr
, sizeof(sockaddr
));
2267 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2269 ERROR("socket failure : %s", strerror(errno
));
2273 ret
= ioctl(fd
, SIOCSIFHWADDR
, &ifr
);
2274 saved_errno
= errno
;
2277 ERROR("ioctl failure : %s", strerror(saved_errno
));
2279 DEBUG("mac address '%s' on '%s' has been setup", hwaddr
, ifr
.ifr_name
);
2284 static int setup_ipv4_addr(struct lxc_list
*ip
, int ifindex
)
2286 struct lxc_list
*iterator
;
2287 struct lxc_inetdev
*inetdev
;
2290 lxc_list_for_each(iterator
, ip
) {
2292 inetdev
= iterator
->elem
;
2294 err
= lxc_ipv4_addr_add(ifindex
, &inetdev
->addr
,
2295 &inetdev
->bcast
, inetdev
->prefix
);
2297 ERROR("failed to setup_ipv4_addr ifindex %d : %s",
2298 ifindex
, strerror(-err
));
2306 static int setup_ipv6_addr(struct lxc_list
*ip
, int ifindex
)
2308 struct lxc_list
*iterator
;
2309 struct lxc_inet6dev
*inet6dev
;
2312 lxc_list_for_each(iterator
, ip
) {
2314 inet6dev
= iterator
->elem
;
2316 err
= lxc_ipv6_addr_add(ifindex
, &inet6dev
->addr
,
2317 &inet6dev
->mcast
, &inet6dev
->acast
,
2320 ERROR("failed to setup_ipv6_addr ifindex %d : %s",
2321 ifindex
, strerror(-err
));
2329 static int lxc_setup_netdev_in_child_namespaces(struct lxc_netdev
*netdev
)
2331 char ifname
[IFNAMSIZ
];
2333 const char *net_type_name
;
2334 char *current_ifname
= ifname
;
2336 /* empty network namespace */
2337 if (!netdev
->ifindex
) {
2338 if (netdev
->flags
& IFF_UP
) {
2339 err
= lxc_netdev_up("lo");
2341 ERROR("failed to set the loopback up : %s",
2347 if (netdev
->type
== LXC_NET_EMPTY
)
2350 if (netdev
->type
== LXC_NET_NONE
)
2353 if (netdev
->type
!= LXC_NET_VETH
) {
2354 net_type_name
= lxc_net_type_to_str(netdev
->type
);
2355 ERROR("%s networks are not supported for containers "
2356 "not setup up by privileged users",
2361 netdev
->ifindex
= if_nametoindex(netdev
->name
);
2364 /* get the new ifindex in case of physical netdev */
2365 if (netdev
->type
== LXC_NET_PHYS
) {
2366 if (!(netdev
->ifindex
= if_nametoindex(netdev
->link
))) {
2367 ERROR("failed to get ifindex for %s",
2373 /* retrieve the name of the interface */
2374 if (!if_indextoname(netdev
->ifindex
, current_ifname
)) {
2375 ERROR("no interface corresponding to index '%d'",
2380 /* default: let the system to choose one interface name */
2382 netdev
->name
= netdev
->type
== LXC_NET_PHYS
?
2383 netdev
->link
: "eth%d";
2385 /* rename the interface name */
2386 if (strcmp(ifname
, netdev
->name
) != 0) {
2387 err
= lxc_netdev_rename_by_name(ifname
, netdev
->name
);
2389 ERROR("failed to rename %s->%s : %s", ifname
, netdev
->name
,
2395 /* Re-read the name of the interface because its name has changed
2396 * and would be automatically allocated by the system
2398 if (!if_indextoname(netdev
->ifindex
, current_ifname
)) {
2399 ERROR("no interface corresponding to index '%d'",
2404 /* set a mac address */
2405 if (netdev
->hwaddr
) {
2406 if (setup_hw_addr(netdev
->hwaddr
, current_ifname
)) {
2407 ERROR("failed to setup hw address for '%s'",
2413 /* setup ipv4 addresses on the interface */
2414 if (setup_ipv4_addr(&netdev
->ipv4
, netdev
->ifindex
)) {
2415 ERROR("failed to setup ip addresses for '%s'",
2420 /* setup ipv6 addresses on the interface */
2421 if (setup_ipv6_addr(&netdev
->ipv6
, netdev
->ifindex
)) {
2422 ERROR("failed to setup ipv6 addresses for '%s'",
2427 /* set the network device up */
2428 if (netdev
->flags
& IFF_UP
) {
2431 err
= lxc_netdev_up(current_ifname
);
2433 ERROR("failed to set '%s' up : %s", current_ifname
,
2438 /* the network is up, make the loopback up too */
2439 err
= lxc_netdev_up("lo");
2441 ERROR("failed to set the loopback up : %s",
2447 /* We can only set up the default routes after bringing
2448 * up the interface, sine bringing up the interface adds
2449 * the link-local routes and we can't add a default
2450 * route if the gateway is not reachable. */
2452 /* setup ipv4 gateway on the interface */
2453 if (netdev
->ipv4_gateway
) {
2454 if (!(netdev
->flags
& IFF_UP
)) {
2455 ERROR("Cannot add ipv4 gateway for %s when not bringing up the interface", ifname
);
2459 if (lxc_list_empty(&netdev
->ipv4
)) {
2460 ERROR("Cannot add ipv4 gateway for %s when not assigning an address", ifname
);
2464 err
= lxc_ipv4_gateway_add(netdev
->ifindex
, netdev
->ipv4_gateway
);
2466 err
= lxc_ipv4_dest_add(netdev
->ifindex
, netdev
->ipv4_gateway
);
2468 ERROR("failed to add ipv4 dest for '%s': %s",
2469 ifname
, strerror(-err
));
2472 err
= lxc_ipv4_gateway_add(netdev
->ifindex
, netdev
->ipv4_gateway
);
2474 ERROR("failed to setup ipv4 gateway for '%s': %s",
2475 ifname
, strerror(-err
));
2476 if (netdev
->ipv4_gateway_auto
) {
2477 char buf
[INET_ADDRSTRLEN
];
2478 inet_ntop(AF_INET
, netdev
->ipv4_gateway
, buf
, sizeof(buf
));
2479 ERROR("tried to set autodetected ipv4 gateway '%s'", buf
);
2486 /* setup ipv6 gateway on the interface */
2487 if (netdev
->ipv6_gateway
) {
2488 if (!(netdev
->flags
& IFF_UP
)) {
2489 ERROR("Cannot add ipv6 gateway for %s when not bringing up the interface", ifname
);
2493 if (lxc_list_empty(&netdev
->ipv6
) && !IN6_IS_ADDR_LINKLOCAL(netdev
->ipv6_gateway
)) {
2494 ERROR("Cannot add ipv6 gateway for %s when not assigning an address", ifname
);
2498 err
= lxc_ipv6_gateway_add(netdev
->ifindex
, netdev
->ipv6_gateway
);
2500 err
= lxc_ipv6_dest_add(netdev
->ifindex
, netdev
->ipv6_gateway
);
2502 ERROR("failed to add ipv6 dest for '%s': %s",
2503 ifname
, strerror(-err
));
2506 err
= lxc_ipv6_gateway_add(netdev
->ifindex
, netdev
->ipv6_gateway
);
2508 ERROR("failed to setup ipv6 gateway for '%s': %s",
2509 ifname
, strerror(-err
));
2510 if (netdev
->ipv6_gateway_auto
) {
2511 char buf
[INET6_ADDRSTRLEN
];
2512 inet_ntop(AF_INET6
, netdev
->ipv6_gateway
, buf
, sizeof(buf
));
2513 ERROR("tried to set autodetected ipv6 gateway '%s'", buf
);
2520 DEBUG("'%s' has been setup", current_ifname
);
2525 static int lxc_setup_networks_in_child_namespaces(const struct lxc_conf
*conf
,
2526 struct lxc_list
*network
)
2528 struct lxc_list
*iterator
;
2529 struct lxc_netdev
*netdev
;
2531 lxc_log_configured_netdevs(conf
);
2533 lxc_list_for_each(iterator
, network
) {
2534 netdev
= iterator
->elem
;
2536 /* REMOVE in LXC 3.0 */
2537 if (netdev
->idx
< 0) {
2538 ERROR("WARNING: using \"lxc.network.*\" keys to define "
2539 "networks is DEPRECATED, please switch to using "
2540 "\"lxc.net.[i].* keys\"");
2543 if (lxc_setup_netdev_in_child_namespaces(netdev
)) {
2544 ERROR("failed to setup netdev");
2549 if (!lxc_list_empty(network
))
2550 INFO("network has been setup");
2555 static int parse_resource(const char *res
) {
2559 for (i
= 0; i
< sizeof(limit_opt
)/sizeof(limit_opt
[0]); ++i
) {
2560 if (strcmp(res
, limit_opt
[i
].name
) == 0)
2561 return limit_opt
[i
].value
;
2564 /* try to see if it's numeric, so the user may specify
2565 * resources that the running kernel knows about but
2567 if (lxc_safe_int(res
, &resid
) == 0)
2572 int setup_resource_limits(struct lxc_list
*limits
, pid_t pid
) {
2573 struct lxc_list
*it
;
2574 struct lxc_limit
*lim
;
2577 lxc_list_for_each(it
, limits
) {
2580 resid
= parse_resource(lim
->resource
);
2582 ERROR("unknown resource %s", lim
->resource
);
2586 if (prlimit(pid
, resid
, &lim
->limit
, NULL
) != 0) {
2587 ERROR("failed to set limit %s: %s", lim
->resource
, strerror(errno
));
2594 /* try to move physical nics to the init netns */
2595 void lxc_restore_phys_nics_to_netns(int netnsfd
, struct lxc_conf
*conf
)
2598 char ifname
[IFNAMSIZ
];
2600 if (netnsfd
< 0 || conf
->num_savednics
== 0)
2603 INFO("Running to reset %d nic names.", conf
->num_savednics
);
2605 oldfd
= lxc_preserve_ns(getpid(), "net");
2607 SYSERROR("Failed to open monitor netns fd.");
2611 if (setns(netnsfd
, 0) != 0) {
2612 SYSERROR("Failed to enter container netns to reset nics");
2616 for (i
=0; i
<conf
->num_savednics
; i
++) {
2617 struct saved_nic
*s
= &conf
->saved_nics
[i
];
2618 /* retrieve the name of the interface */
2619 if (!if_indextoname(s
->ifindex
, ifname
)) {
2620 WARN("no interface corresponding to index '%d'", s
->ifindex
);
2623 if (lxc_netdev_move_by_name(ifname
, 1, s
->orig_name
))
2624 WARN("Error moving nic name:%s back to host netns", ifname
);
2627 conf
->num_savednics
= 0;
2629 if (setns(oldfd
, 0) != 0)
2630 SYSERROR("Failed to re-enter monitor's netns");
2634 static char *default_rootfs_mount
= LXCROOTFSMOUNT
;
2636 struct lxc_conf
*lxc_conf_init(void)
2638 struct lxc_conf
*new;
2641 new = malloc(sizeof(*new));
2643 ERROR("lxc_conf_init : %s", strerror(errno
));
2646 memset(new, 0, sizeof(*new));
2648 new->loglevel
= LXC_LOG_LEVEL_NOTSET
;
2649 new->personality
= -1;
2651 new->console
.log_path
= NULL
;
2652 new->console
.log_fd
= -1;
2653 new->console
.path
= NULL
;
2654 new->console
.peer
= -1;
2655 new->console
.peerpty
.busy
= -1;
2656 new->console
.peerpty
.master
= -1;
2657 new->console
.peerpty
.slave
= -1;
2658 new->console
.master
= -1;
2659 new->console
.slave
= -1;
2660 new->console
.name
[0] = '\0';
2661 new->maincmd_fd
= -1;
2663 new->rootfs
.mount
= strdup(default_rootfs_mount
);
2664 if (!new->rootfs
.mount
) {
2665 ERROR("lxc_conf_init : %s", strerror(errno
));
2671 lxc_list_init(&new->cgroup
);
2672 lxc_list_init(&new->network
);
2673 lxc_list_init(&new->mount_list
);
2674 lxc_list_init(&new->caps
);
2675 lxc_list_init(&new->keepcaps
);
2676 lxc_list_init(&new->id_map
);
2677 lxc_list_init(&new->includes
);
2678 lxc_list_init(&new->aliens
);
2679 lxc_list_init(&new->environment
);
2680 lxc_list_init(&new->limits
);
2681 for (i
=0; i
<NUM_LXC_HOOKS
; i
++)
2682 lxc_list_init(&new->hooks
[i
]);
2683 lxc_list_init(&new->groups
);
2684 new->lsm_aa_profile
= NULL
;
2685 new->lsm_se_context
= NULL
;
2686 new->tmp_umount_proc
= 0;
2688 for (i
= 0; i
< LXC_NS_MAX
; i
++)
2689 new->inherit_ns_fd
[i
] = -1;
2691 /* if running in a new user namespace, init and COMMAND
2692 * default to running as UID/GID 0 when using lxc-execute */
2699 static int instantiate_veth(struct lxc_handler
*handler
, struct lxc_netdev
*netdev
)
2701 char *veth1
, *veth2
;
2702 char veth1buf
[IFNAMSIZ
], veth2buf
[IFNAMSIZ
];
2703 int bridge_index
, err
;
2704 unsigned int mtu
= 0;
2706 if (netdev
->priv
.veth_attr
.pair
) {
2707 veth1
= netdev
->priv
.veth_attr
.pair
;
2708 if (handler
->conf
->reboot
)
2709 lxc_netdev_delete_by_name(veth1
);
2711 err
= snprintf(veth1buf
, sizeof(veth1buf
), "vethXXXXXX");
2712 if (err
>= sizeof(veth1buf
)) { /* can't *really* happen, but... */
2713 ERROR("veth1 name too long");
2716 veth1
= lxc_mkifname(veth1buf
);
2718 ERROR("failed to allocate a temporary name");
2721 /* store away for deconf */
2722 memcpy(netdev
->priv
.veth_attr
.veth1
, veth1
, IFNAMSIZ
);
2725 snprintf(veth2buf
, sizeof(veth2buf
), "vethXXXXXX");
2726 veth2
= lxc_mkifname(veth2buf
);
2728 ERROR("failed to allocate a temporary name");
2732 err
= lxc_veth_create(veth1
, veth2
);
2734 ERROR("failed to create veth pair \"%s\" and \"%s\": %s", veth1
,
2735 veth2
, strerror(-err
));
2739 /* changing the high byte of the mac address to 0xfe, the bridge interface
2740 * will always keep the host's mac address and not take the mac address
2742 err
= setup_private_host_hw_addr(veth1
);
2744 ERROR("failed to change mac address of host interface \"%s\": %s",
2745 veth1
, strerror(-err
));
2749 netdev
->ifindex
= if_nametoindex(veth2
);
2750 if (!netdev
->ifindex
) {
2751 ERROR("failed to retrieve the index for \"%s\"", veth2
);
2756 if (lxc_safe_uint(netdev
->mtu
, &mtu
) < 0)
2757 WARN("failed to parse mtu from");
2759 INFO("retrieved mtu %d", mtu
);
2760 } else if (netdev
->link
) {
2761 bridge_index
= if_nametoindex(netdev
->link
);
2763 mtu
= netdev_get_mtu(bridge_index
);
2764 INFO("retrieved mtu %d from %s", mtu
, netdev
->link
);
2766 mtu
= netdev_get_mtu(netdev
->ifindex
);
2767 INFO("retrieved mtu %d from %s", mtu
, veth2
);
2772 err
= lxc_netdev_set_mtu(veth1
, mtu
);
2774 err
= lxc_netdev_set_mtu(veth2
, mtu
);
2776 ERROR("failed to set mtu \"%d\" for veth pair \"%s\" "
2778 mtu
, veth1
, veth2
, strerror(-err
));
2784 err
= lxc_bridge_attach(handler
->lxcpath
, handler
->name
, netdev
->link
, veth1
);
2786 ERROR("failed to attach \"%s\" to bridge \"%s\": %s",
2787 veth1
, netdev
->link
, strerror(-err
));
2790 INFO("attached \"%s\" to bridge \"%s\"", veth1
, netdev
->link
);
2793 err
= lxc_netdev_up(veth1
);
2795 ERROR("failed to set \"%s\" up: %s", veth1
, strerror(-err
));
2799 if (netdev
->upscript
) {
2800 err
= run_script(handler
->name
, "net", netdev
->upscript
, "up",
2801 "veth", veth1
, (char*) NULL
);
2806 DEBUG("instantiated veth \"%s/%s\", index is \"%d\"", veth1
, veth2
,
2812 if (netdev
->ifindex
!= 0)
2813 lxc_netdev_delete_by_name(veth1
);
2814 if (!netdev
->priv
.veth_attr
.pair
)
2820 static int shutdown_veth(struct lxc_handler
*handler
, struct lxc_netdev
*netdev
)
2825 if (netdev
->priv
.veth_attr
.pair
)
2826 veth1
= netdev
->priv
.veth_attr
.pair
;
2828 veth1
= netdev
->priv
.veth_attr
.veth1
;
2830 if (netdev
->downscript
) {
2831 err
= run_script(handler
->name
, "net", netdev
->downscript
,
2832 "down", "veth", veth1
, (char*) NULL
);
2839 static int instantiate_macvlan(struct lxc_handler
*handler
, struct lxc_netdev
*netdev
)
2841 char peerbuf
[IFNAMSIZ
], *peer
;
2844 if (!netdev
->link
) {
2845 ERROR("no link specified for macvlan netdev");
2849 err
= snprintf(peerbuf
, sizeof(peerbuf
), "mcXXXXXX");
2850 if (err
>= sizeof(peerbuf
))
2853 peer
= lxc_mkifname(peerbuf
);
2855 ERROR("failed to make a temporary name");
2859 err
= lxc_macvlan_create(netdev
->link
, peer
,
2860 netdev
->priv
.macvlan_attr
.mode
);
2862 ERROR("failed to create macvlan interface '%s' on '%s' : %s",
2863 peer
, netdev
->link
, strerror(-err
));
2867 netdev
->ifindex
= if_nametoindex(peer
);
2868 if (!netdev
->ifindex
) {
2869 ERROR("failed to retrieve the index for %s", peer
);
2873 if (netdev
->upscript
) {
2874 err
= run_script(handler
->name
, "net", netdev
->upscript
, "up",
2875 "macvlan", netdev
->link
, (char*) NULL
);
2880 DEBUG("instantiated macvlan '%s', index is '%d' and mode '%d'",
2881 peer
, netdev
->ifindex
, netdev
->priv
.macvlan_attr
.mode
);
2885 lxc_netdev_delete_by_name(peer
);
2890 static int shutdown_macvlan(struct lxc_handler
*handler
, struct lxc_netdev
*netdev
)
2894 if (netdev
->downscript
) {
2895 err
= run_script(handler
->name
, "net", netdev
->downscript
,
2896 "down", "macvlan", netdev
->link
,
2904 /* XXX: merge with instantiate_macvlan */
2905 static int instantiate_vlan(struct lxc_handler
*handler
, struct lxc_netdev
*netdev
)
2907 char peer
[IFNAMSIZ
];
2909 static uint16_t vlan_cntr
= 0;
2910 unsigned int mtu
= 0;
2912 if (!netdev
->link
) {
2913 ERROR("no link specified for vlan netdev");
2917 err
= snprintf(peer
, sizeof(peer
), "vlan%d-%d", netdev
->priv
.vlan_attr
.vid
, vlan_cntr
++);
2918 if (err
>= sizeof(peer
)) {
2919 ERROR("peer name too long");
2923 err
= lxc_vlan_create(netdev
->link
, peer
, netdev
->priv
.vlan_attr
.vid
);
2925 ERROR("failed to create vlan interface '%s' on '%s' : %s",
2926 peer
, netdev
->link
, strerror(-err
));
2930 netdev
->ifindex
= if_nametoindex(peer
);
2931 if (!netdev
->ifindex
) {
2932 ERROR("failed to retrieve the ifindex for %s", peer
);
2933 lxc_netdev_delete_by_name(peer
);
2937 DEBUG("instantiated vlan '%s', ifindex is '%d'", " vlan1000",
2940 if (lxc_safe_uint(netdev
->mtu
, &mtu
) < 0) {
2941 ERROR("Failed to retrieve mtu from: '%d'/'%s'.",
2942 netdev
->ifindex
, netdev
->name
);
2945 err
= lxc_netdev_set_mtu(peer
, mtu
);
2947 ERROR("failed to set mtu '%s' for %s : %s",
2948 netdev
->mtu
, peer
, strerror(-err
));
2949 lxc_netdev_delete_by_name(peer
);
2957 static int shutdown_vlan(struct lxc_handler
*handler
, struct lxc_netdev
*netdev
)
2962 static int instantiate_phys(struct lxc_handler
*handler
, struct lxc_netdev
*netdev
)
2964 if (!netdev
->link
) {
2965 ERROR("no link specified for the physical interface");
2969 netdev
->ifindex
= if_nametoindex(netdev
->link
);
2970 if (!netdev
->ifindex
) {
2971 ERROR("failed to retrieve the index for %s", netdev
->link
);
2975 if (netdev
->upscript
) {
2977 err
= run_script(handler
->name
, "net", netdev
->upscript
,
2978 "up", "phys", netdev
->link
, (char*) NULL
);
2986 static int shutdown_phys(struct lxc_handler
*handler
, struct lxc_netdev
*netdev
)
2990 if (netdev
->downscript
) {
2991 err
= run_script(handler
->name
, "net", netdev
->downscript
,
2992 "down", "phys", netdev
->link
, (char*) NULL
);
2999 static int instantiate_none(struct lxc_handler
*handler
, struct lxc_netdev
*netdev
)
3001 netdev
->ifindex
= 0;
3005 static int instantiate_empty(struct lxc_handler
*handler
, struct lxc_netdev
*netdev
)
3007 netdev
->ifindex
= 0;
3008 if (netdev
->upscript
) {
3010 err
= run_script(handler
->name
, "net", netdev
->upscript
,
3011 "up", "empty", (char*) NULL
);
3018 static int shutdown_empty(struct lxc_handler
*handler
, struct lxc_netdev
*netdev
)
3022 if (netdev
->downscript
) {
3023 err
= run_script(handler
->name
, "net", netdev
->downscript
,
3024 "down", "empty", (char*) NULL
);
3031 static int shutdown_none(struct lxc_handler
*handler
, struct lxc_netdev
*netdev
)
3036 int lxc_requests_empty_network(struct lxc_handler
*handler
)
3038 struct lxc_list
*network
= &handler
->conf
->network
;
3039 struct lxc_list
*iterator
;
3040 struct lxc_netdev
*netdev
;
3041 bool found_none
= false, found_nic
= false;
3043 if (lxc_list_empty(network
))
3046 lxc_list_for_each(iterator
, network
) {
3048 netdev
= iterator
->elem
;
3050 if (netdev
->type
== LXC_NET_NONE
)
3055 if (found_none
&& !found_nic
)
3060 int lxc_setup_networks_in_parent_namespaces(struct lxc_handler
*handler
)
3063 struct lxc_netdev
*netdev
;
3064 struct lxc_list
*iterator
;
3065 struct lxc_list
*network
= &handler
->conf
->network
;
3067 /* We need to be root. */
3068 am_root
= (getuid() == 0);
3072 lxc_list_for_each(iterator
, network
) {
3073 netdev
= iterator
->elem
;
3075 if (netdev
->type
< 0 || netdev
->type
> LXC_NET_MAXCONFTYPE
) {
3076 ERROR("invalid network configuration type '%d'",
3081 if (netdev
->type
!= LXC_NET_MACVLAN
&&
3082 netdev
->priv
.macvlan_attr
.mode
) {
3083 ERROR("Invalid macvlan.mode for a non-macvlan netdev");
3087 if (netdev
->type
!= LXC_NET_VETH
&&
3088 netdev
->priv
.veth_attr
.pair
) {
3089 ERROR("Invalid veth pair for a non-veth netdev");
3093 if (netdev
->type
!= LXC_NET_VLAN
&&
3094 netdev
->priv
.vlan_attr
.vid
> 0) {
3095 ERROR("Invalid vlan.id for a non-macvlan netdev");
3099 if (netdev_conf
[netdev
->type
](handler
, netdev
)) {
3100 ERROR("failed to create netdev");
3109 bool lxc_delete_network(struct lxc_handler
*handler
)
3112 struct lxc_list
*network
= &handler
->conf
->network
;
3113 struct lxc_list
*iterator
;
3114 struct lxc_netdev
*netdev
;
3115 bool deleted_all
= true;
3117 lxc_list_for_each(iterator
, network
) {
3118 netdev
= iterator
->elem
;
3120 if (netdev
->ifindex
!= 0 && netdev
->type
== LXC_NET_PHYS
) {
3121 if (lxc_netdev_rename_by_index(netdev
->ifindex
, netdev
->link
))
3122 WARN("Failed to rename interface with index %d "
3123 "to its initial name \"%s\".",
3124 netdev
->ifindex
, netdev
->link
);
3128 if (netdev_deconf
[netdev
->type
](handler
, netdev
)) {
3129 WARN("Failed to destroy netdev");
3132 /* Recent kernel remove the virtual interfaces when the network
3133 * namespace is destroyed but in case we did not moved the
3134 * interface to the network namespace, we have to destroy it
3136 if (netdev
->ifindex
!= 0) {
3137 ret
= lxc_netdev_delete_by_index(netdev
->ifindex
);
3138 if (-ret
== ENODEV
) {
3139 INFO("Interface \"%s\" with index %d already "
3140 "deleted or existing in different network "
3142 netdev
->name
? netdev
->name
: "(null)",
3144 } else if (ret
< 0) {
3145 deleted_all
= false;
3146 WARN("Failed to remove interface \"%s\" with "
3148 netdev
->name
? netdev
->name
: "(null)",
3149 netdev
->ifindex
, strerror(-ret
));
3151 INFO("Removed interface \"%s\" with index %d.",
3152 netdev
->name
? netdev
->name
: "(null)",
3157 /* Explicitly delete host veth device to prevent lingering
3158 * devices. We had issues in LXD around this.
3160 if (netdev
->ifindex
!= 0 && netdev
->type
== LXC_NET_VETH
&& !am_unpriv()) {
3162 if (netdev
->priv
.veth_attr
.pair
) {
3163 hostveth
= netdev
->priv
.veth_attr
.pair
;
3164 ret
= lxc_netdev_delete_by_name(hostveth
);
3166 WARN("Failed to remove interface \"%s\" from host: %s.", hostveth
, strerror(-ret
));
3168 INFO("Removed interface \"%s\" from host.", hostveth
);
3170 } else if (strlen(netdev
->priv
.veth_attr
.veth1
) > 0) {
3171 hostveth
= netdev
->priv
.veth_attr
.veth1
;
3172 ret
= lxc_netdev_delete_by_name(hostveth
);
3174 WARN("Failed to remove \"%s\" from host: %s.", hostveth
, strerror(-ret
));
3176 INFO("Removed interface \"%s\" from host.", hostveth
);
3177 memset((void *)&netdev
->priv
.veth_attr
.veth1
, 0, sizeof(netdev
->priv
.veth_attr
.veth1
));
3186 #define LXC_USERNIC_PATH LIBEXECDIR "/lxc/lxc-user-nic"
3188 /* lxc-user-nic returns "interface_name:interface_name\n" */
3189 #define MAX_BUFFER_SIZE IFNAMSIZ * 2 + 2
3190 static int unpriv_assign_nic(const char *lxcpath
, char *lxcname
,
3191 struct lxc_netdev
*netdev
, pid_t pid
)
3194 int bytes
, pipefd
[2];
3195 char *token
, *saveptr
= NULL
;
3196 char buffer
[MAX_BUFFER_SIZE
];
3197 char netdev_link
[IFNAMSIZ
+ 1];
3199 if (netdev
->type
!= LXC_NET_VETH
) {
3200 ERROR("nic type %d not support for unprivileged use",
3205 if (pipe(pipefd
) < 0) {
3206 SYSERROR("pipe failed");
3218 if (child
== 0) { // child
3219 /* Call lxc-user-nic pid type bridge. */
3221 char pidstr
[LXC_NUMSTRLEN64
];
3223 close(pipefd
[0]); /* Close the read-end of the pipe. */
3225 /* Redirect stdout to write-end of the pipe. */
3226 ret
= dup2(pipefd
[1], STDOUT_FILENO
);
3227 close(pipefd
[1]); /* Close the write-end of the pipe. */
3229 SYSERROR("Failed to dup2() to redirect stdout to pipe file descriptor.");
3234 strncpy(netdev_link
, netdev
->link
, IFNAMSIZ
);
3236 strncpy(netdev_link
, "none", IFNAMSIZ
);
3238 ret
= snprintf(pidstr
, LXC_NUMSTRLEN64
, "%d", pid
);
3239 if (ret
< 0 || ret
>= LXC_NUMSTRLEN64
)
3241 pidstr
[LXC_NUMSTRLEN64
- 1] = '\0';
3243 INFO("Execing lxc-user-nic %s %s %s veth %s %s", lxcpath
,
3244 lxcname
, pidstr
, netdev_link
, netdev
->name
);
3245 execlp(LXC_USERNIC_PATH
, LXC_USERNIC_PATH
, lxcpath
, lxcname
,
3246 pidstr
, "veth", netdev_link
, netdev
->name
, NULL
);
3248 SYSERROR("Failed to exec lxc-user-nic.");
3252 /* close the write-end of the pipe */
3255 bytes
= read(pipefd
[0], &buffer
, MAX_BUFFER_SIZE
);
3257 SYSERROR("Failed to read from pipe file descriptor.");
3258 buffer
[bytes
- 1] = '\0';
3260 if (wait_for_pid(child
) != 0) {
3265 /* close the read-end of the pipe */
3268 /* fill netdev->name field */
3269 token
= strtok_r(buffer
, ":", &saveptr
);
3273 netdev
->name
= malloc(IFNAMSIZ
+ 1);
3274 if (!netdev
->name
) {
3275 SYSERROR("Failed to allocate memory.");
3278 memset(netdev
->name
, 0, IFNAMSIZ
+ 1);
3279 strncpy(netdev
->name
, token
, IFNAMSIZ
);
3281 /* fill netdev->veth_attr.pair field */
3282 token
= strtok_r(NULL
, ":", &saveptr
);
3286 netdev
->priv
.veth_attr
.pair
= strdup(token
);
3287 if (!netdev
->priv
.veth_attr
.pair
) {
3288 ERROR("Failed to allocate memory.");
3295 int lxc_assign_network(const char *lxcpath
, char *lxcname
,
3296 struct lxc_list
*network
, pid_t pid
)
3298 struct lxc_list
*iterator
;
3299 struct lxc_netdev
*netdev
;
3300 char ifname
[IFNAMSIZ
];
3301 int am_root
= (getuid() == 0);
3304 lxc_list_for_each(iterator
, network
) {
3306 netdev
= iterator
->elem
;
3308 if (netdev
->type
== LXC_NET_VETH
&& !am_root
) {
3310 INFO("mtu ignored due to insufficient privilege");
3311 if (unpriv_assign_nic(lxcpath
, lxcname
, netdev
, pid
))
3313 /* lxc-user-nic has moved the nic to the new ns.
3314 * unpriv_assign_nic() fills in netdev->name.
3315 * netdev->ifindex will be filed in at
3316 * lxc_setup_netdev_in_child_namespaces.
3321 /* empty network namespace, nothing to move */
3322 if (!netdev
->ifindex
)
3325 /* retrieve the name of the interface */
3326 if (!if_indextoname(netdev
->ifindex
, ifname
)) {
3327 ERROR("no interface corresponding to index '%d'", netdev
->ifindex
);
3331 err
= lxc_netdev_move_by_name(ifname
, pid
, NULL
);
3333 ERROR("failed to move '%s' to the container : %s",
3334 netdev
->link
, strerror(-err
));
3338 DEBUG("move '%s'/'%s' to '%d': .", ifname
, netdev
->name
, pid
);
3344 static int write_id_mapping(enum idtype idtype
, pid_t pid
, const char *buf
,
3347 char path
[MAXPATHLEN
];
3350 ret
= snprintf(path
, MAXPATHLEN
, "/proc/%d/%cid_map", pid
,
3351 idtype
== ID_TYPE_UID
? 'u' : 'g');
3352 if (ret
< 0 || ret
>= MAXPATHLEN
) {
3353 ERROR("failed to create path \"%s\"", path
);
3357 fd
= open(path
, O_WRONLY
);
3359 SYSERROR("failed to open \"%s\"", path
);
3364 ret
= lxc_write_nointr(fd
, buf
, buf_size
);
3365 if (ret
!= buf_size
) {
3366 SYSERROR("failed to write %cid mapping to \"%s\"",
3367 idtype
== ID_TYPE_UID
? 'u' : 'g', path
);
3376 /* Check whether a binary exist and has either CAP_SETUID, CAP_SETGID or both.
3378 * @return 1 if functional binary was found
3379 * @return 0 if binary exists but is lacking privilege
3380 * @return -ENOENT if binary does not exist
3381 * @return -EINVAL if cap to check is neither CAP_SETUID nor CAP_SETGID
3384 static int idmaptool_on_path_and_privileged(const char *binary
, cap_value_t cap
)
3391 if (cap
!= CAP_SETUID
&& cap
!= CAP_SETGID
)
3394 path
= on_path(binary
, NULL
);
3398 ret
= stat(path
, &st
);
3404 /* Check if the binary is setuid. */
3405 if (st
.st_mode
& S_ISUID
) {
3406 DEBUG("The binary \"%s\" does have the setuid bit set.", path
);
3411 #if HAVE_LIBCAP && LIBCAP_SUPPORTS_FILE_CAPABILITIES
3412 /* Check if it has the CAP_SETUID capability. */
3413 if ((cap
& CAP_SETUID
) &&
3414 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_EFFECTIVE
) &&
3415 lxc_file_cap_is_set(path
, CAP_SETUID
, CAP_PERMITTED
)) {
3416 DEBUG("The binary \"%s\" has CAP_SETUID in its CAP_EFFECTIVE "
3417 "and CAP_PERMITTED sets.", path
);
3422 /* Check if it has the CAP_SETGID capability. */
3423 if ((cap
& CAP_SETGID
) &&
3424 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_EFFECTIVE
) &&
3425 lxc_file_cap_is_set(path
, CAP_SETGID
, CAP_PERMITTED
)) {
3426 DEBUG("The binary \"%s\" has CAP_SETGID in its CAP_EFFECTIVE "
3427 "and CAP_PERMITTED sets.", path
);
3432 /* If we cannot check for file capabilities we need to give the benefit
3433 * of the doubt. Otherwise we might fail even though all the necessary
3434 * file capabilities are set.
3436 DEBUG("Cannot check for file capabilites as full capability support is "
3437 "missing. Manual intervention needed.");
3446 int lxc_map_ids_exec_wrapper(void *args
)
3448 execl("/bin/sh", "sh", "-c", (char *)args
, (char *)NULL
);
3452 int lxc_map_ids(struct lxc_list
*idmap
, pid_t pid
)
3455 struct lxc_list
*iterator
;
3460 char cmd_output
[MAXPATHLEN
];
3461 /* strlen("new@idmap") = 9
3469 * We add some additional space to make sure that we really have
3470 * LXC_IDMAPLEN bytes available for our the {g,u]id mapping.
3472 char mapbuf
[9 + 1 + LXC_NUMSTRLEN64
+ 1 + LXC_IDMAPLEN
] = {0};
3473 int ret
= 0, uidmap
= 0, gidmap
= 0;
3474 bool use_shadow
= false, had_entry
= false;
3476 /* If new{g,u}idmap exists, that is, if shadow is handing out subuid
3477 * ranges, then insist that root also reserve ranges in subuid. This
3478 * will protected it by preventing another user from being handed the
3481 uidmap
= idmaptool_on_path_and_privileged("newuidmap", CAP_SETUID
);
3482 if (uidmap
== -ENOENT
)
3483 WARN("newuidmap binary is missing");
3485 WARN("newuidmap is lacking necessary privileges");
3487 gidmap
= idmaptool_on_path_and_privileged("newgidmap", CAP_SETGID
);
3488 if (gidmap
== -ENOENT
)
3489 WARN("newgidmap binary is missing");
3491 WARN("newgidmap is lacking necessary privileges");
3493 if (uidmap
> 0 && gidmap
> 0) {
3494 DEBUG("Functional newuidmap and newgidmap binary found.");
3497 /* In case unprivileged users run application containers via
3498 * execute() or a start*() there are valid cases where they may
3499 * only want to map their own {g,u}id. Let's not block them from
3500 * doing so by requiring geteuid() == 0.
3502 DEBUG("No newuidmap and newgidmap binary found. Trying to "
3503 "write directly with euid %d.", geteuid());
3506 for (type
= ID_TYPE_UID
, u_or_g
= 'u'; type
<= ID_TYPE_GID
;
3507 type
++, u_or_g
= 'g') {
3511 pos
+= sprintf(mapbuf
, "new%cidmap %d", u_or_g
, pid
);
3513 lxc_list_for_each(iterator
, idmap
) {
3514 /* The kernel only takes <= 4k for writes to
3515 * /proc/<nr>/[ug]id_map
3517 map
= iterator
->elem
;
3518 if (map
->idtype
!= type
)
3523 left
= LXC_IDMAPLEN
- (pos
- mapbuf
);
3524 fill
= snprintf(pos
, left
, "%s%lu %lu %lu%s",
3525 use_shadow
? " " : "", map
->nsid
,
3526 map
->hostid
, map
->range
,
3527 use_shadow
? "" : "\n");
3528 if (fill
<= 0 || fill
>= left
)
3529 SYSERROR("Too many {g,u}id mappings defined.");
3536 /* Try to catch the ouput of new{g,u}idmap to make debugging
3540 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3541 lxc_map_ids_exec_wrapper
,
3544 ERROR("new%cidmap failed to write mapping: %s",
3545 u_or_g
, cmd_output
);
3549 ret
= write_id_mapping(type
, pid
, mapbuf
, pos
- mapbuf
);
3554 memset(mapbuf
, 0, sizeof(mapbuf
));
3561 * return the host uid/gid to which the container root is mapped in
3563 * Return true if id was found, false otherwise.
3565 bool get_mapped_rootid(struct lxc_conf
*conf
, enum idtype idtype
,
3568 struct lxc_list
*it
;
3571 lxc_list_for_each(it
, &conf
->id_map
) {
3573 if (map
->idtype
!= idtype
)
3583 int mapped_hostid(unsigned id
, struct lxc_conf
*conf
, enum idtype idtype
)
3585 struct lxc_list
*it
;
3587 lxc_list_for_each(it
, &conf
->id_map
) {
3589 if (map
->idtype
!= idtype
)
3591 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
)
3592 return (id
- map
->hostid
) + map
->nsid
;
3597 int find_unmapped_nsid(struct lxc_conf
*conf
, enum idtype idtype
)
3599 struct lxc_list
*it
;
3601 unsigned int freeid
= 0;
3603 lxc_list_for_each(it
, &conf
->id_map
) {
3605 if (map
->idtype
!= idtype
)
3607 if (freeid
>= map
->nsid
&& freeid
< map
->nsid
+ map
->range
) {
3608 freeid
= map
->nsid
+ map
->range
;
3615 int lxc_find_gateway_addresses(struct lxc_handler
*handler
)
3617 struct lxc_list
*network
= &handler
->conf
->network
;
3618 struct lxc_list
*iterator
;
3619 struct lxc_netdev
*netdev
;
3622 lxc_list_for_each(iterator
, network
) {
3623 netdev
= iterator
->elem
;
3625 if (!netdev
->ipv4_gateway_auto
&& !netdev
->ipv6_gateway_auto
)
3628 if (netdev
->type
!= LXC_NET_VETH
&& netdev
->type
!= LXC_NET_MACVLAN
) {
3629 ERROR("gateway = auto only supported for "
3630 "veth and macvlan");
3634 if (!netdev
->link
) {
3635 ERROR("gateway = auto needs a link interface");
3639 link_index
= if_nametoindex(netdev
->link
);
3643 if (netdev
->ipv4_gateway_auto
) {
3644 if (lxc_ipv4_addr_get(link_index
, &netdev
->ipv4_gateway
)) {
3645 ERROR("failed to automatically find ipv4 gateway "
3646 "address from link interface '%s'", netdev
->link
);
3651 if (netdev
->ipv6_gateway_auto
) {
3652 if (lxc_ipv6_addr_get(link_index
, &netdev
->ipv6_gateway
)) {
3653 ERROR("failed to automatically find ipv6 gateway "
3654 "address from link interface '%s'", netdev
->link
);
3663 int lxc_create_tty(const char *name
, struct lxc_conf
*conf
)
3665 struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
3668 /* no tty in the configuration */
3672 tty_info
->pty_info
= malloc(sizeof(*tty_info
->pty_info
) * conf
->tty
);
3673 if (!tty_info
->pty_info
) {
3674 SYSERROR("failed to allocate struct *pty_info");
3678 for (i
= 0; i
< conf
->tty
; i
++) {
3679 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
3682 ret
= openpty(&pty_info
->master
, &pty_info
->slave
,
3683 pty_info
->name
, NULL
, NULL
);
3686 SYSERROR("failed to create pty device number %d", i
);
3687 tty_info
->nbtty
= i
;
3688 lxc_delete_tty(tty_info
);
3692 DEBUG("allocated pty \"%s\" with master fd %d and slave fd %d",
3693 pty_info
->name
, pty_info
->master
, pty_info
->slave
);
3695 /* Prevent leaking the file descriptors to the container */
3696 ret
= fcntl(pty_info
->master
, F_SETFD
, FD_CLOEXEC
);
3698 WARN("failed to set FD_CLOEXEC flag on master fd %d of "
3699 "pty device \"%s\": %s",
3700 pty_info
->master
, pty_info
->name
, strerror(errno
));
3702 ret
= fcntl(pty_info
->slave
, F_SETFD
, FD_CLOEXEC
);
3704 WARN("failed to set FD_CLOEXEC flag on slave fd %d of "
3705 "pty device \"%s\": %s",
3706 pty_info
->slave
, pty_info
->name
, strerror(errno
));
3711 tty_info
->nbtty
= conf
->tty
;
3713 INFO("finished allocating %d pts devices", conf
->tty
);
3717 void lxc_delete_tty(struct lxc_tty_info
*tty_info
)
3721 for (i
= 0; i
< tty_info
->nbtty
; i
++) {
3722 struct lxc_pty_info
*pty_info
= &tty_info
->pty_info
[i
];
3724 close(pty_info
->master
);
3725 close(pty_info
->slave
);
3728 free(tty_info
->pty_info
);
3729 tty_info
->pty_info
= NULL
;
3730 tty_info
->nbtty
= 0;
3734 int chown_mapped_root_exec_wrapper(void *args
)
3736 execvp("lxc-usernsexec", args
);
3741 * chown_mapped_root: for an unprivileged user with uid/gid X to
3742 * chown a dir to subuid/subgid Y, he needs to run chown as root
3743 * in a userns where nsid 0 is mapped to hostuid/hostgid Y, and
3744 * nsid Y is mapped to hostuid/hostgid X. That way, the container
3745 * root is privileged with respect to hostuid/hostgid X, allowing
3746 * him to do the chown.
3748 int chown_mapped_root(char *path
, struct lxc_conf
*conf
)
3750 uid_t rootuid
, rootgid
;
3752 char *chownpath
= path
;
3753 int hostuid
, hostgid
, ret
;
3755 char map1
[100], map2
[100], map3
[100], map4
[100], map5
[100];
3757 char *args1
[] = {"lxc-usernsexec",
3762 "--", "chown", ugid
, path
,
3764 char *args2
[] = {"lxc-usernsexec",
3770 "--", "chown", ugid
, path
,
3772 char cmd_output
[MAXPATHLEN
];
3774 hostuid
= geteuid();
3775 hostgid
= getegid();
3777 if (!get_mapped_rootid(conf
, ID_TYPE_UID
, &val
)) {
3778 ERROR("No uid mapping for container root");
3781 rootuid
= (uid_t
)val
;
3782 if (!get_mapped_rootid(conf
, ID_TYPE_GID
, &val
)) {
3783 ERROR("No gid mapping for container root");
3786 rootgid
= (gid_t
)val
;
3789 * In case of overlay, we want only the writeable layer to be chowned
3791 if (strncmp(path
, "overlayfs:", 10) == 0 || strncmp(path
, "aufs:", 5) == 0) {
3792 chownpath
= strchr(path
, ':');
3794 ERROR("Bad overlay path: %s", path
);
3797 chownpath
= strchr(chownpath
+ 1, ':');
3799 ERROR("Bad overlay path: %s", path
);
3806 if (chown(path
, rootuid
, rootgid
) < 0) {
3807 ERROR("Error chowning %s", path
);
3813 if (rootuid
== hostuid
) {
3815 INFO("%s: container root is our uid; no need to chown" ,__func__
);
3819 /* save the current gid of "path" */
3820 if (stat(path
, &sb
) < 0) {
3821 ERROR("Error stat %s", path
);
3825 /* Update the path argument in case this was overlayfs. */
3826 args1
[sizeof(args1
) / sizeof(args1
[0]) - 2] = path
;
3827 args2
[sizeof(args2
) / sizeof(args2
[0]) - 2] = path
;
3830 * A file has to be group-owned by a gid mapped into the
3831 * container, or the container won't be privileged over it.
3833 DEBUG("trying to chown \"%s\" to %d", path
, hostgid
);
3834 if (sb
.st_uid
== hostuid
&&
3835 mapped_hostid(sb
.st_gid
, conf
, ID_TYPE_GID
) < 0 &&
3836 chown(path
, -1, hostgid
) < 0) {
3837 ERROR("Failed chgrping %s", path
);
3842 ret
= snprintf(map1
, 100, "u:0:%d:1", rootuid
);
3843 if (ret
< 0 || ret
>= 100) {
3844 ERROR("Error uid printing map string");
3848 // "u:hostuid:hostuid:1"
3849 ret
= snprintf(map2
, 100, "u:%d:%d:1", hostuid
, hostuid
);
3850 if (ret
< 0 || ret
>= 100) {
3851 ERROR("Error uid printing map string");
3856 ret
= snprintf(map3
, 100, "g:0:%d:1", rootgid
);
3857 if (ret
< 0 || ret
>= 100) {
3858 ERROR("Error gid printing map string");
3862 // "g:pathgid:rootgid+pathgid:1"
3863 ret
= snprintf(map4
, 100, "g:%d:%d:1", (gid_t
)sb
.st_gid
,
3864 rootgid
+ (gid_t
)sb
.st_gid
);
3865 if (ret
< 0 || ret
>= 100) {
3866 ERROR("Error gid printing map string");
3870 // "g:hostgid:hostgid:1"
3871 ret
= snprintf(map5
, 100, "g:%d:%d:1", hostgid
, hostgid
);
3872 if (ret
< 0 || ret
>= 100) {
3873 ERROR("Error gid printing map string");
3877 // "0:pathgid" (chown)
3878 ret
= snprintf(ugid
, 100, "0:%d", (gid_t
)sb
.st_gid
);
3879 if (ret
< 0 || ret
>= 100) {
3880 ERROR("Error owner printing format string for chown");
3884 if (hostgid
== sb
.st_gid
)
3885 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3886 chown_mapped_root_exec_wrapper
,
3889 ret
= run_command(cmd_output
, sizeof(cmd_output
),
3890 chown_mapped_root_exec_wrapper
,
3893 ERROR("lxc-usernsexec failed: %s", cmd_output
);
3898 int lxc_ttys_shift_ids(struct lxc_conf
*c
)
3900 if (lxc_list_empty(&c
->id_map
))
3903 if (!strcmp(c
->console
.name
, ""))
3906 if (chown_mapped_root(c
->console
.name
, c
) < 0) {
3907 ERROR("failed to chown console \"%s\"", c
->console
.name
);
3911 TRACE("chowned console \"%s\"", c
->console
.name
);
3916 /* NOTE: Must not be called from inside the container namespace! */
3917 int lxc_create_tmp_proc_mount(struct lxc_conf
*conf
)
3921 mounted
= lxc_mount_proc_if_needed(conf
->rootfs
.path
? conf
->rootfs
.mount
: "");
3922 if (mounted
== -1) {
3923 SYSERROR("failed to mount /proc in the container");
3924 /* continue only if there is no rootfs */
3925 if (conf
->rootfs
.path
)
3927 } else if (mounted
== 1) {
3928 conf
->tmp_umount_proc
= 1;
3934 void tmp_proc_unmount(struct lxc_conf
*lxc_conf
)
3936 if (lxc_conf
->tmp_umount_proc
== 1) {
3938 lxc_conf
->tmp_umount_proc
= 0;
3942 void remount_all_slave(void)
3944 /* walk /proc/mounts and change any shared entries to slave */
3945 FILE *f
= fopen("/proc/self/mountinfo", "r");
3950 SYSERROR("Failed to open /proc/self/mountinfo to mark all shared");
3951 ERROR("Continuing container startup...");
3955 while (getline(&line
, &len
, f
) != -1) {
3956 char *target
, *opts
;
3957 target
= get_field(line
, 4);
3960 opts
= get_field(target
, 2);
3963 null_endofword(opts
);
3964 if (!strstr(opts
, "shared"))
3966 null_endofword(target
);
3967 if (mount(NULL
, target
, NULL
, MS_SLAVE
, NULL
)) {
3968 SYSERROR("Failed to make %s rslave", target
);
3969 ERROR("Continuing...");
3976 void lxc_execute_bind_init(struct lxc_conf
*conf
)
3979 char path
[PATH_MAX
], destpath
[PATH_MAX
], *p
;
3981 /* If init exists in the container, don't bind mount a static one */
3982 p
= choose_init(conf
->rootfs
.mount
);
3988 ret
= snprintf(path
, PATH_MAX
, SBINDIR
"/init.lxc.static");
3989 if (ret
< 0 || ret
>= PATH_MAX
) {
3990 WARN("Path name too long searching for lxc.init.static");
3994 if (!file_exists(path
)) {
3995 INFO("%s does not exist on host", path
);
3999 ret
= snprintf(destpath
, PATH_MAX
, "%s%s", conf
->rootfs
.mount
, "/init.lxc.static");
4000 if (ret
< 0 || ret
>= PATH_MAX
) {
4001 WARN("Path name too long for container's lxc.init.static");
4005 if (!file_exists(destpath
)) {
4006 FILE * pathfile
= fopen(destpath
, "wb");
4008 SYSERROR("Failed to create mount target '%s'", destpath
);
4014 ret
= safe_mount(path
, destpath
, "none", MS_BIND
, NULL
, conf
->rootfs
.mount
);
4016 SYSERROR("Failed to bind lxc.init.static into container");
4017 INFO("lxc.init.static bound into container at %s", path
);
4021 * This does the work of remounting / if it is shared, calling the
4022 * container pre-mount hooks, and mounting the rootfs.
4024 int do_rootfs_setup(struct lxc_conf
*conf
, const char *name
, const char *lxcpath
)
4026 if (conf
->rootfs_setup
) {
4028 * rootfs was set up in another namespace. bind-mount it
4029 * to give us a mount in our own ns so we can pivot_root to it
4031 const char *path
= conf
->rootfs
.mount
;
4032 if (mount(path
, path
, "rootfs", MS_BIND
, NULL
) < 0) {
4033 ERROR("Failed to bind-mount container / onto itself");
4039 remount_all_slave();
4041 if (run_lxc_hooks(name
, "pre-mount", conf
, lxcpath
, NULL
)) {
4042 ERROR("failed to run pre-mount hooks for container '%s'.", name
);
4046 if (lxc_setup_rootfs(conf
)) {
4047 ERROR("failed to setup rootfs for '%s'", name
);
4051 conf
->rootfs_setup
= true;
4055 static bool verify_start_hooks(struct lxc_conf
*conf
)
4057 struct lxc_list
*it
;
4058 char path
[MAXPATHLEN
];
4059 lxc_list_for_each(it
, &conf
->hooks
[LXCHOOK_START
]) {
4060 char *hookname
= it
->elem
;
4064 ret
= snprintf(path
, MAXPATHLEN
, "%s%s",
4065 conf
->rootfs
.path
? conf
->rootfs
.mount
: "", hookname
);
4066 if (ret
< 0 || ret
>= MAXPATHLEN
)
4068 ret
= stat(path
, &st
);
4070 SYSERROR("Start hook %s not found in container",
4080 static int lxc_send_ttys_to_parent(struct lxc_handler
*handler
)
4084 struct lxc_pty_info
*pty_info
;
4085 struct lxc_conf
*conf
= handler
->conf
;
4086 const struct lxc_tty_info
*tty_info
= &conf
->tty_info
;
4087 int sock
= handler
->ttysock
[0];
4089 size_t num_ttyfds
= (2 * conf
->tty
);
4091 ttyfds
= malloc(num_ttyfds
* sizeof(int));
4095 for (i
= 0; i
< num_ttyfds
; i
++) {
4096 pty_info
= &tty_info
->pty_info
[i
/ 2];
4097 ttyfds
[i
++] = pty_info
->slave
;
4098 ttyfds
[i
] = pty_info
->master
;
4099 TRACE("send pty \"%s\" with master fd %d and slave fd %d to "
4101 pty_info
->name
, pty_info
->master
, pty_info
->slave
);
4104 ret
= lxc_abstract_unix_send_fds(sock
, ttyfds
, num_ttyfds
, NULL
, 0);
4106 ERROR("failed to send %d ttys to parent: %s", conf
->tty
,
4109 TRACE("sent %d ttys to parent", conf
->tty
);
4111 close(handler
->ttysock
[0]);
4112 close(handler
->ttysock
[1]);
4114 for (i
= 0; i
< num_ttyfds
; i
++)
4122 int lxc_setup(struct lxc_handler
*handler
)
4124 const char *name
= handler
->name
;
4125 struct lxc_conf
*lxc_conf
= handler
->conf
;
4126 const char *lxcpath
= handler
->lxcpath
;
4128 if (do_rootfs_setup(lxc_conf
, name
, lxcpath
) < 0) {
4129 ERROR("Error setting up rootfs mount after spawn");
4133 if (lxc_conf
->inherit_ns_fd
[LXC_NS_UTS
] == -1) {
4134 if (setup_utsname(lxc_conf
->utsname
)) {
4135 ERROR("failed to setup the utsname for '%s'", name
);
4140 if (lxc_setup_networks_in_child_namespaces(lxc_conf
,
4141 &lxc_conf
->network
)) {
4142 ERROR("failed to setup the network for '%s'", name
);
4146 if (lxc_conf
->autodev
> 0) {
4147 if (mount_autodev(name
, &lxc_conf
->rootfs
, lxcpath
)) {
4148 ERROR("failed to mount /dev in the container");
4153 /* do automatic mounts (mainly /proc and /sys), but exclude
4154 * those that need to wait until other stuff has finished
4156 if (lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& ~LXC_AUTO_CGROUP_MASK
, handler
) < 0) {
4157 ERROR("failed to setup the automatic mounts for '%s'", name
);
4161 if (setup_mount(&lxc_conf
->rootfs
, lxc_conf
->fstab
, name
, lxcpath
)) {
4162 ERROR("failed to setup the mounts for '%s'", name
);
4166 if (!lxc_list_empty(&lxc_conf
->mount_list
) && setup_mount_entries(&lxc_conf
->rootfs
, &lxc_conf
->mount_list
, name
, lxcpath
)) {
4167 ERROR("failed to setup the mount entries for '%s'", name
);
4171 /* Make sure any start hooks are in the container */
4172 if (!verify_start_hooks(lxc_conf
))
4175 if (lxc_conf
->is_execute
)
4176 lxc_execute_bind_init(lxc_conf
);
4178 /* now mount only cgroup, if wanted;
4179 * before, /sys could not have been mounted
4180 * (is either mounted automatically or via fstab entries)
4182 if (lxc_mount_auto_mounts(lxc_conf
, lxc_conf
->auto_mounts
& LXC_AUTO_CGROUP_MASK
, handler
) < 0) {
4183 ERROR("failed to setup the automatic mounts for '%s'", name
);
4187 if (run_lxc_hooks(name
, "mount", lxc_conf
, lxcpath
, NULL
)) {
4188 ERROR("failed to run mount hooks for container '%s'.", name
);
4192 if (lxc_conf
->autodev
> 0) {
4193 if (run_lxc_hooks(name
, "autodev", lxc_conf
, lxcpath
, NULL
)) {
4194 ERROR("failed to run autodev hooks for container '%s'.", name
);
4197 if (lxc_fill_autodev(&lxc_conf
->rootfs
)) {
4198 ERROR("failed to populate /dev in the container");
4203 if (!lxc_conf
->is_execute
&& lxc_setup_console(&lxc_conf
->rootfs
, &lxc_conf
->console
, lxc_conf
->ttydir
)) {
4204 ERROR("failed to setup the console for '%s'", name
);
4208 if (lxc_conf
->kmsg
) {
4209 if (setup_kmsg(&lxc_conf
->rootfs
, &lxc_conf
->console
)) // don't fail
4210 ERROR("failed to setup kmsg for '%s'", name
);
4213 if (!lxc_conf
->is_execute
&& setup_dev_symlinks(&lxc_conf
->rootfs
)) {
4214 ERROR("failed to setup /dev symlinks for '%s'", name
);
4218 /* mount /proc if it's not already there */
4219 if (lxc_create_tmp_proc_mount(lxc_conf
) < 0) {
4220 ERROR("failed to LSM mount proc for '%s'", name
);
4224 if (setup_pivot_root(&lxc_conf
->rootfs
)) {
4225 ERROR("failed to set rootfs for '%s'", name
);
4229 if (lxc_setup_devpts(lxc_conf
->pts
)) {
4230 ERROR("failed to setup the new pts instance");
4234 if (lxc_create_tty(name
, lxc_conf
)) {
4235 ERROR("failed to create the ttys");
4239 if (lxc_send_ttys_to_parent(handler
) < 0) {
4240 ERROR("failure sending console info to parent");
4244 if (!lxc_conf
->is_execute
&& lxc_setup_tty(lxc_conf
)) {
4245 ERROR("failed to setup the ttys for '%s'", name
);
4249 if (lxc_conf
->pty_names
&& setenv("container_ttys", lxc_conf
->pty_names
, 1))
4250 SYSERROR("failed to set environment variable for container ptys");
4253 if (setup_personality(lxc_conf
->personality
)) {
4254 ERROR("failed to setup personality");
4258 if (!lxc_list_empty(&lxc_conf
->keepcaps
)) {
4259 if (!lxc_list_empty(&lxc_conf
->caps
)) {
4260 ERROR("Container requests lxc.cap.drop and lxc.cap.keep: either use lxc.cap.drop or lxc.cap.keep, not both.");
4263 if (dropcaps_except(&lxc_conf
->keepcaps
)) {
4264 ERROR("failed to keep requested caps");
4267 } else if (setup_caps(&lxc_conf
->caps
)) {
4268 ERROR("failed to drop capabilities");
4272 NOTICE("'%s' is setup.", name
);
4277 int run_lxc_hooks(const char *name
, char *hook
, struct lxc_conf
*conf
,
4278 const char *lxcpath
, char *argv
[])
4281 struct lxc_list
*it
;
4283 if (strcmp(hook
, "pre-start") == 0)
4284 which
= LXCHOOK_PRESTART
;
4285 else if (strcmp(hook
, "pre-mount") == 0)
4286 which
= LXCHOOK_PREMOUNT
;
4287 else if (strcmp(hook
, "mount") == 0)
4288 which
= LXCHOOK_MOUNT
;
4289 else if (strcmp(hook
, "autodev") == 0)
4290 which
= LXCHOOK_AUTODEV
;
4291 else if (strcmp(hook
, "start") == 0)
4292 which
= LXCHOOK_START
;
4293 else if (strcmp(hook
, "stop") == 0)
4294 which
= LXCHOOK_STOP
;
4295 else if (strcmp(hook
, "post-stop") == 0)
4296 which
= LXCHOOK_POSTSTOP
;
4297 else if (strcmp(hook
, "clone") == 0)
4298 which
= LXCHOOK_CLONE
;
4299 else if (strcmp(hook
, "destroy") == 0)
4300 which
= LXCHOOK_DESTROY
;
4303 lxc_list_for_each(it
, &conf
->hooks
[which
]) {
4305 char *hookname
= it
->elem
;
4306 ret
= run_script_argv(name
, "lxc", hookname
, hook
, lxcpath
, argv
);
4313 int lxc_clear_config_caps(struct lxc_conf
*c
)
4315 struct lxc_list
*it
,*next
;
4317 lxc_list_for_each_safe(it
, &c
->caps
, next
) {
4325 static int lxc_free_idmap(struct lxc_list
*id_map
) {
4326 struct lxc_list
*it
, *next
;
4328 lxc_list_for_each_safe(it
, id_map
, next
) {
4336 int lxc_clear_idmaps(struct lxc_conf
*c
)
4338 return lxc_free_idmap(&c
->id_map
);
4341 int lxc_clear_config_keepcaps(struct lxc_conf
*c
)
4343 struct lxc_list
*it
,*next
;
4345 lxc_list_for_each_safe(it
, &c
->keepcaps
, next
) {
4353 int lxc_clear_cgroups(struct lxc_conf
*c
, const char *key
)
4355 struct lxc_list
*it
,*next
;
4357 const char *k
= NULL
;
4359 if (strcmp(key
, "lxc.cgroup") == 0)
4361 else if (strncmp(key
, "lxc.cgroup.", sizeof("lxc.cgroup.")-1) == 0)
4362 k
= key
+ sizeof("lxc.cgroup.")-1;
4366 lxc_list_for_each_safe(it
, &c
->cgroup
, next
) {
4367 struct lxc_cgroup
*cg
= it
->elem
;
4368 if (!all
&& strcmp(cg
->subsystem
, k
) != 0)
4371 free(cg
->subsystem
);
4379 int lxc_clear_limits(struct lxc_conf
*c
, const char *key
)
4381 struct lxc_list
*it
, *next
;
4383 const char *k
= NULL
;
4385 if (strcmp(key
, "lxc.limit") == 0)
4387 else if (strncmp(key
, "lxc.limit.", sizeof("lxc.limit.")-1) == 0)
4388 k
= key
+ sizeof("lxc.limit.")-1;
4392 lxc_list_for_each_safe(it
, &c
->limits
, next
) {
4393 struct lxc_limit
*lim
= it
->elem
;
4394 if (!all
&& strcmp(lim
->resource
, k
) != 0)
4397 free(lim
->resource
);
4404 int lxc_clear_groups(struct lxc_conf
*c
)
4406 struct lxc_list
*it
,*next
;
4408 lxc_list_for_each_safe(it
, &c
->groups
, next
) {
4416 int lxc_clear_environment(struct lxc_conf
*c
)
4418 struct lxc_list
*it
,*next
;
4420 lxc_list_for_each_safe(it
, &c
->environment
, next
) {
4429 int lxc_clear_mount_entries(struct lxc_conf
*c
)
4431 struct lxc_list
*it
,*next
;
4433 lxc_list_for_each_safe(it
, &c
->mount_list
, next
) {
4441 int lxc_clear_automounts(struct lxc_conf
*c
)
4447 int lxc_clear_hooks(struct lxc_conf
*c
, const char *key
)
4449 struct lxc_list
*it
,*next
;
4450 bool all
= false, done
= false;
4451 const char *k
= NULL
;
4454 if (strcmp(key
, "lxc.hook") == 0)
4456 else if (strncmp(key
, "lxc.hook.", sizeof("lxc.hook.")-1) == 0)
4457 k
= key
+ sizeof("lxc.hook.")-1;
4461 for (i
=0; i
<NUM_LXC_HOOKS
; i
++) {
4462 if (all
|| strcmp(k
, lxchook_names
[i
]) == 0) {
4463 lxc_list_for_each_safe(it
, &c
->hooks
[i
], next
) {
4473 ERROR("Invalid hook key: %s", key
);
4479 static void lxc_clear_saved_nics(struct lxc_conf
*conf
)
4483 if (!conf
->saved_nics
)
4485 for (i
=0; i
< conf
->num_savednics
; i
++)
4486 free(conf
->saved_nics
[i
].orig_name
);
4487 free(conf
->saved_nics
);
4490 static inline void lxc_clear_aliens(struct lxc_conf
*conf
)
4492 struct lxc_list
*it
,*next
;
4494 lxc_list_for_each_safe(it
, &conf
->aliens
, next
) {
4501 void lxc_clear_includes(struct lxc_conf
*conf
)
4503 struct lxc_list
*it
,*next
;
4505 lxc_list_for_each_safe(it
, &conf
->includes
, next
) {
4512 void lxc_conf_free(struct lxc_conf
*conf
)
4516 if (current_config
== conf
)
4517 current_config
= NULL
;
4518 free(conf
->console
.log_path
);
4519 free(conf
->console
.path
);
4520 free(conf
->rootfs
.mount
);
4521 free(conf
->rootfs
.bdev_type
);
4522 free(conf
->rootfs
.options
);
4523 free(conf
->rootfs
.path
);
4524 free(conf
->logfile
);
4525 if (conf
->logfd
!= -1)
4527 free(conf
->utsname
);
4531 free(conf
->init_cmd
);
4532 free(conf
->unexpanded_config
);
4533 free(conf
->pty_names
);
4535 lxc_free_networks(&conf
->network
);
4536 free(conf
->lsm_aa_profile
);
4537 free(conf
->lsm_se_context
);
4538 lxc_seccomp_free(conf
);
4539 lxc_clear_config_caps(conf
);
4540 lxc_clear_config_keepcaps(conf
);
4541 lxc_clear_cgroups(conf
, "lxc.cgroup");
4542 lxc_clear_hooks(conf
, "lxc.hook");
4543 lxc_clear_mount_entries(conf
);
4544 lxc_clear_saved_nics(conf
);
4545 lxc_clear_idmaps(conf
);
4546 lxc_clear_groups(conf
);
4547 lxc_clear_includes(conf
);
4548 lxc_clear_aliens(conf
);
4549 lxc_clear_environment(conf
);
4550 lxc_clear_limits(conf
, "lxc.limit");
4554 struct userns_fn_data
{
4556 const char *fn_name
;
4561 static int run_userns_fn(void *data
)
4563 struct userns_fn_data
*d
= data
;
4566 /* Close write end of the pipe. */
4569 /* Wait for parent to finish establishing a new mapping in the user
4570 * namespace we are executing in.
4572 if (read(d
->p
[0], &c
, 1) != 1)
4575 /* Close read end of the pipe. */
4579 TRACE("calling function \"%s\"", d
->fn_name
);
4580 /* Call function to run. */
4581 return d
->fn(d
->arg
);
4584 static struct id_map
*mapped_hostid_entry(struct lxc_conf
*conf
, unsigned id
,
4587 struct lxc_list
*it
;
4589 struct id_map
*retmap
= NULL
;
4591 lxc_list_for_each(it
, &conf
->id_map
) {
4593 if (map
->idtype
!= idtype
)
4596 if (id
>= map
->hostid
&& id
< map
->hostid
+ map
->range
) {
4605 retmap
= malloc(sizeof(*retmap
));
4609 memcpy(retmap
, map
, sizeof(*retmap
));
4614 * Allocate a new {g,u}id mapping for the given {g,u}id. Re-use an already
4615 * existing one or establish a new one.
4617 static struct id_map
*idmap_add(struct lxc_conf
*conf
, uid_t id
, enum idtype type
)
4620 struct id_map
*entry
= NULL
;
4622 /* Reuse existing mapping. */
4623 entry
= mapped_hostid_entry(conf
, id
, type
);
4627 /* Find new mapping. */
4628 hostid_mapped
= find_unmapped_nsid(conf
, type
);
4629 if (hostid_mapped
< 0) {
4630 DEBUG("failed to find free mapping for id %d", id
);
4634 entry
= malloc(sizeof(*entry
));
4638 entry
->idtype
= type
;
4639 entry
->nsid
= hostid_mapped
;
4640 entry
->hostid
= (unsigned long)id
;
4646 /* Run a function in a new user namespace.
4647 * The caller's euid/egid will be mapped if it is not already.
4648 * Afaict, userns_exec_1() is only used to operate based on privileges for the
4649 * user's own {g,u}id on the host and for the container root's unmapped {g,u}id.
4650 * This means we require only to establish a mapping from:
4651 * - the container root {g,u}id as seen from the host > user's host {g,u}id
4652 * - the container root -> some sub{g,u}id
4653 * The former we add, if the user did not specifiy a mapping. The latter we
4654 * retrieve from the ontainer's configured {g,u}id mappings as it must have been
4655 * there to start the container in the first place.
4657 int userns_exec_1(struct lxc_conf
*conf
, int (*fn
)(void *), void *data
,
4658 const char *fn_name
)
4662 struct userns_fn_data d
;
4664 struct lxc_list
*it
;
4668 struct lxc_list
*idmap
= NULL
, *tmplist
= NULL
;
4669 struct id_map
*container_root_uid
= NULL
, *container_root_gid
= NULL
,
4670 *host_uid_map
= NULL
, *host_gid_map
= NULL
;
4674 SYSERROR("opening pipe");
4678 d
.fn_name
= fn_name
;
4683 /* Clone child in new user namespace. */
4684 pid
= lxc_clone(run_userns_fn
, &d
, CLONE_NEWUSER
);
4686 ERROR("failed to clone child process in new user namespace");
4693 /* Find container root. */
4694 lxc_list_for_each(it
, &conf
->id_map
) {
4700 if (map
->idtype
== ID_TYPE_UID
&& container_root_uid
== NULL
) {
4701 container_root_uid
= malloc(sizeof(*container_root_uid
));
4702 if (!container_root_uid
)
4704 container_root_uid
->idtype
= map
->idtype
;
4705 container_root_uid
->hostid
= map
->hostid
;
4706 container_root_uid
->nsid
= 0;
4707 container_root_uid
->range
= map
->range
;
4708 } else if (map
->idtype
== ID_TYPE_GID
&& container_root_gid
== NULL
) {
4709 container_root_gid
= malloc(sizeof(*container_root_gid
));
4710 if (!container_root_gid
)
4712 container_root_gid
->idtype
= map
->idtype
;
4713 container_root_gid
->hostid
= map
->hostid
;
4714 container_root_gid
->nsid
= 0;
4715 container_root_gid
->range
= map
->range
;
4718 /* Found container root. */
4719 if (container_root_uid
&& container_root_gid
)
4723 /* This is actually checked earlier but it can't hurt. */
4724 if (!container_root_uid
|| !container_root_gid
) {
4725 ERROR("no mapping for container root found");
4729 host_uid_map
= container_root_uid
;
4730 host_gid_map
= container_root_gid
;
4732 /* Check whether the {g,u}id of the user has a mapping. */
4735 if (euid
!= container_root_uid
->hostid
)
4736 host_uid_map
= idmap_add(conf
, euid
, ID_TYPE_UID
);
4738 if (egid
!= container_root_gid
->hostid
)
4739 host_gid_map
= idmap_add(conf
, egid
, ID_TYPE_GID
);
4741 if (!host_uid_map
) {
4742 DEBUG("failed to find mapping for uid %d", euid
);
4746 if (!host_gid_map
) {
4747 DEBUG("failed to find mapping for gid %d", egid
);
4751 /* Allocate new {g,u}id map list. */
4752 idmap
= malloc(sizeof(*idmap
));
4755 lxc_list_init(idmap
);
4757 /* Add container root to the map. */
4758 tmplist
= malloc(sizeof(*tmplist
));
4761 lxc_list_add_elem(tmplist
, container_root_uid
);
4762 lxc_list_add_tail(idmap
, tmplist
);
4764 if (host_uid_map
&& (host_uid_map
!= container_root_uid
)) {
4765 /* idmap will now keep track of that memory. */
4766 container_root_uid
= NULL
;
4768 /* Add container root to the map. */
4769 tmplist
= malloc(sizeof(*tmplist
));
4772 lxc_list_add_elem(tmplist
, host_uid_map
);
4773 lxc_list_add_tail(idmap
, tmplist
);
4775 /* idmap will now keep track of that memory. */
4776 container_root_uid
= NULL
;
4777 /* idmap will now keep track of that memory. */
4778 host_uid_map
= NULL
;
4780 tmplist
= malloc(sizeof(*tmplist
));
4783 lxc_list_add_elem(tmplist
, container_root_gid
);
4784 lxc_list_add_tail(idmap
, tmplist
);
4786 if (host_gid_map
&& (host_gid_map
!= container_root_gid
)) {
4787 /* idmap will now keep track of that memory. */
4788 container_root_gid
= NULL
;
4790 tmplist
= malloc(sizeof(*tmplist
));
4793 lxc_list_add_elem(tmplist
, host_gid_map
);
4794 lxc_list_add_tail(idmap
, tmplist
);
4796 /* idmap will now keep track of that memory. */
4797 container_root_gid
= NULL
;
4798 /* idmap will now keep track of that memory. */
4799 host_gid_map
= NULL
;
4801 if (lxc_log_get_level() == LXC_LOG_LEVEL_TRACE
||
4802 conf
->loglevel
== LXC_LOG_LEVEL_TRACE
) {
4803 lxc_list_for_each(it
, idmap
) {
4805 TRACE("establishing %cid mapping for \"%d\" in new "
4806 "user namespace: nsuid %lu - hostid %lu - range "
4808 (map
->idtype
== ID_TYPE_UID
) ? 'u' : 'g', pid
,
4809 map
->nsid
, map
->hostid
, map
->range
);
4813 /* Set up {g,u}id mapping for user namespace of child process. */
4814 ret
= lxc_map_ids(idmap
, pid
);
4816 ERROR("error setting up {g,u}id mappings for child process "
4822 /* Tell child to proceed. */
4823 if (write(p
[1], &c
, 1) != 1) {
4824 SYSERROR("failed telling child process \"%d\" to proceed", pid
);
4828 /* Wait for child to finish. */
4829 ret
= wait_for_pid(pid
);
4833 lxc_free_idmap(idmap
);
4834 if (container_root_uid
)
4835 free(container_root_uid
);
4836 if (container_root_gid
)
4837 free(container_root_gid
);
4838 if (host_uid_map
&& (host_uid_map
!= container_root_uid
))
4840 if (host_gid_map
&& (host_gid_map
!= container_root_gid
))
4850 /* not thread-safe, do not use from api without first forking */
4851 static char* getuname(void)
4853 struct passwd
*result
;
4855 result
= getpwuid(geteuid());
4859 return strdup(result
->pw_name
);
4862 /* not thread-safe, do not use from api without first forking */
4863 static char *getgname(void)
4865 struct group
*result
;
4867 result
= getgrgid(getegid());
4871 return strdup(result
->gr_name
);
4874 /* not thread-safe, do not use from api without first forking */
4875 void suggest_default_idmap(void)
4878 unsigned int uid
= 0, urange
= 0, gid
= 0, grange
= 0;
4880 char *uname
, *gname
;
4883 if (!(uname
= getuname()))
4886 if (!(gname
= getgname())) {
4891 f
= fopen(subuidfile
, "r");
4893 ERROR("Your system is not configured with subuids");
4898 while (getline(&line
, &len
, f
) != -1) {
4899 size_t no_newline
= 0;
4900 char *p
= strchr(line
, ':'), *p2
;
4907 if (strcmp(line
, uname
))
4909 p2
= strchr(p
, ':');
4916 no_newline
= strcspn(p2
, "\n");
4917 p2
[no_newline
] = '\0';
4919 if (lxc_safe_uint(p
, &uid
) < 0)
4920 WARN("Could not parse UID.");
4921 if (lxc_safe_uint(p2
, &urange
) < 0)
4922 WARN("Could not parse UID range.");
4926 f
= fopen(subgidfile
, "r");
4928 ERROR("Your system is not configured with subgids");
4933 while (getline(&line
, &len
, f
) != -1) {
4934 size_t no_newline
= 0;
4935 char *p
= strchr(line
, ':'), *p2
;
4942 if (strcmp(line
, uname
))
4944 p2
= strchr(p
, ':');
4951 no_newline
= strcspn(p2
, "\n");
4952 p2
[no_newline
] = '\0';
4954 if (lxc_safe_uint(p
, &gid
) < 0)
4955 WARN("Could not parse GID.");
4956 if (lxc_safe_uint(p2
, &grange
) < 0)
4957 WARN("Could not parse GID range.");
4963 if (!urange
|| !grange
) {
4964 ERROR("You do not have subuids or subgids allocated");
4965 ERROR("Unprivileged containers require subuids and subgids");
4969 ERROR("You must either run as root, or define uid mappings");
4970 ERROR("To pass uid mappings to lxc-create, you could create");
4971 ERROR("~/.config/lxc/default.conf:");
4972 ERROR("lxc.include = %s", LXC_DEFAULT_CONFIG
);
4973 ERROR("lxc.id_map = u 0 %u %u", uid
, urange
);
4974 ERROR("lxc.id_map = g 0 %u %u", gid
, grange
);
4980 static void free_cgroup_settings(struct lxc_list
*result
)
4982 struct lxc_list
*iterator
, *next
;
4984 lxc_list_for_each_safe(iterator
, result
, next
) {
4985 lxc_list_del(iterator
);
4992 * Return the list of cgroup_settings sorted according to the following rules
4993 * 1. Put memory.limit_in_bytes before memory.memsw.limit_in_bytes
4995 struct lxc_list
*sort_cgroup_settings(struct lxc_list
* cgroup_settings
)
4997 struct lxc_list
*result
;
4998 struct lxc_list
*memsw_limit
= NULL
;
4999 struct lxc_list
*it
= NULL
;
5000 struct lxc_cgroup
*cg
= NULL
;
5001 struct lxc_list
*item
= NULL
;
5003 result
= malloc(sizeof(*result
));
5005 ERROR("failed to allocate memory to sort cgroup settings");
5008 lxc_list_init(result
);
5010 /*Iterate over the cgroup settings and copy them to the output list*/
5011 lxc_list_for_each(it
, cgroup_settings
) {
5012 item
= malloc(sizeof(*item
));
5014 ERROR("failed to allocate memory to sort cgroup settings");
5015 free_cgroup_settings(result
);
5018 item
->elem
= it
->elem
;
5020 if (strcmp(cg
->subsystem
, "memory.memsw.limit_in_bytes") == 0) {
5021 /* Store the memsw_limit location */
5023 } else if (strcmp(cg
->subsystem
, "memory.limit_in_bytes") == 0 && memsw_limit
!= NULL
) {
5024 /* lxc.cgroup.memory.memsw.limit_in_bytes is found before
5025 * lxc.cgroup.memory.limit_in_bytes, swap these two items */
5026 item
->elem
= memsw_limit
->elem
;
5027 memsw_limit
->elem
= it
->elem
;
5029 lxc_list_add_tail(result
, item
);