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 #include "initutils.h"
44 /* Define __S_ISTYPE if missing from the C library. */
46 #define __S_ISTYPE(mode, mask) (((mode)&S_IFMT) == (mask))
50 /* Maximum number for 64 bit integer is a string with 21 digits: 2^64 - 1 = 21 */
51 #define LXC_NUMSTRLEN64 21
52 #define LXC_LINELEN 4096
53 #define LXC_IDMAPLEN 4096
55 /* returns 1 on success, 0 if there were any failures */
56 extern int lxc_rmdir_onedev(char *path
, const char *exclude
);
57 extern int get_u16(unsigned short *val
, const char *arg
, int base
);
58 extern int mkdir_p(const char *dir
, mode_t mode
);
59 extern char *get_rundir(void);
61 /* Define getline() if missing from the C library */
64 #include <../include/getline.h>
68 /* Define setns() if missing from the C library */
70 static inline int setns(int fd
, int nstype
)
73 return syscall(__NR_setns
, fd
, nstype
);
74 #elif defined(__NR_set_ns)
75 return syscall(__NR_set_ns
, fd
, nstype
);
83 /* Define unshare() if missing from the C library */
85 static inline int unshare(int flags
)
88 return syscall(__NR_unshare
, flags
);
95 extern int unshare(int);
98 /* Define signalfd() if missing from the C library */
99 #ifdef HAVE_SYS_SIGNALFD_H
100 # include <sys/signalfd.h>
102 /* assume kernel headers are too old */
104 struct signalfd_siginfo
114 uint32_t ssi_overrun
;
125 # ifndef __NR_signalfd4
126 /* assume kernel headers are too old */
128 # define __NR_signalfd4 327
130 # define __NR_signalfd4 289
132 # define __NR_signalfd4 313
134 # define __NR_signalfd4 322
136 # define __NR_signalfd4 355
137 # elif __mips__ && _MIPS_SIM == _ABIO32
138 # define __NR_signalfd4 4324
139 # elif __mips__ && _MIPS_SIM == _ABI64
140 # define __NR_signalfd4 5283
141 # elif __mips__ && _MIPS_SIM == _ABIN32
142 # define __NR_signalfd4 6287
146 # ifndef __NR_signalfd
147 /* assume kernel headers are too old */
149 # define __NR_signalfd 321
151 # define __NR_signalfd 282
153 # define __NR_signalfd 305
155 # define __NR_signalfd 316
157 # define __NR_signalfd 349
158 # elif __mips__ && _MIPS_SIM == _ABIO32
159 # define __NR_signalfd 4317
160 # elif __mips__ && _MIPS_SIM == _ABI64
161 # define __NR_signalfd 5276
162 # elif __mips__ && _MIPS_SIM == _ABIN32
163 # define __NR_signalfd 6280
167 static inline int signalfd(int fd
, const sigset_t
*mask
, int flags
)
171 retval
= syscall (__NR_signalfd4
, fd
, mask
, _NSIG
/ 8, flags
);
172 if (errno
== ENOSYS
&& flags
== 0)
173 retval
= syscall (__NR_signalfd
, fd
, mask
, _NSIG
/ 8);
179 #ifndef LO_FLAGS_AUTOCLEAR
180 #define LO_FLAGS_AUTOCLEAR 4
183 #ifndef LOOP_CTL_GET_FREE
184 #define LOOP_CTL_GET_FREE 0x4C82
187 /* Struct to carry child pid from lxc_popen() to lxc_pclose().
188 * Not an opaque struct to allow direct access to the underlying FILE *
189 * (i.e., struct lxc_popen_FILE *file; fgets(buf, sizeof(buf), file->f))
190 * without additional wrappers.
192 struct lxc_popen_FILE
{
198 /* popen(command, "re") replacement that restores default signal mask
199 * via sigprocmask(2) (unblocks all signals) after fork(2) but prior to calling exec(3).
200 * In short, popen(command, "re") does pipe() + fork() + exec()
201 * while lxc_popen(command) does pipe() + fork() + sigprocmask() + exec().
202 * Returns pointer to struct lxc_popen_FILE, that should be freed with lxc_pclose().
203 * On error returns NULL.
205 extern struct lxc_popen_FILE
*lxc_popen(const char *command
);
207 /* pclose() replacement to be used on struct lxc_popen_FILE *,
208 * returned by lxc_popen().
209 * Waits for associated process to terminate, returns its exit status and
210 * frees resources, pointed to by struct lxc_popen_FILE *.
212 extern int lxc_pclose(struct lxc_popen_FILE
*fp
);
215 * BUILD_BUG_ON - break compile if a condition is true.
216 * @condition: the condition which the compiler should know is false.
218 * If you have some code which relies on certain constants being equal, or
219 * other compile-time-evaluated condition, you should use BUILD_BUG_ON to
220 * detect if someone changes it.
222 * The implementation uses gcc's reluctance to create a negative array, but
223 * gcc (as of 4.4) only emits that error for obvious cases (eg. not arguments
224 * to inline functions). So as a fallback we use the optimizer; if it can't
225 * prove the condition is false, it will cause a link error on the undefined
226 * "__build_bug_on_failed". This error message can be harder to track down
227 * though, hence the two different methods.
230 #define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
232 extern int __build_bug_on_failed
;
233 #define BUILD_BUG_ON(condition) \
235 ((void)sizeof(char[1 - 2*!!(condition)])); \
236 if (condition) __build_bug_on_failed = 1; \
241 * wait on a child we forked
243 extern int wait_for_pid(pid_t pid
);
244 extern int lxc_wait_for_pid_status(pid_t pid
);
246 /* send and receive buffers completely */
247 extern ssize_t
lxc_write_nointr(int fd
, const void* buf
, size_t count
);
248 extern ssize_t
lxc_read_nointr(int fd
, void* buf
, size_t count
);
249 extern ssize_t
lxc_read_nointr_expect(int fd
, void *buf
, size_t count
,
250 const void *expected_buf
);
252 #define SHA_DIGEST_LENGTH 20
253 extern int sha1sum_file(char *fnam
, unsigned char *md_value
);
256 /* read and write whole files */
257 extern int lxc_write_to_file(const char *filename
, const void *buf
,
258 size_t count
, bool add_newline
);
259 extern int lxc_read_from_file(const char *filename
, void* buf
, size_t count
);
261 /* convert variadic argument lists to arrays (for execl type argument lists) */
262 extern char** lxc_va_arg_list_to_argv(va_list ap
, size_t skip
, int do_strdup
);
263 extern const char** lxc_va_arg_list_to_argv_const(va_list ap
, size_t skip
);
265 /* Some simple string functions; if they return pointers, they are allocated
268 extern char *lxc_string_replace(const char *needle
, const char *replacement
,
269 const char *haystack
);
270 extern bool lxc_string_in_array(const char *needle
, const char **haystack
);
271 extern char *lxc_string_join(const char *sep
, const char **parts
,
273 /* Normalize and split path: Leading and trailing / are removed, multiple
274 * / are compactified, .. and . are resolved (.. on the top level is considered
278 * foo/../bar -> { bar, NULL }
280 * ./bar/baz/.. -> { bar, NULL }
281 * foo//bar -> { foo, bar, NULL }
283 extern char **lxc_normalize_path(const char *path
);
284 /* remove multiple slashes from the path, e.g. ///foo//bar -> /foo/bar */
285 extern char *lxc_deslashify(const char *path
);
286 extern char *lxc_append_paths(const char *first
, const char *second
);
287 /* Note: the following two functions use strtok(), so they will never
288 * consider an empty element, even if two delimiters are next to
291 extern bool lxc_string_in_list(const char *needle
, const char *haystack
,
293 extern char **lxc_string_split(const char *string
, char sep
);
294 extern char **lxc_string_split_and_trim(const char *string
, char sep
);
295 extern char **lxc_string_split_quoted(char *string
);
296 /* Append string to NULL-terminated string array. */
297 extern int lxc_append_string(char ***list
, char *entry
);
299 /* some simple array manipulation utilities */
300 typedef void (*lxc_free_fn
)(void *);
301 typedef void *(*lxc_dup_fn
)(void *);
302 extern int lxc_grow_array(void ***array
, size_t *capacity
, size_t new_size
,
303 size_t capacity_increment
);
304 extern void lxc_free_array(void **array
, lxc_free_fn element_free_fn
);
305 extern size_t lxc_array_len(void **array
);
307 extern void **lxc_append_null_to_array(void **array
, size_t count
);
309 /* mmap() wrapper. lxc_strmmap() will take care to \0-terminate files so that
310 * normal string-handling functions can be used on the buffer. */
311 extern void *lxc_strmmap(void *addr
, size_t length
, int prot
, int flags
, int fd
,
313 /* munmap() wrapper. Use it to free memory mmap()ed with lxc_strmmap(). */
314 extern int lxc_strmunmap(void *addr
, size_t length
);
316 /* initialize rand with urandom */
317 extern int randseed(bool);
319 inline static bool am_unpriv(void) {
320 return geteuid() != 0;
324 * parse /proc/self/uid_map to find what @orig maps to
326 extern uid_t
get_ns_uid(uid_t orig
);
328 extern bool dir_exists(const char *path
);
330 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
331 extern uint64_t fnv_64a_buf(void *buf
, size_t len
, uint64_t hval
);
333 extern int detect_shared_rootfs(void);
334 extern bool detect_ramfs_rootfs(void);
335 extern char *on_path(const char *cmd
, const char *rootfs
);
336 extern bool file_exists(const char *f
);
337 extern bool cgns_supported(void);
338 extern char *choose_init(const char *rootfs
);
339 extern int print_to_file(const char *file
, const char *content
);
340 extern bool switch_to_ns(pid_t pid
, const char *ns
);
341 extern int is_dir(const char *path
);
342 extern char *get_template_path(const char *t
);
343 extern int setproctitle(char *title
);
344 extern int safe_mount(const char *src
, const char *dest
, const char *fstype
,
345 unsigned long flags
, const void *data
,
347 extern int lxc_mount_proc_if_needed(const char *rootfs
);
348 extern int open_devnull(void);
349 extern int set_stdfds(int fd
);
350 extern int null_stdfds(void);
351 extern int lxc_count_file_lines(const char *fn
);
352 extern int lxc_preserve_ns(const int pid
, const char *ns
);
354 /* Check whether a signal is blocked by a process. */
355 extern bool task_blocking_signal(pid_t pid
, int signal
);
357 /* Helper functions to parse numbers. */
358 extern int lxc_safe_uint(const char *numstr
, unsigned int *converted
);
359 extern int lxc_safe_int(const char *numstr
, int *converted
);
360 extern int lxc_safe_long(const char *numstr
, long int *converted
);
361 extern int lxc_safe_ulong(const char *numstr
, unsigned long *converted
);
363 /* Switch to a new uid and gid. */
364 extern int lxc_switch_uid_gid(uid_t uid
, gid_t gid
);
365 extern int lxc_setgroups(int size
, gid_t list
[]);
367 /* Find an unused loop device and associate it with source. */
368 extern int lxc_prepare_loop_dev(const char *source
, char *loop_dev
, int flags
);
370 /* Clear all mounts on a given node.
371 * >= 0 successfully cleared. The number returned is the number of umounts
373 * < 0 error umounting. Return -errno.
375 extern int lxc_unstack_mountpoint(const char *path
, bool lazy
);
378 * run_command runs a command and collect it's std{err,out} output in buf.
380 * @param[out] buf The buffer where the commands std{err,out] output will be
381 * read into. If no output was produced, buf will be memset
383 * @param[in] buf_size The size of buf. This function will reserve one byte for
385 * @param[in] child_fn The function to be run in the child process. This
386 * function must exec.
387 * @param[in] args Arguments to be passed to child_fn.
389 extern int run_command(char *buf
, size_t buf_size
, int (*child_fn
)(void *),
392 /* Concatenate all passed-in strings into one path. Do not fail. If any piece
393 * is not prefixed with '/', add a '/'.
395 extern char *must_make_path(const char *first
, ...) __attribute__((sentinel
));
397 /* return copy of string @entry; do not fail. */
398 extern char *must_copy_string(const char *entry
);
400 /* Re-alllocate a pointer, do not fail */
401 extern void *must_realloc(void *orig
, size_t sz
);
403 /* __typeof__ should be safe to use with all compilers. */
404 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
405 extern bool has_fs_type(const char *path
, fs_type_magic magic_val
);
406 extern bool is_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
);
407 extern bool lxc_nic_exists(char *nic
);
409 #endif /* __LXC_UTILS_H */