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 /* We have two different magic values for overlayfs, yay. */
170 #ifndef OVERLAYFS_SUPER_MAGIC
171 #define OVERLAYFS_SUPER_MAGIC 0x794c764f
174 #ifndef OVERLAY_SUPER_MAGIC
175 #define OVERLAY_SUPER_MAGIC 0x794c7630
178 /* In overlayfs, st_dev is unreliable. So on overlayfs we don't do the
181 static bool is_native_overlayfs(const char *path
)
183 if (has_fs_type(path
, OVERLAY_SUPER_MAGIC
) ||
184 has_fs_type(path
, OVERLAYFS_SUPER_MAGIC
))
190 /* returns 0 on success, -1 if there were any failures */
191 extern int lxc_rmdir_onedev(const char *path
, const char *exclude
)
196 if (is_native_overlayfs(path
))
199 if (lstat(path
, &mystat
) < 0) {
203 ERROR("Failed to stat %s", path
);
207 return _recursive_rmdir(path
, mystat
.st_dev
, exclude
, 0, onedev
);
210 /* borrowed from iproute2 */
211 extern int get_u16(unsigned short *val
, const char *arg
, int base
)
220 res
= strtoul(arg
, &ptr
, base
);
221 if (!ptr
|| ptr
== arg
|| *ptr
|| res
> 0xFFFF || errno
!= 0)
229 extern int mkdir_p(const char *dir
, mode_t mode
)
231 const char *tmp
= dir
;
232 const char *orig
= dir
;
236 dir
= tmp
+ strspn(tmp
, "/");
237 tmp
= dir
+ strcspn(dir
, "/");
239 makeme
= strndup(orig
, dir
- orig
);
241 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
242 SYSERROR("failed to create directory '%s'", makeme
);
259 if (stat(RUNTIME_PATH
, &sb
) < 0)
262 if (geteuid() == sb
.st_uid
|| getegid() == sb
.st_gid
) {
263 rundir
= strdup(RUNTIME_PATH
);
267 rundir
= getenv("XDG_RUNTIME_DIR");
269 rundir
= strdup(rundir
);
273 INFO("XDG_RUNTIME_DIR isn't set in the environment.");
274 homedir
= getenv("HOME");
276 ERROR("HOME isn't set in the environment.");
280 rundir
= malloc(sizeof(char) * (17 + strlen(homedir
)));
284 sprintf(rundir
, "%s/.cache/lxc/run/", homedir
);
289 int wait_for_pid(pid_t pid
)
294 ret
= waitpid(pid
, &status
, 0);
305 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
311 int lxc_wait_for_pid_status(pid_t pid
)
316 ret
= waitpid(pid
, &status
, 0);
330 ssize_t
lxc_write_nointr(int fd
, const void *buf
, size_t count
)
334 ret
= write(fd
, buf
, count
);
335 if (ret
< 0 && errno
== EINTR
)
341 ssize_t
lxc_read_nointr(int fd
, void *buf
, size_t count
)
345 ret
= read(fd
, buf
, count
);
346 if (ret
< 0 && errno
== EINTR
)
352 ssize_t
lxc_read_nointr_expect(int fd
, void *buf
, size_t count
, const void *expected_buf
)
356 ret
= lxc_read_nointr(fd
, buf
, count
);
360 if ((size_t)ret
!= count
)
363 if (expected_buf
&& memcmp(buf
, expected_buf
, count
) != 0) {
372 #include <gnutls/gnutls.h>
373 #include <gnutls/crypto.h>
375 __attribute__((constructor
))
376 static void gnutls_lxc_init(void)
378 gnutls_global_init();
381 int sha1sum_file(char *fnam
, unsigned char *digest
)
391 f
= fopen_cloexec(fnam
, "r");
393 SYSERROR("Error opening template");
397 if (fseek(f
, 0, SEEK_END
) < 0) {
398 SYSERROR("Error seeking to end of template");
403 if ((flen
= ftell(f
)) < 0) {
404 SYSERROR("Error telling size of template");
409 if (fseek(f
, 0, SEEK_SET
) < 0) {
410 SYSERROR("Error seeking to start of template");
415 if ((buf
= malloc(flen
+1)) == NULL
) {
416 SYSERROR("Out of memory");
421 if (fread(buf
, 1, flen
, f
) != flen
) {
422 SYSERROR("Failure reading template");
429 SYSERROR("Failre closing template");
435 ret
= gnutls_hash_fast(GNUTLS_DIG_SHA1
, buf
, flen
, (void *)digest
);
441 char** lxc_va_arg_list_to_argv(va_list ap
, size_t skip
, int do_strdup
)
444 size_t count
= 1 + skip
;
447 /* first determine size of argument list, we don't want to reallocate
452 char* arg
= va_arg(ap2
, char*);
459 result
= calloc(count
, sizeof(char*));
465 char* arg
= va_arg(ap
, char*);
468 arg
= do_strdup
? strdup(arg
) : arg
;
471 result
[count
++] = arg
;
474 /* calloc has already set last element to NULL*/
482 const char** lxc_va_arg_list_to_argv_const(va_list ap
, size_t skip
)
484 return (const char**)lxc_va_arg_list_to_argv(ap
, skip
, 0);
487 struct lxc_popen_FILE
*lxc_popen(const char *command
)
492 struct lxc_popen_FILE
*fp
= NULL
;
494 ret
= pipe2(pipe_fds
, O_CLOEXEC
);
507 /* duplicate stdout */
508 if (pipe_fds
[1] != STDOUT_FILENO
)
509 ret
= dup2(pipe_fds
[1], STDOUT_FILENO
);
511 ret
= fcntl(pipe_fds
[1], F_SETFD
, 0);
517 /* duplicate stderr */
518 if (pipe_fds
[1] != STDERR_FILENO
)
519 ret
= dup2(pipe_fds
[1], STDERR_FILENO
);
521 ret
= fcntl(pipe_fds
[1], F_SETFD
, 0);
526 /* unblock all signals */
527 ret
= sigfillset(&mask
);
531 ret
= pthread_sigmask(SIG_UNBLOCK
, &mask
, NULL
);
535 execl("/bin/sh", "sh", "-c", command
, (char *)NULL
);
542 fp
= malloc(sizeof(*fp
));
546 memset(fp
, 0, sizeof(*fp
));
548 fp
->child_pid
= child_pid
;
549 fp
->pipe
= pipe_fds
[0];
551 /* From now on, closing fp->f will also close fp->pipe. So only ever
552 * call fclose(fp->f).
554 fp
->f
= fdopen(pipe_fds
[0], "r");
561 /* We can only close pipe_fds[0] if fdopen() didn't succeed or wasn't
562 * called yet. Otherwise the fd belongs to the file opened by fdopen()
563 * since it isn't dup()ed.
565 if (fp
&& !fp
->f
&& pipe_fds
[0] >= 0)
568 if (pipe_fds
[1] >= 0)
580 int lxc_pclose(struct lxc_popen_FILE
*fp
)
589 wait_pid
= waitpid(fp
->child_pid
, &wstatus
, 0);
590 } while (wait_pid
< 0 && errno
== EINTR
);
601 char *lxc_string_replace(const char *needle
, const char *replacement
, const char *haystack
)
603 ssize_t len
= -1, saved_len
= -1;
605 size_t replacement_len
= strlen(replacement
);
606 size_t needle_len
= strlen(needle
);
608 /* should be executed exactly twice */
609 while (len
== -1 || result
== NULL
) {
615 result
= calloc(1, len
+ 1);
624 for (last_p
= (char *)haystack
, p
= strstr(last_p
, needle
); p
; last_p
= p
, p
= strstr(last_p
, needle
)) {
625 part_len
= (ssize_t
)(p
- last_p
);
626 if (result
&& part_len
> 0)
627 memcpy(&result
[len
], last_p
, part_len
);
631 if (result
&& replacement_len
> 0)
632 memcpy(&result
[len
], replacement
, replacement_len
);
634 len
+= replacement_len
;
638 part_len
= strlen(last_p
);
639 if (result
&& part_len
> 0)
640 memcpy(&result
[len
], last_p
, part_len
);
645 /* make sure we did the same thing twice,
646 * once for calculating length, the other
647 * time for copying data */
648 if (saved_len
!= len
) {
653 /* make sure we didn't overwrite any buffer,
654 * due to calloc the string should be 0-terminated */
655 if (result
[len
] != '\0') {
663 bool lxc_string_in_array(const char *needle
, const char **haystack
)
665 for (; haystack
&& *haystack
; haystack
++)
666 if (!strcmp(needle
, *haystack
))
672 char *lxc_string_join(const char *sep
, const char **parts
, bool use_as_prefix
)
676 size_t sep_len
= strlen(sep
);
677 size_t result_len
= use_as_prefix
* sep_len
;
680 /* calculate new string length */
681 for (p
= (char **)parts
; *p
; p
++)
682 result_len
+= (p
> (char **)parts
) * sep_len
+ strlen(*p
);
684 buf_len
= result_len
+ 1;
685 result
= calloc(buf_len
, 1);
690 (void)strlcpy(result
, sep
, buf_len
);
692 for (p
= (char **)parts
; *p
; p
++) {
693 if (p
> (char **)parts
)
694 (void)strlcat(result
, sep
, buf_len
);
696 (void)strlcat(result
, *p
, buf_len
);
702 char **lxc_normalize_path(const char *path
)
706 size_t components_len
= 0;
709 components
= lxc_string_split(path
, '/');
713 for (p
= components
; *p
; p
++)
716 /* resolve '.' and '..' */
717 for (pos
= 0; pos
< components_len
; ) {
718 if (!strcmp(components
[pos
], ".") || (!strcmp(components
[pos
], "..") && pos
== 0)) {
719 /* eat this element */
720 free(components
[pos
]);
721 memmove(&components
[pos
], &components
[pos
+1], sizeof(char *) * (components_len
- pos
));
723 } else if (!strcmp(components
[pos
], "..")) {
724 /* eat this and the previous element */
725 free(components
[pos
- 1]);
726 free(components
[pos
]);
727 memmove(&components
[pos
-1], &components
[pos
+1], sizeof(char *) * (components_len
- pos
));
738 char *lxc_deslashify(const char *path
)
748 parts
= lxc_normalize_path(dup
);
754 /* We'll end up here if path == "///" or path == "". */
758 lxc_free_array((void **)parts
, free
);
762 n
= strcspn(dup
, "/");
765 lxc_free_array((void **)parts
, free
);
775 p
= lxc_string_join("/", (const char **)parts
, *dup
== '/');
777 lxc_free_array((void **)parts
, free
);
781 char *lxc_append_paths(const char *first
, const char *second
)
786 const char *pattern
= "%s%s";
788 len
= strlen(first
) + strlen(second
) + 1;
789 if (second
[0] != '/') {
794 result
= calloc(1, len
);
798 ret
= snprintf(result
, len
, pattern
, first
, second
);
799 if (ret
< 0 || (size_t)ret
>= len
) {
807 bool lxc_string_in_list(const char *needle
, const char *haystack
, char _sep
)
810 char sep
[2] = { _sep
, '\0' };
813 if (!haystack
|| !needle
)
816 len
= strlen(haystack
);
817 str
= alloca(len
+ 1);
818 (void)strlcpy(str
, haystack
, len
+ 1);
820 lxc_iterate_parts(token
, str
, sep
)
821 if (strcmp(needle
, token
) == 0)
827 char **lxc_string_split(const char *string
, char _sep
)
830 char sep
[2] = {_sep
, '\0'};
831 char **tmp
= NULL
, **result
= NULL
;
832 size_t result_capacity
= 0;
833 size_t result_count
= 0;
838 return calloc(1, sizeof(char *));
840 len
= strlen(string
);
841 str
= alloca(len
+ 1);
842 (void)strlcpy(str
, string
, len
+ 1);
844 lxc_iterate_parts(token
, str
, sep
) {
845 r
= lxc_grow_array((void ***)&result
, &result_capacity
, result_count
+ 1, 16);
849 result
[result_count
] = strdup(token
);
850 if (!result
[result_count
])
856 /* if we allocated too much, reduce it */
857 tmp
= realloc(result
, (result_count
+ 1) * sizeof(char *));
863 /* Make sure we don't return uninitialized memory. */
864 if (result_count
== 0)
871 lxc_free_array((void **)result
, free
);
876 static bool complete_word(char ***result
, char *start
, char *end
, size_t *cap
, size_t *cnt
)
880 r
= lxc_grow_array((void ***)result
, cap
, 2 + *cnt
, 16);
884 (*result
)[*cnt
] = strndup(start
, end
- start
);
885 if (!(*result
)[*cnt
])
894 * Given a a string 'one two "three four"', split into three words,
895 * one, two, and "three four"
897 char **lxc_string_split_quoted(char *string
)
899 char *nextword
= string
, *p
, state
;
900 char **result
= NULL
;
901 size_t result_capacity
= 0;
902 size_t result_count
= 0;
904 if (!string
|| !*string
)
905 return calloc(1, sizeof(char *));
907 // TODO I'm *not* handling escaped quote
909 for (p
= string
; *p
; p
++) {
914 else if (*p
== '"' || *p
== '\'') {
924 complete_word(&result
, nextword
, p
, &result_capacity
, &result_count
);
932 complete_word(&result
, nextword
+1, p
, &result_capacity
, &result_count
);
941 complete_word(&result
, nextword
, p
, &result_capacity
, &result_count
);
943 return realloc(result
, (result_count
+ 1) * sizeof(char *));
946 char **lxc_string_split_and_trim(const char *string
, char _sep
)
949 char sep
[2] = { _sep
, '\0' };
950 char **result
= NULL
;
951 size_t result_capacity
= 0;
952 size_t result_count
= 0;
958 return calloc(1, sizeof(char *));
960 len
= strlen(string
);
961 str
= alloca(len
+ 1);
962 (void)strlcpy(str
, string
, len
+ 1);
964 lxc_iterate_parts(token
, str
, sep
) {
965 while (token
[0] == ' ' || token
[0] == '\t')
969 while (i
> 0 && (token
[i
- 1] == ' ' || token
[i
- 1] == '\t')) {
974 r
= lxc_grow_array((void ***)&result
, &result_capacity
, result_count
+ 1, 16);
978 result
[result_count
] = strdup(token
);
979 if (!result
[result_count
])
985 /* if we allocated too much, reduce it */
986 return realloc(result
, (result_count
+ 1) * sizeof(char *));
990 lxc_free_array((void **)result
, free
);
995 void lxc_free_array(void **array
, lxc_free_fn element_free_fn
)
999 for (p
= array
; p
&& *p
; p
++)
1000 element_free_fn(*p
);
1005 int lxc_grow_array(void ***array
, size_t *capacity
, size_t new_size
, size_t capacity_increment
)
1007 size_t new_capacity
;
1010 /* first time around, catch some trivial mistakes of the user
1011 * only initializing one of these */
1012 if (!*array
|| !*capacity
) {
1017 new_capacity
= *capacity
;
1018 while (new_size
+ 1 > new_capacity
)
1019 new_capacity
+= capacity_increment
;
1021 if (new_capacity
!= *capacity
) {
1022 /* we have to reallocate */
1023 new_array
= realloc(*array
, new_capacity
* sizeof(void *));
1027 memset(&new_array
[*capacity
], 0, (new_capacity
- (*capacity
)) * sizeof(void *));
1029 *capacity
= new_capacity
;
1032 /* array has sufficient elements */
1036 size_t lxc_array_len(void **array
)
1041 for (p
= array
; p
&& *p
; p
++)
1047 int lxc_write_to_file(const char *filename
, const void *buf
, size_t count
,
1048 bool add_newline
, mode_t mode
)
1050 int fd
, saved_errno
;
1053 fd
= open(filename
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_CLOEXEC
, mode
);
1057 ret
= lxc_write_nointr(fd
, buf
, count
);
1061 if ((size_t)ret
!= count
)
1065 ret
= lxc_write_nointr(fd
, "\n", 1);
1074 saved_errno
= errno
;
1076 errno
= saved_errno
;
1080 int lxc_read_from_file(const char *filename
, void *buf
, size_t count
)
1082 int fd
= -1, saved_errno
;
1085 fd
= open(filename
, O_RDONLY
| O_CLOEXEC
);
1089 if (!buf
|| !count
) {
1093 while ((ret
= lxc_read_nointr(fd
, buf2
, 100)) > 0)
1099 memset(buf
, 0, count
);
1100 ret
= lxc_read_nointr(fd
, buf
, count
);
1104 SYSERROR("Read %s", filename
);
1106 saved_errno
= errno
;
1108 errno
= saved_errno
;
1112 void **lxc_append_null_to_array(void **array
, size_t count
)
1116 /* Append NULL to the array */
1118 temp
= realloc(array
, (count
+ 1) * sizeof(*array
));
1121 for (i
= 0; i
< count
; i
++)
1128 array
[count
] = NULL
;
1134 int randseed(bool srand_it
)
1137 srand pre-seed function based on /dev/urandom
1139 unsigned int seed
= time(NULL
) + getpid();
1142 f
= fopen("/dev/urandom", "r");
1144 int ret
= fread(&seed
, sizeof(seed
), 1, f
);
1146 SYSDEBUG("unable to fread /dev/urandom, fallback to time+pid rand seed");
1157 uid_t
get_ns_uid(uid_t orig
)
1161 uid_t nsid
, hostid
, range
;
1162 FILE *f
= fopen("/proc/self/uid_map", "r");
1166 while (getline(&line
, &sz
, f
) != -1) {
1167 if (sscanf(line
, "%u %u %u", &nsid
, &hostid
, &range
) != 3)
1170 if (hostid
<= orig
&& hostid
+ range
> orig
) {
1171 nsid
+= orig
- hostid
;
1184 bool dir_exists(const char *path
)
1189 ret
= stat(path
, &sb
);
1191 /* Could be something other than eexist, just say "no". */
1194 return S_ISDIR(sb
.st_mode
);
1197 /* Note we don't use SHA-1 here as we don't want to depend on HAVE_GNUTLS.
1198 * FNV has good anti collision properties and we're not worried
1199 * about pre-image resistance or one-way-ness, we're just trying to make
1200 * the name unique in the 108 bytes of space we have.
1202 uint64_t fnv_64a_buf(void *buf
, size_t len
, uint64_t hval
)
1206 for(bp
= buf
; bp
< (unsigned char *)buf
+ len
; bp
++)
1208 /* xor the bottom with the current octet */
1209 hval
^= (uint64_t)*bp
;
1212 * multiply by the 64 bit FNV magic prime mod 2^64
1214 hval
+= (hval
<< 1) + (hval
<< 4) + (hval
<< 5) +
1215 (hval
<< 7) + (hval
<< 8) + (hval
<< 40);
1221 bool is_shared_mountpoint(const char *path
)
1223 char buf
[LXC_LINELEN
];
1228 f
= fopen("/proc/self/mountinfo", "r");
1232 while (fgets(buf
, LXC_LINELEN
, f
)) {
1233 for (p
= buf
, i
= 0; p
&& i
< 4; i
++)
1234 p
= strchr(p
+ 1, ' ');
1238 p2
= strchr(p
+ 1, ' ');
1243 if (strcmp(p
+ 1, path
) == 0) {
1244 /* This is the path. Is it shared? */
1245 p
= strchr(p2
+ 1, ' ');
1246 if (p
&& strstr(p
, "shared:")) {
1258 * Detect whether / is mounted MS_SHARED. The only way I know of to
1259 * check that is through /proc/self/mountinfo.
1260 * I'm only checking for /. If the container rootfs or mount location
1261 * is MS_SHARED, but not '/', then you're out of luck - figuring that
1262 * out would be too much work to be worth it.
1264 int detect_shared_rootfs(void)
1266 if (is_shared_mountpoint("/"))
1271 bool switch_to_ns(pid_t pid
, const char *ns
) {
1273 char nspath
[MAXPATHLEN
];
1275 /* Switch to new ns */
1276 ret
= snprintf(nspath
, MAXPATHLEN
, "/proc/%d/ns/%s", pid
, ns
);
1277 if (ret
< 0 || ret
>= MAXPATHLEN
)
1280 fd
= open(nspath
, O_RDONLY
);
1282 SYSERROR("Failed to open %s", nspath
);
1288 SYSERROR("Failed to set process %d to %s of %d.", pid
, ns
, fd
);
1298 * looking at fs/proc_namespace.c, it appears we can
1299 * actually expect the rootfs entry to very specifically contain
1300 * " - rootfs rootfs "
1301 * IIUC, so long as we've chrooted so that rootfs is not our root,
1302 * the rootfs entry should always be skipped in mountinfo contents.
1304 bool detect_ramfs_rootfs(void)
1312 f
= fopen("/proc/self/mountinfo", "r");
1316 while (getline(&line
, &len
, f
) != -1) {
1317 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
1318 p
= strchr(p
+ 1, ' ');
1322 p2
= strchr(p
+ 1, ' ');
1327 if (strcmp(p
+ 1, "/") == 0) {
1328 /* This is '/'. Is it the ramfs? */
1329 p
= strchr(p2
+ 1, '-');
1330 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
1333 INFO("Rootfs is located on ramfs");
1344 char *on_path(const char *cmd
, const char *rootfs
) {
1345 char *entry
= NULL
, *path
= NULL
;
1346 char cmdpath
[MAXPATHLEN
];
1349 path
= getenv("PATH");
1353 path
= strdup(path
);
1357 lxc_iterate_parts(entry
, path
, ":") {
1359 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s/%s", rootfs
, entry
, cmd
);
1361 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s", entry
, cmd
);
1362 if (ret
< 0 || ret
>= MAXPATHLEN
)
1365 if (access(cmdpath
, X_OK
) == 0) {
1367 return strdup(cmdpath
);
1375 bool file_exists(const char *f
)
1377 struct stat statbuf
;
1379 return stat(f
, &statbuf
) == 0;
1382 bool cgns_supported(void)
1384 return file_exists("/proc/self/ns/cgroup");
1387 /* historically lxc-init has been under /usr/lib/lxc and under
1388 * /usr/lib/$ARCH/lxc. It now lives as $prefix/sbin/init.lxc.
1390 char *choose_init(const char *rootfs
)
1393 const char *empty
= "",
1395 int ret
, env_set
= 0;
1397 if (!getenv("PATH")) {
1398 if (setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 0))
1399 SYSERROR("Failed to setenv");
1404 retv
= on_path("init.lxc", rootfs
);
1407 if (unsetenv("PATH"))
1408 SYSERROR("Failed to unsetenv");
1414 retv
= malloc(PATH_MAX
);
1423 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, SBINDIR
, "/init.lxc");
1424 if (ret
< 0 || ret
>= PATH_MAX
) {
1425 ERROR("pathname too long");
1429 if (access(retv
, X_OK
) == 0)
1432 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, LXCINITDIR
, "/lxc/lxc-init");
1433 if (ret
< 0 || ret
>= PATH_MAX
) {
1434 ERROR("pathname too long");
1438 if (access(retv
, X_OK
) == 0)
1441 ret
= snprintf(retv
, PATH_MAX
, "%s/usr/lib/lxc/lxc-init", tmp
);
1442 if (ret
< 0 || ret
>= PATH_MAX
) {
1443 ERROR("pathname too long");
1447 if (access(retv
, X_OK
) == 0)
1450 ret
= snprintf(retv
, PATH_MAX
, "%s/sbin/lxc-init", tmp
);
1451 if (ret
< 0 || ret
>= PATH_MAX
) {
1452 ERROR("pathname too long");
1456 if (access(retv
, X_OK
) == 0)
1460 * Last resort, look for the statically compiled init.lxc which we
1461 * hopefully bind-mounted in.
1462 * If we are called during container setup, and we get to this point,
1463 * then the init.lxc.static from the host will need to be bind-mounted
1464 * in. So we return NULL here to indicate that.
1469 ret
= snprintf(retv
, PATH_MAX
, "/init.lxc.static");
1470 if (ret
< 0 || ret
>= PATH_MAX
) {
1471 WARN("Nonsense - name /lxc.init.static too long");
1475 if (access(retv
, X_OK
) == 0)
1483 int print_to_file(const char *file
, const char *content
)
1488 f
= fopen(file
, "w");
1492 if (fprintf(f
, "%s", content
) != strlen(content
))
1499 int is_dir(const char *path
)
1501 struct stat statbuf
;
1504 ret
= stat(path
, &statbuf
);
1505 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
1512 * Given the '-t' template option to lxc-create, figure out what to
1513 * do. If the template is a full executable path, use that. If it
1514 * is something like 'sshd', then return $templatepath/lxc-sshd.
1515 * On success return the template, on error return NULL.
1517 char *get_template_path(const char *t
)
1522 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
1527 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
1529 tpath
= malloc(len
);
1533 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
1534 if (ret
< 0 || ret
>= len
) {
1539 if (access(tpath
, X_OK
) < 0) {
1540 SYSERROR("bad template: %s", t
);
1549 * @path: a pathname where / replaced with '\0'.
1550 * @offsetp: pointer to int showing which path segment was last seen.
1551 * Updated on return to reflect the next segment.
1552 * @fulllen: full original path length.
1553 * Returns a pointer to the next path segment, or NULL if done.
1555 static char *get_nextpath(char *path
, int *offsetp
, int fulllen
)
1557 int offset
= *offsetp
;
1559 if (offset
>= fulllen
)
1562 while (path
[offset
] != '\0' && offset
< fulllen
)
1565 while (path
[offset
] == '\0' && offset
< fulllen
)
1569 return (offset
< fulllen
) ? &path
[offset
] : NULL
;
1573 * Check that @subdir is a subdir of @dir. @len is the length of
1574 * @dir (to avoid having to recalculate it).
1576 static bool is_subdir(const char *subdir
, const char *dir
, size_t len
)
1578 size_t subdirlen
= strlen(subdir
);
1580 if (subdirlen
< len
)
1583 if (strncmp(subdir
, dir
, len
) != 0)
1586 if (dir
[len
-1] == '/')
1589 if (subdir
[len
] == '/' || subdirlen
== len
)
1596 * Check if the open fd is a symlink. Return -ELOOP if it is. Return
1597 * -ENOENT if we couldn't fstat. Return 0 if the fd is ok.
1599 static int check_symlink(int fd
)
1604 ret
= fstat(fd
, &sb
);
1608 if (S_ISLNK(sb
.st_mode
))
1615 * Open a file or directory, provided that it contains no symlinks.
1617 * CAVEAT: This function must not be used for other purposes than container
1618 * setup before executing the container's init
1620 static int open_if_safe(int dirfd
, const char *nextpath
)
1622 int newfd
= openat(dirfd
, nextpath
, O_RDONLY
| O_NOFOLLOW
);
1623 if (newfd
>= 0) /* Was not a symlink, all good. */
1629 if (errno
== EPERM
|| errno
== EACCES
) {
1630 /* We're not root (cause we got EPERM) so try opening with
1633 newfd
= openat(dirfd
, nextpath
, O_PATH
| O_NOFOLLOW
);
1635 /* O_PATH will return an fd for symlinks. We know
1636 * nextpath wasn't a symlink at last openat, so if fd is
1637 * now a link, then something * fishy is going on.
1639 int ret
= check_symlink(newfd
);
1651 * Open a path intending for mounting, ensuring that the final path
1652 * is inside the container's rootfs.
1654 * CAVEAT: This function must not be used for other purposes than container
1655 * setup before executing the container's init
1657 * @target: path to be opened
1658 * @prefix_skip: a part of @target in which to ignore symbolic links. This
1659 * would be the container's rootfs.
1661 * Return an open fd for the path, or <0 on error.
1663 static int open_without_symlink(const char *target
, const char *prefix_skip
)
1665 int curlen
= 0, dirfd
, fulllen
, i
;
1668 fulllen
= strlen(target
);
1670 /* make sure prefix-skip makes sense */
1671 if (prefix_skip
&& strlen(prefix_skip
) > 0) {
1672 curlen
= strlen(prefix_skip
);
1673 if (!is_subdir(target
, prefix_skip
, curlen
)) {
1674 ERROR("WHOA there - target '%s' didn't start with prefix '%s'",
1675 target
, prefix_skip
);
1680 * get_nextpath() expects the curlen argument to be
1681 * on a (turned into \0) / or before it, so decrement
1682 * curlen to make sure that happens
1691 /* Make a copy of target which we can hack up, and tokenize it */
1692 if ((dup
= strdup(target
)) == NULL
) {
1693 SYSERROR("Out of memory checking for symbolic link");
1697 for (i
= 0; i
< fulllen
; i
++) {
1702 dirfd
= open(prefix_skip
, O_RDONLY
);
1707 int newfd
, saved_errno
;
1710 if ((nextpath
= get_nextpath(dup
, &curlen
, fulllen
)) == NULL
)
1713 newfd
= open_if_safe(dirfd
, nextpath
);
1714 saved_errno
= errno
;
1719 errno
= saved_errno
;
1721 SYSERROR("%s in %s was a symbolic link!", nextpath
, target
);
1733 * Safely mount a path into a container, ensuring that the mount target
1734 * is under the container's @rootfs. (If @rootfs is NULL, then the container
1735 * uses the host's /)
1737 * CAVEAT: This function must not be used for other purposes than container
1738 * setup before executing the container's init
1740 int safe_mount(const char *src
, const char *dest
, const char *fstype
,
1741 unsigned long flags
, const void *data
, const char *rootfs
)
1743 int destfd
, ret
, saved_errno
;
1744 /* Only needs enough for /proc/self/fd/<fd>. */
1745 char srcbuf
[50], destbuf
[50];
1747 const char *mntsrc
= src
;
1752 /* todo - allow symlinks for relative paths if 'allowsymlinks' option is passed */
1753 if (flags
& MS_BIND
&& src
&& src
[0] != '/') {
1754 INFO("this is a relative bind mount");
1756 srcfd
= open_without_symlink(src
, NULL
);
1760 ret
= snprintf(srcbuf
, 50, "/proc/self/fd/%d", srcfd
);
1761 if (ret
< 0 || ret
> 50) {
1763 ERROR("Out of memory");
1769 destfd
= open_without_symlink(dest
, rootfs
);
1772 saved_errno
= errno
;
1774 errno
= saved_errno
;
1780 ret
= snprintf(destbuf
, 50, "/proc/self/fd/%d", destfd
);
1781 if (ret
< 0 || ret
> 50) {
1786 ERROR("Out of memory");
1790 ret
= mount(mntsrc
, destbuf
, fstype
, flags
, data
);
1791 saved_errno
= errno
;
1797 errno
= saved_errno
;
1798 SYSERROR("Failed to mount %s onto %s", src
? src
: "(null)", dest
);
1806 * Mount a proc under @rootfs if proc self points to a pid other than
1807 * my own. This is needed to have a known-good proc mount for setting
1808 * up LSMs both at container startup and attach.
1810 * @rootfs : the rootfs where proc should be mounted
1812 * Returns < 0 on failure, 0 if the correct proc was already mounted
1813 * and 1 if a new proc was mounted.
1815 * NOTE: not to be called from inside the container namespace!
1817 int lxc_mount_proc_if_needed(const char *rootfs
)
1819 char path
[MAXPATHLEN
];
1820 int link_to_pid
, linklen
, mypid
, ret
;
1821 char link
[LXC_NUMSTRLEN64
] = {0};
1823 ret
= snprintf(path
, MAXPATHLEN
, "%s/proc/self", rootfs
);
1824 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1825 SYSERROR("proc path name too long");
1829 linklen
= readlink(path
, link
, LXC_NUMSTRLEN64
);
1831 ret
= snprintf(path
, MAXPATHLEN
, "%s/proc", rootfs
);
1832 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1833 SYSERROR("proc path name too long");
1837 /* /proc not mounted */
1839 if (mkdir(path
, 0755) && errno
!= EEXIST
)
1843 } else if (linklen
>= LXC_NUMSTRLEN64
) {
1844 link
[linklen
- 1] = '\0';
1845 ERROR("readlink returned truncated content: \"%s\"", link
);
1849 mypid
= lxc_raw_getpid();
1850 INFO("I am %d, /proc/self points to \"%s\"", mypid
, link
);
1852 if (lxc_safe_int(link
, &link_to_pid
) < 0)
1855 /* correct procfs is already mounted */
1856 if (link_to_pid
== mypid
)
1859 ret
= umount2(path
, MNT_DETACH
);
1861 WARN("failed to umount \"%s\" with MNT_DETACH", path
);
1864 /* rootfs is NULL */
1865 if (!strcmp(rootfs
, ""))
1866 ret
= mount("proc", path
, "proc", 0, NULL
);
1868 ret
= safe_mount("proc", path
, "proc", 0, NULL
, rootfs
);
1872 INFO("mounted /proc in container for security transition");
1876 int open_devnull(void)
1878 int fd
= open("/dev/null", O_RDWR
);
1881 SYSERROR("Can't open /dev/null");
1886 int set_stdfds(int fd
)
1893 ret
= dup2(fd
, STDIN_FILENO
);
1897 ret
= dup2(fd
, STDOUT_FILENO
);
1901 ret
= dup2(fd
, STDERR_FILENO
);
1908 int null_stdfds(void)
1913 fd
= open_devnull();
1915 ret
= set_stdfds(fd
);
1923 * Return the number of lines in file @fn, or -1 on error
1925 int lxc_count_file_lines(const char *fn
)
1932 f
= fopen_cloexec(fn
, "r");
1936 while (getline(&line
, &sz
, f
) != -1) {
1945 /* Check whether a signal is blocked by a process. */
1946 /* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
1947 #define __PROC_STATUS_LEN (6 + (LXC_NUMSTRLEN64) + 7 + 1)
1948 bool task_blocks_signal(pid_t pid
, int signal
)
1951 char status
[__PROC_STATUS_LEN
];
1953 uint64_t sigblk
= 0, one
= 1;
1958 ret
= snprintf(status
, __PROC_STATUS_LEN
, "/proc/%d/status", pid
);
1959 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
1962 f
= fopen(status
, "r");
1966 while (getline(&line
, &n
, f
) != -1) {
1969 if (strncmp(line
, "SigBlk:", 7))
1972 numstr
= lxc_trim_whitespace_in_place(line
+ 7);
1973 ret
= lxc_safe_uint64(numstr
, &sigblk
, 16);
1980 if (sigblk
& (one
<< (signal
- 1)))
1989 static int lxc_append_null_to_list(void ***list
)
1995 for (; (*list
)[newentry
]; newentry
++) {
1999 tmp
= realloc(*list
, (newentry
+ 2) * sizeof(void **));
2004 (*list
)[newentry
+ 1] = NULL
;
2009 int lxc_append_string(char ***list
, char *entry
)
2014 newentry
= lxc_append_null_to_list((void ***)list
);
2018 copy
= strdup(entry
);
2022 (*list
)[newentry
] = copy
;
2027 int lxc_preserve_ns(const int pid
, const char *ns
)
2030 /* 5 /proc + 21 /int_as_str + 3 /ns + 20 /NS_NAME + 1 \0 */
2031 #define __NS_PATH_LEN 50
2032 char path
[__NS_PATH_LEN
];
2034 /* This way we can use this function to also check whether namespaces
2035 * are supported by the kernel by passing in the NULL or the empty
2038 ret
= snprintf(path
, __NS_PATH_LEN
, "/proc/%d/ns%s%s", pid
,
2039 !ns
|| strcmp(ns
, "") == 0 ? "" : "/",
2040 !ns
|| strcmp(ns
, "") == 0 ? "" : ns
);
2041 if (ret
< 0 || (size_t)ret
>= __NS_PATH_LEN
) {
2046 return open(path
, O_RDONLY
| O_CLOEXEC
);
2049 int lxc_safe_uint(const char *numstr
, unsigned int *converted
)
2052 unsigned long int uli
;
2054 while (isspace(*numstr
))
2061 uli
= strtoul(numstr
, &err
, 0);
2062 if (errno
== ERANGE
&& uli
== ULONG_MAX
)
2065 if (err
== numstr
|| *err
!= '\0')
2071 *converted
= (unsigned int)uli
;
2075 int lxc_safe_ulong(const char *numstr
, unsigned long *converted
)
2078 unsigned long int uli
;
2080 while (isspace(*numstr
))
2087 uli
= strtoul(numstr
, &err
, 0);
2088 if (errno
== ERANGE
&& uli
== ULONG_MAX
)
2091 if (err
== numstr
|| *err
!= '\0')
2098 int lxc_safe_uint64(const char *numstr
, uint64_t *converted
, int base
)
2103 while (isspace(*numstr
))
2110 u
= strtoull(numstr
, &err
, base
);
2111 if (errno
== ERANGE
&& u
== ULLONG_MAX
)
2114 if (err
== numstr
|| *err
!= '\0')
2121 int lxc_safe_int(const char *numstr
, int *converted
)
2124 signed long int sli
;
2127 sli
= strtol(numstr
, &err
, 0);
2128 if (errno
== ERANGE
&& (sli
== LONG_MAX
|| sli
== LONG_MIN
))
2131 if (errno
!= 0 && sli
== 0)
2134 if (err
== numstr
|| *err
!= '\0')
2137 if (sli
> INT_MAX
|| sli
< INT_MIN
)
2140 *converted
= (int)sli
;
2144 int lxc_safe_long(const char *numstr
, long int *converted
)
2147 signed long int sli
;
2150 sli
= strtol(numstr
, &err
, 0);
2151 if (errno
== ERANGE
&& (sli
== LONG_MAX
|| sli
== LONG_MIN
))
2154 if (errno
!= 0 && sli
== 0)
2157 if (err
== numstr
|| *err
!= '\0')
2164 int lxc_safe_long_long(const char *numstr
, long long int *converted
)
2167 signed long long int sli
;
2170 sli
= strtoll(numstr
, &err
, 0);
2171 if (errno
== ERANGE
&& (sli
== LLONG_MAX
|| sli
== LLONG_MIN
))
2174 if (errno
!= 0 && sli
== 0)
2177 if (err
== numstr
|| *err
!= '\0')
2184 int lxc_switch_uid_gid(uid_t uid
, gid_t gid
)
2186 if (setgid(gid
) < 0) {
2187 SYSERROR("Failed to switch to gid %d.", gid
);
2190 NOTICE("Switched to gid %d.", gid
);
2192 if (setuid(uid
) < 0) {
2193 SYSERROR("Failed to switch to uid %d.", uid
);
2196 NOTICE("Switched to uid %d.", uid
);
2201 /* Simple covenience function which enables uniform logging. */
2202 int lxc_setgroups(int size
, gid_t list
[])
2204 if (setgroups(size
, list
) < 0) {
2205 SYSERROR("Failed to setgroups().");
2208 NOTICE("Dropped additional groups.");
2213 static int lxc_get_unused_loop_dev_legacy(char *loop_name
)
2216 struct loop_info64 lo64
;
2218 int dfd
= -1, fd
= -1, ret
= -1;
2220 dir
= opendir("/dev");
2224 while ((dp
= readdir(dir
))) {
2225 if (strncmp(dp
->d_name
, "loop", 4) != 0)
2232 fd
= openat(dfd
, dp
->d_name
, O_RDWR
);
2236 ret
= ioctl(fd
, LOOP_GET_STATUS64
, &lo64
);
2238 if (ioctl(fd
, LOOP_GET_STATUS64
, &lo64
) == 0 ||
2246 ret
= snprintf(loop_name
, LO_NAME_SIZE
, "/dev/%s", dp
->d_name
);
2247 if (ret
< 0 || ret
>= LO_NAME_SIZE
) {
2264 static int lxc_get_unused_loop_dev(char *name_loop
)
2267 int fd_ctl
= -1, fd_tmp
= -1;
2269 fd_ctl
= open("/dev/loop-control", O_RDWR
| O_CLOEXEC
);
2273 loop_nr
= ioctl(fd_ctl
, LOOP_CTL_GET_FREE
);
2277 ret
= snprintf(name_loop
, LO_NAME_SIZE
, "/dev/loop%d", loop_nr
);
2278 if (ret
< 0 || ret
>= LO_NAME_SIZE
)
2281 fd_tmp
= open(name_loop
, O_RDWR
| O_CLOEXEC
);
2290 int lxc_prepare_loop_dev(const char *source
, char *loop_dev
, int flags
)
2293 struct loop_info64 lo64
;
2294 int fd_img
= -1, fret
= -1, fd_loop
= -1;
2296 fd_loop
= lxc_get_unused_loop_dev(loop_dev
);
2298 if (fd_loop
== -ENODEV
)
2299 fd_loop
= lxc_get_unused_loop_dev_legacy(loop_dev
);
2304 fd_img
= open(source
, O_RDWR
| O_CLOEXEC
);
2308 ret
= ioctl(fd_loop
, LOOP_SET_FD
, fd_img
);
2312 memset(&lo64
, 0, sizeof(lo64
));
2313 lo64
.lo_flags
= flags
;
2315 ret
= ioctl(fd_loop
, LOOP_SET_STATUS64
, &lo64
);
2325 if (fret
< 0 && fd_loop
>= 0) {
2333 int lxc_unstack_mountpoint(const char *path
, bool lazy
)
2339 ret
= umount2(path
, lazy
? MNT_DETACH
: 0);
2341 /* We consider anything else than EINVAL deadly to prevent going
2342 * into an infinite loop. (The other alternative is constantly
2343 * parsing /proc/self/mountinfo which is yucky and probably
2346 if (errno
!= EINVAL
)
2349 /* Just stop counting when this happens. That'd just be so
2350 * stupid that we won't even bother trying to report back the
2351 * correct value anymore.
2353 if (umounts
!= INT_MAX
)
2356 /* We succeeded in umounting. Make sure that there's no other
2357 * mountpoint stacked underneath.
2365 int run_command(char *buf
, size_t buf_size
, int (*child_fn
)(void *), void *args
)
2368 int ret
, fret
, pipefd
[2];
2371 /* Make sure our callers do not receive uninitialized memory. */
2372 if (buf_size
> 0 && buf
)
2375 if (pipe(pipefd
) < 0) {
2376 SYSERROR("failed to create pipe");
2380 child
= lxc_raw_clone(0);
2384 SYSERROR("failed to create new process");
2389 /* Close the read-end of the pipe. */
2392 /* Redirect std{err,out} to write-end of the
2395 ret
= dup2(pipefd
[1], STDOUT_FILENO
);
2397 ret
= dup2(pipefd
[1], STDERR_FILENO
);
2399 /* Close the write-end of the pipe. */
2403 SYSERROR("failed to duplicate std{err,out} file descriptor");
2404 _exit(EXIT_FAILURE
);
2407 /* Does not return. */
2409 ERROR("failed to exec command");
2410 _exit(EXIT_FAILURE
);
2413 /* close the write-end of the pipe */
2416 if (buf
&& buf_size
> 0) {
2417 bytes
= lxc_read_nointr(pipefd
[0], buf
, buf_size
- 1);
2419 buf
[bytes
- 1] = '\0';
2422 fret
= wait_for_pid(child
);
2423 /* close the read-end of the pipe */
2429 char *must_concat(const char *first
, ...)
2433 size_t cur_len
, it_len
;
2435 dest
= must_copy_string(first
);
2436 cur_len
= it_len
= strlen(first
);
2438 va_start(args
, first
);
2439 while ((cur
= va_arg(args
, char *)) != NULL
) {
2440 it_len
= strlen(cur
);
2442 dest
= must_realloc(dest
, cur_len
+ it_len
+ 1);
2444 (void)memcpy(dest
+ cur_len
, cur
, it_len
);
2453 char *must_make_path(const char *first
, ...)
2457 size_t full_len
= strlen(first
);
2460 dest
= must_copy_string(first
);
2462 va_start(args
, first
);
2463 while ((cur
= va_arg(args
, char *)) != NULL
) {
2464 full_len
+= strlen(cur
);
2468 buf_len
= full_len
+ 1;
2469 dest
= must_realloc(dest
, buf_len
);
2472 (void)strlcat(dest
, "/", buf_len
);
2473 (void)strlcat(dest
, cur
, buf_len
);
2480 char *must_append_path(char *first
, ...)
2488 full_len
= strlen(first
);
2489 va_start(args
, first
);
2490 while ((cur
= va_arg(args
, char *)) != NULL
) {
2491 full_len
+= strlen(cur
);
2495 buf_len
= full_len
+ 1;
2496 dest
= must_realloc(dest
, buf_len
);
2499 (void)strlcat(dest
, "/", buf_len
);
2500 (void)strlcat(dest
, cur
, buf_len
);
2507 char *must_copy_string(const char *entry
)
2515 ret
= strdup(entry
);
2521 void *must_realloc(void *orig
, size_t sz
)
2526 ret
= realloc(orig
, sz
);
2532 bool is_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
2534 return (fs
->f_type
== (fs_type_magic
)magic_val
);
2537 bool has_fs_type(const char *path
, fs_type_magic magic_val
)
2543 ret
= statfs(path
, &sb
);
2547 has_type
= is_fs_type(&sb
, magic_val
);
2548 if (!has_type
&& magic_val
== RAMFS_MAGIC
)
2549 WARN("When the ramfs it a tmpfs statfs() might report tmpfs");
2554 bool fhas_fs_type(int fd
, fs_type_magic magic_val
)
2559 ret
= fstatfs(fd
, &sb
);
2563 return is_fs_type(&sb
, magic_val
);
2566 bool lxc_nic_exists(char *nic
)
2568 #define __LXC_SYS_CLASS_NET_LEN 15 + IFNAMSIZ + 1
2569 char path
[__LXC_SYS_CLASS_NET_LEN
];
2573 if (!strcmp(nic
, "none"))
2576 ret
= snprintf(path
, __LXC_SYS_CLASS_NET_LEN
, "/sys/class/net/%s", nic
);
2577 if (ret
< 0 || (size_t)ret
>= __LXC_SYS_CLASS_NET_LEN
)
2580 ret
= stat(path
, &sb
);
2587 int lxc_make_tmpfile(char *template, bool rm
)
2593 fd
= mkstemp(template);
2601 ret
= unlink(template);
2610 int parse_byte_size_string(const char *s
, int64_t *converted
)
2612 int ret
, suffix_len
;
2614 int64_t mltpl
, overflow
;
2616 char dup
[LXC_NUMSTRLEN64
+ 2];
2617 char suffix
[3] = {0};
2619 if (!s
|| !strcmp(s
, ""))
2622 end
= stpncpy(dup
, s
, sizeof(dup
) - 1);
2626 if (isdigit(*(end
- 1)))
2628 else if (isalpha(*(end
- 1)))
2633 if (suffix_len
> 0 && (end
- 2) == dup
&& !isdigit(*(end
- 2)))
2636 if (suffix_len
> 0 && isalpha(*(end
- 2)))
2639 if (suffix_len
> 0) {
2640 memcpy(suffix
, end
- suffix_len
, suffix_len
);
2641 *(suffix
+ suffix_len
) = '\0';
2642 *(end
- suffix_len
) = '\0';
2644 dup
[lxc_char_right_gc(dup
, strlen(dup
))] = '\0';
2646 ret
= lxc_safe_long_long(dup
, &conv
);
2650 if (suffix_len
!= 2) {
2655 if (strcasecmp(suffix
, "KB") == 0)
2657 else if (strcasecmp(suffix
, "MB") == 0)
2658 mltpl
= 1024 * 1024;
2659 else if (strcasecmp(suffix
, "GB") == 0)
2660 mltpl
= 1024 * 1024 * 1024;
2664 overflow
= conv
* mltpl
;
2665 if (conv
!= 0 && (overflow
/ conv
) != mltpl
)
2668 *converted
= overflow
;
2672 uint64_t lxc_find_next_power2(uint64_t n
)
2674 /* 0 is not valid input. We return 0 to the caller since 0 is not a
2675 * valid power of two.
2690 int lxc_set_death_signal(int signal
)
2695 ret
= prctl(PR_SET_PDEATHSIG
, prctl_arg(signal
), prctl_arg(0),
2696 prctl_arg(0), prctl_arg(0));
2698 /* Check whether we have been orphaned. */
2699 ppid
= (pid_t
)syscall(SYS_getppid
);
2703 self
= lxc_raw_getpid();
2704 ret
= kill(self
, SIGKILL
);
2710 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d", signal
);
2717 void remove_trailing_newlines(char *l
)
2724 while (--p
>= l
&& *p
== '\n')
2728 int fd_cloexec(int fd
, bool cloexec
)
2732 oflags
= fcntl(fd
, F_GETFD
, 0);
2737 nflags
= oflags
| FD_CLOEXEC
;
2739 nflags
= oflags
& ~FD_CLOEXEC
;
2741 if (nflags
== oflags
)
2744 if (fcntl(fd
, F_SETFD
, nflags
) < 0)
2750 int recursive_destroy(char *dirname
)
2753 struct dirent
*direntp
;
2757 dir
= opendir(dirname
);
2761 while ((direntp
= readdir(dir
))) {
2765 if (!strcmp(direntp
->d_name
, ".") ||
2766 !strcmp(direntp
->d_name
, ".."))
2769 pathname
= must_make_path(dirname
, direntp
->d_name
, NULL
);
2771 ret
= lstat(pathname
, &mystat
);
2774 WARN("Failed to stat \"%s\"", pathname
);
2780 if (!S_ISDIR(mystat
.st_mode
))
2783 ret
= recursive_destroy(pathname
);
2791 ret
= rmdir(dirname
);
2794 SYSWARN("Failed to delete \"%s\"", dirname
);
2799 ret
= closedir(dir
);
2802 SYSWARN("Failed to delete \"%s\"", dirname
);