]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/util.h
util-lib: split out hex/dec/oct encoding/decoding into its own file
[thirdparty/systemd.git] / src / basic / util.h
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 #pragma once
4
5 /***
6 This file is part of systemd.
7
8 Copyright 2010 Lennart Poettering
9
10 systemd is free software; you can redistribute it and/or modify it
11 under the terms of the GNU Lesser General Public License as published by
12 the Free Software Foundation; either version 2.1 of the License, or
13 (at your option) any later version.
14
15 systemd is distributed in the hope that it will be useful, but
16 WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 Lesser General Public License for more details.
19
20 You should have received a copy of the GNU Lesser General Public License
21 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 ***/
23
24 #include <alloca.h>
25 #include <dirent.h>
26 #include <fcntl.h>
27 #include <inttypes.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <mntent.h>
31 #include <stdarg.h>
32 #include <stdbool.h>
33 #include <stddef.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <sys/inotify.h>
37 #include <sys/socket.h>
38 #include <sys/stat.h>
39 #include <sys/statfs.h>
40 #include <sys/types.h>
41 #include <time.h>
42 #include <unistd.h>
43
44 #include "formats-util.h"
45 #include "macro.h"
46 #include "missing.h"
47 #include "time-util.h"
48
49 /* What is interpreted as whitespace? */
50 #define WHITESPACE " \t\n\r"
51 #define NEWLINE "\n\r"
52 #define QUOTES "\"\'"
53 #define COMMENTS "#;"
54 #define GLOB_CHARS "*?["
55
56 size_t page_size(void) _pure_;
57 #define PAGE_ALIGN(l) ALIGN_TO((l), page_size())
58
59 #define new(t, n) ((t*) malloc_multiply(sizeof(t), (n)))
60
61 #define new0(t, n) ((t*) calloc((n), sizeof(t)))
62
63 #define newa(t, n) ((t*) alloca(sizeof(t)*(n)))
64
65 #define newa0(t, n) ((t*) alloca0(sizeof(t)*(n)))
66
67 #define newdup(t, p, n) ((t*) memdup_multiply(p, sizeof(t), (n)))
68
69 #define malloc0(n) (calloc(1, (n)))
70
71 static inline void *mfree(void *memory) {
72 free(memory);
73 return NULL;
74 }
75
76 static inline const char* yes_no(bool b) {
77 return b ? "yes" : "no";
78 }
79
80 static inline const char* true_false(bool b) {
81 return b ? "true" : "false";
82 }
83
84 static inline const char* one_zero(bool b) {
85 return b ? "1" : "0";
86 }
87
88 int readlinkat_malloc(int fd, const char *p, char **ret);
89 int readlink_malloc(const char *p, char **r);
90 int readlink_value(const char *p, char **ret);
91 int readlink_and_make_absolute(const char *p, char **r);
92 int readlink_and_canonicalize(const char *p, char **r);
93
94 char *file_in_same_dir(const char *path, const char *filename);
95
96 int rmdir_parents(const char *path, const char *stop);
97
98 bool dirent_is_file(const struct dirent *de) _pure_;
99 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) _pure_;
100
101 bool hidden_file(const char *filename) _pure_;
102
103 /* For basic lookup tables with strictly enumerated entries */
104 #define _DEFINE_STRING_TABLE_LOOKUP_TO_STRING(name,type,scope) \
105 scope const char *name##_to_string(type i) { \
106 if (i < 0 || i >= (type) ELEMENTSOF(name##_table)) \
107 return NULL; \
108 return name##_table[i]; \
109 }
110
111 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key);
112
113 #define _DEFINE_STRING_TABLE_LOOKUP_FROM_STRING(name,type,scope) \
114 scope type name##_from_string(const char *s) { \
115 return (type) string_table_lookup(name##_table, ELEMENTSOF(name##_table), s); \
116 }
117
118 #define _DEFINE_STRING_TABLE_LOOKUP(name,type,scope) \
119 _DEFINE_STRING_TABLE_LOOKUP_TO_STRING(name,type,scope) \
120 _DEFINE_STRING_TABLE_LOOKUP_FROM_STRING(name,type,scope) \
121 struct __useless_struct_to_allow_trailing_semicolon__
122
123 #define DEFINE_STRING_TABLE_LOOKUP(name,type) _DEFINE_STRING_TABLE_LOOKUP(name,type,)
124 #define DEFINE_PRIVATE_STRING_TABLE_LOOKUP(name,type) _DEFINE_STRING_TABLE_LOOKUP(name,type,static)
125 #define DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(name,type) _DEFINE_STRING_TABLE_LOOKUP_TO_STRING(name,type,static)
126 #define DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(name,type) _DEFINE_STRING_TABLE_LOOKUP_FROM_STRING(name,type,static)
127
128 /* For string conversions where numbers are also acceptable */
129 #define DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(name,type,max) \
130 int name##_to_string_alloc(type i, char **str) { \
131 char *s; \
132 if (i < 0 || i > max) \
133 return -ERANGE; \
134 if (i < (type) ELEMENTSOF(name##_table)) { \
135 s = strdup(name##_table[i]); \
136 if (!s) \
137 return -ENOMEM; \
138 } else { \
139 if (asprintf(&s, "%i", i) < 0) \
140 return -ENOMEM; \
141 } \
142 *str = s; \
143 return 0; \
144 } \
145 type name##_from_string(const char *s) { \
146 type i; \
147 unsigned u = 0; \
148 if (!s) \
149 return (type) -1; \
150 for (i = 0; i < (type) ELEMENTSOF(name##_table); i++) \
151 if (streq_ptr(name##_table[i], s)) \
152 return i; \
153 if (safe_atou(s, &u) >= 0 && u <= max) \
154 return (type) u; \
155 return (type) -1; \
156 } \
157 struct __useless_struct_to_allow_trailing_semicolon__
158
159 bool fstype_is_network(const char *fstype);
160
161 int fopen_temporary(const char *path, FILE **_f, char **_temp_path);
162
163 bool is_device_path(const char *path);
164
165 int dir_is_empty(const char *path);
166 char* dirname_malloc(const char *path);
167
168 static inline int dir_is_populated(const char *path) {
169 int r;
170 r = dir_is_empty(path);
171 if (r < 0)
172 return r;
173 return !r;
174 }
175
176 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid);
177 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid);
178
179 typedef long statfs_f_type_t;
180
181 bool is_fs_type(const struct statfs *s, statfs_f_type_t magic_value) _pure_;
182 int fd_check_fstype(int fd, statfs_f_type_t magic_value);
183 int path_check_fstype(const char *path, statfs_f_type_t magic_value);
184
185 bool is_temporary_fs(const struct statfs *s) _pure_;
186 int fd_is_temporary_fs(int fd);
187
188 #define xsprintf(buf, fmt, ...) \
189 assert_message_se((size_t) snprintf(buf, ELEMENTSOF(buf), fmt, __VA_ARGS__) < ELEMENTSOF(buf), \
190 "xsprintf: " #buf "[] must be big enough")
191
192 int files_same(const char *filea, const char *fileb);
193
194 int running_in_chroot(void);
195
196 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode);
197 int touch(const char *path);
198
199 noreturn void freeze(void);
200
201 bool null_or_empty(struct stat *st) _pure_;
202 int null_or_empty_path(const char *fn);
203 int null_or_empty_fd(int fd);
204
205 DIR *xopendirat(int dirfd, const char *name, int flags);
206
207 char *fstab_node_to_udev_node(const char *p);
208
209 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]);
210
211 bool plymouth_running(void);
212
213 int symlink_idempotent(const char *from, const char *to);
214
215 int symlink_atomic(const char *from, const char *to);
216 int mknod_atomic(const char *path, mode_t mode, dev_t dev);
217 int mkfifo_atomic(const char *path, mode_t mode);
218
219 int fchmod_umask(int fd, mode_t mode);
220
221 bool display_is_local(const char *display) _pure_;
222 int socket_from_display(const char *display, char **path);
223
224 int glob_exists(const char *path);
225 int glob_extend(char ***strv, const char *path);
226
227 int dirent_ensure_type(DIR *d, struct dirent *de);
228
229 int get_files_in_directory(const char *path, char ***list);
230
231 bool is_main_thread(void);
232
233 int block_get_whole_disk(dev_t d, dev_t *ret);
234
235 #define NULSTR_FOREACH(i, l) \
236 for ((i) = (l); (i) && *(i); (i) = strchr((i), 0)+1)
237
238 #define NULSTR_FOREACH_PAIR(i, j, l) \
239 for ((i) = (l), (j) = strchr((i), 0)+1; (i) && *(i); (i) = strchr((j), 0)+1, (j) = *(i) ? strchr((i), 0)+1 : (i))
240
241 int ioprio_class_to_string_alloc(int i, char **s);
242 int ioprio_class_from_string(const char *s);
243
244 const char *sigchld_code_to_string(int i) _const_;
245 int sigchld_code_from_string(const char *s) _pure_;
246
247 int log_facility_unshifted_to_string_alloc(int i, char **s);
248 int log_facility_unshifted_from_string(const char *s);
249 bool log_facility_unshifted_is_valid(int faciliy);
250
251 int log_level_to_string_alloc(int i, char **s);
252 int log_level_from_string(const char *s);
253 bool log_level_is_valid(int level);
254
255 int sched_policy_to_string_alloc(int i, char **s);
256 int sched_policy_from_string(const char *s);
257
258 const char *rlimit_to_string(int i) _const_;
259 int rlimit_from_string(const char *s) _pure_;
260
261 extern int saved_argc;
262 extern char **saved_argv;
263
264 bool kexec_loaded(void);
265
266 int prot_from_flags(int flags) _const_;
267
268 void* memdup(const void *p, size_t l) _alloc_(2);
269
270 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...);
271
272 int setrlimit_closest(int resource, const struct rlimit *rlim);
273
274 bool http_url_is_valid(const char *url) _pure_;
275 bool documentation_url_is_valid(const char *url) _pure_;
276
277 bool http_etag_is_valid(const char *etag);
278
279 bool in_initrd(void);
280
281 static inline void freep(void *p) {
282 free(*(void**) p);
283 }
284
285 static inline void umaskp(mode_t *u) {
286 umask(*u);
287 }
288
289 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, endmntent);
290
291 #define _cleanup_free_ _cleanup_(freep)
292 #define _cleanup_umask_ _cleanup_(umaskp)
293 #define _cleanup_globfree_ _cleanup_(globfree)
294 #define _cleanup_endmntent_ _cleanup_(endmntentp)
295
296 _malloc_ _alloc_(1, 2) static inline void *malloc_multiply(size_t a, size_t b) {
297 if (_unlikely_(b != 0 && a > ((size_t) -1) / b))
298 return NULL;
299
300 return malloc(a * b);
301 }
302
303 _alloc_(2, 3) static inline void *realloc_multiply(void *p, size_t a, size_t b) {
304 if (_unlikely_(b != 0 && a > ((size_t) -1) / b))
305 return NULL;
306
307 return realloc(p, a * b);
308 }
309
310 _alloc_(2, 3) static inline void *memdup_multiply(const void *p, size_t a, size_t b) {
311 if (_unlikely_(b != 0 && a > ((size_t) -1) / b))
312 return NULL;
313
314 return memdup(p, a * b);
315 }
316
317 bool filename_is_valid(const char *p) _pure_;
318 bool path_is_safe(const char *p) _pure_;
319 bool string_is_safe(const char *p) _pure_;
320
321 /**
322 * Check if a string contains any glob patterns.
323 */
324 _pure_ static inline bool string_is_glob(const char *p) {
325 return !!strpbrk(p, GLOB_CHARS);
326 }
327
328 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
329 int (*compar) (const void *, const void *, void *),
330 void *arg);
331
332 #define _(String) gettext (String)
333 #define N_(String) String
334 void init_gettext(void);
335 bool is_locale_utf8(void);
336
337 typedef enum DrawSpecialChar {
338 DRAW_TREE_VERTICAL,
339 DRAW_TREE_BRANCH,
340 DRAW_TREE_RIGHT,
341 DRAW_TREE_SPACE,
342 DRAW_TRIANGULAR_BULLET,
343 DRAW_BLACK_CIRCLE,
344 DRAW_ARROW,
345 DRAW_DASH,
346 _DRAW_SPECIAL_CHAR_MAX
347 } DrawSpecialChar;
348
349 const char *draw_special_char(DrawSpecialChar ch);
350
351 int on_ac_power(void);
352
353 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f);
354 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f);
355
356 #define FOREACH_LINE(line, f, on_error) \
357 for (;;) \
358 if (!fgets(line, sizeof(line), f)) { \
359 if (ferror(f)) { \
360 on_error; \
361 } \
362 break; \
363 } else
364
365 #define FOREACH_DIRENT(de, d, on_error) \
366 for (errno = 0, de = readdir(d);; errno = 0, de = readdir(d)) \
367 if (!de) { \
368 if (errno > 0) { \
369 on_error; \
370 } \
371 break; \
372 } else if (hidden_file((de)->d_name)) \
373 continue; \
374 else
375
376 #define FOREACH_DIRENT_ALL(de, d, on_error) \
377 for (errno = 0, de = readdir(d);; errno = 0, de = readdir(d)) \
378 if (!de) { \
379 if (errno > 0) { \
380 on_error; \
381 } \
382 break; \
383 } else
384
385 static inline void *mempset(void *s, int c, size_t n) {
386 memset(s, c, n);
387 return (uint8_t*)s + n;
388 }
389
390 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size);
391 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size);
392 #define GREEDY_REALLOC(array, allocated, need) \
393 greedy_realloc((void**) &(array), &(allocated), (need), sizeof((array)[0]))
394
395 #define GREEDY_REALLOC0(array, allocated, need) \
396 greedy_realloc0((void**) &(array), &(allocated), (need), sizeof((array)[0]))
397
398 static inline void _reset_errno_(int *saved_errno) {
399 errno = *saved_errno;
400 }
401
402 #define PROTECT_ERRNO _cleanup_(_reset_errno_) __attribute__((unused)) int _saved_errno_ = errno
403
404 static inline int negative_errno(void) {
405 /* This helper should be used to shut up gcc if you know 'errno' is
406 * negative. Instead of "return -errno;", use "return negative_errno();"
407 * It will suppress bogus gcc warnings in case it assumes 'errno' might
408 * be 0 and thus the caller's error-handling might not be triggered. */
409 assert_return(errno > 0, -EINVAL);
410 return -errno;
411 }
412
413 struct _umask_struct_ {
414 mode_t mask;
415 bool quit;
416 };
417
418 static inline void _reset_umask_(struct _umask_struct_ *s) {
419 umask(s->mask);
420 };
421
422 #define RUN_WITH_UMASK(mask) \
423 for (_cleanup_(_reset_umask_) struct _umask_struct_ _saved_umask_ = { umask(mask), false }; \
424 !_saved_umask_.quit ; \
425 _saved_umask_.quit = true)
426
427 static inline unsigned u64log2(uint64_t n) {
428 #if __SIZEOF_LONG_LONG__ == 8
429 return (n > 1) ? (unsigned) __builtin_clzll(n) ^ 63U : 0;
430 #else
431 #error "Wut?"
432 #endif
433 }
434
435 static inline unsigned u32ctz(uint32_t n) {
436 #if __SIZEOF_INT__ == 4
437 return __builtin_ctz(n);
438 #else
439 #error "Wut?"
440 #endif
441 }
442
443 static inline unsigned log2i(int x) {
444 assert(x > 0);
445
446 return __SIZEOF_INT__ * 8 - __builtin_clz(x) - 1;
447 }
448
449 static inline unsigned log2u(unsigned x) {
450 assert(x > 0);
451
452 return sizeof(unsigned) * 8 - __builtin_clz(x) - 1;
453 }
454
455 static inline unsigned log2u_round_up(unsigned x) {
456 assert(x > 0);
457
458 if (x == 1)
459 return 0;
460
461 return log2u(x - 1) + 1;
462 }
463
464 #define DECIMAL_STR_WIDTH(x) \
465 ({ \
466 typeof(x) _x_ = (x); \
467 unsigned ans = 1; \
468 while (_x_ /= 10) \
469 ans++; \
470 ans; \
471 })
472
473 int unlink_noerrno(const char *path);
474
475 #define alloca0(n) \
476 ({ \
477 char *_new_; \
478 size_t _len_ = n; \
479 _new_ = alloca(_len_); \
480 (void *) memset(_new_, 0, _len_); \
481 })
482
483 /* It's not clear what alignment glibc/gcc alloca() guarantee, hence provide a guaranteed safe version */
484 #define alloca_align(size, align) \
485 ({ \
486 void *_ptr_; \
487 size_t _mask_ = (align) - 1; \
488 _ptr_ = alloca((size) + _mask_); \
489 (void*)(((uintptr_t)_ptr_ + _mask_) & ~_mask_); \
490 })
491
492 #define alloca0_align(size, align) \
493 ({ \
494 void *_new_; \
495 size_t _size_ = (size); \
496 _new_ = alloca_align(_size_, (align)); \
497 (void*)memset(_new_, 0, _size_); \
498 })
499
500 bool id128_is_valid(const char *s) _pure_;
501
502 int shall_restore_state(void);
503
504 /**
505 * Normal qsort requires base to be nonnull. Here were require
506 * that only if nmemb > 0.
507 */
508 static inline void qsort_safe(void *base, size_t nmemb, size_t size, comparison_fn_t compar) {
509 if (nmemb <= 1)
510 return;
511
512 assert(base);
513 qsort(base, nmemb, size, compar);
514 }
515
516 int proc_cmdline(char **ret);
517 int parse_proc_cmdline(int (*parse_word)(const char *key, const char *value));
518 int get_proc_cmdline_key(const char *parameter, char **value);
519
520 int container_get_leader(const char *machine, pid_t *pid);
521
522 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *userns_fd, int *root_fd);
523 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int userns_fd, int root_fd);
524
525 int mkostemp_safe(char *pattern, int flags);
526 int open_tmpfile(const char *path, int flags);
527
528 int fd_warn_permissions(const char *path, int fd);
529
530 #ifndef PERSONALITY_INVALID
531 /* personality(7) documents that 0xffffffffUL is used for querying the
532 * current personality, hence let's use that here as error
533 * indicator. */
534 #define PERSONALITY_INVALID 0xffffffffLU
535 #endif
536
537 unsigned long personality_from_string(const char *p);
538 const char *personality_to_string(unsigned long);
539
540 uint64_t physical_memory(void);
541
542 union file_handle_union {
543 struct file_handle handle;
544 char padding[sizeof(struct file_handle) + MAX_HANDLE_SZ];
545 };
546 #define FILE_HANDLE_INIT { .handle.handle_bytes = MAX_HANDLE_SZ }
547
548 int update_reboot_param_file(const char *param);
549
550 int umount_recursive(const char *target, int flags);
551
552 int bind_remount_recursive(const char *prefix, bool ro);
553
554 int fflush_and_check(FILE *f);
555
556 int tempfn_xxxxxx(const char *p, const char *extra, char **ret);
557 int tempfn_random(const char *p, const char *extra, char **ret);
558 int tempfn_random_child(const char *p, const char *extra, char **ret);
559
560 int take_password_lock(const char *root);
561
562 int is_symlink(const char *path);
563 int is_dir(const char *path, bool follow);
564 int is_device_node(const char *path);
565
566 #define INOTIFY_EVENT_MAX (sizeof(struct inotify_event) + NAME_MAX + 1)
567
568 #define FOREACH_INOTIFY_EVENT(e, buffer, sz) \
569 for ((e) = &buffer.ev; \
570 (uint8_t*) (e) < (uint8_t*) (buffer.raw) + (sz); \
571 (e) = (struct inotify_event*) ((uint8_t*) (e) + sizeof(struct inotify_event) + (e)->len))
572
573 union inotify_event_buffer {
574 struct inotify_event ev;
575 uint8_t raw[INOTIFY_EVENT_MAX];
576 };
577
578 #define laccess(path, mode) faccessat(AT_FDCWD, (path), (mode), AT_SYMLINK_NOFOLLOW)
579
580 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags);
581
582 int fd_setcrtime(int fd, usec_t usec);
583 int fd_getcrtime(int fd, usec_t *usec);
584 int path_getcrtime(const char *p, usec_t *usec);
585 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags);
586
587 int chattr_fd(int fd, unsigned value, unsigned mask);
588 int chattr_path(const char *p, unsigned value, unsigned mask);
589
590 int read_attr_fd(int fd, unsigned *ret);
591 int read_attr_path(const char *p, unsigned *ret);
592
593 #define RLIMIT_MAKE_CONST(lim) ((struct rlimit) { lim, lim })
594
595 int syslog_parse_priority(const char **p, int *priority, bool with_facility);
596
597 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath);
598
599 int mount_move_root(const char *path);
600
601 int getxattr_malloc(const char *path, const char *name, char **value, bool allow_symlink);
602 int fgetxattr_malloc(int fd, const char *name, char **value);
603
604 int version(void);
605
606 bool fdname_is_valid(const char *s);
607
608 bool oom_score_adjust_is_valid(int oa);