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