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