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