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