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
31 #include <sys/types.h>
34 #include <sys/param.h>
35 #include <sys/mount.h>
39 #include <sys/types.h>
47 lxc_log_define(lxc_utils
, lxc
);
49 static int _recursive_rmdir_onedev(char *dirname
, dev_t pdev
,
50 const char *exclude
, int level
)
52 struct dirent dirent
, *direntp
;
55 char pathname
[MAXPATHLEN
];
56 bool hadexclude
= false;
58 dir
= opendir(dirname
);
60 ERROR("%s: failed to open %s", __func__
, dirname
);
64 while (!readdir_r(dir
, &dirent
, &direntp
)) {
71 if (!strcmp(direntp
->d_name
, ".") ||
72 !strcmp(direntp
->d_name
, ".."))
75 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
76 if (rc
< 0 || rc
>= MAXPATHLEN
) {
77 ERROR("pathname too long");
82 if (!level
&& exclude
&& !strcmp(direntp
->d_name
, exclude
)) {
83 ret
= rmdir(pathname
);
87 INFO("Not deleting snapshots");
91 ret
= unlink(pathname
);
93 INFO("%s: failed to remove %s", __func__
, pathname
);
96 SYSERROR("%s: failed to rmdir %s", __func__
, pathname
);
104 ret
= lstat(pathname
, &mystat
);
106 ERROR("%s: failed to stat %s", __func__
, pathname
);
110 if (mystat
.st_dev
!= pdev
)
112 if (S_ISDIR(mystat
.st_mode
)) {
113 if (_recursive_rmdir_onedev(pathname
, pdev
, exclude
, level
+1) < 0)
116 if (unlink(pathname
) < 0) {
117 ERROR("%s: failed to delete %s", __func__
, pathname
);
123 if (rmdir(dirname
) < 0) {
125 ERROR("%s: failed to delete %s", __func__
, dirname
);
132 ERROR("%s: failed to close directory %s", __func__
, dirname
);
136 return failed
? -1 : 0;
139 /* returns 0 on success, -1 if there were any failures */
140 extern int lxc_rmdir_onedev(char *path
, const char *exclude
)
144 if (lstat(path
, &mystat
) < 0) {
145 ERROR("%s: failed to stat %s", __func__
, path
);
149 return _recursive_rmdir_onedev(path
, mystat
.st_dev
, exclude
, 0);
152 static int mount_fs(const char *source
, const char *target
, const char *type
)
154 /* the umount may fail */
156 WARN("failed to unmount %s : %s", target
, strerror(errno
));
158 if (mount(source
, target
, type
, 0, NULL
)) {
159 ERROR("failed to mount %s : %s", target
, strerror(errno
));
163 DEBUG("'%s' mounted on '%s'", source
, target
);
168 extern void lxc_setup_fs(void)
170 if (mount_fs("proc", "/proc", "proc"))
171 INFO("failed to remount proc");
173 /* if we can't mount /dev/shm, continue anyway */
174 if (mount_fs("shmfs", "/dev/shm", "tmpfs"))
175 INFO("failed to mount /dev/shm");
177 /* If we were able to mount /dev/shm, then /dev exists */
178 /* Sure, but it's read-only per config :) */
179 if (access("/dev/mqueue", F_OK
) && mkdir("/dev/mqueue", 0666)) {
180 DEBUG("failed to create '/dev/mqueue'");
184 /* continue even without posix message queue support */
185 if (mount_fs("mqueue", "/dev/mqueue", "mqueue"))
186 INFO("failed to mount /dev/mqueue");
189 /* borrowed from iproute2 */
190 extern int get_u16(unsigned short *val
, const char *arg
, int base
)
199 res
= strtoul(arg
, &ptr
, base
);
200 if (!ptr
|| ptr
== arg
|| *ptr
|| res
> 0xFFFF || errno
!= 0)
208 extern int mkdir_p(const char *dir
, mode_t mode
)
210 const char *tmp
= dir
;
211 const char *orig
= dir
;
215 dir
= tmp
+ strspn(tmp
, "/");
216 tmp
= dir
+ strcspn(dir
, "/");
217 makeme
= strndup(orig
, dir
- orig
);
219 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
220 SYSERROR("failed to create directory '%s'", makeme
);
231 extern void remove_trailing_slashes(char *p
)
234 while (--l
>= 0 && (p
[l
] == '/' || p
[l
] == '\n'))
238 static char *copy_global_config_value(char *p
)
245 if (p
[len
-1] == '\n') {
249 retbuf
= malloc(len
+1);
256 #define DEFAULT_VG "lxc"
257 #define DEFAULT_THIN_POOL "lxc"
258 #define DEFAULT_ZFSROOT "lxc"
260 const char *lxc_global_config_value(const char *option_name
)
262 static const char * const options
[][2] = {
263 { "lxc.bdev.lvm.vg", DEFAULT_VG
},
264 { "lxc.bdev.lvm.thin_pool", DEFAULT_THIN_POOL
},
265 { "lxc.bdev.zfs.root", DEFAULT_ZFSROOT
},
266 { "lxc.lxcpath", NULL
},
267 { "lxc.default_config", NULL
},
268 { "lxc.cgroup.pattern", DEFAULT_CGROUP_PATTERN
},
269 { "lxc.cgroup.use", NULL
},
273 /* placed in the thread local storage pool for non-bionic targets */
275 static __thread
const char *values
[sizeof(options
) / sizeof(options
[0])] = { 0 };
277 static const char *values
[sizeof(options
) / sizeof(options
[0])] = { 0 };
279 char *user_config_path
= NULL
;
280 char *user_default_config_path
= NULL
;
281 char *user_lxc_path
= NULL
;
284 const char *user_home
= getenv("HOME");
288 user_config_path
= malloc(sizeof(char) * (22 + strlen(user_home
)));
289 user_default_config_path
= malloc(sizeof(char) * (26 + strlen(user_home
)));
290 user_lxc_path
= malloc(sizeof(char) * (19 + strlen(user_home
)));
292 sprintf(user_config_path
, "%s/.config/lxc/lxc.conf", user_home
);
293 sprintf(user_default_config_path
, "%s/.config/lxc/default.conf", user_home
);
294 sprintf(user_lxc_path
, "%s/.local/share/lxc/", user_home
);
297 user_config_path
= strdup(LXC_GLOBAL_CONF
);
298 user_default_config_path
= strdup(LXC_DEFAULT_CONFIG
);
299 user_lxc_path
= strdup(LXCPATH
);
302 const char * const (*ptr
)[2];
304 char buf
[1024], *p
, *p2
;
307 for (i
= 0, ptr
= options
; (*ptr
)[0]; ptr
++, i
++) {
308 if (!strcmp(option_name
, (*ptr
)[0]))
312 free(user_config_path
);
313 free(user_default_config_path
);
320 free(user_config_path
);
321 free(user_default_config_path
);
326 fin
= fopen_cloexec(user_config_path
, "r");
327 free(user_config_path
);
329 while (fgets(buf
, 1024, fin
)) {
332 p
= strstr(buf
, option_name
);
335 /* see if there was just white space in front
338 for (p2
= buf
; p2
< p
; p2
++) {
339 if (*p2
!= ' ' && *p2
!= '\t')
347 /* see if there was just white space after
350 for (p2
+= strlen(option_name
); p2
< p
; p2
++) {
351 if (*p2
!= ' ' && *p2
!= '\t')
357 while (*p
&& (*p
== ' ' || *p
== '\t')) p
++;
361 free(user_default_config_path
);
363 if (strcmp(option_name
, "lxc.lxcpath") == 0) {
365 user_lxc_path
= copy_global_config_value(p
);
366 remove_trailing_slashes(user_lxc_path
);
367 values
[i
] = user_lxc_path
;
371 values
[i
] = copy_global_config_value(p
);
376 /* could not find value, use default */
377 if (strcmp(option_name
, "lxc.lxcpath") == 0) {
378 remove_trailing_slashes(user_lxc_path
);
379 values
[i
] = user_lxc_path
;
380 free(user_default_config_path
);
382 else if (strcmp(option_name
, "lxc.default_config") == 0) {
383 values
[i
] = user_default_config_path
;
387 free(user_default_config_path
);
389 values
[i
] = (*ptr
)[1];
391 /* special case: if default value is NULL,
392 * and there is no config, don't view that
409 if (geteuid() == 0) {
410 rundir
= strdup(RUNTIME_PATH
);
414 rundir
= getenv("XDG_RUNTIME_DIR");
416 rundir
= strdup(rundir
);
420 INFO("XDG_RUNTIME_DIR isn't set in the environment.");
421 homedir
= getenv("HOME");
423 ERROR("HOME isn't set in the environment.");
427 rundir
= malloc(sizeof(char) * (17 + strlen(homedir
)));
428 sprintf(rundir
, "%s/.cache/lxc/run/", homedir
);
433 int wait_for_pid(pid_t pid
)
438 ret
= waitpid(pid
, &status
, 0);
446 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
451 int lxc_wait_for_pid_status(pid_t pid
)
456 ret
= waitpid(pid
, &status
, 0);
467 ssize_t
lxc_write_nointr(int fd
, const void* buf
, size_t count
)
471 ret
= write(fd
, buf
, count
);
472 if (ret
< 0 && errno
== EINTR
)
477 ssize_t
lxc_read_nointr(int fd
, void* buf
, size_t count
)
481 ret
= read(fd
, buf
, count
);
482 if (ret
< 0 && errno
== EINTR
)
487 ssize_t
lxc_read_nointr_expect(int fd
, void* buf
, size_t count
, const void* expected_buf
)
490 ret
= lxc_read_nointr(fd
, buf
, count
);
493 if ((size_t)ret
!= count
)
495 if (expected_buf
&& memcmp(buf
, expected_buf
, count
) != 0) {
503 #include <gnutls/gnutls.h>
504 #include <gnutls/crypto.h>
506 __attribute__((constructor
))
507 static void gnutls_lxc_init(void)
509 gnutls_global_init();
512 int sha1sum_file(char *fnam
, unsigned char *digest
)
521 f
= fopen_cloexec(fnam
, "r");
523 SYSERROR("Error opening template");
526 if (fseek(f
, 0, SEEK_END
) < 0) {
527 SYSERROR("Error seeking to end of template");
531 if ((flen
= ftell(f
)) < 0) {
532 SYSERROR("Error telling size of template");
536 if (fseek(f
, 0, SEEK_SET
) < 0) {
537 SYSERROR("Error seeking to start of template");
541 if ((buf
= malloc(flen
+1)) == NULL
) {
542 SYSERROR("Out of memory");
546 if (fread(buf
, 1, flen
, f
) != flen
) {
547 SYSERROR("Failure reading template");
553 SYSERROR("Failre closing template");
558 ret
= gnutls_hash_fast(GNUTLS_DIG_SHA1
, buf
, flen
, (void *)digest
);
564 char** lxc_va_arg_list_to_argv(va_list ap
, size_t skip
, int do_strdup
)
567 size_t count
= 1 + skip
;
570 /* first determine size of argument list, we don't want to reallocate
575 char* arg
= va_arg(ap2
, char*);
582 result
= calloc(count
, sizeof(char*));
587 char* arg
= va_arg(ap
, char*);
590 arg
= do_strdup
? strdup(arg
) : arg
;
593 result
[count
++] = arg
;
596 /* calloc has already set last element to NULL*/
604 const char** lxc_va_arg_list_to_argv_const(va_list ap
, size_t skip
)
606 return (const char**)lxc_va_arg_list_to_argv(ap
, skip
, 0);
609 FILE *fopen_cloexec(const char *path
, const char *mode
)
617 if (!strncmp(mode
, "r+", 2)) {
620 } else if (!strncmp(mode
, "r", 1)) {
621 open_mode
= O_RDONLY
;
623 } else if (!strncmp(mode
, "w+", 2)) {
624 open_mode
= O_RDWR
| O_TRUNC
| O_CREAT
;
626 } else if (!strncmp(mode
, "w", 1)) {
627 open_mode
= O_WRONLY
| O_TRUNC
| O_CREAT
;
629 } else if (!strncmp(mode
, "a+", 2)) {
630 open_mode
= O_RDWR
| O_CREAT
| O_APPEND
;
632 } else if (!strncmp(mode
, "a", 1)) {
633 open_mode
= O_WRONLY
| O_CREAT
| O_APPEND
;
636 for (; mode
[step
]; step
++)
637 if (mode
[step
] == 'x')
639 open_mode
|= O_CLOEXEC
;
641 fd
= open(path
, open_mode
, 0666);
645 ret
= fdopen(fd
, mode
);
653 extern struct lxc_popen_FILE
*lxc_popen(const char *command
)
655 struct lxc_popen_FILE
*fp
= NULL
;
656 int parent_end
= -1, child_end
= -1;
660 int r
= pipe2(pipe_fds
, O_CLOEXEC
);
663 ERROR("pipe2 failure");
667 parent_end
= pipe_fds
[0];
668 child_end
= pipe_fds
[1];
672 if (child_pid
== 0) {
674 int child_std_end
= STDOUT_FILENO
;
676 if (child_end
!= child_std_end
) {
677 /* dup2() doesn't dup close-on-exec flag */
678 dup2(child_end
, child_std_end
);
680 /* it's safe not to close child_end here
681 * as it's marked close-on-exec anyway
685 * The descriptor is already the one we will use.
686 * But it must not be marked close-on-exec.
689 if (fcntl(child_end
, F_SETFD
, 0) != 0) {
690 SYSERROR("Failed to remove FD_CLOEXEC from fd.");
697 * This is the main/only reason
698 * why we do our lousy popen() emulation.
703 sigprocmask(SIG_UNBLOCK
, &mask
, NULL
);
706 execl("/bin/sh", "sh", "-c", command
, (char *) NULL
);
716 ERROR("fork failure");
720 fp
= calloc(1, sizeof(*fp
));
722 ERROR("failed to allocate memory");
726 fp
->f
= fdopen(parent_end
, "r");
728 ERROR("fdopen failure");
732 fp
->child_pid
= child_pid
;
741 parent_end
= -1; /* so we do not close it second time */
747 if (parent_end
!= -1)
753 extern int lxc_pclose(struct lxc_popen_FILE
*fp
)
762 child_pid
= fp
->child_pid
;
763 /* free memory (we still need to close file stream) */
768 if (!f
|| fclose(f
)) {
769 ERROR("fclose failure");
774 wait_pid
= waitpid(child_pid
, &wstatus
, 0);
775 } while (wait_pid
== -1 && errno
== EINTR
);
777 if (wait_pid
== -1) {
778 ERROR("waitpid failure");
785 char *lxc_string_replace(const char *needle
, const char *replacement
, const char *haystack
)
787 ssize_t len
= -1, saved_len
= -1;
789 size_t replacement_len
= strlen(replacement
);
790 size_t needle_len
= strlen(needle
);
792 /* should be executed exactly twice */
793 while (len
== -1 || result
== NULL
) {
799 result
= calloc(1, len
+ 1);
807 for (last_p
= (char *)haystack
, p
= strstr(last_p
, needle
); p
; last_p
= p
, p
= strstr(last_p
, needle
)) {
808 part_len
= (ssize_t
)(p
- last_p
);
809 if (result
&& part_len
> 0)
810 memcpy(&result
[len
], last_p
, part_len
);
812 if (result
&& replacement_len
> 0)
813 memcpy(&result
[len
], replacement
, replacement_len
);
814 len
+= replacement_len
;
817 part_len
= strlen(last_p
);
818 if (result
&& part_len
> 0)
819 memcpy(&result
[len
], last_p
, part_len
);
823 /* make sure we did the same thing twice,
824 * once for calculating length, the other
825 * time for copying data */
826 assert(saved_len
== len
);
827 /* make sure we didn't overwrite any buffer,
828 * due to calloc the string should be 0-terminated */
829 assert(result
[len
] == '\0');
834 bool lxc_string_in_array(const char *needle
, const char **haystack
)
836 for (; haystack
&& *haystack
; haystack
++)
837 if (!strcmp(needle
, *haystack
))
842 char *lxc_string_join(const char *sep
, const char **parts
, bool use_as_prefix
)
846 size_t sep_len
= strlen(sep
);
847 size_t result_len
= use_as_prefix
* sep_len
;
849 /* calculate new string length */
850 for (p
= (char **)parts
; *p
; p
++)
851 result_len
+= (p
> (char **)parts
) * sep_len
+ strlen(*p
);
853 result
= calloc(result_len
+ 1, 1);
859 for (p
= (char **)parts
; *p
; p
++) {
860 if (p
> (char **)parts
)
868 char **lxc_normalize_path(const char *path
)
872 size_t components_len
= 0;
875 components
= lxc_string_split(path
, '/');
878 for (p
= components
; *p
; p
++)
881 /* resolve '.' and '..' */
882 for (pos
= 0; pos
< components_len
; ) {
883 if (!strcmp(components
[pos
], ".") || (!strcmp(components
[pos
], "..") && pos
== 0)) {
884 /* eat this element */
885 free(components
[pos
]);
886 memmove(&components
[pos
], &components
[pos
+1], sizeof(char *) * (components_len
- pos
));
888 } else if (!strcmp(components
[pos
], "..")) {
889 /* eat this and the previous element */
890 free(components
[pos
- 1]);
891 free(components
[pos
]);
892 memmove(&components
[pos
-1], &components
[pos
+1], sizeof(char *) * (components_len
- pos
));
903 char *lxc_append_paths(const char *first
, const char *second
)
905 size_t len
= strlen(first
) + strlen(second
) + 1;
906 const char *pattern
= "%s%s";
909 if (second
[0] != '/') {
914 result
= calloc(1, len
);
918 snprintf(result
, len
, pattern
, first
, second
);
922 bool lxc_string_in_list(const char *needle
, const char *haystack
, char _sep
)
924 char *token
, *str
, *saveptr
= NULL
;
925 char sep
[2] = { _sep
, '\0' };
927 if (!haystack
|| !needle
)
930 str
= alloca(strlen(haystack
)+1);
931 strcpy(str
, haystack
);
932 for (; (token
= strtok_r(str
, sep
, &saveptr
)); str
= NULL
) {
933 if (strcmp(needle
, token
) == 0)
940 char **lxc_string_split(const char *string
, char _sep
)
942 char *token
, *str
, *saveptr
= NULL
;
943 char sep
[2] = { _sep
, '\0' };
944 char **result
= NULL
;
945 size_t result_capacity
= 0;
946 size_t result_count
= 0;
950 return calloc(1, sizeof(char *));
952 str
= alloca(strlen(string
)+1);
954 for (; (token
= strtok_r(str
, sep
, &saveptr
)); str
= NULL
) {
955 r
= lxc_grow_array((void ***)&result
, &result_capacity
, result_count
+ 1, 16);
958 result
[result_count
] = strdup(token
);
959 if (!result
[result_count
])
964 /* if we allocated too much, reduce it */
965 return realloc(result
, (result_count
+ 1) * sizeof(char *));
968 lxc_free_array((void **)result
, free
);
973 char **lxc_string_split_and_trim(const char *string
, char _sep
)
975 char *token
, *str
, *saveptr
= NULL
;
976 char sep
[2] = { _sep
, '\0' };
977 char **result
= NULL
;
978 size_t result_capacity
= 0;
979 size_t result_count
= 0;
984 return calloc(1, sizeof(char *));
986 str
= alloca(strlen(string
)+1);
988 for (; (token
= strtok_r(str
, sep
, &saveptr
)); str
= NULL
) {
989 while (token
[0] == ' ' || token
[0] == '\t')
992 while (i
> 0 && (token
[i
- 1] == ' ' || token
[i
- 1] == '\t')) {
996 r
= lxc_grow_array((void ***)&result
, &result_capacity
, result_count
+ 1, 16);
999 result
[result_count
] = strdup(token
);
1000 if (!result
[result_count
])
1005 /* if we allocated too much, reduce it */
1006 return realloc(result
, (result_count
+ 1) * sizeof(char *));
1008 saved_errno
= errno
;
1009 lxc_free_array((void **)result
, free
);
1010 errno
= saved_errno
;
1014 void lxc_free_array(void **array
, lxc_free_fn element_free_fn
)
1017 for (p
= array
; p
&& *p
; p
++)
1018 element_free_fn(*p
);
1022 int lxc_grow_array(void ***array
, size_t* capacity
, size_t new_size
, size_t capacity_increment
)
1024 size_t new_capacity
;
1027 /* first time around, catch some trivial mistakes of the user
1028 * only initializing one of these */
1029 if (!*array
|| !*capacity
) {
1034 new_capacity
= *capacity
;
1035 while (new_size
+ 1 > new_capacity
)
1036 new_capacity
+= capacity_increment
;
1037 if (new_capacity
!= *capacity
) {
1038 /* we have to reallocate */
1039 new_array
= realloc(*array
, new_capacity
* sizeof(void *));
1042 memset(&new_array
[*capacity
], 0, (new_capacity
- (*capacity
)) * sizeof(void *));
1044 *capacity
= new_capacity
;
1047 /* array has sufficient elements */
1051 size_t lxc_array_len(void **array
)
1056 for (p
= array
; p
&& *p
; p
++)
1062 int lxc_write_to_file(const char *filename
, const void* buf
, size_t count
, bool add_newline
)
1064 int fd
, saved_errno
;
1067 fd
= open(filename
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_CLOEXEC
, 0666);
1070 ret
= lxc_write_nointr(fd
, buf
, count
);
1073 if ((size_t)ret
!= count
)
1076 ret
= lxc_write_nointr(fd
, "\n", 1);
1084 saved_errno
= errno
;
1086 errno
= saved_errno
;
1090 int lxc_read_from_file(const char *filename
, void* buf
, size_t count
)
1092 int fd
= -1, saved_errno
;
1095 fd
= open(filename
, O_RDONLY
| O_CLOEXEC
);
1099 if (!buf
|| !count
) {
1102 while ((ret
= read(fd
, buf2
, 100)) > 0)
1107 memset(buf
, 0, count
);
1108 ret
= read(fd
, buf
, count
);
1112 ERROR("read %s: %s", filename
, strerror(errno
));
1114 saved_errno
= errno
;
1116 errno
= saved_errno
;
1120 void **lxc_append_null_to_array(void **array
, size_t count
)
1124 /* Append NULL to the array */
1126 temp
= realloc(array
, (count
+ 1) * sizeof(*array
));
1129 for (i
= 0; i
< count
; i
++)
1135 array
[count
] = NULL
;
1140 int randseed(bool srand_it
)
1143 srand pre-seed function based on /dev/urandom
1145 unsigned int seed
=time(NULL
)+getpid();
1148 f
= fopen("/dev/urandom", "r");
1150 int ret
= fread(&seed
, sizeof(seed
), 1, f
);
1152 DEBUG("unable to fread /dev/urandom, %s, fallback to time+pid rand seed", strerror(errno
));
1162 uid_t
get_ns_uid(uid_t orig
)
1166 uid_t nsid
, hostid
, range
;
1167 FILE *f
= fopen("/proc/self/uid_map", "r");
1171 while (getline(&line
, &sz
, f
) != -1) {
1172 if (sscanf(line
, "%u %u %u", &nsid
, &hostid
, &range
) != 3)
1174 if (hostid
<= orig
&& hostid
+ range
> orig
) {
1175 nsid
+= orig
- hostid
;
1187 bool dir_exists(const char *path
)
1192 ret
= stat(path
, &sb
);
1194 // could be something other than eexist, just say no
1196 return S_ISDIR(sb
.st_mode
);
1199 /* Note we don't use SHA-1 here as we don't want to depend on HAVE_GNUTLS.
1200 * FNV has good anti collision properties and we're not worried
1201 * about pre-image resistance or one-way-ness, we're just trying to make
1202 * the name unique in the 108 bytes of space we have.
1204 uint64_t fnv_64a_buf(void *buf
, size_t len
, uint64_t hval
)
1208 for(bp
= buf
; bp
< (unsigned char *)buf
+ len
; bp
++)
1210 /* xor the bottom with the current octet */
1211 hval
^= (uint64_t)*bp
;
1214 * multiply by the 64 bit FNV magic prime mod 2^64
1216 hval
+= (hval
<< 1) + (hval
<< 4) + (hval
<< 5) +
1217 (hval
<< 7) + (hval
<< 8) + (hval
<< 40);
1224 * Detect whether / is mounted MS_SHARED. The only way I know of to
1225 * check that is through /proc/self/mountinfo.
1226 * I'm only checking for /. If the container rootfs or mount location
1227 * is MS_SHARED, but not '/', then you're out of luck - figuring that
1228 * out would be too much work to be worth it.
1230 #define LINELEN 4096
1231 int detect_shared_rootfs(void)
1233 char buf
[LINELEN
], *p
;
1238 f
= fopen("/proc/self/mountinfo", "r");
1241 while (fgets(buf
, LINELEN
, f
)) {
1242 for (p
= buf
, i
=0; p
&& i
< 4; i
++)
1243 p
= strchr(p
+1, ' ');
1246 p2
= strchr(p
+1, ' ');
1250 if (strcmp(p
+1, "/") == 0) {
1251 // this is '/'. is it shared?
1252 p
= strchr(p2
+1, ' ');
1253 if (p
&& strstr(p
, "shared:")) {
1264 * looking at fs/proc_namespace.c, it appears we can
1265 * actually expect the rootfs entry to very specifically contain
1266 * " - rootfs rootfs "
1267 * IIUC, so long as we've chrooted so that rootfs is not our root,
1268 * the rootfs entry should always be skipped in mountinfo contents.
1270 int detect_ramfs_rootfs(void)
1272 char buf
[LINELEN
], *p
;
1277 f
= fopen("/proc/self/mountinfo", "r");
1280 while (fgets(buf
, LINELEN
, f
)) {
1281 for (p
= buf
, i
=0; p
&& i
< 4; i
++)
1282 p
= strchr(p
+1, ' ');
1285 p2
= strchr(p
+1, ' ');
1289 if (strcmp(p
+1, "/") == 0) {
1290 // this is '/'. is it the ramfs?
1291 p
= strchr(p2
+1, '-');
1292 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
1302 char *on_path(char *cmd
, const char *rootfs
) {
1305 char *saveptr
= NULL
;
1306 char cmdpath
[MAXPATHLEN
];
1309 path
= getenv("PATH");
1313 path
= strdup(path
);
1317 entry
= strtok_r(path
, ":", &saveptr
);
1320 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s/%s", rootfs
, entry
, cmd
);
1322 ret
= snprintf(cmdpath
, MAXPATHLEN
, "%s/%s", entry
, cmd
);
1324 if (ret
< 0 || ret
>= MAXPATHLEN
)
1327 if (access(cmdpath
, X_OK
) == 0) {
1329 return strdup(cmdpath
);
1333 entry
= strtok_r(NULL
, ":", &saveptr
);
1340 bool file_exists(const char *f
)
1342 struct stat statbuf
;
1344 return stat(f
, &statbuf
) == 0;
1347 /* historically lxc-init has been under /usr/lib/lxc and under
1348 * /usr/lib/$ARCH/lxc. It now lives as $prefix/sbin/init.lxc.
1350 char *choose_init(const char *rootfs
)
1353 int ret
, env_set
= 0;
1356 if (!getenv("PATH")) {
1357 if (setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 0))
1358 SYSERROR("Failed to setenv");
1362 retv
= on_path("init.lxc", rootfs
);
1365 if (unsetenv("PATH"))
1366 SYSERROR("Failed to unsetenv");
1372 retv
= malloc(PATH_MAX
);
1377 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/init.lxc", rootfs
, SBINDIR
);
1379 ret
= snprintf(retv
, PATH_MAX
, SBINDIR
"/init.lxc");
1380 if (ret
< 0 || ret
>= PATH_MAX
) {
1381 ERROR("pathname too long");
1385 ret
= stat(retv
, &mystat
);
1390 ret
= snprintf(retv
, PATH_MAX
, "%s/%s/lxc/lxc-init", rootfs
, LXCINITDIR
);
1392 ret
= snprintf(retv
, PATH_MAX
, LXCINITDIR
"/lxc/lxc-init");
1393 if (ret
< 0 || ret
>= PATH_MAX
) {
1394 ERROR("pathname too long");
1398 ret
= stat(retv
, &mystat
);
1403 ret
= snprintf(retv
, PATH_MAX
, "%s/usr/lib/lxc/lxc-init", rootfs
);
1405 ret
= snprintf(retv
, PATH_MAX
, "/usr/lib/lxc/lxc-init");
1406 if (ret
< 0 || ret
>= PATH_MAX
) {
1407 ERROR("pathname too long");
1410 ret
= stat(retv
, &mystat
);
1415 ret
= snprintf(retv
, PATH_MAX
, "%s/sbin/lxc-init", rootfs
);
1417 ret
= snprintf(retv
, PATH_MAX
, "/sbin/lxc-init");
1418 if (ret
< 0 || ret
>= PATH_MAX
) {
1419 ERROR("pathname too long");
1422 ret
= stat(retv
, &mystat
);
1427 * Last resort, look for the statically compiled init.lxc which we
1428 * hopefully bind-mounted in.
1429 * If we are called during container setup, and we get to this point,
1430 * then the init.lxc.static from the host will need to be bind-mounted
1431 * in. So we return NULL here to indicate that.
1436 ret
= snprintf(retv
, PATH_MAX
, "/init.lxc.static");
1437 if (ret
< 0 || ret
>= PATH_MAX
) {
1438 WARN("Nonsense - name /lxc.init.static too long");
1441 ret
= stat(retv
, &mystat
);
1450 int print_to_file(const char *file
, const char *content
)
1455 f
= fopen(file
, "w");
1458 if (fprintf(f
, "%s", content
) != strlen(content
))