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