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 DEBUG("unable to fread /dev/urandom, %s, fallback to time+pid rand seed", strerror(errno
));
1093 uid_t
get_ns_uid(uid_t orig
)
1097 uid_t nsid
, hostid
, range
;
1098 FILE *f
= fopen("/proc/self/uid_map", "r");
1102 while (getline(&line
, &sz
, f
) != -1) {
1103 if (sscanf(line
, "%u %u %u", &nsid
, &hostid
, &range
) != 3)
1105 if (hostid
<= orig
&& hostid
+ range
> orig
) {
1106 nsid
+= orig
- hostid
;
1118 bool dir_exists(const char *path
)
1123 ret
= stat(path
, &sb
);
1125 /* Could be something other than eexist, just say "no". */
1127 return S_ISDIR(sb
.st_mode
);
1130 /* Note we don't use SHA-1 here as we don't want to depend on HAVE_GNUTLS.
1131 * FNV has good anti collision properties and we're not worried
1132 * about pre-image resistance or one-way-ness, we're just trying to make
1133 * the name unique in the 108 bytes of space we have.
1135 uint64_t fnv_64a_buf(void *buf
, size_t len
, uint64_t hval
)
1139 for(bp
= buf
; bp
< (unsigned char *)buf
+ len
; bp
++)
1141 /* xor the bottom with the current octet */
1142 hval
^= (uint64_t)*bp
;
1145 * multiply by the 64 bit FNV magic prime mod 2^64
1147 hval
+= (hval
<< 1) + (hval
<< 4) + (hval
<< 5) +
1148 (hval
<< 7) + (hval
<< 8) + (hval
<< 40);
1155 * Detect whether / is mounted MS_SHARED. The only way I know of to
1156 * check that is through /proc/self/mountinfo.
1157 * I'm only checking for /. If the container rootfs or mount location
1158 * is MS_SHARED, but not '/', then you're out of luck - figuring that
1159 * out would be too much work to be worth it.
1161 int detect_shared_rootfs(void)
1163 char buf
[LXC_LINELEN
], *p
;
1168 f
= fopen("/proc/self/mountinfo", "r");
1171 while (fgets(buf
, LXC_LINELEN
, f
)) {
1172 for (p
= buf
, i
= 0; p
&& i
< 4; i
++)
1173 p
= strchr(p
+ 1, ' ');
1176 p2
= strchr(p
+ 1, ' ');
1180 if (strcmp(p
+ 1, "/") == 0) {
1181 /* This is '/'. Is it shared? */
1182 p
= strchr(p2
+ 1, ' ');
1183 if (p
&& strstr(p
, "shared:")) {
1193 bool switch_to_ns(pid_t pid
, const char *ns
) {
1195 char nspath
[MAXPATHLEN
];
1197 /* Switch to new ns */
1198 ret
= snprintf(nspath
, MAXPATHLEN
, "/proc/%d/ns/%s", pid
, ns
);
1199 if (ret
< 0 || ret
>= MAXPATHLEN
)
1202 fd
= open(nspath
, O_RDONLY
);
1204 SYSERROR("failed to open %s", nspath
);
1210 SYSERROR("failed to set process %d to %s of %d.", pid
, ns
, fd
);
1219 * looking at fs/proc_namespace.c, it appears we can
1220 * actually expect the rootfs entry to very specifically contain
1221 * " - rootfs rootfs "
1222 * IIUC, so long as we've chrooted so that rootfs is not our root,
1223 * the rootfs entry should always be skipped in mountinfo contents.
1225 bool detect_ramfs_rootfs(void)
1233 f
= fopen("/proc/self/mountinfo", "r");
1237 while (getline(&line
, &len
, f
) != -1) {
1238 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
1239 p
= strchr(p
+ 1, ' ');
1242 p2
= strchr(p
+ 1, ' ');
1246 if (strcmp(p
+ 1, "/") == 0) {
1247 /* This is '/'. Is it the ramfs? */
1248 p
= strchr(p2
+ 1, '-');
1249 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
1261 char *on_path(const char *cmd
, const char *rootfs
) {
1264 char *saveptr
= NULL
;
1265 char cmdpath
[MAXPATHLEN
];
1268 path
= getenv("PATH");
1272 path
= strdup(path
);
1276 entry
= strtok_r(path
, ":", &saveptr
);
1279 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s/%s", rootfs
, entry
, cmd
);
1281 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s", entry
, cmd
);
1283 if (ret
< 0 || ret
>= MAXPATHLEN
)
1286 if (access(cmdpath
, X_OK
) == 0) {
1288 return strdup(cmdpath
);
1292 entry
= strtok_r(NULL
, ":", &saveptr
);
1299 bool file_exists(const char *f
)
1301 struct stat statbuf
;
1303 return stat(f
, &statbuf
) == 0;
1306 bool cgns_supported(void)
1308 return file_exists("/proc/self/ns/cgroup");
1311 /* historically lxc-init has been under /usr/lib/lxc and under
1312 * /usr/lib/$ARCH/lxc. It now lives as $prefix/sbin/init.lxc.
1314 char *choose_init(const char *rootfs
)
1317 const char *empty
= "",
1319 int ret
, env_set
= 0;
1321 if (!getenv("PATH")) {
1322 if (setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 0))
1323 SYSERROR("Failed to setenv");
1327 retv
= on_path("init.lxc", rootfs
);
1330 if (unsetenv("PATH"))
1331 SYSERROR("Failed to unsetenv");
1337 retv
= malloc(PATH_MAX
);
1346 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, SBINDIR
, "/init.lxc");
1347 if (ret
< 0 || ret
>= PATH_MAX
) {
1348 ERROR("pathname too long");
1351 if (access(retv
, X_OK
) == 0)
1354 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, LXCINITDIR
, "/lxc/lxc-init");
1355 if (ret
< 0 || ret
>= PATH_MAX
) {
1356 ERROR("pathname too long");
1359 if (access(retv
, X_OK
) == 0)
1362 ret
= snprintf(retv
, PATH_MAX
, "%s/usr/lib/lxc/lxc-init", tmp
);
1363 if (ret
< 0 || ret
>= PATH_MAX
) {
1364 ERROR("pathname too long");
1367 if (access(retv
, X_OK
) == 0)
1370 ret
= snprintf(retv
, PATH_MAX
, "%s/sbin/lxc-init", tmp
);
1371 if (ret
< 0 || ret
>= PATH_MAX
) {
1372 ERROR("pathname too long");
1375 if (access(retv
, X_OK
) == 0)
1379 * Last resort, look for the statically compiled init.lxc which we
1380 * hopefully bind-mounted in.
1381 * If we are called during container setup, and we get to this point,
1382 * then the init.lxc.static from the host will need to be bind-mounted
1383 * in. So we return NULL here to indicate that.
1388 ret
= snprintf(retv
, PATH_MAX
, "/init.lxc.static");
1389 if (ret
< 0 || ret
>= PATH_MAX
) {
1390 WARN("Nonsense - name /lxc.init.static too long");
1393 if (access(retv
, X_OK
) == 0)
1401 int print_to_file(const char *file
, const char *content
)
1406 f
= fopen(file
, "w");
1409 if (fprintf(f
, "%s", content
) != strlen(content
))
1415 int is_dir(const char *path
)
1417 struct stat statbuf
;
1418 int ret
= stat(path
, &statbuf
);
1419 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
1425 * Given the '-t' template option to lxc-create, figure out what to
1426 * do. If the template is a full executable path, use that. If it
1427 * is something like 'sshd', then return $templatepath/lxc-sshd.
1428 * On success return the template, on error return NULL.
1430 char *get_template_path(const char *t
)
1435 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
1440 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
1441 tpath
= malloc(len
);
1444 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
1445 if (ret
< 0 || ret
>= len
) {
1449 if (access(tpath
, X_OK
) < 0) {
1450 SYSERROR("bad template: %s", t
);
1459 * @path: a pathname where / replaced with '\0'.
1460 * @offsetp: pointer to int showing which path segment was last seen.
1461 * Updated on return to reflect the next segment.
1462 * @fulllen: full original path length.
1463 * Returns a pointer to the next path segment, or NULL if done.
1465 static char *get_nextpath(char *path
, int *offsetp
, int fulllen
)
1467 int offset
= *offsetp
;
1469 if (offset
>= fulllen
)
1472 while (path
[offset
] != '\0' && offset
< fulllen
)
1474 while (path
[offset
] == '\0' && offset
< fulllen
)
1478 return (offset
< fulllen
) ? &path
[offset
] : NULL
;
1482 * Check that @subdir is a subdir of @dir. @len is the length of
1483 * @dir (to avoid having to recalculate it).
1485 static bool is_subdir(const char *subdir
, const char *dir
, size_t len
)
1487 size_t subdirlen
= strlen(subdir
);
1489 if (subdirlen
< len
)
1491 if (strncmp(subdir
, dir
, len
) != 0)
1493 if (dir
[len
-1] == '/')
1495 if (subdir
[len
] == '/' || subdirlen
== len
)
1501 * Check if the open fd is a symlink. Return -ELOOP if it is. Return
1502 * -ENOENT if we couldn't fstat. Return 0 if the fd is ok.
1504 static int check_symlink(int fd
)
1507 int ret
= fstat(fd
, &sb
);
1510 if (S_ISLNK(sb
.st_mode
))
1516 * Open a file or directory, provided that it contains no symlinks.
1518 * CAVEAT: This function must not be used for other purposes than container
1519 * setup before executing the container's init
1521 static int open_if_safe(int dirfd
, const char *nextpath
)
1523 int newfd
= openat(dirfd
, nextpath
, O_RDONLY
| O_NOFOLLOW
);
1524 if (newfd
>= 0) /* Was not a symlink, all good. */
1530 if (errno
== EPERM
|| errno
== EACCES
) {
1531 /* We're not root (cause we got EPERM) so try opening with
1534 newfd
= openat(dirfd
, nextpath
, O_PATH
| O_NOFOLLOW
);
1536 /* O_PATH will return an fd for symlinks. We know
1537 * nextpath wasn't a symlink at last openat, so if fd is
1538 * now a link, then something * fishy is going on.
1540 int ret
= check_symlink(newfd
);
1552 * Open a path intending for mounting, ensuring that the final path
1553 * is inside the container's rootfs.
1555 * CAVEAT: This function must not be used for other purposes than container
1556 * setup before executing the container's init
1558 * @target: path to be opened
1559 * @prefix_skip: a part of @target in which to ignore symbolic links. This
1560 * would be the container's rootfs.
1562 * Return an open fd for the path, or <0 on error.
1564 static int open_without_symlink(const char *target
, const char *prefix_skip
)
1566 int curlen
= 0, dirfd
, fulllen
, i
;
1569 fulllen
= strlen(target
);
1571 /* make sure prefix-skip makes sense */
1572 if (prefix_skip
&& strlen(prefix_skip
) > 0) {
1573 curlen
= strlen(prefix_skip
);
1574 if (!is_subdir(target
, prefix_skip
, curlen
)) {
1575 ERROR("WHOA there - target '%s' didn't start with prefix '%s'",
1576 target
, prefix_skip
);
1580 * get_nextpath() expects the curlen argument to be
1581 * on a (turned into \0) / or before it, so decrement
1582 * curlen to make sure that happens
1591 /* Make a copy of target which we can hack up, and tokenize it */
1592 if ((dup
= strdup(target
)) == NULL
) {
1593 SYSERROR("Out of memory checking for symbolic link");
1596 for (i
= 0; i
< fulllen
; i
++) {
1601 dirfd
= open(prefix_skip
, O_RDONLY
);
1605 int newfd
, saved_errno
;
1608 if ((nextpath
= get_nextpath(dup
, &curlen
, fulllen
)) == NULL
)
1610 newfd
= open_if_safe(dirfd
, nextpath
);
1611 saved_errno
= errno
;
1615 errno
= saved_errno
;
1617 SYSERROR("%s in %s was a symbolic link!", nextpath
, target
);
1628 * Safely mount a path into a container, ensuring that the mount target
1629 * is under the container's @rootfs. (If @rootfs is NULL, then the container
1630 * uses the host's /)
1632 * CAVEAT: This function must not be used for other purposes than container
1633 * setup before executing the container's init
1635 int safe_mount(const char *src
, const char *dest
, const char *fstype
,
1636 unsigned long flags
, const void *data
, const char *rootfs
)
1638 int destfd
, ret
, saved_errno
;
1639 /* Only needs enough for /proc/self/fd/<fd>. */
1640 char srcbuf
[50], destbuf
[50];
1642 const char *mntsrc
= src
;
1647 /* todo - allow symlinks for relative paths if 'allowsymlinks' option is passed */
1648 if (flags
& MS_BIND
&& src
&& src
[0] != '/') {
1649 INFO("this is a relative bind mount");
1650 srcfd
= open_without_symlink(src
, NULL
);
1653 ret
= snprintf(srcbuf
, 50, "/proc/self/fd/%d", srcfd
);
1654 if (ret
< 0 || ret
> 50) {
1656 ERROR("Out of memory");
1662 destfd
= open_without_symlink(dest
, rootfs
);
1665 saved_errno
= errno
;
1667 errno
= saved_errno
;
1672 ret
= snprintf(destbuf
, 50, "/proc/self/fd/%d", destfd
);
1673 if (ret
< 0 || ret
> 50) {
1677 ERROR("Out of memory");
1681 ret
= mount(mntsrc
, destbuf
, fstype
, flags
, data
);
1682 saved_errno
= errno
;
1687 errno
= saved_errno
;
1688 SYSERROR("Failed to mount %s onto %s", src
? src
: "(null)", dest
);
1696 * Mount a proc under @rootfs if proc self points to a pid other than
1697 * my own. This is needed to have a known-good proc mount for setting
1698 * up LSMs both at container startup and attach.
1700 * @rootfs : the rootfs where proc should be mounted
1702 * Returns < 0 on failure, 0 if the correct proc was already mounted
1703 * and 1 if a new proc was mounted.
1705 * NOTE: not to be called from inside the container namespace!
1707 int lxc_mount_proc_if_needed(const char *rootfs
)
1709 char path
[MAXPATHLEN
];
1710 int link_to_pid
, linklen
, mypid
, ret
;
1711 char link
[LXC_NUMSTRLEN64
] = {0};
1713 ret
= snprintf(path
, MAXPATHLEN
, "%s/proc/self", rootfs
);
1714 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1715 SYSERROR("proc path name too long");
1719 linklen
= readlink(path
, link
, LXC_NUMSTRLEN64
);
1721 ret
= snprintf(path
, MAXPATHLEN
, "%s/proc", rootfs
);
1722 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1723 SYSERROR("proc path name too long");
1727 /* /proc not mounted */
1729 if (mkdir(path
, 0755) && errno
!= EEXIST
)
1732 } else if (linklen
>= LXC_NUMSTRLEN64
) {
1733 link
[linklen
- 1] = '\0';
1734 ERROR("readlink returned truncated content: \"%s\"", link
);
1738 mypid
= lxc_raw_getpid();
1739 INFO("I am %d, /proc/self points to \"%s\"", mypid
, link
);
1741 if (lxc_safe_int(link
, &link_to_pid
) < 0)
1744 /* correct procfs is already mounted */
1745 if (link_to_pid
== mypid
)
1748 ret
= umount2(path
, MNT_DETACH
);
1750 WARN("failed to umount \"%s\" with MNT_DETACH", path
);
1753 /* rootfs is NULL */
1754 if (!strcmp(rootfs
, ""))
1755 ret
= mount("proc", path
, "proc", 0, NULL
);
1757 ret
= safe_mount("proc", path
, "proc", 0, NULL
, rootfs
);
1761 INFO("mounted /proc in container for security transition");
1765 int open_devnull(void)
1767 int fd
= open("/dev/null", O_RDWR
);
1770 SYSERROR("Can't open /dev/null");
1775 int set_stdfds(int fd
)
1782 ret
= dup2(fd
, STDIN_FILENO
);
1786 ret
= dup2(fd
, STDOUT_FILENO
);
1790 ret
= dup2(fd
, STDERR_FILENO
);
1797 int null_stdfds(void)
1800 int fd
= open_devnull();
1803 ret
= set_stdfds(fd
);
1811 * Return the number of lines in file @fn, or -1 on error
1813 int lxc_count_file_lines(const char *fn
)
1820 f
= fopen_cloexec(fn
, "r");
1824 while (getline(&line
, &sz
, f
) != -1) {
1832 /* Check whether a signal is blocked by a process. */
1833 /* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
1834 #define __PROC_STATUS_LEN (6 + (LXC_NUMSTRLEN64) + 7 + 1)
1835 bool task_blocks_signal(pid_t pid
, int signal
)
1838 char status
[__PROC_STATUS_LEN
];
1840 uint64_t sigblk
= 0, one
= 1;
1845 ret
= snprintf(status
, __PROC_STATUS_LEN
, "/proc/%d/status", pid
);
1846 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
1849 f
= fopen(status
, "r");
1853 while (getline(&line
, &n
, f
) != -1) {
1856 if (strncmp(line
, "SigBlk:", 7))
1859 numstr
= lxc_trim_whitespace_in_place(line
+ 7);
1860 ret
= lxc_safe_uint64(numstr
, &sigblk
, 16);
1867 if (sigblk
& (one
<< (signal
- 1)))
1876 static int lxc_append_null_to_list(void ***list
)
1882 for (; (*list
)[newentry
]; newentry
++) {
1886 tmp
= realloc(*list
, (newentry
+ 2) * sizeof(void **));
1891 (*list
)[newentry
+ 1] = NULL
;
1896 int lxc_append_string(char ***list
, char *entry
)
1901 newentry
= lxc_append_null_to_list((void ***)list
);
1905 copy
= strdup(entry
);
1909 (*list
)[newentry
] = copy
;
1914 int lxc_preserve_ns(const int pid
, const char *ns
)
1917 /* 5 /proc + 21 /int_as_str + 3 /ns + 20 /NS_NAME + 1 \0 */
1918 #define __NS_PATH_LEN 50
1919 char path
[__NS_PATH_LEN
];
1921 /* This way we can use this function to also check whether namespaces
1922 * are supported by the kernel by passing in the NULL or the empty
1925 ret
= snprintf(path
, __NS_PATH_LEN
, "/proc/%d/ns%s%s", pid
,
1926 !ns
|| strcmp(ns
, "") == 0 ? "" : "/",
1927 !ns
|| strcmp(ns
, "") == 0 ? "" : ns
);
1929 if (ret
< 0 || (size_t)ret
>= __NS_PATH_LEN
)
1932 return open(path
, O_RDONLY
| O_CLOEXEC
);
1935 int lxc_safe_uint(const char *numstr
, unsigned int *converted
)
1938 unsigned long int uli
;
1940 while (isspace(*numstr
))
1947 uli
= strtoul(numstr
, &err
, 0);
1948 if (errno
== ERANGE
&& uli
== ULONG_MAX
)
1951 if (err
== numstr
|| *err
!= '\0')
1957 *converted
= (unsigned int)uli
;
1961 int lxc_safe_ulong(const char *numstr
, unsigned long *converted
)
1964 unsigned long int uli
;
1966 while (isspace(*numstr
))
1973 uli
= strtoul(numstr
, &err
, 0);
1974 if (errno
== ERANGE
&& uli
== ULONG_MAX
)
1977 if (err
== numstr
|| *err
!= '\0')
1984 int lxc_safe_uint64(const char *numstr
, uint64_t *converted
, int base
)
1989 while (isspace(*numstr
))
1996 u
= strtoull(numstr
, &err
, base
);
1997 if (errno
== ERANGE
&& u
== ULLONG_MAX
)
2000 if (err
== numstr
|| *err
!= '\0')
2007 int lxc_safe_int(const char *numstr
, int *converted
)
2010 signed long int sli
;
2013 sli
= strtol(numstr
, &err
, 0);
2014 if (errno
== ERANGE
&& (sli
== LONG_MAX
|| sli
== LONG_MIN
))
2017 if (errno
!= 0 && sli
== 0)
2020 if (err
== numstr
|| *err
!= '\0')
2023 if (sli
> INT_MAX
|| sli
< INT_MIN
)
2026 *converted
= (int)sli
;
2030 int lxc_safe_long(const char *numstr
, long int *converted
)
2033 signed long int sli
;
2036 sli
= strtol(numstr
, &err
, 0);
2037 if (errno
== ERANGE
&& (sli
== LONG_MAX
|| sli
== LONG_MIN
))
2040 if (errno
!= 0 && sli
== 0)
2043 if (err
== numstr
|| *err
!= '\0')
2050 int lxc_safe_long_long(const char *numstr
, long long int *converted
)
2053 signed long long int sli
;
2056 sli
= strtoll(numstr
, &err
, 0);
2057 if (errno
== ERANGE
&& (sli
== LLONG_MAX
|| sli
== LLONG_MIN
))
2060 if (errno
!= 0 && sli
== 0)
2063 if (err
== numstr
|| *err
!= '\0')
2070 int lxc_switch_uid_gid(uid_t uid
, gid_t gid
)
2072 if (setgid(gid
) < 0) {
2073 SYSERROR("Failed to switch to gid %d.", gid
);
2076 NOTICE("Switched to gid %d.", gid
);
2078 if (setuid(uid
) < 0) {
2079 SYSERROR("Failed to switch to uid %d.", uid
);
2082 NOTICE("Switched to uid %d.", uid
);
2087 /* Simple covenience function which enables uniform logging. */
2088 int lxc_setgroups(int size
, gid_t list
[])
2090 if (setgroups(size
, list
) < 0) {
2091 SYSERROR("Failed to setgroups().");
2094 NOTICE("Dropped additional groups.");
2099 static int lxc_get_unused_loop_dev_legacy(char *loop_name
)
2102 struct loop_info64 lo64
;
2104 int dfd
= -1, fd
= -1, ret
= -1;
2106 dir
= opendir("/dev");
2110 while ((dp
= readdir(dir
))) {
2111 if (strncmp(dp
->d_name
, "loop", 4) != 0)
2118 fd
= openat(dfd
, dp
->d_name
, O_RDWR
);
2122 ret
= ioctl(fd
, LOOP_GET_STATUS64
, &lo64
);
2124 if (ioctl(fd
, LOOP_GET_STATUS64
, &lo64
) == 0 ||
2132 ret
= snprintf(loop_name
, LO_NAME_SIZE
, "/dev/%s", dp
->d_name
);
2133 if (ret
< 0 || ret
>= LO_NAME_SIZE
) {
2150 static int lxc_get_unused_loop_dev(char *name_loop
)
2153 int fd_ctl
= -1, fd_tmp
= -1;
2155 fd_ctl
= open("/dev/loop-control", O_RDWR
| O_CLOEXEC
);
2159 loop_nr
= ioctl(fd_ctl
, LOOP_CTL_GET_FREE
);
2163 ret
= snprintf(name_loop
, LO_NAME_SIZE
, "/dev/loop%d", loop_nr
);
2164 if (ret
< 0 || ret
>= LO_NAME_SIZE
)
2167 fd_tmp
= open(name_loop
, O_RDWR
| O_CLOEXEC
);
2176 int lxc_prepare_loop_dev(const char *source
, char *loop_dev
, int flags
)
2179 struct loop_info64 lo64
;
2180 int fd_img
= -1, fret
= -1, fd_loop
= -1;
2182 fd_loop
= lxc_get_unused_loop_dev(loop_dev
);
2184 if (fd_loop
== -ENODEV
)
2185 fd_loop
= lxc_get_unused_loop_dev_legacy(loop_dev
);
2190 fd_img
= open(source
, O_RDWR
| O_CLOEXEC
);
2194 ret
= ioctl(fd_loop
, LOOP_SET_FD
, fd_img
);
2198 memset(&lo64
, 0, sizeof(lo64
));
2199 lo64
.lo_flags
= flags
;
2201 ret
= ioctl(fd_loop
, LOOP_SET_STATUS64
, &lo64
);
2211 if (fret
< 0 && fd_loop
>= 0) {
2219 int lxc_unstack_mountpoint(const char *path
, bool lazy
)
2225 ret
= umount2(path
, lazy
? MNT_DETACH
: 0);
2227 /* We consider anything else than EINVAL deadly to prevent going
2228 * into an infinite loop. (The other alternative is constantly
2229 * parsing /proc/self/mountinfo which is yucky and probably
2232 if (errno
!= EINVAL
)
2235 /* Just stop counting when this happens. That'd just be so
2236 * stupid that we won't even bother trying to report back the
2237 * correct value anymore.
2239 if (umounts
!= INT_MAX
)
2241 /* We succeeded in umounting. Make sure that there's no other
2242 * mountpoint stacked underneath.
2250 int run_command(char *buf
, size_t buf_size
, int (*child_fn
)(void *), void *args
)
2253 int ret
, fret
, pipefd
[2];
2256 /* Make sure our callers do not receive uninitialized memory. */
2257 if (buf_size
> 0 && buf
)
2260 if (pipe(pipefd
) < 0) {
2261 SYSERROR("failed to create pipe");
2265 child
= lxc_raw_clone(0);
2269 SYSERROR("failed to create new process");
2274 /* Close the read-end of the pipe. */
2277 /* Redirect std{err,out} to write-end of the
2280 ret
= dup2(pipefd
[1], STDOUT_FILENO
);
2282 ret
= dup2(pipefd
[1], STDERR_FILENO
);
2284 /* Close the write-end of the pipe. */
2288 SYSERROR("failed to duplicate std{err,out} file descriptor");
2289 _exit(EXIT_FAILURE
);
2292 /* Does not return. */
2294 ERROR("failed to exec command");
2295 _exit(EXIT_FAILURE
);
2298 /* close the write-end of the pipe */
2301 if (buf
&& buf_size
> 0) {
2302 bytes
= read(pipefd
[0], buf
, buf_size
- 1);
2304 buf
[bytes
- 1] = '\0';
2307 fret
= wait_for_pid(child
);
2308 /* close the read-end of the pipe */
2314 char *must_make_path(const char *first
, ...)
2318 size_t full_len
= strlen(first
);
2321 dest
= must_copy_string(first
);
2323 va_start(args
, first
);
2324 while ((cur
= va_arg(args
, char *)) != NULL
) {
2325 full_len
+= strlen(cur
);
2329 buf_len
= full_len
+ 1;
2330 dest
= must_realloc(dest
, buf_len
);
2333 (void)strlcat(dest
, "/", buf_len
);
2334 (void)strlcat(dest
, cur
, buf_len
);
2341 char *must_append_path(char *first
, ...)
2349 full_len
= strlen(first
);
2350 va_start(args
, first
);
2351 while ((cur
= va_arg(args
, char *)) != NULL
) {
2352 full_len
+= strlen(cur
);
2356 buf_len
= full_len
+ 1;
2357 dest
= must_realloc(dest
, buf_len
);
2360 (void)strlcat(dest
, "/", buf_len
);
2361 (void)strlcat(dest
, cur
, buf_len
);
2368 char *must_copy_string(const char *entry
)
2375 ret
= strdup(entry
);
2381 void *must_realloc(void *orig
, size_t sz
)
2386 ret
= realloc(orig
, sz
);
2392 bool is_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
2394 return (fs
->f_type
== (fs_type_magic
)magic_val
);
2397 bool has_fs_type(const char *path
, fs_type_magic magic_val
)
2403 ret
= statfs(path
, &sb
);
2407 has_type
= is_fs_type(&sb
, magic_val
);
2408 if (!has_type
&& magic_val
== RAMFS_MAGIC
)
2409 WARN("When the ramfs it a tmpfs statfs() might report tmpfs");
2414 bool lxc_nic_exists(char *nic
)
2416 #define __LXC_SYS_CLASS_NET_LEN 15 + IFNAMSIZ + 1
2417 char path
[__LXC_SYS_CLASS_NET_LEN
];
2421 if (!strcmp(nic
, "none"))
2424 ret
= snprintf(path
, __LXC_SYS_CLASS_NET_LEN
, "/sys/class/net/%s", nic
);
2425 if (ret
< 0 || (size_t)ret
>= __LXC_SYS_CLASS_NET_LEN
)
2428 ret
= stat(path
, &sb
);
2435 int lxc_make_tmpfile(char *template, bool rm
)
2441 fd
= mkstemp(template);
2449 ret
= unlink(template);
2458 int parse_byte_size_string(const char *s
, int64_t *converted
)
2460 int ret
, suffix_len
;
2462 int64_t mltpl
, overflow
;
2464 char dup
[LXC_NUMSTRLEN64
+ 2];
2465 char suffix
[3] = {0};
2467 if (!s
|| !strcmp(s
, ""))
2470 end
= stpncpy(dup
, s
, sizeof(dup
) - 1);
2474 if (isdigit(*(end
- 1)))
2476 else if (isalpha(*(end
- 1)))
2481 if (suffix_len
> 0 && (end
- 2) == dup
&& !isdigit(*(end
- 2)))
2484 if (suffix_len
> 0 && isalpha(*(end
- 2)))
2487 if (suffix_len
> 0) {
2488 memcpy(suffix
, end
- suffix_len
, suffix_len
);
2489 *(suffix
+ suffix_len
) = '\0';
2490 *(end
- suffix_len
) = '\0';
2492 dup
[lxc_char_right_gc(dup
, strlen(dup
))] = '\0';
2494 ret
= lxc_safe_long_long(dup
, &conv
);
2498 if (suffix_len
!= 2) {
2503 if (strcasecmp(suffix
, "KB") == 0)
2505 else if (strcasecmp(suffix
, "MB") == 0)
2506 mltpl
= 1024 * 1024;
2507 else if (strcasecmp(suffix
, "GB") == 0)
2508 mltpl
= 1024 * 1024 * 1024;
2512 overflow
= conv
* mltpl
;
2513 if (conv
!= 0 && (overflow
/ conv
) != mltpl
)
2516 *converted
= overflow
;
2520 uint64_t lxc_find_next_power2(uint64_t n
)
2522 /* 0 is not valid input. We return 0 to the caller since 0 is not a
2523 * valid power of two.
2538 int lxc_set_death_signal(int signal
)
2543 ret
= prctl(PR_SET_PDEATHSIG
, signal
, 0, 0, 0);
2545 /* Check whether we have been orphaned. */
2546 ppid
= (pid_t
)syscall(SYS_getppid
);
2550 self
= lxc_raw_getpid();
2551 ret
= kill(self
, SIGKILL
);
2557 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d", signal
);
2564 void remove_trailing_newlines(char *l
)
2571 while (--p
>= l
&& *p
== '\n')