1 /* SPDX-License-Identifier: LGPL-2.1+ */
6 #define __STDC_FORMAT_MACROS /* Required for PRIu64 to work. */
21 #include <sys/mount.h>
22 /* Needs to be after sys/mount.h header */
24 #include <sys/param.h>
25 #include <sys/prctl.h>
27 #include <sys/types.h>
35 #include "memory_utils.h"
36 #include "namespace.h"
38 #include "raw_syscalls.h"
39 #include "syscall_wrappers.h"
43 #include "include/strlcpy.h"
47 #include "include/strlcat.h"
51 #define O_PATH 010000000
55 #define O_NOFOLLOW 00400000
58 lxc_log_define(utils
, lxc
);
61 * if path is btrfs, tries to remove it and any subvolumes beneath it
63 extern bool btrfs_try_remove_subvol(const char *path
);
65 static int _recursive_rmdir(const char *dirname
, dev_t pdev
,
66 const char *exclude
, int level
, bool onedev
)
68 __do_closedir
DIR *dir
= NULL
;
70 bool hadexclude
= false;
72 struct dirent
*direntp
;
73 char pathname
[PATH_MAX
];
75 dir
= opendir(dirname
);
77 return log_error(-1, "Failed to open \"%s\"", dirname
);
79 while ((direntp
= readdir(dir
))) {
83 if (!strcmp(direntp
->d_name
, ".") ||
84 !strcmp(direntp
->d_name
, ".."))
87 rc
= snprintf(pathname
, PATH_MAX
, "%s/%s", dirname
, direntp
->d_name
);
88 if (rc
< 0 || rc
>= PATH_MAX
) {
89 ERROR("The name of path is too long");
94 if (!level
&& exclude
&& !strcmp(direntp
->d_name
, exclude
)) {
95 ret
= rmdir(pathname
);
99 INFO("Not deleting snapshot \"%s\"", pathname
);
103 ret
= unlink(pathname
);
105 INFO("Failed to remove \"%s\"", pathname
);
108 SYSERROR("Failed to rmdir \"%s\"", pathname
);
117 ret
= lstat(pathname
, &mystat
);
119 SYSERROR("Failed to stat \"%s\"", pathname
);
124 if (onedev
&& mystat
.st_dev
!= pdev
) {
125 if (btrfs_try_remove_subvol(pathname
))
126 INFO("Removed btrfs subvolume at \"%s\"", pathname
);
130 if (S_ISDIR(mystat
.st_mode
)) {
131 if (_recursive_rmdir(pathname
, pdev
, exclude
, level
+ 1, onedev
) < 0)
134 ret
= unlink(pathname
);
136 __do_close
int fd
= -EBADF
;
138 fd
= open(pathname
, O_RDONLY
| O_CLOEXEC
| O_NONBLOCK
);
140 /* The file might be marked immutable. */
142 ret
= ioctl(fd
, FS_IOC_GETFLAGS
, &attr
);
144 SYSERROR("Failed to retrieve file flags");
145 attr
&= ~FS_IMMUTABLE_FL
;
146 ret
= ioctl(fd
, FS_IOC_SETFLAGS
, &attr
);
148 SYSERROR("Failed to set file flags");
151 ret
= unlink(pathname
);
153 SYSERROR("Failed to delete \"%s\"", pathname
);
160 if (rmdir(dirname
) < 0 && !btrfs_try_remove_subvol(dirname
) && !hadexclude
) {
161 SYSERROR("Failed to delete \"%s\"", dirname
);
165 return failed
? -1 : 0;
169 * In overlayfs, st_dev is unreliable. So on overlayfs we don't do the
170 * lxc_rmdir_onedev().
172 static inline bool is_native_overlayfs(const char *path
)
174 return has_fs_type(path
, OVERLAY_SUPER_MAGIC
) ||
175 has_fs_type(path
, OVERLAYFS_SUPER_MAGIC
);
178 /* returns 0 on success, -1 if there were any failures */
179 extern int lxc_rmdir_onedev(const char *path
, const char *exclude
)
184 if (is_native_overlayfs(path
))
187 if (lstat(path
, &mystat
) < 0) {
191 return log_error_errno(-1, errno
, "Failed to stat \"%s\"", path
);
194 return _recursive_rmdir(path
, mystat
.st_dev
, exclude
, 0, onedev
);
197 /* borrowed from iproute2 */
198 extern int get_u16(unsigned short *val
, const char *arg
, int base
)
207 res
= strtoul(arg
, &ptr
, base
);
208 if (!ptr
|| ptr
== arg
|| *ptr
|| res
> 0xFFFF || errno
!= 0)
216 int mkdir_p(const char *dir
, mode_t mode
)
218 const char *tmp
= dir
;
219 const char *orig
= dir
;
222 __do_free
char *makeme
= NULL
;
225 dir
= tmp
+ strspn(tmp
, "/");
226 tmp
= dir
+ strcspn(dir
, "/");
228 makeme
= strndup(orig
, dir
- orig
);
230 return ret_set_errno(-1, ENOMEM
);
232 ret
= mkdir(makeme
, mode
);
233 if (ret
< 0 && errno
!= EEXIST
)
234 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", makeme
);
236 } while (tmp
!= dir
);
248 if (stat(RUNTIME_PATH
, &sb
) < 0)
251 if (geteuid() == sb
.st_uid
|| getegid() == sb
.st_gid
)
252 return strdup(RUNTIME_PATH
);
254 rundir
= getenv("XDG_RUNTIME_DIR");
256 return strdup(rundir
);
258 INFO("XDG_RUNTIME_DIR isn't set in the environment");
259 homedir
= getenv("HOME");
261 return log_error(NULL
, "HOME isn't set in the environment");
263 len
= strlen(homedir
) + 17;
264 rundir
= malloc(sizeof(char) * len
);
268 snprintf(rundir
, len
, "%s/.cache/lxc/run/", homedir
);
272 int wait_for_pid(pid_t pid
)
277 ret
= waitpid(pid
, &status
, 0);
288 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
294 int wait_for_pidfd(int pidfd
)
302 ret
= waitid(P_PIDFD
, pidfd
, &info
, __WALL
| WEXITED
);
303 } while (ret
< 0 && errno
== EINTR
);
305 return !ret
&& WIFEXITED(info
.si_status
) && WEXITSTATUS(info
.si_status
) == 0;
308 int lxc_wait_for_pid_status(pid_t pid
)
313 ret
= waitpid(pid
, &status
, 0);
328 #include <openssl/evp.h>
330 static int do_sha1_hash(const char *buf
, int buflen
, unsigned char *md_value
,
331 unsigned int *md_len
)
336 md
= EVP_get_digestbyname("sha1");
338 return log_error(-1, "Unknown message digest: sha1\n");
340 mdctx
= EVP_MD_CTX_create();
341 EVP_DigestInit_ex(mdctx
, md
, NULL
);
342 EVP_DigestUpdate(mdctx
, buf
, buflen
);
343 EVP_DigestFinal_ex(mdctx
, md_value
, md_len
);
344 EVP_MD_CTX_destroy(mdctx
);
349 int sha1sum_file(char *fnam
, unsigned char *digest
, unsigned int *md_len
)
351 __do_free
char *buf
= NULL
;
352 __do_fclose
FILE *f
= NULL
;
359 f
= fopen_cloexec(fnam
, "r");
361 return log_error_errno(-1, errno
, "Failed to open template \"%s\"", fnam
);
363 if (fseek(f
, 0, SEEK_END
) < 0)
364 return log_error_errno(-1, errno
, "Failed to seek to end of template");
368 return log_error_errno(-1, errno
, "Failed to tell size of template");
370 if (fseek(f
, 0, SEEK_SET
) < 0)
371 return log_error_errno(-1, errno
, "Failed to seek to start of template");
373 buf
= malloc(flen
+ 1);
375 return log_error_errno(-1, ENOMEM
, "Out of memory");
377 if (fread(buf
, 1, flen
, f
) != flen
)
378 return log_error_errno(-1, errno
, "Failed to read template");
381 ret
= do_sha1_hash(buf
, flen
, (void *)digest
, md_len
);
386 struct lxc_popen_FILE
*lxc_popen(const char *command
)
391 struct lxc_popen_FILE
*fp
= NULL
;
393 ret
= pipe2(pipe_fds
, O_CLOEXEC
);
406 /* duplicate stdout */
407 if (pipe_fds
[1] != STDOUT_FILENO
)
408 ret
= dup2(pipe_fds
[1], STDOUT_FILENO
);
410 ret
= fcntl(pipe_fds
[1], F_SETFD
, 0);
416 /* duplicate stderr */
417 if (pipe_fds
[1] != STDERR_FILENO
)
418 ret
= dup2(pipe_fds
[1], STDERR_FILENO
);
420 ret
= fcntl(pipe_fds
[1], F_SETFD
, 0);
425 /* unblock all signals */
426 ret
= sigfillset(&mask
);
430 ret
= pthread_sigmask(SIG_UNBLOCK
, &mask
, NULL
);
434 /* check if /bin/sh exist, otherwise try Android location /system/bin/sh */
435 if (file_exists("/bin/sh"))
436 execl("/bin/sh", "sh", "-c", command
, (char *)NULL
);
438 execl("/system/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
)
507 __do_fclose
FILE *f
= NULL
;
509 * srand pre-seed function based on /dev/urandom
511 unsigned int seed
= time(NULL
) + getpid();
513 f
= fopen("/dev/urandom", "re");
515 int ret
= fread(&seed
, sizeof(seed
), 1, f
);
517 SYSDEBUG("Unable to fread /dev/urandom, fallback to time+pid rand seed");
526 uid_t
get_ns_uid(uid_t orig
)
528 __do_free
char *line
= NULL
;
529 __do_fclose
FILE *f
= NULL
;
531 uid_t nsid
, hostid
, range
;
533 f
= fopen("/proc/self/uid_map", "re");
535 return log_error_errno(0, errno
, "Failed to open uid_map");
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 return nsid
+= orig
- hostid
;
545 return LXC_INVALID_UID
;
548 gid_t
get_ns_gid(gid_t orig
)
550 __do_free
char *line
= NULL
;
551 __do_fclose
FILE *f
= NULL
;
553 gid_t nsid
, hostid
, range
;
555 f
= fopen("/proc/self/gid_map", "re");
557 return log_error_errno(0, errno
, "Failed to open gid_map");
559 while (getline(&line
, &sz
, f
) != -1) {
560 if (sscanf(line
, "%u %u %u", &nsid
, &hostid
, &range
) != 3)
563 if (hostid
<= orig
&& hostid
+ range
> orig
)
564 return nsid
+= orig
- hostid
;
567 return LXC_INVALID_GID
;
570 bool dir_exists(const char *path
)
575 ret
= stat(path
, &sb
);
577 /* Could be something other than eexist, just say "no". */
580 return S_ISDIR(sb
.st_mode
);
583 /* Note we don't use SHA-1 here as we don't want to depend on HAVE_GNUTLS.
584 * FNV has good anti collision properties and we're not worried
585 * about pre-image resistance or one-way-ness, we're just trying to make
586 * the name unique in the 108 bytes of space we have.
588 uint64_t fnv_64a_buf(void *buf
, size_t len
, uint64_t hval
)
592 for(bp
= buf
; bp
< (unsigned char *)buf
+ len
; bp
++) {
593 /* xor the bottom with the current octet */
594 hval
^= (uint64_t)*bp
;
597 * multiply by the 64 bit FNV magic prime mod 2^64
599 hval
+= (hval
<< 1) + (hval
<< 4) + (hval
<< 5) +
600 (hval
<< 7) + (hval
<< 8) + (hval
<< 40);
606 bool is_shared_mountpoint(const char *path
)
608 __do_fclose
FILE *f
= NULL
;
609 __do_free
char *line
= NULL
;
613 f
= fopen("/proc/self/mountinfo", "re");
617 while (getline(&line
, &len
, f
) > 0) {
618 char *slider1
, *slider2
;
620 for (slider1
= line
, i
= 0; slider1
&& i
< 4; i
++)
621 slider1
= strchr(slider1
+ 1, ' ');
626 slider2
= strchr(slider1
+ 1, ' ');
631 if (strcmp(slider1
+ 1, path
) == 0) {
632 /* This is the path. Is it shared? */
633 slider1
= strchr(slider2
+ 1, ' ');
634 if (slider1
&& strstr(slider1
, "shared:"))
643 * Detect whether / is mounted MS_SHARED. The only way I know of to
644 * check that is through /proc/self/mountinfo.
645 * I'm only checking for /. If the container rootfs or mount location
646 * is MS_SHARED, but not '/', then you're out of luck - figuring that
647 * out would be too much work to be worth it.
649 int detect_shared_rootfs(void)
651 if (is_shared_mountpoint("/"))
657 bool switch_to_ns(pid_t pid
, const char *ns
)
659 __do_close
int fd
= -EBADF
;
661 char nspath
[STRLITERALLEN("/proc//ns/")
662 + INTTYPE_TO_STRLEN(pid_t
)
663 + LXC_NAMESPACE_NAME_MAX
];
665 /* Switch to new ns */
666 ret
= snprintf(nspath
, sizeof(nspath
), "/proc/%d/ns/%s", pid
, ns
);
667 if (ret
< 0 || ret
>= sizeof(nspath
))
670 fd
= open(nspath
, O_RDONLY
| O_CLOEXEC
);
672 return log_error_errno(false, errno
, "Failed to open \"%s\"", nspath
);
676 return log_error_errno(false, errno
, "Failed to set process %d to \"%s\" of %d", pid
, ns
, fd
);
682 * looking at fs/proc_namespace.c, it appears we can
683 * actually expect the rootfs entry to very specifically contain
684 * " - rootfs rootfs "
685 * IIUC, so long as we've chrooted so that rootfs is not our root,
686 * the rootfs entry should always be skipped in mountinfo contents.
688 bool detect_ramfs_rootfs(void)
690 __do_free
char *line
= NULL
;
691 __do_free
void *fopen_cache
= NULL
;
692 __do_fclose
FILE *f
= NULL
;
695 f
= fopen_cached("/proc/self/mountinfo", "re", &fopen_cache
);
699 while (getline(&line
, &len
, f
) != -1) {
703 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
704 p
= strchr(p
+ 1, ' ');
708 p2
= strchr(p
+ 1, ' ');
712 if (strcmp(p
+ 1, "/") == 0) {
713 /* This is '/'. Is it the ramfs? */
714 p
= strchr(p2
+ 1, '-');
715 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0)
723 char *on_path(const char *cmd
, const char *rootfs
)
725 __do_free
char *path
= NULL
;
727 char cmdpath
[PATH_MAX
];
730 path
= getenv("PATH");
738 lxc_iterate_parts(entry
, path
, ":") {
740 ret
= snprintf(cmdpath
, PATH_MAX
, "%s/%s/%s", rootfs
,
743 ret
= snprintf(cmdpath
, PATH_MAX
, "%s/%s", entry
, cmd
);
744 if (ret
< 0 || ret
>= PATH_MAX
)
747 if (access(cmdpath
, X_OK
) == 0)
748 return strdup(cmdpath
);
754 bool cgns_supported(void)
756 return file_exists("/proc/self/ns/cgroup");
759 /* historically lxc-init has been under /usr/lib/lxc and under
760 * /usr/lib/$ARCH/lxc. It now lives as $prefix/sbin/init.lxc.
762 char *choose_init(const char *rootfs
)
765 const char *empty
= "",
767 int ret
, env_set
= 0;
769 if (!getenv("PATH")) {
770 if (setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 0))
771 SYSERROR("Failed to setenv");
776 retv
= on_path("init.lxc", rootfs
);
779 if (unsetenv("PATH"))
780 SYSERROR("Failed to unsetenv");
785 retv
= malloc(PATH_MAX
);
794 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, SBINDIR
, "/init.lxc");
795 if (ret
< 0 || ret
>= PATH_MAX
) {
796 ERROR("The name of path is too long");
800 if (access(retv
, X_OK
) == 0)
803 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, LXCINITDIR
, "/lxc/lxc-init");
804 if (ret
< 0 || ret
>= PATH_MAX
) {
805 ERROR("The name of path is too long");
809 if (access(retv
, X_OK
) == 0)
812 ret
= snprintf(retv
, PATH_MAX
, "%s/usr/lib/lxc/lxc-init", tmp
);
813 if (ret
< 0 || ret
>= PATH_MAX
) {
814 ERROR("The name of path is too long");
818 if (access(retv
, X_OK
) == 0)
821 ret
= snprintf(retv
, PATH_MAX
, "%s/sbin/lxc-init", tmp
);
822 if (ret
< 0 || ret
>= PATH_MAX
) {
823 ERROR("The name of path is too long");
827 if (access(retv
, X_OK
) == 0)
831 * Last resort, look for the statically compiled init.lxc which we
832 * hopefully bind-mounted in.
833 * If we are called during container setup, and we get to this point,
834 * then the init.lxc.static from the host will need to be bind-mounted
835 * in. So we return NULL here to indicate that.
840 ret
= snprintf(retv
, PATH_MAX
, "/init.lxc.static");
841 if (ret
< 0 || ret
>= PATH_MAX
) {
842 WARN("Nonsense - name /lxc.init.static too long");
846 if (access(retv
, X_OK
) == 0)
855 * Given the '-t' template option to lxc-create, figure out what to
856 * do. If the template is a full executable path, use that. If it
857 * is something like 'sshd', then return $templatepath/lxc-sshd.
858 * On success return the template, on error return NULL.
860 char *get_template_path(const char *t
)
866 if (access(t
, X_OK
) == 0) {
869 SYSERROR("Bad template pathname: %s", t
);
874 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
880 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
881 if (ret
< 0 || ret
>= len
) {
886 if (access(tpath
, X_OK
) < 0) {
887 SYSERROR("bad template: %s", t
);
896 * @path: a pathname where / replaced with '\0'.
897 * @offsetp: pointer to int showing which path segment was last seen.
898 * Updated on return to reflect the next segment.
899 * @fulllen: full original path length.
900 * Returns a pointer to the next path segment, or NULL if done.
902 static char *get_nextpath(char *path
, int *offsetp
, int fulllen
)
904 int offset
= *offsetp
;
906 if (offset
>= fulllen
)
909 while (offset
< fulllen
&& path
[offset
] != '\0')
912 while (offset
< fulllen
&& path
[offset
] == '\0')
917 return (offset
< fulllen
) ? &path
[offset
] : NULL
;
921 * Check that @subdir is a subdir of @dir. @len is the length of
922 * @dir (to avoid having to recalculate it).
924 static bool is_subdir(const char *subdir
, const char *dir
, size_t len
)
926 size_t subdirlen
= strlen(subdir
);
931 if (strncmp(subdir
, dir
, len
) != 0)
934 if (dir
[len
-1] == '/')
937 if (subdir
[len
] == '/' || subdirlen
== len
)
944 * Check if the open fd is a symlink. Return -ELOOP if it is. Return
945 * -ENOENT if we couldn't fstat. Return 0 if the fd is ok.
947 static int check_symlink(int fd
)
952 ret
= fstat(fd
, &sb
);
956 if (S_ISLNK(sb
.st_mode
))
963 * Open a file or directory, provided that it contains no symlinks.
965 * CAVEAT: This function must not be used for other purposes than container
966 * setup before executing the container's init
968 static int open_if_safe(int dirfd
, const char *nextpath
)
970 int newfd
= openat(dirfd
, nextpath
, O_RDONLY
| O_NOFOLLOW
);
971 if (newfd
>= 0) /* Was not a symlink, all good. */
977 if (errno
== EPERM
|| errno
== EACCES
) {
978 /* We're not root (cause we got EPERM) so try opening with
981 newfd
= openat(dirfd
, nextpath
, O_PATH
| O_NOFOLLOW
);
983 /* O_PATH will return an fd for symlinks. We know
984 * nextpath wasn't a symlink at last openat, so if fd is
985 * now a link, then something * fishy is going on.
987 int ret
= check_symlink(newfd
);
999 * Open a path intending for mounting, ensuring that the final path
1000 * is inside the container's rootfs.
1002 * CAVEAT: This function must not be used for other purposes than container
1003 * setup before executing the container's init
1005 * @target: path to be opened
1006 * @prefix_skip: a part of @target in which to ignore symbolic links. This
1007 * would be the container's rootfs.
1009 * Return an open fd for the path, or <0 on error.
1011 static int open_without_symlink(const char *target
, const char *prefix_skip
)
1013 int curlen
= 0, dirfd
, fulllen
, i
;
1016 fulllen
= strlen(target
);
1018 /* make sure prefix-skip makes sense */
1019 if (prefix_skip
&& strlen(prefix_skip
) > 0) {
1020 curlen
= strlen(prefix_skip
);
1021 if (!is_subdir(target
, prefix_skip
, curlen
)) {
1022 ERROR("WHOA there - target \"%s\" didn't start with prefix \"%s\"",
1023 target
, prefix_skip
);
1028 * get_nextpath() expects the curlen argument to be
1029 * on a (turned into \0) / or before it, so decrement
1030 * curlen to make sure that happens
1039 /* Make a copy of target which we can hack up, and tokenize it */
1040 if ((dup
= strdup(target
)) == NULL
) {
1041 ERROR("Out of memory checking for symbolic link");
1045 for (i
= 0; i
< fulllen
; i
++) {
1050 dirfd
= open(prefix_skip
, O_RDONLY
);
1052 SYSERROR("Failed to open path \"%s\"", prefix_skip
);
1057 int newfd
, saved_errno
;
1060 if ((nextpath
= get_nextpath(dup
, &curlen
, fulllen
)) == NULL
)
1063 newfd
= open_if_safe(dirfd
, nextpath
);
1064 saved_errno
= errno
;
1069 errno
= saved_errno
;
1071 SYSERROR("%s in %s was a symbolic link!", nextpath
, target
);
1083 * Safely mount a path into a container, ensuring that the mount target
1084 * is under the container's @rootfs. (If @rootfs is NULL, then the container
1085 * uses the host's /)
1087 * CAVEAT: This function must not be used for other purposes than container
1088 * setup before executing the container's init
1090 int safe_mount(const char *src
, const char *dest
, const char *fstype
,
1091 unsigned long flags
, const void *data
, const char *rootfs
)
1093 int destfd
, ret
, saved_errno
;
1094 /* Only needs enough for /proc/self/fd/<fd>. */
1095 char srcbuf
[50], destbuf
[50];
1097 const char *mntsrc
= src
;
1102 /* todo - allow symlinks for relative paths if 'allowsymlinks' option is passed */
1103 if (flags
& MS_BIND
&& src
&& src
[0] != '/') {
1104 INFO("This is a relative bind mount");
1106 srcfd
= open_without_symlink(src
, NULL
);
1110 ret
= snprintf(srcbuf
, sizeof(srcbuf
), "/proc/self/fd/%d", srcfd
);
1111 if (ret
< 0 || ret
>= (int)sizeof(srcbuf
)) {
1113 ERROR("Out of memory");
1119 destfd
= open_without_symlink(dest
, rootfs
);
1122 saved_errno
= errno
;
1124 errno
= saved_errno
;
1130 ret
= snprintf(destbuf
, sizeof(destbuf
), "/proc/self/fd/%d", destfd
);
1131 if (ret
< 0 || ret
>= (int)sizeof(destbuf
)) {
1136 ERROR("Out of memory");
1140 ret
= mount(mntsrc
, destbuf
, fstype
, flags
, data
);
1141 saved_errno
= errno
;
1147 errno
= saved_errno
;
1148 SYSERROR("Failed to mount \"%s\" onto \"%s\"", src
? src
: "(null)", dest
);
1156 * Mount a proc under @rootfs if proc self points to a pid other than
1157 * my own. This is needed to have a known-good proc mount for setting
1158 * up LSMs both at container startup and attach.
1160 * @rootfs : the rootfs where proc should be mounted
1162 * Returns < 0 on failure, 0 if the correct proc was already mounted
1163 * and 1 if a new proc was mounted.
1165 * NOTE: not to be called from inside the container namespace!
1167 int lxc_mount_proc_if_needed(const char *rootfs
)
1169 char path
[PATH_MAX
] = {0};
1170 int link_to_pid
, linklen
, mypid
, ret
;
1171 char link
[INTTYPE_TO_STRLEN(pid_t
)] = {0};
1173 ret
= snprintf(path
, PATH_MAX
, "%s/proc/self", rootfs
);
1174 if (ret
< 0 || ret
>= PATH_MAX
) {
1175 SYSERROR("The name of proc path is too long");
1179 linklen
= readlink(path
, link
, sizeof(link
));
1181 ret
= snprintf(path
, PATH_MAX
, "%s/proc", rootfs
);
1182 if (ret
< 0 || ret
>= PATH_MAX
) {
1183 SYSERROR("The name of proc path is too long");
1187 /* /proc not mounted */
1189 if (mkdir(path
, 0755) && errno
!= EEXIST
)
1193 } else if (linklen
>= sizeof(link
)) {
1194 link
[linklen
- 1] = '\0';
1195 ERROR("Readlink returned truncated content: \"%s\"", link
);
1199 mypid
= lxc_raw_getpid();
1200 INFO("I am %d, /proc/self points to \"%s\"", mypid
, link
);
1202 if (lxc_safe_int(link
, &link_to_pid
) < 0)
1205 /* correct procfs is already mounted */
1206 if (link_to_pid
== mypid
)
1209 ret
= umount2(path
, MNT_DETACH
);
1211 SYSWARN("Failed to umount \"%s\" with MNT_DETACH", path
);
1214 /* rootfs is NULL */
1215 if (!strcmp(rootfs
, ""))
1216 ret
= mount("proc", path
, "proc", 0, NULL
);
1218 ret
= safe_mount("proc", path
, "proc", 0, NULL
, rootfs
);
1222 INFO("Mounted /proc in container for security transition");
1226 int open_devnull(void)
1228 int fd
= open("/dev/null", O_RDWR
);
1230 SYSERROR("Can't open /dev/null");
1235 int set_stdfds(int fd
)
1242 ret
= dup2(fd
, STDIN_FILENO
);
1246 ret
= dup2(fd
, STDOUT_FILENO
);
1250 ret
= dup2(fd
, STDERR_FILENO
);
1257 int null_stdfds(void)
1262 fd
= open_devnull();
1264 ret
= set_stdfds(fd
);
1271 /* Check whether a signal is blocked by a process. */
1272 /* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
1273 #define __PROC_STATUS_LEN (6 + INTTYPE_TO_STRLEN(pid_t) + 7 + 1)
1274 bool task_blocks_signal(pid_t pid
, int signal
)
1276 __do_free
char *line
= NULL
;
1277 __do_fclose
FILE *f
= NULL
;
1279 char status
[__PROC_STATUS_LEN
] = {0};
1280 uint64_t sigblk
= 0, one
= 1;
1284 ret
= snprintf(status
, __PROC_STATUS_LEN
, "/proc/%d/status", pid
);
1285 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
1288 f
= fopen(status
, "re");
1292 while (getline(&line
, &n
, f
) != -1) {
1295 if (strncmp(line
, "SigBlk:", 7))
1298 numstr
= lxc_trim_whitespace_in_place(line
+ 7);
1299 ret
= lxc_safe_uint64(numstr
, &sigblk
, 16);
1306 if (sigblk
& (one
<< (signal
- 1)))
1312 int lxc_preserve_ns(const int pid
, const char *ns
)
1315 /* 5 /proc + 21 /int_as_str + 3 /ns + 20 /NS_NAME + 1 \0 */
1316 #define __NS_PATH_LEN 50
1317 char path
[__NS_PATH_LEN
];
1319 /* This way we can use this function to also check whether namespaces
1320 * are supported by the kernel by passing in the NULL or the empty
1323 ret
= snprintf(path
, __NS_PATH_LEN
, "/proc/%d/ns%s%s", pid
,
1324 !ns
|| strcmp(ns
, "") == 0 ? "" : "/",
1325 !ns
|| strcmp(ns
, "") == 0 ? "" : ns
);
1326 if (ret
< 0 || (size_t)ret
>= __NS_PATH_LEN
) {
1331 return open(path
, O_RDONLY
| O_CLOEXEC
);
1334 bool lxc_switch_uid_gid(uid_t uid
, gid_t gid
)
1338 if (gid
!= LXC_INVALID_GID
) {
1341 SYSERROR("Failed to switch to gid %d", gid
);
1344 NOTICE("Switched to gid %d", gid
);
1347 if (uid
!= LXC_INVALID_UID
) {
1350 SYSERROR("Failed to switch to uid %d", uid
);
1353 NOTICE("Switched to uid %d", uid
);
1359 /* Simple convenience function which enables uniform logging. */
1360 bool lxc_setgroups(int size
, gid_t list
[])
1362 if (setgroups(size
, list
) < 0) {
1363 SYSERROR("Failed to setgroups()");
1366 NOTICE("Dropped additional groups");
1371 static int lxc_get_unused_loop_dev_legacy(char *loop_name
)
1374 struct loop_info64 lo64
;
1376 int dfd
= -1, fd
= -1, ret
= -1;
1378 dir
= opendir("/dev");
1380 SYSERROR("Failed to open \"/dev\"");
1384 while ((dp
= readdir(dir
))) {
1385 if (strncmp(dp
->d_name
, "loop", 4) != 0)
1392 fd
= openat(dfd
, dp
->d_name
, O_RDWR
);
1396 ret
= ioctl(fd
, LOOP_GET_STATUS64
, &lo64
);
1398 if (ioctl(fd
, LOOP_GET_STATUS64
, &lo64
) == 0 ||
1406 ret
= snprintf(loop_name
, LO_NAME_SIZE
, "/dev/%s", dp
->d_name
);
1407 if (ret
< 0 || ret
>= LO_NAME_SIZE
) {
1424 static int lxc_get_unused_loop_dev(char *name_loop
)
1427 int fd_ctl
= -1, fd_tmp
= -1;
1429 fd_ctl
= open("/dev/loop-control", O_RDWR
| O_CLOEXEC
);
1431 SYSERROR("Failed to open loop control");
1435 loop_nr
= ioctl(fd_ctl
, LOOP_CTL_GET_FREE
);
1437 SYSERROR("Failed to get loop control");
1441 ret
= snprintf(name_loop
, LO_NAME_SIZE
, "/dev/loop%d", loop_nr
);
1442 if (ret
< 0 || ret
>= LO_NAME_SIZE
)
1445 fd_tmp
= open(name_loop
, O_RDWR
| O_CLOEXEC
);
1447 /* on Android loop devices are moved under /dev/block, give it a shot */
1448 ret
= snprintf(name_loop
, LO_NAME_SIZE
, "/dev/block/loop%d", loop_nr
);
1449 if (ret
< 0 || ret
>= LO_NAME_SIZE
)
1452 fd_tmp
= open(name_loop
, O_RDWR
| O_CLOEXEC
);
1454 SYSERROR("Failed to open loop \"%s\"", name_loop
);
1462 int lxc_prepare_loop_dev(const char *source
, char *loop_dev
, int flags
)
1465 struct loop_info64 lo64
;
1466 int fd_img
= -1, fret
= -1, fd_loop
= -1;
1468 fd_loop
= lxc_get_unused_loop_dev(loop_dev
);
1470 if (fd_loop
!= -ENODEV
)
1473 fd_loop
= lxc_get_unused_loop_dev_legacy(loop_dev
);
1478 fd_img
= open(source
, O_RDWR
| O_CLOEXEC
);
1480 SYSERROR("Failed to open source \"%s\"", source
);
1484 ret
= ioctl(fd_loop
, LOOP_SET_FD
, fd_img
);
1486 SYSERROR("Failed to set loop fd");
1490 memset(&lo64
, 0, sizeof(lo64
));
1491 lo64
.lo_flags
= flags
;
1493 strlcpy((char *)lo64
.lo_file_name
, source
, LO_NAME_SIZE
);
1495 ret
= ioctl(fd_loop
, LOOP_SET_STATUS64
, &lo64
);
1497 SYSERROR("Failed to set loop status64");
1507 if (fret
< 0 && fd_loop
>= 0) {
1515 int lxc_unstack_mountpoint(const char *path
, bool lazy
)
1521 ret
= umount2(path
, lazy
? MNT_DETACH
: 0);
1523 /* We consider anything else than EINVAL deadly to prevent going
1524 * into an infinite loop. (The other alternative is constantly
1525 * parsing /proc/self/mountinfo which is yucky and probably
1528 if (errno
!= EINVAL
)
1531 /* Just stop counting when this happens. That'd just be so
1532 * stupid that we won't even bother trying to report back the
1533 * correct value anymore.
1535 if (umounts
!= INT_MAX
)
1538 /* We succeeded in umounting. Make sure that there's no other
1539 * mountpoint stacked underneath.
1547 int run_command_internal(char *buf
, size_t buf_size
, int (*child_fn
)(void *), void *args
, bool wait_status
)
1550 int ret
, fret
, pipefd
[2];
1553 /* Make sure our callers do not receive uninitialized memory. */
1554 if (buf_size
> 0 && buf
)
1557 if (pipe(pipefd
) < 0) {
1558 SYSERROR("Failed to create pipe");
1562 child
= lxc_raw_clone(0, NULL
);
1566 SYSERROR("Failed to create new process");
1571 /* Close the read-end of the pipe. */
1574 /* Redirect std{err,out} to write-end of the
1577 ret
= dup2(pipefd
[1], STDOUT_FILENO
);
1579 ret
= dup2(pipefd
[1], STDERR_FILENO
);
1581 /* Close the write-end of the pipe. */
1585 SYSERROR("Failed to duplicate std{err,out} file descriptor");
1586 _exit(EXIT_FAILURE
);
1589 /* Does not return. */
1591 ERROR("Failed to exec command");
1592 _exit(EXIT_FAILURE
);
1595 /* close the write-end of the pipe */
1598 if (buf
&& buf_size
> 0) {
1599 bytes
= lxc_read_nointr(pipefd
[0], buf
, buf_size
- 1);
1601 buf
[bytes
- 1] = '\0';
1605 fret
= lxc_wait_for_pid_status(child
);
1607 fret
= wait_for_pid(child
);
1609 /* close the read-end of the pipe */
1615 int run_command(char *buf
, size_t buf_size
, int (*child_fn
)(void *), void *args
)
1617 return run_command_internal(buf
, buf_size
, child_fn
, args
, false);
1620 int run_command_status(char *buf
, size_t buf_size
, int (*child_fn
)(void *), void *args
)
1622 return run_command_internal(buf
, buf_size
, child_fn
, args
, true);
1625 bool lxc_nic_exists(char *nic
)
1627 #define __LXC_SYS_CLASS_NET_LEN 15 + IFNAMSIZ + 1
1628 char path
[__LXC_SYS_CLASS_NET_LEN
];
1632 if (!strcmp(nic
, "none"))
1635 ret
= snprintf(path
, __LXC_SYS_CLASS_NET_LEN
, "/sys/class/net/%s", nic
);
1636 if (ret
< 0 || (size_t)ret
>= __LXC_SYS_CLASS_NET_LEN
)
1639 ret
= stat(path
, &sb
);
1646 uint64_t lxc_find_next_power2(uint64_t n
)
1648 /* 0 is not valid input. We return 0 to the caller since 0 is not a
1649 * valid power of two.
1664 static int process_dead(/* takes */ int status_fd
)
1666 __do_close
int dupfd
= -EBADF
;
1667 __do_free
char *line
= NULL
;
1668 __do_fclose
FILE *f
= NULL
;
1672 dupfd
= dup(status_fd
);
1676 if (fd_cloexec(dupfd
, true) < 0)
1679 f
= fdopen(dupfd
, "re");
1683 /* Transfer ownership of fd. */
1687 while (getline(&line
, &n
, f
) != -1) {
1690 if (strncmp(line
, "State:", 6))
1693 state
= lxc_trim_whitespace_in_place(line
+ 6);
1694 /* only check whether process is dead or zombie for now */
1695 if (*state
== 'X' || *state
== 'Z')
1702 int lxc_set_death_signal(int signal
, pid_t parent
, int parent_status_fd
)
1707 ret
= prctl(PR_SET_PDEATHSIG
, prctl_arg(signal
), prctl_arg(0),
1708 prctl_arg(0), prctl_arg(0));
1710 /* verify that we haven't been orphaned in the meantime */
1711 ppid
= (pid_t
)syscall(SYS_getppid
);
1712 if (ppid
== 0) { /* parent outside our pidns */
1713 if (parent_status_fd
< 0)
1716 if (process_dead(parent_status_fd
) == 1)
1717 return raise(SIGKILL
);
1718 } else if (ppid
!= parent
) {
1719 return raise(SIGKILL
);
1728 int fd_cloexec(int fd
, bool cloexec
)
1732 oflags
= fcntl(fd
, F_GETFD
, 0);
1737 nflags
= oflags
| FD_CLOEXEC
;
1739 nflags
= oflags
& ~FD_CLOEXEC
;
1741 if (nflags
== oflags
)
1744 if (fcntl(fd
, F_SETFD
, nflags
) < 0)
1750 int lxc_rm_rf(const char *dirname
)
1752 __do_closedir
DIR *dir
= NULL
;
1755 struct dirent
*direntp
;
1757 dir
= opendir(dirname
);
1759 return log_error_errno(-1, errno
, "Failed to open dir \"%s\"", dirname
);
1761 while ((direntp
= readdir(dir
))) {
1762 __do_free
char *pathname
= NULL
;
1765 if (!strcmp(direntp
->d_name
, ".") ||
1766 !strcmp(direntp
->d_name
, ".."))
1769 pathname
= must_make_path(dirname
, direntp
->d_name
, NULL
);
1770 ret
= lstat(pathname
, &mystat
);
1773 SYSWARN("Failed to stat \"%s\"", pathname
);
1779 if (!S_ISDIR(mystat
.st_mode
))
1782 ret
= lxc_rm_rf(pathname
);
1787 ret
= rmdir(dirname
);
1789 return log_warn_errno(-1, errno
, "Failed to delete \"%s\"", dirname
);
1794 int lxc_setup_keyring(char *keyring_label
)
1796 key_serial_t keyring
;
1799 if (keyring_label
) {
1800 if (lsm_keyring_label_set(keyring_label
) < 0) {
1801 ERROR("Couldn't set keyring label");
1805 /* Try to allocate a new session keyring for the container to prevent
1806 * information leaks.
1808 keyring
= keyctl(KEYCTL_JOIN_SESSION_KEYRING
, prctl_arg(0),
1809 prctl_arg(0), prctl_arg(0), prctl_arg(0));
1813 DEBUG("The keyctl() syscall is not supported or blocked");
1818 DEBUG("Failed to access kernel keyring. Continuing...");
1821 SYSERROR("Failed to create kernel keyring");
1829 bool lxc_can_use_pidfd(int pidfd
)
1834 return log_error(false, "Kernel does not support pidfds");
1837 * We don't care whether or not children were in a waitable state. We
1838 * just care whether waitid() recognizes P_PIDFD.
1840 * Btw, while I have your attention, the above waitid() code is an
1841 * excellent example of how _not_ to do flag-based kernel APIs. So if
1842 * you ever go into kernel development or are already and you add this
1843 * kind of flag potpourri even though you have read this comment shame
1844 * on you. May the gods of operating system development have mercy on
1845 * your soul because I won't.
1847 ret
= waitid(P_PIDFD
, pidfd
, NULL
,
1848 /* Type of children to wait for. */
1850 /* How to wait for them. */
1852 /* What state to wait for. */
1853 WEXITED
| WSTOPPED
| WCONTINUED
);
1855 return log_error_errno(false, errno
, "Kernel does not support waiting on processes through pidfds");
1857 ret
= lxc_raw_pidfd_send_signal(pidfd
, 0, NULL
, 0);
1859 return log_error_errno(false, errno
, "Kernel does not support sending singals through pidfds");
1861 return log_trace(true, "Kernel supports pidfds");
1864 int fix_stdio_permissions(uid_t uid
)
1866 __do_close
int devnull_fd
= -EBADF
;
1868 int std_fds
[] = {STDIN_FILENO
, STDOUT_FILENO
, STDERR_FILENO
};
1870 struct stat st
, st_null
;
1872 devnull_fd
= open_devnull();
1874 return log_warn_errno(-1, errno
, "Failed to open \"/dev/null\"");
1876 ret
= fstat(devnull_fd
, &st_null
);
1878 return log_warn_errno(-errno
, errno
, "Failed to stat \"/dev/null\"");
1880 for (int i
= 0; i
< ARRAY_SIZE(std_fds
); i
++) {
1881 ret
= fstat(std_fds
[i
], &st
);
1883 SYSWARN("Failed to stat standard I/O file descriptor %d", std_fds
[i
]);
1888 if (st
.st_rdev
== st_null
.st_rdev
)
1891 ret
= fchown(std_fds
[i
], uid
, st
.st_gid
);
1893 SYSWARN("Failed to chown standard I/O file descriptor %d to uid %d and gid %d",
1894 std_fds
[i
], uid
, st
.st_gid
);
1898 ret
= fchmod(std_fds
[i
], 0700);
1900 SYSWARN("Failed to chmod standard I/O file descriptor %d", std_fds
[i
]);