]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/util.c
selinux: properly query policy for FIFO files
[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
871d7de4
LP
1662char *format_timespan(char *buf, size_t l, usec_t t) {
1663 static const struct {
1664 const char *suffix;
1665 usec_t usec;
1666 } table[] = {
1667 { "w", USEC_PER_WEEK },
1668 { "d", USEC_PER_DAY },
1669 { "h", USEC_PER_HOUR },
1670 { "min", USEC_PER_MINUTE },
1671 { "s", USEC_PER_SEC },
1672 { "ms", USEC_PER_MSEC },
1673 { "us", 1 },
1674 };
1675
1676 unsigned i;
1677 char *p = buf;
1678
1679 assert(buf);
1680 assert(l > 0);
1681
1682 if (t == (usec_t) -1)
1683 return NULL;
1684
4502d22c
LP
1685 if (t == 0) {
1686 snprintf(p, l, "0");
1687 p[l-1] = 0;
1688 return p;
1689 }
1690
871d7de4
LP
1691 /* The result of this function can be parsed with parse_usec */
1692
1693 for (i = 0; i < ELEMENTSOF(table); i++) {
1694 int k;
1695 size_t n;
1696
1697 if (t < table[i].usec)
1698 continue;
1699
1700 if (l <= 1)
1701 break;
1702
1703 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1704 n = MIN((size_t) k, l);
1705
1706 l -= n;
1707 p += n;
1708
1709 t %= table[i].usec;
1710 }
1711
1712 *p = 0;
1713
1714 return buf;
1715}
1716
42856c10
LP
1717bool fstype_is_network(const char *fstype) {
1718 static const char * const table[] = {
1719 "cifs",
1720 "smbfs",
1721 "ncpfs",
1722 "nfs",
ca139f94
LP
1723 "nfs4",
1724 "gfs",
1725 "gfs2"
42856c10
LP
1726 };
1727
1728 unsigned i;
1729
1730 for (i = 0; i < ELEMENTSOF(table); i++)
1731 if (streq(table[i], fstype))
1732 return true;
1733
1734 return false;
1735}
1736
601f6a1e
LP
1737int chvt(int vt) {
1738 int fd, r = 0;
1739
1740 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1741 return -errno;
1742
1743 if (vt < 0) {
1744 int tiocl[2] = {
1745 TIOCL_GETKMSGREDIRECT,
1746 0
1747 };
1748
1749 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1750 return -errno;
1751
1752 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1753 }
1754
1755 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1756 r = -errno;
1757
a16e1123 1758 close_nointr_nofail(r);
601f6a1e
LP
1759 return r;
1760}
1761
80876c20
LP
1762int read_one_char(FILE *f, char *ret, bool *need_nl) {
1763 struct termios old_termios, new_termios;
1764 char c;
1765 char line[1024];
1766
1767 assert(f);
1768 assert(ret);
1769
1770 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1771 new_termios = old_termios;
1772
1773 new_termios.c_lflag &= ~ICANON;
1774 new_termios.c_cc[VMIN] = 1;
1775 new_termios.c_cc[VTIME] = 0;
1776
1777 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1778 size_t k;
1779
1780 k = fread(&c, 1, 1, f);
1781
1782 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1783
1784 if (k <= 0)
1785 return -EIO;
1786
1787 if (need_nl)
1788 *need_nl = c != '\n';
1789
1790 *ret = c;
1791 return 0;
1792 }
1793 }
1794
1795 if (!(fgets(line, sizeof(line), f)))
1796 return -EIO;
1797
1798 truncate_nl(line);
1799
1800 if (strlen(line) != 1)
1801 return -EBADMSG;
1802
1803 if (need_nl)
1804 *need_nl = false;
1805
1806 *ret = line[0];
1807 return 0;
1808}
1809
1810int ask(char *ret, const char *replies, const char *text, ...) {
1811 assert(ret);
1812 assert(replies);
1813 assert(text);
1814
1815 for (;;) {
1816 va_list ap;
1817 char c;
1818 int r;
1819 bool need_nl = true;
1820
b1b2dc0c
LP
1821 fputs("\x1B[1m", stdout);
1822
80876c20
LP
1823 va_start(ap, text);
1824 vprintf(text, ap);
1825 va_end(ap);
1826
b1b2dc0c
LP
1827 fputs("\x1B[0m", stdout);
1828
80876c20
LP
1829 fflush(stdout);
1830
1831 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1832
1833 if (r == -EBADMSG) {
1834 puts("Bad input, please try again.");
1835 continue;
1836 }
1837
1838 putchar('\n');
1839 return r;
1840 }
1841
1842 if (need_nl)
1843 putchar('\n');
1844
1845 if (strchr(replies, c)) {
1846 *ret = c;
1847 return 0;
1848 }
1849
1850 puts("Read unexpected character, please try again.");
1851 }
1852}
1853
1854int reset_terminal(int fd) {
1855 struct termios termios;
1856 int r = 0;
3fe5e5d4
LP
1857 long arg;
1858
1859 /* Set terminal to some sane defaults */
80876c20
LP
1860
1861 assert(fd >= 0);
1862
3fe5e5d4
LP
1863 /* First, unlock termios */
1864 zero(termios);
1865 ioctl(fd, TIOCSLCKTRMIOS, &termios);
1866
1867 /* Disable exclusive mode, just in case */
1868 ioctl(fd, TIOCNXCL);
1869
1870 /* Enable console unicode mode */
1871 arg = K_UNICODE;
1872 ioctl(fd, KDSKBMODE, &arg);
80876c20
LP
1873
1874 if (tcgetattr(fd, &termios) < 0) {
1875 r = -errno;
1876 goto finish;
1877 }
1878
aaf694ca
LP
1879 /* We only reset the stuff that matters to the software. How
1880 * hardware is set up we don't touch assuming that somebody
1881 * else will do that for us */
1882
1883 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
80876c20
LP
1884 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1885 termios.c_oflag |= ONLCR;
1886 termios.c_cflag |= CREAD;
1887 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1888
1889 termios.c_cc[VINTR] = 03; /* ^C */
1890 termios.c_cc[VQUIT] = 034; /* ^\ */
1891 termios.c_cc[VERASE] = 0177;
1892 termios.c_cc[VKILL] = 025; /* ^X */
1893 termios.c_cc[VEOF] = 04; /* ^D */
1894 termios.c_cc[VSTART] = 021; /* ^Q */
1895 termios.c_cc[VSTOP] = 023; /* ^S */
1896 termios.c_cc[VSUSP] = 032; /* ^Z */
1897 termios.c_cc[VLNEXT] = 026; /* ^V */
1898 termios.c_cc[VWERASE] = 027; /* ^W */
1899 termios.c_cc[VREPRINT] = 022; /* ^R */
aaf694ca
LP
1900 termios.c_cc[VEOL] = 0;
1901 termios.c_cc[VEOL2] = 0;
80876c20
LP
1902
1903 termios.c_cc[VTIME] = 0;
1904 termios.c_cc[VMIN] = 1;
1905
1906 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1907 r = -errno;
1908
1909finish:
1910 /* Just in case, flush all crap out */
1911 tcflush(fd, TCIOFLUSH);
1912
1913 return r;
1914}
1915
1916int open_terminal(const char *name, int mode) {
1917 int fd, r;
1918
1919 if ((fd = open(name, mode)) < 0)
1920 return -errno;
1921
1922 if ((r = isatty(fd)) < 0) {
1923 close_nointr_nofail(fd);
1924 return -errno;
1925 }
1926
1927 if (!r) {
1928 close_nointr_nofail(fd);
1929 return -ENOTTY;
1930 }
1931
1932 return fd;
1933}
1934
1935int flush_fd(int fd) {
1936 struct pollfd pollfd;
1937
1938 zero(pollfd);
1939 pollfd.fd = fd;
1940 pollfd.events = POLLIN;
1941
1942 for (;;) {
1943 char buf[1024];
1944 ssize_t l;
1945 int r;
1946
1947 if ((r = poll(&pollfd, 1, 0)) < 0) {
1948
1949 if (errno == EINTR)
1950 continue;
1951
1952 return -errno;
1953 }
1954
1955 if (r == 0)
1956 return 0;
1957
1958 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1959
1960 if (errno == EINTR)
1961 continue;
1962
1963 if (errno == EAGAIN)
1964 return 0;
1965
1966 return -errno;
1967 }
1968
1969 if (l <= 0)
1970 return 0;
1971 }
1972}
1973
21de3988 1974int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
bab45044 1975 int fd = -1, notify = -1, r, wd = -1;
80876c20
LP
1976
1977 assert(name);
1978
1979 /* We use inotify to be notified when the tty is closed. We
1980 * create the watch before checking if we can actually acquire
1981 * it, so that we don't lose any event.
1982 *
1983 * Note: strictly speaking this actually watches for the
1984 * device being closed, it does *not* really watch whether a
1985 * tty loses its controlling process. However, unless some
1986 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1987 * its tty otherwise this will not become a problem. As long
1988 * as the administrator makes sure not configure any service
1989 * on the same tty as an untrusted user this should not be a
1990 * problem. (Which he probably should not do anyway.) */
1991
1992 if (!fail && !force) {
1993 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1994 r = -errno;
1995 goto fail;
1996 }
1997
1998 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1999 r = -errno;
2000 goto fail;
2001 }
2002 }
2003
2004 for (;;) {
e3d1855b
LP
2005 if (notify >= 0)
2006 if ((r = flush_fd(notify)) < 0)
2007 goto fail;
80876c20
LP
2008
2009 /* We pass here O_NOCTTY only so that we can check the return
2010 * value TIOCSCTTY and have a reliable way to figure out if we
2011 * successfully became the controlling process of the tty */
2012 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2013 return -errno;
2014
2015 /* First, try to get the tty */
21de3988
LP
2016 r = ioctl(fd, TIOCSCTTY, force);
2017
2018 /* Sometimes it makes sense to ignore TIOCSCTTY
2019 * returning EPERM, i.e. when very likely we already
2020 * are have this controlling terminal. */
2021 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2022 r = 0;
2023
2024 if (r < 0 && (force || fail || errno != EPERM)) {
80876c20
LP
2025 r = -errno;
2026 goto fail;
2027 }
2028
2029 if (r >= 0)
2030 break;
2031
2032 assert(!fail);
2033 assert(!force);
2034 assert(notify >= 0);
2035
2036 for (;;) {
2037 struct inotify_event e;
2038 ssize_t l;
2039
2040 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
2041
2042 if (l < 0) {
2043
2044 if (errno == EINTR)
2045 continue;
2046
2047 r = -errno;
2048 } else
2049 r = -EIO;
2050
2051 goto fail;
2052 }
2053
2054 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
7bc0351d 2055 r = -EIO;
80876c20
LP
2056 goto fail;
2057 }
2058
2059 break;
2060 }
2061
2062 /* We close the tty fd here since if the old session
2063 * ended our handle will be dead. It's important that
2064 * we do this after sleeping, so that we don't enter
2065 * an endless loop. */
2066 close_nointr_nofail(fd);
2067 }
2068
2069 if (notify >= 0)
a16e1123 2070 close_nointr_nofail(notify);
80876c20
LP
2071
2072 if ((r = reset_terminal(fd)) < 0)
2073 log_warning("Failed to reset terminal: %s", strerror(-r));
2074
2075 return fd;
2076
2077fail:
2078 if (fd >= 0)
a16e1123 2079 close_nointr_nofail(fd);
80876c20
LP
2080
2081 if (notify >= 0)
a16e1123 2082 close_nointr_nofail(notify);
80876c20
LP
2083
2084 return r;
2085}
2086
2087int release_terminal(void) {
2088 int r = 0, fd;
57cd2192 2089 struct sigaction sa_old, sa_new;
80876c20 2090
57cd2192 2091 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
80876c20
LP
2092 return -errno;
2093
57cd2192
LP
2094 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2095 * by our own TIOCNOTTY */
2096
2097 zero(sa_new);
2098 sa_new.sa_handler = SIG_IGN;
2099 sa_new.sa_flags = SA_RESTART;
2100 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2101
80876c20
LP
2102 if (ioctl(fd, TIOCNOTTY) < 0)
2103 r = -errno;
2104
57cd2192
LP
2105 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2106
80876c20
LP
2107 close_nointr_nofail(fd);
2108 return r;
2109}
2110
9a34ec5f
LP
2111int sigaction_many(const struct sigaction *sa, ...) {
2112 va_list ap;
2113 int r = 0, sig;
2114
2115 va_start(ap, sa);
2116 while ((sig = va_arg(ap, int)) > 0)
2117 if (sigaction(sig, sa, NULL) < 0)
2118 r = -errno;
2119 va_end(ap);
2120
2121 return r;
2122}
2123
2124int ignore_signals(int sig, ...) {
a337c6fc 2125 struct sigaction sa;
9a34ec5f
LP
2126 va_list ap;
2127 int r = 0;
a337c6fc
LP
2128
2129 zero(sa);
2130 sa.sa_handler = SIG_IGN;
2131 sa.sa_flags = SA_RESTART;
2132
9a34ec5f
LP
2133 if (sigaction(sig, &sa, NULL) < 0)
2134 r = -errno;
2135
2136 va_start(ap, sig);
2137 while ((sig = va_arg(ap, int)) > 0)
2138 if (sigaction(sig, &sa, NULL) < 0)
2139 r = -errno;
2140 va_end(ap);
2141
2142 return r;
2143}
2144
2145int default_signals(int sig, ...) {
2146 struct sigaction sa;
2147 va_list ap;
2148 int r = 0;
2149
2150 zero(sa);
2151 sa.sa_handler = SIG_DFL;
2152 sa.sa_flags = SA_RESTART;
2153
2154 if (sigaction(sig, &sa, NULL) < 0)
2155 r = -errno;
2156
2157 va_start(ap, sig);
2158 while ((sig = va_arg(ap, int)) > 0)
2159 if (sigaction(sig, &sa, NULL) < 0)
2160 r = -errno;
2161 va_end(ap);
2162
2163 return r;
a337c6fc
LP
2164}
2165
8d567588
LP
2166int close_pipe(int p[]) {
2167 int a = 0, b = 0;
2168
2169 assert(p);
2170
2171 if (p[0] >= 0) {
2172 a = close_nointr(p[0]);
2173 p[0] = -1;
2174 }
2175
2176 if (p[1] >= 0) {
2177 b = close_nointr(p[1]);
2178 p[1] = -1;
2179 }
2180
2181 return a < 0 ? a : b;
2182}
2183
eb22ac37 2184ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
8d567588
LP
2185 uint8_t *p;
2186 ssize_t n = 0;
2187
2188 assert(fd >= 0);
2189 assert(buf);
2190
2191 p = buf;
2192
2193 while (nbytes > 0) {
2194 ssize_t k;
2195
2196 if ((k = read(fd, p, nbytes)) <= 0) {
2197
eb22ac37 2198 if (k < 0 && errno == EINTR)
8d567588
LP
2199 continue;
2200
eb22ac37 2201 if (k < 0 && errno == EAGAIN && do_poll) {
8d567588
LP
2202 struct pollfd pollfd;
2203
2204 zero(pollfd);
2205 pollfd.fd = fd;
2206 pollfd.events = POLLIN;
2207
2208 if (poll(&pollfd, 1, -1) < 0) {
2209 if (errno == EINTR)
2210 continue;
2211
2212 return n > 0 ? n : -errno;
2213 }
2214
2215 if (pollfd.revents != POLLIN)
2216 return n > 0 ? n : -EIO;
2217
2218 continue;
2219 }
2220
2221 return n > 0 ? n : (k < 0 ? -errno : 0);
2222 }
2223
2224 p += k;
2225 nbytes -= k;
2226 n += k;
2227 }
2228
2229 return n;
2230}
2231
eb22ac37
LP
2232ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2233 const uint8_t *p;
2234 ssize_t n = 0;
2235
2236 assert(fd >= 0);
2237 assert(buf);
2238
2239 p = buf;
2240
2241 while (nbytes > 0) {
2242 ssize_t k;
2243
2244 if ((k = write(fd, p, nbytes)) <= 0) {
2245
2246 if (k < 0 && errno == EINTR)
2247 continue;
2248
2249 if (k < 0 && errno == EAGAIN && do_poll) {
2250 struct pollfd pollfd;
2251
2252 zero(pollfd);
2253 pollfd.fd = fd;
2254 pollfd.events = POLLOUT;
2255
2256 if (poll(&pollfd, 1, -1) < 0) {
2257 if (errno == EINTR)
2258 continue;
2259
2260 return n > 0 ? n : -errno;
2261 }
2262
2263 if (pollfd.revents != POLLOUT)
2264 return n > 0 ? n : -EIO;
2265
2266 continue;
2267 }
2268
2269 return n > 0 ? n : (k < 0 ? -errno : 0);
2270 }
2271
2272 p += k;
2273 nbytes -= k;
2274 n += k;
2275 }
2276
2277 return n;
2278}
2279
8d567588
LP
2280int path_is_mount_point(const char *t) {
2281 struct stat a, b;
35d2e7ec
LP
2282 char *parent;
2283 int r;
8d567588
LP
2284
2285 if (lstat(t, &a) < 0) {
8d567588
LP
2286 if (errno == ENOENT)
2287 return 0;
2288
2289 return -errno;
2290 }
2291
35d2e7ec
LP
2292 if ((r = parent_of_path(t, &parent)) < 0)
2293 return r;
8d567588 2294
35d2e7ec
LP
2295 r = lstat(parent, &b);
2296 free(parent);
8d567588 2297
35d2e7ec
LP
2298 if (r < 0)
2299 return -errno;
8d567588
LP
2300
2301 return a.st_dev != b.st_dev;
2302}
2303
24a6e4a4
LP
2304int parse_usec(const char *t, usec_t *usec) {
2305 static const struct {
2306 const char *suffix;
2307 usec_t usec;
2308 } table[] = {
2309 { "sec", USEC_PER_SEC },
2310 { "s", USEC_PER_SEC },
2311 { "min", USEC_PER_MINUTE },
2312 { "hr", USEC_PER_HOUR },
2313 { "h", USEC_PER_HOUR },
2314 { "d", USEC_PER_DAY },
2315 { "w", USEC_PER_WEEK },
2316 { "msec", USEC_PER_MSEC },
2317 { "ms", USEC_PER_MSEC },
2318 { "m", USEC_PER_MINUTE },
2319 { "usec", 1ULL },
2320 { "us", 1ULL },
2321 { "", USEC_PER_SEC },
2322 };
2323
2324 const char *p;
2325 usec_t r = 0;
2326
2327 assert(t);
2328 assert(usec);
2329
2330 p = t;
2331 do {
2332 long long l;
2333 char *e;
2334 unsigned i;
2335
2336 errno = 0;
2337 l = strtoll(p, &e, 10);
2338
2339 if (errno != 0)
2340 return -errno;
2341
2342 if (l < 0)
2343 return -ERANGE;
2344
2345 if (e == p)
2346 return -EINVAL;
2347
2348 e += strspn(e, WHITESPACE);
2349
2350 for (i = 0; i < ELEMENTSOF(table); i++)
2351 if (startswith(e, table[i].suffix)) {
2352 r += (usec_t) l * table[i].usec;
2353 p = e + strlen(table[i].suffix);
2354 break;
2355 }
2356
2357 if (i >= ELEMENTSOF(table))
2358 return -EINVAL;
2359
2360 } while (*p != 0);
2361
2362 *usec = r;
2363
2364 return 0;
2365}
2366
843d2643
LP
2367int make_stdio(int fd) {
2368 int r, s, t;
2369
2370 assert(fd >= 0);
2371
2372 r = dup2(fd, STDIN_FILENO);
2373 s = dup2(fd, STDOUT_FILENO);
2374 t = dup2(fd, STDERR_FILENO);
2375
2376 if (fd >= 3)
2377 close_nointr_nofail(fd);
2378
2379 if (r < 0 || s < 0 || t < 0)
2380 return -errno;
2381
2382 return 0;
2383}
2384
cb8a8f78
LP
2385bool is_clean_exit(int code, int status) {
2386
2387 if (code == CLD_EXITED)
2388 return status == 0;
2389
2390 /* If a daemon does not implement handlers for some of the
2391 * signals that's not considered an unclean shutdown */
2392 if (code == CLD_KILLED)
2393 return
2394 status == SIGHUP ||
2395 status == SIGINT ||
2396 status == SIGTERM ||
2397 status == SIGPIPE;
2398
2399 return false;
2400}
2401
d06dacd0
LP
2402bool is_clean_exit_lsb(int code, int status) {
2403
2404 if (is_clean_exit(code, status))
2405 return true;
2406
2407 return
2408 code == CLD_EXITED &&
2409 (status == EXIT_NOTINSTALLED || status == EXIT_NOTCONFIGURED);
2410}
2411
8407a5d0
LP
2412bool is_device_path(const char *path) {
2413
2414 /* Returns true on paths that refer to a device, either in
2415 * sysfs or in /dev */
2416
2417 return
2418 path_startswith(path, "/dev/") ||
2419 path_startswith(path, "/sys/");
2420}
2421
01f78473
LP
2422int dir_is_empty(const char *path) {
2423 DIR *d;
2424 int r;
2425 struct dirent buf, *de;
2426
2427 if (!(d = opendir(path)))
2428 return -errno;
2429
2430 for (;;) {
2431 if ((r = readdir_r(d, &buf, &de)) > 0) {
2432 r = -r;
2433 break;
2434 }
2435
2436 if (!de) {
2437 r = 1;
2438 break;
2439 }
2440
2441 if (!ignore_file(de->d_name)) {
2442 r = 0;
2443 break;
2444 }
2445 }
2446
2447 closedir(d);
2448 return r;
2449}
2450
d3782d60
LP
2451unsigned long long random_ull(void) {
2452 int fd;
2453 uint64_t ull;
2454 ssize_t r;
2455
2456 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2457 goto fallback;
2458
eb22ac37 2459 r = loop_read(fd, &ull, sizeof(ull), true);
d3782d60
LP
2460 close_nointr_nofail(fd);
2461
2462 if (r != sizeof(ull))
2463 goto fallback;
2464
2465 return ull;
2466
2467fallback:
2468 return random() * RAND_MAX + random();
2469}
2470
5b6319dc
LP
2471void rename_process(const char name[8]) {
2472 assert(name);
2473
2474 prctl(PR_SET_NAME, name);
2475
2476 /* This is a like a poor man's setproctitle(). The string
2477 * passed should fit in 7 chars (i.e. the length of
2478 * "systemd") */
2479
2480 if (program_invocation_name)
2481 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2482}
2483
7d793605
LP
2484void sigset_add_many(sigset_t *ss, ...) {
2485 va_list ap;
2486 int sig;
2487
2488 assert(ss);
2489
2490 va_start(ap, ss);
2491 while ((sig = va_arg(ap, int)) > 0)
2492 assert_se(sigaddset(ss, sig) == 0);
2493 va_end(ap);
2494}
2495
ef2f1067
LP
2496char* gethostname_malloc(void) {
2497 struct utsname u;
2498
2499 assert_se(uname(&u) >= 0);
2500
2501 if (u.nodename[0])
2502 return strdup(u.nodename);
2503
2504 return strdup(u.sysname);
2505}
2506
2507char* getlogname_malloc(void) {
2508 uid_t uid;
2509 long bufsize;
2510 char *buf, *name;
2511 struct passwd pwbuf, *pw = NULL;
2512 struct stat st;
2513
2514 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2515 uid = st.st_uid;
2516 else
2517 uid = getuid();
2518
2519 /* Shortcut things to avoid NSS lookups */
2520 if (uid == 0)
2521 return strdup("root");
2522
2523 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2524 bufsize = 4096;
2525
2526 if (!(buf = malloc(bufsize)))
2527 return NULL;
2528
2529 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2530 name = strdup(pw->pw_name);
2531 free(buf);
2532 return name;
2533 }
2534
2535 free(buf);
2536
2537 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2538 return NULL;
2539
2540 return name;
2541}
2542
8c6db833
LP
2543int getttyname_malloc(char **r) {
2544 char path[PATH_MAX], *p, *c;
618e02c7 2545 int k;
8c6db833
LP
2546
2547 assert(r);
ef2f1067 2548
618e02c7
LP
2549 if ((k = ttyname_r(STDIN_FILENO, path, sizeof(path))) != 0)
2550 return -k;
ef2f1067
LP
2551
2552 char_array_0(path);
2553
2554 p = path;
2555 if (startswith(path, "/dev/"))
2556 p += 5;
2557
8c6db833
LP
2558 if (!(c = strdup(p)))
2559 return -ENOMEM;
2560
2561 *r = c;
2562 return 0;
2563}
2564
2565static int rm_rf_children(int fd, bool only_dirs) {
2566 DIR *d;
2567 int ret = 0;
2568
2569 assert(fd >= 0);
2570
2571 /* This returns the first error we run into, but nevertheless
2572 * tries to go on */
2573
2574 if (!(d = fdopendir(fd))) {
2575 close_nointr_nofail(fd);
4c633005
LP
2576
2577 return errno == ENOENT ? 0 : -errno;
8c6db833
LP
2578 }
2579
2580 for (;;) {
2581 struct dirent buf, *de;
2582 bool is_dir;
2583 int r;
2584
2585 if ((r = readdir_r(d, &buf, &de)) != 0) {
2586 if (ret == 0)
2587 ret = -r;
2588 break;
2589 }
2590
2591 if (!de)
2592 break;
2593
2594 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2595 continue;
2596
2597 if (de->d_type == DT_UNKNOWN) {
2598 struct stat st;
2599
2600 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
4c633005 2601 if (ret == 0 && errno != ENOENT)
8c6db833
LP
2602 ret = -errno;
2603 continue;
2604 }
2605
2606 is_dir = S_ISDIR(st.st_mode);
2607 } else
2608 is_dir = de->d_type == DT_DIR;
2609
2610 if (is_dir) {
2611 int subdir_fd;
2612
2613 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
4c633005 2614 if (ret == 0 && errno != ENOENT)
8c6db833
LP
2615 ret = -errno;
2616 continue;
2617 }
2618
2619 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2620 if (ret == 0)
2621 ret = r;
2622 }
2623
2624 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
4c633005 2625 if (ret == 0 && errno != ENOENT)
8c6db833
LP
2626 ret = -errno;
2627 }
2628 } else if (!only_dirs) {
2629
2630 if (unlinkat(fd, de->d_name, 0) < 0) {
4c633005 2631 if (ret == 0 && errno != ENOENT)
8c6db833
LP
2632 ret = -errno;
2633 }
2634 }
2635 }
2636
2637 closedir(d);
2638
2639 return ret;
2640}
2641
2642int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2643 int fd;
2644 int r;
2645
2646 assert(path);
2647
2648 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2649
2650 if (errno != ENOTDIR)
2651 return -errno;
2652
2653 if (delete_root && !only_dirs)
2654 if (unlink(path) < 0)
2655 return -errno;
2656
2657 return 0;
2658 }
2659
2660 r = rm_rf_children(fd, only_dirs);
2661
2662 if (delete_root)
2663 if (rmdir(path) < 0) {
2664 if (r == 0)
2665 r = -errno;
2666 }
2667
2668 return r;
2669}
2670
2671int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2672 assert(path);
2673
2674 /* Under the assumption that we are running privileged we
2675 * first change the access mode and only then hand out
2676 * ownership to avoid a window where access is too open. */
2677
2678 if (chmod(path, mode) < 0)
2679 return -errno;
2680
2681 if (chown(path, uid, gid) < 0)
2682 return -errno;
2683
2684 return 0;
ef2f1067
LP
2685}
2686
82c121a4
LP
2687cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2688 cpu_set_t *r;
2689 unsigned n = 1024;
2690
2691 /* Allocates the cpuset in the right size */
2692
2693 for (;;) {
2694 if (!(r = CPU_ALLOC(n)))
2695 return NULL;
2696
2697 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2698 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2699
2700 if (ncpus)
2701 *ncpus = n;
2702
2703 return r;
2704 }
2705
2706 CPU_FREE(r);
2707
2708 if (errno != EINVAL)
2709 return NULL;
2710
2711 n *= 2;
2712 }
2713}
2714
9e58ff9c
LP
2715void status_vprintf(const char *format, va_list ap) {
2716 char *s = NULL;
2717 int fd = -1;
2718
2719 assert(format);
2720
2721 /* This independent of logging, as status messages are
2722 * optional and go exclusively to the console. */
2723
2724 if (vasprintf(&s, format, ap) < 0)
2725 goto finish;
2726
2727 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2728 goto finish;
2729
2730 write(fd, s, strlen(s));
2731
2732finish:
2733 free(s);
2734
2735 if (fd >= 0)
2736 close_nointr_nofail(fd);
2737}
2738
c846ff47
LP
2739void status_printf(const char *format, ...) {
2740 va_list ap;
2741
2742 assert(format);
2743
2744 va_start(ap, format);
2745 status_vprintf(format, ap);
2746 va_end(ap);
2747}
2748
2749void status_welcome(void) {
2750
2751#if defined(TARGET_FEDORA)
2752 char *r;
2753
2754 if (read_one_line_file("/etc/system-release", &r) < 0)
2755 return;
2756
2757 truncate_nl(r);
2758
2759 /* This tries to mimic the color magic the old Red Hat sysinit
2760 * script did. */
2761
2762 if (startswith(r, "Red Hat"))
2e54424d 2763 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r); /* Red for RHEL */
c846ff47 2764 else if (startswith(r, "Fedora"))
2e54424d 2765 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r); /* Blue for Fedora */
c846ff47 2766 else
2e54424d 2767 status_printf("Welcome to %s!\n", r);
c846ff47
LP
2768
2769 free(r);
2770
2771#elif defined(TARGET_SUSE)
2772 char *r;
2773
2774 if (read_one_line_file("/etc/SuSE-release", &r) < 0)
2775 return;
2776
2777 truncate_nl(r);
2778
2e54424d 2779 status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r); /* Green for SUSE */
c846ff47
LP
2780 free(r);
2781#else
2782#warning "You probably should add a welcome text logic here."
2783#endif
2784}
2785
fab56fc5
LP
2786char *replace_env(const char *format, char **env) {
2787 enum {
2788 WORD,
c24eb49e 2789 CURLY,
fab56fc5
LP
2790 VARIABLE
2791 } state = WORD;
2792
2793 const char *e, *word = format;
2794 char *r = NULL, *k;
2795
2796 assert(format);
2797
2798 for (e = format; *e; e ++) {
2799
2800 switch (state) {
2801
2802 case WORD:
2803 if (*e == '$')
c24eb49e 2804 state = CURLY;
fab56fc5
LP
2805 break;
2806
c24eb49e
LP
2807 case CURLY:
2808 if (*e == '{') {
fab56fc5
LP
2809 if (!(k = strnappend(r, word, e-word-1)))
2810 goto fail;
2811
2812 free(r);
2813 r = k;
2814
2815 word = e-1;
2816 state = VARIABLE;
2817
2818 } else if (*e == '$') {
2819 if (!(k = strnappend(r, word, e-word)))
2820 goto fail;
2821
2822 free(r);
2823 r = k;
2824
2825 word = e+1;
2826 state = WORD;
2827 } else
2828 state = WORD;
2829 break;
2830
2831 case VARIABLE:
c24eb49e 2832 if (*e == '}') {
b95cf362 2833 const char *t;
fab56fc5 2834
b95cf362
LP
2835 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
2836 t = "";
fab56fc5 2837
b95cf362
LP
2838 if (!(k = strappend(r, t)))
2839 goto fail;
fab56fc5 2840
b95cf362
LP
2841 free(r);
2842 r = k;
fab56fc5 2843
b95cf362 2844 word = e+1;
fab56fc5
LP
2845 state = WORD;
2846 }
2847 break;
2848 }
2849 }
2850
2851 if (!(k = strnappend(r, word, e-word)))
2852 goto fail;
2853
2854 free(r);
2855 return k;
2856
2857fail:
2858 free(r);
2859 return NULL;
2860}
2861
2862char **replace_env_argv(char **argv, char **env) {
2863 char **r, **i;
c24eb49e
LP
2864 unsigned k = 0, l = 0;
2865
2866 l = strv_length(argv);
fab56fc5 2867
c24eb49e 2868 if (!(r = new(char*, l+1)))
fab56fc5
LP
2869 return NULL;
2870
2871 STRV_FOREACH(i, argv) {
c24eb49e
LP
2872
2873 /* If $FOO appears as single word, replace it by the split up variable */
b95cf362
LP
2874 if ((*i)[0] == '$' && (*i)[1] != '{') {
2875 char *e;
2876 char **w, **m;
2877 unsigned q;
c24eb49e 2878
b95cf362 2879 if ((e = strv_env_get(env, *i+1))) {
c24eb49e
LP
2880
2881 if (!(m = strv_split_quoted(e))) {
2882 r[k] = NULL;
2883 strv_free(r);
2884 return NULL;
2885 }
b95cf362
LP
2886 } else
2887 m = NULL;
c24eb49e 2888
b95cf362
LP
2889 q = strv_length(m);
2890 l = l + q - 1;
c24eb49e 2891
b95cf362
LP
2892 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
2893 r[k] = NULL;
2894 strv_free(r);
2895 strv_free(m);
2896 return NULL;
2897 }
c24eb49e 2898
b95cf362
LP
2899 r = w;
2900 if (m) {
c24eb49e
LP
2901 memcpy(r + k, m, q * sizeof(char*));
2902 free(m);
c24eb49e 2903 }
b95cf362
LP
2904
2905 k += q;
2906 continue;
c24eb49e
LP
2907 }
2908
2909 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
fab56fc5
LP
2910 if (!(r[k++] = replace_env(*i, env))) {
2911 strv_free(r);
2912 return NULL;
2913 }
2914 }
2915
2916 r[k] = NULL;
2917 return r;
2918}
2919
fa776d8e
LP
2920int columns(void) {
2921 static __thread int parsed_columns = 0;
2922 const char *e;
2923
2924 if (parsed_columns > 0)
2925 return parsed_columns;
2926
2927 if ((e = getenv("COLUMNS")))
2928 parsed_columns = atoi(e);
2929
2930 if (parsed_columns <= 0) {
2931 struct winsize ws;
2932 zero(ws);
2933
2934 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
2935 parsed_columns = ws.ws_col;
2936 }
2937
2938 if (parsed_columns <= 0)
2939 parsed_columns = 80;
2940
2941 return parsed_columns;
2942}
2943
b4f10a5e
LP
2944int running_in_chroot(void) {
2945 struct stat a, b;
2946
2947 zero(a);
2948 zero(b);
2949
2950 /* Only works as root */
2951
2952 if (stat("/proc/1/root", &a) < 0)
2953 return -errno;
2954
2955 if (stat("/", &b) < 0)
2956 return -errno;
2957
2958 return
2959 a.st_dev != b.st_dev ||
2960 a.st_ino != b.st_ino;
2961}
2962
8fe914ec
LP
2963char *ellipsize(const char *s, unsigned length, unsigned percent) {
2964 size_t l, x;
2965 char *r;
2966
2967 assert(s);
2968 assert(percent <= 100);
2969 assert(length >= 3);
2970
2971 l = strlen(s);
2972
2973 if (l <= 3 || l <= length)
2974 return strdup(s);
2975
2976 if (!(r = new0(char, length+1)))
2977 return r;
2978
2979 x = (length * percent) / 100;
2980
2981 if (x > length - 3)
2982 x = length - 3;
2983
2984 memcpy(r, s, x);
2985 r[x] = '.';
2986 r[x+1] = '.';
2987 r[x+2] = '.';
2988 memcpy(r + x + 3,
2989 s + l - (length - x - 3),
2990 length - x - 3);
2991
2992 return r;
2993}
2994
f6144808
LP
2995int touch(const char *path) {
2996 int fd;
2997
2998 assert(path);
2999
3000 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0666)) < 0)
3001 return -errno;
3002
3003 close_nointr_nofail(fd);
3004 return 0;
3005}
afea26ad 3006
1dccbe19
LP
3007static const char *const ioprio_class_table[] = {
3008 [IOPRIO_CLASS_NONE] = "none",
3009 [IOPRIO_CLASS_RT] = "realtime",
3010 [IOPRIO_CLASS_BE] = "best-effort",
3011 [IOPRIO_CLASS_IDLE] = "idle"
3012};
3013
3014DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
3015
3016static const char *const sigchld_code_table[] = {
3017 [CLD_EXITED] = "exited",
3018 [CLD_KILLED] = "killed",
3019 [CLD_DUMPED] = "dumped",
3020 [CLD_TRAPPED] = "trapped",
3021 [CLD_STOPPED] = "stopped",
3022 [CLD_CONTINUED] = "continued",
3023};
3024
3025DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3026
3027static const char *const log_facility_table[LOG_NFACILITIES] = {
3028 [LOG_FAC(LOG_KERN)] = "kern",
3029 [LOG_FAC(LOG_USER)] = "user",
3030 [LOG_FAC(LOG_MAIL)] = "mail",
3031 [LOG_FAC(LOG_DAEMON)] = "daemon",
3032 [LOG_FAC(LOG_AUTH)] = "auth",
3033 [LOG_FAC(LOG_SYSLOG)] = "syslog",
3034 [LOG_FAC(LOG_LPR)] = "lpr",
3035 [LOG_FAC(LOG_NEWS)] = "news",
3036 [LOG_FAC(LOG_UUCP)] = "uucp",
3037 [LOG_FAC(LOG_CRON)] = "cron",
3038 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3039 [LOG_FAC(LOG_FTP)] = "ftp",
3040 [LOG_FAC(LOG_LOCAL0)] = "local0",
3041 [LOG_FAC(LOG_LOCAL1)] = "local1",
3042 [LOG_FAC(LOG_LOCAL2)] = "local2",
3043 [LOG_FAC(LOG_LOCAL3)] = "local3",
3044 [LOG_FAC(LOG_LOCAL4)] = "local4",
3045 [LOG_FAC(LOG_LOCAL5)] = "local5",
3046 [LOG_FAC(LOG_LOCAL6)] = "local6",
3047 [LOG_FAC(LOG_LOCAL7)] = "local7"
3048};
3049
3050DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
3051
3052static const char *const log_level_table[] = {
3053 [LOG_EMERG] = "emerg",
3054 [LOG_ALERT] = "alert",
3055 [LOG_CRIT] = "crit",
3056 [LOG_ERR] = "err",
3057 [LOG_WARNING] = "warning",
3058 [LOG_NOTICE] = "notice",
3059 [LOG_INFO] = "info",
3060 [LOG_DEBUG] = "debug"
3061};
3062
3063DEFINE_STRING_TABLE_LOOKUP(log_level, int);
3064
3065static const char* const sched_policy_table[] = {
3066 [SCHED_OTHER] = "other",
3067 [SCHED_BATCH] = "batch",
3068 [SCHED_IDLE] = "idle",
3069 [SCHED_FIFO] = "fifo",
3070 [SCHED_RR] = "rr"
3071};
3072
3073DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
3074
3075static const char* const rlimit_table[] = {
3076 [RLIMIT_CPU] = "LimitCPU",
3077 [RLIMIT_FSIZE] = "LimitFSIZE",
3078 [RLIMIT_DATA] = "LimitDATA",
3079 [RLIMIT_STACK] = "LimitSTACK",
3080 [RLIMIT_CORE] = "LimitCORE",
3081 [RLIMIT_RSS] = "LimitRSS",
3082 [RLIMIT_NOFILE] = "LimitNOFILE",
3083 [RLIMIT_AS] = "LimitAS",
3084 [RLIMIT_NPROC] = "LimitNPROC",
3085 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3086 [RLIMIT_LOCKS] = "LimitLOCKS",
3087 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3088 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3089 [RLIMIT_NICE] = "LimitNICE",
3090 [RLIMIT_RTPRIO] = "LimitRTPRIO",
3091 [RLIMIT_RTTIME] = "LimitRTTIME"
3092};
3093
3094DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4fd5948e
LP
3095
3096static const char* const ip_tos_table[] = {
3097 [IPTOS_LOWDELAY] = "low-delay",
3098 [IPTOS_THROUGHPUT] = "throughput",
3099 [IPTOS_RELIABILITY] = "reliability",
3100 [IPTOS_LOWCOST] = "low-cost",
3101};
3102
3103DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
2e22afe9
LP
3104
3105static const char *const signal_table[] = {
3106 [SIGHUP] = "HUP",
3107 [SIGINT] = "INT",
3108 [SIGQUIT] = "QUIT",
3109 [SIGILL] = "ILL",
3110 [SIGTRAP] = "TRAP",
3111 [SIGABRT] = "ABRT",
3112 [SIGBUS] = "BUS",
3113 [SIGFPE] = "FPE",
3114 [SIGKILL] = "KILL",
3115 [SIGUSR1] = "USR1",
3116 [SIGSEGV] = "SEGV",
3117 [SIGUSR2] = "USR2",
3118 [SIGPIPE] = "PIPE",
3119 [SIGALRM] = "ALRM",
3120 [SIGTERM] = "TERM",
3121 [SIGSTKFLT] = "STKFLT",
3122 [SIGCHLD] = "CHLD",
3123 [SIGCONT] = "CONT",
3124 [SIGSTOP] = "STOP",
3125 [SIGTSTP] = "TSTP",
3126 [SIGTTIN] = "TTIN",
3127 [SIGTTOU] = "TTOU",
3128 [SIGURG] = "URG",
3129 [SIGXCPU] = "XCPU",
3130 [SIGXFSZ] = "XFSZ",
3131 [SIGVTALRM] = "VTALRM",
3132 [SIGPROF] = "PROF",
3133 [SIGWINCH] = "WINCH",
3134 [SIGIO] = "IO",
3135 [SIGPWR] = "PWR",
3136 [SIGSYS] = "SYS"
3137};
3138
3139DEFINE_STRING_TABLE_LOOKUP(signal, int);