]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/util.c
units: fix rescue.service race with plymouth
[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>
ac123445 53#include <sys/capability.h>
7948c4df
KS
54#include <sys/time.h>
55#include <linux/rtc.h>
8092a428 56#include <glob.h>
4b67834e 57#include <grp.h>
60918275
LP
58
59#include "macro.h"
60#include "util.h"
1dccbe19
LP
61#include "ioprio.h"
62#include "missing.h"
a9f5d454 63#include "log.h"
65d2ebdc 64#include "strv.h"
e51bc1a2 65#include "label.h"
d06dacd0 66#include "exit-status.h"
83cc030f 67#include "hashmap.h"
56cf987f 68
9a0e6896
LP
69int saved_argc = 0;
70char **saved_argv = NULL;
71
37f85e66 72size_t page_size(void) {
73 static __thread size_t pgsz = 0;
74 long r;
75
3bfc7184 76 if (_likely_(pgsz))
37f85e66 77 return pgsz;
78
79 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
80
81 pgsz = (size_t) r;
82
83 return pgsz;
84}
85
e05797fb
LP
86bool streq_ptr(const char *a, const char *b) {
87
88 /* Like streq(), but tries to make sense of NULL pointers */
89
90 if (a && b)
91 return streq(a, b);
92
93 if (!a && !b)
94 return true;
95
96 return false;
97}
98
47be870b 99usec_t now(clockid_t clock_id) {
60918275
LP
100 struct timespec ts;
101
47be870b 102 assert_se(clock_gettime(clock_id, &ts) == 0);
60918275
LP
103
104 return timespec_load(&ts);
105}
106
63983207 107dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
871d7de4
LP
108 assert(ts);
109
110 ts->realtime = now(CLOCK_REALTIME);
111 ts->monotonic = now(CLOCK_MONOTONIC);
112
113 return ts;
114}
115
a185c5aa
LP
116dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
117 int64_t delta;
118 assert(ts);
119
120 ts->realtime = u;
121
122 if (u == 0)
123 ts->monotonic = 0;
124 else {
125 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
126
127 ts->monotonic = now(CLOCK_MONOTONIC);
128
129 if ((int64_t) ts->monotonic > delta)
130 ts->monotonic -= delta;
131 else
132 ts->monotonic = 0;
133 }
134
135 return ts;
136}
137
60918275
LP
138usec_t timespec_load(const struct timespec *ts) {
139 assert(ts);
140
141 return
142 (usec_t) ts->tv_sec * USEC_PER_SEC +
143 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
144}
145
146struct timespec *timespec_store(struct timespec *ts, usec_t u) {
147 assert(ts);
148
149 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
150 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
151
152 return ts;
153}
154
155usec_t timeval_load(const struct timeval *tv) {
156 assert(tv);
157
158 return
159 (usec_t) tv->tv_sec * USEC_PER_SEC +
160 (usec_t) tv->tv_usec;
161}
162
163struct timeval *timeval_store(struct timeval *tv, usec_t u) {
164 assert(tv);
165
166 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
167 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
168
169 return tv;
170}
171
172bool endswith(const char *s, const char *postfix) {
173 size_t sl, pl;
174
175 assert(s);
176 assert(postfix);
177
178 sl = strlen(s);
179 pl = strlen(postfix);
180
d4d0d4db
LP
181 if (pl == 0)
182 return true;
183
60918275
LP
184 if (sl < pl)
185 return false;
186
187 return memcmp(s + sl - pl, postfix, pl) == 0;
188}
189
190bool startswith(const char *s, const char *prefix) {
191 size_t sl, pl;
192
193 assert(s);
194 assert(prefix);
195
196 sl = strlen(s);
197 pl = strlen(prefix);
198
d4d0d4db
LP
199 if (pl == 0)
200 return true;
201
60918275
LP
202 if (sl < pl)
203 return false;
204
205 return memcmp(s, prefix, pl) == 0;
206}
207
3177a7fa
MAP
208bool startswith_no_case(const char *s, const char *prefix) {
209 size_t sl, pl;
210 unsigned i;
211
212 assert(s);
213 assert(prefix);
214
215 sl = strlen(s);
216 pl = strlen(prefix);
217
218 if (pl == 0)
219 return true;
220
221 if (sl < pl)
222 return false;
223
224 for(i = 0; i < pl; ++i) {
225 if (tolower(s[i]) != tolower(prefix[i]))
226 return false;
227 }
228
229 return true;
230}
231
79d6d816
LP
232bool first_word(const char *s, const char *word) {
233 size_t sl, wl;
234
235 assert(s);
236 assert(word);
237
238 sl = strlen(s);
239 wl = strlen(word);
240
241 if (sl < wl)
242 return false;
243
d4d0d4db
LP
244 if (wl == 0)
245 return true;
246
79d6d816
LP
247 if (memcmp(s, word, wl) != 0)
248 return false;
249
d4d0d4db
LP
250 return s[wl] == 0 ||
251 strchr(WHITESPACE, s[wl]);
79d6d816
LP
252}
253
42f4e3c4 254int close_nointr(int fd) {
60918275
LP
255 assert(fd >= 0);
256
257 for (;;) {
258 int r;
259
48f82119
LP
260 r = close(fd);
261 if (r >= 0)
60918275
LP
262 return r;
263
264 if (errno != EINTR)
48f82119 265 return -errno;
60918275
LP
266 }
267}
85261803 268
85f136b5 269void close_nointr_nofail(int fd) {
80876c20 270 int saved_errno = errno;
85f136b5
LP
271
272 /* like close_nointr() but cannot fail, and guarantees errno
273 * is unchanged */
274
275 assert_se(close_nointr(fd) == 0);
80876c20
LP
276
277 errno = saved_errno;
85f136b5
LP
278}
279
5b6319dc
LP
280void close_many(const int fds[], unsigned n_fd) {
281 unsigned i;
282
283 for (i = 0; i < n_fd; i++)
284 close_nointr_nofail(fds[i]);
285}
286
85261803
LP
287int parse_boolean(const char *v) {
288 assert(v);
289
44d8db9e 290 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
85261803 291 return 1;
44d8db9e 292 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
85261803
LP
293 return 0;
294
295 return -EINVAL;
296}
297
3ba686c1 298int parse_pid(const char *s, pid_t* ret_pid) {
0b172489 299 unsigned long ul = 0;
3ba686c1
LP
300 pid_t pid;
301 int r;
302
303 assert(s);
304 assert(ret_pid);
305
306 if ((r = safe_atolu(s, &ul)) < 0)
307 return r;
308
309 pid = (pid_t) ul;
310
311 if ((unsigned long) pid != ul)
312 return -ERANGE;
313
314 if (pid <= 0)
315 return -ERANGE;
316
317 *ret_pid = pid;
318 return 0;
319}
320
034a2a52
LP
321int parse_uid(const char *s, uid_t* ret_uid) {
322 unsigned long ul = 0;
323 uid_t uid;
324 int r;
325
326 assert(s);
327 assert(ret_uid);
328
329 if ((r = safe_atolu(s, &ul)) < 0)
330 return r;
331
332 uid = (uid_t) ul;
333
334 if ((unsigned long) uid != ul)
335 return -ERANGE;
336
337 *ret_uid = uid;
338 return 0;
339}
340
85261803
LP
341int safe_atou(const char *s, unsigned *ret_u) {
342 char *x = NULL;
034c6ed7 343 unsigned long l;
85261803
LP
344
345 assert(s);
346 assert(ret_u);
347
348 errno = 0;
349 l = strtoul(s, &x, 0);
350
351 if (!x || *x || errno)
352 return errno ? -errno : -EINVAL;
353
034c6ed7 354 if ((unsigned long) (unsigned) l != l)
85261803
LP
355 return -ERANGE;
356
357 *ret_u = (unsigned) l;
358 return 0;
359}
360
361int safe_atoi(const char *s, int *ret_i) {
362 char *x = NULL;
034c6ed7 363 long l;
85261803
LP
364
365 assert(s);
366 assert(ret_i);
367
368 errno = 0;
369 l = strtol(s, &x, 0);
370
371 if (!x || *x || errno)
372 return errno ? -errno : -EINVAL;
373
034c6ed7 374 if ((long) (int) l != l)
85261803
LP
375 return -ERANGE;
376
034c6ed7
LP
377 *ret_i = (int) l;
378 return 0;
379}
380
034c6ed7
LP
381int safe_atollu(const char *s, long long unsigned *ret_llu) {
382 char *x = NULL;
383 unsigned long long l;
384
385 assert(s);
386 assert(ret_llu);
387
388 errno = 0;
389 l = strtoull(s, &x, 0);
390
391 if (!x || *x || errno)
392 return errno ? -errno : -EINVAL;
393
394 *ret_llu = l;
395 return 0;
396}
397
398int safe_atolli(const char *s, long long int *ret_lli) {
399 char *x = NULL;
400 long long l;
401
402 assert(s);
403 assert(ret_lli);
404
405 errno = 0;
406 l = strtoll(s, &x, 0);
407
408 if (!x || *x || errno)
409 return errno ? -errno : -EINVAL;
410
411 *ret_lli = l;
85261803
LP
412 return 0;
413}
a41e8209 414
a41e8209 415/* Split a string into words. */
65d2ebdc 416char *split(const char *c, size_t *l, const char *separator, char **state) {
a41e8209
LP
417 char *current;
418
419 current = *state ? *state : (char*) c;
420
421 if (!*current || *c == 0)
422 return NULL;
423
65d2ebdc
LP
424 current += strspn(current, separator);
425 *l = strcspn(current, separator);
82919e3d
LP
426 *state = current+*l;
427
428 return (char*) current;
429}
430
034c6ed7
LP
431/* Split a string into words, but consider strings enclosed in '' and
432 * "" as words even if they include spaces. */
433char *split_quoted(const char *c, size_t *l, char **state) {
0bab36f2
LP
434 char *current, *e;
435 bool escaped = false;
034c6ed7
LP
436
437 current = *state ? *state : (char*) c;
438
439 if (!*current || *c == 0)
440 return NULL;
441
442 current += strspn(current, WHITESPACE);
443
444 if (*current == '\'') {
445 current ++;
034c6ed7 446
0bab36f2
LP
447 for (e = current; *e; e++) {
448 if (escaped)
449 escaped = false;
450 else if (*e == '\\')
451 escaped = true;
452 else if (*e == '\'')
453 break;
454 }
455
456 *l = e-current;
457 *state = *e == 0 ? e : e+1;
034c6ed7
LP
458 } else if (*current == '\"') {
459 current ++;
034c6ed7 460
0bab36f2
LP
461 for (e = current; *e; e++) {
462 if (escaped)
463 escaped = false;
464 else if (*e == '\\')
465 escaped = true;
466 else if (*e == '\"')
467 break;
468 }
469
470 *l = e-current;
471 *state = *e == 0 ? e : e+1;
034c6ed7 472 } else {
0bab36f2
LP
473 for (e = current; *e; e++) {
474 if (escaped)
475 escaped = false;
476 else if (*e == '\\')
477 escaped = true;
478 else if (strchr(WHITESPACE, *e))
479 break;
480 }
481 *l = e-current;
482 *state = e;
034c6ed7
LP
483 }
484
485 return (char*) current;
486}
487
65d2ebdc
LP
488char **split_path_and_make_absolute(const char *p) {
489 char **l;
490 assert(p);
491
492 if (!(l = strv_split(p, ":")))
493 return NULL;
494
495 if (!strv_path_make_absolute_cwd(l)) {
496 strv_free(l);
497 return NULL;
498 }
499
500 return l;
501}
502
034c6ed7
LP
503int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
504 int r;
505 FILE *f;
20c03b7b 506 char fn[PATH_MAX], line[LINE_MAX], *p;
bb00e604 507 long unsigned ppid;
034c6ed7 508
8480e784 509 assert(pid > 0);
034c6ed7
LP
510 assert(_ppid);
511
bb00e604 512 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
8480e784 513 char_array_0(fn);
034c6ed7 514
ccaa6149 515 if (!(f = fopen(fn, "re")))
034c6ed7
LP
516 return -errno;
517
518 if (!(fgets(line, sizeof(line), f))) {
519 r = -errno;
520 fclose(f);
521 return r;
522 }
523
524 fclose(f);
525
526 /* Let's skip the pid and comm fields. The latter is enclosed
527 * in () but does not escape any () in its value, so let's
528 * skip over it manually */
529
530 if (!(p = strrchr(line, ')')))
531 return -EIO;
532
533 p++;
534
535 if (sscanf(p, " "
536 "%*c " /* state */
bb00e604 537 "%lu ", /* ppid */
034c6ed7
LP
538 &ppid) != 1)
539 return -EIO;
540
bb00e604 541 if ((long unsigned) (pid_t) ppid != ppid)
034c6ed7
LP
542 return -ERANGE;
543
544 *_ppid = (pid_t) ppid;
545
546 return 0;
547}
548
7640a5de
LP
549int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
550 int r;
551 FILE *f;
552 char fn[PATH_MAX], line[LINE_MAX], *p;
553
554 assert(pid > 0);
555 assert(st);
556
557 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
558 char_array_0(fn);
559
ccaa6149 560 if (!(f = fopen(fn, "re")))
7640a5de
LP
561 return -errno;
562
563 if (!(fgets(line, sizeof(line), f))) {
564 r = -errno;
565 fclose(f);
566 return r;
567 }
568
569 fclose(f);
570
571 /* Let's skip the pid and comm fields. The latter is enclosed
572 * in () but does not escape any () in its value, so let's
573 * skip over it manually */
574
575 if (!(p = strrchr(line, ')')))
576 return -EIO;
577
578 p++;
579
580 if (sscanf(p, " "
581 "%*c " /* state */
582 "%*d " /* ppid */
583 "%*d " /* pgrp */
584 "%*d " /* session */
585 "%*d " /* tty_nr */
586 "%*d " /* tpgid */
587 "%*u " /* flags */
588 "%*u " /* minflt */
589 "%*u " /* cminflt */
590 "%*u " /* majflt */
591 "%*u " /* cmajflt */
592 "%*u " /* utime */
593 "%*u " /* stime */
594 "%*d " /* cutime */
595 "%*d " /* cstime */
596 "%*d " /* priority */
597 "%*d " /* nice */
598 "%*d " /* num_threads */
599 "%*d " /* itrealvalue */
600 "%llu " /* starttime */,
601 st) != 1)
602 return -EIO;
603
604 return 0;
605}
606
034c6ed7
LP
607int write_one_line_file(const char *fn, const char *line) {
608 FILE *f;
609 int r;
610
611 assert(fn);
612 assert(line);
613
614 if (!(f = fopen(fn, "we")))
615 return -errno;
616
34ca941c 617 errno = 0;
034c6ed7
LP
618 if (fputs(line, f) < 0) {
619 r = -errno;
620 goto finish;
621 }
622
8e1bd70d
LP
623 if (!endswith(line, "\n"))
624 fputc('\n', f);
625
151b190e
LP
626 fflush(f);
627
628 if (ferror(f)) {
629 if (errno != 0)
630 r = -errno;
631 else
632 r = -EIO;
633 } else
634 r = 0;
635
034c6ed7
LP
636finish:
637 fclose(f);
638 return r;
639}
640
34ca941c
LP
641int fchmod_umask(int fd, mode_t m) {
642 mode_t u;
643 int r;
644
645 u = umask(0777);
646 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
647 umask(u);
648
649 return r;
650}
651
652int write_one_line_file_atomic(const char *fn, const char *line) {
653 FILE *f;
654 int r;
655 char *p;
656
657 assert(fn);
658 assert(line);
659
660 r = fopen_temporary(fn, &f, &p);
661 if (r < 0)
662 return r;
663
664 fchmod_umask(fileno(f), 0644);
665
666 errno = 0;
667 if (fputs(line, f) < 0) {
668 r = -errno;
669 goto finish;
670 }
671
672 if (!endswith(line, "\n"))
673 fputc('\n', f);
674
675 fflush(f);
676
677 if (ferror(f)) {
678 if (errno != 0)
679 r = -errno;
680 else
681 r = -EIO;
682 } else {
683 if (rename(p, fn) < 0)
684 r = -errno;
685 else
686 r = 0;
687 }
688
689finish:
690 if (r < 0)
691 unlink(p);
692
693 fclose(f);
694 free(p);
695
696 return r;
697}
698
034c6ed7
LP
699int read_one_line_file(const char *fn, char **line) {
700 FILE *f;
701 int r;
97c4a07d 702 char t[LINE_MAX], *c;
034c6ed7
LP
703
704 assert(fn);
705 assert(line);
706
707 if (!(f = fopen(fn, "re")))
708 return -errno;
709
710 if (!(fgets(t, sizeof(t), f))) {
711 r = -errno;
712 goto finish;
713 }
714
715 if (!(c = strdup(t))) {
716 r = -ENOMEM;
717 goto finish;
718 }
719
6f9a471a
LP
720 truncate_nl(c);
721
034c6ed7
LP
722 *line = c;
723 r = 0;
724
725finish:
726 fclose(f);
727 return r;
728}
44d8db9e 729
34ca941c 730int read_full_file(const char *fn, char **contents, size_t *size) {
97c4a07d
LP
731 FILE *f;
732 int r;
733 size_t n, l;
734 char *buf = NULL;
735 struct stat st;
736
737 if (!(f = fopen(fn, "re")))
738 return -errno;
739
740 if (fstat(fileno(f), &st) < 0) {
741 r = -errno;
742 goto finish;
743 }
744
34ca941c
LP
745 /* Safety check */
746 if (st.st_size > 4*1024*1024) {
747 r = -E2BIG;
748 goto finish;
749 }
750
97c4a07d
LP
751 n = st.st_size > 0 ? st.st_size : LINE_MAX;
752 l = 0;
753
754 for (;;) {
755 char *t;
756 size_t k;
757
758 if (!(t = realloc(buf, n+1))) {
759 r = -ENOMEM;
760 goto finish;
761 }
762
763 buf = t;
764 k = fread(buf + l, 1, n - l, f);
765
766 if (k <= 0) {
767 if (ferror(f)) {
768 r = -errno;
769 goto finish;
770 }
771
772 break;
773 }
774
775 l += k;
776 n *= 2;
777
778 /* Safety check */
779 if (n > 4*1024*1024) {
780 r = -E2BIG;
781 goto finish;
782 }
783 }
784
785 if (buf)
786 buf[l] = 0;
787 else if (!(buf = calloc(1, 1))) {
788 r = -errno;
789 goto finish;
790 }
791
792 *contents = buf;
793 buf = NULL;
794
34ca941c
LP
795 if (size)
796 *size = l;
797
97c4a07d
LP
798 r = 0;
799
800finish:
801 fclose(f);
802 free(buf);
803
804 return r;
805}
806
807int parse_env_file(
808 const char *fname,
c899f8c6 809 const char *separator, ...) {
97c4a07d 810
ce8a6aa1 811 int r = 0;
44d91056 812 char *contents = NULL, *p;
97c4a07d
LP
813
814 assert(fname);
c899f8c6 815 assert(separator);
97c4a07d 816
34ca941c 817 if ((r = read_full_file(fname, &contents, NULL)) < 0)
97c4a07d
LP
818 return r;
819
820 p = contents;
821 for (;;) {
822 const char *key = NULL;
823
c899f8c6 824 p += strspn(p, separator);
97c4a07d
LP
825 p += strspn(p, WHITESPACE);
826
827 if (!*p)
828 break;
829
830 if (!strchr(COMMENTS, *p)) {
831 va_list ap;
832 char **value;
833
c899f8c6 834 va_start(ap, separator);
97c4a07d
LP
835 while ((key = va_arg(ap, char *))) {
836 size_t n;
837 char *v;
838
839 value = va_arg(ap, char **);
840
841 n = strlen(key);
842 if (strncmp(p, key, n) != 0 ||
843 p[n] != '=')
844 continue;
845
846 p += n + 1;
c899f8c6 847 n = strcspn(p, separator);
97c4a07d
LP
848
849 if (n >= 2 &&
e7db37dd
LP
850 strchr(QUOTES, p[0]) &&
851 p[n-1] == p[0])
97c4a07d
LP
852 v = strndup(p+1, n-2);
853 else
854 v = strndup(p, n);
855
856 if (!v) {
857 r = -ENOMEM;
858 va_end(ap);
859 goto fail;
860 }
861
dd36de4d
KS
862 if (v[0] == '\0') {
863 /* return empty value strings as NULL */
864 free(v);
865 v = NULL;
866 }
867
97c4a07d
LP
868 free(*value);
869 *value = v;
870
871 p += n;
ce8a6aa1
LP
872
873 r ++;
97c4a07d
LP
874 break;
875 }
876 va_end(ap);
877 }
878
879 if (!key)
c899f8c6 880 p += strcspn(p, separator);
97c4a07d
LP
881 }
882
97c4a07d
LP
883fail:
884 free(contents);
885 return r;
886}
887
8c7be95e
LP
888int load_env_file(
889 const char *fname,
890 char ***rl) {
891
892 FILE *f;
893 char **m = 0;
894 int r;
895
896 assert(fname);
897 assert(rl);
898
899 if (!(f = fopen(fname, "re")))
900 return -errno;
901
902 while (!feof(f)) {
903 char l[LINE_MAX], *p, *u;
904 char **t;
905
906 if (!fgets(l, sizeof(l), f)) {
907 if (feof(f))
908 break;
909
910 r = -errno;
911 goto finish;
912 }
913
914 p = strstrip(l);
915
916 if (!*p)
917 continue;
918
919 if (strchr(COMMENTS, *p))
920 continue;
921
922 if (!(u = normalize_env_assignment(p))) {
923 log_error("Out of memory");
924 r = -ENOMEM;
925 goto finish;
926 }
927
928 t = strv_append(m, u);
929 free(u);
930
931 if (!t) {
932 log_error("Out of memory");
933 r = -ENOMEM;
934 goto finish;
935 }
936
937 strv_free(m);
938 m = t;
939 }
940
941 r = 0;
942
943 *rl = m;
944 m = NULL;
945
946finish:
947 if (f)
948 fclose(f);
949
950 strv_free(m);
951
952 return r;
953}
954
7640a5de 955int write_env_file(const char *fname, char **l) {
34ca941c 956 char **i, *p;
7640a5de
LP
957 FILE *f;
958 int r;
959
34ca941c
LP
960 r = fopen_temporary(fname, &f, &p);
961 if (r < 0)
962 return r;
7640a5de 963
34ca941c
LP
964 fchmod_umask(fileno(f), 0644);
965
966 errno = 0;
7640a5de
LP
967 STRV_FOREACH(i, l) {
968 fputs(*i, f);
969 fputc('\n', f);
970 }
971
972 fflush(f);
973
34ca941c
LP
974 if (ferror(f)) {
975 if (errno != 0)
976 r = -errno;
977 else
978 r = -EIO;
979 } else {
980 if (rename(p, fname) < 0)
981 r = -errno;
982 else
983 r = 0;
984 }
985
986 if (r < 0)
987 unlink(p);
988
7640a5de 989 fclose(f);
34ca941c 990 free(p);
7640a5de
LP
991
992 return r;
993}
994
7072ced8
LP
995char *truncate_nl(char *s) {
996 assert(s);
997
998 s[strcspn(s, NEWLINE)] = 0;
999 return s;
1000}
1001
1002int get_process_name(pid_t pid, char **name) {
1003 char *p;
1004 int r;
1005
1006 assert(pid >= 1);
1007 assert(name);
1008
bb00e604 1009 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
7072ced8
LP
1010 return -ENOMEM;
1011
1012 r = read_one_line_file(p, name);
1013 free(p);
1014
1015 if (r < 0)
1016 return r;
1017
7072ced8
LP
1018 return 0;
1019}
1020
c59760ee
LP
1021int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
1022 char *p, *r, *k;
1023 int c;
1024 bool space = false;
1025 size_t left;
1026 FILE *f;
1027
1028 assert(pid >= 1);
1029 assert(max_length > 0);
1030 assert(line);
1031
1032 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1033 return -ENOMEM;
1034
ccaa6149 1035 f = fopen(p, "re");
c59760ee
LP
1036 free(p);
1037
1038 if (!f)
1039 return -errno;
1040
1041 if (!(r = new(char, max_length))) {
1042 fclose(f);
1043 return -ENOMEM;
1044 }
1045
1046 k = r;
1047 left = max_length;
1048 while ((c = getc(f)) != EOF) {
1049
1050 if (isprint(c)) {
1051 if (space) {
1052 if (left <= 4)
1053 break;
1054
1055 *(k++) = ' ';
057fbb58 1056 left--;
c59760ee
LP
1057 space = false;
1058 }
1059
1060 if (left <= 4)
1061 break;
1062
1063 *(k++) = (char) c;
057fbb58 1064 left--;
c59760ee
LP
1065 } else
1066 space = true;
1067 }
1068
1069 if (left <= 4) {
1070 size_t n = MIN(left-1, 3U);
1071 memcpy(k, "...", n);
1072 k[n] = 0;
1073 } else
1074 *k = 0;
1075
1076 fclose(f);
1077
35d2e7ec
LP
1078 /* Kernel threads have no argv[] */
1079 if (r[0] == 0) {
1080 char *t;
1081 int h;
1082
1083 free(r);
1084
1085 if ((h = get_process_name(pid, &t)) < 0)
1086 return h;
1087
1088 h = asprintf(&r, "[%s]", t);
1089 free(t);
1090
1091 if (h < 0)
1092 return -ENOMEM;
1093 }
fa776d8e 1094
c59760ee
LP
1095 *line = r;
1096 return 0;
1097}
1098
fab56fc5
LP
1099char *strnappend(const char *s, const char *suffix, size_t b) {
1100 size_t a;
44d8db9e
LP
1101 char *r;
1102
fab56fc5
LP
1103 if (!s && !suffix)
1104 return strdup("");
1105
1106 if (!s)
1107 return strndup(suffix, b);
1108
1109 if (!suffix)
1110 return strdup(s);
1111
44d8db9e
LP
1112 assert(s);
1113 assert(suffix);
1114
1115 a = strlen(s);
44d8db9e
LP
1116
1117 if (!(r = new(char, a+b+1)))
1118 return NULL;
1119
1120 memcpy(r, s, a);
1121 memcpy(r+a, suffix, b);
1122 r[a+b] = 0;
1123
1124 return r;
1125}
87f0e418 1126
fab56fc5
LP
1127char *strappend(const char *s, const char *suffix) {
1128 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1129}
1130
87f0e418
LP
1131int readlink_malloc(const char *p, char **r) {
1132 size_t l = 100;
1133
1134 assert(p);
1135 assert(r);
1136
1137 for (;;) {
1138 char *c;
1139 ssize_t n;
1140
1141 if (!(c = new(char, l)))
1142 return -ENOMEM;
1143
1144 if ((n = readlink(p, c, l-1)) < 0) {
1145 int ret = -errno;
1146 free(c);
1147 return ret;
1148 }
1149
1150 if ((size_t) n < l-1) {
1151 c[n] = 0;
1152 *r = c;
1153 return 0;
1154 }
1155
1156 free(c);
1157 l *= 2;
1158 }
1159}
1160
2c7108c4
LP
1161int readlink_and_make_absolute(const char *p, char **r) {
1162 char *target, *k;
1163 int j;
1164
1165 assert(p);
1166 assert(r);
1167
1168 if ((j = readlink_malloc(p, &target)) < 0)
1169 return j;
1170
1171 k = file_in_same_dir(p, target);
1172 free(target);
1173
1174 if (!k)
1175 return -ENOMEM;
1176
1177 *r = k;
1178 return 0;
1179}
1180
83096483
LP
1181int readlink_and_canonicalize(const char *p, char **r) {
1182 char *t, *s;
1183 int j;
1184
1185 assert(p);
1186 assert(r);
1187
1188 j = readlink_and_make_absolute(p, &t);
1189 if (j < 0)
1190 return j;
1191
1192 s = canonicalize_file_name(t);
1193 if (s) {
1194 free(t);
1195 *r = s;
1196 } else
1197 *r = t;
1198
1199 path_kill_slashes(*r);
1200
1201 return 0;
1202}
1203
35d2e7ec
LP
1204int parent_of_path(const char *path, char **_r) {
1205 const char *e, *a = NULL, *b = NULL, *p;
1206 char *r;
1207 bool slash = false;
1208
1209 assert(path);
1210 assert(_r);
1211
1212 if (!*path)
1213 return -EINVAL;
1214
1215 for (e = path; *e; e++) {
1216
1217 if (!slash && *e == '/') {
1218 a = b;
1219 b = e;
1220 slash = true;
1221 } else if (slash && *e != '/')
1222 slash = false;
1223 }
1224
1225 if (*(e-1) == '/')
1226 p = a;
1227 else
1228 p = b;
1229
1230 if (!p)
1231 return -EINVAL;
1232
1233 if (p == path)
1234 r = strdup("/");
1235 else
1236 r = strndup(path, p-path);
1237
1238 if (!r)
1239 return -ENOMEM;
1240
1241 *_r = r;
1242 return 0;
1243}
1244
1245
87f0e418
LP
1246char *file_name_from_path(const char *p) {
1247 char *r;
1248
1249 assert(p);
1250
1251 if ((r = strrchr(p, '/')))
1252 return r + 1;
1253
1254 return (char*) p;
1255}
0301abf4
LP
1256
1257bool path_is_absolute(const char *p) {
1258 assert(p);
1259
1260 return p[0] == '/';
1261}
1262
1263bool is_path(const char *p) {
1264
1265 return !!strchr(p, '/');
1266}
1267
1268char *path_make_absolute(const char *p, const char *prefix) {
0301abf4
LP
1269 assert(p);
1270
65d2ebdc
LP
1271 /* Makes every item in the list an absolute path by prepending
1272 * the prefix, if specified and necessary */
1273
0301abf4
LP
1274 if (path_is_absolute(p) || !prefix)
1275 return strdup(p);
1276
44d91056 1277 return join(prefix, "/", p, NULL);
0301abf4 1278}
2a987ee8 1279
65d2ebdc
LP
1280char *path_make_absolute_cwd(const char *p) {
1281 char *cwd, *r;
1282
1283 assert(p);
1284
1285 /* Similar to path_make_absolute(), but prefixes with the
1286 * current working directory. */
1287
1288 if (path_is_absolute(p))
1289 return strdup(p);
1290
1291 if (!(cwd = get_current_dir_name()))
1292 return NULL;
1293
1294 r = path_make_absolute(p, cwd);
1295 free(cwd);
1296
1297 return r;
1298}
1299
1300char **strv_path_make_absolute_cwd(char **l) {
1301 char **s;
1302
1303 /* Goes through every item in the string list and makes it
1304 * absolute. This works in place and won't rollback any
1305 * changes on failure. */
1306
1307 STRV_FOREACH(s, l) {
1308 char *t;
1309
1310 if (!(t = path_make_absolute_cwd(*s)))
1311 return NULL;
1312
1313 free(*s);
1314 *s = t;
1315 }
1316
1317 return l;
1318}
1319
c3f6d675
LP
1320char **strv_path_canonicalize(char **l) {
1321 char **s;
1322 unsigned k = 0;
1323 bool enomem = false;
1324
1325 if (strv_isempty(l))
1326 return l;
1327
1328 /* Goes through every item in the string list and canonicalize
1329 * the path. This works in place and won't rollback any
1330 * changes on failure. */
1331
1332 STRV_FOREACH(s, l) {
1333 char *t, *u;
1334
1335 t = path_make_absolute_cwd(*s);
1336 free(*s);
1337
1338 if (!t) {
1339 enomem = true;
1340 continue;
1341 }
1342
1343 errno = 0;
1344 u = canonicalize_file_name(t);
1345 free(t);
1346
1347 if (!u) {
1348 if (errno == ENOMEM || !errno)
1349 enomem = true;
1350
1351 continue;
1352 }
1353
1354 l[k++] = u;
1355 }
1356
1357 l[k] = NULL;
1358
1359 if (enomem)
1360 return NULL;
1361
1362 return l;
a9dd2082
LP
1363}
1364
1365char **strv_path_remove_empty(char **l) {
1366 char **f, **t;
1367
1368 if (!l)
1369 return NULL;
1370
1371 for (f = t = l; *f; f++) {
1372
1373 if (dir_is_empty(*f) > 0) {
1374 free(*f);
1375 continue;
1376 }
1377
1378 *(t++) = *f;
1379 }
1380
1381 *t = NULL;
1382 return l;
c3f6d675
LP
1383}
1384
2a987ee8
LP
1385int reset_all_signal_handlers(void) {
1386 int sig;
1387
1388 for (sig = 1; sig < _NSIG; sig++) {
1389 struct sigaction sa;
1390
1391 if (sig == SIGKILL || sig == SIGSTOP)
1392 continue;
1393
1394 zero(sa);
1395 sa.sa_handler = SIG_DFL;
431c32bf 1396 sa.sa_flags = SA_RESTART;
2a987ee8
LP
1397
1398 /* On Linux the first two RT signals are reserved by
1399 * glibc, and sigaction() will return EINVAL for them. */
1400 if ((sigaction(sig, &sa, NULL) < 0))
1401 if (errno != EINVAL)
1402 return -errno;
1403 }
1404
8e274523 1405 return 0;
2a987ee8 1406}
4a72ff34
LP
1407
1408char *strstrip(char *s) {
57a8eca8 1409 char *e;
4a72ff34
LP
1410
1411 /* Drops trailing whitespace. Modifies the string in
1412 * place. Returns pointer to first non-space character */
1413
1414 s += strspn(s, WHITESPACE);
1415
57a8eca8
LP
1416 for (e = strchr(s, 0); e > s; e --)
1417 if (!strchr(WHITESPACE, e[-1]))
1418 break;
4a72ff34 1419
57a8eca8 1420 *e = 0;
4a72ff34
LP
1421
1422 return s;
4a72ff34
LP
1423}
1424
ee9b5e01
LP
1425char *delete_chars(char *s, const char *bad) {
1426 char *f, *t;
1427
1428 /* Drops all whitespace, regardless where in the string */
1429
1430 for (f = s, t = s; *f; f++) {
1431 if (strchr(bad, *f))
1432 continue;
1433
1434 *(t++) = *f;
1435 }
1436
1437 *t = 0;
1438
1439 return s;
1440}
1441
ab1f0633
LP
1442bool in_charset(const char *s, const char* charset) {
1443 const char *i;
1444
1445 assert(s);
1446 assert(charset);
1447
1448 for (i = s; *i; i++)
1449 if (!strchr(charset, *i))
1450 return false;
1451
1452 return true;
1453}
1454
4a72ff34
LP
1455char *file_in_same_dir(const char *path, const char *filename) {
1456 char *e, *r;
1457 size_t k;
1458
1459 assert(path);
1460 assert(filename);
1461
1462 /* This removes the last component of path and appends
1463 * filename, unless the latter is absolute anyway or the
1464 * former isn't */
1465
1466 if (path_is_absolute(filename))
1467 return strdup(filename);
1468
1469 if (!(e = strrchr(path, '/')))
1470 return strdup(filename);
1471
1472 k = strlen(filename);
1473 if (!(r = new(char, e-path+1+k+1)))
1474 return NULL;
1475
1476 memcpy(r, path, e-path+1);
1477 memcpy(r+(e-path)+1, filename, k+1);
1478
1479 return r;
1480}
fb624d04 1481
8c6db833
LP
1482int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1483 struct stat st;
1484
56cf987f 1485 if (label_mkdir(path, mode) >= 0)
8c6db833
LP
1486 if (chmod_and_chown(path, mode, uid, gid) < 0)
1487 return -errno;
1488
1489 if (lstat(path, &st) < 0)
1490 return -errno;
1491
1492 if ((st.st_mode & 0777) != mode ||
1493 st.st_uid != uid ||
1494 st.st_gid != gid ||
1495 !S_ISDIR(st.st_mode)) {
1496 errno = EEXIST;
1497 return -errno;
1498 }
1499
1500 return 0;
1501}
1502
1503
a9f5d454
LP
1504int mkdir_parents(const char *path, mode_t mode) {
1505 const char *p, *e;
1506
1507 assert(path);
1508
1509 /* Creates every parent directory in the path except the last
1510 * component. */
1511
1512 p = path + strspn(path, "/");
1513 for (;;) {
1514 int r;
1515 char *t;
1516
1517 e = p + strcspn(p, "/");
1518 p = e + strspn(e, "/");
1519
1520 /* Is this the last component? If so, then we're
1521 * done */
1522 if (*p == 0)
1523 return 0;
1524
1525 if (!(t = strndup(path, e - path)))
1526 return -ENOMEM;
1527
56cf987f 1528 r = label_mkdir(t, mode);
a9f5d454
LP
1529 free(t);
1530
1531 if (r < 0 && errno != EEXIST)
1532 return -errno;
1533 }
1534}
1535
bbd67135
LP
1536int mkdir_p(const char *path, mode_t mode) {
1537 int r;
1538
1539 /* Like mkdir -p */
1540
1541 if ((r = mkdir_parents(path, mode)) < 0)
1542 return r;
1543
56cf987f 1544 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
bbd67135
LP
1545 return -errno;
1546
1547 return 0;
1548}
1549
c32dd69b
LP
1550int rmdir_parents(const char *path, const char *stop) {
1551 size_t l;
1552 int r = 0;
1553
1554 assert(path);
1555 assert(stop);
1556
1557 l = strlen(path);
1558
1559 /* Skip trailing slashes */
1560 while (l > 0 && path[l-1] == '/')
1561 l--;
1562
1563 while (l > 0) {
1564 char *t;
1565
1566 /* Skip last component */
1567 while (l > 0 && path[l-1] != '/')
1568 l--;
1569
1570 /* Skip trailing slashes */
1571 while (l > 0 && path[l-1] == '/')
1572 l--;
1573
1574 if (l <= 0)
1575 break;
1576
1577 if (!(t = strndup(path, l)))
1578 return -ENOMEM;
1579
1580 if (path_startswith(stop, t)) {
1581 free(t);
1582 return 0;
1583 }
1584
1585 r = rmdir(t);
1586 free(t);
1587
1588 if (r < 0)
1589 if (errno != ENOENT)
1590 return -errno;
1591 }
1592
1593 return 0;
1594}
1595
1596
fb624d04
LP
1597char hexchar(int x) {
1598 static const char table[16] = "0123456789abcdef";
1599
1600 return table[x & 15];
1601}
4fe88d28
LP
1602
1603int unhexchar(char c) {
1604
1605 if (c >= '0' && c <= '9')
1606 return c - '0';
1607
1608 if (c >= 'a' && c <= 'f')
ea430986 1609 return c - 'a' + 10;
4fe88d28
LP
1610
1611 if (c >= 'A' && c <= 'F')
ea430986 1612 return c - 'A' + 10;
4fe88d28
LP
1613
1614 return -1;
1615}
1616
1617char octchar(int x) {
1618 return '0' + (x & 7);
1619}
1620
1621int unoctchar(char c) {
1622
1623 if (c >= '0' && c <= '7')
1624 return c - '0';
1625
1626 return -1;
1627}
1628
5af98f82
LP
1629char decchar(int x) {
1630 return '0' + (x % 10);
1631}
1632
1633int undecchar(char c) {
1634
1635 if (c >= '0' && c <= '9')
1636 return c - '0';
1637
1638 return -1;
1639}
1640
4fe88d28
LP
1641char *cescape(const char *s) {
1642 char *r, *t;
1643 const char *f;
1644
1645 assert(s);
1646
1647 /* Does C style string escaping. */
1648
1649 if (!(r = new(char, strlen(s)*4 + 1)))
1650 return NULL;
1651
1652 for (f = s, t = r; *f; f++)
1653
1654 switch (*f) {
1655
1656 case '\a':
1657 *(t++) = '\\';
1658 *(t++) = 'a';
1659 break;
1660 case '\b':
1661 *(t++) = '\\';
1662 *(t++) = 'b';
1663 break;
1664 case '\f':
1665 *(t++) = '\\';
1666 *(t++) = 'f';
1667 break;
1668 case '\n':
1669 *(t++) = '\\';
1670 *(t++) = 'n';
1671 break;
1672 case '\r':
1673 *(t++) = '\\';
1674 *(t++) = 'r';
1675 break;
1676 case '\t':
1677 *(t++) = '\\';
1678 *(t++) = 't';
1679 break;
1680 case '\v':
1681 *(t++) = '\\';
1682 *(t++) = 'v';
1683 break;
1684 case '\\':
1685 *(t++) = '\\';
1686 *(t++) = '\\';
1687 break;
1688 case '"':
1689 *(t++) = '\\';
1690 *(t++) = '"';
1691 break;
1692 case '\'':
1693 *(t++) = '\\';
1694 *(t++) = '\'';
1695 break;
1696
1697 default:
1698 /* For special chars we prefer octal over
1699 * hexadecimal encoding, simply because glib's
1700 * g_strescape() does the same */
1701 if ((*f < ' ') || (*f >= 127)) {
1702 *(t++) = '\\';
1703 *(t++) = octchar((unsigned char) *f >> 6);
1704 *(t++) = octchar((unsigned char) *f >> 3);
1705 *(t++) = octchar((unsigned char) *f);
1706 } else
1707 *(t++) = *f;
1708 break;
1709 }
1710
1711 *t = 0;
1712
1713 return r;
1714}
1715
6febfd0d 1716char *cunescape_length(const char *s, size_t length) {
4fe88d28
LP
1717 char *r, *t;
1718 const char *f;
1719
1720 assert(s);
1721
1722 /* Undoes C style string escaping */
1723
6febfd0d 1724 if (!(r = new(char, length+1)))
4fe88d28
LP
1725 return r;
1726
6febfd0d 1727 for (f = s, t = r; f < s + length; f++) {
4fe88d28
LP
1728
1729 if (*f != '\\') {
1730 *(t++) = *f;
1731 continue;
1732 }
1733
1734 f++;
1735
1736 switch (*f) {
1737
1738 case 'a':
1739 *(t++) = '\a';
1740 break;
1741 case 'b':
1742 *(t++) = '\b';
1743 break;
1744 case 'f':
1745 *(t++) = '\f';
1746 break;
1747 case 'n':
1748 *(t++) = '\n';
1749 break;
1750 case 'r':
1751 *(t++) = '\r';
1752 break;
1753 case 't':
1754 *(t++) = '\t';
1755 break;
1756 case 'v':
1757 *(t++) = '\v';
1758 break;
1759 case '\\':
1760 *(t++) = '\\';
1761 break;
1762 case '"':
1763 *(t++) = '"';
1764 break;
1765 case '\'':
1766 *(t++) = '\'';
1767 break;
1768
e167fb86
LP
1769 case 's':
1770 /* This is an extension of the XDG syntax files */
1771 *(t++) = ' ';
1772 break;
1773
4fe88d28
LP
1774 case 'x': {
1775 /* hexadecimal encoding */
1776 int a, b;
1777
1778 if ((a = unhexchar(f[1])) < 0 ||
1779 (b = unhexchar(f[2])) < 0) {
1780 /* Invalid escape code, let's take it literal then */
1781 *(t++) = '\\';
1782 *(t++) = 'x';
1783 } else {
1784 *(t++) = (char) ((a << 4) | b);
1785 f += 2;
1786 }
1787
1788 break;
1789 }
1790
1791 case '0':
1792 case '1':
1793 case '2':
1794 case '3':
1795 case '4':
1796 case '5':
1797 case '6':
1798 case '7': {
1799 /* octal encoding */
1800 int a, b, c;
1801
1802 if ((a = unoctchar(f[0])) < 0 ||
1803 (b = unoctchar(f[1])) < 0 ||
1804 (c = unoctchar(f[2])) < 0) {
1805 /* Invalid escape code, let's take it literal then */
1806 *(t++) = '\\';
1807 *(t++) = f[0];
1808 } else {
1809 *(t++) = (char) ((a << 6) | (b << 3) | c);
1810 f += 2;
1811 }
1812
1813 break;
1814 }
1815
1816 case 0:
1817 /* premature end of string.*/
1818 *(t++) = '\\';
1819 goto finish;
1820
1821 default:
1822 /* Invalid escape code, let's take it literal then */
1823 *(t++) = '\\';
f3d4cc01 1824 *(t++) = *f;
4fe88d28
LP
1825 break;
1826 }
1827 }
1828
1829finish:
1830 *t = 0;
1831 return r;
1832}
1833
6febfd0d
LP
1834char *cunescape(const char *s) {
1835 return cunescape_length(s, strlen(s));
1836}
4fe88d28
LP
1837
1838char *xescape(const char *s, const char *bad) {
1839 char *r, *t;
1840 const char *f;
1841
1842 /* Escapes all chars in bad, in addition to \ and all special
1843 * chars, in \xFF style escaping. May be reversed with
1844 * cunescape. */
1845
1846 if (!(r = new(char, strlen(s)*4+1)))
1847 return NULL;
1848
1849 for (f = s, t = r; *f; f++) {
1850
b866264a
LP
1851 if ((*f < ' ') || (*f >= 127) ||
1852 (*f == '\\') || strchr(bad, *f)) {
4fe88d28
LP
1853 *(t++) = '\\';
1854 *(t++) = 'x';
1855 *(t++) = hexchar(*f >> 4);
1856 *(t++) = hexchar(*f);
1857 } else
1858 *(t++) = *f;
1859 }
1860
1861 *t = 0;
1862
1863 return r;
1864}
1865
ea430986 1866char *bus_path_escape(const char *s) {
ea430986
LP
1867 char *r, *t;
1868 const char *f;
1869
47be870b
LP
1870 assert(s);
1871
ea430986
LP
1872 /* Escapes all chars that D-Bus' object path cannot deal
1873 * with. Can be reverse with bus_path_unescape() */
1874
1875 if (!(r = new(char, strlen(s)*3+1)))
1876 return NULL;
1877
1878 for (f = s, t = r; *f; f++) {
1879
1880 if (!(*f >= 'A' && *f <= 'Z') &&
1881 !(*f >= 'a' && *f <= 'z') &&
1882 !(*f >= '0' && *f <= '9')) {
1883 *(t++) = '_';
1884 *(t++) = hexchar(*f >> 4);
1885 *(t++) = hexchar(*f);
1886 } else
1887 *(t++) = *f;
1888 }
1889
1890 *t = 0;
1891
1892 return r;
1893}
1894
9e2f7c11 1895char *bus_path_unescape(const char *f) {
ea430986 1896 char *r, *t;
ea430986 1897
9e2f7c11 1898 assert(f);
47be870b 1899
9e2f7c11 1900 if (!(r = strdup(f)))
ea430986
LP
1901 return NULL;
1902
9e2f7c11 1903 for (t = r; *f; f++) {
ea430986
LP
1904
1905 if (*f == '_') {
1906 int a, b;
1907
1908 if ((a = unhexchar(f[1])) < 0 ||
1909 (b = unhexchar(f[2])) < 0) {
1910 /* Invalid escape code, let's take it literal then */
1911 *(t++) = '_';
1912 } else {
1913 *(t++) = (char) ((a << 4) | b);
1914 f += 2;
1915 }
1916 } else
1917 *(t++) = *f;
1918 }
1919
1920 *t = 0;
1921
1922 return r;
1923}
1924
4fe88d28
LP
1925char *path_kill_slashes(char *path) {
1926 char *f, *t;
1927 bool slash = false;
1928
1929 /* Removes redundant inner and trailing slashes. Modifies the
1930 * passed string in-place.
1931 *
1932 * ///foo///bar/ becomes /foo/bar
1933 */
1934
1935 for (f = path, t = path; *f; f++) {
1936
1937 if (*f == '/') {
1938 slash = true;
1939 continue;
1940 }
1941
1942 if (slash) {
1943 slash = false;
1944 *(t++) = '/';
1945 }
1946
1947 *(t++) = *f;
1948 }
1949
1950 /* Special rule, if we are talking of the root directory, a
1951 trailing slash is good */
1952
1953 if (t == path && slash)
1954 *(t++) = '/';
1955
1956 *t = 0;
1957 return path;
1958}
1959
1960bool path_startswith(const char *path, const char *prefix) {
1961 assert(path);
1962 assert(prefix);
1963
1964 if ((path[0] == '/') != (prefix[0] == '/'))
1965 return false;
1966
1967 for (;;) {
1968 size_t a, b;
1969
1970 path += strspn(path, "/");
1971 prefix += strspn(prefix, "/");
1972
1973 if (*prefix == 0)
1974 return true;
1975
1976 if (*path == 0)
1977 return false;
1978
1979 a = strcspn(path, "/");
1980 b = strcspn(prefix, "/");
1981
1982 if (a != b)
1983 return false;
1984
1985 if (memcmp(path, prefix, a) != 0)
1986 return false;
1987
1988 path += a;
1989 prefix += b;
1990 }
1991}
1992
15ae422b
LP
1993bool path_equal(const char *a, const char *b) {
1994 assert(a);
1995 assert(b);
1996
1997 if ((a[0] == '/') != (b[0] == '/'))
1998 return false;
1999
2000 for (;;) {
2001 size_t j, k;
2002
2003 a += strspn(a, "/");
2004 b += strspn(b, "/");
2005
2006 if (*a == 0 && *b == 0)
2007 return true;
2008
2009 if (*a == 0 || *b == 0)
2010 return false;
2011
2012 j = strcspn(a, "/");
2013 k = strcspn(b, "/");
2014
2015 if (j != k)
2016 return false;
2017
2018 if (memcmp(a, b, j) != 0)
2019 return false;
2020
2021 a += j;
2022 b += k;
2023 }
2024}
2025
67d51650 2026char *ascii_strlower(char *t) {
4fe88d28
LP
2027 char *p;
2028
67d51650 2029 assert(t);
4fe88d28 2030
67d51650 2031 for (p = t; *p; p++)
4fe88d28
LP
2032 if (*p >= 'A' && *p <= 'Z')
2033 *p = *p - 'A' + 'a';
2034
67d51650 2035 return t;
4fe88d28 2036}
1dccbe19 2037
c85dc17b
LP
2038bool ignore_file(const char *filename) {
2039 assert(filename);
2040
2041 return
2042 filename[0] == '.' ||
6c78be3c 2043 streq(filename, "lost+found") ||
e472d476
LP
2044 streq(filename, "aquota.user") ||
2045 streq(filename, "aquota.group") ||
c85dc17b
LP
2046 endswith(filename, "~") ||
2047 endswith(filename, ".rpmnew") ||
2048 endswith(filename, ".rpmsave") ||
2049 endswith(filename, ".rpmorig") ||
2050 endswith(filename, ".dpkg-old") ||
2051 endswith(filename, ".dpkg-new") ||
2052 endswith(filename, ".swp");
2053}
2054
3a0ecb08
LP
2055int fd_nonblock(int fd, bool nonblock) {
2056 int flags;
2057
2058 assert(fd >= 0);
2059
2060 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2061 return -errno;
2062
2063 if (nonblock)
2064 flags |= O_NONBLOCK;
2065 else
2066 flags &= ~O_NONBLOCK;
2067
2068 if (fcntl(fd, F_SETFL, flags) < 0)
2069 return -errno;
2070
2071 return 0;
2072}
2073
2074int fd_cloexec(int fd, bool cloexec) {
2075 int flags;
2076
2077 assert(fd >= 0);
2078
2079 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2080 return -errno;
2081
2082 if (cloexec)
2083 flags |= FD_CLOEXEC;
2084 else
2085 flags &= ~FD_CLOEXEC;
2086
2087 if (fcntl(fd, F_SETFD, flags) < 0)
2088 return -errno;
2089
2090 return 0;
2091}
2092
a0d40ac5
LP
2093int close_all_fds(const int except[], unsigned n_except) {
2094 DIR *d;
2095 struct dirent *de;
2096 int r = 0;
2097
2098 if (!(d = opendir("/proc/self/fd")))
2099 return -errno;
2100
2101 while ((de = readdir(d))) {
a7610064 2102 int fd = -1;
a0d40ac5 2103
a16e1123 2104 if (ignore_file(de->d_name))
a0d40ac5
LP
2105 continue;
2106
720ce21d
LP
2107 if (safe_atoi(de->d_name, &fd) < 0)
2108 /* Let's better ignore this, just in case */
2109 continue;
a0d40ac5
LP
2110
2111 if (fd < 3)
2112 continue;
2113
2114 if (fd == dirfd(d))
2115 continue;
2116
2117 if (except) {
2118 bool found;
2119 unsigned i;
2120
2121 found = false;
2122 for (i = 0; i < n_except; i++)
2123 if (except[i] == fd) {
2124 found = true;
2125 break;
2126 }
2127
2128 if (found)
2129 continue;
2130 }
2131
720ce21d 2132 if (close_nointr(fd) < 0) {
2f357920 2133 /* Valgrind has its own FD and doesn't want to have it closed */
720ce21d
LP
2134 if (errno != EBADF && r == 0)
2135 r = -errno;
2f357920 2136 }
a0d40ac5
LP
2137 }
2138
a0d40ac5
LP
2139 closedir(d);
2140 return r;
2141}
2142
db12775d
LP
2143bool chars_intersect(const char *a, const char *b) {
2144 const char *p;
2145
2146 /* Returns true if any of the chars in a are in b. */
2147 for (p = a; *p; p++)
2148 if (strchr(b, *p))
2149 return true;
2150
2151 return false;
2152}
2153
8b6c7120
LP
2154char *format_timestamp(char *buf, size_t l, usec_t t) {
2155 struct tm tm;
2156 time_t sec;
2157
2158 assert(buf);
2159 assert(l > 0);
2160
2161 if (t <= 0)
2162 return NULL;
2163
f872ec33 2164 sec = (time_t) (t / USEC_PER_SEC);
8b6c7120
LP
2165
2166 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2167 return NULL;
2168
2169 return buf;
2170}
2171
584be568
LP
2172char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2173 usec_t n, d;
2174
2175 n = now(CLOCK_REALTIME);
2176
2177 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2178 return NULL;
2179
2180 d = n - t;
2181
2182 if (d >= USEC_PER_YEAR)
2183 snprintf(buf, l, "%llu years and %llu months ago",
2184 (unsigned long long) (d / USEC_PER_YEAR),
2185 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2186 else if (d >= USEC_PER_MONTH)
2187 snprintf(buf, l, "%llu months and %llu days ago",
2188 (unsigned long long) (d / USEC_PER_MONTH),
2189 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2190 else if (d >= USEC_PER_WEEK)
2191 snprintf(buf, l, "%llu weeks and %llu days ago",
2192 (unsigned long long) (d / USEC_PER_WEEK),
2193 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2194 else if (d >= 2*USEC_PER_DAY)
2195 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2196 else if (d >= 25*USEC_PER_HOUR)
2197 snprintf(buf, l, "1 day and %lluh ago",
2198 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2199 else if (d >= 6*USEC_PER_HOUR)
2200 snprintf(buf, l, "%lluh ago",
2201 (unsigned long long) (d / USEC_PER_HOUR));
2202 else if (d >= USEC_PER_HOUR)
2203 snprintf(buf, l, "%lluh %llumin ago",
2204 (unsigned long long) (d / USEC_PER_HOUR),
2205 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2206 else if (d >= 5*USEC_PER_MINUTE)
2207 snprintf(buf, l, "%llumin ago",
2208 (unsigned long long) (d / USEC_PER_MINUTE));
2209 else if (d >= USEC_PER_MINUTE)
2210 snprintf(buf, l, "%llumin %llus ago",
2211 (unsigned long long) (d / USEC_PER_MINUTE),
2212 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2213 else if (d >= USEC_PER_SEC)
2214 snprintf(buf, l, "%llus ago",
2215 (unsigned long long) (d / USEC_PER_SEC));
2216 else if (d >= USEC_PER_MSEC)
2217 snprintf(buf, l, "%llums ago",
2218 (unsigned long long) (d / USEC_PER_MSEC));
2219 else if (d > 0)
2220 snprintf(buf, l, "%lluus ago",
2221 (unsigned long long) d);
2222 else
2223 snprintf(buf, l, "now");
2224
2225 buf[l-1] = 0;
2226 return buf;
2227}
2228
871d7de4
LP
2229char *format_timespan(char *buf, size_t l, usec_t t) {
2230 static const struct {
2231 const char *suffix;
2232 usec_t usec;
2233 } table[] = {
2234 { "w", USEC_PER_WEEK },
2235 { "d", USEC_PER_DAY },
2236 { "h", USEC_PER_HOUR },
2237 { "min", USEC_PER_MINUTE },
2238 { "s", USEC_PER_SEC },
2239 { "ms", USEC_PER_MSEC },
2240 { "us", 1 },
2241 };
2242
2243 unsigned i;
2244 char *p = buf;
2245
2246 assert(buf);
2247 assert(l > 0);
2248
2249 if (t == (usec_t) -1)
2250 return NULL;
2251
4502d22c
LP
2252 if (t == 0) {
2253 snprintf(p, l, "0");
2254 p[l-1] = 0;
2255 return p;
2256 }
2257
871d7de4
LP
2258 /* The result of this function can be parsed with parse_usec */
2259
2260 for (i = 0; i < ELEMENTSOF(table); i++) {
2261 int k;
2262 size_t n;
2263
2264 if (t < table[i].usec)
2265 continue;
2266
2267 if (l <= 1)
2268 break;
2269
2270 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2271 n = MIN((size_t) k, l);
2272
2273 l -= n;
2274 p += n;
2275
2276 t %= table[i].usec;
2277 }
2278
2279 *p = 0;
2280
2281 return buf;
2282}
2283
42856c10
LP
2284bool fstype_is_network(const char *fstype) {
2285 static const char * const table[] = {
2286 "cifs",
2287 "smbfs",
2288 "ncpfs",
2289 "nfs",
ca139f94
LP
2290 "nfs4",
2291 "gfs",
2292 "gfs2"
42856c10
LP
2293 };
2294
2295 unsigned i;
2296
2297 for (i = 0; i < ELEMENTSOF(table); i++)
2298 if (streq(table[i], fstype))
2299 return true;
2300
2301 return false;
2302}
2303
601f6a1e
LP
2304int chvt(int vt) {
2305 int fd, r = 0;
2306
74bc3bdc 2307 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
601f6a1e
LP
2308 return -errno;
2309
2310 if (vt < 0) {
2311 int tiocl[2] = {
2312 TIOCL_GETKMSGREDIRECT,
2313 0
2314 };
2315
2316 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2317 return -errno;
2318
2319 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2320 }
2321
2322 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2323 r = -errno;
2324
a16e1123 2325 close_nointr_nofail(r);
601f6a1e
LP
2326 return r;
2327}
2328
80876c20
LP
2329int read_one_char(FILE *f, char *ret, bool *need_nl) {
2330 struct termios old_termios, new_termios;
2331 char c;
20c03b7b 2332 char line[LINE_MAX];
80876c20
LP
2333
2334 assert(f);
2335 assert(ret);
2336
2337 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2338 new_termios = old_termios;
2339
2340 new_termios.c_lflag &= ~ICANON;
2341 new_termios.c_cc[VMIN] = 1;
2342 new_termios.c_cc[VTIME] = 0;
2343
2344 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2345 size_t k;
2346
2347 k = fread(&c, 1, 1, f);
2348
2349 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2350
2351 if (k <= 0)
2352 return -EIO;
2353
2354 if (need_nl)
2355 *need_nl = c != '\n';
2356
2357 *ret = c;
2358 return 0;
2359 }
2360 }
2361
2362 if (!(fgets(line, sizeof(line), f)))
2363 return -EIO;
2364
2365 truncate_nl(line);
2366
2367 if (strlen(line) != 1)
2368 return -EBADMSG;
2369
2370 if (need_nl)
2371 *need_nl = false;
2372
2373 *ret = line[0];
2374 return 0;
2375}
2376
2377int ask(char *ret, const char *replies, const char *text, ...) {
1b39d4b9
LP
2378 bool on_tty;
2379
80876c20
LP
2380 assert(ret);
2381 assert(replies);
2382 assert(text);
2383
1b39d4b9
LP
2384 on_tty = isatty(STDOUT_FILENO);
2385
80876c20
LP
2386 for (;;) {
2387 va_list ap;
2388 char c;
2389 int r;
2390 bool need_nl = true;
2391
1b39d4b9
LP
2392 if (on_tty)
2393 fputs("\x1B[1m", stdout);
b1b2dc0c 2394
80876c20
LP
2395 va_start(ap, text);
2396 vprintf(text, ap);
2397 va_end(ap);
2398
1b39d4b9
LP
2399 if (on_tty)
2400 fputs("\x1B[0m", stdout);
b1b2dc0c 2401
80876c20
LP
2402 fflush(stdout);
2403
2404 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2405
2406 if (r == -EBADMSG) {
2407 puts("Bad input, please try again.");
2408 continue;
2409 }
2410
2411 putchar('\n');
2412 return r;
2413 }
2414
2415 if (need_nl)
2416 putchar('\n');
2417
2418 if (strchr(replies, c)) {
2419 *ret = c;
2420 return 0;
2421 }
2422
2423 puts("Read unexpected character, please try again.");
2424 }
2425}
2426
6ea832a2 2427int reset_terminal_fd(int fd) {
80876c20
LP
2428 struct termios termios;
2429 int r = 0;
3fe5e5d4
LP
2430 long arg;
2431
2432 /* Set terminal to some sane defaults */
80876c20
LP
2433
2434 assert(fd >= 0);
2435
eed1d0e3
LP
2436 /* We leave locked terminal attributes untouched, so that
2437 * Plymouth may set whatever it wants to set, and we don't
2438 * interfere with that. */
3fe5e5d4
LP
2439
2440 /* Disable exclusive mode, just in case */
2441 ioctl(fd, TIOCNXCL);
2442
2443 /* Enable console unicode mode */
2444 arg = K_UNICODE;
2445 ioctl(fd, KDSKBMODE, &arg);
80876c20
LP
2446
2447 if (tcgetattr(fd, &termios) < 0) {
2448 r = -errno;
2449 goto finish;
2450 }
2451
aaf694ca
LP
2452 /* We only reset the stuff that matters to the software. How
2453 * hardware is set up we don't touch assuming that somebody
2454 * else will do that for us */
2455
2456 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
80876c20
LP
2457 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2458 termios.c_oflag |= ONLCR;
2459 termios.c_cflag |= CREAD;
2460 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2461
2462 termios.c_cc[VINTR] = 03; /* ^C */
2463 termios.c_cc[VQUIT] = 034; /* ^\ */
2464 termios.c_cc[VERASE] = 0177;
2465 termios.c_cc[VKILL] = 025; /* ^X */
2466 termios.c_cc[VEOF] = 04; /* ^D */
2467 termios.c_cc[VSTART] = 021; /* ^Q */
2468 termios.c_cc[VSTOP] = 023; /* ^S */
2469 termios.c_cc[VSUSP] = 032; /* ^Z */
2470 termios.c_cc[VLNEXT] = 026; /* ^V */
2471 termios.c_cc[VWERASE] = 027; /* ^W */
2472 termios.c_cc[VREPRINT] = 022; /* ^R */
aaf694ca
LP
2473 termios.c_cc[VEOL] = 0;
2474 termios.c_cc[VEOL2] = 0;
80876c20
LP
2475
2476 termios.c_cc[VTIME] = 0;
2477 termios.c_cc[VMIN] = 1;
2478
2479 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2480 r = -errno;
2481
2482finish:
2483 /* Just in case, flush all crap out */
2484 tcflush(fd, TCIOFLUSH);
2485
2486 return r;
2487}
2488
6ea832a2
LP
2489int reset_terminal(const char *name) {
2490 int fd, r;
2491
2492 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2493 if (fd < 0)
2494 return fd;
2495
2496 r = reset_terminal_fd(fd);
2497 close_nointr_nofail(fd);
2498
2499 return r;
2500}
2501
80876c20
LP
2502int open_terminal(const char *name, int mode) {
2503 int fd, r;
f73f76ac 2504 unsigned c = 0;
80876c20 2505
f73f76ac
LP
2506 /*
2507 * If a TTY is in the process of being closed opening it might
2508 * cause EIO. This is horribly awful, but unlikely to be
2509 * changed in the kernel. Hence we work around this problem by
2510 * retrying a couple of times.
2511 *
2512 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2513 */
2514
2515 for (;;) {
2516 if ((fd = open(name, mode)) >= 0)
2517 break;
2518
2519 if (errno != EIO)
2520 return -errno;
2521
2522 if (c >= 20)
2523 return -errno;
2524
2525 usleep(50 * USEC_PER_MSEC);
2526 c++;
2527 }
2528
2529 if (fd < 0)
80876c20
LP
2530 return -errno;
2531
2532 if ((r = isatty(fd)) < 0) {
2533 close_nointr_nofail(fd);
2534 return -errno;
2535 }
2536
2537 if (!r) {
2538 close_nointr_nofail(fd);
2539 return -ENOTTY;
2540 }
2541
2542 return fd;
2543}
2544
2545int flush_fd(int fd) {
2546 struct pollfd pollfd;
2547
2548 zero(pollfd);
2549 pollfd.fd = fd;
2550 pollfd.events = POLLIN;
2551
2552 for (;;) {
20c03b7b 2553 char buf[LINE_MAX];
80876c20
LP
2554 ssize_t l;
2555 int r;
2556
2557 if ((r = poll(&pollfd, 1, 0)) < 0) {
2558
2559 if (errno == EINTR)
2560 continue;
2561
2562 return -errno;
2563 }
2564
2565 if (r == 0)
2566 return 0;
2567
2568 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2569
2570 if (errno == EINTR)
2571 continue;
2572
2573 if (errno == EAGAIN)
2574 return 0;
2575
2576 return -errno;
2577 }
2578
2579 if (l <= 0)
2580 return 0;
2581 }
2582}
2583
21de3988 2584int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
bab45044 2585 int fd = -1, notify = -1, r, wd = -1;
80876c20
LP
2586
2587 assert(name);
2588
2589 /* We use inotify to be notified when the tty is closed. We
2590 * create the watch before checking if we can actually acquire
2591 * it, so that we don't lose any event.
2592 *
2593 * Note: strictly speaking this actually watches for the
2594 * device being closed, it does *not* really watch whether a
2595 * tty loses its controlling process. However, unless some
2596 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2597 * its tty otherwise this will not become a problem. As long
2598 * as the administrator makes sure not configure any service
2599 * on the same tty as an untrusted user this should not be a
2600 * problem. (Which he probably should not do anyway.) */
2601
2602 if (!fail && !force) {
2603 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2604 r = -errno;
2605 goto fail;
2606 }
2607
2608 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2609 r = -errno;
2610 goto fail;
2611 }
2612 }
2613
2614 for (;;) {
e3d1855b
LP
2615 if (notify >= 0)
2616 if ((r = flush_fd(notify)) < 0)
2617 goto fail;
80876c20
LP
2618
2619 /* We pass here O_NOCTTY only so that we can check the return
2620 * value TIOCSCTTY and have a reliable way to figure out if we
2621 * successfully became the controlling process of the tty */
6ea832a2
LP
2622 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2623 return fd;
80876c20
LP
2624
2625 /* First, try to get the tty */
21de3988
LP
2626 r = ioctl(fd, TIOCSCTTY, force);
2627
2628 /* Sometimes it makes sense to ignore TIOCSCTTY
2629 * returning EPERM, i.e. when very likely we already
2630 * are have this controlling terminal. */
2631 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2632 r = 0;
2633
2634 if (r < 0 && (force || fail || errno != EPERM)) {
80876c20
LP
2635 r = -errno;
2636 goto fail;
2637 }
2638
2639 if (r >= 0)
2640 break;
2641
2642 assert(!fail);
2643 assert(!force);
2644 assert(notify >= 0);
2645
2646 for (;;) {
f601daa7 2647 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
80876c20 2648 ssize_t l;
f601daa7 2649 struct inotify_event *e;
80876c20 2650
f601daa7 2651 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
80876c20 2652
f601daa7
LP
2653 if (errno == EINTR)
2654 continue;
2655
2656 r = -errno;
2657 goto fail;
2658 }
2659
2660 e = (struct inotify_event*) inotify_buffer;
80876c20 2661
f601daa7
LP
2662 while (l > 0) {
2663 size_t step;
80876c20 2664
f601daa7 2665 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
80876c20 2666 r = -EIO;
f601daa7
LP
2667 goto fail;
2668 }
80876c20 2669
f601daa7
LP
2670 step = sizeof(struct inotify_event) + e->len;
2671 assert(step <= (size_t) l);
80876c20 2672
f601daa7
LP
2673 e = (struct inotify_event*) ((uint8_t*) e + step);
2674 l -= step;
80876c20
LP
2675 }
2676
2677 break;
2678 }
2679
2680 /* We close the tty fd here since if the old session
2681 * ended our handle will be dead. It's important that
2682 * we do this after sleeping, so that we don't enter
2683 * an endless loop. */
2684 close_nointr_nofail(fd);
2685 }
2686
2687 if (notify >= 0)
a16e1123 2688 close_nointr_nofail(notify);
80876c20 2689
6ea832a2 2690 if ((r = reset_terminal_fd(fd)) < 0)
80876c20
LP
2691 log_warning("Failed to reset terminal: %s", strerror(-r));
2692
2693 return fd;
2694
2695fail:
2696 if (fd >= 0)
a16e1123 2697 close_nointr_nofail(fd);
80876c20
LP
2698
2699 if (notify >= 0)
a16e1123 2700 close_nointr_nofail(notify);
80876c20
LP
2701
2702 return r;
2703}
2704
2705int release_terminal(void) {
2706 int r = 0, fd;
57cd2192 2707 struct sigaction sa_old, sa_new;
80876c20 2708
ccaa6149 2709 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
80876c20
LP
2710 return -errno;
2711
57cd2192
LP
2712 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2713 * by our own TIOCNOTTY */
2714
2715 zero(sa_new);
2716 sa_new.sa_handler = SIG_IGN;
2717 sa_new.sa_flags = SA_RESTART;
2718 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2719
80876c20
LP
2720 if (ioctl(fd, TIOCNOTTY) < 0)
2721 r = -errno;
2722
57cd2192
LP
2723 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2724
80876c20
LP
2725 close_nointr_nofail(fd);
2726 return r;
2727}
2728
9a34ec5f
LP
2729int sigaction_many(const struct sigaction *sa, ...) {
2730 va_list ap;
2731 int r = 0, sig;
2732
2733 va_start(ap, sa);
2734 while ((sig = va_arg(ap, int)) > 0)
2735 if (sigaction(sig, sa, NULL) < 0)
2736 r = -errno;
2737 va_end(ap);
2738
2739 return r;
2740}
2741
2742int ignore_signals(int sig, ...) {
a337c6fc 2743 struct sigaction sa;
9a34ec5f
LP
2744 va_list ap;
2745 int r = 0;
a337c6fc
LP
2746
2747 zero(sa);
2748 sa.sa_handler = SIG_IGN;
2749 sa.sa_flags = SA_RESTART;
2750
9a34ec5f
LP
2751 if (sigaction(sig, &sa, NULL) < 0)
2752 r = -errno;
2753
2754 va_start(ap, sig);
2755 while ((sig = va_arg(ap, int)) > 0)
2756 if (sigaction(sig, &sa, NULL) < 0)
2757 r = -errno;
2758 va_end(ap);
2759
2760 return r;
2761}
2762
2763int default_signals(int sig, ...) {
2764 struct sigaction sa;
2765 va_list ap;
2766 int r = 0;
2767
2768 zero(sa);
2769 sa.sa_handler = SIG_DFL;
2770 sa.sa_flags = SA_RESTART;
2771
2772 if (sigaction(sig, &sa, NULL) < 0)
2773 r = -errno;
2774
2775 va_start(ap, sig);
2776 while ((sig = va_arg(ap, int)) > 0)
2777 if (sigaction(sig, &sa, NULL) < 0)
2778 r = -errno;
2779 va_end(ap);
2780
2781 return r;
a337c6fc
LP
2782}
2783
8d567588
LP
2784int close_pipe(int p[]) {
2785 int a = 0, b = 0;
2786
2787 assert(p);
2788
2789 if (p[0] >= 0) {
2790 a = close_nointr(p[0]);
2791 p[0] = -1;
2792 }
2793
2794 if (p[1] >= 0) {
2795 b = close_nointr(p[1]);
2796 p[1] = -1;
2797 }
2798
2799 return a < 0 ? a : b;
2800}
2801
eb22ac37 2802ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
8d567588
LP
2803 uint8_t *p;
2804 ssize_t n = 0;
2805
2806 assert(fd >= 0);
2807 assert(buf);
2808
2809 p = buf;
2810
2811 while (nbytes > 0) {
2812 ssize_t k;
2813
2814 if ((k = read(fd, p, nbytes)) <= 0) {
2815
eb22ac37 2816 if (k < 0 && errno == EINTR)
8d567588
LP
2817 continue;
2818
eb22ac37 2819 if (k < 0 && errno == EAGAIN && do_poll) {
8d567588
LP
2820 struct pollfd pollfd;
2821
2822 zero(pollfd);
2823 pollfd.fd = fd;
2824 pollfd.events = POLLIN;
2825
2826 if (poll(&pollfd, 1, -1) < 0) {
2827 if (errno == EINTR)
2828 continue;
2829
2830 return n > 0 ? n : -errno;
2831 }
2832
2833 if (pollfd.revents != POLLIN)
2834 return n > 0 ? n : -EIO;
2835
2836 continue;
2837 }
2838
2839 return n > 0 ? n : (k < 0 ? -errno : 0);
2840 }
2841
2842 p += k;
2843 nbytes -= k;
2844 n += k;
2845 }
2846
2847 return n;
2848}
2849
eb22ac37
LP
2850ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2851 const uint8_t *p;
2852 ssize_t n = 0;
2853
2854 assert(fd >= 0);
2855 assert(buf);
2856
2857 p = buf;
2858
2859 while (nbytes > 0) {
2860 ssize_t k;
2861
2862 if ((k = write(fd, p, nbytes)) <= 0) {
2863
2864 if (k < 0 && errno == EINTR)
2865 continue;
2866
2867 if (k < 0 && errno == EAGAIN && do_poll) {
2868 struct pollfd pollfd;
2869
2870 zero(pollfd);
2871 pollfd.fd = fd;
2872 pollfd.events = POLLOUT;
2873
2874 if (poll(&pollfd, 1, -1) < 0) {
2875 if (errno == EINTR)
2876 continue;
2877
2878 return n > 0 ? n : -errno;
2879 }
2880
2881 if (pollfd.revents != POLLOUT)
2882 return n > 0 ? n : -EIO;
2883
2884 continue;
2885 }
2886
2887 return n > 0 ? n : (k < 0 ? -errno : 0);
2888 }
2889
2890 p += k;
2891 nbytes -= k;
2892 n += k;
2893 }
2894
2895 return n;
2896}
2897
0c85a4f3 2898int path_is_mount_point(const char *t, bool allow_symlink) {
8d567588 2899 struct stat a, b;
35d2e7ec
LP
2900 char *parent;
2901 int r;
8d567588 2902
0c85a4f3
LP
2903 if (allow_symlink)
2904 r = stat(t, &a);
2905 else
2906 r = lstat(t, &a);
2907
2908 if (r < 0) {
8d567588
LP
2909 if (errno == ENOENT)
2910 return 0;
2911
2912 return -errno;
2913 }
2914
0c85a4f3
LP
2915 r = parent_of_path(t, &parent);
2916 if (r < 0)
35d2e7ec 2917 return r;
8d567588 2918
35d2e7ec
LP
2919 r = lstat(parent, &b);
2920 free(parent);
8d567588 2921
35d2e7ec
LP
2922 if (r < 0)
2923 return -errno;
8d567588
LP
2924
2925 return a.st_dev != b.st_dev;
2926}
2927
24a6e4a4
LP
2928int parse_usec(const char *t, usec_t *usec) {
2929 static const struct {
2930 const char *suffix;
2931 usec_t usec;
2932 } table[] = {
2933 { "sec", USEC_PER_SEC },
2934 { "s", USEC_PER_SEC },
2935 { "min", USEC_PER_MINUTE },
2936 { "hr", USEC_PER_HOUR },
2937 { "h", USEC_PER_HOUR },
2938 { "d", USEC_PER_DAY },
2939 { "w", USEC_PER_WEEK },
2940 { "msec", USEC_PER_MSEC },
2941 { "ms", USEC_PER_MSEC },
2942 { "m", USEC_PER_MINUTE },
2943 { "usec", 1ULL },
2944 { "us", 1ULL },
2945 { "", USEC_PER_SEC },
2946 };
2947
2948 const char *p;
2949 usec_t r = 0;
2950
2951 assert(t);
2952 assert(usec);
2953
2954 p = t;
2955 do {
2956 long long l;
2957 char *e;
2958 unsigned i;
2959
2960 errno = 0;
2961 l = strtoll(p, &e, 10);
2962
2963 if (errno != 0)
2964 return -errno;
2965
2966 if (l < 0)
2967 return -ERANGE;
2968
2969 if (e == p)
2970 return -EINVAL;
2971
2972 e += strspn(e, WHITESPACE);
2973
2974 for (i = 0; i < ELEMENTSOF(table); i++)
2975 if (startswith(e, table[i].suffix)) {
2976 r += (usec_t) l * table[i].usec;
2977 p = e + strlen(table[i].suffix);
2978 break;
2979 }
2980
2981 if (i >= ELEMENTSOF(table))
2982 return -EINVAL;
2983
2984 } while (*p != 0);
2985
2986 *usec = r;
2987
2988 return 0;
2989}
2990
ab1f0633
LP
2991int parse_bytes(const char *t, off_t *bytes) {
2992 static const struct {
2993 const char *suffix;
2994 off_t factor;
2995 } table[] = {
2996 { "B", 1 },
2997 { "K", 1024ULL },
2998 { "M", 1024ULL*1024ULL },
2999 { "G", 1024ULL*1024ULL*1024ULL },
3000 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3001 { "", 1 },
3002 };
3003
3004 const char *p;
3005 off_t r = 0;
3006
3007 assert(t);
3008 assert(bytes);
3009
3010 p = t;
3011 do {
3012 long long l;
3013 char *e;
3014 unsigned i;
3015
3016 errno = 0;
3017 l = strtoll(p, &e, 10);
3018
3019 if (errno != 0)
3020 return -errno;
3021
3022 if (l < 0)
3023 return -ERANGE;
3024
3025 if (e == p)
3026 return -EINVAL;
3027
3028 e += strspn(e, WHITESPACE);
3029
3030 for (i = 0; i < ELEMENTSOF(table); i++)
3031 if (startswith(e, table[i].suffix)) {
3032 r += (off_t) l * table[i].factor;
3033 p = e + strlen(table[i].suffix);
3034 break;
3035 }
3036
3037 if (i >= ELEMENTSOF(table))
3038 return -EINVAL;
3039
3040 } while (*p != 0);
3041
3042 *bytes = r;
3043
3044 return 0;
3045}
3046
843d2643
LP
3047int make_stdio(int fd) {
3048 int r, s, t;
3049
3050 assert(fd >= 0);
3051
3052 r = dup2(fd, STDIN_FILENO);
3053 s = dup2(fd, STDOUT_FILENO);
3054 t = dup2(fd, STDERR_FILENO);
3055
3056 if (fd >= 3)
3057 close_nointr_nofail(fd);
3058
3059 if (r < 0 || s < 0 || t < 0)
3060 return -errno;
3061
7862f62d
LP
3062 fd_cloexec(STDIN_FILENO, false);
3063 fd_cloexec(STDOUT_FILENO, false);
3064 fd_cloexec(STDERR_FILENO, false);
3065
843d2643
LP
3066 return 0;
3067}
3068
ade509ce
LP
3069int make_null_stdio(void) {
3070 int null_fd;
3071
3072 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3073 return -errno;
3074
3075 return make_stdio(null_fd);
3076}
3077
8407a5d0
LP
3078bool is_device_path(const char *path) {
3079
3080 /* Returns true on paths that refer to a device, either in
3081 * sysfs or in /dev */
3082
3083 return
3084 path_startswith(path, "/dev/") ||
3085 path_startswith(path, "/sys/");
3086}
3087
01f78473
LP
3088int dir_is_empty(const char *path) {
3089 DIR *d;
3090 int r;
3091 struct dirent buf, *de;
3092
3093 if (!(d = opendir(path)))
3094 return -errno;
3095
3096 for (;;) {
3097 if ((r = readdir_r(d, &buf, &de)) > 0) {
3098 r = -r;
3099 break;
3100 }
3101
3102 if (!de) {
3103 r = 1;
3104 break;
3105 }
3106
3107 if (!ignore_file(de->d_name)) {
3108 r = 0;
3109 break;
3110 }
3111 }
3112
3113 closedir(d);
3114 return r;
3115}
3116
d3782d60
LP
3117unsigned long long random_ull(void) {
3118 int fd;
3119 uint64_t ull;
3120 ssize_t r;
3121
3122 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3123 goto fallback;
3124
eb22ac37 3125 r = loop_read(fd, &ull, sizeof(ull), true);
d3782d60
LP
3126 close_nointr_nofail(fd);
3127
3128 if (r != sizeof(ull))
3129 goto fallback;
3130
3131 return ull;
3132
3133fallback:
3134 return random() * RAND_MAX + random();
3135}
3136
5b6319dc
LP
3137void rename_process(const char name[8]) {
3138 assert(name);
3139
3140 prctl(PR_SET_NAME, name);
3141
3142 /* This is a like a poor man's setproctitle(). The string
3143 * passed should fit in 7 chars (i.e. the length of
3144 * "systemd") */
3145
3146 if (program_invocation_name)
3147 strncpy(program_invocation_name, name, strlen(program_invocation_name));
9a0e6896
LP
3148
3149 if (saved_argc > 0) {
3150 int i;
3151
3152 if (saved_argv[0])
3153 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3154
3155 for (i = 1; i < saved_argc; i++) {
3156 if (!saved_argv[i])
3157 break;
3158
3159 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3160 }
3161 }
5b6319dc
LP
3162}
3163
7d793605
LP
3164void sigset_add_many(sigset_t *ss, ...) {
3165 va_list ap;
3166 int sig;
3167
3168 assert(ss);
3169
3170 va_start(ap, ss);
3171 while ((sig = va_arg(ap, int)) > 0)
3172 assert_se(sigaddset(ss, sig) == 0);
3173 va_end(ap);
3174}
3175
ef2f1067
LP
3176char* gethostname_malloc(void) {
3177 struct utsname u;
3178
3179 assert_se(uname(&u) >= 0);
3180
3181 if (u.nodename[0])
3182 return strdup(u.nodename);
3183
3184 return strdup(u.sysname);
3185}
3186
3187char* getlogname_malloc(void) {
3188 uid_t uid;
3189 long bufsize;
3190 char *buf, *name;
3191 struct passwd pwbuf, *pw = NULL;
3192 struct stat st;
3193
3194 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3195 uid = st.st_uid;
3196 else
3197 uid = getuid();
3198
3199 /* Shortcut things to avoid NSS lookups */
3200 if (uid == 0)
3201 return strdup("root");
3202
3203 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3204 bufsize = 4096;
3205
3206 if (!(buf = malloc(bufsize)))
3207 return NULL;
3208
3209 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3210 name = strdup(pw->pw_name);
3211 free(buf);
3212 return name;
3213 }
3214
3215 free(buf);
3216
3217 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3218 return NULL;
3219
3220 return name;
3221}
3222
fc116c6a
LP
3223int getttyname_malloc(int fd, char **r) {
3224 char path[PATH_MAX], *c;
618e02c7 3225 int k;
8c6db833
LP
3226
3227 assert(r);
ef2f1067 3228
fc116c6a 3229 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
618e02c7 3230 return -k;
ef2f1067
LP
3231
3232 char_array_0(path);
3233
fc116c6a 3234 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
8c6db833
LP
3235 return -ENOMEM;
3236
3237 *r = c;
3238 return 0;
3239}
3240
fc116c6a
LP
3241int getttyname_harder(int fd, char **r) {
3242 int k;
3243 char *s;
3244
3245 if ((k = getttyname_malloc(fd, &s)) < 0)
3246 return k;
3247
3248 if (streq(s, "tty")) {
3249 free(s);
4d6d6518 3250 return get_ctty(0, NULL, r);
fc116c6a
LP
3251 }
3252
3253 *r = s;
3254 return 0;
3255}
3256
4d6d6518 3257int get_ctty_devnr(pid_t pid, dev_t *d) {
fc116c6a 3258 int k;
4d6d6518 3259 char line[LINE_MAX], *p, *fn;
fc116c6a
LP
3260 unsigned long ttynr;
3261 FILE *f;
3262
4d6d6518
LP
3263 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3264 return -ENOMEM;
3265
3266 f = fopen(fn, "re");
3267 free(fn);
3268 if (!f)
fc116c6a
LP
3269 return -errno;
3270
4d6d6518 3271 if (!fgets(line, sizeof(line), f)) {
fc116c6a
LP
3272 k = -errno;
3273 fclose(f);
3274 return k;
3275 }
3276
3277 fclose(f);
3278
4d6d6518
LP
3279 p = strrchr(line, ')');
3280 if (!p)
fc116c6a
LP
3281 return -EIO;
3282
3283 p++;
3284
3285 if (sscanf(p, " "
3286 "%*c " /* state */
3287 "%*d " /* ppid */
3288 "%*d " /* pgrp */
3289 "%*d " /* session */
3290 "%lu ", /* ttynr */
3291 &ttynr) != 1)
3292 return -EIO;
3293
3294 *d = (dev_t) ttynr;
3295 return 0;
3296}
3297
4d6d6518 3298int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
fc116c6a 3299 int k;
20c03b7b 3300 char fn[PATH_MAX], *s, *b, *p;
fc116c6a
LP
3301 dev_t devnr;
3302
3303 assert(r);
3304
4d6d6518
LP
3305 k = get_ctty_devnr(pid, &devnr);
3306 if (k < 0)
fc116c6a
LP
3307 return k;
3308
3309 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3310 char_array_0(fn);
3311
3312 if ((k = readlink_malloc(fn, &s)) < 0) {
3313
3314 if (k != -ENOENT)
3315 return k;
3316
46824d0e
LP
3317 /* This is an ugly hack */
3318 if (major(devnr) == 136) {
3319 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3320 return -ENOMEM;
3321
3322 *r = b;
3323 if (_devnr)
3324 *_devnr = devnr;
3325
3326 return 0;
3327 }
3328
fc116c6a
LP
3329 /* Probably something like the ptys which have no
3330 * symlink in /dev/char. Let's return something
3331 * vaguely useful. */
3332
3333 if (!(b = strdup(fn + 5)))
3334 return -ENOMEM;
3335
3336 *r = b;
46824d0e
LP
3337 if (_devnr)
3338 *_devnr = devnr;
3339
fc116c6a
LP
3340 return 0;
3341 }
3342
3343 if (startswith(s, "/dev/"))
3344 p = s + 5;
3345 else if (startswith(s, "../"))
3346 p = s + 3;
3347 else
3348 p = s;
3349
3350 b = strdup(p);
3351 free(s);
3352
3353 if (!b)
3354 return -ENOMEM;
3355
3356 *r = b;
46824d0e
LP
3357 if (_devnr)
3358 *_devnr = devnr;
3359
fc116c6a
LP
3360 return 0;
3361}
3362
ad293f5a 3363static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) {
8c6db833
LP
3364 DIR *d;
3365 int ret = 0;
3366
3367 assert(fd >= 0);
3368
3369 /* This returns the first error we run into, but nevertheless
3370 * tries to go on */
3371
3372 if (!(d = fdopendir(fd))) {
3373 close_nointr_nofail(fd);
4c633005
LP
3374
3375 return errno == ENOENT ? 0 : -errno;
8c6db833
LP
3376 }
3377
3378 for (;;) {
3379 struct dirent buf, *de;
ad293f5a 3380 bool is_dir, keep_around = false;
8c6db833
LP
3381 int r;
3382
3383 if ((r = readdir_r(d, &buf, &de)) != 0) {
3384 if (ret == 0)
3385 ret = -r;
3386 break;
3387 }
3388
3389 if (!de)
3390 break;
3391
3392 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3393 continue;
3394
3395 if (de->d_type == DT_UNKNOWN) {
3396 struct stat st;
3397
3398 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
4c633005 3399 if (ret == 0 && errno != ENOENT)
8c6db833
LP
3400 ret = -errno;
3401 continue;
3402 }
3403
ad293f5a
LP
3404 if (honour_sticky)
3405 keep_around = st.st_uid == 0 && (st.st_mode & S_ISVTX);
3406
8c6db833 3407 is_dir = S_ISDIR(st.st_mode);
ad293f5a
LP
3408
3409 } else {
3410 if (honour_sticky) {
3411 struct stat st;
3412
3413 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3414 if (ret == 0 && errno != ENOENT)
3415 ret = -errno;
3416 continue;
3417 }
3418
3419 keep_around = st.st_uid == 0 && (st.st_mode & S_ISVTX);
3420 }
3421
8c6db833 3422 is_dir = de->d_type == DT_DIR;
ad293f5a 3423 }
8c6db833
LP
3424
3425 if (is_dir) {
3426 int subdir_fd;
3427
3428 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
4c633005 3429 if (ret == 0 && errno != ENOENT)
8c6db833
LP
3430 ret = -errno;
3431 continue;
3432 }
3433
ad293f5a 3434 if ((r = rm_rf_children(subdir_fd, only_dirs, honour_sticky)) < 0) {
8c6db833
LP
3435 if (ret == 0)
3436 ret = r;
3437 }
3438
ad293f5a
LP
3439 if (!keep_around)
3440 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3441 if (ret == 0 && errno != ENOENT)
3442 ret = -errno;
3443 }
3444
3445 } else if (!only_dirs && !keep_around) {
8c6db833
LP
3446
3447 if (unlinkat(fd, de->d_name, 0) < 0) {
4c633005 3448 if (ret == 0 && errno != ENOENT)
8c6db833
LP
3449 ret = -errno;
3450 }
3451 }
3452 }
3453
3454 closedir(d);
3455
3456 return ret;
3457}
3458
ad293f5a 3459int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
8c6db833
LP
3460 int fd;
3461 int r;
3462
3463 assert(path);
3464
3465 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3466
3467 if (errno != ENOTDIR)
3468 return -errno;
3469
3470 if (delete_root && !only_dirs)
3471 if (unlink(path) < 0)
3472 return -errno;
3473
3474 return 0;
3475 }
3476
ad293f5a
LP
3477 r = rm_rf_children(fd, only_dirs, honour_sticky);
3478
3479 if (delete_root) {
3480
3481 if (honour_sticky && file_is_sticky(path) > 0)
3482 return r;
8c6db833 3483
e27796a0 3484 if (rmdir(path) < 0 && errno != ENOENT) {
8c6db833
LP
3485 if (r == 0)
3486 r = -errno;
3487 }
ad293f5a 3488 }
8c6db833
LP
3489
3490 return r;
3491}
3492
3493int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3494 assert(path);
3495
3496 /* Under the assumption that we are running privileged we
3497 * first change the access mode and only then hand out
3498 * ownership to avoid a window where access is too open. */
3499
3500 if (chmod(path, mode) < 0)
3501 return -errno;
3502
3503 if (chown(path, uid, gid) < 0)
3504 return -errno;
3505
3506 return 0;
ef2f1067
LP
3507}
3508
82c121a4
LP
3509cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3510 cpu_set_t *r;
3511 unsigned n = 1024;
3512
3513 /* Allocates the cpuset in the right size */
3514
3515 for (;;) {
3516 if (!(r = CPU_ALLOC(n)))
3517 return NULL;
3518
3519 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3520 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3521
3522 if (ncpus)
3523 *ncpus = n;
3524
3525 return r;
3526 }
3527
3528 CPU_FREE(r);
3529
3530 if (errno != EINVAL)
3531 return NULL;
3532
3533 n *= 2;
3534 }
3535}
3536
9e58ff9c
LP
3537void status_vprintf(const char *format, va_list ap) {
3538 char *s = NULL;
3539 int fd = -1;
3540
3541 assert(format);
3542
3543 /* This independent of logging, as status messages are
3544 * optional and go exclusively to the console. */
3545
3546 if (vasprintf(&s, format, ap) < 0)
3547 goto finish;
3548
3549 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3550 goto finish;
3551
3552 write(fd, s, strlen(s));
3553
3554finish:
3555 free(s);
3556
3557 if (fd >= 0)
3558 close_nointr_nofail(fd);
3559}
3560
c846ff47
LP
3561void status_printf(const char *format, ...) {
3562 va_list ap;
3563
3564 assert(format);
3565
3566 va_start(ap, format);
3567 status_vprintf(format, ap);
3568 va_end(ap);
3569}
3570
3571void status_welcome(void) {
10aa7034
LP
3572 char *pretty_name = NULL, *ansi_color = NULL;
3573 const char *const_pretty = NULL, *const_color = NULL;
3574 int r;
c846ff47 3575
10aa7034
LP
3576 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3577 "PRETTY_NAME", &pretty_name,
3578 "ANSI_COLOR", &ansi_color,
3579 NULL)) < 0) {
c846ff47 3580
10aa7034
LP
3581 if (r != -ENOENT)
3582 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3583 }
c846ff47 3584
10aa7034
LP
3585#if defined(TARGET_FEDORA)
3586 if (!pretty_name) {
3587 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
c846ff47 3588
10aa7034
LP
3589 if (r != -ENOENT)
3590 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
6f9a471a 3591 }
10aa7034 3592 }
c846ff47 3593
10aa7034 3594 if (!ansi_color && pretty_name) {
c846ff47 3595
10aa7034
LP
3596 /* This tries to mimic the color magic the old Red Hat sysinit
3597 * script did. */
3598
3599 if (startswith(pretty_name, "Red Hat"))
3600 const_color = "0;31"; /* Red for RHEL */
3601 else if (startswith(pretty_name, "Fedora"))
3602 const_color = "0;34"; /* Blue for Fedora */
3603 }
c846ff47
LP
3604
3605#elif defined(TARGET_SUSE)
c846ff47 3606
10aa7034
LP
3607 if (!pretty_name) {
3608 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
c846ff47 3609
10aa7034
LP
3610 if (r != -ENOENT)
3611 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
6f9a471a 3612 }
10aa7034 3613 }
c846ff47 3614
10aa7034
LP
3615 if (!ansi_color)
3616 const_color = "0;32"; /* Green for openSUSE */
5a6225fd 3617
0d37b36b 3618#elif defined(TARGET_GENTOO)
0d37b36b 3619
10aa7034
LP
3620 if (!pretty_name) {
3621 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
0d37b36b 3622
10aa7034
LP
3623 if (r != -ENOENT)
3624 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
6f9a471a 3625 }
10aa7034 3626 }
0d37b36b 3627
10aa7034
LP
3628 if (!ansi_color)
3629 const_color = "1;34"; /* Light Blue for Gentoo */
5a6225fd 3630
a338bab5
AS
3631#elif defined(TARGET_ALTLINUX)
3632
3633 if (!pretty_name) {
3634 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3635
3636 if (r != -ENOENT)
3637 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
6f9a471a 3638 }
a338bab5
AS
3639 }
3640
3641 if (!ansi_color)
3642 const_color = "0;36"; /* Cyan for ALTLinux */
3643
3644
5a6225fd 3645#elif defined(TARGET_DEBIAN)
5a6225fd 3646
10aa7034 3647 if (!pretty_name) {
22927a36 3648 char *version;
c8bffa43 3649
22927a36 3650 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
5a6225fd 3651
10aa7034
LP
3652 if (r != -ENOENT)
3653 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
22927a36 3654 } else {
22927a36
MB
3655 pretty_name = strappend("Debian ", version);
3656 free(version);
c8bffa43
LP
3657
3658 if (!pretty_name)
3659 log_warning("Failed to allocate Debian version string.");
22927a36 3660 }
10aa7034 3661 }
5a6225fd 3662
10aa7034
LP
3663 if (!ansi_color)
3664 const_color = "1;31"; /* Light Red for Debian */
5a6225fd 3665
274914f9 3666#elif defined(TARGET_UBUNTU)
10aa7034
LP
3667
3668 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3669 "DISTRIB_DESCRIPTION", &pretty_name,
3670 NULL)) < 0) {
3671
3672 if (r != -ENOENT)
3673 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3674 }
3675
3676 if (!ansi_color)
3677 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3678
1de4d79b
AB
3679#elif defined(TARGET_MANDRIVA)
3680
3681 if (!pretty_name) {
3682 char *s, *p;
3683
3684 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3685 if (r != -ENOENT)
3686 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3687 } else {
3688 p = strstr(s, " release ");
3689 if (p) {
3690 *p = '\0';
3691 p += 9;
3692 p[strcspn(p, " ")] = '\0';
3693
3694 /* This corresponds to standard rc.sysinit */
3695 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3696 const_color = "1;36";
3697 else
3698 log_warning("Failed to allocate Mandriva version string.");
3699 } else
3700 log_warning("Failed to parse /etc/mandriva-release");
3701 free(s);
3702 }
3703 }
54e4fdef 3704#elif defined(TARGET_MEEGO)
1de4d79b 3705
54e4fdef
CF
3706 if (!pretty_name) {
3707 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3708
3709 if (r != -ENOENT)
3710 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3711 }
3712 }
3713
3714 if (!ansi_color)
3715 const_color = "1;35"; /* Bright Magenta for MeeGo */
c846ff47 3716#endif
10aa7034
LP
3717
3718 if (!pretty_name && !const_pretty)
3719 const_pretty = "Linux";
3720
3721 if (!ansi_color && !const_color)
3722 const_color = "1";
3723
da71f23c 3724 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
10aa7034
LP
3725 const_color ? const_color : ansi_color,
3726 const_pretty ? const_pretty : pretty_name);
86a3475b
LP
3727
3728 free(ansi_color);
3729 free(pretty_name);
c846ff47
LP
3730}
3731
fab56fc5
LP
3732char *replace_env(const char *format, char **env) {
3733 enum {
3734 WORD,
c24eb49e 3735 CURLY,
fab56fc5
LP
3736 VARIABLE
3737 } state = WORD;
3738
3739 const char *e, *word = format;
3740 char *r = NULL, *k;
3741
3742 assert(format);
3743
3744 for (e = format; *e; e ++) {
3745
3746 switch (state) {
3747
3748 case WORD:
3749 if (*e == '$')
c24eb49e 3750 state = CURLY;
fab56fc5
LP
3751 break;
3752
c24eb49e
LP
3753 case CURLY:
3754 if (*e == '{') {
fab56fc5
LP
3755 if (!(k = strnappend(r, word, e-word-1)))
3756 goto fail;
3757
3758 free(r);
3759 r = k;
3760
3761 word = e-1;
3762 state = VARIABLE;
3763
3764 } else if (*e == '$') {
3765 if (!(k = strnappend(r, word, e-word)))
3766 goto fail;
3767
3768 free(r);
3769 r = k;
3770
3771 word = e+1;
3772 state = WORD;
3773 } else
3774 state = WORD;
3775 break;
3776
3777 case VARIABLE:
c24eb49e 3778 if (*e == '}') {
b95cf362 3779 const char *t;
fab56fc5 3780
b95cf362
LP
3781 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3782 t = "";
fab56fc5 3783
b95cf362
LP
3784 if (!(k = strappend(r, t)))
3785 goto fail;
fab56fc5 3786
b95cf362
LP
3787 free(r);
3788 r = k;
fab56fc5 3789
b95cf362 3790 word = e+1;
fab56fc5
LP
3791 state = WORD;
3792 }
3793 break;
3794 }
3795 }
3796
3797 if (!(k = strnappend(r, word, e-word)))
3798 goto fail;
3799
3800 free(r);
3801 return k;
3802
3803fail:
3804 free(r);
3805 return NULL;
3806}
3807
3808char **replace_env_argv(char **argv, char **env) {
3809 char **r, **i;
c24eb49e
LP
3810 unsigned k = 0, l = 0;
3811
3812 l = strv_length(argv);
fab56fc5 3813
c24eb49e 3814 if (!(r = new(char*, l+1)))
fab56fc5
LP
3815 return NULL;
3816
3817 STRV_FOREACH(i, argv) {
c24eb49e
LP
3818
3819 /* If $FOO appears as single word, replace it by the split up variable */
b95cf362
LP
3820 if ((*i)[0] == '$' && (*i)[1] != '{') {
3821 char *e;
3822 char **w, **m;
3823 unsigned q;
c24eb49e 3824
b95cf362 3825 if ((e = strv_env_get(env, *i+1))) {
c24eb49e
LP
3826
3827 if (!(m = strv_split_quoted(e))) {
3828 r[k] = NULL;
3829 strv_free(r);
3830 return NULL;
3831 }
b95cf362
LP
3832 } else
3833 m = NULL;
c24eb49e 3834
b95cf362
LP
3835 q = strv_length(m);
3836 l = l + q - 1;
c24eb49e 3837
b95cf362
LP
3838 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3839 r[k] = NULL;
3840 strv_free(r);
3841 strv_free(m);
3842 return NULL;
3843 }
c24eb49e 3844
b95cf362
LP
3845 r = w;
3846 if (m) {
c24eb49e
LP
3847 memcpy(r + k, m, q * sizeof(char*));
3848 free(m);
c24eb49e 3849 }
b95cf362
LP
3850
3851 k += q;
3852 continue;
c24eb49e
LP
3853 }
3854
3855 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
fab56fc5
LP
3856 if (!(r[k++] = replace_env(*i, env))) {
3857 strv_free(r);
3858 return NULL;
3859 }
3860 }
3861
3862 r[k] = NULL;
3863 return r;
3864}
3865
fa776d8e
LP
3866int columns(void) {
3867 static __thread int parsed_columns = 0;
3868 const char *e;
3869
3bfc7184 3870 if (_likely_(parsed_columns > 0))
fa776d8e
LP
3871 return parsed_columns;
3872
3873 if ((e = getenv("COLUMNS")))
3874 parsed_columns = atoi(e);
3875
3876 if (parsed_columns <= 0) {
3877 struct winsize ws;
3878 zero(ws);
3879
9ed95f43 3880 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
fa776d8e
LP
3881 parsed_columns = ws.ws_col;
3882 }
3883
3884 if (parsed_columns <= 0)
3885 parsed_columns = 80;
3886
3887 return parsed_columns;
3888}
3889
b4f10a5e
LP
3890int running_in_chroot(void) {
3891 struct stat a, b;
3892
3893 zero(a);
3894 zero(b);
3895
3896 /* Only works as root */
3897
3898 if (stat("/proc/1/root", &a) < 0)
3899 return -errno;
3900
3901 if (stat("/", &b) < 0)
3902 return -errno;
3903
3904 return
3905 a.st_dev != b.st_dev ||
3906 a.st_ino != b.st_ino;
3907}
3908
8fe914ec
LP
3909char *ellipsize(const char *s, unsigned length, unsigned percent) {
3910 size_t l, x;
3911 char *r;
3912
3913 assert(s);
3914 assert(percent <= 100);
3915 assert(length >= 3);
3916
3917 l = strlen(s);
3918
3919 if (l <= 3 || l <= length)
3920 return strdup(s);
3921
3922 if (!(r = new0(char, length+1)))
3923 return r;
3924
3925 x = (length * percent) / 100;
3926
3927 if (x > length - 3)
3928 x = length - 3;
3929
3930 memcpy(r, s, x);
3931 r[x] = '.';
3932 r[x+1] = '.';
3933 r[x+2] = '.';
3934 memcpy(r + x + 3,
3935 s + l - (length - x - 3),
3936 length - x - 3);
3937
3938 return r;
3939}
3940
f6144808
LP
3941int touch(const char *path) {
3942 int fd;
3943
3944 assert(path);
3945
14f3c825 3946 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
f6144808
LP
3947 return -errno;
3948
3949 close_nointr_nofail(fd);
3950 return 0;
3951}
afea26ad 3952
97c4a07d 3953char *unquote(const char *s, const char* quotes) {
11ce3427
LP
3954 size_t l;
3955 assert(s);
3956
3957 if ((l = strlen(s)) < 2)
3958 return strdup(s);
3959
97c4a07d 3960 if (strchr(quotes, s[0]) && s[l-1] == s[0])
11ce3427
LP
3961 return strndup(s+1, l-2);
3962
3963 return strdup(s);
3964}
3965
5f7c426e
LP
3966char *normalize_env_assignment(const char *s) {
3967 char *name, *value, *p, *r;
3968
3969 p = strchr(s, '=');
3970
3971 if (!p) {
3972 if (!(r = strdup(s)))
3973 return NULL;
3974
3975 return strstrip(r);
3976 }
3977
3978 if (!(name = strndup(s, p - s)))
3979 return NULL;
3980
3981 if (!(p = strdup(p+1))) {
3982 free(name);
3983 return NULL;
3984 }
3985
3986 value = unquote(strstrip(p), QUOTES);
3987 free(p);
3988
3989 if (!value) {
5f7c426e
LP
3990 free(name);
3991 return NULL;
3992 }
3993
3994 if (asprintf(&r, "%s=%s", name, value) < 0)
3995 r = NULL;
3996
3997 free(value);
3998 free(name);
3999
4000 return r;
4001}
4002
8e12a6ae 4003int wait_for_terminate(pid_t pid, siginfo_t *status) {
1968a360
LP
4004 siginfo_t dummy;
4005
2e78aa99 4006 assert(pid >= 1);
1968a360
LP
4007
4008 if (!status)
4009 status = &dummy;
2e78aa99
LP
4010
4011 for (;;) {
8e12a6ae
LP
4012 zero(*status);
4013
4014 if (waitid(P_PID, pid, status, WEXITED) < 0) {
2e78aa99
LP
4015
4016 if (errno == EINTR)
4017 continue;
4018
4019 return -errno;
4020 }
4021
4022 return 0;
4023 }
4024}
4025
97c4a07d
LP
4026int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4027 int r;
4028 siginfo_t status;
4029
4030 assert(name);
4031 assert(pid > 1);
4032
4033 if ((r = wait_for_terminate(pid, &status)) < 0) {
4034 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4035 return r;
4036 }
4037
4038 if (status.si_code == CLD_EXITED) {
4039 if (status.si_status != 0) {
4040 log_warning("%s failed with error code %i.", name, status.si_status);
0a27cf3f 4041 return status.si_status;
97c4a07d
LP
4042 }
4043
4044 log_debug("%s succeeded.", name);
4045 return 0;
4046
4047 } else if (status.si_code == CLD_KILLED ||
4048 status.si_code == CLD_DUMPED) {
4049
4050 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4051 return -EPROTO;
4052 }
4053
4054 log_warning("%s failed due to unknown reason.", name);
4055 return -EPROTO;
4056
4057}
4058
3c14d26c 4059void freeze(void) {
720ce21d
LP
4060
4061 /* Make sure nobody waits for us on a socket anymore */
4062 close_all_fds(NULL, 0);
4063
c29597a1
LP
4064 sync();
4065
3c14d26c
LP
4066 for (;;)
4067 pause();
4068}
4069
00dc5d76
LP
4070bool null_or_empty(struct stat *st) {
4071 assert(st);
4072
4073 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4074 return true;
4075
c8f26f42 4076 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
00dc5d76
LP
4077 return true;
4078
4079 return false;
4080}
4081
83096483
LP
4082int null_or_empty_path(const char *fn) {
4083 struct stat st;
4084
4085 assert(fn);
4086
4087 if (stat(fn, &st) < 0)
4088 return -errno;
4089
4090 return null_or_empty(&st);
4091}
4092
a247755d 4093DIR *xopendirat(int fd, const char *name, int flags) {
c4731d11
LP
4094 int nfd;
4095 DIR *d;
4096
4097 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4098 return NULL;
4099
4100 if (!(d = fdopendir(nfd))) {
4101 close_nointr_nofail(nfd);
4102 return NULL;
4103 }
4104
4105 return d;
3b63d2d3
LP
4106}
4107
8a0867d6
LP
4108int signal_from_string_try_harder(const char *s) {
4109 int signo;
4110 assert(s);
4111
4112 if ((signo = signal_from_string(s)) <= 0)
4113 if (startswith(s, "SIG"))
4114 return signal_from_string(s+3);
4115
4116 return signo;
4117}
4118
10717a1a
LP
4119void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4120
4121 assert(f);
4122 assert(name);
4123 assert(t);
4124
4125 if (!dual_timestamp_is_set(t))
4126 return;
4127
4128 fprintf(f, "%s=%llu %llu\n",
4129 name,
4130 (unsigned long long) t->realtime,
4131 (unsigned long long) t->monotonic);
4132}
4133
799fd0fd 4134void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
10717a1a
LP
4135 unsigned long long a, b;
4136
10717a1a
LP
4137 assert(value);
4138 assert(t);
4139
4140 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4141 log_debug("Failed to parse finish timestamp value %s", value);
4142 else {
4143 t->realtime = a;
4144 t->monotonic = b;
4145 }
4146}
4147
e23a0ce8
LP
4148char *fstab_node_to_udev_node(const char *p) {
4149 char *dn, *t, *u;
4150 int r;
4151
4152 /* FIXME: to follow udev's logic 100% we need to leave valid
4153 * UTF8 chars unescaped */
4154
4155 if (startswith(p, "LABEL=")) {
4156
4157 if (!(u = unquote(p+6, "\"\'")))
4158 return NULL;
4159
4160 t = xescape(u, "/ ");
4161 free(u);
4162
4163 if (!t)
4164 return NULL;
4165
4166 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4167 free(t);
4168
4169 if (r < 0)
4170 return NULL;
4171
4172 return dn;
4173 }
4174
4175 if (startswith(p, "UUID=")) {
4176
4177 if (!(u = unquote(p+5, "\"\'")))
4178 return NULL;
4179
4180 t = xescape(u, "/ ");
4181 free(u);
4182
4183 if (!t)
4184 return NULL;
4185
0058d7b9 4186 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
e23a0ce8
LP
4187 free(t);
4188
4189 if (r < 0)
4190 return NULL;
4191
4192 return dn;
4193 }
4194
4195 return strdup(p);
4196}
4197
e9ddabc2
LP
4198void filter_environ(const char *prefix) {
4199 int i, j;
4200 assert(prefix);
4201
4202 if (!environ)
4203 return;
4204
4205 for (i = 0, j = 0; environ[i]; i++) {
4206
4207 if (startswith(environ[i], prefix))
4208 continue;
4209
4210 environ[j++] = environ[i];
4211 }
4212
4213 environ[j] = NULL;
4214}
4215
f212ac12
LP
4216bool tty_is_vc(const char *tty) {
4217 assert(tty);
4218
4219 if (startswith(tty, "/dev/"))
4220 tty += 5;
4221
98a28fef
LP
4222 return vtnr_from_tty(tty) >= 0;
4223}
4224
4225int vtnr_from_tty(const char *tty) {
4226 int i, r;
4227
4228 assert(tty);
4229
4230 if (startswith(tty, "/dev/"))
4231 tty += 5;
4232
4233 if (!startswith(tty, "tty") )
4234 return -EINVAL;
4235
4236 if (tty[3] < '0' || tty[3] > '9')
4237 return -EINVAL;
4238
4239 r = safe_atoi(tty+3, &i);
4240 if (r < 0)
4241 return r;
4242
4243 if (i < 0 || i > 63)
4244 return -EINVAL;
4245
4246 return i;
f212ac12
LP
4247}
4248
e3aa71c3 4249const char *default_term_for_tty(const char *tty) {
3030ccd7
LP
4250 char *active = NULL;
4251 const char *term;
4252
e3aa71c3
LP
4253 assert(tty);
4254
4255 if (startswith(tty, "/dev/"))
4256 tty += 5;
4257
3030ccd7
LP
4258 /* Resolve where /dev/console is pointing when determining
4259 * TERM */
4260 if (streq(tty, "console"))
4261 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
079a09fb
LP
4262 /* If multiple log outputs are configured the
4263 * last one is what /dev/console points to */
4264 if ((tty = strrchr(active, ' ')))
4265 tty++;
4266 else
4267 tty = active;
3030ccd7
LP
4268 }
4269
f212ac12 4270 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
3030ccd7 4271 free(active);
e3aa71c3 4272
3030ccd7 4273 return term;
e3aa71c3
LP
4274}
4275
07faed4f
LP
4276/* Returns a short identifier for the various VM implementations */
4277int detect_vm(const char **id) {
46a08e38
LP
4278
4279#if defined(__i386__) || defined(__x86_64__)
4280
4281 /* Both CPUID and DMI are x86 specific interfaces... */
4282
721bca57 4283 static const char *const dmi_vendors[] = {
46a08e38
LP
4284 "/sys/class/dmi/id/sys_vendor",
4285 "/sys/class/dmi/id/board_vendor",
4286 "/sys/class/dmi/id/bios_vendor"
4287 };
4288
4e08da90 4289 static const char dmi_vendor_table[] =
07faed4f
LP
4290 "QEMU\0" "qemu\0"
4291 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4292 "VMware\0" "vmware\0"
4293 "VMW\0" "vmware\0"
4294 "Microsoft Corporation\0" "microsoft\0"
4295 "innotek GmbH\0" "oracle\0"
4296 "Xen\0" "xen\0"
34df5a34 4297 "Bochs\0" "bochs\0";
07faed4f 4298
4e08da90 4299 static const char cpuid_vendor_table[] =
07faed4f
LP
4300 "XenVMMXenVMM\0" "xen\0"
4301 "KVMKVMKVM\0" "kvm\0"
4302 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
4303 "VMwareVMware\0" "vmware\0"
4304 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
34df5a34 4305 "Microsoft Hv\0" "microsoft\0";
07faed4f
LP
4306
4307 uint32_t eax, ecx;
46a08e38
LP
4308 union {
4309 uint32_t sig32[3];
4310 char text[13];
4311 } sig;
46a08e38 4312 unsigned i;
07faed4f 4313 const char *j, *k;
721bca57 4314 bool hypervisor;
46a08e38
LP
4315
4316 /* http://lwn.net/Articles/301888/ */
4317 zero(sig);
4318
46a08e38
LP
4319#if defined (__i386__)
4320#define REG_a "eax"
4321#define REG_b "ebx"
4322#elif defined (__amd64__)
4323#define REG_a "rax"
4324#define REG_b "rbx"
4325#endif
4326
07faed4f
LP
4327 /* First detect whether there is a hypervisor */
4328 eax = 1;
46a08e38
LP
4329 __asm__ __volatile__ (
4330 /* ebx/rbx is being used for PIC! */
4331 " push %%"REG_b" \n\t"
4332 " cpuid \n\t"
46a08e38
LP
4333 " pop %%"REG_b" \n\t"
4334
07faed4f 4335 : "=a" (eax), "=c" (ecx)
46a08e38
LP
4336 : "0" (eax)
4337 );
4338
ec195f55 4339 hypervisor = !!(ecx & 0x80000000U);
721bca57
LP
4340
4341 if (hypervisor) {
07faed4f
LP
4342
4343 /* There is a hypervisor, see what it is */
4344 eax = 0x40000000U;
4345 __asm__ __volatile__ (
4346 /* ebx/rbx is being used for PIC! */
4347 " push %%"REG_b" \n\t"
4348 " cpuid \n\t"
4349 " mov %%ebx, %1 \n\t"
4350 " pop %%"REG_b" \n\t"
4351
4352 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
4353 : "0" (eax)
4354 );
4355
4356 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
4357 if (streq(sig.text, j)) {
4358
4359 if (id)
4360 *id = k;
4361
4362 return 1;
4363 }
721bca57 4364 }
07faed4f 4365
721bca57
LP
4366 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
4367 char *s;
4368 int r;
4369 const char *found = NULL;
4370
4371 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
4372 if (r != -ENOENT)
4373 return r;
4374
4375 continue;
4376 }
4377
4378 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
4379 if (startswith(s, j))
4380 found = k;
4381 free(s);
4382
4383 if (found) {
4384 if (id)
4385 *id = found;
4386
4387 return 1;
4388 }
4389 }
4390
4391 if (hypervisor) {
07faed4f
LP
4392 if (id)
4393 *id = "other";
4394
4395 return 1;
4396 }
46a08e38 4397
721bca57 4398#endif
07faed4f
LP
4399 return 0;
4400}
4401
ef2df9f4 4402int detect_container(const char **id) {
f9b9232b
LP
4403 FILE *f;
4404
ef2df9f4
LP
4405 /* Unfortunately many of these operations require root access
4406 * in one way or another */
f9b9232b 4407
ef2df9f4
LP
4408 if (geteuid() != 0)
4409 return -EPERM;
4410
4411 if (running_in_chroot() > 0) {
f9b9232b
LP
4412
4413 if (id)
ef2df9f4 4414 *id = "chroot";
f9b9232b
LP
4415
4416 return 1;
4417 }
07faed4f 4418
ef2df9f4
LP
4419 /* /proc/vz exists in container and outside of the container,
4420 * /proc/bc only outside of the container. */
4421 if (access("/proc/vz", F_OK) >= 0 &&
4422 access("/proc/bc", F_OK) < 0) {
07faed4f 4423
ef2df9f4
LP
4424 if (id)
4425 *id = "openvz";
4426
4427 return 1;
f9b9232b 4428 }
07faed4f 4429
ccaa6149 4430 if ((f = fopen("/proc/self/cgroup", "re"))) {
f9b9232b
LP
4431
4432 for (;;) {
4433 char line[LINE_MAX], *p;
4434
4435 if (!fgets(line, sizeof(line), f))
4436 break;
4437
4438 if (!(p = strchr(strstrip(line), ':')))
4439 continue;
4440
4441 if (strncmp(p, ":ns:", 4))
4442 continue;
4443
4444 if (!streq(p, ":ns:/")) {
4445 fclose(f);
4446
ef2df9f4 4447 if (id)
28cf382a 4448 *id = "pidns";
ef2df9f4
LP
4449
4450 return 1;
f9b9232b
LP
4451 }
4452 }
4453
4454 fclose(f);
07faed4f
LP
4455 }
4456
ef2df9f4
LP
4457 return 0;
4458}
4459
4460/* Returns a short identifier for the various VM/container implementations */
4461int detect_virtualization(const char **id) {
4462 static __thread const char *cached_id = NULL;
4463 const char *_id;
4464 int r;
4465
3bfc7184 4466 if (_likely_(cached_id)) {
ef2df9f4
LP
4467
4468 if (cached_id == (const char*) -1)
4469 return 0;
4470
4471 if (id)
4472 *id = cached_id;
4473
4474 return 1;
f9b9232b 4475 }
07faed4f 4476
ef2df9f4
LP
4477 if ((r = detect_container(&_id)) != 0)
4478 goto finish;
4479
f9b9232b 4480 r = detect_vm(&_id);
07faed4f 4481
f9b9232b 4482finish:
ef2df9f4 4483 if (r > 0) {
f9b9232b 4484 cached_id = _id;
07faed4f 4485
ef2df9f4
LP
4486 if (id)
4487 *id = _id;
4488 } else if (r == 0)
4489 cached_id = (const char*) -1;
f9b9232b
LP
4490
4491 return r;
46a08e38
LP
4492}
4493
fb19a739
LP
4494bool dirent_is_file(struct dirent *de) {
4495 assert(de);
4496
4497 if (ignore_file(de->d_name))
4498 return false;
4499
4500 if (de->d_type != DT_REG &&
4501 de->d_type != DT_LNK &&
4502 de->d_type != DT_UNKNOWN)
4503 return false;
4504
4505 return true;
4506}
4507
83cc030f
LP
4508void execute_directory(const char *directory, DIR *d, char *argv[]) {
4509 DIR *_d = NULL;
4510 struct dirent *de;
4511 Hashmap *pids = NULL;
4512
4513 assert(directory);
4514
4515 /* Executes all binaries in a directory in parallel and waits
4516 * until all they all finished. */
4517
4518 if (!d) {
4519 if (!(_d = opendir(directory))) {
4520
4521 if (errno == ENOENT)
4522 return;
4523
4524 log_error("Failed to enumerate directory %s: %m", directory);
4525 return;
4526 }
4527
4528 d = _d;
4529 }
4530
4531 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4532 log_error("Failed to allocate set.");
4533 goto finish;
4534 }
4535
4536 while ((de = readdir(d))) {
4537 char *path;
4538 pid_t pid;
4539 int k;
4540
fb19a739 4541 if (!dirent_is_file(de))
83cc030f
LP
4542 continue;
4543
4544 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4545 log_error("Out of memory");
4546 continue;
4547 }
4548
4549 if ((pid = fork()) < 0) {
4550 log_error("Failed to fork: %m");
4551 free(path);
4552 continue;
4553 }
4554
4555 if (pid == 0) {
4556 char *_argv[2];
4557 /* Child */
4558
4559 if (!argv) {
4560 _argv[0] = path;
4561 _argv[1] = NULL;
4562 argv = _argv;
4563 } else
4564 if (!argv[0])
4565 argv[0] = path;
4566
4567 execv(path, argv);
4568
4569 log_error("Failed to execute %s: %m", path);
4570 _exit(EXIT_FAILURE);
4571 }
4572
4573 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4574
4575 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4576 log_error("Failed to add PID to set: %s", strerror(-k));
4577 free(path);
4578 }
4579 }
4580
4581 while (!hashmap_isempty(pids)) {
4582 siginfo_t si;
4583 char *path;
4584
4585 zero(si);
4586 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4587
4588 if (errno == EINTR)
4589 continue;
4590
4591 log_error("waitid() failed: %m");
4592 goto finish;
4593 }
4594
4595 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4596 if (!is_clean_exit(si.si_code, si.si_status)) {
4597 if (si.si_code == CLD_EXITED)
4598 log_error("%s exited with exit status %i.", path, si.si_status);
4599 else
4600 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4601 } else
4602 log_debug("%s exited successfully.", path);
4603
4604 free(path);
4605 }
4606 }
4607
4608finish:
4609 if (_d)
4610 closedir(_d);
4611
4612 if (pids)
4613 hashmap_free_free(pids);
4614}
4615
430c18ed
LP
4616int kill_and_sigcont(pid_t pid, int sig) {
4617 int r;
4618
4619 r = kill(pid, sig) < 0 ? -errno : 0;
4620
4621 if (r >= 0)
4622 kill(pid, SIGCONT);
4623
4624 return r;
4625}
4626
05feefe0
LP
4627bool nulstr_contains(const char*nulstr, const char *needle) {
4628 const char *i;
4629
4630 if (!nulstr)
4631 return false;
4632
4633 NULSTR_FOREACH(i, nulstr)
4634 if (streq(i, needle))
4635 return true;
4636
4637 return false;
4638}
4639
6faa1114 4640bool plymouth_running(void) {
9408a2d2 4641 return access("/run/plymouth/pid", F_OK) >= 0;
6faa1114
LP
4642}
4643
7c3b203c
LP
4644void parse_syslog_priority(char **p, int *priority) {
4645 int a = 0, b = 0, c = 0;
4646 int k;
4647
4648 assert(p);
4649 assert(*p);
4650 assert(priority);
4651
4652 if ((*p)[0] != '<')
4653 return;
4654
4655 if (!strchr(*p, '>'))
4656 return;
4657
4658 if ((*p)[2] == '>') {
4659 c = undecchar((*p)[1]);
4660 k = 3;
4661 } else if ((*p)[3] == '>') {
4662 b = undecchar((*p)[1]);
4663 c = undecchar((*p)[2]);
4664 k = 4;
4665 } else if ((*p)[4] == '>') {
4666 a = undecchar((*p)[1]);
4667 b = undecchar((*p)[2]);
4668 c = undecchar((*p)[3]);
4669 k = 5;
4670 } else
4671 return;
4672
4673 if (a < 0 || b < 0 || c < 0)
4674 return;
4675
4676 *priority = a*100+b*10+c;
4677 *p += k;
4678}
4679
ac123445
LP
4680int have_effective_cap(int value) {
4681 cap_t cap;
4682 cap_flag_value_t fv;
4683 int r;
4684
4685 if (!(cap = cap_get_proc()))
4686 return -errno;
4687
4688 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4689 r = -errno;
4690 else
4691 r = fv == CAP_SET;
4692
4693 cap_free(cap);
4694 return r;
4695}
4696
9beb3f4d
LP
4697char* strshorten(char *s, size_t l) {
4698 assert(s);
4699
4700 if (l < strlen(s))
4701 s[l] = 0;
4702
4703 return s;
4704}
4705
4706static bool hostname_valid_char(char c) {
4707 return
4708 (c >= 'a' && c <= 'z') ||
4709 (c >= 'A' && c <= 'Z') ||
4710 (c >= '0' && c <= '9') ||
4711 c == '-' ||
4712 c == '_' ||
4713 c == '.';
4714}
4715
4716bool hostname_is_valid(const char *s) {
4717 const char *p;
4718
4719 if (isempty(s))
4720 return false;
4721
4722 for (p = s; *p; p++)
4723 if (!hostname_valid_char(*p))
4724 return false;
4725
4726 if (p-s > HOST_NAME_MAX)
4727 return false;
4728
4729 return true;
4730}
4731
4732char* hostname_cleanup(char *s) {
4733 char *p, *d;
4734
4735 for (p = s, d = s; *p; p++)
4736 if ((*p >= 'a' && *p <= 'z') ||
4737 (*p >= 'A' && *p <= 'Z') ||
4738 (*p >= '0' && *p <= '9') ||
4739 *p == '-' ||
4740 *p == '_' ||
4741 *p == '.')
4742 *(d++) = *p;
4743
4744 *d = 0;
4745
4746 strshorten(s, HOST_NAME_MAX);
4747 return s;
4748}
4749
1325aa42
LP
4750int pipe_eof(int fd) {
4751 struct pollfd pollfd;
4752 int r;
4753
4754 zero(pollfd);
4755 pollfd.fd = fd;
4756 pollfd.events = POLLIN|POLLHUP;
4757
4758 r = poll(&pollfd, 1, 0);
4759 if (r < 0)
4760 return -errno;
4761
4762 if (r == 0)
4763 return 0;
4764
4765 return pollfd.revents & POLLHUP;
4766}
4767
5a3ab509
LP
4768int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4769 FILE *f;
4770 char *t;
4771 const char *fn;
4772 size_t k;
4773 int fd;
4774
4775 assert(path);
4776 assert(_f);
4777 assert(_temp_path);
4778
4779 t = new(char, strlen(path) + 1 + 6 + 1);
4780 if (!t)
4781 return -ENOMEM;
4782
4783 fn = file_name_from_path(path);
4784 k = fn-path;
4785 memcpy(t, path, k);
4786 t[k] = '.';
4787 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4788
4789 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4790 if (fd < 0) {
4791 free(t);
4792 return -errno;
4793 }
4794
4795 f = fdopen(fd, "we");
4796 if (!f) {
4797 unlink(t);
4798 free(t);
4799 return -errno;
4800 }
4801
4802 *_f = f;
4803 *_temp_path = t;
4804
4805 return 0;
4806}
4807
6ea832a2 4808int terminal_vhangup_fd(int fd) {
5a3ab509
LP
4809 assert(fd >= 0);
4810
6ea832a2
LP
4811 if (ioctl(fd, TIOCVHANGUP) < 0)
4812 return -errno;
4813
4814 return 0;
4815}
4816
4817int terminal_vhangup(const char *name) {
4818 int fd, r;
4819
4820 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4821 if (fd < 0)
4822 return fd;
4823
4824 r = terminal_vhangup_fd(fd);
4825 close_nointr_nofail(fd);
4826
4827 return r;
4828}
4829
4830int vt_disallocate(const char *name) {
4831 int fd, r;
4832 unsigned u;
6ea832a2
LP
4833
4834 /* Deallocate the VT if possible. If not possible
4835 * (i.e. because it is the active one), at least clear it
4836 * entirely (including the scrollback buffer) */
4837
b83bc4e9
LP
4838 if (!startswith(name, "/dev/"))
4839 return -EINVAL;
4840
4841 if (!tty_is_vc(name)) {
4842 /* So this is not a VT. I guess we cannot deallocate
4843 * it then. But let's at least clear the screen */
4844
4845 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4846 if (fd < 0)
4847 return fd;
4848
8585357a
LP
4849 loop_write(fd,
4850 "\033[r" /* clear scrolling region */
4851 "\033[H" /* move home */
4852 "\033[2J", /* clear screen */
4853 10, false);
b83bc4e9
LP
4854 close_nointr_nofail(fd);
4855
4856 return 0;
4857 }
6ea832a2
LP
4858
4859 if (!startswith(name, "/dev/tty"))
4860 return -EINVAL;
4861
4862 r = safe_atou(name+8, &u);
4863 if (r < 0)
4864 return r;
4865
4866 if (u <= 0)
b83bc4e9 4867 return -EINVAL;
6ea832a2 4868
b83bc4e9 4869 /* Try to deallocate */
6ea832a2
LP
4870 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4871 if (fd < 0)
4872 return fd;
4873
4874 r = ioctl(fd, VT_DISALLOCATE, u);
b83bc4e9 4875 close_nointr_nofail(fd);
6ea832a2 4876
b83bc4e9
LP
4877 if (r >= 0)
4878 return 0;
6ea832a2 4879
b83bc4e9 4880 if (errno != EBUSY)
6ea832a2 4881 return -errno;
6ea832a2 4882
b83bc4e9
LP
4883 /* Couldn't deallocate, so let's clear it fully with
4884 * scrollback */
4885 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
6ea832a2 4886 if (fd < 0)
b83bc4e9 4887 return fd;
6ea832a2 4888
8585357a
LP
4889 loop_write(fd,
4890 "\033[r" /* clear scrolling region */
4891 "\033[H" /* move home */
4892 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4893 10, false);
b83bc4e9 4894 close_nointr_nofail(fd);
6ea832a2 4895
b83bc4e9 4896 return 0;
6ea832a2
LP
4897}
4898
db1413d7
KS
4899
4900static int file_is_conf(const struct dirent *d, const char *suffix) {
4901 assert(d);
4902
4903 if (ignore_file(d->d_name))
4904 return 0;
4905
4906 if (d->d_type != DT_REG &&
4907 d->d_type != DT_LNK &&
4908 d->d_type != DT_UNKNOWN)
4909 return 0;
4910
4911 return endswith(d->d_name, suffix);
4912}
4913
4914static int files_add(Hashmap *h, const char *path, const char *suffix) {
4915 DIR *dir;
f782b8d0 4916 struct dirent buffer, *de;
db1413d7
KS
4917 int r = 0;
4918
4919 dir = opendir(path);
4920 if (!dir) {
4921 if (errno == ENOENT)
4922 return 0;
4923 return -errno;
4924 }
4925
f782b8d0
LP
4926 for (;;) {
4927 int k;
223a3558 4928 char *p, *f;
f782b8d0
LP
4929
4930 k = readdir_r(dir, &buffer, &de);
4931 if (k != 0) {
4932 r = -k;
4933 goto finish;
4934 }
4935
4936 if (!de)
4937 break;
db1413d7
KS
4938
4939 if (!file_is_conf(de, suffix))
4940 continue;
4941
223a3558 4942 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
db1413d7
KS
4943 r = -ENOMEM;
4944 goto finish;
4945 }
4946
223a3558
KS
4947 f = canonicalize_file_name(p);
4948 if (!f) {
4949 log_error("Failed to canonicalize file name '%s': %m", p);
4950 free(p);
4951 continue;
4952 }
4953 free(p);
4954
db1413d7 4955 log_debug("found: %s\n", f);
f782b8d0 4956 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
db1413d7
KS
4957 free(f);
4958 }
4959
4960finish:
4961 closedir(dir);
4962 return r;
4963}
4964
4965static int base_cmp(const void *a, const void *b) {
4966 const char *s1, *s2;
4967
4968 s1 = *(char * const *)a;
4969 s2 = *(char * const *)b;
4970 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4971}
4972
44143309 4973int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
223a3558
KS
4974 Hashmap *fh = NULL;
4975 char **dirs = NULL;
db1413d7 4976 char **files = NULL;
223a3558 4977 char **p;
db1413d7 4978 va_list ap;
44143309 4979 int r = 0;
db1413d7 4980
223a3558
KS
4981 va_start(ap, dir);
4982 dirs = strv_new_ap(dir, ap);
4983 va_end(ap);
4984 if (!dirs) {
4985 r = -ENOMEM;
4986 goto finish;
4987 }
4988 if (!strv_path_canonicalize(dirs)) {
4989 r = -ENOMEM;
4990 goto finish;
4991 }
4992 if (!strv_uniq(dirs)) {
4993 r = -ENOMEM;
4994 goto finish;
4995 }
4996
db1413d7
KS
4997 fh = hashmap_new(string_hash_func, string_compare_func);
4998 if (!fh) {
44143309 4999 r = -ENOMEM;
db1413d7
KS
5000 goto finish;
5001 }
5002
223a3558
KS
5003 STRV_FOREACH(p, dirs) {
5004 if (files_add(fh, *p, suffix) < 0) {
db1413d7 5005 log_error("Failed to search for files.");
44143309 5006 r = -EINVAL;
db1413d7
KS
5007 goto finish;
5008 }
db1413d7 5009 }
db1413d7
KS
5010
5011 files = hashmap_get_strv(fh);
5012 if (files == NULL) {
5013 log_error("Failed to compose list of files.");
44143309 5014 r = -ENOMEM;
db1413d7
KS
5015 goto finish;
5016 }
5017
5018 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
8d0e38a2 5019
db1413d7 5020finish:
223a3558 5021 strv_free(dirs);
db1413d7 5022 hashmap_free(fh);
44143309
KS
5023 *strv = files;
5024 return r;
db1413d7 5025}
7948c4df 5026
2076cf88 5027int hwclock_is_localtime(void) {
7948c4df 5028 FILE *f;
7948c4df
KS
5029 bool local = false;
5030
5031 /*
5032 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
5033 * # /etc/adjtime
2076cf88 5034 * 0.0 0 0
7948c4df
KS
5035 * 0
5036 * UTC
5037 */
5038 f = fopen("/etc/adjtime", "re");
5039 if (f) {
2076cf88
LP
5040 char line[LINE_MAX];
5041 bool b;
5042
5043 b = fgets(line, sizeof(line), f) &&
5044 fgets(line, sizeof(line), f) &&
5045 fgets(line, sizeof(line), f);
5046
7948c4df 5047 fclose(f);
2076cf88
LP
5048
5049 if (!b)
5050 return -EIO;
5051
5052
5053 truncate_nl(line);
5054 local = streq(line, "LOCAL");
5055
5056 } else if (errno != -ENOENT)
5057 return -errno;
5058
7948c4df
KS
5059 return local;
5060}
5061
ff4daf5a 5062int hwclock_apply_localtime_delta(int *min) {
7948c4df 5063 const struct timeval *tv_null = NULL;
2076cf88 5064 struct timespec ts;
7948c4df
KS
5065 struct tm *tm;
5066 int minuteswest;
5067 struct timezone tz;
5068
2076cf88
LP
5069 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
5070 assert_se(tm = localtime(&ts.tv_sec));
7948c4df
KS
5071 minuteswest = tm->tm_gmtoff / 60;
5072
5073 tz.tz_minuteswest = -minuteswest;
5074 tz.tz_dsttime = 0; /* DST_NONE*/
5075
5076 /*
5077 * If the hardware clock does not run in UTC, but in local time:
5078 * The very first time we set the kernel's timezone, it will warp
5079 * the clock so that it runs in UTC instead of local time.
5080 */
5081 if (settimeofday(tv_null, &tz) < 0)
5082 return -errno;
ff4daf5a
KS
5083 if (min)
5084 *min = minuteswest;
5085 return 0;
2076cf88
LP
5086}
5087
5088int hwclock_reset_localtime_delta(void) {
5089 const struct timeval *tv_null = NULL;
5090 struct timezone tz;
5091
5092 tz.tz_minuteswest = 0;
5093 tz.tz_dsttime = 0; /* DST_NONE*/
5094
5095 if (settimeofday(tv_null, &tz) < 0)
5096 return -errno;
5097
5098 return 0;
7948c4df
KS
5099}
5100
5101int hwclock_get_time(struct tm *tm) {
5102 int fd;
5103 int err = 0;
5104
2076cf88
LP
5105 assert(tm);
5106
7948c4df
KS
5107 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
5108 if (fd < 0)
5109 return -errno;
2076cf88
LP
5110
5111 /* This leaves the timezone fields of struct tm
5112 * uninitialized! */
7948c4df
KS
5113 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5114 err = -errno;
2076cf88
LP
5115
5116 /* We don't now daylight saving, so we reset this in order not
5117 * to confused mktime(). */
5118 tm->tm_isdst = -1;
5119
5120 close_nointr_nofail(fd);
7948c4df
KS
5121
5122 return err;
5123}
5124
5125int hwclock_set_time(const struct tm *tm) {
5126 int fd;
5127 int err = 0;
5128
2076cf88
LP
5129 assert(tm);
5130
7948c4df
KS
5131 fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
5132 if (fd < 0)
5133 return -errno;
2076cf88 5134
7948c4df
KS
5135 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5136 err = -errno;
2076cf88
LP
5137
5138 close_nointr_nofail(fd);
7948c4df
KS
5139
5140 return err;
5141}
f41607a6 5142
34ca941c
LP
5143int copy_file(const char *from, const char *to) {
5144 int r, fdf, fdt;
5145
5146 assert(from);
5147 assert(to);
5148
5149 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5150 if (fdf < 0)
5151 return -errno;
5152
5153 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5154 if (fdt < 0) {
5155 close_nointr_nofail(fdf);
5156 return -errno;
5157 }
5158
5159 for (;;) {
5160 char buf[PIPE_BUF];
5161 ssize_t n, k;
5162
5163 n = read(fdf, buf, sizeof(buf));
5164 if (n < 0) {
5165 r = -errno;
5166
5167 close_nointr_nofail(fdf);
5168 close_nointr(fdt);
5169 unlink(to);
5170
5171 return r;
5172 }
5173
5174 if (n == 0)
5175 break;
5176
5177 errno = 0;
5178 k = loop_write(fdt, buf, n, false);
5179 if (n != k) {
5180 r = k < 0 ? k : (errno ? -errno : -EIO);
5181
5182 close_nointr_nofail(fdf);
5183 close_nointr(fdt);
5184
5185 unlink(to);
5186 return r;
5187 }
5188 }
5189
5190 close_nointr_nofail(fdf);
5191 r = close_nointr(fdt);
5192
5193 if (r < 0) {
5194 unlink(to);
5195 return r;
5196 }
5197
5198 return 0;
5199}
5200
5201int symlink_or_copy(const char *from, const char *to) {
5202 char *pf = NULL, *pt = NULL;
5203 struct stat a, b;
5204 int r;
5205
5206 assert(from);
5207 assert(to);
5208
5209 if (parent_of_path(from, &pf) < 0 ||
5210 parent_of_path(to, &pt) < 0) {
5211 r = -ENOMEM;
5212 goto finish;
5213 }
5214
5215 if (stat(pf, &a) < 0 ||
5216 stat(pt, &b) < 0) {
5217 r = -errno;
5218 goto finish;
5219 }
5220
5221 if (a.st_dev != b.st_dev) {
5222 free(pf);
5223 free(pt);
5224
5225 return copy_file(from, to);
5226 }
5227
5228 if (symlink(from, to) < 0) {
5229 r = -errno;
5230 goto finish;
5231 }
5232
5233 r = 0;
5234
5235finish:
5236 free(pf);
5237 free(pt);
5238
5239 return r;
5240}
5241
5242int symlink_or_copy_atomic(const char *from, const char *to) {
5243 char *t, *x;
5244 const char *fn;
5245 size_t k;
5246 unsigned long long ull;
5247 unsigned i;
5248 int r;
5249
5250 assert(from);
5251 assert(to);
5252
5253 t = new(char, strlen(to) + 1 + 16 + 1);
5254 if (!t)
5255 return -ENOMEM;
5256
5257 fn = file_name_from_path(to);
5258 k = fn-to;
5259 memcpy(t, to, k);
5260 t[k] = '.';
5261 x = stpcpy(t+k+1, fn);
5262
5263 ull = random_ull();
5264 for (i = 0; i < 16; i++) {
5265 *(x++) = hexchar(ull & 0xF);
5266 ull >>= 4;
5267 }
5268
5269 *x = 0;
5270
5271 r = symlink_or_copy(from, t);
5272 if (r < 0) {
5273 unlink(t);
5274 free(t);
5275 return r;
5276 }
5277
5278 if (rename(t, to) < 0) {
5279 r = -errno;
5280 unlink(t);
5281 free(t);
5282 return r;
5283 }
5284
5285 free(t);
5286 return r;
5287}
5288
98a28fef
LP
5289int audit_session_from_pid(pid_t pid, uint32_t *id) {
5290 char *p, *s;
5291 uint32_t u;
5292 int r;
5293
5294 assert(pid >= 1);
5295 assert(id);
5296
5297 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5298 return -ENOENT;
5299
5300 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5301 return -ENOMEM;
5302
5303 r = read_one_line_file(p, &s);
5304 free(p);
5305 if (r < 0)
5306 return r;
5307
5308 r = safe_atou32(s, &u);
5309 free(s);
5310
5311 if (r < 0)
5312 return r;
5313
5314 if (u == (uint32_t) -1 || u <= 0)
5315 return -ENOENT;
5316
5317 *id = u;
5318 return 0;
5319}
5320
4d6d6518
LP
5321bool display_is_local(const char *display) {
5322 assert(display);
5323
5324 return
5325 display[0] == ':' &&
5326 display[1] >= '0' &&
5327 display[1] <= '9';
5328}
5329
5330int socket_from_display(const char *display, char **path) {
5331 size_t k;
5332 char *f, *c;
5333
5334 assert(display);
5335 assert(path);
5336
5337 if (!display_is_local(display))
5338 return -EINVAL;
5339
5340 k = strspn(display+1, "0123456789");
5341
5342 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5343 if (!f)
5344 return -ENOMEM;
5345
5346 c = stpcpy(f, "/tmp/.X11-unix/X");
5347 memcpy(c, display+1, k);
5348 c[k] = 0;
5349
5350 *path = f;
5351
5352 return 0;
5353}
5354
1cccf435
MV
5355int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5356 struct passwd *p;
ddd88763 5357 uid_t u;
1cccf435
MV
5358
5359 assert(username);
5360 assert(*username);
1cccf435
MV
5361
5362 /* We enforce some special rules for uid=0: in order to avoid
5363 * NSS lookups for root we hardcode its data. */
5364
5365 if (streq(*username, "root") || streq(*username, "0")) {
5366 *username = "root";
4b67834e
LP
5367
5368 if (uid)
5369 *uid = 0;
5370
5371 if (gid)
5372 *gid = 0;
5373
5374 if (home)
5375 *home = "/root";
1cccf435
MV
5376 return 0;
5377 }
5378
ddd88763 5379 if (parse_uid(*username, &u) >= 0) {
1cccf435 5380 errno = 0;
ddd88763 5381 p = getpwuid(u);
1cccf435
MV
5382
5383 /* If there are multiple users with the same id, make
5384 * sure to leave $USER to the configured value instead
5385 * of the first occurrence in the database. However if
5386 * the uid was configured by a numeric uid, then let's
5387 * pick the real username from /etc/passwd. */
5388 if (p)
5389 *username = p->pw_name;
5390 } else {
5391 errno = 0;
5392 p = getpwnam(*username);
5393 }
5394
5395 if (!p)
5396 return errno != 0 ? -errno : -ESRCH;
5397
4b67834e
LP
5398 if (uid)
5399 *uid = p->pw_uid;
5400
5401 if (gid)
5402 *gid = p->pw_gid;
5403
5404 if (home)
5405 *home = p->pw_dir;
5406
5407 return 0;
5408}
5409
5410int get_group_creds(const char **groupname, gid_t *gid) {
5411 struct group *g;
5412 gid_t id;
5413
5414 assert(groupname);
5415
5416 /* We enforce some special rules for gid=0: in order to avoid
5417 * NSS lookups for root we hardcode its data. */
5418
5419 if (streq(*groupname, "root") || streq(*groupname, "0")) {
5420 *groupname = "root";
5421
5422 if (gid)
5423 *gid = 0;
5424
5425 return 0;
5426 }
5427
5428 if (parse_gid(*groupname, &id) >= 0) {
5429 errno = 0;
5430 g = getgrgid(id);
5431
5432 if (g)
5433 *groupname = g->gr_name;
5434 } else {
5435 errno = 0;
5436 g = getgrnam(*groupname);
5437 }
5438
5439 if (!g)
5440 return errno != 0 ? -errno : -ESRCH;
5441
5442 if (gid)
5443 *gid = g->gr_gid;
5444
1cccf435
MV
5445 return 0;
5446}
5447
8092a428
LP
5448int glob_exists(const char *path) {
5449 glob_t g;
5450 int r, k;
5451
5452 assert(path);
5453
5454 zero(g);
5455 errno = 0;
5456 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5457
5458 if (k == GLOB_NOMATCH)
5459 r = 0;
5460 else if (k == GLOB_NOSPACE)
5461 r = -ENOMEM;
5462 else if (k == 0)
5463 r = !strv_isempty(g.gl_pathv);
5464 else
5465 r = errno ? -errno : -EIO;
5466
5467 globfree(&g);
5468
5469 return r;
5470}
5471
83096483
LP
5472int dirent_ensure_type(DIR *d, struct dirent *de) {
5473 struct stat st;
5474
5475 assert(d);
5476 assert(de);
5477
5478 if (de->d_type != DT_UNKNOWN)
5479 return 0;
5480
5481 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5482 return -errno;
5483
5484 de->d_type =
5485 S_ISREG(st.st_mode) ? DT_REG :
5486 S_ISDIR(st.st_mode) ? DT_DIR :
5487 S_ISLNK(st.st_mode) ? DT_LNK :
5488 S_ISFIFO(st.st_mode) ? DT_FIFO :
5489 S_ISSOCK(st.st_mode) ? DT_SOCK :
5490 S_ISCHR(st.st_mode) ? DT_CHR :
5491 S_ISBLK(st.st_mode) ? DT_BLK :
5492 DT_UNKNOWN;
5493
5494 return 0;
5495}
5496
5497int in_search_path(const char *path, char **search) {
5498 char **i, *parent;
5499 int r;
5500
5501 r = parent_of_path(path, &parent);
5502 if (r < 0)
5503 return r;
5504
5505 r = 0;
5506
5507 STRV_FOREACH(i, search) {
5508 if (path_equal(parent, *i)) {
5509 r = 1;
5510 break;
5511 }
5512 }
5513
5514 free(parent);
5515
5516 return r;
5517}
5518
034a2a52
LP
5519int get_files_in_directory(const char *path, char ***list) {
5520 DIR *d;
5521 int r = 0;
5522 unsigned n = 0;
5523 char **l = NULL;
5524
5525 assert(path);
d60ef526
LP
5526
5527 /* Returns all files in a directory in *list, and the number
5528 * of files as return value. If list is NULL returns only the
5529 * number */
034a2a52
LP
5530
5531 d = opendir(path);
5532 for (;;) {
5533 struct dirent buffer, *de;
5534 int k;
5535
5536 k = readdir_r(d, &buffer, &de);
5537 if (k != 0) {
5538 r = -k;
5539 goto finish;
5540 }
5541
5542 if (!de)
5543 break;
5544
5545 dirent_ensure_type(d, de);
5546
5547 if (!dirent_is_file(de))
5548 continue;
5549
d60ef526
LP
5550 if (list) {
5551 if ((unsigned) r >= n) {
5552 char **t;
034a2a52 5553
d60ef526
LP
5554 n = MAX(16, 2*r);
5555 t = realloc(l, sizeof(char*) * n);
5556 if (!t) {
5557 r = -ENOMEM;
5558 goto finish;
5559 }
034a2a52 5560
d60ef526
LP
5561 l = t;
5562 }
034a2a52 5563
d60ef526 5564 assert((unsigned) r < n);
034a2a52 5565
d60ef526
LP
5566 l[r] = strdup(de->d_name);
5567 if (!l[r]) {
5568 r = -ENOMEM;
5569 goto finish;
5570 }
034a2a52 5571
d60ef526
LP
5572 l[++r] = NULL;
5573 } else
5574 r++;
034a2a52
LP
5575 }
5576
5577finish:
5578 if (d)
5579 closedir(d);
5580
d60ef526
LP
5581 if (r >= 0) {
5582 if (list)
5583 *list = l;
5584 } else
034a2a52
LP
5585 strv_free(l);
5586
5587 return r;
5588}
5589
911a4828
LP
5590char *join(const char *x, ...) {
5591 va_list ap;
5592 size_t l;
5593 char *r, *p;
5594
5595 va_start(ap, x);
5596
5597 if (x) {
5598 l = strlen(x);
5599
5600 for (;;) {
5601 const char *t;
5602
5603 t = va_arg(ap, const char *);
5604 if (!t)
5605 break;
5606
5607 l += strlen(t);
5608 }
5609 } else
5610 l = 0;
5611
5612 va_end(ap);
5613
5614 r = new(char, l+1);
5615 if (!r)
5616 return NULL;
5617
5618 if (x) {
5619 p = stpcpy(r, x);
5620
5621 va_start(ap, x);
5622
5623 for (;;) {
5624 const char *t;
5625
5626 t = va_arg(ap, const char *);
5627 if (!t)
5628 break;
5629
5630 p = stpcpy(p, t);
5631 }
5632 } else
5633 r[0] = 0;
5634
5635 return r;
5636}
5637
b636465b
LP
5638bool is_main_thread(void) {
5639 static __thread int cached = 0;
5640
5641 if (_unlikely_(cached == 0))
5642 cached = getpid() == gettid() ? 1 : -1;
5643
5644 return cached > 0;
5645}
5646
94959f0f
LP
5647int block_get_whole_disk(dev_t d, dev_t *ret) {
5648 char *p, *s;
5649 int r;
5650 unsigned n, m;
5651
5652 assert(ret);
5653
5654 /* If it has a queue this is good enough for us */
5655 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5656 return -ENOMEM;
5657
5658 r = access(p, F_OK);
5659 free(p);
5660
5661 if (r >= 0) {
5662 *ret = d;
5663 return 0;
5664 }
5665
5666 /* If it is a partition find the originating device */
5667 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5668 return -ENOMEM;
5669
5670 r = access(p, F_OK);
5671 free(p);
5672
5673 if (r < 0)
5674 return -ENOENT;
5675
5676 /* Get parent dev_t */
5677 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5678 return -ENOMEM;
5679
5680 r = read_one_line_file(p, &s);
5681 free(p);
5682
5683 if (r < 0)
5684 return r;
5685
5686 r = sscanf(s, "%u:%u", &m, &n);
5687 free(s);
5688
5689 if (r != 2)
5690 return -EINVAL;
5691
5692 /* Only return this if it is really good enough for us. */
5693 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5694 return -ENOMEM;
5695
5696 r = access(p, F_OK);
5697 free(p);
5698
5699 if (r >= 0) {
5700 *ret = makedev(m, n);
5701 return 0;
5702 }
5703
5704 return -ENOENT;
5705}
5706
ad293f5a
LP
5707int file_is_sticky(const char *p) {
5708 struct stat st;
5709
5710 assert(p);
5711
5712 if (lstat(p, &st) < 0)
5713 return -errno;
5714
5715 return
5716 st.st_uid == 0 &&
5717 (st.st_mode & S_ISVTX);
5718}
94959f0f 5719
f41607a6
LP
5720static const char *const ioprio_class_table[] = {
5721 [IOPRIO_CLASS_NONE] = "none",
5722 [IOPRIO_CLASS_RT] = "realtime",
5723 [IOPRIO_CLASS_BE] = "best-effort",
5724 [IOPRIO_CLASS_IDLE] = "idle"
5725};
5726
5727DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5728
5729static const char *const sigchld_code_table[] = {
5730 [CLD_EXITED] = "exited",
5731 [CLD_KILLED] = "killed",
5732 [CLD_DUMPED] = "dumped",
5733 [CLD_TRAPPED] = "trapped",
5734 [CLD_STOPPED] = "stopped",
5735 [CLD_CONTINUED] = "continued",
5736};
5737
5738DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5739
5740static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5741 [LOG_FAC(LOG_KERN)] = "kern",
5742 [LOG_FAC(LOG_USER)] = "user",
5743 [LOG_FAC(LOG_MAIL)] = "mail",
5744 [LOG_FAC(LOG_DAEMON)] = "daemon",
5745 [LOG_FAC(LOG_AUTH)] = "auth",
5746 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5747 [LOG_FAC(LOG_LPR)] = "lpr",
5748 [LOG_FAC(LOG_NEWS)] = "news",
5749 [LOG_FAC(LOG_UUCP)] = "uucp",
5750 [LOG_FAC(LOG_CRON)] = "cron",
5751 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5752 [LOG_FAC(LOG_FTP)] = "ftp",
5753 [LOG_FAC(LOG_LOCAL0)] = "local0",
5754 [LOG_FAC(LOG_LOCAL1)] = "local1",
5755 [LOG_FAC(LOG_LOCAL2)] = "local2",
5756 [LOG_FAC(LOG_LOCAL3)] = "local3",
5757 [LOG_FAC(LOG_LOCAL4)] = "local4",
5758 [LOG_FAC(LOG_LOCAL5)] = "local5",
5759 [LOG_FAC(LOG_LOCAL6)] = "local6",
5760 [LOG_FAC(LOG_LOCAL7)] = "local7"
5761};
5762
5763DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5764
5765static const char *const log_level_table[] = {
5766 [LOG_EMERG] = "emerg",
5767 [LOG_ALERT] = "alert",
5768 [LOG_CRIT] = "crit",
5769 [LOG_ERR] = "err",
5770 [LOG_WARNING] = "warning",
5771 [LOG_NOTICE] = "notice",
5772 [LOG_INFO] = "info",
5773 [LOG_DEBUG] = "debug"
5774};
5775
5776DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5777
5778static const char* const sched_policy_table[] = {
5779 [SCHED_OTHER] = "other",
5780 [SCHED_BATCH] = "batch",
5781 [SCHED_IDLE] = "idle",
5782 [SCHED_FIFO] = "fifo",
5783 [SCHED_RR] = "rr"
5784};
5785
5786DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5787
5788static const char* const rlimit_table[] = {
5789 [RLIMIT_CPU] = "LimitCPU",
5790 [RLIMIT_FSIZE] = "LimitFSIZE",
5791 [RLIMIT_DATA] = "LimitDATA",
5792 [RLIMIT_STACK] = "LimitSTACK",
5793 [RLIMIT_CORE] = "LimitCORE",
5794 [RLIMIT_RSS] = "LimitRSS",
5795 [RLIMIT_NOFILE] = "LimitNOFILE",
5796 [RLIMIT_AS] = "LimitAS",
5797 [RLIMIT_NPROC] = "LimitNPROC",
5798 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5799 [RLIMIT_LOCKS] = "LimitLOCKS",
5800 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5801 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5802 [RLIMIT_NICE] = "LimitNICE",
5803 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5804 [RLIMIT_RTTIME] = "LimitRTTIME"
5805};
5806
5807DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5808
5809static const char* const ip_tos_table[] = {
5810 [IPTOS_LOWDELAY] = "low-delay",
5811 [IPTOS_THROUGHPUT] = "throughput",
5812 [IPTOS_RELIABILITY] = "reliability",
5813 [IPTOS_LOWCOST] = "low-cost",
5814};
5815
5816DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5817
5818static const char *const signal_table[] = {
5819 [SIGHUP] = "HUP",
5820 [SIGINT] = "INT",
5821 [SIGQUIT] = "QUIT",
5822 [SIGILL] = "ILL",
5823 [SIGTRAP] = "TRAP",
5824 [SIGABRT] = "ABRT",
5825 [SIGBUS] = "BUS",
5826 [SIGFPE] = "FPE",
5827 [SIGKILL] = "KILL",
5828 [SIGUSR1] = "USR1",
5829 [SIGSEGV] = "SEGV",
5830 [SIGUSR2] = "USR2",
5831 [SIGPIPE] = "PIPE",
5832 [SIGALRM] = "ALRM",
5833 [SIGTERM] = "TERM",
5834#ifdef SIGSTKFLT
5835 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5836#endif
5837 [SIGCHLD] = "CHLD",
5838 [SIGCONT] = "CONT",
5839 [SIGSTOP] = "STOP",
5840 [SIGTSTP] = "TSTP",
5841 [SIGTTIN] = "TTIN",
5842 [SIGTTOU] = "TTOU",
5843 [SIGURG] = "URG",
5844 [SIGXCPU] = "XCPU",
5845 [SIGXFSZ] = "XFSZ",
5846 [SIGVTALRM] = "VTALRM",
5847 [SIGPROF] = "PROF",
5848 [SIGWINCH] = "WINCH",
5849 [SIGIO] = "IO",
5850 [SIGPWR] = "PWR",
5851 [SIGSYS] = "SYS"
5852};
5853
5854DEFINE_STRING_TABLE_LOOKUP(signal, int);
65457142
FC
5855
5856bool kexec_loaded(void) {
5857 bool loaded = false;
5858 char *s;
5859
5860 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5861 if (s[0] == '1')
5862 loaded = true;
5863 free(s);
5864 }
5865 return loaded;
5866}