]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/util.c
update TODO
[thirdparty/systemd.git] / src / util.c
CommitLineData
d6c9574f 1/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
60918275 2
a7334b09
LP
3/***
4 This file is part of systemd.
5
6 Copyright 2010 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20***/
21
60918275
LP
22#include <assert.h>
23#include <string.h>
24#include <unistd.h>
25#include <errno.h>
85261803 26#include <stdlib.h>
034c6ed7
LP
27#include <signal.h>
28#include <stdio.h>
1dccbe19
LP
29#include <syslog.h>
30#include <sched.h>
31#include <sys/resource.h>
ef886c6a 32#include <linux/sched.h>
a9f5d454
LP
33#include <sys/types.h>
34#include <sys/stat.h>
3a0ecb08 35#include <fcntl.h>
a0d40ac5 36#include <dirent.h>
601f6a1e
LP
37#include <sys/ioctl.h>
38#include <linux/vt.h>
39#include <linux/tiocl.h>
80876c20
LP
40#include <termios.h>
41#include <stdarg.h>
42#include <sys/inotify.h>
43#include <sys/poll.h>
8d567588 44#include <libgen.h>
3177a7fa 45#include <ctype.h>
5b6319dc 46#include <sys/prctl.h>
ef2f1067
LP
47#include <sys/utsname.h>
48#include <pwd.h>
4fd5948e 49#include <netinet/ip.h>
3fe5e5d4 50#include <linux/kd.h>
afea26ad 51#include <dlfcn.h>
2e78aa99 52#include <sys/wait.h>
ac123445 53#include <sys/capability.h>
7948c4df
KS
54#include <sys/time.h>
55#include <linux/rtc.h>
8092a428 56#include <glob.h>
4b67834e 57#include <grp.h>
87d2c1ff 58#include <sys/mman.h>
60918275
LP
59
60#include "macro.h"
61#include "util.h"
1dccbe19
LP
62#include "ioprio.h"
63#include "missing.h"
a9f5d454 64#include "log.h"
65d2ebdc 65#include "strv.h"
e51bc1a2 66#include "label.h"
d06dacd0 67#include "exit-status.h"
83cc030f 68#include "hashmap.h"
56cf987f 69
9a0e6896
LP
70int saved_argc = 0;
71char **saved_argv = NULL;
72
37f85e66 73size_t page_size(void) {
74 static __thread size_t pgsz = 0;
75 long r;
76
87d2c1ff 77 if (_likely_(pgsz > 0))
37f85e66 78 return pgsz;
79
80 assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
81
82 pgsz = (size_t) r;
83
84 return pgsz;
85}
86
e05797fb
LP
87bool streq_ptr(const char *a, const char *b) {
88
89 /* Like streq(), but tries to make sense of NULL pointers */
90
91 if (a && b)
92 return streq(a, b);
93
94 if (!a && !b)
95 return true;
96
97 return false;
98}
99
47be870b 100usec_t now(clockid_t clock_id) {
60918275
LP
101 struct timespec ts;
102
47be870b 103 assert_se(clock_gettime(clock_id, &ts) == 0);
60918275
LP
104
105 return timespec_load(&ts);
106}
107
63983207 108dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
871d7de4
LP
109 assert(ts);
110
111 ts->realtime = now(CLOCK_REALTIME);
112 ts->monotonic = now(CLOCK_MONOTONIC);
113
114 return ts;
115}
116
a185c5aa
LP
117dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
118 int64_t delta;
119 assert(ts);
120
121 ts->realtime = u;
122
123 if (u == 0)
124 ts->monotonic = 0;
125 else {
126 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
127
128 ts->monotonic = now(CLOCK_MONOTONIC);
129
130 if ((int64_t) ts->monotonic > delta)
131 ts->monotonic -= delta;
132 else
133 ts->monotonic = 0;
134 }
135
136 return ts;
137}
138
60918275
LP
139usec_t timespec_load(const struct timespec *ts) {
140 assert(ts);
141
142 return
143 (usec_t) ts->tv_sec * USEC_PER_SEC +
144 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
145}
146
147struct timespec *timespec_store(struct timespec *ts, usec_t u) {
148 assert(ts);
149
150 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
151 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
152
153 return ts;
154}
155
156usec_t timeval_load(const struct timeval *tv) {
157 assert(tv);
158
159 return
160 (usec_t) tv->tv_sec * USEC_PER_SEC +
161 (usec_t) tv->tv_usec;
162}
163
164struct timeval *timeval_store(struct timeval *tv, usec_t u) {
165 assert(tv);
166
167 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
168 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
169
170 return tv;
171}
172
173bool endswith(const char *s, const char *postfix) {
174 size_t sl, pl;
175
176 assert(s);
177 assert(postfix);
178
179 sl = strlen(s);
180 pl = strlen(postfix);
181
d4d0d4db
LP
182 if (pl == 0)
183 return true;
184
60918275
LP
185 if (sl < pl)
186 return false;
187
188 return memcmp(s + sl - pl, postfix, pl) == 0;
189}
190
191bool startswith(const char *s, const char *prefix) {
192 size_t sl, pl;
193
194 assert(s);
195 assert(prefix);
196
197 sl = strlen(s);
198 pl = strlen(prefix);
199
d4d0d4db
LP
200 if (pl == 0)
201 return true;
202
60918275
LP
203 if (sl < pl)
204 return false;
205
206 return memcmp(s, prefix, pl) == 0;
207}
208
3177a7fa
MAP
209bool startswith_no_case(const char *s, const char *prefix) {
210 size_t sl, pl;
211 unsigned i;
212
213 assert(s);
214 assert(prefix);
215
216 sl = strlen(s);
217 pl = strlen(prefix);
218
219 if (pl == 0)
220 return true;
221
222 if (sl < pl)
223 return false;
224
225 for(i = 0; i < pl; ++i) {
226 if (tolower(s[i]) != tolower(prefix[i]))
227 return false;
228 }
229
230 return true;
231}
232
79d6d816
LP
233bool first_word(const char *s, const char *word) {
234 size_t sl, wl;
235
236 assert(s);
237 assert(word);
238
239 sl = strlen(s);
240 wl = strlen(word);
241
242 if (sl < wl)
243 return false;
244
d4d0d4db
LP
245 if (wl == 0)
246 return true;
247
79d6d816
LP
248 if (memcmp(s, word, wl) != 0)
249 return false;
250
d4d0d4db
LP
251 return s[wl] == 0 ||
252 strchr(WHITESPACE, s[wl]);
79d6d816
LP
253}
254
42f4e3c4 255int close_nointr(int fd) {
60918275
LP
256 assert(fd >= 0);
257
258 for (;;) {
259 int r;
260
48f82119
LP
261 r = close(fd);
262 if (r >= 0)
60918275
LP
263 return r;
264
265 if (errno != EINTR)
48f82119 266 return -errno;
60918275
LP
267 }
268}
85261803 269
85f136b5 270void close_nointr_nofail(int fd) {
80876c20 271 int saved_errno = errno;
85f136b5
LP
272
273 /* like close_nointr() but cannot fail, and guarantees errno
274 * is unchanged */
275
276 assert_se(close_nointr(fd) == 0);
80876c20
LP
277
278 errno = saved_errno;
85f136b5
LP
279}
280
5b6319dc
LP
281void close_many(const int fds[], unsigned n_fd) {
282 unsigned i;
283
284 for (i = 0; i < n_fd; i++)
285 close_nointr_nofail(fds[i]);
286}
287
85261803
LP
288int parse_boolean(const char *v) {
289 assert(v);
290
44d8db9e 291 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
85261803 292 return 1;
44d8db9e 293 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
85261803
LP
294 return 0;
295
296 return -EINVAL;
297}
298
3ba686c1 299int parse_pid(const char *s, pid_t* ret_pid) {
0b172489 300 unsigned long ul = 0;
3ba686c1
LP
301 pid_t pid;
302 int r;
303
304 assert(s);
305 assert(ret_pid);
306
307 if ((r = safe_atolu(s, &ul)) < 0)
308 return r;
309
310 pid = (pid_t) ul;
311
312 if ((unsigned long) pid != ul)
313 return -ERANGE;
314
315 if (pid <= 0)
316 return -ERANGE;
317
318 *ret_pid = pid;
319 return 0;
320}
321
034a2a52
LP
322int parse_uid(const char *s, uid_t* ret_uid) {
323 unsigned long ul = 0;
324 uid_t uid;
325 int r;
326
327 assert(s);
328 assert(ret_uid);
329
330 if ((r = safe_atolu(s, &ul)) < 0)
331 return r;
332
333 uid = (uid_t) ul;
334
335 if ((unsigned long) uid != ul)
336 return -ERANGE;
337
338 *ret_uid = uid;
339 return 0;
340}
341
85261803
LP
342int safe_atou(const char *s, unsigned *ret_u) {
343 char *x = NULL;
034c6ed7 344 unsigned long l;
85261803
LP
345
346 assert(s);
347 assert(ret_u);
348
349 errno = 0;
350 l = strtoul(s, &x, 0);
351
352 if (!x || *x || errno)
353 return errno ? -errno : -EINVAL;
354
034c6ed7 355 if ((unsigned long) (unsigned) l != l)
85261803
LP
356 return -ERANGE;
357
358 *ret_u = (unsigned) l;
359 return 0;
360}
361
362int safe_atoi(const char *s, int *ret_i) {
363 char *x = NULL;
034c6ed7 364 long l;
85261803
LP
365
366 assert(s);
367 assert(ret_i);
368
369 errno = 0;
370 l = strtol(s, &x, 0);
371
372 if (!x || *x || errno)
373 return errno ? -errno : -EINVAL;
374
034c6ed7 375 if ((long) (int) l != l)
85261803
LP
376 return -ERANGE;
377
034c6ed7
LP
378 *ret_i = (int) l;
379 return 0;
380}
381
034c6ed7
LP
382int safe_atollu(const char *s, long long unsigned *ret_llu) {
383 char *x = NULL;
384 unsigned long long l;
385
386 assert(s);
387 assert(ret_llu);
388
389 errno = 0;
390 l = strtoull(s, &x, 0);
391
392 if (!x || *x || errno)
393 return errno ? -errno : -EINVAL;
394
395 *ret_llu = l;
396 return 0;
397}
398
399int safe_atolli(const char *s, long long int *ret_lli) {
400 char *x = NULL;
401 long long l;
402
403 assert(s);
404 assert(ret_lli);
405
406 errno = 0;
407 l = strtoll(s, &x, 0);
408
409 if (!x || *x || errno)
410 return errno ? -errno : -EINVAL;
411
412 *ret_lli = l;
85261803
LP
413 return 0;
414}
a41e8209 415
a41e8209 416/* Split a string into words. */
65d2ebdc 417char *split(const char *c, size_t *l, const char *separator, char **state) {
a41e8209
LP
418 char *current;
419
420 current = *state ? *state : (char*) c;
421
422 if (!*current || *c == 0)
423 return NULL;
424
65d2ebdc
LP
425 current += strspn(current, separator);
426 *l = strcspn(current, separator);
82919e3d
LP
427 *state = current+*l;
428
429 return (char*) current;
430}
431
034c6ed7
LP
432/* Split a string into words, but consider strings enclosed in '' and
433 * "" as words even if they include spaces. */
434char *split_quoted(const char *c, size_t *l, char **state) {
0bab36f2
LP
435 char *current, *e;
436 bool escaped = false;
034c6ed7
LP
437
438 current = *state ? *state : (char*) c;
439
440 if (!*current || *c == 0)
441 return NULL;
442
443 current += strspn(current, WHITESPACE);
444
445 if (*current == '\'') {
446 current ++;
034c6ed7 447
0bab36f2
LP
448 for (e = current; *e; e++) {
449 if (escaped)
450 escaped = false;
451 else if (*e == '\\')
452 escaped = true;
453 else if (*e == '\'')
454 break;
455 }
456
457 *l = e-current;
458 *state = *e == 0 ? e : e+1;
034c6ed7
LP
459 } else if (*current == '\"') {
460 current ++;
034c6ed7 461
0bab36f2
LP
462 for (e = current; *e; e++) {
463 if (escaped)
464 escaped = false;
465 else if (*e == '\\')
466 escaped = true;
467 else if (*e == '\"')
468 break;
469 }
470
471 *l = e-current;
472 *state = *e == 0 ? e : e+1;
034c6ed7 473 } else {
0bab36f2
LP
474 for (e = current; *e; e++) {
475 if (escaped)
476 escaped = false;
477 else if (*e == '\\')
478 escaped = true;
479 else if (strchr(WHITESPACE, *e))
480 break;
481 }
482 *l = e-current;
483 *state = e;
034c6ed7
LP
484 }
485
486 return (char*) current;
487}
488
65d2ebdc
LP
489char **split_path_and_make_absolute(const char *p) {
490 char **l;
491 assert(p);
492
493 if (!(l = strv_split(p, ":")))
494 return NULL;
495
496 if (!strv_path_make_absolute_cwd(l)) {
497 strv_free(l);
498 return NULL;
499 }
500
501 return l;
502}
503
034c6ed7
LP
504int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
505 int r;
506 FILE *f;
20c03b7b 507 char fn[PATH_MAX], line[LINE_MAX], *p;
bb00e604 508 long unsigned ppid;
034c6ed7 509
8480e784 510 assert(pid > 0);
034c6ed7
LP
511 assert(_ppid);
512
bb00e604 513 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
8480e784 514 char_array_0(fn);
034c6ed7 515
ccaa6149 516 if (!(f = fopen(fn, "re")))
034c6ed7
LP
517 return -errno;
518
519 if (!(fgets(line, sizeof(line), f))) {
35d50f55 520 r = feof(f) ? -EIO : -errno;
034c6ed7
LP
521 fclose(f);
522 return r;
523 }
524
525 fclose(f);
526
527 /* Let's skip the pid and comm fields. The latter is enclosed
528 * in () but does not escape any () in its value, so let's
529 * skip over it manually */
530
531 if (!(p = strrchr(line, ')')))
532 return -EIO;
533
534 p++;
535
536 if (sscanf(p, " "
537 "%*c " /* state */
bb00e604 538 "%lu ", /* ppid */
034c6ed7
LP
539 &ppid) != 1)
540 return -EIO;
541
bb00e604 542 if ((long unsigned) (pid_t) ppid != ppid)
034c6ed7
LP
543 return -ERANGE;
544
545 *_ppid = (pid_t) ppid;
546
547 return 0;
548}
549
7640a5de
LP
550int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
551 int r;
552 FILE *f;
553 char fn[PATH_MAX], line[LINE_MAX], *p;
554
555 assert(pid > 0);
556 assert(st);
557
558 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
559 char_array_0(fn);
560
ccaa6149 561 if (!(f = fopen(fn, "re")))
7640a5de
LP
562 return -errno;
563
564 if (!(fgets(line, sizeof(line), f))) {
35d50f55 565 r = feof(f) ? -EIO : -errno;
7640a5de
LP
566 fclose(f);
567 return r;
568 }
569
570 fclose(f);
571
572 /* Let's skip the pid and comm fields. The latter is enclosed
573 * in () but does not escape any () in its value, so let's
574 * skip over it manually */
575
576 if (!(p = strrchr(line, ')')))
577 return -EIO;
578
579 p++;
580
581 if (sscanf(p, " "
582 "%*c " /* state */
583 "%*d " /* ppid */
584 "%*d " /* pgrp */
585 "%*d " /* session */
586 "%*d " /* tty_nr */
587 "%*d " /* tpgid */
588 "%*u " /* flags */
589 "%*u " /* minflt */
590 "%*u " /* cminflt */
591 "%*u " /* majflt */
592 "%*u " /* cmajflt */
593 "%*u " /* utime */
594 "%*u " /* stime */
595 "%*d " /* cutime */
596 "%*d " /* cstime */
597 "%*d " /* priority */
598 "%*d " /* nice */
599 "%*d " /* num_threads */
600 "%*d " /* itrealvalue */
601 "%llu " /* starttime */,
602 st) != 1)
603 return -EIO;
604
605 return 0;
606}
607
034c6ed7
LP
608int write_one_line_file(const char *fn, const char *line) {
609 FILE *f;
610 int r;
611
612 assert(fn);
613 assert(line);
614
615 if (!(f = fopen(fn, "we")))
616 return -errno;
617
34ca941c 618 errno = 0;
034c6ed7
LP
619 if (fputs(line, f) < 0) {
620 r = -errno;
621 goto finish;
622 }
623
8e1bd70d
LP
624 if (!endswith(line, "\n"))
625 fputc('\n', f);
626
151b190e
LP
627 fflush(f);
628
629 if (ferror(f)) {
630 if (errno != 0)
631 r = -errno;
632 else
633 r = -EIO;
634 } else
635 r = 0;
636
034c6ed7
LP
637finish:
638 fclose(f);
639 return r;
640}
641
34ca941c
LP
642int fchmod_umask(int fd, mode_t m) {
643 mode_t u;
644 int r;
645
646 u = umask(0777);
647 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
648 umask(u);
649
650 return r;
651}
652
653int write_one_line_file_atomic(const char *fn, const char *line) {
654 FILE *f;
655 int r;
656 char *p;
657
658 assert(fn);
659 assert(line);
660
661 r = fopen_temporary(fn, &f, &p);
662 if (r < 0)
663 return r;
664
665 fchmod_umask(fileno(f), 0644);
666
667 errno = 0;
668 if (fputs(line, f) < 0) {
669 r = -errno;
670 goto finish;
671 }
672
673 if (!endswith(line, "\n"))
674 fputc('\n', f);
675
676 fflush(f);
677
678 if (ferror(f)) {
679 if (errno != 0)
680 r = -errno;
681 else
682 r = -EIO;
683 } else {
684 if (rename(p, fn) < 0)
685 r = -errno;
686 else
687 r = 0;
688 }
689
690finish:
691 if (r < 0)
692 unlink(p);
693
694 fclose(f);
695 free(p);
696
697 return r;
698}
699
034c6ed7
LP
700int read_one_line_file(const char *fn, char **line) {
701 FILE *f;
702 int r;
97c4a07d 703 char t[LINE_MAX], *c;
034c6ed7
LP
704
705 assert(fn);
706 assert(line);
707
4099a281
LP
708 f = fopen(fn, "re");
709 if (!f)
034c6ed7
LP
710 return -errno;
711
4099a281
LP
712 if (!fgets(t, sizeof(t), f)) {
713
714 if (ferror(f)) {
715 r = -errno;
716 goto finish;
717 }
718
719 t[0] = 0;
034c6ed7
LP
720 }
721
4099a281
LP
722 c = strdup(t);
723 if (!c) {
034c6ed7
LP
724 r = -ENOMEM;
725 goto finish;
726 }
727
6f9a471a
LP
728 truncate_nl(c);
729
034c6ed7
LP
730 *line = c;
731 r = 0;
732
733finish:
734 fclose(f);
735 return r;
736}
44d8db9e 737
34ca941c 738int read_full_file(const char *fn, char **contents, size_t *size) {
97c4a07d
LP
739 FILE *f;
740 int r;
741 size_t n, l;
742 char *buf = NULL;
743 struct stat st;
744
745 if (!(f = fopen(fn, "re")))
746 return -errno;
747
748 if (fstat(fileno(f), &st) < 0) {
749 r = -errno;
750 goto finish;
751 }
752
34ca941c
LP
753 /* Safety check */
754 if (st.st_size > 4*1024*1024) {
755 r = -E2BIG;
756 goto finish;
757 }
758
97c4a07d
LP
759 n = st.st_size > 0 ? st.st_size : LINE_MAX;
760 l = 0;
761
762 for (;;) {
763 char *t;
764 size_t k;
765
766 if (!(t = realloc(buf, n+1))) {
767 r = -ENOMEM;
768 goto finish;
769 }
770
771 buf = t;
772 k = fread(buf + l, 1, n - l, f);
773
774 if (k <= 0) {
775 if (ferror(f)) {
776 r = -errno;
777 goto finish;
778 }
779
780 break;
781 }
782
783 l += k;
784 n *= 2;
785
786 /* Safety check */
787 if (n > 4*1024*1024) {
788 r = -E2BIG;
789 goto finish;
790 }
791 }
792
f8440af5 793 buf[l] = 0;
97c4a07d
LP
794 *contents = buf;
795 buf = NULL;
796
34ca941c
LP
797 if (size)
798 *size = l;
799
97c4a07d
LP
800 r = 0;
801
802finish:
803 fclose(f);
804 free(buf);
805
806 return r;
807}
808
809int parse_env_file(
810 const char *fname,
c899f8c6 811 const char *separator, ...) {
97c4a07d 812
ce8a6aa1 813 int r = 0;
44d91056 814 char *contents = NULL, *p;
97c4a07d
LP
815
816 assert(fname);
c899f8c6 817 assert(separator);
97c4a07d 818
34ca941c 819 if ((r = read_full_file(fname, &contents, NULL)) < 0)
97c4a07d
LP
820 return r;
821
822 p = contents;
823 for (;;) {
824 const char *key = NULL;
825
c899f8c6 826 p += strspn(p, separator);
97c4a07d
LP
827 p += strspn(p, WHITESPACE);
828
829 if (!*p)
830 break;
831
832 if (!strchr(COMMENTS, *p)) {
833 va_list ap;
834 char **value;
835
c899f8c6 836 va_start(ap, separator);
97c4a07d
LP
837 while ((key = va_arg(ap, char *))) {
838 size_t n;
839 char *v;
840
841 value = va_arg(ap, char **);
842
843 n = strlen(key);
844 if (strncmp(p, key, n) != 0 ||
845 p[n] != '=')
846 continue;
847
848 p += n + 1;
c899f8c6 849 n = strcspn(p, separator);
97c4a07d
LP
850
851 if (n >= 2 &&
e7db37dd
LP
852 strchr(QUOTES, p[0]) &&
853 p[n-1] == p[0])
97c4a07d
LP
854 v = strndup(p+1, n-2);
855 else
856 v = strndup(p, n);
857
858 if (!v) {
859 r = -ENOMEM;
860 va_end(ap);
861 goto fail;
862 }
863
dd36de4d
KS
864 if (v[0] == '\0') {
865 /* return empty value strings as NULL */
866 free(v);
867 v = NULL;
868 }
869
97c4a07d
LP
870 free(*value);
871 *value = v;
872
873 p += n;
ce8a6aa1
LP
874
875 r ++;
97c4a07d
LP
876 break;
877 }
878 va_end(ap);
879 }
880
881 if (!key)
c899f8c6 882 p += strcspn(p, separator);
97c4a07d
LP
883 }
884
97c4a07d
LP
885fail:
886 free(contents);
887 return r;
888}
889
8c7be95e
LP
890int load_env_file(
891 const char *fname,
892 char ***rl) {
893
894 FILE *f;
6a39419f 895 char **m = NULL;
8c7be95e
LP
896 int r;
897
898 assert(fname);
899 assert(rl);
900
901 if (!(f = fopen(fname, "re")))
902 return -errno;
903
904 while (!feof(f)) {
905 char l[LINE_MAX], *p, *u;
906 char **t;
907
908 if (!fgets(l, sizeof(l), f)) {
909 if (feof(f))
910 break;
911
912 r = -errno;
913 goto finish;
914 }
915
916 p = strstrip(l);
917
918 if (!*p)
919 continue;
920
921 if (strchr(COMMENTS, *p))
922 continue;
923
924 if (!(u = normalize_env_assignment(p))) {
925 log_error("Out of memory");
926 r = -ENOMEM;
927 goto finish;
928 }
929
930 t = strv_append(m, u);
931 free(u);
932
933 if (!t) {
934 log_error("Out of memory");
935 r = -ENOMEM;
936 goto finish;
937 }
938
939 strv_free(m);
940 m = t;
941 }
942
943 r = 0;
944
945 *rl = m;
946 m = NULL;
947
948finish:
949 if (f)
950 fclose(f);
951
952 strv_free(m);
953
954 return r;
955}
956
7640a5de 957int write_env_file(const char *fname, char **l) {
34ca941c 958 char **i, *p;
7640a5de
LP
959 FILE *f;
960 int r;
961
34ca941c
LP
962 r = fopen_temporary(fname, &f, &p);
963 if (r < 0)
964 return r;
7640a5de 965
34ca941c
LP
966 fchmod_umask(fileno(f), 0644);
967
968 errno = 0;
7640a5de
LP
969 STRV_FOREACH(i, l) {
970 fputs(*i, f);
971 fputc('\n', f);
972 }
973
974 fflush(f);
975
34ca941c
LP
976 if (ferror(f)) {
977 if (errno != 0)
978 r = -errno;
979 else
980 r = -EIO;
981 } else {
982 if (rename(p, fname) < 0)
983 r = -errno;
984 else
985 r = 0;
986 }
987
988 if (r < 0)
989 unlink(p);
990
7640a5de 991 fclose(f);
34ca941c 992 free(p);
7640a5de
LP
993
994 return r;
995}
996
7072ced8
LP
997char *truncate_nl(char *s) {
998 assert(s);
999
1000 s[strcspn(s, NEWLINE)] = 0;
1001 return s;
1002}
1003
87d2c1ff 1004int get_process_comm(pid_t pid, char **name) {
7072ced8
LP
1005 int r;
1006
7072ced8
LP
1007 assert(name);
1008
87d2c1ff
LP
1009 if (pid == 0)
1010 r = read_one_line_file("/proc/self/comm", name);
1011 else {
1012 char *p;
1013 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
1014 return -ENOMEM;
7072ced8 1015
87d2c1ff
LP
1016 r = read_one_line_file(p, name);
1017 free(p);
1018 }
7072ced8 1019
87d2c1ff 1020 return r;
7072ced8
LP
1021}
1022
87d2c1ff
LP
1023int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
1024 char *r, *k;
c59760ee
LP
1025 int c;
1026 bool space = false;
1027 size_t left;
1028 FILE *f;
1029
c59760ee
LP
1030 assert(max_length > 0);
1031 assert(line);
1032
87d2c1ff
LP
1033 if (pid == 0)
1034 f = fopen("/proc/self/cmdline", "re");
1035 else {
1036 char *p;
1037 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1038 return -ENOMEM;
c59760ee 1039
87d2c1ff
LP
1040 f = fopen(p, "re");
1041 free(p);
1042 }
c59760ee
LP
1043
1044 if (!f)
1045 return -errno;
1046
87d2c1ff
LP
1047 r = new(char, max_length);
1048 if (!r) {
c59760ee
LP
1049 fclose(f);
1050 return -ENOMEM;
1051 }
1052
1053 k = r;
1054 left = max_length;
1055 while ((c = getc(f)) != EOF) {
1056
1057 if (isprint(c)) {
1058 if (space) {
1059 if (left <= 4)
1060 break;
1061
1062 *(k++) = ' ';
057fbb58 1063 left--;
c59760ee
LP
1064 space = false;
1065 }
1066
1067 if (left <= 4)
1068 break;
1069
1070 *(k++) = (char) c;
057fbb58 1071 left--;
c59760ee
LP
1072 } else
1073 space = true;
1074 }
1075
1076 if (left <= 4) {
1077 size_t n = MIN(left-1, 3U);
1078 memcpy(k, "...", n);
1079 k[n] = 0;
1080 } else
1081 *k = 0;
1082
1083 fclose(f);
1084
35d2e7ec
LP
1085 /* Kernel threads have no argv[] */
1086 if (r[0] == 0) {
1087 char *t;
1088 int h;
1089
1090 free(r);
1091
87d2c1ff
LP
1092 if (!comm_fallback)
1093 return -ENOENT;
1094
1095 h = get_process_comm(pid, &t);
1096 if (h < 0)
35d2e7ec
LP
1097 return h;
1098
87d2c1ff 1099 r = join("[", t, "]", NULL);
35d2e7ec
LP
1100 free(t);
1101
87d2c1ff 1102 if (!r)
35d2e7ec
LP
1103 return -ENOMEM;
1104 }
fa776d8e 1105
c59760ee
LP
1106 *line = r;
1107 return 0;
1108}
1109
1e5678d0
LP
1110int is_kernel_thread(pid_t pid) {
1111 char *p;
1112 size_t count;
1113 char c;
1114 bool eof;
1115 FILE *f;
1116
1117 if (pid == 0)
1118 return 0;
1119
1120 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1121 return -ENOMEM;
1122
1123 f = fopen(p, "re");
1124 free(p);
1125
1126 if (!f)
1127 return -errno;
1128
1129 count = fread(&c, 1, 1, f);
1130 eof = feof(f);
1131 fclose(f);
1132
1133 /* Kernel threads have an empty cmdline */
1134
1135 if (count <= 0)
1136 return eof ? 1 : -errno;
1137
1138 return 0;
1139}
1140
87d2c1ff
LP
1141int get_process_exe(pid_t pid, char **name) {
1142 int r;
1143
1144 assert(name);
1145
1146 if (pid == 0)
1147 r = readlink_malloc("/proc/self/exe", name);
1148 else {
1149 char *p;
1150 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1151 return -ENOMEM;
1152
1153 r = readlink_malloc(p, name);
1154 free(p);
1155 }
1156
1157 return r;
1158}
1159
7e4ab3c5
LP
1160int get_process_uid(pid_t pid, uid_t *uid) {
1161 char *p;
1162 FILE *f;
1163 int r;
1164
1165 assert(uid);
1166
1167 if (pid == 0)
1168 return getuid();
1169
1170 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1171 return -ENOMEM;
1172
1173 f = fopen(p, "re");
1174 free(p);
1175
1176 if (!f)
1177 return -errno;
1178
1179 while (!feof(f)) {
1180 char line[LINE_MAX], *l;
1181
1182 if (!fgets(line, sizeof(line), f)) {
1183 if (feof(f))
1184 break;
1185
1186 r = -errno;
1187 goto finish;
1188 }
1189
1190 l = strstrip(line);
1191
1192 if (startswith(l, "Uid:")) {
1193 l += 4;
1194 l += strspn(l, WHITESPACE);
1195
1196 l[strcspn(l, WHITESPACE)] = 0;
1197
1198 r = parse_uid(l, uid);
1199 goto finish;
1200 }
1201 }
1202
1203 r = -EIO;
1204
1205finish:
1206 fclose(f);
1207
1208 return r;
1209}
1210
fab56fc5
LP
1211char *strnappend(const char *s, const char *suffix, size_t b) {
1212 size_t a;
44d8db9e
LP
1213 char *r;
1214
fab56fc5
LP
1215 if (!s && !suffix)
1216 return strdup("");
1217
1218 if (!s)
1219 return strndup(suffix, b);
1220
1221 if (!suffix)
1222 return strdup(s);
1223
44d8db9e
LP
1224 assert(s);
1225 assert(suffix);
1226
1227 a = strlen(s);
44d8db9e
LP
1228
1229 if (!(r = new(char, a+b+1)))
1230 return NULL;
1231
1232 memcpy(r, s, a);
1233 memcpy(r+a, suffix, b);
1234 r[a+b] = 0;
1235
1236 return r;
1237}
87f0e418 1238
fab56fc5
LP
1239char *strappend(const char *s, const char *suffix) {
1240 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1241}
1242
87f0e418
LP
1243int readlink_malloc(const char *p, char **r) {
1244 size_t l = 100;
1245
1246 assert(p);
1247 assert(r);
1248
1249 for (;;) {
1250 char *c;
1251 ssize_t n;
1252
1253 if (!(c = new(char, l)))
1254 return -ENOMEM;
1255
1256 if ((n = readlink(p, c, l-1)) < 0) {
1257 int ret = -errno;
1258 free(c);
1259 return ret;
1260 }
1261
1262 if ((size_t) n < l-1) {
1263 c[n] = 0;
1264 *r = c;
1265 return 0;
1266 }
1267
1268 free(c);
1269 l *= 2;
1270 }
1271}
1272
2c7108c4
LP
1273int readlink_and_make_absolute(const char *p, char **r) {
1274 char *target, *k;
1275 int j;
1276
1277 assert(p);
1278 assert(r);
1279
1280 if ((j = readlink_malloc(p, &target)) < 0)
1281 return j;
1282
1283 k = file_in_same_dir(p, target);
1284 free(target);
1285
1286 if (!k)
1287 return -ENOMEM;
1288
1289 *r = k;
1290 return 0;
1291}
1292
83096483
LP
1293int readlink_and_canonicalize(const char *p, char **r) {
1294 char *t, *s;
1295 int j;
1296
1297 assert(p);
1298 assert(r);
1299
1300 j = readlink_and_make_absolute(p, &t);
1301 if (j < 0)
1302 return j;
1303
1304 s = canonicalize_file_name(t);
1305 if (s) {
1306 free(t);
1307 *r = s;
1308 } else
1309 *r = t;
1310
1311 path_kill_slashes(*r);
1312
1313 return 0;
1314}
1315
35d2e7ec
LP
1316int parent_of_path(const char *path, char **_r) {
1317 const char *e, *a = NULL, *b = NULL, *p;
1318 char *r;
1319 bool slash = false;
1320
1321 assert(path);
1322 assert(_r);
1323
1324 if (!*path)
1325 return -EINVAL;
1326
1327 for (e = path; *e; e++) {
1328
1329 if (!slash && *e == '/') {
1330 a = b;
1331 b = e;
1332 slash = true;
1333 } else if (slash && *e != '/')
1334 slash = false;
1335 }
1336
1337 if (*(e-1) == '/')
1338 p = a;
1339 else
1340 p = b;
1341
1342 if (!p)
1343 return -EINVAL;
1344
1345 if (p == path)
1346 r = strdup("/");
1347 else
1348 r = strndup(path, p-path);
1349
1350 if (!r)
1351 return -ENOMEM;
1352
1353 *_r = r;
1354 return 0;
1355}
1356
1357
87f0e418
LP
1358char *file_name_from_path(const char *p) {
1359 char *r;
1360
1361 assert(p);
1362
1363 if ((r = strrchr(p, '/')))
1364 return r + 1;
1365
1366 return (char*) p;
1367}
0301abf4
LP
1368
1369bool path_is_absolute(const char *p) {
1370 assert(p);
1371
1372 return p[0] == '/';
1373}
1374
1375bool is_path(const char *p) {
1376
1377 return !!strchr(p, '/');
1378}
1379
1380char *path_make_absolute(const char *p, const char *prefix) {
0301abf4
LP
1381 assert(p);
1382
65d2ebdc
LP
1383 /* Makes every item in the list an absolute path by prepending
1384 * the prefix, if specified and necessary */
1385
0301abf4
LP
1386 if (path_is_absolute(p) || !prefix)
1387 return strdup(p);
1388
44d91056 1389 return join(prefix, "/", p, NULL);
0301abf4 1390}
2a987ee8 1391
65d2ebdc
LP
1392char *path_make_absolute_cwd(const char *p) {
1393 char *cwd, *r;
1394
1395 assert(p);
1396
1397 /* Similar to path_make_absolute(), but prefixes with the
1398 * current working directory. */
1399
1400 if (path_is_absolute(p))
1401 return strdup(p);
1402
1403 if (!(cwd = get_current_dir_name()))
1404 return NULL;
1405
1406 r = path_make_absolute(p, cwd);
1407 free(cwd);
1408
1409 return r;
1410}
1411
1412char **strv_path_make_absolute_cwd(char **l) {
1413 char **s;
1414
1415 /* Goes through every item in the string list and makes it
1416 * absolute. This works in place and won't rollback any
1417 * changes on failure. */
1418
1419 STRV_FOREACH(s, l) {
1420 char *t;
1421
1422 if (!(t = path_make_absolute_cwd(*s)))
1423 return NULL;
1424
1425 free(*s);
1426 *s = t;
1427 }
1428
1429 return l;
1430}
1431
c3f6d675
LP
1432char **strv_path_canonicalize(char **l) {
1433 char **s;
1434 unsigned k = 0;
1435 bool enomem = false;
1436
1437 if (strv_isempty(l))
1438 return l;
1439
1440 /* Goes through every item in the string list and canonicalize
1441 * the path. This works in place and won't rollback any
1442 * changes on failure. */
1443
1444 STRV_FOREACH(s, l) {
1445 char *t, *u;
1446
1447 t = path_make_absolute_cwd(*s);
1448 free(*s);
1449
1450 if (!t) {
1451 enomem = true;
1452 continue;
1453 }
1454
1455 errno = 0;
1456 u = canonicalize_file_name(t);
1457 free(t);
1458
1459 if (!u) {
1460 if (errno == ENOMEM || !errno)
1461 enomem = true;
1462
1463 continue;
1464 }
1465
1466 l[k++] = u;
1467 }
1468
1469 l[k] = NULL;
1470
1471 if (enomem)
1472 return NULL;
1473
1474 return l;
a9dd2082
LP
1475}
1476
1477char **strv_path_remove_empty(char **l) {
1478 char **f, **t;
1479
1480 if (!l)
1481 return NULL;
1482
1483 for (f = t = l; *f; f++) {
1484
1485 if (dir_is_empty(*f) > 0) {
1486 free(*f);
1487 continue;
1488 }
1489
1490 *(t++) = *f;
1491 }
1492
1493 *t = NULL;
1494 return l;
c3f6d675
LP
1495}
1496
2a987ee8
LP
1497int reset_all_signal_handlers(void) {
1498 int sig;
1499
1500 for (sig = 1; sig < _NSIG; sig++) {
1501 struct sigaction sa;
1502
1503 if (sig == SIGKILL || sig == SIGSTOP)
1504 continue;
1505
1506 zero(sa);
1507 sa.sa_handler = SIG_DFL;
431c32bf 1508 sa.sa_flags = SA_RESTART;
2a987ee8
LP
1509
1510 /* On Linux the first two RT signals are reserved by
1511 * glibc, and sigaction() will return EINVAL for them. */
1512 if ((sigaction(sig, &sa, NULL) < 0))
1513 if (errno != EINVAL)
1514 return -errno;
1515 }
1516
8e274523 1517 return 0;
2a987ee8 1518}
4a72ff34
LP
1519
1520char *strstrip(char *s) {
57a8eca8 1521 char *e;
4a72ff34
LP
1522
1523 /* Drops trailing whitespace. Modifies the string in
1524 * place. Returns pointer to first non-space character */
1525
1526 s += strspn(s, WHITESPACE);
1527
57a8eca8
LP
1528 for (e = strchr(s, 0); e > s; e --)
1529 if (!strchr(WHITESPACE, e[-1]))
1530 break;
4a72ff34 1531
57a8eca8 1532 *e = 0;
4a72ff34
LP
1533
1534 return s;
4a72ff34
LP
1535}
1536
ee9b5e01
LP
1537char *delete_chars(char *s, const char *bad) {
1538 char *f, *t;
1539
1540 /* Drops all whitespace, regardless where in the string */
1541
1542 for (f = s, t = s; *f; f++) {
1543 if (strchr(bad, *f))
1544 continue;
1545
1546 *(t++) = *f;
1547 }
1548
1549 *t = 0;
1550
1551 return s;
1552}
1553
ab1f0633
LP
1554bool in_charset(const char *s, const char* charset) {
1555 const char *i;
1556
1557 assert(s);
1558 assert(charset);
1559
1560 for (i = s; *i; i++)
1561 if (!strchr(charset, *i))
1562 return false;
1563
1564 return true;
1565}
1566
4a72ff34
LP
1567char *file_in_same_dir(const char *path, const char *filename) {
1568 char *e, *r;
1569 size_t k;
1570
1571 assert(path);
1572 assert(filename);
1573
1574 /* This removes the last component of path and appends
1575 * filename, unless the latter is absolute anyway or the
1576 * former isn't */
1577
1578 if (path_is_absolute(filename))
1579 return strdup(filename);
1580
1581 if (!(e = strrchr(path, '/')))
1582 return strdup(filename);
1583
1584 k = strlen(filename);
1585 if (!(r = new(char, e-path+1+k+1)))
1586 return NULL;
1587
1588 memcpy(r, path, e-path+1);
1589 memcpy(r+(e-path)+1, filename, k+1);
1590
1591 return r;
1592}
fb624d04 1593
8c6db833
LP
1594int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1595 struct stat st;
1596
56cf987f 1597 if (label_mkdir(path, mode) >= 0)
8c6db833
LP
1598 if (chmod_and_chown(path, mode, uid, gid) < 0)
1599 return -errno;
1600
1601 if (lstat(path, &st) < 0)
1602 return -errno;
1603
1604 if ((st.st_mode & 0777) != mode ||
1605 st.st_uid != uid ||
1606 st.st_gid != gid ||
1607 !S_ISDIR(st.st_mode)) {
1608 errno = EEXIST;
1609 return -errno;
1610 }
1611
1612 return 0;
1613}
1614
1615
a9f5d454
LP
1616int mkdir_parents(const char *path, mode_t mode) {
1617 const char *p, *e;
1618
1619 assert(path);
1620
1621 /* Creates every parent directory in the path except the last
1622 * component. */
1623
1624 p = path + strspn(path, "/");
1625 for (;;) {
1626 int r;
1627 char *t;
1628
1629 e = p + strcspn(p, "/");
1630 p = e + strspn(e, "/");
1631
1632 /* Is this the last component? If so, then we're
1633 * done */
1634 if (*p == 0)
1635 return 0;
1636
1637 if (!(t = strndup(path, e - path)))
1638 return -ENOMEM;
1639
56cf987f 1640 r = label_mkdir(t, mode);
a9f5d454
LP
1641 free(t);
1642
1643 if (r < 0 && errno != EEXIST)
1644 return -errno;
1645 }
1646}
1647
bbd67135
LP
1648int mkdir_p(const char *path, mode_t mode) {
1649 int r;
1650
1651 /* Like mkdir -p */
1652
1653 if ((r = mkdir_parents(path, mode)) < 0)
1654 return r;
1655
56cf987f 1656 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
bbd67135
LP
1657 return -errno;
1658
1659 return 0;
1660}
1661
c32dd69b
LP
1662int rmdir_parents(const char *path, const char *stop) {
1663 size_t l;
1664 int r = 0;
1665
1666 assert(path);
1667 assert(stop);
1668
1669 l = strlen(path);
1670
1671 /* Skip trailing slashes */
1672 while (l > 0 && path[l-1] == '/')
1673 l--;
1674
1675 while (l > 0) {
1676 char *t;
1677
1678 /* Skip last component */
1679 while (l > 0 && path[l-1] != '/')
1680 l--;
1681
1682 /* Skip trailing slashes */
1683 while (l > 0 && path[l-1] == '/')
1684 l--;
1685
1686 if (l <= 0)
1687 break;
1688
1689 if (!(t = strndup(path, l)))
1690 return -ENOMEM;
1691
1692 if (path_startswith(stop, t)) {
1693 free(t);
1694 return 0;
1695 }
1696
1697 r = rmdir(t);
1698 free(t);
1699
1700 if (r < 0)
1701 if (errno != ENOENT)
1702 return -errno;
1703 }
1704
1705 return 0;
1706}
1707
1708
fb624d04
LP
1709char hexchar(int x) {
1710 static const char table[16] = "0123456789abcdef";
1711
1712 return table[x & 15];
1713}
4fe88d28
LP
1714
1715int unhexchar(char c) {
1716
1717 if (c >= '0' && c <= '9')
1718 return c - '0';
1719
1720 if (c >= 'a' && c <= 'f')
ea430986 1721 return c - 'a' + 10;
4fe88d28
LP
1722
1723 if (c >= 'A' && c <= 'F')
ea430986 1724 return c - 'A' + 10;
4fe88d28
LP
1725
1726 return -1;
1727}
1728
1729char octchar(int x) {
1730 return '0' + (x & 7);
1731}
1732
1733int unoctchar(char c) {
1734
1735 if (c >= '0' && c <= '7')
1736 return c - '0';
1737
1738 return -1;
1739}
1740
5af98f82
LP
1741char decchar(int x) {
1742 return '0' + (x % 10);
1743}
1744
1745int undecchar(char c) {
1746
1747 if (c >= '0' && c <= '9')
1748 return c - '0';
1749
1750 return -1;
1751}
1752
4fe88d28
LP
1753char *cescape(const char *s) {
1754 char *r, *t;
1755 const char *f;
1756
1757 assert(s);
1758
1759 /* Does C style string escaping. */
1760
1761 if (!(r = new(char, strlen(s)*4 + 1)))
1762 return NULL;
1763
1764 for (f = s, t = r; *f; f++)
1765
1766 switch (*f) {
1767
1768 case '\a':
1769 *(t++) = '\\';
1770 *(t++) = 'a';
1771 break;
1772 case '\b':
1773 *(t++) = '\\';
1774 *(t++) = 'b';
1775 break;
1776 case '\f':
1777 *(t++) = '\\';
1778 *(t++) = 'f';
1779 break;
1780 case '\n':
1781 *(t++) = '\\';
1782 *(t++) = 'n';
1783 break;
1784 case '\r':
1785 *(t++) = '\\';
1786 *(t++) = 'r';
1787 break;
1788 case '\t':
1789 *(t++) = '\\';
1790 *(t++) = 't';
1791 break;
1792 case '\v':
1793 *(t++) = '\\';
1794 *(t++) = 'v';
1795 break;
1796 case '\\':
1797 *(t++) = '\\';
1798 *(t++) = '\\';
1799 break;
1800 case '"':
1801 *(t++) = '\\';
1802 *(t++) = '"';
1803 break;
1804 case '\'':
1805 *(t++) = '\\';
1806 *(t++) = '\'';
1807 break;
1808
1809 default:
1810 /* For special chars we prefer octal over
1811 * hexadecimal encoding, simply because glib's
1812 * g_strescape() does the same */
1813 if ((*f < ' ') || (*f >= 127)) {
1814 *(t++) = '\\';
1815 *(t++) = octchar((unsigned char) *f >> 6);
1816 *(t++) = octchar((unsigned char) *f >> 3);
1817 *(t++) = octchar((unsigned char) *f);
1818 } else
1819 *(t++) = *f;
1820 break;
1821 }
1822
1823 *t = 0;
1824
1825 return r;
1826}
1827
6febfd0d 1828char *cunescape_length(const char *s, size_t length) {
4fe88d28
LP
1829 char *r, *t;
1830 const char *f;
1831
1832 assert(s);
1833
1834 /* Undoes C style string escaping */
1835
7f110ff9
LP
1836 r = new(char, length+1);
1837 if (!r)
4fe88d28
LP
1838 return r;
1839
6febfd0d 1840 for (f = s, t = r; f < s + length; f++) {
4fe88d28
LP
1841
1842 if (*f != '\\') {
1843 *(t++) = *f;
1844 continue;
1845 }
1846
1847 f++;
1848
1849 switch (*f) {
1850
1851 case 'a':
1852 *(t++) = '\a';
1853 break;
1854 case 'b':
1855 *(t++) = '\b';
1856 break;
1857 case 'f':
1858 *(t++) = '\f';
1859 break;
1860 case 'n':
1861 *(t++) = '\n';
1862 break;
1863 case 'r':
1864 *(t++) = '\r';
1865 break;
1866 case 't':
1867 *(t++) = '\t';
1868 break;
1869 case 'v':
1870 *(t++) = '\v';
1871 break;
1872 case '\\':
1873 *(t++) = '\\';
1874 break;
1875 case '"':
1876 *(t++) = '"';
1877 break;
1878 case '\'':
1879 *(t++) = '\'';
1880 break;
1881
e167fb86
LP
1882 case 's':
1883 /* This is an extension of the XDG syntax files */
1884 *(t++) = ' ';
1885 break;
1886
4fe88d28
LP
1887 case 'x': {
1888 /* hexadecimal encoding */
1889 int a, b;
1890
7f110ff9
LP
1891 a = unhexchar(f[1]);
1892 b = unhexchar(f[2]);
1893
1894 if (a < 0 || b < 0) {
4fe88d28
LP
1895 /* Invalid escape code, let's take it literal then */
1896 *(t++) = '\\';
1897 *(t++) = 'x';
1898 } else {
1899 *(t++) = (char) ((a << 4) | b);
1900 f += 2;
1901 }
1902
1903 break;
1904 }
1905
1906 case '0':
1907 case '1':
1908 case '2':
1909 case '3':
1910 case '4':
1911 case '5':
1912 case '6':
1913 case '7': {
1914 /* octal encoding */
1915 int a, b, c;
1916
7f110ff9
LP
1917 a = unoctchar(f[0]);
1918 b = unoctchar(f[1]);
1919 c = unoctchar(f[2]);
1920
1921 if (a < 0 || b < 0 || c < 0) {
4fe88d28
LP
1922 /* Invalid escape code, let's take it literal then */
1923 *(t++) = '\\';
1924 *(t++) = f[0];
1925 } else {
1926 *(t++) = (char) ((a << 6) | (b << 3) | c);
1927 f += 2;
1928 }
1929
1930 break;
1931 }
1932
1933 case 0:
1934 /* premature end of string.*/
1935 *(t++) = '\\';
1936 goto finish;
1937
1938 default:
1939 /* Invalid escape code, let's take it literal then */
1940 *(t++) = '\\';
f3d4cc01 1941 *(t++) = *f;
4fe88d28
LP
1942 break;
1943 }
1944 }
1945
1946finish:
1947 *t = 0;
1948 return r;
1949}
1950
6febfd0d
LP
1951char *cunescape(const char *s) {
1952 return cunescape_length(s, strlen(s));
1953}
4fe88d28
LP
1954
1955char *xescape(const char *s, const char *bad) {
1956 char *r, *t;
1957 const char *f;
1958
1959 /* Escapes all chars in bad, in addition to \ and all special
1960 * chars, in \xFF style escaping. May be reversed with
1961 * cunescape. */
1962
1963 if (!(r = new(char, strlen(s)*4+1)))
1964 return NULL;
1965
1966 for (f = s, t = r; *f; f++) {
1967
b866264a
LP
1968 if ((*f < ' ') || (*f >= 127) ||
1969 (*f == '\\') || strchr(bad, *f)) {
4fe88d28
LP
1970 *(t++) = '\\';
1971 *(t++) = 'x';
1972 *(t++) = hexchar(*f >> 4);
1973 *(t++) = hexchar(*f);
1974 } else
1975 *(t++) = *f;
1976 }
1977
1978 *t = 0;
1979
1980 return r;
1981}
1982
ea430986 1983char *bus_path_escape(const char *s) {
ea430986
LP
1984 char *r, *t;
1985 const char *f;
1986
47be870b
LP
1987 assert(s);
1988
ea430986
LP
1989 /* Escapes all chars that D-Bus' object path cannot deal
1990 * with. Can be reverse with bus_path_unescape() */
1991
1992 if (!(r = new(char, strlen(s)*3+1)))
1993 return NULL;
1994
1995 for (f = s, t = r; *f; f++) {
1996
1997 if (!(*f >= 'A' && *f <= 'Z') &&
1998 !(*f >= 'a' && *f <= 'z') &&
1999 !(*f >= '0' && *f <= '9')) {
2000 *(t++) = '_';
2001 *(t++) = hexchar(*f >> 4);
2002 *(t++) = hexchar(*f);
2003 } else
2004 *(t++) = *f;
2005 }
2006
2007 *t = 0;
2008
2009 return r;
2010}
2011
9e2f7c11 2012char *bus_path_unescape(const char *f) {
ea430986 2013 char *r, *t;
ea430986 2014
9e2f7c11 2015 assert(f);
47be870b 2016
9e2f7c11 2017 if (!(r = strdup(f)))
ea430986
LP
2018 return NULL;
2019
9e2f7c11 2020 for (t = r; *f; f++) {
ea430986
LP
2021
2022 if (*f == '_') {
2023 int a, b;
2024
2025 if ((a = unhexchar(f[1])) < 0 ||
2026 (b = unhexchar(f[2])) < 0) {
2027 /* Invalid escape code, let's take it literal then */
2028 *(t++) = '_';
2029 } else {
2030 *(t++) = (char) ((a << 4) | b);
2031 f += 2;
2032 }
2033 } else
2034 *(t++) = *f;
2035 }
2036
2037 *t = 0;
2038
2039 return r;
2040}
2041
4fe88d28
LP
2042char *path_kill_slashes(char *path) {
2043 char *f, *t;
2044 bool slash = false;
2045
2046 /* Removes redundant inner and trailing slashes. Modifies the
2047 * passed string in-place.
2048 *
2049 * ///foo///bar/ becomes /foo/bar
2050 */
2051
2052 for (f = path, t = path; *f; f++) {
2053
2054 if (*f == '/') {
2055 slash = true;
2056 continue;
2057 }
2058
2059 if (slash) {
2060 slash = false;
2061 *(t++) = '/';
2062 }
2063
2064 *(t++) = *f;
2065 }
2066
2067 /* Special rule, if we are talking of the root directory, a
2068 trailing slash is good */
2069
2070 if (t == path && slash)
2071 *(t++) = '/';
2072
2073 *t = 0;
2074 return path;
2075}
2076
2077bool path_startswith(const char *path, const char *prefix) {
2078 assert(path);
2079 assert(prefix);
2080
2081 if ((path[0] == '/') != (prefix[0] == '/'))
2082 return false;
2083
2084 for (;;) {
2085 size_t a, b;
2086
2087 path += strspn(path, "/");
2088 prefix += strspn(prefix, "/");
2089
2090 if (*prefix == 0)
2091 return true;
2092
2093 if (*path == 0)
2094 return false;
2095
2096 a = strcspn(path, "/");
2097 b = strcspn(prefix, "/");
2098
2099 if (a != b)
2100 return false;
2101
2102 if (memcmp(path, prefix, a) != 0)
2103 return false;
2104
2105 path += a;
2106 prefix += b;
2107 }
2108}
2109
15ae422b
LP
2110bool path_equal(const char *a, const char *b) {
2111 assert(a);
2112 assert(b);
2113
2114 if ((a[0] == '/') != (b[0] == '/'))
2115 return false;
2116
2117 for (;;) {
2118 size_t j, k;
2119
2120 a += strspn(a, "/");
2121 b += strspn(b, "/");
2122
2123 if (*a == 0 && *b == 0)
2124 return true;
2125
2126 if (*a == 0 || *b == 0)
2127 return false;
2128
2129 j = strcspn(a, "/");
2130 k = strcspn(b, "/");
2131
2132 if (j != k)
2133 return false;
2134
2135 if (memcmp(a, b, j) != 0)
2136 return false;
2137
2138 a += j;
2139 b += k;
2140 }
2141}
2142
67d51650 2143char *ascii_strlower(char *t) {
4fe88d28
LP
2144 char *p;
2145
67d51650 2146 assert(t);
4fe88d28 2147
67d51650 2148 for (p = t; *p; p++)
4fe88d28
LP
2149 if (*p >= 'A' && *p <= 'Z')
2150 *p = *p - 'A' + 'a';
2151
67d51650 2152 return t;
4fe88d28 2153}
1dccbe19 2154
c85dc17b
LP
2155bool ignore_file(const char *filename) {
2156 assert(filename);
2157
2158 return
2159 filename[0] == '.' ||
6c78be3c 2160 streq(filename, "lost+found") ||
e472d476
LP
2161 streq(filename, "aquota.user") ||
2162 streq(filename, "aquota.group") ||
c85dc17b
LP
2163 endswith(filename, "~") ||
2164 endswith(filename, ".rpmnew") ||
2165 endswith(filename, ".rpmsave") ||
2166 endswith(filename, ".rpmorig") ||
2167 endswith(filename, ".dpkg-old") ||
2168 endswith(filename, ".dpkg-new") ||
2169 endswith(filename, ".swp");
2170}
2171
3a0ecb08
LP
2172int fd_nonblock(int fd, bool nonblock) {
2173 int flags;
2174
2175 assert(fd >= 0);
2176
2177 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2178 return -errno;
2179
2180 if (nonblock)
2181 flags |= O_NONBLOCK;
2182 else
2183 flags &= ~O_NONBLOCK;
2184
2185 if (fcntl(fd, F_SETFL, flags) < 0)
2186 return -errno;
2187
2188 return 0;
2189}
2190
2191int fd_cloexec(int fd, bool cloexec) {
2192 int flags;
2193
2194 assert(fd >= 0);
2195
2196 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2197 return -errno;
2198
2199 if (cloexec)
2200 flags |= FD_CLOEXEC;
2201 else
2202 flags &= ~FD_CLOEXEC;
2203
2204 if (fcntl(fd, F_SETFD, flags) < 0)
2205 return -errno;
2206
2207 return 0;
2208}
2209
b19be9eb
LP
2210static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
2211 unsigned i;
2212
2213 assert(n_fdset == 0 || fdset);
2214
2215 for (i = 0; i < n_fdset; i++)
2216 if (fdset[i] == fd)
2217 return true;
2218
2219 return false;
2220}
2221
a0d40ac5
LP
2222int close_all_fds(const int except[], unsigned n_except) {
2223 DIR *d;
2224 struct dirent *de;
2225 int r = 0;
2226
b19be9eb
LP
2227 assert(n_except == 0 || except);
2228
2229 d = opendir("/proc/self/fd");
2230 if (!d) {
2231 int fd;
2232 struct rlimit rl;
2233
2234 /* When /proc isn't available (for example in chroots)
2235 * the fallback is brute forcing through the fd
2236 * table */
2237
2238 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
2239 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
2240
2241 if (fd_in_set(fd, except, n_except))
2242 continue;
2243
2244 if (close_nointr(fd) < 0)
2245 if (errno != EBADF && r == 0)
2246 r = -errno;
2247 }
2248
2249 return r;
2250 }
a0d40ac5
LP
2251
2252 while ((de = readdir(d))) {
a7610064 2253 int fd = -1;
a0d40ac5 2254
a16e1123 2255 if (ignore_file(de->d_name))
a0d40ac5
LP
2256 continue;
2257
720ce21d
LP
2258 if (safe_atoi(de->d_name, &fd) < 0)
2259 /* Let's better ignore this, just in case */
2260 continue;
a0d40ac5
LP
2261
2262 if (fd < 3)
2263 continue;
2264
2265 if (fd == dirfd(d))
2266 continue;
2267
b19be9eb
LP
2268 if (fd_in_set(fd, except, n_except))
2269 continue;
a0d40ac5 2270
720ce21d 2271 if (close_nointr(fd) < 0) {
2f357920 2272 /* Valgrind has its own FD and doesn't want to have it closed */
720ce21d
LP
2273 if (errno != EBADF && r == 0)
2274 r = -errno;
2f357920 2275 }
a0d40ac5
LP
2276 }
2277
a0d40ac5
LP
2278 closedir(d);
2279 return r;
2280}
2281
db12775d
LP
2282bool chars_intersect(const char *a, const char *b) {
2283 const char *p;
2284
2285 /* Returns true if any of the chars in a are in b. */
2286 for (p = a; *p; p++)
2287 if (strchr(b, *p))
2288 return true;
2289
2290 return false;
2291}
2292
8b6c7120
LP
2293char *format_timestamp(char *buf, size_t l, usec_t t) {
2294 struct tm tm;
2295 time_t sec;
2296
2297 assert(buf);
2298 assert(l > 0);
2299
2300 if (t <= 0)
2301 return NULL;
2302
f872ec33 2303 sec = (time_t) (t / USEC_PER_SEC);
8b6c7120
LP
2304
2305 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2306 return NULL;
2307
2308 return buf;
2309}
2310
584be568
LP
2311char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2312 usec_t n, d;
2313
2314 n = now(CLOCK_REALTIME);
2315
2316 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2317 return NULL;
2318
2319 d = n - t;
2320
2321 if (d >= USEC_PER_YEAR)
2322 snprintf(buf, l, "%llu years and %llu months ago",
2323 (unsigned long long) (d / USEC_PER_YEAR),
2324 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2325 else if (d >= USEC_PER_MONTH)
2326 snprintf(buf, l, "%llu months and %llu days ago",
2327 (unsigned long long) (d / USEC_PER_MONTH),
2328 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2329 else if (d >= USEC_PER_WEEK)
2330 snprintf(buf, l, "%llu weeks and %llu days ago",
2331 (unsigned long long) (d / USEC_PER_WEEK),
2332 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2333 else if (d >= 2*USEC_PER_DAY)
2334 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2335 else if (d >= 25*USEC_PER_HOUR)
2336 snprintf(buf, l, "1 day and %lluh ago",
2337 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2338 else if (d >= 6*USEC_PER_HOUR)
2339 snprintf(buf, l, "%lluh ago",
2340 (unsigned long long) (d / USEC_PER_HOUR));
2341 else if (d >= USEC_PER_HOUR)
2342 snprintf(buf, l, "%lluh %llumin ago",
2343 (unsigned long long) (d / USEC_PER_HOUR),
2344 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2345 else if (d >= 5*USEC_PER_MINUTE)
2346 snprintf(buf, l, "%llumin ago",
2347 (unsigned long long) (d / USEC_PER_MINUTE));
2348 else if (d >= USEC_PER_MINUTE)
2349 snprintf(buf, l, "%llumin %llus ago",
2350 (unsigned long long) (d / USEC_PER_MINUTE),
2351 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2352 else if (d >= USEC_PER_SEC)
2353 snprintf(buf, l, "%llus ago",
2354 (unsigned long long) (d / USEC_PER_SEC));
2355 else if (d >= USEC_PER_MSEC)
2356 snprintf(buf, l, "%llums ago",
2357 (unsigned long long) (d / USEC_PER_MSEC));
2358 else if (d > 0)
2359 snprintf(buf, l, "%lluus ago",
2360 (unsigned long long) d);
2361 else
2362 snprintf(buf, l, "now");
2363
2364 buf[l-1] = 0;
2365 return buf;
2366}
2367
871d7de4
LP
2368char *format_timespan(char *buf, size_t l, usec_t t) {
2369 static const struct {
2370 const char *suffix;
2371 usec_t usec;
2372 } table[] = {
2373 { "w", USEC_PER_WEEK },
2374 { "d", USEC_PER_DAY },
2375 { "h", USEC_PER_HOUR },
2376 { "min", USEC_PER_MINUTE },
2377 { "s", USEC_PER_SEC },
2378 { "ms", USEC_PER_MSEC },
2379 { "us", 1 },
2380 };
2381
2382 unsigned i;
2383 char *p = buf;
2384
2385 assert(buf);
2386 assert(l > 0);
2387
2388 if (t == (usec_t) -1)
2389 return NULL;
2390
4502d22c
LP
2391 if (t == 0) {
2392 snprintf(p, l, "0");
2393 p[l-1] = 0;
2394 return p;
2395 }
2396
871d7de4
LP
2397 /* The result of this function can be parsed with parse_usec */
2398
2399 for (i = 0; i < ELEMENTSOF(table); i++) {
2400 int k;
2401 size_t n;
2402
2403 if (t < table[i].usec)
2404 continue;
2405
2406 if (l <= 1)
2407 break;
2408
2409 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2410 n = MIN((size_t) k, l);
2411
2412 l -= n;
2413 p += n;
2414
2415 t %= table[i].usec;
2416 }
2417
2418 *p = 0;
2419
2420 return buf;
2421}
2422
42856c10
LP
2423bool fstype_is_network(const char *fstype) {
2424 static const char * const table[] = {
2425 "cifs",
2426 "smbfs",
2427 "ncpfs",
2428 "nfs",
ca139f94
LP
2429 "nfs4",
2430 "gfs",
2431 "gfs2"
42856c10
LP
2432 };
2433
2434 unsigned i;
2435
2436 for (i = 0; i < ELEMENTSOF(table); i++)
2437 if (streq(table[i], fstype))
2438 return true;
2439
2440 return false;
2441}
2442
601f6a1e
LP
2443int chvt(int vt) {
2444 int fd, r = 0;
2445
74bc3bdc 2446 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
601f6a1e
LP
2447 return -errno;
2448
2449 if (vt < 0) {
2450 int tiocl[2] = {
2451 TIOCL_GETKMSGREDIRECT,
2452 0
2453 };
2454
678abaf9
TJ
2455 if (ioctl(fd, TIOCLINUX, tiocl) < 0) {
2456 r = -errno;
2457 goto fail;
2458 }
601f6a1e
LP
2459
2460 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2461 }
2462
2463 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2464 r = -errno;
2465
678abaf9
TJ
2466fail:
2467 close_nointr_nofail(fd);
601f6a1e
LP
2468 return r;
2469}
2470
8f2d43a0 2471int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
80876c20
LP
2472 struct termios old_termios, new_termios;
2473 char c;
20c03b7b 2474 char line[LINE_MAX];
80876c20
LP
2475
2476 assert(f);
2477 assert(ret);
2478
2479 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2480 new_termios = old_termios;
2481
2482 new_termios.c_lflag &= ~ICANON;
2483 new_termios.c_cc[VMIN] = 1;
2484 new_termios.c_cc[VTIME] = 0;
2485
2486 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2487 size_t k;
2488
8f2d43a0
LP
2489 if (t != (usec_t) -1) {
2490 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2491 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2492 return -ETIMEDOUT;
2493 }
2494 }
2495
80876c20
LP
2496 k = fread(&c, 1, 1, f);
2497
2498 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2499
2500 if (k <= 0)
2501 return -EIO;
2502
2503 if (need_nl)
2504 *need_nl = c != '\n';
2505
2506 *ret = c;
2507 return 0;
2508 }
2509 }
2510
8f2d43a0
LP
2511 if (t != (usec_t) -1)
2512 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2513 return -ETIMEDOUT;
2514
2515 if (!fgets(line, sizeof(line), f))
80876c20
LP
2516 return -EIO;
2517
2518 truncate_nl(line);
2519
2520 if (strlen(line) != 1)
2521 return -EBADMSG;
2522
2523 if (need_nl)
2524 *need_nl = false;
2525
2526 *ret = line[0];
2527 return 0;
2528}
2529
2530int ask(char *ret, const char *replies, const char *text, ...) {
1b39d4b9
LP
2531 bool on_tty;
2532
80876c20
LP
2533 assert(ret);
2534 assert(replies);
2535 assert(text);
2536
1b39d4b9
LP
2537 on_tty = isatty(STDOUT_FILENO);
2538
80876c20
LP
2539 for (;;) {
2540 va_list ap;
2541 char c;
2542 int r;
2543 bool need_nl = true;
2544
1b39d4b9 2545 if (on_tty)
c1072ea0 2546 fputs(ANSI_HIGHLIGHT_ON, stdout);
b1b2dc0c 2547
80876c20
LP
2548 va_start(ap, text);
2549 vprintf(text, ap);
2550 va_end(ap);
2551
1b39d4b9 2552 if (on_tty)
c1072ea0 2553 fputs(ANSI_HIGHLIGHT_OFF, stdout);
b1b2dc0c 2554
80876c20
LP
2555 fflush(stdout);
2556
8f2d43a0
LP
2557 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2558 if (r < 0) {
80876c20
LP
2559
2560 if (r == -EBADMSG) {
2561 puts("Bad input, please try again.");
2562 continue;
2563 }
2564
2565 putchar('\n');
2566 return r;
2567 }
2568
2569 if (need_nl)
2570 putchar('\n');
2571
2572 if (strchr(replies, c)) {
2573 *ret = c;
2574 return 0;
2575 }
2576
2577 puts("Read unexpected character, please try again.");
2578 }
2579}
2580
512947d4 2581int reset_terminal_fd(int fd, bool switch_to_text) {
80876c20
LP
2582 struct termios termios;
2583 int r = 0;
3fe5e5d4
LP
2584
2585 /* Set terminal to some sane defaults */
80876c20
LP
2586
2587 assert(fd >= 0);
2588
eed1d0e3
LP
2589 /* We leave locked terminal attributes untouched, so that
2590 * Plymouth may set whatever it wants to set, and we don't
2591 * interfere with that. */
3fe5e5d4
LP
2592
2593 /* Disable exclusive mode, just in case */
2594 ioctl(fd, TIOCNXCL);
2595
5c0100a5 2596 /* Switch to text mode */
512947d4
MS
2597 if (switch_to_text)
2598 ioctl(fd, KDSETMODE, KD_TEXT);
5c0100a5 2599
3fe5e5d4 2600 /* Enable console unicode mode */
df465b3f 2601 ioctl(fd, KDSKBMODE, K_UNICODE);
80876c20
LP
2602
2603 if (tcgetattr(fd, &termios) < 0) {
2604 r = -errno;
2605 goto finish;
2606 }
2607
aaf694ca
LP
2608 /* We only reset the stuff that matters to the software. How
2609 * hardware is set up we don't touch assuming that somebody
2610 * else will do that for us */
2611
2612 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
80876c20
LP
2613 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2614 termios.c_oflag |= ONLCR;
2615 termios.c_cflag |= CREAD;
2616 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2617
2618 termios.c_cc[VINTR] = 03; /* ^C */
2619 termios.c_cc[VQUIT] = 034; /* ^\ */
2620 termios.c_cc[VERASE] = 0177;
2621 termios.c_cc[VKILL] = 025; /* ^X */
2622 termios.c_cc[VEOF] = 04; /* ^D */
2623 termios.c_cc[VSTART] = 021; /* ^Q */
2624 termios.c_cc[VSTOP] = 023; /* ^S */
2625 termios.c_cc[VSUSP] = 032; /* ^Z */
2626 termios.c_cc[VLNEXT] = 026; /* ^V */
2627 termios.c_cc[VWERASE] = 027; /* ^W */
2628 termios.c_cc[VREPRINT] = 022; /* ^R */
aaf694ca
LP
2629 termios.c_cc[VEOL] = 0;
2630 termios.c_cc[VEOL2] = 0;
80876c20
LP
2631
2632 termios.c_cc[VTIME] = 0;
2633 termios.c_cc[VMIN] = 1;
2634
2635 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2636 r = -errno;
2637
2638finish:
2639 /* Just in case, flush all crap out */
2640 tcflush(fd, TCIOFLUSH);
2641
2642 return r;
2643}
2644
6ea832a2
LP
2645int reset_terminal(const char *name) {
2646 int fd, r;
2647
2648 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2649 if (fd < 0)
2650 return fd;
2651
512947d4 2652 r = reset_terminal_fd(fd, true);
6ea832a2
LP
2653 close_nointr_nofail(fd);
2654
2655 return r;
2656}
2657
80876c20
LP
2658int open_terminal(const char *name, int mode) {
2659 int fd, r;
f73f76ac 2660 unsigned c = 0;
80876c20 2661
f73f76ac
LP
2662 /*
2663 * If a TTY is in the process of being closed opening it might
2664 * cause EIO. This is horribly awful, but unlikely to be
2665 * changed in the kernel. Hence we work around this problem by
2666 * retrying a couple of times.
2667 *
2668 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2669 */
2670
2671 for (;;) {
2672 if ((fd = open(name, mode)) >= 0)
2673 break;
2674
2675 if (errno != EIO)
2676 return -errno;
2677
2678 if (c >= 20)
2679 return -errno;
2680
2681 usleep(50 * USEC_PER_MSEC);
2682 c++;
2683 }
2684
2685 if (fd < 0)
80876c20
LP
2686 return -errno;
2687
2688 if ((r = isatty(fd)) < 0) {
2689 close_nointr_nofail(fd);
2690 return -errno;
2691 }
2692
2693 if (!r) {
2694 close_nointr_nofail(fd);
2695 return -ENOTTY;
2696 }
2697
2698 return fd;
2699}
2700
2701int flush_fd(int fd) {
2702 struct pollfd pollfd;
2703
2704 zero(pollfd);
2705 pollfd.fd = fd;
2706 pollfd.events = POLLIN;
2707
2708 for (;;) {
20c03b7b 2709 char buf[LINE_MAX];
80876c20
LP
2710 ssize_t l;
2711 int r;
2712
2713 if ((r = poll(&pollfd, 1, 0)) < 0) {
2714
2715 if (errno == EINTR)
2716 continue;
2717
2718 return -errno;
2719 }
2720
2721 if (r == 0)
2722 return 0;
2723
2724 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2725
2726 if (errno == EINTR)
2727 continue;
2728
2729 if (errno == EAGAIN)
2730 return 0;
2731
2732 return -errno;
2733 }
2734
2735 if (l <= 0)
2736 return 0;
2737 }
2738}
2739
21de3988 2740int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
bab45044 2741 int fd = -1, notify = -1, r, wd = -1;
80876c20
LP
2742
2743 assert(name);
2744
2745 /* We use inotify to be notified when the tty is closed. We
2746 * create the watch before checking if we can actually acquire
2747 * it, so that we don't lose any event.
2748 *
2749 * Note: strictly speaking this actually watches for the
2750 * device being closed, it does *not* really watch whether a
2751 * tty loses its controlling process. However, unless some
2752 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2753 * its tty otherwise this will not become a problem. As long
2754 * as the administrator makes sure not configure any service
2755 * on the same tty as an untrusted user this should not be a
2756 * problem. (Which he probably should not do anyway.) */
2757
2758 if (!fail && !force) {
2759 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2760 r = -errno;
2761 goto fail;
2762 }
2763
2764 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2765 r = -errno;
2766 goto fail;
2767 }
2768 }
2769
2770 for (;;) {
e3d1855b
LP
2771 if (notify >= 0)
2772 if ((r = flush_fd(notify)) < 0)
2773 goto fail;
80876c20
LP
2774
2775 /* We pass here O_NOCTTY only so that we can check the return
2776 * value TIOCSCTTY and have a reliable way to figure out if we
2777 * successfully became the controlling process of the tty */
6ea832a2
LP
2778 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2779 return fd;
80876c20
LP
2780
2781 /* First, try to get the tty */
21de3988
LP
2782 r = ioctl(fd, TIOCSCTTY, force);
2783
2784 /* Sometimes it makes sense to ignore TIOCSCTTY
2785 * returning EPERM, i.e. when very likely we already
2786 * are have this controlling terminal. */
2787 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2788 r = 0;
2789
2790 if (r < 0 && (force || fail || errno != EPERM)) {
80876c20
LP
2791 r = -errno;
2792 goto fail;
2793 }
2794
2795 if (r >= 0)
2796 break;
2797
2798 assert(!fail);
2799 assert(!force);
2800 assert(notify >= 0);
2801
2802 for (;;) {
f601daa7 2803 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
80876c20 2804 ssize_t l;
f601daa7 2805 struct inotify_event *e;
80876c20 2806
50f20cfd 2807 if ((l = read(notify, inotify_buffer, sizeof(inotify_buffer))) < 0) {
80876c20 2808
f601daa7
LP
2809 if (errno == EINTR)
2810 continue;
2811
2812 r = -errno;
2813 goto fail;
2814 }
2815
2816 e = (struct inotify_event*) inotify_buffer;
80876c20 2817
f601daa7
LP
2818 while (l > 0) {
2819 size_t step;
80876c20 2820
f601daa7 2821 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
80876c20 2822 r = -EIO;
f601daa7
LP
2823 goto fail;
2824 }
80876c20 2825
f601daa7
LP
2826 step = sizeof(struct inotify_event) + e->len;
2827 assert(step <= (size_t) l);
80876c20 2828
f601daa7
LP
2829 e = (struct inotify_event*) ((uint8_t*) e + step);
2830 l -= step;
80876c20
LP
2831 }
2832
2833 break;
2834 }
2835
2836 /* We close the tty fd here since if the old session
2837 * ended our handle will be dead. It's important that
2838 * we do this after sleeping, so that we don't enter
2839 * an endless loop. */
2840 close_nointr_nofail(fd);
2841 }
2842
2843 if (notify >= 0)
a16e1123 2844 close_nointr_nofail(notify);
80876c20 2845
512947d4
MS
2846 r = reset_terminal_fd(fd, true);
2847 if (r < 0)
80876c20
LP
2848 log_warning("Failed to reset terminal: %s", strerror(-r));
2849
2850 return fd;
2851
2852fail:
2853 if (fd >= 0)
a16e1123 2854 close_nointr_nofail(fd);
80876c20
LP
2855
2856 if (notify >= 0)
a16e1123 2857 close_nointr_nofail(notify);
80876c20
LP
2858
2859 return r;
2860}
2861
2862int release_terminal(void) {
2863 int r = 0, fd;
57cd2192 2864 struct sigaction sa_old, sa_new;
80876c20 2865
ccaa6149 2866 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
80876c20
LP
2867 return -errno;
2868
57cd2192
LP
2869 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2870 * by our own TIOCNOTTY */
2871
2872 zero(sa_new);
2873 sa_new.sa_handler = SIG_IGN;
2874 sa_new.sa_flags = SA_RESTART;
2875 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2876
80876c20
LP
2877 if (ioctl(fd, TIOCNOTTY) < 0)
2878 r = -errno;
2879
57cd2192
LP
2880 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2881
80876c20
LP
2882 close_nointr_nofail(fd);
2883 return r;
2884}
2885
9a34ec5f
LP
2886int sigaction_many(const struct sigaction *sa, ...) {
2887 va_list ap;
2888 int r = 0, sig;
2889
2890 va_start(ap, sa);
2891 while ((sig = va_arg(ap, int)) > 0)
2892 if (sigaction(sig, sa, NULL) < 0)
2893 r = -errno;
2894 va_end(ap);
2895
2896 return r;
2897}
2898
2899int ignore_signals(int sig, ...) {
a337c6fc 2900 struct sigaction sa;
9a34ec5f
LP
2901 va_list ap;
2902 int r = 0;
a337c6fc
LP
2903
2904 zero(sa);
2905 sa.sa_handler = SIG_IGN;
2906 sa.sa_flags = SA_RESTART;
2907
9a34ec5f
LP
2908 if (sigaction(sig, &sa, NULL) < 0)
2909 r = -errno;
2910
2911 va_start(ap, sig);
2912 while ((sig = va_arg(ap, int)) > 0)
2913 if (sigaction(sig, &sa, NULL) < 0)
2914 r = -errno;
2915 va_end(ap);
2916
2917 return r;
2918}
2919
2920int default_signals(int sig, ...) {
2921 struct sigaction sa;
2922 va_list ap;
2923 int r = 0;
2924
2925 zero(sa);
2926 sa.sa_handler = SIG_DFL;
2927 sa.sa_flags = SA_RESTART;
2928
2929 if (sigaction(sig, &sa, NULL) < 0)
2930 r = -errno;
2931
2932 va_start(ap, sig);
2933 while ((sig = va_arg(ap, int)) > 0)
2934 if (sigaction(sig, &sa, NULL) < 0)
2935 r = -errno;
2936 va_end(ap);
2937
2938 return r;
a337c6fc
LP
2939}
2940
8d567588
LP
2941int close_pipe(int p[]) {
2942 int a = 0, b = 0;
2943
2944 assert(p);
2945
2946 if (p[0] >= 0) {
2947 a = close_nointr(p[0]);
2948 p[0] = -1;
2949 }
2950
2951 if (p[1] >= 0) {
2952 b = close_nointr(p[1]);
2953 p[1] = -1;
2954 }
2955
2956 return a < 0 ? a : b;
2957}
2958
eb22ac37 2959ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
8d567588
LP
2960 uint8_t *p;
2961 ssize_t n = 0;
2962
2963 assert(fd >= 0);
2964 assert(buf);
2965
2966 p = buf;
2967
2968 while (nbytes > 0) {
2969 ssize_t k;
2970
2971 if ((k = read(fd, p, nbytes)) <= 0) {
2972
eb22ac37 2973 if (k < 0 && errno == EINTR)
8d567588
LP
2974 continue;
2975
eb22ac37 2976 if (k < 0 && errno == EAGAIN && do_poll) {
8d567588
LP
2977 struct pollfd pollfd;
2978
2979 zero(pollfd);
2980 pollfd.fd = fd;
2981 pollfd.events = POLLIN;
2982
2983 if (poll(&pollfd, 1, -1) < 0) {
2984 if (errno == EINTR)
2985 continue;
2986
2987 return n > 0 ? n : -errno;
2988 }
2989
2990 if (pollfd.revents != POLLIN)
2991 return n > 0 ? n : -EIO;
2992
2993 continue;
2994 }
2995
2996 return n > 0 ? n : (k < 0 ? -errno : 0);
2997 }
2998
2999 p += k;
3000 nbytes -= k;
3001 n += k;
3002 }
3003
3004 return n;
3005}
3006
eb22ac37
LP
3007ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
3008 const uint8_t *p;
3009 ssize_t n = 0;
3010
3011 assert(fd >= 0);
3012 assert(buf);
3013
3014 p = buf;
3015
3016 while (nbytes > 0) {
3017 ssize_t k;
3018
fe652127
LP
3019 k = write(fd, p, nbytes);
3020 if (k <= 0) {
eb22ac37
LP
3021
3022 if (k < 0 && errno == EINTR)
3023 continue;
3024
3025 if (k < 0 && errno == EAGAIN && do_poll) {
3026 struct pollfd pollfd;
3027
3028 zero(pollfd);
3029 pollfd.fd = fd;
3030 pollfd.events = POLLOUT;
3031
3032 if (poll(&pollfd, 1, -1) < 0) {
3033 if (errno == EINTR)
3034 continue;
3035
3036 return n > 0 ? n : -errno;
3037 }
3038
3039 if (pollfd.revents != POLLOUT)
3040 return n > 0 ? n : -EIO;
3041
3042 continue;
3043 }
3044
3045 return n > 0 ? n : (k < 0 ? -errno : 0);
3046 }
3047
3048 p += k;
3049 nbytes -= k;
3050 n += k;
3051 }
3052
3053 return n;
3054}
3055
0c85a4f3 3056int path_is_mount_point(const char *t, bool allow_symlink) {
8d567588 3057 struct stat a, b;
35d2e7ec
LP
3058 char *parent;
3059 int r;
8d567588 3060
0c85a4f3
LP
3061 if (allow_symlink)
3062 r = stat(t, &a);
3063 else
3064 r = lstat(t, &a);
3065
3066 if (r < 0) {
8d567588
LP
3067 if (errno == ENOENT)
3068 return 0;
3069
3070 return -errno;
3071 }
3072
0c85a4f3
LP
3073 r = parent_of_path(t, &parent);
3074 if (r < 0)
35d2e7ec 3075 return r;
8d567588 3076
35d2e7ec
LP
3077 r = lstat(parent, &b);
3078 free(parent);
8d567588 3079
35d2e7ec
LP
3080 if (r < 0)
3081 return -errno;
8d567588
LP
3082
3083 return a.st_dev != b.st_dev;
3084}
3085
24a6e4a4
LP
3086int parse_usec(const char *t, usec_t *usec) {
3087 static const struct {
3088 const char *suffix;
3089 usec_t usec;
3090 } table[] = {
3091 { "sec", USEC_PER_SEC },
3092 { "s", USEC_PER_SEC },
3093 { "min", USEC_PER_MINUTE },
3094 { "hr", USEC_PER_HOUR },
3095 { "h", USEC_PER_HOUR },
3096 { "d", USEC_PER_DAY },
3097 { "w", USEC_PER_WEEK },
3098 { "msec", USEC_PER_MSEC },
3099 { "ms", USEC_PER_MSEC },
3100 { "m", USEC_PER_MINUTE },
3101 { "usec", 1ULL },
3102 { "us", 1ULL },
3103 { "", USEC_PER_SEC },
3104 };
3105
3106 const char *p;
3107 usec_t r = 0;
3108
3109 assert(t);
3110 assert(usec);
3111
3112 p = t;
3113 do {
3114 long long l;
3115 char *e;
3116 unsigned i;
3117
3118 errno = 0;
3119 l = strtoll(p, &e, 10);
3120
3121 if (errno != 0)
3122 return -errno;
3123
3124 if (l < 0)
3125 return -ERANGE;
3126
3127 if (e == p)
3128 return -EINVAL;
3129
3130 e += strspn(e, WHITESPACE);
3131
3132 for (i = 0; i < ELEMENTSOF(table); i++)
3133 if (startswith(e, table[i].suffix)) {
3134 r += (usec_t) l * table[i].usec;
3135 p = e + strlen(table[i].suffix);
3136 break;
3137 }
3138
3139 if (i >= ELEMENTSOF(table))
3140 return -EINVAL;
3141
3142 } while (*p != 0);
3143
3144 *usec = r;
3145
3146 return 0;
3147}
3148
ab1f0633
LP
3149int parse_bytes(const char *t, off_t *bytes) {
3150 static const struct {
3151 const char *suffix;
3152 off_t factor;
3153 } table[] = {
3154 { "B", 1 },
3155 { "K", 1024ULL },
3156 { "M", 1024ULL*1024ULL },
3157 { "G", 1024ULL*1024ULL*1024ULL },
3158 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
32895bb3
LP
3159 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3160 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
ab1f0633
LP
3161 { "", 1 },
3162 };
3163
3164 const char *p;
3165 off_t r = 0;
3166
3167 assert(t);
3168 assert(bytes);
3169
3170 p = t;
3171 do {
3172 long long l;
3173 char *e;
3174 unsigned i;
3175
3176 errno = 0;
3177 l = strtoll(p, &e, 10);
3178
3179 if (errno != 0)
3180 return -errno;
3181
3182 if (l < 0)
3183 return -ERANGE;
3184
3185 if (e == p)
3186 return -EINVAL;
3187
3188 e += strspn(e, WHITESPACE);
3189
3190 for (i = 0; i < ELEMENTSOF(table); i++)
3191 if (startswith(e, table[i].suffix)) {
3192 r += (off_t) l * table[i].factor;
3193 p = e + strlen(table[i].suffix);
3194 break;
3195 }
3196
3197 if (i >= ELEMENTSOF(table))
3198 return -EINVAL;
3199
3200 } while (*p != 0);
3201
3202 *bytes = r;
3203
3204 return 0;
3205}
3206
843d2643
LP
3207int make_stdio(int fd) {
3208 int r, s, t;
3209
3210 assert(fd >= 0);
3211
3212 r = dup2(fd, STDIN_FILENO);
3213 s = dup2(fd, STDOUT_FILENO);
3214 t = dup2(fd, STDERR_FILENO);
3215
3216 if (fd >= 3)
3217 close_nointr_nofail(fd);
3218
3219 if (r < 0 || s < 0 || t < 0)
3220 return -errno;
3221
7862f62d
LP
3222 fd_cloexec(STDIN_FILENO, false);
3223 fd_cloexec(STDOUT_FILENO, false);
3224 fd_cloexec(STDERR_FILENO, false);
3225
843d2643
LP
3226 return 0;
3227}
3228
ade509ce
LP
3229int make_null_stdio(void) {
3230 int null_fd;
3231
3232 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3233 return -errno;
3234
3235 return make_stdio(null_fd);
3236}
3237
8407a5d0
LP
3238bool is_device_path(const char *path) {
3239
3240 /* Returns true on paths that refer to a device, either in
3241 * sysfs or in /dev */
3242
3243 return
3244 path_startswith(path, "/dev/") ||
3245 path_startswith(path, "/sys/");
3246}
3247
01f78473
LP
3248int dir_is_empty(const char *path) {
3249 DIR *d;
3250 int r;
3251 struct dirent buf, *de;
3252
3253 if (!(d = opendir(path)))
3254 return -errno;
3255
3256 for (;;) {
3257 if ((r = readdir_r(d, &buf, &de)) > 0) {
3258 r = -r;
3259 break;
3260 }
3261
3262 if (!de) {
3263 r = 1;
3264 break;
3265 }
3266
3267 if (!ignore_file(de->d_name)) {
3268 r = 0;
3269 break;
3270 }
3271 }
3272
3273 closedir(d);
3274 return r;
3275}
3276
d3782d60
LP
3277unsigned long long random_ull(void) {
3278 int fd;
3279 uint64_t ull;
3280 ssize_t r;
3281
3282 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3283 goto fallback;
3284
eb22ac37 3285 r = loop_read(fd, &ull, sizeof(ull), true);
d3782d60
LP
3286 close_nointr_nofail(fd);
3287
3288 if (r != sizeof(ull))
3289 goto fallback;
3290
3291 return ull;
3292
3293fallback:
3294 return random() * RAND_MAX + random();
3295}
3296
5b6319dc
LP
3297void rename_process(const char name[8]) {
3298 assert(name);
3299
5d6b1584
LP
3300 /* This is a like a poor man's setproctitle(). It changes the
3301 * comm field, argv[0], and also the glibc's internally used
3302 * name of the process. For the first one a limit of 16 chars
3303 * applies, to the second one usually one of 10 (i.e. length
3304 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3305 * "systemd"). If you pass a longer string it will be
3306 * truncated */
5b6319dc 3307
5d6b1584 3308 prctl(PR_SET_NAME, name);
5b6319dc
LP
3309
3310 if (program_invocation_name)
3311 strncpy(program_invocation_name, name, strlen(program_invocation_name));
9a0e6896
LP
3312
3313 if (saved_argc > 0) {
3314 int i;
3315
3316 if (saved_argv[0])
3317 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3318
3319 for (i = 1; i < saved_argc; i++) {
3320 if (!saved_argv[i])
3321 break;
3322
3323 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3324 }
3325 }
5b6319dc
LP
3326}
3327
7d793605
LP
3328void sigset_add_many(sigset_t *ss, ...) {
3329 va_list ap;
3330 int sig;
3331
3332 assert(ss);
3333
3334 va_start(ap, ss);
3335 while ((sig = va_arg(ap, int)) > 0)
3336 assert_se(sigaddset(ss, sig) == 0);
3337 va_end(ap);
3338}
3339
ef2f1067
LP
3340char* gethostname_malloc(void) {
3341 struct utsname u;
3342
3343 assert_se(uname(&u) >= 0);
3344
3345 if (u.nodename[0])
3346 return strdup(u.nodename);
3347
3348 return strdup(u.sysname);
3349}
3350
3351char* getlogname_malloc(void) {
3352 uid_t uid;
3353 long bufsize;
3354 char *buf, *name;
3355 struct passwd pwbuf, *pw = NULL;
3356 struct stat st;
3357
3358 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3359 uid = st.st_uid;
3360 else
3361 uid = getuid();
3362
3363 /* Shortcut things to avoid NSS lookups */
3364 if (uid == 0)
3365 return strdup("root");
3366
3367 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3368 bufsize = 4096;
3369
3370 if (!(buf = malloc(bufsize)))
3371 return NULL;
3372
3373 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3374 name = strdup(pw->pw_name);
3375 free(buf);
3376 return name;
3377 }
3378
3379 free(buf);
3380
3381 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3382 return NULL;
3383
3384 return name;
3385}
3386
fc116c6a
LP
3387int getttyname_malloc(int fd, char **r) {
3388 char path[PATH_MAX], *c;
618e02c7 3389 int k;
8c6db833
LP
3390
3391 assert(r);
ef2f1067 3392
fc116c6a 3393 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
618e02c7 3394 return -k;
ef2f1067
LP
3395
3396 char_array_0(path);
3397
fc116c6a 3398 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
8c6db833
LP
3399 return -ENOMEM;
3400
3401 *r = c;
3402 return 0;
3403}
3404
fc116c6a
LP
3405int getttyname_harder(int fd, char **r) {
3406 int k;
3407 char *s;
3408
3409 if ((k = getttyname_malloc(fd, &s)) < 0)
3410 return k;
3411
3412 if (streq(s, "tty")) {
3413 free(s);
4d6d6518 3414 return get_ctty(0, NULL, r);
fc116c6a
LP
3415 }
3416
3417 *r = s;
3418 return 0;
3419}
3420
4d6d6518 3421int get_ctty_devnr(pid_t pid, dev_t *d) {
fc116c6a 3422 int k;
4d6d6518 3423 char line[LINE_MAX], *p, *fn;
fc116c6a
LP
3424 unsigned long ttynr;
3425 FILE *f;
3426
4d6d6518
LP
3427 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3428 return -ENOMEM;
3429
3430 f = fopen(fn, "re");
3431 free(fn);
3432 if (!f)
fc116c6a
LP
3433 return -errno;
3434
4d6d6518 3435 if (!fgets(line, sizeof(line), f)) {
35d50f55 3436 k = feof(f) ? -EIO : -errno;
fc116c6a
LP
3437 fclose(f);
3438 return k;
3439 }
3440
3441 fclose(f);
3442
4d6d6518
LP
3443 p = strrchr(line, ')');
3444 if (!p)
fc116c6a
LP
3445 return -EIO;
3446
3447 p++;
3448
3449 if (sscanf(p, " "
3450 "%*c " /* state */
3451 "%*d " /* ppid */
3452 "%*d " /* pgrp */
3453 "%*d " /* session */
3454 "%lu ", /* ttynr */
3455 &ttynr) != 1)
3456 return -EIO;
3457
3458 *d = (dev_t) ttynr;
3459 return 0;
3460}
3461
4d6d6518 3462int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
fc116c6a 3463 int k;
20c03b7b 3464 char fn[PATH_MAX], *s, *b, *p;
fc116c6a
LP
3465 dev_t devnr;
3466
3467 assert(r);
3468
4d6d6518
LP
3469 k = get_ctty_devnr(pid, &devnr);
3470 if (k < 0)
fc116c6a
LP
3471 return k;
3472
3473 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3474 char_array_0(fn);
3475
3476 if ((k = readlink_malloc(fn, &s)) < 0) {
3477
3478 if (k != -ENOENT)
3479 return k;
3480
46824d0e
LP
3481 /* This is an ugly hack */
3482 if (major(devnr) == 136) {
3483 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3484 return -ENOMEM;
3485
3486 *r = b;
3487 if (_devnr)
3488 *_devnr = devnr;
3489
3490 return 0;
3491 }
3492
fc116c6a
LP
3493 /* Probably something like the ptys which have no
3494 * symlink in /dev/char. Let's return something
3495 * vaguely useful. */
3496
3497 if (!(b = strdup(fn + 5)))
3498 return -ENOMEM;
3499
3500 *r = b;
46824d0e
LP
3501 if (_devnr)
3502 *_devnr = devnr;
3503
fc116c6a
LP
3504 return 0;
3505 }
3506
3507 if (startswith(s, "/dev/"))
3508 p = s + 5;
3509 else if (startswith(s, "../"))
3510 p = s + 3;
3511 else
3512 p = s;
3513
3514 b = strdup(p);
3515 free(s);
3516
3517 if (!b)
3518 return -ENOMEM;
3519
3520 *r = b;
46824d0e
LP
3521 if (_devnr)
3522 *_devnr = devnr;
3523
fc116c6a
LP
3524 return 0;
3525}
3526
ad293f5a 3527static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) {
8c6db833
LP
3528 DIR *d;
3529 int ret = 0;
3530
3531 assert(fd >= 0);
3532
3533 /* This returns the first error we run into, but nevertheless
3534 * tries to go on */
3535
3536 if (!(d = fdopendir(fd))) {
3537 close_nointr_nofail(fd);
4c633005
LP
3538
3539 return errno == ENOENT ? 0 : -errno;
8c6db833
LP
3540 }
3541
3542 for (;;) {
3543 struct dirent buf, *de;
ad293f5a 3544 bool is_dir, keep_around = false;
8c6db833
LP
3545 int r;
3546
3547 if ((r = readdir_r(d, &buf, &de)) != 0) {
3548 if (ret == 0)
3549 ret = -r;
3550 break;
3551 }
3552
3553 if (!de)
3554 break;
3555
3556 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3557 continue;
3558
3559 if (de->d_type == DT_UNKNOWN) {
3560 struct stat st;
3561
3562 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
4c633005 3563 if (ret == 0 && errno != ENOENT)
8c6db833
LP
3564 ret = -errno;
3565 continue;
3566 }
3567
ad293f5a 3568 if (honour_sticky)
8d53b453
LP
3569 keep_around =
3570 (st.st_uid == 0 || st.st_uid == getuid()) &&
3571 (st.st_mode & S_ISVTX);
ad293f5a 3572
8c6db833 3573 is_dir = S_ISDIR(st.st_mode);
ad293f5a
LP
3574
3575 } else {
3576 if (honour_sticky) {
3577 struct stat st;
3578
3579 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3580 if (ret == 0 && errno != ENOENT)
3581 ret = -errno;
3582 continue;
3583 }
3584
8d53b453
LP
3585 keep_around =
3586 (st.st_uid == 0 || st.st_uid == getuid()) &&
3587 (st.st_mode & S_ISVTX);
ad293f5a
LP
3588 }
3589
8c6db833 3590 is_dir = de->d_type == DT_DIR;
ad293f5a 3591 }
8c6db833
LP
3592
3593 if (is_dir) {
3594 int subdir_fd;
3595
3596 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
4c633005 3597 if (ret == 0 && errno != ENOENT)
8c6db833
LP
3598 ret = -errno;
3599 continue;
3600 }
3601
ad293f5a 3602 if ((r = rm_rf_children(subdir_fd, only_dirs, honour_sticky)) < 0) {
8c6db833
LP
3603 if (ret == 0)
3604 ret = r;
3605 }
3606
ad293f5a
LP
3607 if (!keep_around)
3608 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3609 if (ret == 0 && errno != ENOENT)
3610 ret = -errno;
3611 }
3612
3613 } else if (!only_dirs && !keep_around) {
8c6db833
LP
3614
3615 if (unlinkat(fd, de->d_name, 0) < 0) {
4c633005 3616 if (ret == 0 && errno != ENOENT)
8c6db833
LP
3617 ret = -errno;
3618 }
3619 }
3620 }
3621
3622 closedir(d);
3623
3624 return ret;
3625}
3626
ad293f5a 3627int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
8c6db833
LP
3628 int fd;
3629 int r;
3630
3631 assert(path);
3632
3633 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3634
3635 if (errno != ENOTDIR)
3636 return -errno;
3637
3638 if (delete_root && !only_dirs)
3639 if (unlink(path) < 0)
3640 return -errno;
3641
3642 return 0;
3643 }
3644
ad293f5a
LP
3645 r = rm_rf_children(fd, only_dirs, honour_sticky);
3646
3647 if (delete_root) {
3648
8d53b453 3649 if (honour_sticky && file_is_priv_sticky(path) > 0)
ad293f5a 3650 return r;
8c6db833 3651
e27796a0 3652 if (rmdir(path) < 0 && errno != ENOENT) {
8c6db833
LP
3653 if (r == 0)
3654 r = -errno;
3655 }
ad293f5a 3656 }
8c6db833
LP
3657
3658 return r;
3659}
3660
3661int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3662 assert(path);
3663
3664 /* Under the assumption that we are running privileged we
3665 * first change the access mode and only then hand out
3666 * ownership to avoid a window where access is too open. */
3667
8d53b453
LP
3668 if (mode != (mode_t) -1)
3669 if (chmod(path, mode) < 0)
3670 return -errno;
8c6db833 3671
8d53b453
LP
3672 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3673 if (chown(path, uid, gid) < 0)
3674 return -errno;
8c6db833
LP
3675
3676 return 0;
ef2f1067
LP
3677}
3678
f4b47811
LP
3679int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3680 assert(fd >= 0);
3681
3682 /* Under the assumption that we are running privileged we
3683 * first change the access mode and only then hand out
3684 * ownership to avoid a window where access is too open. */
3685
3686 if (fchmod(fd, mode) < 0)
3687 return -errno;
3688
3689 if (fchown(fd, uid, gid) < 0)
3690 return -errno;
3691
3692 return 0;
3693}
3694
82c121a4
LP
3695cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3696 cpu_set_t *r;
3697 unsigned n = 1024;
3698
3699 /* Allocates the cpuset in the right size */
3700
3701 for (;;) {
3702 if (!(r = CPU_ALLOC(n)))
3703 return NULL;
3704
3705 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3706 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3707
3708 if (ncpus)
3709 *ncpus = n;
3710
3711 return r;
3712 }
3713
3714 CPU_FREE(r);
3715
3716 if (errno != EINVAL)
3717 return NULL;
3718
3719 n *= 2;
3720 }
3721}
3722
67e5cc4f 3723void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
81beb750
LP
3724 char *s = NULL, *spaces = NULL, *e;
3725 int fd = -1, c;
3726 size_t emax, sl, left;
3727 struct iovec iovec[5];
3728 int n = 0;
9e58ff9c
LP
3729
3730 assert(format);
3731
3732 /* This independent of logging, as status messages are
3733 * optional and go exclusively to the console. */
3734
3735 if (vasprintf(&s, format, ap) < 0)
3736 goto finish;
3737
67e5cc4f 3738 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
81beb750 3739 if (fd < 0)
9e58ff9c
LP
3740 goto finish;
3741
67e5cc4f
LP
3742 if (ellipse) {
3743 c = fd_columns(fd);
3744 if (c <= 0)
3745 c = 80;
81beb750 3746
67e5cc4f
LP
3747 if (status) {
3748 sl = 2 + 6 + 1; /* " [" status "]" */
3749 emax = (size_t) c > sl ? c - sl - 1 : 0;
3750 } else
3751 emax = c - 1;
81beb750 3752
67e5cc4f
LP
3753 e = ellipsize(s, emax, 75);
3754 if (e) {
3755 free(s);
3756 s = e;
3757 }
81beb750
LP
3758 }
3759
3760 zero(iovec);
3761 IOVEC_SET_STRING(iovec[n++], s);
3762
67e5cc4f
LP
3763 if (ellipse) {
3764 sl = strlen(s);
3765 left = emax > sl ? emax - sl : 0;
3766 if (left > 0) {
3767 spaces = malloc(left);
3768 if (spaces) {
3769 memset(spaces, ' ', left);
3770 iovec[n].iov_base = spaces;
3771 iovec[n].iov_len = left;
3772 n++;
3773 }
81beb750
LP
3774 }
3775 }
3776
3777 if (status) {
3778 IOVEC_SET_STRING(iovec[n++], " [");
3779 IOVEC_SET_STRING(iovec[n++], status);
3780 IOVEC_SET_STRING(iovec[n++], "]\n");
3781 } else
3782 IOVEC_SET_STRING(iovec[n++], "\n");
3783
3784 writev(fd, iovec, n);
9e58ff9c
LP
3785
3786finish:
3787 free(s);
81beb750 3788 free(spaces);
9e58ff9c
LP
3789
3790 if (fd >= 0)
3791 close_nointr_nofail(fd);
3792}
3793
67e5cc4f 3794void status_printf(const char *status, bool ellipse, const char *format, ...) {
c846ff47
LP
3795 va_list ap;
3796
3797 assert(format);
3798
3799 va_start(ap, format);
67e5cc4f 3800 status_vprintf(status, ellipse, format, ap);
c846ff47
LP
3801 va_end(ap);
3802}
3803
3804void status_welcome(void) {
10aa7034
LP
3805 char *pretty_name = NULL, *ansi_color = NULL;
3806 const char *const_pretty = NULL, *const_color = NULL;
3807 int r;
c846ff47 3808
10aa7034
LP
3809 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3810 "PRETTY_NAME", &pretty_name,
3811 "ANSI_COLOR", &ansi_color,
3812 NULL)) < 0) {
c846ff47 3813
10aa7034
LP
3814 if (r != -ENOENT)
3815 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3816 }
c846ff47 3817
10aa7034
LP
3818 if (!pretty_name && !const_pretty)
3819 const_pretty = "Linux";
3820
3821 if (!ansi_color && !const_color)
3822 const_color = "1";
3823
81beb750 3824 status_printf(NULL,
67e5cc4f 3825 false,
81beb750 3826 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
10aa7034
LP
3827 const_color ? const_color : ansi_color,
3828 const_pretty ? const_pretty : pretty_name);
86a3475b
LP
3829
3830 free(ansi_color);
3831 free(pretty_name);
c846ff47
LP
3832}
3833
fab56fc5
LP
3834char *replace_env(const char *format, char **env) {
3835 enum {
3836 WORD,
c24eb49e 3837 CURLY,
fab56fc5
LP
3838 VARIABLE
3839 } state = WORD;
3840
3841 const char *e, *word = format;
3842 char *r = NULL, *k;
3843
3844 assert(format);
3845
3846 for (e = format; *e; e ++) {
3847
3848 switch (state) {
3849
3850 case WORD:
3851 if (*e == '$')
c24eb49e 3852 state = CURLY;
fab56fc5
LP
3853 break;
3854
c24eb49e
LP
3855 case CURLY:
3856 if (*e == '{') {
fab56fc5
LP
3857 if (!(k = strnappend(r, word, e-word-1)))
3858 goto fail;
3859
3860 free(r);
3861 r = k;
3862
3863 word = e-1;
3864 state = VARIABLE;
3865
3866 } else if (*e == '$') {
3867 if (!(k = strnappend(r, word, e-word)))
3868 goto fail;
3869
3870 free(r);
3871 r = k;
3872
3873 word = e+1;
3874 state = WORD;
3875 } else
3876 state = WORD;
3877 break;
3878
3879 case VARIABLE:
c24eb49e 3880 if (*e == '}') {
b95cf362 3881 const char *t;
fab56fc5 3882
b95cf362
LP
3883 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3884 t = "";
fab56fc5 3885
b95cf362
LP
3886 if (!(k = strappend(r, t)))
3887 goto fail;
fab56fc5 3888
b95cf362
LP
3889 free(r);
3890 r = k;
fab56fc5 3891
b95cf362 3892 word = e+1;
fab56fc5
LP
3893 state = WORD;
3894 }
3895 break;
3896 }
3897 }
3898
3899 if (!(k = strnappend(r, word, e-word)))
3900 goto fail;
3901
3902 free(r);
3903 return k;
3904
3905fail:
3906 free(r);
3907 return NULL;
3908}
3909
3910char **replace_env_argv(char **argv, char **env) {
3911 char **r, **i;
c24eb49e
LP
3912 unsigned k = 0, l = 0;
3913
3914 l = strv_length(argv);
fab56fc5 3915
c24eb49e 3916 if (!(r = new(char*, l+1)))
fab56fc5
LP
3917 return NULL;
3918
3919 STRV_FOREACH(i, argv) {
c24eb49e
LP
3920
3921 /* If $FOO appears as single word, replace it by the split up variable */
b95cf362
LP
3922 if ((*i)[0] == '$' && (*i)[1] != '{') {
3923 char *e;
3924 char **w, **m;
3925 unsigned q;
c24eb49e 3926
b95cf362 3927 if ((e = strv_env_get(env, *i+1))) {
c24eb49e
LP
3928
3929 if (!(m = strv_split_quoted(e))) {
3930 r[k] = NULL;
3931 strv_free(r);
3932 return NULL;
3933 }
b95cf362
LP
3934 } else
3935 m = NULL;
c24eb49e 3936
b95cf362
LP
3937 q = strv_length(m);
3938 l = l + q - 1;
c24eb49e 3939
b95cf362
LP
3940 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3941 r[k] = NULL;
3942 strv_free(r);
3943 strv_free(m);
3944 return NULL;
3945 }
c24eb49e 3946
b95cf362
LP
3947 r = w;
3948 if (m) {
c24eb49e
LP
3949 memcpy(r + k, m, q * sizeof(char*));
3950 free(m);
c24eb49e 3951 }
b95cf362
LP
3952
3953 k += q;
3954 continue;
c24eb49e
LP
3955 }
3956
3957 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
fab56fc5
LP
3958 if (!(r[k++] = replace_env(*i, env))) {
3959 strv_free(r);
3960 return NULL;
3961 }
3962 }
3963
3964 r[k] = NULL;
3965 return r;
3966}
3967
81beb750
LP
3968int fd_columns(int fd) {
3969 struct winsize ws;
3970 zero(ws);
3971
3972 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3973 return -errno;
3974
3975 if (ws.ws_col <= 0)
3976 return -EIO;
3977
3978 return ws.ws_col;
3979}
3980
72f59706 3981unsigned columns(void) {
fa776d8e
LP
3982 static __thread int parsed_columns = 0;
3983 const char *e;
3984
3bfc7184 3985 if (_likely_(parsed_columns > 0))
fa776d8e
LP
3986 return parsed_columns;
3987
81beb750
LP
3988 e = getenv("COLUMNS");
3989 if (e)
fa776d8e
LP
3990 parsed_columns = atoi(e);
3991
81beb750
LP
3992 if (parsed_columns <= 0)
3993 parsed_columns = fd_columns(STDOUT_FILENO);
fa776d8e
LP
3994
3995 if (parsed_columns <= 0)
3996 parsed_columns = 80;
3997
3998 return parsed_columns;
3999}
4000
8f2d43a0
LP
4001int fd_lines(int fd) {
4002 struct winsize ws;
4003 zero(ws);
4004
4005 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
4006 return -errno;
4007
4008 if (ws.ws_row <= 0)
4009 return -EIO;
4010
4011 return ws.ws_row;
4012}
4013
4014unsigned lines(void) {
4015 static __thread int parsed_lines = 0;
4016 const char *e;
4017
4018 if (_likely_(parsed_lines > 0))
4019 return parsed_lines;
4020
4021 e = getenv("LINES");
4022 if (e)
4023 parsed_lines = atoi(e);
4024
4025 if (parsed_lines <= 0)
4026 parsed_lines = fd_lines(STDOUT_FILENO);
4027
4028 if (parsed_lines <= 0)
4029 parsed_lines = 25;
4030
4031 return parsed_lines;
4032}
4033
b4f10a5e
LP
4034int running_in_chroot(void) {
4035 struct stat a, b;
4036
4037 zero(a);
4038 zero(b);
4039
4040 /* Only works as root */
4041
4042 if (stat("/proc/1/root", &a) < 0)
4043 return -errno;
4044
4045 if (stat("/", &b) < 0)
4046 return -errno;
4047
4048 return
4049 a.st_dev != b.st_dev ||
4050 a.st_ino != b.st_ino;
4051}
4052
72f59706
LP
4053char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
4054 size_t x;
8fe914ec
LP
4055 char *r;
4056
4057 assert(s);
4058 assert(percent <= 100);
72f59706 4059 assert(new_length >= 3);
8fe914ec 4060
72f59706
LP
4061 if (old_length <= 3 || old_length <= new_length)
4062 return strndup(s, old_length);
8fe914ec 4063
72f59706
LP
4064 r = new0(char, new_length+1);
4065 if (!r)
8fe914ec
LP
4066 return r;
4067
72f59706 4068 x = (new_length * percent) / 100;
8fe914ec 4069
72f59706
LP
4070 if (x > new_length - 3)
4071 x = new_length - 3;
8fe914ec
LP
4072
4073 memcpy(r, s, x);
4074 r[x] = '.';
4075 r[x+1] = '.';
4076 r[x+2] = '.';
4077 memcpy(r + x + 3,
72f59706
LP
4078 s + old_length - (new_length - x - 3),
4079 new_length - x - 3);
8fe914ec
LP
4080
4081 return r;
4082}
4083
72f59706
LP
4084char *ellipsize(const char *s, size_t length, unsigned percent) {
4085 return ellipsize_mem(s, strlen(s), length, percent);
4086}
4087
f6144808
LP
4088int touch(const char *path) {
4089 int fd;
4090
4091 assert(path);
4092
14f3c825 4093 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
f6144808
LP
4094 return -errno;
4095
4096 close_nointr_nofail(fd);
4097 return 0;
4098}
afea26ad 4099
97c4a07d 4100char *unquote(const char *s, const char* quotes) {
11ce3427
LP
4101 size_t l;
4102 assert(s);
4103
31ed59c5
LP
4104 l = strlen(s);
4105 if (l < 2)
11ce3427
LP
4106 return strdup(s);
4107
97c4a07d 4108 if (strchr(quotes, s[0]) && s[l-1] == s[0])
11ce3427
LP
4109 return strndup(s+1, l-2);
4110
4111 return strdup(s);
4112}
4113
5f7c426e
LP
4114char *normalize_env_assignment(const char *s) {
4115 char *name, *value, *p, *r;
4116
4117 p = strchr(s, '=');
4118
4119 if (!p) {
4120 if (!(r = strdup(s)))
4121 return NULL;
4122
4123 return strstrip(r);
4124 }
4125
4126 if (!(name = strndup(s, p - s)))
4127 return NULL;
4128
4129 if (!(p = strdup(p+1))) {
4130 free(name);
4131 return NULL;
4132 }
4133
4134 value = unquote(strstrip(p), QUOTES);
4135 free(p);
4136
4137 if (!value) {
5f7c426e
LP
4138 free(name);
4139 return NULL;
4140 }
4141
4142 if (asprintf(&r, "%s=%s", name, value) < 0)
4143 r = NULL;
4144
4145 free(value);
4146 free(name);
4147
4148 return r;
4149}
4150
8e12a6ae 4151int wait_for_terminate(pid_t pid, siginfo_t *status) {
1968a360
LP
4152 siginfo_t dummy;
4153
2e78aa99 4154 assert(pid >= 1);
1968a360
LP
4155
4156 if (!status)
4157 status = &dummy;
2e78aa99
LP
4158
4159 for (;;) {
8e12a6ae
LP
4160 zero(*status);
4161
4162 if (waitid(P_PID, pid, status, WEXITED) < 0) {
2e78aa99
LP
4163
4164 if (errno == EINTR)
4165 continue;
4166
4167 return -errno;
4168 }
4169
4170 return 0;
4171 }
4172}
4173
97c4a07d
LP
4174int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4175 int r;
4176 siginfo_t status;
4177
4178 assert(name);
4179 assert(pid > 1);
4180
4181 if ((r = wait_for_terminate(pid, &status)) < 0) {
4182 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4183 return r;
4184 }
4185
4186 if (status.si_code == CLD_EXITED) {
4187 if (status.si_status != 0) {
4188 log_warning("%s failed with error code %i.", name, status.si_status);
0a27cf3f 4189 return status.si_status;
97c4a07d
LP
4190 }
4191
4192 log_debug("%s succeeded.", name);
4193 return 0;
4194
4195 } else if (status.si_code == CLD_KILLED ||
4196 status.si_code == CLD_DUMPED) {
4197
4198 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4199 return -EPROTO;
4200 }
4201
4202 log_warning("%s failed due to unknown reason.", name);
4203 return -EPROTO;
4204
4205}
4206
6a39419f 4207_noreturn_ void freeze(void) {
720ce21d
LP
4208
4209 /* Make sure nobody waits for us on a socket anymore */
4210 close_all_fds(NULL, 0);
4211
c29597a1
LP
4212 sync();
4213
3c14d26c
LP
4214 for (;;)
4215 pause();
4216}
4217
00dc5d76
LP
4218bool null_or_empty(struct stat *st) {
4219 assert(st);
4220
4221 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4222 return true;
4223
c8f26f42 4224 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
00dc5d76
LP
4225 return true;
4226
4227 return false;
4228}
4229
83096483
LP
4230int null_or_empty_path(const char *fn) {
4231 struct stat st;
4232
4233 assert(fn);
4234
4235 if (stat(fn, &st) < 0)
4236 return -errno;
4237
4238 return null_or_empty(&st);
4239}
4240
a247755d 4241DIR *xopendirat(int fd, const char *name, int flags) {
c4731d11
LP
4242 int nfd;
4243 DIR *d;
4244
4245 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4246 return NULL;
4247
4248 if (!(d = fdopendir(nfd))) {
4249 close_nointr_nofail(nfd);
4250 return NULL;
4251 }
4252
4253 return d;
3b63d2d3
LP
4254}
4255
8a0867d6
LP
4256int signal_from_string_try_harder(const char *s) {
4257 int signo;
4258 assert(s);
4259
4260 if ((signo = signal_from_string(s)) <= 0)
4261 if (startswith(s, "SIG"))
4262 return signal_from_string(s+3);
4263
4264 return signo;
4265}
4266
10717a1a
LP
4267void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4268
4269 assert(f);
4270 assert(name);
4271 assert(t);
4272
4273 if (!dual_timestamp_is_set(t))
4274 return;
4275
4276 fprintf(f, "%s=%llu %llu\n",
4277 name,
4278 (unsigned long long) t->realtime,
4279 (unsigned long long) t->monotonic);
4280}
4281
799fd0fd 4282void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
10717a1a
LP
4283 unsigned long long a, b;
4284
10717a1a
LP
4285 assert(value);
4286 assert(t);
4287
4288 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4289 log_debug("Failed to parse finish timestamp value %s", value);
4290 else {
4291 t->realtime = a;
4292 t->monotonic = b;
4293 }
4294}
4295
e23a0ce8
LP
4296char *fstab_node_to_udev_node(const char *p) {
4297 char *dn, *t, *u;
4298 int r;
4299
4300 /* FIXME: to follow udev's logic 100% we need to leave valid
4301 * UTF8 chars unescaped */
4302
4303 if (startswith(p, "LABEL=")) {
4304
4305 if (!(u = unquote(p+6, "\"\'")))
4306 return NULL;
4307
4308 t = xescape(u, "/ ");
4309 free(u);
4310
4311 if (!t)
4312 return NULL;
4313
4314 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4315 free(t);
4316
4317 if (r < 0)
4318 return NULL;
4319
4320 return dn;
4321 }
4322
4323 if (startswith(p, "UUID=")) {
4324
4325 if (!(u = unquote(p+5, "\"\'")))
4326 return NULL;
4327
4328 t = xescape(u, "/ ");
4329 free(u);
4330
4331 if (!t)
4332 return NULL;
4333
0058d7b9 4334 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
e23a0ce8
LP
4335 free(t);
4336
4337 if (r < 0)
4338 return NULL;
4339
4340 return dn;
4341 }
4342
4343 return strdup(p);
4344}
4345
e9ddabc2
LP
4346void filter_environ(const char *prefix) {
4347 int i, j;
4348 assert(prefix);
4349
4350 if (!environ)
4351 return;
4352
4353 for (i = 0, j = 0; environ[i]; i++) {
4354
4355 if (startswith(environ[i], prefix))
4356 continue;
4357
4358 environ[j++] = environ[i];
4359 }
4360
4361 environ[j] = NULL;
4362}
4363
f212ac12
LP
4364bool tty_is_vc(const char *tty) {
4365 assert(tty);
4366
4367 if (startswith(tty, "/dev/"))
4368 tty += 5;
4369
98a28fef
LP
4370 return vtnr_from_tty(tty) >= 0;
4371}
4372
4373int vtnr_from_tty(const char *tty) {
4374 int i, r;
4375
4376 assert(tty);
4377
4378 if (startswith(tty, "/dev/"))
4379 tty += 5;
4380
4381 if (!startswith(tty, "tty") )
4382 return -EINVAL;
4383
4384 if (tty[3] < '0' || tty[3] > '9')
4385 return -EINVAL;
4386
4387 r = safe_atoi(tty+3, &i);
4388 if (r < 0)
4389 return r;
4390
4391 if (i < 0 || i > 63)
4392 return -EINVAL;
4393
4394 return i;
f212ac12
LP
4395}
4396
3043935f 4397bool tty_is_vc_resolve(const char *tty) {
3030ccd7 4398 char *active = NULL;
3043935f 4399 bool b;
3030ccd7 4400
e3aa71c3
LP
4401 assert(tty);
4402
4403 if (startswith(tty, "/dev/"))
4404 tty += 5;
4405
3043935f 4406 /* Resolve where /dev/console is pointing to */
3030ccd7
LP
4407 if (streq(tty, "console"))
4408 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
079a09fb
LP
4409 /* If multiple log outputs are configured the
4410 * last one is what /dev/console points to */
3043935f
LP
4411 tty = strrchr(active, ' ');
4412 if (tty)
079a09fb
LP
4413 tty++;
4414 else
4415 tty = active;
3030ccd7
LP
4416 }
4417
3043935f 4418 b = tty_is_vc(tty);
3030ccd7 4419 free(active);
e3aa71c3 4420
3043935f
LP
4421 return b;
4422}
4423
4424const char *default_term_for_tty(const char *tty) {
4425 assert(tty);
4426
4427 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt100";
e3aa71c3
LP
4428}
4429
87d2c1ff 4430bool dirent_is_file(const struct dirent *de) {
fb19a739
LP
4431 assert(de);
4432
4433 if (ignore_file(de->d_name))
4434 return false;
4435
4436 if (de->d_type != DT_REG &&
4437 de->d_type != DT_LNK &&
4438 de->d_type != DT_UNKNOWN)
4439 return false;
4440
4441 return true;
4442}
4443
87d2c1ff
LP
4444bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4445 assert(de);
4446
4447 if (!dirent_is_file(de))
4448 return false;
4449
4450 return endswith(de->d_name, suffix);
4451}
4452
83cc030f
LP
4453void execute_directory(const char *directory, DIR *d, char *argv[]) {
4454 DIR *_d = NULL;
4455 struct dirent *de;
4456 Hashmap *pids = NULL;
4457
4458 assert(directory);
4459
4460 /* Executes all binaries in a directory in parallel and waits
4461 * until all they all finished. */
4462
4463 if (!d) {
4464 if (!(_d = opendir(directory))) {
4465
4466 if (errno == ENOENT)
4467 return;
4468
4469 log_error("Failed to enumerate directory %s: %m", directory);
4470 return;
4471 }
4472
4473 d = _d;
4474 }
4475
4476 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4477 log_error("Failed to allocate set.");
4478 goto finish;
4479 }
4480
4481 while ((de = readdir(d))) {
4482 char *path;
4483 pid_t pid;
4484 int k;
4485
fb19a739 4486 if (!dirent_is_file(de))
83cc030f
LP
4487 continue;
4488
4489 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4490 log_error("Out of memory");
4491 continue;
4492 }
4493
4494 if ((pid = fork()) < 0) {
4495 log_error("Failed to fork: %m");
4496 free(path);
4497 continue;
4498 }
4499
4500 if (pid == 0) {
4501 char *_argv[2];
4502 /* Child */
4503
4504 if (!argv) {
4505 _argv[0] = path;
4506 _argv[1] = NULL;
4507 argv = _argv;
4508 } else
4509 if (!argv[0])
4510 argv[0] = path;
4511
4512 execv(path, argv);
4513
4514 log_error("Failed to execute %s: %m", path);
4515 _exit(EXIT_FAILURE);
4516 }
4517
4518 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4519
4520 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4521 log_error("Failed to add PID to set: %s", strerror(-k));
4522 free(path);
4523 }
4524 }
4525
4526 while (!hashmap_isempty(pids)) {
ec3f9b53 4527 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
83cc030f
LP
4528 siginfo_t si;
4529 char *path;
4530
4531 zero(si);
ec3f9b53 4532 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
83cc030f
LP
4533
4534 if (errno == EINTR)
4535 continue;
4536
4537 log_error("waitid() failed: %m");
4538 goto finish;
4539 }
4540
4541 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4542 if (!is_clean_exit(si.si_code, si.si_status)) {
4543 if (si.si_code == CLD_EXITED)
4544 log_error("%s exited with exit status %i.", path, si.si_status);
4545 else
4546 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4547 } else
4548 log_debug("%s exited successfully.", path);
4549
4550 free(path);
4551 }
4552 }
4553
4554finish:
4555 if (_d)
4556 closedir(_d);
4557
4558 if (pids)
4559 hashmap_free_free(pids);
4560}
4561
430c18ed
LP
4562int kill_and_sigcont(pid_t pid, int sig) {
4563 int r;
4564
4565 r = kill(pid, sig) < 0 ? -errno : 0;
4566
4567 if (r >= 0)
4568 kill(pid, SIGCONT);
4569
4570 return r;
4571}
4572
05feefe0
LP
4573bool nulstr_contains(const char*nulstr, const char *needle) {
4574 const char *i;
4575
4576 if (!nulstr)
4577 return false;
4578
4579 NULSTR_FOREACH(i, nulstr)
4580 if (streq(i, needle))
4581 return true;
4582
4583 return false;
4584}
4585
6faa1114 4586bool plymouth_running(void) {
9408a2d2 4587 return access("/run/plymouth/pid", F_OK) >= 0;
6faa1114
LP
4588}
4589
7c3b203c
LP
4590void parse_syslog_priority(char **p, int *priority) {
4591 int a = 0, b = 0, c = 0;
4592 int k;
4593
4594 assert(p);
4595 assert(*p);
4596 assert(priority);
4597
4598 if ((*p)[0] != '<')
4599 return;
4600
4601 if (!strchr(*p, '>'))
4602 return;
4603
4604 if ((*p)[2] == '>') {
4605 c = undecchar((*p)[1]);
4606 k = 3;
4607 } else if ((*p)[3] == '>') {
4608 b = undecchar((*p)[1]);
4609 c = undecchar((*p)[2]);
4610 k = 4;
4611 } else if ((*p)[4] == '>') {
4612 a = undecchar((*p)[1]);
4613 b = undecchar((*p)[2]);
4614 c = undecchar((*p)[3]);
4615 k = 5;
4616 } else
4617 return;
4618
4619 if (a < 0 || b < 0 || c < 0)
4620 return;
4621
4622 *priority = a*100+b*10+c;
4623 *p += k;
4624}
4625
87d2c1ff
LP
4626void skip_syslog_pid(char **buf) {
4627 char *p;
4628
4629 assert(buf);
4630 assert(*buf);
4631
4632 p = *buf;
4633
4634 if (*p != '[')
4635 return;
4636
4637 p++;
4638 p += strspn(p, "0123456789");
4639
4640 if (*p != ']')
4641 return;
4642
4643 p++;
4644
4645 *buf = p;
4646}
4647
4648void skip_syslog_date(char **buf) {
4649 enum {
4650 LETTER,
4651 SPACE,
4652 NUMBER,
4653 SPACE_OR_NUMBER,
4654 COLON
4655 } sequence[] = {
4656 LETTER, LETTER, LETTER,
4657 SPACE,
4658 SPACE_OR_NUMBER, NUMBER,
4659 SPACE,
4660 SPACE_OR_NUMBER, NUMBER,
4661 COLON,
4662 SPACE_OR_NUMBER, NUMBER,
4663 COLON,
4664 SPACE_OR_NUMBER, NUMBER,
4665 SPACE
4666 };
4667
4668 char *p;
4669 unsigned i;
4670
4671 assert(buf);
4672 assert(*buf);
4673
4674 p = *buf;
4675
4676 for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
4677
4678 if (!*p)
4679 return;
4680
4681 switch (sequence[i]) {
4682
4683 case SPACE:
4684 if (*p != ' ')
4685 return;
4686 break;
4687
4688 case SPACE_OR_NUMBER:
4689 if (*p == ' ')
4690 break;
4691
4692 /* fall through */
4693
4694 case NUMBER:
4695 if (*p < '0' || *p > '9')
4696 return;
4697
4698 break;
4699
4700 case LETTER:
4701 if (!(*p >= 'A' && *p <= 'Z') &&
4702 !(*p >= 'a' && *p <= 'z'))
4703 return;
4704
4705 break;
4706
4707 case COLON:
4708 if (*p != ':')
4709 return;
4710 break;
4711
4712 }
4713 }
4714
4715 *buf = p;
4716}
4717
ac123445
LP
4718int have_effective_cap(int value) {
4719 cap_t cap;
4720 cap_flag_value_t fv;
4721 int r;
4722
4723 if (!(cap = cap_get_proc()))
4724 return -errno;
4725
4726 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4727 r = -errno;
4728 else
4729 r = fv == CAP_SET;
4730
4731 cap_free(cap);
4732 return r;
4733}
4734
9beb3f4d
LP
4735char* strshorten(char *s, size_t l) {
4736 assert(s);
4737
4738 if (l < strlen(s))
4739 s[l] = 0;
4740
4741 return s;
4742}
4743
4744static bool hostname_valid_char(char c) {
4745 return
4746 (c >= 'a' && c <= 'z') ||
4747 (c >= 'A' && c <= 'Z') ||
4748 (c >= '0' && c <= '9') ||
4749 c == '-' ||
4750 c == '_' ||
4751 c == '.';
4752}
4753
4754bool hostname_is_valid(const char *s) {
4755 const char *p;
4756
4757 if (isempty(s))
4758 return false;
4759
4760 for (p = s; *p; p++)
4761 if (!hostname_valid_char(*p))
4762 return false;
4763
4764 if (p-s > HOST_NAME_MAX)
4765 return false;
4766
4767 return true;
4768}
4769
4770char* hostname_cleanup(char *s) {
4771 char *p, *d;
4772
4773 for (p = s, d = s; *p; p++)
4774 if ((*p >= 'a' && *p <= 'z') ||
4775 (*p >= 'A' && *p <= 'Z') ||
4776 (*p >= '0' && *p <= '9') ||
4777 *p == '-' ||
4778 *p == '_' ||
4779 *p == '.')
4780 *(d++) = *p;
4781
4782 *d = 0;
4783
4784 strshorten(s, HOST_NAME_MAX);
4785 return s;
4786}
4787
1325aa42
LP
4788int pipe_eof(int fd) {
4789 struct pollfd pollfd;
4790 int r;
4791
4792 zero(pollfd);
4793 pollfd.fd = fd;
4794 pollfd.events = POLLIN|POLLHUP;
4795
4796 r = poll(&pollfd, 1, 0);
4797 if (r < 0)
4798 return -errno;
4799
4800 if (r == 0)
4801 return 0;
4802
4803 return pollfd.revents & POLLHUP;
4804}
4805
8f2d43a0 4806int fd_wait_for_event(int fd, int event, usec_t t) {
df50185b
LP
4807 struct pollfd pollfd;
4808 int r;
4809
4810 zero(pollfd);
4811 pollfd.fd = fd;
4812 pollfd.events = event;
4813
8f2d43a0 4814 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
df50185b
LP
4815 if (r < 0)
4816 return -errno;
4817
4818 if (r == 0)
4819 return 0;
4820
4821 return pollfd.revents;
4822}
4823
5a3ab509
LP
4824int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4825 FILE *f;
4826 char *t;
4827 const char *fn;
4828 size_t k;
4829 int fd;
4830
4831 assert(path);
4832 assert(_f);
4833 assert(_temp_path);
4834
4835 t = new(char, strlen(path) + 1 + 6 + 1);
4836 if (!t)
4837 return -ENOMEM;
4838
4839 fn = file_name_from_path(path);
4840 k = fn-path;
4841 memcpy(t, path, k);
4842 t[k] = '.';
4843 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4844
4845 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4846 if (fd < 0) {
4847 free(t);
4848 return -errno;
4849 }
4850
4851 f = fdopen(fd, "we");
4852 if (!f) {
4853 unlink(t);
4854 free(t);
4855 return -errno;
4856 }
4857
4858 *_f = f;
4859 *_temp_path = t;
4860
4861 return 0;
4862}
4863
6ea832a2 4864int terminal_vhangup_fd(int fd) {
5a3ab509
LP
4865 assert(fd >= 0);
4866
6ea832a2
LP
4867 if (ioctl(fd, TIOCVHANGUP) < 0)
4868 return -errno;
4869
4870 return 0;
4871}
4872
4873int terminal_vhangup(const char *name) {
4874 int fd, r;
4875
4876 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4877 if (fd < 0)
4878 return fd;
4879
4880 r = terminal_vhangup_fd(fd);
4881 close_nointr_nofail(fd);
4882
4883 return r;
4884}
4885
4886int vt_disallocate(const char *name) {
4887 int fd, r;
4888 unsigned u;
6ea832a2
LP
4889
4890 /* Deallocate the VT if possible. If not possible
4891 * (i.e. because it is the active one), at least clear it
4892 * entirely (including the scrollback buffer) */
4893
b83bc4e9
LP
4894 if (!startswith(name, "/dev/"))
4895 return -EINVAL;
4896
4897 if (!tty_is_vc(name)) {
4898 /* So this is not a VT. I guess we cannot deallocate
4899 * it then. But let's at least clear the screen */
4900
4901 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4902 if (fd < 0)
4903 return fd;
4904
8585357a
LP
4905 loop_write(fd,
4906 "\033[r" /* clear scrolling region */
4907 "\033[H" /* move home */
4908 "\033[2J", /* clear screen */
4909 10, false);
b83bc4e9
LP
4910 close_nointr_nofail(fd);
4911
4912 return 0;
4913 }
6ea832a2
LP
4914
4915 if (!startswith(name, "/dev/tty"))
4916 return -EINVAL;
4917
4918 r = safe_atou(name+8, &u);
4919 if (r < 0)
4920 return r;
4921
4922 if (u <= 0)
b83bc4e9 4923 return -EINVAL;
6ea832a2 4924
b83bc4e9 4925 /* Try to deallocate */
6ea832a2
LP
4926 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4927 if (fd < 0)
4928 return fd;
4929
4930 r = ioctl(fd, VT_DISALLOCATE, u);
b83bc4e9 4931 close_nointr_nofail(fd);
6ea832a2 4932
b83bc4e9
LP
4933 if (r >= 0)
4934 return 0;
6ea832a2 4935
b83bc4e9 4936 if (errno != EBUSY)
6ea832a2 4937 return -errno;
6ea832a2 4938
b83bc4e9
LP
4939 /* Couldn't deallocate, so let's clear it fully with
4940 * scrollback */
4941 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
6ea832a2 4942 if (fd < 0)
b83bc4e9 4943 return fd;
6ea832a2 4944
8585357a
LP
4945 loop_write(fd,
4946 "\033[r" /* clear scrolling region */
4947 "\033[H" /* move home */
4948 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4949 10, false);
b83bc4e9 4950 close_nointr_nofail(fd);
6ea832a2 4951
b83bc4e9 4952 return 0;
6ea832a2
LP
4953}
4954
db1413d7
KS
4955static int files_add(Hashmap *h, const char *path, const char *suffix) {
4956 DIR *dir;
f782b8d0 4957 struct dirent buffer, *de;
db1413d7
KS
4958 int r = 0;
4959
4960 dir = opendir(path);
4961 if (!dir) {
4962 if (errno == ENOENT)
4963 return 0;
4964 return -errno;
4965 }
4966
f782b8d0
LP
4967 for (;;) {
4968 int k;
223a3558 4969 char *p, *f;
f782b8d0
LP
4970
4971 k = readdir_r(dir, &buffer, &de);
4972 if (k != 0) {
4973 r = -k;
4974 goto finish;
4975 }
4976
4977 if (!de)
4978 break;
db1413d7 4979
87d2c1ff 4980 if (!dirent_is_file_with_suffix(de, suffix))
db1413d7
KS
4981 continue;
4982
223a3558 4983 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
db1413d7
KS
4984 r = -ENOMEM;
4985 goto finish;
4986 }
4987
223a3558
KS
4988 f = canonicalize_file_name(p);
4989 if (!f) {
4990 log_error("Failed to canonicalize file name '%s': %m", p);
4991 free(p);
4992 continue;
4993 }
4994 free(p);
4995
db1413d7 4996 log_debug("found: %s\n", f);
f782b8d0 4997 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
db1413d7
KS
4998 free(f);
4999 }
5000
5001finish:
5002 closedir(dir);
5003 return r;
5004}
5005
5006static int base_cmp(const void *a, const void *b) {
5007 const char *s1, *s2;
5008
5009 s1 = *(char * const *)a;
5010 s2 = *(char * const *)b;
5011 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
5012}
5013
44143309 5014int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
223a3558
KS
5015 Hashmap *fh = NULL;
5016 char **dirs = NULL;
db1413d7 5017 char **files = NULL;
223a3558 5018 char **p;
db1413d7 5019 va_list ap;
44143309 5020 int r = 0;
db1413d7 5021
223a3558
KS
5022 va_start(ap, dir);
5023 dirs = strv_new_ap(dir, ap);
5024 va_end(ap);
5025 if (!dirs) {
5026 r = -ENOMEM;
5027 goto finish;
5028 }
5029 if (!strv_path_canonicalize(dirs)) {
5030 r = -ENOMEM;
5031 goto finish;
5032 }
5033 if (!strv_uniq(dirs)) {
5034 r = -ENOMEM;
5035 goto finish;
5036 }
5037
db1413d7
KS
5038 fh = hashmap_new(string_hash_func, string_compare_func);
5039 if (!fh) {
44143309 5040 r = -ENOMEM;
db1413d7
KS
5041 goto finish;
5042 }
5043
223a3558
KS
5044 STRV_FOREACH(p, dirs) {
5045 if (files_add(fh, *p, suffix) < 0) {
db1413d7 5046 log_error("Failed to search for files.");
44143309 5047 r = -EINVAL;
db1413d7
KS
5048 goto finish;
5049 }
db1413d7 5050 }
db1413d7
KS
5051
5052 files = hashmap_get_strv(fh);
5053 if (files == NULL) {
5054 log_error("Failed to compose list of files.");
44143309 5055 r = -ENOMEM;
db1413d7
KS
5056 goto finish;
5057 }
5058
5059 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
8d0e38a2 5060
db1413d7 5061finish:
223a3558 5062 strv_free(dirs);
db1413d7 5063 hashmap_free(fh);
44143309
KS
5064 *strv = files;
5065 return r;
db1413d7 5066}
7948c4df 5067
2076cf88 5068int hwclock_is_localtime(void) {
7948c4df 5069 FILE *f;
7948c4df
KS
5070 bool local = false;
5071
5072 /*
5073 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
5074 * # /etc/adjtime
2076cf88 5075 * 0.0 0 0
7948c4df
KS
5076 * 0
5077 * UTC
5078 */
5079 f = fopen("/etc/adjtime", "re");
5080 if (f) {
2076cf88
LP
5081 char line[LINE_MAX];
5082 bool b;
5083
5084 b = fgets(line, sizeof(line), f) &&
5085 fgets(line, sizeof(line), f) &&
5086 fgets(line, sizeof(line), f);
5087
7948c4df 5088 fclose(f);
2076cf88
LP
5089
5090 if (!b)
5091 return -EIO;
5092
5093
5094 truncate_nl(line);
5095 local = streq(line, "LOCAL");
5096
5097 } else if (errno != -ENOENT)
5098 return -errno;
5099
7948c4df
KS
5100 return local;
5101}
5102
ff4daf5a 5103int hwclock_apply_localtime_delta(int *min) {
7948c4df 5104 const struct timeval *tv_null = NULL;
2076cf88 5105 struct timespec ts;
7948c4df
KS
5106 struct tm *tm;
5107 int minuteswest;
5108 struct timezone tz;
5109
2076cf88
LP
5110 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
5111 assert_se(tm = localtime(&ts.tv_sec));
7948c4df
KS
5112 minuteswest = tm->tm_gmtoff / 60;
5113
5114 tz.tz_minuteswest = -minuteswest;
5115 tz.tz_dsttime = 0; /* DST_NONE*/
5116
5117 /*
5118 * If the hardware clock does not run in UTC, but in local time:
5119 * The very first time we set the kernel's timezone, it will warp
5120 * the clock so that it runs in UTC instead of local time.
5121 */
5122 if (settimeofday(tv_null, &tz) < 0)
5123 return -errno;
ff4daf5a
KS
5124 if (min)
5125 *min = minuteswest;
5126 return 0;
2076cf88
LP
5127}
5128
5129int hwclock_reset_localtime_delta(void) {
5130 const struct timeval *tv_null = NULL;
5131 struct timezone tz;
5132
5133 tz.tz_minuteswest = 0;
5134 tz.tz_dsttime = 0; /* DST_NONE*/
5135
5136 if (settimeofday(tv_null, &tz) < 0)
5137 return -errno;
5138
5139 return 0;
7948c4df
KS
5140}
5141
51122dc9
LP
5142int rtc_open(int flags) {
5143 int fd;
5144 DIR *d;
5145
7c697168
LP
5146 /* First, we try to make use of the /dev/rtc symlink. If that
5147 * doesn't exist, we open the first RTC which has hctosys=1
5148 * set. If we don't find any we just take the first RTC that
5149 * exists at all. */
5150
5151 fd = open("/dev/rtc", flags);
5152 if (fd >= 0)
5153 return fd;
51122dc9
LP
5154
5155 d = opendir("/sys/class/rtc");
5156 if (!d)
5157 goto fallback;
5158
5159 for (;;) {
5160 char *p, *v;
5161 struct dirent buf, *de;
5162 int r;
5163
5164 r = readdir_r(d, &buf, &de);
5165 if (r != 0)
5166 goto fallback;
5167
5168 if (!de)
5169 goto fallback;
5170
5171 if (ignore_file(de->d_name))
5172 continue;
5173
5174 p = join("/sys/class/rtc/", de->d_name, "/hctosys", NULL);
5175 if (!p) {
5176 closedir(d);
5177 return -ENOMEM;
5178 }
5179
5180 r = read_one_line_file(p, &v);
5181 free(p);
5182
5183 if (r < 0)
5184 continue;
5185
5186 r = parse_boolean(v);
5187 free(v);
5188
5189 if (r <= 0)
5190 continue;
5191
5192 p = strappend("/dev/", de->d_name);
5193 fd = open(p, flags);
5194 free(p);
5195
5196 if (fd >= 0) {
5197 closedir(d);
5198 return fd;
5199 }
5200 }
5201
5202fallback:
5203 if (d)
5204 closedir(d);
5205
5206 fd = open("/dev/rtc0", flags);
5207 if (fd < 0)
5208 return -errno;
5209
5210 return fd;
5211}
5212
7948c4df
KS
5213int hwclock_get_time(struct tm *tm) {
5214 int fd;
5215 int err = 0;
5216
2076cf88
LP
5217 assert(tm);
5218
51122dc9 5219 fd = rtc_open(O_RDONLY|O_CLOEXEC);
7948c4df
KS
5220 if (fd < 0)
5221 return -errno;
2076cf88
LP
5222
5223 /* This leaves the timezone fields of struct tm
5224 * uninitialized! */
7948c4df
KS
5225 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5226 err = -errno;
2076cf88
LP
5227
5228 /* We don't now daylight saving, so we reset this in order not
5229 * to confused mktime(). */
5230 tm->tm_isdst = -1;
5231
5232 close_nointr_nofail(fd);
7948c4df
KS
5233
5234 return err;
5235}
5236
5237int hwclock_set_time(const struct tm *tm) {
5238 int fd;
5239 int err = 0;
5240
2076cf88
LP
5241 assert(tm);
5242
51122dc9 5243 fd = rtc_open(O_RDONLY|O_CLOEXEC);
7948c4df
KS
5244 if (fd < 0)
5245 return -errno;
2076cf88 5246
7948c4df
KS
5247 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5248 err = -errno;
2076cf88
LP
5249
5250 close_nointr_nofail(fd);
7948c4df
KS
5251
5252 return err;
5253}
f41607a6 5254
34ca941c
LP
5255int copy_file(const char *from, const char *to) {
5256 int r, fdf, fdt;
5257
5258 assert(from);
5259 assert(to);
5260
5261 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5262 if (fdf < 0)
5263 return -errno;
5264
5265 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5266 if (fdt < 0) {
5267 close_nointr_nofail(fdf);
5268 return -errno;
5269 }
5270
5271 for (;;) {
5272 char buf[PIPE_BUF];
5273 ssize_t n, k;
5274
5275 n = read(fdf, buf, sizeof(buf));
5276 if (n < 0) {
5277 r = -errno;
5278
5279 close_nointr_nofail(fdf);
5280 close_nointr(fdt);
5281 unlink(to);
5282
5283 return r;
5284 }
5285
5286 if (n == 0)
5287 break;
5288
5289 errno = 0;
5290 k = loop_write(fdt, buf, n, false);
5291 if (n != k) {
5292 r = k < 0 ? k : (errno ? -errno : -EIO);
5293
5294 close_nointr_nofail(fdf);
5295 close_nointr(fdt);
5296
5297 unlink(to);
5298 return r;
5299 }
5300 }
5301
5302 close_nointr_nofail(fdf);
5303 r = close_nointr(fdt);
5304
5305 if (r < 0) {
5306 unlink(to);
5307 return r;
5308 }
5309
5310 return 0;
5311}
5312
5313int symlink_or_copy(const char *from, const char *to) {
5314 char *pf = NULL, *pt = NULL;
5315 struct stat a, b;
5316 int r;
5317
5318 assert(from);
5319 assert(to);
5320
5321 if (parent_of_path(from, &pf) < 0 ||
5322 parent_of_path(to, &pt) < 0) {
5323 r = -ENOMEM;
5324 goto finish;
5325 }
5326
5327 if (stat(pf, &a) < 0 ||
5328 stat(pt, &b) < 0) {
5329 r = -errno;
5330 goto finish;
5331 }
5332
5333 if (a.st_dev != b.st_dev) {
5334 free(pf);
5335 free(pt);
5336
5337 return copy_file(from, to);
5338 }
5339
5340 if (symlink(from, to) < 0) {
5341 r = -errno;
5342 goto finish;
5343 }
5344
5345 r = 0;
5346
5347finish:
5348 free(pf);
5349 free(pt);
5350
5351 return r;
5352}
5353
5354int symlink_or_copy_atomic(const char *from, const char *to) {
5355 char *t, *x;
5356 const char *fn;
5357 size_t k;
5358 unsigned long long ull;
5359 unsigned i;
5360 int r;
5361
5362 assert(from);
5363 assert(to);
5364
5365 t = new(char, strlen(to) + 1 + 16 + 1);
5366 if (!t)
5367 return -ENOMEM;
5368
5369 fn = file_name_from_path(to);
5370 k = fn-to;
5371 memcpy(t, to, k);
5372 t[k] = '.';
5373 x = stpcpy(t+k+1, fn);
5374
5375 ull = random_ull();
5376 for (i = 0; i < 16; i++) {
5377 *(x++) = hexchar(ull & 0xF);
5378 ull >>= 4;
5379 }
5380
5381 *x = 0;
5382
5383 r = symlink_or_copy(from, t);
5384 if (r < 0) {
5385 unlink(t);
5386 free(t);
5387 return r;
5388 }
5389
5390 if (rename(t, to) < 0) {
5391 r = -errno;
5392 unlink(t);
5393 free(t);
5394 return r;
5395 }
5396
5397 free(t);
5398 return r;
5399}
5400
98a28fef 5401int audit_session_from_pid(pid_t pid, uint32_t *id) {
87d2c1ff 5402 char *s;
98a28fef
LP
5403 uint32_t u;
5404 int r;
5405
98a28fef
LP
5406 assert(id);
5407
5408 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5409 return -ENOENT;
5410
87d2c1ff
LP
5411 if (pid == 0)
5412 r = read_one_line_file("/proc/self/sessionid", &s);
5413 else {
5414 char *p;
5415
5416 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5417 return -ENOMEM;
5418
5419 r = read_one_line_file(p, &s);
5420 free(p);
5421 }
98a28fef 5422
98a28fef
LP
5423 if (r < 0)
5424 return r;
5425
5426 r = safe_atou32(s, &u);
5427 free(s);
5428
5429 if (r < 0)
5430 return r;
5431
5432 if (u == (uint32_t) -1 || u <= 0)
5433 return -ENOENT;
5434
5435 *id = u;
5436 return 0;
5437}
5438
87d2c1ff
LP
5439int audit_loginuid_from_pid(pid_t pid, uid_t *uid) {
5440 char *s;
5441 uid_t u;
5442 int r;
5443
5444 assert(uid);
5445
5446 /* Only use audit login uid if we are executed with sufficient
5447 * capabilities so that pam_loginuid could do its job. If we
5448 * are lacking the CAP_AUDIT_CONTROL capabality we most likely
5449 * are being run in a container and /proc/self/loginuid is
5450 * useless since it probably contains a uid of the host
5451 * system. */
5452
5453 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5454 return -ENOENT;
5455
5456 if (pid == 0)
5457 r = read_one_line_file("/proc/self/loginuid", &s);
5458 else {
5459 char *p;
5460
5461 if (asprintf(&p, "/proc/%lu/loginuid", (unsigned long) pid) < 0)
5462 return -ENOMEM;
5463
5464 r = read_one_line_file(p, &s);
5465 free(p);
5466 }
5467
5468 if (r < 0)
5469 return r;
5470
5471 r = parse_uid(s, &u);
5472 free(s);
5473
5474 if (r < 0)
5475 return r;
5476
5477 if (u == (uid_t) -1)
5478 return -ENOENT;
5479
5480 *uid = (uid_t) u;
5481 return 0;
5482}
5483
4d6d6518
LP
5484bool display_is_local(const char *display) {
5485 assert(display);
5486
5487 return
5488 display[0] == ':' &&
5489 display[1] >= '0' &&
5490 display[1] <= '9';
5491}
5492
5493int socket_from_display(const char *display, char **path) {
5494 size_t k;
5495 char *f, *c;
5496
5497 assert(display);
5498 assert(path);
5499
5500 if (!display_is_local(display))
5501 return -EINVAL;
5502
5503 k = strspn(display+1, "0123456789");
5504
5505 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5506 if (!f)
5507 return -ENOMEM;
5508
5509 c = stpcpy(f, "/tmp/.X11-unix/X");
5510 memcpy(c, display+1, k);
5511 c[k] = 0;
5512
5513 *path = f;
5514
5515 return 0;
5516}
5517
1cccf435
MV
5518int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5519 struct passwd *p;
ddd88763 5520 uid_t u;
1cccf435
MV
5521
5522 assert(username);
5523 assert(*username);
1cccf435
MV
5524
5525 /* We enforce some special rules for uid=0: in order to avoid
5526 * NSS lookups for root we hardcode its data. */
5527
5528 if (streq(*username, "root") || streq(*username, "0")) {
5529 *username = "root";
4b67834e
LP
5530
5531 if (uid)
5532 *uid = 0;
5533
5534 if (gid)
5535 *gid = 0;
5536
5537 if (home)
5538 *home = "/root";
1cccf435
MV
5539 return 0;
5540 }
5541
ddd88763 5542 if (parse_uid(*username, &u) >= 0) {
1cccf435 5543 errno = 0;
ddd88763 5544 p = getpwuid(u);
1cccf435
MV
5545
5546 /* If there are multiple users with the same id, make
5547 * sure to leave $USER to the configured value instead
5548 * of the first occurrence in the database. However if
5549 * the uid was configured by a numeric uid, then let's
5550 * pick the real username from /etc/passwd. */
5551 if (p)
5552 *username = p->pw_name;
5553 } else {
5554 errno = 0;
5555 p = getpwnam(*username);
5556 }
5557
5558 if (!p)
5559 return errno != 0 ? -errno : -ESRCH;
5560
4b67834e
LP
5561 if (uid)
5562 *uid = p->pw_uid;
5563
5564 if (gid)
5565 *gid = p->pw_gid;
5566
5567 if (home)
5568 *home = p->pw_dir;
5569
5570 return 0;
5571}
5572
5573int get_group_creds(const char **groupname, gid_t *gid) {
5574 struct group *g;
5575 gid_t id;
5576
5577 assert(groupname);
5578
5579 /* We enforce some special rules for gid=0: in order to avoid
5580 * NSS lookups for root we hardcode its data. */
5581
5582 if (streq(*groupname, "root") || streq(*groupname, "0")) {
5583 *groupname = "root";
5584
5585 if (gid)
5586 *gid = 0;
5587
5588 return 0;
5589 }
5590
5591 if (parse_gid(*groupname, &id) >= 0) {
5592 errno = 0;
5593 g = getgrgid(id);
5594
5595 if (g)
5596 *groupname = g->gr_name;
5597 } else {
5598 errno = 0;
5599 g = getgrnam(*groupname);
5600 }
5601
5602 if (!g)
5603 return errno != 0 ? -errno : -ESRCH;
5604
5605 if (gid)
5606 *gid = g->gr_gid;
5607
1cccf435
MV
5608 return 0;
5609}
5610
8092a428
LP
5611int glob_exists(const char *path) {
5612 glob_t g;
5613 int r, k;
5614
5615 assert(path);
5616
5617 zero(g);
5618 errno = 0;
5619 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5620
5621 if (k == GLOB_NOMATCH)
5622 r = 0;
5623 else if (k == GLOB_NOSPACE)
5624 r = -ENOMEM;
5625 else if (k == 0)
5626 r = !strv_isempty(g.gl_pathv);
5627 else
5628 r = errno ? -errno : -EIO;
5629
5630 globfree(&g);
5631
5632 return r;
5633}
5634
83096483
LP
5635int dirent_ensure_type(DIR *d, struct dirent *de) {
5636 struct stat st;
5637
5638 assert(d);
5639 assert(de);
5640
5641 if (de->d_type != DT_UNKNOWN)
5642 return 0;
5643
5644 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5645 return -errno;
5646
5647 de->d_type =
5648 S_ISREG(st.st_mode) ? DT_REG :
5649 S_ISDIR(st.st_mode) ? DT_DIR :
5650 S_ISLNK(st.st_mode) ? DT_LNK :
5651 S_ISFIFO(st.st_mode) ? DT_FIFO :
5652 S_ISSOCK(st.st_mode) ? DT_SOCK :
5653 S_ISCHR(st.st_mode) ? DT_CHR :
5654 S_ISBLK(st.st_mode) ? DT_BLK :
5655 DT_UNKNOWN;
5656
5657 return 0;
5658}
5659
5660int in_search_path(const char *path, char **search) {
5661 char **i, *parent;
5662 int r;
5663
5664 r = parent_of_path(path, &parent);
5665 if (r < 0)
5666 return r;
5667
5668 r = 0;
5669
5670 STRV_FOREACH(i, search) {
5671 if (path_equal(parent, *i)) {
5672 r = 1;
5673 break;
5674 }
5675 }
5676
5677 free(parent);
5678
5679 return r;
5680}
5681
034a2a52
LP
5682int get_files_in_directory(const char *path, char ***list) {
5683 DIR *d;
5684 int r = 0;
5685 unsigned n = 0;
5686 char **l = NULL;
5687
5688 assert(path);
d60ef526
LP
5689
5690 /* Returns all files in a directory in *list, and the number
5691 * of files as return value. If list is NULL returns only the
5692 * number */
034a2a52
LP
5693
5694 d = opendir(path);
8ea913b2
LP
5695 if (!d)
5696 return -errno;
5697
034a2a52
LP
5698 for (;;) {
5699 struct dirent buffer, *de;
5700 int k;
5701
5702 k = readdir_r(d, &buffer, &de);
5703 if (k != 0) {
5704 r = -k;
5705 goto finish;
5706 }
5707
5708 if (!de)
5709 break;
5710
5711 dirent_ensure_type(d, de);
5712
5713 if (!dirent_is_file(de))
5714 continue;
5715
d60ef526
LP
5716 if (list) {
5717 if ((unsigned) r >= n) {
5718 char **t;
034a2a52 5719
d60ef526
LP
5720 n = MAX(16, 2*r);
5721 t = realloc(l, sizeof(char*) * n);
5722 if (!t) {
5723 r = -ENOMEM;
5724 goto finish;
5725 }
034a2a52 5726
d60ef526
LP
5727 l = t;
5728 }
034a2a52 5729
d60ef526 5730 assert((unsigned) r < n);
034a2a52 5731
d60ef526
LP
5732 l[r] = strdup(de->d_name);
5733 if (!l[r]) {
5734 r = -ENOMEM;
5735 goto finish;
5736 }
034a2a52 5737
d60ef526
LP
5738 l[++r] = NULL;
5739 } else
5740 r++;
034a2a52
LP
5741 }
5742
5743finish:
5744 if (d)
5745 closedir(d);
5746
d60ef526
LP
5747 if (r >= 0) {
5748 if (list)
5749 *list = l;
5750 } else
034a2a52
LP
5751 strv_free(l);
5752
5753 return r;
5754}
5755
911a4828
LP
5756char *join(const char *x, ...) {
5757 va_list ap;
5758 size_t l;
5759 char *r, *p;
5760
5761 va_start(ap, x);
5762
5763 if (x) {
5764 l = strlen(x);
5765
5766 for (;;) {
5767 const char *t;
5768
5769 t = va_arg(ap, const char *);
5770 if (!t)
5771 break;
5772
5773 l += strlen(t);
5774 }
5775 } else
5776 l = 0;
5777
5778 va_end(ap);
5779
5780 r = new(char, l+1);
5781 if (!r)
5782 return NULL;
5783
5784 if (x) {
5785 p = stpcpy(r, x);
5786
5787 va_start(ap, x);
5788
5789 for (;;) {
5790 const char *t;
5791
5792 t = va_arg(ap, const char *);
5793 if (!t)
5794 break;
5795
5796 p = stpcpy(p, t);
5797 }
8ea913b2
LP
5798
5799 va_end(ap);
911a4828
LP
5800 } else
5801 r[0] = 0;
5802
5803 return r;
5804}
5805
b636465b
LP
5806bool is_main_thread(void) {
5807 static __thread int cached = 0;
5808
5809 if (_unlikely_(cached == 0))
5810 cached = getpid() == gettid() ? 1 : -1;
5811
5812 return cached > 0;
5813}
5814
94959f0f
LP
5815int block_get_whole_disk(dev_t d, dev_t *ret) {
5816 char *p, *s;
5817 int r;
5818 unsigned n, m;
5819
5820 assert(ret);
5821
5822 /* If it has a queue this is good enough for us */
5823 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5824 return -ENOMEM;
5825
5826 r = access(p, F_OK);
5827 free(p);
5828
5829 if (r >= 0) {
5830 *ret = d;
5831 return 0;
5832 }
5833
5834 /* If it is a partition find the originating device */
5835 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5836 return -ENOMEM;
5837
5838 r = access(p, F_OK);
5839 free(p);
5840
5841 if (r < 0)
5842 return -ENOENT;
5843
5844 /* Get parent dev_t */
5845 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5846 return -ENOMEM;
5847
5848 r = read_one_line_file(p, &s);
5849 free(p);
5850
5851 if (r < 0)
5852 return r;
5853
5854 r = sscanf(s, "%u:%u", &m, &n);
5855 free(s);
5856
5857 if (r != 2)
5858 return -EINVAL;
5859
5860 /* Only return this if it is really good enough for us. */
5861 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5862 return -ENOMEM;
5863
5864 r = access(p, F_OK);
5865 free(p);
5866
5867 if (r >= 0) {
5868 *ret = makedev(m, n);
5869 return 0;
5870 }
5871
5872 return -ENOENT;
5873}
5874
8d53b453 5875int file_is_priv_sticky(const char *p) {
ad293f5a
LP
5876 struct stat st;
5877
5878 assert(p);
5879
5880 if (lstat(p, &st) < 0)
5881 return -errno;
5882
5883 return
8d53b453 5884 (st.st_uid == 0 || st.st_uid == getuid()) &&
ad293f5a
LP
5885 (st.st_mode & S_ISVTX);
5886}
94959f0f 5887
f41607a6
LP
5888static const char *const ioprio_class_table[] = {
5889 [IOPRIO_CLASS_NONE] = "none",
5890 [IOPRIO_CLASS_RT] = "realtime",
5891 [IOPRIO_CLASS_BE] = "best-effort",
5892 [IOPRIO_CLASS_IDLE] = "idle"
5893};
5894
5895DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5896
5897static const char *const sigchld_code_table[] = {
5898 [CLD_EXITED] = "exited",
5899 [CLD_KILLED] = "killed",
5900 [CLD_DUMPED] = "dumped",
5901 [CLD_TRAPPED] = "trapped",
5902 [CLD_STOPPED] = "stopped",
5903 [CLD_CONTINUED] = "continued",
5904};
5905
5906DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5907
5908static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5909 [LOG_FAC(LOG_KERN)] = "kern",
5910 [LOG_FAC(LOG_USER)] = "user",
5911 [LOG_FAC(LOG_MAIL)] = "mail",
5912 [LOG_FAC(LOG_DAEMON)] = "daemon",
5913 [LOG_FAC(LOG_AUTH)] = "auth",
5914 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5915 [LOG_FAC(LOG_LPR)] = "lpr",
5916 [LOG_FAC(LOG_NEWS)] = "news",
5917 [LOG_FAC(LOG_UUCP)] = "uucp",
5918 [LOG_FAC(LOG_CRON)] = "cron",
5919 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5920 [LOG_FAC(LOG_FTP)] = "ftp",
5921 [LOG_FAC(LOG_LOCAL0)] = "local0",
5922 [LOG_FAC(LOG_LOCAL1)] = "local1",
5923 [LOG_FAC(LOG_LOCAL2)] = "local2",
5924 [LOG_FAC(LOG_LOCAL3)] = "local3",
5925 [LOG_FAC(LOG_LOCAL4)] = "local4",
5926 [LOG_FAC(LOG_LOCAL5)] = "local5",
5927 [LOG_FAC(LOG_LOCAL6)] = "local6",
5928 [LOG_FAC(LOG_LOCAL7)] = "local7"
5929};
5930
5931DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5932
5933static const char *const log_level_table[] = {
5934 [LOG_EMERG] = "emerg",
5935 [LOG_ALERT] = "alert",
5936 [LOG_CRIT] = "crit",
5937 [LOG_ERR] = "err",
5938 [LOG_WARNING] = "warning",
5939 [LOG_NOTICE] = "notice",
5940 [LOG_INFO] = "info",
5941 [LOG_DEBUG] = "debug"
5942};
5943
5944DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5945
5946static const char* const sched_policy_table[] = {
5947 [SCHED_OTHER] = "other",
5948 [SCHED_BATCH] = "batch",
5949 [SCHED_IDLE] = "idle",
5950 [SCHED_FIFO] = "fifo",
5951 [SCHED_RR] = "rr"
5952};
5953
5954DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5955
5956static const char* const rlimit_table[] = {
5957 [RLIMIT_CPU] = "LimitCPU",
5958 [RLIMIT_FSIZE] = "LimitFSIZE",
5959 [RLIMIT_DATA] = "LimitDATA",
5960 [RLIMIT_STACK] = "LimitSTACK",
5961 [RLIMIT_CORE] = "LimitCORE",
5962 [RLIMIT_RSS] = "LimitRSS",
5963 [RLIMIT_NOFILE] = "LimitNOFILE",
5964 [RLIMIT_AS] = "LimitAS",
5965 [RLIMIT_NPROC] = "LimitNPROC",
5966 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5967 [RLIMIT_LOCKS] = "LimitLOCKS",
5968 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5969 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5970 [RLIMIT_NICE] = "LimitNICE",
5971 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5972 [RLIMIT_RTTIME] = "LimitRTTIME"
5973};
5974
5975DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5976
5977static const char* const ip_tos_table[] = {
5978 [IPTOS_LOWDELAY] = "low-delay",
5979 [IPTOS_THROUGHPUT] = "throughput",
5980 [IPTOS_RELIABILITY] = "reliability",
5981 [IPTOS_LOWCOST] = "low-cost",
5982};
5983
5984DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5985
4e240ab0 5986static const char *const __signal_table[] = {
f41607a6
LP
5987 [SIGHUP] = "HUP",
5988 [SIGINT] = "INT",
5989 [SIGQUIT] = "QUIT",
5990 [SIGILL] = "ILL",
5991 [SIGTRAP] = "TRAP",
5992 [SIGABRT] = "ABRT",
5993 [SIGBUS] = "BUS",
5994 [SIGFPE] = "FPE",
5995 [SIGKILL] = "KILL",
5996 [SIGUSR1] = "USR1",
5997 [SIGSEGV] = "SEGV",
5998 [SIGUSR2] = "USR2",
5999 [SIGPIPE] = "PIPE",
6000 [SIGALRM] = "ALRM",
6001 [SIGTERM] = "TERM",
6002#ifdef SIGSTKFLT
6003 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
6004#endif
6005 [SIGCHLD] = "CHLD",
6006 [SIGCONT] = "CONT",
6007 [SIGSTOP] = "STOP",
6008 [SIGTSTP] = "TSTP",
6009 [SIGTTIN] = "TTIN",
6010 [SIGTTOU] = "TTOU",
6011 [SIGURG] = "URG",
6012 [SIGXCPU] = "XCPU",
6013 [SIGXFSZ] = "XFSZ",
6014 [SIGVTALRM] = "VTALRM",
6015 [SIGPROF] = "PROF",
6016 [SIGWINCH] = "WINCH",
6017 [SIGIO] = "IO",
6018 [SIGPWR] = "PWR",
6019 [SIGSYS] = "SYS"
6020};
6021
4e240ab0
MS
6022DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
6023
6024const char *signal_to_string(int signo) {
6025 static __thread char buf[12];
6026 const char *name;
6027
6028 name = __signal_to_string(signo);
6029 if (name)
6030 return name;
6031
6032 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
6033 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
6034 else
6035 snprintf(buf, sizeof(buf) - 1, "%d", signo);
6036 char_array_0(buf);
6037 return buf;
6038}
6039
6040int signal_from_string(const char *s) {
6041 int signo;
6042 int offset = 0;
6043 unsigned u;
6044
6045 signo =__signal_from_string(s);
6046 if (signo > 0)
6047 return signo;
6048
6049 if (startswith(s, "RTMIN+")) {
6050 s += 6;
6051 offset = SIGRTMIN;
6052 }
6053 if (safe_atou(s, &u) >= 0) {
6054 signo = (int) u + offset;
6055 if (signo > 0 && signo < _NSIG)
6056 return signo;
6057 }
6058 return -1;
6059}
65457142
FC
6060
6061bool kexec_loaded(void) {
6062 bool loaded = false;
6063 char *s;
6064
6065 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
6066 if (s[0] == '1')
6067 loaded = true;
6068 free(s);
6069 }
6070 return loaded;
6071}
fb9de93d
LP
6072
6073int strdup_or_null(const char *a, char **b) {
6074 char *c;
6075
6076 assert(b);
6077
6078 if (!a) {
6079 *b = NULL;
6080 return 0;
6081 }
6082
6083 c = strdup(a);
6084 if (!c)
6085 return -ENOMEM;
6086
6087 *b = c;
6088 return 0;
6089}
64685e0c 6090
87d2c1ff
LP
6091int prot_from_flags(int flags) {
6092
6093 switch (flags & O_ACCMODE) {
6094
6095 case O_RDONLY:
6096 return PROT_READ;
6097
6098 case O_WRONLY:
6099 return PROT_WRITE;
6100
6101 case O_RDWR:
6102 return PROT_READ|PROT_WRITE;
6103
6104 default:
6105 return -EINVAL;
6106 }
7c99e0c1 6107}
689b9a22 6108
64685e0c
LP
6109unsigned long cap_last_cap(void) {
6110 static __thread unsigned long saved;
6111 static __thread bool valid = false;
6112 unsigned long p;
6113
6114 if (valid)
6115 return saved;
6116
6117 p = (unsigned long) CAP_LAST_CAP;
6118
6119 if (prctl(PR_CAPBSET_READ, p) < 0) {
6120
6121 /* Hmm, look downwards, until we find one that
6122 * works */
6123 for (p--; p > 0; p --)
6124 if (prctl(PR_CAPBSET_READ, p) >= 0)
6125 break;
6126
6127 } else {
6128
6129 /* Hmm, look upwards, until we find one that doesn't
6130 * work */
6131 for (;; p++)
6132 if (prctl(PR_CAPBSET_READ, p+1) < 0)
6133 break;
6134 }
6135
6136 saved = p;
6137 valid = true;
6138
6139 return p;
6140}
babfc091
LP
6141
6142char *format_bytes(char *buf, size_t l, off_t t) {
c0f99c21 6143 unsigned i;
babfc091
LP
6144
6145 static const struct {
6146 const char *suffix;
6147 off_t factor;
6148 } table[] = {
32895bb3
LP
6149 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6150 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
babfc091
LP
6151 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
6152 { "G", 1024ULL*1024ULL*1024ULL },
6153 { "M", 1024ULL*1024ULL },
6154 { "K", 1024ULL },
6155 };
6156
6157 for (i = 0; i < ELEMENTSOF(table); i++) {
6158
6159 if (t >= table[i].factor) {
6160 snprintf(buf, l,
6161 "%llu.%llu%s",
6162 (unsigned long long) (t / table[i].factor),
6163 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
6164 table[i].suffix);
6165
6166 goto finish;
6167 }
6168 }
6169
6170 snprintf(buf, l, "%lluB", (unsigned long long) t);
6171
6172finish:
6173 buf[l-1] = 0;
6174 return buf;
6175
6176}
55d7bfc1
LP
6177
6178void* memdup(const void *p, size_t l) {
6179 void *r;
6180
6181 assert(p);
6182
6183 r = malloc(l);
6184 if (!r)
6185 return NULL;
6186
6187 memcpy(r, p, l);
6188 return r;
6189}
bb99a35a
LP
6190
6191int fd_inc_sndbuf(int fd, size_t n) {
6192 int r, value;
6193 socklen_t l = sizeof(value);
6194
6195 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
6196 if (r >= 0 &&
6197 l == sizeof(value) &&
6198 (size_t) value >= n*2)
6199 return 0;
6200
6201 value = (int) n;
6202 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
6203 if (r < 0)
6204 return -errno;
6205
6206 return 1;
6207}
6208
6209int fd_inc_rcvbuf(int fd, size_t n) {
6210 int r, value;
6211 socklen_t l = sizeof(value);
6212
6213 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
6214 if (r >= 0 &&
6215 l == sizeof(value) &&
6216 (size_t) value >= n*2)
6217 return 0;
6218
6219 value = (int) n;
6220 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
6221 if (r < 0)
6222 return -errno;
6223
6224 return 1;
6225}