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