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