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