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 "process_utils.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 (strequal(direntp
->d_name
, ".") ||
84 strequal(direntp
->d_name
, ".."))
87 rc
= strnprintf(pathname
, sizeof(pathname
), "%s/%s", dirname
, direntp
->d_name
);
89 ERROR("The name of path is too long");
94 if (!level
&& exclude
&& strequal(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
)
204 return ret_errno(EINVAL
);
207 res
= strtoul(arg
, &ptr
, base
);
208 if (!ptr
|| ptr
== arg
|| *ptr
|| res
> 0xFFFF || errno
!= 0)
209 return ret_errno(ERANGE
);
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
);
241 char *get_rundir(void)
243 __do_free
char *rundir
= NULL
;
250 if (stat(RUNTIME_PATH
, &sb
) < 0)
253 if (geteuid() == sb
.st_uid
|| getegid() == sb
.st_gid
)
254 return strdup(RUNTIME_PATH
);
256 static_rundir
= getenv("XDG_RUNTIME_DIR");
258 return strdup(static_rundir
);
260 INFO("XDG_RUNTIME_DIR isn't set in the environment");
261 homedir
= getenv("HOME");
263 return log_error(NULL
, "HOME isn't set in the environment");
265 len
= strlen(homedir
) + 17;
266 rundir
= malloc(sizeof(char) * len
);
270 ret
= strnprintf(rundir
, len
, "%s/.cache/lxc/run/", homedir
);
272 return ret_set_errno(NULL
, EIO
);
274 return move_ptr(rundir
);
277 int wait_for_pid(pid_t pid
)
282 ret
= waitpid(pid
, &status
, 0);
293 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
299 int wait_for_pidfd(int pidfd
)
307 ret
= waitid(P_PIDFD
, pidfd
, &info
, __WALL
| WEXITED
);
308 } while (ret
< 0 && errno
== EINTR
);
310 return !ret
&& WIFEXITED(info
.si_status
) && WEXITSTATUS(info
.si_status
) == 0;
313 int lxc_wait_for_pid_status(pid_t pid
)
318 ret
= waitpid(pid
, &status
, 0);
333 #include <openssl/evp.h>
335 static int do_sha1_hash(const char *buf
, int buflen
, unsigned char *md_value
,
336 unsigned int *md_len
)
341 md
= EVP_get_digestbyname("sha1");
343 return log_error(-1, "Unknown message digest: sha1\n");
345 mdctx
= EVP_MD_CTX_create();
346 EVP_DigestInit_ex(mdctx
, md
, NULL
);
347 EVP_DigestUpdate(mdctx
, buf
, buflen
);
348 EVP_DigestFinal_ex(mdctx
, md_value
, md_len
);
349 EVP_MD_CTX_destroy(mdctx
);
354 int sha1sum_file(char *fnam
, unsigned char *digest
, unsigned int *md_len
)
356 __do_free
char *buf
= NULL
;
357 __do_fclose
FILE *f
= NULL
;
364 f
= fopen_cloexec(fnam
, "r");
366 return log_error_errno(-1, errno
, "Failed to open template \"%s\"", fnam
);
368 if (fseek(f
, 0, SEEK_END
) < 0)
369 return log_error_errno(-1, errno
, "Failed to seek to end of template");
373 return log_error_errno(-1, errno
, "Failed to tell size of template");
375 if (fseek(f
, 0, SEEK_SET
) < 0)
376 return log_error_errno(-1, errno
, "Failed to seek to start of template");
378 buf
= malloc(flen
+ 1);
380 return log_error_errno(-1, ENOMEM
, "Out of memory");
382 if (fread(buf
, 1, flen
, f
) != flen
)
383 return log_error_errno(-1, errno
, "Failed to read template");
386 ret
= do_sha1_hash(buf
, flen
, (void *)digest
, md_len
);
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 /* check if /bin/sh exist, otherwise try Android location /system/bin/sh */
440 if (file_exists("/bin/sh"))
441 execl("/bin/sh", "sh", "-c", command
, (char *)NULL
);
443 execl("/system/bin/sh", "sh", "-c", command
, (char *)NULL
);
451 fp
= malloc(sizeof(*fp
));
455 memset(fp
, 0, sizeof(*fp
));
457 fp
->child_pid
= child_pid
;
458 fp
->pipe
= pipe_fds
[0];
460 /* From now on, closing fp->f will also close fp->pipe. So only ever
461 * call fclose(fp->f).
463 fp
->f
= fdopen(pipe_fds
[0], "r");
470 /* We can only close pipe_fds[0] if fdopen() didn't succeed or wasn't
471 * called yet. Otherwise the fd belongs to the file opened by fdopen()
472 * since it isn't dup()ed.
474 if (fp
&& !fp
->f
&& pipe_fds
[0] >= 0)
477 if (pipe_fds
[1] >= 0)
489 int lxc_pclose(struct lxc_popen_FILE
*fp
)
498 wait_pid
= waitpid(fp
->child_pid
, &wstatus
, 0);
499 } while (wait_pid
< 0 && errno
== EINTR
);
510 int randseed(bool srand_it
)
512 __do_fclose
FILE *f
= NULL
;
514 * srand pre-seed function based on /dev/urandom
516 unsigned int seed
= time(NULL
) + getpid();
518 f
= fopen("/dev/urandom", "re");
520 int ret
= fread(&seed
, sizeof(seed
), 1, f
);
522 SYSDEBUG("Unable to fread /dev/urandom, fallback to time+pid rand seed");
531 uid_t
get_ns_uid(uid_t orig
)
533 __do_free
char *line
= NULL
;
534 __do_fclose
FILE *f
= NULL
;
536 uid_t nsid
, hostid
, range
;
538 f
= fopen("/proc/self/uid_map", "re");
540 return log_error_errno(0, errno
, "Failed to open uid_map");
542 while (getline(&line
, &sz
, f
) != -1) {
543 if (sscanf(line
, "%u %u %u", &nsid
, &hostid
, &range
) != 3)
546 if (hostid
<= orig
&& hostid
+ range
> orig
)
547 return nsid
+= orig
- hostid
;
550 return LXC_INVALID_UID
;
553 gid_t
get_ns_gid(gid_t orig
)
555 __do_free
char *line
= NULL
;
556 __do_fclose
FILE *f
= NULL
;
558 gid_t nsid
, hostid
, range
;
560 f
= fopen("/proc/self/gid_map", "re");
562 return log_error_errno(0, errno
, "Failed to open gid_map");
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 return nsid
+= orig
- hostid
;
572 return LXC_INVALID_GID
;
575 bool dir_exists(const char *path
)
577 return exists_dir_at(-1, path
);
580 /* Note we don't use SHA-1 here as we don't want to depend on HAVE_GNUTLS.
581 * FNV has good anti collision properties and we're not worried
582 * about pre-image resistance or one-way-ness, we're just trying to make
583 * the name unique in the 108 bytes of space we have.
585 uint64_t fnv_64a_buf(void *buf
, size_t len
, uint64_t hval
)
589 for(bp
= buf
; bp
< (unsigned char *)buf
+ len
; bp
++) {
590 /* xor the bottom with the current octet */
591 hval
^= (uint64_t)*bp
;
594 * multiply by the 64 bit FNV magic prime mod 2^64
596 hval
+= (hval
<< 1) + (hval
<< 4) + (hval
<< 5) +
597 (hval
<< 7) + (hval
<< 8) + (hval
<< 40);
603 bool is_shared_mountpoint(const char *path
)
605 __do_fclose
FILE *f
= NULL
;
606 __do_free
char *line
= NULL
;
610 f
= fopen("/proc/self/mountinfo", "re");
614 while (getline(&line
, &len
, f
) > 0) {
615 char *slider1
, *slider2
;
617 for (slider1
= line
, i
= 0; slider1
&& i
< 4; i
++)
618 slider1
= strchr(slider1
+ 1, ' ');
623 slider2
= strchr(slider1
+ 1, ' ');
628 if (strequal(slider1
+ 1, path
)) {
629 /* This is the path. Is it shared? */
630 slider1
= strchr(slider2
+ 1, ' ');
631 if (slider1
&& strstr(slider1
, "shared:"))
640 * Detect whether / is mounted MS_SHARED. The only way I know of to
641 * check that is through /proc/self/mountinfo.
642 * I'm only checking for /. If the container rootfs or mount location
643 * is MS_SHARED, but not '/', then you're out of luck - figuring that
644 * out would be too much work to be worth it.
646 int detect_shared_rootfs(void)
648 if (is_shared_mountpoint("/"))
654 bool switch_to_ns(pid_t pid
, const char *ns
)
656 __do_close
int fd
= -EBADF
;
658 char nspath
[STRLITERALLEN("/proc//ns/")
659 + INTTYPE_TO_STRLEN(pid_t
)
660 + LXC_NAMESPACE_NAME_MAX
];
662 /* Switch to new ns */
663 ret
= strnprintf(nspath
, sizeof(nspath
), "/proc/%d/ns/%s", pid
, ns
);
667 fd
= open(nspath
, O_RDONLY
| O_CLOEXEC
);
669 return log_error_errno(false, errno
, "Failed to open \"%s\"", nspath
);
673 return log_error_errno(false, errno
, "Failed to set process %d to \"%s\" of %d", pid
, ns
, fd
);
679 * looking at fs/proc_namespace.c, it appears we can
680 * actually expect the rootfs entry to very specifically contain
681 * " - rootfs rootfs "
682 * IIUC, so long as we've chrooted so that rootfs is not our root,
683 * the rootfs entry should always be skipped in mountinfo contents.
685 bool detect_ramfs_rootfs(void)
687 __do_free
char *line
= NULL
;
688 __do_free
void *fopen_cache
= NULL
;
689 __do_fclose
FILE *f
= NULL
;
692 f
= fopen_cached("/proc/self/mountinfo", "re", &fopen_cache
);
696 while (getline(&line
, &len
, f
) != -1) {
700 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
701 p
= strchr(p
+ 1, ' ');
705 p2
= strchr(p
+ 1, ' ');
709 if (strequal(p
+ 1, "/")) {
710 /* This is '/'. Is it the ramfs? */
711 p
= strchr(p2
+ 1, '-');
712 if (p
&& strnequal(p
, "- rootfs ", 9))
720 char *on_path(const char *cmd
, const char *rootfs
)
722 __do_free
char *path
= NULL
;
724 char cmdpath
[PATH_MAX
];
727 path
= getenv("PATH");
735 lxc_iterate_parts(entry
, path
, ":") {
737 ret
= strnprintf(cmdpath
, sizeof(cmdpath
), "%s/%s/%s", rootfs
, entry
, cmd
);
739 ret
= strnprintf(cmdpath
, sizeof(cmdpath
), "%s/%s", entry
, cmd
);
743 if (access(cmdpath
, X_OK
) == 0)
744 return strdup(cmdpath
);
750 /* historically lxc-init has been under /usr/lib/lxc and under
751 * /usr/lib/$ARCH/lxc. It now lives as $prefix/sbin/init.lxc.
753 char *choose_init(const char *rootfs
)
756 const char *empty
= "",
758 int ret
, env_set
= 0;
760 if (!getenv("PATH")) {
761 if (setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 0))
762 SYSERROR("Failed to setenv");
767 retv
= on_path("init.lxc", rootfs
);
770 if (unsetenv("PATH"))
771 SYSERROR("Failed to unsetenv");
776 retv
= malloc(PATH_MAX
);
785 ret
= strnprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, SBINDIR
, "/init.lxc");
787 ERROR("The name of path is too long");
791 if (access(retv
, X_OK
) == 0)
794 ret
= strnprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, LXCINITDIR
, "/lxc/lxc-init");
796 ERROR("The name of path is too long");
800 if (access(retv
, X_OK
) == 0)
803 ret
= strnprintf(retv
, PATH_MAX
, "%s/usr/lib/lxc/lxc-init", tmp
);
805 ERROR("The name of path is too long");
809 if (access(retv
, X_OK
) == 0)
812 ret
= strnprintf(retv
, PATH_MAX
, "%s/sbin/lxc-init", tmp
);
814 ERROR("The name of path is too long");
818 if (access(retv
, X_OK
) == 0)
822 * Last resort, look for the statically compiled init.lxc which we
823 * hopefully bind-mounted in.
824 * If we are called during container setup, and we get to this point,
825 * then the init.lxc.static from the host will need to be bind-mounted
826 * in. So we return NULL here to indicate that.
831 ret
= strnprintf(retv
, PATH_MAX
, "/init.lxc.static");
833 WARN("Nonsense - name /lxc.init.static too long");
837 if (access(retv
, X_OK
) == 0)
846 * Given the '-t' template option to lxc-create, figure out what to
847 * do. If the template is a full executable path, use that. If it
848 * is something like 'sshd', then return $templatepath/lxc-sshd.
849 * On success return the template, on error return NULL.
851 char *get_template_path(const char *t
)
857 if (access(t
, X_OK
) == 0) {
860 SYSERROR("Bad template pathname: %s", t
);
865 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
871 ret
= strnprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
877 if (access(tpath
, X_OK
) < 0) {
878 SYSERROR("bad template: %s", t
);
887 * @path: a pathname where / replaced with '\0'.
888 * @offsetp: pointer to int showing which path segment was last seen.
889 * Updated on return to reflect the next segment.
890 * @fulllen: full original path length.
891 * Returns a pointer to the next path segment, or NULL if done.
893 static char *get_nextpath(char *path
, int *offsetp
, int fulllen
)
895 int offset
= *offsetp
;
897 if (offset
>= fulllen
)
900 while (offset
< fulllen
&& path
[offset
] != '\0')
903 while (offset
< fulllen
&& path
[offset
] == '\0')
908 return (offset
< fulllen
) ? &path
[offset
] : NULL
;
912 * Check that @subdir is a subdir of @dir. @len is the length of
913 * @dir (to avoid having to recalculate it).
915 static bool is_subdir(const char *subdir
, const char *dir
, size_t len
)
917 size_t subdirlen
= strlen(subdir
);
922 if (!strnequal(subdir
, dir
, len
))
925 if (dir
[len
-1] == '/')
928 if (subdir
[len
] == '/' || subdirlen
== len
)
935 * Check if the open fd is a symlink. Return -ELOOP if it is. Return
936 * -ENOENT if we couldn't fstat. Return 0 if the fd is ok.
938 static int check_symlink(int fd
)
943 ret
= fstat(fd
, &sb
);
947 if (S_ISLNK(sb
.st_mode
))
954 * Open a file or directory, provided that it contains no symlinks.
956 * CAVEAT: This function must not be used for other purposes than container
957 * setup before executing the container's init
959 static int open_if_safe(int dirfd
, const char *nextpath
)
961 int newfd
= openat(dirfd
, nextpath
, O_RDONLY
| O_NOFOLLOW
);
962 if (newfd
>= 0) /* Was not a symlink, all good. */
968 if (errno
== EPERM
|| errno
== EACCES
) {
969 /* We're not root (cause we got EPERM) so try opening with
972 newfd
= openat(dirfd
, nextpath
, O_PATH
| O_NOFOLLOW
);
974 /* O_PATH will return an fd for symlinks. We know
975 * nextpath wasn't a symlink at last openat, so if fd is
976 * now a link, then something * fishy is going on.
978 int ret
= check_symlink(newfd
);
990 * Open a path intending for mounting, ensuring that the final path
991 * is inside the container's rootfs.
993 * CAVEAT: This function must not be used for other purposes than container
994 * setup before executing the container's init
996 * @target: path to be opened
997 * @prefix_skip: a part of @target in which to ignore symbolic links. This
998 * would be the container's rootfs.
1000 * Return an open fd for the path, or <0 on error.
1002 static int open_without_symlink(const char *target
, const char *prefix_skip
)
1004 int curlen
= 0, dirfd
, fulllen
, i
;
1007 fulllen
= strlen(target
);
1009 /* make sure prefix-skip makes sense */
1010 if (prefix_skip
&& strlen(prefix_skip
) > 0) {
1011 curlen
= strlen(prefix_skip
);
1012 if (!is_subdir(target
, prefix_skip
, curlen
)) {
1013 ERROR("WHOA there - target \"%s\" didn't start with prefix \"%s\"",
1014 target
, prefix_skip
);
1019 * get_nextpath() expects the curlen argument to be
1020 * on a (turned into \0) / or before it, so decrement
1021 * curlen to make sure that happens
1030 /* Make a copy of target which we can hack up, and tokenize it */
1031 if ((dup
= strdup(target
)) == NULL
) {
1032 ERROR("Out of memory checking for symbolic link");
1036 for (i
= 0; i
< fulllen
; i
++) {
1041 dirfd
= open(prefix_skip
, O_RDONLY
);
1043 SYSERROR("Failed to open path \"%s\"", prefix_skip
);
1048 int newfd
, saved_errno
;
1051 if ((nextpath
= get_nextpath(dup
, &curlen
, fulllen
)) == NULL
)
1054 newfd
= open_if_safe(dirfd
, nextpath
);
1055 saved_errno
= errno
;
1060 errno
= saved_errno
;
1062 SYSERROR("%s in %s was a symbolic link!", nextpath
, target
);
1073 int __safe_mount_beneath_at(int beneath_fd
, const char *src
, const char *dst
, const char *fstype
,
1074 unsigned int flags
, const void *data
)
1076 __do_close
int source_fd
= -EBADF
, target_fd
= -EBADF
;
1077 struct lxc_open_how how
= {
1078 .flags
= PROTECT_OPATH_DIRECTORY
,
1079 .resolve
= PROTECT_LOOKUP_BENEATH_WITH_MAGICLINKS
,
1082 char src_buf
[LXC_PROC_PID_FD_LEN
], tgt_buf
[LXC_PROC_PID_FD_LEN
];
1087 if ((flags
& MS_BIND
) && src
&& src
[0] != '/') {
1088 source_fd
= openat2(beneath_fd
, src
, &how
, sizeof(how
));
1091 ret
= strnprintf(src_buf
, sizeof(src_buf
), "/proc/self/fd/%d", source_fd
);
1098 target_fd
= openat2(beneath_fd
, dst
, &how
, sizeof(how
));
1100 return log_error_errno(-errno
, errno
, "Failed to open %d(%s)", beneath_fd
, dst
);
1101 ret
= strnprintf(tgt_buf
, sizeof(tgt_buf
), "/proc/self/fd/%d", target_fd
);
1105 if (!is_empty_string(src_buf
))
1106 ret
= mount(src_buf
, tgt_buf
, fstype
, flags
, data
);
1108 ret
= mount(src
, tgt_buf
, fstype
, flags
, data
);
1113 int safe_mount_beneath(const char *beneath
, const char *src
, const char *dst
, const char *fstype
,
1114 unsigned int flags
, const void *data
)
1116 __do_close
int beneath_fd
= -EBADF
;
1117 const char *path
= beneath
? beneath
: "/";
1119 beneath_fd
= openat(-1, path
, PROTECT_OPATH_DIRECTORY
);
1121 return log_error_errno(-errno
, errno
, "Failed to open %s", path
);
1123 return __safe_mount_beneath_at(beneath_fd
, src
, dst
, fstype
, flags
, data
);
1126 int safe_mount_beneath_at(int beneath_fd
, const char *src
, const char *dst
, const char *fstype
,
1127 unsigned int flags
, const void *data
)
1129 return __safe_mount_beneath_at(beneath_fd
, src
, dst
, fstype
, flags
, data
);
1133 * Safely mount a path into a container, ensuring that the mount target
1134 * is under the container's @rootfs. (If @rootfs is NULL, then the container
1135 * uses the host's /)
1137 * CAVEAT: This function must not be used for other purposes than container
1138 * setup before executing the container's init
1140 int safe_mount(const char *src
, const char *dest
, const char *fstype
,
1141 unsigned long flags
, const void *data
, const char *rootfs
)
1143 int destfd
, ret
, saved_errno
;
1144 /* Only needs enough for /proc/self/fd/<fd>. */
1145 char srcbuf
[50], destbuf
[50];
1147 const char *mntsrc
= src
;
1152 /* todo - allow symlinks for relative paths if 'allowsymlinks' option is passed */
1153 if (flags
& MS_BIND
&& src
&& src
[0] != '/') {
1154 INFO("This is a relative bind mount");
1156 srcfd
= open_without_symlink(src
, NULL
);
1160 ret
= strnprintf(srcbuf
, sizeof(srcbuf
), "/proc/self/fd/%d", srcfd
);
1163 ERROR("Out of memory");
1169 destfd
= open_without_symlink(dest
, rootfs
);
1172 saved_errno
= errno
;
1174 errno
= saved_errno
;
1180 ret
= strnprintf(destbuf
, sizeof(destbuf
), "/proc/self/fd/%d", destfd
);
1186 ERROR("Out of memory");
1190 ret
= mount(mntsrc
, destbuf
, fstype
, flags
, data
);
1191 saved_errno
= errno
;
1197 errno
= saved_errno
;
1198 SYSERROR("Failed to mount \"%s\" onto \"%s\"", src
? src
: "(null)", dest
);
1205 int open_devnull(void)
1207 int fd
= open("/dev/null", O_RDWR
);
1209 SYSERROR("Can't open /dev/null");
1214 int set_stdfds(int fd
)
1221 ret
= dup2(fd
, STDIN_FILENO
);
1225 ret
= dup2(fd
, STDOUT_FILENO
);
1229 ret
= dup2(fd
, STDERR_FILENO
);
1236 int null_stdfds(void)
1241 fd
= open_devnull();
1243 ret
= set_stdfds(fd
);
1250 /* Check whether a signal is blocked by a process. */
1251 /* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
1252 #define __PROC_STATUS_LEN (6 + INTTYPE_TO_STRLEN(pid_t) + 7 + 1)
1253 bool task_blocks_signal(pid_t pid
, int signal
)
1255 __do_free
char *line
= NULL
;
1256 __do_fclose
FILE *f
= NULL
;
1258 char status
[__PROC_STATUS_LEN
] = {0};
1259 uint64_t sigblk
= 0, one
= 1;
1263 ret
= strnprintf(status
, sizeof(status
), "/proc/%d/status", pid
);
1267 f
= fopen(status
, "re");
1271 while (getline(&line
, &n
, f
) != -1) {
1274 if (!strnequal(line
, "SigBlk:", 7))
1277 numstr
= lxc_trim_whitespace_in_place(line
+ 7);
1278 ret
= lxc_safe_uint64(numstr
, &sigblk
, 16);
1285 if (sigblk
& (one
<< (signal
- 1)))
1291 int lxc_preserve_ns(const int pid
, const char *ns
)
1294 /* 5 /proc + 21 /int_as_str + 3 /ns + 20 /NS_NAME + 1 \0 */
1295 #define __NS_PATH_LEN 50
1296 char path
[__NS_PATH_LEN
];
1298 /* This way we can use this function to also check whether namespaces
1299 * are supported by the kernel by passing in the NULL or the empty
1302 ret
= strnprintf(path
, sizeof(path
), "/proc/%d/ns%s%s", pid
,
1303 !ns
|| strequal(ns
, "") ? "" : "/",
1304 !ns
|| strequal(ns
, "") ? "" : ns
);
1306 return ret_errno(EIO
);
1308 return open(path
, O_RDONLY
| O_CLOEXEC
);
1311 bool lxc_switch_uid_gid(uid_t uid
, gid_t gid
)
1315 if (gid
!= LXC_INVALID_GID
) {
1316 ret
= setresgid(gid
, gid
, gid
);
1318 SYSERROR("Failed to switch to gid %d", gid
);
1321 NOTICE("Switched to gid %d", gid
);
1324 if (uid
!= LXC_INVALID_UID
) {
1325 ret
= setresuid(uid
, uid
, uid
);
1327 SYSERROR("Failed to switch to uid %d", uid
);
1330 NOTICE("Switched to uid %d", uid
);
1336 /* Simple convenience function which enables uniform logging. */
1337 bool lxc_drop_groups(void)
1341 ret
= setgroups(0, NULL
);
1343 return log_error_errno(false, errno
, "Failed to drop supplimentary groups");
1345 NOTICE("Dropped supplimentary groups");
1349 bool lxc_setgroups(gid_t list
[], size_t size
)
1353 ret
= setgroups(size
, list
);
1355 return log_error_errno(false, errno
, "Failed to set supplimentary groups");
1357 if (size
> 0 && lxc_log_trace()) {
1358 for (size_t i
= 0; i
< size
; i
++)
1359 TRACE("Setting supplimentary group %d", list
[i
]);
1362 NOTICE("Set supplimentary groups");
1366 static int lxc_get_unused_loop_dev_legacy(char *loop_name
)
1369 struct loop_info64 lo64
;
1371 int dfd
= -1, fd
= -1, ret
= -1;
1373 dir
= opendir("/dev");
1375 SYSERROR("Failed to open \"/dev\"");
1379 while ((dp
= readdir(dir
))) {
1380 if (!strnequal(dp
->d_name
, "loop", 4))
1387 fd
= openat(dfd
, dp
->d_name
, O_RDWR
);
1391 ret
= ioctl(fd
, LOOP_GET_STATUS64
, &lo64
);
1393 if (ioctl(fd
, LOOP_GET_STATUS64
, &lo64
) == 0 ||
1401 ret
= strnprintf(loop_name
, LO_NAME_SIZE
, "/dev/%s", dp
->d_name
);
1419 static int lxc_get_unused_loop_dev(char *name_loop
)
1422 int fd_ctl
= -1, fd_tmp
= -1;
1424 fd_ctl
= open("/dev/loop-control", O_RDWR
| O_CLOEXEC
);
1426 SYSERROR("Failed to open loop control");
1430 loop_nr
= ioctl(fd_ctl
, LOOP_CTL_GET_FREE
);
1432 SYSERROR("Failed to get loop control");
1436 ret
= strnprintf(name_loop
, LO_NAME_SIZE
, "/dev/loop%d", loop_nr
);
1440 fd_tmp
= open(name_loop
, O_RDWR
| O_CLOEXEC
);
1442 /* on Android loop devices are moved under /dev/block, give it a shot */
1443 ret
= strnprintf(name_loop
, LO_NAME_SIZE
, "/dev/block/loop%d", loop_nr
);
1447 fd_tmp
= open(name_loop
, O_RDWR
| O_CLOEXEC
);
1449 SYSERROR("Failed to open loop \"%s\"", name_loop
);
1457 int lxc_prepare_loop_dev(const char *source
, char *loop_dev
, int flags
)
1460 struct loop_info64 lo64
;
1461 int fd_img
= -1, fret
= -1, fd_loop
= -1;
1463 fd_loop
= lxc_get_unused_loop_dev(loop_dev
);
1465 if (fd_loop
!= -ENODEV
)
1468 fd_loop
= lxc_get_unused_loop_dev_legacy(loop_dev
);
1473 fd_img
= open(source
, O_RDWR
| O_CLOEXEC
);
1475 SYSERROR("Failed to open source \"%s\"", source
);
1479 ret
= ioctl(fd_loop
, LOOP_SET_FD
, fd_img
);
1481 SYSERROR("Failed to set loop fd");
1485 memset(&lo64
, 0, sizeof(lo64
));
1486 lo64
.lo_flags
= flags
;
1488 strlcpy((char *)lo64
.lo_file_name
, source
, LO_NAME_SIZE
);
1490 ret
= ioctl(fd_loop
, LOOP_SET_STATUS64
, &lo64
);
1492 SYSERROR("Failed to set loop status64");
1502 if (fret
< 0 && fd_loop
>= 0) {
1510 int lxc_unstack_mountpoint(const char *path
, bool lazy
)
1516 ret
= umount2(path
, lazy
? MNT_DETACH
: 0);
1518 /* We consider anything else than EINVAL deadly to prevent going
1519 * into an infinite loop. (The other alternative is constantly
1520 * parsing /proc/self/mountinfo which is yucky and probably
1523 if (errno
!= EINVAL
)
1526 /* Just stop counting when this happens. That'd just be so
1527 * stupid that we won't even bother trying to report back the
1528 * correct value anymore.
1530 if (umounts
!= INT_MAX
)
1533 /* We succeeded in umounting. Make sure that there's no other
1534 * mountpoint stacked underneath.
1542 static int run_command_internal(char *buf
, size_t buf_size
, int (*child_fn
)(void *), void *args
, bool wait_status
)
1545 int ret
, fret
, pipefd
[2];
1548 /* Make sure our callers do not receive uninitialized memory. */
1549 if (buf_size
> 0 && buf
)
1552 if (pipe(pipefd
) < 0) {
1553 SYSERROR("Failed to create pipe");
1557 child
= lxc_raw_clone(0, NULL
);
1561 SYSERROR("Failed to create new process");
1566 /* Close the read-end of the pipe. */
1569 /* Redirect std{err,out} to write-end of the
1572 ret
= dup2(pipefd
[1], STDOUT_FILENO
);
1574 ret
= dup2(pipefd
[1], STDERR_FILENO
);
1576 /* Close the write-end of the pipe. */
1580 SYSERROR("Failed to duplicate std{err,out} file descriptor");
1581 _exit(EXIT_FAILURE
);
1584 /* Does not return. */
1586 ERROR("Failed to exec command");
1587 _exit(EXIT_FAILURE
);
1590 /* close the write-end of the pipe */
1593 if (buf
&& buf_size
> 0) {
1594 bytes
= lxc_read_nointr(pipefd
[0], buf
, buf_size
- 1);
1596 buf
[bytes
- 1] = '\0';
1600 fret
= lxc_wait_for_pid_status(child
);
1602 fret
= wait_for_pid(child
);
1604 /* close the read-end of the pipe */
1610 int run_command(char *buf
, size_t buf_size
, int (*child_fn
)(void *), void *args
)
1612 return run_command_internal(buf
, buf_size
, child_fn
, args
, false);
1615 int run_command_status(char *buf
, size_t buf_size
, int (*child_fn
)(void *), void *args
)
1617 return run_command_internal(buf
, buf_size
, child_fn
, args
, true);
1620 bool lxc_nic_exists(char *nic
)
1622 #define __LXC_SYS_CLASS_NET_LEN 15 + IFNAMSIZ + 1
1623 char path
[__LXC_SYS_CLASS_NET_LEN
];
1627 if (strequal(nic
, "none"))
1630 ret
= strnprintf(path
, sizeof(path
), "/sys/class/net/%s", nic
);
1634 ret
= stat(path
, &sb
);
1641 uint64_t lxc_find_next_power2(uint64_t n
)
1643 /* 0 is not valid input. We return 0 to the caller since 0 is not a
1644 * valid power of two.
1659 static int process_dead(/* takes */ int status_fd
)
1661 __do_close
int dupfd
= -EBADF
;
1662 __do_free
char *line
= NULL
;
1663 __do_fclose
FILE *f
= NULL
;
1667 dupfd
= dup(status_fd
);
1671 if (fd_cloexec(dupfd
, true) < 0)
1674 f
= fdopen(dupfd
, "re");
1678 /* Transfer ownership of fd. */
1682 while (getline(&line
, &n
, f
) != -1) {
1685 if (!strnequal(line
, "State:", 6))
1688 state
= lxc_trim_whitespace_in_place(line
+ 6);
1689 /* only check whether process is dead or zombie for now */
1690 if (*state
== 'X' || *state
== 'Z')
1697 int lxc_set_death_signal(int signal
, pid_t parent
, int parent_status_fd
)
1702 ret
= prctl(PR_SET_PDEATHSIG
, prctl_arg(signal
), prctl_arg(0),
1703 prctl_arg(0), prctl_arg(0));
1705 /* verify that we haven't been orphaned in the meantime */
1706 ppid
= (pid_t
)syscall(SYS_getppid
);
1707 if (ppid
== 0) { /* parent outside our pidns */
1708 if (parent_status_fd
< 0)
1711 if (process_dead(parent_status_fd
) == 1)
1712 return raise(SIGKILL
);
1713 } else if (ppid
!= parent
) {
1714 return raise(SIGKILL
);
1723 int lxc_rm_rf(const char *dirname
)
1725 __do_closedir
DIR *dir
= NULL
;
1728 struct dirent
*direntp
;
1730 dir
= opendir(dirname
);
1732 return log_error_errno(-1, errno
, "Failed to open dir \"%s\"", dirname
);
1734 while ((direntp
= readdir(dir
))) {
1735 __do_free
char *pathname
= NULL
;
1738 if (strequal(direntp
->d_name
, ".") ||
1739 strequal(direntp
->d_name
, ".."))
1742 pathname
= must_make_path(dirname
, direntp
->d_name
, NULL
);
1743 ret
= lstat(pathname
, &mystat
);
1746 SYSWARN("Failed to stat \"%s\"", pathname
);
1752 if (!S_ISDIR(mystat
.st_mode
))
1755 ret
= lxc_rm_rf(pathname
);
1760 ret
= rmdir(dirname
);
1762 return log_warn_errno(-1, errno
, "Failed to delete \"%s\"", dirname
);
1767 bool lxc_can_use_pidfd(int pidfd
)
1772 return log_error(false, "Kernel does not support pidfds");
1775 * We don't care whether or not children were in a waitable state. We
1776 * just care whether waitid() recognizes P_PIDFD.
1778 * Btw, while I have your attention, the above waitid() code is an
1779 * excellent example of how _not_ to do flag-based kernel APIs. So if
1780 * you ever go into kernel development or are already and you add this
1781 * kind of flag potpourri even though you have read this comment shame
1782 * on you. May the gods of operating system development have mercy on
1783 * your soul because I won't.
1785 ret
= waitid(P_PIDFD
, pidfd
, NULL
,
1786 /* Type of children to wait for. */
1788 /* How to wait for them. */
1790 /* What state to wait for. */
1791 WEXITED
| WSTOPPED
| WCONTINUED
);
1793 return log_error_errno(false, errno
, "Kernel does not support waiting on processes through pidfds");
1795 ret
= lxc_raw_pidfd_send_signal(pidfd
, 0, NULL
, 0);
1797 return log_error_errno(false, errno
, "Kernel does not support sending singals through pidfds");
1799 return log_trace(true, "Kernel supports pidfds");
1802 int fix_stdio_permissions(uid_t uid
)
1804 __do_close
int devnull_fd
= -EBADF
;
1806 int std_fds
[] = {STDIN_FILENO
, STDOUT_FILENO
, STDERR_FILENO
};
1808 struct stat st
, st_null
;
1810 devnull_fd
= open_devnull();
1812 return log_trace_errno(-1, errno
, "Failed to open \"/dev/null\"");
1814 ret
= fstat(devnull_fd
, &st_null
);
1816 return log_trace_errno(-errno
, errno
, "Failed to stat \"/dev/null\"");
1818 for (int i
= 0; i
< ARRAY_SIZE(std_fds
); i
++) {
1819 ret
= fstat(std_fds
[i
], &st
);
1821 SYSWARN("Failed to stat standard I/O file descriptor %d", std_fds
[i
]);
1826 if (st
.st_rdev
== st_null
.st_rdev
)
1829 ret
= fchown(std_fds
[i
], uid
, st
.st_gid
);
1831 SYSTRACE("Failed to chown standard I/O file descriptor %d to uid %d and gid %d",
1832 std_fds
[i
], uid
, st
.st_gid
);
1837 ret
= fchmod(std_fds
[i
], 0700);
1839 SYSTRACE("Failed to chmod standard I/O file descriptor %d", std_fds
[i
]);
1847 bool multiply_overflow(int64_t base
, uint64_t mult
, int64_t *res
)
1849 if (base
> 0 && base
> (INT64_MAX
/ mult
))
1852 if (base
< 0 && base
< (INT64_MIN
/ mult
))
1859 int print_r(int fd
, const char *path
)
1861 __do_close
int dfd
= -EBADF
, dfd_dup
= -EBADF
;
1862 __do_closedir
DIR *dir
= NULL
;
1864 struct dirent
*direntp
;
1867 if (is_empty_string(path
)) {
1868 char buf
[LXC_PROC_SELF_FD_LEN
];
1870 ret
= strnprintf(buf
, sizeof(buf
), "/proc/self/fd/%d", fd
);
1872 return ret_errno(EIO
);
1875 * O_PATH file descriptors can't be used so we need to re-open
1878 dfd
= openat(-EBADF
, buf
, O_CLOEXEC
| O_DIRECTORY
, 0);
1880 dfd
= openat(fd
, path
, O_CLOEXEC
| O_DIRECTORY
, 0);
1885 dfd_dup
= dup_cloexec(dfd
);
1889 dir
= fdopendir(dfd
);
1892 /* Transfer ownership to fdopendir(). */
1895 while ((direntp
= readdir(dir
))) {
1896 if (!strcmp(direntp
->d_name
, ".") ||
1897 !strcmp(direntp
->d_name
, ".."))
1900 ret
= fstatat(dfd_dup
, direntp
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
);
1901 if (ret
< 0 && errno
!= ENOENT
)
1905 if (S_ISDIR(st
.st_mode
))
1906 ret
= print_r(dfd_dup
, direntp
->d_name
);
1908 INFO("mode(%o):uid(%d):gid(%d) -> %d/%s\n",
1909 (st
.st_mode
& ~S_IFMT
), st
.st_uid
, st
.st_gid
, dfd_dup
,
1911 if (ret
< 0 && errno
!= ENOENT
)
1915 if (is_empty_string(path
))
1916 ret
= fstatat(fd
, "", &st
, AT_NO_AUTOMOUNT
| AT_SYMLINK_NOFOLLOW
| AT_EMPTY_PATH
);
1918 ret
= fstatat(fd
, path
, &st
, AT_NO_AUTOMOUNT
| AT_SYMLINK_NOFOLLOW
);
1922 INFO("mode(%o):uid(%d):gid(%d) -> %s",
1923 (st
.st_mode
& ~S_IFMT
), st
.st_uid
, st
.st_gid
, maybe_empty(path
));