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))
54 /* Maximum number for 64 bit integer is a string with 21 digits: 2^64 - 1 = 21 */
55 #define LXC_NUMSTRLEN64 21
56 #define LXC_LINELEN 4096
57 #define LXC_IDMAPLEN 4096
59 /* returns 1 on success, 0 if there were any failures */
60 extern int lxc_rmdir_onedev(char *path
, const char *exclude
);
61 extern int get_u16(unsigned short *val
, const char *arg
, int base
);
62 extern int mkdir_p(const char *dir
, mode_t mode
);
63 extern char *get_rundir(void);
65 /* Define getline() if missing from the C library */
68 #include <../include/getline.h>
72 /* Define setns() if missing from the C library */
74 static inline int setns(int fd
, int nstype
)
77 return syscall(__NR_setns
, fd
, nstype
);
78 #elif defined(__NR_set_ns)
79 return syscall(__NR_set_ns
, fd
, nstype
);
87 /* Define unshare() if missing from the C library */
89 static inline int unshare(int flags
)
92 return syscall(__NR_unshare
, flags
);
99 extern int unshare(int);
102 /* Define signalfd() if missing from the C library */
103 #ifdef HAVE_SYS_SIGNALFD_H
104 # include <sys/signalfd.h>
106 /* assume kernel headers are too old */
108 struct signalfd_siginfo
118 uint32_t ssi_overrun
;
129 # ifndef __NR_signalfd4
130 /* assume kernel headers are too old */
132 # define __NR_signalfd4 327
134 # define __NR_signalfd4 289
136 # define __NR_signalfd4 313
138 # define __NR_signalfd4 322
140 # define __NR_signalfd4 355
141 # elif __mips__ && _MIPS_SIM == _ABIO32
142 # define __NR_signalfd4 4324
143 # elif __mips__ && _MIPS_SIM == _ABI64
144 # define __NR_signalfd4 5283
145 # elif __mips__ && _MIPS_SIM == _ABIN32
146 # define __NR_signalfd4 6287
150 # ifndef __NR_signalfd
151 /* assume kernel headers are too old */
153 # define __NR_signalfd 321
155 # define __NR_signalfd 282
157 # define __NR_signalfd 305
159 # define __NR_signalfd 316
161 # define __NR_signalfd 349
162 # elif __mips__ && _MIPS_SIM == _ABIO32
163 # define __NR_signalfd 4317
164 # elif __mips__ && _MIPS_SIM == _ABI64
165 # define __NR_signalfd 5276
166 # elif __mips__ && _MIPS_SIM == _ABIN32
167 # define __NR_signalfd 6280
171 static inline int signalfd(int fd
, const sigset_t
*mask
, int flags
)
175 retval
= syscall (__NR_signalfd4
, fd
, mask
, _NSIG
/ 8, flags
);
176 if (errno
== ENOSYS
&& flags
== 0)
177 retval
= syscall (__NR_signalfd
, fd
, mask
, _NSIG
/ 8);
183 #ifndef LO_FLAGS_AUTOCLEAR
184 #define LO_FLAGS_AUTOCLEAR 4
187 #ifndef LOOP_CTL_GET_FREE
188 #define LOOP_CTL_GET_FREE 0x4C82
193 #define MFD_CLOEXEC 0x0001U
196 #ifndef MFD_ALLOW_SEALING
197 #define MFD_ALLOW_SEALING 0x0002U
200 #ifndef HAVE_MEMFD_CREATE
201 static inline int memfd_create(const char *name
, unsigned int flags
) {
202 #ifndef __NR_memfd_create
204 #define __NR_memfd_create 356
205 #elif defined __x86_64__
206 #define __NR_memfd_create 319
207 #elif defined __arm__
208 #define __NR_memfd_create 385
209 #elif defined __aarch64__
210 #define __NR_memfd_create 279
211 #elif defined __s390__
212 #define __NR_memfd_create 350
213 #elif defined __powerpc__
214 #define __NR_memfd_create 360
215 #elif defined __sparc__
216 #define __NR_memfd_create 348
217 #elif defined __blackfin__
218 #define __NR_memfd_create 390
219 #elif defined __ia64__
220 #define __NR_memfd_create 1340
221 #elif defined _MIPS_SIM
222 #if _MIPS_SIM == _MIPS_SIM_ABI32
223 #define __NR_memfd_create 4354
225 #if _MIPS_SIM == _MIPS_SIM_NABI32
226 #define __NR_memfd_create 6318
228 #if _MIPS_SIM == _MIPS_SIM_ABI64
229 #define __NR_memfd_create 5314
233 #ifdef __NR_memfd_create
234 return syscall(__NR_memfd_create
, name
, flags
);
241 extern int memfd_create(const char *name
, unsigned int flags
);
244 static inline int lxc_set_cloexec(int fd
)
246 return fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
249 /* Struct to carry child pid from lxc_popen() to lxc_pclose().
250 * Not an opaque struct to allow direct access to the underlying FILE *
251 * (i.e., struct lxc_popen_FILE *file; fgets(buf, sizeof(buf), file->f))
252 * without additional wrappers.
254 struct lxc_popen_FILE
{
260 /* popen(command, "re") replacement that restores default signal mask
261 * via sigprocmask(2) (unblocks all signals) after fork(2) but prior to calling exec(3).
262 * In short, popen(command, "re") does pipe() + fork() + exec()
263 * while lxc_popen(command) does pipe() + fork() + sigprocmask() + exec().
264 * Returns pointer to struct lxc_popen_FILE, that should be freed with lxc_pclose().
265 * On error returns NULL.
267 extern struct lxc_popen_FILE
*lxc_popen(const char *command
);
269 /* pclose() replacement to be used on struct lxc_popen_FILE *,
270 * returned by lxc_popen().
271 * Waits for associated process to terminate, returns its exit status and
272 * frees resources, pointed to by struct lxc_popen_FILE *.
274 extern int lxc_pclose(struct lxc_popen_FILE
*fp
);
277 * BUILD_BUG_ON - break compile if a condition is true.
278 * @condition: the condition which the compiler should know is false.
280 * If you have some code which relies on certain constants being equal, or
281 * other compile-time-evaluated condition, you should use BUILD_BUG_ON to
282 * detect if someone changes it.
284 * The implementation uses gcc's reluctance to create a negative array, but
285 * gcc (as of 4.4) only emits that error for obvious cases (eg. not arguments
286 * to inline functions). So as a fallback we use the optimizer; if it can't
287 * prove the condition is false, it will cause a link error on the undefined
288 * "__build_bug_on_failed". This error message can be harder to track down
289 * though, hence the two different methods.
292 #define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
294 extern int __build_bug_on_failed
;
295 #define BUILD_BUG_ON(condition) \
297 ((void)sizeof(char[1 - 2*!!(condition)])); \
298 if (condition) __build_bug_on_failed = 1; \
303 * wait on a child we forked
305 extern int wait_for_pid(pid_t pid
);
306 extern int lxc_wait_for_pid_status(pid_t pid
);
308 /* send and receive buffers completely */
309 extern ssize_t
lxc_write_nointr(int fd
, const void* buf
, size_t count
);
310 extern ssize_t
lxc_read_nointr(int fd
, void* buf
, size_t count
);
311 extern ssize_t
lxc_read_nointr_expect(int fd
, void *buf
, size_t count
,
312 const void *expected_buf
);
314 #define SHA_DIGEST_LENGTH 20
315 extern int sha1sum_file(char *fnam
, unsigned char *md_value
);
318 /* read and write whole files */
319 extern int lxc_write_to_file(const char *filename
, const void *buf
,
320 size_t count
, bool add_newline
);
321 extern int lxc_read_from_file(const char *filename
, void* buf
, size_t count
);
323 /* convert variadic argument lists to arrays (for execl type argument lists) */
324 extern char** lxc_va_arg_list_to_argv(va_list ap
, size_t skip
, int do_strdup
);
325 extern const char** lxc_va_arg_list_to_argv_const(va_list ap
, size_t skip
);
327 /* Some simple string functions; if they return pointers, they are allocated
330 extern char *lxc_string_replace(const char *needle
, const char *replacement
,
331 const char *haystack
);
332 extern bool lxc_string_in_array(const char *needle
, const char **haystack
);
333 extern char *lxc_string_join(const char *sep
, const char **parts
,
335 /* Normalize and split path: Leading and trailing / are removed, multiple
336 * / are compactified, .. and . are resolved (.. on the top level is considered
340 * foo/../bar -> { bar, NULL }
342 * ./bar/baz/.. -> { bar, NULL }
343 * foo//bar -> { foo, bar, NULL }
345 extern char **lxc_normalize_path(const char *path
);
346 /* remove multiple slashes from the path, e.g. ///foo//bar -> /foo/bar */
347 extern char *lxc_deslashify(const char *path
);
348 extern char *lxc_append_paths(const char *first
, const char *second
);
349 /* Note: the following two functions use strtok(), so they will never
350 * consider an empty element, even if two delimiters are next to
353 extern bool lxc_string_in_list(const char *needle
, const char *haystack
,
355 extern char **lxc_string_split(const char *string
, char sep
);
356 extern char **lxc_string_split_and_trim(const char *string
, char sep
);
357 extern char **lxc_string_split_quoted(char *string
);
358 /* Append string to NULL-terminated string array. */
359 extern int lxc_append_string(char ***list
, char *entry
);
361 /* some simple array manipulation utilities */
362 typedef void (*lxc_free_fn
)(void *);
363 typedef void *(*lxc_dup_fn
)(void *);
364 extern int lxc_grow_array(void ***array
, size_t *capacity
, size_t new_size
,
365 size_t capacity_increment
);
366 extern void lxc_free_array(void **array
, lxc_free_fn element_free_fn
);
367 extern size_t lxc_array_len(void **array
);
369 extern void **lxc_append_null_to_array(void **array
, size_t count
);
371 /* mmap() wrapper. lxc_strmmap() will take care to \0-terminate files so that
372 * normal string-handling functions can be used on the buffer. */
373 extern void *lxc_strmmap(void *addr
, size_t length
, int prot
, int flags
, int fd
,
375 /* munmap() wrapper. Use it to free memory mmap()ed with lxc_strmmap(). */
376 extern int lxc_strmunmap(void *addr
, size_t length
);
378 /* initialize rand with urandom */
379 extern int randseed(bool);
381 inline static bool am_unpriv(void) {
382 return geteuid() != 0;
386 * parse /proc/self/uid_map to find what @orig maps to
388 extern uid_t
get_ns_uid(uid_t orig
);
390 extern bool dir_exists(const char *path
);
392 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
393 extern uint64_t fnv_64a_buf(void *buf
, size_t len
, uint64_t hval
);
395 extern int detect_shared_rootfs(void);
396 extern bool detect_ramfs_rootfs(void);
397 extern char *on_path(const char *cmd
, const char *rootfs
);
398 extern bool file_exists(const char *f
);
399 extern bool cgns_supported(void);
400 extern char *choose_init(const char *rootfs
);
401 extern int print_to_file(const char *file
, const char *content
);
402 extern bool switch_to_ns(pid_t pid
, const char *ns
);
403 extern int is_dir(const char *path
);
404 extern char *get_template_path(const char *t
);
405 extern int safe_mount(const char *src
, const char *dest
, const char *fstype
,
406 unsigned long flags
, const void *data
,
408 extern int lxc_mount_proc_if_needed(const char *rootfs
);
409 extern int open_devnull(void);
410 extern int set_stdfds(int fd
);
411 extern int null_stdfds(void);
412 extern int lxc_count_file_lines(const char *fn
);
413 extern int lxc_preserve_ns(const int pid
, const char *ns
);
415 /* Check whether a signal is blocked by a process. */
416 extern bool task_blocking_signal(pid_t pid
, int signal
);
418 /* Helper functions to parse numbers. */
419 extern int lxc_safe_uint(const char *numstr
, unsigned int *converted
);
420 extern int lxc_safe_int(const char *numstr
, int *converted
);
421 extern int lxc_safe_long(const char *numstr
, long int *converted
);
422 extern int lxc_safe_ulong(const char *numstr
, unsigned long *converted
);
424 /* Switch to a new uid and gid. */
425 extern int lxc_switch_uid_gid(uid_t uid
, gid_t gid
);
426 extern int lxc_setgroups(int size
, gid_t list
[]);
428 /* Find an unused loop device and associate it with source. */
429 extern int lxc_prepare_loop_dev(const char *source
, char *loop_dev
, int flags
);
431 /* Clear all mounts on a given node.
432 * >= 0 successfully cleared. The number returned is the number of umounts
434 * < 0 error umounting. Return -errno.
436 extern int lxc_unstack_mountpoint(const char *path
, bool lazy
);
439 * run_command runs a command and collect it's std{err,out} output in buf.
441 * @param[out] buf The buffer where the commands std{err,out] output will be
442 * read into. If no output was produced, buf will be memset
444 * @param[in] buf_size The size of buf. This function will reserve one byte for
446 * @param[in] child_fn The function to be run in the child process. This
447 * function must exec.
448 * @param[in] args Arguments to be passed to child_fn.
450 extern int run_command(char *buf
, size_t buf_size
, int (*child_fn
)(void *),
453 /* Concatenate all passed-in strings into one path. Do not fail. If any piece
454 * is not prefixed with '/', add a '/'.
456 extern char *must_make_path(const char *first
, ...) __attribute__((sentinel
));
458 /* return copy of string @entry; do not fail. */
459 extern char *must_copy_string(const char *entry
);
461 /* Re-alllocate a pointer, do not fail */
462 extern void *must_realloc(void *orig
, size_t sz
);
464 /* __typeof__ should be safe to use with all compilers. */
465 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
466 extern bool has_fs_type(const char *path
, fs_type_magic magic_val
);
467 extern bool is_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
);
468 extern bool lxc_nic_exists(char *nic
);
469 extern int lxc_make_tmpfile(char *template, bool rm
);
470 extern uint64_t lxc_getpagesize(void);
472 #endif /* __LXC_UTILS_H */