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