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