]>
git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/utils.c
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
26 #define __STDC_FORMAT_MACROS /* Required for PRIu64 to work. */
41 #include <sys/mount.h>
42 #include <sys/param.h>
43 #include <sys/prctl.h>
45 #include <sys/types.h>
50 #include "namespace.h"
55 #include "include/strlcpy.h"
59 #include "include/strlcat.h"
63 #define O_PATH 010000000
67 #define O_NOFOLLOW 00400000
70 lxc_log_define(utils
, lxc
);
73 * if path is btrfs, tries to remove it and any subvolumes beneath it
75 extern bool btrfs_try_remove_subvol(const char *path
);
77 static int _recursive_rmdir(const char *dirname
, dev_t pdev
,
78 const char *exclude
, int level
, bool onedev
)
80 struct dirent
*direntp
;
83 char pathname
[MAXPATHLEN
];
84 bool hadexclude
= false;
86 dir
= opendir(dirname
);
88 ERROR("failed to open %s", dirname
);
92 while ((direntp
= readdir(dir
))) {
96 if (!strcmp(direntp
->d_name
, ".") ||
97 !strcmp(direntp
->d_name
, ".."))
100 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
101 if (rc
< 0 || rc
>= MAXPATHLEN
) {
102 ERROR("pathname too long");
107 if (!level
&& exclude
&& !strcmp(direntp
->d_name
, exclude
)) {
108 ret
= rmdir(pathname
);
112 INFO("Not deleting snapshot %s", pathname
);
116 ret
= unlink(pathname
);
118 INFO("Failed to remove %s", pathname
);
121 SYSERROR("Failed to rmdir %s", pathname
);
129 ret
= lstat(pathname
, &mystat
);
131 ERROR("Failed to stat %s", pathname
);
136 if (onedev
&& mystat
.st_dev
!= pdev
) {
137 /* TODO should we be checking /proc/self/mountinfo for
138 * pathname and not doing this if found? */
139 if (btrfs_try_remove_subvol(pathname
))
140 INFO("Removed btrfs subvolume at %s\n", pathname
);
144 if (S_ISDIR(mystat
.st_mode
)) {
145 if (_recursive_rmdir(pathname
, pdev
, exclude
, level
+1, onedev
) < 0)
148 if (unlink(pathname
) < 0) {
149 SYSERROR("Failed to delete %s", pathname
);
155 if (rmdir(dirname
) < 0 && !btrfs_try_remove_subvol(dirname
) && !hadexclude
) {
156 ERROR("Failed to delete %s", dirname
);
162 ERROR("Failed to close directory %s", dirname
);
166 return failed
? -1 : 0;
169 /* In overlayfs, st_dev is unreliable. So on overlayfs we don't do the
172 static bool is_native_overlayfs(const char *path
)
174 if (has_fs_type(path
, OVERLAY_SUPER_MAGIC
) ||
175 has_fs_type(path
, OVERLAYFS_SUPER_MAGIC
))
181 /* returns 0 on success, -1 if there were any failures */
182 extern int lxc_rmdir_onedev(const char *path
, const char *exclude
)
187 if (is_native_overlayfs(path
))
190 if (lstat(path
, &mystat
) < 0) {
194 ERROR("Failed to stat %s", path
);
198 return _recursive_rmdir(path
, mystat
.st_dev
, exclude
, 0, onedev
);
201 /* borrowed from iproute2 */
202 extern int get_u16(unsigned short *val
, const char *arg
, int base
)
211 res
= strtoul(arg
, &ptr
, base
);
212 if (!ptr
|| ptr
== arg
|| *ptr
|| res
> 0xFFFF || errno
!= 0)
220 extern int mkdir_p(const char *dir
, mode_t mode
)
222 const char *tmp
= dir
;
223 const char *orig
= dir
;
227 dir
= tmp
+ strspn(tmp
, "/");
228 tmp
= dir
+ strcspn(dir
, "/");
230 makeme
= strndup(orig
, dir
- orig
);
232 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
233 SYSERROR("failed to create directory '%s'", makeme
);
250 if (stat(RUNTIME_PATH
, &sb
) < 0)
253 if (geteuid() == sb
.st_uid
|| getegid() == sb
.st_gid
) {
254 rundir
= strdup(RUNTIME_PATH
);
258 rundir
= getenv("XDG_RUNTIME_DIR");
260 rundir
= strdup(rundir
);
264 INFO("XDG_RUNTIME_DIR isn't set in the environment.");
265 homedir
= getenv("HOME");
267 ERROR("HOME isn't set in the environment.");
271 rundir
= malloc(sizeof(char) * (17 + strlen(homedir
)));
275 sprintf(rundir
, "%s/.cache/lxc/run/", homedir
);
280 int wait_for_pid(pid_t pid
)
285 ret
= waitpid(pid
, &status
, 0);
296 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
302 int lxc_wait_for_pid_status(pid_t pid
)
307 ret
= waitpid(pid
, &status
, 0);
322 #include <gnutls/gnutls.h>
323 #include <gnutls/crypto.h>
325 __attribute__((constructor
))
326 static void gnutls_lxc_init(void)
328 gnutls_global_init();
331 int sha1sum_file(char *fnam
, unsigned char *digest
)
341 f
= fopen_cloexec(fnam
, "r");
343 SYSERROR("Error opening template");
347 if (fseek(f
, 0, SEEK_END
) < 0) {
348 SYSERROR("Error seeking to end of template");
353 if ((flen
= ftell(f
)) < 0) {
354 SYSERROR("Error telling size of template");
359 if (fseek(f
, 0, SEEK_SET
) < 0) {
360 SYSERROR("Error seeking to start of template");
365 if ((buf
= malloc(flen
+1)) == NULL
) {
366 SYSERROR("Out of memory");
371 if (fread(buf
, 1, flen
, f
) != flen
) {
372 SYSERROR("Failure reading template");
379 SYSERROR("Failre closing template");
385 ret
= gnutls_hash_fast(GNUTLS_DIG_SHA1
, buf
, flen
, (void *)digest
);
391 struct lxc_popen_FILE
*lxc_popen(const char *command
)
396 struct lxc_popen_FILE
*fp
= NULL
;
398 ret
= pipe2(pipe_fds
, O_CLOEXEC
);
411 /* duplicate stdout */
412 if (pipe_fds
[1] != STDOUT_FILENO
)
413 ret
= dup2(pipe_fds
[1], STDOUT_FILENO
);
415 ret
= fcntl(pipe_fds
[1], F_SETFD
, 0);
421 /* duplicate stderr */
422 if (pipe_fds
[1] != STDERR_FILENO
)
423 ret
= dup2(pipe_fds
[1], STDERR_FILENO
);
425 ret
= fcntl(pipe_fds
[1], F_SETFD
, 0);
430 /* unblock all signals */
431 ret
= sigfillset(&mask
);
435 ret
= pthread_sigmask(SIG_UNBLOCK
, &mask
, NULL
);
439 execl("/bin/sh", "sh", "-c", command
, (char *)NULL
);
446 fp
= malloc(sizeof(*fp
));
450 memset(fp
, 0, sizeof(*fp
));
452 fp
->child_pid
= child_pid
;
453 fp
->pipe
= pipe_fds
[0];
455 /* From now on, closing fp->f will also close fp->pipe. So only ever
456 * call fclose(fp->f).
458 fp
->f
= fdopen(pipe_fds
[0], "r");
465 /* We can only close pipe_fds[0] if fdopen() didn't succeed or wasn't
466 * called yet. Otherwise the fd belongs to the file opened by fdopen()
467 * since it isn't dup()ed.
469 if (fp
&& !fp
->f
&& pipe_fds
[0] >= 0)
472 if (pipe_fds
[1] >= 0)
484 int lxc_pclose(struct lxc_popen_FILE
*fp
)
493 wait_pid
= waitpid(fp
->child_pid
, &wstatus
, 0);
494 } while (wait_pid
< 0 && errno
== EINTR
);
505 int randseed(bool srand_it
)
508 srand pre-seed function based on /dev/urandom
510 unsigned int seed
= time(NULL
) + getpid();
513 f
= fopen("/dev/urandom", "r");
515 int ret
= fread(&seed
, sizeof(seed
), 1, f
);
517 SYSDEBUG("unable to fread /dev/urandom, fallback to time+pid rand seed");
528 uid_t
get_ns_uid(uid_t orig
)
532 uid_t nsid
, hostid
, range
;
533 FILE *f
= fopen("/proc/self/uid_map", "r");
537 while (getline(&line
, &sz
, f
) != -1) {
538 if (sscanf(line
, "%u %u %u", &nsid
, &hostid
, &range
) != 3)
541 if (hostid
<= orig
&& hostid
+ range
> orig
) {
542 nsid
+= orig
- hostid
;
547 nsid
= LXC_INVALID_UID
;
555 gid_t
get_ns_gid(gid_t orig
)
559 gid_t nsid
, hostid
, range
;
560 FILE *f
= fopen("/proc/self/gid_map", "r");
564 while (getline(&line
, &sz
, f
) != -1) {
565 if (sscanf(line
, "%u %u %u", &nsid
, &hostid
, &range
) != 3)
568 if (hostid
<= orig
&& hostid
+ range
> orig
) {
569 nsid
+= orig
- hostid
;
574 nsid
= LXC_INVALID_GID
;
582 bool dir_exists(const char *path
)
587 ret
= stat(path
, &sb
);
589 /* Could be something other than eexist, just say "no". */
592 return S_ISDIR(sb
.st_mode
);
595 /* Note we don't use SHA-1 here as we don't want to depend on HAVE_GNUTLS.
596 * FNV has good anti collision properties and we're not worried
597 * about pre-image resistance or one-way-ness, we're just trying to make
598 * the name unique in the 108 bytes of space we have.
600 uint64_t fnv_64a_buf(void *buf
, size_t len
, uint64_t hval
)
604 for(bp
= buf
; bp
< (unsigned char *)buf
+ len
; bp
++)
606 /* xor the bottom with the current octet */
607 hval
^= (uint64_t)*bp
;
610 * multiply by the 64 bit FNV magic prime mod 2^64
612 hval
+= (hval
<< 1) + (hval
<< 4) + (hval
<< 5) +
613 (hval
<< 7) + (hval
<< 8) + (hval
<< 40);
619 bool is_shared_mountpoint(const char *path
)
621 char buf
[LXC_LINELEN
];
626 f
= fopen("/proc/self/mountinfo", "r");
630 while (fgets(buf
, LXC_LINELEN
, f
)) {
631 for (p
= buf
, i
= 0; p
&& i
< 4; i
++)
632 p
= strchr(p
+ 1, ' ');
636 p2
= strchr(p
+ 1, ' ');
641 if (strcmp(p
+ 1, path
) == 0) {
642 /* This is the path. Is it shared? */
643 p
= strchr(p2
+ 1, ' ');
644 if (p
&& strstr(p
, "shared:")) {
656 * Detect whether / is mounted MS_SHARED. The only way I know of to
657 * check that is through /proc/self/mountinfo.
658 * I'm only checking for /. If the container rootfs or mount location
659 * is MS_SHARED, but not '/', then you're out of luck - figuring that
660 * out would be too much work to be worth it.
662 int detect_shared_rootfs(void)
664 if (is_shared_mountpoint("/"))
669 bool switch_to_ns(pid_t pid
, const char *ns
)
672 char nspath
[MAXPATHLEN
];
674 /* Switch to new ns */
675 ret
= snprintf(nspath
, MAXPATHLEN
, "/proc/%d/ns/%s", pid
, ns
);
676 if (ret
< 0 || ret
>= MAXPATHLEN
)
679 fd
= open(nspath
, O_RDONLY
);
681 SYSERROR("Failed to open %s", nspath
);
687 SYSERROR("Failed to set process %d to %s of %d.", pid
, ns
, fd
);
697 * looking at fs/proc_namespace.c, it appears we can
698 * actually expect the rootfs entry to very specifically contain
699 * " - rootfs rootfs "
700 * IIUC, so long as we've chrooted so that rootfs is not our root,
701 * the rootfs entry should always be skipped in mountinfo contents.
703 bool detect_ramfs_rootfs(void)
711 f
= fopen("/proc/self/mountinfo", "r");
715 while (getline(&line
, &len
, f
) != -1) {
716 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
717 p
= strchr(p
+ 1, ' ');
721 p2
= strchr(p
+ 1, ' ');
726 if (strcmp(p
+ 1, "/") == 0) {
727 /* This is '/'. Is it the ramfs? */
728 p
= strchr(p2
+ 1, '-');
729 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
732 INFO("Rootfs is located on ramfs");
743 char *on_path(const char *cmd
, const char *rootfs
)
745 char *entry
= NULL
, *path
= NULL
;
746 char cmdpath
[MAXPATHLEN
];
749 path
= getenv("PATH");
757 lxc_iterate_parts (entry
, path
, ":") {
759 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s/%s", rootfs
,
762 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s", entry
, cmd
);
763 if (ret
< 0 || ret
>= MAXPATHLEN
)
766 if (access(cmdpath
, X_OK
) == 0) {
768 return strdup(cmdpath
);
776 bool cgns_supported(void)
778 return file_exists("/proc/self/ns/cgroup");
781 /* historically lxc-init has been under /usr/lib/lxc and under
782 * /usr/lib/$ARCH/lxc. It now lives as $prefix/sbin/init.lxc.
784 char *choose_init(const char *rootfs
)
787 const char *empty
= "",
789 int ret
, env_set
= 0;
791 if (!getenv("PATH")) {
792 if (setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 0))
793 SYSERROR("Failed to setenv");
798 retv
= on_path("init.lxc", rootfs
);
801 if (unsetenv("PATH"))
802 SYSERROR("Failed to unsetenv");
808 retv
= malloc(PATH_MAX
);
817 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, SBINDIR
, "/init.lxc");
818 if (ret
< 0 || ret
>= PATH_MAX
) {
819 ERROR("pathname too long");
823 if (access(retv
, X_OK
) == 0)
826 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, LXCINITDIR
, "/lxc/lxc-init");
827 if (ret
< 0 || ret
>= PATH_MAX
) {
828 ERROR("pathname too long");
832 if (access(retv
, X_OK
) == 0)
835 ret
= snprintf(retv
, PATH_MAX
, "%s/usr/lib/lxc/lxc-init", tmp
);
836 if (ret
< 0 || ret
>= PATH_MAX
) {
837 ERROR("pathname too long");
841 if (access(retv
, X_OK
) == 0)
844 ret
= snprintf(retv
, PATH_MAX
, "%s/sbin/lxc-init", tmp
);
845 if (ret
< 0 || ret
>= PATH_MAX
) {
846 ERROR("pathname too long");
850 if (access(retv
, X_OK
) == 0)
854 * Last resort, look for the statically compiled init.lxc which we
855 * hopefully bind-mounted in.
856 * If we are called during container setup, and we get to this point,
857 * then the init.lxc.static from the host will need to be bind-mounted
858 * in. So we return NULL here to indicate that.
863 ret
= snprintf(retv
, PATH_MAX
, "/init.lxc.static");
864 if (ret
< 0 || ret
>= PATH_MAX
) {
865 WARN("Nonsense - name /lxc.init.static too long");
869 if (access(retv
, X_OK
) == 0)
878 * Given the '-t' template option to lxc-create, figure out what to
879 * do. If the template is a full executable path, use that. If it
880 * is something like 'sshd', then return $templatepath/lxc-sshd.
881 * On success return the template, on error return NULL.
883 char *get_template_path(const char *t
)
888 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
893 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
899 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
900 if (ret
< 0 || ret
>= len
) {
905 if (access(tpath
, X_OK
) < 0) {
906 SYSERROR("bad template: %s", t
);
915 * @path: a pathname where / replaced with '\0'.
916 * @offsetp: pointer to int showing which path segment was last seen.
917 * Updated on return to reflect the next segment.
918 * @fulllen: full original path length.
919 * Returns a pointer to the next path segment, or NULL if done.
921 static char *get_nextpath(char *path
, int *offsetp
, int fulllen
)
923 int offset
= *offsetp
;
925 if (offset
>= fulllen
)
928 while (offset
< fulllen
&& path
[offset
] != '\0')
931 while (offset
< fulllen
&& path
[offset
] == '\0')
935 return (offset
< fulllen
) ? &path
[offset
] : NULL
;
939 * Check that @subdir is a subdir of @dir. @len is the length of
940 * @dir (to avoid having to recalculate it).
942 static bool is_subdir(const char *subdir
, const char *dir
, size_t len
)
944 size_t subdirlen
= strlen(subdir
);
949 if (strncmp(subdir
, dir
, len
) != 0)
952 if (dir
[len
-1] == '/')
955 if (subdir
[len
] == '/' || subdirlen
== len
)
962 * Check if the open fd is a symlink. Return -ELOOP if it is. Return
963 * -ENOENT if we couldn't fstat. Return 0 if the fd is ok.
965 static int check_symlink(int fd
)
970 ret
= fstat(fd
, &sb
);
974 if (S_ISLNK(sb
.st_mode
))
981 * Open a file or directory, provided that it contains no symlinks.
983 * CAVEAT: This function must not be used for other purposes than container
984 * setup before executing the container's init
986 static int open_if_safe(int dirfd
, const char *nextpath
)
988 int newfd
= openat(dirfd
, nextpath
, O_RDONLY
| O_NOFOLLOW
);
989 if (newfd
>= 0) /* Was not a symlink, all good. */
995 if (errno
== EPERM
|| errno
== EACCES
) {
996 /* We're not root (cause we got EPERM) so try opening with
999 newfd
= openat(dirfd
, nextpath
, O_PATH
| O_NOFOLLOW
);
1001 /* O_PATH will return an fd for symlinks. We know
1002 * nextpath wasn't a symlink at last openat, so if fd is
1003 * now a link, then something * fishy is going on.
1005 int ret
= check_symlink(newfd
);
1017 * Open a path intending for mounting, ensuring that the final path
1018 * is inside the container's rootfs.
1020 * CAVEAT: This function must not be used for other purposes than container
1021 * setup before executing the container's init
1023 * @target: path to be opened
1024 * @prefix_skip: a part of @target in which to ignore symbolic links. This
1025 * would be the container's rootfs.
1027 * Return an open fd for the path, or <0 on error.
1029 static int open_without_symlink(const char *target
, const char *prefix_skip
)
1031 int curlen
= 0, dirfd
, fulllen
, i
;
1034 fulllen
= strlen(target
);
1036 /* make sure prefix-skip makes sense */
1037 if (prefix_skip
&& strlen(prefix_skip
) > 0) {
1038 curlen
= strlen(prefix_skip
);
1039 if (!is_subdir(target
, prefix_skip
, curlen
)) {
1040 ERROR("WHOA there - target '%s' didn't start with prefix '%s'",
1041 target
, prefix_skip
);
1046 * get_nextpath() expects the curlen argument to be
1047 * on a (turned into \0) / or before it, so decrement
1048 * curlen to make sure that happens
1057 /* Make a copy of target which we can hack up, and tokenize it */
1058 if ((dup
= strdup(target
)) == NULL
) {
1059 SYSERROR("Out of memory checking for symbolic link");
1063 for (i
= 0; i
< fulllen
; i
++) {
1068 dirfd
= open(prefix_skip
, O_RDONLY
);
1073 int newfd
, saved_errno
;
1076 if ((nextpath
= get_nextpath(dup
, &curlen
, fulllen
)) == NULL
)
1079 newfd
= open_if_safe(dirfd
, nextpath
);
1080 saved_errno
= errno
;
1085 errno
= saved_errno
;
1087 SYSERROR("%s in %s was a symbolic link!", nextpath
, target
);
1099 * Safely mount a path into a container, ensuring that the mount target
1100 * is under the container's @rootfs. (If @rootfs is NULL, then the container
1101 * uses the host's /)
1103 * CAVEAT: This function must not be used for other purposes than container
1104 * setup before executing the container's init
1106 int safe_mount(const char *src
, const char *dest
, const char *fstype
,
1107 unsigned long flags
, const void *data
, const char *rootfs
)
1109 int destfd
, ret
, saved_errno
;
1110 /* Only needs enough for /proc/self/fd/<fd>. */
1111 char srcbuf
[50], destbuf
[50];
1113 const char *mntsrc
= src
;
1118 /* todo - allow symlinks for relative paths if 'allowsymlinks' option is passed */
1119 if (flags
& MS_BIND
&& src
&& src
[0] != '/') {
1120 INFO("this is a relative bind mount");
1122 srcfd
= open_without_symlink(src
, NULL
);
1126 ret
= snprintf(srcbuf
, 50, "/proc/self/fd/%d", srcfd
);
1127 if (ret
< 0 || ret
> 50) {
1129 ERROR("Out of memory");
1135 destfd
= open_without_symlink(dest
, rootfs
);
1138 saved_errno
= errno
;
1140 errno
= saved_errno
;
1146 ret
= snprintf(destbuf
, 50, "/proc/self/fd/%d", destfd
);
1147 if (ret
< 0 || ret
> 50) {
1152 ERROR("Out of memory");
1156 ret
= mount(mntsrc
, destbuf
, fstype
, flags
, data
);
1157 saved_errno
= errno
;
1163 errno
= saved_errno
;
1164 SYSERROR("Failed to mount %s onto %s", src
? src
: "(null)", dest
);
1172 * Mount a proc under @rootfs if proc self points to a pid other than
1173 * my own. This is needed to have a known-good proc mount for setting
1174 * up LSMs both at container startup and attach.
1176 * @rootfs : the rootfs where proc should be mounted
1178 * Returns < 0 on failure, 0 if the correct proc was already mounted
1179 * and 1 if a new proc was mounted.
1181 * NOTE: not to be called from inside the container namespace!
1183 int lxc_mount_proc_if_needed(const char *rootfs
)
1185 char path
[MAXPATHLEN
];
1186 int link_to_pid
, linklen
, mypid
, ret
;
1187 char link
[INTTYPE_TO_STRLEN(pid_t
)] = {0};
1189 ret
= snprintf(path
, MAXPATHLEN
, "%s/proc/self", rootfs
);
1190 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1191 SYSERROR("proc path name too long");
1195 linklen
= readlink(path
, link
, sizeof(link
));
1197 ret
= snprintf(path
, MAXPATHLEN
, "%s/proc", rootfs
);
1198 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1199 SYSERROR("proc path name too long");
1203 /* /proc not mounted */
1205 if (mkdir(path
, 0755) && errno
!= EEXIST
)
1209 } else if (linklen
>= sizeof(link
)) {
1210 link
[linklen
- 1] = '\0';
1211 ERROR("readlink returned truncated content: \"%s\"", link
);
1215 mypid
= lxc_raw_getpid();
1216 INFO("I am %d, /proc/self points to \"%s\"", mypid
, link
);
1218 if (lxc_safe_int(link
, &link_to_pid
) < 0)
1221 /* correct procfs is already mounted */
1222 if (link_to_pid
== mypid
)
1225 ret
= umount2(path
, MNT_DETACH
);
1227 WARN("failed to umount \"%s\" with MNT_DETACH", path
);
1230 /* rootfs is NULL */
1231 if (!strcmp(rootfs
, ""))
1232 ret
= mount("proc", path
, "proc", 0, NULL
);
1234 ret
= safe_mount("proc", path
, "proc", 0, NULL
, rootfs
);
1238 INFO("mounted /proc in container for security transition");
1242 int open_devnull(void)
1244 int fd
= open("/dev/null", O_RDWR
);
1247 SYSERROR("Can't open /dev/null");
1252 int set_stdfds(int fd
)
1259 ret
= dup2(fd
, STDIN_FILENO
);
1263 ret
= dup2(fd
, STDOUT_FILENO
);
1267 ret
= dup2(fd
, STDERR_FILENO
);
1274 int null_stdfds(void)
1279 fd
= open_devnull();
1281 ret
= set_stdfds(fd
);
1288 /* Check whether a signal is blocked by a process. */
1289 /* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
1290 #define __PROC_STATUS_LEN (6 + INTTYPE_TO_STRLEN(pid_t) + 7 + 1)
1291 bool task_blocks_signal(pid_t pid
, int signal
)
1294 char status
[__PROC_STATUS_LEN
];
1296 uint64_t sigblk
= 0, one
= 1;
1301 ret
= snprintf(status
, __PROC_STATUS_LEN
, "/proc/%d/status", pid
);
1302 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
1305 f
= fopen(status
, "r");
1309 while (getline(&line
, &n
, f
) != -1) {
1312 if (strncmp(line
, "SigBlk:", 7))
1315 numstr
= lxc_trim_whitespace_in_place(line
+ 7);
1316 ret
= lxc_safe_uint64(numstr
, &sigblk
, 16);
1323 if (sigblk
& (one
<< (signal
- 1)))
1332 int lxc_preserve_ns(const int pid
, const char *ns
)
1335 /* 5 /proc + 21 /int_as_str + 3 /ns + 20 /NS_NAME + 1 \0 */
1336 #define __NS_PATH_LEN 50
1337 char path
[__NS_PATH_LEN
];
1339 /* This way we can use this function to also check whether namespaces
1340 * are supported by the kernel by passing in the NULL or the empty
1343 ret
= snprintf(path
, __NS_PATH_LEN
, "/proc/%d/ns%s%s", pid
,
1344 !ns
|| strcmp(ns
, "") == 0 ? "" : "/",
1345 !ns
|| strcmp(ns
, "") == 0 ? "" : ns
);
1346 if (ret
< 0 || (size_t)ret
>= __NS_PATH_LEN
) {
1351 return open(path
, O_RDONLY
| O_CLOEXEC
);
1354 int lxc_switch_uid_gid(uid_t uid
, gid_t gid
)
1358 if (gid
!= LXC_INVALID_GID
) {
1361 SYSERROR("Failed to switch to gid %d", gid
);
1364 NOTICE("Switched to gid %d", gid
);
1367 if (uid
!= LXC_INVALID_UID
) {
1370 SYSERROR("Failed to switch to uid %d", uid
);
1373 NOTICE("Switched to uid %d", uid
);
1379 /* Simple covenience function which enables uniform logging. */
1380 int lxc_setgroups(int size
, gid_t list
[])
1382 if (setgroups(size
, list
) < 0) {
1383 SYSERROR("Failed to setgroups().");
1386 NOTICE("Dropped additional groups.");
1391 static int lxc_get_unused_loop_dev_legacy(char *loop_name
)
1394 struct loop_info64 lo64
;
1396 int dfd
= -1, fd
= -1, ret
= -1;
1398 dir
= opendir("/dev");
1402 while ((dp
= readdir(dir
))) {
1403 if (strncmp(dp
->d_name
, "loop", 4) != 0)
1410 fd
= openat(dfd
, dp
->d_name
, O_RDWR
);
1414 ret
= ioctl(fd
, LOOP_GET_STATUS64
, &lo64
);
1416 if (ioctl(fd
, LOOP_GET_STATUS64
, &lo64
) == 0 ||
1424 ret
= snprintf(loop_name
, LO_NAME_SIZE
, "/dev/%s", dp
->d_name
);
1425 if (ret
< 0 || ret
>= LO_NAME_SIZE
) {
1442 static int lxc_get_unused_loop_dev(char *name_loop
)
1445 int fd_ctl
= -1, fd_tmp
= -1;
1447 fd_ctl
= open("/dev/loop-control", O_RDWR
| O_CLOEXEC
);
1451 loop_nr
= ioctl(fd_ctl
, LOOP_CTL_GET_FREE
);
1455 ret
= snprintf(name_loop
, LO_NAME_SIZE
, "/dev/loop%d", loop_nr
);
1456 if (ret
< 0 || ret
>= LO_NAME_SIZE
)
1459 fd_tmp
= open(name_loop
, O_RDWR
| O_CLOEXEC
);
1468 int lxc_prepare_loop_dev(const char *source
, char *loop_dev
, int flags
)
1471 struct loop_info64 lo64
;
1472 int fd_img
= -1, fret
= -1, fd_loop
= -1;
1474 fd_loop
= lxc_get_unused_loop_dev(loop_dev
);
1476 if (fd_loop
== -ENODEV
)
1477 fd_loop
= lxc_get_unused_loop_dev_legacy(loop_dev
);
1482 fd_img
= open(source
, O_RDWR
| O_CLOEXEC
);
1486 ret
= ioctl(fd_loop
, LOOP_SET_FD
, fd_img
);
1490 memset(&lo64
, 0, sizeof(lo64
));
1491 lo64
.lo_flags
= flags
;
1493 ret
= ioctl(fd_loop
, LOOP_SET_STATUS64
, &lo64
);
1503 if (fret
< 0 && fd_loop
>= 0) {
1511 int lxc_unstack_mountpoint(const char *path
, bool lazy
)
1517 ret
= umount2(path
, lazy
? MNT_DETACH
: 0);
1519 /* We consider anything else than EINVAL deadly to prevent going
1520 * into an infinite loop. (The other alternative is constantly
1521 * parsing /proc/self/mountinfo which is yucky and probably
1524 if (errno
!= EINVAL
)
1527 /* Just stop counting when this happens. That'd just be so
1528 * stupid that we won't even bother trying to report back the
1529 * correct value anymore.
1531 if (umounts
!= INT_MAX
)
1534 /* We succeeded in umounting. Make sure that there's no other
1535 * mountpoint stacked underneath.
1543 int run_command(char *buf
, size_t buf_size
, int (*child_fn
)(void *), void *args
)
1546 int ret
, fret
, pipefd
[2];
1549 /* Make sure our callers do not receive uninitialized memory. */
1550 if (buf_size
> 0 && buf
)
1553 if (pipe(pipefd
) < 0) {
1554 SYSERROR("failed to create pipe");
1558 child
= lxc_raw_clone(0);
1562 SYSERROR("failed to create new process");
1567 /* Close the read-end of the pipe. */
1570 /* Redirect std{err,out} to write-end of the
1573 ret
= dup2(pipefd
[1], STDOUT_FILENO
);
1575 ret
= dup2(pipefd
[1], STDERR_FILENO
);
1577 /* Close the write-end of the pipe. */
1581 SYSERROR("failed to duplicate std{err,out} file descriptor");
1582 _exit(EXIT_FAILURE
);
1585 /* Does not return. */
1587 ERROR("failed to exec command");
1588 _exit(EXIT_FAILURE
);
1591 /* close the write-end of the pipe */
1594 if (buf
&& buf_size
> 0) {
1595 bytes
= lxc_read_nointr(pipefd
[0], buf
, buf_size
- 1);
1597 buf
[bytes
- 1] = '\0';
1600 fret
= wait_for_pid(child
);
1601 /* close the read-end of the pipe */
1607 bool lxc_nic_exists(char *nic
)
1609 #define __LXC_SYS_CLASS_NET_LEN 15 + IFNAMSIZ + 1
1610 char path
[__LXC_SYS_CLASS_NET_LEN
];
1614 if (!strcmp(nic
, "none"))
1617 ret
= snprintf(path
, __LXC_SYS_CLASS_NET_LEN
, "/sys/class/net/%s", nic
);
1618 if (ret
< 0 || (size_t)ret
>= __LXC_SYS_CLASS_NET_LEN
)
1621 ret
= stat(path
, &sb
);
1628 uint64_t lxc_find_next_power2(uint64_t n
)
1630 /* 0 is not valid input. We return 0 to the caller since 0 is not a
1631 * valid power of two.
1646 int lxc_set_death_signal(int signal
)
1651 ret
= prctl(PR_SET_PDEATHSIG
, prctl_arg(signal
), prctl_arg(0),
1652 prctl_arg(0), prctl_arg(0));
1654 /* Check whether we have been orphaned. */
1655 ppid
= (pid_t
)syscall(SYS_getppid
);
1659 self
= lxc_raw_getpid();
1660 ret
= kill(self
, SIGKILL
);
1666 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d", signal
);
1673 int fd_cloexec(int fd
, bool cloexec
)
1677 oflags
= fcntl(fd
, F_GETFD
, 0);
1682 nflags
= oflags
| FD_CLOEXEC
;
1684 nflags
= oflags
& ~FD_CLOEXEC
;
1686 if (nflags
== oflags
)
1689 if (fcntl(fd
, F_SETFD
, nflags
) < 0)
1695 int recursive_destroy(char *dirname
)
1698 struct dirent
*direntp
;
1702 dir
= opendir(dirname
);
1706 while ((direntp
= readdir(dir
))) {
1710 if (!strcmp(direntp
->d_name
, ".") ||
1711 !strcmp(direntp
->d_name
, ".."))
1714 pathname
= must_make_path(dirname
, direntp
->d_name
, NULL
);
1716 ret
= lstat(pathname
, &mystat
);
1719 WARN("Failed to stat \"%s\"", pathname
);
1725 if (!S_ISDIR(mystat
.st_mode
))
1728 ret
= recursive_destroy(pathname
);
1736 ret
= rmdir(dirname
);
1739 SYSWARN("Failed to delete \"%s\"", dirname
);
1744 ret
= closedir(dir
);
1747 SYSWARN("Failed to delete \"%s\"", dirname
);