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 unshare() if missing from the C library */
125 static inline int unshare(int flags
)
128 return syscall(__NR_unshare
, flags
);
135 extern int unshare(int);
138 /* Define signalfd() if missing from the C library */
139 #ifdef HAVE_SYS_SIGNALFD_H
140 # include <sys/signalfd.h>
142 /* assume kernel headers are too old */
144 struct signalfd_siginfo
154 uint32_t ssi_overrun
;
165 # ifndef __NR_signalfd4
166 /* assume kernel headers are too old */
168 # define __NR_signalfd4 327
170 # define __NR_signalfd4 289
172 # define __NR_signalfd4 313
174 # define __NR_signalfd4 322
176 # define __NR_signalfd4 355
177 # elif __mips__ && _MIPS_SIM == _ABIO32
178 # define __NR_signalfd4 4324
179 # elif __mips__ && _MIPS_SIM == _ABI64
180 # define __NR_signalfd4 5283
181 # elif __mips__ && _MIPS_SIM == _ABIN32
182 # define __NR_signalfd4 6287
186 # ifndef __NR_signalfd
187 /* assume kernel headers are too old */
189 # define __NR_signalfd 321
191 # define __NR_signalfd 282
193 # define __NR_signalfd 305
195 # define __NR_signalfd 316
197 # define __NR_signalfd 349
198 # elif __mips__ && _MIPS_SIM == _ABIO32
199 # define __NR_signalfd 4317
200 # elif __mips__ && _MIPS_SIM == _ABI64
201 # define __NR_signalfd 5276
202 # elif __mips__ && _MIPS_SIM == _ABIN32
203 # define __NR_signalfd 6280
207 static inline int signalfd(int fd
, const sigset_t
*mask
, int flags
)
211 retval
= syscall (__NR_signalfd4
, fd
, mask
, _NSIG
/ 8, flags
);
212 if (errno
== ENOSYS
&& flags
== 0)
213 retval
= syscall (__NR_signalfd
, fd
, mask
, _NSIG
/ 8);
219 #ifndef LO_FLAGS_AUTOCLEAR
220 #define LO_FLAGS_AUTOCLEAR 4
223 #ifndef LOOP_CTL_GET_FREE
224 #define LOOP_CTL_GET_FREE 0x4C82
229 #define MFD_CLOEXEC 0x0001U
232 #ifndef MFD_ALLOW_SEALING
233 #define MFD_ALLOW_SEALING 0x0002U
236 #ifndef HAVE_MEMFD_CREATE
237 static inline int memfd_create(const char *name
, unsigned int flags
) {
238 #ifndef __NR_memfd_create
240 #define __NR_memfd_create 356
241 #elif defined __x86_64__
242 #define __NR_memfd_create 319
243 #elif defined __arm__
244 #define __NR_memfd_create 385
245 #elif defined __aarch64__
246 #define __NR_memfd_create 279
247 #elif defined __s390__
248 #define __NR_memfd_create 350
249 #elif defined __powerpc__
250 #define __NR_memfd_create 360
251 #elif defined __sparc__
252 #define __NR_memfd_create 348
253 #elif defined __blackfin__
254 #define __NR_memfd_create 390
255 #elif defined __ia64__
256 #define __NR_memfd_create 1340
257 #elif defined _MIPS_SIM
258 #if _MIPS_SIM == _MIPS_SIM_ABI32
259 #define __NR_memfd_create 4354
261 #if _MIPS_SIM == _MIPS_SIM_NABI32
262 #define __NR_memfd_create 6318
264 #if _MIPS_SIM == _MIPS_SIM_ABI64
265 #define __NR_memfd_create 5314
269 #ifdef __NR_memfd_create
270 return syscall(__NR_memfd_create
, name
, flags
);
277 extern int memfd_create(const char *name
, unsigned int flags
);
280 static inline int lxc_set_cloexec(int fd
)
282 return fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
285 /* Struct to carry child pid from lxc_popen() to lxc_pclose().
286 * Not an opaque struct to allow direct access to the underlying FILE *
287 * (i.e., struct lxc_popen_FILE *file; fgets(buf, sizeof(buf), file->f))
288 * without additional wrappers.
290 struct lxc_popen_FILE
{
296 /* popen(command, "re") replacement that restores default signal mask
297 * via sigprocmask(2) (unblocks all signals) after fork(2) but prior to calling exec(3).
298 * In short, popen(command, "re") does pipe() + fork() + exec()
299 * while lxc_popen(command) does pipe() + fork() + sigprocmask() + exec().
300 * Returns pointer to struct lxc_popen_FILE, that should be freed with lxc_pclose().
301 * On error returns NULL.
303 extern struct lxc_popen_FILE
*lxc_popen(const char *command
);
305 /* pclose() replacement to be used on struct lxc_popen_FILE *,
306 * returned by lxc_popen().
307 * Waits for associated process to terminate, returns its exit status and
308 * frees resources, pointed to by struct lxc_popen_FILE *.
310 extern int lxc_pclose(struct lxc_popen_FILE
*fp
);
313 * BUILD_BUG_ON - break compile if a condition is true.
314 * @condition: the condition which the compiler should know is false.
316 * If you have some code which relies on certain constants being equal, or
317 * other compile-time-evaluated condition, you should use BUILD_BUG_ON to
318 * detect if someone changes it.
320 * The implementation uses gcc's reluctance to create a negative array, but
321 * gcc (as of 4.4) only emits that error for obvious cases (eg. not arguments
322 * to inline functions). So as a fallback we use the optimizer; if it can't
323 * prove the condition is false, it will cause a link error on the undefined
324 * "__build_bug_on_failed". This error message can be harder to track down
325 * though, hence the two different methods.
328 #define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
330 extern int __build_bug_on_failed
;
331 #define BUILD_BUG_ON(condition) \
333 ((void)sizeof(char[1 - 2*!!(condition)])); \
334 if (condition) __build_bug_on_failed = 1; \
339 * wait on a child we forked
341 extern int wait_for_pid(pid_t pid
);
342 extern int lxc_wait_for_pid_status(pid_t pid
);
344 /* send and receive buffers completely */
345 extern ssize_t
lxc_write_nointr(int fd
, const void* buf
, size_t count
);
346 extern ssize_t
lxc_read_nointr(int fd
, void* buf
, size_t count
);
347 extern ssize_t
lxc_read_nointr_expect(int fd
, void *buf
, size_t count
,
348 const void *expected_buf
);
350 #define SHA_DIGEST_LENGTH 20
351 extern int sha1sum_file(char *fnam
, unsigned char *md_value
);
354 /* read and write whole files */
355 extern int lxc_write_to_file(const char *filename
, const void *buf
,
356 size_t count
, bool add_newline
);
357 extern int lxc_read_from_file(const char *filename
, void* buf
, size_t count
);
359 /* convert variadic argument lists to arrays (for execl type argument lists) */
360 extern char** lxc_va_arg_list_to_argv(va_list ap
, size_t skip
, int do_strdup
);
361 extern const char** lxc_va_arg_list_to_argv_const(va_list ap
, size_t skip
);
363 /* Some simple string functions; if they return pointers, they are allocated
366 extern char *lxc_string_replace(const char *needle
, const char *replacement
,
367 const char *haystack
);
368 extern bool lxc_string_in_array(const char *needle
, const char **haystack
);
369 extern char *lxc_string_join(const char *sep
, const char **parts
,
371 /* Normalize and split path: Leading and trailing / are removed, multiple
372 * / are compactified, .. and . are resolved (.. on the top level is considered
376 * foo/../bar -> { bar, NULL }
378 * ./bar/baz/.. -> { bar, NULL }
379 * foo//bar -> { foo, bar, NULL }
381 extern char **lxc_normalize_path(const char *path
);
382 /* remove multiple slashes from the path, e.g. ///foo//bar -> /foo/bar */
383 extern char *lxc_deslashify(const char *path
);
384 extern char *lxc_append_paths(const char *first
, const char *second
);
385 /* Note: the following two functions use strtok(), so they will never
386 * consider an empty element, even if two delimiters are next to
389 extern bool lxc_string_in_list(const char *needle
, const char *haystack
,
391 extern char **lxc_string_split(const char *string
, char sep
);
392 extern char **lxc_string_split_and_trim(const char *string
, char sep
);
393 extern char **lxc_string_split_quoted(char *string
);
394 /* Append string to NULL-terminated string array. */
395 extern int lxc_append_string(char ***list
, char *entry
);
397 /* some simple array manipulation utilities */
398 typedef void (*lxc_free_fn
)(void *);
399 typedef void *(*lxc_dup_fn
)(void *);
400 extern int lxc_grow_array(void ***array
, size_t *capacity
, size_t new_size
,
401 size_t capacity_increment
);
402 extern void lxc_free_array(void **array
, lxc_free_fn element_free_fn
);
403 extern size_t lxc_array_len(void **array
);
405 extern void **lxc_append_null_to_array(void **array
, size_t count
);
407 /* mmap() wrapper. lxc_strmmap() will take care to \0-terminate files so that
408 * normal string-handling functions can be used on the buffer. */
409 extern void *lxc_strmmap(void *addr
, size_t length
, int prot
, int flags
, int fd
,
411 /* munmap() wrapper. Use it to free memory mmap()ed with lxc_strmmap(). */
412 extern int lxc_strmunmap(void *addr
, size_t length
);
414 /* initialize rand with urandom */
415 extern int randseed(bool);
417 inline static bool am_unpriv(void) {
418 return geteuid() != 0;
422 * parse /proc/self/uid_map to find what @orig maps to
424 extern uid_t
get_ns_uid(uid_t orig
);
426 extern bool dir_exists(const char *path
);
428 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
429 extern uint64_t fnv_64a_buf(void *buf
, size_t len
, uint64_t hval
);
431 extern int detect_shared_rootfs(void);
432 extern bool detect_ramfs_rootfs(void);
433 extern char *on_path(const char *cmd
, const char *rootfs
);
434 extern bool file_exists(const char *f
);
435 extern bool cgns_supported(void);
436 extern char *choose_init(const char *rootfs
);
437 extern int print_to_file(const char *file
, const char *content
);
438 extern bool switch_to_ns(pid_t pid
, const char *ns
);
439 extern int is_dir(const char *path
);
440 extern char *get_template_path(const char *t
);
441 extern int safe_mount(const char *src
, const char *dest
, const char *fstype
,
442 unsigned long flags
, const void *data
,
444 extern int lxc_mount_proc_if_needed(const char *rootfs
);
445 extern int open_devnull(void);
446 extern int set_stdfds(int fd
);
447 extern int null_stdfds(void);
448 extern int lxc_count_file_lines(const char *fn
);
449 extern int lxc_preserve_ns(const int pid
, const char *ns
);
451 /* Check whether a signal is blocked by a process. */
452 extern bool task_blocking_signal(pid_t pid
, int signal
);
454 /* Helper functions to parse numbers. */
455 extern int lxc_safe_uint(const char *numstr
, unsigned int *converted
);
456 extern int lxc_safe_int(const char *numstr
, int *converted
);
457 extern int lxc_safe_long(const char *numstr
, long int *converted
);
458 extern int lxc_safe_long_long(const char *numstr
, long long int *converted
);
459 extern int lxc_safe_ulong(const char *numstr
, unsigned long *converted
);
460 /* Handles B, kb, MB, GB. Detects overflows and reports -ERANGE. */
461 extern int parse_byte_size_string(const char *s
, int64_t *converted
);
463 /* Switch to a new uid and gid. */
464 extern int lxc_switch_uid_gid(uid_t uid
, gid_t gid
);
465 extern int lxc_setgroups(int size
, gid_t list
[]);
467 /* Find an unused loop device and associate it with source. */
468 extern int lxc_prepare_loop_dev(const char *source
, char *loop_dev
, int flags
);
470 /* Clear all mounts on a given node.
471 * >= 0 successfully cleared. The number returned is the number of umounts
473 * < 0 error umounting. Return -errno.
475 extern int lxc_unstack_mountpoint(const char *path
, bool lazy
);
478 * run_command runs a command and collect it's std{err,out} output in buf.
480 * @param[out] buf The buffer where the commands std{err,out] output will be
481 * read into. If no output was produced, buf will be memset
483 * @param[in] buf_size The size of buf. This function will reserve one byte for
485 * @param[in] child_fn The function to be run in the child process. This
486 * function must exec.
487 * @param[in] args Arguments to be passed to child_fn.
489 extern int run_command(char *buf
, size_t buf_size
, int (*child_fn
)(void *),
492 /* Concatenate all passed-in strings into one path. Do not fail. If any piece
493 * is not prefixed with '/', add a '/'.
495 extern char *must_make_path(const char *first
, ...) __attribute__((sentinel
));
497 /* return copy of string @entry; do not fail. */
498 extern char *must_copy_string(const char *entry
);
500 /* Re-alllocate a pointer, do not fail */
501 extern void *must_realloc(void *orig
, size_t sz
);
503 /* __typeof__ should be safe to use with all compilers. */
504 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
505 extern bool has_fs_type(const char *path
, fs_type_magic magic_val
);
506 extern bool is_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
);
507 extern bool lxc_nic_exists(char *nic
);
508 extern int lxc_make_tmpfile(char *template, bool rm
);
509 extern uint64_t lxc_getpagesize(void);
511 /* If n is not a power of 2 this function will return the next power of 2
512 * greater than that number. Note that this function always returns the *next*
513 * power of 2 *greater* that number not the *nearest*. For example, passing 1025
514 * as argument this function will return 2048 although the closest power of 2
516 * If the caller passes in 0 they will receive 0 in return since this is invalid
517 * input and 0 is not a power of 2.
519 extern uint64_t lxc_find_next_power2(uint64_t n
);
521 #endif /* __LXC_UTILS_H */