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(lxc_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
);
135 if (onedev
&& mystat
.st_dev
!= pdev
) {
136 /* TODO should we be checking /proc/self/mountinfo for
137 * pathname and not doing this if found? */
138 if (btrfs_try_remove_subvol(pathname
))
139 INFO("Removed btrfs subvolume at %s\n", pathname
);
142 if (S_ISDIR(mystat
.st_mode
)) {
143 if (_recursive_rmdir(pathname
, pdev
, exclude
, level
+1, onedev
) < 0)
146 if (unlink(pathname
) < 0) {
147 SYSERROR("Failed to delete %s", pathname
);
153 if (rmdir(dirname
) < 0 && !btrfs_try_remove_subvol(dirname
) && !hadexclude
) {
154 ERROR("Failed to delete %s", dirname
);
160 ERROR("Failed to close directory %s", dirname
);
164 return failed
? -1 : 0;
167 /* We have two different magic values for overlayfs, yay. */
168 #ifndef OVERLAYFS_SUPER_MAGIC
169 #define OVERLAYFS_SUPER_MAGIC 0x794c764f
172 #ifndef OVERLAY_SUPER_MAGIC
173 #define OVERLAY_SUPER_MAGIC 0x794c7630
176 /* In overlayfs, st_dev is unreliable. So on overlayfs we don't do the
179 static bool is_native_overlayfs(const char *path
)
181 if (has_fs_type(path
, OVERLAY_SUPER_MAGIC
) ||
182 has_fs_type(path
, OVERLAYFS_SUPER_MAGIC
))
188 /* returns 0 on success, -1 if there were any failures */
189 extern int lxc_rmdir_onedev(const char *path
, const char *exclude
)
194 if (is_native_overlayfs(path
))
197 if (lstat(path
, &mystat
) < 0) {
201 ERROR("Failed to stat %s", path
);
205 return _recursive_rmdir(path
, mystat
.st_dev
, exclude
, 0, onedev
);
208 /* borrowed from iproute2 */
209 extern int get_u16(unsigned short *val
, const char *arg
, int base
)
218 res
= strtoul(arg
, &ptr
, base
);
219 if (!ptr
|| ptr
== arg
|| *ptr
|| res
> 0xFFFF || errno
!= 0)
227 extern int mkdir_p(const char *dir
, mode_t mode
)
229 const char *tmp
= dir
;
230 const char *orig
= dir
;
234 dir
= tmp
+ strspn(tmp
, "/");
235 tmp
= dir
+ strcspn(dir
, "/");
236 makeme
= strndup(orig
, dir
- orig
);
238 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
239 SYSERROR("failed to create directory '%s'", makeme
);
256 if (stat(RUNTIME_PATH
, &sb
) < 0) {
260 if (geteuid() == sb
.st_uid
|| getegid() == sb
.st_gid
) {
261 rundir
= strdup(RUNTIME_PATH
);
265 rundir
= getenv("XDG_RUNTIME_DIR");
267 rundir
= strdup(rundir
);
271 INFO("XDG_RUNTIME_DIR isn't set in the environment.");
272 homedir
= getenv("HOME");
274 ERROR("HOME isn't set in the environment.");
278 rundir
= malloc(sizeof(char) * (17 + strlen(homedir
)));
279 sprintf(rundir
, "%s/.cache/lxc/run/", homedir
);
284 int wait_for_pid(pid_t pid
)
289 ret
= waitpid(pid
, &status
, 0);
297 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
302 int lxc_wait_for_pid_status(pid_t pid
)
307 ret
= waitpid(pid
, &status
, 0);
318 ssize_t
lxc_write_nointr(int fd
, const void* buf
, size_t count
)
322 ret
= write(fd
, buf
, count
);
323 if (ret
< 0 && errno
== EINTR
)
328 ssize_t
lxc_read_nointr(int fd
, void* buf
, size_t count
)
332 ret
= read(fd
, buf
, count
);
333 if (ret
< 0 && errno
== EINTR
)
338 ssize_t
lxc_read_nointr_expect(int fd
, void* buf
, size_t count
, const void* expected_buf
)
341 ret
= lxc_read_nointr(fd
, buf
, count
);
344 if ((size_t)ret
!= count
)
346 if (expected_buf
&& memcmp(buf
, expected_buf
, count
) != 0) {
354 #include <gnutls/gnutls.h>
355 #include <gnutls/crypto.h>
357 __attribute__((constructor
))
358 static void gnutls_lxc_init(void)
360 gnutls_global_init();
363 int sha1sum_file(char *fnam
, unsigned char *digest
)
372 f
= fopen_cloexec(fnam
, "r");
374 SYSERROR("Error opening template");
377 if (fseek(f
, 0, SEEK_END
) < 0) {
378 SYSERROR("Error seeking to end of template");
382 if ((flen
= ftell(f
)) < 0) {
383 SYSERROR("Error telling size of template");
387 if (fseek(f
, 0, SEEK_SET
) < 0) {
388 SYSERROR("Error seeking to start of template");
392 if ((buf
= malloc(flen
+1)) == NULL
) {
393 SYSERROR("Out of memory");
397 if (fread(buf
, 1, flen
, f
) != flen
) {
398 SYSERROR("Failure reading template");
404 SYSERROR("Failre closing template");
409 ret
= gnutls_hash_fast(GNUTLS_DIG_SHA1
, buf
, flen
, (void *)digest
);
415 char** lxc_va_arg_list_to_argv(va_list ap
, size_t skip
, int do_strdup
)
418 size_t count
= 1 + skip
;
421 /* first determine size of argument list, we don't want to reallocate
426 char* arg
= va_arg(ap2
, char*);
433 result
= calloc(count
, sizeof(char*));
438 char* arg
= va_arg(ap
, char*);
441 arg
= do_strdup
? strdup(arg
) : arg
;
444 result
[count
++] = arg
;
447 /* calloc has already set last element to NULL*/
455 const char** lxc_va_arg_list_to_argv_const(va_list ap
, size_t skip
)
457 return (const char**)lxc_va_arg_list_to_argv(ap
, skip
, 0);
460 struct lxc_popen_FILE
*lxc_popen(const char *command
)
465 struct lxc_popen_FILE
*fp
= NULL
;
467 ret
= pipe2(pipe_fds
, O_CLOEXEC
);
480 /* duplicate stdout */
481 if (pipe_fds
[1] != STDOUT_FILENO
)
482 ret
= dup2(pipe_fds
[1], STDOUT_FILENO
);
484 ret
= fcntl(pipe_fds
[1], F_SETFD
, 0);
490 /* duplicate stderr */
491 if (pipe_fds
[1] != STDERR_FILENO
)
492 ret
= dup2(pipe_fds
[1], STDERR_FILENO
);
494 ret
= fcntl(pipe_fds
[1], F_SETFD
, 0);
499 /* unblock all signals */
500 ret
= sigfillset(&mask
);
504 ret
= pthread_sigmask(SIG_UNBLOCK
, &mask
, NULL
);
508 execl("/bin/sh", "sh", "-c", command
, (char *)NULL
);
515 fp
= malloc(sizeof(*fp
));
518 memset(fp
, 0, sizeof(*fp
));
520 fp
->child_pid
= child_pid
;
521 fp
->pipe
= pipe_fds
[0];
523 /* From now on, closing fp->f will also close fp->pipe. So only ever
524 * call fclose(fp->f).
526 fp
->f
= fdopen(pipe_fds
[0], "r");
533 /* We can only close pipe_fds[0] if fdopen() didn't succeed or wasn't
534 * called yet. Otherwise the fd belongs to the file opened by fdopen()
535 * since it isn't dup()ed.
537 if (fp
&& !fp
->f
&& pipe_fds
[0] >= 0)
540 if (pipe_fds
[1] >= 0)
552 int lxc_pclose(struct lxc_popen_FILE
*fp
)
561 wait_pid
= waitpid(fp
->child_pid
, &wstatus
, 0);
562 } while (wait_pid
< 0 && errno
== EINTR
);
573 char *lxc_string_replace(const char *needle
, const char *replacement
, const char *haystack
)
575 ssize_t len
= -1, saved_len
= -1;
577 size_t replacement_len
= strlen(replacement
);
578 size_t needle_len
= strlen(needle
);
580 /* should be executed exactly twice */
581 while (len
== -1 || result
== NULL
) {
587 result
= calloc(1, len
+ 1);
595 for (last_p
= (char *)haystack
, p
= strstr(last_p
, needle
); p
; last_p
= p
, p
= strstr(last_p
, needle
)) {
596 part_len
= (ssize_t
)(p
- last_p
);
597 if (result
&& part_len
> 0)
598 memcpy(&result
[len
], last_p
, part_len
);
600 if (result
&& replacement_len
> 0)
601 memcpy(&result
[len
], replacement
, replacement_len
);
602 len
+= replacement_len
;
605 part_len
= strlen(last_p
);
606 if (result
&& part_len
> 0)
607 memcpy(&result
[len
], last_p
, part_len
);
611 /* make sure we did the same thing twice,
612 * once for calculating length, the other
613 * time for copying data */
614 if (saved_len
!= len
) {
618 /* make sure we didn't overwrite any buffer,
619 * due to calloc the string should be 0-terminated */
620 if (result
[len
] != '\0') {
628 bool lxc_string_in_array(const char *needle
, const char **haystack
)
630 for (; haystack
&& *haystack
; haystack
++)
631 if (!strcmp(needle
, *haystack
))
636 char *lxc_string_join(const char *sep
, const char **parts
, bool use_as_prefix
)
640 size_t sep_len
= strlen(sep
);
641 size_t result_len
= use_as_prefix
* sep_len
;
644 /* calculate new string length */
645 for (p
= (char **)parts
; *p
; p
++)
646 result_len
+= (p
> (char **)parts
) * sep_len
+ strlen(*p
);
648 buf_len
= result_len
+ 1;
649 result
= calloc(buf_len
, 1);
654 (void)strlcpy(result
, sep
, buf_len
);
656 for (p
= (char **)parts
; *p
; p
++) {
657 if (p
> (char **)parts
)
658 (void)strlcat(result
, sep
, buf_len
);
659 (void)strlcat(result
, *p
, buf_len
);
665 char **lxc_normalize_path(const char *path
)
669 size_t components_len
= 0;
672 components
= lxc_string_split(path
, '/');
675 for (p
= components
; *p
; p
++)
678 /* resolve '.' and '..' */
679 for (pos
= 0; pos
< components_len
; ) {
680 if (!strcmp(components
[pos
], ".") || (!strcmp(components
[pos
], "..") && pos
== 0)) {
681 /* eat this element */
682 free(components
[pos
]);
683 memmove(&components
[pos
], &components
[pos
+1], sizeof(char *) * (components_len
- pos
));
685 } else if (!strcmp(components
[pos
], "..")) {
686 /* eat this and the previous element */
687 free(components
[pos
- 1]);
688 free(components
[pos
]);
689 memmove(&components
[pos
-1], &components
[pos
+1], sizeof(char *) * (components_len
- pos
));
700 char *lxc_deslashify(const char *path
)
710 parts
= lxc_normalize_path(dup
);
716 /* We'll end up here if path == "///" or path == "". */
720 lxc_free_array((void **)parts
, free
);
723 n
= strcspn(dup
, "/");
726 lxc_free_array((void **)parts
, free
);
736 p
= lxc_string_join("/", (const char **)parts
, *dup
== '/');
738 lxc_free_array((void **)parts
, free
);
742 char *lxc_append_paths(const char *first
, const char *second
)
747 const char *pattern
= "%s%s";
749 len
= strlen(first
) + strlen(second
) + 1;
750 if (second
[0] != '/') {
755 result
= calloc(1, len
);
759 ret
= snprintf(result
, len
, pattern
, first
, second
);
760 if (ret
< 0 || (size_t)ret
>= len
) {
768 bool lxc_string_in_list(const char *needle
, const char *haystack
, char _sep
)
770 char *token
, *str
, *saveptr
= NULL
;
771 char sep
[2] = { _sep
, '\0' };
774 if (!haystack
|| !needle
)
777 len
= strlen(haystack
);
778 str
= alloca(len
+ 1);
779 (void)strlcpy(str
, haystack
, len
+ 1);
781 for (; (token
= strtok_r(str
, sep
, &saveptr
)); str
= NULL
) {
782 if (strcmp(needle
, token
) == 0)
789 char **lxc_string_split(const char *string
, char _sep
)
791 char *token
, *str
, *saveptr
= NULL
;
792 char sep
[2] = {_sep
, '\0'};
793 char **tmp
= NULL
, **result
= NULL
;
794 size_t result_capacity
= 0;
795 size_t result_count
= 0;
800 return calloc(1, sizeof(char *));
802 len
= strlen(string
);
803 str
= alloca(len
+ 1);
804 (void)strlcpy(str
, string
, len
+ 1);
806 for (; (token
= strtok_r(str
, sep
, &saveptr
)); str
= NULL
) {
807 r
= lxc_grow_array((void ***)&result
, &result_capacity
, result_count
+ 1, 16);
810 result
[result_count
] = strdup(token
);
811 if (!result
[result_count
])
816 /* if we allocated too much, reduce it */
817 tmp
= realloc(result
, (result_count
+ 1) * sizeof(char *));
821 /* Make sure we don't return uninitialized memory. */
822 if (result_count
== 0)
827 lxc_free_array((void **)result
, free
);
832 static bool complete_word(char ***result
, char *start
, char *end
, size_t *cap
, size_t *cnt
)
836 r
= lxc_grow_array((void ***)result
, cap
, 2 + *cnt
, 16);
839 (*result
)[*cnt
] = strndup(start
, end
- start
);
840 if (!(*result
)[*cnt
])
848 * Given a a string 'one two "three four"', split into three words,
849 * one, two, and "three four"
851 char **lxc_string_split_quoted(char *string
)
853 char *nextword
= string
, *p
, state
;
854 char **result
= NULL
;
855 size_t result_capacity
= 0;
856 size_t result_count
= 0;
858 if (!string
|| !*string
)
859 return calloc(1, sizeof(char *));
861 // TODO I'm *not* handling escaped quote
863 for (p
= string
; *p
; p
++) {
868 else if (*p
== '"' || *p
== '\'') {
878 complete_word(&result
, nextword
, p
, &result_capacity
, &result_count
);
886 complete_word(&result
, nextword
+1, p
, &result_capacity
, &result_count
);
895 complete_word(&result
, nextword
, p
, &result_capacity
, &result_count
);
897 return realloc(result
, (result_count
+ 1) * sizeof(char *));
900 char **lxc_string_split_and_trim(const char *string
, char _sep
)
902 char *token
, *str
, *saveptr
= NULL
;
903 char sep
[2] = { _sep
, '\0' };
904 char **result
= NULL
;
905 size_t result_capacity
= 0;
906 size_t result_count
= 0;
912 return calloc(1, sizeof(char *));
914 len
= strlen(string
);
915 str
= alloca(len
+ 1);
916 (void)strlcpy(str
, string
, len
+ 1);
918 for (; (token
= strtok_r(str
, sep
, &saveptr
)); str
= NULL
) {
919 while (token
[0] == ' ' || token
[0] == '\t')
922 while (i
> 0 && (token
[i
- 1] == ' ' || token
[i
- 1] == '\t')) {
926 r
= lxc_grow_array((void ***)&result
, &result_capacity
, result_count
+ 1, 16);
929 result
[result_count
] = strdup(token
);
930 if (!result
[result_count
])
935 /* if we allocated too much, reduce it */
936 return realloc(result
, (result_count
+ 1) * sizeof(char *));
939 lxc_free_array((void **)result
, free
);
944 void lxc_free_array(void **array
, lxc_free_fn element_free_fn
)
947 for (p
= array
; p
&& *p
; p
++)
952 int lxc_grow_array(void ***array
, size_t* capacity
, size_t new_size
, size_t capacity_increment
)
957 /* first time around, catch some trivial mistakes of the user
958 * only initializing one of these */
959 if (!*array
|| !*capacity
) {
964 new_capacity
= *capacity
;
965 while (new_size
+ 1 > new_capacity
)
966 new_capacity
+= capacity_increment
;
967 if (new_capacity
!= *capacity
) {
968 /* we have to reallocate */
969 new_array
= realloc(*array
, new_capacity
* sizeof(void *));
972 memset(&new_array
[*capacity
], 0, (new_capacity
- (*capacity
)) * sizeof(void *));
974 *capacity
= new_capacity
;
977 /* array has sufficient elements */
981 size_t lxc_array_len(void **array
)
986 for (p
= array
; p
&& *p
; p
++)
992 int lxc_write_to_file(const char *filename
, const void *buf
, size_t count
,
993 bool add_newline
, mode_t mode
)
998 fd
= open(filename
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_CLOEXEC
, mode
);
1001 ret
= lxc_write_nointr(fd
, buf
, count
);
1004 if ((size_t)ret
!= count
)
1007 ret
= lxc_write_nointr(fd
, "\n", 1);
1015 saved_errno
= errno
;
1017 errno
= saved_errno
;
1021 int lxc_read_from_file(const char *filename
, void* buf
, size_t count
)
1023 int fd
= -1, saved_errno
;
1026 fd
= open(filename
, O_RDONLY
| O_CLOEXEC
);
1030 if (!buf
|| !count
) {
1033 while ((ret
= read(fd
, buf2
, 100)) > 0)
1038 memset(buf
, 0, count
);
1039 ret
= read(fd
, buf
, count
);
1043 ERROR("read %s: %s", filename
, strerror(errno
));
1045 saved_errno
= errno
;
1047 errno
= saved_errno
;
1051 void **lxc_append_null_to_array(void **array
, size_t count
)
1055 /* Append NULL to the array */
1057 temp
= realloc(array
, (count
+ 1) * sizeof(*array
));
1060 for (i
= 0; i
< count
; i
++)
1066 array
[count
] = NULL
;
1071 int randseed(bool srand_it
)
1074 srand pre-seed function based on /dev/urandom
1076 unsigned int seed
= time(NULL
) + getpid();
1079 f
= fopen("/dev/urandom", "r");
1081 int ret
= fread(&seed
, sizeof(seed
), 1, f
);
1083 SYSDEBUG("unable to fread /dev/urandom, fallback to time+pid rand seed");
1094 uid_t
get_ns_uid(uid_t orig
)
1098 uid_t nsid
, hostid
, range
;
1099 FILE *f
= fopen("/proc/self/uid_map", "r");
1103 while (getline(&line
, &sz
, f
) != -1) {
1104 if (sscanf(line
, "%u %u %u", &nsid
, &hostid
, &range
) != 3)
1106 if (hostid
<= orig
&& hostid
+ range
> orig
) {
1107 nsid
+= orig
- hostid
;
1119 bool dir_exists(const char *path
)
1124 ret
= stat(path
, &sb
);
1126 /* Could be something other than eexist, just say "no". */
1128 return S_ISDIR(sb
.st_mode
);
1131 /* Note we don't use SHA-1 here as we don't want to depend on HAVE_GNUTLS.
1132 * FNV has good anti collision properties and we're not worried
1133 * about pre-image resistance or one-way-ness, we're just trying to make
1134 * the name unique in the 108 bytes of space we have.
1136 uint64_t fnv_64a_buf(void *buf
, size_t len
, uint64_t hval
)
1140 for(bp
= buf
; bp
< (unsigned char *)buf
+ len
; bp
++)
1142 /* xor the bottom with the current octet */
1143 hval
^= (uint64_t)*bp
;
1146 * multiply by the 64 bit FNV magic prime mod 2^64
1148 hval
+= (hval
<< 1) + (hval
<< 4) + (hval
<< 5) +
1149 (hval
<< 7) + (hval
<< 8) + (hval
<< 40);
1156 * Detect whether / is mounted MS_SHARED. The only way I know of to
1157 * check that is through /proc/self/mountinfo.
1158 * I'm only checking for /. If the container rootfs or mount location
1159 * is MS_SHARED, but not '/', then you're out of luck - figuring that
1160 * out would be too much work to be worth it.
1162 int detect_shared_rootfs(void)
1164 char buf
[LXC_LINELEN
], *p
;
1169 f
= fopen("/proc/self/mountinfo", "r");
1172 while (fgets(buf
, LXC_LINELEN
, f
)) {
1173 for (p
= buf
, i
= 0; p
&& i
< 4; i
++)
1174 p
= strchr(p
+ 1, ' ');
1177 p2
= strchr(p
+ 1, ' ');
1181 if (strcmp(p
+ 1, "/") == 0) {
1182 /* This is '/'. Is it shared? */
1183 p
= strchr(p2
+ 1, ' ');
1184 if (p
&& strstr(p
, "shared:")) {
1194 bool switch_to_ns(pid_t pid
, const char *ns
) {
1196 char nspath
[MAXPATHLEN
];
1198 /* Switch to new ns */
1199 ret
= snprintf(nspath
, MAXPATHLEN
, "/proc/%d/ns/%s", pid
, ns
);
1200 if (ret
< 0 || ret
>= MAXPATHLEN
)
1203 fd
= open(nspath
, O_RDONLY
);
1205 SYSERROR("failed to open %s", nspath
);
1211 SYSERROR("failed to set process %d to %s of %d.", pid
, ns
, fd
);
1220 * looking at fs/proc_namespace.c, it appears we can
1221 * actually expect the rootfs entry to very specifically contain
1222 * " - rootfs rootfs "
1223 * IIUC, so long as we've chrooted so that rootfs is not our root,
1224 * the rootfs entry should always be skipped in mountinfo contents.
1226 bool detect_ramfs_rootfs(void)
1234 f
= fopen("/proc/self/mountinfo", "r");
1238 while (getline(&line
, &len
, f
) != -1) {
1239 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
1240 p
= strchr(p
+ 1, ' ');
1243 p2
= strchr(p
+ 1, ' ');
1247 if (strcmp(p
+ 1, "/") == 0) {
1248 /* This is '/'. Is it the ramfs? */
1249 p
= strchr(p2
+ 1, '-');
1250 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
1262 char *on_path(const char *cmd
, const char *rootfs
) {
1265 char *saveptr
= NULL
;
1266 char cmdpath
[MAXPATHLEN
];
1269 path
= getenv("PATH");
1273 path
= strdup(path
);
1277 entry
= strtok_r(path
, ":", &saveptr
);
1280 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s/%s", rootfs
, entry
, cmd
);
1282 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s", entry
, cmd
);
1284 if (ret
< 0 || ret
>= MAXPATHLEN
)
1287 if (access(cmdpath
, X_OK
) == 0) {
1289 return strdup(cmdpath
);
1293 entry
= strtok_r(NULL
, ":", &saveptr
);
1300 bool file_exists(const char *f
)
1302 struct stat statbuf
;
1304 return stat(f
, &statbuf
) == 0;
1307 bool cgns_supported(void)
1309 return file_exists("/proc/self/ns/cgroup");
1312 /* historically lxc-init has been under /usr/lib/lxc and under
1313 * /usr/lib/$ARCH/lxc. It now lives as $prefix/sbin/init.lxc.
1315 char *choose_init(const char *rootfs
)
1318 const char *empty
= "",
1320 int ret
, env_set
= 0;
1322 if (!getenv("PATH")) {
1323 if (setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 0))
1324 SYSERROR("Failed to setenv");
1328 retv
= on_path("init.lxc", rootfs
);
1331 if (unsetenv("PATH"))
1332 SYSERROR("Failed to unsetenv");
1338 retv
= malloc(PATH_MAX
);
1347 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, SBINDIR
, "/init.lxc");
1348 if (ret
< 0 || ret
>= PATH_MAX
) {
1349 ERROR("pathname too long");
1352 if (access(retv
, X_OK
) == 0)
1355 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, LXCINITDIR
, "/lxc/lxc-init");
1356 if (ret
< 0 || ret
>= PATH_MAX
) {
1357 ERROR("pathname too long");
1360 if (access(retv
, X_OK
) == 0)
1363 ret
= snprintf(retv
, PATH_MAX
, "%s/usr/lib/lxc/lxc-init", tmp
);
1364 if (ret
< 0 || ret
>= PATH_MAX
) {
1365 ERROR("pathname too long");
1368 if (access(retv
, X_OK
) == 0)
1371 ret
= snprintf(retv
, PATH_MAX
, "%s/sbin/lxc-init", tmp
);
1372 if (ret
< 0 || ret
>= PATH_MAX
) {
1373 ERROR("pathname too long");
1376 if (access(retv
, X_OK
) == 0)
1380 * Last resort, look for the statically compiled init.lxc which we
1381 * hopefully bind-mounted in.
1382 * If we are called during container setup, and we get to this point,
1383 * then the init.lxc.static from the host will need to be bind-mounted
1384 * in. So we return NULL here to indicate that.
1389 ret
= snprintf(retv
, PATH_MAX
, "/init.lxc.static");
1390 if (ret
< 0 || ret
>= PATH_MAX
) {
1391 WARN("Nonsense - name /lxc.init.static too long");
1394 if (access(retv
, X_OK
) == 0)
1402 int print_to_file(const char *file
, const char *content
)
1407 f
= fopen(file
, "w");
1410 if (fprintf(f
, "%s", content
) != strlen(content
))
1416 int is_dir(const char *path
)
1418 struct stat statbuf
;
1419 int ret
= stat(path
, &statbuf
);
1420 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
1426 * Given the '-t' template option to lxc-create, figure out what to
1427 * do. If the template is a full executable path, use that. If it
1428 * is something like 'sshd', then return $templatepath/lxc-sshd.
1429 * On success return the template, on error return NULL.
1431 char *get_template_path(const char *t
)
1436 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
1441 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
1442 tpath
= malloc(len
);
1445 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
1446 if (ret
< 0 || ret
>= len
) {
1450 if (access(tpath
, X_OK
) < 0) {
1451 SYSERROR("bad template: %s", t
);
1460 * @path: a pathname where / replaced with '\0'.
1461 * @offsetp: pointer to int showing which path segment was last seen.
1462 * Updated on return to reflect the next segment.
1463 * @fulllen: full original path length.
1464 * Returns a pointer to the next path segment, or NULL if done.
1466 static char *get_nextpath(char *path
, int *offsetp
, int fulllen
)
1468 int offset
= *offsetp
;
1470 if (offset
>= fulllen
)
1473 while (path
[offset
] != '\0' && offset
< fulllen
)
1475 while (path
[offset
] == '\0' && offset
< fulllen
)
1479 return (offset
< fulllen
) ? &path
[offset
] : NULL
;
1483 * Check that @subdir is a subdir of @dir. @len is the length of
1484 * @dir (to avoid having to recalculate it).
1486 static bool is_subdir(const char *subdir
, const char *dir
, size_t len
)
1488 size_t subdirlen
= strlen(subdir
);
1490 if (subdirlen
< len
)
1492 if (strncmp(subdir
, dir
, len
) != 0)
1494 if (dir
[len
-1] == '/')
1496 if (subdir
[len
] == '/' || subdirlen
== len
)
1502 * Check if the open fd is a symlink. Return -ELOOP if it is. Return
1503 * -ENOENT if we couldn't fstat. Return 0 if the fd is ok.
1505 static int check_symlink(int fd
)
1508 int ret
= fstat(fd
, &sb
);
1511 if (S_ISLNK(sb
.st_mode
))
1517 * Open a file or directory, provided that it contains no symlinks.
1519 * CAVEAT: This function must not be used for other purposes than container
1520 * setup before executing the container's init
1522 static int open_if_safe(int dirfd
, const char *nextpath
)
1524 int newfd
= openat(dirfd
, nextpath
, O_RDONLY
| O_NOFOLLOW
);
1525 if (newfd
>= 0) /* Was not a symlink, all good. */
1531 if (errno
== EPERM
|| errno
== EACCES
) {
1532 /* We're not root (cause we got EPERM) so try opening with
1535 newfd
= openat(dirfd
, nextpath
, O_PATH
| O_NOFOLLOW
);
1537 /* O_PATH will return an fd for symlinks. We know
1538 * nextpath wasn't a symlink at last openat, so if fd is
1539 * now a link, then something * fishy is going on.
1541 int ret
= check_symlink(newfd
);
1553 * Open a path intending for mounting, ensuring that the final path
1554 * is inside the container's rootfs.
1556 * CAVEAT: This function must not be used for other purposes than container
1557 * setup before executing the container's init
1559 * @target: path to be opened
1560 * @prefix_skip: a part of @target in which to ignore symbolic links. This
1561 * would be the container's rootfs.
1563 * Return an open fd for the path, or <0 on error.
1565 static int open_without_symlink(const char *target
, const char *prefix_skip
)
1567 int curlen
= 0, dirfd
, fulllen
, i
;
1570 fulllen
= strlen(target
);
1572 /* make sure prefix-skip makes sense */
1573 if (prefix_skip
&& strlen(prefix_skip
) > 0) {
1574 curlen
= strlen(prefix_skip
);
1575 if (!is_subdir(target
, prefix_skip
, curlen
)) {
1576 ERROR("WHOA there - target '%s' didn't start with prefix '%s'",
1577 target
, prefix_skip
);
1581 * get_nextpath() expects the curlen argument to be
1582 * on a (turned into \0) / or before it, so decrement
1583 * curlen to make sure that happens
1592 /* Make a copy of target which we can hack up, and tokenize it */
1593 if ((dup
= strdup(target
)) == NULL
) {
1594 SYSERROR("Out of memory checking for symbolic link");
1597 for (i
= 0; i
< fulllen
; i
++) {
1602 dirfd
= open(prefix_skip
, O_RDONLY
);
1606 int newfd
, saved_errno
;
1609 if ((nextpath
= get_nextpath(dup
, &curlen
, fulllen
)) == NULL
)
1611 newfd
= open_if_safe(dirfd
, nextpath
);
1612 saved_errno
= errno
;
1616 errno
= saved_errno
;
1618 SYSERROR("%s in %s was a symbolic link!", nextpath
, target
);
1629 * Safely mount a path into a container, ensuring that the mount target
1630 * is under the container's @rootfs. (If @rootfs is NULL, then the container
1631 * uses the host's /)
1633 * CAVEAT: This function must not be used for other purposes than container
1634 * setup before executing the container's init
1636 int safe_mount(const char *src
, const char *dest
, const char *fstype
,
1637 unsigned long flags
, const void *data
, const char *rootfs
)
1639 int destfd
, ret
, saved_errno
;
1640 /* Only needs enough for /proc/self/fd/<fd>. */
1641 char srcbuf
[50], destbuf
[50];
1643 const char *mntsrc
= src
;
1648 /* todo - allow symlinks for relative paths if 'allowsymlinks' option is passed */
1649 if (flags
& MS_BIND
&& src
&& src
[0] != '/') {
1650 INFO("this is a relative bind mount");
1651 srcfd
= open_without_symlink(src
, NULL
);
1654 ret
= snprintf(srcbuf
, 50, "/proc/self/fd/%d", srcfd
);
1655 if (ret
< 0 || ret
> 50) {
1657 ERROR("Out of memory");
1663 destfd
= open_without_symlink(dest
, rootfs
);
1666 saved_errno
= errno
;
1668 errno
= saved_errno
;
1673 ret
= snprintf(destbuf
, 50, "/proc/self/fd/%d", destfd
);
1674 if (ret
< 0 || ret
> 50) {
1678 ERROR("Out of memory");
1682 ret
= mount(mntsrc
, destbuf
, fstype
, flags
, data
);
1683 saved_errno
= errno
;
1688 errno
= saved_errno
;
1689 SYSERROR("Failed to mount %s onto %s", src
? src
: "(null)", dest
);
1697 * Mount a proc under @rootfs if proc self points to a pid other than
1698 * my own. This is needed to have a known-good proc mount for setting
1699 * up LSMs both at container startup and attach.
1701 * @rootfs : the rootfs where proc should be mounted
1703 * Returns < 0 on failure, 0 if the correct proc was already mounted
1704 * and 1 if a new proc was mounted.
1706 * NOTE: not to be called from inside the container namespace!
1708 int lxc_mount_proc_if_needed(const char *rootfs
)
1710 char path
[MAXPATHLEN
];
1711 int link_to_pid
, linklen
, mypid
, ret
;
1712 char link
[LXC_NUMSTRLEN64
] = {0};
1714 ret
= snprintf(path
, MAXPATHLEN
, "%s/proc/self", rootfs
);
1715 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1716 SYSERROR("proc path name too long");
1720 linklen
= readlink(path
, link
, LXC_NUMSTRLEN64
);
1722 ret
= snprintf(path
, MAXPATHLEN
, "%s/proc", rootfs
);
1723 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1724 SYSERROR("proc path name too long");
1728 /* /proc not mounted */
1730 if (mkdir(path
, 0755) && errno
!= EEXIST
)
1733 } else if (linklen
>= LXC_NUMSTRLEN64
) {
1734 link
[linklen
- 1] = '\0';
1735 ERROR("readlink returned truncated content: \"%s\"", link
);
1739 mypid
= lxc_raw_getpid();
1740 INFO("I am %d, /proc/self points to \"%s\"", mypid
, link
);
1742 if (lxc_safe_int(link
, &link_to_pid
) < 0)
1745 /* correct procfs is already mounted */
1746 if (link_to_pid
== mypid
)
1749 ret
= umount2(path
, MNT_DETACH
);
1751 WARN("failed to umount \"%s\" with MNT_DETACH", path
);
1754 /* rootfs is NULL */
1755 if (!strcmp(rootfs
, ""))
1756 ret
= mount("proc", path
, "proc", 0, NULL
);
1758 ret
= safe_mount("proc", path
, "proc", 0, NULL
, rootfs
);
1762 INFO("mounted /proc in container for security transition");
1766 int open_devnull(void)
1768 int fd
= open("/dev/null", O_RDWR
);
1771 SYSERROR("Can't open /dev/null");
1776 int set_stdfds(int fd
)
1783 ret
= dup2(fd
, STDIN_FILENO
);
1787 ret
= dup2(fd
, STDOUT_FILENO
);
1791 ret
= dup2(fd
, STDERR_FILENO
);
1798 int null_stdfds(void)
1801 int fd
= open_devnull();
1804 ret
= set_stdfds(fd
);
1812 * Return the number of lines in file @fn, or -1 on error
1814 int lxc_count_file_lines(const char *fn
)
1821 f
= fopen_cloexec(fn
, "r");
1825 while (getline(&line
, &sz
, f
) != -1) {
1833 /* Check whether a signal is blocked by a process. */
1834 /* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
1835 #define __PROC_STATUS_LEN (6 + (LXC_NUMSTRLEN64) + 7 + 1)
1836 bool task_blocks_signal(pid_t pid
, int signal
)
1839 char status
[__PROC_STATUS_LEN
];
1841 uint64_t sigblk
= 0, one
= 1;
1846 ret
= snprintf(status
, __PROC_STATUS_LEN
, "/proc/%d/status", pid
);
1847 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
1850 f
= fopen(status
, "r");
1854 while (getline(&line
, &n
, f
) != -1) {
1857 if (strncmp(line
, "SigBlk:", 7))
1860 numstr
= lxc_trim_whitespace_in_place(line
+ 7);
1861 ret
= lxc_safe_uint64(numstr
, &sigblk
, 16);
1868 if (sigblk
& (one
<< (signal
- 1)))
1877 static int lxc_append_null_to_list(void ***list
)
1883 for (; (*list
)[newentry
]; newentry
++) {
1887 tmp
= realloc(*list
, (newentry
+ 2) * sizeof(void **));
1892 (*list
)[newentry
+ 1] = NULL
;
1897 int lxc_append_string(char ***list
, char *entry
)
1902 newentry
= lxc_append_null_to_list((void ***)list
);
1906 copy
= strdup(entry
);
1910 (*list
)[newentry
] = copy
;
1915 int lxc_preserve_ns(const int pid
, const char *ns
)
1918 /* 5 /proc + 21 /int_as_str + 3 /ns + 20 /NS_NAME + 1 \0 */
1919 #define __NS_PATH_LEN 50
1920 char path
[__NS_PATH_LEN
];
1922 /* This way we can use this function to also check whether namespaces
1923 * are supported by the kernel by passing in the NULL or the empty
1926 ret
= snprintf(path
, __NS_PATH_LEN
, "/proc/%d/ns%s%s", pid
,
1927 !ns
|| strcmp(ns
, "") == 0 ? "" : "/",
1928 !ns
|| strcmp(ns
, "") == 0 ? "" : ns
);
1930 if (ret
< 0 || (size_t)ret
>= __NS_PATH_LEN
)
1933 return open(path
, O_RDONLY
| O_CLOEXEC
);
1936 int lxc_safe_uint(const char *numstr
, unsigned int *converted
)
1939 unsigned long int uli
;
1941 while (isspace(*numstr
))
1948 uli
= strtoul(numstr
, &err
, 0);
1949 if (errno
== ERANGE
&& uli
== ULONG_MAX
)
1952 if (err
== numstr
|| *err
!= '\0')
1958 *converted
= (unsigned int)uli
;
1962 int lxc_safe_ulong(const char *numstr
, unsigned long *converted
)
1965 unsigned long int uli
;
1967 while (isspace(*numstr
))
1974 uli
= strtoul(numstr
, &err
, 0);
1975 if (errno
== ERANGE
&& uli
== ULONG_MAX
)
1978 if (err
== numstr
|| *err
!= '\0')
1985 int lxc_safe_uint64(const char *numstr
, uint64_t *converted
, int base
)
1990 while (isspace(*numstr
))
1997 u
= strtoull(numstr
, &err
, base
);
1998 if (errno
== ERANGE
&& u
== ULLONG_MAX
)
2001 if (err
== numstr
|| *err
!= '\0')
2008 int lxc_safe_int(const char *numstr
, int *converted
)
2011 signed long int sli
;
2014 sli
= strtol(numstr
, &err
, 0);
2015 if (errno
== ERANGE
&& (sli
== LONG_MAX
|| sli
== LONG_MIN
))
2018 if (errno
!= 0 && sli
== 0)
2021 if (err
== numstr
|| *err
!= '\0')
2024 if (sli
> INT_MAX
|| sli
< INT_MIN
)
2027 *converted
= (int)sli
;
2031 int lxc_safe_long(const char *numstr
, long int *converted
)
2034 signed long int sli
;
2037 sli
= strtol(numstr
, &err
, 0);
2038 if (errno
== ERANGE
&& (sli
== LONG_MAX
|| sli
== LONG_MIN
))
2041 if (errno
!= 0 && sli
== 0)
2044 if (err
== numstr
|| *err
!= '\0')
2051 int lxc_safe_long_long(const char *numstr
, long long int *converted
)
2054 signed long long int sli
;
2057 sli
= strtoll(numstr
, &err
, 0);
2058 if (errno
== ERANGE
&& (sli
== LLONG_MAX
|| sli
== LLONG_MIN
))
2061 if (errno
!= 0 && sli
== 0)
2064 if (err
== numstr
|| *err
!= '\0')
2071 int lxc_switch_uid_gid(uid_t uid
, gid_t gid
)
2073 if (setgid(gid
) < 0) {
2074 SYSERROR("Failed to switch to gid %d.", gid
);
2077 NOTICE("Switched to gid %d.", gid
);
2079 if (setuid(uid
) < 0) {
2080 SYSERROR("Failed to switch to uid %d.", uid
);
2083 NOTICE("Switched to uid %d.", uid
);
2088 /* Simple covenience function which enables uniform logging. */
2089 int lxc_setgroups(int size
, gid_t list
[])
2091 if (setgroups(size
, list
) < 0) {
2092 SYSERROR("Failed to setgroups().");
2095 NOTICE("Dropped additional groups.");
2100 static int lxc_get_unused_loop_dev_legacy(char *loop_name
)
2103 struct loop_info64 lo64
;
2105 int dfd
= -1, fd
= -1, ret
= -1;
2107 dir
= opendir("/dev");
2111 while ((dp
= readdir(dir
))) {
2112 if (strncmp(dp
->d_name
, "loop", 4) != 0)
2119 fd
= openat(dfd
, dp
->d_name
, O_RDWR
);
2123 ret
= ioctl(fd
, LOOP_GET_STATUS64
, &lo64
);
2125 if (ioctl(fd
, LOOP_GET_STATUS64
, &lo64
) == 0 ||
2133 ret
= snprintf(loop_name
, LO_NAME_SIZE
, "/dev/%s", dp
->d_name
);
2134 if (ret
< 0 || ret
>= LO_NAME_SIZE
) {
2151 static int lxc_get_unused_loop_dev(char *name_loop
)
2154 int fd_ctl
= -1, fd_tmp
= -1;
2156 fd_ctl
= open("/dev/loop-control", O_RDWR
| O_CLOEXEC
);
2160 loop_nr
= ioctl(fd_ctl
, LOOP_CTL_GET_FREE
);
2164 ret
= snprintf(name_loop
, LO_NAME_SIZE
, "/dev/loop%d", loop_nr
);
2165 if (ret
< 0 || ret
>= LO_NAME_SIZE
)
2168 fd_tmp
= open(name_loop
, O_RDWR
| O_CLOEXEC
);
2177 int lxc_prepare_loop_dev(const char *source
, char *loop_dev
, int flags
)
2180 struct loop_info64 lo64
;
2181 int fd_img
= -1, fret
= -1, fd_loop
= -1;
2183 fd_loop
= lxc_get_unused_loop_dev(loop_dev
);
2185 if (fd_loop
== -ENODEV
)
2186 fd_loop
= lxc_get_unused_loop_dev_legacy(loop_dev
);
2191 fd_img
= open(source
, O_RDWR
| O_CLOEXEC
);
2195 ret
= ioctl(fd_loop
, LOOP_SET_FD
, fd_img
);
2199 memset(&lo64
, 0, sizeof(lo64
));
2200 lo64
.lo_flags
= flags
;
2202 ret
= ioctl(fd_loop
, LOOP_SET_STATUS64
, &lo64
);
2212 if (fret
< 0 && fd_loop
>= 0) {
2220 int lxc_unstack_mountpoint(const char *path
, bool lazy
)
2226 ret
= umount2(path
, lazy
? MNT_DETACH
: 0);
2228 /* We consider anything else than EINVAL deadly to prevent going
2229 * into an infinite loop. (The other alternative is constantly
2230 * parsing /proc/self/mountinfo which is yucky and probably
2233 if (errno
!= EINVAL
)
2236 /* Just stop counting when this happens. That'd just be so
2237 * stupid that we won't even bother trying to report back the
2238 * correct value anymore.
2240 if (umounts
!= INT_MAX
)
2242 /* We succeeded in umounting. Make sure that there's no other
2243 * mountpoint stacked underneath.
2251 int run_command(char *buf
, size_t buf_size
, int (*child_fn
)(void *), void *args
)
2254 int ret
, fret
, pipefd
[2];
2257 /* Make sure our callers do not receive uninitialized memory. */
2258 if (buf_size
> 0 && buf
)
2261 if (pipe(pipefd
) < 0) {
2262 SYSERROR("failed to create pipe");
2266 child
= lxc_raw_clone(0);
2270 SYSERROR("failed to create new process");
2275 /* Close the read-end of the pipe. */
2278 /* Redirect std{err,out} to write-end of the
2281 ret
= dup2(pipefd
[1], STDOUT_FILENO
);
2283 ret
= dup2(pipefd
[1], STDERR_FILENO
);
2285 /* Close the write-end of the pipe. */
2289 SYSERROR("failed to duplicate std{err,out} file descriptor");
2290 _exit(EXIT_FAILURE
);
2293 /* Does not return. */
2295 ERROR("failed to exec command");
2296 _exit(EXIT_FAILURE
);
2299 /* close the write-end of the pipe */
2302 if (buf
&& buf_size
> 0) {
2303 bytes
= read(pipefd
[0], buf
, buf_size
- 1);
2305 buf
[bytes
- 1] = '\0';
2308 fret
= wait_for_pid(child
);
2309 /* close the read-end of the pipe */
2315 char *must_make_path(const char *first
, ...)
2319 size_t full_len
= strlen(first
);
2322 dest
= must_copy_string(first
);
2324 va_start(args
, first
);
2325 while ((cur
= va_arg(args
, char *)) != NULL
) {
2326 full_len
+= strlen(cur
);
2330 buf_len
= full_len
+ 1;
2331 dest
= must_realloc(dest
, buf_len
);
2334 (void)strlcat(dest
, "/", buf_len
);
2335 (void)strlcat(dest
, cur
, buf_len
);
2342 char *must_append_path(char *first
, ...)
2350 full_len
= strlen(first
);
2351 va_start(args
, first
);
2352 while ((cur
= va_arg(args
, char *)) != NULL
) {
2353 full_len
+= strlen(cur
);
2357 buf_len
= full_len
+ 1;
2358 dest
= must_realloc(dest
, buf_len
);
2361 (void)strlcat(dest
, "/", buf_len
);
2362 (void)strlcat(dest
, cur
, buf_len
);
2369 char *must_copy_string(const char *entry
)
2376 ret
= strdup(entry
);
2382 void *must_realloc(void *orig
, size_t sz
)
2387 ret
= realloc(orig
, sz
);
2393 bool is_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
2395 return (fs
->f_type
== (fs_type_magic
)magic_val
);
2398 bool has_fs_type(const char *path
, fs_type_magic magic_val
)
2404 ret
= statfs(path
, &sb
);
2408 has_type
= is_fs_type(&sb
, magic_val
);
2409 if (!has_type
&& magic_val
== RAMFS_MAGIC
)
2410 WARN("When the ramfs it a tmpfs statfs() might report tmpfs");
2415 bool lxc_nic_exists(char *nic
)
2417 #define __LXC_SYS_CLASS_NET_LEN 15 + IFNAMSIZ + 1
2418 char path
[__LXC_SYS_CLASS_NET_LEN
];
2422 if (!strcmp(nic
, "none"))
2425 ret
= snprintf(path
, __LXC_SYS_CLASS_NET_LEN
, "/sys/class/net/%s", nic
);
2426 if (ret
< 0 || (size_t)ret
>= __LXC_SYS_CLASS_NET_LEN
)
2429 ret
= stat(path
, &sb
);
2436 int lxc_make_tmpfile(char *template, bool rm
)
2442 fd
= mkstemp(template);
2450 ret
= unlink(template);
2459 int parse_byte_size_string(const char *s
, int64_t *converted
)
2461 int ret
, suffix_len
;
2463 int64_t mltpl
, overflow
;
2465 char dup
[LXC_NUMSTRLEN64
+ 2];
2466 char suffix
[3] = {0};
2468 if (!s
|| !strcmp(s
, ""))
2471 end
= stpncpy(dup
, s
, sizeof(dup
) - 1);
2475 if (isdigit(*(end
- 1)))
2477 else if (isalpha(*(end
- 1)))
2482 if (suffix_len
> 0 && (end
- 2) == dup
&& !isdigit(*(end
- 2)))
2485 if (suffix_len
> 0 && isalpha(*(end
- 2)))
2488 if (suffix_len
> 0) {
2489 memcpy(suffix
, end
- suffix_len
, suffix_len
);
2490 *(suffix
+ suffix_len
) = '\0';
2491 *(end
- suffix_len
) = '\0';
2493 dup
[lxc_char_right_gc(dup
, strlen(dup
))] = '\0';
2495 ret
= lxc_safe_long_long(dup
, &conv
);
2499 if (suffix_len
!= 2) {
2504 if (strcasecmp(suffix
, "KB") == 0)
2506 else if (strcasecmp(suffix
, "MB") == 0)
2507 mltpl
= 1024 * 1024;
2508 else if (strcasecmp(suffix
, "GB") == 0)
2509 mltpl
= 1024 * 1024 * 1024;
2513 overflow
= conv
* mltpl
;
2514 if (conv
!= 0 && (overflow
/ conv
) != mltpl
)
2517 *converted
= overflow
;
2521 uint64_t lxc_find_next_power2(uint64_t n
)
2523 /* 0 is not valid input. We return 0 to the caller since 0 is not a
2524 * valid power of two.
2539 int lxc_set_death_signal(int signal
)
2544 ret
= prctl(PR_SET_PDEATHSIG
, signal
, 0, 0, 0);
2546 /* Check whether we have been orphaned. */
2547 ppid
= (pid_t
)syscall(SYS_getppid
);
2551 self
= lxc_raw_getpid();
2552 ret
= kill(self
, SIGKILL
);
2558 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d", signal
);
2565 void remove_trailing_newlines(char *l
)
2572 while (--p
>= l
&& *p
== '\n')