chiark / gitweb /
f9f96ce8ac6326497e9f03e36bf9ecd8809aed0b
[elogind.git] / src / shared / 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 <time.h>
28 #include <stdarg.h>
29 #include <stdbool.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <signal.h>
33 #include <sched.h>
34 #include <limits.h>
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <sys/stat.h>
38 #include <dirent.h>
39 #include <stddef.h>
40 #include <unistd.h>
41 #include <locale.h>
42 #include <mntent.h>
43 #include <sys/inotify.h>
44 #include <sys/statfs.h>
45
46 #include "macro.h"
47 #include "missing.h"
48 #include "time-util.h"
49 #include "formats-util.h"
50
51 /* What is interpreted as whitespace? */
52 #define WHITESPACE " \t\n\r"
53 #define NEWLINE    "\n\r"
54 #define QUOTES     "\"\'"
55 #define COMMENTS   "#;"
56 #define GLOB_CHARS "*?["
57
58 /* What characters are special in the shell? */
59 /* must be escaped outside and inside double-quotes */
60 #define SHELL_NEED_ESCAPE "\"\\`$"
61 /* can be escaped or double-quoted */
62 #define SHELL_NEED_QUOTES SHELL_NEED_ESCAPE GLOB_CHARS "'()<>|&;"
63
64 #define FORMAT_BYTES_MAX 8
65
66 #define ANSI_HIGHLIGHT_ON "\x1B[1;39m"
67 #define ANSI_RED_ON "\x1B[31m"
68 #define ANSI_HIGHLIGHT_RED_ON "\x1B[1;31m"
69 #define ANSI_GREEN_ON "\x1B[32m"
70 #define ANSI_HIGHLIGHT_GREEN_ON "\x1B[1;32m"
71 #define ANSI_HIGHLIGHT_YELLOW_ON "\x1B[1;33m"
72 #define ANSI_HIGHLIGHT_BLUE_ON "\x1B[1;34m"
73 #define ANSI_HIGHLIGHT_OFF "\x1B[0m"
74 #define ANSI_ERASE_TO_END_OF_LINE "\x1B[K"
75
76 size_t page_size(void) _pure_;
77 #define PAGE_ALIGN(l) ALIGN_TO((l), page_size())
78
79 #define streq(a,b) (strcmp((a),(b)) == 0)
80 #define strneq(a, b, n) (strncmp((a), (b), (n)) == 0)
81 #define strcaseeq(a,b) (strcasecmp((a),(b)) == 0)
82 #define strncaseeq(a, b, n) (strncasecmp((a), (b), (n)) == 0)
83
84 bool streq_ptr(const char *a, const char *b) _pure_;
85
86 #define new(t, n) ((t*) malloc_multiply(sizeof(t), (n)))
87
88 #define new0(t, n) ((t*) calloc((n), sizeof(t)))
89
90 #define newa(t, n) ((t*) alloca(sizeof(t)*(n)))
91
92 #define newa0(t, n) ((t*) alloca0(sizeof(t)*(n)))
93
94 #define newdup(t, p, n) ((t*) memdup_multiply(p, sizeof(t), (n)))
95
96 #define malloc0(n) (calloc((n), 1))
97
98 static inline const char* yes_no(bool b) {
99         return b ? "yes" : "no";
100 }
101
102 static inline const char* true_false(bool b) {
103         return b ? "true" : "false";
104 }
105
106 static inline const char* one_zero(bool b) {
107         return b ? "1" : "0";
108 }
109
110 static inline const char* strempty(const char *s) {
111         return s ? s : "";
112 }
113
114 static inline const char* strnull(const char *s) {
115         return s ? s : "(null)";
116 }
117
118 static inline const char *strna(const char *s) {
119         return s ? s : "n/a";
120 }
121
122 static inline bool isempty(const char *p) {
123         return !p || !p[0];
124 }
125
126 static inline char *startswith(const char *s, const char *prefix) {
127         size_t l;
128
129         l = strlen(prefix);
130         if (strncmp(s, prefix, l) == 0)
131                 return (char*) s + l;
132
133         return NULL;
134 }
135
136 static inline char *startswith_no_case(const char *s, const char *prefix) {
137         size_t l;
138
139         l = strlen(prefix);
140         if (strncasecmp(s, prefix, l) == 0)
141                 return (char*) s + l;
142
143         return NULL;
144 }
145
146 char *endswith(const char *s, const char *postfix) _pure_;
147 char *endswith_no_case(const char *s, const char *postfix) _pure_;
148
149 char *first_word(const char *s, const char *word) _pure_;
150
151 int close_nointr(int fd);
152 int safe_close(int fd);
153 void safe_close_pair(int p[]);
154
155 void close_many(const int fds[], unsigned n_fd);
156
157 int parse_size(const char *t, off_t base, off_t *size);
158
159 int parse_boolean(const char *v) _pure_;
160 int parse_pid(const char *s, pid_t* ret_pid);
161 int parse_uid(const char *s, uid_t* ret_uid);
162 #define parse_gid(s, ret_uid) parse_uid(s, ret_uid)
163
164 int safe_atou(const char *s, unsigned *ret_u);
165 int safe_atoi(const char *s, int *ret_i);
166
167 int safe_atollu(const char *s, unsigned long long *ret_u);
168 int safe_atolli(const char *s, long long int *ret_i);
169
170 int safe_atod(const char *s, double *ret_d);
171
172 int safe_atou8(const char *s, uint8_t *ret);
173
174 #if LONG_MAX == INT_MAX
175 static inline int safe_atolu(const char *s, unsigned long *ret_u) {
176         assert_cc(sizeof(unsigned long) == sizeof(unsigned));
177         return safe_atou(s, (unsigned*) ret_u);
178 }
179 static inline int safe_atoli(const char *s, long int *ret_u) {
180         assert_cc(sizeof(long int) == sizeof(int));
181         return safe_atoi(s, (int*) ret_u);
182 }
183 #else
184 static inline int safe_atolu(const char *s, unsigned long *ret_u) {
185         assert_cc(sizeof(unsigned long) == sizeof(unsigned long long));
186         return safe_atollu(s, (unsigned long long*) ret_u);
187 }
188 static inline int safe_atoli(const char *s, long int *ret_u) {
189         assert_cc(sizeof(long int) == sizeof(long long int));
190         return safe_atolli(s, (long long int*) ret_u);
191 }
192 #endif
193
194 static inline int safe_atou32(const char *s, uint32_t *ret_u) {
195         assert_cc(sizeof(uint32_t) == sizeof(unsigned));
196         return safe_atou(s, (unsigned*) ret_u);
197 }
198
199 static inline int safe_atoi32(const char *s, int32_t *ret_i) {
200         assert_cc(sizeof(int32_t) == sizeof(int));
201         return safe_atoi(s, (int*) ret_i);
202 }
203
204 static inline int safe_atou64(const char *s, uint64_t *ret_u) {
205         assert_cc(sizeof(uint64_t) == sizeof(unsigned long long));
206         return safe_atollu(s, (unsigned long long*) ret_u);
207 }
208
209 static inline int safe_atoi64(const char *s, int64_t *ret_i) {
210         assert_cc(sizeof(int64_t) == sizeof(long long int));
211         return safe_atolli(s, (long long int*) ret_i);
212 }
213
214 int safe_atou16(const char *s, uint16_t *ret);
215 int safe_atoi16(const char *s, int16_t *ret);
216
217 const char* split(const char **state, size_t *l, const char *separator, bool quoted);
218
219 #define FOREACH_WORD(word, length, s, state)                            \
220         _FOREACH_WORD(word, length, s, WHITESPACE, false, state)
221
222 #define FOREACH_WORD_SEPARATOR(word, length, s, separator, state)       \
223         _FOREACH_WORD(word, length, s, separator, false, state)
224
225 #define FOREACH_WORD_QUOTED(word, length, s, state)                     \
226         _FOREACH_WORD(word, length, s, WHITESPACE, true, state)
227
228 #define _FOREACH_WORD(word, length, s, separator, quoted, state)        \
229         for ((state) = (s), (word) = split(&(state), &(length), (separator), (quoted)); (word); (word) = split(&(state), &(length), (separator), (quoted)))
230
231 char *strappend(const char *s, const char *suffix);
232 char *strnappend(const char *s, const char *suffix, size_t length);
233
234 char *replace_env(const char *format, char **env);
235 char **replace_env_argv(char **argv, char **env);
236
237 int readlinkat_malloc(int fd, const char *p, char **ret);
238 int readlink_malloc(const char *p, char **r);
239 int readlink_value(const char *p, char **ret);
240 int readlink_and_make_absolute(const char *p, char **r);
241 int readlink_and_canonicalize(const char *p, char **r);
242
243 int reset_all_signal_handlers(void);
244 int reset_signal_mask(void);
245
246 char *strstrip(char *s);
247 char *delete_chars(char *s, const char *bad);
248 char *truncate_nl(char *s);
249
250 char *file_in_same_dir(const char *path, const char *filename);
251
252 int rmdir_parents(const char *path, const char *stop);
253
254 char hexchar(int x) _const_;
255 int unhexchar(char c) _const_;
256 char octchar(int x) _const_;
257 int unoctchar(char c) _const_;
258 char decchar(int x) _const_;
259 int undecchar(char c) _const_;
260
261 char *cescape(const char *s);
262 size_t cescape_char(char c, char *buf);
263
264 typedef enum UnescapeFlags {
265         UNESCAPE_RELAX = 1,
266 } UnescapeFlags;
267
268 int cunescape(const char *s, UnescapeFlags flags, char **ret);
269 int cunescape_length(const char *s, size_t length, UnescapeFlags flags, char **ret);
270 int cunescape_length_with_prefix(const char *s, size_t length, const char *prefix, UnescapeFlags flags, char **ret);
271
272 char *xescape(const char *s, const char *bad);
273
274 char *ascii_strlower(char *path);
275
276 bool dirent_is_file(const struct dirent *de) _pure_;
277 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) _pure_;
278
279 bool hidden_file(const char *filename) _pure_;
280
281 bool chars_intersect(const char *a, const char *b) _pure_;
282
283 int make_stdio(int fd);
284 int make_null_stdio(void);
285 int make_console_stdio(void);
286
287 int dev_urandom(void *p, size_t n);
288 void random_bytes(void *p, size_t n);
289 void initialize_srand(void);
290
291 static inline uint64_t random_u64(void) {
292         uint64_t u;
293         random_bytes(&u, sizeof(u));
294         return u;
295 }
296
297 static inline uint32_t random_u32(void) {
298         uint32_t u;
299         random_bytes(&u, sizeof(u));
300         return u;
301 }
302
303 /* For basic lookup tables with strictly enumerated entries */
304 #define _DEFINE_STRING_TABLE_LOOKUP_TO_STRING(name,type,scope)          \
305         scope const char *name##_to_string(type i) {                    \
306                 if (i < 0 || i >= (type) ELEMENTSOF(name##_table))      \
307                         return NULL;                                    \
308                 return name##_table[i];                                 \
309         }
310
311 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key);
312
313 #define _DEFINE_STRING_TABLE_LOOKUP_FROM_STRING(name,type,scope)                                \
314         scope inline type name##_from_string(const char *s) {                                   \
315                 return (type)string_table_lookup(name##_table, ELEMENTSOF(name##_table), s);    \
316         }
317
318 #define _DEFINE_STRING_TABLE_LOOKUP(name,type,scope)                    \
319         _DEFINE_STRING_TABLE_LOOKUP_TO_STRING(name,type,scope)          \
320         _DEFINE_STRING_TABLE_LOOKUP_FROM_STRING(name,type,scope)        \
321         struct __useless_struct_to_allow_trailing_semicolon__
322
323 #define DEFINE_STRING_TABLE_LOOKUP(name,type) _DEFINE_STRING_TABLE_LOOKUP(name,type,)
324 #define DEFINE_PRIVATE_STRING_TABLE_LOOKUP(name,type) _DEFINE_STRING_TABLE_LOOKUP(name,type,static)
325 #define DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(name,type) _DEFINE_STRING_TABLE_LOOKUP_TO_STRING(name,type,static)
326 #define DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(name,type) _DEFINE_STRING_TABLE_LOOKUP_FROM_STRING(name,type,static)
327
328 /* For string conversions where numbers are also acceptable */
329 #define DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(name,type,max)         \
330         int name##_to_string_alloc(type i, char **str) {                \
331                 char *s;                                                \
332                 int r;                                                  \
333                 if (i < 0 || i > max)                                   \
334                         return -ERANGE;                                 \
335                 if (i < (type) ELEMENTSOF(name##_table)) {              \
336                         s = strdup(name##_table[i]);                    \
337                         if (!s)                                         \
338                                 return log_oom();                       \
339                 } else {                                                \
340                         r = asprintf(&s, "%i", i);                      \
341                         if (r < 0)                                      \
342                                 return log_oom();                       \
343                 }                                                       \
344                 *str = s;                                               \
345                 return 0;                                               \
346         }                                                               \
347         type name##_from_string(const char *s) {                        \
348                 type i;                                                 \
349                 unsigned u = 0;                                         \
350                 assert(s);                                              \
351                 for (i = 0; i < (type)ELEMENTSOF(name##_table); i++)    \
352                         if (name##_table[i] &&                          \
353                             streq(name##_table[i], s))                  \
354                                 return i;                               \
355                 if (safe_atou(s, &u) >= 0 && u <= max)                  \
356                         return (type) u;                                \
357                 return (type) -1;                                       \
358         }                                                               \
359         struct __useless_struct_to_allow_trailing_semicolon__
360
361 int fd_nonblock(int fd, bool nonblock);
362 int fd_cloexec(int fd, bool cloexec);
363
364 int close_all_fds(const int except[], unsigned n_except);
365
366 bool fstype_is_network(const char *fstype);
367
368 int chvt(int vt);
369
370 int read_one_char(FILE *f, char *ret, usec_t timeout, bool *need_nl);
371 int ask_char(char *ret, const char *replies, const char *text, ...) _printf_(3, 4);
372 int ask_string(char **ret, const char *text, ...) _printf_(2, 3);
373
374 int reset_terminal_fd(int fd, bool switch_to_text);
375 int reset_terminal(const char *name);
376
377 int open_terminal(const char *name, int mode);
378 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm, usec_t timeout);
379 int release_terminal(void);
380
381 int flush_fd(int fd);
382
383 int ignore_signals(int sig, ...);
384 int default_signals(int sig, ...);
385 int sigaction_many(const struct sigaction *sa, ...);
386
387 int fopen_temporary(const char *path, FILE **_f, char **_temp_path);
388
389 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll);
390 int loop_read_exact(int fd, void *buf, size_t nbytes, bool do_poll);
391 int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll);
392
393 bool is_device_path(const char *path);
394
395 int dir_is_empty(const char *path);
396 char* dirname_malloc(const char *path);
397
398 void sigset_add_many(sigset_t *ss, ...);
399 int sigprocmask_many(int how, ...);
400
401 bool hostname_is_set(void);
402
403 char* lookup_uid(uid_t uid);
404 char* gethostname_malloc(void);
405 char* getlogname_malloc(void);
406 char* getusername_malloc(void);
407
408 int getttyname_malloc(int fd, char **r);
409 int getttyname_harder(int fd, char **r);
410
411 int get_ctty_devnr(pid_t pid, dev_t *d);
412 int get_ctty(pid_t, dev_t *_devnr, char **r);
413
414 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid);
415 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid);
416
417 bool is_temporary_fs(const struct statfs *s) _pure_;
418 int fd_is_temporary_fs(int fd);
419
420 int pipe_eof(int fd);
421
422 cpu_set_t* cpu_set_malloc(unsigned *ncpus);
423
424 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) _printf_(4,0);
425 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) _printf_(4,5);
426
427 #define xsprintf(buf, fmt, ...) assert_se((size_t) snprintf(buf, ELEMENTSOF(buf), fmt, __VA_ARGS__) < ELEMENTSOF(buf))
428
429 int fd_columns(int fd);
430 unsigned columns(void);
431 int fd_lines(int fd);
432 unsigned lines(void);
433 void columns_lines_cache_reset(int _unused_ signum);
434
435 bool on_tty(void);
436
437 static inline const char *ansi_highlight(void) {
438         return on_tty() ? ANSI_HIGHLIGHT_ON : "";
439 }
440
441 static inline const char *ansi_highlight_red(void) {
442         return on_tty() ? ANSI_HIGHLIGHT_RED_ON : "";
443 }
444
445 static inline const char *ansi_highlight_green(void) {
446         return on_tty() ? ANSI_HIGHLIGHT_GREEN_ON : "";
447 }
448
449 static inline const char *ansi_highlight_yellow(void) {
450         return on_tty() ? ANSI_HIGHLIGHT_YELLOW_ON : "";
451 }
452
453 static inline const char *ansi_highlight_blue(void) {
454         return on_tty() ? ANSI_HIGHLIGHT_BLUE_ON : "";
455 }
456
457 static inline const char *ansi_highlight_off(void) {
458         return on_tty() ? ANSI_HIGHLIGHT_OFF : "";
459 }
460
461 int files_same(const char *filea, const char *fileb);
462
463 int running_in_chroot(void);
464
465 char *ellipsize(const char *s, size_t length, unsigned percent);
466                                    /* bytes                 columns */
467 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent);
468
469 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode);
470 int touch(const char *path);
471
472 noreturn void freeze(void);
473
474 bool null_or_empty(struct stat *st) _pure_;
475 int null_or_empty_path(const char *fn);
476 int null_or_empty_fd(int fd);
477
478 DIR *xopendirat(int dirfd, const char *name, int flags);
479
480 char *fstab_node_to_udev_node(const char *p);
481
482 char *resolve_dev_console(char **active);
483 bool tty_is_vc(const char *tty);
484 bool tty_is_vc_resolve(const char *tty);
485 bool tty_is_console(const char *tty) _pure_;
486 int vtnr_from_tty(const char *tty);
487 const char *default_term_for_tty(const char *tty);
488
489 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]);
490
491 bool nulstr_contains(const char*nulstr, const char *needle);
492
493 bool plymouth_running(void);
494
495 bool hostname_is_valid(const char *s) _pure_;
496 char* hostname_cleanup(char *s, bool lowercase);
497
498 bool machine_name_is_valid(const char *s) _pure_;
499
500 char* strshorten(char *s, size_t l);
501
502 int terminal_vhangup_fd(int fd);
503 int terminal_vhangup(const char *name);
504
505 int vt_disallocate(const char *name);
506
507 int symlink_atomic(const char *from, const char *to);
508 int mknod_atomic(const char *path, mode_t mode, dev_t dev);
509 int mkfifo_atomic(const char *path, mode_t mode);
510
511 int fchmod_umask(int fd, mode_t mode);
512
513 bool display_is_local(const char *display) _pure_;
514 int socket_from_display(const char *display, char **path);
515
516 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home, const char **shell);
517 int get_group_creds(const char **groupname, gid_t *gid);
518
519 int in_gid(gid_t gid);
520 int in_group(const char *name);
521
522 char* uid_to_name(uid_t uid);
523 char* gid_to_name(gid_t gid);
524
525 int glob_exists(const char *path);
526 int glob_extend(char ***strv, const char *path);
527
528 int dirent_ensure_type(DIR *d, struct dirent *de);
529
530 int get_files_in_directory(const char *path, char ***list);
531
532 char *strjoin(const char *x, ...) _sentinel_;
533
534 bool is_main_thread(void);
535
536 static inline bool _pure_ in_charset(const char *s, const char* charset) {
537         assert(s);
538         assert(charset);
539         return s[strspn(s, charset)] == '\0';
540 }
541
542 int block_get_whole_disk(dev_t d, dev_t *ret);
543
544 #define NULSTR_FOREACH(i, l)                                    \
545         for ((i) = (l); (i) && *(i); (i) = strchr((i), 0)+1)
546
547 #define NULSTR_FOREACH_PAIR(i, j, l)                             \
548         for ((i) = (l), (j) = strchr((i), 0)+1; (i) && *(i); (i) = strchr((j), 0)+1, (j) = *(i) ? strchr((i), 0)+1 : (i))
549
550 int ioprio_class_to_string_alloc(int i, char **s);
551 int ioprio_class_from_string(const char *s);
552
553 const char *sigchld_code_to_string(int i) _const_;
554 int sigchld_code_from_string(const char *s) _pure_;
555
556 int log_facility_unshifted_to_string_alloc(int i, char **s);
557 int log_facility_unshifted_from_string(const char *s);
558
559 int log_level_to_string_alloc(int i, char **s);
560 int log_level_from_string(const char *s);
561
562 int sched_policy_to_string_alloc(int i, char **s);
563 int sched_policy_from_string(const char *s);
564
565 const char *rlimit_to_string(int i) _const_;
566 int rlimit_from_string(const char *s) _pure_;
567
568 int ip_tos_to_string_alloc(int i, char **s);
569 int ip_tos_from_string(const char *s);
570
571 const char *signal_to_string(int i) _const_;
572 int signal_from_string(const char *s) _pure_;
573
574 int signal_from_string_try_harder(const char *s);
575
576 extern int saved_argc;
577 extern char **saved_argv;
578
579 bool kexec_loaded(void);
580
581 int prot_from_flags(int flags) _const_;
582
583 char *format_bytes(char *buf, size_t l, off_t t);
584
585 int fd_wait_for_event(int fd, int event, usec_t timeout);
586
587 void* memdup(const void *p, size_t l) _alloc_(2);
588
589 int fd_inc_sndbuf(int fd, size_t n);
590 int fd_inc_rcvbuf(int fd, size_t n);
591
592 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...);
593
594 int setrlimit_closest(int resource, const struct rlimit *rlim);
595
596 bool http_url_is_valid(const char *url) _pure_;
597 bool documentation_url_is_valid(const char *url) _pure_;
598
599 bool http_etag_is_valid(const char *etag);
600
601 bool in_initrd(void);
602
603 void warn_melody(void);
604
605 int get_home_dir(char **ret);
606 int get_shell(char **_ret);
607
608 static inline void freep(void *p) {
609         free(*(void**) p);
610 }
611
612 static inline void closep(int *fd) {
613         safe_close(*fd);
614 }
615
616 static inline void umaskp(mode_t *u) {
617         umask(*u);
618 }
619
620 static inline void close_pairp(int (*p)[2]) {
621         safe_close_pair(*p);
622 }
623
624 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, fclose);
625 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, pclose);
626 DEFINE_TRIVIAL_CLEANUP_FUNC(DIR*, closedir);
627 DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, endmntent);
628
629 #define _cleanup_free_ _cleanup_(freep)
630 #define _cleanup_close_ _cleanup_(closep)
631 #define _cleanup_umask_ _cleanup_(umaskp)
632 #define _cleanup_globfree_ _cleanup_(globfree)
633 #define _cleanup_fclose_ _cleanup_(fclosep)
634 #define _cleanup_pclose_ _cleanup_(pclosep)
635 #define _cleanup_closedir_ _cleanup_(closedirp)
636 #define _cleanup_endmntent_ _cleanup_(endmntentp)
637 #define _cleanup_close_pair_ _cleanup_(close_pairp)
638
639 _malloc_  _alloc_(1, 2) static inline void *malloc_multiply(size_t a, size_t b) {
640         if (_unlikely_(b != 0 && a > ((size_t) -1) / b))
641                 return NULL;
642
643         return malloc(a * b);
644 }
645
646 _alloc_(2, 3) static inline void *realloc_multiply(void *p, size_t a, size_t b) {
647         if (_unlikely_(b != 0 && a > ((size_t) -1) / b))
648                 return NULL;
649
650         return realloc(p, a * b);
651 }
652
653 _alloc_(2, 3) static inline void *memdup_multiply(const void *p, size_t a, size_t b) {
654         if (_unlikely_(b != 0 && a > ((size_t) -1) / b))
655                 return NULL;
656
657         return memdup(p, a * b);
658 }
659
660 bool filename_is_valid(const char *p) _pure_;
661 bool path_is_safe(const char *p) _pure_;
662 bool string_is_safe(const char *p) _pure_;
663 bool string_has_cc(const char *p, const char *ok) _pure_;
664
665 /**
666  * Check if a string contains any glob patterns.
667  */
668 _pure_ static inline bool string_is_glob(const char *p) {
669         return !!strpbrk(p, GLOB_CHARS);
670 }
671
672 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
673                  int (*compar) (const void *, const void *, void *),
674                  void *arg);
675
676 #define _(String) gettext (String)
677 void init_gettext(void);
678 bool is_locale_utf8(void);
679
680 typedef enum DrawSpecialChar {
681         DRAW_TREE_VERTICAL,
682         DRAW_TREE_BRANCH,
683         DRAW_TREE_RIGHT,
684         DRAW_TREE_SPACE,
685         DRAW_TRIANGULAR_BULLET,
686         DRAW_BLACK_CIRCLE,
687         DRAW_ARROW,
688         DRAW_DASH,
689         _DRAW_SPECIAL_CHAR_MAX
690 } DrawSpecialChar;
691
692 const char *draw_special_char(DrawSpecialChar ch);
693
694 char *strreplace(const char *text, const char *old_string, const char *new_string);
695
696 char *strip_tab_ansi(char **p, size_t *l);
697
698 int on_ac_power(void);
699
700 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f);
701 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f);
702
703 #define FOREACH_LINE(line, f, on_error)                         \
704         for (;;)                                                \
705                 if (!fgets(line, sizeof(line), f)) {            \
706                         if (ferror(f)) {                        \
707                                 on_error;                       \
708                         }                                       \
709                         break;                                  \
710                 } else
711
712 #define FOREACH_DIRENT(de, d, on_error)                                 \
713         for (errno = 0, de = readdir(d);; errno = 0, de = readdir(d))   \
714                 if (!de) {                                              \
715                         if (errno > 0) {                                \
716                                 on_error;                               \
717                         }                                               \
718                         break;                                          \
719                 } else if (hidden_file((de)->d_name))                   \
720                         continue;                                       \
721                 else
722
723 #define FOREACH_DIRENT_ALL(de, d, on_error)                             \
724         for (errno = 0, de = readdir(d);; errno = 0, de = readdir(d))   \
725                 if (!de) {                                              \
726                         if (errno > 0) {                                \
727                                 on_error;                               \
728                         }                                               \
729                         break;                                          \
730                 } else
731
732 static inline void *mempset(void *s, int c, size_t n) {
733         memset(s, c, n);
734         return (uint8_t*)s + n;
735 }
736
737 char *hexmem(const void *p, size_t l);
738 void *unhexmem(const char *p, size_t l);
739
740 char *strextend(char **x, ...) _sentinel_;
741 char *strrep(const char *s, unsigned n);
742
743 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size);
744 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size);
745 #define GREEDY_REALLOC(array, allocated, need)                          \
746         greedy_realloc((void**) &(array), &(allocated), (need), sizeof((array)[0]))
747
748 #define GREEDY_REALLOC0(array, allocated, need)                         \
749         greedy_realloc0((void**) &(array), &(allocated), (need), sizeof((array)[0]))
750
751 static inline void _reset_errno_(int *saved_errno) {
752         errno = *saved_errno;
753 }
754
755 #define PROTECT_ERRNO _cleanup_(_reset_errno_) __attribute__((unused)) int _saved_errno_ = errno
756
757 static inline int negative_errno(void) {
758         /* This helper should be used to shut up gcc if you know 'errno' is
759          * negative. Instead of "return -errno;", use "return negative_errno();"
760          * It will suppress bogus gcc warnings in case it assumes 'errno' might
761          * be 0 and thus the caller's error-handling might not be triggered. */
762         assert_return(errno > 0, -EINVAL);
763         return -errno;
764 }
765
766 struct _umask_struct_ {
767         mode_t mask;
768         bool quit;
769 };
770
771 static inline void _reset_umask_(struct _umask_struct_ *s) {
772         umask(s->mask);
773 };
774
775 #define RUN_WITH_UMASK(mask)                                            \
776         for (_cleanup_(_reset_umask_) struct _umask_struct_ _saved_umask_ = { umask(mask), false }; \
777              !_saved_umask_.quit ;                                      \
778              _saved_umask_.quit = true)
779
780 static inline unsigned u64log2(uint64_t n) {
781 #if __SIZEOF_LONG_LONG__ == 8
782         return (n > 1) ? (unsigned) __builtin_clzll(n) ^ 63U : 0;
783 #else
784 #error "Wut?"
785 #endif
786 }
787
788 static inline unsigned u32ctz(uint32_t n) {
789 #if __SIZEOF_INT__ == 4
790         return __builtin_ctz(n);
791 #else
792 #error "Wut?"
793 #endif
794 }
795
796 static inline unsigned log2i(int x) {
797         assert(x > 0);
798
799         return __SIZEOF_INT__ * 8 - __builtin_clz(x) - 1;
800 }
801
802 static inline unsigned log2u(unsigned x) {
803         assert(x > 0);
804
805         return sizeof(unsigned) * 8 - __builtin_clz(x) - 1;
806 }
807
808 static inline unsigned log2u_round_up(unsigned x) {
809         assert(x > 0);
810
811         if (x == 1)
812                 return 0;
813
814         return log2u(x - 1) + 1;
815 }
816
817 static inline bool logind_running(void) {
818         return access("/run/systemd/seats/", F_OK) >= 0;
819 }
820
821 #define DECIMAL_STR_WIDTH(x)                            \
822         ({                                              \
823                 typeof(x) _x_ = (x);                    \
824                 unsigned ans = 1;                       \
825                 while (_x_ /= 10)                       \
826                         ans++;                          \
827                 ans;                                    \
828         })
829
830 int unlink_noerrno(const char *path);
831
832 #define alloca0(n)                                      \
833         ({                                              \
834                 char *_new_;                            \
835                 size_t _len_ = n;                       \
836                 _new_ = alloca(_len_);                  \
837                 (void *) memset(_new_, 0, _len_);       \
838         })
839
840 /* It's not clear what alignment glibc/gcc alloca() guarantee, hence provide a guaranteed safe version */
841 #define alloca_align(size, align)                                       \
842         ({                                                              \
843                 void *_ptr_;                                            \
844                 size_t _mask_ = (align) - 1;                            \
845                 _ptr_ = alloca((size) + _mask_);                        \
846                 (void*)(((uintptr_t)_ptr_ + _mask_) & ~_mask_);         \
847         })
848
849 #define alloca0_align(size, align)                                      \
850         ({                                                              \
851                 void *_new_;                                            \
852                 size_t _size_ = (size);                                 \
853                 _new_ = alloca_align(_size_, (align));                  \
854                 (void*)memset(_new_, 0, _size_);                        \
855         })
856
857 #define strjoina(a, ...)                                                \
858         ({                                                              \
859                 const char *_appendees_[] = { a, __VA_ARGS__ };         \
860                 char *_d_, *_p_;                                        \
861                 int _len_ = 0;                                          \
862                 unsigned _i_;                                           \
863                 for (_i_ = 0; _i_ < ELEMENTSOF(_appendees_) && _appendees_[_i_]; _i_++) \
864                         _len_ += strlen(_appendees_[_i_]);              \
865                 _p_ = _d_ = alloca(_len_ + 1);                          \
866                 for (_i_ = 0; _i_ < ELEMENTSOF(_appendees_) && _appendees_[_i_]; _i_++) \
867                         _p_ = stpcpy(_p_, _appendees_[_i_]);            \
868                 *_p_ = 0;                                               \
869                 _d_;                                                    \
870         })
871
872 bool id128_is_valid(const char *s) _pure_;
873
874 int split_pair(const char *s, const char *sep, char **l, char **r);
875
876 int shall_restore_state(void);
877
878 /**
879  * Normal qsort requires base to be nonnull. Here were require
880  * that only if nmemb > 0.
881  */
882 static inline void qsort_safe(void *base, size_t nmemb, size_t size,
883                               int (*compar)(const void *, const void *)) {
884         if (nmemb) {
885                 assert(base);
886                 qsort(base, nmemb, size, compar);
887         }
888 }
889
890 int proc_cmdline(char **ret);
891 int parse_proc_cmdline(int (*parse_word)(const char *key, const char *value));
892 int get_proc_cmdline_key(const char *parameter, char **value);
893
894 int container_get_leader(const char *machine, pid_t *pid);
895
896 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd);
897 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd);
898
899 int getpeercred(int fd, struct ucred *ucred);
900 int getpeersec(int fd, char **ret);
901
902 int writev_safe(int fd, const struct iovec *w, int j);
903
904 int mkostemp_safe(char *pattern, int flags);
905 int open_tmpfile(const char *path, int flags);
906
907 int fd_warn_permissions(const char *path, int fd);
908
909 unsigned long personality_from_string(const char *p);
910 const char *personality_to_string(unsigned long);
911
912 uint64_t physical_memory(void);
913
914 void hexdump(FILE *f, const void *p, size_t s);
915
916 union file_handle_union {
917         struct file_handle handle;
918         char padding[sizeof(struct file_handle) + MAX_HANDLE_SZ];
919 };
920 #define FILE_HANDLE_INIT { .handle.handle_bytes = MAX_HANDLE_SZ }
921
922 int update_reboot_param_file(const char *param);
923
924 int umount_recursive(const char *target, int flags);
925
926 int bind_remount_recursive(const char *prefix, bool ro);
927
928 int fflush_and_check(FILE *f);
929
930 int tempfn_xxxxxx(const char *p, char **ret);
931 int tempfn_random(const char *p, char **ret);
932 int tempfn_random_child(const char *p, char **ret);
933
934 bool is_localhost(const char *hostname);
935
936 int take_password_lock(const char *root);
937
938 int is_symlink(const char *path);
939 int is_dir(const char *path, bool follow);
940
941 typedef enum UnquoteFlags {
942         UNQUOTE_RELAX     = 1,
943         UNQUOTE_CUNESCAPE = 2,
944 } UnquoteFlags;
945
946 int unquote_first_word(const char **p, char **ret, UnquoteFlags flags);
947 int unquote_many_words(const char **p, UnquoteFlags flags, ...) _sentinel_;
948
949 int free_and_strdup(char **p, const char *s);
950
951 int sethostname_idempotent(const char *s);
952
953 #define INOTIFY_EVENT_MAX (sizeof(struct inotify_event) + NAME_MAX + 1)
954
955 #define FOREACH_INOTIFY_EVENT(e, buffer, sz) \
956         for ((e) = &buffer.ev;                                \
957              (uint8_t*) (e) < (uint8_t*) (buffer.raw) + (sz); \
958              (e) = (struct inotify_event*) ((uint8_t*) (e) + sizeof(struct inotify_event) + (e)->len))
959
960 union inotify_event_buffer {
961         struct inotify_event ev;
962         uint8_t raw[INOTIFY_EVENT_MAX];
963 };
964
965 #define laccess(path, mode) faccessat(AT_FDCWD, (path), (mode), AT_SYMLINK_NOFOLLOW)
966
967 int ptsname_malloc(int fd, char **ret);
968
969 int openpt_in_namespace(pid_t pid, int flags);
970
971 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags);
972
973 int fd_setcrtime(int fd, usec_t usec);
974 int fd_getcrtime(int fd, usec_t *usec);
975 int path_getcrtime(const char *p, usec_t *usec);
976 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags);
977
978 int chattr_fd(int fd, unsigned value, unsigned mask);
979 int chattr_path(const char *p, unsigned value, unsigned mask);
980
981 int read_attr_fd(int fd, unsigned *ret);
982 int read_attr_path(const char *p, unsigned *ret);
983
984 typedef struct LockFile {
985         char *path;
986         int fd;
987         int operation;
988 } LockFile;
989
990 int make_lock_file(const char *p, int operation, LockFile *ret);
991 int make_lock_file_for(const char *p, int operation, LockFile *ret);
992 void release_lock_file(LockFile *f);
993
994 #define _cleanup_release_lock_file_ _cleanup_(release_lock_file)
995
996 #define LOCK_FILE_INIT { .fd = -1, .path = NULL }
997
998 #define RLIMIT_MAKE_CONST(lim) ((struct rlimit) { lim, lim })
999
1000 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length);
1001
1002 void sigkill_wait(pid_t *pid);
1003 #define _cleanup_sigkill_wait_ _cleanup_(sigkill_wait)
1004
1005 int syslog_parse_priority(const char **p, int *priority, bool with_facility);
1006
1007 void cmsg_close_all(struct msghdr *mh);
1008
1009 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath);
1010
1011 char *shell_maybe_quote(const char *s);
1012
1013 int parse_mode(const char *s, mode_t *ret);