]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/utils.h
utils: define __NR_setns if missing on old glibcs
[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 <linux/types.h>
39 #include <sys/syscall.h>
40 #include <sys/types.h>
41 #include <sys/vfs.h>
42
43 #ifdef HAVE_LINUX_MEMFD_H
44 #include <linux/memfd.h>
45 #endif
46
47 #include "initutils.h"
48
49 /* Define __S_ISTYPE if missing from the C library. */
50 #ifndef __S_ISTYPE
51 #define __S_ISTYPE(mode, mask) (((mode)&S_IFMT) == (mask))
52 #endif
53
54 #if HAVE_LIBCAP
55 #ifndef CAP_SETFCAP
56 #define CAP_SETFCAP 31
57 #endif
58
59 #ifndef CAP_MAC_OVERRIDE
60 #define CAP_MAC_OVERRIDE 32
61 #endif
62
63 #ifndef CAP_MAC_ADMIN
64 #define CAP_MAC_ADMIN 33
65 #endif
66 #endif
67
68 #ifndef PR_CAPBSET_DROP
69 #define PR_CAPBSET_DROP 24
70 #endif
71
72 #ifndef LO_FLAGS_AUTOCLEAR
73 #define LO_FLAGS_AUTOCLEAR 4
74 #endif
75
76 #ifndef CAP_SETUID
77 #define CAP_SETUID 7
78 #endif
79
80 #ifndef CAP_SETGID
81 #define CAP_SETGID 6
82 #endif
83
84 /* needed for cgroup automount checks, regardless of whether we
85 * have included linux/capability.h or not */
86 #ifndef CAP_SYS_ADMIN
87 #define CAP_SYS_ADMIN 21
88 #endif
89
90 #ifndef CGROUP_SUPER_MAGIC
91 #define CGROUP_SUPER_MAGIC 0x27e0eb
92 #endif
93
94 #ifndef CGROUP2_SUPER_MAGIC
95 #define CGROUP2_SUPER_MAGIC 0x63677270
96 #endif
97
98 /* Useful macros */
99 /* Maximum number for 64 bit integer is a string with 21 digits: 2^64 - 1 = 21 */
100 #define LXC_NUMSTRLEN64 21
101 #define LXC_LINELEN 4096
102 #define LXC_IDMAPLEN 4096
103 #define LXC_MAX_BUFFER 4096
104
105 /* returns 1 on success, 0 if there were any failures */
106 extern int lxc_rmdir_onedev(const char *path, const char *exclude);
107 extern int get_u16(unsigned short *val, const char *arg, int base);
108 extern int mkdir_p(const char *dir, mode_t mode);
109 extern char *get_rundir(void);
110
111 /* Define getline() if missing from the C library */
112 #ifndef HAVE_GETLINE
113 #ifdef HAVE_FGETLN
114 #include <../include/getline.h>
115 #endif
116 #endif
117
118 #if !defined(__NR_setns) && !defined(__NR_set_ns)
119 #if defined(__x86_64__)
120 #define __NR_setns 308
121 #elif defined(__i386__)
122 #define __NR_setns 346
123 #elif defined(__arm__)
124 #define __NR_setns 375
125 #elif defined(__aarch64__)
126 #define __NR_setns 375
127 #elif defined(__powerpc__)
128 #define __NR_setns 350
129 #elif defined(__s390__)
130 #define __NR_setns 339
131 #endif
132 #endif
133
134 /* Define setns() if missing from the C library */
135 #ifndef HAVE_SETNS
136 static inline int setns(int fd, int nstype)
137 {
138 #ifdef __NR_setns
139 return syscall(__NR_setns, fd, nstype);
140 #elif defined(__NR_set_ns)
141 return syscall(__NR_set_ns, fd, nstype);
142 #else
143 errno = ENOSYS;
144 return -1;
145 #endif
146 }
147 #endif
148
149 /* Define sethostname() if missing from the C library */
150 #ifndef HAVE_SETHOSTNAME
151 static inline int sethostname(const char * name, size_t len)
152 {
153 #ifdef __NR_sethostname
154 return syscall(__NR_sethostname, name, len);
155 #else
156 errno = ENOSYS;
157 return -1;
158 #endif
159 }
160 #endif
161
162 /* Define unshare() if missing from the C library */
163 #ifndef HAVE_UNSHARE
164 static inline int unshare(int flags)
165 {
166 #ifdef __NR_unshare
167 return syscall(__NR_unshare, flags);
168 #else
169 errno = ENOSYS;
170 return -1;
171 #endif
172 }
173 #else
174 extern int unshare(int);
175 #endif
176
177 /* Define signalfd() if missing from the C library */
178 #ifdef HAVE_SYS_SIGNALFD_H
179 # include <sys/signalfd.h>
180 #else
181 /* assume kernel headers are too old */
182 #include <stdint.h>
183 struct signalfd_siginfo
184 {
185 uint32_t ssi_signo;
186 int32_t ssi_errno;
187 int32_t ssi_code;
188 uint32_t ssi_pid;
189 uint32_t ssi_uid;
190 int32_t ssi_fd;
191 uint32_t ssi_tid;
192 uint32_t ssi_band;
193 uint32_t ssi_overrun;
194 uint32_t ssi_trapno;
195 int32_t ssi_status;
196 int32_t ssi_int;
197 uint64_t ssi_ptr;
198 uint64_t ssi_utime;
199 uint64_t ssi_stime;
200 uint64_t ssi_addr;
201 uint8_t __pad[48];
202 };
203
204 # ifndef __NR_signalfd4
205 /* assume kernel headers are too old */
206 # if __i386__
207 # define __NR_signalfd4 327
208 # elif __x86_64__
209 # define __NR_signalfd4 289
210 # elif __powerpc__
211 # define __NR_signalfd4 313
212 # elif __s390x__
213 # define __NR_signalfd4 322
214 # elif __arm__
215 # define __NR_signalfd4 355
216 # elif __mips__ && _MIPS_SIM == _ABIO32
217 # define __NR_signalfd4 4324
218 # elif __mips__ && _MIPS_SIM == _ABI64
219 # define __NR_signalfd4 5283
220 # elif __mips__ && _MIPS_SIM == _ABIN32
221 # define __NR_signalfd4 6287
222 # endif
223 #endif
224
225 # ifndef __NR_signalfd
226 /* assume kernel headers are too old */
227 # if __i386__
228 # define __NR_signalfd 321
229 # elif __x86_64__
230 # define __NR_signalfd 282
231 # elif __powerpc__
232 # define __NR_signalfd 305
233 # elif __s390x__
234 # define __NR_signalfd 316
235 # elif __arm__
236 # define __NR_signalfd 349
237 # elif __mips__ && _MIPS_SIM == _ABIO32
238 # define __NR_signalfd 4317
239 # elif __mips__ && _MIPS_SIM == _ABI64
240 # define __NR_signalfd 5276
241 # elif __mips__ && _MIPS_SIM == _ABIN32
242 # define __NR_signalfd 6280
243 # endif
244 #endif
245
246 static inline int signalfd(int fd, const sigset_t *mask, int flags)
247 {
248 int retval;
249
250 retval = syscall (__NR_signalfd4, fd, mask, _NSIG / 8, flags);
251 if (errno == ENOSYS && flags == 0)
252 retval = syscall (__NR_signalfd, fd, mask, _NSIG / 8);
253 return retval;
254 }
255 #endif
256
257 /* loop devices */
258 #ifndef LO_FLAGS_AUTOCLEAR
259 #define LO_FLAGS_AUTOCLEAR 4
260 #endif
261
262 #ifndef LOOP_CTL_GET_FREE
263 #define LOOP_CTL_GET_FREE 0x4C82
264 #endif
265
266 /* memfd_create() */
267 #ifndef MFD_CLOEXEC
268 #define MFD_CLOEXEC 0x0001U
269 #endif
270
271 #ifndef MFD_ALLOW_SEALING
272 #define MFD_ALLOW_SEALING 0x0002U
273 #endif
274
275 #ifndef HAVE_MEMFD_CREATE
276 static inline int memfd_create(const char *name, unsigned int flags) {
277 #ifndef __NR_memfd_create
278 #if defined __i386__
279 #define __NR_memfd_create 356
280 #elif defined __x86_64__
281 #define __NR_memfd_create 319
282 #elif defined __arm__
283 #define __NR_memfd_create 385
284 #elif defined __aarch64__
285 #define __NR_memfd_create 279
286 #elif defined __s390__
287 #define __NR_memfd_create 350
288 #elif defined __powerpc__
289 #define __NR_memfd_create 360
290 #elif defined __sparc__
291 #define __NR_memfd_create 348
292 #elif defined __blackfin__
293 #define __NR_memfd_create 390
294 #elif defined __ia64__
295 #define __NR_memfd_create 1340
296 #elif defined _MIPS_SIM
297 #if _MIPS_SIM == _MIPS_SIM_ABI32
298 #define __NR_memfd_create 4354
299 #endif
300 #if _MIPS_SIM == _MIPS_SIM_NABI32
301 #define __NR_memfd_create 6318
302 #endif
303 #if _MIPS_SIM == _MIPS_SIM_ABI64
304 #define __NR_memfd_create 5314
305 #endif
306 #endif
307 #endif
308 #ifdef __NR_memfd_create
309 return syscall(__NR_memfd_create, name, flags);
310 #else
311 errno = ENOSYS;
312 return -1;
313 #endif
314 }
315 #else
316 extern int memfd_create(const char *name, unsigned int flags);
317 #endif
318
319 static inline int lxc_set_cloexec(int fd)
320 {
321 return fcntl(fd, F_SETFD, FD_CLOEXEC);
322 }
323
324 /* Struct to carry child pid from lxc_popen() to lxc_pclose().
325 * Not an opaque struct to allow direct access to the underlying FILE *
326 * (i.e., struct lxc_popen_FILE *file; fgets(buf, sizeof(buf), file->f))
327 * without additional wrappers.
328 */
329 struct lxc_popen_FILE {
330 int pipe;
331 FILE *f;
332 pid_t child_pid;
333 };
334
335 /* popen(command, "re") replacement that restores default signal mask
336 * via sigprocmask(2) (unblocks all signals) after fork(2) but prior to calling exec(3).
337 * In short, popen(command, "re") does pipe() + fork() + exec()
338 * while lxc_popen(command) does pipe() + fork() + sigprocmask() + exec().
339 * Returns pointer to struct lxc_popen_FILE, that should be freed with lxc_pclose().
340 * On error returns NULL.
341 */
342 extern struct lxc_popen_FILE *lxc_popen(const char *command);
343
344 /* pclose() replacement to be used on struct lxc_popen_FILE *,
345 * returned by lxc_popen().
346 * Waits for associated process to terminate, returns its exit status and
347 * frees resources, pointed to by struct lxc_popen_FILE *.
348 */
349 extern int lxc_pclose(struct lxc_popen_FILE *fp);
350
351 /**
352 * BUILD_BUG_ON - break compile if a condition is true.
353 * @condition: the condition which the compiler should know is false.
354 *
355 * If you have some code which relies on certain constants being equal, or
356 * other compile-time-evaluated condition, you should use BUILD_BUG_ON to
357 * detect if someone changes it.
358 *
359 * The implementation uses gcc's reluctance to create a negative array, but
360 * gcc (as of 4.4) only emits that error for obvious cases (eg. not arguments
361 * to inline functions). So as a fallback we use the optimizer; if it can't
362 * prove the condition is false, it will cause a link error on the undefined
363 * "__build_bug_on_failed". This error message can be harder to track down
364 * though, hence the two different methods.
365 */
366 #ifndef __OPTIMIZE__
367 #define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
368 #else
369 extern int __build_bug_on_failed;
370 #define BUILD_BUG_ON(condition) \
371 do { \
372 ((void)sizeof(char[1 - 2*!!(condition)])); \
373 if (condition) __build_bug_on_failed = 1; \
374 } while(0)
375 #endif
376
377 /*
378 * wait on a child we forked
379 */
380 extern int wait_for_pid(pid_t pid);
381 extern int lxc_wait_for_pid_status(pid_t pid);
382
383 /* send and receive buffers completely */
384 extern ssize_t lxc_write_nointr(int fd, const void* buf, size_t count);
385 extern ssize_t lxc_read_nointr(int fd, void* buf, size_t count);
386 extern ssize_t lxc_read_nointr_expect(int fd, void *buf, size_t count,
387 const void *expected_buf);
388 #if HAVE_LIBGNUTLS
389 #define SHA_DIGEST_LENGTH 20
390 extern int sha1sum_file(char *fnam, unsigned char *md_value);
391 #endif
392
393 /* read and write whole files */
394 extern int lxc_write_to_file(const char *filename, const void *buf,
395 size_t count, bool add_newline);
396 extern int lxc_read_from_file(const char *filename, void* buf, size_t count);
397
398 /* convert variadic argument lists to arrays (for execl type argument lists) */
399 extern char** lxc_va_arg_list_to_argv(va_list ap, size_t skip, int do_strdup);
400 extern const char** lxc_va_arg_list_to_argv_const(va_list ap, size_t skip);
401
402 /* Some simple string functions; if they return pointers, they are allocated
403 * buffers.
404 */
405 extern char *lxc_string_replace(const char *needle, const char *replacement,
406 const char *haystack);
407 extern bool lxc_string_in_array(const char *needle, const char **haystack);
408 extern char *lxc_string_join(const char *sep, const char **parts,
409 bool use_as_prefix);
410 /* Normalize and split path: Leading and trailing / are removed, multiple
411 * / are compactified, .. and . are resolved (.. on the top level is considered
412 * identical to .).
413 * Examples:
414 * / -> { NULL }
415 * foo/../bar -> { bar, NULL }
416 * ../../ -> { NULL }
417 * ./bar/baz/.. -> { bar, NULL }
418 * foo//bar -> { foo, bar, NULL }
419 */
420 extern char **lxc_normalize_path(const char *path);
421 /* remove multiple slashes from the path, e.g. ///foo//bar -> /foo/bar */
422 extern char *lxc_deslashify(const char *path);
423 extern char *lxc_append_paths(const char *first, const char *second);
424 /* Note: the following two functions use strtok(), so they will never
425 * consider an empty element, even if two delimiters are next to
426 * each other.
427 */
428 extern bool lxc_string_in_list(const char *needle, const char *haystack,
429 char sep);
430 extern char **lxc_string_split(const char *string, char sep);
431 extern char **lxc_string_split_and_trim(const char *string, char sep);
432 extern char **lxc_string_split_quoted(char *string);
433 /* Append string to NULL-terminated string array. */
434 extern int lxc_append_string(char ***list, char *entry);
435
436 /* some simple array manipulation utilities */
437 typedef void (*lxc_free_fn)(void *);
438 typedef void *(*lxc_dup_fn)(void *);
439 extern int lxc_grow_array(void ***array, size_t *capacity, size_t new_size,
440 size_t capacity_increment);
441 extern void lxc_free_array(void **array, lxc_free_fn element_free_fn);
442 extern size_t lxc_array_len(void **array);
443
444 extern void **lxc_append_null_to_array(void **array, size_t count);
445
446 /* initialize rand with urandom */
447 extern int randseed(bool);
448
449 /* are we unprivileged with respect to our namespaces */
450 inline static bool am_guest_unpriv(void) {
451 return geteuid() != 0;
452 }
453
454 /* are we unprivileged with respect to init_user_ns */
455 inline static bool am_host_unpriv(void)
456 {
457 FILE *f;
458 uid_t user, host, count;
459 int ret;
460
461 if (geteuid() != 0)
462 return true;
463
464 /* Now: are we in a user namespace? Because then we're also
465 * unprivileged.
466 */
467 f = fopen("/proc/self/uid_map", "r");
468 if (!f) {
469 return false;
470 }
471
472 ret = fscanf(f, "%u %u %u", &user, &host, &count);
473 fclose(f);
474 if (ret != 3) {
475 return false;
476 }
477
478 if (user != 0 || host != 0 || count != UINT32_MAX)
479 return true;
480 return false;
481 }
482
483 /*
484 * parse /proc/self/uid_map to find what @orig maps to
485 */
486 extern uid_t get_ns_uid(uid_t orig);
487
488 extern bool dir_exists(const char *path);
489
490 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
491 extern uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval);
492
493 extern int detect_shared_rootfs(void);
494 extern bool detect_ramfs_rootfs(void);
495 extern char *on_path(const char *cmd, const char *rootfs);
496 extern bool file_exists(const char *f);
497 extern bool cgns_supported(void);
498 extern char *choose_init(const char *rootfs);
499 extern int print_to_file(const char *file, const char *content);
500 extern bool switch_to_ns(pid_t pid, const char *ns);
501 extern int is_dir(const char *path);
502 extern char *get_template_path(const char *t);
503 extern int safe_mount(const char *src, const char *dest, const char *fstype,
504 unsigned long flags, const void *data,
505 const char *rootfs);
506 extern int lxc_mount_proc_if_needed(const char *rootfs);
507 extern int open_devnull(void);
508 extern int set_stdfds(int fd);
509 extern int null_stdfds(void);
510 extern int lxc_count_file_lines(const char *fn);
511 extern int lxc_preserve_ns(const int pid, const char *ns);
512
513 /* Check whether a signal is blocked by a process. */
514 extern bool task_blocking_signal(pid_t pid, int signal);
515
516 /* Helper functions to parse numbers. */
517 extern int lxc_safe_uint(const char *numstr, unsigned int *converted);
518 extern int lxc_safe_int(const char *numstr, int *converted);
519 extern int lxc_safe_long(const char *numstr, long int *converted);
520 extern int lxc_safe_long_long(const char *numstr, long long int *converted);
521 extern int lxc_safe_ulong(const char *numstr, unsigned long *converted);
522 /* Handles B, kb, MB, GB. Detects overflows and reports -ERANGE. */
523 extern int parse_byte_size_string(const char *s, int64_t *converted);
524
525 /* Switch to a new uid and gid. */
526 extern int lxc_switch_uid_gid(uid_t uid, gid_t gid);
527 extern int lxc_setgroups(int size, gid_t list[]);
528
529 /* Find an unused loop device and associate it with source. */
530 extern int lxc_prepare_loop_dev(const char *source, char *loop_dev, int flags);
531
532 /* Clear all mounts on a given node.
533 * >= 0 successfully cleared. The number returned is the number of umounts
534 * performed.
535 * < 0 error umounting. Return -errno.
536 */
537 extern int lxc_unstack_mountpoint(const char *path, bool lazy);
538
539 /*
540 * run_command runs a command and collect it's std{err,out} output in buf.
541 *
542 * @param[out] buf The buffer where the commands std{err,out] output will be
543 * read into. If no output was produced, buf will be memset
544 * to 0.
545 * @param[in] buf_size The size of buf. This function will reserve one byte for
546 * \0-termination.
547 * @param[in] child_fn The function to be run in the child process. This
548 * function must exec.
549 * @param[in] args Arguments to be passed to child_fn.
550 */
551 extern int run_command(char *buf, size_t buf_size, int (*child_fn)(void *),
552 void *args);
553
554 /* Concatenate all passed-in strings into one path. Do not fail. If any piece
555 * is not prefixed with '/', add a '/'.
556 */
557 __attribute__((sentinel)) extern char *must_make_path(const char *first, ...);
558 __attribute__((sentinel)) extern char *must_append_path(char *first, ...);
559
560 /* return copy of string @entry; do not fail. */
561 extern char *must_copy_string(const char *entry);
562
563 /* Re-alllocate a pointer, do not fail */
564 extern void *must_realloc(void *orig, size_t sz);
565
566 /* __typeof__ should be safe to use with all compilers. */
567 typedef __typeof__(((struct statfs *)NULL)->f_type) fs_type_magic;
568 extern bool has_fs_type(const char *path, fs_type_magic magic_val);
569 extern bool is_fs_type(const struct statfs *fs, fs_type_magic magic_val);
570 extern bool lxc_nic_exists(char *nic);
571 extern int lxc_make_tmpfile(char *template, bool rm);
572
573 static inline uint64_t lxc_getpagesize(void)
574 {
575 int64_t pgsz;
576
577 pgsz = sysconf(_SC_PAGESIZE);
578 if (pgsz <= 0)
579 pgsz = 1 << 12;
580
581 return pgsz;
582 }
583
584 /* If n is not a power of 2 this function will return the next power of 2
585 * greater than that number. Note that this function always returns the *next*
586 * power of 2 *greater* that number not the *nearest*. For example, passing 1025
587 * as argument this function will return 2048 although the closest power of 2
588 * would be 1024.
589 * If the caller passes in 0 they will receive 0 in return since this is invalid
590 * input and 0 is not a power of 2.
591 */
592 extern uint64_t lxc_find_next_power2(uint64_t n);
593
594 static inline pid_t lxc_raw_gettid(void)
595 {
596 #ifdef SYS_gettid
597 return syscall(SYS_gettid);
598 #else
599 return lxc_raw_getpid();
600 #endif
601 }
602
603 /* Set a signal the child process will receive after the parent has died. */
604 extern int lxc_set_death_signal(int signal);
605
606 #endif /* __LXC_UTILS_H */