]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/utils.h
utils: add lxc_getpagesize()
[mirror_lxc.git] / src / lxc / utils.h
1 /*
2 * lxc: linux Container library
3 *
4 * (C) Copyright IBM Corp. 2007, 2008
5 *
6 * Authors:
7 * Daniel Lezcano <daniel.lezcano at free.fr>
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
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23 #ifndef __LXC_UTILS_H
24 #define __LXC_UTILS_H
25
26 /* Properly support loop devices on 32bit systems. */
27 #define _FILE_OFFSET_BITS 64
28
29 #include "config.h"
30
31 #include <errno.h>
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <stdbool.h>
35 #include <unistd.h>
36 #include <linux/loop.h>
37 #include <linux/magic.h>
38 #include <sys/syscall.h>
39 #include <sys/types.h>
40 #include <sys/vfs.h>
41
42 #ifdef HAVE_LINUX_MEMFD_H
43 #include <linux/memfd.h>
44 #endif
45
46 #include "initutils.h"
47
48 /* Define __S_ISTYPE if missing from the C library. */
49 #ifndef __S_ISTYPE
50 #define __S_ISTYPE(mode, mask) (((mode)&S_IFMT) == (mask))
51 #endif
52
53 /* Useful macros */
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
58
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);
64
65 /* Define getline() if missing from the C library */
66 #ifndef HAVE_GETLINE
67 #ifdef HAVE_FGETLN
68 #include <../include/getline.h>
69 #endif
70 #endif
71
72 /* Define setns() if missing from the C library */
73 #ifndef HAVE_SETNS
74 static inline int setns(int fd, int nstype)
75 {
76 #ifdef __NR_setns
77 return syscall(__NR_setns, fd, nstype);
78 #elif defined(__NR_set_ns)
79 return syscall(__NR_set_ns, fd, nstype);
80 #else
81 errno = ENOSYS;
82 return -1;
83 #endif
84 }
85 #endif
86
87 /* Define unshare() if missing from the C library */
88 #ifndef HAVE_UNSHARE
89 static inline int unshare(int flags)
90 {
91 #ifdef __NR_unshare
92 return syscall(__NR_unshare, flags);
93 #else
94 errno = ENOSYS;
95 return -1;
96 #endif
97 }
98 #else
99 extern int unshare(int);
100 #endif
101
102 /* Define signalfd() if missing from the C library */
103 #ifdef HAVE_SYS_SIGNALFD_H
104 # include <sys/signalfd.h>
105 #else
106 /* assume kernel headers are too old */
107 #include <stdint.h>
108 struct signalfd_siginfo
109 {
110 uint32_t ssi_signo;
111 int32_t ssi_errno;
112 int32_t ssi_code;
113 uint32_t ssi_pid;
114 uint32_t ssi_uid;
115 int32_t ssi_fd;
116 uint32_t ssi_tid;
117 uint32_t ssi_band;
118 uint32_t ssi_overrun;
119 uint32_t ssi_trapno;
120 int32_t ssi_status;
121 int32_t ssi_int;
122 uint64_t ssi_ptr;
123 uint64_t ssi_utime;
124 uint64_t ssi_stime;
125 uint64_t ssi_addr;
126 uint8_t __pad[48];
127 };
128
129 # ifndef __NR_signalfd4
130 /* assume kernel headers are too old */
131 # if __i386__
132 # define __NR_signalfd4 327
133 # elif __x86_64__
134 # define __NR_signalfd4 289
135 # elif __powerpc__
136 # define __NR_signalfd4 313
137 # elif __s390x__
138 # define __NR_signalfd4 322
139 # elif __arm__
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
147 # endif
148 #endif
149
150 # ifndef __NR_signalfd
151 /* assume kernel headers are too old */
152 # if __i386__
153 # define __NR_signalfd 321
154 # elif __x86_64__
155 # define __NR_signalfd 282
156 # elif __powerpc__
157 # define __NR_signalfd 305
158 # elif __s390x__
159 # define __NR_signalfd 316
160 # elif __arm__
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
168 # endif
169 #endif
170
171 static inline int signalfd(int fd, const sigset_t *mask, int flags)
172 {
173 int retval;
174
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);
178 return retval;
179 }
180 #endif
181
182 /* loop devices */
183 #ifndef LO_FLAGS_AUTOCLEAR
184 #define LO_FLAGS_AUTOCLEAR 4
185 #endif
186
187 #ifndef LOOP_CTL_GET_FREE
188 #define LOOP_CTL_GET_FREE 0x4C82
189 #endif
190
191 /* memfd_create() */
192 #ifndef MFD_CLOEXEC
193 #define MFD_CLOEXEC 0x0001U
194 #endif
195
196 #ifndef MFD_ALLOW_SEALING
197 #define MFD_ALLOW_SEALING 0x0002U
198 #endif
199
200 #ifndef HAVE_MEMFD_CREATE
201 static inline int memfd_create(const char *name, unsigned int flags) {
202 #ifndef __NR_memfd_create
203 #if defined __i386__
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
224 #endif
225 #if _MIPS_SIM == _MIPS_SIM_NABI32
226 #define __NR_memfd_create 6318
227 #endif
228 #if _MIPS_SIM == _MIPS_SIM_ABI64
229 #define __NR_memfd_create 5314
230 #endif
231 #endif
232 #endif
233 #ifdef __NR_memfd_create
234 return syscall(__NR_memfd_create, name, flags);
235 #else
236 errno = ENOSYS;
237 return -1;
238 #endif
239 }
240 #else
241 extern int memfd_create(const char *name, unsigned int flags);
242 #endif
243
244 static inline int lxc_set_cloexec(int fd)
245 {
246 return fcntl(fd, F_SETFD, FD_CLOEXEC);
247 }
248
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.
253 */
254 struct lxc_popen_FILE {
255 int pipe;
256 FILE *f;
257 pid_t child_pid;
258 };
259
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.
266 */
267 extern struct lxc_popen_FILE *lxc_popen(const char *command);
268
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 *.
273 */
274 extern int lxc_pclose(struct lxc_popen_FILE *fp);
275
276 /**
277 * BUILD_BUG_ON - break compile if a condition is true.
278 * @condition: the condition which the compiler should know is false.
279 *
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.
283 *
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.
290 */
291 #ifndef __OPTIMIZE__
292 #define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
293 #else
294 extern int __build_bug_on_failed;
295 #define BUILD_BUG_ON(condition) \
296 do { \
297 ((void)sizeof(char[1 - 2*!!(condition)])); \
298 if (condition) __build_bug_on_failed = 1; \
299 } while(0)
300 #endif
301
302 /*
303 * wait on a child we forked
304 */
305 extern int wait_for_pid(pid_t pid);
306 extern int lxc_wait_for_pid_status(pid_t pid);
307
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);
313 #if HAVE_LIBGNUTLS
314 #define SHA_DIGEST_LENGTH 20
315 extern int sha1sum_file(char *fnam, unsigned char *md_value);
316 #endif
317
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);
322
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);
326
327 /* Some simple string functions; if they return pointers, they are allocated
328 * buffers.
329 */
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,
334 bool use_as_prefix);
335 /* Normalize and split path: Leading and trailing / are removed, multiple
336 * / are compactified, .. and . are resolved (.. on the top level is considered
337 * identical to .).
338 * Examples:
339 * / -> { NULL }
340 * foo/../bar -> { bar, NULL }
341 * ../../ -> { NULL }
342 * ./bar/baz/.. -> { bar, NULL }
343 * foo//bar -> { foo, bar, NULL }
344 */
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
351 * each other.
352 */
353 extern bool lxc_string_in_list(const char *needle, const char *haystack,
354 char sep);
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);
360
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);
368
369 extern void **lxc_append_null_to_array(void **array, size_t count);
370
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,
374 off_t offset);
375 /* munmap() wrapper. Use it to free memory mmap()ed with lxc_strmmap(). */
376 extern int lxc_strmunmap(void *addr, size_t length);
377
378 /* initialize rand with urandom */
379 extern int randseed(bool);
380
381 inline static bool am_unpriv(void) {
382 return geteuid() != 0;
383 }
384
385 /*
386 * parse /proc/self/uid_map to find what @orig maps to
387 */
388 extern uid_t get_ns_uid(uid_t orig);
389
390 extern bool dir_exists(const char *path);
391
392 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
393 extern uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval);
394
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,
407 const char *rootfs);
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);
414
415 /* Check whether a signal is blocked by a process. */
416 extern bool task_blocking_signal(pid_t pid, int signal);
417
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);
423
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[]);
427
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);
430
431 /* Clear all mounts on a given node.
432 * >= 0 successfully cleared. The number returned is the number of umounts
433 * performed.
434 * < 0 error umounting. Return -errno.
435 */
436 extern int lxc_unstack_mountpoint(const char *path, bool lazy);
437
438 /*
439 * run_command runs a command and collect it's std{err,out} output in buf.
440 *
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
443 * to 0.
444 * @param[in] buf_size The size of buf. This function will reserve one byte for
445 * \0-termination.
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.
449 */
450 extern int run_command(char *buf, size_t buf_size, int (*child_fn)(void *),
451 void *args);
452
453 /* Concatenate all passed-in strings into one path. Do not fail. If any piece
454 * is not prefixed with '/', add a '/'.
455 */
456 extern char *must_make_path(const char *first, ...) __attribute__((sentinel));
457
458 /* return copy of string @entry; do not fail. */
459 extern char *must_copy_string(const char *entry);
460
461 /* Re-alllocate a pointer, do not fail */
462 extern void *must_realloc(void *orig, size_t sz);
463
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);
471
472 #endif /* __LXC_UTILS_H */