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 /* Properly support loop devices on 32bit systems. */
27 #define _FILE_OFFSET_BITS 64
36 #include <linux/loop.h>
37 #include <linux/magic.h>
38 #include <linux/types.h>
39 #include <sys/syscall.h>
40 #include <sys/types.h>
43 #ifdef HAVE_LINUX_MEMFD_H
44 #include <linux/memfd.h>
47 #include "initutils.h"
49 /* Define __S_ISTYPE if missing from the C library. */
51 #define __S_ISTYPE(mode, mask) (((mode)&S_IFMT) == (mask))
56 #define CAP_SETFCAP 31
59 #ifndef CAP_MAC_OVERRIDE
60 #define CAP_MAC_OVERRIDE 32
64 #define CAP_MAC_ADMIN 33
68 #ifndef PR_CAPBSET_DROP
69 #define PR_CAPBSET_DROP 24
72 #ifndef LO_FLAGS_AUTOCLEAR
73 #define LO_FLAGS_AUTOCLEAR 4
84 /* needed for cgroup automount checks, regardless of whether we
85 * have included linux/capability.h or not */
87 #define CAP_SYS_ADMIN 21
90 #ifndef CGROUP_SUPER_MAGIC
91 #define CGROUP_SUPER_MAGIC 0x27e0eb
94 #ifndef CGROUP2_SUPER_MAGIC
95 #define CGROUP2_SUPER_MAGIC 0x63677270
99 /* Maximum number for 64 bit integer is a string with 21 digits: 2^64 - 1 = 21 */
100 #define LXC_NUMSTRLEN64 21
101 #define LXC_LINELEN 4096
102 #define LXC_IDMAPLEN 4096
103 #define LXC_MAX_BUFFER 4096
106 * <pid-as-str> = LXC_NUMSTRLEN64
110 * <fd-as-str> = LXC_NUMSTRLEN64
114 #define LXC_PROC_PID_FD_LEN (6 + LXC_NUMSTRLEN64 + 4 + LXC_NUMSTRLEN64 + 1)
116 /* returns 1 on success, 0 if there were any failures */
117 extern int lxc_rmdir_onedev(const char *path
, const char *exclude
);
118 extern int get_u16(unsigned short *val
, const char *arg
, int base
);
119 extern int mkdir_p(const char *dir
, mode_t mode
);
120 extern char *get_rundir(void);
122 /* Define getline() if missing from the C library */
125 #include <../include/getline.h>
129 #if !defined(__NR_setns) && !defined(__NR_set_ns)
130 #if defined(__x86_64__)
131 #define __NR_setns 308
132 #elif defined(__i386__)
133 #define __NR_setns 346
134 #elif defined(__arm__)
135 #define __NR_setns 375
136 #elif defined(__aarch64__)
137 #define __NR_setns 375
138 #elif defined(__powerpc__)
139 #define __NR_setns 350
140 #elif defined(__s390__)
141 #define __NR_setns 339
145 /* Define setns() if missing from the C library */
147 static inline int setns(int fd
, int nstype
)
150 return syscall(__NR_setns
, fd
, nstype
);
151 #elif defined(__NR_set_ns)
152 return syscall(__NR_set_ns
, fd
, nstype
);
160 /* Define sethostname() if missing from the C library */
161 #ifndef HAVE_SETHOSTNAME
162 static inline int sethostname(const char * name
, size_t len
)
164 #ifdef __NR_sethostname
165 return syscall(__NR_sethostname
, name
, len
);
173 /* Define unshare() if missing from the C library */
175 static inline int unshare(int flags
)
178 return syscall(__NR_unshare
, flags
);
185 extern int unshare(int);
188 /* Define signalfd() if missing from the C library */
189 #ifdef HAVE_SYS_SIGNALFD_H
190 # include <sys/signalfd.h>
192 /* assume kernel headers are too old */
194 struct signalfd_siginfo
204 uint32_t ssi_overrun
;
215 # ifndef __NR_signalfd4
216 /* assume kernel headers are too old */
218 # define __NR_signalfd4 327
220 # define __NR_signalfd4 289
222 # define __NR_signalfd4 313
224 # define __NR_signalfd4 322
226 # define __NR_signalfd4 355
227 # elif __mips__ && _MIPS_SIM == _ABIO32
228 # define __NR_signalfd4 4324
229 # elif __mips__ && _MIPS_SIM == _ABI64
230 # define __NR_signalfd4 5283
231 # elif __mips__ && _MIPS_SIM == _ABIN32
232 # define __NR_signalfd4 6287
236 # ifndef __NR_signalfd
237 /* assume kernel headers are too old */
239 # define __NR_signalfd 321
241 # define __NR_signalfd 282
243 # define __NR_signalfd 305
245 # define __NR_signalfd 316
247 # define __NR_signalfd 349
248 # elif __mips__ && _MIPS_SIM == _ABIO32
249 # define __NR_signalfd 4317
250 # elif __mips__ && _MIPS_SIM == _ABI64
251 # define __NR_signalfd 5276
252 # elif __mips__ && _MIPS_SIM == _ABIN32
253 # define __NR_signalfd 6280
257 static inline int signalfd(int fd
, const sigset_t
*mask
, int flags
)
261 retval
= syscall (__NR_signalfd4
, fd
, mask
, _NSIG
/ 8, flags
);
262 if (errno
== ENOSYS
&& flags
== 0)
263 retval
= syscall (__NR_signalfd
, fd
, mask
, _NSIG
/ 8);
269 #ifndef LO_FLAGS_AUTOCLEAR
270 #define LO_FLAGS_AUTOCLEAR 4
273 #ifndef LOOP_CTL_GET_FREE
274 #define LOOP_CTL_GET_FREE 0x4C82
279 #define MFD_CLOEXEC 0x0001U
282 #ifndef MFD_ALLOW_SEALING
283 #define MFD_ALLOW_SEALING 0x0002U
286 #ifndef HAVE_MEMFD_CREATE
287 static inline int memfd_create(const char *name
, unsigned int flags
) {
288 #ifndef __NR_memfd_create
290 #define __NR_memfd_create 356
291 #elif defined __x86_64__
292 #define __NR_memfd_create 319
293 #elif defined __arm__
294 #define __NR_memfd_create 385
295 #elif defined __aarch64__
296 #define __NR_memfd_create 279
297 #elif defined __s390__
298 #define __NR_memfd_create 350
299 #elif defined __powerpc__
300 #define __NR_memfd_create 360
301 #elif defined __sparc__
302 #define __NR_memfd_create 348
303 #elif defined __blackfin__
304 #define __NR_memfd_create 390
305 #elif defined __ia64__
306 #define __NR_memfd_create 1340
307 #elif defined _MIPS_SIM
308 #if _MIPS_SIM == _MIPS_SIM_ABI32
309 #define __NR_memfd_create 4354
311 #if _MIPS_SIM == _MIPS_SIM_NABI32
312 #define __NR_memfd_create 6318
314 #if _MIPS_SIM == _MIPS_SIM_ABI64
315 #define __NR_memfd_create 5314
319 #ifdef __NR_memfd_create
320 return syscall(__NR_memfd_create
, name
, flags
);
327 extern int memfd_create(const char *name
, unsigned int flags
);
330 static inline int lxc_set_cloexec(int fd
)
332 return fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
335 /* Struct to carry child pid from lxc_popen() to lxc_pclose().
336 * Not an opaque struct to allow direct access to the underlying FILE *
337 * (i.e., struct lxc_popen_FILE *file; fgets(buf, sizeof(buf), file->f))
338 * without additional wrappers.
340 struct lxc_popen_FILE
{
346 /* popen(command, "re") replacement that restores default signal mask
347 * via sigprocmask(2) (unblocks all signals) after fork(2) but prior to calling exec(3).
348 * In short, popen(command, "re") does pipe() + fork() + exec()
349 * while lxc_popen(command) does pipe() + fork() + sigprocmask() + exec().
350 * Returns pointer to struct lxc_popen_FILE, that should be freed with lxc_pclose().
351 * On error returns NULL.
353 extern struct lxc_popen_FILE
*lxc_popen(const char *command
);
355 /* pclose() replacement to be used on struct lxc_popen_FILE *,
356 * returned by lxc_popen().
357 * Waits for associated process to terminate, returns its exit status and
358 * frees resources, pointed to by struct lxc_popen_FILE *.
360 extern int lxc_pclose(struct lxc_popen_FILE
*fp
);
363 * BUILD_BUG_ON - break compile if a condition is true.
364 * @condition: the condition which the compiler should know is false.
366 * If you have some code which relies on certain constants being equal, or
367 * other compile-time-evaluated condition, you should use BUILD_BUG_ON to
368 * detect if someone changes it.
370 * The implementation uses gcc's reluctance to create a negative array, but
371 * gcc (as of 4.4) only emits that error for obvious cases (eg. not arguments
372 * to inline functions). So as a fallback we use the optimizer; if it can't
373 * prove the condition is false, it will cause a link error on the undefined
374 * "__build_bug_on_failed". This error message can be harder to track down
375 * though, hence the two different methods.
378 #define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
380 extern int __build_bug_on_failed
;
381 #define BUILD_BUG_ON(condition) \
383 ((void)sizeof(char[1 - 2*!!(condition)])); \
384 if (condition) __build_bug_on_failed = 1; \
389 * wait on a child we forked
391 extern int wait_for_pid(pid_t pid
);
392 extern int lxc_wait_for_pid_status(pid_t pid
);
394 /* send and receive buffers completely */
395 extern ssize_t
lxc_write_nointr(int fd
, const void* buf
, size_t count
);
396 extern ssize_t
lxc_read_nointr(int fd
, void* buf
, size_t count
);
397 extern ssize_t
lxc_read_nointr_expect(int fd
, void *buf
, size_t count
,
398 const void *expected_buf
);
400 #define SHA_DIGEST_LENGTH 20
401 extern int sha1sum_file(char *fnam
, unsigned char *md_value
);
404 /* read and write whole files */
405 extern int lxc_write_to_file(const char *filename
, const void *buf
,
406 size_t count
, bool add_newline
, mode_t mode
);
407 extern int lxc_read_from_file(const char *filename
, void* buf
, size_t count
);
409 /* convert variadic argument lists to arrays (for execl type argument lists) */
410 extern char** lxc_va_arg_list_to_argv(va_list ap
, size_t skip
, int do_strdup
);
411 extern const char** lxc_va_arg_list_to_argv_const(va_list ap
, size_t skip
);
413 /* Some simple string functions; if they return pointers, they are allocated
416 extern char *lxc_string_replace(const char *needle
, const char *replacement
,
417 const char *haystack
);
418 extern bool lxc_string_in_array(const char *needle
, const char **haystack
);
419 extern char *lxc_string_join(const char *sep
, const char **parts
,
421 /* Normalize and split path: Leading and trailing / are removed, multiple
422 * / are compactified, .. and . are resolved (.. on the top level is considered
426 * foo/../bar -> { bar, NULL }
428 * ./bar/baz/.. -> { bar, NULL }
429 * foo//bar -> { foo, bar, NULL }
431 extern char **lxc_normalize_path(const char *path
);
432 /* remove multiple slashes from the path, e.g. ///foo//bar -> /foo/bar */
433 extern char *lxc_deslashify(const char *path
);
434 extern char *lxc_append_paths(const char *first
, const char *second
);
435 /* Note: the following two functions use strtok(), so they will never
436 * consider an empty element, even if two delimiters are next to
439 extern bool lxc_string_in_list(const char *needle
, const char *haystack
,
441 extern char **lxc_string_split(const char *string
, char sep
);
442 extern char **lxc_string_split_and_trim(const char *string
, char sep
);
443 extern char **lxc_string_split_quoted(char *string
);
444 /* Append string to NULL-terminated string array. */
445 extern int lxc_append_string(char ***list
, char *entry
);
447 /* some simple array manipulation utilities */
448 typedef void (*lxc_free_fn
)(void *);
449 typedef void *(*lxc_dup_fn
)(void *);
450 extern int lxc_grow_array(void ***array
, size_t *capacity
, size_t new_size
,
451 size_t capacity_increment
);
452 extern void lxc_free_array(void **array
, lxc_free_fn element_free_fn
);
453 extern size_t lxc_array_len(void **array
);
455 extern void **lxc_append_null_to_array(void **array
, size_t count
);
457 /* initialize rand with urandom */
458 extern int randseed(bool);
460 /* are we unprivileged with respect to our namespaces */
461 inline static bool am_guest_unpriv(void) {
462 return geteuid() != 0;
465 /* are we unprivileged with respect to init_user_ns */
466 inline static bool am_host_unpriv(void)
469 uid_t user
, host
, count
;
475 /* Now: are we in a user namespace? Because then we're also
478 f
= fopen("/proc/self/uid_map", "r");
483 ret
= fscanf(f
, "%u %u %u", &user
, &host
, &count
);
489 if (user
!= 0 || host
!= 0 || count
!= UINT32_MAX
)
495 * parse /proc/self/uid_map to find what @orig maps to
497 extern uid_t
get_ns_uid(uid_t orig
);
499 extern bool dir_exists(const char *path
);
501 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
502 extern uint64_t fnv_64a_buf(void *buf
, size_t len
, uint64_t hval
);
504 extern int detect_shared_rootfs(void);
505 extern bool detect_ramfs_rootfs(void);
506 extern char *on_path(const char *cmd
, const char *rootfs
);
507 extern bool file_exists(const char *f
);
508 extern bool cgns_supported(void);
509 extern char *choose_init(const char *rootfs
);
510 extern int print_to_file(const char *file
, const char *content
);
511 extern bool switch_to_ns(pid_t pid
, const char *ns
);
512 extern int is_dir(const char *path
);
513 extern char *get_template_path(const char *t
);
514 extern int safe_mount(const char *src
, const char *dest
, const char *fstype
,
515 unsigned long flags
, const void *data
,
517 extern int lxc_mount_proc_if_needed(const char *rootfs
);
518 extern int open_devnull(void);
519 extern int set_stdfds(int fd
);
520 extern int null_stdfds(void);
521 extern int lxc_count_file_lines(const char *fn
);
522 extern int lxc_preserve_ns(const int pid
, const char *ns
);
524 /* Check whether a signal is blocked by a process. */
525 extern bool task_blocking_signal(pid_t pid
, int signal
);
527 /* Helper functions to parse numbers. */
528 extern int lxc_safe_uint(const char *numstr
, unsigned int *converted
);
529 extern int lxc_safe_int(const char *numstr
, int *converted
);
530 extern int lxc_safe_long(const char *numstr
, long int *converted
);
531 extern int lxc_safe_long_long(const char *numstr
, long long int *converted
);
532 extern int lxc_safe_ulong(const char *numstr
, unsigned long *converted
);
533 extern int lxc_safe_uint64(const char *numstr
, uint64_t *converted
);
534 /* Handles B, kb, MB, GB. Detects overflows and reports -ERANGE. */
535 extern int parse_byte_size_string(const char *s
, int64_t *converted
);
537 /* Switch to a new uid and gid. */
538 extern int lxc_switch_uid_gid(uid_t uid
, gid_t gid
);
539 extern int lxc_setgroups(int size
, gid_t list
[]);
541 /* Find an unused loop device and associate it with source. */
542 extern int lxc_prepare_loop_dev(const char *source
, char *loop_dev
, int flags
);
544 /* Clear all mounts on a given node.
545 * >= 0 successfully cleared. The number returned is the number of umounts
547 * < 0 error umounting. Return -errno.
549 extern int lxc_unstack_mountpoint(const char *path
, bool lazy
);
552 * run_command runs a command and collect it's std{err,out} output in buf.
554 * @param[out] buf The buffer where the commands std{err,out] output will be
555 * read into. If no output was produced, buf will be memset
557 * @param[in] buf_size The size of buf. This function will reserve one byte for
559 * @param[in] child_fn The function to be run in the child process. This
560 * function must exec.
561 * @param[in] args Arguments to be passed to child_fn.
563 extern int run_command(char *buf
, size_t buf_size
, int (*child_fn
)(void *),
566 /* Concatenate all passed-in strings into one path. Do not fail. If any piece
567 * is not prefixed with '/', add a '/'.
569 __attribute__((sentinel
)) extern char *must_make_path(const char *first
, ...);
570 __attribute__((sentinel
)) extern char *must_append_path(char *first
, ...);
572 /* return copy of string @entry; do not fail. */
573 extern char *must_copy_string(const char *entry
);
575 /* Re-alllocate a pointer, do not fail */
576 extern void *must_realloc(void *orig
, size_t sz
);
578 /* __typeof__ should be safe to use with all compilers. */
579 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
580 extern bool has_fs_type(const char *path
, fs_type_magic magic_val
);
581 extern bool is_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
);
582 extern bool lxc_nic_exists(char *nic
);
583 extern int lxc_make_tmpfile(char *template, bool rm
);
585 static inline uint64_t lxc_getpagesize(void)
589 pgsz
= sysconf(_SC_PAGESIZE
);
596 /* If n is not a power of 2 this function will return the next power of 2
597 * greater than that number. Note that this function always returns the *next*
598 * power of 2 *greater* that number not the *nearest*. For example, passing 1025
599 * as argument this function will return 2048 although the closest power of 2
601 * If the caller passes in 0 they will receive 0 in return since this is invalid
602 * input and 0 is not a power of 2.
604 extern uint64_t lxc_find_next_power2(uint64_t n
);
606 static inline pid_t
lxc_raw_gettid(void)
609 return syscall(SYS_gettid
);
611 return lxc_raw_getpid();
615 /* Set a signal the child process will receive after the parent has died. */
616 extern int lxc_set_death_signal(int signal
);
618 #endif /* __LXC_UTILS_H */