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