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 #define O_PATH 010000000
63 #define O_NOFOLLOW 00400000
66 lxc_log_define(lxc_utils
, lxc
);
69 * if path is btrfs, tries to remove it and any subvolumes beneath it
71 extern bool btrfs_try_remove_subvol(const char *path
);
73 static int _recursive_rmdir(const char *dirname
, dev_t pdev
,
74 const char *exclude
, int level
, bool onedev
)
76 struct dirent
*direntp
;
79 char pathname
[MAXPATHLEN
];
80 bool hadexclude
= false;
82 dir
= opendir(dirname
);
84 ERROR("failed to open %s", dirname
);
88 while ((direntp
= readdir(dir
))) {
92 if (!strcmp(direntp
->d_name
, ".") ||
93 !strcmp(direntp
->d_name
, ".."))
96 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
97 if (rc
< 0 || rc
>= MAXPATHLEN
) {
98 ERROR("pathname too long");
103 if (!level
&& exclude
&& !strcmp(direntp
->d_name
, exclude
)) {
104 ret
= rmdir(pathname
);
108 INFO("Not deleting snapshot %s", pathname
);
112 ret
= unlink(pathname
);
114 INFO("Failed to remove %s", pathname
);
117 SYSERROR("Failed to rmdir %s", pathname
);
125 ret
= lstat(pathname
, &mystat
);
127 ERROR("Failed to stat %s", pathname
);
131 if (onedev
&& mystat
.st_dev
!= pdev
) {
132 /* TODO should we be checking /proc/self/mountinfo for
133 * pathname and not doing this if found? */
134 if (btrfs_try_remove_subvol(pathname
))
135 INFO("Removed btrfs subvolume at %s\n", pathname
);
138 if (S_ISDIR(mystat
.st_mode
)) {
139 if (_recursive_rmdir(pathname
, pdev
, exclude
, level
+1, onedev
) < 0)
142 if (unlink(pathname
) < 0) {
143 SYSERROR("Failed to delete %s", pathname
);
149 if (rmdir(dirname
) < 0 && !btrfs_try_remove_subvol(dirname
) && !hadexclude
) {
150 ERROR("Failed to delete %s", dirname
);
156 ERROR("Failed to close directory %s", dirname
);
160 return failed
? -1 : 0;
163 /* We have two different magic values for overlayfs, yay. */
164 #ifndef OVERLAYFS_SUPER_MAGIC
165 #define OVERLAYFS_SUPER_MAGIC 0x794c764f
168 #ifndef OVERLAY_SUPER_MAGIC
169 #define OVERLAY_SUPER_MAGIC 0x794c7630
172 /* In overlayfs, st_dev is unreliable. So on overlayfs we don't do the
175 static bool is_native_overlayfs(const char *path
)
177 if (has_fs_type(path
, OVERLAY_SUPER_MAGIC
) ||
178 has_fs_type(path
, OVERLAYFS_SUPER_MAGIC
))
184 /* returns 0 on success, -1 if there were any failures */
185 extern int lxc_rmdir_onedev(const char *path
, const char *exclude
)
190 if (is_native_overlayfs(path
))
193 if (lstat(path
, &mystat
) < 0) {
197 ERROR("Failed to stat %s", path
);
201 return _recursive_rmdir(path
, mystat
.st_dev
, exclude
, 0, onedev
);
204 /* borrowed from iproute2 */
205 extern int get_u16(unsigned short *val
, const char *arg
, int base
)
214 res
= strtoul(arg
, &ptr
, base
);
215 if (!ptr
|| ptr
== arg
|| *ptr
|| res
> 0xFFFF || errno
!= 0)
223 extern int mkdir_p(const char *dir
, mode_t mode
)
225 const char *tmp
= dir
;
226 const char *orig
= dir
;
230 dir
= tmp
+ strspn(tmp
, "/");
231 tmp
= dir
+ strcspn(dir
, "/");
232 makeme
= strndup(orig
, dir
- orig
);
234 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
235 SYSERROR("failed to create directory '%s'", makeme
);
252 if (stat(RUNTIME_PATH
, &sb
) < 0) {
256 if (geteuid() == sb
.st_uid
|| getegid() == sb
.st_gid
) {
257 rundir
= strdup(RUNTIME_PATH
);
261 rundir
= getenv("XDG_RUNTIME_DIR");
263 rundir
= strdup(rundir
);
267 INFO("XDG_RUNTIME_DIR isn't set in the environment.");
268 homedir
= getenv("HOME");
270 ERROR("HOME isn't set in the environment.");
274 rundir
= malloc(sizeof(char) * (17 + strlen(homedir
)));
275 sprintf(rundir
, "%s/.cache/lxc/run/", homedir
);
280 int wait_for_pid(pid_t pid
)
285 ret
= waitpid(pid
, &status
, 0);
293 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
298 int lxc_wait_for_pid_status(pid_t pid
)
303 ret
= waitpid(pid
, &status
, 0);
314 ssize_t
lxc_write_nointr(int fd
, const void* buf
, size_t count
)
318 ret
= write(fd
, buf
, count
);
319 if (ret
< 0 && errno
== EINTR
)
324 ssize_t
lxc_read_nointr(int fd
, void* buf
, size_t count
)
328 ret
= read(fd
, buf
, count
);
329 if (ret
< 0 && errno
== EINTR
)
334 ssize_t
lxc_read_nointr_expect(int fd
, void* buf
, size_t count
, const void* expected_buf
)
337 ret
= lxc_read_nointr(fd
, buf
, count
);
340 if ((size_t)ret
!= count
)
342 if (expected_buf
&& memcmp(buf
, expected_buf
, count
) != 0) {
350 #include <gnutls/gnutls.h>
351 #include <gnutls/crypto.h>
353 __attribute__((constructor
))
354 static void gnutls_lxc_init(void)
356 gnutls_global_init();
359 int sha1sum_file(char *fnam
, unsigned char *digest
)
368 f
= fopen_cloexec(fnam
, "r");
370 SYSERROR("Error opening template");
373 if (fseek(f
, 0, SEEK_END
) < 0) {
374 SYSERROR("Error seeking to end of template");
378 if ((flen
= ftell(f
)) < 0) {
379 SYSERROR("Error telling size of template");
383 if (fseek(f
, 0, SEEK_SET
) < 0) {
384 SYSERROR("Error seeking to start of template");
388 if ((buf
= malloc(flen
+1)) == NULL
) {
389 SYSERROR("Out of memory");
393 if (fread(buf
, 1, flen
, f
) != flen
) {
394 SYSERROR("Failure reading template");
400 SYSERROR("Failre closing template");
405 ret
= gnutls_hash_fast(GNUTLS_DIG_SHA1
, buf
, flen
, (void *)digest
);
411 char** lxc_va_arg_list_to_argv(va_list ap
, size_t skip
, int do_strdup
)
414 size_t count
= 1 + skip
;
417 /* first determine size of argument list, we don't want to reallocate
422 char* arg
= va_arg(ap2
, char*);
429 result
= calloc(count
, sizeof(char*));
434 char* arg
= va_arg(ap
, char*);
437 arg
= do_strdup
? strdup(arg
) : arg
;
440 result
[count
++] = arg
;
443 /* calloc has already set last element to NULL*/
451 const char** lxc_va_arg_list_to_argv_const(va_list ap
, size_t skip
)
453 return (const char**)lxc_va_arg_list_to_argv(ap
, skip
, 0);
456 struct lxc_popen_FILE
*lxc_popen(const char *command
)
461 struct lxc_popen_FILE
*fp
= NULL
;
463 ret
= pipe2(pipe_fds
, O_CLOEXEC
);
476 /* duplicate stdout */
477 if (pipe_fds
[1] != STDOUT_FILENO
)
478 ret
= dup2(pipe_fds
[1], STDOUT_FILENO
);
480 ret
= fcntl(pipe_fds
[1], F_SETFD
, 0);
486 /* duplicate stderr */
487 if (pipe_fds
[1] != STDERR_FILENO
)
488 ret
= dup2(pipe_fds
[1], STDERR_FILENO
);
490 ret
= fcntl(pipe_fds
[1], F_SETFD
, 0);
495 /* unblock all signals */
496 ret
= sigfillset(&mask
);
500 ret
= pthread_sigmask(SIG_UNBLOCK
, &mask
, NULL
);
504 execl("/bin/sh", "sh", "-c", command
, (char *)NULL
);
511 fp
= malloc(sizeof(*fp
));
514 memset(fp
, 0, sizeof(*fp
));
516 fp
->child_pid
= child_pid
;
517 fp
->pipe
= pipe_fds
[0];
519 /* From now on, closing fp->f will also close fp->pipe. So only ever
520 * call fclose(fp->f).
522 fp
->f
= fdopen(pipe_fds
[0], "r");
529 /* We can only close pipe_fds[0] if fdopen() didn't succeed or wasn't
530 * called yet. Otherwise the fd belongs to the file opened by fdopen()
531 * since it isn't dup()ed.
533 if (fp
&& !fp
->f
&& pipe_fds
[0] >= 0)
536 if (pipe_fds
[1] >= 0)
548 int lxc_pclose(struct lxc_popen_FILE
*fp
)
557 wait_pid
= waitpid(fp
->child_pid
, &wstatus
, 0);
558 } while (wait_pid
< 0 && errno
== EINTR
);
569 char *lxc_string_replace(const char *needle
, const char *replacement
, const char *haystack
)
571 ssize_t len
= -1, saved_len
= -1;
573 size_t replacement_len
= strlen(replacement
);
574 size_t needle_len
= strlen(needle
);
576 /* should be executed exactly twice */
577 while (len
== -1 || result
== NULL
) {
583 result
= calloc(1, len
+ 1);
591 for (last_p
= (char *)haystack
, p
= strstr(last_p
, needle
); p
; last_p
= p
, p
= strstr(last_p
, needle
)) {
592 part_len
= (ssize_t
)(p
- last_p
);
593 if (result
&& part_len
> 0)
594 memcpy(&result
[len
], last_p
, part_len
);
596 if (result
&& replacement_len
> 0)
597 memcpy(&result
[len
], replacement
, replacement_len
);
598 len
+= replacement_len
;
601 part_len
= strlen(last_p
);
602 if (result
&& part_len
> 0)
603 memcpy(&result
[len
], last_p
, part_len
);
607 /* make sure we did the same thing twice,
608 * once for calculating length, the other
609 * time for copying data */
610 if (saved_len
!= len
) {
614 /* make sure we didn't overwrite any buffer,
615 * due to calloc the string should be 0-terminated */
616 if (result
[len
] != '\0') {
624 bool lxc_string_in_array(const char *needle
, const char **haystack
)
626 for (; haystack
&& *haystack
; haystack
++)
627 if (!strcmp(needle
, *haystack
))
632 char *lxc_string_join(const char *sep
, const char **parts
, bool use_as_prefix
)
636 size_t sep_len
= strlen(sep
);
637 size_t result_len
= use_as_prefix
* sep_len
;
639 /* calculate new string length */
640 for (p
= (char **)parts
; *p
; p
++)
641 result_len
+= (p
> (char **)parts
) * sep_len
+ strlen(*p
);
643 result
= calloc(result_len
+ 1, 1);
648 (void)strlcpy(result
, sep
, result_len
+ 1);
650 for (p
= (char **)parts
; *p
; p
++) {
651 if (p
> (char **)parts
)
659 char **lxc_normalize_path(const char *path
)
663 size_t components_len
= 0;
666 components
= lxc_string_split(path
, '/');
669 for (p
= components
; *p
; p
++)
672 /* resolve '.' and '..' */
673 for (pos
= 0; pos
< components_len
; ) {
674 if (!strcmp(components
[pos
], ".") || (!strcmp(components
[pos
], "..") && pos
== 0)) {
675 /* eat this element */
676 free(components
[pos
]);
677 memmove(&components
[pos
], &components
[pos
+1], sizeof(char *) * (components_len
- pos
));
679 } else if (!strcmp(components
[pos
], "..")) {
680 /* eat this and the previous element */
681 free(components
[pos
- 1]);
682 free(components
[pos
]);
683 memmove(&components
[pos
-1], &components
[pos
+1], sizeof(char *) * (components_len
- pos
));
694 char *lxc_deslashify(const char *path
)
704 parts
= lxc_normalize_path(dup
);
710 /* We'll end up here if path == "///" or path == "". */
714 lxc_free_array((void **)parts
, free
);
717 n
= strcspn(dup
, "/");
720 lxc_free_array((void **)parts
, free
);
730 p
= lxc_string_join("/", (const char **)parts
, *dup
== '/');
732 lxc_free_array((void **)parts
, free
);
736 char *lxc_append_paths(const char *first
, const char *second
)
741 const char *pattern
= "%s%s";
743 len
= strlen(first
) + strlen(second
) + 1;
744 if (second
[0] != '/') {
749 result
= calloc(1, len
);
753 ret
= snprintf(result
, len
, pattern
, first
, second
);
754 if (ret
< 0 || (size_t)ret
>= len
) {
762 bool lxc_string_in_list(const char *needle
, const char *haystack
, char _sep
)
764 char *token
, *str
, *saveptr
= NULL
;
765 char sep
[2] = { _sep
, '\0' };
768 if (!haystack
|| !needle
)
771 len
= strlen(haystack
);
772 str
= alloca(len
+ 1);
773 (void)strlcpy(str
, haystack
, len
+ 1);
775 for (; (token
= strtok_r(str
, sep
, &saveptr
)); str
= NULL
) {
776 if (strcmp(needle
, token
) == 0)
783 char **lxc_string_split(const char *string
, char _sep
)
785 char *token
, *str
, *saveptr
= NULL
;
786 char sep
[2] = {_sep
, '\0'};
787 char **tmp
= NULL
, **result
= NULL
;
788 size_t result_capacity
= 0;
789 size_t result_count
= 0;
794 return calloc(1, sizeof(char *));
796 len
= strlen(string
);
797 str
= alloca(len
+ 1);
798 (void)strlcpy(str
, string
, len
+ 1);
800 for (; (token
= strtok_r(str
, sep
, &saveptr
)); str
= NULL
) {
801 r
= lxc_grow_array((void ***)&result
, &result_capacity
, result_count
+ 1, 16);
804 result
[result_count
] = strdup(token
);
805 if (!result
[result_count
])
810 /* if we allocated too much, reduce it */
811 tmp
= realloc(result
, (result_count
+ 1) * sizeof(char *));
815 /* Make sure we don't return uninitialized memory. */
816 if (result_count
== 0)
821 lxc_free_array((void **)result
, free
);
826 static bool complete_word(char ***result
, char *start
, char *end
, size_t *cap
, size_t *cnt
)
830 r
= lxc_grow_array((void ***)result
, cap
, 2 + *cnt
, 16);
833 (*result
)[*cnt
] = strndup(start
, end
- start
);
834 if (!(*result
)[*cnt
])
842 * Given a a string 'one two "three four"', split into three words,
843 * one, two, and "three four"
845 char **lxc_string_split_quoted(char *string
)
847 char *nextword
= string
, *p
, state
;
848 char **result
= NULL
;
849 size_t result_capacity
= 0;
850 size_t result_count
= 0;
852 if (!string
|| !*string
)
853 return calloc(1, sizeof(char *));
855 // TODO I'm *not* handling escaped quote
857 for (p
= string
; *p
; p
++) {
862 else if (*p
== '"' || *p
== '\'') {
872 complete_word(&result
, nextword
, p
, &result_capacity
, &result_count
);
880 complete_word(&result
, nextword
+1, p
, &result_capacity
, &result_count
);
889 complete_word(&result
, nextword
, p
, &result_capacity
, &result_count
);
891 return realloc(result
, (result_count
+ 1) * sizeof(char *));
894 char **lxc_string_split_and_trim(const char *string
, char _sep
)
896 char *token
, *str
, *saveptr
= NULL
;
897 char sep
[2] = { _sep
, '\0' };
898 char **result
= NULL
;
899 size_t result_capacity
= 0;
900 size_t result_count
= 0;
906 return calloc(1, sizeof(char *));
908 len
= strlen(string
);
909 str
= alloca(len
+ 1);
910 (void)strlcpy(str
, string
, len
+ 1);
912 for (; (token
= strtok_r(str
, sep
, &saveptr
)); str
= NULL
) {
913 while (token
[0] == ' ' || token
[0] == '\t')
916 while (i
> 0 && (token
[i
- 1] == ' ' || token
[i
- 1] == '\t')) {
920 r
= lxc_grow_array((void ***)&result
, &result_capacity
, result_count
+ 1, 16);
923 result
[result_count
] = strdup(token
);
924 if (!result
[result_count
])
929 /* if we allocated too much, reduce it */
930 return realloc(result
, (result_count
+ 1) * sizeof(char *));
933 lxc_free_array((void **)result
, free
);
938 void lxc_free_array(void **array
, lxc_free_fn element_free_fn
)
941 for (p
= array
; p
&& *p
; p
++)
946 int lxc_grow_array(void ***array
, size_t* capacity
, size_t new_size
, size_t capacity_increment
)
951 /* first time around, catch some trivial mistakes of the user
952 * only initializing one of these */
953 if (!*array
|| !*capacity
) {
958 new_capacity
= *capacity
;
959 while (new_size
+ 1 > new_capacity
)
960 new_capacity
+= capacity_increment
;
961 if (new_capacity
!= *capacity
) {
962 /* we have to reallocate */
963 new_array
= realloc(*array
, new_capacity
* sizeof(void *));
966 memset(&new_array
[*capacity
], 0, (new_capacity
- (*capacity
)) * sizeof(void *));
968 *capacity
= new_capacity
;
971 /* array has sufficient elements */
975 size_t lxc_array_len(void **array
)
980 for (p
= array
; p
&& *p
; p
++)
986 int lxc_write_to_file(const char *filename
, const void *buf
, size_t count
,
987 bool add_newline
, mode_t mode
)
992 fd
= open(filename
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_CLOEXEC
, mode
);
995 ret
= lxc_write_nointr(fd
, buf
, count
);
998 if ((size_t)ret
!= count
)
1001 ret
= lxc_write_nointr(fd
, "\n", 1);
1009 saved_errno
= errno
;
1011 errno
= saved_errno
;
1015 int lxc_read_from_file(const char *filename
, void* buf
, size_t count
)
1017 int fd
= -1, saved_errno
;
1020 fd
= open(filename
, O_RDONLY
| O_CLOEXEC
);
1024 if (!buf
|| !count
) {
1027 while ((ret
= read(fd
, buf2
, 100)) > 0)
1032 memset(buf
, 0, count
);
1033 ret
= read(fd
, buf
, count
);
1037 ERROR("read %s: %s", filename
, strerror(errno
));
1039 saved_errno
= errno
;
1041 errno
= saved_errno
;
1045 void **lxc_append_null_to_array(void **array
, size_t count
)
1049 /* Append NULL to the array */
1051 temp
= realloc(array
, (count
+ 1) * sizeof(*array
));
1054 for (i
= 0; i
< count
; i
++)
1060 array
[count
] = NULL
;
1065 int randseed(bool srand_it
)
1068 srand pre-seed function based on /dev/urandom
1070 unsigned int seed
= time(NULL
) + getpid();
1073 f
= fopen("/dev/urandom", "r");
1075 int ret
= fread(&seed
, sizeof(seed
), 1, f
);
1077 DEBUG("unable to fread /dev/urandom, %s, fallback to time+pid rand seed", strerror(errno
));
1087 uid_t
get_ns_uid(uid_t orig
)
1091 uid_t nsid
, hostid
, range
;
1092 FILE *f
= fopen("/proc/self/uid_map", "r");
1096 while (getline(&line
, &sz
, f
) != -1) {
1097 if (sscanf(line
, "%u %u %u", &nsid
, &hostid
, &range
) != 3)
1099 if (hostid
<= orig
&& hostid
+ range
> orig
) {
1100 nsid
+= orig
- hostid
;
1112 bool dir_exists(const char *path
)
1117 ret
= stat(path
, &sb
);
1119 /* Could be something other than eexist, just say "no". */
1121 return S_ISDIR(sb
.st_mode
);
1124 /* Note we don't use SHA-1 here as we don't want to depend on HAVE_GNUTLS.
1125 * FNV has good anti collision properties and we're not worried
1126 * about pre-image resistance or one-way-ness, we're just trying to make
1127 * the name unique in the 108 bytes of space we have.
1129 uint64_t fnv_64a_buf(void *buf
, size_t len
, uint64_t hval
)
1133 for(bp
= buf
; bp
< (unsigned char *)buf
+ len
; bp
++)
1135 /* xor the bottom with the current octet */
1136 hval
^= (uint64_t)*bp
;
1139 * multiply by the 64 bit FNV magic prime mod 2^64
1141 hval
+= (hval
<< 1) + (hval
<< 4) + (hval
<< 5) +
1142 (hval
<< 7) + (hval
<< 8) + (hval
<< 40);
1149 * Detect whether / is mounted MS_SHARED. The only way I know of to
1150 * check that is through /proc/self/mountinfo.
1151 * I'm only checking for /. If the container rootfs or mount location
1152 * is MS_SHARED, but not '/', then you're out of luck - figuring that
1153 * out would be too much work to be worth it.
1155 int detect_shared_rootfs(void)
1157 char buf
[LXC_LINELEN
], *p
;
1162 f
= fopen("/proc/self/mountinfo", "r");
1165 while (fgets(buf
, LXC_LINELEN
, f
)) {
1166 for (p
= buf
, i
= 0; p
&& i
< 4; i
++)
1167 p
= strchr(p
+ 1, ' ');
1170 p2
= strchr(p
+ 1, ' ');
1174 if (strcmp(p
+ 1, "/") == 0) {
1175 /* This is '/'. Is it shared? */
1176 p
= strchr(p2
+ 1, ' ');
1177 if (p
&& strstr(p
, "shared:")) {
1187 bool switch_to_ns(pid_t pid
, const char *ns
) {
1189 char nspath
[MAXPATHLEN
];
1191 /* Switch to new ns */
1192 ret
= snprintf(nspath
, MAXPATHLEN
, "/proc/%d/ns/%s", pid
, ns
);
1193 if (ret
< 0 || ret
>= MAXPATHLEN
)
1196 fd
= open(nspath
, O_RDONLY
);
1198 SYSERROR("failed to open %s", nspath
);
1204 SYSERROR("failed to set process %d to %s of %d.", pid
, ns
, fd
);
1213 * looking at fs/proc_namespace.c, it appears we can
1214 * actually expect the rootfs entry to very specifically contain
1215 * " - rootfs rootfs "
1216 * IIUC, so long as we've chrooted so that rootfs is not our root,
1217 * the rootfs entry should always be skipped in mountinfo contents.
1219 bool detect_ramfs_rootfs(void)
1227 f
= fopen("/proc/self/mountinfo", "r");
1231 while (getline(&line
, &len
, f
) != -1) {
1232 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
1233 p
= strchr(p
+ 1, ' ');
1236 p2
= strchr(p
+ 1, ' ');
1240 if (strcmp(p
+ 1, "/") == 0) {
1241 /* This is '/'. Is it the ramfs? */
1242 p
= strchr(p2
+ 1, '-');
1243 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
1255 char *on_path(const char *cmd
, const char *rootfs
) {
1258 char *saveptr
= NULL
;
1259 char cmdpath
[MAXPATHLEN
];
1262 path
= getenv("PATH");
1266 path
= strdup(path
);
1270 entry
= strtok_r(path
, ":", &saveptr
);
1273 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s/%s", rootfs
, entry
, cmd
);
1275 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s", entry
, cmd
);
1277 if (ret
< 0 || ret
>= MAXPATHLEN
)
1280 if (access(cmdpath
, X_OK
) == 0) {
1282 return strdup(cmdpath
);
1286 entry
= strtok_r(NULL
, ":", &saveptr
);
1293 bool file_exists(const char *f
)
1295 struct stat statbuf
;
1297 return stat(f
, &statbuf
) == 0;
1300 bool cgns_supported(void)
1302 return file_exists("/proc/self/ns/cgroup");
1305 /* historically lxc-init has been under /usr/lib/lxc and under
1306 * /usr/lib/$ARCH/lxc. It now lives as $prefix/sbin/init.lxc.
1308 char *choose_init(const char *rootfs
)
1311 const char *empty
= "",
1313 int ret
, env_set
= 0;
1315 if (!getenv("PATH")) {
1316 if (setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 0))
1317 SYSERROR("Failed to setenv");
1321 retv
= on_path("init.lxc", rootfs
);
1324 if (unsetenv("PATH"))
1325 SYSERROR("Failed to unsetenv");
1331 retv
= malloc(PATH_MAX
);
1340 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, SBINDIR
, "/init.lxc");
1341 if (ret
< 0 || ret
>= PATH_MAX
) {
1342 ERROR("pathname too long");
1345 if (access(retv
, X_OK
) == 0)
1348 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, LXCINITDIR
, "/lxc/lxc-init");
1349 if (ret
< 0 || ret
>= PATH_MAX
) {
1350 ERROR("pathname too long");
1353 if (access(retv
, X_OK
) == 0)
1356 ret
= snprintf(retv
, PATH_MAX
, "%s/usr/lib/lxc/lxc-init", tmp
);
1357 if (ret
< 0 || ret
>= PATH_MAX
) {
1358 ERROR("pathname too long");
1361 if (access(retv
, X_OK
) == 0)
1364 ret
= snprintf(retv
, PATH_MAX
, "%s/sbin/lxc-init", tmp
);
1365 if (ret
< 0 || ret
>= PATH_MAX
) {
1366 ERROR("pathname too long");
1369 if (access(retv
, X_OK
) == 0)
1373 * Last resort, look for the statically compiled init.lxc which we
1374 * hopefully bind-mounted in.
1375 * If we are called during container setup, and we get to this point,
1376 * then the init.lxc.static from the host will need to be bind-mounted
1377 * in. So we return NULL here to indicate that.
1382 ret
= snprintf(retv
, PATH_MAX
, "/init.lxc.static");
1383 if (ret
< 0 || ret
>= PATH_MAX
) {
1384 WARN("Nonsense - name /lxc.init.static too long");
1387 if (access(retv
, X_OK
) == 0)
1395 int print_to_file(const char *file
, const char *content
)
1400 f
= fopen(file
, "w");
1403 if (fprintf(f
, "%s", content
) != strlen(content
))
1409 int is_dir(const char *path
)
1411 struct stat statbuf
;
1412 int ret
= stat(path
, &statbuf
);
1413 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
1419 * Given the '-t' template option to lxc-create, figure out what to
1420 * do. If the template is a full executable path, use that. If it
1421 * is something like 'sshd', then return $templatepath/lxc-sshd.
1422 * On success return the template, on error return NULL.
1424 char *get_template_path(const char *t
)
1429 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
1434 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
1435 tpath
= malloc(len
);
1438 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
1439 if (ret
< 0 || ret
>= len
) {
1443 if (access(tpath
, X_OK
) < 0) {
1444 SYSERROR("bad template: %s", t
);
1453 * @path: a pathname where / replaced with '\0'.
1454 * @offsetp: pointer to int showing which path segment was last seen.
1455 * Updated on return to reflect the next segment.
1456 * @fulllen: full original path length.
1457 * Returns a pointer to the next path segment, or NULL if done.
1459 static char *get_nextpath(char *path
, int *offsetp
, int fulllen
)
1461 int offset
= *offsetp
;
1463 if (offset
>= fulllen
)
1466 while (path
[offset
] != '\0' && offset
< fulllen
)
1468 while (path
[offset
] == '\0' && offset
< fulllen
)
1472 return (offset
< fulllen
) ? &path
[offset
] : NULL
;
1476 * Check that @subdir is a subdir of @dir. @len is the length of
1477 * @dir (to avoid having to recalculate it).
1479 static bool is_subdir(const char *subdir
, const char *dir
, size_t len
)
1481 size_t subdirlen
= strlen(subdir
);
1483 if (subdirlen
< len
)
1485 if (strncmp(subdir
, dir
, len
) != 0)
1487 if (dir
[len
-1] == '/')
1489 if (subdir
[len
] == '/' || subdirlen
== len
)
1495 * Check if the open fd is a symlink. Return -ELOOP if it is. Return
1496 * -ENOENT if we couldn't fstat. Return 0 if the fd is ok.
1498 static int check_symlink(int fd
)
1501 int ret
= fstat(fd
, &sb
);
1504 if (S_ISLNK(sb
.st_mode
))
1510 * Open a file or directory, provided that it contains no symlinks.
1512 * CAVEAT: This function must not be used for other purposes than container
1513 * setup before executing the container's init
1515 static int open_if_safe(int dirfd
, const char *nextpath
)
1517 int newfd
= openat(dirfd
, nextpath
, O_RDONLY
| O_NOFOLLOW
);
1518 if (newfd
>= 0) /* Was not a symlink, all good. */
1524 if (errno
== EPERM
|| errno
== EACCES
) {
1525 /* We're not root (cause we got EPERM) so try opening with
1528 newfd
= openat(dirfd
, nextpath
, O_PATH
| O_NOFOLLOW
);
1530 /* O_PATH will return an fd for symlinks. We know
1531 * nextpath wasn't a symlink at last openat, so if fd is
1532 * now a link, then something * fishy is going on.
1534 int ret
= check_symlink(newfd
);
1546 * Open a path intending for mounting, ensuring that the final path
1547 * is inside the container's rootfs.
1549 * CAVEAT: This function must not be used for other purposes than container
1550 * setup before executing the container's init
1552 * @target: path to be opened
1553 * @prefix_skip: a part of @target in which to ignore symbolic links. This
1554 * would be the container's rootfs.
1556 * Return an open fd for the path, or <0 on error.
1558 static int open_without_symlink(const char *target
, const char *prefix_skip
)
1560 int curlen
= 0, dirfd
, fulllen
, i
;
1563 fulllen
= strlen(target
);
1565 /* make sure prefix-skip makes sense */
1566 if (prefix_skip
&& strlen(prefix_skip
) > 0) {
1567 curlen
= strlen(prefix_skip
);
1568 if (!is_subdir(target
, prefix_skip
, curlen
)) {
1569 ERROR("WHOA there - target '%s' didn't start with prefix '%s'",
1570 target
, prefix_skip
);
1574 * get_nextpath() expects the curlen argument to be
1575 * on a (turned into \0) / or before it, so decrement
1576 * curlen to make sure that happens
1585 /* Make a copy of target which we can hack up, and tokenize it */
1586 if ((dup
= strdup(target
)) == NULL
) {
1587 SYSERROR("Out of memory checking for symbolic link");
1590 for (i
= 0; i
< fulllen
; i
++) {
1595 dirfd
= open(prefix_skip
, O_RDONLY
);
1599 int newfd
, saved_errno
;
1602 if ((nextpath
= get_nextpath(dup
, &curlen
, fulllen
)) == NULL
)
1604 newfd
= open_if_safe(dirfd
, nextpath
);
1605 saved_errno
= errno
;
1609 errno
= saved_errno
;
1611 SYSERROR("%s in %s was a symbolic link!", nextpath
, target
);
1622 * Safely mount a path into a container, ensuring that the mount target
1623 * is under the container's @rootfs. (If @rootfs is NULL, then the container
1624 * uses the host's /)
1626 * CAVEAT: This function must not be used for other purposes than container
1627 * setup before executing the container's init
1629 int safe_mount(const char *src
, const char *dest
, const char *fstype
,
1630 unsigned long flags
, const void *data
, const char *rootfs
)
1632 int destfd
, ret
, saved_errno
;
1633 /* Only needs enough for /proc/self/fd/<fd>. */
1634 char srcbuf
[50], destbuf
[50];
1636 const char *mntsrc
= src
;
1641 /* todo - allow symlinks for relative paths if 'allowsymlinks' option is passed */
1642 if (flags
& MS_BIND
&& src
&& src
[0] != '/') {
1643 INFO("this is a relative bind mount");
1644 srcfd
= open_without_symlink(src
, NULL
);
1647 ret
= snprintf(srcbuf
, 50, "/proc/self/fd/%d", srcfd
);
1648 if (ret
< 0 || ret
> 50) {
1650 ERROR("Out of memory");
1656 destfd
= open_without_symlink(dest
, rootfs
);
1659 saved_errno
= errno
;
1661 errno
= saved_errno
;
1666 ret
= snprintf(destbuf
, 50, "/proc/self/fd/%d", destfd
);
1667 if (ret
< 0 || ret
> 50) {
1671 ERROR("Out of memory");
1675 ret
= mount(mntsrc
, destbuf
, fstype
, flags
, data
);
1676 saved_errno
= errno
;
1681 errno
= saved_errno
;
1682 SYSERROR("Failed to mount %s onto %s", src
? src
: "(null)", dest
);
1690 * Mount a proc under @rootfs if proc self points to a pid other than
1691 * my own. This is needed to have a known-good proc mount for setting
1692 * up LSMs both at container startup and attach.
1694 * @rootfs : the rootfs where proc should be mounted
1696 * Returns < 0 on failure, 0 if the correct proc was already mounted
1697 * and 1 if a new proc was mounted.
1699 * NOTE: not to be called from inside the container namespace!
1701 int lxc_mount_proc_if_needed(const char *rootfs
)
1703 char path
[MAXPATHLEN
];
1704 int link_to_pid
, linklen
, mypid
, ret
;
1705 char link
[LXC_NUMSTRLEN64
] = {0};
1707 ret
= snprintf(path
, MAXPATHLEN
, "%s/proc/self", rootfs
);
1708 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1709 SYSERROR("proc path name too long");
1713 linklen
= readlink(path
, link
, LXC_NUMSTRLEN64
);
1715 ret
= snprintf(path
, MAXPATHLEN
, "%s/proc", rootfs
);
1716 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1717 SYSERROR("proc path name too long");
1721 /* /proc not mounted */
1723 if (mkdir(path
, 0755) && errno
!= EEXIST
)
1726 } else if (linklen
>= LXC_NUMSTRLEN64
) {
1727 link
[linklen
- 1] = '\0';
1728 ERROR("readlink returned truncated content: \"%s\"", link
);
1732 mypid
= lxc_raw_getpid();
1733 INFO("I am %d, /proc/self points to \"%s\"", mypid
, link
);
1735 if (lxc_safe_int(link
, &link_to_pid
) < 0)
1738 /* correct procfs is already mounted */
1739 if (link_to_pid
== mypid
)
1742 ret
= umount2(path
, MNT_DETACH
);
1744 WARN("failed to umount \"%s\" with MNT_DETACH", path
);
1747 /* rootfs is NULL */
1748 if (!strcmp(rootfs
, ""))
1749 ret
= mount("proc", path
, "proc", 0, NULL
);
1751 ret
= safe_mount("proc", path
, "proc", 0, NULL
, rootfs
);
1755 INFO("mounted /proc in container for security transition");
1759 int open_devnull(void)
1761 int fd
= open("/dev/null", O_RDWR
);
1764 SYSERROR("Can't open /dev/null");
1769 int set_stdfds(int fd
)
1776 ret
= dup2(fd
, STDIN_FILENO
);
1780 ret
= dup2(fd
, STDOUT_FILENO
);
1784 ret
= dup2(fd
, STDERR_FILENO
);
1791 int null_stdfds(void)
1794 int fd
= open_devnull();
1797 ret
= set_stdfds(fd
);
1805 * Return the number of lines in file @fn, or -1 on error
1807 int lxc_count_file_lines(const char *fn
)
1814 f
= fopen_cloexec(fn
, "r");
1818 while (getline(&line
, &sz
, f
) != -1) {
1826 /* Check whether a signal is blocked by a process. */
1827 /* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
1828 #define __PROC_STATUS_LEN (6 + (LXC_NUMSTRLEN64) + 7 + 1)
1829 bool task_blocks_signal(pid_t pid
, int signal
)
1832 char status
[__PROC_STATUS_LEN
];
1834 uint64_t sigblk
= 0, one
= 1;
1839 ret
= snprintf(status
, __PROC_STATUS_LEN
, "/proc/%d/status", pid
);
1840 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
1843 f
= fopen(status
, "r");
1847 while (getline(&line
, &n
, f
) != -1) {
1850 if (strncmp(line
, "SigBlk:", 7))
1853 numstr
= lxc_trim_whitespace_in_place(line
+ 7);
1854 ret
= lxc_safe_uint64(numstr
, &sigblk
, 16);
1861 if (sigblk
& (one
<< (signal
- 1)))
1870 static int lxc_append_null_to_list(void ***list
)
1876 for (; (*list
)[newentry
]; newentry
++) {
1880 tmp
= realloc(*list
, (newentry
+ 2) * sizeof(void **));
1885 (*list
)[newentry
+ 1] = NULL
;
1890 int lxc_append_string(char ***list
, char *entry
)
1895 newentry
= lxc_append_null_to_list((void ***)list
);
1899 copy
= strdup(entry
);
1903 (*list
)[newentry
] = copy
;
1908 int lxc_preserve_ns(const int pid
, const char *ns
)
1911 /* 5 /proc + 21 /int_as_str + 3 /ns + 20 /NS_NAME + 1 \0 */
1912 #define __NS_PATH_LEN 50
1913 char path
[__NS_PATH_LEN
];
1915 /* This way we can use this function to also check whether namespaces
1916 * are supported by the kernel by passing in the NULL or the empty
1919 ret
= snprintf(path
, __NS_PATH_LEN
, "/proc/%d/ns%s%s", pid
,
1920 !ns
|| strcmp(ns
, "") == 0 ? "" : "/",
1921 !ns
|| strcmp(ns
, "") == 0 ? "" : ns
);
1923 if (ret
< 0 || (size_t)ret
>= __NS_PATH_LEN
)
1926 return open(path
, O_RDONLY
| O_CLOEXEC
);
1929 int lxc_safe_uint(const char *numstr
, unsigned int *converted
)
1932 unsigned long int uli
;
1934 while (isspace(*numstr
))
1941 uli
= strtoul(numstr
, &err
, 0);
1942 if (errno
== ERANGE
&& uli
== ULONG_MAX
)
1945 if (err
== numstr
|| *err
!= '\0')
1951 *converted
= (unsigned int)uli
;
1955 int lxc_safe_ulong(const char *numstr
, unsigned long *converted
)
1958 unsigned long int uli
;
1960 while (isspace(*numstr
))
1967 uli
= strtoul(numstr
, &err
, 0);
1968 if (errno
== ERANGE
&& uli
== ULONG_MAX
)
1971 if (err
== numstr
|| *err
!= '\0')
1978 int lxc_safe_uint64(const char *numstr
, uint64_t *converted
, int base
)
1983 while (isspace(*numstr
))
1990 u
= strtoull(numstr
, &err
, base
);
1991 if (errno
== ERANGE
&& u
== ULLONG_MAX
)
1994 if (err
== numstr
|| *err
!= '\0')
2001 int lxc_safe_int(const char *numstr
, int *converted
)
2004 signed long int sli
;
2007 sli
= strtol(numstr
, &err
, 0);
2008 if (errno
== ERANGE
&& (sli
== LONG_MAX
|| sli
== LONG_MIN
))
2011 if (errno
!= 0 && sli
== 0)
2014 if (err
== numstr
|| *err
!= '\0')
2017 if (sli
> INT_MAX
|| sli
< INT_MIN
)
2020 *converted
= (int)sli
;
2024 int lxc_safe_long(const char *numstr
, long int *converted
)
2027 signed long int sli
;
2030 sli
= strtol(numstr
, &err
, 0);
2031 if (errno
== ERANGE
&& (sli
== LONG_MAX
|| sli
== LONG_MIN
))
2034 if (errno
!= 0 && sli
== 0)
2037 if (err
== numstr
|| *err
!= '\0')
2044 int lxc_safe_long_long(const char *numstr
, long long int *converted
)
2047 signed long long int sli
;
2050 sli
= strtoll(numstr
, &err
, 0);
2051 if (errno
== ERANGE
&& (sli
== LLONG_MAX
|| sli
== LLONG_MIN
))
2054 if (errno
!= 0 && sli
== 0)
2057 if (err
== numstr
|| *err
!= '\0')
2064 int lxc_switch_uid_gid(uid_t uid
, gid_t gid
)
2066 if (setgid(gid
) < 0) {
2067 SYSERROR("Failed to switch to gid %d.", gid
);
2070 NOTICE("Switched to gid %d.", gid
);
2072 if (setuid(uid
) < 0) {
2073 SYSERROR("Failed to switch to uid %d.", uid
);
2076 NOTICE("Switched to uid %d.", uid
);
2081 /* Simple covenience function which enables uniform logging. */
2082 int lxc_setgroups(int size
, gid_t list
[])
2084 if (setgroups(size
, list
) < 0) {
2085 SYSERROR("Failed to setgroups().");
2088 NOTICE("Dropped additional groups.");
2093 static int lxc_get_unused_loop_dev_legacy(char *loop_name
)
2096 struct loop_info64 lo64
;
2098 int dfd
= -1, fd
= -1, ret
= -1;
2100 dir
= opendir("/dev");
2104 while ((dp
= readdir(dir
))) {
2105 if (strncmp(dp
->d_name
, "loop", 4) != 0)
2112 fd
= openat(dfd
, dp
->d_name
, O_RDWR
);
2116 ret
= ioctl(fd
, LOOP_GET_STATUS64
, &lo64
);
2118 if (ioctl(fd
, LOOP_GET_STATUS64
, &lo64
) == 0 ||
2126 ret
= snprintf(loop_name
, LO_NAME_SIZE
, "/dev/%s", dp
->d_name
);
2127 if (ret
< 0 || ret
>= LO_NAME_SIZE
) {
2144 static int lxc_get_unused_loop_dev(char *name_loop
)
2147 int fd_ctl
= -1, fd_tmp
= -1;
2149 fd_ctl
= open("/dev/loop-control", O_RDWR
| O_CLOEXEC
);
2153 loop_nr
= ioctl(fd_ctl
, LOOP_CTL_GET_FREE
);
2157 ret
= snprintf(name_loop
, LO_NAME_SIZE
, "/dev/loop%d", loop_nr
);
2158 if (ret
< 0 || ret
>= LO_NAME_SIZE
)
2161 fd_tmp
= open(name_loop
, O_RDWR
| O_CLOEXEC
);
2170 int lxc_prepare_loop_dev(const char *source
, char *loop_dev
, int flags
)
2173 struct loop_info64 lo64
;
2174 int fd_img
= -1, fret
= -1, fd_loop
= -1;
2176 fd_loop
= lxc_get_unused_loop_dev(loop_dev
);
2178 if (fd_loop
== -ENODEV
)
2179 fd_loop
= lxc_get_unused_loop_dev_legacy(loop_dev
);
2184 fd_img
= open(source
, O_RDWR
| O_CLOEXEC
);
2188 ret
= ioctl(fd_loop
, LOOP_SET_FD
, fd_img
);
2192 memset(&lo64
, 0, sizeof(lo64
));
2193 lo64
.lo_flags
= flags
;
2195 ret
= ioctl(fd_loop
, LOOP_SET_STATUS64
, &lo64
);
2205 if (fret
< 0 && fd_loop
>= 0) {
2213 int lxc_unstack_mountpoint(const char *path
, bool lazy
)
2219 ret
= umount2(path
, lazy
? MNT_DETACH
: 0);
2221 /* We consider anything else than EINVAL deadly to prevent going
2222 * into an infinite loop. (The other alternative is constantly
2223 * parsing /proc/self/mountinfo which is yucky and probably
2226 if (errno
!= EINVAL
)
2229 /* Just stop counting when this happens. That'd just be so
2230 * stupid that we won't even bother trying to report back the
2231 * correct value anymore.
2233 if (umounts
!= INT_MAX
)
2235 /* We succeeded in umounting. Make sure that there's no other
2236 * mountpoint stacked underneath.
2244 int run_command(char *buf
, size_t buf_size
, int (*child_fn
)(void *), void *args
)
2247 int ret
, fret
, pipefd
[2];
2250 /* Make sure our callers do not receive uninitialized memory. */
2251 if (buf_size
> 0 && buf
)
2254 if (pipe(pipefd
) < 0) {
2255 SYSERROR("failed to create pipe");
2259 child
= lxc_raw_clone(0);
2263 SYSERROR("failed to create new process");
2268 /* Close the read-end of the pipe. */
2271 /* Redirect std{err,out} to write-end of the
2274 ret
= dup2(pipefd
[1], STDOUT_FILENO
);
2276 ret
= dup2(pipefd
[1], STDERR_FILENO
);
2278 /* Close the write-end of the pipe. */
2282 SYSERROR("failed to duplicate std{err,out} file descriptor");
2283 _exit(EXIT_FAILURE
);
2286 /* Does not return. */
2288 ERROR("failed to exec command");
2289 _exit(EXIT_FAILURE
);
2292 /* close the write-end of the pipe */
2295 if (buf
&& buf_size
> 0) {
2296 bytes
= read(pipefd
[0], buf
, buf_size
- 1);
2298 buf
[bytes
- 1] = '\0';
2301 fret
= wait_for_pid(child
);
2302 /* close the read-end of the pipe */
2308 char *must_make_path(const char *first
, ...)
2312 size_t full_len
= strlen(first
);
2314 dest
= must_copy_string(first
);
2316 va_start(args
, first
);
2317 while ((cur
= va_arg(args
, char *)) != NULL
) {
2318 full_len
+= strlen(cur
);
2321 dest
= must_realloc(dest
, full_len
+ 1);
2331 char *must_append_path(char *first
, ...)
2338 full_len
= strlen(first
);
2339 va_start(args
, first
);
2340 while ((cur
= va_arg(args
, char *)) != NULL
) {
2341 full_len
+= strlen(cur
);
2346 dest
= must_realloc(dest
, full_len
+ 1);
2358 char *must_copy_string(const char *entry
)
2365 ret
= strdup(entry
);
2371 void *must_realloc(void *orig
, size_t sz
)
2376 ret
= realloc(orig
, sz
);
2382 bool is_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
2384 return (fs
->f_type
== (fs_type_magic
)magic_val
);
2387 bool has_fs_type(const char *path
, fs_type_magic magic_val
)
2393 ret
= statfs(path
, &sb
);
2397 has_type
= is_fs_type(&sb
, magic_val
);
2398 if (!has_type
&& magic_val
== RAMFS_MAGIC
)
2399 WARN("When the ramfs it a tmpfs statfs() might report tmpfs");
2404 bool lxc_nic_exists(char *nic
)
2406 #define __LXC_SYS_CLASS_NET_LEN 15 + IFNAMSIZ + 1
2407 char path
[__LXC_SYS_CLASS_NET_LEN
];
2411 if (!strcmp(nic
, "none"))
2414 ret
= snprintf(path
, __LXC_SYS_CLASS_NET_LEN
, "/sys/class/net/%s", nic
);
2415 if (ret
< 0 || (size_t)ret
>= __LXC_SYS_CLASS_NET_LEN
)
2418 ret
= stat(path
, &sb
);
2425 int lxc_make_tmpfile(char *template, bool rm
)
2431 fd
= mkstemp(template);
2439 ret
= unlink(template);
2448 int parse_byte_size_string(const char *s
, int64_t *converted
)
2450 int ret
, suffix_len
;
2452 int64_t mltpl
, overflow
;
2454 char dup
[LXC_NUMSTRLEN64
+ 2];
2455 char suffix
[3] = {0};
2457 if (!s
|| !strcmp(s
, ""))
2460 end
= stpncpy(dup
, s
, sizeof(dup
) - 1);
2464 if (isdigit(*(end
- 1)))
2466 else if (isalpha(*(end
- 1)))
2471 if (suffix_len
> 0 && (end
- 2) == dup
&& !isdigit(*(end
- 2)))
2474 if (suffix_len
> 0 && isalpha(*(end
- 2)))
2477 if (suffix_len
> 0) {
2478 memcpy(suffix
, end
- suffix_len
, suffix_len
);
2479 *(suffix
+ suffix_len
) = '\0';
2480 *(end
- suffix_len
) = '\0';
2482 dup
[lxc_char_right_gc(dup
, strlen(dup
))] = '\0';
2484 ret
= lxc_safe_long_long(dup
, &conv
);
2488 if (suffix_len
!= 2) {
2493 if (strcasecmp(suffix
, "KB") == 0)
2495 else if (strcasecmp(suffix
, "MB") == 0)
2496 mltpl
= 1024 * 1024;
2497 else if (strcasecmp(suffix
, "GB") == 0)
2498 mltpl
= 1024 * 1024 * 1024;
2502 overflow
= conv
* mltpl
;
2503 if (conv
!= 0 && (overflow
/ conv
) != mltpl
)
2506 *converted
= overflow
;
2510 uint64_t lxc_find_next_power2(uint64_t n
)
2512 /* 0 is not valid input. We return 0 to the caller since 0 is not a
2513 * valid power of two.
2528 int lxc_set_death_signal(int signal
)
2533 ret
= prctl(PR_SET_PDEATHSIG
, signal
, 0, 0, 0);
2535 /* Check whether we have been orphaned. */
2536 ppid
= (pid_t
)syscall(SYS_getppid
);
2540 self
= lxc_raw_getpid();
2541 ret
= kill(self
, SIGKILL
);
2547 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d", signal
);
2554 void remove_trailing_newlines(char *l
)
2561 while (--p
>= l
&& *p
== '\n')