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
= read(fd
, buf2
, 100)) > 0)
1099 memset(buf
, 0, count
);
1100 ret
= read(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) {
1343 char *on_path(const char *cmd
, const char *rootfs
) {
1344 char *entry
= NULL
, *path
= NULL
;
1345 char cmdpath
[MAXPATHLEN
];
1348 path
= getenv("PATH");
1352 path
= strdup(path
);
1356 lxc_iterate_parts(entry
, path
, ":") {
1358 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s/%s", rootfs
, entry
, cmd
);
1360 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s", entry
, cmd
);
1361 if (ret
< 0 || ret
>= MAXPATHLEN
)
1364 if (access(cmdpath
, X_OK
) == 0) {
1366 return strdup(cmdpath
);
1374 bool file_exists(const char *f
)
1376 struct stat statbuf
;
1378 return stat(f
, &statbuf
) == 0;
1381 bool cgns_supported(void)
1383 return file_exists("/proc/self/ns/cgroup");
1386 /* historically lxc-init has been under /usr/lib/lxc and under
1387 * /usr/lib/$ARCH/lxc. It now lives as $prefix/sbin/init.lxc.
1389 char *choose_init(const char *rootfs
)
1392 const char *empty
= "",
1394 int ret
, env_set
= 0;
1396 if (!getenv("PATH")) {
1397 if (setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 0))
1398 SYSERROR("Failed to setenv");
1403 retv
= on_path("init.lxc", rootfs
);
1406 if (unsetenv("PATH"))
1407 SYSERROR("Failed to unsetenv");
1413 retv
= malloc(PATH_MAX
);
1422 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, SBINDIR
, "/init.lxc");
1423 if (ret
< 0 || ret
>= PATH_MAX
) {
1424 ERROR("pathname too long");
1428 if (access(retv
, X_OK
) == 0)
1431 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, LXCINITDIR
, "/lxc/lxc-init");
1432 if (ret
< 0 || ret
>= PATH_MAX
) {
1433 ERROR("pathname too long");
1437 if (access(retv
, X_OK
) == 0)
1440 ret
= snprintf(retv
, PATH_MAX
, "%s/usr/lib/lxc/lxc-init", tmp
);
1441 if (ret
< 0 || ret
>= PATH_MAX
) {
1442 ERROR("pathname too long");
1446 if (access(retv
, X_OK
) == 0)
1449 ret
= snprintf(retv
, PATH_MAX
, "%s/sbin/lxc-init", tmp
);
1450 if (ret
< 0 || ret
>= PATH_MAX
) {
1451 ERROR("pathname too long");
1455 if (access(retv
, X_OK
) == 0)
1459 * Last resort, look for the statically compiled init.lxc which we
1460 * hopefully bind-mounted in.
1461 * If we are called during container setup, and we get to this point,
1462 * then the init.lxc.static from the host will need to be bind-mounted
1463 * in. So we return NULL here to indicate that.
1468 ret
= snprintf(retv
, PATH_MAX
, "/init.lxc.static");
1469 if (ret
< 0 || ret
>= PATH_MAX
) {
1470 WARN("Nonsense - name /lxc.init.static too long");
1474 if (access(retv
, X_OK
) == 0)
1482 int print_to_file(const char *file
, const char *content
)
1487 f
= fopen(file
, "w");
1491 if (fprintf(f
, "%s", content
) != strlen(content
))
1498 int is_dir(const char *path
)
1500 struct stat statbuf
;
1503 ret
= stat(path
, &statbuf
);
1504 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
1511 * Given the '-t' template option to lxc-create, figure out what to
1512 * do. If the template is a full executable path, use that. If it
1513 * is something like 'sshd', then return $templatepath/lxc-sshd.
1514 * On success return the template, on error return NULL.
1516 char *get_template_path(const char *t
)
1521 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
1526 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
1528 tpath
= malloc(len
);
1532 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
1533 if (ret
< 0 || ret
>= len
) {
1538 if (access(tpath
, X_OK
) < 0) {
1539 SYSERROR("bad template: %s", t
);
1548 * @path: a pathname where / replaced with '\0'.
1549 * @offsetp: pointer to int showing which path segment was last seen.
1550 * Updated on return to reflect the next segment.
1551 * @fulllen: full original path length.
1552 * Returns a pointer to the next path segment, or NULL if done.
1554 static char *get_nextpath(char *path
, int *offsetp
, int fulllen
)
1556 int offset
= *offsetp
;
1558 if (offset
>= fulllen
)
1561 while (path
[offset
] != '\0' && offset
< fulllen
)
1564 while (path
[offset
] == '\0' && offset
< fulllen
)
1568 return (offset
< fulllen
) ? &path
[offset
] : NULL
;
1572 * Check that @subdir is a subdir of @dir. @len is the length of
1573 * @dir (to avoid having to recalculate it).
1575 static bool is_subdir(const char *subdir
, const char *dir
, size_t len
)
1577 size_t subdirlen
= strlen(subdir
);
1579 if (subdirlen
< len
)
1582 if (strncmp(subdir
, dir
, len
) != 0)
1585 if (dir
[len
-1] == '/')
1588 if (subdir
[len
] == '/' || subdirlen
== len
)
1595 * Check if the open fd is a symlink. Return -ELOOP if it is. Return
1596 * -ENOENT if we couldn't fstat. Return 0 if the fd is ok.
1598 static int check_symlink(int fd
)
1603 ret
= fstat(fd
, &sb
);
1607 if (S_ISLNK(sb
.st_mode
))
1614 * Open a file or directory, provided that it contains no symlinks.
1616 * CAVEAT: This function must not be used for other purposes than container
1617 * setup before executing the container's init
1619 static int open_if_safe(int dirfd
, const char *nextpath
)
1621 int newfd
= openat(dirfd
, nextpath
, O_RDONLY
| O_NOFOLLOW
);
1622 if (newfd
>= 0) /* Was not a symlink, all good. */
1628 if (errno
== EPERM
|| errno
== EACCES
) {
1629 /* We're not root (cause we got EPERM) so try opening with
1632 newfd
= openat(dirfd
, nextpath
, O_PATH
| O_NOFOLLOW
);
1634 /* O_PATH will return an fd for symlinks. We know
1635 * nextpath wasn't a symlink at last openat, so if fd is
1636 * now a link, then something * fishy is going on.
1638 int ret
= check_symlink(newfd
);
1650 * Open a path intending for mounting, ensuring that the final path
1651 * is inside the container's rootfs.
1653 * CAVEAT: This function must not be used for other purposes than container
1654 * setup before executing the container's init
1656 * @target: path to be opened
1657 * @prefix_skip: a part of @target in which to ignore symbolic links. This
1658 * would be the container's rootfs.
1660 * Return an open fd for the path, or <0 on error.
1662 static int open_without_symlink(const char *target
, const char *prefix_skip
)
1664 int curlen
= 0, dirfd
, fulllen
, i
;
1667 fulllen
= strlen(target
);
1669 /* make sure prefix-skip makes sense */
1670 if (prefix_skip
&& strlen(prefix_skip
) > 0) {
1671 curlen
= strlen(prefix_skip
);
1672 if (!is_subdir(target
, prefix_skip
, curlen
)) {
1673 ERROR("WHOA there - target '%s' didn't start with prefix '%s'",
1674 target
, prefix_skip
);
1679 * get_nextpath() expects the curlen argument to be
1680 * on a (turned into \0) / or before it, so decrement
1681 * curlen to make sure that happens
1690 /* Make a copy of target which we can hack up, and tokenize it */
1691 if ((dup
= strdup(target
)) == NULL
) {
1692 SYSERROR("Out of memory checking for symbolic link");
1696 for (i
= 0; i
< fulllen
; i
++) {
1701 dirfd
= open(prefix_skip
, O_RDONLY
);
1706 int newfd
, saved_errno
;
1709 if ((nextpath
= get_nextpath(dup
, &curlen
, fulllen
)) == NULL
)
1712 newfd
= open_if_safe(dirfd
, nextpath
);
1713 saved_errno
= errno
;
1718 errno
= saved_errno
;
1720 SYSERROR("%s in %s was a symbolic link!", nextpath
, target
);
1732 * Safely mount a path into a container, ensuring that the mount target
1733 * is under the container's @rootfs. (If @rootfs is NULL, then the container
1734 * uses the host's /)
1736 * CAVEAT: This function must not be used for other purposes than container
1737 * setup before executing the container's init
1739 int safe_mount(const char *src
, const char *dest
, const char *fstype
,
1740 unsigned long flags
, const void *data
, const char *rootfs
)
1742 int destfd
, ret
, saved_errno
;
1743 /* Only needs enough for /proc/self/fd/<fd>. */
1744 char srcbuf
[50], destbuf
[50];
1746 const char *mntsrc
= src
;
1751 /* todo - allow symlinks for relative paths if 'allowsymlinks' option is passed */
1752 if (flags
& MS_BIND
&& src
&& src
[0] != '/') {
1753 INFO("this is a relative bind mount");
1755 srcfd
= open_without_symlink(src
, NULL
);
1759 ret
= snprintf(srcbuf
, 50, "/proc/self/fd/%d", srcfd
);
1760 if (ret
< 0 || ret
> 50) {
1762 ERROR("Out of memory");
1768 destfd
= open_without_symlink(dest
, rootfs
);
1771 saved_errno
= errno
;
1773 errno
= saved_errno
;
1779 ret
= snprintf(destbuf
, 50, "/proc/self/fd/%d", destfd
);
1780 if (ret
< 0 || ret
> 50) {
1785 ERROR("Out of memory");
1789 ret
= mount(mntsrc
, destbuf
, fstype
, flags
, data
);
1790 saved_errno
= errno
;
1796 errno
= saved_errno
;
1797 SYSERROR("Failed to mount %s onto %s", src
? src
: "(null)", dest
);
1805 * Mount a proc under @rootfs if proc self points to a pid other than
1806 * my own. This is needed to have a known-good proc mount for setting
1807 * up LSMs both at container startup and attach.
1809 * @rootfs : the rootfs where proc should be mounted
1811 * Returns < 0 on failure, 0 if the correct proc was already mounted
1812 * and 1 if a new proc was mounted.
1814 * NOTE: not to be called from inside the container namespace!
1816 int lxc_mount_proc_if_needed(const char *rootfs
)
1818 char path
[MAXPATHLEN
];
1819 int link_to_pid
, linklen
, mypid
, ret
;
1820 char link
[LXC_NUMSTRLEN64
] = {0};
1822 ret
= snprintf(path
, MAXPATHLEN
, "%s/proc/self", rootfs
);
1823 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1824 SYSERROR("proc path name too long");
1828 linklen
= readlink(path
, link
, LXC_NUMSTRLEN64
);
1830 ret
= snprintf(path
, MAXPATHLEN
, "%s/proc", rootfs
);
1831 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1832 SYSERROR("proc path name too long");
1836 /* /proc not mounted */
1838 if (mkdir(path
, 0755) && errno
!= EEXIST
)
1842 } else if (linklen
>= LXC_NUMSTRLEN64
) {
1843 link
[linklen
- 1] = '\0';
1844 ERROR("readlink returned truncated content: \"%s\"", link
);
1848 mypid
= lxc_raw_getpid();
1849 INFO("I am %d, /proc/self points to \"%s\"", mypid
, link
);
1851 if (lxc_safe_int(link
, &link_to_pid
) < 0)
1854 /* correct procfs is already mounted */
1855 if (link_to_pid
== mypid
)
1858 ret
= umount2(path
, MNT_DETACH
);
1860 WARN("failed to umount \"%s\" with MNT_DETACH", path
);
1863 /* rootfs is NULL */
1864 if (!strcmp(rootfs
, ""))
1865 ret
= mount("proc", path
, "proc", 0, NULL
);
1867 ret
= safe_mount("proc", path
, "proc", 0, NULL
, rootfs
);
1871 INFO("mounted /proc in container for security transition");
1875 int open_devnull(void)
1877 int fd
= open("/dev/null", O_RDWR
);
1880 SYSERROR("Can't open /dev/null");
1885 int set_stdfds(int fd
)
1892 ret
= dup2(fd
, STDIN_FILENO
);
1896 ret
= dup2(fd
, STDOUT_FILENO
);
1900 ret
= dup2(fd
, STDERR_FILENO
);
1907 int null_stdfds(void)
1912 fd
= open_devnull();
1914 ret
= set_stdfds(fd
);
1922 * Return the number of lines in file @fn, or -1 on error
1924 int lxc_count_file_lines(const char *fn
)
1931 f
= fopen_cloexec(fn
, "r");
1935 while (getline(&line
, &sz
, f
) != -1) {
1944 /* Check whether a signal is blocked by a process. */
1945 /* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
1946 #define __PROC_STATUS_LEN (6 + (LXC_NUMSTRLEN64) + 7 + 1)
1947 bool task_blocks_signal(pid_t pid
, int signal
)
1950 char status
[__PROC_STATUS_LEN
];
1952 uint64_t sigblk
= 0, one
= 1;
1957 ret
= snprintf(status
, __PROC_STATUS_LEN
, "/proc/%d/status", pid
);
1958 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
1961 f
= fopen(status
, "r");
1965 while (getline(&line
, &n
, f
) != -1) {
1968 if (strncmp(line
, "SigBlk:", 7))
1971 numstr
= lxc_trim_whitespace_in_place(line
+ 7);
1972 ret
= lxc_safe_uint64(numstr
, &sigblk
, 16);
1979 if (sigblk
& (one
<< (signal
- 1)))
1988 static int lxc_append_null_to_list(void ***list
)
1994 for (; (*list
)[newentry
]; newentry
++) {
1998 tmp
= realloc(*list
, (newentry
+ 2) * sizeof(void **));
2003 (*list
)[newentry
+ 1] = NULL
;
2008 int lxc_append_string(char ***list
, char *entry
)
2013 newentry
= lxc_append_null_to_list((void ***)list
);
2017 copy
= strdup(entry
);
2021 (*list
)[newentry
] = copy
;
2026 int lxc_preserve_ns(const int pid
, const char *ns
)
2029 /* 5 /proc + 21 /int_as_str + 3 /ns + 20 /NS_NAME + 1 \0 */
2030 #define __NS_PATH_LEN 50
2031 char path
[__NS_PATH_LEN
];
2033 /* This way we can use this function to also check whether namespaces
2034 * are supported by the kernel by passing in the NULL or the empty
2037 ret
= snprintf(path
, __NS_PATH_LEN
, "/proc/%d/ns%s%s", pid
,
2038 !ns
|| strcmp(ns
, "") == 0 ? "" : "/",
2039 !ns
|| strcmp(ns
, "") == 0 ? "" : ns
);
2040 if (ret
< 0 || (size_t)ret
>= __NS_PATH_LEN
) {
2045 return open(path
, O_RDONLY
| O_CLOEXEC
);
2048 int lxc_safe_uint(const char *numstr
, unsigned int *converted
)
2051 unsigned long int uli
;
2053 while (isspace(*numstr
))
2060 uli
= strtoul(numstr
, &err
, 0);
2061 if (errno
== ERANGE
&& uli
== ULONG_MAX
)
2064 if (err
== numstr
|| *err
!= '\0')
2070 *converted
= (unsigned int)uli
;
2074 int lxc_safe_ulong(const char *numstr
, unsigned long *converted
)
2077 unsigned long int uli
;
2079 while (isspace(*numstr
))
2086 uli
= strtoul(numstr
, &err
, 0);
2087 if (errno
== ERANGE
&& uli
== ULONG_MAX
)
2090 if (err
== numstr
|| *err
!= '\0')
2097 int lxc_safe_uint64(const char *numstr
, uint64_t *converted
, int base
)
2102 while (isspace(*numstr
))
2109 u
= strtoull(numstr
, &err
, base
);
2110 if (errno
== ERANGE
&& u
== ULLONG_MAX
)
2113 if (err
== numstr
|| *err
!= '\0')
2120 int lxc_safe_int(const char *numstr
, int *converted
)
2123 signed long int sli
;
2126 sli
= strtol(numstr
, &err
, 0);
2127 if (errno
== ERANGE
&& (sli
== LONG_MAX
|| sli
== LONG_MIN
))
2130 if (errno
!= 0 && sli
== 0)
2133 if (err
== numstr
|| *err
!= '\0')
2136 if (sli
> INT_MAX
|| sli
< INT_MIN
)
2139 *converted
= (int)sli
;
2143 int lxc_safe_long(const char *numstr
, long int *converted
)
2146 signed long int sli
;
2149 sli
= strtol(numstr
, &err
, 0);
2150 if (errno
== ERANGE
&& (sli
== LONG_MAX
|| sli
== LONG_MIN
))
2153 if (errno
!= 0 && sli
== 0)
2156 if (err
== numstr
|| *err
!= '\0')
2163 int lxc_safe_long_long(const char *numstr
, long long int *converted
)
2166 signed long long int sli
;
2169 sli
= strtoll(numstr
, &err
, 0);
2170 if (errno
== ERANGE
&& (sli
== LLONG_MAX
|| sli
== LLONG_MIN
))
2173 if (errno
!= 0 && sli
== 0)
2176 if (err
== numstr
|| *err
!= '\0')
2183 int lxc_switch_uid_gid(uid_t uid
, gid_t gid
)
2185 if (setgid(gid
) < 0) {
2186 SYSERROR("Failed to switch to gid %d.", gid
);
2189 NOTICE("Switched to gid %d.", gid
);
2191 if (setuid(uid
) < 0) {
2192 SYSERROR("Failed to switch to uid %d.", uid
);
2195 NOTICE("Switched to uid %d.", uid
);
2200 /* Simple covenience function which enables uniform logging. */
2201 int lxc_setgroups(int size
, gid_t list
[])
2203 if (setgroups(size
, list
) < 0) {
2204 SYSERROR("Failed to setgroups().");
2207 NOTICE("Dropped additional groups.");
2212 static int lxc_get_unused_loop_dev_legacy(char *loop_name
)
2215 struct loop_info64 lo64
;
2217 int dfd
= -1, fd
= -1, ret
= -1;
2219 dir
= opendir("/dev");
2223 while ((dp
= readdir(dir
))) {
2224 if (strncmp(dp
->d_name
, "loop", 4) != 0)
2231 fd
= openat(dfd
, dp
->d_name
, O_RDWR
);
2235 ret
= ioctl(fd
, LOOP_GET_STATUS64
, &lo64
);
2237 if (ioctl(fd
, LOOP_GET_STATUS64
, &lo64
) == 0 ||
2245 ret
= snprintf(loop_name
, LO_NAME_SIZE
, "/dev/%s", dp
->d_name
);
2246 if (ret
< 0 || ret
>= LO_NAME_SIZE
) {
2263 static int lxc_get_unused_loop_dev(char *name_loop
)
2266 int fd_ctl
= -1, fd_tmp
= -1;
2268 fd_ctl
= open("/dev/loop-control", O_RDWR
| O_CLOEXEC
);
2272 loop_nr
= ioctl(fd_ctl
, LOOP_CTL_GET_FREE
);
2276 ret
= snprintf(name_loop
, LO_NAME_SIZE
, "/dev/loop%d", loop_nr
);
2277 if (ret
< 0 || ret
>= LO_NAME_SIZE
)
2280 fd_tmp
= open(name_loop
, O_RDWR
| O_CLOEXEC
);
2289 int lxc_prepare_loop_dev(const char *source
, char *loop_dev
, int flags
)
2292 struct loop_info64 lo64
;
2293 int fd_img
= -1, fret
= -1, fd_loop
= -1;
2295 fd_loop
= lxc_get_unused_loop_dev(loop_dev
);
2297 if (fd_loop
== -ENODEV
)
2298 fd_loop
= lxc_get_unused_loop_dev_legacy(loop_dev
);
2303 fd_img
= open(source
, O_RDWR
| O_CLOEXEC
);
2307 ret
= ioctl(fd_loop
, LOOP_SET_FD
, fd_img
);
2311 memset(&lo64
, 0, sizeof(lo64
));
2312 lo64
.lo_flags
= flags
;
2314 ret
= ioctl(fd_loop
, LOOP_SET_STATUS64
, &lo64
);
2324 if (fret
< 0 && fd_loop
>= 0) {
2332 int lxc_unstack_mountpoint(const char *path
, bool lazy
)
2338 ret
= umount2(path
, lazy
? MNT_DETACH
: 0);
2340 /* We consider anything else than EINVAL deadly to prevent going
2341 * into an infinite loop. (The other alternative is constantly
2342 * parsing /proc/self/mountinfo which is yucky and probably
2345 if (errno
!= EINVAL
)
2348 /* Just stop counting when this happens. That'd just be so
2349 * stupid that we won't even bother trying to report back the
2350 * correct value anymore.
2352 if (umounts
!= INT_MAX
)
2355 /* We succeeded in umounting. Make sure that there's no other
2356 * mountpoint stacked underneath.
2364 int run_command(char *buf
, size_t buf_size
, int (*child_fn
)(void *), void *args
)
2367 int ret
, fret
, pipefd
[2];
2370 /* Make sure our callers do not receive uninitialized memory. */
2371 if (buf_size
> 0 && buf
)
2374 if (pipe(pipefd
) < 0) {
2375 SYSERROR("failed to create pipe");
2379 child
= lxc_raw_clone(0);
2383 SYSERROR("failed to create new process");
2388 /* Close the read-end of the pipe. */
2391 /* Redirect std{err,out} to write-end of the
2394 ret
= dup2(pipefd
[1], STDOUT_FILENO
);
2396 ret
= dup2(pipefd
[1], STDERR_FILENO
);
2398 /* Close the write-end of the pipe. */
2402 SYSERROR("failed to duplicate std{err,out} file descriptor");
2403 _exit(EXIT_FAILURE
);
2406 /* Does not return. */
2408 ERROR("failed to exec command");
2409 _exit(EXIT_FAILURE
);
2412 /* close the write-end of the pipe */
2415 if (buf
&& buf_size
> 0) {
2416 bytes
= read(pipefd
[0], buf
, buf_size
- 1);
2418 buf
[bytes
- 1] = '\0';
2421 fret
= wait_for_pid(child
);
2422 /* close the read-end of the pipe */
2428 char *must_concat(const char *first
, ...)
2432 size_t cur_len
, it_len
;
2434 dest
= must_copy_string(first
);
2435 cur_len
= it_len
= strlen(first
);
2437 va_start(args
, first
);
2438 while ((cur
= va_arg(args
, char *)) != NULL
) {
2439 it_len
= strlen(cur
);
2441 dest
= must_realloc(dest
, cur_len
+ it_len
+ 1);
2443 (void)memcpy(dest
+ cur_len
, cur
, it_len
);
2452 char *must_make_path(const char *first
, ...)
2456 size_t full_len
= strlen(first
);
2459 dest
= must_copy_string(first
);
2461 va_start(args
, first
);
2462 while ((cur
= va_arg(args
, char *)) != NULL
) {
2463 full_len
+= strlen(cur
);
2467 buf_len
= full_len
+ 1;
2468 dest
= must_realloc(dest
, buf_len
);
2471 (void)strlcat(dest
, "/", buf_len
);
2472 (void)strlcat(dest
, cur
, buf_len
);
2479 char *must_append_path(char *first
, ...)
2487 full_len
= strlen(first
);
2488 va_start(args
, first
);
2489 while ((cur
= va_arg(args
, char *)) != NULL
) {
2490 full_len
+= strlen(cur
);
2494 buf_len
= full_len
+ 1;
2495 dest
= must_realloc(dest
, buf_len
);
2498 (void)strlcat(dest
, "/", buf_len
);
2499 (void)strlcat(dest
, cur
, buf_len
);
2506 char *must_copy_string(const char *entry
)
2514 ret
= strdup(entry
);
2520 void *must_realloc(void *orig
, size_t sz
)
2525 ret
= realloc(orig
, sz
);
2531 bool is_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
2533 return (fs
->f_type
== (fs_type_magic
)magic_val
);
2536 bool has_fs_type(const char *path
, fs_type_magic magic_val
)
2542 ret
= statfs(path
, &sb
);
2546 has_type
= is_fs_type(&sb
, magic_val
);
2547 if (!has_type
&& magic_val
== RAMFS_MAGIC
)
2548 WARN("When the ramfs it a tmpfs statfs() might report tmpfs");
2553 bool lxc_nic_exists(char *nic
)
2555 #define __LXC_SYS_CLASS_NET_LEN 15 + IFNAMSIZ + 1
2556 char path
[__LXC_SYS_CLASS_NET_LEN
];
2560 if (!strcmp(nic
, "none"))
2563 ret
= snprintf(path
, __LXC_SYS_CLASS_NET_LEN
, "/sys/class/net/%s", nic
);
2564 if (ret
< 0 || (size_t)ret
>= __LXC_SYS_CLASS_NET_LEN
)
2567 ret
= stat(path
, &sb
);
2574 int lxc_make_tmpfile(char *template, bool rm
)
2580 fd
= mkstemp(template);
2588 ret
= unlink(template);
2597 int parse_byte_size_string(const char *s
, int64_t *converted
)
2599 int ret
, suffix_len
;
2601 int64_t mltpl
, overflow
;
2603 char dup
[LXC_NUMSTRLEN64
+ 2];
2604 char suffix
[3] = {0};
2606 if (!s
|| !strcmp(s
, ""))
2609 end
= stpncpy(dup
, s
, sizeof(dup
) - 1);
2613 if (isdigit(*(end
- 1)))
2615 else if (isalpha(*(end
- 1)))
2620 if (suffix_len
> 0 && (end
- 2) == dup
&& !isdigit(*(end
- 2)))
2623 if (suffix_len
> 0 && isalpha(*(end
- 2)))
2626 if (suffix_len
> 0) {
2627 memcpy(suffix
, end
- suffix_len
, suffix_len
);
2628 *(suffix
+ suffix_len
) = '\0';
2629 *(end
- suffix_len
) = '\0';
2631 dup
[lxc_char_right_gc(dup
, strlen(dup
))] = '\0';
2633 ret
= lxc_safe_long_long(dup
, &conv
);
2637 if (suffix_len
!= 2) {
2642 if (strcasecmp(suffix
, "KB") == 0)
2644 else if (strcasecmp(suffix
, "MB") == 0)
2645 mltpl
= 1024 * 1024;
2646 else if (strcasecmp(suffix
, "GB") == 0)
2647 mltpl
= 1024 * 1024 * 1024;
2651 overflow
= conv
* mltpl
;
2652 if (conv
!= 0 && (overflow
/ conv
) != mltpl
)
2655 *converted
= overflow
;
2659 uint64_t lxc_find_next_power2(uint64_t n
)
2661 /* 0 is not valid input. We return 0 to the caller since 0 is not a
2662 * valid power of two.
2677 int lxc_set_death_signal(int signal
)
2682 ret
= prctl(PR_SET_PDEATHSIG
, signal
, 0, 0, 0);
2684 /* Check whether we have been orphaned. */
2685 ppid
= (pid_t
)syscall(SYS_getppid
);
2689 self
= lxc_raw_getpid();
2690 ret
= kill(self
, SIGKILL
);
2696 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d", signal
);
2703 void remove_trailing_newlines(char *l
)
2710 while (--p
>= l
&& *p
== '\n')
2714 int fd_cloexec(int fd
, bool cloexec
)
2718 oflags
= fcntl(fd
, F_GETFD
, 0);
2723 nflags
= oflags
| FD_CLOEXEC
;
2725 nflags
= oflags
& ~FD_CLOEXEC
;
2727 if (nflags
== oflags
)
2730 if (fcntl(fd
, F_SETFD
, nflags
) < 0)
2736 int recursive_destroy(char *dirname
)
2739 struct dirent
*direntp
;
2743 dir
= opendir(dirname
);
2747 while ((direntp
= readdir(dir
))) {
2751 if (!strcmp(direntp
->d_name
, ".") ||
2752 !strcmp(direntp
->d_name
, ".."))
2755 pathname
= must_make_path(dirname
, direntp
->d_name
, NULL
);
2757 ret
= lstat(pathname
, &mystat
);
2760 WARN("Failed to stat \"%s\"", pathname
);
2766 if (!S_ISDIR(mystat
.st_mode
))
2769 ret
= recursive_destroy(pathname
);
2777 ret
= rmdir(dirname
);
2780 SYSWARN("Failed to delete \"%s\"", dirname
);
2785 ret
= closedir(dir
);
2788 SYSWARN("Failed to delete \"%s\"", dirname
);