]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/util.h
util-lib: split stat()/statfs()/stavfs() related calls into stat-util.[ch]
[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 <fcntl.h>
26 #include <inttypes.h>
27 #include <limits.h>
28 #include <locale.h>
29 #include <stdarg.h>
30 #include <stdbool.h>
31 #include <stddef.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <sys/inotify.h>
35 #include <sys/socket.h>
36 #include <sys/stat.h>
37 #include <sys/statfs.h>
38 #include <sys/types.h>
39 #include <time.h>
40 #include <unistd.h>
41
42 #include "formats-util.h"
43 #include "macro.h"
44 #include "missing.h"
45 #include "time-util.h"
46
47 /* What is interpreted as whitespace? */
48 #define WHITESPACE " \t\n\r"
49 #define NEWLINE "\n\r"
50 #define QUOTES "\"\'"
51 #define COMMENTS "#;"
52 #define GLOB_CHARS "*?["
53
54 size_t page_size(void) _pure_;
55 #define PAGE_ALIGN(l) ALIGN_TO((l), page_size())
56
57 #define new(t, n) ((t*) malloc_multiply(sizeof(t), (n)))
58
59 #define new0(t, n) ((t*) calloc((n), sizeof(t)))
60
61 #define newa(t, n) ((t*) alloca(sizeof(t)*(n)))
62
63 #define newa0(t, n) ((t*) alloca0(sizeof(t)*(n)))
64
65 #define newdup(t, p, n) ((t*) memdup_multiply(p, sizeof(t), (n)))
66
67 #define malloc0(n) (calloc(1, (n)))
68
69 static inline void *mfree(void *memory) {
70 free(memory);
71 return NULL;
72 }
73
74 static inline const char* yes_no(bool b) {
75 return b ? "yes" : "no";
76 }
77
78 static inline const char* true_false(bool b) {
79 return b ? "true" : "false";
80 }
81
82 static inline const char* one_zero(bool b) {
83 return b ? "1" : "0";
84 }
85
86 /* For basic lookup tables with strictly enumerated entries */
87 #define _DEFINE_STRING_TABLE_LOOKUP_TO_STRING(name,type,scope) \
88 scope const char *name##_to_string(type i) { \
89 if (i < 0 || i >= (type) ELEMENTSOF(name##_table)) \
90 return NULL; \
91 return name##_table[i]; \
92 }
93
94 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key);
95
96 #define _DEFINE_STRING_TABLE_LOOKUP_FROM_STRING(name,type,scope) \
97 scope type name##_from_string(const char *s) { \
98 return (type) string_table_lookup(name##_table, ELEMENTSOF(name##_table), s); \
99 }
100
101 #define _DEFINE_STRING_TABLE_LOOKUP(name,type,scope) \
102 _DEFINE_STRING_TABLE_LOOKUP_TO_STRING(name,type,scope) \
103 _DEFINE_STRING_TABLE_LOOKUP_FROM_STRING(name,type,scope) \
104 struct __useless_struct_to_allow_trailing_semicolon__
105
106 #define DEFINE_STRING_TABLE_LOOKUP(name,type) _DEFINE_STRING_TABLE_LOOKUP(name,type,)
107 #define DEFINE_PRIVATE_STRING_TABLE_LOOKUP(name,type) _DEFINE_STRING_TABLE_LOOKUP(name,type,static)
108 #define DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(name,type) _DEFINE_STRING_TABLE_LOOKUP_TO_STRING(name,type,static)
109 #define DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(name,type) _DEFINE_STRING_TABLE_LOOKUP_FROM_STRING(name,type,static)
110
111 /* For string conversions where numbers are also acceptable */
112 #define DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(name,type,max) \
113 int name##_to_string_alloc(type i, char **str) { \
114 char *s; \
115 if (i < 0 || i > max) \
116 return -ERANGE; \
117 if (i < (type) ELEMENTSOF(name##_table)) { \
118 s = strdup(name##_table[i]); \
119 if (!s) \
120 return -ENOMEM; \
121 } else { \
122 if (asprintf(&s, "%i", i) < 0) \
123 return -ENOMEM; \
124 } \
125 *str = s; \
126 return 0; \
127 } \
128 type name##_from_string(const char *s) { \
129 type i; \
130 unsigned u = 0; \
131 if (!s) \
132 return (type) -1; \
133 for (i = 0; i < (type) ELEMENTSOF(name##_table); i++) \
134 if (streq_ptr(name##_table[i], s)) \
135 return i; \
136 if (safe_atou(s, &u) >= 0 && u <= max) \
137 return (type) u; \
138 return (type) -1; \
139 } \
140 struct __useless_struct_to_allow_trailing_semicolon__
141
142 bool fstype_is_network(const char *fstype);
143
144 #define xsprintf(buf, fmt, ...) \
145 assert_message_se((size_t) snprintf(buf, ELEMENTSOF(buf), fmt, __VA_ARGS__) < ELEMENTSOF(buf), \
146 "xsprintf: " #buf "[] must be big enough")
147
148 int running_in_chroot(void);
149
150 noreturn void freeze(void);
151
152 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]);
153
154 bool plymouth_running(void);
155
156 bool display_is_local(const char *display) _pure_;
157 int socket_from_display(const char *display, char **path);
158
159 int glob_exists(const char *path);
160 int glob_extend(char ***strv, const char *path);
161
162 bool is_main_thread(void);
163
164 int block_get_whole_disk(dev_t d, dev_t *ret);
165
166 #define NULSTR_FOREACH(i, l) \
167 for ((i) = (l); (i) && *(i); (i) = strchr((i), 0)+1)
168
169 #define NULSTR_FOREACH_PAIR(i, j, l) \
170 for ((i) = (l), (j) = strchr((i), 0)+1; (i) && *(i); (i) = strchr((j), 0)+1, (j) = *(i) ? strchr((i), 0)+1 : (i))
171
172 int ioprio_class_to_string_alloc(int i, char **s);
173 int ioprio_class_from_string(const char *s);
174
175 const char *sigchld_code_to_string(int i) _const_;
176 int sigchld_code_from_string(const char *s) _pure_;
177
178 int log_facility_unshifted_to_string_alloc(int i, char **s);
179 int log_facility_unshifted_from_string(const char *s);
180 bool log_facility_unshifted_is_valid(int faciliy);
181
182 int log_level_to_string_alloc(int i, char **s);
183 int log_level_from_string(const char *s);
184 bool log_level_is_valid(int level);
185
186 int sched_policy_to_string_alloc(int i, char **s);
187 int sched_policy_from_string(const char *s);
188
189 extern int saved_argc;
190 extern char **saved_argv;
191
192 bool kexec_loaded(void);
193
194 int prot_from_flags(int flags) _const_;
195
196 void* memdup(const void *p, size_t l) _alloc_(2);
197
198 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...);
199
200 bool http_url_is_valid(const char *url) _pure_;
201 bool documentation_url_is_valid(const char *url) _pure_;
202
203 bool http_etag_is_valid(const char *etag);
204
205 bool in_initrd(void);
206
207 static inline void freep(void *p) {
208 free(*(void**) p);
209 }
210
211 static inline void umaskp(mode_t *u) {
212 umask(*u);
213 }
214
215 #define _cleanup_free_ _cleanup_(freep)
216 #define _cleanup_umask_ _cleanup_(umaskp)
217 #define _cleanup_globfree_ _cleanup_(globfree)
218
219 _malloc_ _alloc_(1, 2) static inline void *malloc_multiply(size_t a, size_t b) {
220 if (_unlikely_(b != 0 && a > ((size_t) -1) / b))
221 return NULL;
222
223 return malloc(a * b);
224 }
225
226 _alloc_(2, 3) static inline void *realloc_multiply(void *p, size_t a, size_t b) {
227 if (_unlikely_(b != 0 && a > ((size_t) -1) / b))
228 return NULL;
229
230 return realloc(p, a * b);
231 }
232
233 _alloc_(2, 3) static inline void *memdup_multiply(const void *p, size_t a, size_t b) {
234 if (_unlikely_(b != 0 && a > ((size_t) -1) / b))
235 return NULL;
236
237 return memdup(p, a * b);
238 }
239
240 /**
241 * Check if a string contains any glob patterns.
242 */
243 _pure_ static inline bool string_is_glob(const char *p) {
244 return !!strpbrk(p, GLOB_CHARS);
245 }
246
247 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
248 int (*compar) (const void *, const void *, void *),
249 void *arg);
250
251 #define _(String) gettext (String)
252 #define N_(String) String
253 void init_gettext(void);
254 bool is_locale_utf8(void);
255
256 typedef enum DrawSpecialChar {
257 DRAW_TREE_VERTICAL,
258 DRAW_TREE_BRANCH,
259 DRAW_TREE_RIGHT,
260 DRAW_TREE_SPACE,
261 DRAW_TRIANGULAR_BULLET,
262 DRAW_BLACK_CIRCLE,
263 DRAW_ARROW,
264 DRAW_DASH,
265 _DRAW_SPECIAL_CHAR_MAX
266 } DrawSpecialChar;
267
268 const char *draw_special_char(DrawSpecialChar ch);
269
270 int on_ac_power(void);
271
272 static inline void *mempset(void *s, int c, size_t n) {
273 memset(s, c, n);
274 return (uint8_t*)s + n;
275 }
276
277 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size);
278 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size);
279 #define GREEDY_REALLOC(array, allocated, need) \
280 greedy_realloc((void**) &(array), &(allocated), (need), sizeof((array)[0]))
281
282 #define GREEDY_REALLOC0(array, allocated, need) \
283 greedy_realloc0((void**) &(array), &(allocated), (need), sizeof((array)[0]))
284
285 static inline void _reset_errno_(int *saved_errno) {
286 errno = *saved_errno;
287 }
288
289 #define PROTECT_ERRNO _cleanup_(_reset_errno_) __attribute__((unused)) int _saved_errno_ = errno
290
291 static inline int negative_errno(void) {
292 /* This helper should be used to shut up gcc if you know 'errno' is
293 * negative. Instead of "return -errno;", use "return negative_errno();"
294 * It will suppress bogus gcc warnings in case it assumes 'errno' might
295 * be 0 and thus the caller's error-handling might not be triggered. */
296 assert_return(errno > 0, -EINVAL);
297 return -errno;
298 }
299
300 struct _umask_struct_ {
301 mode_t mask;
302 bool quit;
303 };
304
305 static inline void _reset_umask_(struct _umask_struct_ *s) {
306 umask(s->mask);
307 };
308
309 #define RUN_WITH_UMASK(mask) \
310 for (_cleanup_(_reset_umask_) struct _umask_struct_ _saved_umask_ = { umask(mask), false }; \
311 !_saved_umask_.quit ; \
312 _saved_umask_.quit = true)
313
314 static inline unsigned u64log2(uint64_t n) {
315 #if __SIZEOF_LONG_LONG__ == 8
316 return (n > 1) ? (unsigned) __builtin_clzll(n) ^ 63U : 0;
317 #else
318 #error "Wut?"
319 #endif
320 }
321
322 static inline unsigned u32ctz(uint32_t n) {
323 #if __SIZEOF_INT__ == 4
324 return __builtin_ctz(n);
325 #else
326 #error "Wut?"
327 #endif
328 }
329
330 static inline unsigned log2i(int x) {
331 assert(x > 0);
332
333 return __SIZEOF_INT__ * 8 - __builtin_clz(x) - 1;
334 }
335
336 static inline unsigned log2u(unsigned x) {
337 assert(x > 0);
338
339 return sizeof(unsigned) * 8 - __builtin_clz(x) - 1;
340 }
341
342 static inline unsigned log2u_round_up(unsigned x) {
343 assert(x > 0);
344
345 if (x == 1)
346 return 0;
347
348 return log2u(x - 1) + 1;
349 }
350
351 #define DECIMAL_STR_WIDTH(x) \
352 ({ \
353 typeof(x) _x_ = (x); \
354 unsigned ans = 1; \
355 while (_x_ /= 10) \
356 ans++; \
357 ans; \
358 })
359
360 #define alloca0(n) \
361 ({ \
362 char *_new_; \
363 size_t _len_ = n; \
364 _new_ = alloca(_len_); \
365 (void *) memset(_new_, 0, _len_); \
366 })
367
368 /* It's not clear what alignment glibc/gcc alloca() guarantee, hence provide a guaranteed safe version */
369 #define alloca_align(size, align) \
370 ({ \
371 void *_ptr_; \
372 size_t _mask_ = (align) - 1; \
373 _ptr_ = alloca((size) + _mask_); \
374 (void*)(((uintptr_t)_ptr_ + _mask_) & ~_mask_); \
375 })
376
377 #define alloca0_align(size, align) \
378 ({ \
379 void *_new_; \
380 size_t _size_ = (size); \
381 _new_ = alloca_align(_size_, (align)); \
382 (void*)memset(_new_, 0, _size_); \
383 })
384
385 bool id128_is_valid(const char *s) _pure_;
386
387 int shall_restore_state(void);
388
389 /**
390 * Normal qsort requires base to be nonnull. Here were require
391 * that only if nmemb > 0.
392 */
393 static inline void qsort_safe(void *base, size_t nmemb, size_t size, comparison_fn_t compar) {
394 if (nmemb <= 1)
395 return;
396
397 assert(base);
398 qsort(base, nmemb, size, compar);
399 }
400
401 int proc_cmdline(char **ret);
402 int parse_proc_cmdline(int (*parse_word)(const char *key, const char *value));
403 int get_proc_cmdline_key(const char *parameter, char **value);
404
405 int container_get_leader(const char *machine, pid_t *pid);
406
407 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *userns_fd, int *root_fd);
408 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int userns_fd, int root_fd);
409
410 #ifndef PERSONALITY_INVALID
411 /* personality(7) documents that 0xffffffffUL is used for querying the
412 * current personality, hence let's use that here as error
413 * indicator. */
414 #define PERSONALITY_INVALID 0xffffffffLU
415 #endif
416
417 unsigned long personality_from_string(const char *p);
418 const char *personality_to_string(unsigned long);
419
420 uint64_t physical_memory(void);
421
422 union file_handle_union {
423 struct file_handle handle;
424 char padding[sizeof(struct file_handle) + MAX_HANDLE_SZ];
425 };
426 #define FILE_HANDLE_INIT { .handle.handle_bytes = MAX_HANDLE_SZ }
427
428 int update_reboot_param_file(const char *param);
429
430 #define INOTIFY_EVENT_MAX (sizeof(struct inotify_event) + NAME_MAX + 1)
431
432 #define FOREACH_INOTIFY_EVENT(e, buffer, sz) \
433 for ((e) = &buffer.ev; \
434 (uint8_t*) (e) < (uint8_t*) (buffer.raw) + (sz); \
435 (e) = (struct inotify_event*) ((uint8_t*) (e) + sizeof(struct inotify_event) + (e)->len))
436
437 union inotify_event_buffer {
438 struct inotify_event ev;
439 uint8_t raw[INOTIFY_EVENT_MAX];
440 };
441
442 int syslog_parse_priority(const char **p, int *priority, bool with_facility);
443
444 int version(void);
445
446 bool fdname_is_valid(const char *s);
447
448 bool oom_score_adjust_is_valid(int oa);