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