]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/util.c
readahead: disable collector automatically on read-only media
[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;
f73f76ac 2137 unsigned c = 0;
80876c20 2138
f73f76ac
LP
2139 /*
2140 * If a TTY is in the process of being closed opening it might
2141 * cause EIO. This is horribly awful, but unlikely to be
2142 * changed in the kernel. Hence we work around this problem by
2143 * retrying a couple of times.
2144 *
2145 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2146 */
2147
2148 for (;;) {
2149 if ((fd = open(name, mode)) >= 0)
2150 break;
2151
2152 if (errno != EIO)
2153 return -errno;
2154
2155 if (c >= 20)
2156 return -errno;
2157
2158 usleep(50 * USEC_PER_MSEC);
2159 c++;
2160 }
2161
2162 if (fd < 0)
80876c20
LP
2163 return -errno;
2164
2165 if ((r = isatty(fd)) < 0) {
2166 close_nointr_nofail(fd);
2167 return -errno;
2168 }
2169
2170 if (!r) {
2171 close_nointr_nofail(fd);
2172 return -ENOTTY;
2173 }
2174
2175 return fd;
2176}
2177
2178int flush_fd(int fd) {
2179 struct pollfd pollfd;
2180
2181 zero(pollfd);
2182 pollfd.fd = fd;
2183 pollfd.events = POLLIN;
2184
2185 for (;;) {
2186 char buf[1024];
2187 ssize_t l;
2188 int r;
2189
2190 if ((r = poll(&pollfd, 1, 0)) < 0) {
2191
2192 if (errno == EINTR)
2193 continue;
2194
2195 return -errno;
2196 }
2197
2198 if (r == 0)
2199 return 0;
2200
2201 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2202
2203 if (errno == EINTR)
2204 continue;
2205
2206 if (errno == EAGAIN)
2207 return 0;
2208
2209 return -errno;
2210 }
2211
2212 if (l <= 0)
2213 return 0;
2214 }
2215}
2216
21de3988 2217int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
bab45044 2218 int fd = -1, notify = -1, r, wd = -1;
80876c20
LP
2219
2220 assert(name);
2221
2222 /* We use inotify to be notified when the tty is closed. We
2223 * create the watch before checking if we can actually acquire
2224 * it, so that we don't lose any event.
2225 *
2226 * Note: strictly speaking this actually watches for the
2227 * device being closed, it does *not* really watch whether a
2228 * tty loses its controlling process. However, unless some
2229 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2230 * its tty otherwise this will not become a problem. As long
2231 * as the administrator makes sure not configure any service
2232 * on the same tty as an untrusted user this should not be a
2233 * problem. (Which he probably should not do anyway.) */
2234
2235 if (!fail && !force) {
2236 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2237 r = -errno;
2238 goto fail;
2239 }
2240
2241 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2242 r = -errno;
2243 goto fail;
2244 }
2245 }
2246
2247 for (;;) {
e3d1855b
LP
2248 if (notify >= 0)
2249 if ((r = flush_fd(notify)) < 0)
2250 goto fail;
80876c20
LP
2251
2252 /* We pass here O_NOCTTY only so that we can check the return
2253 * value TIOCSCTTY and have a reliable way to figure out if we
2254 * successfully became the controlling process of the tty */
2255 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2256 return -errno;
2257
2258 /* First, try to get the tty */
21de3988
LP
2259 r = ioctl(fd, TIOCSCTTY, force);
2260
2261 /* Sometimes it makes sense to ignore TIOCSCTTY
2262 * returning EPERM, i.e. when very likely we already
2263 * are have this controlling terminal. */
2264 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2265 r = 0;
2266
2267 if (r < 0 && (force || fail || errno != EPERM)) {
80876c20
LP
2268 r = -errno;
2269 goto fail;
2270 }
2271
2272 if (r >= 0)
2273 break;
2274
2275 assert(!fail);
2276 assert(!force);
2277 assert(notify >= 0);
2278
2279 for (;;) {
f601daa7 2280 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
80876c20 2281 ssize_t l;
f601daa7 2282 struct inotify_event *e;
80876c20 2283
f601daa7 2284 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
80876c20 2285
f601daa7
LP
2286 if (errno == EINTR)
2287 continue;
2288
2289 r = -errno;
2290 goto fail;
2291 }
2292
2293 e = (struct inotify_event*) inotify_buffer;
80876c20 2294
f601daa7
LP
2295 while (l > 0) {
2296 size_t step;
80876c20 2297
f601daa7 2298 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
80876c20 2299 r = -EIO;
f601daa7
LP
2300 goto fail;
2301 }
80876c20 2302
f601daa7
LP
2303 step = sizeof(struct inotify_event) + e->len;
2304 assert(step <= (size_t) l);
80876c20 2305
f601daa7
LP
2306 e = (struct inotify_event*) ((uint8_t*) e + step);
2307 l -= step;
80876c20
LP
2308 }
2309
2310 break;
2311 }
2312
2313 /* We close the tty fd here since if the old session
2314 * ended our handle will be dead. It's important that
2315 * we do this after sleeping, so that we don't enter
2316 * an endless loop. */
2317 close_nointr_nofail(fd);
2318 }
2319
2320 if (notify >= 0)
a16e1123 2321 close_nointr_nofail(notify);
80876c20
LP
2322
2323 if ((r = reset_terminal(fd)) < 0)
2324 log_warning("Failed to reset terminal: %s", strerror(-r));
2325
2326 return fd;
2327
2328fail:
2329 if (fd >= 0)
a16e1123 2330 close_nointr_nofail(fd);
80876c20
LP
2331
2332 if (notify >= 0)
a16e1123 2333 close_nointr_nofail(notify);
80876c20
LP
2334
2335 return r;
2336}
2337
2338int release_terminal(void) {
2339 int r = 0, fd;
57cd2192 2340 struct sigaction sa_old, sa_new;
80876c20 2341
57cd2192 2342 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
80876c20
LP
2343 return -errno;
2344
57cd2192
LP
2345 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2346 * by our own TIOCNOTTY */
2347
2348 zero(sa_new);
2349 sa_new.sa_handler = SIG_IGN;
2350 sa_new.sa_flags = SA_RESTART;
2351 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2352
80876c20
LP
2353 if (ioctl(fd, TIOCNOTTY) < 0)
2354 r = -errno;
2355
57cd2192
LP
2356 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2357
80876c20
LP
2358 close_nointr_nofail(fd);
2359 return r;
2360}
2361
9a34ec5f
LP
2362int sigaction_many(const struct sigaction *sa, ...) {
2363 va_list ap;
2364 int r = 0, sig;
2365
2366 va_start(ap, sa);
2367 while ((sig = va_arg(ap, int)) > 0)
2368 if (sigaction(sig, sa, NULL) < 0)
2369 r = -errno;
2370 va_end(ap);
2371
2372 return r;
2373}
2374
2375int ignore_signals(int sig, ...) {
a337c6fc 2376 struct sigaction sa;
9a34ec5f
LP
2377 va_list ap;
2378 int r = 0;
a337c6fc
LP
2379
2380 zero(sa);
2381 sa.sa_handler = SIG_IGN;
2382 sa.sa_flags = SA_RESTART;
2383
9a34ec5f
LP
2384 if (sigaction(sig, &sa, NULL) < 0)
2385 r = -errno;
2386
2387 va_start(ap, sig);
2388 while ((sig = va_arg(ap, int)) > 0)
2389 if (sigaction(sig, &sa, NULL) < 0)
2390 r = -errno;
2391 va_end(ap);
2392
2393 return r;
2394}
2395
2396int default_signals(int sig, ...) {
2397 struct sigaction sa;
2398 va_list ap;
2399 int r = 0;
2400
2401 zero(sa);
2402 sa.sa_handler = SIG_DFL;
2403 sa.sa_flags = SA_RESTART;
2404
2405 if (sigaction(sig, &sa, NULL) < 0)
2406 r = -errno;
2407
2408 va_start(ap, sig);
2409 while ((sig = va_arg(ap, int)) > 0)
2410 if (sigaction(sig, &sa, NULL) < 0)
2411 r = -errno;
2412 va_end(ap);
2413
2414 return r;
a337c6fc
LP
2415}
2416
8d567588
LP
2417int close_pipe(int p[]) {
2418 int a = 0, b = 0;
2419
2420 assert(p);
2421
2422 if (p[0] >= 0) {
2423 a = close_nointr(p[0]);
2424 p[0] = -1;
2425 }
2426
2427 if (p[1] >= 0) {
2428 b = close_nointr(p[1]);
2429 p[1] = -1;
2430 }
2431
2432 return a < 0 ? a : b;
2433}
2434
eb22ac37 2435ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
8d567588
LP
2436 uint8_t *p;
2437 ssize_t n = 0;
2438
2439 assert(fd >= 0);
2440 assert(buf);
2441
2442 p = buf;
2443
2444 while (nbytes > 0) {
2445 ssize_t k;
2446
2447 if ((k = read(fd, p, nbytes)) <= 0) {
2448
eb22ac37 2449 if (k < 0 && errno == EINTR)
8d567588
LP
2450 continue;
2451
eb22ac37 2452 if (k < 0 && errno == EAGAIN && do_poll) {
8d567588
LP
2453 struct pollfd pollfd;
2454
2455 zero(pollfd);
2456 pollfd.fd = fd;
2457 pollfd.events = POLLIN;
2458
2459 if (poll(&pollfd, 1, -1) < 0) {
2460 if (errno == EINTR)
2461 continue;
2462
2463 return n > 0 ? n : -errno;
2464 }
2465
2466 if (pollfd.revents != POLLIN)
2467 return n > 0 ? n : -EIO;
2468
2469 continue;
2470 }
2471
2472 return n > 0 ? n : (k < 0 ? -errno : 0);
2473 }
2474
2475 p += k;
2476 nbytes -= k;
2477 n += k;
2478 }
2479
2480 return n;
2481}
2482
eb22ac37
LP
2483ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2484 const uint8_t *p;
2485 ssize_t n = 0;
2486
2487 assert(fd >= 0);
2488 assert(buf);
2489
2490 p = buf;
2491
2492 while (nbytes > 0) {
2493 ssize_t k;
2494
2495 if ((k = write(fd, p, nbytes)) <= 0) {
2496
2497 if (k < 0 && errno == EINTR)
2498 continue;
2499
2500 if (k < 0 && errno == EAGAIN && do_poll) {
2501 struct pollfd pollfd;
2502
2503 zero(pollfd);
2504 pollfd.fd = fd;
2505 pollfd.events = POLLOUT;
2506
2507 if (poll(&pollfd, 1, -1) < 0) {
2508 if (errno == EINTR)
2509 continue;
2510
2511 return n > 0 ? n : -errno;
2512 }
2513
2514 if (pollfd.revents != POLLOUT)
2515 return n > 0 ? n : -EIO;
2516
2517 continue;
2518 }
2519
2520 return n > 0 ? n : (k < 0 ? -errno : 0);
2521 }
2522
2523 p += k;
2524 nbytes -= k;
2525 n += k;
2526 }
2527
2528 return n;
2529}
2530
8d567588
LP
2531int path_is_mount_point(const char *t) {
2532 struct stat a, b;
35d2e7ec
LP
2533 char *parent;
2534 int r;
8d567588
LP
2535
2536 if (lstat(t, &a) < 0) {
8d567588
LP
2537 if (errno == ENOENT)
2538 return 0;
2539
2540 return -errno;
2541 }
2542
35d2e7ec
LP
2543 if ((r = parent_of_path(t, &parent)) < 0)
2544 return r;
8d567588 2545
35d2e7ec
LP
2546 r = lstat(parent, &b);
2547 free(parent);
8d567588 2548
35d2e7ec
LP
2549 if (r < 0)
2550 return -errno;
8d567588
LP
2551
2552 return a.st_dev != b.st_dev;
2553}
2554
24a6e4a4
LP
2555int parse_usec(const char *t, usec_t *usec) {
2556 static const struct {
2557 const char *suffix;
2558 usec_t usec;
2559 } table[] = {
2560 { "sec", USEC_PER_SEC },
2561 { "s", USEC_PER_SEC },
2562 { "min", USEC_PER_MINUTE },
2563 { "hr", USEC_PER_HOUR },
2564 { "h", USEC_PER_HOUR },
2565 { "d", USEC_PER_DAY },
2566 { "w", USEC_PER_WEEK },
2567 { "msec", USEC_PER_MSEC },
2568 { "ms", USEC_PER_MSEC },
2569 { "m", USEC_PER_MINUTE },
2570 { "usec", 1ULL },
2571 { "us", 1ULL },
2572 { "", USEC_PER_SEC },
2573 };
2574
2575 const char *p;
2576 usec_t r = 0;
2577
2578 assert(t);
2579 assert(usec);
2580
2581 p = t;
2582 do {
2583 long long l;
2584 char *e;
2585 unsigned i;
2586
2587 errno = 0;
2588 l = strtoll(p, &e, 10);
2589
2590 if (errno != 0)
2591 return -errno;
2592
2593 if (l < 0)
2594 return -ERANGE;
2595
2596 if (e == p)
2597 return -EINVAL;
2598
2599 e += strspn(e, WHITESPACE);
2600
2601 for (i = 0; i < ELEMENTSOF(table); i++)
2602 if (startswith(e, table[i].suffix)) {
2603 r += (usec_t) l * table[i].usec;
2604 p = e + strlen(table[i].suffix);
2605 break;
2606 }
2607
2608 if (i >= ELEMENTSOF(table))
2609 return -EINVAL;
2610
2611 } while (*p != 0);
2612
2613 *usec = r;
2614
2615 return 0;
2616}
2617
843d2643
LP
2618int make_stdio(int fd) {
2619 int r, s, t;
2620
2621 assert(fd >= 0);
2622
2623 r = dup2(fd, STDIN_FILENO);
2624 s = dup2(fd, STDOUT_FILENO);
2625 t = dup2(fd, STDERR_FILENO);
2626
2627 if (fd >= 3)
2628 close_nointr_nofail(fd);
2629
2630 if (r < 0 || s < 0 || t < 0)
2631 return -errno;
2632
2633 return 0;
2634}
2635
ade509ce
LP
2636int make_null_stdio(void) {
2637 int null_fd;
2638
2639 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2640 return -errno;
2641
2642 return make_stdio(null_fd);
2643}
2644
8407a5d0
LP
2645bool is_device_path(const char *path) {
2646
2647 /* Returns true on paths that refer to a device, either in
2648 * sysfs or in /dev */
2649
2650 return
2651 path_startswith(path, "/dev/") ||
2652 path_startswith(path, "/sys/");
2653}
2654
01f78473
LP
2655int dir_is_empty(const char *path) {
2656 DIR *d;
2657 int r;
2658 struct dirent buf, *de;
2659
2660 if (!(d = opendir(path)))
2661 return -errno;
2662
2663 for (;;) {
2664 if ((r = readdir_r(d, &buf, &de)) > 0) {
2665 r = -r;
2666 break;
2667 }
2668
2669 if (!de) {
2670 r = 1;
2671 break;
2672 }
2673
2674 if (!ignore_file(de->d_name)) {
2675 r = 0;
2676 break;
2677 }
2678 }
2679
2680 closedir(d);
2681 return r;
2682}
2683
d3782d60
LP
2684unsigned long long random_ull(void) {
2685 int fd;
2686 uint64_t ull;
2687 ssize_t r;
2688
2689 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2690 goto fallback;
2691
eb22ac37 2692 r = loop_read(fd, &ull, sizeof(ull), true);
d3782d60
LP
2693 close_nointr_nofail(fd);
2694
2695 if (r != sizeof(ull))
2696 goto fallback;
2697
2698 return ull;
2699
2700fallback:
2701 return random() * RAND_MAX + random();
2702}
2703
5b6319dc
LP
2704void rename_process(const char name[8]) {
2705 assert(name);
2706
2707 prctl(PR_SET_NAME, name);
2708
2709 /* This is a like a poor man's setproctitle(). The string
2710 * passed should fit in 7 chars (i.e. the length of
2711 * "systemd") */
2712
2713 if (program_invocation_name)
2714 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2715}
2716
7d793605
LP
2717void sigset_add_many(sigset_t *ss, ...) {
2718 va_list ap;
2719 int sig;
2720
2721 assert(ss);
2722
2723 va_start(ap, ss);
2724 while ((sig = va_arg(ap, int)) > 0)
2725 assert_se(sigaddset(ss, sig) == 0);
2726 va_end(ap);
2727}
2728
ef2f1067
LP
2729char* gethostname_malloc(void) {
2730 struct utsname u;
2731
2732 assert_se(uname(&u) >= 0);
2733
2734 if (u.nodename[0])
2735 return strdup(u.nodename);
2736
2737 return strdup(u.sysname);
2738}
2739
2740char* getlogname_malloc(void) {
2741 uid_t uid;
2742 long bufsize;
2743 char *buf, *name;
2744 struct passwd pwbuf, *pw = NULL;
2745 struct stat st;
2746
2747 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2748 uid = st.st_uid;
2749 else
2750 uid = getuid();
2751
2752 /* Shortcut things to avoid NSS lookups */
2753 if (uid == 0)
2754 return strdup("root");
2755
2756 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2757 bufsize = 4096;
2758
2759 if (!(buf = malloc(bufsize)))
2760 return NULL;
2761
2762 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2763 name = strdup(pw->pw_name);
2764 free(buf);
2765 return name;
2766 }
2767
2768 free(buf);
2769
2770 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2771 return NULL;
2772
2773 return name;
2774}
2775
fc116c6a
LP
2776int getttyname_malloc(int fd, char **r) {
2777 char path[PATH_MAX], *c;
618e02c7 2778 int k;
8c6db833
LP
2779
2780 assert(r);
ef2f1067 2781
fc116c6a 2782 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
618e02c7 2783 return -k;
ef2f1067
LP
2784
2785 char_array_0(path);
2786
fc116c6a 2787 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
8c6db833
LP
2788 return -ENOMEM;
2789
2790 *r = c;
2791 return 0;
2792}
2793
fc116c6a
LP
2794int getttyname_harder(int fd, char **r) {
2795 int k;
2796 char *s;
2797
2798 if ((k = getttyname_malloc(fd, &s)) < 0)
2799 return k;
2800
2801 if (streq(s, "tty")) {
2802 free(s);
2803 return get_ctty(r);
2804 }
2805
2806 *r = s;
2807 return 0;
2808}
2809
2810int get_ctty_devnr(dev_t *d) {
2811 int k;
2812 char line[256], *p;
2813 unsigned long ttynr;
2814 FILE *f;
2815
2816 if (!(f = fopen("/proc/self/stat", "r")))
2817 return -errno;
2818
2819 if (!(fgets(line, sizeof(line), f))) {
2820 k = -errno;
2821 fclose(f);
2822 return k;
2823 }
2824
2825 fclose(f);
2826
2827 if (!(p = strrchr(line, ')')))
2828 return -EIO;
2829
2830 p++;
2831
2832 if (sscanf(p, " "
2833 "%*c " /* state */
2834 "%*d " /* ppid */
2835 "%*d " /* pgrp */
2836 "%*d " /* session */
2837 "%lu ", /* ttynr */
2838 &ttynr) != 1)
2839 return -EIO;
2840
2841 *d = (dev_t) ttynr;
2842 return 0;
2843}
2844
2845int get_ctty(char **r) {
2846 int k;
2847 char fn[128], *s, *b, *p;
2848 dev_t devnr;
2849
2850 assert(r);
2851
2852 if ((k = get_ctty_devnr(&devnr)) < 0)
2853 return k;
2854
2855 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2856 char_array_0(fn);
2857
2858 if ((k = readlink_malloc(fn, &s)) < 0) {
2859
2860 if (k != -ENOENT)
2861 return k;
2862
2863 /* Probably something like the ptys which have no
2864 * symlink in /dev/char. Let's return something
2865 * vaguely useful. */
2866
2867 if (!(b = strdup(fn + 5)))
2868 return -ENOMEM;
2869
2870 *r = b;
2871 return 0;
2872 }
2873
2874 if (startswith(s, "/dev/"))
2875 p = s + 5;
2876 else if (startswith(s, "../"))
2877 p = s + 3;
2878 else
2879 p = s;
2880
2881 b = strdup(p);
2882 free(s);
2883
2884 if (!b)
2885 return -ENOMEM;
2886
2887 *r = b;
2888 return 0;
2889}
2890
8c6db833
LP
2891static int rm_rf_children(int fd, bool only_dirs) {
2892 DIR *d;
2893 int ret = 0;
2894
2895 assert(fd >= 0);
2896
2897 /* This returns the first error we run into, but nevertheless
2898 * tries to go on */
2899
2900 if (!(d = fdopendir(fd))) {
2901 close_nointr_nofail(fd);
4c633005
LP
2902
2903 return errno == ENOENT ? 0 : -errno;
8c6db833
LP
2904 }
2905
2906 for (;;) {
2907 struct dirent buf, *de;
2908 bool is_dir;
2909 int r;
2910
2911 if ((r = readdir_r(d, &buf, &de)) != 0) {
2912 if (ret == 0)
2913 ret = -r;
2914 break;
2915 }
2916
2917 if (!de)
2918 break;
2919
2920 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2921 continue;
2922
2923 if (de->d_type == DT_UNKNOWN) {
2924 struct stat st;
2925
2926 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
4c633005 2927 if (ret == 0 && errno != ENOENT)
8c6db833
LP
2928 ret = -errno;
2929 continue;
2930 }
2931
2932 is_dir = S_ISDIR(st.st_mode);
2933 } else
2934 is_dir = de->d_type == DT_DIR;
2935
2936 if (is_dir) {
2937 int subdir_fd;
2938
2939 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
4c633005 2940 if (ret == 0 && errno != ENOENT)
8c6db833
LP
2941 ret = -errno;
2942 continue;
2943 }
2944
2945 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2946 if (ret == 0)
2947 ret = r;
2948 }
2949
2950 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
4c633005 2951 if (ret == 0 && errno != ENOENT)
8c6db833
LP
2952 ret = -errno;
2953 }
2954 } else if (!only_dirs) {
2955
2956 if (unlinkat(fd, de->d_name, 0) < 0) {
4c633005 2957 if (ret == 0 && errno != ENOENT)
8c6db833
LP
2958 ret = -errno;
2959 }
2960 }
2961 }
2962
2963 closedir(d);
2964
2965 return ret;
2966}
2967
2968int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2969 int fd;
2970 int r;
2971
2972 assert(path);
2973
2974 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2975
2976 if (errno != ENOTDIR)
2977 return -errno;
2978
2979 if (delete_root && !only_dirs)
2980 if (unlink(path) < 0)
2981 return -errno;
2982
2983 return 0;
2984 }
2985
2986 r = rm_rf_children(fd, only_dirs);
2987
2988 if (delete_root)
2989 if (rmdir(path) < 0) {
2990 if (r == 0)
2991 r = -errno;
2992 }
2993
2994 return r;
2995}
2996
2997int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2998 assert(path);
2999
3000 /* Under the assumption that we are running privileged we
3001 * first change the access mode and only then hand out
3002 * ownership to avoid a window where access is too open. */
3003
3004 if (chmod(path, mode) < 0)
3005 return -errno;
3006
3007 if (chown(path, uid, gid) < 0)
3008 return -errno;
3009
3010 return 0;
ef2f1067
LP
3011}
3012
82c121a4
LP
3013cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3014 cpu_set_t *r;
3015 unsigned n = 1024;
3016
3017 /* Allocates the cpuset in the right size */
3018
3019 for (;;) {
3020 if (!(r = CPU_ALLOC(n)))
3021 return NULL;
3022
3023 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3024 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3025
3026 if (ncpus)
3027 *ncpus = n;
3028
3029 return r;
3030 }
3031
3032 CPU_FREE(r);
3033
3034 if (errno != EINVAL)
3035 return NULL;
3036
3037 n *= 2;
3038 }
3039}
3040
9e58ff9c
LP
3041void status_vprintf(const char *format, va_list ap) {
3042 char *s = NULL;
3043 int fd = -1;
3044
3045 assert(format);
3046
3047 /* This independent of logging, as status messages are
3048 * optional and go exclusively to the console. */
3049
3050 if (vasprintf(&s, format, ap) < 0)
3051 goto finish;
3052
3053 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
3054 goto finish;
3055
3056 write(fd, s, strlen(s));
3057
3058finish:
3059 free(s);
3060
3061 if (fd >= 0)
3062 close_nointr_nofail(fd);
3063}
3064
c846ff47
LP
3065void status_printf(const char *format, ...) {
3066 va_list ap;
3067
3068 assert(format);
3069
3070 va_start(ap, format);
3071 status_vprintf(format, ap);
3072 va_end(ap);
3073}
3074
3075void status_welcome(void) {
10aa7034
LP
3076 char *pretty_name = NULL, *ansi_color = NULL;
3077 const char *const_pretty = NULL, *const_color = NULL;
3078 int r;
c846ff47 3079
10aa7034
LP
3080 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3081 "PRETTY_NAME", &pretty_name,
3082 "ANSI_COLOR", &ansi_color,
3083 NULL)) < 0) {
c846ff47 3084
10aa7034
LP
3085 if (r != -ENOENT)
3086 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3087 }
c846ff47 3088
10aa7034
LP
3089#if defined(TARGET_FEDORA)
3090 if (!pretty_name) {
3091 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
c846ff47 3092
10aa7034
LP
3093 if (r != -ENOENT)
3094 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3095 } else
3096 truncate_nl(pretty_name);
3097 }
c846ff47 3098
10aa7034 3099 if (!ansi_color && pretty_name) {
c846ff47 3100
10aa7034
LP
3101 /* This tries to mimic the color magic the old Red Hat sysinit
3102 * script did. */
3103
3104 if (startswith(pretty_name, "Red Hat"))
3105 const_color = "0;31"; /* Red for RHEL */
3106 else if (startswith(pretty_name, "Fedora"))
3107 const_color = "0;34"; /* Blue for Fedora */
3108 }
c846ff47
LP
3109
3110#elif defined(TARGET_SUSE)
c846ff47 3111
10aa7034
LP
3112 if (!pretty_name) {
3113 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
c846ff47 3114
10aa7034
LP
3115 if (r != -ENOENT)
3116 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3117 } else
3118 truncate_nl(pretty_name);
3119 }
c846ff47 3120
10aa7034
LP
3121 if (!ansi_color)
3122 const_color = "0;32"; /* Green for openSUSE */
5a6225fd 3123
0d37b36b 3124#elif defined(TARGET_GENTOO)
0d37b36b 3125
10aa7034
LP
3126 if (!pretty_name) {
3127 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
0d37b36b 3128
10aa7034
LP
3129 if (r != -ENOENT)
3130 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3131 } else
3132 truncate_nl(pretty_name);
3133 }
0d37b36b 3134
10aa7034
LP
3135 if (!ansi_color)
3136 const_color = "1;34"; /* Light Blue for Gentoo */
5a6225fd 3137
a338bab5
AS
3138#elif defined(TARGET_ALTLINUX)
3139
3140 if (!pretty_name) {
3141 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3142
3143 if (r != -ENOENT)
3144 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3145 } else
3146 truncate_nl(pretty_name);
3147 }
3148
3149 if (!ansi_color)
3150 const_color = "0;36"; /* Cyan for ALTLinux */
3151
3152
5a6225fd 3153#elif defined(TARGET_DEBIAN)
5a6225fd 3154
10aa7034 3155 if (!pretty_name) {
22927a36 3156 char *version;
c8bffa43 3157
22927a36 3158 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
5a6225fd 3159
10aa7034
LP
3160 if (r != -ENOENT)
3161 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
22927a36
MB
3162 } else {
3163 truncate_nl(version);
3164 pretty_name = strappend("Debian ", version);
3165 free(version);
c8bffa43
LP
3166
3167 if (!pretty_name)
3168 log_warning("Failed to allocate Debian version string.");
22927a36 3169 }
10aa7034 3170 }
5a6225fd 3171
10aa7034
LP
3172 if (!ansi_color)
3173 const_color = "1;31"; /* Light Red for Debian */
5a6225fd 3174
274914f9 3175#elif defined(TARGET_UBUNTU)
10aa7034
LP
3176
3177 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3178 "DISTRIB_DESCRIPTION", &pretty_name,
3179 NULL)) < 0) {
3180
3181 if (r != -ENOENT)
3182 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3183 }
3184
3185 if (!ansi_color)
3186 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3187
c846ff47 3188#endif
10aa7034
LP
3189
3190 if (!pretty_name && !const_pretty)
3191 const_pretty = "Linux";
3192
3193 if (!ansi_color && !const_color)
3194 const_color = "1";
3195
da71f23c 3196 status_printf("\nWelcome to \x1B[%sm%s\x1B[0m!\n\n",
10aa7034
LP
3197 const_color ? const_color : ansi_color,
3198 const_pretty ? const_pretty : pretty_name);
86a3475b
LP
3199
3200 free(ansi_color);
3201 free(pretty_name);
c846ff47
LP
3202}
3203
fab56fc5
LP
3204char *replace_env(const char *format, char **env) {
3205 enum {
3206 WORD,
c24eb49e 3207 CURLY,
fab56fc5
LP
3208 VARIABLE
3209 } state = WORD;
3210
3211 const char *e, *word = format;
3212 char *r = NULL, *k;
3213
3214 assert(format);
3215
3216 for (e = format; *e; e ++) {
3217
3218 switch (state) {
3219
3220 case WORD:
3221 if (*e == '$')
c24eb49e 3222 state = CURLY;
fab56fc5
LP
3223 break;
3224
c24eb49e
LP
3225 case CURLY:
3226 if (*e == '{') {
fab56fc5
LP
3227 if (!(k = strnappend(r, word, e-word-1)))
3228 goto fail;
3229
3230 free(r);
3231 r = k;
3232
3233 word = e-1;
3234 state = VARIABLE;
3235
3236 } else if (*e == '$') {
3237 if (!(k = strnappend(r, word, e-word)))
3238 goto fail;
3239
3240 free(r);
3241 r = k;
3242
3243 word = e+1;
3244 state = WORD;
3245 } else
3246 state = WORD;
3247 break;
3248
3249 case VARIABLE:
c24eb49e 3250 if (*e == '}') {
b95cf362 3251 const char *t;
fab56fc5 3252
b95cf362
LP
3253 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3254 t = "";
fab56fc5 3255
b95cf362
LP
3256 if (!(k = strappend(r, t)))
3257 goto fail;
fab56fc5 3258
b95cf362
LP
3259 free(r);
3260 r = k;
fab56fc5 3261
b95cf362 3262 word = e+1;
fab56fc5
LP
3263 state = WORD;
3264 }
3265 break;
3266 }
3267 }
3268
3269 if (!(k = strnappend(r, word, e-word)))
3270 goto fail;
3271
3272 free(r);
3273 return k;
3274
3275fail:
3276 free(r);
3277 return NULL;
3278}
3279
3280char **replace_env_argv(char **argv, char **env) {
3281 char **r, **i;
c24eb49e
LP
3282 unsigned k = 0, l = 0;
3283
3284 l = strv_length(argv);
fab56fc5 3285
c24eb49e 3286 if (!(r = new(char*, l+1)))
fab56fc5
LP
3287 return NULL;
3288
3289 STRV_FOREACH(i, argv) {
c24eb49e
LP
3290
3291 /* If $FOO appears as single word, replace it by the split up variable */
b95cf362
LP
3292 if ((*i)[0] == '$' && (*i)[1] != '{') {
3293 char *e;
3294 char **w, **m;
3295 unsigned q;
c24eb49e 3296
b95cf362 3297 if ((e = strv_env_get(env, *i+1))) {
c24eb49e
LP
3298
3299 if (!(m = strv_split_quoted(e))) {
3300 r[k] = NULL;
3301 strv_free(r);
3302 return NULL;
3303 }
b95cf362
LP
3304 } else
3305 m = NULL;
c24eb49e 3306
b95cf362
LP
3307 q = strv_length(m);
3308 l = l + q - 1;
c24eb49e 3309
b95cf362
LP
3310 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3311 r[k] = NULL;
3312 strv_free(r);
3313 strv_free(m);
3314 return NULL;
3315 }
c24eb49e 3316
b95cf362
LP
3317 r = w;
3318 if (m) {
c24eb49e
LP
3319 memcpy(r + k, m, q * sizeof(char*));
3320 free(m);
c24eb49e 3321 }
b95cf362
LP
3322
3323 k += q;
3324 continue;
c24eb49e
LP
3325 }
3326
3327 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
fab56fc5
LP
3328 if (!(r[k++] = replace_env(*i, env))) {
3329 strv_free(r);
3330 return NULL;
3331 }
3332 }
3333
3334 r[k] = NULL;
3335 return r;
3336}
3337
fa776d8e
LP
3338int columns(void) {
3339 static __thread int parsed_columns = 0;
3340 const char *e;
3341
3342 if (parsed_columns > 0)
3343 return parsed_columns;
3344
3345 if ((e = getenv("COLUMNS")))
3346 parsed_columns = atoi(e);
3347
3348 if (parsed_columns <= 0) {
3349 struct winsize ws;
3350 zero(ws);
3351
9ed95f43 3352 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
fa776d8e
LP
3353 parsed_columns = ws.ws_col;
3354 }
3355
3356 if (parsed_columns <= 0)
3357 parsed_columns = 80;
3358
3359 return parsed_columns;
3360}
3361
b4f10a5e
LP
3362int running_in_chroot(void) {
3363 struct stat a, b;
3364
3365 zero(a);
3366 zero(b);
3367
3368 /* Only works as root */
3369
3370 if (stat("/proc/1/root", &a) < 0)
3371 return -errno;
3372
3373 if (stat("/", &b) < 0)
3374 return -errno;
3375
3376 return
3377 a.st_dev != b.st_dev ||
3378 a.st_ino != b.st_ino;
3379}
3380
8fe914ec
LP
3381char *ellipsize(const char *s, unsigned length, unsigned percent) {
3382 size_t l, x;
3383 char *r;
3384
3385 assert(s);
3386 assert(percent <= 100);
3387 assert(length >= 3);
3388
3389 l = strlen(s);
3390
3391 if (l <= 3 || l <= length)
3392 return strdup(s);
3393
3394 if (!(r = new0(char, length+1)))
3395 return r;
3396
3397 x = (length * percent) / 100;
3398
3399 if (x > length - 3)
3400 x = length - 3;
3401
3402 memcpy(r, s, x);
3403 r[x] = '.';
3404 r[x+1] = '.';
3405 r[x+2] = '.';
3406 memcpy(r + x + 3,
3407 s + l - (length - x - 3),
3408 length - x - 3);
3409
3410 return r;
3411}
3412
f6144808
LP
3413int touch(const char *path) {
3414 int fd;
3415
3416 assert(path);
3417
3418 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0666)) < 0)
3419 return -errno;
3420
3421 close_nointr_nofail(fd);
3422 return 0;
3423}
afea26ad 3424
97c4a07d 3425char *unquote(const char *s, const char* quotes) {
11ce3427
LP
3426 size_t l;
3427 assert(s);
3428
3429 if ((l = strlen(s)) < 2)
3430 return strdup(s);
3431
97c4a07d 3432 if (strchr(quotes, s[0]) && s[l-1] == s[0])
11ce3427
LP
3433 return strndup(s+1, l-2);
3434
3435 return strdup(s);
3436}
3437
5f7c426e
LP
3438char *normalize_env_assignment(const char *s) {
3439 char *name, *value, *p, *r;
3440
3441 p = strchr(s, '=');
3442
3443 if (!p) {
3444 if (!(r = strdup(s)))
3445 return NULL;
3446
3447 return strstrip(r);
3448 }
3449
3450 if (!(name = strndup(s, p - s)))
3451 return NULL;
3452
3453 if (!(p = strdup(p+1))) {
3454 free(name);
3455 return NULL;
3456 }
3457
3458 value = unquote(strstrip(p), QUOTES);
3459 free(p);
3460
3461 if (!value) {
3462 free(p);
3463 free(name);
3464 return NULL;
3465 }
3466
3467 if (asprintf(&r, "%s=%s", name, value) < 0)
3468 r = NULL;
3469
3470 free(value);
3471 free(name);
3472
3473 return r;
3474}
3475
8e12a6ae 3476int wait_for_terminate(pid_t pid, siginfo_t *status) {
2e78aa99
LP
3477 assert(pid >= 1);
3478 assert(status);
3479
3480 for (;;) {
8e12a6ae
LP
3481 zero(*status);
3482
3483 if (waitid(P_PID, pid, status, WEXITED) < 0) {
2e78aa99
LP
3484
3485 if (errno == EINTR)
3486 continue;
3487
3488 return -errno;
3489 }
3490
3491 return 0;
3492 }
3493}
3494
97c4a07d
LP
3495int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3496 int r;
3497 siginfo_t status;
3498
3499 assert(name);
3500 assert(pid > 1);
3501
3502 if ((r = wait_for_terminate(pid, &status)) < 0) {
3503 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3504 return r;
3505 }
3506
3507 if (status.si_code == CLD_EXITED) {
3508 if (status.si_status != 0) {
3509 log_warning("%s failed with error code %i.", name, status.si_status);
3510 return -EPROTO;
3511 }
3512
3513 log_debug("%s succeeded.", name);
3514 return 0;
3515
3516 } else if (status.si_code == CLD_KILLED ||
3517 status.si_code == CLD_DUMPED) {
3518
3519 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3520 return -EPROTO;
3521 }
3522
3523 log_warning("%s failed due to unknown reason.", name);
3524 return -EPROTO;
3525
3526}
3527
3c14d26c 3528void freeze(void) {
c29597a1
LP
3529 sync();
3530
3c14d26c
LP
3531 for (;;)
3532 pause();
3533}
3534
00dc5d76
LP
3535bool null_or_empty(struct stat *st) {
3536 assert(st);
3537
3538 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3539 return true;
3540
c8f26f42 3541 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
00dc5d76
LP
3542 return true;
3543
3544 return false;
3545}
3546
a247755d 3547DIR *xopendirat(int fd, const char *name, int flags) {
c4731d11
LP
3548 int nfd;
3549 DIR *d;
3550
3551 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
3552 return NULL;
3553
3554 if (!(d = fdopendir(nfd))) {
3555 close_nointr_nofail(nfd);
3556 return NULL;
3557 }
3558
3559 return d;
3b63d2d3
LP
3560}
3561
8a0867d6
LP
3562int signal_from_string_try_harder(const char *s) {
3563 int signo;
3564 assert(s);
3565
3566 if ((signo = signal_from_string(s)) <= 0)
3567 if (startswith(s, "SIG"))
3568 return signal_from_string(s+3);
3569
3570 return signo;
3571}
3572
10717a1a
LP
3573void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3574
3575 assert(f);
3576 assert(name);
3577 assert(t);
3578
3579 if (!dual_timestamp_is_set(t))
3580 return;
3581
3582 fprintf(f, "%s=%llu %llu\n",
3583 name,
3584 (unsigned long long) t->realtime,
3585 (unsigned long long) t->monotonic);
3586}
3587
799fd0fd 3588void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
10717a1a
LP
3589 unsigned long long a, b;
3590
10717a1a
LP
3591 assert(value);
3592 assert(t);
3593
3594 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3595 log_debug("Failed to parse finish timestamp value %s", value);
3596 else {
3597 t->realtime = a;
3598 t->monotonic = b;
3599 }
3600}
3601
e23a0ce8
LP
3602char *fstab_node_to_udev_node(const char *p) {
3603 char *dn, *t, *u;
3604 int r;
3605
3606 /* FIXME: to follow udev's logic 100% we need to leave valid
3607 * UTF8 chars unescaped */
3608
3609 if (startswith(p, "LABEL=")) {
3610
3611 if (!(u = unquote(p+6, "\"\'")))
3612 return NULL;
3613
3614 t = xescape(u, "/ ");
3615 free(u);
3616
3617 if (!t)
3618 return NULL;
3619
3620 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3621 free(t);
3622
3623 if (r < 0)
3624 return NULL;
3625
3626 return dn;
3627 }
3628
3629 if (startswith(p, "UUID=")) {
3630
3631 if (!(u = unquote(p+5, "\"\'")))
3632 return NULL;
3633
3634 t = xescape(u, "/ ");
3635 free(u);
3636
3637 if (!t)
3638 return NULL;
3639
0058d7b9 3640 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
e23a0ce8
LP
3641 free(t);
3642
3643 if (r < 0)
3644 return NULL;
3645
3646 return dn;
3647 }
3648
3649 return strdup(p);
3650}
3651
e9ddabc2
LP
3652void filter_environ(const char *prefix) {
3653 int i, j;
3654 assert(prefix);
3655
3656 if (!environ)
3657 return;
3658
3659 for (i = 0, j = 0; environ[i]; i++) {
3660
3661 if (startswith(environ[i], prefix))
3662 continue;
3663
3664 environ[j++] = environ[i];
3665 }
3666
3667 environ[j] = NULL;
3668}
3669
f212ac12
LP
3670bool tty_is_vc(const char *tty) {
3671 assert(tty);
3672
3673 if (startswith(tty, "/dev/"))
3674 tty += 5;
3675
3676 return startswith(tty, "tty") &&
3677 tty[3] >= '0' && tty[3] <= '9';
3678}
3679
e3aa71c3 3680const char *default_term_for_tty(const char *tty) {
3030ccd7
LP
3681 char *active = NULL;
3682 const char *term;
3683
e3aa71c3
LP
3684 assert(tty);
3685
3686 if (startswith(tty, "/dev/"))
3687 tty += 5;
3688
3030ccd7
LP
3689 /* Resolve where /dev/console is pointing when determining
3690 * TERM */
3691 if (streq(tty, "console"))
3692 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3693 truncate_nl(active);
079a09fb
LP
3694
3695 /* If multiple log outputs are configured the
3696 * last one is what /dev/console points to */
3697 if ((tty = strrchr(active, ' ')))
3698 tty++;
3699 else
3700 tty = active;
3030ccd7
LP
3701 }
3702
f212ac12 3703 term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
3030ccd7 3704 free(active);
e3aa71c3 3705
3030ccd7 3706 return term;
e3aa71c3
LP
3707}
3708
07faed4f
LP
3709/* Returns a short identifier for the various VM implementations */
3710int detect_vm(const char **id) {
46a08e38
LP
3711
3712#if defined(__i386__) || defined(__x86_64__)
3713
3714 /* Both CPUID and DMI are x86 specific interfaces... */
3715
721bca57 3716 static const char *const dmi_vendors[] = {
46a08e38
LP
3717 "/sys/class/dmi/id/sys_vendor",
3718 "/sys/class/dmi/id/board_vendor",
3719 "/sys/class/dmi/id/bios_vendor"
3720 };
3721
4e08da90 3722 static const char dmi_vendor_table[] =
07faed4f
LP
3723 "QEMU\0" "qemu\0"
3724 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3725 "VMware\0" "vmware\0"
3726 "VMW\0" "vmware\0"
3727 "Microsoft Corporation\0" "microsoft\0"
3728 "innotek GmbH\0" "oracle\0"
3729 "Xen\0" "xen\0"
721bca57 3730 "Bochs\0" "bochs\0"
07faed4f
LP
3731 "\0";
3732
4e08da90 3733 static const char cpuid_vendor_table[] =
07faed4f
LP
3734 "XenVMMXenVMM\0" "xen\0"
3735 "KVMKVMKVM\0" "kvm\0"
3736 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
3737 "VMwareVMware\0" "vmware\0"
3738 /* http://msdn.microsoft.com/en-us/library/ff542428.aspx */
3739 "Microsoft Hv\0" "microsoft\0"
3740 "\0";
3741
3742 uint32_t eax, ecx;
46a08e38
LP
3743 union {
3744 uint32_t sig32[3];
3745 char text[13];
3746 } sig;
46a08e38 3747 unsigned i;
07faed4f 3748 const char *j, *k;
721bca57 3749 bool hypervisor;
46a08e38
LP
3750
3751 /* http://lwn.net/Articles/301888/ */
3752 zero(sig);
3753
46a08e38
LP
3754#if defined (__i386__)
3755#define REG_a "eax"
3756#define REG_b "ebx"
3757#elif defined (__amd64__)
3758#define REG_a "rax"
3759#define REG_b "rbx"
3760#endif
3761
07faed4f
LP
3762 /* First detect whether there is a hypervisor */
3763 eax = 1;
46a08e38
LP
3764 __asm__ __volatile__ (
3765 /* ebx/rbx is being used for PIC! */
3766 " push %%"REG_b" \n\t"
3767 " cpuid \n\t"
46a08e38
LP
3768 " pop %%"REG_b" \n\t"
3769
07faed4f 3770 : "=a" (eax), "=c" (ecx)
46a08e38
LP
3771 : "0" (eax)
3772 );
3773
721bca57
LP
3774 hypervisor = !!(ecx & ecx & 0x80000000U);
3775
3776 if (hypervisor) {
07faed4f
LP
3777
3778 /* There is a hypervisor, see what it is */
3779 eax = 0x40000000U;
3780 __asm__ __volatile__ (
3781 /* ebx/rbx is being used for PIC! */
3782 " push %%"REG_b" \n\t"
3783 " cpuid \n\t"
3784 " mov %%ebx, %1 \n\t"
3785 " pop %%"REG_b" \n\t"
3786
3787 : "=a" (eax), "=r" (sig.sig32[0]), "=c" (sig.sig32[1]), "=d" (sig.sig32[2])
3788 : "0" (eax)
3789 );
3790
3791 NULSTR_FOREACH_PAIR(j, k, cpuid_vendor_table)
3792 if (streq(sig.text, j)) {
3793
3794 if (id)
3795 *id = k;
3796
3797 return 1;
3798 }
721bca57 3799 }
07faed4f 3800
721bca57
LP
3801 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
3802 char *s;
3803 int r;
3804 const char *found = NULL;
3805
3806 if ((r = read_one_line_file(dmi_vendors[i], &s)) < 0) {
3807 if (r != -ENOENT)
3808 return r;
3809
3810 continue;
3811 }
3812
3813 NULSTR_FOREACH_PAIR(j, k, dmi_vendor_table)
3814 if (startswith(s, j))
3815 found = k;
3816 free(s);
3817
3818 if (found) {
3819 if (id)
3820 *id = found;
3821
3822 return 1;
3823 }
3824 }
3825
3826 if (hypervisor) {
07faed4f
LP
3827 if (id)
3828 *id = "other";
3829
3830 return 1;
3831 }
46a08e38 3832
721bca57 3833#endif
07faed4f
LP
3834 return 0;
3835}
3836
3837/* Returns a short identifier for the various VM/container implementations */
3838int detect_virtualization(const char **id) {
3839 int r;
3840
3841 /* Unfortunately most of these operations require root access
3842 * in one way or another */
3843 if (geteuid() != 0)
3844 return -EPERM;
3845
3846 if ((r = running_in_chroot()) > 0) {
3847 if (id)
3848 *id = "chroot";
3849
3850 return r;
3851 }
3852
3853 /* /proc/vz exists in container and outside of the container,
3854 * /proc/bc only outside of the container. */
3855 if (access("/proc/vz", F_OK) >= 0 &&
3856 access("/proc/bc", F_OK) < 0) {
3857
3858 if (id)
3859 *id = "openvz";
3860
3861 return 1;
3862 }
3863
3864 return detect_vm(id);
46a08e38
LP
3865}
3866
83cc030f
LP
3867void execute_directory(const char *directory, DIR *d, char *argv[]) {
3868 DIR *_d = NULL;
3869 struct dirent *de;
3870 Hashmap *pids = NULL;
3871
3872 assert(directory);
3873
3874 /* Executes all binaries in a directory in parallel and waits
3875 * until all they all finished. */
3876
3877 if (!d) {
3878 if (!(_d = opendir(directory))) {
3879
3880 if (errno == ENOENT)
3881 return;
3882
3883 log_error("Failed to enumerate directory %s: %m", directory);
3884 return;
3885 }
3886
3887 d = _d;
3888 }
3889
3890 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3891 log_error("Failed to allocate set.");
3892 goto finish;
3893 }
3894
3895 while ((de = readdir(d))) {
3896 char *path;
3897 pid_t pid;
3898 int k;
3899
3900 if (ignore_file(de->d_name))
3901 continue;
3902
3903 if (de->d_type != DT_REG &&
3904 de->d_type != DT_LNK &&
3905 de->d_type != DT_UNKNOWN)
3906 continue;
3907
3908 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3909 log_error("Out of memory");
3910 continue;
3911 }
3912
3913 if ((pid = fork()) < 0) {
3914 log_error("Failed to fork: %m");
3915 free(path);
3916 continue;
3917 }
3918
3919 if (pid == 0) {
3920 char *_argv[2];
3921 /* Child */
3922
3923 if (!argv) {
3924 _argv[0] = path;
3925 _argv[1] = NULL;
3926 argv = _argv;
3927 } else
3928 if (!argv[0])
3929 argv[0] = path;
3930
3931 execv(path, argv);
3932
3933 log_error("Failed to execute %s: %m", path);
3934 _exit(EXIT_FAILURE);
3935 }
3936
3937 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3938
3939 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3940 log_error("Failed to add PID to set: %s", strerror(-k));
3941 free(path);
3942 }
3943 }
3944
3945 while (!hashmap_isempty(pids)) {
3946 siginfo_t si;
3947 char *path;
3948
3949 zero(si);
3950 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
3951
3952 if (errno == EINTR)
3953 continue;
3954
3955 log_error("waitid() failed: %m");
3956 goto finish;
3957 }
3958
3959 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3960 if (!is_clean_exit(si.si_code, si.si_status)) {
3961 if (si.si_code == CLD_EXITED)
3962 log_error("%s exited with exit status %i.", path, si.si_status);
3963 else
3964 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3965 } else
3966 log_debug("%s exited successfully.", path);
3967
3968 free(path);
3969 }
3970 }
3971
3972finish:
3973 if (_d)
3974 closedir(_d);
3975
3976 if (pids)
3977 hashmap_free_free(pids);
3978}
3979
1dccbe19
LP
3980static const char *const ioprio_class_table[] = {
3981 [IOPRIO_CLASS_NONE] = "none",
3982 [IOPRIO_CLASS_RT] = "realtime",
3983 [IOPRIO_CLASS_BE] = "best-effort",
3984 [IOPRIO_CLASS_IDLE] = "idle"
3985};
3986
3987DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
3988
3989static const char *const sigchld_code_table[] = {
3990 [CLD_EXITED] = "exited",
3991 [CLD_KILLED] = "killed",
3992 [CLD_DUMPED] = "dumped",
3993 [CLD_TRAPPED] = "trapped",
3994 [CLD_STOPPED] = "stopped",
3995 [CLD_CONTINUED] = "continued",
3996};
3997
3998DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3999
4000static const char *const log_facility_table[LOG_NFACILITIES] = {
4001 [LOG_FAC(LOG_KERN)] = "kern",
4002 [LOG_FAC(LOG_USER)] = "user",
4003 [LOG_FAC(LOG_MAIL)] = "mail",
4004 [LOG_FAC(LOG_DAEMON)] = "daemon",
4005 [LOG_FAC(LOG_AUTH)] = "auth",
4006 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4007 [LOG_FAC(LOG_LPR)] = "lpr",
4008 [LOG_FAC(LOG_NEWS)] = "news",
4009 [LOG_FAC(LOG_UUCP)] = "uucp",
4010 [LOG_FAC(LOG_CRON)] = "cron",
4011 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4012 [LOG_FAC(LOG_FTP)] = "ftp",
4013 [LOG_FAC(LOG_LOCAL0)] = "local0",
4014 [LOG_FAC(LOG_LOCAL1)] = "local1",
4015 [LOG_FAC(LOG_LOCAL2)] = "local2",
4016 [LOG_FAC(LOG_LOCAL3)] = "local3",
4017 [LOG_FAC(LOG_LOCAL4)] = "local4",
4018 [LOG_FAC(LOG_LOCAL5)] = "local5",
4019 [LOG_FAC(LOG_LOCAL6)] = "local6",
4020 [LOG_FAC(LOG_LOCAL7)] = "local7"
4021};
4022
4023DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
4024
4025static const char *const log_level_table[] = {
4026 [LOG_EMERG] = "emerg",
4027 [LOG_ALERT] = "alert",
4028 [LOG_CRIT] = "crit",
4029 [LOG_ERR] = "err",
4030 [LOG_WARNING] = "warning",
4031 [LOG_NOTICE] = "notice",
4032 [LOG_INFO] = "info",
4033 [LOG_DEBUG] = "debug"
4034};
4035
4036DEFINE_STRING_TABLE_LOOKUP(log_level, int);
4037
4038static const char* const sched_policy_table[] = {
4039 [SCHED_OTHER] = "other",
4040 [SCHED_BATCH] = "batch",
4041 [SCHED_IDLE] = "idle",
4042 [SCHED_FIFO] = "fifo",
4043 [SCHED_RR] = "rr"
4044};
4045
4046DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
4047
4048static const char* const rlimit_table[] = {
4049 [RLIMIT_CPU] = "LimitCPU",
4050 [RLIMIT_FSIZE] = "LimitFSIZE",
4051 [RLIMIT_DATA] = "LimitDATA",
4052 [RLIMIT_STACK] = "LimitSTACK",
4053 [RLIMIT_CORE] = "LimitCORE",
4054 [RLIMIT_RSS] = "LimitRSS",
4055 [RLIMIT_NOFILE] = "LimitNOFILE",
4056 [RLIMIT_AS] = "LimitAS",
4057 [RLIMIT_NPROC] = "LimitNPROC",
4058 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4059 [RLIMIT_LOCKS] = "LimitLOCKS",
4060 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4061 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4062 [RLIMIT_NICE] = "LimitNICE",
4063 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4064 [RLIMIT_RTTIME] = "LimitRTTIME"
4065};
4066
4067DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4fd5948e
LP
4068
4069static const char* const ip_tos_table[] = {
4070 [IPTOS_LOWDELAY] = "low-delay",
4071 [IPTOS_THROUGHPUT] = "throughput",
4072 [IPTOS_RELIABILITY] = "reliability",
4073 [IPTOS_LOWCOST] = "low-cost",
4074};
4075
4076DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
2e22afe9
LP
4077
4078static const char *const signal_table[] = {
4079 [SIGHUP] = "HUP",
4080 [SIGINT] = "INT",
4081 [SIGQUIT] = "QUIT",
4082 [SIGILL] = "ILL",
4083 [SIGTRAP] = "TRAP",
4084 [SIGABRT] = "ABRT",
4085 [SIGBUS] = "BUS",
4086 [SIGFPE] = "FPE",
4087 [SIGKILL] = "KILL",
4088 [SIGUSR1] = "USR1",
4089 [SIGSEGV] = "SEGV",
4090 [SIGUSR2] = "USR2",
4091 [SIGPIPE] = "PIPE",
4092 [SIGALRM] = "ALRM",
4093 [SIGTERM] = "TERM",
f26ee0b9
LP
4094#ifdef SIGSTKFLT
4095 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4096#endif
2e22afe9
LP
4097 [SIGCHLD] = "CHLD",
4098 [SIGCONT] = "CONT",
4099 [SIGSTOP] = "STOP",
4100 [SIGTSTP] = "TSTP",
4101 [SIGTTIN] = "TTIN",
4102 [SIGTTOU] = "TTOU",
4103 [SIGURG] = "URG",
4104 [SIGXCPU] = "XCPU",
4105 [SIGXFSZ] = "XFSZ",
4106 [SIGVTALRM] = "VTALRM",
4107 [SIGPROF] = "PROF",
4108 [SIGWINCH] = "WINCH",
4109 [SIGIO] = "IO",
4110 [SIGPWR] = "PWR",
4111 [SIGSYS] = "SYS"
4112};
4113
4114DEFINE_STRING_TABLE_LOOKUP(signal, int);