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