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 #define O_PATH 010000000
59 #define O_NOFOLLOW 00400000
62 lxc_log_define(lxc_utils
, lxc
);
65 * if path is btrfs, tries to remove it and any subvolumes beneath it
67 extern bool btrfs_try_remove_subvol(const char *path
);
69 static int _recursive_rmdir(const char *dirname
, dev_t pdev
,
70 const char *exclude
, int level
, bool onedev
)
72 struct dirent
*direntp
;
75 char pathname
[MAXPATHLEN
];
76 bool hadexclude
= false;
78 dir
= opendir(dirname
);
80 ERROR("failed to open %s", dirname
);
84 while ((direntp
= readdir(dir
))) {
88 if (!strcmp(direntp
->d_name
, ".") ||
89 !strcmp(direntp
->d_name
, ".."))
92 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
93 if (rc
< 0 || rc
>= MAXPATHLEN
) {
94 ERROR("pathname too long");
99 if (!level
&& exclude
&& !strcmp(direntp
->d_name
, exclude
)) {
100 ret
= rmdir(pathname
);
104 INFO("Not deleting snapshot %s", pathname
);
108 ret
= unlink(pathname
);
110 INFO("Failed to remove %s", pathname
);
113 SYSERROR("Failed to rmdir %s", pathname
);
121 ret
= lstat(pathname
, &mystat
);
123 ERROR("Failed to stat %s", pathname
);
127 if (onedev
&& mystat
.st_dev
!= pdev
) {
128 /* TODO should we be checking /proc/self/mountinfo for
129 * pathname and not doing this if found? */
130 if (btrfs_try_remove_subvol(pathname
))
131 INFO("Removed btrfs subvolume at %s\n", pathname
);
134 if (S_ISDIR(mystat
.st_mode
)) {
135 if (_recursive_rmdir(pathname
, pdev
, exclude
, level
+1, onedev
) < 0)
138 if (unlink(pathname
) < 0) {
139 SYSERROR("Failed to delete %s", pathname
);
145 if (rmdir(dirname
) < 0 && !btrfs_try_remove_subvol(dirname
) && !hadexclude
) {
146 ERROR("Failed to delete %s", dirname
);
152 ERROR("Failed to close directory %s", dirname
);
156 return failed
? -1 : 0;
159 /* We have two different magic values for overlayfs, yay. */
160 #ifndef OVERLAYFS_SUPER_MAGIC
161 #define OVERLAYFS_SUPER_MAGIC 0x794c764f
164 #ifndef OVERLAY_SUPER_MAGIC
165 #define OVERLAY_SUPER_MAGIC 0x794c7630
168 /* In overlayfs, st_dev is unreliable. So on overlayfs we don't do the
171 static bool is_native_overlayfs(const char *path
)
173 if (has_fs_type(path
, OVERLAY_SUPER_MAGIC
) ||
174 has_fs_type(path
, OVERLAYFS_SUPER_MAGIC
))
180 /* returns 0 on success, -1 if there were any failures */
181 extern int lxc_rmdir_onedev(const char *path
, const char *exclude
)
186 if (is_native_overlayfs(path
))
189 if (lstat(path
, &mystat
) < 0) {
193 ERROR("Failed to stat %s", path
);
197 return _recursive_rmdir(path
, mystat
.st_dev
, exclude
, 0, onedev
);
200 /* borrowed from iproute2 */
201 extern int get_u16(unsigned short *val
, const char *arg
, int base
)
210 res
= strtoul(arg
, &ptr
, base
);
211 if (!ptr
|| ptr
== arg
|| *ptr
|| res
> 0xFFFF || errno
!= 0)
219 extern int mkdir_p(const char *dir
, mode_t mode
)
221 const char *tmp
= dir
;
222 const char *orig
= dir
;
226 dir
= tmp
+ strspn(tmp
, "/");
227 tmp
= dir
+ strcspn(dir
, "/");
228 makeme
= strndup(orig
, dir
- orig
);
230 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
231 SYSERROR("failed to create directory '%s'", makeme
);
248 if (stat(RUNTIME_PATH
, &sb
) < 0) {
252 if (geteuid() == sb
.st_uid
|| getegid() == sb
.st_gid
) {
253 rundir
= strdup(RUNTIME_PATH
);
257 rundir
= getenv("XDG_RUNTIME_DIR");
259 rundir
= strdup(rundir
);
263 INFO("XDG_RUNTIME_DIR isn't set in the environment.");
264 homedir
= getenv("HOME");
266 ERROR("HOME isn't set in the environment.");
270 rundir
= malloc(sizeof(char) * (17 + strlen(homedir
)));
271 sprintf(rundir
, "%s/.cache/lxc/run/", homedir
);
276 int wait_for_pid(pid_t pid
)
281 ret
= waitpid(pid
, &status
, 0);
289 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
294 int lxc_wait_for_pid_status(pid_t pid
)
299 ret
= waitpid(pid
, &status
, 0);
310 ssize_t
lxc_write_nointr(int fd
, const void* buf
, size_t count
)
314 ret
= write(fd
, buf
, count
);
315 if (ret
< 0 && errno
== EINTR
)
320 ssize_t
lxc_read_nointr(int fd
, void* buf
, size_t count
)
324 ret
= read(fd
, buf
, count
);
325 if (ret
< 0 && errno
== EINTR
)
330 ssize_t
lxc_read_nointr_expect(int fd
, void* buf
, size_t count
, const void* expected_buf
)
333 ret
= lxc_read_nointr(fd
, buf
, count
);
336 if ((size_t)ret
!= count
)
338 if (expected_buf
&& memcmp(buf
, expected_buf
, count
) != 0) {
346 #include <gnutls/gnutls.h>
347 #include <gnutls/crypto.h>
349 __attribute__((constructor
))
350 static void gnutls_lxc_init(void)
352 gnutls_global_init();
355 int sha1sum_file(char *fnam
, unsigned char *digest
)
364 f
= fopen_cloexec(fnam
, "r");
366 SYSERROR("Error opening template");
369 if (fseek(f
, 0, SEEK_END
) < 0) {
370 SYSERROR("Error seeking to end of template");
374 if ((flen
= ftell(f
)) < 0) {
375 SYSERROR("Error telling size of template");
379 if (fseek(f
, 0, SEEK_SET
) < 0) {
380 SYSERROR("Error seeking to start of template");
384 if ((buf
= malloc(flen
+1)) == NULL
) {
385 SYSERROR("Out of memory");
389 if (fread(buf
, 1, flen
, f
) != flen
) {
390 SYSERROR("Failure reading template");
396 SYSERROR("Failre closing template");
401 ret
= gnutls_hash_fast(GNUTLS_DIG_SHA1
, buf
, flen
, (void *)digest
);
407 char** lxc_va_arg_list_to_argv(va_list ap
, size_t skip
, int do_strdup
)
410 size_t count
= 1 + skip
;
413 /* first determine size of argument list, we don't want to reallocate
418 char* arg
= va_arg(ap2
, char*);
425 result
= calloc(count
, sizeof(char*));
430 char* arg
= va_arg(ap
, char*);
433 arg
= do_strdup
? strdup(arg
) : arg
;
436 result
[count
++] = arg
;
439 /* calloc has already set last element to NULL*/
447 const char** lxc_va_arg_list_to_argv_const(va_list ap
, size_t skip
)
449 return (const char**)lxc_va_arg_list_to_argv(ap
, skip
, 0);
452 struct lxc_popen_FILE
*lxc_popen(const char *command
)
457 struct lxc_popen_FILE
*fp
= NULL
;
459 ret
= pipe2(pipe_fds
, O_CLOEXEC
);
472 /* duplicate stdout */
473 if (pipe_fds
[1] != STDOUT_FILENO
)
474 ret
= dup2(pipe_fds
[1], STDOUT_FILENO
);
476 ret
= fcntl(pipe_fds
[1], F_SETFD
, 0);
482 /* duplicate stderr */
483 if (pipe_fds
[1] != STDERR_FILENO
)
484 ret
= dup2(pipe_fds
[1], STDERR_FILENO
);
486 ret
= fcntl(pipe_fds
[1], F_SETFD
, 0);
491 /* unblock all signals */
492 ret
= sigfillset(&mask
);
496 ret
= pthread_sigmask(SIG_UNBLOCK
, &mask
, NULL
);
500 execl("/bin/sh", "sh", "-c", command
, (char *)NULL
);
507 fp
= malloc(sizeof(*fp
));
510 memset(fp
, 0, sizeof(*fp
));
512 fp
->child_pid
= child_pid
;
513 fp
->pipe
= pipe_fds
[0];
515 /* From now on, closing fp->f will also close fp->pipe. So only ever
516 * call fclose(fp->f).
518 fp
->f
= fdopen(pipe_fds
[0], "r");
525 /* We can only close pipe_fds[0] if fdopen() didn't succeed or wasn't
526 * called yet. Otherwise the fd belongs to the file opened by fdopen()
527 * since it isn't dup()ed.
529 if (fp
&& !fp
->f
&& pipe_fds
[0] >= 0)
532 if (pipe_fds
[1] >= 0)
544 int lxc_pclose(struct lxc_popen_FILE
*fp
)
553 wait_pid
= waitpid(fp
->child_pid
, &wstatus
, 0);
554 } while (wait_pid
< 0 && errno
== EINTR
);
565 char *lxc_string_replace(const char *needle
, const char *replacement
, const char *haystack
)
567 ssize_t len
= -1, saved_len
= -1;
569 size_t replacement_len
= strlen(replacement
);
570 size_t needle_len
= strlen(needle
);
572 /* should be executed exactly twice */
573 while (len
== -1 || result
== NULL
) {
579 result
= calloc(1, len
+ 1);
587 for (last_p
= (char *)haystack
, p
= strstr(last_p
, needle
); p
; last_p
= p
, p
= strstr(last_p
, needle
)) {
588 part_len
= (ssize_t
)(p
- last_p
);
589 if (result
&& part_len
> 0)
590 memcpy(&result
[len
], last_p
, part_len
);
592 if (result
&& replacement_len
> 0)
593 memcpy(&result
[len
], replacement
, replacement_len
);
594 len
+= replacement_len
;
597 part_len
= strlen(last_p
);
598 if (result
&& part_len
> 0)
599 memcpy(&result
[len
], last_p
, part_len
);
603 /* make sure we did the same thing twice,
604 * once for calculating length, the other
605 * time for copying data */
606 if (saved_len
!= len
) {
610 /* make sure we didn't overwrite any buffer,
611 * due to calloc the string should be 0-terminated */
612 if (result
[len
] != '\0') {
620 bool lxc_string_in_array(const char *needle
, const char **haystack
)
622 for (; haystack
&& *haystack
; haystack
++)
623 if (!strcmp(needle
, *haystack
))
628 char *lxc_string_join(const char *sep
, const char **parts
, bool use_as_prefix
)
632 size_t sep_len
= strlen(sep
);
633 size_t result_len
= use_as_prefix
* sep_len
;
635 /* calculate new string length */
636 for (p
= (char **)parts
; *p
; p
++)
637 result_len
+= (p
> (char **)parts
) * sep_len
+ strlen(*p
);
639 result
= calloc(result_len
+ 1, 1);
645 for (p
= (char **)parts
; *p
; p
++) {
646 if (p
> (char **)parts
)
654 char **lxc_normalize_path(const char *path
)
658 size_t components_len
= 0;
661 components
= lxc_string_split(path
, '/');
664 for (p
= components
; *p
; p
++)
667 /* resolve '.' and '..' */
668 for (pos
= 0; pos
< components_len
; ) {
669 if (!strcmp(components
[pos
], ".") || (!strcmp(components
[pos
], "..") && pos
== 0)) {
670 /* eat this element */
671 free(components
[pos
]);
672 memmove(&components
[pos
], &components
[pos
+1], sizeof(char *) * (components_len
- pos
));
674 } else if (!strcmp(components
[pos
], "..")) {
675 /* eat this and the previous element */
676 free(components
[pos
- 1]);
677 free(components
[pos
]);
678 memmove(&components
[pos
-1], &components
[pos
+1], sizeof(char *) * (components_len
- pos
));
689 char *lxc_deslashify(const char *path
)
699 parts
= lxc_normalize_path(dup
);
705 /* We'll end up here if path == "///" or path == "". */
709 lxc_free_array((void **)parts
, free
);
712 n
= strcspn(dup
, "/");
715 lxc_free_array((void **)parts
, free
);
725 p
= lxc_string_join("/", (const char **)parts
, *dup
== '/');
727 lxc_free_array((void **)parts
, free
);
731 char *lxc_append_paths(const char *first
, const char *second
)
736 const char *pattern
= "%s%s";
738 len
= strlen(first
) + strlen(second
) + 1;
739 if (second
[0] != '/') {
744 result
= calloc(1, len
);
748 ret
= snprintf(result
, len
, pattern
, first
, second
);
749 if (ret
< 0 || (size_t)ret
>= len
) {
757 bool lxc_string_in_list(const char *needle
, const char *haystack
, char _sep
)
759 char *token
, *str
, *saveptr
= NULL
;
760 char sep
[2] = { _sep
, '\0' };
762 if (!haystack
|| !needle
)
765 str
= alloca(strlen(haystack
)+1);
766 strcpy(str
, haystack
);
767 for (; (token
= strtok_r(str
, sep
, &saveptr
)); str
= NULL
) {
768 if (strcmp(needle
, token
) == 0)
775 char **lxc_string_split(const char *string
, char _sep
)
777 char *token
, *str
, *saveptr
= NULL
;
778 char sep
[2] = {_sep
, '\0'};
779 char **tmp
= NULL
, **result
= NULL
;
780 size_t result_capacity
= 0;
781 size_t result_count
= 0;
785 return calloc(1, sizeof(char *));
787 str
= alloca(strlen(string
) + 1);
789 for (; (token
= strtok_r(str
, sep
, &saveptr
)); str
= NULL
) {
790 r
= lxc_grow_array((void ***)&result
, &result_capacity
, result_count
+ 1, 16);
793 result
[result_count
] = strdup(token
);
794 if (!result
[result_count
])
799 /* if we allocated too much, reduce it */
800 tmp
= realloc(result
, (result_count
+ 1) * sizeof(char *));
804 /* Make sure we don't return uninitialized memory. */
805 if (result_count
== 0)
810 lxc_free_array((void **)result
, free
);
815 static bool complete_word(char ***result
, char *start
, char *end
, size_t *cap
, size_t *cnt
)
819 r
= lxc_grow_array((void ***)result
, cap
, 2 + *cnt
, 16);
822 (*result
)[*cnt
] = strndup(start
, end
- start
);
823 if (!(*result
)[*cnt
])
831 * Given a a string 'one two "three four"', split into three words,
832 * one, two, and "three four"
834 char **lxc_string_split_quoted(char *string
)
836 char *nextword
= string
, *p
, state
;
837 char **result
= NULL
;
838 size_t result_capacity
= 0;
839 size_t result_count
= 0;
841 if (!string
|| !*string
)
842 return calloc(1, sizeof(char *));
844 // TODO I'm *not* handling escaped quote
846 for (p
= string
; *p
; p
++) {
851 else if (*p
== '"' || *p
== '\'') {
861 complete_word(&result
, nextword
, p
, &result_capacity
, &result_count
);
869 complete_word(&result
, nextword
+1, p
, &result_capacity
, &result_count
);
878 complete_word(&result
, nextword
, p
, &result_capacity
, &result_count
);
880 return realloc(result
, (result_count
+ 1) * sizeof(char *));
883 char **lxc_string_split_and_trim(const char *string
, char _sep
)
885 char *token
, *str
, *saveptr
= NULL
;
886 char sep
[2] = { _sep
, '\0' };
887 char **result
= NULL
;
888 size_t result_capacity
= 0;
889 size_t result_count
= 0;
894 return calloc(1, sizeof(char *));
896 str
= alloca(strlen(string
)+1);
898 for (; (token
= strtok_r(str
, sep
, &saveptr
)); str
= NULL
) {
899 while (token
[0] == ' ' || token
[0] == '\t')
902 while (i
> 0 && (token
[i
- 1] == ' ' || token
[i
- 1] == '\t')) {
906 r
= lxc_grow_array((void ***)&result
, &result_capacity
, result_count
+ 1, 16);
909 result
[result_count
] = strdup(token
);
910 if (!result
[result_count
])
915 /* if we allocated too much, reduce it */
916 return realloc(result
, (result_count
+ 1) * sizeof(char *));
919 lxc_free_array((void **)result
, free
);
924 void lxc_free_array(void **array
, lxc_free_fn element_free_fn
)
927 for (p
= array
; p
&& *p
; p
++)
932 int lxc_grow_array(void ***array
, size_t* capacity
, size_t new_size
, size_t capacity_increment
)
937 /* first time around, catch some trivial mistakes of the user
938 * only initializing one of these */
939 if (!*array
|| !*capacity
) {
944 new_capacity
= *capacity
;
945 while (new_size
+ 1 > new_capacity
)
946 new_capacity
+= capacity_increment
;
947 if (new_capacity
!= *capacity
) {
948 /* we have to reallocate */
949 new_array
= realloc(*array
, new_capacity
* sizeof(void *));
952 memset(&new_array
[*capacity
], 0, (new_capacity
- (*capacity
)) * sizeof(void *));
954 *capacity
= new_capacity
;
957 /* array has sufficient elements */
961 size_t lxc_array_len(void **array
)
966 for (p
= array
; p
&& *p
; p
++)
972 int lxc_write_to_file(const char *filename
, const void *buf
, size_t count
,
973 bool add_newline
, mode_t mode
)
978 fd
= open(filename
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_CLOEXEC
, mode
);
981 ret
= lxc_write_nointr(fd
, buf
, count
);
984 if ((size_t)ret
!= count
)
987 ret
= lxc_write_nointr(fd
, "\n", 1);
1001 int lxc_read_from_file(const char *filename
, void* buf
, size_t count
)
1003 int fd
= -1, saved_errno
;
1006 fd
= open(filename
, O_RDONLY
| O_CLOEXEC
);
1010 if (!buf
|| !count
) {
1013 while ((ret
= read(fd
, buf2
, 100)) > 0)
1018 memset(buf
, 0, count
);
1019 ret
= read(fd
, buf
, count
);
1023 ERROR("read %s: %s", filename
, strerror(errno
));
1025 saved_errno
= errno
;
1027 errno
= saved_errno
;
1031 void **lxc_append_null_to_array(void **array
, size_t count
)
1035 /* Append NULL to the array */
1037 temp
= realloc(array
, (count
+ 1) * sizeof(*array
));
1040 for (i
= 0; i
< count
; i
++)
1046 array
[count
] = NULL
;
1051 int randseed(bool srand_it
)
1054 srand pre-seed function based on /dev/urandom
1056 unsigned int seed
= time(NULL
) + getpid();
1059 f
= fopen("/dev/urandom", "r");
1061 int ret
= fread(&seed
, sizeof(seed
), 1, f
);
1063 DEBUG("unable to fread /dev/urandom, %s, fallback to time+pid rand seed", strerror(errno
));
1073 uid_t
get_ns_uid(uid_t orig
)
1077 uid_t nsid
, hostid
, range
;
1078 FILE *f
= fopen("/proc/self/uid_map", "r");
1082 while (getline(&line
, &sz
, f
) != -1) {
1083 if (sscanf(line
, "%u %u %u", &nsid
, &hostid
, &range
) != 3)
1085 if (hostid
<= orig
&& hostid
+ range
> orig
) {
1086 nsid
+= orig
- hostid
;
1098 bool dir_exists(const char *path
)
1103 ret
= stat(path
, &sb
);
1105 /* Could be something other than eexist, just say "no". */
1107 return S_ISDIR(sb
.st_mode
);
1110 /* Note we don't use SHA-1 here as we don't want to depend on HAVE_GNUTLS.
1111 * FNV has good anti collision properties and we're not worried
1112 * about pre-image resistance or one-way-ness, we're just trying to make
1113 * the name unique in the 108 bytes of space we have.
1115 uint64_t fnv_64a_buf(void *buf
, size_t len
, uint64_t hval
)
1119 for(bp
= buf
; bp
< (unsigned char *)buf
+ len
; bp
++)
1121 /* xor the bottom with the current octet */
1122 hval
^= (uint64_t)*bp
;
1125 * multiply by the 64 bit FNV magic prime mod 2^64
1127 hval
+= (hval
<< 1) + (hval
<< 4) + (hval
<< 5) +
1128 (hval
<< 7) + (hval
<< 8) + (hval
<< 40);
1135 * Detect whether / is mounted MS_SHARED. The only way I know of to
1136 * check that is through /proc/self/mountinfo.
1137 * I'm only checking for /. If the container rootfs or mount location
1138 * is MS_SHARED, but not '/', then you're out of luck - figuring that
1139 * out would be too much work to be worth it.
1141 int detect_shared_rootfs(void)
1143 char buf
[LXC_LINELEN
], *p
;
1148 f
= fopen("/proc/self/mountinfo", "r");
1151 while (fgets(buf
, LXC_LINELEN
, f
)) {
1152 for (p
= buf
, i
= 0; p
&& i
< 4; i
++)
1153 p
= strchr(p
+ 1, ' ');
1156 p2
= strchr(p
+ 1, ' ');
1160 if (strcmp(p
+ 1, "/") == 0) {
1161 /* This is '/'. Is it shared? */
1162 p
= strchr(p2
+ 1, ' ');
1163 if (p
&& strstr(p
, "shared:")) {
1173 bool switch_to_ns(pid_t pid
, const char *ns
) {
1175 char nspath
[MAXPATHLEN
];
1177 /* Switch to new ns */
1178 ret
= snprintf(nspath
, MAXPATHLEN
, "/proc/%d/ns/%s", pid
, ns
);
1179 if (ret
< 0 || ret
>= MAXPATHLEN
)
1182 fd
= open(nspath
, O_RDONLY
);
1184 SYSERROR("failed to open %s", nspath
);
1190 SYSERROR("failed to set process %d to %s of %d.", pid
, ns
, fd
);
1199 * looking at fs/proc_namespace.c, it appears we can
1200 * actually expect the rootfs entry to very specifically contain
1201 * " - rootfs rootfs "
1202 * IIUC, so long as we've chrooted so that rootfs is not our root,
1203 * the rootfs entry should always be skipped in mountinfo contents.
1205 bool detect_ramfs_rootfs(void)
1213 f
= fopen("/proc/self/mountinfo", "r");
1217 while (getline(&line
, &len
, f
) != -1) {
1218 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
1219 p
= strchr(p
+ 1, ' ');
1222 p2
= strchr(p
+ 1, ' ');
1226 if (strcmp(p
+ 1, "/") == 0) {
1227 /* This is '/'. Is it the ramfs? */
1228 p
= strchr(p2
+ 1, '-');
1229 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
1241 char *on_path(const char *cmd
, const char *rootfs
) {
1244 char *saveptr
= NULL
;
1245 char cmdpath
[MAXPATHLEN
];
1248 path
= getenv("PATH");
1252 path
= strdup(path
);
1256 entry
= strtok_r(path
, ":", &saveptr
);
1259 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s/%s", rootfs
, entry
, cmd
);
1261 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s", entry
, cmd
);
1263 if (ret
< 0 || ret
>= MAXPATHLEN
)
1266 if (access(cmdpath
, X_OK
) == 0) {
1268 return strdup(cmdpath
);
1272 entry
= strtok_r(NULL
, ":", &saveptr
);
1279 bool file_exists(const char *f
)
1281 struct stat statbuf
;
1283 return stat(f
, &statbuf
) == 0;
1286 bool cgns_supported(void)
1288 return file_exists("/proc/self/ns/cgroup");
1291 /* historically lxc-init has been under /usr/lib/lxc and under
1292 * /usr/lib/$ARCH/lxc. It now lives as $prefix/sbin/init.lxc.
1294 char *choose_init(const char *rootfs
)
1297 const char *empty
= "",
1299 int ret
, env_set
= 0;
1301 if (!getenv("PATH")) {
1302 if (setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 0))
1303 SYSERROR("Failed to setenv");
1307 retv
= on_path("init.lxc", rootfs
);
1310 if (unsetenv("PATH"))
1311 SYSERROR("Failed to unsetenv");
1317 retv
= malloc(PATH_MAX
);
1326 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, SBINDIR
, "/init.lxc");
1327 if (ret
< 0 || ret
>= PATH_MAX
) {
1328 ERROR("pathname too long");
1331 if (access(retv
, X_OK
) == 0)
1334 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/%s", tmp
, LXCINITDIR
, "/lxc/lxc-init");
1335 if (ret
< 0 || ret
>= PATH_MAX
) {
1336 ERROR("pathname too long");
1339 if (access(retv
, X_OK
) == 0)
1342 ret
= snprintf(retv
, PATH_MAX
, "%s/usr/lib/lxc/lxc-init", tmp
);
1343 if (ret
< 0 || ret
>= PATH_MAX
) {
1344 ERROR("pathname too long");
1347 if (access(retv
, X_OK
) == 0)
1350 ret
= snprintf(retv
, PATH_MAX
, "%s/sbin/lxc-init", tmp
);
1351 if (ret
< 0 || ret
>= PATH_MAX
) {
1352 ERROR("pathname too long");
1355 if (access(retv
, X_OK
) == 0)
1359 * Last resort, look for the statically compiled init.lxc which we
1360 * hopefully bind-mounted in.
1361 * If we are called during container setup, and we get to this point,
1362 * then the init.lxc.static from the host will need to be bind-mounted
1363 * in. So we return NULL here to indicate that.
1368 ret
= snprintf(retv
, PATH_MAX
, "/init.lxc.static");
1369 if (ret
< 0 || ret
>= PATH_MAX
) {
1370 WARN("Nonsense - name /lxc.init.static too long");
1373 if (access(retv
, X_OK
) == 0)
1381 int print_to_file(const char *file
, const char *content
)
1386 f
= fopen(file
, "w");
1389 if (fprintf(f
, "%s", content
) != strlen(content
))
1395 int is_dir(const char *path
)
1397 struct stat statbuf
;
1398 int ret
= stat(path
, &statbuf
);
1399 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
1405 * Given the '-t' template option to lxc-create, figure out what to
1406 * do. If the template is a full executable path, use that. If it
1407 * is something like 'sshd', then return $templatepath/lxc-sshd.
1408 * On success return the template, on error return NULL.
1410 char *get_template_path(const char *t
)
1415 if (t
[0] == '/' && access(t
, X_OK
) == 0) {
1420 len
= strlen(LXCTEMPLATEDIR
) + strlen(t
) + strlen("/lxc-") + 1;
1421 tpath
= malloc(len
);
1424 ret
= snprintf(tpath
, len
, "%s/lxc-%s", LXCTEMPLATEDIR
, t
);
1425 if (ret
< 0 || ret
>= len
) {
1429 if (access(tpath
, X_OK
) < 0) {
1430 SYSERROR("bad template: %s", t
);
1439 * @path: a pathname where / replaced with '\0'.
1440 * @offsetp: pointer to int showing which path segment was last seen.
1441 * Updated on return to reflect the next segment.
1442 * @fulllen: full original path length.
1443 * Returns a pointer to the next path segment, or NULL if done.
1445 static char *get_nextpath(char *path
, int *offsetp
, int fulllen
)
1447 int offset
= *offsetp
;
1449 if (offset
>= fulllen
)
1452 while (path
[offset
] != '\0' && offset
< fulllen
)
1454 while (path
[offset
] == '\0' && offset
< fulllen
)
1458 return (offset
< fulllen
) ? &path
[offset
] : NULL
;
1462 * Check that @subdir is a subdir of @dir. @len is the length of
1463 * @dir (to avoid having to recalculate it).
1465 static bool is_subdir(const char *subdir
, const char *dir
, size_t len
)
1467 size_t subdirlen
= strlen(subdir
);
1469 if (subdirlen
< len
)
1471 if (strncmp(subdir
, dir
, len
) != 0)
1473 if (dir
[len
-1] == '/')
1475 if (subdir
[len
] == '/' || subdirlen
== len
)
1481 * Check if the open fd is a symlink. Return -ELOOP if it is. Return
1482 * -ENOENT if we couldn't fstat. Return 0 if the fd is ok.
1484 static int check_symlink(int fd
)
1487 int ret
= fstat(fd
, &sb
);
1490 if (S_ISLNK(sb
.st_mode
))
1496 * Open a file or directory, provided that it contains no symlinks.
1498 * CAVEAT: This function must not be used for other purposes than container
1499 * setup before executing the container's init
1501 static int open_if_safe(int dirfd
, const char *nextpath
)
1503 int newfd
= openat(dirfd
, nextpath
, O_RDONLY
| O_NOFOLLOW
);
1504 if (newfd
>= 0) /* Was not a symlink, all good. */
1510 if (errno
== EPERM
|| errno
== EACCES
) {
1511 /* We're not root (cause we got EPERM) so try opening with
1514 newfd
= openat(dirfd
, nextpath
, O_PATH
| O_NOFOLLOW
);
1516 /* O_PATH will return an fd for symlinks. We know
1517 * nextpath wasn't a symlink at last openat, so if fd is
1518 * now a link, then something * fishy is going on.
1520 int ret
= check_symlink(newfd
);
1532 * Open a path intending for mounting, ensuring that the final path
1533 * is inside the container's rootfs.
1535 * CAVEAT: This function must not be used for other purposes than container
1536 * setup before executing the container's init
1538 * @target: path to be opened
1539 * @prefix_skip: a part of @target in which to ignore symbolic links. This
1540 * would be the container's rootfs.
1542 * Return an open fd for the path, or <0 on error.
1544 static int open_without_symlink(const char *target
, const char *prefix_skip
)
1546 int curlen
= 0, dirfd
, fulllen
, i
;
1549 fulllen
= strlen(target
);
1551 /* make sure prefix-skip makes sense */
1552 if (prefix_skip
&& strlen(prefix_skip
) > 0) {
1553 curlen
= strlen(prefix_skip
);
1554 if (!is_subdir(target
, prefix_skip
, curlen
)) {
1555 ERROR("WHOA there - target '%s' didn't start with prefix '%s'",
1556 target
, prefix_skip
);
1560 * get_nextpath() expects the curlen argument to be
1561 * on a (turned into \0) / or before it, so decrement
1562 * curlen to make sure that happens
1571 /* Make a copy of target which we can hack up, and tokenize it */
1572 if ((dup
= strdup(target
)) == NULL
) {
1573 SYSERROR("Out of memory checking for symbolic link");
1576 for (i
= 0; i
< fulllen
; i
++) {
1581 dirfd
= open(prefix_skip
, O_RDONLY
);
1585 int newfd
, saved_errno
;
1588 if ((nextpath
= get_nextpath(dup
, &curlen
, fulllen
)) == NULL
)
1590 newfd
= open_if_safe(dirfd
, nextpath
);
1591 saved_errno
= errno
;
1595 errno
= saved_errno
;
1597 SYSERROR("%s in %s was a symbolic link!", nextpath
, target
);
1608 * Safely mount a path into a container, ensuring that the mount target
1609 * is under the container's @rootfs. (If @rootfs is NULL, then the container
1610 * uses the host's /)
1612 * CAVEAT: This function must not be used for other purposes than container
1613 * setup before executing the container's init
1615 int safe_mount(const char *src
, const char *dest
, const char *fstype
,
1616 unsigned long flags
, const void *data
, const char *rootfs
)
1618 int destfd
, ret
, saved_errno
;
1619 /* Only needs enough for /proc/self/fd/<fd>. */
1620 char srcbuf
[50], destbuf
[50];
1622 const char *mntsrc
= src
;
1627 /* todo - allow symlinks for relative paths if 'allowsymlinks' option is passed */
1628 if (flags
& MS_BIND
&& src
&& src
[0] != '/') {
1629 INFO("this is a relative bind mount");
1630 srcfd
= open_without_symlink(src
, NULL
);
1633 ret
= snprintf(srcbuf
, 50, "/proc/self/fd/%d", srcfd
);
1634 if (ret
< 0 || ret
> 50) {
1636 ERROR("Out of memory");
1642 destfd
= open_without_symlink(dest
, rootfs
);
1645 saved_errno
= errno
;
1647 errno
= saved_errno
;
1652 ret
= snprintf(destbuf
, 50, "/proc/self/fd/%d", destfd
);
1653 if (ret
< 0 || ret
> 50) {
1657 ERROR("Out of memory");
1661 ret
= mount(mntsrc
, destbuf
, fstype
, flags
, data
);
1662 saved_errno
= errno
;
1667 errno
= saved_errno
;
1668 SYSERROR("Failed to mount %s onto %s", src
? src
: "(null)", dest
);
1676 * Mount a proc under @rootfs if proc self points to a pid other than
1677 * my own. This is needed to have a known-good proc mount for setting
1678 * up LSMs both at container startup and attach.
1680 * @rootfs : the rootfs where proc should be mounted
1682 * Returns < 0 on failure, 0 if the correct proc was already mounted
1683 * and 1 if a new proc was mounted.
1685 * NOTE: not to be called from inside the container namespace!
1687 int lxc_mount_proc_if_needed(const char *rootfs
)
1689 char path
[MAXPATHLEN
];
1690 int link_to_pid
, linklen
, mypid
, ret
;
1691 char link
[LXC_NUMSTRLEN64
] = {0};
1693 ret
= snprintf(path
, MAXPATHLEN
, "%s/proc/self", rootfs
);
1694 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1695 SYSERROR("proc path name too long");
1699 linklen
= readlink(path
, link
, LXC_NUMSTRLEN64
);
1701 ret
= snprintf(path
, MAXPATHLEN
, "%s/proc", rootfs
);
1702 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1703 SYSERROR("proc path name too long");
1707 /* /proc not mounted */
1709 if (mkdir(path
, 0755) && errno
!= EEXIST
)
1712 } else if (linklen
>= LXC_NUMSTRLEN64
) {
1713 link
[linklen
- 1] = '\0';
1714 ERROR("readlink returned truncated content: \"%s\"", link
);
1718 mypid
= lxc_raw_getpid();
1719 INFO("I am %d, /proc/self points to \"%s\"", mypid
, link
);
1721 if (lxc_safe_int(link
, &link_to_pid
) < 0)
1724 /* correct procfs is already mounted */
1725 if (link_to_pid
== mypid
)
1728 ret
= umount2(path
, MNT_DETACH
);
1730 WARN("failed to umount \"%s\" with MNT_DETACH", path
);
1733 /* rootfs is NULL */
1734 if (!strcmp(rootfs
, ""))
1735 ret
= mount("proc", path
, "proc", 0, NULL
);
1737 ret
= safe_mount("proc", path
, "proc", 0, NULL
, rootfs
);
1741 INFO("mounted /proc in container for security transition");
1745 int open_devnull(void)
1747 int fd
= open("/dev/null", O_RDWR
);
1750 SYSERROR("Can't open /dev/null");
1755 int set_stdfds(int fd
)
1762 ret
= dup2(fd
, STDIN_FILENO
);
1766 ret
= dup2(fd
, STDOUT_FILENO
);
1770 ret
= dup2(fd
, STDERR_FILENO
);
1777 int null_stdfds(void)
1780 int fd
= open_devnull();
1783 ret
= set_stdfds(fd
);
1791 * Return the number of lines in file @fn, or -1 on error
1793 int lxc_count_file_lines(const char *fn
)
1800 f
= fopen_cloexec(fn
, "r");
1804 while (getline(&line
, &sz
, f
) != -1) {
1812 /* Check whether a signal is blocked by a process. */
1813 /* /proc/pid-to-str/status\0 = (5 + 21 + 7 + 1) */
1814 #define __PROC_STATUS_LEN (6 + (LXC_NUMSTRLEN64) + 7 + 1)
1815 bool task_blocks_signal(pid_t pid
, int signal
)
1818 char status
[__PROC_STATUS_LEN
];
1820 uint64_t sigblk
= 0, one
= 1;
1825 ret
= snprintf(status
, __PROC_STATUS_LEN
, "/proc/%d/status", pid
);
1826 if (ret
< 0 || ret
>= __PROC_STATUS_LEN
)
1829 f
= fopen(status
, "r");
1833 while (getline(&line
, &n
, f
) != -1) {
1836 if (strncmp(line
, "SigBlk:", 7))
1839 numstr
= lxc_trim_whitespace_in_place(line
+ 7);
1840 ret
= lxc_safe_uint64(numstr
, &sigblk
, 16);
1847 if (sigblk
& (one
<< (signal
- 1)))
1856 static int lxc_append_null_to_list(void ***list
)
1862 for (; (*list
)[newentry
]; newentry
++) {
1866 tmp
= realloc(*list
, (newentry
+ 2) * sizeof(void **));
1871 (*list
)[newentry
+ 1] = NULL
;
1876 int lxc_append_string(char ***list
, char *entry
)
1881 newentry
= lxc_append_null_to_list((void ***)list
);
1885 copy
= strdup(entry
);
1889 (*list
)[newentry
] = copy
;
1894 int lxc_preserve_ns(const int pid
, const char *ns
)
1897 /* 5 /proc + 21 /int_as_str + 3 /ns + 20 /NS_NAME + 1 \0 */
1898 #define __NS_PATH_LEN 50
1899 char path
[__NS_PATH_LEN
];
1901 /* This way we can use this function to also check whether namespaces
1902 * are supported by the kernel by passing in the NULL or the empty
1905 ret
= snprintf(path
, __NS_PATH_LEN
, "/proc/%d/ns%s%s", pid
,
1906 !ns
|| strcmp(ns
, "") == 0 ? "" : "/",
1907 !ns
|| strcmp(ns
, "") == 0 ? "" : ns
);
1909 if (ret
< 0 || (size_t)ret
>= __NS_PATH_LEN
)
1912 return open(path
, O_RDONLY
| O_CLOEXEC
);
1915 int lxc_safe_uint(const char *numstr
, unsigned int *converted
)
1918 unsigned long int uli
;
1920 while (isspace(*numstr
))
1927 uli
= strtoul(numstr
, &err
, 0);
1928 if (errno
== ERANGE
&& uli
== ULONG_MAX
)
1931 if (err
== numstr
|| *err
!= '\0')
1937 *converted
= (unsigned int)uli
;
1941 int lxc_safe_ulong(const char *numstr
, unsigned long *converted
)
1944 unsigned long int uli
;
1946 while (isspace(*numstr
))
1953 uli
= strtoul(numstr
, &err
, 0);
1954 if (errno
== ERANGE
&& uli
== ULONG_MAX
)
1957 if (err
== numstr
|| *err
!= '\0')
1964 int lxc_safe_uint64(const char *numstr
, uint64_t *converted
, int base
)
1969 while (isspace(*numstr
))
1976 u
= strtoull(numstr
, &err
, base
);
1977 if (errno
== ERANGE
&& u
== ULLONG_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
))) {
2091 if (strncmp(dp
->d_name
, "loop", 4) != 0)
2098 fd
= openat(dfd
, dp
->d_name
, O_RDWR
);
2102 ret
= ioctl(fd
, LOOP_GET_STATUS64
, &lo64
);
2104 if (ioctl(fd
, LOOP_GET_STATUS64
, &lo64
) == 0 ||
2112 ret
= snprintf(loop_name
, LO_NAME_SIZE
, "/dev/%s", dp
->d_name
);
2113 if (ret
< 0 || ret
>= LO_NAME_SIZE
) {
2130 static int lxc_get_unused_loop_dev(char *name_loop
)
2133 int fd_ctl
= -1, fd_tmp
= -1;
2135 fd_ctl
= open("/dev/loop-control", O_RDWR
| O_CLOEXEC
);
2139 loop_nr
= ioctl(fd_ctl
, LOOP_CTL_GET_FREE
);
2143 ret
= snprintf(name_loop
, LO_NAME_SIZE
, "/dev/loop%d", loop_nr
);
2144 if (ret
< 0 || ret
>= LO_NAME_SIZE
)
2147 fd_tmp
= open(name_loop
, O_RDWR
| O_CLOEXEC
);
2156 int lxc_prepare_loop_dev(const char *source
, char *loop_dev
, int flags
)
2159 struct loop_info64 lo64
;
2160 int fd_img
= -1, fret
= -1, fd_loop
= -1;
2162 fd_loop
= lxc_get_unused_loop_dev(loop_dev
);
2164 if (fd_loop
== -ENODEV
)
2165 fd_loop
= lxc_get_unused_loop_dev_legacy(loop_dev
);
2170 fd_img
= open(source
, O_RDWR
| O_CLOEXEC
);
2174 ret
= ioctl(fd_loop
, LOOP_SET_FD
, fd_img
);
2178 memset(&lo64
, 0, sizeof(lo64
));
2179 lo64
.lo_flags
= flags
;
2181 ret
= ioctl(fd_loop
, LOOP_SET_STATUS64
, &lo64
);
2191 if (fret
< 0 && fd_loop
>= 0) {
2199 int lxc_unstack_mountpoint(const char *path
, bool lazy
)
2205 ret
= umount2(path
, lazy
? MNT_DETACH
: 0);
2207 /* We consider anything else than EINVAL deadly to prevent going
2208 * into an infinite loop. (The other alternative is constantly
2209 * parsing /proc/self/mountinfo which is yucky and probably
2212 if (errno
!= EINVAL
)
2215 /* Just stop counting when this happens. That'd just be so
2216 * stupid that we won't even bother trying to report back the
2217 * correct value anymore.
2219 if (umounts
!= INT_MAX
)
2221 /* We succeeded in umounting. Make sure that there's no other
2222 * mountpoint stacked underneath.
2230 int run_command(char *buf
, size_t buf_size
, int (*child_fn
)(void *), void *args
)
2233 int ret
, fret
, pipefd
[2];
2236 /* Make sure our callers do not receive uninitialized memory. */
2237 if (buf_size
> 0 && buf
)
2240 if (pipe(pipefd
) < 0) {
2241 SYSERROR("failed to create pipe");
2245 child
= lxc_raw_clone(0);
2249 SYSERROR("failed to create new process");
2254 /* Close the read-end of the pipe. */
2257 /* Redirect std{err,out} to write-end of the
2260 ret
= dup2(pipefd
[1], STDOUT_FILENO
);
2262 ret
= dup2(pipefd
[1], STDERR_FILENO
);
2264 /* Close the write-end of the pipe. */
2268 SYSERROR("failed to duplicate std{err,out} file descriptor");
2269 _exit(EXIT_FAILURE
);
2272 /* Does not return. */
2274 ERROR("failed to exec command");
2275 _exit(EXIT_FAILURE
);
2278 /* close the write-end of the pipe */
2281 if (buf
&& buf_size
> 0) {
2282 bytes
= read(pipefd
[0], buf
, buf_size
- 1);
2284 buf
[bytes
- 1] = '\0';
2287 fret
= wait_for_pid(child
);
2288 /* close the read-end of the pipe */
2294 char *must_make_path(const char *first
, ...)
2298 size_t full_len
= strlen(first
);
2300 dest
= must_copy_string(first
);
2302 va_start(args
, first
);
2303 while ((cur
= va_arg(args
, char *)) != NULL
) {
2304 full_len
+= strlen(cur
);
2307 dest
= must_realloc(dest
, full_len
+ 1);
2317 char *must_append_path(char *first
, ...)
2324 full_len
= strlen(first
);
2325 va_start(args
, first
);
2326 while ((cur
= va_arg(args
, char *)) != NULL
) {
2327 full_len
+= strlen(cur
);
2332 dest
= must_realloc(dest
, full_len
+ 1);
2344 char *must_copy_string(const char *entry
)
2351 ret
= strdup(entry
);
2357 void *must_realloc(void *orig
, size_t sz
)
2362 ret
= realloc(orig
, sz
);
2368 bool is_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
2370 return (fs
->f_type
== (fs_type_magic
)magic_val
);
2373 bool has_fs_type(const char *path
, fs_type_magic magic_val
)
2379 ret
= statfs(path
, &sb
);
2383 has_type
= is_fs_type(&sb
, magic_val
);
2384 if (!has_type
&& magic_val
== RAMFS_MAGIC
)
2385 WARN("When the ramfs it a tmpfs statfs() might report tmpfs");
2390 bool lxc_nic_exists(char *nic
)
2392 #define __LXC_SYS_CLASS_NET_LEN 15 + IFNAMSIZ + 1
2393 char path
[__LXC_SYS_CLASS_NET_LEN
];
2397 if (!strcmp(nic
, "none"))
2400 ret
= snprintf(path
, __LXC_SYS_CLASS_NET_LEN
, "/sys/class/net/%s", nic
);
2401 if (ret
< 0 || (size_t)ret
>= __LXC_SYS_CLASS_NET_LEN
)
2404 ret
= stat(path
, &sb
);
2411 int lxc_make_tmpfile(char *template, bool rm
)
2415 fd
= mkstemp(template);
2422 ret
= unlink(template);
2431 int parse_byte_size_string(const char *s
, int64_t *converted
)
2433 int ret
, suffix_len
;
2435 int64_t mltpl
, overflow
;
2437 char dup
[LXC_NUMSTRLEN64
+ 2];
2438 char suffix
[3] = {0};
2440 if (!s
|| !strcmp(s
, ""))
2443 end
= stpncpy(dup
, s
, sizeof(dup
) - 1);
2447 if (isdigit(*(end
- 1)))
2449 else if (isalpha(*(end
- 1)))
2454 if (suffix_len
> 0 && (end
- 2) == dup
&& !isdigit(*(end
- 2)))
2457 if (suffix_len
> 0 && isalpha(*(end
- 2)))
2460 if (suffix_len
> 0) {
2461 memcpy(suffix
, end
- suffix_len
, suffix_len
);
2462 *(suffix
+ suffix_len
) = '\0';
2463 *(end
- suffix_len
) = '\0';
2465 dup
[lxc_char_right_gc(dup
, strlen(dup
))] = '\0';
2467 ret
= lxc_safe_long_long(dup
, &conv
);
2471 if (suffix_len
!= 2) {
2476 if (strcasecmp(suffix
, "KB") == 0)
2478 else if (strcasecmp(suffix
, "MB") == 0)
2479 mltpl
= 1024 * 1024;
2480 else if (strcasecmp(suffix
, "GB") == 0)
2481 mltpl
= 1024 * 1024 * 1024;
2485 overflow
= conv
* mltpl
;
2486 if (conv
!= 0 && (overflow
/ conv
) != mltpl
)
2489 *converted
= overflow
;
2493 uint64_t lxc_find_next_power2(uint64_t n
)
2495 /* 0 is not valid input. We return 0 to the caller since 0 is not a
2496 * valid power of two.
2511 int lxc_set_death_signal(int signal
)
2516 ret
= prctl(PR_SET_PDEATHSIG
, signal
, 0, 0, 0);
2518 /* Check whether we have been orphaned. */
2519 ppid
= (pid_t
)syscall(SYS_getppid
);
2523 self
= lxc_raw_getpid();
2524 ret
= kill(self
, SIGKILL
);
2530 SYSERROR("Failed to set PR_SET_PDEATHSIG to %d", signal
);
2537 void remove_trailing_newlines(char *l
)
2544 while (--p
>= l
&& *p
== '\n')