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. */
40 #include <sys/mount.h>
41 #include <sys/param.h>
42 #include <sys/prctl.h>
44 #include <sys/types.h>
49 #include "namespace.h"
54 #define O_PATH 010000000
58 #define O_NOFOLLOW 00400000
61 lxc_log_define(lxc_utils
, lxc
);
64 * if path is btrfs, tries to remove it and any subvolumes beneath it
66 extern bool btrfs_try_remove_subvol(const char *path
);
68 static int _recursive_rmdir(const char *dirname
, dev_t pdev
,
69 const char *exclude
, int level
, bool onedev
)
71 struct dirent
*direntp
;
74 char pathname
[MAXPATHLEN
];
75 bool hadexclude
= false;
77 dir
= opendir(dirname
);
79 ERROR("failed to open %s", dirname
);
83 while ((direntp
= readdir(dir
))) {
90 if (!strcmp(direntp
->d_name
, ".") ||
91 !strcmp(direntp
->d_name
, ".."))
94 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
95 if (rc
< 0 || rc
>= MAXPATHLEN
) {
96 ERROR("pathname too long");
101 if (!level
&& exclude
&& !strcmp(direntp
->d_name
, exclude
)) {
102 ret
= rmdir(pathname
);
106 INFO("Not deleting snapshot %s", pathname
);
110 ret
= unlink(pathname
);
112 INFO("Failed to remove %s", pathname
);
115 SYSERROR("Failed to rmdir %s", pathname
);
123 ret
= lstat(pathname
, &mystat
);
125 ERROR("Failed to stat %s", pathname
);
129 if (onedev
&& mystat
.st_dev
!= pdev
) {
130 /* TODO should we be checking /proc/self/mountinfo for
131 * pathname and not doing this if found? */
132 if (btrfs_try_remove_subvol(pathname
))
133 INFO("Removed btrfs subvolume at %s\n", pathname
);
136 if (S_ISDIR(mystat
.st_mode
)) {
137 if (_recursive_rmdir(pathname
, pdev
, exclude
, level
+1, onedev
) < 0)
140 if (unlink(pathname
) < 0) {
141 SYSERROR("Failed to delete %s", pathname
);
147 if (rmdir(dirname
) < 0 && !btrfs_try_remove_subvol(dirname
) && !hadexclude
) {
148 ERROR("Failed to delete %s", dirname
);
154 ERROR("Failed to close directory %s", dirname
);
158 return failed
? -1 : 0;
161 /* We have two different magic values for overlayfs, yay. */
162 #ifndef OVERLAYFS_SUPER_MAGIC
163 #define OVERLAYFS_SUPER_MAGIC 0x794c764f
166 #ifndef OVERLAY_SUPER_MAGIC
167 #define OVERLAY_SUPER_MAGIC 0x794c7630
170 /* In overlayfs, st_dev is unreliable. So on overlayfs we don't do the
173 static bool is_native_overlayfs(const char *path
)
175 if (has_fs_type(path
, OVERLAY_SUPER_MAGIC
) ||
176 has_fs_type(path
, OVERLAYFS_SUPER_MAGIC
))
182 /* returns 0 on success, -1 if there were any failures */
183 extern int lxc_rmdir_onedev(const char *path
, const char *exclude
)
188 if (is_native_overlayfs(path
))
191 if (lstat(path
, &mystat
) < 0) {
195 ERROR("Failed to stat %s", path
);
199 return _recursive_rmdir(path
, mystat
.st_dev
, exclude
, 0, onedev
);
202 /* borrowed from iproute2 */
203 extern int get_u16(unsigned short *val
, const char *arg
, int base
)
212 res
= strtoul(arg
, &ptr
, base
);
213 if (!ptr
|| ptr
== arg
|| *ptr
|| res
> 0xFFFF || errno
!= 0)
221 extern int mkdir_p(const char *dir
, mode_t mode
)
223 const char *tmp
= dir
;
224 const char *orig
= dir
;
228 dir
= tmp
+ strspn(tmp
, "/");
229 tmp
= dir
+ strcspn(dir
, "/");
230 makeme
= strndup(orig
, dir
- orig
);
232 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
233 SYSERROR("failed to create directory '%s'", makeme
);
250 if (stat(RUNTIME_PATH
, &sb
) < 0) {
254 if (geteuid() == sb
.st_uid
|| getegid() == sb
.st_gid
) {
255 rundir
= strdup(RUNTIME_PATH
);
259 rundir
= getenv("XDG_RUNTIME_DIR");
261 rundir
= strdup(rundir
);
265 INFO("XDG_RUNTIME_DIR isn't set in the environment.");
266 homedir
= getenv("HOME");
268 ERROR("HOME isn't set in the environment.");
272 rundir
= malloc(sizeof(char) * (17 + strlen(homedir
)));
273 sprintf(rundir
, "%s/.cache/lxc/run/", homedir
);
278 int wait_for_pid(pid_t pid
)
283 ret
= waitpid(pid
, &status
, 0);
291 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
296 int lxc_wait_for_pid_status(pid_t pid
)
301 ret
= waitpid(pid
, &status
, 0);
312 ssize_t
lxc_write_nointr(int fd
, const void* buf
, size_t count
)
316 ret
= write(fd
, buf
, count
);
317 if (ret
< 0 && errno
== EINTR
)
322 ssize_t
lxc_read_nointr(int fd
, void* buf
, size_t count
)
326 ret
= read(fd
, buf
, count
);
327 if (ret
< 0 && errno
== EINTR
)
332 ssize_t
lxc_read_nointr_expect(int fd
, void* buf
, size_t count
, const void* expected_buf
)
335 ret
= lxc_read_nointr(fd
, buf
, count
);
338 if ((size_t)ret
!= count
)
340 if (expected_buf
&& memcmp(buf
, expected_buf
, count
) != 0) {
348 #include <gnutls/gnutls.h>
349 #include <gnutls/crypto.h>
351 __attribute__((constructor
))
352 static void gnutls_lxc_init(void)
354 gnutls_global_init();
357 int sha1sum_file(char *fnam
, unsigned char *digest
)
366 f
= fopen_cloexec(fnam
, "r");
368 SYSERROR("Error opening template");
371 if (fseek(f
, 0, SEEK_END
) < 0) {
372 SYSERROR("Error seeking to end of template");
376 if ((flen
= ftell(f
)) < 0) {
377 SYSERROR("Error telling size of template");
381 if (fseek(f
, 0, SEEK_SET
) < 0) {
382 SYSERROR("Error seeking to start of template");
386 if ((buf
= malloc(flen
+1)) == NULL
) {
387 SYSERROR("Out of memory");
391 if (fread(buf
, 1, flen
, f
) != flen
) {
392 SYSERROR("Failure reading template");
398 SYSERROR("Failre closing template");
403 ret
= gnutls_hash_fast(GNUTLS_DIG_SHA1
, buf
, flen
, (void *)digest
);
409 char** lxc_va_arg_list_to_argv(va_list ap
, size_t skip
, int do_strdup
)
412 size_t count
= 1 + skip
;
415 /* first determine size of argument list, we don't want to reallocate
420 char* arg
= va_arg(ap2
, char*);
427 result
= calloc(count
, sizeof(char*));
432 char* arg
= va_arg(ap
, char*);
435 arg
= do_strdup
? strdup(arg
) : arg
;
438 result
[count
++] = arg
;
441 /* calloc has already set last element to NULL*/
449 const char** lxc_va_arg_list_to_argv_const(va_list ap
, size_t skip
)
451 return (const char**)lxc_va_arg_list_to_argv(ap
, skip
, 0);
454 struct lxc_popen_FILE
*lxc_popen(const char *command
)
459 struct lxc_popen_FILE
*fp
= NULL
;
461 ret
= pipe2(pipe_fds
, O_CLOEXEC
);
474 /* duplicate stdout */
475 if (pipe_fds
[1] != STDOUT_FILENO
)
476 ret
= dup2(pipe_fds
[1], STDOUT_FILENO
);
478 ret
= fcntl(pipe_fds
[1], F_SETFD
, 0);
484 /* duplicate stderr */
485 if (pipe_fds
[1] != STDERR_FILENO
)
486 ret
= dup2(pipe_fds
[1], STDERR_FILENO
);
488 ret
= fcntl(pipe_fds
[1], F_SETFD
, 0);
493 /* unblock all signals */
494 ret
= sigfillset(&mask
);
498 ret
= sigprocmask(SIG_UNBLOCK
, &mask
, NULL
);
502 execl("/bin/sh", "sh", "-c", command
, (char *)NULL
);
509 fp
= malloc(sizeof(*fp
));
512 memset(fp
, 0, sizeof(*fp
));
514 fp
->child_pid
= child_pid
;
515 fp
->pipe
= pipe_fds
[0];
517 /* From now on, closing fp->f will also close fp->pipe. So only ever
518 * call fclose(fp->f).
520 fp
->f
= fdopen(pipe_fds
[0], "r");
527 /* We can only close pipe_fds[0] if fdopen() didn't succeed or wasn't
528 * called yet. Otherwise the fd belongs to the file opened by fdopen()
529 * since it isn't dup()ed.
531 if (fp
&& !fp
->f
&& pipe_fds
[0] >= 0)
534 if (pipe_fds
[1] >= 0)
546 int lxc_pclose(struct lxc_popen_FILE
*fp
)
555 wait_pid
= waitpid(fp
->child_pid
, &wstatus
, 0);
556 } while (wait_pid
< 0 && errno
== EINTR
);
567 char *lxc_string_replace(const char *needle
, const char *replacement
, const char *haystack
)
569 ssize_t len
= -1, saved_len
= -1;
571 size_t replacement_len
= strlen(replacement
);
572 size_t needle_len
= strlen(needle
);
574 /* should be executed exactly twice */
575 while (len
== -1 || result
== NULL
) {
581 result
= calloc(1, len
+ 1);
589 for (last_p
= (char *)haystack
, p
= strstr(last_p
, needle
); p
; last_p
= p
, p
= strstr(last_p
, needle
)) {
590 part_len
= (ssize_t
)(p
- last_p
);
591 if (result
&& part_len
> 0)
592 memcpy(&result
[len
], last_p
, part_len
);
594 if (result
&& replacement_len
> 0)
595 memcpy(&result
[len
], replacement
, replacement_len
);
596 len
+= replacement_len
;
599 part_len
= strlen(last_p
);
600 if (result
&& part_len
> 0)
601 memcpy(&result
[len
], last_p
, part_len
);
605 /* make sure we did the same thing twice,
606 * once for calculating length, the other
607 * time for copying data */
608 if (saved_len
!= len
) {
612 /* make sure we didn't overwrite any buffer,
613 * due to calloc the string should be 0-terminated */
614 if (result
[len
] != '\0') {
622 bool lxc_string_in_array(const char *needle
, const char **haystack
)
624 for (; haystack
&& *haystack
; haystack
++)
625 if (!strcmp(needle
, *haystack
))
630 char *lxc_string_join(const char *sep
, const char **parts
, bool use_as_prefix
)
634 size_t sep_len
= strlen(sep
);
635 size_t result_len
= use_as_prefix
* sep_len
;
637 /* calculate new string length */
638 for (p
= (char **)parts
; *p
; p
++)
639 result_len
+= (p
> (char **)parts
) * sep_len
+ strlen(*p
);
641 result
= calloc(result_len
+ 1, 1);
647 for (p
= (char **)parts
; *p
; p
++) {
648 if (p
> (char **)parts
)
656 char **lxc_normalize_path(const char *path
)
660 size_t components_len
= 0;
663 components
= lxc_string_split(path
, '/');
666 for (p
= components
; *p
; p
++)
669 /* resolve '.' and '..' */
670 for (pos
= 0; pos
< components_len
; ) {
671 if (!strcmp(components
[pos
], ".") || (!strcmp(components
[pos
], "..") && pos
== 0)) {
672 /* eat this element */
673 free(components
[pos
]);
674 memmove(&components
[pos
], &components
[pos
+1], sizeof(char *) * (components_len
- pos
));
676 } else if (!strcmp(components
[pos
], "..")) {
677 /* eat this and the previous element */
678 free(components
[pos
- 1]);
679 free(components
[pos
]);
680 memmove(&components
[pos
-1], &components
[pos
+1], sizeof(char *) * (components_len
- pos
));
691 char *lxc_deslashify(const char *path
)
701 parts
= lxc_normalize_path(dup
);
707 /* We'll end up here if path == "///" or path == "". */
711 lxc_free_array((void **)parts
, free
);
714 n
= strcspn(dup
, "/");
717 lxc_free_array((void **)parts
, free
);
727 p
= lxc_string_join("/", (const char **)parts
, *dup
== '/');
729 lxc_free_array((void **)parts
, free
);
733 char *lxc_append_paths(const char *first
, const char *second
)
738 const char *pattern
= "%s%s";
740 len
= strlen(first
) + strlen(second
) + 1;
741 if (second
[0] != '/') {
746 result
= calloc(1, len
);
750 ret
= snprintf(result
, len
, pattern
, first
, second
);
751 if (ret
< 0 || (size_t)ret
>= len
) {
759 bool lxc_string_in_list(const char *needle
, const char *haystack
, char _sep
)
761 char *token
, *str
, *saveptr
= NULL
;
762 char sep
[2] = { _sep
, '\0' };
764 if (!haystack
|| !needle
)
767 str
= alloca(strlen(haystack
)+1);
768 strcpy(str
, haystack
);
769 for (; (token
= strtok_r(str
, sep
, &saveptr
)); str
= NULL
) {
770 if (strcmp(needle
, token
) == 0)
777 char **lxc_string_split(const char *string
, char _sep
)
779 char *token
, *str
, *saveptr
= NULL
;
780 char sep
[2] = {_sep
, '\0'};
781 char **tmp
= NULL
, **result
= NULL
;
782 size_t result_capacity
= 0;
783 size_t result_count
= 0;
787 return calloc(1, sizeof(char *));
789 str
= alloca(strlen(string
) + 1);
791 for (; (token
= strtok_r(str
, sep
, &saveptr
)); str
= NULL
) {
792 r
= lxc_grow_array((void ***)&result
, &result_capacity
, result_count
+ 1, 16);
795 result
[result_count
] = strdup(token
);
796 if (!result
[result_count
])
801 /* if we allocated too much, reduce it */
802 tmp
= realloc(result
, (result_count
+ 1) * sizeof(char *));
806 /* Make sure we don't return uninitialized memory. */
807 if (result_count
== 0)
812 lxc_free_array((void **)result
, free
);
817 static bool complete_word(char ***result
, char *start
, char *end
, size_t *cap
, size_t *cnt
)
821 r
= lxc_grow_array((void ***)result
, cap
, 2 + *cnt
, 16);
824 (*result
)[*cnt
] = strndup(start
, end
- start
);
825 if (!(*result
)[*cnt
])
833 * Given a a string 'one two "three four"', split into three words,
834 * one, two, and "three four"
836 char **lxc_string_split_quoted(char *string
)
838 char *nextword
= string
, *p
, state
;
839 char **result
= NULL
;
840 size_t result_capacity
= 0;
841 size_t result_count
= 0;
843 if (!string
|| !*string
)
844 return calloc(1, sizeof(char *));
846 // TODO I'm *not* handling escaped quote
848 for (p
= string
; *p
; p
++) {
853 else if (*p
== '"' || *p
== '\'') {
863 complete_word(&result
, nextword
, p
, &result_capacity
, &result_count
);
871 complete_word(&result
, nextword
+1, p
, &result_capacity
, &result_count
);
880 complete_word(&result
, nextword
, p
, &result_capacity
, &result_count
);
882 return realloc(result
, (result_count
+ 1) * sizeof(char *));
885 char **lxc_string_split_and_trim(const char *string
, char _sep
)
887 char *token
, *str
, *saveptr
= NULL
;
888 char sep
[2] = { _sep
, '\0' };
889 char **result
= NULL
;
890 size_t result_capacity
= 0;
891 size_t result_count
= 0;
896 return calloc(1, sizeof(char *));
898 str
= alloca(strlen(string
)+1);
900 for (; (token
= strtok_r(str
, sep
, &saveptr
)); str
= NULL
) {
901 while (token
[0] == ' ' || token
[0] == '\t')
904 while (i
> 0 && (token
[i
- 1] == ' ' || token
[i
- 1] == '\t')) {
908 r
= lxc_grow_array((void ***)&result
, &result_capacity
, result_count
+ 1, 16);
911 result
[result_count
] = strdup(token
);
912 if (!result
[result_count
])
917 /* if we allocated too much, reduce it */
918 return realloc(result
, (result_count
+ 1) * sizeof(char *));
921 lxc_free_array((void **)result
, free
);
926 void lxc_free_array(void **array
, lxc_free_fn element_free_fn
)
929 for (p
= array
; p
&& *p
; p
++)
934 int lxc_grow_array(void ***array
, size_t* capacity
, size_t new_size
, size_t capacity_increment
)
939 /* first time around, catch some trivial mistakes of the user
940 * only initializing one of these */
941 if (!*array
|| !*capacity
) {
946 new_capacity
= *capacity
;
947 while (new_size
+ 1 > new_capacity
)
948 new_capacity
+= capacity_increment
;
949 if (new_capacity
!= *capacity
) {
950 /* we have to reallocate */
951 new_array
= realloc(*array
, new_capacity
* sizeof(void *));
954 memset(&new_array
[*capacity
], 0, (new_capacity
- (*capacity
)) * sizeof(void *));
956 *capacity
= new_capacity
;
959 /* array has sufficient elements */
963 size_t lxc_array_len(void **array
)
968 for (p
= array
; p
&& *p
; p
++)
974 int lxc_write_to_file(const char *filename
, const void* buf
, size_t count
, bool add_newline
)
979 fd
= open(filename
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_CLOEXEC
, 0666);
982 ret
= lxc_write_nointr(fd
, buf
, count
);
985 if ((size_t)ret
!= count
)
988 ret
= lxc_write_nointr(fd
, "\n", 1);
1002 int lxc_read_from_file(const char *filename
, void* buf
, size_t count
)
1004 int fd
= -1, saved_errno
;
1007 fd
= open(filename
, O_RDONLY
| O_CLOEXEC
);
1011 if (!buf
|| !count
) {
1014 while ((ret
= read(fd
, buf2
, 100)) > 0)
1019 memset(buf
, 0, count
);
1020 ret
= read(fd
, buf
, count
);
1024 ERROR("read %s: %s", filename
, strerror(errno
));
1026 saved_errno
= errno
;
1028 errno
= saved_errno
;
1032 void **lxc_append_null_to_array(void **array
, size_t count
)
1036 /* Append NULL to the array */
1038 temp
= realloc(array
, (count
+ 1) * sizeof(*array
));
1041 for (i
= 0; i
< count
; i
++)
1047 array
[count
] = NULL
;
1052 int randseed(bool srand_it
)
1055 srand pre-seed function based on /dev/urandom
1057 unsigned int seed
= time(NULL
) + getpid();
1060 f
= fopen("/dev/urandom", "r");
1062 int ret
= fread(&seed
, sizeof(seed
), 1, f
);
1064 DEBUG("unable to fread /dev/urandom, %s, fallback to time+pid rand seed", strerror(errno
));
1074 uid_t
get_ns_uid(uid_t orig
)
1078 uid_t nsid
, hostid
, range
;
1079 FILE *f
= fopen("/proc/self/uid_map", "r");
1083 while (getline(&line
, &sz
, f
) != -1) {
1084 if (sscanf(line
, "%u %u %u", &nsid
, &hostid
, &range
) != 3)
1086 if (hostid
<= orig
&& hostid
+ range
> orig
) {
1087 nsid
+= orig
- hostid
;
1099 bool dir_exists(const char *path
)
1104 ret
= stat(path
, &sb
);
1106 /* Could be something other than eexist, just say "no". */
1108 return S_ISDIR(sb
.st_mode
);
1111 /* Note we don't use SHA-1 here as we don't want to depend on HAVE_GNUTLS.
1112 * FNV has good anti collision properties and we're not worried
1113 * about pre-image resistance or one-way-ness, we're just trying to make
1114 * the name unique in the 108 bytes of space we have.
1116 uint64_t fnv_64a_buf(void *buf
, size_t len
, uint64_t hval
)
1120 for(bp
= buf
; bp
< (unsigned char *)buf
+ len
; bp
++)
1122 /* xor the bottom with the current octet */
1123 hval
^= (uint64_t)*bp
;
1126 * multiply by the 64 bit FNV magic prime mod 2^64
1128 hval
+= (hval
<< 1) + (hval
<< 4) + (hval
<< 5) +
1129 (hval
<< 7) + (hval
<< 8) + (hval
<< 40);
1136 * Detect whether / is mounted MS_SHARED. The only way I know of to
1137 * check that is through /proc/self/mountinfo.
1138 * I'm only checking for /. If the container rootfs or mount location
1139 * is MS_SHARED, but not '/', then you're out of luck - figuring that
1140 * out would be too much work to be worth it.
1142 int detect_shared_rootfs(void)
1144 char buf
[LXC_LINELEN
], *p
;
1149 f
= fopen("/proc/self/mountinfo", "r");
1152 while (fgets(buf
, LXC_LINELEN
, f
)) {
1153 for (p
= buf
, i
= 0; p
&& i
< 4; i
++)
1154 p
= strchr(p
+ 1, ' ');
1157 p2
= strchr(p
+ 1, ' ');
1161 if (strcmp(p
+ 1, "/") == 0) {
1162 /* This is '/'. Is it shared? */
1163 p
= strchr(p2
+ 1, ' ');
1164 if (p
&& strstr(p
, "shared:")) {
1174 bool switch_to_ns(pid_t pid
, const char *ns
) {
1176 char nspath
[MAXPATHLEN
];
1178 /* Switch to new ns */
1179 ret
= snprintf(nspath
, MAXPATHLEN
, "/proc/%d/ns/%s", pid
, ns
);
1180 if (ret
< 0 || ret
>= MAXPATHLEN
)
1183 fd
= open(nspath
, O_RDONLY
);
1185 SYSERROR("failed to open %s", nspath
);
1191 SYSERROR("failed to set process %d to %s of %d.", pid
, ns
, fd
);
1200 * looking at fs/proc_namespace.c, it appears we can
1201 * actually expect the rootfs entry to very specifically contain
1202 * " - rootfs rootfs "
1203 * IIUC, so long as we've chrooted so that rootfs is not our root,
1204 * the rootfs entry should always be skipped in mountinfo contents.
1206 bool detect_ramfs_rootfs(void)
1214 f
= fopen("/proc/self/mountinfo", "r");
1218 while (getline(&line
, &len
, f
) != -1) {
1219 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
1220 p
= strchr(p
+ 1, ' ');
1223 p2
= strchr(p
+ 1, ' ');
1227 if (strcmp(p
+ 1, "/") == 0) {
1228 /* This is '/'. Is it the ramfs? */
1229 p
= strchr(p2
+ 1, '-');
1230 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
1242 char *on_path(const char *cmd
, const char *rootfs
) {
1245 char *saveptr
= NULL
;
1246 char cmdpath
[MAXPATHLEN
];
1249 path
= getenv("PATH");
1253 path
= strdup(path
);
1257 entry
= strtok_r(path
, ":", &saveptr
);
1260 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s/%s", rootfs
, entry
, cmd
);
1262 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s", entry
, cmd
);
1264 if (ret
< 0 || ret
>= MAXPATHLEN
)
1267 if (access(cmdpath
, X_OK
) == 0) {
1269 return strdup(cmdpath
);
1273 entry
= strtok_r(NULL
, ":", &saveptr
);
1280 bool file_exists(const char *f
)
1282 struct stat statbuf
;
1284 return stat(f
, &statbuf
) == 0;
1287 bool cgns_supported(void)
1289 return file_exists("/proc/self/ns/cgroup");
1292 /* historically lxc-init has been under /usr/lib/lxc and under
1293 * /usr/lib/$ARCH/lxc. It now lives as $prefix/sbin/init.lxc.
1295 char *choose_init(const char *rootfs
)
1298 const char *empty
= "",
1300 int ret
, env_set
= 0;
1302 if (!getenv("PATH")) {
1303 if (setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 0))
1304 SYSERROR("Failed to setenv");
1308 retv
= on_path("init.lxc", rootfs
);
1311 if (unsetenv("PATH"))
1312 SYSERROR("Failed to unsetenv");
1318 retv
= malloc(PATH_MAX
);
1327 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, SBINDIR
, "/init.lxc");
1328 if (ret
< 0 || ret
>= PATH_MAX
) {
1329 ERROR("pathname too long");
1332 if (access(retv
, X_OK
) == 0)
1335 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, LXCINITDIR
, "/lxc/lxc-init");
1336 if (ret
< 0 || ret
>= PATH_MAX
) {
1337 ERROR("pathname too long");
1340 if (access(retv
, X_OK
) == 0)
1343 ret
= snprintf(retv
, PATH_MAX
, "%s/usr/lib/lxc/lxc-init", tmp
);
1344 if (ret
< 0 || ret
>= PATH_MAX
) {
1345 ERROR("pathname too long");
1348 if (access(retv
, X_OK
) == 0)
1351 ret
= snprintf(retv
, PATH_MAX
, "%s/sbin/lxc-init", tmp
);
1352 if (ret
< 0 || ret
>= PATH_MAX
) {
1353 ERROR("pathname too long");
1356 if (access(retv
, X_OK
) == 0)
1360 * Last resort, look for the statically compiled init.lxc which we
1361 * hopefully bind-mounted in.
1362 * If we are called during container setup, and we get to this point,
1363 * then the init.lxc.static from the host will need to be bind-mounted
1364 * in. So we return NULL here to indicate that.
1369 ret
= snprintf(retv
, PATH_MAX
, "/init.lxc.static");
1370 if (ret
< 0 || ret
>= PATH_MAX
) {
1371 WARN("Nonsense - name /lxc.init.static too long");
1374 if (access(retv
, X_OK
) == 0)
1382 int print_to_file(const char *file
, const char *content
)
1387 f
= fopen(file
, "w");
1390 if (fprintf(f
, "%s", content
) != strlen(content
))
1396 int is_dir(const char *path
)
1398 struct stat statbuf
;
1399 int ret
= stat(path
, &statbuf
);
1400 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
1406 * Given the '-t' template option to lxc-create, figure out what to
1407 * do. If the template is a full executable path, use that. If it
1408 * is something like 'sshd', then return $templatepath/lxc-sshd.
1409 * On success return the template, on error return NULL.
1411 char *get_template_path(const char *t
)
1416 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
1421 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
1422 tpath
= malloc(len
);
1425 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
1426 if (ret
< 0 || ret
>= len
) {
1430 if (access(tpath
, X_OK
) < 0) {
1431 SYSERROR("bad template: %s", t
);
1440 * @path: a pathname where / replaced with '\0'.
1441 * @offsetp: pointer to int showing which path segment was last seen.
1442 * Updated on return to reflect the next segment.
1443 * @fulllen: full original path length.
1444 * Returns a pointer to the next path segment, or NULL if done.
1446 static char *get_nextpath(char *path
, int *offsetp
, int fulllen
)
1448 int offset
= *offsetp
;
1450 if (offset
>= fulllen
)
1453 while (path
[offset
] != '\0' && offset
< fulllen
)
1455 while (path
[offset
] == '\0' && offset
< fulllen
)
1459 return (offset
< fulllen
) ? &path
[offset
] : NULL
;
1463 * Check that @subdir is a subdir of @dir. @len is the length of
1464 * @dir (to avoid having to recalculate it).
1466 static bool is_subdir(const char *subdir
, const char *dir
, size_t len
)
1468 size_t subdirlen
= strlen(subdir
);
1470 if (subdirlen
< len
)
1472 if (strncmp(subdir
, dir
, len
) != 0)
1474 if (dir
[len
-1] == '/')
1476 if (subdir
[len
] == '/' || subdirlen
== len
)
1482 * Check if the open fd is a symlink. Return -ELOOP if it is. Return
1483 * -ENOENT if we couldn't fstat. Return 0 if the fd is ok.
1485 static int check_symlink(int fd
)
1488 int ret
= fstat(fd
, &sb
);
1491 if (S_ISLNK(sb
.st_mode
))
1497 * Open a file or directory, provided that it contains no symlinks.
1499 * CAVEAT: This function must not be used for other purposes than container
1500 * setup before executing the container's init
1502 static int open_if_safe(int dirfd
, const char *nextpath
)
1504 int newfd
= openat(dirfd
, nextpath
, O_RDONLY
| O_NOFOLLOW
);
1505 if (newfd
>= 0) /* Was not a symlink, all good. */
1511 if (errno
== EPERM
|| errno
== EACCES
) {
1512 /* We're not root (cause we got EPERM) so try opening with
1515 newfd
= openat(dirfd
, nextpath
, O_PATH
| O_NOFOLLOW
);
1517 /* O_PATH will return an fd for symlinks. We know
1518 * nextpath wasn't a symlink at last openat, so if fd is
1519 * now a link, then something * fishy is going on.
1521 int ret
= check_symlink(newfd
);
1533 * Open a path intending for mounting, ensuring that the final path
1534 * is inside the container's rootfs.
1536 * CAVEAT: This function must not be used for other purposes than container
1537 * setup before executing the container's init
1539 * @target: path to be opened
1540 * @prefix_skip: a part of @target in which to ignore symbolic links. This
1541 * would be the container's rootfs.
1543 * Return an open fd for the path, or <0 on error.
1545 static int open_without_symlink(const char *target
, const char *prefix_skip
)
1547 int curlen
= 0, dirfd
, fulllen
, i
;
1550 fulllen
= strlen(target
);
1552 /* make sure prefix-skip makes sense */
1553 if (prefix_skip
&& strlen(prefix_skip
) > 0) {
1554 curlen
= strlen(prefix_skip
);
1555 if (!is_subdir(target
, prefix_skip
, curlen
)) {
1556 ERROR("WHOA there - target '%s' didn't start with prefix '%s'",
1557 target
, prefix_skip
);
1561 * get_nextpath() expects the curlen argument to be
1562 * on a (turned into \0) / or before it, so decrement
1563 * curlen to make sure that happens
1572 /* Make a copy of target which we can hack up, and tokenize it */
1573 if ((dup
= strdup(target
)) == NULL
) {
1574 SYSERROR("Out of memory checking for symbolic link");
1577 for (i
= 0; i
< fulllen
; i
++) {
1582 dirfd
= open(prefix_skip
, O_RDONLY
);
1586 int newfd
, saved_errno
;
1589 if ((nextpath
= get_nextpath(dup
, &curlen
, fulllen
)) == NULL
)
1591 newfd
= open_if_safe(dirfd
, nextpath
);
1592 saved_errno
= errno
;
1596 errno
= saved_errno
;
1598 SYSERROR("%s in %s was a symbolic link!", nextpath
, target
);
1609 * Safely mount a path into a container, ensuring that the mount target
1610 * is under the container's @rootfs. (If @rootfs is NULL, then the container
1611 * uses the host's /)
1613 * CAVEAT: This function must not be used for other purposes than container
1614 * setup before executing the container's init
1616 int safe_mount(const char *src
, const char *dest
, const char *fstype
,
1617 unsigned long flags
, const void *data
, const char *rootfs
)
1619 int destfd
, ret
, saved_errno
;
1620 /* Only needs enough for /proc/self/fd/<fd>. */
1621 char srcbuf
[50], destbuf
[50];
1623 const char *mntsrc
= src
;
1628 /* todo - allow symlinks for relative paths if 'allowsymlinks' option is passed */
1629 if (flags
& MS_BIND
&& src
&& src
[0] != '/') {
1630 INFO("this is a relative bind mount");
1631 srcfd
= open_without_symlink(src
, NULL
);
1634 ret
= snprintf(srcbuf
, 50, "/proc/self/fd/%d", srcfd
);
1635 if (ret
< 0 || ret
> 50) {
1637 ERROR("Out of memory");
1643 destfd
= open_without_symlink(dest
, rootfs
);
1646 saved_errno
= errno
;
1648 errno
= saved_errno
;
1653 ret
= snprintf(destbuf
, 50, "/proc/self/fd/%d", destfd
);
1654 if (ret
< 0 || ret
> 50) {
1658 ERROR("Out of memory");
1662 ret
= mount(mntsrc
, destbuf
, fstype
, flags
, data
);
1663 saved_errno
= errno
;
1668 errno
= saved_errno
;
1669 SYSERROR("Failed to mount %s onto %s", src
? src
: "(null)", dest
);
1677 * Mount a proc under @rootfs if proc self points to a pid other than
1678 * my own. This is needed to have a known-good proc mount for setting
1679 * up LSMs both at container startup and attach.
1681 * @rootfs : the rootfs where proc should be mounted
1683 * Returns < 0 on failure, 0 if the correct proc was already mounted
1684 * and 1 if a new proc was mounted.
1686 * NOTE: not to be called from inside the container namespace!
1688 int lxc_mount_proc_if_needed(const char *rootfs
)
1690 char path
[MAXPATHLEN
];
1691 int link_to_pid
, linklen
, mypid
, ret
;
1692 char link
[LXC_NUMSTRLEN64
] = {0};
1694 ret
= snprintf(path
, MAXPATHLEN
, "%s/proc/self", rootfs
);
1695 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1696 SYSERROR("proc path name too long");
1700 linklen
= readlink(path
, link
, LXC_NUMSTRLEN64
);
1702 ret
= snprintf(path
, MAXPATHLEN
, "%s/proc", rootfs
);
1703 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1704 SYSERROR("proc path name too long");
1708 /* /proc not mounted */
1710 if (mkdir(path
, 0755) && errno
!= EEXIST
)
1713 } else if (linklen
>= LXC_NUMSTRLEN64
) {
1714 link
[linklen
- 1] = '\0';
1715 ERROR("readlink returned truncated content: \"%s\"", link
);
1719 mypid
= lxc_raw_getpid();
1720 INFO("I am %d, /proc/self points to \"%s\"", mypid
, link
);
1722 if (lxc_safe_int(link
, &link_to_pid
) < 0)
1725 /* correct procfs is already mounted */
1726 if (link_to_pid
== mypid
)
1729 ret
= umount2(path
, MNT_DETACH
);
1731 WARN("failed to umount \"%s\" with MNT_DETACH", path
);
1734 /* rootfs is NULL */
1735 if (!strcmp(rootfs
, ""))
1736 ret
= mount("proc", path
, "proc", 0, NULL
);
1738 ret
= safe_mount("proc", path
, "proc", 0, NULL
, rootfs
);
1742 INFO("mounted /proc in container for security transition");
1746 int open_devnull(void)
1748 int fd
= open("/dev/null", O_RDWR
);
1751 SYSERROR("Can't open /dev/null");
1756 int set_stdfds(int fd
)
1763 ret
= dup2(fd
, STDIN_FILENO
);
1767 ret
= dup2(fd
, STDOUT_FILENO
);
1771 ret
= dup2(fd
, STDERR_FILENO
);
1778 int null_stdfds(void)
1781 int fd
= open_devnull();
1784 ret
= set_stdfds(fd
);
1792 * Return the number of lines in file @fn, or -1 on error
1794 int lxc_count_file_lines(const char *fn
)
1801 f
= fopen_cloexec(fn
, "r");
1805 while (getline(&line
, &sz
, f
) != -1) {
1813 void *lxc_strmmap(void *addr
, size_t length
, int prot
, int flags
, int fd
,
1816 void *tmp
= NULL
, *overlap
= NULL
;
1818 /* We establish an anonymous mapping that is one byte larger than the
1819 * underlying file. The pages handed to us are zero filled. */
1820 tmp
= mmap(addr
, length
+ 1, PROT_READ
, MAP_PRIVATE
| MAP_ANONYMOUS
, -1, 0);
1821 if (tmp
== MAP_FAILED
)
1824 /* Now we establish a fixed-address mapping starting at the address we
1825 * received from our anonymous mapping and replace all bytes excluding
1826 * the additional \0-byte with the file. This allows us to use normal
1827 * string-handling functions. */
1828 overlap
= mmap(tmp
, length
, prot
, MAP_FIXED
| flags
, fd
, offset
);
1829 if (overlap
== MAP_FAILED
)
1830 munmap(tmp
, length
+ 1);
1835 int lxc_strmunmap(void *addr
, size_t length
)
1837 return munmap(addr
, length
+ 1);
1840 /* Check whether a signal is blocked by a process. */
1841 /* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
1842 #define __PROC_STATUS_LEN (5 + (LXC_NUMSTRLEN64) + 7 + 1)
1843 bool task_blocking_signal(pid_t pid
, int signal
)
1847 long unsigned int sigblk
= 0;
1852 char status
[__PROC_STATUS_LEN
];
1854 ret
= snprintf(status
, __PROC_STATUS_LEN
, "/proc/%d/status", pid
);
1855 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
1858 f
= fopen(status
, "r");
1862 while (getline(&line
, &n
, f
) != -1) {
1863 if (strncmp(line
, "SigBlk:\t", 8))
1866 if (sscanf(line
+ 8, "%lx", &sigblk
) != 1)
1870 if (sigblk
& (1LU << (signal
- 1)))
1879 static int lxc_append_null_to_list(void ***list
)
1885 for (; (*list
)[newentry
]; newentry
++) {
1889 tmp
= realloc(*list
, (newentry
+ 2) * sizeof(void **));
1894 (*list
)[newentry
+ 1] = NULL
;
1899 int lxc_append_string(char ***list
, char *entry
)
1904 newentry
= lxc_append_null_to_list((void ***)list
);
1908 copy
= strdup(entry
);
1912 (*list
)[newentry
] = copy
;
1917 int lxc_preserve_ns(const int pid
, const char *ns
)
1920 /* 5 /proc + 21 /int_as_str + 3 /ns + 20 /NS_NAME + 1 \0 */
1921 #define __NS_PATH_LEN 50
1922 char path
[__NS_PATH_LEN
];
1924 /* This way we can use this function to also check whether namespaces
1925 * are supported by the kernel by passing in the NULL or the empty
1928 ret
= snprintf(path
, __NS_PATH_LEN
, "/proc/%d/ns%s%s", pid
,
1929 !ns
|| strcmp(ns
, "") == 0 ? "" : "/",
1930 !ns
|| strcmp(ns
, "") == 0 ? "" : ns
);
1932 if (ret
< 0 || (size_t)ret
>= __NS_PATH_LEN
)
1935 return open(path
, O_RDONLY
| O_CLOEXEC
);
1938 int lxc_safe_uint(const char *numstr
, unsigned int *converted
)
1941 unsigned long int uli
;
1943 while (isspace(*numstr
))
1950 uli
= strtoul(numstr
, &err
, 0);
1951 if (errno
== ERANGE
&& uli
== ULONG_MAX
)
1954 if (err
== numstr
|| *err
!= '\0')
1960 *converted
= (unsigned int)uli
;
1964 int lxc_safe_ulong(const char *numstr
, unsigned long *converted
)
1967 unsigned long int uli
;
1969 while (isspace(*numstr
))
1976 uli
= strtoul(numstr
, &err
, 0);
1977 if (errno
== ERANGE
&& uli
== ULONG_MAX
)
1980 if (err
== numstr
|| *err
!= '\0')
1987 int lxc_safe_int(const char *numstr
, int *converted
)
1990 signed long int sli
;
1993 sli
= strtol(numstr
, &err
, 0);
1994 if (errno
== ERANGE
&& (sli
== LONG_MAX
|| sli
== LONG_MIN
))
1997 if (errno
!= 0 && sli
== 0)
2000 if (err
== numstr
|| *err
!= '\0')
2003 if (sli
> INT_MAX
|| sli
< INT_MIN
)
2006 *converted
= (int)sli
;
2010 int lxc_safe_long(const char *numstr
, long int *converted
)
2013 signed long int sli
;
2016 sli
= strtol(numstr
, &err
, 0);
2017 if (errno
== ERANGE
&& (sli
== LONG_MAX
|| sli
== LONG_MIN
))
2020 if (errno
!= 0 && sli
== 0)
2023 if (err
== numstr
|| *err
!= '\0')
2030 int lxc_safe_long_long(const char *numstr
, long long int *converted
)
2033 signed long long int sli
;
2036 sli
= strtoll(numstr
, &err
, 0);
2037 if (errno
== ERANGE
&& (sli
== LLONG_MAX
|| sli
== LLONG_MIN
))
2040 if (errno
!= 0 && sli
== 0)
2043 if (err
== numstr
|| *err
!= '\0')
2050 int lxc_switch_uid_gid(uid_t uid
, gid_t gid
)
2052 if (setgid(gid
) < 0) {
2053 SYSERROR("Failed to switch to gid %d.", gid
);
2056 NOTICE("Switched to gid %d.", gid
);
2058 if (setuid(uid
) < 0) {
2059 SYSERROR("Failed to switch to uid %d.", uid
);
2062 NOTICE("Switched to uid %d.", uid
);
2067 /* Simple covenience function which enables uniform logging. */
2068 int lxc_setgroups(int size
, gid_t list
[])
2070 if (setgroups(size
, list
) < 0) {
2071 SYSERROR("Failed to setgroups().");
2074 NOTICE("Dropped additional groups.");
2079 static int lxc_get_unused_loop_dev_legacy(char *loop_name
)
2082 struct loop_info64 lo64
;
2084 int dfd
= -1, fd
= -1, ret
= -1;
2086 dir
= opendir("/dev");
2090 while ((dp
= readdir(dir
))) {
2094 if (strncmp(dp
->d_name
, "loop", 4) != 0)
2101 fd
= openat(dfd
, dp
->d_name
, O_RDWR
);
2105 ret
= ioctl(fd
, LOOP_GET_STATUS64
, &lo64
);
2107 if (ioctl(fd
, LOOP_GET_STATUS64
, &lo64
) == 0 ||
2115 ret
= snprintf(loop_name
, LO_NAME_SIZE
, "/dev/%s", dp
->d_name
);
2116 if (ret
< 0 || ret
>= LO_NAME_SIZE
) {
2133 static int lxc_get_unused_loop_dev(char *name_loop
)
2136 int fd_ctl
= -1, fd_tmp
= -1;
2138 fd_ctl
= open("/dev/loop-control", O_RDWR
| O_CLOEXEC
);
2142 loop_nr
= ioctl(fd_ctl
, LOOP_CTL_GET_FREE
);
2146 ret
= snprintf(name_loop
, LO_NAME_SIZE
, "/dev/loop%d", loop_nr
);
2147 if (ret
< 0 || ret
>= LO_NAME_SIZE
)
2150 fd_tmp
= open(name_loop
, O_RDWR
| O_CLOEXEC
);
2159 int lxc_prepare_loop_dev(const char *source
, char *loop_dev
, int flags
)
2162 struct loop_info64 lo64
;
2163 int fd_img
= -1, fret
= -1, fd_loop
= -1;
2165 fd_loop
= lxc_get_unused_loop_dev(loop_dev
);
2167 if (fd_loop
== -ENODEV
)
2168 fd_loop
= lxc_get_unused_loop_dev_legacy(loop_dev
);
2173 fd_img
= open(source
, O_RDWR
| O_CLOEXEC
);
2177 ret
= ioctl(fd_loop
, LOOP_SET_FD
, fd_img
);
2181 memset(&lo64
, 0, sizeof(lo64
));
2182 lo64
.lo_flags
= flags
;
2184 ret
= ioctl(fd_loop
, LOOP_SET_STATUS64
, &lo64
);
2194 if (fret
< 0 && fd_loop
>= 0) {
2202 int lxc_unstack_mountpoint(const char *path
, bool lazy
)
2208 ret
= umount2(path
, lazy
? MNT_DETACH
: 0);
2210 /* We consider anything else than EINVAL deadly to prevent going
2211 * into an infinite loop. (The other alternative is constantly
2212 * parsing /proc/self/mountinfo which is yucky and probably
2215 if (errno
!= EINVAL
)
2218 /* Just stop counting when this happens. That'd just be so
2219 * stupid that we won't even bother trying to report back the
2220 * correct value anymore.
2222 if (umounts
!= INT_MAX
)
2224 /* We succeeded in umounting. Make sure that there's no other
2225 * mountpoint stacked underneath.
2233 int run_command(char *buf
, size_t buf_size
, int (*child_fn
)(void *), void *args
)
2236 int ret
, fret
, pipefd
[2];
2239 /* Make sure our callers do not receive unitialized memory. */
2240 if (buf_size
> 0 && buf
)
2243 if (pipe(pipefd
) < 0) {
2244 SYSERROR("failed to create pipe");
2248 child
= lxc_raw_clone(0);
2252 SYSERROR("failed to create new process");
2257 /* Close the read-end of the pipe. */
2260 /* Redirect std{err,out} to write-end of the
2263 ret
= dup2(pipefd
[1], STDOUT_FILENO
);
2265 ret
= dup2(pipefd
[1], STDERR_FILENO
);
2267 /* Close the write-end of the pipe. */
2271 SYSERROR("failed to duplicate std{err,out} file descriptor");
2275 /* Does not return. */
2277 ERROR("failed to exec command");
2281 /* close the write-end of the pipe */
2284 if (buf
&& buf_size
> 0) {
2285 bytes
= read(pipefd
[0], buf
, buf_size
- 1);
2287 buf
[bytes
- 1] = '\0';
2290 fret
= wait_for_pid(child
);
2291 /* close the read-end of the pipe */
2297 char *must_make_path(const char *first
, ...)
2301 size_t full_len
= strlen(first
);
2303 dest
= must_copy_string(first
);
2305 va_start(args
, first
);
2306 while ((cur
= va_arg(args
, char *)) != NULL
) {
2307 full_len
+= strlen(cur
);
2310 dest
= must_realloc(dest
, full_len
+ 1);
2320 char *must_append_path(char *first
, ...)
2327 full_len
= strlen(first
);
2328 va_start(args
, first
);
2329 while ((cur
= va_arg(args
, char *)) != NULL
) {
2330 full_len
+= strlen(cur
);
2335 dest
= must_realloc(dest
, full_len
+ 1);
2347 char *must_copy_string(const char *entry
)
2354 ret
= strdup(entry
);
2360 void *must_realloc(void *orig
, size_t sz
)
2365 ret
= realloc(orig
, sz
);
2371 bool is_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
2373 return (fs
->f_type
== (fs_type_magic
)magic_val
);
2376 bool has_fs_type(const char *path
, fs_type_magic magic_val
)
2382 ret
= statfs(path
, &sb
);
2386 has_type
= is_fs_type(&sb
, magic_val
);
2387 if (!has_type
&& magic_val
== RAMFS_MAGIC
)
2388 WARN("When the ramfs it a tmpfs statfs() might report tmpfs");
2393 bool lxc_nic_exists(char *nic
)
2395 #define __LXC_SYS_CLASS_NET_LEN 15 + IFNAMSIZ + 1
2396 char path
[__LXC_SYS_CLASS_NET_LEN
];
2400 if (!strcmp(nic
, "none"))
2403 ret
= snprintf(path
, __LXC_SYS_CLASS_NET_LEN
, "/sys/class/net/%s", nic
);
2404 if (ret
< 0 || (size_t)ret
>= __LXC_SYS_CLASS_NET_LEN
)
2407 ret
= stat(path
, &sb
);
2414 int lxc_make_tmpfile(char *template, bool rm
)
2418 fd
= mkstemp(template);
2425 ret
= unlink(template);
2434 int parse_byte_size_string(const char *s
, int64_t *converted
)
2436 int ret
, suffix_len
;
2438 int64_t mltpl
, overflow
;
2440 char dup
[LXC_NUMSTRLEN64
+ 2];
2441 char suffix
[3] = {0};
2443 if (!s
|| !strcmp(s
, ""))
2446 end
= stpncpy(dup
, s
, sizeof(dup
));
2450 if (isdigit(*(end
- 1)))
2452 else if (isalpha(*(end
- 1)))
2457 if (suffix_len
> 0 && (end
- 2) == dup
&& !isdigit(*(end
- 2)))
2460 if (suffix_len
> 0 && isalpha(*(end
- 2)))
2463 if (suffix_len
> 0) {
2464 memcpy(suffix
, end
- suffix_len
, suffix_len
);
2465 *(suffix
+ suffix_len
) = '\0';
2466 *(end
- suffix_len
) = '\0';
2468 dup
[lxc_char_right_gc(dup
, strlen(dup
))] = '\0';
2470 ret
= lxc_safe_long_long(dup
, &conv
);
2474 if (suffix_len
!= 2) {
2479 if (!strcmp(suffix
, "kB"))
2481 else if (!strcmp(suffix
, "MB"))
2482 mltpl
= 1024 * 1024;
2483 else if (!strcmp(suffix
, "GB"))
2484 mltpl
= 1024 * 1024 * 1024;
2488 overflow
= conv
* mltpl
;
2489 if (conv
!= 0 && (overflow
/ conv
) != mltpl
)
2492 *converted
= overflow
;
2496 uint64_t lxc_find_next_power2(uint64_t n
)
2498 /* 0 is not valid input. We return 0 to the caller since 0 is not a
2499 * valid power of two.