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 <sys/syscall.h>
39 #include <sys/types.h>
42 #ifdef HAVE_LINUX_MEMFD_H
43 #include <linux/memfd.h>
46 #include "initutils.h"
48 /* Define __S_ISTYPE if missing from the C library. */
50 #define __S_ISTYPE(mode, mask) (((mode)&S_IFMT) == (mask))
55 #define CAP_SETFCAP 31
58 #ifndef CAP_MAC_OVERRIDE
59 #define CAP_MAC_OVERRIDE 32
63 #define CAP_MAC_ADMIN 33
67 #ifndef PR_CAPBSET_DROP
68 #define PR_CAPBSET_DROP 24
71 #ifndef LO_FLAGS_AUTOCLEAR
72 #define LO_FLAGS_AUTOCLEAR 4
83 /* needed for cgroup automount checks, regardless of whether we
84 * have included linux/capability.h or not */
86 #define CAP_SYS_ADMIN 21
89 #ifndef CGROUP_SUPER_MAGIC
90 #define CGROUP_SUPER_MAGIC 0x27e0eb
93 #ifndef CGROUP2_SUPER_MAGIC
94 #define CGROUP2_SUPER_MAGIC 0x63677270
98 /* Maximum number for 64 bit integer is a string with 21 digits: 2^64 - 1 = 21 */
99 #define LXC_NUMSTRLEN64 21
100 #define LXC_LINELEN 4096
101 #define LXC_IDMAPLEN 4096
103 /* returns 1 on success, 0 if there were any failures */
104 extern int lxc_rmdir_onedev(const char *path
, const char *exclude
);
105 extern int get_u16(unsigned short *val
, const char *arg
, int base
);
106 extern int mkdir_p(const char *dir
, mode_t mode
);
107 extern char *get_rundir(void);
109 /* Define getline() if missing from the C library */
112 #include <../include/getline.h>
116 /* Define setns() if missing from the C library */
118 static inline int setns(int fd
, int nstype
)
121 return syscall(__NR_setns
, fd
, nstype
);
122 #elif defined(__NR_set_ns)
123 return syscall(__NR_set_ns
, fd
, nstype
);
131 /* Define sethostname() if missing from the C library */
132 #ifndef HAVE_SETHOSTNAME
133 static inline int sethostname(const char * name
, size_t len
)
135 #ifdef __NR_sethostname
136 return syscall(__NR_sethostname
, name
, len
);
144 /* Define unshare() if missing from the C library */
146 static inline int unshare(int flags
)
149 return syscall(__NR_unshare
, flags
);
156 extern int unshare(int);
159 /* Define signalfd() if missing from the C library */
160 #ifdef HAVE_SYS_SIGNALFD_H
161 # include <sys/signalfd.h>
163 /* assume kernel headers are too old */
165 struct signalfd_siginfo
175 uint32_t ssi_overrun
;
186 # ifndef __NR_signalfd4
187 /* assume kernel headers are too old */
189 # define __NR_signalfd4 327
191 # define __NR_signalfd4 289
193 # define __NR_signalfd4 313
195 # define __NR_signalfd4 322
197 # define __NR_signalfd4 355
198 # elif __mips__ && _MIPS_SIM == _ABIO32
199 # define __NR_signalfd4 4324
200 # elif __mips__ && _MIPS_SIM == _ABI64
201 # define __NR_signalfd4 5283
202 # elif __mips__ && _MIPS_SIM == _ABIN32
203 # define __NR_signalfd4 6287
207 # ifndef __NR_signalfd
208 /* assume kernel headers are too old */
210 # define __NR_signalfd 321
212 # define __NR_signalfd 282
214 # define __NR_signalfd 305
216 # define __NR_signalfd 316
218 # define __NR_signalfd 349
219 # elif __mips__ && _MIPS_SIM == _ABIO32
220 # define __NR_signalfd 4317
221 # elif __mips__ && _MIPS_SIM == _ABI64
222 # define __NR_signalfd 5276
223 # elif __mips__ && _MIPS_SIM == _ABIN32
224 # define __NR_signalfd 6280
228 static inline int signalfd(int fd
, const sigset_t
*mask
, int flags
)
232 retval
= syscall (__NR_signalfd4
, fd
, mask
, _NSIG
/ 8, flags
);
233 if (errno
== ENOSYS
&& flags
== 0)
234 retval
= syscall (__NR_signalfd
, fd
, mask
, _NSIG
/ 8);
240 #ifndef LO_FLAGS_AUTOCLEAR
241 #define LO_FLAGS_AUTOCLEAR 4
244 #ifndef LOOP_CTL_GET_FREE
245 #define LOOP_CTL_GET_FREE 0x4C82
250 #define MFD_CLOEXEC 0x0001U
253 #ifndef MFD_ALLOW_SEALING
254 #define MFD_ALLOW_SEALING 0x0002U
257 #ifndef HAVE_MEMFD_CREATE
258 static inline int memfd_create(const char *name
, unsigned int flags
) {
259 #ifndef __NR_memfd_create
261 #define __NR_memfd_create 356
262 #elif defined __x86_64__
263 #define __NR_memfd_create 319
264 #elif defined __arm__
265 #define __NR_memfd_create 385
266 #elif defined __aarch64__
267 #define __NR_memfd_create 279
268 #elif defined __s390__
269 #define __NR_memfd_create 350
270 #elif defined __powerpc__
271 #define __NR_memfd_create 360
272 #elif defined __sparc__
273 #define __NR_memfd_create 348
274 #elif defined __blackfin__
275 #define __NR_memfd_create 390
276 #elif defined __ia64__
277 #define __NR_memfd_create 1340
278 #elif defined _MIPS_SIM
279 #if _MIPS_SIM == _MIPS_SIM_ABI32
280 #define __NR_memfd_create 4354
282 #if _MIPS_SIM == _MIPS_SIM_NABI32
283 #define __NR_memfd_create 6318
285 #if _MIPS_SIM == _MIPS_SIM_ABI64
286 #define __NR_memfd_create 5314
290 #ifdef __NR_memfd_create
291 return syscall(__NR_memfd_create
, name
, flags
);
298 extern int memfd_create(const char *name
, unsigned int flags
);
301 static inline int lxc_set_cloexec(int fd
)
303 return fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
306 /* Struct to carry child pid from lxc_popen() to lxc_pclose().
307 * Not an opaque struct to allow direct access to the underlying FILE *
308 * (i.e., struct lxc_popen_FILE *file; fgets(buf, sizeof(buf), file->f))
309 * without additional wrappers.
311 struct lxc_popen_FILE
{
317 /* popen(command, "re") replacement that restores default signal mask
318 * via sigprocmask(2) (unblocks all signals) after fork(2) but prior to calling exec(3).
319 * In short, popen(command, "re") does pipe() + fork() + exec()
320 * while lxc_popen(command) does pipe() + fork() + sigprocmask() + exec().
321 * Returns pointer to struct lxc_popen_FILE, that should be freed with lxc_pclose().
322 * On error returns NULL.
324 extern struct lxc_popen_FILE
*lxc_popen(const char *command
);
326 /* pclose() replacement to be used on struct lxc_popen_FILE *,
327 * returned by lxc_popen().
328 * Waits for associated process to terminate, returns its exit status and
329 * frees resources, pointed to by struct lxc_popen_FILE *.
331 extern int lxc_pclose(struct lxc_popen_FILE
*fp
);
334 * BUILD_BUG_ON - break compile if a condition is true.
335 * @condition: the condition which the compiler should know is false.
337 * If you have some code which relies on certain constants being equal, or
338 * other compile-time-evaluated condition, you should use BUILD_BUG_ON to
339 * detect if someone changes it.
341 * The implementation uses gcc's reluctance to create a negative array, but
342 * gcc (as of 4.4) only emits that error for obvious cases (eg. not arguments
343 * to inline functions). So as a fallback we use the optimizer; if it can't
344 * prove the condition is false, it will cause a link error on the undefined
345 * "__build_bug_on_failed". This error message can be harder to track down
346 * though, hence the two different methods.
349 #define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
351 extern int __build_bug_on_failed
;
352 #define BUILD_BUG_ON(condition) \
354 ((void)sizeof(char[1 - 2*!!(condition)])); \
355 if (condition) __build_bug_on_failed = 1; \
360 * wait on a child we forked
362 extern int wait_for_pid(pid_t pid
);
363 extern int lxc_wait_for_pid_status(pid_t pid
);
365 /* send and receive buffers completely */
366 extern ssize_t
lxc_write_nointr(int fd
, const void* buf
, size_t count
);
367 extern ssize_t
lxc_read_nointr(int fd
, void* buf
, size_t count
);
368 extern ssize_t
lxc_read_nointr_expect(int fd
, void *buf
, size_t count
,
369 const void *expected_buf
);
371 #define SHA_DIGEST_LENGTH 20
372 extern int sha1sum_file(char *fnam
, unsigned char *md_value
);
375 /* read and write whole files */
376 extern int lxc_write_to_file(const char *filename
, const void *buf
,
377 size_t count
, bool add_newline
);
378 extern int lxc_read_from_file(const char *filename
, void* buf
, size_t count
);
380 /* convert variadic argument lists to arrays (for execl type argument lists) */
381 extern char** lxc_va_arg_list_to_argv(va_list ap
, size_t skip
, int do_strdup
);
382 extern const char** lxc_va_arg_list_to_argv_const(va_list ap
, size_t skip
);
384 /* Some simple string functions; if they return pointers, they are allocated
387 extern char *lxc_string_replace(const char *needle
, const char *replacement
,
388 const char *haystack
);
389 extern bool lxc_string_in_array(const char *needle
, const char **haystack
);
390 extern char *lxc_string_join(const char *sep
, const char **parts
,
392 /* Normalize and split path: Leading and trailing / are removed, multiple
393 * / are compactified, .. and . are resolved (.. on the top level is considered
397 * foo/../bar -> { bar, NULL }
399 * ./bar/baz/.. -> { bar, NULL }
400 * foo//bar -> { foo, bar, NULL }
402 extern char **lxc_normalize_path(const char *path
);
403 /* remove multiple slashes from the path, e.g. ///foo//bar -> /foo/bar */
404 extern char *lxc_deslashify(const char *path
);
405 extern char *lxc_append_paths(const char *first
, const char *second
);
406 /* Note: the following two functions use strtok(), so they will never
407 * consider an empty element, even if two delimiters are next to
410 extern bool lxc_string_in_list(const char *needle
, const char *haystack
,
412 extern char **lxc_string_split(const char *string
, char sep
);
413 extern char **lxc_string_split_and_trim(const char *string
, char sep
);
414 extern char **lxc_string_split_quoted(char *string
);
415 /* Append string to NULL-terminated string array. */
416 extern int lxc_append_string(char ***list
, char *entry
);
418 /* some simple array manipulation utilities */
419 typedef void (*lxc_free_fn
)(void *);
420 typedef void *(*lxc_dup_fn
)(void *);
421 extern int lxc_grow_array(void ***array
, size_t *capacity
, size_t new_size
,
422 size_t capacity_increment
);
423 extern void lxc_free_array(void **array
, lxc_free_fn element_free_fn
);
424 extern size_t lxc_array_len(void **array
);
426 extern void **lxc_append_null_to_array(void **array
, size_t count
);
428 /* mmap() wrapper. lxc_strmmap() will take care to \0-terminate files so that
429 * normal string-handling functions can be used on the buffer. */
430 extern void *lxc_strmmap(void *addr
, size_t length
, int prot
, int flags
, int fd
,
432 /* munmap() wrapper. Use it to free memory mmap()ed with lxc_strmmap(). */
433 extern int lxc_strmunmap(void *addr
, size_t length
);
435 /* initialize rand with urandom */
436 extern int randseed(bool);
438 /* are we unprivileged with respect to our namespaces */
439 inline static bool am_guest_unpriv(void) {
440 return geteuid() != 0;
443 /* are we unprivileged with respect to init_user_ns */
444 inline static bool am_host_unpriv(void)
447 uid_t user
, host
, count
;
453 /* Now: are we in a user namespace? Because then we're also
456 f
= fopen("/proc/self/uid_map", "r");
461 ret
= fscanf(f
, "%u %u %u", &user
, &host
, &count
);
467 if (user
!= 0 || host
!= 0 || count
!= UINT32_MAX
)
473 * parse /proc/self/uid_map to find what @orig maps to
475 extern uid_t
get_ns_uid(uid_t orig
);
477 extern bool dir_exists(const char *path
);
479 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
480 extern uint64_t fnv_64a_buf(void *buf
, size_t len
, uint64_t hval
);
482 extern int detect_shared_rootfs(void);
483 extern bool detect_ramfs_rootfs(void);
484 extern char *on_path(const char *cmd
, const char *rootfs
);
485 extern bool file_exists(const char *f
);
486 extern bool cgns_supported(void);
487 extern char *choose_init(const char *rootfs
);
488 extern int print_to_file(const char *file
, const char *content
);
489 extern bool switch_to_ns(pid_t pid
, const char *ns
);
490 extern int is_dir(const char *path
);
491 extern char *get_template_path(const char *t
);
492 extern int safe_mount(const char *src
, const char *dest
, const char *fstype
,
493 unsigned long flags
, const void *data
,
495 extern int lxc_mount_proc_if_needed(const char *rootfs
);
496 extern int open_devnull(void);
497 extern int set_stdfds(int fd
);
498 extern int null_stdfds(void);
499 extern int lxc_count_file_lines(const char *fn
);
500 extern int lxc_preserve_ns(const int pid
, const char *ns
);
502 /* Check whether a signal is blocked by a process. */
503 extern bool task_blocking_signal(pid_t pid
, int signal
);
505 /* Helper functions to parse numbers. */
506 extern int lxc_safe_uint(const char *numstr
, unsigned int *converted
);
507 extern int lxc_safe_int(const char *numstr
, int *converted
);
508 extern int lxc_safe_long(const char *numstr
, long int *converted
);
509 extern int lxc_safe_long_long(const char *numstr
, long long int *converted
);
510 extern int lxc_safe_ulong(const char *numstr
, unsigned long *converted
);
511 /* Handles B, kb, MB, GB. Detects overflows and reports -ERANGE. */
512 extern int parse_byte_size_string(const char *s
, int64_t *converted
);
514 /* Switch to a new uid and gid. */
515 extern int lxc_switch_uid_gid(uid_t uid
, gid_t gid
);
516 extern int lxc_setgroups(int size
, gid_t list
[]);
518 /* Find an unused loop device and associate it with source. */
519 extern int lxc_prepare_loop_dev(const char *source
, char *loop_dev
, int flags
);
521 /* Clear all mounts on a given node.
522 * >= 0 successfully cleared. The number returned is the number of umounts
524 * < 0 error umounting. Return -errno.
526 extern int lxc_unstack_mountpoint(const char *path
, bool lazy
);
529 * run_command runs a command and collect it's std{err,out} output in buf.
531 * @param[out] buf The buffer where the commands std{err,out] output will be
532 * read into. If no output was produced, buf will be memset
534 * @param[in] buf_size The size of buf. This function will reserve one byte for
536 * @param[in] child_fn The function to be run in the child process. This
537 * function must exec.
538 * @param[in] args Arguments to be passed to child_fn.
540 extern int run_command(char *buf
, size_t buf_size
, int (*child_fn
)(void *),
543 /* Concatenate all passed-in strings into one path. Do not fail. If any piece
544 * is not prefixed with '/', add a '/'.
546 __attribute__((sentinel
)) extern char *must_make_path(const char *first
, ...);
547 __attribute__((sentinel
)) extern char *must_append_path(char *first
, ...);
549 /* return copy of string @entry; do not fail. */
550 extern char *must_copy_string(const char *entry
);
552 /* Re-alllocate a pointer, do not fail */
553 extern void *must_realloc(void *orig
, size_t sz
);
555 /* __typeof__ should be safe to use with all compilers. */
556 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
557 extern bool has_fs_type(const char *path
, fs_type_magic magic_val
);
558 extern bool is_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
);
559 extern bool lxc_nic_exists(char *nic
);
560 extern int lxc_make_tmpfile(char *template, bool rm
);
562 static inline uint64_t lxc_getpagesize(void)
566 pgsz
= sysconf(_SC_PAGESIZE
);
573 /* If n is not a power of 2 this function will return the next power of 2
574 * greater than that number. Note that this function always returns the *next*
575 * power of 2 *greater* that number not the *nearest*. For example, passing 1025
576 * as argument this function will return 2048 although the closest power of 2
578 * If the caller passes in 0 they will receive 0 in return since this is invalid
579 * input and 0 is not a power of 2.
581 extern uint64_t lxc_find_next_power2(uint64_t n
);
583 static inline pid_t
lxc_raw_gettid(void)
586 return syscall(SYS_gettid
);
588 return lxc_raw_getpid();
592 #endif /* __LXC_UTILS_H */