]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/util.c
journald: use SCM_SECURITY to race-freely determine peer SELinux label
[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
a0d40ac5
LP
2210int close_all_fds(const int except[], unsigned n_except) {
2211 DIR *d;
2212 struct dirent *de;
2213 int r = 0;
2214
2215 if (!(d = opendir("/proc/self/fd")))
2216 return -errno;
2217
2218 while ((de = readdir(d))) {
a7610064 2219 int fd = -1;
a0d40ac5 2220
a16e1123 2221 if (ignore_file(de->d_name))
a0d40ac5
LP
2222 continue;
2223
720ce21d
LP
2224 if (safe_atoi(de->d_name, &fd) < 0)
2225 /* Let's better ignore this, just in case */
2226 continue;
a0d40ac5
LP
2227
2228 if (fd < 3)
2229 continue;
2230
2231 if (fd == dirfd(d))
2232 continue;
2233
2234 if (except) {
2235 bool found;
2236 unsigned i;
2237
2238 found = false;
2239 for (i = 0; i < n_except; i++)
2240 if (except[i] == fd) {
2241 found = true;
2242 break;
2243 }
2244
2245 if (found)
2246 continue;
2247 }
2248
720ce21d 2249 if (close_nointr(fd) < 0) {
2f357920 2250 /* Valgrind has its own FD and doesn't want to have it closed */
720ce21d
LP
2251 if (errno != EBADF && r == 0)
2252 r = -errno;
2f357920 2253 }
a0d40ac5
LP
2254 }
2255
a0d40ac5
LP
2256 closedir(d);
2257 return r;
2258}
2259
db12775d
LP
2260bool chars_intersect(const char *a, const char *b) {
2261 const char *p;
2262
2263 /* Returns true if any of the chars in a are in b. */
2264 for (p = a; *p; p++)
2265 if (strchr(b, *p))
2266 return true;
2267
2268 return false;
2269}
2270
8b6c7120
LP
2271char *format_timestamp(char *buf, size_t l, usec_t t) {
2272 struct tm tm;
2273 time_t sec;
2274
2275 assert(buf);
2276 assert(l > 0);
2277
2278 if (t <= 0)
2279 return NULL;
2280
f872ec33 2281 sec = (time_t) (t / USEC_PER_SEC);
8b6c7120
LP
2282
2283 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2284 return NULL;
2285
2286 return buf;
2287}
2288
584be568
LP
2289char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2290 usec_t n, d;
2291
2292 n = now(CLOCK_REALTIME);
2293
2294 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2295 return NULL;
2296
2297 d = n - t;
2298
2299 if (d >= USEC_PER_YEAR)
2300 snprintf(buf, l, "%llu years and %llu months ago",
2301 (unsigned long long) (d / USEC_PER_YEAR),
2302 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2303 else if (d >= USEC_PER_MONTH)
2304 snprintf(buf, l, "%llu months and %llu days ago",
2305 (unsigned long long) (d / USEC_PER_MONTH),
2306 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2307 else if (d >= USEC_PER_WEEK)
2308 snprintf(buf, l, "%llu weeks and %llu days ago",
2309 (unsigned long long) (d / USEC_PER_WEEK),
2310 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2311 else if (d >= 2*USEC_PER_DAY)
2312 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2313 else if (d >= 25*USEC_PER_HOUR)
2314 snprintf(buf, l, "1 day and %lluh ago",
2315 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2316 else if (d >= 6*USEC_PER_HOUR)
2317 snprintf(buf, l, "%lluh ago",
2318 (unsigned long long) (d / USEC_PER_HOUR));
2319 else if (d >= USEC_PER_HOUR)
2320 snprintf(buf, l, "%lluh %llumin ago",
2321 (unsigned long long) (d / USEC_PER_HOUR),
2322 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2323 else if (d >= 5*USEC_PER_MINUTE)
2324 snprintf(buf, l, "%llumin ago",
2325 (unsigned long long) (d / USEC_PER_MINUTE));
2326 else if (d >= USEC_PER_MINUTE)
2327 snprintf(buf, l, "%llumin %llus ago",
2328 (unsigned long long) (d / USEC_PER_MINUTE),
2329 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2330 else if (d >= USEC_PER_SEC)
2331 snprintf(buf, l, "%llus ago",
2332 (unsigned long long) (d / USEC_PER_SEC));
2333 else if (d >= USEC_PER_MSEC)
2334 snprintf(buf, l, "%llums ago",
2335 (unsigned long long) (d / USEC_PER_MSEC));
2336 else if (d > 0)
2337 snprintf(buf, l, "%lluus ago",
2338 (unsigned long long) d);
2339 else
2340 snprintf(buf, l, "now");
2341
2342 buf[l-1] = 0;
2343 return buf;
2344}
2345
871d7de4
LP
2346char *format_timespan(char *buf, size_t l, usec_t t) {
2347 static const struct {
2348 const char *suffix;
2349 usec_t usec;
2350 } table[] = {
2351 { "w", USEC_PER_WEEK },
2352 { "d", USEC_PER_DAY },
2353 { "h", USEC_PER_HOUR },
2354 { "min", USEC_PER_MINUTE },
2355 { "s", USEC_PER_SEC },
2356 { "ms", USEC_PER_MSEC },
2357 { "us", 1 },
2358 };
2359
2360 unsigned i;
2361 char *p = buf;
2362
2363 assert(buf);
2364 assert(l > 0);
2365
2366 if (t == (usec_t) -1)
2367 return NULL;
2368
4502d22c
LP
2369 if (t == 0) {
2370 snprintf(p, l, "0");
2371 p[l-1] = 0;
2372 return p;
2373 }
2374
871d7de4
LP
2375 /* The result of this function can be parsed with parse_usec */
2376
2377 for (i = 0; i < ELEMENTSOF(table); i++) {
2378 int k;
2379 size_t n;
2380
2381 if (t < table[i].usec)
2382 continue;
2383
2384 if (l <= 1)
2385 break;
2386
2387 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2388 n = MIN((size_t) k, l);
2389
2390 l -= n;
2391 p += n;
2392
2393 t %= table[i].usec;
2394 }
2395
2396 *p = 0;
2397
2398 return buf;
2399}
2400
42856c10
LP
2401bool fstype_is_network(const char *fstype) {
2402 static const char * const table[] = {
2403 "cifs",
2404 "smbfs",
2405 "ncpfs",
2406 "nfs",
ca139f94
LP
2407 "nfs4",
2408 "gfs",
2409 "gfs2"
42856c10
LP
2410 };
2411
2412 unsigned i;
2413
2414 for (i = 0; i < ELEMENTSOF(table); i++)
2415 if (streq(table[i], fstype))
2416 return true;
2417
2418 return false;
2419}
2420
601f6a1e
LP
2421int chvt(int vt) {
2422 int fd, r = 0;
2423
74bc3bdc 2424 if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
601f6a1e
LP
2425 return -errno;
2426
2427 if (vt < 0) {
2428 int tiocl[2] = {
2429 TIOCL_GETKMSGREDIRECT,
2430 0
2431 };
2432
678abaf9
TJ
2433 if (ioctl(fd, TIOCLINUX, tiocl) < 0) {
2434 r = -errno;
2435 goto fail;
2436 }
601f6a1e
LP
2437
2438 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2439 }
2440
2441 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2442 r = -errno;
2443
678abaf9
TJ
2444fail:
2445 close_nointr_nofail(fd);
601f6a1e
LP
2446 return r;
2447}
2448
8f2d43a0 2449int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
80876c20
LP
2450 struct termios old_termios, new_termios;
2451 char c;
20c03b7b 2452 char line[LINE_MAX];
80876c20
LP
2453
2454 assert(f);
2455 assert(ret);
2456
2457 if (tcgetattr(fileno(f), &old_termios) >= 0) {
2458 new_termios = old_termios;
2459
2460 new_termios.c_lflag &= ~ICANON;
2461 new_termios.c_cc[VMIN] = 1;
2462 new_termios.c_cc[VTIME] = 0;
2463
2464 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2465 size_t k;
2466
8f2d43a0
LP
2467 if (t != (usec_t) -1) {
2468 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2469 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2470 return -ETIMEDOUT;
2471 }
2472 }
2473
80876c20
LP
2474 k = fread(&c, 1, 1, f);
2475
2476 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2477
2478 if (k <= 0)
2479 return -EIO;
2480
2481 if (need_nl)
2482 *need_nl = c != '\n';
2483
2484 *ret = c;
2485 return 0;
2486 }
2487 }
2488
8f2d43a0
LP
2489 if (t != (usec_t) -1)
2490 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2491 return -ETIMEDOUT;
2492
2493 if (!fgets(line, sizeof(line), f))
80876c20
LP
2494 return -EIO;
2495
2496 truncate_nl(line);
2497
2498 if (strlen(line) != 1)
2499 return -EBADMSG;
2500
2501 if (need_nl)
2502 *need_nl = false;
2503
2504 *ret = line[0];
2505 return 0;
2506}
2507
2508int ask(char *ret, const char *replies, const char *text, ...) {
1b39d4b9
LP
2509 bool on_tty;
2510
80876c20
LP
2511 assert(ret);
2512 assert(replies);
2513 assert(text);
2514
1b39d4b9
LP
2515 on_tty = isatty(STDOUT_FILENO);
2516
80876c20
LP
2517 for (;;) {
2518 va_list ap;
2519 char c;
2520 int r;
2521 bool need_nl = true;
2522
1b39d4b9 2523 if (on_tty)
c1072ea0 2524 fputs(ANSI_HIGHLIGHT_ON, stdout);
b1b2dc0c 2525
80876c20
LP
2526 va_start(ap, text);
2527 vprintf(text, ap);
2528 va_end(ap);
2529
1b39d4b9 2530 if (on_tty)
c1072ea0 2531 fputs(ANSI_HIGHLIGHT_OFF, stdout);
b1b2dc0c 2532
80876c20
LP
2533 fflush(stdout);
2534
8f2d43a0
LP
2535 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2536 if (r < 0) {
80876c20
LP
2537
2538 if (r == -EBADMSG) {
2539 puts("Bad input, please try again.");
2540 continue;
2541 }
2542
2543 putchar('\n');
2544 return r;
2545 }
2546
2547 if (need_nl)
2548 putchar('\n');
2549
2550 if (strchr(replies, c)) {
2551 *ret = c;
2552 return 0;
2553 }
2554
2555 puts("Read unexpected character, please try again.");
2556 }
2557}
2558
512947d4 2559int reset_terminal_fd(int fd, bool switch_to_text) {
80876c20
LP
2560 struct termios termios;
2561 int r = 0;
3fe5e5d4
LP
2562
2563 /* Set terminal to some sane defaults */
80876c20
LP
2564
2565 assert(fd >= 0);
2566
eed1d0e3
LP
2567 /* We leave locked terminal attributes untouched, so that
2568 * Plymouth may set whatever it wants to set, and we don't
2569 * interfere with that. */
3fe5e5d4
LP
2570
2571 /* Disable exclusive mode, just in case */
2572 ioctl(fd, TIOCNXCL);
2573
5c0100a5 2574 /* Switch to text mode */
512947d4
MS
2575 if (switch_to_text)
2576 ioctl(fd, KDSETMODE, KD_TEXT);
5c0100a5 2577
3fe5e5d4 2578 /* Enable console unicode mode */
df465b3f 2579 ioctl(fd, KDSKBMODE, K_UNICODE);
80876c20
LP
2580
2581 if (tcgetattr(fd, &termios) < 0) {
2582 r = -errno;
2583 goto finish;
2584 }
2585
aaf694ca
LP
2586 /* We only reset the stuff that matters to the software. How
2587 * hardware is set up we don't touch assuming that somebody
2588 * else will do that for us */
2589
2590 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
80876c20
LP
2591 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2592 termios.c_oflag |= ONLCR;
2593 termios.c_cflag |= CREAD;
2594 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2595
2596 termios.c_cc[VINTR] = 03; /* ^C */
2597 termios.c_cc[VQUIT] = 034; /* ^\ */
2598 termios.c_cc[VERASE] = 0177;
2599 termios.c_cc[VKILL] = 025; /* ^X */
2600 termios.c_cc[VEOF] = 04; /* ^D */
2601 termios.c_cc[VSTART] = 021; /* ^Q */
2602 termios.c_cc[VSTOP] = 023; /* ^S */
2603 termios.c_cc[VSUSP] = 032; /* ^Z */
2604 termios.c_cc[VLNEXT] = 026; /* ^V */
2605 termios.c_cc[VWERASE] = 027; /* ^W */
2606 termios.c_cc[VREPRINT] = 022; /* ^R */
aaf694ca
LP
2607 termios.c_cc[VEOL] = 0;
2608 termios.c_cc[VEOL2] = 0;
80876c20
LP
2609
2610 termios.c_cc[VTIME] = 0;
2611 termios.c_cc[VMIN] = 1;
2612
2613 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2614 r = -errno;
2615
2616finish:
2617 /* Just in case, flush all crap out */
2618 tcflush(fd, TCIOFLUSH);
2619
2620 return r;
2621}
2622
6ea832a2
LP
2623int reset_terminal(const char *name) {
2624 int fd, r;
2625
2626 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2627 if (fd < 0)
2628 return fd;
2629
512947d4 2630 r = reset_terminal_fd(fd, true);
6ea832a2
LP
2631 close_nointr_nofail(fd);
2632
2633 return r;
2634}
2635
80876c20
LP
2636int open_terminal(const char *name, int mode) {
2637 int fd, r;
f73f76ac 2638 unsigned c = 0;
80876c20 2639
f73f76ac
LP
2640 /*
2641 * If a TTY is in the process of being closed opening it might
2642 * cause EIO. This is horribly awful, but unlikely to be
2643 * changed in the kernel. Hence we work around this problem by
2644 * retrying a couple of times.
2645 *
2646 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2647 */
2648
2649 for (;;) {
2650 if ((fd = open(name, mode)) >= 0)
2651 break;
2652
2653 if (errno != EIO)
2654 return -errno;
2655
2656 if (c >= 20)
2657 return -errno;
2658
2659 usleep(50 * USEC_PER_MSEC);
2660 c++;
2661 }
2662
2663 if (fd < 0)
80876c20
LP
2664 return -errno;
2665
2666 if ((r = isatty(fd)) < 0) {
2667 close_nointr_nofail(fd);
2668 return -errno;
2669 }
2670
2671 if (!r) {
2672 close_nointr_nofail(fd);
2673 return -ENOTTY;
2674 }
2675
2676 return fd;
2677}
2678
2679int flush_fd(int fd) {
2680 struct pollfd pollfd;
2681
2682 zero(pollfd);
2683 pollfd.fd = fd;
2684 pollfd.events = POLLIN;
2685
2686 for (;;) {
20c03b7b 2687 char buf[LINE_MAX];
80876c20
LP
2688 ssize_t l;
2689 int r;
2690
2691 if ((r = poll(&pollfd, 1, 0)) < 0) {
2692
2693 if (errno == EINTR)
2694 continue;
2695
2696 return -errno;
2697 }
2698
2699 if (r == 0)
2700 return 0;
2701
2702 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2703
2704 if (errno == EINTR)
2705 continue;
2706
2707 if (errno == EAGAIN)
2708 return 0;
2709
2710 return -errno;
2711 }
2712
2713 if (l <= 0)
2714 return 0;
2715 }
2716}
2717
21de3988 2718int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
bab45044 2719 int fd = -1, notify = -1, r, wd = -1;
80876c20
LP
2720
2721 assert(name);
2722
2723 /* We use inotify to be notified when the tty is closed. We
2724 * create the watch before checking if we can actually acquire
2725 * it, so that we don't lose any event.
2726 *
2727 * Note: strictly speaking this actually watches for the
2728 * device being closed, it does *not* really watch whether a
2729 * tty loses its controlling process. However, unless some
2730 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2731 * its tty otherwise this will not become a problem. As long
2732 * as the administrator makes sure not configure any service
2733 * on the same tty as an untrusted user this should not be a
2734 * problem. (Which he probably should not do anyway.) */
2735
2736 if (!fail && !force) {
2737 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2738 r = -errno;
2739 goto fail;
2740 }
2741
2742 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2743 r = -errno;
2744 goto fail;
2745 }
2746 }
2747
2748 for (;;) {
e3d1855b
LP
2749 if (notify >= 0)
2750 if ((r = flush_fd(notify)) < 0)
2751 goto fail;
80876c20
LP
2752
2753 /* We pass here O_NOCTTY only so that we can check the return
2754 * value TIOCSCTTY and have a reliable way to figure out if we
2755 * successfully became the controlling process of the tty */
6ea832a2
LP
2756 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2757 return fd;
80876c20
LP
2758
2759 /* First, try to get the tty */
21de3988
LP
2760 r = ioctl(fd, TIOCSCTTY, force);
2761
2762 /* Sometimes it makes sense to ignore TIOCSCTTY
2763 * returning EPERM, i.e. when very likely we already
2764 * are have this controlling terminal. */
2765 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2766 r = 0;
2767
2768 if (r < 0 && (force || fail || errno != EPERM)) {
80876c20
LP
2769 r = -errno;
2770 goto fail;
2771 }
2772
2773 if (r >= 0)
2774 break;
2775
2776 assert(!fail);
2777 assert(!force);
2778 assert(notify >= 0);
2779
2780 for (;;) {
f601daa7 2781 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
80876c20 2782 ssize_t l;
f601daa7 2783 struct inotify_event *e;
80876c20 2784
50f20cfd 2785 if ((l = read(notify, inotify_buffer, sizeof(inotify_buffer))) < 0) {
80876c20 2786
f601daa7
LP
2787 if (errno == EINTR)
2788 continue;
2789
2790 r = -errno;
2791 goto fail;
2792 }
2793
2794 e = (struct inotify_event*) inotify_buffer;
80876c20 2795
f601daa7
LP
2796 while (l > 0) {
2797 size_t step;
80876c20 2798
f601daa7 2799 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
80876c20 2800 r = -EIO;
f601daa7
LP
2801 goto fail;
2802 }
80876c20 2803
f601daa7
LP
2804 step = sizeof(struct inotify_event) + e->len;
2805 assert(step <= (size_t) l);
80876c20 2806
f601daa7
LP
2807 e = (struct inotify_event*) ((uint8_t*) e + step);
2808 l -= step;
80876c20
LP
2809 }
2810
2811 break;
2812 }
2813
2814 /* We close the tty fd here since if the old session
2815 * ended our handle will be dead. It's important that
2816 * we do this after sleeping, so that we don't enter
2817 * an endless loop. */
2818 close_nointr_nofail(fd);
2819 }
2820
2821 if (notify >= 0)
a16e1123 2822 close_nointr_nofail(notify);
80876c20 2823
512947d4
MS
2824 r = reset_terminal_fd(fd, true);
2825 if (r < 0)
80876c20
LP
2826 log_warning("Failed to reset terminal: %s", strerror(-r));
2827
2828 return fd;
2829
2830fail:
2831 if (fd >= 0)
a16e1123 2832 close_nointr_nofail(fd);
80876c20
LP
2833
2834 if (notify >= 0)
a16e1123 2835 close_nointr_nofail(notify);
80876c20
LP
2836
2837 return r;
2838}
2839
2840int release_terminal(void) {
2841 int r = 0, fd;
57cd2192 2842 struct sigaction sa_old, sa_new;
80876c20 2843
ccaa6149 2844 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
80876c20
LP
2845 return -errno;
2846
57cd2192
LP
2847 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2848 * by our own TIOCNOTTY */
2849
2850 zero(sa_new);
2851 sa_new.sa_handler = SIG_IGN;
2852 sa_new.sa_flags = SA_RESTART;
2853 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2854
80876c20
LP
2855 if (ioctl(fd, TIOCNOTTY) < 0)
2856 r = -errno;
2857
57cd2192
LP
2858 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2859
80876c20
LP
2860 close_nointr_nofail(fd);
2861 return r;
2862}
2863
9a34ec5f
LP
2864int sigaction_many(const struct sigaction *sa, ...) {
2865 va_list ap;
2866 int r = 0, sig;
2867
2868 va_start(ap, sa);
2869 while ((sig = va_arg(ap, int)) > 0)
2870 if (sigaction(sig, sa, NULL) < 0)
2871 r = -errno;
2872 va_end(ap);
2873
2874 return r;
2875}
2876
2877int ignore_signals(int sig, ...) {
a337c6fc 2878 struct sigaction sa;
9a34ec5f
LP
2879 va_list ap;
2880 int r = 0;
a337c6fc
LP
2881
2882 zero(sa);
2883 sa.sa_handler = SIG_IGN;
2884 sa.sa_flags = SA_RESTART;
2885
9a34ec5f
LP
2886 if (sigaction(sig, &sa, NULL) < 0)
2887 r = -errno;
2888
2889 va_start(ap, sig);
2890 while ((sig = va_arg(ap, int)) > 0)
2891 if (sigaction(sig, &sa, NULL) < 0)
2892 r = -errno;
2893 va_end(ap);
2894
2895 return r;
2896}
2897
2898int default_signals(int sig, ...) {
2899 struct sigaction sa;
2900 va_list ap;
2901 int r = 0;
2902
2903 zero(sa);
2904 sa.sa_handler = SIG_DFL;
2905 sa.sa_flags = SA_RESTART;
2906
2907 if (sigaction(sig, &sa, NULL) < 0)
2908 r = -errno;
2909
2910 va_start(ap, sig);
2911 while ((sig = va_arg(ap, int)) > 0)
2912 if (sigaction(sig, &sa, NULL) < 0)
2913 r = -errno;
2914 va_end(ap);
2915
2916 return r;
a337c6fc
LP
2917}
2918
8d567588
LP
2919int close_pipe(int p[]) {
2920 int a = 0, b = 0;
2921
2922 assert(p);
2923
2924 if (p[0] >= 0) {
2925 a = close_nointr(p[0]);
2926 p[0] = -1;
2927 }
2928
2929 if (p[1] >= 0) {
2930 b = close_nointr(p[1]);
2931 p[1] = -1;
2932 }
2933
2934 return a < 0 ? a : b;
2935}
2936
eb22ac37 2937ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
8d567588
LP
2938 uint8_t *p;
2939 ssize_t n = 0;
2940
2941 assert(fd >= 0);
2942 assert(buf);
2943
2944 p = buf;
2945
2946 while (nbytes > 0) {
2947 ssize_t k;
2948
2949 if ((k = read(fd, p, nbytes)) <= 0) {
2950
eb22ac37 2951 if (k < 0 && errno == EINTR)
8d567588
LP
2952 continue;
2953
eb22ac37 2954 if (k < 0 && errno == EAGAIN && do_poll) {
8d567588
LP
2955 struct pollfd pollfd;
2956
2957 zero(pollfd);
2958 pollfd.fd = fd;
2959 pollfd.events = POLLIN;
2960
2961 if (poll(&pollfd, 1, -1) < 0) {
2962 if (errno == EINTR)
2963 continue;
2964
2965 return n > 0 ? n : -errno;
2966 }
2967
2968 if (pollfd.revents != POLLIN)
2969 return n > 0 ? n : -EIO;
2970
2971 continue;
2972 }
2973
2974 return n > 0 ? n : (k < 0 ? -errno : 0);
2975 }
2976
2977 p += k;
2978 nbytes -= k;
2979 n += k;
2980 }
2981
2982 return n;
2983}
2984
eb22ac37
LP
2985ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2986 const uint8_t *p;
2987 ssize_t n = 0;
2988
2989 assert(fd >= 0);
2990 assert(buf);
2991
2992 p = buf;
2993
2994 while (nbytes > 0) {
2995 ssize_t k;
2996
fe652127
LP
2997 k = write(fd, p, nbytes);
2998 if (k <= 0) {
eb22ac37
LP
2999
3000 if (k < 0 && errno == EINTR)
3001 continue;
3002
3003 if (k < 0 && errno == EAGAIN && do_poll) {
3004 struct pollfd pollfd;
3005
3006 zero(pollfd);
3007 pollfd.fd = fd;
3008 pollfd.events = POLLOUT;
3009
3010 if (poll(&pollfd, 1, -1) < 0) {
3011 if (errno == EINTR)
3012 continue;
3013
3014 return n > 0 ? n : -errno;
3015 }
3016
3017 if (pollfd.revents != POLLOUT)
3018 return n > 0 ? n : -EIO;
3019
3020 continue;
3021 }
3022
3023 return n > 0 ? n : (k < 0 ? -errno : 0);
3024 }
3025
3026 p += k;
3027 nbytes -= k;
3028 n += k;
3029 }
3030
3031 return n;
3032}
3033
0c85a4f3 3034int path_is_mount_point(const char *t, bool allow_symlink) {
8d567588 3035 struct stat a, b;
35d2e7ec
LP
3036 char *parent;
3037 int r;
8d567588 3038
0c85a4f3
LP
3039 if (allow_symlink)
3040 r = stat(t, &a);
3041 else
3042 r = lstat(t, &a);
3043
3044 if (r < 0) {
8d567588
LP
3045 if (errno == ENOENT)
3046 return 0;
3047
3048 return -errno;
3049 }
3050
0c85a4f3
LP
3051 r = parent_of_path(t, &parent);
3052 if (r < 0)
35d2e7ec 3053 return r;
8d567588 3054
35d2e7ec
LP
3055 r = lstat(parent, &b);
3056 free(parent);
8d567588 3057
35d2e7ec
LP
3058 if (r < 0)
3059 return -errno;
8d567588
LP
3060
3061 return a.st_dev != b.st_dev;
3062}
3063
24a6e4a4
LP
3064int parse_usec(const char *t, usec_t *usec) {
3065 static const struct {
3066 const char *suffix;
3067 usec_t usec;
3068 } table[] = {
3069 { "sec", USEC_PER_SEC },
3070 { "s", USEC_PER_SEC },
3071 { "min", USEC_PER_MINUTE },
3072 { "hr", USEC_PER_HOUR },
3073 { "h", USEC_PER_HOUR },
3074 { "d", USEC_PER_DAY },
3075 { "w", USEC_PER_WEEK },
3076 { "msec", USEC_PER_MSEC },
3077 { "ms", USEC_PER_MSEC },
3078 { "m", USEC_PER_MINUTE },
3079 { "usec", 1ULL },
3080 { "us", 1ULL },
3081 { "", USEC_PER_SEC },
3082 };
3083
3084 const char *p;
3085 usec_t r = 0;
3086
3087 assert(t);
3088 assert(usec);
3089
3090 p = t;
3091 do {
3092 long long l;
3093 char *e;
3094 unsigned i;
3095
3096 errno = 0;
3097 l = strtoll(p, &e, 10);
3098
3099 if (errno != 0)
3100 return -errno;
3101
3102 if (l < 0)
3103 return -ERANGE;
3104
3105 if (e == p)
3106 return -EINVAL;
3107
3108 e += strspn(e, WHITESPACE);
3109
3110 for (i = 0; i < ELEMENTSOF(table); i++)
3111 if (startswith(e, table[i].suffix)) {
3112 r += (usec_t) l * table[i].usec;
3113 p = e + strlen(table[i].suffix);
3114 break;
3115 }
3116
3117 if (i >= ELEMENTSOF(table))
3118 return -EINVAL;
3119
3120 } while (*p != 0);
3121
3122 *usec = r;
3123
3124 return 0;
3125}
3126
ab1f0633
LP
3127int parse_bytes(const char *t, off_t *bytes) {
3128 static const struct {
3129 const char *suffix;
3130 off_t factor;
3131 } table[] = {
3132 { "B", 1 },
3133 { "K", 1024ULL },
3134 { "M", 1024ULL*1024ULL },
3135 { "G", 1024ULL*1024ULL*1024ULL },
3136 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
32895bb3
LP
3137 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3138 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
ab1f0633
LP
3139 { "", 1 },
3140 };
3141
3142 const char *p;
3143 off_t r = 0;
3144
3145 assert(t);
3146 assert(bytes);
3147
3148 p = t;
3149 do {
3150 long long l;
3151 char *e;
3152 unsigned i;
3153
3154 errno = 0;
3155 l = strtoll(p, &e, 10);
3156
3157 if (errno != 0)
3158 return -errno;
3159
3160 if (l < 0)
3161 return -ERANGE;
3162
3163 if (e == p)
3164 return -EINVAL;
3165
3166 e += strspn(e, WHITESPACE);
3167
3168 for (i = 0; i < ELEMENTSOF(table); i++)
3169 if (startswith(e, table[i].suffix)) {
3170 r += (off_t) l * table[i].factor;
3171 p = e + strlen(table[i].suffix);
3172 break;
3173 }
3174
3175 if (i >= ELEMENTSOF(table))
3176 return -EINVAL;
3177
3178 } while (*p != 0);
3179
3180 *bytes = r;
3181
3182 return 0;
3183}
3184
843d2643
LP
3185int make_stdio(int fd) {
3186 int r, s, t;
3187
3188 assert(fd >= 0);
3189
3190 r = dup2(fd, STDIN_FILENO);
3191 s = dup2(fd, STDOUT_FILENO);
3192 t = dup2(fd, STDERR_FILENO);
3193
3194 if (fd >= 3)
3195 close_nointr_nofail(fd);
3196
3197 if (r < 0 || s < 0 || t < 0)
3198 return -errno;
3199
7862f62d
LP
3200 fd_cloexec(STDIN_FILENO, false);
3201 fd_cloexec(STDOUT_FILENO, false);
3202 fd_cloexec(STDERR_FILENO, false);
3203
843d2643
LP
3204 return 0;
3205}
3206
ade509ce
LP
3207int make_null_stdio(void) {
3208 int null_fd;
3209
3210 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3211 return -errno;
3212
3213 return make_stdio(null_fd);
3214}
3215
8407a5d0
LP
3216bool is_device_path(const char *path) {
3217
3218 /* Returns true on paths that refer to a device, either in
3219 * sysfs or in /dev */
3220
3221 return
3222 path_startswith(path, "/dev/") ||
3223 path_startswith(path, "/sys/");
3224}
3225
01f78473
LP
3226int dir_is_empty(const char *path) {
3227 DIR *d;
3228 int r;
3229 struct dirent buf, *de;
3230
3231 if (!(d = opendir(path)))
3232 return -errno;
3233
3234 for (;;) {
3235 if ((r = readdir_r(d, &buf, &de)) > 0) {
3236 r = -r;
3237 break;
3238 }
3239
3240 if (!de) {
3241 r = 1;
3242 break;
3243 }
3244
3245 if (!ignore_file(de->d_name)) {
3246 r = 0;
3247 break;
3248 }
3249 }
3250
3251 closedir(d);
3252 return r;
3253}
3254
d3782d60
LP
3255unsigned long long random_ull(void) {
3256 int fd;
3257 uint64_t ull;
3258 ssize_t r;
3259
3260 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3261 goto fallback;
3262
eb22ac37 3263 r = loop_read(fd, &ull, sizeof(ull), true);
d3782d60
LP
3264 close_nointr_nofail(fd);
3265
3266 if (r != sizeof(ull))
3267 goto fallback;
3268
3269 return ull;
3270
3271fallback:
3272 return random() * RAND_MAX + random();
3273}
3274
5b6319dc
LP
3275void rename_process(const char name[8]) {
3276 assert(name);
3277
5d6b1584
LP
3278 /* This is a like a poor man's setproctitle(). It changes the
3279 * comm field, argv[0], and also the glibc's internally used
3280 * name of the process. For the first one a limit of 16 chars
3281 * applies, to the second one usually one of 10 (i.e. length
3282 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3283 * "systemd"). If you pass a longer string it will be
3284 * truncated */
5b6319dc 3285
5d6b1584 3286 prctl(PR_SET_NAME, name);
5b6319dc
LP
3287
3288 if (program_invocation_name)
3289 strncpy(program_invocation_name, name, strlen(program_invocation_name));
9a0e6896
LP
3290
3291 if (saved_argc > 0) {
3292 int i;
3293
3294 if (saved_argv[0])
3295 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3296
3297 for (i = 1; i < saved_argc; i++) {
3298 if (!saved_argv[i])
3299 break;
3300
3301 memset(saved_argv[i], 0, strlen(saved_argv[i]));
3302 }
3303 }
5b6319dc
LP
3304}
3305
7d793605
LP
3306void sigset_add_many(sigset_t *ss, ...) {
3307 va_list ap;
3308 int sig;
3309
3310 assert(ss);
3311
3312 va_start(ap, ss);
3313 while ((sig = va_arg(ap, int)) > 0)
3314 assert_se(sigaddset(ss, sig) == 0);
3315 va_end(ap);
3316}
3317
ef2f1067
LP
3318char* gethostname_malloc(void) {
3319 struct utsname u;
3320
3321 assert_se(uname(&u) >= 0);
3322
3323 if (u.nodename[0])
3324 return strdup(u.nodename);
3325
3326 return strdup(u.sysname);
3327}
3328
3329char* getlogname_malloc(void) {
3330 uid_t uid;
3331 long bufsize;
3332 char *buf, *name;
3333 struct passwd pwbuf, *pw = NULL;
3334 struct stat st;
3335
3336 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3337 uid = st.st_uid;
3338 else
3339 uid = getuid();
3340
3341 /* Shortcut things to avoid NSS lookups */
3342 if (uid == 0)
3343 return strdup("root");
3344
3345 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3346 bufsize = 4096;
3347
3348 if (!(buf = malloc(bufsize)))
3349 return NULL;
3350
3351 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3352 name = strdup(pw->pw_name);
3353 free(buf);
3354 return name;
3355 }
3356
3357 free(buf);
3358
3359 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3360 return NULL;
3361
3362 return name;
3363}
3364
fc116c6a
LP
3365int getttyname_malloc(int fd, char **r) {
3366 char path[PATH_MAX], *c;
618e02c7 3367 int k;
8c6db833
LP
3368
3369 assert(r);
ef2f1067 3370
fc116c6a 3371 if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
618e02c7 3372 return -k;
ef2f1067
LP
3373
3374 char_array_0(path);
3375
fc116c6a 3376 if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
8c6db833
LP
3377 return -ENOMEM;
3378
3379 *r = c;
3380 return 0;
3381}
3382
fc116c6a
LP
3383int getttyname_harder(int fd, char **r) {
3384 int k;
3385 char *s;
3386
3387 if ((k = getttyname_malloc(fd, &s)) < 0)
3388 return k;
3389
3390 if (streq(s, "tty")) {
3391 free(s);
4d6d6518 3392 return get_ctty(0, NULL, r);
fc116c6a
LP
3393 }
3394
3395 *r = s;
3396 return 0;
3397}
3398
4d6d6518 3399int get_ctty_devnr(pid_t pid, dev_t *d) {
fc116c6a 3400 int k;
4d6d6518 3401 char line[LINE_MAX], *p, *fn;
fc116c6a
LP
3402 unsigned long ttynr;
3403 FILE *f;
3404
4d6d6518
LP
3405 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3406 return -ENOMEM;
3407
3408 f = fopen(fn, "re");
3409 free(fn);
3410 if (!f)
fc116c6a
LP
3411 return -errno;
3412
4d6d6518 3413 if (!fgets(line, sizeof(line), f)) {
35d50f55 3414 k = feof(f) ? -EIO : -errno;
fc116c6a
LP
3415 fclose(f);
3416 return k;
3417 }
3418
3419 fclose(f);
3420
4d6d6518
LP
3421 p = strrchr(line, ')');
3422 if (!p)
fc116c6a
LP
3423 return -EIO;
3424
3425 p++;
3426
3427 if (sscanf(p, " "
3428 "%*c " /* state */
3429 "%*d " /* ppid */
3430 "%*d " /* pgrp */
3431 "%*d " /* session */
3432 "%lu ", /* ttynr */
3433 &ttynr) != 1)
3434 return -EIO;
3435
3436 *d = (dev_t) ttynr;
3437 return 0;
3438}
3439
4d6d6518 3440int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
fc116c6a 3441 int k;
20c03b7b 3442 char fn[PATH_MAX], *s, *b, *p;
fc116c6a
LP
3443 dev_t devnr;
3444
3445 assert(r);
3446
4d6d6518
LP
3447 k = get_ctty_devnr(pid, &devnr);
3448 if (k < 0)
fc116c6a
LP
3449 return k;
3450
3451 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3452 char_array_0(fn);
3453
3454 if ((k = readlink_malloc(fn, &s)) < 0) {
3455
3456 if (k != -ENOENT)
3457 return k;
3458
46824d0e
LP
3459 /* This is an ugly hack */
3460 if (major(devnr) == 136) {
3461 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3462 return -ENOMEM;
3463
3464 *r = b;
3465 if (_devnr)
3466 *_devnr = devnr;
3467
3468 return 0;
3469 }
3470
fc116c6a
LP
3471 /* Probably something like the ptys which have no
3472 * symlink in /dev/char. Let's return something
3473 * vaguely useful. */
3474
3475 if (!(b = strdup(fn + 5)))
3476 return -ENOMEM;
3477
3478 *r = b;
46824d0e
LP
3479 if (_devnr)
3480 *_devnr = devnr;
3481
fc116c6a
LP
3482 return 0;
3483 }
3484
3485 if (startswith(s, "/dev/"))
3486 p = s + 5;
3487 else if (startswith(s, "../"))
3488 p = s + 3;
3489 else
3490 p = s;
3491
3492 b = strdup(p);
3493 free(s);
3494
3495 if (!b)
3496 return -ENOMEM;
3497
3498 *r = b;
46824d0e
LP
3499 if (_devnr)
3500 *_devnr = devnr;
3501
fc116c6a
LP
3502 return 0;
3503}
3504
ad293f5a 3505static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) {
8c6db833
LP
3506 DIR *d;
3507 int ret = 0;
3508
3509 assert(fd >= 0);
3510
3511 /* This returns the first error we run into, but nevertheless
3512 * tries to go on */
3513
3514 if (!(d = fdopendir(fd))) {
3515 close_nointr_nofail(fd);
4c633005
LP
3516
3517 return errno == ENOENT ? 0 : -errno;
8c6db833
LP
3518 }
3519
3520 for (;;) {
3521 struct dirent buf, *de;
ad293f5a 3522 bool is_dir, keep_around = false;
8c6db833
LP
3523 int r;
3524
3525 if ((r = readdir_r(d, &buf, &de)) != 0) {
3526 if (ret == 0)
3527 ret = -r;
3528 break;
3529 }
3530
3531 if (!de)
3532 break;
3533
3534 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3535 continue;
3536
3537 if (de->d_type == DT_UNKNOWN) {
3538 struct stat st;
3539
3540 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
4c633005 3541 if (ret == 0 && errno != ENOENT)
8c6db833
LP
3542 ret = -errno;
3543 continue;
3544 }
3545
ad293f5a 3546 if (honour_sticky)
8d53b453
LP
3547 keep_around =
3548 (st.st_uid == 0 || st.st_uid == getuid()) &&
3549 (st.st_mode & S_ISVTX);
ad293f5a 3550
8c6db833 3551 is_dir = S_ISDIR(st.st_mode);
ad293f5a
LP
3552
3553 } else {
3554 if (honour_sticky) {
3555 struct stat st;
3556
3557 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3558 if (ret == 0 && errno != ENOENT)
3559 ret = -errno;
3560 continue;
3561 }
3562
8d53b453
LP
3563 keep_around =
3564 (st.st_uid == 0 || st.st_uid == getuid()) &&
3565 (st.st_mode & S_ISVTX);
ad293f5a
LP
3566 }
3567
8c6db833 3568 is_dir = de->d_type == DT_DIR;
ad293f5a 3569 }
8c6db833
LP
3570
3571 if (is_dir) {
3572 int subdir_fd;
3573
3574 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
4c633005 3575 if (ret == 0 && errno != ENOENT)
8c6db833
LP
3576 ret = -errno;
3577 continue;
3578 }
3579
ad293f5a 3580 if ((r = rm_rf_children(subdir_fd, only_dirs, honour_sticky)) < 0) {
8c6db833
LP
3581 if (ret == 0)
3582 ret = r;
3583 }
3584
ad293f5a
LP
3585 if (!keep_around)
3586 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3587 if (ret == 0 && errno != ENOENT)
3588 ret = -errno;
3589 }
3590
3591 } else if (!only_dirs && !keep_around) {
8c6db833
LP
3592
3593 if (unlinkat(fd, de->d_name, 0) < 0) {
4c633005 3594 if (ret == 0 && errno != ENOENT)
8c6db833
LP
3595 ret = -errno;
3596 }
3597 }
3598 }
3599
3600 closedir(d);
3601
3602 return ret;
3603}
3604
ad293f5a 3605int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
8c6db833
LP
3606 int fd;
3607 int r;
3608
3609 assert(path);
3610
3611 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3612
3613 if (errno != ENOTDIR)
3614 return -errno;
3615
3616 if (delete_root && !only_dirs)
3617 if (unlink(path) < 0)
3618 return -errno;
3619
3620 return 0;
3621 }
3622
ad293f5a
LP
3623 r = rm_rf_children(fd, only_dirs, honour_sticky);
3624
3625 if (delete_root) {
3626
8d53b453 3627 if (honour_sticky && file_is_priv_sticky(path) > 0)
ad293f5a 3628 return r;
8c6db833 3629
e27796a0 3630 if (rmdir(path) < 0 && errno != ENOENT) {
8c6db833
LP
3631 if (r == 0)
3632 r = -errno;
3633 }
ad293f5a 3634 }
8c6db833
LP
3635
3636 return r;
3637}
3638
3639int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3640 assert(path);
3641
3642 /* Under the assumption that we are running privileged we
3643 * first change the access mode and only then hand out
3644 * ownership to avoid a window where access is too open. */
3645
8d53b453
LP
3646 if (mode != (mode_t) -1)
3647 if (chmod(path, mode) < 0)
3648 return -errno;
8c6db833 3649
8d53b453
LP
3650 if (uid != (uid_t) -1 || gid != (gid_t) -1)
3651 if (chown(path, uid, gid) < 0)
3652 return -errno;
8c6db833
LP
3653
3654 return 0;
ef2f1067
LP
3655}
3656
f4b47811
LP
3657int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3658 assert(fd >= 0);
3659
3660 /* Under the assumption that we are running privileged we
3661 * first change the access mode and only then hand out
3662 * ownership to avoid a window where access is too open. */
3663
3664 if (fchmod(fd, mode) < 0)
3665 return -errno;
3666
3667 if (fchown(fd, uid, gid) < 0)
3668 return -errno;
3669
3670 return 0;
3671}
3672
82c121a4
LP
3673cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3674 cpu_set_t *r;
3675 unsigned n = 1024;
3676
3677 /* Allocates the cpuset in the right size */
3678
3679 for (;;) {
3680 if (!(r = CPU_ALLOC(n)))
3681 return NULL;
3682
3683 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3684 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3685
3686 if (ncpus)
3687 *ncpus = n;
3688
3689 return r;
3690 }
3691
3692 CPU_FREE(r);
3693
3694 if (errno != EINVAL)
3695 return NULL;
3696
3697 n *= 2;
3698 }
3699}
3700
67e5cc4f 3701void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
81beb750
LP
3702 char *s = NULL, *spaces = NULL, *e;
3703 int fd = -1, c;
3704 size_t emax, sl, left;
3705 struct iovec iovec[5];
3706 int n = 0;
9e58ff9c
LP
3707
3708 assert(format);
3709
3710 /* This independent of logging, as status messages are
3711 * optional and go exclusively to the console. */
3712
3713 if (vasprintf(&s, format, ap) < 0)
3714 goto finish;
3715
67e5cc4f 3716 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
81beb750 3717 if (fd < 0)
9e58ff9c
LP
3718 goto finish;
3719
67e5cc4f
LP
3720 if (ellipse) {
3721 c = fd_columns(fd);
3722 if (c <= 0)
3723 c = 80;
81beb750 3724
67e5cc4f
LP
3725 if (status) {
3726 sl = 2 + 6 + 1; /* " [" status "]" */
3727 emax = (size_t) c > sl ? c - sl - 1 : 0;
3728 } else
3729 emax = c - 1;
81beb750 3730
67e5cc4f
LP
3731 e = ellipsize(s, emax, 75);
3732 if (e) {
3733 free(s);
3734 s = e;
3735 }
81beb750
LP
3736 }
3737
3738 zero(iovec);
3739 IOVEC_SET_STRING(iovec[n++], s);
3740
67e5cc4f
LP
3741 if (ellipse) {
3742 sl = strlen(s);
3743 left = emax > sl ? emax - sl : 0;
3744 if (left > 0) {
3745 spaces = malloc(left);
3746 if (spaces) {
3747 memset(spaces, ' ', left);
3748 iovec[n].iov_base = spaces;
3749 iovec[n].iov_len = left;
3750 n++;
3751 }
81beb750
LP
3752 }
3753 }
3754
3755 if (status) {
3756 IOVEC_SET_STRING(iovec[n++], " [");
3757 IOVEC_SET_STRING(iovec[n++], status);
3758 IOVEC_SET_STRING(iovec[n++], "]\n");
3759 } else
3760 IOVEC_SET_STRING(iovec[n++], "\n");
3761
3762 writev(fd, iovec, n);
9e58ff9c
LP
3763
3764finish:
3765 free(s);
81beb750 3766 free(spaces);
9e58ff9c
LP
3767
3768 if (fd >= 0)
3769 close_nointr_nofail(fd);
3770}
3771
67e5cc4f 3772void status_printf(const char *status, bool ellipse, const char *format, ...) {
c846ff47
LP
3773 va_list ap;
3774
3775 assert(format);
3776
3777 va_start(ap, format);
67e5cc4f 3778 status_vprintf(status, ellipse, format, ap);
c846ff47
LP
3779 va_end(ap);
3780}
3781
3782void status_welcome(void) {
10aa7034
LP
3783 char *pretty_name = NULL, *ansi_color = NULL;
3784 const char *const_pretty = NULL, *const_color = NULL;
3785 int r;
c846ff47 3786
10aa7034
LP
3787 if ((r = parse_env_file("/etc/os-release", NEWLINE,
3788 "PRETTY_NAME", &pretty_name,
3789 "ANSI_COLOR", &ansi_color,
3790 NULL)) < 0) {
c846ff47 3791
10aa7034
LP
3792 if (r != -ENOENT)
3793 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3794 }
c846ff47 3795
10aa7034
LP
3796 if (!pretty_name && !const_pretty)
3797 const_pretty = "Linux";
3798
3799 if (!ansi_color && !const_color)
3800 const_color = "1";
3801
81beb750 3802 status_printf(NULL,
67e5cc4f 3803 false,
81beb750 3804 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
10aa7034
LP
3805 const_color ? const_color : ansi_color,
3806 const_pretty ? const_pretty : pretty_name);
86a3475b
LP
3807
3808 free(ansi_color);
3809 free(pretty_name);
c846ff47
LP
3810}
3811
fab56fc5
LP
3812char *replace_env(const char *format, char **env) {
3813 enum {
3814 WORD,
c24eb49e 3815 CURLY,
fab56fc5
LP
3816 VARIABLE
3817 } state = WORD;
3818
3819 const char *e, *word = format;
3820 char *r = NULL, *k;
3821
3822 assert(format);
3823
3824 for (e = format; *e; e ++) {
3825
3826 switch (state) {
3827
3828 case WORD:
3829 if (*e == '$')
c24eb49e 3830 state = CURLY;
fab56fc5
LP
3831 break;
3832
c24eb49e
LP
3833 case CURLY:
3834 if (*e == '{') {
fab56fc5
LP
3835 if (!(k = strnappend(r, word, e-word-1)))
3836 goto fail;
3837
3838 free(r);
3839 r = k;
3840
3841 word = e-1;
3842 state = VARIABLE;
3843
3844 } else if (*e == '$') {
3845 if (!(k = strnappend(r, word, e-word)))
3846 goto fail;
3847
3848 free(r);
3849 r = k;
3850
3851 word = e+1;
3852 state = WORD;
3853 } else
3854 state = WORD;
3855 break;
3856
3857 case VARIABLE:
c24eb49e 3858 if (*e == '}') {
b95cf362 3859 const char *t;
fab56fc5 3860
b95cf362
LP
3861 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3862 t = "";
fab56fc5 3863
b95cf362
LP
3864 if (!(k = strappend(r, t)))
3865 goto fail;
fab56fc5 3866
b95cf362
LP
3867 free(r);
3868 r = k;
fab56fc5 3869
b95cf362 3870 word = e+1;
fab56fc5
LP
3871 state = WORD;
3872 }
3873 break;
3874 }
3875 }
3876
3877 if (!(k = strnappend(r, word, e-word)))
3878 goto fail;
3879
3880 free(r);
3881 return k;
3882
3883fail:
3884 free(r);
3885 return NULL;
3886}
3887
3888char **replace_env_argv(char **argv, char **env) {
3889 char **r, **i;
c24eb49e
LP
3890 unsigned k = 0, l = 0;
3891
3892 l = strv_length(argv);
fab56fc5 3893
c24eb49e 3894 if (!(r = new(char*, l+1)))
fab56fc5
LP
3895 return NULL;
3896
3897 STRV_FOREACH(i, argv) {
c24eb49e
LP
3898
3899 /* If $FOO appears as single word, replace it by the split up variable */
b95cf362
LP
3900 if ((*i)[0] == '$' && (*i)[1] != '{') {
3901 char *e;
3902 char **w, **m;
3903 unsigned q;
c24eb49e 3904
b95cf362 3905 if ((e = strv_env_get(env, *i+1))) {
c24eb49e
LP
3906
3907 if (!(m = strv_split_quoted(e))) {
3908 r[k] = NULL;
3909 strv_free(r);
3910 return NULL;
3911 }
b95cf362
LP
3912 } else
3913 m = NULL;
c24eb49e 3914
b95cf362
LP
3915 q = strv_length(m);
3916 l = l + q - 1;
c24eb49e 3917
b95cf362
LP
3918 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3919 r[k] = NULL;
3920 strv_free(r);
3921 strv_free(m);
3922 return NULL;
3923 }
c24eb49e 3924
b95cf362
LP
3925 r = w;
3926 if (m) {
c24eb49e
LP
3927 memcpy(r + k, m, q * sizeof(char*));
3928 free(m);
c24eb49e 3929 }
b95cf362
LP
3930
3931 k += q;
3932 continue;
c24eb49e
LP
3933 }
3934
3935 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
fab56fc5
LP
3936 if (!(r[k++] = replace_env(*i, env))) {
3937 strv_free(r);
3938 return NULL;
3939 }
3940 }
3941
3942 r[k] = NULL;
3943 return r;
3944}
3945
81beb750
LP
3946int fd_columns(int fd) {
3947 struct winsize ws;
3948 zero(ws);
3949
3950 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3951 return -errno;
3952
3953 if (ws.ws_col <= 0)
3954 return -EIO;
3955
3956 return ws.ws_col;
3957}
3958
72f59706 3959unsigned columns(void) {
fa776d8e
LP
3960 static __thread int parsed_columns = 0;
3961 const char *e;
3962
3bfc7184 3963 if (_likely_(parsed_columns > 0))
fa776d8e
LP
3964 return parsed_columns;
3965
81beb750
LP
3966 e = getenv("COLUMNS");
3967 if (e)
fa776d8e
LP
3968 parsed_columns = atoi(e);
3969
81beb750
LP
3970 if (parsed_columns <= 0)
3971 parsed_columns = fd_columns(STDOUT_FILENO);
fa776d8e
LP
3972
3973 if (parsed_columns <= 0)
3974 parsed_columns = 80;
3975
3976 return parsed_columns;
3977}
3978
8f2d43a0
LP
3979int fd_lines(int fd) {
3980 struct winsize ws;
3981 zero(ws);
3982
3983 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3984 return -errno;
3985
3986 if (ws.ws_row <= 0)
3987 return -EIO;
3988
3989 return ws.ws_row;
3990}
3991
3992unsigned lines(void) {
3993 static __thread int parsed_lines = 0;
3994 const char *e;
3995
3996 if (_likely_(parsed_lines > 0))
3997 return parsed_lines;
3998
3999 e = getenv("LINES");
4000 if (e)
4001 parsed_lines = atoi(e);
4002
4003 if (parsed_lines <= 0)
4004 parsed_lines = fd_lines(STDOUT_FILENO);
4005
4006 if (parsed_lines <= 0)
4007 parsed_lines = 25;
4008
4009 return parsed_lines;
4010}
4011
b4f10a5e
LP
4012int running_in_chroot(void) {
4013 struct stat a, b;
4014
4015 zero(a);
4016 zero(b);
4017
4018 /* Only works as root */
4019
4020 if (stat("/proc/1/root", &a) < 0)
4021 return -errno;
4022
4023 if (stat("/", &b) < 0)
4024 return -errno;
4025
4026 return
4027 a.st_dev != b.st_dev ||
4028 a.st_ino != b.st_ino;
4029}
4030
72f59706
LP
4031char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
4032 size_t x;
8fe914ec
LP
4033 char *r;
4034
4035 assert(s);
4036 assert(percent <= 100);
72f59706 4037 assert(new_length >= 3);
8fe914ec 4038
72f59706
LP
4039 if (old_length <= 3 || old_length <= new_length)
4040 return strndup(s, old_length);
8fe914ec 4041
72f59706
LP
4042 r = new0(char, new_length+1);
4043 if (!r)
8fe914ec
LP
4044 return r;
4045
72f59706 4046 x = (new_length * percent) / 100;
8fe914ec 4047
72f59706
LP
4048 if (x > new_length - 3)
4049 x = new_length - 3;
8fe914ec
LP
4050
4051 memcpy(r, s, x);
4052 r[x] = '.';
4053 r[x+1] = '.';
4054 r[x+2] = '.';
4055 memcpy(r + x + 3,
72f59706
LP
4056 s + old_length - (new_length - x - 3),
4057 new_length - x - 3);
8fe914ec
LP
4058
4059 return r;
4060}
4061
72f59706
LP
4062char *ellipsize(const char *s, size_t length, unsigned percent) {
4063 return ellipsize_mem(s, strlen(s), length, percent);
4064}
4065
f6144808
LP
4066int touch(const char *path) {
4067 int fd;
4068
4069 assert(path);
4070
14f3c825 4071 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
f6144808
LP
4072 return -errno;
4073
4074 close_nointr_nofail(fd);
4075 return 0;
4076}
afea26ad 4077
97c4a07d 4078char *unquote(const char *s, const char* quotes) {
11ce3427
LP
4079 size_t l;
4080 assert(s);
4081
31ed59c5
LP
4082 l = strlen(s);
4083 if (l < 2)
11ce3427
LP
4084 return strdup(s);
4085
97c4a07d 4086 if (strchr(quotes, s[0]) && s[l-1] == s[0])
11ce3427
LP
4087 return strndup(s+1, l-2);
4088
4089 return strdup(s);
4090}
4091
5f7c426e
LP
4092char *normalize_env_assignment(const char *s) {
4093 char *name, *value, *p, *r;
4094
4095 p = strchr(s, '=');
4096
4097 if (!p) {
4098 if (!(r = strdup(s)))
4099 return NULL;
4100
4101 return strstrip(r);
4102 }
4103
4104 if (!(name = strndup(s, p - s)))
4105 return NULL;
4106
4107 if (!(p = strdup(p+1))) {
4108 free(name);
4109 return NULL;
4110 }
4111
4112 value = unquote(strstrip(p), QUOTES);
4113 free(p);
4114
4115 if (!value) {
5f7c426e
LP
4116 free(name);
4117 return NULL;
4118 }
4119
4120 if (asprintf(&r, "%s=%s", name, value) < 0)
4121 r = NULL;
4122
4123 free(value);
4124 free(name);
4125
4126 return r;
4127}
4128
8e12a6ae 4129int wait_for_terminate(pid_t pid, siginfo_t *status) {
1968a360
LP
4130 siginfo_t dummy;
4131
2e78aa99 4132 assert(pid >= 1);
1968a360
LP
4133
4134 if (!status)
4135 status = &dummy;
2e78aa99
LP
4136
4137 for (;;) {
8e12a6ae
LP
4138 zero(*status);
4139
4140 if (waitid(P_PID, pid, status, WEXITED) < 0) {
2e78aa99
LP
4141
4142 if (errno == EINTR)
4143 continue;
4144
4145 return -errno;
4146 }
4147
4148 return 0;
4149 }
4150}
4151
97c4a07d
LP
4152int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4153 int r;
4154 siginfo_t status;
4155
4156 assert(name);
4157 assert(pid > 1);
4158
4159 if ((r = wait_for_terminate(pid, &status)) < 0) {
4160 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4161 return r;
4162 }
4163
4164 if (status.si_code == CLD_EXITED) {
4165 if (status.si_status != 0) {
4166 log_warning("%s failed with error code %i.", name, status.si_status);
0a27cf3f 4167 return status.si_status;
97c4a07d
LP
4168 }
4169
4170 log_debug("%s succeeded.", name);
4171 return 0;
4172
4173 } else if (status.si_code == CLD_KILLED ||
4174 status.si_code == CLD_DUMPED) {
4175
4176 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4177 return -EPROTO;
4178 }
4179
4180 log_warning("%s failed due to unknown reason.", name);
4181 return -EPROTO;
4182
4183}
4184
6a39419f 4185_noreturn_ void freeze(void) {
720ce21d
LP
4186
4187 /* Make sure nobody waits for us on a socket anymore */
4188 close_all_fds(NULL, 0);
4189
c29597a1
LP
4190 sync();
4191
3c14d26c
LP
4192 for (;;)
4193 pause();
4194}
4195
00dc5d76
LP
4196bool null_or_empty(struct stat *st) {
4197 assert(st);
4198
4199 if (S_ISREG(st->st_mode) && st->st_size <= 0)
4200 return true;
4201
c8f26f42 4202 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
00dc5d76
LP
4203 return true;
4204
4205 return false;
4206}
4207
83096483
LP
4208int null_or_empty_path(const char *fn) {
4209 struct stat st;
4210
4211 assert(fn);
4212
4213 if (stat(fn, &st) < 0)
4214 return -errno;
4215
4216 return null_or_empty(&st);
4217}
4218
a247755d 4219DIR *xopendirat(int fd, const char *name, int flags) {
c4731d11
LP
4220 int nfd;
4221 DIR *d;
4222
4223 if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4224 return NULL;
4225
4226 if (!(d = fdopendir(nfd))) {
4227 close_nointr_nofail(nfd);
4228 return NULL;
4229 }
4230
4231 return d;
3b63d2d3
LP
4232}
4233
8a0867d6
LP
4234int signal_from_string_try_harder(const char *s) {
4235 int signo;
4236 assert(s);
4237
4238 if ((signo = signal_from_string(s)) <= 0)
4239 if (startswith(s, "SIG"))
4240 return signal_from_string(s+3);
4241
4242 return signo;
4243}
4244
10717a1a
LP
4245void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4246
4247 assert(f);
4248 assert(name);
4249 assert(t);
4250
4251 if (!dual_timestamp_is_set(t))
4252 return;
4253
4254 fprintf(f, "%s=%llu %llu\n",
4255 name,
4256 (unsigned long long) t->realtime,
4257 (unsigned long long) t->monotonic);
4258}
4259
799fd0fd 4260void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
10717a1a
LP
4261 unsigned long long a, b;
4262
10717a1a
LP
4263 assert(value);
4264 assert(t);
4265
4266 if (sscanf(value, "%lli %llu", &a, &b) != 2)
4267 log_debug("Failed to parse finish timestamp value %s", value);
4268 else {
4269 t->realtime = a;
4270 t->monotonic = b;
4271 }
4272}
4273
e23a0ce8
LP
4274char *fstab_node_to_udev_node(const char *p) {
4275 char *dn, *t, *u;
4276 int r;
4277
4278 /* FIXME: to follow udev's logic 100% we need to leave valid
4279 * UTF8 chars unescaped */
4280
4281 if (startswith(p, "LABEL=")) {
4282
4283 if (!(u = unquote(p+6, "\"\'")))
4284 return NULL;
4285
4286 t = xescape(u, "/ ");
4287 free(u);
4288
4289 if (!t)
4290 return NULL;
4291
4292 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4293 free(t);
4294
4295 if (r < 0)
4296 return NULL;
4297
4298 return dn;
4299 }
4300
4301 if (startswith(p, "UUID=")) {
4302
4303 if (!(u = unquote(p+5, "\"\'")))
4304 return NULL;
4305
4306 t = xescape(u, "/ ");
4307 free(u);
4308
4309 if (!t)
4310 return NULL;
4311
0058d7b9 4312 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
e23a0ce8
LP
4313 free(t);
4314
4315 if (r < 0)
4316 return NULL;
4317
4318 return dn;
4319 }
4320
4321 return strdup(p);
4322}
4323
e9ddabc2
LP
4324void filter_environ(const char *prefix) {
4325 int i, j;
4326 assert(prefix);
4327
4328 if (!environ)
4329 return;
4330
4331 for (i = 0, j = 0; environ[i]; i++) {
4332
4333 if (startswith(environ[i], prefix))
4334 continue;
4335
4336 environ[j++] = environ[i];
4337 }
4338
4339 environ[j] = NULL;
4340}
4341
f212ac12
LP
4342bool tty_is_vc(const char *tty) {
4343 assert(tty);
4344
4345 if (startswith(tty, "/dev/"))
4346 tty += 5;
4347
98a28fef
LP
4348 return vtnr_from_tty(tty) >= 0;
4349}
4350
4351int vtnr_from_tty(const char *tty) {
4352 int i, r;
4353
4354 assert(tty);
4355
4356 if (startswith(tty, "/dev/"))
4357 tty += 5;
4358
4359 if (!startswith(tty, "tty") )
4360 return -EINVAL;
4361
4362 if (tty[3] < '0' || tty[3] > '9')
4363 return -EINVAL;
4364
4365 r = safe_atoi(tty+3, &i);
4366 if (r < 0)
4367 return r;
4368
4369 if (i < 0 || i > 63)
4370 return -EINVAL;
4371
4372 return i;
f212ac12
LP
4373}
4374
3043935f 4375bool tty_is_vc_resolve(const char *tty) {
3030ccd7 4376 char *active = NULL;
3043935f 4377 bool b;
3030ccd7 4378
e3aa71c3
LP
4379 assert(tty);
4380
4381 if (startswith(tty, "/dev/"))
4382 tty += 5;
4383
3043935f 4384 /* Resolve where /dev/console is pointing to */
3030ccd7
LP
4385 if (streq(tty, "console"))
4386 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
079a09fb
LP
4387 /* If multiple log outputs are configured the
4388 * last one is what /dev/console points to */
3043935f
LP
4389 tty = strrchr(active, ' ');
4390 if (tty)
079a09fb
LP
4391 tty++;
4392 else
4393 tty = active;
3030ccd7
LP
4394 }
4395
3043935f 4396 b = tty_is_vc(tty);
3030ccd7 4397 free(active);
e3aa71c3 4398
3043935f
LP
4399 return b;
4400}
4401
4402const char *default_term_for_tty(const char *tty) {
4403 assert(tty);
4404
4405 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt100";
e3aa71c3
LP
4406}
4407
87d2c1ff 4408bool dirent_is_file(const struct dirent *de) {
fb19a739
LP
4409 assert(de);
4410
4411 if (ignore_file(de->d_name))
4412 return false;
4413
4414 if (de->d_type != DT_REG &&
4415 de->d_type != DT_LNK &&
4416 de->d_type != DT_UNKNOWN)
4417 return false;
4418
4419 return true;
4420}
4421
87d2c1ff
LP
4422bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4423 assert(de);
4424
4425 if (!dirent_is_file(de))
4426 return false;
4427
4428 return endswith(de->d_name, suffix);
4429}
4430
83cc030f
LP
4431void execute_directory(const char *directory, DIR *d, char *argv[]) {
4432 DIR *_d = NULL;
4433 struct dirent *de;
4434 Hashmap *pids = NULL;
4435
4436 assert(directory);
4437
4438 /* Executes all binaries in a directory in parallel and waits
4439 * until all they all finished. */
4440
4441 if (!d) {
4442 if (!(_d = opendir(directory))) {
4443
4444 if (errno == ENOENT)
4445 return;
4446
4447 log_error("Failed to enumerate directory %s: %m", directory);
4448 return;
4449 }
4450
4451 d = _d;
4452 }
4453
4454 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4455 log_error("Failed to allocate set.");
4456 goto finish;
4457 }
4458
4459 while ((de = readdir(d))) {
4460 char *path;
4461 pid_t pid;
4462 int k;
4463
fb19a739 4464 if (!dirent_is_file(de))
83cc030f
LP
4465 continue;
4466
4467 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4468 log_error("Out of memory");
4469 continue;
4470 }
4471
4472 if ((pid = fork()) < 0) {
4473 log_error("Failed to fork: %m");
4474 free(path);
4475 continue;
4476 }
4477
4478 if (pid == 0) {
4479 char *_argv[2];
4480 /* Child */
4481
4482 if (!argv) {
4483 _argv[0] = path;
4484 _argv[1] = NULL;
4485 argv = _argv;
4486 } else
4487 if (!argv[0])
4488 argv[0] = path;
4489
4490 execv(path, argv);
4491
4492 log_error("Failed to execute %s: %m", path);
4493 _exit(EXIT_FAILURE);
4494 }
4495
4496 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4497
4498 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4499 log_error("Failed to add PID to set: %s", strerror(-k));
4500 free(path);
4501 }
4502 }
4503
4504 while (!hashmap_isempty(pids)) {
ec3f9b53 4505 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
83cc030f
LP
4506 siginfo_t si;
4507 char *path;
4508
4509 zero(si);
ec3f9b53 4510 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
83cc030f
LP
4511
4512 if (errno == EINTR)
4513 continue;
4514
4515 log_error("waitid() failed: %m");
4516 goto finish;
4517 }
4518
4519 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4520 if (!is_clean_exit(si.si_code, si.si_status)) {
4521 if (si.si_code == CLD_EXITED)
4522 log_error("%s exited with exit status %i.", path, si.si_status);
4523 else
4524 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4525 } else
4526 log_debug("%s exited successfully.", path);
4527
4528 free(path);
4529 }
4530 }
4531
4532finish:
4533 if (_d)
4534 closedir(_d);
4535
4536 if (pids)
4537 hashmap_free_free(pids);
4538}
4539
430c18ed
LP
4540int kill_and_sigcont(pid_t pid, int sig) {
4541 int r;
4542
4543 r = kill(pid, sig) < 0 ? -errno : 0;
4544
4545 if (r >= 0)
4546 kill(pid, SIGCONT);
4547
4548 return r;
4549}
4550
05feefe0
LP
4551bool nulstr_contains(const char*nulstr, const char *needle) {
4552 const char *i;
4553
4554 if (!nulstr)
4555 return false;
4556
4557 NULSTR_FOREACH(i, nulstr)
4558 if (streq(i, needle))
4559 return true;
4560
4561 return false;
4562}
4563
6faa1114 4564bool plymouth_running(void) {
9408a2d2 4565 return access("/run/plymouth/pid", F_OK) >= 0;
6faa1114
LP
4566}
4567
7c3b203c
LP
4568void parse_syslog_priority(char **p, int *priority) {
4569 int a = 0, b = 0, c = 0;
4570 int k;
4571
4572 assert(p);
4573 assert(*p);
4574 assert(priority);
4575
4576 if ((*p)[0] != '<')
4577 return;
4578
4579 if (!strchr(*p, '>'))
4580 return;
4581
4582 if ((*p)[2] == '>') {
4583 c = undecchar((*p)[1]);
4584 k = 3;
4585 } else if ((*p)[3] == '>') {
4586 b = undecchar((*p)[1]);
4587 c = undecchar((*p)[2]);
4588 k = 4;
4589 } else if ((*p)[4] == '>') {
4590 a = undecchar((*p)[1]);
4591 b = undecchar((*p)[2]);
4592 c = undecchar((*p)[3]);
4593 k = 5;
4594 } else
4595 return;
4596
4597 if (a < 0 || b < 0 || c < 0)
4598 return;
4599
4600 *priority = a*100+b*10+c;
4601 *p += k;
4602}
4603
87d2c1ff
LP
4604void skip_syslog_pid(char **buf) {
4605 char *p;
4606
4607 assert(buf);
4608 assert(*buf);
4609
4610 p = *buf;
4611
4612 if (*p != '[')
4613 return;
4614
4615 p++;
4616 p += strspn(p, "0123456789");
4617
4618 if (*p != ']')
4619 return;
4620
4621 p++;
4622
4623 *buf = p;
4624}
4625
4626void skip_syslog_date(char **buf) {
4627 enum {
4628 LETTER,
4629 SPACE,
4630 NUMBER,
4631 SPACE_OR_NUMBER,
4632 COLON
4633 } sequence[] = {
4634 LETTER, LETTER, LETTER,
4635 SPACE,
4636 SPACE_OR_NUMBER, NUMBER,
4637 SPACE,
4638 SPACE_OR_NUMBER, NUMBER,
4639 COLON,
4640 SPACE_OR_NUMBER, NUMBER,
4641 COLON,
4642 SPACE_OR_NUMBER, NUMBER,
4643 SPACE
4644 };
4645
4646 char *p;
4647 unsigned i;
4648
4649 assert(buf);
4650 assert(*buf);
4651
4652 p = *buf;
4653
4654 for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
4655
4656 if (!*p)
4657 return;
4658
4659 switch (sequence[i]) {
4660
4661 case SPACE:
4662 if (*p != ' ')
4663 return;
4664 break;
4665
4666 case SPACE_OR_NUMBER:
4667 if (*p == ' ')
4668 break;
4669
4670 /* fall through */
4671
4672 case NUMBER:
4673 if (*p < '0' || *p > '9')
4674 return;
4675
4676 break;
4677
4678 case LETTER:
4679 if (!(*p >= 'A' && *p <= 'Z') &&
4680 !(*p >= 'a' && *p <= 'z'))
4681 return;
4682
4683 break;
4684
4685 case COLON:
4686 if (*p != ':')
4687 return;
4688 break;
4689
4690 }
4691 }
4692
4693 *buf = p;
4694}
4695
ac123445
LP
4696int have_effective_cap(int value) {
4697 cap_t cap;
4698 cap_flag_value_t fv;
4699 int r;
4700
4701 if (!(cap = cap_get_proc()))
4702 return -errno;
4703
4704 if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4705 r = -errno;
4706 else
4707 r = fv == CAP_SET;
4708
4709 cap_free(cap);
4710 return r;
4711}
4712
9beb3f4d
LP
4713char* strshorten(char *s, size_t l) {
4714 assert(s);
4715
4716 if (l < strlen(s))
4717 s[l] = 0;
4718
4719 return s;
4720}
4721
4722static bool hostname_valid_char(char c) {
4723 return
4724 (c >= 'a' && c <= 'z') ||
4725 (c >= 'A' && c <= 'Z') ||
4726 (c >= '0' && c <= '9') ||
4727 c == '-' ||
4728 c == '_' ||
4729 c == '.';
4730}
4731
4732bool hostname_is_valid(const char *s) {
4733 const char *p;
4734
4735 if (isempty(s))
4736 return false;
4737
4738 for (p = s; *p; p++)
4739 if (!hostname_valid_char(*p))
4740 return false;
4741
4742 if (p-s > HOST_NAME_MAX)
4743 return false;
4744
4745 return true;
4746}
4747
4748char* hostname_cleanup(char *s) {
4749 char *p, *d;
4750
4751 for (p = s, d = s; *p; p++)
4752 if ((*p >= 'a' && *p <= 'z') ||
4753 (*p >= 'A' && *p <= 'Z') ||
4754 (*p >= '0' && *p <= '9') ||
4755 *p == '-' ||
4756 *p == '_' ||
4757 *p == '.')
4758 *(d++) = *p;
4759
4760 *d = 0;
4761
4762 strshorten(s, HOST_NAME_MAX);
4763 return s;
4764}
4765
1325aa42
LP
4766int pipe_eof(int fd) {
4767 struct pollfd pollfd;
4768 int r;
4769
4770 zero(pollfd);
4771 pollfd.fd = fd;
4772 pollfd.events = POLLIN|POLLHUP;
4773
4774 r = poll(&pollfd, 1, 0);
4775 if (r < 0)
4776 return -errno;
4777
4778 if (r == 0)
4779 return 0;
4780
4781 return pollfd.revents & POLLHUP;
4782}
4783
8f2d43a0 4784int fd_wait_for_event(int fd, int event, usec_t t) {
df50185b
LP
4785 struct pollfd pollfd;
4786 int r;
4787
4788 zero(pollfd);
4789 pollfd.fd = fd;
4790 pollfd.events = event;
4791
8f2d43a0 4792 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
df50185b
LP
4793 if (r < 0)
4794 return -errno;
4795
4796 if (r == 0)
4797 return 0;
4798
4799 return pollfd.revents;
4800}
4801
5a3ab509
LP
4802int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4803 FILE *f;
4804 char *t;
4805 const char *fn;
4806 size_t k;
4807 int fd;
4808
4809 assert(path);
4810 assert(_f);
4811 assert(_temp_path);
4812
4813 t = new(char, strlen(path) + 1 + 6 + 1);
4814 if (!t)
4815 return -ENOMEM;
4816
4817 fn = file_name_from_path(path);
4818 k = fn-path;
4819 memcpy(t, path, k);
4820 t[k] = '.';
4821 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4822
4823 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4824 if (fd < 0) {
4825 free(t);
4826 return -errno;
4827 }
4828
4829 f = fdopen(fd, "we");
4830 if (!f) {
4831 unlink(t);
4832 free(t);
4833 return -errno;
4834 }
4835
4836 *_f = f;
4837 *_temp_path = t;
4838
4839 return 0;
4840}
4841
6ea832a2 4842int terminal_vhangup_fd(int fd) {
5a3ab509
LP
4843 assert(fd >= 0);
4844
6ea832a2
LP
4845 if (ioctl(fd, TIOCVHANGUP) < 0)
4846 return -errno;
4847
4848 return 0;
4849}
4850
4851int terminal_vhangup(const char *name) {
4852 int fd, r;
4853
4854 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4855 if (fd < 0)
4856 return fd;
4857
4858 r = terminal_vhangup_fd(fd);
4859 close_nointr_nofail(fd);
4860
4861 return r;
4862}
4863
4864int vt_disallocate(const char *name) {
4865 int fd, r;
4866 unsigned u;
6ea832a2
LP
4867
4868 /* Deallocate the VT if possible. If not possible
4869 * (i.e. because it is the active one), at least clear it
4870 * entirely (including the scrollback buffer) */
4871
b83bc4e9
LP
4872 if (!startswith(name, "/dev/"))
4873 return -EINVAL;
4874
4875 if (!tty_is_vc(name)) {
4876 /* So this is not a VT. I guess we cannot deallocate
4877 * it then. But let's at least clear the screen */
4878
4879 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4880 if (fd < 0)
4881 return fd;
4882
8585357a
LP
4883 loop_write(fd,
4884 "\033[r" /* clear scrolling region */
4885 "\033[H" /* move home */
4886 "\033[2J", /* clear screen */
4887 10, false);
b83bc4e9
LP
4888 close_nointr_nofail(fd);
4889
4890 return 0;
4891 }
6ea832a2
LP
4892
4893 if (!startswith(name, "/dev/tty"))
4894 return -EINVAL;
4895
4896 r = safe_atou(name+8, &u);
4897 if (r < 0)
4898 return r;
4899
4900 if (u <= 0)
b83bc4e9 4901 return -EINVAL;
6ea832a2 4902
b83bc4e9 4903 /* Try to deallocate */
6ea832a2
LP
4904 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4905 if (fd < 0)
4906 return fd;
4907
4908 r = ioctl(fd, VT_DISALLOCATE, u);
b83bc4e9 4909 close_nointr_nofail(fd);
6ea832a2 4910
b83bc4e9
LP
4911 if (r >= 0)
4912 return 0;
6ea832a2 4913
b83bc4e9 4914 if (errno != EBUSY)
6ea832a2 4915 return -errno;
6ea832a2 4916
b83bc4e9
LP
4917 /* Couldn't deallocate, so let's clear it fully with
4918 * scrollback */
4919 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
6ea832a2 4920 if (fd < 0)
b83bc4e9 4921 return fd;
6ea832a2 4922
8585357a
LP
4923 loop_write(fd,
4924 "\033[r" /* clear scrolling region */
4925 "\033[H" /* move home */
4926 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4927 10, false);
b83bc4e9 4928 close_nointr_nofail(fd);
6ea832a2 4929
b83bc4e9 4930 return 0;
6ea832a2
LP
4931}
4932
db1413d7
KS
4933static int files_add(Hashmap *h, const char *path, const char *suffix) {
4934 DIR *dir;
f782b8d0 4935 struct dirent buffer, *de;
db1413d7
KS
4936 int r = 0;
4937
4938 dir = opendir(path);
4939 if (!dir) {
4940 if (errno == ENOENT)
4941 return 0;
4942 return -errno;
4943 }
4944
f782b8d0
LP
4945 for (;;) {
4946 int k;
223a3558 4947 char *p, *f;
f782b8d0
LP
4948
4949 k = readdir_r(dir, &buffer, &de);
4950 if (k != 0) {
4951 r = -k;
4952 goto finish;
4953 }
4954
4955 if (!de)
4956 break;
db1413d7 4957
87d2c1ff 4958 if (!dirent_is_file_with_suffix(de, suffix))
db1413d7
KS
4959 continue;
4960
223a3558 4961 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
db1413d7
KS
4962 r = -ENOMEM;
4963 goto finish;
4964 }
4965
223a3558
KS
4966 f = canonicalize_file_name(p);
4967 if (!f) {
4968 log_error("Failed to canonicalize file name '%s': %m", p);
4969 free(p);
4970 continue;
4971 }
4972 free(p);
4973
db1413d7 4974 log_debug("found: %s\n", f);
f782b8d0 4975 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
db1413d7
KS
4976 free(f);
4977 }
4978
4979finish:
4980 closedir(dir);
4981 return r;
4982}
4983
4984static int base_cmp(const void *a, const void *b) {
4985 const char *s1, *s2;
4986
4987 s1 = *(char * const *)a;
4988 s2 = *(char * const *)b;
4989 return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4990}
4991
44143309 4992int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
223a3558
KS
4993 Hashmap *fh = NULL;
4994 char **dirs = NULL;
db1413d7 4995 char **files = NULL;
223a3558 4996 char **p;
db1413d7 4997 va_list ap;
44143309 4998 int r = 0;
db1413d7 4999
223a3558
KS
5000 va_start(ap, dir);
5001 dirs = strv_new_ap(dir, ap);
5002 va_end(ap);
5003 if (!dirs) {
5004 r = -ENOMEM;
5005 goto finish;
5006 }
5007 if (!strv_path_canonicalize(dirs)) {
5008 r = -ENOMEM;
5009 goto finish;
5010 }
5011 if (!strv_uniq(dirs)) {
5012 r = -ENOMEM;
5013 goto finish;
5014 }
5015
db1413d7
KS
5016 fh = hashmap_new(string_hash_func, string_compare_func);
5017 if (!fh) {
44143309 5018 r = -ENOMEM;
db1413d7
KS
5019 goto finish;
5020 }
5021
223a3558
KS
5022 STRV_FOREACH(p, dirs) {
5023 if (files_add(fh, *p, suffix) < 0) {
db1413d7 5024 log_error("Failed to search for files.");
44143309 5025 r = -EINVAL;
db1413d7
KS
5026 goto finish;
5027 }
db1413d7 5028 }
db1413d7
KS
5029
5030 files = hashmap_get_strv(fh);
5031 if (files == NULL) {
5032 log_error("Failed to compose list of files.");
44143309 5033 r = -ENOMEM;
db1413d7
KS
5034 goto finish;
5035 }
5036
5037 qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
8d0e38a2 5038
db1413d7 5039finish:
223a3558 5040 strv_free(dirs);
db1413d7 5041 hashmap_free(fh);
44143309
KS
5042 *strv = files;
5043 return r;
db1413d7 5044}
7948c4df 5045
2076cf88 5046int hwclock_is_localtime(void) {
7948c4df 5047 FILE *f;
7948c4df
KS
5048 bool local = false;
5049
5050 /*
5051 * The third line of adjtime is "UTC" or "LOCAL" or nothing.
5052 * # /etc/adjtime
2076cf88 5053 * 0.0 0 0
7948c4df
KS
5054 * 0
5055 * UTC
5056 */
5057 f = fopen("/etc/adjtime", "re");
5058 if (f) {
2076cf88
LP
5059 char line[LINE_MAX];
5060 bool b;
5061
5062 b = fgets(line, sizeof(line), f) &&
5063 fgets(line, sizeof(line), f) &&
5064 fgets(line, sizeof(line), f);
5065
7948c4df 5066 fclose(f);
2076cf88
LP
5067
5068 if (!b)
5069 return -EIO;
5070
5071
5072 truncate_nl(line);
5073 local = streq(line, "LOCAL");
5074
5075 } else if (errno != -ENOENT)
5076 return -errno;
5077
7948c4df
KS
5078 return local;
5079}
5080
ff4daf5a 5081int hwclock_apply_localtime_delta(int *min) {
7948c4df 5082 const struct timeval *tv_null = NULL;
2076cf88 5083 struct timespec ts;
7948c4df
KS
5084 struct tm *tm;
5085 int minuteswest;
5086 struct timezone tz;
5087
2076cf88
LP
5088 assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
5089 assert_se(tm = localtime(&ts.tv_sec));
7948c4df
KS
5090 minuteswest = tm->tm_gmtoff / 60;
5091
5092 tz.tz_minuteswest = -minuteswest;
5093 tz.tz_dsttime = 0; /* DST_NONE*/
5094
5095 /*
5096 * If the hardware clock does not run in UTC, but in local time:
5097 * The very first time we set the kernel's timezone, it will warp
5098 * the clock so that it runs in UTC instead of local time.
5099 */
5100 if (settimeofday(tv_null, &tz) < 0)
5101 return -errno;
ff4daf5a
KS
5102 if (min)
5103 *min = minuteswest;
5104 return 0;
2076cf88
LP
5105}
5106
5107int hwclock_reset_localtime_delta(void) {
5108 const struct timeval *tv_null = NULL;
5109 struct timezone tz;
5110
5111 tz.tz_minuteswest = 0;
5112 tz.tz_dsttime = 0; /* DST_NONE*/
5113
5114 if (settimeofday(tv_null, &tz) < 0)
5115 return -errno;
5116
5117 return 0;
7948c4df
KS
5118}
5119
51122dc9
LP
5120int rtc_open(int flags) {
5121 int fd;
5122 DIR *d;
5123
7c697168
LP
5124 /* First, we try to make use of the /dev/rtc symlink. If that
5125 * doesn't exist, we open the first RTC which has hctosys=1
5126 * set. If we don't find any we just take the first RTC that
5127 * exists at all. */
5128
5129 fd = open("/dev/rtc", flags);
5130 if (fd >= 0)
5131 return fd;
51122dc9
LP
5132
5133 d = opendir("/sys/class/rtc");
5134 if (!d)
5135 goto fallback;
5136
5137 for (;;) {
5138 char *p, *v;
5139 struct dirent buf, *de;
5140 int r;
5141
5142 r = readdir_r(d, &buf, &de);
5143 if (r != 0)
5144 goto fallback;
5145
5146 if (!de)
5147 goto fallback;
5148
5149 if (ignore_file(de->d_name))
5150 continue;
5151
5152 p = join("/sys/class/rtc/", de->d_name, "/hctosys", NULL);
5153 if (!p) {
5154 closedir(d);
5155 return -ENOMEM;
5156 }
5157
5158 r = read_one_line_file(p, &v);
5159 free(p);
5160
5161 if (r < 0)
5162 continue;
5163
5164 r = parse_boolean(v);
5165 free(v);
5166
5167 if (r <= 0)
5168 continue;
5169
5170 p = strappend("/dev/", de->d_name);
5171 fd = open(p, flags);
5172 free(p);
5173
5174 if (fd >= 0) {
5175 closedir(d);
5176 return fd;
5177 }
5178 }
5179
5180fallback:
5181 if (d)
5182 closedir(d);
5183
5184 fd = open("/dev/rtc0", flags);
5185 if (fd < 0)
5186 return -errno;
5187
5188 return fd;
5189}
5190
7948c4df
KS
5191int hwclock_get_time(struct tm *tm) {
5192 int fd;
5193 int err = 0;
5194
2076cf88
LP
5195 assert(tm);
5196
51122dc9 5197 fd = rtc_open(O_RDONLY|O_CLOEXEC);
7948c4df
KS
5198 if (fd < 0)
5199 return -errno;
2076cf88
LP
5200
5201 /* This leaves the timezone fields of struct tm
5202 * uninitialized! */
7948c4df
KS
5203 if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5204 err = -errno;
2076cf88
LP
5205
5206 /* We don't now daylight saving, so we reset this in order not
5207 * to confused mktime(). */
5208 tm->tm_isdst = -1;
5209
5210 close_nointr_nofail(fd);
7948c4df
KS
5211
5212 return err;
5213}
5214
5215int hwclock_set_time(const struct tm *tm) {
5216 int fd;
5217 int err = 0;
5218
2076cf88
LP
5219 assert(tm);
5220
51122dc9 5221 fd = rtc_open(O_RDONLY|O_CLOEXEC);
7948c4df
KS
5222 if (fd < 0)
5223 return -errno;
2076cf88 5224
7948c4df
KS
5225 if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5226 err = -errno;
2076cf88
LP
5227
5228 close_nointr_nofail(fd);
7948c4df
KS
5229
5230 return err;
5231}
f41607a6 5232
34ca941c
LP
5233int copy_file(const char *from, const char *to) {
5234 int r, fdf, fdt;
5235
5236 assert(from);
5237 assert(to);
5238
5239 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5240 if (fdf < 0)
5241 return -errno;
5242
5243 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5244 if (fdt < 0) {
5245 close_nointr_nofail(fdf);
5246 return -errno;
5247 }
5248
5249 for (;;) {
5250 char buf[PIPE_BUF];
5251 ssize_t n, k;
5252
5253 n = read(fdf, buf, sizeof(buf));
5254 if (n < 0) {
5255 r = -errno;
5256
5257 close_nointr_nofail(fdf);
5258 close_nointr(fdt);
5259 unlink(to);
5260
5261 return r;
5262 }
5263
5264 if (n == 0)
5265 break;
5266
5267 errno = 0;
5268 k = loop_write(fdt, buf, n, false);
5269 if (n != k) {
5270 r = k < 0 ? k : (errno ? -errno : -EIO);
5271
5272 close_nointr_nofail(fdf);
5273 close_nointr(fdt);
5274
5275 unlink(to);
5276 return r;
5277 }
5278 }
5279
5280 close_nointr_nofail(fdf);
5281 r = close_nointr(fdt);
5282
5283 if (r < 0) {
5284 unlink(to);
5285 return r;
5286 }
5287
5288 return 0;
5289}
5290
5291int symlink_or_copy(const char *from, const char *to) {
5292 char *pf = NULL, *pt = NULL;
5293 struct stat a, b;
5294 int r;
5295
5296 assert(from);
5297 assert(to);
5298
5299 if (parent_of_path(from, &pf) < 0 ||
5300 parent_of_path(to, &pt) < 0) {
5301 r = -ENOMEM;
5302 goto finish;
5303 }
5304
5305 if (stat(pf, &a) < 0 ||
5306 stat(pt, &b) < 0) {
5307 r = -errno;
5308 goto finish;
5309 }
5310
5311 if (a.st_dev != b.st_dev) {
5312 free(pf);
5313 free(pt);
5314
5315 return copy_file(from, to);
5316 }
5317
5318 if (symlink(from, to) < 0) {
5319 r = -errno;
5320 goto finish;
5321 }
5322
5323 r = 0;
5324
5325finish:
5326 free(pf);
5327 free(pt);
5328
5329 return r;
5330}
5331
5332int symlink_or_copy_atomic(const char *from, const char *to) {
5333 char *t, *x;
5334 const char *fn;
5335 size_t k;
5336 unsigned long long ull;
5337 unsigned i;
5338 int r;
5339
5340 assert(from);
5341 assert(to);
5342
5343 t = new(char, strlen(to) + 1 + 16 + 1);
5344 if (!t)
5345 return -ENOMEM;
5346
5347 fn = file_name_from_path(to);
5348 k = fn-to;
5349 memcpy(t, to, k);
5350 t[k] = '.';
5351 x = stpcpy(t+k+1, fn);
5352
5353 ull = random_ull();
5354 for (i = 0; i < 16; i++) {
5355 *(x++) = hexchar(ull & 0xF);
5356 ull >>= 4;
5357 }
5358
5359 *x = 0;
5360
5361 r = symlink_or_copy(from, t);
5362 if (r < 0) {
5363 unlink(t);
5364 free(t);
5365 return r;
5366 }
5367
5368 if (rename(t, to) < 0) {
5369 r = -errno;
5370 unlink(t);
5371 free(t);
5372 return r;
5373 }
5374
5375 free(t);
5376 return r;
5377}
5378
98a28fef 5379int audit_session_from_pid(pid_t pid, uint32_t *id) {
87d2c1ff 5380 char *s;
98a28fef
LP
5381 uint32_t u;
5382 int r;
5383
98a28fef
LP
5384 assert(id);
5385
5386 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5387 return -ENOENT;
5388
87d2c1ff
LP
5389 if (pid == 0)
5390 r = read_one_line_file("/proc/self/sessionid", &s);
5391 else {
5392 char *p;
5393
5394 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5395 return -ENOMEM;
5396
5397 r = read_one_line_file(p, &s);
5398 free(p);
5399 }
98a28fef 5400
98a28fef
LP
5401 if (r < 0)
5402 return r;
5403
5404 r = safe_atou32(s, &u);
5405 free(s);
5406
5407 if (r < 0)
5408 return r;
5409
5410 if (u == (uint32_t) -1 || u <= 0)
5411 return -ENOENT;
5412
5413 *id = u;
5414 return 0;
5415}
5416
87d2c1ff
LP
5417int audit_loginuid_from_pid(pid_t pid, uid_t *uid) {
5418 char *s;
5419 uid_t u;
5420 int r;
5421
5422 assert(uid);
5423
5424 /* Only use audit login uid if we are executed with sufficient
5425 * capabilities so that pam_loginuid could do its job. If we
5426 * are lacking the CAP_AUDIT_CONTROL capabality we most likely
5427 * are being run in a container and /proc/self/loginuid is
5428 * useless since it probably contains a uid of the host
5429 * system. */
5430
5431 if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5432 return -ENOENT;
5433
5434 if (pid == 0)
5435 r = read_one_line_file("/proc/self/loginuid", &s);
5436 else {
5437 char *p;
5438
5439 if (asprintf(&p, "/proc/%lu/loginuid", (unsigned long) pid) < 0)
5440 return -ENOMEM;
5441
5442 r = read_one_line_file(p, &s);
5443 free(p);
5444 }
5445
5446 if (r < 0)
5447 return r;
5448
5449 r = parse_uid(s, &u);
5450 free(s);
5451
5452 if (r < 0)
5453 return r;
5454
5455 if (u == (uid_t) -1)
5456 return -ENOENT;
5457
5458 *uid = (uid_t) u;
5459 return 0;
5460}
5461
4d6d6518
LP
5462bool display_is_local(const char *display) {
5463 assert(display);
5464
5465 return
5466 display[0] == ':' &&
5467 display[1] >= '0' &&
5468 display[1] <= '9';
5469}
5470
5471int socket_from_display(const char *display, char **path) {
5472 size_t k;
5473 char *f, *c;
5474
5475 assert(display);
5476 assert(path);
5477
5478 if (!display_is_local(display))
5479 return -EINVAL;
5480
5481 k = strspn(display+1, "0123456789");
5482
5483 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5484 if (!f)
5485 return -ENOMEM;
5486
5487 c = stpcpy(f, "/tmp/.X11-unix/X");
5488 memcpy(c, display+1, k);
5489 c[k] = 0;
5490
5491 *path = f;
5492
5493 return 0;
5494}
5495
1cccf435
MV
5496int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5497 struct passwd *p;
ddd88763 5498 uid_t u;
1cccf435
MV
5499
5500 assert(username);
5501 assert(*username);
1cccf435
MV
5502
5503 /* We enforce some special rules for uid=0: in order to avoid
5504 * NSS lookups for root we hardcode its data. */
5505
5506 if (streq(*username, "root") || streq(*username, "0")) {
5507 *username = "root";
4b67834e
LP
5508
5509 if (uid)
5510 *uid = 0;
5511
5512 if (gid)
5513 *gid = 0;
5514
5515 if (home)
5516 *home = "/root";
1cccf435
MV
5517 return 0;
5518 }
5519
ddd88763 5520 if (parse_uid(*username, &u) >= 0) {
1cccf435 5521 errno = 0;
ddd88763 5522 p = getpwuid(u);
1cccf435
MV
5523
5524 /* If there are multiple users with the same id, make
5525 * sure to leave $USER to the configured value instead
5526 * of the first occurrence in the database. However if
5527 * the uid was configured by a numeric uid, then let's
5528 * pick the real username from /etc/passwd. */
5529 if (p)
5530 *username = p->pw_name;
5531 } else {
5532 errno = 0;
5533 p = getpwnam(*username);
5534 }
5535
5536 if (!p)
5537 return errno != 0 ? -errno : -ESRCH;
5538
4b67834e
LP
5539 if (uid)
5540 *uid = p->pw_uid;
5541
5542 if (gid)
5543 *gid = p->pw_gid;
5544
5545 if (home)
5546 *home = p->pw_dir;
5547
5548 return 0;
5549}
5550
5551int get_group_creds(const char **groupname, gid_t *gid) {
5552 struct group *g;
5553 gid_t id;
5554
5555 assert(groupname);
5556
5557 /* We enforce some special rules for gid=0: in order to avoid
5558 * NSS lookups for root we hardcode its data. */
5559
5560 if (streq(*groupname, "root") || streq(*groupname, "0")) {
5561 *groupname = "root";
5562
5563 if (gid)
5564 *gid = 0;
5565
5566 return 0;
5567 }
5568
5569 if (parse_gid(*groupname, &id) >= 0) {
5570 errno = 0;
5571 g = getgrgid(id);
5572
5573 if (g)
5574 *groupname = g->gr_name;
5575 } else {
5576 errno = 0;
5577 g = getgrnam(*groupname);
5578 }
5579
5580 if (!g)
5581 return errno != 0 ? -errno : -ESRCH;
5582
5583 if (gid)
5584 *gid = g->gr_gid;
5585
1cccf435
MV
5586 return 0;
5587}
5588
8092a428
LP
5589int glob_exists(const char *path) {
5590 glob_t g;
5591 int r, k;
5592
5593 assert(path);
5594
5595 zero(g);
5596 errno = 0;
5597 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5598
5599 if (k == GLOB_NOMATCH)
5600 r = 0;
5601 else if (k == GLOB_NOSPACE)
5602 r = -ENOMEM;
5603 else if (k == 0)
5604 r = !strv_isempty(g.gl_pathv);
5605 else
5606 r = errno ? -errno : -EIO;
5607
5608 globfree(&g);
5609
5610 return r;
5611}
5612
83096483
LP
5613int dirent_ensure_type(DIR *d, struct dirent *de) {
5614 struct stat st;
5615
5616 assert(d);
5617 assert(de);
5618
5619 if (de->d_type != DT_UNKNOWN)
5620 return 0;
5621
5622 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5623 return -errno;
5624
5625 de->d_type =
5626 S_ISREG(st.st_mode) ? DT_REG :
5627 S_ISDIR(st.st_mode) ? DT_DIR :
5628 S_ISLNK(st.st_mode) ? DT_LNK :
5629 S_ISFIFO(st.st_mode) ? DT_FIFO :
5630 S_ISSOCK(st.st_mode) ? DT_SOCK :
5631 S_ISCHR(st.st_mode) ? DT_CHR :
5632 S_ISBLK(st.st_mode) ? DT_BLK :
5633 DT_UNKNOWN;
5634
5635 return 0;
5636}
5637
5638int in_search_path(const char *path, char **search) {
5639 char **i, *parent;
5640 int r;
5641
5642 r = parent_of_path(path, &parent);
5643 if (r < 0)
5644 return r;
5645
5646 r = 0;
5647
5648 STRV_FOREACH(i, search) {
5649 if (path_equal(parent, *i)) {
5650 r = 1;
5651 break;
5652 }
5653 }
5654
5655 free(parent);
5656
5657 return r;
5658}
5659
034a2a52
LP
5660int get_files_in_directory(const char *path, char ***list) {
5661 DIR *d;
5662 int r = 0;
5663 unsigned n = 0;
5664 char **l = NULL;
5665
5666 assert(path);
d60ef526
LP
5667
5668 /* Returns all files in a directory in *list, and the number
5669 * of files as return value. If list is NULL returns only the
5670 * number */
034a2a52
LP
5671
5672 d = opendir(path);
8ea913b2
LP
5673 if (!d)
5674 return -errno;
5675
034a2a52
LP
5676 for (;;) {
5677 struct dirent buffer, *de;
5678 int k;
5679
5680 k = readdir_r(d, &buffer, &de);
5681 if (k != 0) {
5682 r = -k;
5683 goto finish;
5684 }
5685
5686 if (!de)
5687 break;
5688
5689 dirent_ensure_type(d, de);
5690
5691 if (!dirent_is_file(de))
5692 continue;
5693
d60ef526
LP
5694 if (list) {
5695 if ((unsigned) r >= n) {
5696 char **t;
034a2a52 5697
d60ef526
LP
5698 n = MAX(16, 2*r);
5699 t = realloc(l, sizeof(char*) * n);
5700 if (!t) {
5701 r = -ENOMEM;
5702 goto finish;
5703 }
034a2a52 5704
d60ef526
LP
5705 l = t;
5706 }
034a2a52 5707
d60ef526 5708 assert((unsigned) r < n);
034a2a52 5709
d60ef526
LP
5710 l[r] = strdup(de->d_name);
5711 if (!l[r]) {
5712 r = -ENOMEM;
5713 goto finish;
5714 }
034a2a52 5715
d60ef526
LP
5716 l[++r] = NULL;
5717 } else
5718 r++;
034a2a52
LP
5719 }
5720
5721finish:
5722 if (d)
5723 closedir(d);
5724
d60ef526
LP
5725 if (r >= 0) {
5726 if (list)
5727 *list = l;
5728 } else
034a2a52
LP
5729 strv_free(l);
5730
5731 return r;
5732}
5733
911a4828
LP
5734char *join(const char *x, ...) {
5735 va_list ap;
5736 size_t l;
5737 char *r, *p;
5738
5739 va_start(ap, x);
5740
5741 if (x) {
5742 l = strlen(x);
5743
5744 for (;;) {
5745 const char *t;
5746
5747 t = va_arg(ap, const char *);
5748 if (!t)
5749 break;
5750
5751 l += strlen(t);
5752 }
5753 } else
5754 l = 0;
5755
5756 va_end(ap);
5757
5758 r = new(char, l+1);
5759 if (!r)
5760 return NULL;
5761
5762 if (x) {
5763 p = stpcpy(r, x);
5764
5765 va_start(ap, x);
5766
5767 for (;;) {
5768 const char *t;
5769
5770 t = va_arg(ap, const char *);
5771 if (!t)
5772 break;
5773
5774 p = stpcpy(p, t);
5775 }
8ea913b2
LP
5776
5777 va_end(ap);
911a4828
LP
5778 } else
5779 r[0] = 0;
5780
5781 return r;
5782}
5783
b636465b
LP
5784bool is_main_thread(void) {
5785 static __thread int cached = 0;
5786
5787 if (_unlikely_(cached == 0))
5788 cached = getpid() == gettid() ? 1 : -1;
5789
5790 return cached > 0;
5791}
5792
94959f0f
LP
5793int block_get_whole_disk(dev_t d, dev_t *ret) {
5794 char *p, *s;
5795 int r;
5796 unsigned n, m;
5797
5798 assert(ret);
5799
5800 /* If it has a queue this is good enough for us */
5801 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5802 return -ENOMEM;
5803
5804 r = access(p, F_OK);
5805 free(p);
5806
5807 if (r >= 0) {
5808 *ret = d;
5809 return 0;
5810 }
5811
5812 /* If it is a partition find the originating device */
5813 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5814 return -ENOMEM;
5815
5816 r = access(p, F_OK);
5817 free(p);
5818
5819 if (r < 0)
5820 return -ENOENT;
5821
5822 /* Get parent dev_t */
5823 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5824 return -ENOMEM;
5825
5826 r = read_one_line_file(p, &s);
5827 free(p);
5828
5829 if (r < 0)
5830 return r;
5831
5832 r = sscanf(s, "%u:%u", &m, &n);
5833 free(s);
5834
5835 if (r != 2)
5836 return -EINVAL;
5837
5838 /* Only return this if it is really good enough for us. */
5839 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5840 return -ENOMEM;
5841
5842 r = access(p, F_OK);
5843 free(p);
5844
5845 if (r >= 0) {
5846 *ret = makedev(m, n);
5847 return 0;
5848 }
5849
5850 return -ENOENT;
5851}
5852
8d53b453 5853int file_is_priv_sticky(const char *p) {
ad293f5a
LP
5854 struct stat st;
5855
5856 assert(p);
5857
5858 if (lstat(p, &st) < 0)
5859 return -errno;
5860
5861 return
8d53b453 5862 (st.st_uid == 0 || st.st_uid == getuid()) &&
ad293f5a
LP
5863 (st.st_mode & S_ISVTX);
5864}
94959f0f 5865
f41607a6
LP
5866static const char *const ioprio_class_table[] = {
5867 [IOPRIO_CLASS_NONE] = "none",
5868 [IOPRIO_CLASS_RT] = "realtime",
5869 [IOPRIO_CLASS_BE] = "best-effort",
5870 [IOPRIO_CLASS_IDLE] = "idle"
5871};
5872
5873DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5874
5875static const char *const sigchld_code_table[] = {
5876 [CLD_EXITED] = "exited",
5877 [CLD_KILLED] = "killed",
5878 [CLD_DUMPED] = "dumped",
5879 [CLD_TRAPPED] = "trapped",
5880 [CLD_STOPPED] = "stopped",
5881 [CLD_CONTINUED] = "continued",
5882};
5883
5884DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5885
5886static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5887 [LOG_FAC(LOG_KERN)] = "kern",
5888 [LOG_FAC(LOG_USER)] = "user",
5889 [LOG_FAC(LOG_MAIL)] = "mail",
5890 [LOG_FAC(LOG_DAEMON)] = "daemon",
5891 [LOG_FAC(LOG_AUTH)] = "auth",
5892 [LOG_FAC(LOG_SYSLOG)] = "syslog",
5893 [LOG_FAC(LOG_LPR)] = "lpr",
5894 [LOG_FAC(LOG_NEWS)] = "news",
5895 [LOG_FAC(LOG_UUCP)] = "uucp",
5896 [LOG_FAC(LOG_CRON)] = "cron",
5897 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5898 [LOG_FAC(LOG_FTP)] = "ftp",
5899 [LOG_FAC(LOG_LOCAL0)] = "local0",
5900 [LOG_FAC(LOG_LOCAL1)] = "local1",
5901 [LOG_FAC(LOG_LOCAL2)] = "local2",
5902 [LOG_FAC(LOG_LOCAL3)] = "local3",
5903 [LOG_FAC(LOG_LOCAL4)] = "local4",
5904 [LOG_FAC(LOG_LOCAL5)] = "local5",
5905 [LOG_FAC(LOG_LOCAL6)] = "local6",
5906 [LOG_FAC(LOG_LOCAL7)] = "local7"
5907};
5908
5909DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5910
5911static const char *const log_level_table[] = {
5912 [LOG_EMERG] = "emerg",
5913 [LOG_ALERT] = "alert",
5914 [LOG_CRIT] = "crit",
5915 [LOG_ERR] = "err",
5916 [LOG_WARNING] = "warning",
5917 [LOG_NOTICE] = "notice",
5918 [LOG_INFO] = "info",
5919 [LOG_DEBUG] = "debug"
5920};
5921
5922DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5923
5924static const char* const sched_policy_table[] = {
5925 [SCHED_OTHER] = "other",
5926 [SCHED_BATCH] = "batch",
5927 [SCHED_IDLE] = "idle",
5928 [SCHED_FIFO] = "fifo",
5929 [SCHED_RR] = "rr"
5930};
5931
5932DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5933
5934static const char* const rlimit_table[] = {
5935 [RLIMIT_CPU] = "LimitCPU",
5936 [RLIMIT_FSIZE] = "LimitFSIZE",
5937 [RLIMIT_DATA] = "LimitDATA",
5938 [RLIMIT_STACK] = "LimitSTACK",
5939 [RLIMIT_CORE] = "LimitCORE",
5940 [RLIMIT_RSS] = "LimitRSS",
5941 [RLIMIT_NOFILE] = "LimitNOFILE",
5942 [RLIMIT_AS] = "LimitAS",
5943 [RLIMIT_NPROC] = "LimitNPROC",
5944 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5945 [RLIMIT_LOCKS] = "LimitLOCKS",
5946 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5947 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5948 [RLIMIT_NICE] = "LimitNICE",
5949 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5950 [RLIMIT_RTTIME] = "LimitRTTIME"
5951};
5952
5953DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5954
5955static const char* const ip_tos_table[] = {
5956 [IPTOS_LOWDELAY] = "low-delay",
5957 [IPTOS_THROUGHPUT] = "throughput",
5958 [IPTOS_RELIABILITY] = "reliability",
5959 [IPTOS_LOWCOST] = "low-cost",
5960};
5961
5962DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5963
4e240ab0 5964static const char *const __signal_table[] = {
f41607a6
LP
5965 [SIGHUP] = "HUP",
5966 [SIGINT] = "INT",
5967 [SIGQUIT] = "QUIT",
5968 [SIGILL] = "ILL",
5969 [SIGTRAP] = "TRAP",
5970 [SIGABRT] = "ABRT",
5971 [SIGBUS] = "BUS",
5972 [SIGFPE] = "FPE",
5973 [SIGKILL] = "KILL",
5974 [SIGUSR1] = "USR1",
5975 [SIGSEGV] = "SEGV",
5976 [SIGUSR2] = "USR2",
5977 [SIGPIPE] = "PIPE",
5978 [SIGALRM] = "ALRM",
5979 [SIGTERM] = "TERM",
5980#ifdef SIGSTKFLT
5981 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5982#endif
5983 [SIGCHLD] = "CHLD",
5984 [SIGCONT] = "CONT",
5985 [SIGSTOP] = "STOP",
5986 [SIGTSTP] = "TSTP",
5987 [SIGTTIN] = "TTIN",
5988 [SIGTTOU] = "TTOU",
5989 [SIGURG] = "URG",
5990 [SIGXCPU] = "XCPU",
5991 [SIGXFSZ] = "XFSZ",
5992 [SIGVTALRM] = "VTALRM",
5993 [SIGPROF] = "PROF",
5994 [SIGWINCH] = "WINCH",
5995 [SIGIO] = "IO",
5996 [SIGPWR] = "PWR",
5997 [SIGSYS] = "SYS"
5998};
5999
4e240ab0
MS
6000DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
6001
6002const char *signal_to_string(int signo) {
6003 static __thread char buf[12];
6004 const char *name;
6005
6006 name = __signal_to_string(signo);
6007 if (name)
6008 return name;
6009
6010 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
6011 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
6012 else
6013 snprintf(buf, sizeof(buf) - 1, "%d", signo);
6014 char_array_0(buf);
6015 return buf;
6016}
6017
6018int signal_from_string(const char *s) {
6019 int signo;
6020 int offset = 0;
6021 unsigned u;
6022
6023 signo =__signal_from_string(s);
6024 if (signo > 0)
6025 return signo;
6026
6027 if (startswith(s, "RTMIN+")) {
6028 s += 6;
6029 offset = SIGRTMIN;
6030 }
6031 if (safe_atou(s, &u) >= 0) {
6032 signo = (int) u + offset;
6033 if (signo > 0 && signo < _NSIG)
6034 return signo;
6035 }
6036 return -1;
6037}
65457142
FC
6038
6039bool kexec_loaded(void) {
6040 bool loaded = false;
6041 char *s;
6042
6043 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
6044 if (s[0] == '1')
6045 loaded = true;
6046 free(s);
6047 }
6048 return loaded;
6049}
fb9de93d
LP
6050
6051int strdup_or_null(const char *a, char **b) {
6052 char *c;
6053
6054 assert(b);
6055
6056 if (!a) {
6057 *b = NULL;
6058 return 0;
6059 }
6060
6061 c = strdup(a);
6062 if (!c)
6063 return -ENOMEM;
6064
6065 *b = c;
6066 return 0;
6067}
64685e0c 6068
87d2c1ff
LP
6069int prot_from_flags(int flags) {
6070
6071 switch (flags & O_ACCMODE) {
6072
6073 case O_RDONLY:
6074 return PROT_READ;
6075
6076 case O_WRONLY:
6077 return PROT_WRITE;
6078
6079 case O_RDWR:
6080 return PROT_READ|PROT_WRITE;
6081
6082 default:
6083 return -EINVAL;
6084 }
7c99e0c1 6085}
689b9a22 6086
64685e0c
LP
6087unsigned long cap_last_cap(void) {
6088 static __thread unsigned long saved;
6089 static __thread bool valid = false;
6090 unsigned long p;
6091
6092 if (valid)
6093 return saved;
6094
6095 p = (unsigned long) CAP_LAST_CAP;
6096
6097 if (prctl(PR_CAPBSET_READ, p) < 0) {
6098
6099 /* Hmm, look downwards, until we find one that
6100 * works */
6101 for (p--; p > 0; p --)
6102 if (prctl(PR_CAPBSET_READ, p) >= 0)
6103 break;
6104
6105 } else {
6106
6107 /* Hmm, look upwards, until we find one that doesn't
6108 * work */
6109 for (;; p++)
6110 if (prctl(PR_CAPBSET_READ, p+1) < 0)
6111 break;
6112 }
6113
6114 saved = p;
6115 valid = true;
6116
6117 return p;
6118}
babfc091
LP
6119
6120char *format_bytes(char *buf, size_t l, off_t t) {
c0f99c21 6121 unsigned i;
babfc091
LP
6122
6123 static const struct {
6124 const char *suffix;
6125 off_t factor;
6126 } table[] = {
32895bb3
LP
6127 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6128 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
babfc091
LP
6129 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
6130 { "G", 1024ULL*1024ULL*1024ULL },
6131 { "M", 1024ULL*1024ULL },
6132 { "K", 1024ULL },
6133 };
6134
6135 for (i = 0; i < ELEMENTSOF(table); i++) {
6136
6137 if (t >= table[i].factor) {
6138 snprintf(buf, l,
6139 "%llu.%llu%s",
6140 (unsigned long long) (t / table[i].factor),
6141 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
6142 table[i].suffix);
6143
6144 goto finish;
6145 }
6146 }
6147
6148 snprintf(buf, l, "%lluB", (unsigned long long) t);
6149
6150finish:
6151 buf[l-1] = 0;
6152 return buf;
6153
6154}
55d7bfc1
LP
6155
6156void* memdup(const void *p, size_t l) {
6157 void *r;
6158
6159 assert(p);
6160
6161 r = malloc(l);
6162 if (!r)
6163 return NULL;
6164
6165 memcpy(r, p, l);
6166 return r;
6167}
bb99a35a
LP
6168
6169int fd_inc_sndbuf(int fd, size_t n) {
6170 int r, value;
6171 socklen_t l = sizeof(value);
6172
6173 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
6174 if (r >= 0 &&
6175 l == sizeof(value) &&
6176 (size_t) value >= n*2)
6177 return 0;
6178
6179 value = (int) n;
6180 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
6181 if (r < 0)
6182 return -errno;
6183
6184 return 1;
6185}
6186
6187int fd_inc_rcvbuf(int fd, size_t n) {
6188 int r, value;
6189 socklen_t l = sizeof(value);
6190
6191 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
6192 if (r >= 0 &&
6193 l == sizeof(value) &&
6194 (size_t) value >= n*2)
6195 return 0;
6196
6197 value = (int) n;
6198 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
6199 if (r < 0)
6200 return -errno;
6201
6202 return 1;
6203}