]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/util.c
pam: rename master user cgroup to 'master'
[thirdparty/systemd.git] / src / util.c
CommitLineData
d6c9574f 1/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
60918275 2
a7334b09
LP
3/***
4 This file is part of systemd.
5
6 Copyright 2010 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20***/
21
60918275
LP
22#include <assert.h>
23#include <string.h>
24#include <unistd.h>
25#include <errno.h>
85261803 26#include <stdlib.h>
034c6ed7
LP
27#include <signal.h>
28#include <stdio.h>
1dccbe19
LP
29#include <syslog.h>
30#include <sched.h>
31#include <sys/resource.h>
ef886c6a 32#include <linux/sched.h>
a9f5d454
LP
33#include <sys/types.h>
34#include <sys/stat.h>
3a0ecb08 35#include <fcntl.h>
a0d40ac5 36#include <dirent.h>
601f6a1e
LP
37#include <sys/ioctl.h>
38#include <linux/vt.h>
39#include <linux/tiocl.h>
80876c20
LP
40#include <termios.h>
41#include <stdarg.h>
42#include <sys/inotify.h>
43#include <sys/poll.h>
8d567588 44#include <libgen.h>
3177a7fa 45#include <ctype.h>
5b6319dc 46#include <sys/prctl.h>
ef2f1067
LP
47#include <sys/utsname.h>
48#include <pwd.h>
4fd5948e 49#include <netinet/ip.h>
3fe5e5d4 50#include <linux/kd.h>
afea26ad 51#include <dlfcn.h>
2e78aa99 52#include <sys/wait.h>
60918275
LP
53
54#include "macro.h"
55#include "util.h"
1dccbe19
LP
56#include "ioprio.h"
57#include "missing.h"
a9f5d454 58#include "log.h"
65d2ebdc 59#include "strv.h"
e51bc1a2 60#include "label.h"
d06dacd0 61#include "exit-status.h"
56cf987f 62
e05797fb
LP
63bool streq_ptr(const char *a, const char *b) {
64
65 /* Like streq(), but tries to make sense of NULL pointers */
66
67 if (a && b)
68 return streq(a, b);
69
70 if (!a && !b)
71 return true;
72
73 return false;
74}
75
47be870b 76usec_t now(clockid_t clock_id) {
60918275
LP
77 struct timespec ts;
78
47be870b 79 assert_se(clock_gettime(clock_id, &ts) == 0);
60918275
LP
80
81 return timespec_load(&ts);
82}
83
63983207 84dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
871d7de4
LP
85 assert(ts);
86
87 ts->realtime = now(CLOCK_REALTIME);
88 ts->monotonic = now(CLOCK_MONOTONIC);
89
90 return ts;
91}
92
60918275
LP
93usec_t timespec_load(const struct timespec *ts) {
94 assert(ts);
95
96 return
97 (usec_t) ts->tv_sec * USEC_PER_SEC +
98 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
99}
100
101struct timespec *timespec_store(struct timespec *ts, usec_t u) {
102 assert(ts);
103
104 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
105 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
106
107 return ts;
108}
109
110usec_t timeval_load(const struct timeval *tv) {
111 assert(tv);
112
113 return
114 (usec_t) tv->tv_sec * USEC_PER_SEC +
115 (usec_t) tv->tv_usec;
116}
117
118struct timeval *timeval_store(struct timeval *tv, usec_t u) {
119 assert(tv);
120
121 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
122 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
123
124 return tv;
125}
126
127bool endswith(const char *s, const char *postfix) {
128 size_t sl, pl;
129
130 assert(s);
131 assert(postfix);
132
133 sl = strlen(s);
134 pl = strlen(postfix);
135
d4d0d4db
LP
136 if (pl == 0)
137 return true;
138
60918275
LP
139 if (sl < pl)
140 return false;
141
142 return memcmp(s + sl - pl, postfix, pl) == 0;
143}
144
145bool startswith(const char *s, const char *prefix) {
146 size_t sl, pl;
147
148 assert(s);
149 assert(prefix);
150
151 sl = strlen(s);
152 pl = strlen(prefix);
153
d4d0d4db
LP
154 if (pl == 0)
155 return true;
156
60918275
LP
157 if (sl < pl)
158 return false;
159
160 return memcmp(s, prefix, pl) == 0;
161}
162
3177a7fa
MAP
163bool startswith_no_case(const char *s, const char *prefix) {
164 size_t sl, pl;
165 unsigned i;
166
167 assert(s);
168 assert(prefix);
169
170 sl = strlen(s);
171 pl = strlen(prefix);
172
173 if (pl == 0)
174 return true;
175
176 if (sl < pl)
177 return false;
178
179 for(i = 0; i < pl; ++i) {
180 if (tolower(s[i]) != tolower(prefix[i]))
181 return false;
182 }
183
184 return true;
185}
186
79d6d816
LP
187bool first_word(const char *s, const char *word) {
188 size_t sl, wl;
189
190 assert(s);
191 assert(word);
192
193 sl = strlen(s);
194 wl = strlen(word);
195
196 if (sl < wl)
197 return false;
198
d4d0d4db
LP
199 if (wl == 0)
200 return true;
201
79d6d816
LP
202 if (memcmp(s, word, wl) != 0)
203 return false;
204
d4d0d4db
LP
205 return s[wl] == 0 ||
206 strchr(WHITESPACE, s[wl]);
79d6d816
LP
207}
208
42f4e3c4 209int close_nointr(int fd) {
60918275
LP
210 assert(fd >= 0);
211
212 for (;;) {
213 int r;
214
215 if ((r = close(fd)) >= 0)
216 return r;
217
218 if (errno != EINTR)
219 return r;
220 }
221}
85261803 222
85f136b5 223void close_nointr_nofail(int fd) {
80876c20 224 int saved_errno = errno;
85f136b5
LP
225
226 /* like close_nointr() but cannot fail, and guarantees errno
227 * is unchanged */
228
229 assert_se(close_nointr(fd) == 0);
80876c20
LP
230
231 errno = saved_errno;
85f136b5
LP
232}
233
5b6319dc
LP
234void close_many(const int fds[], unsigned n_fd) {
235 unsigned i;
236
237 for (i = 0; i < n_fd; i++)
238 close_nointr_nofail(fds[i]);
239}
240
85261803
LP
241int parse_boolean(const char *v) {
242 assert(v);
243
44d8db9e 244 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
85261803 245 return 1;
44d8db9e 246 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
85261803
LP
247 return 0;
248
249 return -EINVAL;
250}
251
3ba686c1
LP
252int parse_pid(const char *s, pid_t* ret_pid) {
253 unsigned long ul;
254 pid_t pid;
255 int r;
256
257 assert(s);
258 assert(ret_pid);
259
260 if ((r = safe_atolu(s, &ul)) < 0)
261 return r;
262
263 pid = (pid_t) ul;
264
265 if ((unsigned long) pid != ul)
266 return -ERANGE;
267
268 if (pid <= 0)
269 return -ERANGE;
270
271 *ret_pid = pid;
272 return 0;
273}
274
85261803
LP
275int safe_atou(const char *s, unsigned *ret_u) {
276 char *x = NULL;
034c6ed7 277 unsigned long l;
85261803
LP
278
279 assert(s);
280 assert(ret_u);
281
282 errno = 0;
283 l = strtoul(s, &x, 0);
284
285 if (!x || *x || errno)
286 return errno ? -errno : -EINVAL;
287
034c6ed7 288 if ((unsigned long) (unsigned) l != l)
85261803
LP
289 return -ERANGE;
290
291 *ret_u = (unsigned) l;
292 return 0;
293}
294
295int safe_atoi(const char *s, int *ret_i) {
296 char *x = NULL;
034c6ed7 297 long l;
85261803
LP
298
299 assert(s);
300 assert(ret_i);
301
302 errno = 0;
303 l = strtol(s, &x, 0);
304
305 if (!x || *x || errno)
306 return errno ? -errno : -EINVAL;
307
034c6ed7 308 if ((long) (int) l != l)
85261803
LP
309 return -ERANGE;
310
034c6ed7
LP
311 *ret_i = (int) l;
312 return 0;
313}
314
034c6ed7
LP
315int safe_atollu(const char *s, long long unsigned *ret_llu) {
316 char *x = NULL;
317 unsigned long long l;
318
319 assert(s);
320 assert(ret_llu);
321
322 errno = 0;
323 l = strtoull(s, &x, 0);
324
325 if (!x || *x || errno)
326 return errno ? -errno : -EINVAL;
327
328 *ret_llu = l;
329 return 0;
330}
331
332int safe_atolli(const char *s, long long int *ret_lli) {
333 char *x = NULL;
334 long long l;
335
336 assert(s);
337 assert(ret_lli);
338
339 errno = 0;
340 l = strtoll(s, &x, 0);
341
342 if (!x || *x || errno)
343 return errno ? -errno : -EINVAL;
344
345 *ret_lli = l;
85261803
LP
346 return 0;
347}
a41e8209 348
a41e8209 349/* Split a string into words. */
65d2ebdc 350char *split(const char *c, size_t *l, const char *separator, char **state) {
a41e8209
LP
351 char *current;
352
353 current = *state ? *state : (char*) c;
354
355 if (!*current || *c == 0)
356 return NULL;
357
65d2ebdc
LP
358 current += strspn(current, separator);
359 *l = strcspn(current, separator);
82919e3d
LP
360 *state = current+*l;
361
362 return (char*) current;
363}
364
034c6ed7
LP
365/* Split a string into words, but consider strings enclosed in '' and
366 * "" as words even if they include spaces. */
367char *split_quoted(const char *c, size_t *l, char **state) {
0bab36f2
LP
368 char *current, *e;
369 bool escaped = false;
034c6ed7
LP
370
371 current = *state ? *state : (char*) c;
372
373 if (!*current || *c == 0)
374 return NULL;
375
376 current += strspn(current, WHITESPACE);
377
378 if (*current == '\'') {
379 current ++;
034c6ed7 380
0bab36f2
LP
381 for (e = current; *e; e++) {
382 if (escaped)
383 escaped = false;
384 else if (*e == '\\')
385 escaped = true;
386 else if (*e == '\'')
387 break;
388 }
389
390 *l = e-current;
391 *state = *e == 0 ? e : e+1;
034c6ed7
LP
392 } else if (*current == '\"') {
393 current ++;
034c6ed7 394
0bab36f2
LP
395 for (e = current; *e; e++) {
396 if (escaped)
397 escaped = false;
398 else if (*e == '\\')
399 escaped = true;
400 else if (*e == '\"')
401 break;
402 }
403
404 *l = e-current;
405 *state = *e == 0 ? e : e+1;
034c6ed7 406 } else {
0bab36f2
LP
407 for (e = current; *e; e++) {
408 if (escaped)
409 escaped = false;
410 else if (*e == '\\')
411 escaped = true;
412 else if (strchr(WHITESPACE, *e))
413 break;
414 }
415 *l = e-current;
416 *state = e;
034c6ed7
LP
417 }
418
419 return (char*) current;
420}
421
65d2ebdc
LP
422char **split_path_and_make_absolute(const char *p) {
423 char **l;
424 assert(p);
425
426 if (!(l = strv_split(p, ":")))
427 return NULL;
428
429 if (!strv_path_make_absolute_cwd(l)) {
430 strv_free(l);
431 return NULL;
432 }
433
434 return l;
435}
436
034c6ed7
LP
437int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
438 int r;
439 FILE *f;
440 char fn[132], line[256], *p;
bb00e604 441 long unsigned ppid;
034c6ed7
LP
442
443 assert(pid >= 0);
444 assert(_ppid);
445
bb00e604 446 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
034c6ed7
LP
447 fn[sizeof(fn)-1] = 0;
448
449 if (!(f = fopen(fn, "r")))
450 return -errno;
451
452 if (!(fgets(line, sizeof(line), f))) {
453 r = -errno;
454 fclose(f);
455 return r;
456 }
457
458 fclose(f);
459
460 /* Let's skip the pid and comm fields. The latter is enclosed
461 * in () but does not escape any () in its value, so let's
462 * skip over it manually */
463
464 if (!(p = strrchr(line, ')')))
465 return -EIO;
466
467 p++;
468
469 if (sscanf(p, " "
470 "%*c " /* state */
bb00e604 471 "%lu ", /* ppid */
034c6ed7
LP
472 &ppid) != 1)
473 return -EIO;
474
bb00e604 475 if ((long unsigned) (pid_t) ppid != ppid)
034c6ed7
LP
476 return -ERANGE;
477
478 *_ppid = (pid_t) ppid;
479
480 return 0;
481}
482
483int write_one_line_file(const char *fn, const char *line) {
484 FILE *f;
485 int r;
486
487 assert(fn);
488 assert(line);
489
490 if (!(f = fopen(fn, "we")))
491 return -errno;
492
493 if (fputs(line, f) < 0) {
494 r = -errno;
495 goto finish;
496 }
497
498 r = 0;
499finish:
500 fclose(f);
501 return r;
502}
503
504int read_one_line_file(const char *fn, char **line) {
505 FILE *f;
506 int r;
97c4a07d 507 char t[LINE_MAX], *c;
034c6ed7
LP
508
509 assert(fn);
510 assert(line);
511
512 if (!(f = fopen(fn, "re")))
513 return -errno;
514
515 if (!(fgets(t, sizeof(t), f))) {
516 r = -errno;
517 goto finish;
518 }
519
520 if (!(c = strdup(t))) {
521 r = -ENOMEM;
522 goto finish;
523 }
524
525 *line = c;
526 r = 0;
527
528finish:
529 fclose(f);
530 return r;
531}
44d8db9e 532
97c4a07d
LP
533int read_full_file(const char *fn, char **contents) {
534 FILE *f;
535 int r;
536 size_t n, l;
537 char *buf = NULL;
538 struct stat st;
539
540 if (!(f = fopen(fn, "re")))
541 return -errno;
542
543 if (fstat(fileno(f), &st) < 0) {
544 r = -errno;
545 goto finish;
546 }
547
548 n = st.st_size > 0 ? st.st_size : LINE_MAX;
549 l = 0;
550
551 for (;;) {
552 char *t;
553 size_t k;
554
555 if (!(t = realloc(buf, n+1))) {
556 r = -ENOMEM;
557 goto finish;
558 }
559
560 buf = t;
561 k = fread(buf + l, 1, n - l, f);
562
563 if (k <= 0) {
564 if (ferror(f)) {
565 r = -errno;
566 goto finish;
567 }
568
569 break;
570 }
571
572 l += k;
573 n *= 2;
574
575 /* Safety check */
576 if (n > 4*1024*1024) {
577 r = -E2BIG;
578 goto finish;
579 }
580 }
581
582 if (buf)
583 buf[l] = 0;
584 else if (!(buf = calloc(1, 1))) {
585 r = -errno;
586 goto finish;
587 }
588
589 *contents = buf;
590 buf = NULL;
591
592 r = 0;
593
594finish:
595 fclose(f);
596 free(buf);
597
598 return r;
599}
600
601int parse_env_file(
602 const char *fname,
c899f8c6 603 const char *separator, ...) {
97c4a07d 604
ce8a6aa1 605 int r = 0;
97c4a07d
LP
606 char *contents, *p;
607
608 assert(fname);
c899f8c6 609 assert(separator);
97c4a07d
LP
610
611 if ((r = read_full_file(fname, &contents)) < 0)
612 return r;
613
614 p = contents;
615 for (;;) {
616 const char *key = NULL;
617
c899f8c6 618 p += strspn(p, separator);
97c4a07d
LP
619 p += strspn(p, WHITESPACE);
620
621 if (!*p)
622 break;
623
624 if (!strchr(COMMENTS, *p)) {
625 va_list ap;
626 char **value;
627
c899f8c6 628 va_start(ap, separator);
97c4a07d
LP
629 while ((key = va_arg(ap, char *))) {
630 size_t n;
631 char *v;
632
633 value = va_arg(ap, char **);
634
635 n = strlen(key);
636 if (strncmp(p, key, n) != 0 ||
637 p[n] != '=')
638 continue;
639
640 p += n + 1;
c899f8c6 641 n = strcspn(p, separator);
97c4a07d
LP
642
643 if (n >= 2 &&
e7db37dd
LP
644 strchr(QUOTES, p[0]) &&
645 p[n-1] == p[0])
97c4a07d
LP
646 v = strndup(p+1, n-2);
647 else
648 v = strndup(p, n);
649
650 if (!v) {
651 r = -ENOMEM;
652 va_end(ap);
653 goto fail;
654 }
655
dd36de4d
KS
656 if (v[0] == '\0') {
657 /* return empty value strings as NULL */
658 free(v);
659 v = NULL;
660 }
661
97c4a07d
LP
662 free(*value);
663 *value = v;
664
665 p += n;
ce8a6aa1
LP
666
667 r ++;
97c4a07d
LP
668 break;
669 }
670 va_end(ap);
671 }
672
673 if (!key)
c899f8c6 674 p += strcspn(p, separator);
97c4a07d
LP
675 }
676
97c4a07d
LP
677fail:
678 free(contents);
679 return r;
680}
681
7072ced8
LP
682char *truncate_nl(char *s) {
683 assert(s);
684
685 s[strcspn(s, NEWLINE)] = 0;
686 return s;
687}
688
689int get_process_name(pid_t pid, char **name) {
690 char *p;
691 int r;
692
693 assert(pid >= 1);
694 assert(name);
695
bb00e604 696 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
7072ced8
LP
697 return -ENOMEM;
698
699 r = read_one_line_file(p, name);
700 free(p);
701
702 if (r < 0)
703 return r;
704
705 truncate_nl(*name);
706 return 0;
707}
708
c59760ee
LP
709int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
710 char *p, *r, *k;
711 int c;
712 bool space = false;
713 size_t left;
714 FILE *f;
715
716 assert(pid >= 1);
717 assert(max_length > 0);
718 assert(line);
719
720 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
721 return -ENOMEM;
722
723 f = fopen(p, "r");
724 free(p);
725
726 if (!f)
727 return -errno;
728
729 if (!(r = new(char, max_length))) {
730 fclose(f);
731 return -ENOMEM;
732 }
733
734 k = r;
735 left = max_length;
736 while ((c = getc(f)) != EOF) {
737
738 if (isprint(c)) {
739 if (space) {
740 if (left <= 4)
741 break;
742
743 *(k++) = ' ';
057fbb58 744 left--;
c59760ee
LP
745 space = false;
746 }
747
748 if (left <= 4)
749 break;
750
751 *(k++) = (char) c;
057fbb58 752 left--;
c59760ee
LP
753 } else
754 space = true;
755 }
756
757 if (left <= 4) {
758 size_t n = MIN(left-1, 3U);
759 memcpy(k, "...", n);
760 k[n] = 0;
761 } else
762 *k = 0;
763
764 fclose(f);
765
35d2e7ec
LP
766 /* Kernel threads have no argv[] */
767 if (r[0] == 0) {
768 char *t;
769 int h;
770
771 free(r);
772
773 if ((h = get_process_name(pid, &t)) < 0)
774 return h;
775
776 h = asprintf(&r, "[%s]", t);
777 free(t);
778
779 if (h < 0)
780 return -ENOMEM;
781 }
fa776d8e 782
c59760ee
LP
783 *line = r;
784 return 0;
785}
786
fab56fc5
LP
787char *strnappend(const char *s, const char *suffix, size_t b) {
788 size_t a;
44d8db9e
LP
789 char *r;
790
fab56fc5
LP
791 if (!s && !suffix)
792 return strdup("");
793
794 if (!s)
795 return strndup(suffix, b);
796
797 if (!suffix)
798 return strdup(s);
799
44d8db9e
LP
800 assert(s);
801 assert(suffix);
802
803 a = strlen(s);
44d8db9e
LP
804
805 if (!(r = new(char, a+b+1)))
806 return NULL;
807
808 memcpy(r, s, a);
809 memcpy(r+a, suffix, b);
810 r[a+b] = 0;
811
812 return r;
813}
87f0e418 814
fab56fc5
LP
815char *strappend(const char *s, const char *suffix) {
816 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
817}
818
87f0e418
LP
819int readlink_malloc(const char *p, char **r) {
820 size_t l = 100;
821
822 assert(p);
823 assert(r);
824
825 for (;;) {
826 char *c;
827 ssize_t n;
828
829 if (!(c = new(char, l)))
830 return -ENOMEM;
831
832 if ((n = readlink(p, c, l-1)) < 0) {
833 int ret = -errno;
834 free(c);
835 return ret;
836 }
837
838 if ((size_t) n < l-1) {
839 c[n] = 0;
840 *r = c;
841 return 0;
842 }
843
844 free(c);
845 l *= 2;
846 }
847}
848
2c7108c4
LP
849int readlink_and_make_absolute(const char *p, char **r) {
850 char *target, *k;
851 int j;
852
853 assert(p);
854 assert(r);
855
856 if ((j = readlink_malloc(p, &target)) < 0)
857 return j;
858
859 k = file_in_same_dir(p, target);
860 free(target);
861
862 if (!k)
863 return -ENOMEM;
864
865 *r = k;
866 return 0;
867}
868
35d2e7ec
LP
869int parent_of_path(const char *path, char **_r) {
870 const char *e, *a = NULL, *b = NULL, *p;
871 char *r;
872 bool slash = false;
873
874 assert(path);
875 assert(_r);
876
877 if (!*path)
878 return -EINVAL;
879
880 for (e = path; *e; e++) {
881
882 if (!slash && *e == '/') {
883 a = b;
884 b = e;
885 slash = true;
886 } else if (slash && *e != '/')
887 slash = false;
888 }
889
890 if (*(e-1) == '/')
891 p = a;
892 else
893 p = b;
894
895 if (!p)
896 return -EINVAL;
897
898 if (p == path)
899 r = strdup("/");
900 else
901 r = strndup(path, p-path);
902
903 if (!r)
904 return -ENOMEM;
905
906 *_r = r;
907 return 0;
908}
909
910
87f0e418
LP
911char *file_name_from_path(const char *p) {
912 char *r;
913
914 assert(p);
915
916 if ((r = strrchr(p, '/')))
917 return r + 1;
918
919 return (char*) p;
920}
0301abf4
LP
921
922bool path_is_absolute(const char *p) {
923 assert(p);
924
925 return p[0] == '/';
926}
927
928bool is_path(const char *p) {
929
930 return !!strchr(p, '/');
931}
932
933char *path_make_absolute(const char *p, const char *prefix) {
934 char *r;
935
936 assert(p);
937
65d2ebdc
LP
938 /* Makes every item in the list an absolute path by prepending
939 * the prefix, if specified and necessary */
940
0301abf4
LP
941 if (path_is_absolute(p) || !prefix)
942 return strdup(p);
943
944 if (asprintf(&r, "%s/%s", prefix, p) < 0)
945 return NULL;
946
947 return r;
948}
2a987ee8 949
65d2ebdc
LP
950char *path_make_absolute_cwd(const char *p) {
951 char *cwd, *r;
952
953 assert(p);
954
955 /* Similar to path_make_absolute(), but prefixes with the
956 * current working directory. */
957
958 if (path_is_absolute(p))
959 return strdup(p);
960
961 if (!(cwd = get_current_dir_name()))
962 return NULL;
963
964 r = path_make_absolute(p, cwd);
965 free(cwd);
966
967 return r;
968}
969
970char **strv_path_make_absolute_cwd(char **l) {
971 char **s;
972
973 /* Goes through every item in the string list and makes it
974 * absolute. This works in place and won't rollback any
975 * changes on failure. */
976
977 STRV_FOREACH(s, l) {
978 char *t;
979
980 if (!(t = path_make_absolute_cwd(*s)))
981 return NULL;
982
983 free(*s);
984 *s = t;
985 }
986
987 return l;
988}
989
c3f6d675
LP
990char **strv_path_canonicalize(char **l) {
991 char **s;
992 unsigned k = 0;
993 bool enomem = false;
994
995 if (strv_isempty(l))
996 return l;
997
998 /* Goes through every item in the string list and canonicalize
999 * the path. This works in place and won't rollback any
1000 * changes on failure. */
1001
1002 STRV_FOREACH(s, l) {
1003 char *t, *u;
1004
1005 t = path_make_absolute_cwd(*s);
1006 free(*s);
1007
1008 if (!t) {
1009 enomem = true;
1010 continue;
1011 }
1012
1013 errno = 0;
1014 u = canonicalize_file_name(t);
1015 free(t);
1016
1017 if (!u) {
1018 if (errno == ENOMEM || !errno)
1019 enomem = true;
1020
1021 continue;
1022 }
1023
1024 l[k++] = u;
1025 }
1026
1027 l[k] = NULL;
1028
1029 if (enomem)
1030 return NULL;
1031
1032 return l;
1033}
1034
2a987ee8
LP
1035int reset_all_signal_handlers(void) {
1036 int sig;
1037
1038 for (sig = 1; sig < _NSIG; sig++) {
1039 struct sigaction sa;
1040
1041 if (sig == SIGKILL || sig == SIGSTOP)
1042 continue;
1043
1044 zero(sa);
1045 sa.sa_handler = SIG_DFL;
431c32bf 1046 sa.sa_flags = SA_RESTART;
2a987ee8
LP
1047
1048 /* On Linux the first two RT signals are reserved by
1049 * glibc, and sigaction() will return EINVAL for them. */
1050 if ((sigaction(sig, &sa, NULL) < 0))
1051 if (errno != EINVAL)
1052 return -errno;
1053 }
1054
8e274523 1055 return 0;
2a987ee8 1056}
4a72ff34
LP
1057
1058char *strstrip(char *s) {
1059 char *e, *l = NULL;
1060
1061 /* Drops trailing whitespace. Modifies the string in
1062 * place. Returns pointer to first non-space character */
1063
1064 s += strspn(s, WHITESPACE);
1065
1066 for (e = s; *e; e++)
1067 if (!strchr(WHITESPACE, *e))
1068 l = e;
1069
1070 if (l)
1071 *(l+1) = 0;
1072 else
1073 *s = 0;
1074
1075 return s;
4a72ff34
LP
1076}
1077
ee9b5e01
LP
1078char *delete_chars(char *s, const char *bad) {
1079 char *f, *t;
1080
1081 /* Drops all whitespace, regardless where in the string */
1082
1083 for (f = s, t = s; *f; f++) {
1084 if (strchr(bad, *f))
1085 continue;
1086
1087 *(t++) = *f;
1088 }
1089
1090 *t = 0;
1091
1092 return s;
1093}
1094
4a72ff34
LP
1095char *file_in_same_dir(const char *path, const char *filename) {
1096 char *e, *r;
1097 size_t k;
1098
1099 assert(path);
1100 assert(filename);
1101
1102 /* This removes the last component of path and appends
1103 * filename, unless the latter is absolute anyway or the
1104 * former isn't */
1105
1106 if (path_is_absolute(filename))
1107 return strdup(filename);
1108
1109 if (!(e = strrchr(path, '/')))
1110 return strdup(filename);
1111
1112 k = strlen(filename);
1113 if (!(r = new(char, e-path+1+k+1)))
1114 return NULL;
1115
1116 memcpy(r, path, e-path+1);
1117 memcpy(r+(e-path)+1, filename, k+1);
1118
1119 return r;
1120}
fb624d04 1121
8c6db833
LP
1122int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1123 struct stat st;
1124
56cf987f 1125 if (label_mkdir(path, mode) >= 0)
8c6db833
LP
1126 if (chmod_and_chown(path, mode, uid, gid) < 0)
1127 return -errno;
1128
1129 if (lstat(path, &st) < 0)
1130 return -errno;
1131
1132 if ((st.st_mode & 0777) != mode ||
1133 st.st_uid != uid ||
1134 st.st_gid != gid ||
1135 !S_ISDIR(st.st_mode)) {
1136 errno = EEXIST;
1137 return -errno;
1138 }
1139
1140 return 0;
1141}
1142
1143
a9f5d454
LP
1144int mkdir_parents(const char *path, mode_t mode) {
1145 const char *p, *e;
1146
1147 assert(path);
1148
1149 /* Creates every parent directory in the path except the last
1150 * component. */
1151
1152 p = path + strspn(path, "/");
1153 for (;;) {
1154 int r;
1155 char *t;
1156
1157 e = p + strcspn(p, "/");
1158 p = e + strspn(e, "/");
1159
1160 /* Is this the last component? If so, then we're
1161 * done */
1162 if (*p == 0)
1163 return 0;
1164
1165 if (!(t = strndup(path, e - path)))
1166 return -ENOMEM;
1167
56cf987f 1168 r = label_mkdir(t, mode);
a9f5d454
LP
1169 free(t);
1170
1171 if (r < 0 && errno != EEXIST)
1172 return -errno;
1173 }
1174}
1175
bbd67135
LP
1176int mkdir_p(const char *path, mode_t mode) {
1177 int r;
1178
1179 /* Like mkdir -p */
1180
1181 if ((r = mkdir_parents(path, mode)) < 0)
1182 return r;
1183
56cf987f 1184 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
bbd67135
LP
1185 return -errno;
1186
1187 return 0;
1188}
1189
c32dd69b
LP
1190int rmdir_parents(const char *path, const char *stop) {
1191 size_t l;
1192 int r = 0;
1193
1194 assert(path);
1195 assert(stop);
1196
1197 l = strlen(path);
1198
1199 /* Skip trailing slashes */
1200 while (l > 0 && path[l-1] == '/')
1201 l--;
1202
1203 while (l > 0) {
1204 char *t;
1205
1206 /* Skip last component */
1207 while (l > 0 && path[l-1] != '/')
1208 l--;
1209
1210 /* Skip trailing slashes */
1211 while (l > 0 && path[l-1] == '/')
1212 l--;
1213
1214 if (l <= 0)
1215 break;
1216
1217 if (!(t = strndup(path, l)))
1218 return -ENOMEM;
1219
1220 if (path_startswith(stop, t)) {
1221 free(t);
1222 return 0;
1223 }
1224
1225 r = rmdir(t);
1226 free(t);
1227
1228 if (r < 0)
1229 if (errno != ENOENT)
1230 return -errno;
1231 }
1232
1233 return 0;
1234}
1235
1236
fb624d04
LP
1237char hexchar(int x) {
1238 static const char table[16] = "0123456789abcdef";
1239
1240 return table[x & 15];
1241}
4fe88d28
LP
1242
1243int unhexchar(char c) {
1244
1245 if (c >= '0' && c <= '9')
1246 return c - '0';
1247
1248 if (c >= 'a' && c <= 'f')
ea430986 1249 return c - 'a' + 10;
4fe88d28
LP
1250
1251 if (c >= 'A' && c <= 'F')
ea430986 1252 return c - 'A' + 10;
4fe88d28
LP
1253
1254 return -1;
1255}
1256
1257char octchar(int x) {
1258 return '0' + (x & 7);
1259}
1260
1261int unoctchar(char c) {
1262
1263 if (c >= '0' && c <= '7')
1264 return c - '0';
1265
1266 return -1;
1267}
1268
5af98f82
LP
1269char decchar(int x) {
1270 return '0' + (x % 10);
1271}
1272
1273int undecchar(char c) {
1274
1275 if (c >= '0' && c <= '9')
1276 return c - '0';
1277
1278 return -1;
1279}
1280
4fe88d28
LP
1281char *cescape(const char *s) {
1282 char *r, *t;
1283 const char *f;
1284
1285 assert(s);
1286
1287 /* Does C style string escaping. */
1288
1289 if (!(r = new(char, strlen(s)*4 + 1)))
1290 return NULL;
1291
1292 for (f = s, t = r; *f; f++)
1293
1294 switch (*f) {
1295
1296 case '\a':
1297 *(t++) = '\\';
1298 *(t++) = 'a';
1299 break;
1300 case '\b':
1301 *(t++) = '\\';
1302 *(t++) = 'b';
1303 break;
1304 case '\f':
1305 *(t++) = '\\';
1306 *(t++) = 'f';
1307 break;
1308 case '\n':
1309 *(t++) = '\\';
1310 *(t++) = 'n';
1311 break;
1312 case '\r':
1313 *(t++) = '\\';
1314 *(t++) = 'r';
1315 break;
1316 case '\t':
1317 *(t++) = '\\';
1318 *(t++) = 't';
1319 break;
1320 case '\v':
1321 *(t++) = '\\';
1322 *(t++) = 'v';
1323 break;
1324 case '\\':
1325 *(t++) = '\\';
1326 *(t++) = '\\';
1327 break;
1328 case '"':
1329 *(t++) = '\\';
1330 *(t++) = '"';
1331 break;
1332 case '\'':
1333 *(t++) = '\\';
1334 *(t++) = '\'';
1335 break;
1336
1337 default:
1338 /* For special chars we prefer octal over
1339 * hexadecimal encoding, simply because glib's
1340 * g_strescape() does the same */
1341 if ((*f < ' ') || (*f >= 127)) {
1342 *(t++) = '\\';
1343 *(t++) = octchar((unsigned char) *f >> 6);
1344 *(t++) = octchar((unsigned char) *f >> 3);
1345 *(t++) = octchar((unsigned char) *f);
1346 } else
1347 *(t++) = *f;
1348 break;
1349 }
1350
1351 *t = 0;
1352
1353 return r;
1354}
1355
6febfd0d 1356char *cunescape_length(const char *s, size_t length) {
4fe88d28
LP
1357 char *r, *t;
1358 const char *f;
1359
1360 assert(s);
1361
1362 /* Undoes C style string escaping */
1363
6febfd0d 1364 if (!(r = new(char, length+1)))
4fe88d28
LP
1365 return r;
1366
6febfd0d 1367 for (f = s, t = r; f < s + length; f++) {
4fe88d28
LP
1368
1369 if (*f != '\\') {
1370 *(t++) = *f;
1371 continue;
1372 }
1373
1374 f++;
1375
1376 switch (*f) {
1377
1378 case 'a':
1379 *(t++) = '\a';
1380 break;
1381 case 'b':
1382 *(t++) = '\b';
1383 break;
1384 case 'f':
1385 *(t++) = '\f';
1386 break;
1387 case 'n':
1388 *(t++) = '\n';
1389 break;
1390 case 'r':
1391 *(t++) = '\r';
1392 break;
1393 case 't':
1394 *(t++) = '\t';
1395 break;
1396 case 'v':
1397 *(t++) = '\v';
1398 break;
1399 case '\\':
1400 *(t++) = '\\';
1401 break;
1402 case '"':
1403 *(t++) = '"';
1404 break;
1405 case '\'':
1406 *(t++) = '\'';
1407 break;
1408
e167fb86
LP
1409 case 's':
1410 /* This is an extension of the XDG syntax files */
1411 *(t++) = ' ';
1412 break;
1413
4fe88d28
LP
1414 case 'x': {
1415 /* hexadecimal encoding */
1416 int a, b;
1417
1418 if ((a = unhexchar(f[1])) < 0 ||
1419 (b = unhexchar(f[2])) < 0) {
1420 /* Invalid escape code, let's take it literal then */
1421 *(t++) = '\\';
1422 *(t++) = 'x';
1423 } else {
1424 *(t++) = (char) ((a << 4) | b);
1425 f += 2;
1426 }
1427
1428 break;
1429 }
1430
1431 case '0':
1432 case '1':
1433 case '2':
1434 case '3':
1435 case '4':
1436 case '5':
1437 case '6':
1438 case '7': {
1439 /* octal encoding */
1440 int a, b, c;
1441
1442 if ((a = unoctchar(f[0])) < 0 ||
1443 (b = unoctchar(f[1])) < 0 ||
1444 (c = unoctchar(f[2])) < 0) {
1445 /* Invalid escape code, let's take it literal then */
1446 *(t++) = '\\';
1447 *(t++) = f[0];
1448 } else {
1449 *(t++) = (char) ((a << 6) | (b << 3) | c);
1450 f += 2;
1451 }
1452
1453 break;
1454 }
1455
1456 case 0:
1457 /* premature end of string.*/
1458 *(t++) = '\\';
1459 goto finish;
1460
1461 default:
1462 /* Invalid escape code, let's take it literal then */
1463 *(t++) = '\\';
f3d4cc01 1464 *(t++) = *f;
4fe88d28
LP
1465 break;
1466 }
1467 }
1468
1469finish:
1470 *t = 0;
1471 return r;
1472}
1473
6febfd0d
LP
1474char *cunescape(const char *s) {
1475 return cunescape_length(s, strlen(s));
1476}
4fe88d28
LP
1477
1478char *xescape(const char *s, const char *bad) {
1479 char *r, *t;
1480 const char *f;
1481
1482 /* Escapes all chars in bad, in addition to \ and all special
1483 * chars, in \xFF style escaping. May be reversed with
1484 * cunescape. */
1485
1486 if (!(r = new(char, strlen(s)*4+1)))
1487 return NULL;
1488
1489 for (f = s, t = r; *f; f++) {
1490
b866264a
LP
1491 if ((*f < ' ') || (*f >= 127) ||
1492 (*f == '\\') || strchr(bad, *f)) {
4fe88d28
LP
1493 *(t++) = '\\';
1494 *(t++) = 'x';
1495 *(t++) = hexchar(*f >> 4);
1496 *(t++) = hexchar(*f);
1497 } else
1498 *(t++) = *f;
1499 }
1500
1501 *t = 0;
1502
1503 return r;
1504}
1505
ea430986 1506char *bus_path_escape(const char *s) {
ea430986
LP
1507 char *r, *t;
1508 const char *f;
1509
47be870b
LP
1510 assert(s);
1511
ea430986
LP
1512 /* Escapes all chars that D-Bus' object path cannot deal
1513 * with. Can be reverse with bus_path_unescape() */
1514
1515 if (!(r = new(char, strlen(s)*3+1)))
1516 return NULL;
1517
1518 for (f = s, t = r; *f; f++) {
1519
1520 if (!(*f >= 'A' && *f <= 'Z') &&
1521 !(*f >= 'a' && *f <= 'z') &&
1522 !(*f >= '0' && *f <= '9')) {
1523 *(t++) = '_';
1524 *(t++) = hexchar(*f >> 4);
1525 *(t++) = hexchar(*f);
1526 } else
1527 *(t++) = *f;
1528 }
1529
1530 *t = 0;
1531
1532 return r;
1533}
1534
9e2f7c11 1535char *bus_path_unescape(const char *f) {
ea430986 1536 char *r, *t;
ea430986 1537
9e2f7c11 1538 assert(f);
47be870b 1539
9e2f7c11 1540 if (!(r = strdup(f)))
ea430986
LP
1541 return NULL;
1542
9e2f7c11 1543 for (t = r; *f; f++) {
ea430986
LP
1544
1545 if (*f == '_') {
1546 int a, b;
1547
1548 if ((a = unhexchar(f[1])) < 0 ||
1549 (b = unhexchar(f[2])) < 0) {
1550 /* Invalid escape code, let's take it literal then */
1551 *(t++) = '_';
1552 } else {
1553 *(t++) = (char) ((a << 4) | b);
1554 f += 2;
1555 }
1556 } else
1557 *(t++) = *f;
1558 }
1559
1560 *t = 0;
1561
1562 return r;
1563}
1564
4fe88d28
LP
1565char *path_kill_slashes(char *path) {
1566 char *f, *t;
1567 bool slash = false;
1568
1569 /* Removes redundant inner and trailing slashes. Modifies the
1570 * passed string in-place.
1571 *
1572 * ///foo///bar/ becomes /foo/bar
1573 */
1574
1575 for (f = path, t = path; *f; f++) {
1576
1577 if (*f == '/') {
1578 slash = true;
1579 continue;
1580 }
1581
1582 if (slash) {
1583 slash = false;
1584 *(t++) = '/';
1585 }
1586
1587 *(t++) = *f;
1588 }
1589
1590 /* Special rule, if we are talking of the root directory, a
1591 trailing slash is good */
1592
1593 if (t == path && slash)
1594 *(t++) = '/';
1595
1596 *t = 0;
1597 return path;
1598}
1599
1600bool path_startswith(const char *path, const char *prefix) {
1601 assert(path);
1602 assert(prefix);
1603
1604 if ((path[0] == '/') != (prefix[0] == '/'))
1605 return false;
1606
1607 for (;;) {
1608 size_t a, b;
1609
1610 path += strspn(path, "/");
1611 prefix += strspn(prefix, "/");
1612
1613 if (*prefix == 0)
1614 return true;
1615
1616 if (*path == 0)
1617 return false;
1618
1619 a = strcspn(path, "/");
1620 b = strcspn(prefix, "/");
1621
1622 if (a != b)
1623 return false;
1624
1625 if (memcmp(path, prefix, a) != 0)
1626 return false;
1627
1628 path += a;
1629 prefix += b;
1630 }
1631}
1632
15ae422b
LP
1633bool path_equal(const char *a, const char *b) {
1634 assert(a);
1635 assert(b);
1636
1637 if ((a[0] == '/') != (b[0] == '/'))
1638 return false;
1639
1640 for (;;) {
1641 size_t j, k;
1642
1643 a += strspn(a, "/");
1644 b += strspn(b, "/");
1645
1646 if (*a == 0 && *b == 0)
1647 return true;
1648
1649 if (*a == 0 || *b == 0)
1650 return false;
1651
1652 j = strcspn(a, "/");
1653 k = strcspn(b, "/");
1654
1655 if (j != k)
1656 return false;
1657
1658 if (memcmp(a, b, j) != 0)
1659 return false;
1660
1661 a += j;
1662 b += k;
1663 }
1664}
1665
67d51650 1666char *ascii_strlower(char *t) {
4fe88d28
LP
1667 char *p;
1668
67d51650 1669 assert(t);
4fe88d28 1670
67d51650 1671 for (p = t; *p; p++)
4fe88d28
LP
1672 if (*p >= 'A' && *p <= 'Z')
1673 *p = *p - 'A' + 'a';
1674
67d51650 1675 return t;
4fe88d28 1676}
1dccbe19 1677
c85dc17b
LP
1678bool ignore_file(const char *filename) {
1679 assert(filename);
1680
1681 return
1682 filename[0] == '.' ||
6c78be3c 1683 streq(filename, "lost+found") ||
e472d476
LP
1684 streq(filename, "aquota.user") ||
1685 streq(filename, "aquota.group") ||
c85dc17b
LP
1686 endswith(filename, "~") ||
1687 endswith(filename, ".rpmnew") ||
1688 endswith(filename, ".rpmsave") ||
1689 endswith(filename, ".rpmorig") ||
1690 endswith(filename, ".dpkg-old") ||
1691 endswith(filename, ".dpkg-new") ||
1692 endswith(filename, ".swp");
1693}
1694
3a0ecb08
LP
1695int fd_nonblock(int fd, bool nonblock) {
1696 int flags;
1697
1698 assert(fd >= 0);
1699
1700 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1701 return -errno;
1702
1703 if (nonblock)
1704 flags |= O_NONBLOCK;
1705 else
1706 flags &= ~O_NONBLOCK;
1707
1708 if (fcntl(fd, F_SETFL, flags) < 0)
1709 return -errno;
1710
1711 return 0;
1712}
1713
1714int fd_cloexec(int fd, bool cloexec) {
1715 int flags;
1716
1717 assert(fd >= 0);
1718
1719 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1720 return -errno;
1721
1722 if (cloexec)
1723 flags |= FD_CLOEXEC;
1724 else
1725 flags &= ~FD_CLOEXEC;
1726
1727 if (fcntl(fd, F_SETFD, flags) < 0)
1728 return -errno;
1729
1730 return 0;
1731}
1732
a0d40ac5
LP
1733int close_all_fds(const int except[], unsigned n_except) {
1734 DIR *d;
1735 struct dirent *de;
1736 int r = 0;
1737
1738 if (!(d = opendir("/proc/self/fd")))
1739 return -errno;
1740
1741 while ((de = readdir(d))) {
a7610064 1742 int fd = -1;
a0d40ac5 1743
a16e1123 1744 if (ignore_file(de->d_name))
a0d40ac5
LP
1745 continue;
1746
1747 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1748 goto finish;
1749
1750 if (fd < 3)
1751 continue;
1752
1753 if (fd == dirfd(d))
1754 continue;
1755
1756 if (except) {
1757 bool found;
1758 unsigned i;
1759
1760 found = false;
1761 for (i = 0; i < n_except; i++)
1762 if (except[i] == fd) {
1763 found = true;
1764 break;
1765 }
1766
1767 if (found)
1768 continue;
1769 }
1770
2f357920
LP
1771 if ((r = close_nointr(fd)) < 0) {
1772 /* Valgrind has its own FD and doesn't want to have it closed */
1773 if (errno != EBADF)
1774 goto finish;
1775 }
a0d40ac5
LP
1776 }
1777
2f357920
LP
1778 r = 0;
1779
a0d40ac5
LP
1780finish:
1781 closedir(d);
1782 return r;
1783}
1784
db12775d
LP
1785bool chars_intersect(const char *a, const char *b) {
1786 const char *p;
1787
1788 /* Returns true if any of the chars in a are in b. */
1789 for (p = a; *p; p++)
1790 if (strchr(b, *p))
1791 return true;
1792
1793 return false;
1794}
1795
8b6c7120
LP
1796char *format_timestamp(char *buf, size_t l, usec_t t) {
1797 struct tm tm;
1798 time_t sec;
1799
1800 assert(buf);
1801 assert(l > 0);
1802
1803 if (t <= 0)
1804 return NULL;
1805
f872ec33 1806 sec = (time_t) (t / USEC_PER_SEC);
8b6c7120
LP
1807
1808 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1809 return NULL;
1810
1811 return buf;
1812}
1813
584be568
LP
1814char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1815 usec_t n, d;
1816
1817 n = now(CLOCK_REALTIME);
1818
1819 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1820 return NULL;
1821
1822 d = n - t;
1823
1824 if (d >= USEC_PER_YEAR)
1825 snprintf(buf, l, "%llu years and %llu months ago",
1826 (unsigned long long) (d / USEC_PER_YEAR),
1827 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1828 else if (d >= USEC_PER_MONTH)
1829 snprintf(buf, l, "%llu months and %llu days ago",
1830 (unsigned long long) (d / USEC_PER_MONTH),
1831 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1832 else if (d >= USEC_PER_WEEK)
1833 snprintf(buf, l, "%llu weeks and %llu days ago",
1834 (unsigned long long) (d / USEC_PER_WEEK),
1835 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1836 else if (d >= 2*USEC_PER_DAY)
1837 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1838 else if (d >= 25*USEC_PER_HOUR)
1839 snprintf(buf, l, "1 day and %lluh ago",
1840 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1841 else if (d >= 6*USEC_PER_HOUR)
1842 snprintf(buf, l, "%lluh ago",
1843 (unsigned long long) (d / USEC_PER_HOUR));
1844 else if (d >= USEC_PER_HOUR)
1845 snprintf(buf, l, "%lluh %llumin ago",
1846 (unsigned long long) (d / USEC_PER_HOUR),
1847 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1848 else if (d >= 5*USEC_PER_MINUTE)
1849 snprintf(buf, l, "%llumin ago",
1850 (unsigned long long) (d / USEC_PER_MINUTE));
1851 else if (d >= USEC_PER_MINUTE)
1852 snprintf(buf, l, "%llumin %llus ago",
1853 (unsigned long long) (d / USEC_PER_MINUTE),
1854 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1855 else if (d >= USEC_PER_SEC)
1856 snprintf(buf, l, "%llus ago",
1857 (unsigned long long) (d / USEC_PER_SEC));
1858 else if (d >= USEC_PER_MSEC)
1859 snprintf(buf, l, "%llums ago",
1860 (unsigned long long) (d / USEC_PER_MSEC));
1861 else if (d > 0)
1862 snprintf(buf, l, "%lluus ago",
1863 (unsigned long long) d);
1864 else
1865 snprintf(buf, l, "now");
1866
1867 buf[l-1] = 0;
1868 return buf;
1869}
1870
871d7de4
LP
1871char *format_timespan(char *buf, size_t l, usec_t t) {
1872 static const struct {
1873 const char *suffix;
1874 usec_t usec;
1875 } table[] = {
1876 { "w", USEC_PER_WEEK },
1877 { "d", USEC_PER_DAY },
1878 { "h", USEC_PER_HOUR },
1879 { "min", USEC_PER_MINUTE },
1880 { "s", USEC_PER_SEC },
1881 { "ms", USEC_PER_MSEC },
1882 { "us", 1 },
1883 };
1884
1885 unsigned i;
1886 char *p = buf;
1887
1888 assert(buf);
1889 assert(l > 0);
1890
1891 if (t == (usec_t) -1)
1892 return NULL;
1893
4502d22c
LP
1894 if (t == 0) {
1895 snprintf(p, l, "0");
1896 p[l-1] = 0;
1897 return p;
1898 }
1899
871d7de4
LP
1900 /* The result of this function can be parsed with parse_usec */
1901
1902 for (i = 0; i < ELEMENTSOF(table); i++) {
1903 int k;
1904 size_t n;
1905
1906 if (t < table[i].usec)
1907 continue;
1908
1909 if (l <= 1)
1910 break;
1911
1912 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1913 n = MIN((size_t) k, l);
1914
1915 l -= n;
1916 p += n;
1917
1918 t %= table[i].usec;
1919 }
1920
1921 *p = 0;
1922
1923 return buf;
1924}
1925
42856c10
LP
1926bool fstype_is_network(const char *fstype) {
1927 static const char * const table[] = {
1928 "cifs",
1929 "smbfs",
1930 "ncpfs",
1931 "nfs",
ca139f94
LP
1932 "nfs4",
1933 "gfs",
1934 "gfs2"
42856c10
LP
1935 };
1936
1937 unsigned i;
1938
1939 for (i = 0; i < ELEMENTSOF(table); i++)
1940 if (streq(table[i], fstype))
1941 return true;
1942
1943 return false;
1944}
1945
601f6a1e
LP
1946int chvt(int vt) {
1947 int fd, r = 0;
1948
1949 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1950 return -errno;
1951
1952 if (vt < 0) {
1953 int tiocl[2] = {
1954 TIOCL_GETKMSGREDIRECT,
1955 0
1956 };
1957
1958 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1959 return -errno;
1960
1961 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1962 }
1963
1964 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1965 r = -errno;
1966
a16e1123 1967 close_nointr_nofail(r);
601f6a1e
LP
1968 return r;
1969}
1970
80876c20
LP
1971int read_one_char(FILE *f, char *ret, bool *need_nl) {
1972 struct termios old_termios, new_termios;
1973 char c;
1974 char line[1024];
1975
1976 assert(f);
1977 assert(ret);
1978
1979 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1980 new_termios = old_termios;
1981
1982 new_termios.c_lflag &= ~ICANON;
1983 new_termios.c_cc[VMIN] = 1;
1984 new_termios.c_cc[VTIME] = 0;
1985
1986 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1987 size_t k;
1988
1989 k = fread(&c, 1, 1, f);
1990
1991 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1992
1993 if (k <= 0)
1994 return -EIO;
1995
1996 if (need_nl)
1997 *need_nl = c != '\n';
1998
1999 *ret = c;
2000 return 0;
2001 }
2002 }
2003
2004 if (!(fgets(line, sizeof(line), f)))
2005 return -EIO;
2006
2007 truncate_nl(line);
2008
2009 if (strlen(line) != 1)
2010 return -EBADMSG;
2011
2012 if (need_nl)
2013 *need_nl = false;
2014
2015 *ret = line[0];
2016 return 0;
2017}
2018
2019int ask(char *ret, const char *replies, const char *text, ...) {
1b39d4b9
LP
2020 bool on_tty;
2021
80876c20
LP
2022 assert(ret);
2023 assert(replies);
2024 assert(text);
2025
1b39d4b9
LP
2026 on_tty = isatty(STDOUT_FILENO);
2027
80876c20
LP
2028 for (;;) {
2029 va_list ap;
2030 char c;
2031 int r;
2032 bool need_nl = true;
2033
1b39d4b9
LP
2034 if (on_tty)
2035 fputs("\x1B[1m", stdout);
b1b2dc0c 2036
80876c20
LP
2037 va_start(ap, text);
2038 vprintf(text, ap);
2039 va_end(ap);
2040
1b39d4b9
LP
2041 if (on_tty)
2042 fputs("\x1B[0m", stdout);
b1b2dc0c 2043
80876c20
LP
2044 fflush(stdout);
2045
2046 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2047
2048 if (r == -EBADMSG) {
2049 puts("Bad input, please try again.");
2050 continue;
2051 }
2052
2053 putchar('\n');
2054 return r;
2055 }
2056
2057 if (need_nl)
2058 putchar('\n');
2059
2060 if (strchr(replies, c)) {
2061 *ret = c;
2062 return 0;
2063 }
2064
2065 puts("Read unexpected character, please try again.");
2066 }
2067}
2068
2069int reset_terminal(int fd) {
2070 struct termios termios;
2071 int r = 0;
3fe5e5d4
LP
2072 long arg;
2073
2074 /* Set terminal to some sane defaults */
80876c20
LP
2075
2076 assert(fd >= 0);
2077
eed1d0e3
LP
2078 /* We leave locked terminal attributes untouched, so that
2079 * Plymouth may set whatever it wants to set, and we don't
2080 * interfere with that. */
3fe5e5d4
LP
2081
2082 /* Disable exclusive mode, just in case */
2083 ioctl(fd, TIOCNXCL);
2084
2085 /* Enable console unicode mode */
2086 arg = K_UNICODE;
2087 ioctl(fd, KDSKBMODE, &arg);
80876c20
LP
2088
2089 if (tcgetattr(fd, &termios) < 0) {
2090 r = -errno;
2091 goto finish;
2092 }
2093
aaf694ca
LP
2094 /* We only reset the stuff that matters to the software. How
2095 * hardware is set up we don't touch assuming that somebody
2096 * else will do that for us */
2097
2098 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
80876c20
LP
2099 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2100 termios.c_oflag |= ONLCR;
2101 termios.c_cflag |= CREAD;
2102 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2103
2104 termios.c_cc[VINTR] = 03; /* ^C */
2105 termios.c_cc[VQUIT] = 034; /* ^\ */
2106 termios.c_cc[VERASE] = 0177;
2107 termios.c_cc[VKILL] = 025; /* ^X */
2108 termios.c_cc[VEOF] = 04; /* ^D */
2109 termios.c_cc[VSTART] = 021; /* ^Q */
2110 termios.c_cc[VSTOP] = 023; /* ^S */
2111 termios.c_cc[VSUSP] = 032; /* ^Z */
2112 termios.c_cc[VLNEXT] = 026; /* ^V */
2113 termios.c_cc[VWERASE] = 027; /* ^W */
2114 termios.c_cc[VREPRINT] = 022; /* ^R */
aaf694ca
LP
2115 termios.c_cc[VEOL] = 0;
2116 termios.c_cc[VEOL2] = 0;
80876c20
LP
2117
2118 termios.c_cc[VTIME] = 0;
2119 termios.c_cc[VMIN] = 1;
2120
2121 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2122 r = -errno;
2123
2124finish:
2125 /* Just in case, flush all crap out */
2126 tcflush(fd, TCIOFLUSH);
2127
2128 return r;
2129}
2130
2131int open_terminal(const char *name, int mode) {
2132 int fd, r;
2133
2134 if ((fd = open(name, mode)) < 0)
2135 return -errno;
2136
2137 if ((r = isatty(fd)) < 0) {
2138 close_nointr_nofail(fd);
2139 return -errno;
2140 }
2141
2142 if (!r) {
2143 close_nointr_nofail(fd);
2144 return -ENOTTY;
2145 }
2146
2147 return fd;
2148}
2149
2150int flush_fd(int fd) {
2151 struct pollfd pollfd;
2152
2153 zero(pollfd);
2154 pollfd.fd = fd;
2155 pollfd.events = POLLIN;
2156
2157 for (;;) {
2158 char buf[1024];
2159 ssize_t l;
2160 int r;
2161
2162 if ((r = poll(&pollfd, 1, 0)) < 0) {
2163
2164 if (errno == EINTR)
2165 continue;
2166
2167 return -errno;
2168 }
2169
2170 if (r == 0)
2171 return 0;
2172
2173 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2174
2175 if (errno == EINTR)
2176 continue;
2177
2178 if (errno == EAGAIN)
2179 return 0;
2180
2181 return -errno;
2182 }
2183
2184 if (l <= 0)
2185 return 0;
2186 }
2187}
2188
21de3988 2189int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
bab45044 2190 int fd = -1, notify = -1, r, wd = -1;
80876c20
LP
2191
2192 assert(name);
2193
2194 /* We use inotify to be notified when the tty is closed. We
2195 * create the watch before checking if we can actually acquire
2196 * it, so that we don't lose any event.
2197 *
2198 * Note: strictly speaking this actually watches for the
2199 * device being closed, it does *not* really watch whether a
2200 * tty loses its controlling process. However, unless some
2201 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2202 * its tty otherwise this will not become a problem. As long
2203 * as the administrator makes sure not configure any service
2204 * on the same tty as an untrusted user this should not be a
2205 * problem. (Which he probably should not do anyway.) */
2206
2207 if (!fail && !force) {
2208 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2209 r = -errno;
2210 goto fail;
2211 }
2212
2213 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2214 r = -errno;
2215 goto fail;
2216 }
2217 }
2218
2219 for (;;) {
e3d1855b
LP
2220 if (notify >= 0)
2221 if ((r = flush_fd(notify)) < 0)
2222 goto fail;
80876c20
LP
2223
2224 /* We pass here O_NOCTTY only so that we can check the return
2225 * value TIOCSCTTY and have a reliable way to figure out if we
2226 * successfully became the controlling process of the tty */
2227 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2228 return -errno;
2229
2230 /* First, try to get the tty */
21de3988
LP
2231 r = ioctl(fd, TIOCSCTTY, force);
2232
2233 /* Sometimes it makes sense to ignore TIOCSCTTY
2234 * returning EPERM, i.e. when very likely we already
2235 * are have this controlling terminal. */
2236 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2237 r = 0;
2238
2239 if (r < 0 && (force || fail || errno != EPERM)) {
80876c20
LP
2240 r = -errno;
2241 goto fail;
2242 }
2243
2244 if (r >= 0)
2245 break;
2246
2247 assert(!fail);
2248 assert(!force);
2249 assert(notify >= 0);
2250
2251 for (;;) {
f601daa7 2252 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
80876c20 2253 ssize_t l;
f601daa7 2254 struct inotify_event *e;
80876c20 2255
f601daa7 2256 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
80876c20 2257
f601daa7
LP
2258 if (errno == EINTR)
2259 continue;
2260
2261 r = -errno;
2262 goto fail;
2263 }
2264
2265 e = (struct inotify_event*) inotify_buffer;
80876c20 2266
f601daa7
LP
2267 while (l > 0) {
2268 size_t step;
80876c20 2269
f601daa7 2270 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
80876c20 2271 r = -EIO;
f601daa7
LP
2272 goto fail;
2273 }
80876c20 2274
f601daa7
LP
2275 step = sizeof(struct inotify_event) + e->len;
2276 assert(step <= (size_t) l);
80876c20 2277
f601daa7
LP
2278 e = (struct inotify_event*) ((uint8_t*) e + step);
2279 l -= step;
80876c20
LP
2280 }
2281
2282 break;
2283 }
2284
2285 /* We close the tty fd here since if the old session
2286 * ended our handle will be dead. It's important that
2287 * we do this after sleeping, so that we don't enter
2288 * an endless loop. */
2289 close_nointr_nofail(fd);
2290 }
2291
2292 if (notify >= 0)
a16e1123 2293 close_nointr_nofail(notify);
80876c20
LP
2294
2295 if ((r = reset_terminal(fd)) < 0)
2296 log_warning("Failed to reset terminal: %s", strerror(-r));
2297
2298 return fd;
2299
2300fail:
2301 if (fd >= 0)
a16e1123 2302 close_nointr_nofail(fd);
80876c20
LP
2303
2304 if (notify >= 0)
a16e1123 2305 close_nointr_nofail(notify);
80876c20
LP
2306
2307 return r;
2308}
2309
2310int release_terminal(void) {
2311 int r = 0, fd;
57cd2192 2312 struct sigaction sa_old, sa_new;
80876c20 2313
57cd2192 2314 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
80876c20
LP
2315 return -errno;
2316
57cd2192
LP
2317 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2318 * by our own TIOCNOTTY */
2319
2320 zero(sa_new);
2321 sa_new.sa_handler = SIG_IGN;
2322 sa_new.sa_flags = SA_RESTART;
2323 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2324
80876c20
LP
2325 if (ioctl(fd, TIOCNOTTY) < 0)
2326 r = -errno;
2327
57cd2192
LP
2328 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2329
80876c20
LP
2330 close_nointr_nofail(fd);
2331 return r;
2332}
2333
9a34ec5f
LP
2334int sigaction_many(const struct sigaction *sa, ...) {
2335 va_list ap;
2336 int r = 0, sig;
2337
2338 va_start(ap, sa);
2339 while ((sig = va_arg(ap, int)) > 0)
2340 if (sigaction(sig, sa, NULL) < 0)
2341 r = -errno;
2342 va_end(ap);
2343
2344 return r;
2345}
2346
2347int ignore_signals(int sig, ...) {
a337c6fc 2348 struct sigaction sa;
9a34ec5f
LP
2349 va_list ap;
2350 int r = 0;
a337c6fc
LP
2351
2352 zero(sa);
2353 sa.sa_handler = SIG_IGN;
2354 sa.sa_flags = SA_RESTART;
2355
9a34ec5f
LP
2356 if (sigaction(sig, &sa, NULL) < 0)
2357 r = -errno;
2358
2359 va_start(ap, sig);
2360 while ((sig = va_arg(ap, int)) > 0)
2361 if (sigaction(sig, &sa, NULL) < 0)
2362 r = -errno;
2363 va_end(ap);
2364
2365 return r;
2366}
2367
2368int default_signals(int sig, ...) {
2369 struct sigaction sa;
2370 va_list ap;
2371 int r = 0;
2372
2373 zero(sa);
2374 sa.sa_handler = SIG_DFL;
2375 sa.sa_flags = SA_RESTART;
2376
2377 if (sigaction(sig, &sa, NULL) < 0)
2378 r = -errno;
2379
2380 va_start(ap, sig);
2381 while ((sig = va_arg(ap, int)) > 0)
2382 if (sigaction(sig, &sa, NULL) < 0)
2383 r = -errno;
2384 va_end(ap);
2385
2386 return r;
a337c6fc
LP
2387}
2388
8d567588
LP
2389int close_pipe(int p[]) {
2390 int a = 0, b = 0;
2391
2392 assert(p);
2393
2394 if (p[0] >= 0) {
2395 a = close_nointr(p[0]);
2396 p[0] = -1;
2397 }
2398
2399 if (p[1] >= 0) {
2400 b = close_nointr(p[1]);
2401 p[1] = -1;
2402 }
2403
2404 return a < 0 ? a : b;
2405}
2406
eb22ac37 2407ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
8d567588
LP
2408 uint8_t *p;
2409 ssize_t n = 0;
2410
2411 assert(fd >= 0);
2412 assert(buf);
2413
2414 p = buf;
2415
2416 while (nbytes > 0) {
2417 ssize_t k;
2418
2419 if ((k = read(fd, p, nbytes)) <= 0) {
2420
eb22ac37 2421 if (k < 0 && errno == EINTR)
8d567588
LP
2422 continue;
2423
eb22ac37 2424 if (k < 0 && errno == EAGAIN && do_poll) {
8d567588
LP
2425 struct pollfd pollfd;
2426
2427 zero(pollfd);
2428 pollfd.fd = fd;
2429 pollfd.events = POLLIN;
2430
2431 if (poll(&pollfd, 1, -1) < 0) {
2432 if (errno == EINTR)
2433 continue;
2434
2435 return n > 0 ? n : -errno;
2436 }
2437
2438 if (pollfd.revents != POLLIN)
2439 return n > 0 ? n : -EIO;
2440
2441 continue;
2442 }
2443
2444 return n > 0 ? n : (k < 0 ? -errno : 0);
2445 }
2446
2447 p += k;
2448 nbytes -= k;
2449 n += k;
2450 }
2451
2452 return n;
2453}
2454
eb22ac37
LP
2455ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2456 const uint8_t *p;
2457 ssize_t n = 0;
2458
2459 assert(fd >= 0);
2460 assert(buf);
2461
2462 p = buf;
2463
2464 while (nbytes > 0) {
2465 ssize_t k;
2466
2467 if ((k = write(fd, p, nbytes)) <= 0) {
2468
2469 if (k < 0 && errno == EINTR)
2470 continue;
2471
2472 if (k < 0 && errno == EAGAIN && do_poll) {
2473 struct pollfd pollfd;
2474
2475 zero(pollfd);
2476 pollfd.fd = fd;
2477 pollfd.events = POLLOUT;
2478
2479 if (poll(&pollfd, 1, -1) < 0) {
2480 if (errno == EINTR)
2481 continue;
2482
2483 return n > 0 ? n : -errno;
2484 }
2485
2486 if (pollfd.revents != POLLOUT)
2487 return n > 0 ? n : -EIO;
2488
2489 continue;
2490 }
2491
2492 return n > 0 ? n : (k < 0 ? -errno : 0);
2493 }
2494
2495 p += k;
2496 nbytes -= k;
2497 n += k;
2498 }
2499
2500 return n;
2501}
2502
8d567588
LP
2503int path_is_mount_point(const char *t) {
2504 struct stat a, b;
35d2e7ec
LP
2505 char *parent;
2506 int r;
8d567588
LP
2507
2508 if (lstat(t, &a) < 0) {
8d567588
LP
2509 if (errno == ENOENT)
2510 return 0;
2511
2512 return -errno;
2513 }
2514
35d2e7ec
LP
2515 if ((r = parent_of_path(t, &parent)) < 0)
2516 return r;
8d567588 2517
35d2e7ec
LP
2518 r = lstat(parent, &b);
2519 free(parent);
8d567588 2520
35d2e7ec
LP
2521 if (r < 0)
2522 return -errno;
8d567588
LP
2523
2524 return a.st_dev != b.st_dev;
2525}
2526
24a6e4a4
LP
2527int parse_usec(const char *t, usec_t *usec) {
2528 static const struct {
2529 const char *suffix;
2530 usec_t usec;
2531 } table[] = {
2532 { "sec", USEC_PER_SEC },
2533 { "s", USEC_PER_SEC },
2534 { "min", USEC_PER_MINUTE },
2535 { "hr", USEC_PER_HOUR },
2536 { "h", USEC_PER_HOUR },
2537 { "d", USEC_PER_DAY },
2538 { "w", USEC_PER_WEEK },
2539 { "msec", USEC_PER_MSEC },
2540 { "ms", USEC_PER_MSEC },
2541 { "m", USEC_PER_MINUTE },
2542 { "usec", 1ULL },
2543 { "us", 1ULL },
2544 { "", USEC_PER_SEC },
2545 };
2546
2547 const char *p;
2548 usec_t r = 0;
2549
2550 assert(t);
2551 assert(usec);
2552
2553 p = t;
2554 do {
2555 long long l;
2556 char *e;
2557 unsigned i;
2558
2559 errno = 0;
2560 l = strtoll(p, &e, 10);
2561
2562 if (errno != 0)
2563 return -errno;
2564
2565 if (l < 0)
2566 return -ERANGE;
2567
2568 if (e == p)
2569 return -EINVAL;
2570
2571 e += strspn(e, WHITESPACE);
2572
2573 for (i = 0; i < ELEMENTSOF(table); i++)
2574 if (startswith(e, table[i].suffix)) {
2575 r += (usec_t) l * table[i].usec;
2576 p = e + strlen(table[i].suffix);
2577 break;
2578 }
2579
2580 if (i >= ELEMENTSOF(table))
2581 return -EINVAL;
2582
2583 } while (*p != 0);
2584
2585 *usec = r;
2586
2587 return 0;
2588}
2589
843d2643
LP
2590int make_stdio(int fd) {
2591 int r, s, t;
2592
2593 assert(fd >= 0);
2594
2595 r = dup2(fd, STDIN_FILENO);
2596 s = dup2(fd, STDOUT_FILENO);
2597 t = dup2(fd, STDERR_FILENO);
2598
2599 if (fd >= 3)
2600 close_nointr_nofail(fd);
2601
2602 if (r < 0 || s < 0 || t < 0)
2603 return -errno;
2604
2605 return 0;
2606}
2607
ade509ce
LP
2608int make_null_stdio(void) {
2609 int null_fd;
2610
2611 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2612 return -errno;
2613
2614 return make_stdio(null_fd);
2615}
2616
cb8a8f78
LP
2617bool is_clean_exit(int code, int status) {
2618
2619 if (code == CLD_EXITED)
2620 return status == 0;
2621
2622 /* If a daemon does not implement handlers for some of the
2623 * signals that's not considered an unclean shutdown */
2624 if (code == CLD_KILLED)
2625 return
2626 status == SIGHUP ||
2627 status == SIGINT ||
2628 status == SIGTERM ||
2629 status == SIGPIPE;
2630
2631 return false;
2632}
2633
d06dacd0
LP
2634bool is_clean_exit_lsb(int code, int status) {
2635
2636 if (is_clean_exit(code, status))
2637 return true;
2638
2639 return
2640 code == CLD_EXITED &&
2641 (status == EXIT_NOTINSTALLED || status == EXIT_NOTCONFIGURED);
2642}
2643
8407a5d0
LP
2644bool is_device_path(const char *path) {
2645
2646 /* Returns true on paths that refer to a device, either in
2647 * sysfs or in /dev */
2648
2649 return
2650 path_startswith(path, "/dev/") ||
2651 path_startswith(path, "/sys/");
2652}
2653
01f78473
LP
2654int dir_is_empty(const char *path) {
2655 DIR *d;
2656 int r;
2657 struct dirent buf, *de;
2658
2659 if (!(d = opendir(path)))
2660 return -errno;
2661
2662 for (;;) {
2663 if ((r = readdir_r(d, &buf, &de)) > 0) {
2664 r = -r;
2665 break;
2666 }
2667
2668 if (!de) {
2669 r = 1;
2670 break;
2671 }
2672
2673 if (!ignore_file(de->d_name)) {
2674 r = 0;
2675 break;
2676 }
2677 }
2678
2679 closedir(d);
2680 return r;
2681}
2682
d3782d60
LP
2683unsigned long long random_ull(void) {
2684 int fd;
2685 uint64_t ull;
2686 ssize_t r;
2687
2688 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2689 goto fallback;
2690
eb22ac37 2691 r = loop_read(fd, &ull, sizeof(ull), true);
d3782d60
LP
2692 close_nointr_nofail(fd);
2693
2694 if (r != sizeof(ull))
2695 goto fallback;
2696
2697 return ull;
2698
2699fallback:
2700 return random() * RAND_MAX + random();
2701}
2702
5b6319dc
LP
2703void rename_process(const char name[8]) {
2704 assert(name);
2705
2706 prctl(PR_SET_NAME, name);
2707
2708 /* This is a like a poor man's setproctitle(). The string
2709 * passed should fit in 7 chars (i.e. the length of
2710 * "systemd") */
2711
2712 if (program_invocation_name)
2713 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2714}
2715
7d793605
LP
2716void sigset_add_many(sigset_t *ss, ...) {
2717 va_list ap;
2718 int sig;
2719
2720 assert(ss);
2721
2722 va_start(ap, ss);
2723 while ((sig = va_arg(ap, int)) > 0)
2724 assert_se(sigaddset(ss, sig) == 0);
2725 va_end(ap);
2726}
2727
ef2f1067
LP
2728char* gethostname_malloc(void) {
2729 struct utsname u;
2730
2731 assert_se(uname(&u) >= 0);
2732
2733 if (u.nodename[0])
2734 return strdup(u.nodename);
2735
2736 return strdup(u.sysname);
2737}
2738
2739char* getlogname_malloc(void) {
2740 uid_t uid;
2741 long bufsize;
2742 char *buf, *name;
2743 struct passwd pwbuf, *pw = NULL;
2744 struct stat st;
2745
2746 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2747 uid = st.st_uid;
2748 else
2749 uid = getuid();
2750
2751 /* Shortcut things to avoid NSS lookups */
2752 if (uid == 0)
2753 return strdup("root");
2754
2755 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2756 bufsize = 4096;
2757
2758 if (!(buf = malloc(bufsize)))
2759 return NULL;
2760
2761 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2762 name = strdup(pw->pw_name);
2763 free(buf);
2764 return name;
2765 }
2766
2767 free(buf);
2768
2769 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2770 return NULL;
2771
2772 return name;
2773}
2774
8c6db833
LP
2775int getttyname_malloc(char **r) {
2776 char path[PATH_MAX], *p, *c;
618e02c7 2777 int k;
8c6db833
LP
2778
2779 assert(r);
ef2f1067 2780
618e02c7
LP
2781 if ((k = ttyname_r(STDIN_FILENO, path, sizeof(path))) != 0)
2782 return -k;
ef2f1067
LP
2783
2784 char_array_0(path);
2785
2786 p = path;
2787 if (startswith(path, "/dev/"))
2788 p += 5;
2789
8c6db833
LP
2790 if (!(c = strdup(p)))
2791 return -ENOMEM;
2792
2793 *r = c;
2794 return 0;
2795}
2796
2797static int rm_rf_children(int fd, bool only_dirs) {
2798 DIR *d;
2799 int ret = 0;
2800
2801 assert(fd >= 0);
2802
2803 /* This returns the first error we run into, but nevertheless
2804 * tries to go on */
2805
2806 if (!(d = fdopendir(fd))) {
2807 close_nointr_nofail(fd);
4c633005
LP
2808
2809 return errno == ENOENT ? 0 : -errno;
8c6db833
LP
2810 }
2811
2812 for (;;) {
2813 struct dirent buf, *de;
2814 bool is_dir;
2815 int r;
2816
2817 if ((r = readdir_r(d, &buf, &de)) != 0) {
2818 if (ret == 0)
2819 ret = -r;
2820 break;
2821 }
2822
2823 if (!de)
2824 break;
2825
2826 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2827 continue;
2828
2829 if (de->d_type == DT_UNKNOWN) {
2830 struct stat st;
2831
2832 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
4c633005 2833 if (ret == 0 && errno != ENOENT)
8c6db833
LP
2834 ret = -errno;
2835 continue;
2836 }
2837
2838 is_dir = S_ISDIR(st.st_mode);
2839 } else
2840 is_dir = de->d_type == DT_DIR;
2841
2842 if (is_dir) {
2843 int subdir_fd;
2844
2845 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
4c633005 2846 if (ret == 0 && errno != ENOENT)
8c6db833
LP
2847 ret = -errno;
2848 continue;
2849 }
2850
2851 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2852 if (ret == 0)
2853 ret = r;
2854 }
2855
2856 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
4c633005 2857 if (ret == 0 && errno != ENOENT)
8c6db833
LP
2858 ret = -errno;
2859 }
2860 } else if (!only_dirs) {
2861
2862 if (unlinkat(fd, de->d_name, 0) < 0) {
4c633005 2863 if (ret == 0 && errno != ENOENT)
8c6db833
LP
2864 ret = -errno;
2865 }
2866 }
2867 }
2868
2869 closedir(d);
2870
2871 return ret;
2872}
2873
2874int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2875 int fd;
2876 int r;
2877
2878 assert(path);
2879
2880 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2881
2882 if (errno != ENOTDIR)
2883 return -errno;
2884
2885 if (delete_root && !only_dirs)
2886 if (unlink(path) < 0)
2887 return -errno;
2888
2889 return 0;
2890 }
2891
2892 r = rm_rf_children(fd, only_dirs);
2893
2894 if (delete_root)
2895 if (rmdir(path) < 0) {
2896 if (r == 0)
2897 r = -errno;
2898 }
2899
2900 return r;
2901}
2902
2903int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2904 assert(path);
2905
2906 /* Under the assumption that we are running privileged we
2907 * first change the access mode and only then hand out
2908 * ownership to avoid a window where access is too open. */
2909
2910 if (chmod(path, mode) < 0)
2911 return -errno;
2912
2913 if (chown(path, uid, gid) < 0)
2914 return -errno;
2915
2916 return 0;
ef2f1067
LP
2917}
2918
82c121a4
LP
2919cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2920 cpu_set_t *r;
2921 unsigned n = 1024;
2922
2923 /* Allocates the cpuset in the right size */
2924
2925 for (;;) {
2926 if (!(r = CPU_ALLOC(n)))
2927 return NULL;
2928
2929 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2930 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2931
2932 if (ncpus)
2933 *ncpus = n;
2934
2935 return r;
2936 }
2937
2938 CPU_FREE(r);
2939
2940 if (errno != EINVAL)
2941 return NULL;
2942
2943 n *= 2;
2944 }
2945}
2946
9e58ff9c
LP
2947void status_vprintf(const char *format, va_list ap) {
2948 char *s = NULL;
2949 int fd = -1;
2950
2951 assert(format);
2952
2953 /* This independent of logging, as status messages are
2954 * optional and go exclusively to the console. */
2955
2956 if (vasprintf(&s, format, ap) < 0)
2957 goto finish;
2958
2959 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2960 goto finish;
2961
2962 write(fd, s, strlen(s));
2963
2964finish:
2965 free(s);
2966
2967 if (fd >= 0)
2968 close_nointr_nofail(fd);
2969}
2970
c846ff47
LP
2971void status_printf(const char *format, ...) {
2972 va_list ap;
2973
2974 assert(format);
2975
2976 va_start(ap, format);
2977 status_vprintf(format, ap);
2978 va_end(ap);
2979}
2980
2981void status_welcome(void) {
2982
2983#if defined(TARGET_FEDORA)
2984 char *r;
2985
2986 if (read_one_line_file("/etc/system-release", &r) < 0)
2987 return;
2988
2989 truncate_nl(r);
2990
2991 /* This tries to mimic the color magic the old Red Hat sysinit
2992 * script did. */
2993
2994 if (startswith(r, "Red Hat"))
2e54424d 2995 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r); /* Red for RHEL */
c846ff47 2996 else if (startswith(r, "Fedora"))
2e54424d 2997 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r); /* Blue for Fedora */
c846ff47 2998 else
9381a724 2999 status_printf("Welcome to \x1B[1m%s\x1B[0m!\n", r); /* Highlight for everything else */
c846ff47
LP
3000
3001 free(r);
3002
3003#elif defined(TARGET_SUSE)
3004 char *r;
3005
3006 if (read_one_line_file("/etc/SuSE-release", &r) < 0)
3007 return;
3008
3009 truncate_nl(r);
3010
2e54424d 3011 status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r); /* Green for SUSE */
0d37b36b 3012 free(r);
5a6225fd 3013
0d37b36b
GSB
3014#elif defined(TARGET_GENTOO)
3015 char *r;
3016
3017 if (read_one_line_file("/etc/gentoo-release", &r) < 0)
3018 return;
3019
3020 truncate_nl(r);
3021
3022 status_printf("Welcome to \x1B[1;34m%s\x1B[0m!\n", r); /* Light Blue for Gentoo */
3023
c846ff47 3024 free(r);
5a6225fd
SD
3025
3026#elif defined(TARGET_DEBIAN)
2e78aa99 3027 char *r;
5a6225fd 3028
2e78aa99
LP
3029 if (read_one_line_file("/etc/debian_version", &r) < 0)
3030 return;
5a6225fd 3031
2e78aa99 3032 truncate_nl(r);
5a6225fd 3033
2e78aa99 3034 status_printf("Welcome to Debian \x1B[1;31m%s\x1B[0m!\n", r); /* Light Red for Debian */
5a6225fd 3035
2e78aa99 3036 free(r);
274914f9
AE
3037#elif defined(TARGET_UBUNTU)
3038 char *desc = NULL;
3039 char *codename = NULL;
3040
3041 if (parse_env_file("/etc/lsb-release", NEWLINE,
3042 "DISTRIB_DESCRIPTION", &desc,
3043 "DISTRIB_CODENAME", &codename, NULL) < 0)
3044 return;
3045 if (desc && codename)
3046 /* Light Red for Ubuntu */
3047 status_printf("Welcome to \x1B[1;31m%s\x1B[0m (%s)\n",
3048 desc, codename);
3049 free(desc);
3050 free(codename);
17dbb83d 3051#elif defined(TARGET_ARCH)
2e78aa99 3052 status_printf("Welcome to \x1B[1;36mArch Linux\x1B[0m!\n"); /* Cyan for Arch */
c846ff47
LP
3053#else
3054#warning "You probably should add a welcome text logic here."
3055#endif
3056}
3057
fab56fc5
LP
3058char *replace_env(const char *format, char **env) {
3059 enum {
3060 WORD,
c24eb49e 3061 CURLY,
fab56fc5
LP
3062 VARIABLE
3063 } state = WORD;
3064
3065 const char *e, *word = format;
3066 char *r = NULL, *k;
3067
3068 assert(format);
3069
3070 for (e = format; *e; e ++) {
3071
3072 switch (state) {
3073
3074 case WORD:
3075 if (*e == '$')
c24eb49e 3076 state = CURLY;
fab56fc5
LP
3077 break;
3078
c24eb49e
LP
3079 case CURLY:
3080 if (*e == '{') {
fab56fc5
LP
3081 if (!(k = strnappend(r, word, e-word-1)))
3082 goto fail;
3083
3084 free(r);
3085 r = k;
3086
3087 word = e-1;
3088 state = VARIABLE;
3089
3090 } else if (*e == '$') {
3091 if (!(k = strnappend(r, word, e-word)))
3092 goto fail;
3093
3094 free(r);
3095 r = k;
3096
3097 word = e+1;
3098 state = WORD;
3099 } else
3100 state = WORD;
3101 break;
3102
3103 case VARIABLE:
c24eb49e 3104 if (*e == '}') {
b95cf362 3105 const char *t;
fab56fc5 3106
b95cf362
LP
3107 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3108 t = "";
fab56fc5 3109
b95cf362
LP
3110 if (!(k = strappend(r, t)))
3111 goto fail;
fab56fc5 3112
b95cf362
LP
3113 free(r);
3114 r = k;
fab56fc5 3115
b95cf362 3116 word = e+1;
fab56fc5
LP
3117 state = WORD;
3118 }
3119 break;
3120 }
3121 }
3122
3123 if (!(k = strnappend(r, word, e-word)))
3124 goto fail;
3125
3126 free(r);
3127 return k;
3128
3129fail:
3130 free(r);
3131 return NULL;
3132}
3133
3134char **replace_env_argv(char **argv, char **env) {
3135 char **r, **i;
c24eb49e
LP
3136 unsigned k = 0, l = 0;
3137
3138 l = strv_length(argv);
fab56fc5 3139
c24eb49e 3140 if (!(r = new(char*, l+1)))
fab56fc5
LP
3141 return NULL;
3142
3143 STRV_FOREACH(i, argv) {
c24eb49e
LP
3144
3145 /* If $FOO appears as single word, replace it by the split up variable */
b95cf362
LP
3146 if ((*i)[0] == '$' && (*i)[1] != '{') {
3147 char *e;
3148 char **w, **m;
3149 unsigned q;
c24eb49e 3150
b95cf362 3151 if ((e = strv_env_get(env, *i+1))) {
c24eb49e
LP
3152
3153 if (!(m = strv_split_quoted(e))) {
3154 r[k] = NULL;
3155 strv_free(r);
3156 return NULL;
3157 }
b95cf362
LP
3158 } else
3159 m = NULL;
c24eb49e 3160
b95cf362
LP
3161 q = strv_length(m);
3162 l = l + q - 1;
c24eb49e 3163
b95cf362
LP
3164 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3165 r[k] = NULL;
3166 strv_free(r);
3167 strv_free(m);
3168 return NULL;
3169 }
c24eb49e 3170
b95cf362
LP
3171 r = w;
3172 if (m) {
c24eb49e
LP
3173 memcpy(r + k, m, q * sizeof(char*));
3174 free(m);
c24eb49e 3175 }
b95cf362
LP
3176
3177 k += q;
3178 continue;
c24eb49e
LP
3179 }
3180
3181 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
fab56fc5
LP
3182 if (!(r[k++] = replace_env(*i, env))) {
3183 strv_free(r);
3184 return NULL;
3185 }
3186 }
3187
3188 r[k] = NULL;
3189 return r;
3190}
3191
fa776d8e
LP
3192int columns(void) {
3193 static __thread int parsed_columns = 0;
3194 const char *e;
3195
3196 if (parsed_columns > 0)
3197 return parsed_columns;
3198
3199 if ((e = getenv("COLUMNS")))
3200 parsed_columns = atoi(e);
3201
3202 if (parsed_columns <= 0) {
3203 struct winsize ws;
3204 zero(ws);
3205
9ed95f43 3206 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
fa776d8e
LP
3207 parsed_columns = ws.ws_col;
3208 }
3209
3210 if (parsed_columns <= 0)
3211 parsed_columns = 80;
3212
3213 return parsed_columns;
3214}
3215
b4f10a5e
LP
3216int running_in_chroot(void) {
3217 struct stat a, b;
3218
3219 zero(a);
3220 zero(b);
3221
3222 /* Only works as root */
3223
3224 if (stat("/proc/1/root", &a) < 0)
3225 return -errno;
3226
3227 if (stat("/", &b) < 0)
3228 return -errno;
3229
3230 return
3231 a.st_dev != b.st_dev ||
3232 a.st_ino != b.st_ino;
3233}
3234
8fe914ec
LP
3235char *ellipsize(const char *s, unsigned length, unsigned percent) {
3236 size_t l, x;
3237 char *r;
3238
3239 assert(s);
3240 assert(percent <= 100);
3241 assert(length >= 3);
3242
3243 l = strlen(s);
3244
3245 if (l <= 3 || l <= length)
3246 return strdup(s);
3247
3248 if (!(r = new0(char, length+1)))
3249 return r;
3250
3251 x = (length * percent) / 100;
3252
3253 if (x > length - 3)
3254 x = length - 3;
3255
3256 memcpy(r, s, x);
3257 r[x] = '.';
3258 r[x+1] = '.';
3259 r[x+2] = '.';
3260 memcpy(r + x + 3,
3261 s + l - (length - x - 3),
3262 length - x - 3);
3263
3264 return r;
3265}
3266
f6144808
LP
3267int touch(const char *path) {
3268 int fd;
3269
3270 assert(path);
3271
3272 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0666)) < 0)
3273 return -errno;
3274
3275 close_nointr_nofail(fd);
3276 return 0;
3277}
afea26ad 3278
97c4a07d 3279char *unquote(const char *s, const char* quotes) {
11ce3427
LP
3280 size_t l;
3281 assert(s);
3282
3283 if ((l = strlen(s)) < 2)
3284 return strdup(s);
3285
97c4a07d 3286 if (strchr(quotes, s[0]) && s[l-1] == s[0])
11ce3427
LP
3287 return strndup(s+1, l-2);
3288
3289 return strdup(s);
3290}
3291
8e12a6ae 3292int wait_for_terminate(pid_t pid, siginfo_t *status) {
2e78aa99
LP
3293 assert(pid >= 1);
3294 assert(status);
3295
3296 for (;;) {
8e12a6ae
LP
3297 zero(*status);
3298
3299 if (waitid(P_PID, pid, status, WEXITED) < 0) {
2e78aa99
LP
3300
3301 if (errno == EINTR)
3302 continue;
3303
3304 return -errno;
3305 }
3306
3307 return 0;
3308 }
3309}
3310
97c4a07d
LP
3311int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3312 int r;
3313 siginfo_t status;
3314
3315 assert(name);
3316 assert(pid > 1);
3317
3318 if ((r = wait_for_terminate(pid, &status)) < 0) {
3319 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3320 return r;
3321 }
3322
3323 if (status.si_code == CLD_EXITED) {
3324 if (status.si_status != 0) {
3325 log_warning("%s failed with error code %i.", name, status.si_status);
3326 return -EPROTO;
3327 }
3328
3329 log_debug("%s succeeded.", name);
3330 return 0;
3331
3332 } else if (status.si_code == CLD_KILLED ||
3333 status.si_code == CLD_DUMPED) {
3334
3335 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3336 return -EPROTO;
3337 }
3338
3339 log_warning("%s failed due to unknown reason.", name);
3340 return -EPROTO;
3341
3342}
3343
3c14d26c
LP
3344void freeze(void) {
3345 for (;;)
3346 pause();
3347}
3348
00dc5d76
LP
3349bool null_or_empty(struct stat *st) {
3350 assert(st);
3351
3352 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3353 return true;
3354
c8f26f42 3355 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
00dc5d76
LP
3356 return true;
3357
3358 return false;
3359}
3360
3b63d2d3
LP
3361DIR *xopendirat(int fd, const char *name) {
3362 return fdopendir(openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC));
3363}
3364
8a0867d6
LP
3365int signal_from_string_try_harder(const char *s) {
3366 int signo;
3367 assert(s);
3368
3369 if ((signo = signal_from_string(s)) <= 0)
3370 if (startswith(s, "SIG"))
3371 return signal_from_string(s+3);
3372
3373 return signo;
3374}
3375
10717a1a
LP
3376void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3377
3378 assert(f);
3379 assert(name);
3380 assert(t);
3381
3382 if (!dual_timestamp_is_set(t))
3383 return;
3384
3385 fprintf(f, "%s=%llu %llu\n",
3386 name,
3387 (unsigned long long) t->realtime,
3388 (unsigned long long) t->monotonic);
3389}
3390
799fd0fd 3391void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
10717a1a
LP
3392 unsigned long long a, b;
3393
10717a1a
LP
3394 assert(value);
3395 assert(t);
3396
3397 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3398 log_debug("Failed to parse finish timestamp value %s", value);
3399 else {
3400 t->realtime = a;
3401 t->monotonic = b;
3402 }
3403}
3404
e23a0ce8
LP
3405char *fstab_node_to_udev_node(const char *p) {
3406 char *dn, *t, *u;
3407 int r;
3408
3409 /* FIXME: to follow udev's logic 100% we need to leave valid
3410 * UTF8 chars unescaped */
3411
3412 if (startswith(p, "LABEL=")) {
3413
3414 if (!(u = unquote(p+6, "\"\'")))
3415 return NULL;
3416
3417 t = xescape(u, "/ ");
3418 free(u);
3419
3420 if (!t)
3421 return NULL;
3422
3423 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3424 free(t);
3425
3426 if (r < 0)
3427 return NULL;
3428
3429 return dn;
3430 }
3431
3432 if (startswith(p, "UUID=")) {
3433
3434 if (!(u = unquote(p+5, "\"\'")))
3435 return NULL;
3436
3437 t = xescape(u, "/ ");
3438 free(u);
3439
3440 if (!t)
3441 return NULL;
3442
3443 r = asprintf(&dn, "/dev/disk/by-uuid/%s", ascii_strlower(t));
3444 free(t);
3445
3446 if (r < 0)
3447 return NULL;
3448
3449 return dn;
3450 }
3451
3452 return strdup(p);
3453}
3454
e9ddabc2
LP
3455void filter_environ(const char *prefix) {
3456 int i, j;
3457 assert(prefix);
3458
3459 if (!environ)
3460 return;
3461
3462 for (i = 0, j = 0; environ[i]; i++) {
3463
3464 if (startswith(environ[i], prefix))
3465 continue;
3466
3467 environ[j++] = environ[i];
3468 }
3469
3470 environ[j] = NULL;
3471}
3472
1dccbe19
LP
3473static const char *const ioprio_class_table[] = {
3474 [IOPRIO_CLASS_NONE] = "none",
3475 [IOPRIO_CLASS_RT] = "realtime",
3476 [IOPRIO_CLASS_BE] = "best-effort",
3477 [IOPRIO_CLASS_IDLE] = "idle"
3478};
3479
3480DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
3481
3482static const char *const sigchld_code_table[] = {
3483 [CLD_EXITED] = "exited",
3484 [CLD_KILLED] = "killed",
3485 [CLD_DUMPED] = "dumped",
3486 [CLD_TRAPPED] = "trapped",
3487 [CLD_STOPPED] = "stopped",
3488 [CLD_CONTINUED] = "continued",
3489};
3490
3491DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3492
3493static const char *const log_facility_table[LOG_NFACILITIES] = {
3494 [LOG_FAC(LOG_KERN)] = "kern",
3495 [LOG_FAC(LOG_USER)] = "user",
3496 [LOG_FAC(LOG_MAIL)] = "mail",
3497 [LOG_FAC(LOG_DAEMON)] = "daemon",
3498 [LOG_FAC(LOG_AUTH)] = "auth",
3499 [LOG_FAC(LOG_SYSLOG)] = "syslog",
3500 [LOG_FAC(LOG_LPR)] = "lpr",
3501 [LOG_FAC(LOG_NEWS)] = "news",
3502 [LOG_FAC(LOG_UUCP)] = "uucp",
3503 [LOG_FAC(LOG_CRON)] = "cron",
3504 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3505 [LOG_FAC(LOG_FTP)] = "ftp",
3506 [LOG_FAC(LOG_LOCAL0)] = "local0",
3507 [LOG_FAC(LOG_LOCAL1)] = "local1",
3508 [LOG_FAC(LOG_LOCAL2)] = "local2",
3509 [LOG_FAC(LOG_LOCAL3)] = "local3",
3510 [LOG_FAC(LOG_LOCAL4)] = "local4",
3511 [LOG_FAC(LOG_LOCAL5)] = "local5",
3512 [LOG_FAC(LOG_LOCAL6)] = "local6",
3513 [LOG_FAC(LOG_LOCAL7)] = "local7"
3514};
3515
3516DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
3517
3518static const char *const log_level_table[] = {
3519 [LOG_EMERG] = "emerg",
3520 [LOG_ALERT] = "alert",
3521 [LOG_CRIT] = "crit",
3522 [LOG_ERR] = "err",
3523 [LOG_WARNING] = "warning",
3524 [LOG_NOTICE] = "notice",
3525 [LOG_INFO] = "info",
3526 [LOG_DEBUG] = "debug"
3527};
3528
3529DEFINE_STRING_TABLE_LOOKUP(log_level, int);
3530
3531static const char* const sched_policy_table[] = {
3532 [SCHED_OTHER] = "other",
3533 [SCHED_BATCH] = "batch",
3534 [SCHED_IDLE] = "idle",
3535 [SCHED_FIFO] = "fifo",
3536 [SCHED_RR] = "rr"
3537};
3538
3539DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
3540
3541static const char* const rlimit_table[] = {
3542 [RLIMIT_CPU] = "LimitCPU",
3543 [RLIMIT_FSIZE] = "LimitFSIZE",
3544 [RLIMIT_DATA] = "LimitDATA",
3545 [RLIMIT_STACK] = "LimitSTACK",
3546 [RLIMIT_CORE] = "LimitCORE",
3547 [RLIMIT_RSS] = "LimitRSS",
3548 [RLIMIT_NOFILE] = "LimitNOFILE",
3549 [RLIMIT_AS] = "LimitAS",
3550 [RLIMIT_NPROC] = "LimitNPROC",
3551 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3552 [RLIMIT_LOCKS] = "LimitLOCKS",
3553 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3554 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3555 [RLIMIT_NICE] = "LimitNICE",
3556 [RLIMIT_RTPRIO] = "LimitRTPRIO",
3557 [RLIMIT_RTTIME] = "LimitRTTIME"
3558};
3559
3560DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4fd5948e
LP
3561
3562static const char* const ip_tos_table[] = {
3563 [IPTOS_LOWDELAY] = "low-delay",
3564 [IPTOS_THROUGHPUT] = "throughput",
3565 [IPTOS_RELIABILITY] = "reliability",
3566 [IPTOS_LOWCOST] = "low-cost",
3567};
3568
3569DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
2e22afe9
LP
3570
3571static const char *const signal_table[] = {
3572 [SIGHUP] = "HUP",
3573 [SIGINT] = "INT",
3574 [SIGQUIT] = "QUIT",
3575 [SIGILL] = "ILL",
3576 [SIGTRAP] = "TRAP",
3577 [SIGABRT] = "ABRT",
3578 [SIGBUS] = "BUS",
3579 [SIGFPE] = "FPE",
3580 [SIGKILL] = "KILL",
3581 [SIGUSR1] = "USR1",
3582 [SIGSEGV] = "SEGV",
3583 [SIGUSR2] = "USR2",
3584 [SIGPIPE] = "PIPE",
3585 [SIGALRM] = "ALRM",
3586 [SIGTERM] = "TERM",
f26ee0b9
LP
3587#ifdef SIGSTKFLT
3588 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
3589#endif
2e22afe9
LP
3590 [SIGCHLD] = "CHLD",
3591 [SIGCONT] = "CONT",
3592 [SIGSTOP] = "STOP",
3593 [SIGTSTP] = "TSTP",
3594 [SIGTTIN] = "TTIN",
3595 [SIGTTOU] = "TTOU",
3596 [SIGURG] = "URG",
3597 [SIGXCPU] = "XCPU",
3598 [SIGXFSZ] = "XFSZ",
3599 [SIGVTALRM] = "VTALRM",
3600 [SIGPROF] = "PROF",
3601 [SIGWINCH] = "WINCH",
3602 [SIGIO] = "IO",
3603 [SIGPWR] = "PWR",
3604 [SIGSYS] = "SYS"
3605};
3606
3607DEFINE_STRING_TABLE_LOOKUP(signal, int);