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
90 /* Maximum number for 64 bit integer is a string with 21 digits: 2^64 - 1 = 21 */
91 #define LXC_NUMSTRLEN64 21
92 #define LXC_LINELEN 4096
93 #define LXC_IDMAPLEN 4096
95 /* returns 1 on success, 0 if there were any failures */
96 extern int lxc_rmdir_onedev(char *path
, const char *exclude
);
97 extern int get_u16(unsigned short *val
, const char *arg
, int base
);
98 extern int mkdir_p(const char *dir
, mode_t mode
);
99 extern char *get_rundir(void);
101 /* Define getline() if missing from the C library */
104 #include <../include/getline.h>
108 /* Define setns() if missing from the C library */
110 static inline int setns(int fd
, int nstype
)
113 return syscall(__NR_setns
, fd
, nstype
);
114 #elif defined(__NR_set_ns)
115 return syscall(__NR_set_ns
, fd
, nstype
);
123 /* Define sethostname() if missing from the C library */
124 #ifndef HAVE_SETHOSTNAME
125 static int sethostname(const char * name
, size_t len
)
127 #ifdef __NR_sethostname
128 return syscall(__NR_sethostname
, name
, len
);
136 /* Define unshare() if missing from the C library */
138 static inline int unshare(int flags
)
141 return syscall(__NR_unshare
, flags
);
148 extern int unshare(int);
151 /* Define signalfd() if missing from the C library */
152 #ifdef HAVE_SYS_SIGNALFD_H
153 # include <sys/signalfd.h>
155 /* assume kernel headers are too old */
157 struct signalfd_siginfo
167 uint32_t ssi_overrun
;
178 # ifndef __NR_signalfd4
179 /* assume kernel headers are too old */
181 # define __NR_signalfd4 327
183 # define __NR_signalfd4 289
185 # define __NR_signalfd4 313
187 # define __NR_signalfd4 322
189 # define __NR_signalfd4 355
190 # elif __mips__ && _MIPS_SIM == _ABIO32
191 # define __NR_signalfd4 4324
192 # elif __mips__ && _MIPS_SIM == _ABI64
193 # define __NR_signalfd4 5283
194 # elif __mips__ && _MIPS_SIM == _ABIN32
195 # define __NR_signalfd4 6287
199 # ifndef __NR_signalfd
200 /* assume kernel headers are too old */
202 # define __NR_signalfd 321
204 # define __NR_signalfd 282
206 # define __NR_signalfd 305
208 # define __NR_signalfd 316
210 # define __NR_signalfd 349
211 # elif __mips__ && _MIPS_SIM == _ABIO32
212 # define __NR_signalfd 4317
213 # elif __mips__ && _MIPS_SIM == _ABI64
214 # define __NR_signalfd 5276
215 # elif __mips__ && _MIPS_SIM == _ABIN32
216 # define __NR_signalfd 6280
220 static inline int signalfd(int fd
, const sigset_t
*mask
, int flags
)
224 retval
= syscall (__NR_signalfd4
, fd
, mask
, _NSIG
/ 8, flags
);
225 if (errno
== ENOSYS
&& flags
== 0)
226 retval
= syscall (__NR_signalfd
, fd
, mask
, _NSIG
/ 8);
232 #ifndef LO_FLAGS_AUTOCLEAR
233 #define LO_FLAGS_AUTOCLEAR 4
236 #ifndef LOOP_CTL_GET_FREE
237 #define LOOP_CTL_GET_FREE 0x4C82
242 #define MFD_CLOEXEC 0x0001U
245 #ifndef MFD_ALLOW_SEALING
246 #define MFD_ALLOW_SEALING 0x0002U
249 #ifndef HAVE_MEMFD_CREATE
250 static inline int memfd_create(const char *name
, unsigned int flags
) {
251 #ifndef __NR_memfd_create
253 #define __NR_memfd_create 356
254 #elif defined __x86_64__
255 #define __NR_memfd_create 319
256 #elif defined __arm__
257 #define __NR_memfd_create 385
258 #elif defined __aarch64__
259 #define __NR_memfd_create 279
260 #elif defined __s390__
261 #define __NR_memfd_create 350
262 #elif defined __powerpc__
263 #define __NR_memfd_create 360
264 #elif defined __sparc__
265 #define __NR_memfd_create 348
266 #elif defined __blackfin__
267 #define __NR_memfd_create 390
268 #elif defined __ia64__
269 #define __NR_memfd_create 1340
270 #elif defined _MIPS_SIM
271 #if _MIPS_SIM == _MIPS_SIM_ABI32
272 #define __NR_memfd_create 4354
274 #if _MIPS_SIM == _MIPS_SIM_NABI32
275 #define __NR_memfd_create 6318
277 #if _MIPS_SIM == _MIPS_SIM_ABI64
278 #define __NR_memfd_create 5314
282 #ifdef __NR_memfd_create
283 return syscall(__NR_memfd_create
, name
, flags
);
290 extern int memfd_create(const char *name
, unsigned int flags
);
293 static inline int lxc_set_cloexec(int fd
)
295 return fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
298 /* Struct to carry child pid from lxc_popen() to lxc_pclose().
299 * Not an opaque struct to allow direct access to the underlying FILE *
300 * (i.e., struct lxc_popen_FILE *file; fgets(buf, sizeof(buf), file->f))
301 * without additional wrappers.
303 struct lxc_popen_FILE
{
309 /* popen(command, "re") replacement that restores default signal mask
310 * via sigprocmask(2) (unblocks all signals) after fork(2) but prior to calling exec(3).
311 * In short, popen(command, "re") does pipe() + fork() + exec()
312 * while lxc_popen(command) does pipe() + fork() + sigprocmask() + exec().
313 * Returns pointer to struct lxc_popen_FILE, that should be freed with lxc_pclose().
314 * On error returns NULL.
316 extern struct lxc_popen_FILE
*lxc_popen(const char *command
);
318 /* pclose() replacement to be used on struct lxc_popen_FILE *,
319 * returned by lxc_popen().
320 * Waits for associated process to terminate, returns its exit status and
321 * frees resources, pointed to by struct lxc_popen_FILE *.
323 extern int lxc_pclose(struct lxc_popen_FILE
*fp
);
326 * BUILD_BUG_ON - break compile if a condition is true.
327 * @condition: the condition which the compiler should know is false.
329 * If you have some code which relies on certain constants being equal, or
330 * other compile-time-evaluated condition, you should use BUILD_BUG_ON to
331 * detect if someone changes it.
333 * The implementation uses gcc's reluctance to create a negative array, but
334 * gcc (as of 4.4) only emits that error for obvious cases (eg. not arguments
335 * to inline functions). So as a fallback we use the optimizer; if it can't
336 * prove the condition is false, it will cause a link error on the undefined
337 * "__build_bug_on_failed". This error message can be harder to track down
338 * though, hence the two different methods.
341 #define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
343 extern int __build_bug_on_failed
;
344 #define BUILD_BUG_ON(condition) \
346 ((void)sizeof(char[1 - 2*!!(condition)])); \
347 if (condition) __build_bug_on_failed = 1; \
352 * wait on a child we forked
354 extern int wait_for_pid(pid_t pid
);
355 extern int lxc_wait_for_pid_status(pid_t pid
);
357 /* send and receive buffers completely */
358 extern ssize_t
lxc_write_nointr(int fd
, const void* buf
, size_t count
);
359 extern ssize_t
lxc_read_nointr(int fd
, void* buf
, size_t count
);
360 extern ssize_t
lxc_read_nointr_expect(int fd
, void *buf
, size_t count
,
361 const void *expected_buf
);
363 #define SHA_DIGEST_LENGTH 20
364 extern int sha1sum_file(char *fnam
, unsigned char *md_value
);
367 /* read and write whole files */
368 extern int lxc_write_to_file(const char *filename
, const void *buf
,
369 size_t count
, bool add_newline
);
370 extern int lxc_read_from_file(const char *filename
, void* buf
, size_t count
);
372 /* convert variadic argument lists to arrays (for execl type argument lists) */
373 extern char** lxc_va_arg_list_to_argv(va_list ap
, size_t skip
, int do_strdup
);
374 extern const char** lxc_va_arg_list_to_argv_const(va_list ap
, size_t skip
);
376 /* Some simple string functions; if they return pointers, they are allocated
379 extern char *lxc_string_replace(const char *needle
, const char *replacement
,
380 const char *haystack
);
381 extern bool lxc_string_in_array(const char *needle
, const char **haystack
);
382 extern char *lxc_string_join(const char *sep
, const char **parts
,
384 /* Normalize and split path: Leading and trailing / are removed, multiple
385 * / are compactified, .. and . are resolved (.. on the top level is considered
389 * foo/../bar -> { bar, NULL }
391 * ./bar/baz/.. -> { bar, NULL }
392 * foo//bar -> { foo, bar, NULL }
394 extern char **lxc_normalize_path(const char *path
);
395 /* remove multiple slashes from the path, e.g. ///foo//bar -> /foo/bar */
396 extern char *lxc_deslashify(const char *path
);
397 extern char *lxc_append_paths(const char *first
, const char *second
);
398 /* Note: the following two functions use strtok(), so they will never
399 * consider an empty element, even if two delimiters are next to
402 extern bool lxc_string_in_list(const char *needle
, const char *haystack
,
404 extern char **lxc_string_split(const char *string
, char sep
);
405 extern char **lxc_string_split_and_trim(const char *string
, char sep
);
406 extern char **lxc_string_split_quoted(char *string
);
407 /* Append string to NULL-terminated string array. */
408 extern int lxc_append_string(char ***list
, char *entry
);
410 /* some simple array manipulation utilities */
411 typedef void (*lxc_free_fn
)(void *);
412 typedef void *(*lxc_dup_fn
)(void *);
413 extern int lxc_grow_array(void ***array
, size_t *capacity
, size_t new_size
,
414 size_t capacity_increment
);
415 extern void lxc_free_array(void **array
, lxc_free_fn element_free_fn
);
416 extern size_t lxc_array_len(void **array
);
418 extern void **lxc_append_null_to_array(void **array
, size_t count
);
420 /* mmap() wrapper. lxc_strmmap() will take care to \0-terminate files so that
421 * normal string-handling functions can be used on the buffer. */
422 extern void *lxc_strmmap(void *addr
, size_t length
, int prot
, int flags
, int fd
,
424 /* munmap() wrapper. Use it to free memory mmap()ed with lxc_strmmap(). */
425 extern int lxc_strmunmap(void *addr
, size_t length
);
427 /* initialize rand with urandom */
428 extern int randseed(bool);
430 inline static bool am_unpriv(void) {
431 return geteuid() != 0;
435 * parse /proc/self/uid_map to find what @orig maps to
437 extern uid_t
get_ns_uid(uid_t orig
);
439 extern bool dir_exists(const char *path
);
441 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
442 extern uint64_t fnv_64a_buf(void *buf
, size_t len
, uint64_t hval
);
444 extern int detect_shared_rootfs(void);
445 extern bool detect_ramfs_rootfs(void);
446 extern char *on_path(const char *cmd
, const char *rootfs
);
447 extern bool file_exists(const char *f
);
448 extern bool cgns_supported(void);
449 extern char *choose_init(const char *rootfs
);
450 extern int print_to_file(const char *file
, const char *content
);
451 extern bool switch_to_ns(pid_t pid
, const char *ns
);
452 extern int is_dir(const char *path
);
453 extern char *get_template_path(const char *t
);
454 extern int safe_mount(const char *src
, const char *dest
, const char *fstype
,
455 unsigned long flags
, const void *data
,
457 extern int lxc_mount_proc_if_needed(const char *rootfs
);
458 extern int open_devnull(void);
459 extern int set_stdfds(int fd
);
460 extern int null_stdfds(void);
461 extern int lxc_count_file_lines(const char *fn
);
462 extern int lxc_preserve_ns(const int pid
, const char *ns
);
464 /* Check whether a signal is blocked by a process. */
465 extern bool task_blocking_signal(pid_t pid
, int signal
);
467 /* Helper functions to parse numbers. */
468 extern int lxc_safe_uint(const char *numstr
, unsigned int *converted
);
469 extern int lxc_safe_int(const char *numstr
, int *converted
);
470 extern int lxc_safe_long(const char *numstr
, long int *converted
);
471 extern int lxc_safe_long_long(const char *numstr
, long long int *converted
);
472 extern int lxc_safe_ulong(const char *numstr
, unsigned long *converted
);
473 /* Handles B, kb, MB, GB. Detects overflows and reports -ERANGE. */
474 extern int parse_byte_size_string(const char *s
, int64_t *converted
);
476 /* Switch to a new uid and gid. */
477 extern int lxc_switch_uid_gid(uid_t uid
, gid_t gid
);
478 extern int lxc_setgroups(int size
, gid_t list
[]);
480 /* Find an unused loop device and associate it with source. */
481 extern int lxc_prepare_loop_dev(const char *source
, char *loop_dev
, int flags
);
483 /* Clear all mounts on a given node.
484 * >= 0 successfully cleared. The number returned is the number of umounts
486 * < 0 error umounting. Return -errno.
488 extern int lxc_unstack_mountpoint(const char *path
, bool lazy
);
491 * run_command runs a command and collect it's std{err,out} output in buf.
493 * @param[out] buf The buffer where the commands std{err,out] output will be
494 * read into. If no output was produced, buf will be memset
496 * @param[in] buf_size The size of buf. This function will reserve one byte for
498 * @param[in] child_fn The function to be run in the child process. This
499 * function must exec.
500 * @param[in] args Arguments to be passed to child_fn.
502 extern int run_command(char *buf
, size_t buf_size
, int (*child_fn
)(void *),
505 /* Concatenate all passed-in strings into one path. Do not fail. If any piece
506 * is not prefixed with '/', add a '/'.
508 extern char *must_make_path(const char *first
, ...) __attribute__((sentinel
));
510 /* return copy of string @entry; do not fail. */
511 extern char *must_copy_string(const char *entry
);
513 /* Re-alllocate a pointer, do not fail */
514 extern void *must_realloc(void *orig
, size_t sz
);
516 /* __typeof__ should be safe to use with all compilers. */
517 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
518 extern bool has_fs_type(const char *path
, fs_type_magic magic_val
);
519 extern bool is_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
);
520 extern bool lxc_nic_exists(char *nic
);
521 extern int lxc_make_tmpfile(char *template, bool rm
);
522 extern uint64_t lxc_getpagesize(void);
524 /* If n is not a power of 2 this function will return the next power of 2
525 * greater than that number. Note that this function always returns the *next*
526 * power of 2 *greater* that number not the *nearest*. For example, passing 1025
527 * as argument this function will return 2048 although the closest power of 2
529 * If the caller passes in 0 they will receive 0 in return since this is invalid
530 * input and 0 is not a power of 2.
532 extern uint64_t lxc_find_next_power2(uint64_t n
);
534 #endif /* __LXC_UTILS_H */