]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/utils.h
Merge pull request #1756 from brauner/2017-08-10/further_lxc_2.1_preparations
[mirror_lxc.git] / src / lxc / utils.h
CommitLineData
0ad19a3f 1/*
2 * lxc: linux Container library
3 *
4 * (C) Copyright IBM Corp. 2007, 2008
5 *
6 * Authors:
9afe19d6 7 * Daniel Lezcano <daniel.lezcano at free.fr>
0ad19a3f 8 *
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.
13 *
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.
18 *
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
250b1eec 21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
0ad19a3f 22 */
f1a4a029
ÇO
23#ifndef __LXC_UTILS_H
24#define __LXC_UTILS_H
0ad19a3f 25
c6868a1f
CB
26/* Properly support loop devices on 32bit systems. */
27#define _FILE_OFFSET_BITS 64
28
a1e5280d
CB
29#include "config.h"
30
6a44839f 31#include <errno.h>
61a1d519 32#include <stdarg.h>
d0386d66 33#include <stdio.h>
502657d5 34#include <stdbool.h>
c6868a1f
CB
35#include <unistd.h>
36#include <linux/loop.h>
29a11a7f 37#include <linux/magic.h>
ec346ea1 38#include <sys/syscall.h>
c797a220 39#include <sys/types.h>
a035c53a 40#include <sys/vfs.h>
f2363e38 41
4295c5de 42#include "initutils.h"
c797a220 43
a394f952
CB
44/* Define __S_ISTYPE if missing from the C library. */
45#ifndef __S_ISTYPE
46#define __S_ISTYPE(mode, mask) (((mode)&S_IFMT) == (mask))
47#endif
48
b07511df
CB
49/* Useful macros */
50/* Maximum number for 64 bit integer is a string with 21 digits: 2^64 - 1 = 21 */
eab15c1e
CB
51#define LXC_NUMSTRLEN64 21
52#define LXC_LINELEN 4096
4bc3b759 53#define LXC_IDMAPLEN 4096
b07511df 54
60bf62d4 55/* returns 1 on success, 0 if there were any failures */
18aa217b 56extern int lxc_rmdir_onedev(char *path, const char *exclude);
7c11d57a 57extern int get_u16(unsigned short *val, const char *arg, int base);
1b09f2c0 58extern int mkdir_p(const char *dir, mode_t mode);
fd8c2777 59extern char *get_rundir(void);
9e60f51d 60
6a44839f
DE
61/* Define getline() if missing from the C library */
62#ifndef HAVE_GETLINE
63#ifdef HAVE_FGETLN
64#include <../include/getline.h>
65#endif
66#endif
67
68/* Define setns() if missing from the C library */
69#ifndef HAVE_SETNS
70static inline int setns(int fd, int nstype)
71{
72#ifdef __NR_setns
73 return syscall(__NR_setns, fd, nstype);
a1258e6d 74#elif defined(__NR_set_ns)
92e23841 75 return syscall(__NR_set_ns, fd, nstype);
6a44839f
DE
76#else
77 errno = ENOSYS;
78 return -1;
79#endif
80}
81#endif
82
83/* Define unshare() if missing from the C library */
84#ifndef HAVE_UNSHARE
85static inline int unshare(int flags)
86{
87#ifdef __NR_unshare
88 return syscall(__NR_unshare, flags);
89#else
90 errno = ENOSYS;
91 return -1;
92#endif
93}
94#else
95int unshare(int);
96#endif
97
b5159817
DE
98/* Define signalfd() if missing from the C library */
99#ifdef HAVE_SYS_SIGNALFD_H
100# include <sys/signalfd.h>
101#else
102/* assume kernel headers are too old */
103#include <stdint.h>
104struct signalfd_siginfo
105{
106 uint32_t ssi_signo;
107 int32_t ssi_errno;
108 int32_t ssi_code;
109 uint32_t ssi_pid;
110 uint32_t ssi_uid;
111 int32_t ssi_fd;
112 uint32_t ssi_tid;
113 uint32_t ssi_band;
114 uint32_t ssi_overrun;
115 uint32_t ssi_trapno;
116 int32_t ssi_status;
117 int32_t ssi_int;
118 uint64_t ssi_ptr;
119 uint64_t ssi_utime;
120 uint64_t ssi_stime;
121 uint64_t ssi_addr;
122 uint8_t __pad[48];
123};
124
125# ifndef __NR_signalfd4
126/* assume kernel headers are too old */
127# if __i386__
128# define __NR_signalfd4 327
129# elif __x86_64__
130# define __NR_signalfd4 289
131# elif __powerpc__
132# define __NR_signalfd4 313
133# elif __s390x__
134# define __NR_signalfd4 322
180edd67
SG
135# elif __arm__
136# define __NR_signalfd4 355
f53b5916
JC
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
b5159817
DE
143# endif
144#endif
145
146# ifndef __NR_signalfd
147/* assume kernel headers are too old */
148# if __i386__
149# define __NR_signalfd 321
150# elif __x86_64__
151# define __NR_signalfd 282
152# elif __powerpc__
153# define __NR_signalfd 305
154# elif __s390x__
155# define __NR_signalfd 316
180edd67
SG
156# elif __arm__
157# define __NR_signalfd 349
f53b5916
JC
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
b5159817
DE
164# endif
165#endif
166
167static inline int signalfd(int fd, const sigset_t *mask, int flags)
168{
169 int retval;
170
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);
174 return retval;
175}
176#endif
177
c6868a1f
CB
178/* loop devices */
179#ifndef LO_FLAGS_AUTOCLEAR
180#define LO_FLAGS_AUTOCLEAR 4
181#endif
182
183#ifndef LOOP_CTL_GET_FREE
184#define LOOP_CTL_GET_FREE 0x4C82
185#endif
186
ebec9176
AM
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.
191 */
192struct lxc_popen_FILE {
193 FILE *f;
194 pid_t child_pid;
195};
196
197/* popen(command, "re") replacement that restores default signal mask
198 * via sigprocmask(2) (unblocks all signals) after fork(2) but prior to calling exec(3).
199 * In short, popen(command, "re") does pipe() + fork() + exec()
200 * while lxc_popen(command) does pipe() + fork() + sigprocmask() + exec().
ebec9176
AM
201 * Returns pointer to struct lxc_popen_FILE, that should be freed with lxc_pclose().
202 * On error returns NULL.
203 */
204extern struct lxc_popen_FILE *lxc_popen(const char *command);
205
206/* pclose() replacement to be used on struct lxc_popen_FILE *,
207 * returned by lxc_popen().
208 * Waits for associated process to terminate, returns its exit status and
209 * frees resources, pointed to by struct lxc_popen_FILE *.
ebec9176
AM
210 */
211extern int lxc_pclose(struct lxc_popen_FILE *fp);
212
e51d4895
DE
213/**
214 * BUILD_BUG_ON - break compile if a condition is true.
215 * @condition: the condition which the compiler should know is false.
216 *
217 * If you have some code which relies on certain constants being equal, or
218 * other compile-time-evaluated condition, you should use BUILD_BUG_ON to
219 * detect if someone changes it.
220 *
221 * The implementation uses gcc's reluctance to create a negative array, but
222 * gcc (as of 4.4) only emits that error for obvious cases (eg. not arguments
223 * to inline functions). So as a fallback we use the optimizer; if it can't
224 * prove the condition is false, it will cause a link error on the undefined
225 * "__build_bug_on_failed". This error message can be harder to track down
226 * though, hence the two different methods.
227 */
228#ifndef __OPTIMIZE__
229#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
230#else
231extern int __build_bug_on_failed;
232#define BUILD_BUG_ON(condition) \
233 do { \
234 ((void)sizeof(char[1 - 2*!!(condition)])); \
235 if (condition) __build_bug_on_failed = 1; \
236 } while(0)
237#endif
238
9be53773
SH
239/*
240 * wait on a child we forked
241 */
242extern int wait_for_pid(pid_t pid);
c797a220 243extern int lxc_wait_for_pid_status(pid_t pid);
9be53773 244
92f023dc 245/* send and receive buffers completely */
650468bb
CS
246extern ssize_t lxc_write_nointr(int fd, const void* buf, size_t count);
247extern ssize_t lxc_read_nointr(int fd, void* buf, size_t count);
248extern ssize_t lxc_read_nointr_expect(int fd, void* buf, size_t count, const void* expected_buf);
3ce74686
SH
249#if HAVE_LIBGNUTLS
250#define SHA_DIGEST_LENGTH 20
251extern int sha1sum_file(char *fnam, unsigned char *md_value);
252#endif
92f023dc 253
0e95426b
CS
254/* read and write whole files */
255extern int lxc_write_to_file(const char *filename, const void* buf, size_t count, bool add_newline);
256extern int lxc_read_from_file(const char *filename, void* buf, size_t count);
0e95426b 257
61a1d519
CS
258/* convert variadic argument lists to arrays (for execl type argument lists) */
259extern char** lxc_va_arg_list_to_argv(va_list ap, size_t skip, int do_strdup);
260extern const char** lxc_va_arg_list_to_argv_const(va_list ap, size_t skip);
261
502657d5
CS
262/* Some simple string functions; if they return pointers, they are allocated buffers. */
263extern char *lxc_string_replace(const char *needle, const char *replacement, const char *haystack);
264extern bool lxc_string_in_array(const char *needle, const char **haystack);
265extern char *lxc_string_join(const char *sep, const char **parts, bool use_as_prefix);
266/* Normalize and split path: Leading and trailing / are removed, multiple
267 * / are compactified, .. and . are resolved (.. on the top level is considered
268 * identical to .).
269 * Examples:
270 * / -> { NULL }
271 * foo/../bar -> { bar, NULL }
272 * ../../ -> { NULL }
273 * ./bar/baz/.. -> { bar, NULL }
274 * foo//bar -> { foo, bar, NULL }
275 */
276extern char **lxc_normalize_path(const char *path);
aeb3682f 277/* remove multiple slashes from the path, e.g. ///foo//bar -> /foo/bar */
eda0afd4 278extern char *lxc_deslashify(const char *path);
24b51482 279extern char *lxc_append_paths(const char *first, const char *second);
502657d5
CS
280/* Note: the following two functions use strtok(), so they will never
281 * consider an empty element, even if two delimiters are next to
282 * each other.
283 */
284extern bool lxc_string_in_list(const char *needle, const char *haystack, char sep);
285extern char **lxc_string_split(const char *string, char sep);
286extern char **lxc_string_split_and_trim(const char *string, char sep);
000dfda7
CB
287/* Append string to NULL-terminated string array. */
288extern int lxc_append_string(char ***list, char *entry);
502657d5
CS
289
290/* some simple array manipulation utilities */
291typedef void (*lxc_free_fn)(void *);
292typedef void *(*lxc_dup_fn)(void *);
293extern int lxc_grow_array(void ***array, size_t* capacity, size_t new_size, size_t capacity_increment);
294extern void lxc_free_array(void **array, lxc_free_fn element_free_fn);
295extern size_t lxc_array_len(void **array);
502657d5 296
799f29ab 297extern void **lxc_append_null_to_array(void **array, size_t count);
1adbd020 298
a1e5280d 299/* mmap() wrapper. lxc_strmmap() will take care to \0-terminate files so that
1adbd020 300 * normal string-handling functions can be used on the buffer. */
25086a5f
CB
301extern void *lxc_strmmap(void *addr, size_t length, int prot, int flags, int fd,
302 off_t offset);
a1e5280d 303/* munmap() wrapper. Use it to free memory mmap()ed with lxc_strmmap(). */
25086a5f 304extern int lxc_strmunmap(void *addr, size_t length);
1adbd020 305
508c263e
SH
306//initialize rand with urandom
307extern int randseed(bool);
052616eb 308
1354955b
SH
309inline static bool am_unpriv(void) {
310 return geteuid() != 0;
311}
5d897655
SH
312
313/*
314 * parse /proc/self/uid_map to find what @orig maps to
315 */
316extern uid_t get_ns_uid(uid_t orig);
c476bdce
SH
317
318extern bool dir_exists(const char *path);
93c379f0
ÇO
319
320#define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
321uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval);
2c6f3fc9
SH
322
323int detect_shared_rootfs(void);
fa454c8e 324bool detect_ramfs_rootfs(void);
df6a2945 325char *on_path(const char *cmd, const char *rootfs);
76a26f55 326bool file_exists(const char *f);
12983ba4 327bool cgns_supported(void);
9d9c111c 328char *choose_init(const char *rootfs);
735f2c6e 329int print_to_file(const char *file, const char *content);
51d0854c 330bool switch_to_ns(pid_t pid, const char *ns);
e1daebd9 331int is_dir(const char *path);
6010a416 332char *get_template_path(const char *t);
0a4be28d 333int setproctitle(char *title);
592fd47a
SH
334int safe_mount(const char *src, const char *dest, const char *fstype,
335 unsigned long flags, const void *data, const char *rootfs);
943144d9 336int lxc_mount_proc_if_needed(const char *rootfs);
f8dd0275
AM
337int open_devnull(void);
338int set_stdfds(int fd);
69aeabac 339int null_stdfds(void);
ccb4cabe 340int lxc_count_file_lines(const char *fn);
a687256f 341int lxc_preserve_ns(const int pid, const char *ns);
330ae3d3
CB
342
343/* Check whether a signal is blocked by a process. */
344bool task_blocking_signal(pid_t pid, int signal);
6bc2eafe
CB
345
346/* Helper functions to parse numbers. */
347int lxc_safe_uint(const char *numstr, unsigned int *converted);
b5f845e7 348int lxc_safe_int(const char *numstr, int *converted);
8c57d930 349int lxc_safe_long(const char *numstr, long int *converted);
681188c1 350int lxc_safe_ulong(const char *numstr, unsigned long *converted);
6bc2eafe 351
dbaf55a3
CB
352/* Switch to a new uid and gid. */
353int lxc_switch_uid_gid(uid_t uid, gid_t gid);
354int lxc_setgroups(int size, gid_t list[]);
355
c6868a1f
CB
356/* Find an unused loop device and associate it with source. */
357int lxc_prepare_loop_dev(const char *source, char *loop_dev, int flags);
358
74251e49
CB
359/* Clear all mounts on a given node.
360 * >= 0 successfully cleared. The number returned is the number of umounts
361 * performed.
362 * < 0 error umounting. Return -errno.
363 */
364int lxc_unstack_mountpoint(const char *path, bool lazy);
365
ea3a694f
CB
366/*
367 * run_command runs a command and collect it's std{err,out} output in buf.
368 *
369 * @param[out] buf The buffer where the commands std{err,out] output will be
370 * read into. If no output was produced, buf will be memset
371 * to 0.
372 * @param[in] buf_size The size of buf. This function will reserve one byte for
373 * \0-termination.
374 * @param[in] child_fn The function to be run in the child process. This
375 * function must exec.
376 * @param[in] args Arguments to be passed to child_fn.
377 */
378int run_command(char *buf, size_t buf_size, int (*child_fn)(void *), void *args);
379
04ad7ffe
CB
380/* Concatenate all passed-in strings into one path. Do not fail. If any piece
381 * is not prefixed with '/', add a '/'.
382 */
383char *must_make_path(const char *first, ...) __attribute__((sentinel));
384
385/* return copy of string @entry; do not fail. */
386char *must_copy_string(const char *entry);
387
388/* Re-alllocate a pointer, do not fail */
389void *must_realloc(void *orig, size_t sz);
390
a035c53a
CB
391/* __typeof__ should be safe to use with all compilers. */
392typedef __typeof__(((struct statfs *)NULL)->f_type) fs_type_magic;
393bool has_fs_type(const char *path, fs_type_magic magic_val);
394bool is_fs_type(const struct statfs *fs, fs_type_magic magic_val);
395
5b72de5f 396#endif /* __LXC_UTILS_H */