]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/util.c
systemctl: don't fail if first argument to shutdown isn't 'now' just warn loudly.
[thirdparty/systemd.git] / src / util.c
CommitLineData
60918275
LP
1/*-*- Mode: C; c-basic-offset: 8 -*-*/
2
a7334b09
LP
3/***
4 This file is part of systemd.
5
6 Copyright 2010 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20***/
21
60918275
LP
22#include <assert.h>
23#include <string.h>
24#include <unistd.h>
25#include <errno.h>
85261803 26#include <stdlib.h>
034c6ed7
LP
27#include <signal.h>
28#include <stdio.h>
1dccbe19
LP
29#include <syslog.h>
30#include <sched.h>
31#include <sys/resource.h>
ef886c6a 32#include <linux/sched.h>
a9f5d454
LP
33#include <sys/types.h>
34#include <sys/stat.h>
3a0ecb08 35#include <fcntl.h>
a0d40ac5 36#include <dirent.h>
601f6a1e
LP
37#include <sys/ioctl.h>
38#include <linux/vt.h>
39#include <linux/tiocl.h>
80876c20
LP
40#include <termios.h>
41#include <stdarg.h>
42#include <sys/inotify.h>
43#include <sys/poll.h>
8d567588 44#include <libgen.h>
3177a7fa 45#include <ctype.h>
5b6319dc 46#include <sys/prctl.h>
ef2f1067
LP
47#include <sys/utsname.h>
48#include <pwd.h>
60918275
LP
49
50#include "macro.h"
51#include "util.h"
1dccbe19
LP
52#include "ioprio.h"
53#include "missing.h"
a9f5d454 54#include "log.h"
65d2ebdc 55#include "strv.h"
60918275 56
e05797fb
LP
57bool streq_ptr(const char *a, const char *b) {
58
59 /* Like streq(), but tries to make sense of NULL pointers */
60
61 if (a && b)
62 return streq(a, b);
63
64 if (!a && !b)
65 return true;
66
67 return false;
68}
69
47be870b 70usec_t now(clockid_t clock_id) {
60918275
LP
71 struct timespec ts;
72
47be870b 73 assert_se(clock_gettime(clock_id, &ts) == 0);
60918275
LP
74
75 return timespec_load(&ts);
76}
77
871d7de4
LP
78timestamp* timestamp_get(timestamp *ts) {
79 assert(ts);
80
81 ts->realtime = now(CLOCK_REALTIME);
82 ts->monotonic = now(CLOCK_MONOTONIC);
83
84 return ts;
85}
86
60918275
LP
87usec_t timespec_load(const struct timespec *ts) {
88 assert(ts);
89
90 return
91 (usec_t) ts->tv_sec * USEC_PER_SEC +
92 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
93}
94
95struct timespec *timespec_store(struct timespec *ts, usec_t u) {
96 assert(ts);
97
98 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
99 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
100
101 return ts;
102}
103
104usec_t timeval_load(const struct timeval *tv) {
105 assert(tv);
106
107 return
108 (usec_t) tv->tv_sec * USEC_PER_SEC +
109 (usec_t) tv->tv_usec;
110}
111
112struct timeval *timeval_store(struct timeval *tv, usec_t u) {
113 assert(tv);
114
115 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
116 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
117
118 return tv;
119}
120
121bool endswith(const char *s, const char *postfix) {
122 size_t sl, pl;
123
124 assert(s);
125 assert(postfix);
126
127 sl = strlen(s);
128 pl = strlen(postfix);
129
d4d0d4db
LP
130 if (pl == 0)
131 return true;
132
60918275
LP
133 if (sl < pl)
134 return false;
135
136 return memcmp(s + sl - pl, postfix, pl) == 0;
137}
138
139bool startswith(const char *s, const char *prefix) {
140 size_t sl, pl;
141
142 assert(s);
143 assert(prefix);
144
145 sl = strlen(s);
146 pl = strlen(prefix);
147
d4d0d4db
LP
148 if (pl == 0)
149 return true;
150
60918275
LP
151 if (sl < pl)
152 return false;
153
154 return memcmp(s, prefix, pl) == 0;
155}
156
3177a7fa
MAP
157bool startswith_no_case(const char *s, const char *prefix) {
158 size_t sl, pl;
159 unsigned i;
160
161 assert(s);
162 assert(prefix);
163
164 sl = strlen(s);
165 pl = strlen(prefix);
166
167 if (pl == 0)
168 return true;
169
170 if (sl < pl)
171 return false;
172
173 for(i = 0; i < pl; ++i) {
174 if (tolower(s[i]) != tolower(prefix[i]))
175 return false;
176 }
177
178 return true;
179}
180
79d6d816
LP
181bool first_word(const char *s, const char *word) {
182 size_t sl, wl;
183
184 assert(s);
185 assert(word);
186
187 sl = strlen(s);
188 wl = strlen(word);
189
190 if (sl < wl)
191 return false;
192
d4d0d4db
LP
193 if (wl == 0)
194 return true;
195
79d6d816
LP
196 if (memcmp(s, word, wl) != 0)
197 return false;
198
d4d0d4db
LP
199 return s[wl] == 0 ||
200 strchr(WHITESPACE, s[wl]);
79d6d816
LP
201}
202
42f4e3c4 203int close_nointr(int fd) {
60918275
LP
204 assert(fd >= 0);
205
206 for (;;) {
207 int r;
208
209 if ((r = close(fd)) >= 0)
210 return r;
211
212 if (errno != EINTR)
213 return r;
214 }
215}
85261803 216
85f136b5 217void close_nointr_nofail(int fd) {
80876c20 218 int saved_errno = errno;
85f136b5
LP
219
220 /* like close_nointr() but cannot fail, and guarantees errno
221 * is unchanged */
222
223 assert_se(close_nointr(fd) == 0);
80876c20
LP
224
225 errno = saved_errno;
85f136b5
LP
226}
227
5b6319dc
LP
228void close_many(const int fds[], unsigned n_fd) {
229 unsigned i;
230
231 for (i = 0; i < n_fd; i++)
232 close_nointr_nofail(fds[i]);
233}
234
85261803
LP
235int parse_boolean(const char *v) {
236 assert(v);
237
44d8db9e 238 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
85261803 239 return 1;
44d8db9e 240 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
85261803
LP
241 return 0;
242
243 return -EINVAL;
244}
245
3ba686c1
LP
246int parse_pid(const char *s, pid_t* ret_pid) {
247 unsigned long ul;
248 pid_t pid;
249 int r;
250
251 assert(s);
252 assert(ret_pid);
253
254 if ((r = safe_atolu(s, &ul)) < 0)
255 return r;
256
257 pid = (pid_t) ul;
258
259 if ((unsigned long) pid != ul)
260 return -ERANGE;
261
262 if (pid <= 0)
263 return -ERANGE;
264
265 *ret_pid = pid;
266 return 0;
267}
268
85261803
LP
269int safe_atou(const char *s, unsigned *ret_u) {
270 char *x = NULL;
034c6ed7 271 unsigned long l;
85261803
LP
272
273 assert(s);
274 assert(ret_u);
275
276 errno = 0;
277 l = strtoul(s, &x, 0);
278
279 if (!x || *x || errno)
280 return errno ? -errno : -EINVAL;
281
034c6ed7 282 if ((unsigned long) (unsigned) l != l)
85261803
LP
283 return -ERANGE;
284
285 *ret_u = (unsigned) l;
286 return 0;
287}
288
289int safe_atoi(const char *s, int *ret_i) {
290 char *x = NULL;
034c6ed7 291 long l;
85261803
LP
292
293 assert(s);
294 assert(ret_i);
295
296 errno = 0;
297 l = strtol(s, &x, 0);
298
299 if (!x || *x || errno)
300 return errno ? -errno : -EINVAL;
301
034c6ed7 302 if ((long) (int) l != l)
85261803
LP
303 return -ERANGE;
304
034c6ed7
LP
305 *ret_i = (int) l;
306 return 0;
307}
308
309int safe_atolu(const char *s, long unsigned *ret_lu) {
310 char *x = NULL;
311 unsigned long l;
312
313 assert(s);
314 assert(ret_lu);
315
316 errno = 0;
317 l = strtoul(s, &x, 0);
318
319 if (!x || *x || errno)
320 return errno ? -errno : -EINVAL;
321
322 *ret_lu = l;
323 return 0;
324}
325
326int safe_atoli(const char *s, long int *ret_li) {
327 char *x = NULL;
328 long l;
329
330 assert(s);
331 assert(ret_li);
332
333 errno = 0;
334 l = strtol(s, &x, 0);
335
336 if (!x || *x || errno)
337 return errno ? -errno : -EINVAL;
338
339 *ret_li = l;
340 return 0;
341}
342
343int safe_atollu(const char *s, long long unsigned *ret_llu) {
344 char *x = NULL;
345 unsigned long long l;
346
347 assert(s);
348 assert(ret_llu);
349
350 errno = 0;
351 l = strtoull(s, &x, 0);
352
353 if (!x || *x || errno)
354 return errno ? -errno : -EINVAL;
355
356 *ret_llu = l;
357 return 0;
358}
359
360int safe_atolli(const char *s, long long int *ret_lli) {
361 char *x = NULL;
362 long long l;
363
364 assert(s);
365 assert(ret_lli);
366
367 errno = 0;
368 l = strtoll(s, &x, 0);
369
370 if (!x || *x || errno)
371 return errno ? -errno : -EINVAL;
372
373 *ret_lli = l;
85261803
LP
374 return 0;
375}
a41e8209 376
a41e8209 377/* Split a string into words. */
65d2ebdc 378char *split(const char *c, size_t *l, const char *separator, char **state) {
a41e8209
LP
379 char *current;
380
381 current = *state ? *state : (char*) c;
382
383 if (!*current || *c == 0)
384 return NULL;
385
65d2ebdc
LP
386 current += strspn(current, separator);
387 *l = strcspn(current, separator);
82919e3d
LP
388 *state = current+*l;
389
390 return (char*) current;
391}
392
034c6ed7
LP
393/* Split a string into words, but consider strings enclosed in '' and
394 * "" as words even if they include spaces. */
395char *split_quoted(const char *c, size_t *l, char **state) {
396 char *current;
397
398 current = *state ? *state : (char*) c;
399
400 if (!*current || *c == 0)
401 return NULL;
402
403 current += strspn(current, WHITESPACE);
404
405 if (*current == '\'') {
406 current ++;
407 *l = strcspn(current, "'");
408 *state = current+*l;
409
410 if (**state == '\'')
411 (*state)++;
412 } else if (*current == '\"') {
413 current ++;
b858b600 414 *l = strcspn(current, "\"");
034c6ed7
LP
415 *state = current+*l;
416
417 if (**state == '\"')
418 (*state)++;
419 } else {
420 *l = strcspn(current, WHITESPACE);
421 *state = current+*l;
422 }
423
44d8db9e
LP
424 /* FIXME: Cannot deal with strings that have spaces AND ticks
425 * in them */
426
034c6ed7
LP
427 return (char*) current;
428}
429
65d2ebdc
LP
430char **split_path_and_make_absolute(const char *p) {
431 char **l;
432 assert(p);
433
434 if (!(l = strv_split(p, ":")))
435 return NULL;
436
437 if (!strv_path_make_absolute_cwd(l)) {
438 strv_free(l);
439 return NULL;
440 }
441
442 return l;
443}
444
034c6ed7
LP
445int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
446 int r;
447 FILE *f;
448 char fn[132], line[256], *p;
449 long long unsigned ppid;
450
451 assert(pid >= 0);
452 assert(_ppid);
453
454 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%llu/stat", (unsigned long long) pid) < (int) (sizeof(fn)-1));
455 fn[sizeof(fn)-1] = 0;
456
457 if (!(f = fopen(fn, "r")))
458 return -errno;
459
460 if (!(fgets(line, sizeof(line), f))) {
461 r = -errno;
462 fclose(f);
463 return r;
464 }
465
466 fclose(f);
467
468 /* Let's skip the pid and comm fields. The latter is enclosed
469 * in () but does not escape any () in its value, so let's
470 * skip over it manually */
471
472 if (!(p = strrchr(line, ')')))
473 return -EIO;
474
475 p++;
476
477 if (sscanf(p, " "
478 "%*c " /* state */
479 "%llu ", /* ppid */
480 &ppid) != 1)
481 return -EIO;
482
483 if ((long long unsigned) (pid_t) ppid != ppid)
484 return -ERANGE;
485
486 *_ppid = (pid_t) ppid;
487
488 return 0;
489}
490
491int write_one_line_file(const char *fn, const char *line) {
492 FILE *f;
493 int r;
494
495 assert(fn);
496 assert(line);
497
498 if (!(f = fopen(fn, "we")))
499 return -errno;
500
501 if (fputs(line, f) < 0) {
502 r = -errno;
503 goto finish;
504 }
505
506 r = 0;
507finish:
508 fclose(f);
509 return r;
510}
511
512int read_one_line_file(const char *fn, char **line) {
513 FILE *f;
514 int r;
11316633 515 char t[2048], *c;
034c6ed7
LP
516
517 assert(fn);
518 assert(line);
519
520 if (!(f = fopen(fn, "re")))
521 return -errno;
522
523 if (!(fgets(t, sizeof(t), f))) {
524 r = -errno;
525 goto finish;
526 }
527
528 if (!(c = strdup(t))) {
529 r = -ENOMEM;
530 goto finish;
531 }
532
533 *line = c;
534 r = 0;
535
536finish:
537 fclose(f);
538 return r;
539}
44d8db9e 540
7072ced8
LP
541char *truncate_nl(char *s) {
542 assert(s);
543
544 s[strcspn(s, NEWLINE)] = 0;
545 return s;
546}
547
548int get_process_name(pid_t pid, char **name) {
549 char *p;
550 int r;
551
552 assert(pid >= 1);
553 assert(name);
554
555 if (asprintf(&p, "/proc/%llu/comm", (unsigned long long) pid) < 0)
556 return -ENOMEM;
557
558 r = read_one_line_file(p, name);
559 free(p);
560
561 if (r < 0)
562 return r;
563
564 truncate_nl(*name);
565 return 0;
566}
567
44d8db9e
LP
568char *strappend(const char *s, const char *suffix) {
569 size_t a, b;
570 char *r;
571
572 assert(s);
573 assert(suffix);
574
575 a = strlen(s);
576 b = strlen(suffix);
577
578 if (!(r = new(char, a+b+1)))
579 return NULL;
580
581 memcpy(r, s, a);
582 memcpy(r+a, suffix, b);
583 r[a+b] = 0;
584
585 return r;
586}
87f0e418
LP
587
588int readlink_malloc(const char *p, char **r) {
589 size_t l = 100;
590
591 assert(p);
592 assert(r);
593
594 for (;;) {
595 char *c;
596 ssize_t n;
597
598 if (!(c = new(char, l)))
599 return -ENOMEM;
600
601 if ((n = readlink(p, c, l-1)) < 0) {
602 int ret = -errno;
603 free(c);
604 return ret;
605 }
606
607 if ((size_t) n < l-1) {
608 c[n] = 0;
609 *r = c;
610 return 0;
611 }
612
613 free(c);
614 l *= 2;
615 }
616}
617
2c7108c4
LP
618int readlink_and_make_absolute(const char *p, char **r) {
619 char *target, *k;
620 int j;
621
622 assert(p);
623 assert(r);
624
625 if ((j = readlink_malloc(p, &target)) < 0)
626 return j;
627
628 k = file_in_same_dir(p, target);
629 free(target);
630
631 if (!k)
632 return -ENOMEM;
633
634 *r = k;
635 return 0;
636}
637
87f0e418
LP
638char *file_name_from_path(const char *p) {
639 char *r;
640
641 assert(p);
642
643 if ((r = strrchr(p, '/')))
644 return r + 1;
645
646 return (char*) p;
647}
0301abf4
LP
648
649bool path_is_absolute(const char *p) {
650 assert(p);
651
652 return p[0] == '/';
653}
654
655bool is_path(const char *p) {
656
657 return !!strchr(p, '/');
658}
659
660char *path_make_absolute(const char *p, const char *prefix) {
661 char *r;
662
663 assert(p);
664
65d2ebdc
LP
665 /* Makes every item in the list an absolute path by prepending
666 * the prefix, if specified and necessary */
667
0301abf4
LP
668 if (path_is_absolute(p) || !prefix)
669 return strdup(p);
670
671 if (asprintf(&r, "%s/%s", prefix, p) < 0)
672 return NULL;
673
674 return r;
675}
2a987ee8 676
65d2ebdc
LP
677char *path_make_absolute_cwd(const char *p) {
678 char *cwd, *r;
679
680 assert(p);
681
682 /* Similar to path_make_absolute(), but prefixes with the
683 * current working directory. */
684
685 if (path_is_absolute(p))
686 return strdup(p);
687
688 if (!(cwd = get_current_dir_name()))
689 return NULL;
690
691 r = path_make_absolute(p, cwd);
692 free(cwd);
693
694 return r;
695}
696
697char **strv_path_make_absolute_cwd(char **l) {
698 char **s;
699
700 /* Goes through every item in the string list and makes it
701 * absolute. This works in place and won't rollback any
702 * changes on failure. */
703
704 STRV_FOREACH(s, l) {
705 char *t;
706
707 if (!(t = path_make_absolute_cwd(*s)))
708 return NULL;
709
710 free(*s);
711 *s = t;
712 }
713
714 return l;
715}
716
c3f6d675
LP
717char **strv_path_canonicalize(char **l) {
718 char **s;
719 unsigned k = 0;
720 bool enomem = false;
721
722 if (strv_isempty(l))
723 return l;
724
725 /* Goes through every item in the string list and canonicalize
726 * the path. This works in place and won't rollback any
727 * changes on failure. */
728
729 STRV_FOREACH(s, l) {
730 char *t, *u;
731
732 t = path_make_absolute_cwd(*s);
733 free(*s);
734
735 if (!t) {
736 enomem = true;
737 continue;
738 }
739
740 errno = 0;
741 u = canonicalize_file_name(t);
742 free(t);
743
744 if (!u) {
745 if (errno == ENOMEM || !errno)
746 enomem = true;
747
748 continue;
749 }
750
751 l[k++] = u;
752 }
753
754 l[k] = NULL;
755
756 if (enomem)
757 return NULL;
758
759 return l;
760}
761
2a987ee8
LP
762int reset_all_signal_handlers(void) {
763 int sig;
764
765 for (sig = 1; sig < _NSIG; sig++) {
766 struct sigaction sa;
767
768 if (sig == SIGKILL || sig == SIGSTOP)
769 continue;
770
771 zero(sa);
772 sa.sa_handler = SIG_DFL;
431c32bf 773 sa.sa_flags = SA_RESTART;
2a987ee8
LP
774
775 /* On Linux the first two RT signals are reserved by
776 * glibc, and sigaction() will return EINVAL for them. */
777 if ((sigaction(sig, &sa, NULL) < 0))
778 if (errno != EINVAL)
779 return -errno;
780 }
781
8e274523 782 return 0;
2a987ee8 783}
4a72ff34
LP
784
785char *strstrip(char *s) {
786 char *e, *l = NULL;
787
788 /* Drops trailing whitespace. Modifies the string in
789 * place. Returns pointer to first non-space character */
790
791 s += strspn(s, WHITESPACE);
792
793 for (e = s; *e; e++)
794 if (!strchr(WHITESPACE, *e))
795 l = e;
796
797 if (l)
798 *(l+1) = 0;
799 else
800 *s = 0;
801
802 return s;
4a72ff34
LP
803}
804
ee9b5e01
LP
805char *delete_chars(char *s, const char *bad) {
806 char *f, *t;
807
808 /* Drops all whitespace, regardless where in the string */
809
810 for (f = s, t = s; *f; f++) {
811 if (strchr(bad, *f))
812 continue;
813
814 *(t++) = *f;
815 }
816
817 *t = 0;
818
819 return s;
820}
821
4a72ff34
LP
822char *file_in_same_dir(const char *path, const char *filename) {
823 char *e, *r;
824 size_t k;
825
826 assert(path);
827 assert(filename);
828
829 /* This removes the last component of path and appends
830 * filename, unless the latter is absolute anyway or the
831 * former isn't */
832
833 if (path_is_absolute(filename))
834 return strdup(filename);
835
836 if (!(e = strrchr(path, '/')))
837 return strdup(filename);
838
839 k = strlen(filename);
840 if (!(r = new(char, e-path+1+k+1)))
841 return NULL;
842
843 memcpy(r, path, e-path+1);
844 memcpy(r+(e-path)+1, filename, k+1);
845
846 return r;
847}
fb624d04 848
a9f5d454
LP
849int mkdir_parents(const char *path, mode_t mode) {
850 const char *p, *e;
851
852 assert(path);
853
854 /* Creates every parent directory in the path except the last
855 * component. */
856
857 p = path + strspn(path, "/");
858 for (;;) {
859 int r;
860 char *t;
861
862 e = p + strcspn(p, "/");
863 p = e + strspn(e, "/");
864
865 /* Is this the last component? If so, then we're
866 * done */
867 if (*p == 0)
868 return 0;
869
870 if (!(t = strndup(path, e - path)))
871 return -ENOMEM;
872
873 r = mkdir(t, mode);
874
875 free(t);
876
877 if (r < 0 && errno != EEXIST)
878 return -errno;
879 }
880}
881
bbd67135
LP
882int mkdir_p(const char *path, mode_t mode) {
883 int r;
884
885 /* Like mkdir -p */
886
887 if ((r = mkdir_parents(path, mode)) < 0)
888 return r;
889
890 if (mkdir(path, mode) < 0)
891 return -errno;
892
893 return 0;
894}
895
fb624d04
LP
896char hexchar(int x) {
897 static const char table[16] = "0123456789abcdef";
898
899 return table[x & 15];
900}
4fe88d28
LP
901
902int unhexchar(char c) {
903
904 if (c >= '0' && c <= '9')
905 return c - '0';
906
907 if (c >= 'a' && c <= 'f')
ea430986 908 return c - 'a' + 10;
4fe88d28
LP
909
910 if (c >= 'A' && c <= 'F')
ea430986 911 return c - 'A' + 10;
4fe88d28
LP
912
913 return -1;
914}
915
916char octchar(int x) {
917 return '0' + (x & 7);
918}
919
920int unoctchar(char c) {
921
922 if (c >= '0' && c <= '7')
923 return c - '0';
924
925 return -1;
926}
927
5af98f82
LP
928char decchar(int x) {
929 return '0' + (x % 10);
930}
931
932int undecchar(char c) {
933
934 if (c >= '0' && c <= '9')
935 return c - '0';
936
937 return -1;
938}
939
4fe88d28
LP
940char *cescape(const char *s) {
941 char *r, *t;
942 const char *f;
943
944 assert(s);
945
946 /* Does C style string escaping. */
947
948 if (!(r = new(char, strlen(s)*4 + 1)))
949 return NULL;
950
951 for (f = s, t = r; *f; f++)
952
953 switch (*f) {
954
955 case '\a':
956 *(t++) = '\\';
957 *(t++) = 'a';
958 break;
959 case '\b':
960 *(t++) = '\\';
961 *(t++) = 'b';
962 break;
963 case '\f':
964 *(t++) = '\\';
965 *(t++) = 'f';
966 break;
967 case '\n':
968 *(t++) = '\\';
969 *(t++) = 'n';
970 break;
971 case '\r':
972 *(t++) = '\\';
973 *(t++) = 'r';
974 break;
975 case '\t':
976 *(t++) = '\\';
977 *(t++) = 't';
978 break;
979 case '\v':
980 *(t++) = '\\';
981 *(t++) = 'v';
982 break;
983 case '\\':
984 *(t++) = '\\';
985 *(t++) = '\\';
986 break;
987 case '"':
988 *(t++) = '\\';
989 *(t++) = '"';
990 break;
991 case '\'':
992 *(t++) = '\\';
993 *(t++) = '\'';
994 break;
995
996 default:
997 /* For special chars we prefer octal over
998 * hexadecimal encoding, simply because glib's
999 * g_strescape() does the same */
1000 if ((*f < ' ') || (*f >= 127)) {
1001 *(t++) = '\\';
1002 *(t++) = octchar((unsigned char) *f >> 6);
1003 *(t++) = octchar((unsigned char) *f >> 3);
1004 *(t++) = octchar((unsigned char) *f);
1005 } else
1006 *(t++) = *f;
1007 break;
1008 }
1009
1010 *t = 0;
1011
1012 return r;
1013}
1014
1015char *cunescape(const char *s) {
1016 char *r, *t;
1017 const char *f;
1018
1019 assert(s);
1020
1021 /* Undoes C style string escaping */
1022
1023 if (!(r = new(char, strlen(s)+1)))
1024 return r;
1025
1026 for (f = s, t = r; *f; f++) {
1027
1028 if (*f != '\\') {
1029 *(t++) = *f;
1030 continue;
1031 }
1032
1033 f++;
1034
1035 switch (*f) {
1036
1037 case 'a':
1038 *(t++) = '\a';
1039 break;
1040 case 'b':
1041 *(t++) = '\b';
1042 break;
1043 case 'f':
1044 *(t++) = '\f';
1045 break;
1046 case 'n':
1047 *(t++) = '\n';
1048 break;
1049 case 'r':
1050 *(t++) = '\r';
1051 break;
1052 case 't':
1053 *(t++) = '\t';
1054 break;
1055 case 'v':
1056 *(t++) = '\v';
1057 break;
1058 case '\\':
1059 *(t++) = '\\';
1060 break;
1061 case '"':
1062 *(t++) = '"';
1063 break;
1064 case '\'':
1065 *(t++) = '\'';
1066 break;
1067
1068 case 'x': {
1069 /* hexadecimal encoding */
1070 int a, b;
1071
1072 if ((a = unhexchar(f[1])) < 0 ||
1073 (b = unhexchar(f[2])) < 0) {
1074 /* Invalid escape code, let's take it literal then */
1075 *(t++) = '\\';
1076 *(t++) = 'x';
1077 } else {
1078 *(t++) = (char) ((a << 4) | b);
1079 f += 2;
1080 }
1081
1082 break;
1083 }
1084
1085 case '0':
1086 case '1':
1087 case '2':
1088 case '3':
1089 case '4':
1090 case '5':
1091 case '6':
1092 case '7': {
1093 /* octal encoding */
1094 int a, b, c;
1095
1096 if ((a = unoctchar(f[0])) < 0 ||
1097 (b = unoctchar(f[1])) < 0 ||
1098 (c = unoctchar(f[2])) < 0) {
1099 /* Invalid escape code, let's take it literal then */
1100 *(t++) = '\\';
1101 *(t++) = f[0];
1102 } else {
1103 *(t++) = (char) ((a << 6) | (b << 3) | c);
1104 f += 2;
1105 }
1106
1107 break;
1108 }
1109
1110 case 0:
1111 /* premature end of string.*/
1112 *(t++) = '\\';
1113 goto finish;
1114
1115 default:
1116 /* Invalid escape code, let's take it literal then */
1117 *(t++) = '\\';
1118 *(t++) = 'f';
1119 break;
1120 }
1121 }
1122
1123finish:
1124 *t = 0;
1125 return r;
1126}
1127
1128
1129char *xescape(const char *s, const char *bad) {
1130 char *r, *t;
1131 const char *f;
1132
1133 /* Escapes all chars in bad, in addition to \ and all special
1134 * chars, in \xFF style escaping. May be reversed with
1135 * cunescape. */
1136
1137 if (!(r = new(char, strlen(s)*4+1)))
1138 return NULL;
1139
1140 for (f = s, t = r; *f; f++) {
1141
b866264a
LP
1142 if ((*f < ' ') || (*f >= 127) ||
1143 (*f == '\\') || strchr(bad, *f)) {
4fe88d28
LP
1144 *(t++) = '\\';
1145 *(t++) = 'x';
1146 *(t++) = hexchar(*f >> 4);
1147 *(t++) = hexchar(*f);
1148 } else
1149 *(t++) = *f;
1150 }
1151
1152 *t = 0;
1153
1154 return r;
1155}
1156
ea430986 1157char *bus_path_escape(const char *s) {
ea430986
LP
1158 char *r, *t;
1159 const char *f;
1160
47be870b
LP
1161 assert(s);
1162
ea430986
LP
1163 /* Escapes all chars that D-Bus' object path cannot deal
1164 * with. Can be reverse with bus_path_unescape() */
1165
1166 if (!(r = new(char, strlen(s)*3+1)))
1167 return NULL;
1168
1169 for (f = s, t = r; *f; f++) {
1170
1171 if (!(*f >= 'A' && *f <= 'Z') &&
1172 !(*f >= 'a' && *f <= 'z') &&
1173 !(*f >= '0' && *f <= '9')) {
1174 *(t++) = '_';
1175 *(t++) = hexchar(*f >> 4);
1176 *(t++) = hexchar(*f);
1177 } else
1178 *(t++) = *f;
1179 }
1180
1181 *t = 0;
1182
1183 return r;
1184}
1185
9e2f7c11 1186char *bus_path_unescape(const char *f) {
ea430986 1187 char *r, *t;
ea430986 1188
9e2f7c11 1189 assert(f);
47be870b 1190
9e2f7c11 1191 if (!(r = strdup(f)))
ea430986
LP
1192 return NULL;
1193
9e2f7c11 1194 for (t = r; *f; f++) {
ea430986
LP
1195
1196 if (*f == '_') {
1197 int a, b;
1198
1199 if ((a = unhexchar(f[1])) < 0 ||
1200 (b = unhexchar(f[2])) < 0) {
1201 /* Invalid escape code, let's take it literal then */
1202 *(t++) = '_';
1203 } else {
1204 *(t++) = (char) ((a << 4) | b);
1205 f += 2;
1206 }
1207 } else
1208 *(t++) = *f;
1209 }
1210
1211 *t = 0;
1212
1213 return r;
1214}
1215
4fe88d28
LP
1216char *path_kill_slashes(char *path) {
1217 char *f, *t;
1218 bool slash = false;
1219
1220 /* Removes redundant inner and trailing slashes. Modifies the
1221 * passed string in-place.
1222 *
1223 * ///foo///bar/ becomes /foo/bar
1224 */
1225
1226 for (f = path, t = path; *f; f++) {
1227
1228 if (*f == '/') {
1229 slash = true;
1230 continue;
1231 }
1232
1233 if (slash) {
1234 slash = false;
1235 *(t++) = '/';
1236 }
1237
1238 *(t++) = *f;
1239 }
1240
1241 /* Special rule, if we are talking of the root directory, a
1242 trailing slash is good */
1243
1244 if (t == path && slash)
1245 *(t++) = '/';
1246
1247 *t = 0;
1248 return path;
1249}
1250
1251bool path_startswith(const char *path, const char *prefix) {
1252 assert(path);
1253 assert(prefix);
1254
1255 if ((path[0] == '/') != (prefix[0] == '/'))
1256 return false;
1257
1258 for (;;) {
1259 size_t a, b;
1260
1261 path += strspn(path, "/");
1262 prefix += strspn(prefix, "/");
1263
1264 if (*prefix == 0)
1265 return true;
1266
1267 if (*path == 0)
1268 return false;
1269
1270 a = strcspn(path, "/");
1271 b = strcspn(prefix, "/");
1272
1273 if (a != b)
1274 return false;
1275
1276 if (memcmp(path, prefix, a) != 0)
1277 return false;
1278
1279 path += a;
1280 prefix += b;
1281 }
1282}
1283
15ae422b
LP
1284bool path_equal(const char *a, const char *b) {
1285 assert(a);
1286 assert(b);
1287
1288 if ((a[0] == '/') != (b[0] == '/'))
1289 return false;
1290
1291 for (;;) {
1292 size_t j, k;
1293
1294 a += strspn(a, "/");
1295 b += strspn(b, "/");
1296
1297 if (*a == 0 && *b == 0)
1298 return true;
1299
1300 if (*a == 0 || *b == 0)
1301 return false;
1302
1303 j = strcspn(a, "/");
1304 k = strcspn(b, "/");
1305
1306 if (j != k)
1307 return false;
1308
1309 if (memcmp(a, b, j) != 0)
1310 return false;
1311
1312 a += j;
1313 b += k;
1314 }
1315}
1316
67d51650 1317char *ascii_strlower(char *t) {
4fe88d28
LP
1318 char *p;
1319
67d51650 1320 assert(t);
4fe88d28 1321
67d51650 1322 for (p = t; *p; p++)
4fe88d28
LP
1323 if (*p >= 'A' && *p <= 'Z')
1324 *p = *p - 'A' + 'a';
1325
67d51650 1326 return t;
4fe88d28 1327}
1dccbe19 1328
c85dc17b
LP
1329bool ignore_file(const char *filename) {
1330 assert(filename);
1331
1332 return
1333 filename[0] == '.' ||
6c78be3c 1334 streq(filename, "lost+found") ||
c85dc17b
LP
1335 endswith(filename, "~") ||
1336 endswith(filename, ".rpmnew") ||
1337 endswith(filename, ".rpmsave") ||
1338 endswith(filename, ".rpmorig") ||
1339 endswith(filename, ".dpkg-old") ||
1340 endswith(filename, ".dpkg-new") ||
1341 endswith(filename, ".swp");
1342}
1343
3a0ecb08
LP
1344int fd_nonblock(int fd, bool nonblock) {
1345 int flags;
1346
1347 assert(fd >= 0);
1348
1349 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1350 return -errno;
1351
1352 if (nonblock)
1353 flags |= O_NONBLOCK;
1354 else
1355 flags &= ~O_NONBLOCK;
1356
1357 if (fcntl(fd, F_SETFL, flags) < 0)
1358 return -errno;
1359
1360 return 0;
1361}
1362
1363int fd_cloexec(int fd, bool cloexec) {
1364 int flags;
1365
1366 assert(fd >= 0);
1367
1368 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1369 return -errno;
1370
1371 if (cloexec)
1372 flags |= FD_CLOEXEC;
1373 else
1374 flags &= ~FD_CLOEXEC;
1375
1376 if (fcntl(fd, F_SETFD, flags) < 0)
1377 return -errno;
1378
1379 return 0;
1380}
1381
a0d40ac5
LP
1382int close_all_fds(const int except[], unsigned n_except) {
1383 DIR *d;
1384 struct dirent *de;
1385 int r = 0;
1386
1387 if (!(d = opendir("/proc/self/fd")))
1388 return -errno;
1389
1390 while ((de = readdir(d))) {
a7610064 1391 int fd = -1;
a0d40ac5 1392
a16e1123 1393 if (ignore_file(de->d_name))
a0d40ac5
LP
1394 continue;
1395
1396 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1397 goto finish;
1398
1399 if (fd < 3)
1400 continue;
1401
1402 if (fd == dirfd(d))
1403 continue;
1404
1405 if (except) {
1406 bool found;
1407 unsigned i;
1408
1409 found = false;
1410 for (i = 0; i < n_except; i++)
1411 if (except[i] == fd) {
1412 found = true;
1413 break;
1414 }
1415
1416 if (found)
1417 continue;
1418 }
1419
2f357920
LP
1420 if ((r = close_nointr(fd)) < 0) {
1421 /* Valgrind has its own FD and doesn't want to have it closed */
1422 if (errno != EBADF)
1423 goto finish;
1424 }
a0d40ac5
LP
1425 }
1426
2f357920
LP
1427 r = 0;
1428
a0d40ac5
LP
1429finish:
1430 closedir(d);
1431 return r;
1432}
1433
db12775d
LP
1434bool chars_intersect(const char *a, const char *b) {
1435 const char *p;
1436
1437 /* Returns true if any of the chars in a are in b. */
1438 for (p = a; *p; p++)
1439 if (strchr(b, *p))
1440 return true;
1441
1442 return false;
1443}
1444
8b6c7120
LP
1445char *format_timestamp(char *buf, size_t l, usec_t t) {
1446 struct tm tm;
1447 time_t sec;
1448
1449 assert(buf);
1450 assert(l > 0);
1451
1452 if (t <= 0)
1453 return NULL;
1454
1455 sec = (time_t) t / USEC_PER_SEC;
1456
1457 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1458 return NULL;
1459
1460 return buf;
1461}
1462
871d7de4
LP
1463char *format_timespan(char *buf, size_t l, usec_t t) {
1464 static const struct {
1465 const char *suffix;
1466 usec_t usec;
1467 } table[] = {
1468 { "w", USEC_PER_WEEK },
1469 { "d", USEC_PER_DAY },
1470 { "h", USEC_PER_HOUR },
1471 { "min", USEC_PER_MINUTE },
1472 { "s", USEC_PER_SEC },
1473 { "ms", USEC_PER_MSEC },
1474 { "us", 1 },
1475 };
1476
1477 unsigned i;
1478 char *p = buf;
1479
1480 assert(buf);
1481 assert(l > 0);
1482
1483 if (t == (usec_t) -1)
1484 return NULL;
1485
1486 /* The result of this function can be parsed with parse_usec */
1487
1488 for (i = 0; i < ELEMENTSOF(table); i++) {
1489 int k;
1490 size_t n;
1491
1492 if (t < table[i].usec)
1493 continue;
1494
1495 if (l <= 1)
1496 break;
1497
1498 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1499 n = MIN((size_t) k, l);
1500
1501 l -= n;
1502 p += n;
1503
1504 t %= table[i].usec;
1505 }
1506
1507 *p = 0;
1508
1509 return buf;
1510}
1511
42856c10
LP
1512bool fstype_is_network(const char *fstype) {
1513 static const char * const table[] = {
1514 "cifs",
1515 "smbfs",
1516 "ncpfs",
1517 "nfs",
ca139f94
LP
1518 "nfs4",
1519 "gfs",
1520 "gfs2"
42856c10
LP
1521 };
1522
1523 unsigned i;
1524
1525 for (i = 0; i < ELEMENTSOF(table); i++)
1526 if (streq(table[i], fstype))
1527 return true;
1528
1529 return false;
1530}
1531
601f6a1e
LP
1532int chvt(int vt) {
1533 int fd, r = 0;
1534
1535 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1536 return -errno;
1537
1538 if (vt < 0) {
1539 int tiocl[2] = {
1540 TIOCL_GETKMSGREDIRECT,
1541 0
1542 };
1543
1544 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1545 return -errno;
1546
1547 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1548 }
1549
1550 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1551 r = -errno;
1552
a16e1123 1553 close_nointr_nofail(r);
601f6a1e
LP
1554 return r;
1555}
1556
80876c20
LP
1557int read_one_char(FILE *f, char *ret, bool *need_nl) {
1558 struct termios old_termios, new_termios;
1559 char c;
1560 char line[1024];
1561
1562 assert(f);
1563 assert(ret);
1564
1565 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1566 new_termios = old_termios;
1567
1568 new_termios.c_lflag &= ~ICANON;
1569 new_termios.c_cc[VMIN] = 1;
1570 new_termios.c_cc[VTIME] = 0;
1571
1572 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1573 size_t k;
1574
1575 k = fread(&c, 1, 1, f);
1576
1577 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1578
1579 if (k <= 0)
1580 return -EIO;
1581
1582 if (need_nl)
1583 *need_nl = c != '\n';
1584
1585 *ret = c;
1586 return 0;
1587 }
1588 }
1589
1590 if (!(fgets(line, sizeof(line), f)))
1591 return -EIO;
1592
1593 truncate_nl(line);
1594
1595 if (strlen(line) != 1)
1596 return -EBADMSG;
1597
1598 if (need_nl)
1599 *need_nl = false;
1600
1601 *ret = line[0];
1602 return 0;
1603}
1604
1605int ask(char *ret, const char *replies, const char *text, ...) {
1606 assert(ret);
1607 assert(replies);
1608 assert(text);
1609
1610 for (;;) {
1611 va_list ap;
1612 char c;
1613 int r;
1614 bool need_nl = true;
1615
b1b2dc0c
LP
1616 fputs("\x1B[1m", stdout);
1617
80876c20
LP
1618 va_start(ap, text);
1619 vprintf(text, ap);
1620 va_end(ap);
1621
b1b2dc0c
LP
1622 fputs("\x1B[0m", stdout);
1623
80876c20
LP
1624 fflush(stdout);
1625
1626 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1627
1628 if (r == -EBADMSG) {
1629 puts("Bad input, please try again.");
1630 continue;
1631 }
1632
1633 putchar('\n');
1634 return r;
1635 }
1636
1637 if (need_nl)
1638 putchar('\n');
1639
1640 if (strchr(replies, c)) {
1641 *ret = c;
1642 return 0;
1643 }
1644
1645 puts("Read unexpected character, please try again.");
1646 }
1647}
1648
1649int reset_terminal(int fd) {
1650 struct termios termios;
1651 int r = 0;
1652
1653 assert(fd >= 0);
1654
aaf694ca 1655 /* Set terminal to some sane defaults */
80876c20
LP
1656
1657 if (tcgetattr(fd, &termios) < 0) {
1658 r = -errno;
1659 goto finish;
1660 }
1661
aaf694ca
LP
1662 /* We only reset the stuff that matters to the software. How
1663 * hardware is set up we don't touch assuming that somebody
1664 * else will do that for us */
1665
1666 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
80876c20
LP
1667 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1668 termios.c_oflag |= ONLCR;
1669 termios.c_cflag |= CREAD;
1670 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1671
1672 termios.c_cc[VINTR] = 03; /* ^C */
1673 termios.c_cc[VQUIT] = 034; /* ^\ */
1674 termios.c_cc[VERASE] = 0177;
1675 termios.c_cc[VKILL] = 025; /* ^X */
1676 termios.c_cc[VEOF] = 04; /* ^D */
1677 termios.c_cc[VSTART] = 021; /* ^Q */
1678 termios.c_cc[VSTOP] = 023; /* ^S */
1679 termios.c_cc[VSUSP] = 032; /* ^Z */
1680 termios.c_cc[VLNEXT] = 026; /* ^V */
1681 termios.c_cc[VWERASE] = 027; /* ^W */
1682 termios.c_cc[VREPRINT] = 022; /* ^R */
aaf694ca
LP
1683 termios.c_cc[VEOL] = 0;
1684 termios.c_cc[VEOL2] = 0;
80876c20
LP
1685
1686 termios.c_cc[VTIME] = 0;
1687 termios.c_cc[VMIN] = 1;
1688
1689 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1690 r = -errno;
1691
1692finish:
1693 /* Just in case, flush all crap out */
1694 tcflush(fd, TCIOFLUSH);
1695
1696 return r;
1697}
1698
1699int open_terminal(const char *name, int mode) {
1700 int fd, r;
1701
1702 if ((fd = open(name, mode)) < 0)
1703 return -errno;
1704
1705 if ((r = isatty(fd)) < 0) {
1706 close_nointr_nofail(fd);
1707 return -errno;
1708 }
1709
1710 if (!r) {
1711 close_nointr_nofail(fd);
1712 return -ENOTTY;
1713 }
1714
1715 return fd;
1716}
1717
1718int flush_fd(int fd) {
1719 struct pollfd pollfd;
1720
1721 zero(pollfd);
1722 pollfd.fd = fd;
1723 pollfd.events = POLLIN;
1724
1725 for (;;) {
1726 char buf[1024];
1727 ssize_t l;
1728 int r;
1729
1730 if ((r = poll(&pollfd, 1, 0)) < 0) {
1731
1732 if (errno == EINTR)
1733 continue;
1734
1735 return -errno;
1736 }
1737
1738 if (r == 0)
1739 return 0;
1740
1741 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1742
1743 if (errno == EINTR)
1744 continue;
1745
1746 if (errno == EAGAIN)
1747 return 0;
1748
1749 return -errno;
1750 }
1751
1752 if (l <= 0)
1753 return 0;
1754 }
1755}
1756
21de3988 1757int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
bab45044 1758 int fd = -1, notify = -1, r, wd = -1;
80876c20
LP
1759
1760 assert(name);
1761
1762 /* We use inotify to be notified when the tty is closed. We
1763 * create the watch before checking if we can actually acquire
1764 * it, so that we don't lose any event.
1765 *
1766 * Note: strictly speaking this actually watches for the
1767 * device being closed, it does *not* really watch whether a
1768 * tty loses its controlling process. However, unless some
1769 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1770 * its tty otherwise this will not become a problem. As long
1771 * as the administrator makes sure not configure any service
1772 * on the same tty as an untrusted user this should not be a
1773 * problem. (Which he probably should not do anyway.) */
1774
1775 if (!fail && !force) {
1776 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1777 r = -errno;
1778 goto fail;
1779 }
1780
1781 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1782 r = -errno;
1783 goto fail;
1784 }
1785 }
1786
1787 for (;;) {
e3d1855b
LP
1788 if (notify >= 0)
1789 if ((r = flush_fd(notify)) < 0)
1790 goto fail;
80876c20
LP
1791
1792 /* We pass here O_NOCTTY only so that we can check the return
1793 * value TIOCSCTTY and have a reliable way to figure out if we
1794 * successfully became the controlling process of the tty */
1795 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1796 return -errno;
1797
1798 /* First, try to get the tty */
21de3988
LP
1799 r = ioctl(fd, TIOCSCTTY, force);
1800
1801 /* Sometimes it makes sense to ignore TIOCSCTTY
1802 * returning EPERM, i.e. when very likely we already
1803 * are have this controlling terminal. */
1804 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1805 r = 0;
1806
1807 if (r < 0 && (force || fail || errno != EPERM)) {
80876c20
LP
1808 r = -errno;
1809 goto fail;
1810 }
1811
1812 if (r >= 0)
1813 break;
1814
1815 assert(!fail);
1816 assert(!force);
1817 assert(notify >= 0);
1818
1819 for (;;) {
1820 struct inotify_event e;
1821 ssize_t l;
1822
1823 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1824
1825 if (l < 0) {
1826
1827 if (errno == EINTR)
1828 continue;
1829
1830 r = -errno;
1831 } else
1832 r = -EIO;
1833
1834 goto fail;
1835 }
1836
1837 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1838 r = -errno;
1839 goto fail;
1840 }
1841
1842 break;
1843 }
1844
1845 /* We close the tty fd here since if the old session
1846 * ended our handle will be dead. It's important that
1847 * we do this after sleeping, so that we don't enter
1848 * an endless loop. */
1849 close_nointr_nofail(fd);
1850 }
1851
1852 if (notify >= 0)
a16e1123 1853 close_nointr_nofail(notify);
80876c20
LP
1854
1855 if ((r = reset_terminal(fd)) < 0)
1856 log_warning("Failed to reset terminal: %s", strerror(-r));
1857
1858 return fd;
1859
1860fail:
1861 if (fd >= 0)
a16e1123 1862 close_nointr_nofail(fd);
80876c20
LP
1863
1864 if (notify >= 0)
a16e1123 1865 close_nointr_nofail(notify);
80876c20
LP
1866
1867 return r;
1868}
1869
1870int release_terminal(void) {
1871 int r = 0, fd;
57cd2192 1872 struct sigaction sa_old, sa_new;
80876c20 1873
57cd2192 1874 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
80876c20
LP
1875 return -errno;
1876
57cd2192
LP
1877 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1878 * by our own TIOCNOTTY */
1879
1880 zero(sa_new);
1881 sa_new.sa_handler = SIG_IGN;
1882 sa_new.sa_flags = SA_RESTART;
1883 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1884
80876c20
LP
1885 if (ioctl(fd, TIOCNOTTY) < 0)
1886 r = -errno;
1887
57cd2192
LP
1888 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1889
80876c20
LP
1890 close_nointr_nofail(fd);
1891 return r;
1892}
1893
9a34ec5f
LP
1894int sigaction_many(const struct sigaction *sa, ...) {
1895 va_list ap;
1896 int r = 0, sig;
1897
1898 va_start(ap, sa);
1899 while ((sig = va_arg(ap, int)) > 0)
1900 if (sigaction(sig, sa, NULL) < 0)
1901 r = -errno;
1902 va_end(ap);
1903
1904 return r;
1905}
1906
1907int ignore_signals(int sig, ...) {
a337c6fc 1908 struct sigaction sa;
9a34ec5f
LP
1909 va_list ap;
1910 int r = 0;
a337c6fc
LP
1911
1912 zero(sa);
1913 sa.sa_handler = SIG_IGN;
1914 sa.sa_flags = SA_RESTART;
1915
9a34ec5f
LP
1916 if (sigaction(sig, &sa, NULL) < 0)
1917 r = -errno;
1918
1919 va_start(ap, sig);
1920 while ((sig = va_arg(ap, int)) > 0)
1921 if (sigaction(sig, &sa, NULL) < 0)
1922 r = -errno;
1923 va_end(ap);
1924
1925 return r;
1926}
1927
1928int default_signals(int sig, ...) {
1929 struct sigaction sa;
1930 va_list ap;
1931 int r = 0;
1932
1933 zero(sa);
1934 sa.sa_handler = SIG_DFL;
1935 sa.sa_flags = SA_RESTART;
1936
1937 if (sigaction(sig, &sa, NULL) < 0)
1938 r = -errno;
1939
1940 va_start(ap, sig);
1941 while ((sig = va_arg(ap, int)) > 0)
1942 if (sigaction(sig, &sa, NULL) < 0)
1943 r = -errno;
1944 va_end(ap);
1945
1946 return r;
a337c6fc
LP
1947}
1948
8d567588
LP
1949int close_pipe(int p[]) {
1950 int a = 0, b = 0;
1951
1952 assert(p);
1953
1954 if (p[0] >= 0) {
1955 a = close_nointr(p[0]);
1956 p[0] = -1;
1957 }
1958
1959 if (p[1] >= 0) {
1960 b = close_nointr(p[1]);
1961 p[1] = -1;
1962 }
1963
1964 return a < 0 ? a : b;
1965}
1966
eb22ac37 1967ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
8d567588
LP
1968 uint8_t *p;
1969 ssize_t n = 0;
1970
1971 assert(fd >= 0);
1972 assert(buf);
1973
1974 p = buf;
1975
1976 while (nbytes > 0) {
1977 ssize_t k;
1978
1979 if ((k = read(fd, p, nbytes)) <= 0) {
1980
eb22ac37 1981 if (k < 0 && errno == EINTR)
8d567588
LP
1982 continue;
1983
eb22ac37 1984 if (k < 0 && errno == EAGAIN && do_poll) {
8d567588
LP
1985 struct pollfd pollfd;
1986
1987 zero(pollfd);
1988 pollfd.fd = fd;
1989 pollfd.events = POLLIN;
1990
1991 if (poll(&pollfd, 1, -1) < 0) {
1992 if (errno == EINTR)
1993 continue;
1994
1995 return n > 0 ? n : -errno;
1996 }
1997
1998 if (pollfd.revents != POLLIN)
1999 return n > 0 ? n : -EIO;
2000
2001 continue;
2002 }
2003
2004 return n > 0 ? n : (k < 0 ? -errno : 0);
2005 }
2006
2007 p += k;
2008 nbytes -= k;
2009 n += k;
2010 }
2011
2012 return n;
2013}
2014
eb22ac37
LP
2015ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2016 const uint8_t *p;
2017 ssize_t n = 0;
2018
2019 assert(fd >= 0);
2020 assert(buf);
2021
2022 p = buf;
2023
2024 while (nbytes > 0) {
2025 ssize_t k;
2026
2027 if ((k = write(fd, p, nbytes)) <= 0) {
2028
2029 if (k < 0 && errno == EINTR)
2030 continue;
2031
2032 if (k < 0 && errno == EAGAIN && do_poll) {
2033 struct pollfd pollfd;
2034
2035 zero(pollfd);
2036 pollfd.fd = fd;
2037 pollfd.events = POLLOUT;
2038
2039 if (poll(&pollfd, 1, -1) < 0) {
2040 if (errno == EINTR)
2041 continue;
2042
2043 return n > 0 ? n : -errno;
2044 }
2045
2046 if (pollfd.revents != POLLOUT)
2047 return n > 0 ? n : -EIO;
2048
2049 continue;
2050 }
2051
2052 return n > 0 ? n : (k < 0 ? -errno : 0);
2053 }
2054
2055 p += k;
2056 nbytes -= k;
2057 n += k;
2058 }
2059
2060 return n;
2061}
2062
8d567588
LP
2063int path_is_mount_point(const char *t) {
2064 struct stat a, b;
2065 char *copy;
2066
2067 if (lstat(t, &a) < 0) {
2068
2069 if (errno == ENOENT)
2070 return 0;
2071
2072 return -errno;
2073 }
2074
2075 if (!(copy = strdup(t)))
2076 return -ENOMEM;
2077
2078 if (lstat(dirname(copy), &b) < 0) {
2079 free(copy);
2080 return -errno;
2081 }
2082
2083 free(copy);
2084
2085 return a.st_dev != b.st_dev;
2086}
2087
24a6e4a4
LP
2088int parse_usec(const char *t, usec_t *usec) {
2089 static const struct {
2090 const char *suffix;
2091 usec_t usec;
2092 } table[] = {
2093 { "sec", USEC_PER_SEC },
2094 { "s", USEC_PER_SEC },
2095 { "min", USEC_PER_MINUTE },
2096 { "hr", USEC_PER_HOUR },
2097 { "h", USEC_PER_HOUR },
2098 { "d", USEC_PER_DAY },
2099 { "w", USEC_PER_WEEK },
2100 { "msec", USEC_PER_MSEC },
2101 { "ms", USEC_PER_MSEC },
2102 { "m", USEC_PER_MINUTE },
2103 { "usec", 1ULL },
2104 { "us", 1ULL },
2105 { "", USEC_PER_SEC },
2106 };
2107
2108 const char *p;
2109 usec_t r = 0;
2110
2111 assert(t);
2112 assert(usec);
2113
2114 p = t;
2115 do {
2116 long long l;
2117 char *e;
2118 unsigned i;
2119
2120 errno = 0;
2121 l = strtoll(p, &e, 10);
2122
2123 if (errno != 0)
2124 return -errno;
2125
2126 if (l < 0)
2127 return -ERANGE;
2128
2129 if (e == p)
2130 return -EINVAL;
2131
2132 e += strspn(e, WHITESPACE);
2133
2134 for (i = 0; i < ELEMENTSOF(table); i++)
2135 if (startswith(e, table[i].suffix)) {
2136 r += (usec_t) l * table[i].usec;
2137 p = e + strlen(table[i].suffix);
2138 break;
2139 }
2140
2141 if (i >= ELEMENTSOF(table))
2142 return -EINVAL;
2143
2144 } while (*p != 0);
2145
2146 *usec = r;
2147
2148 return 0;
2149}
2150
843d2643
LP
2151int make_stdio(int fd) {
2152 int r, s, t;
2153
2154 assert(fd >= 0);
2155
2156 r = dup2(fd, STDIN_FILENO);
2157 s = dup2(fd, STDOUT_FILENO);
2158 t = dup2(fd, STDERR_FILENO);
2159
2160 if (fd >= 3)
2161 close_nointr_nofail(fd);
2162
2163 if (r < 0 || s < 0 || t < 0)
2164 return -errno;
2165
2166 return 0;
2167}
2168
cb8a8f78
LP
2169bool is_clean_exit(int code, int status) {
2170
2171 if (code == CLD_EXITED)
2172 return status == 0;
2173
2174 /* If a daemon does not implement handlers for some of the
2175 * signals that's not considered an unclean shutdown */
2176 if (code == CLD_KILLED)
2177 return
2178 status == SIGHUP ||
2179 status == SIGINT ||
2180 status == SIGTERM ||
2181 status == SIGPIPE;
2182
2183 return false;
2184}
2185
8407a5d0
LP
2186bool is_device_path(const char *path) {
2187
2188 /* Returns true on paths that refer to a device, either in
2189 * sysfs or in /dev */
2190
2191 return
2192 path_startswith(path, "/dev/") ||
2193 path_startswith(path, "/sys/");
2194}
2195
01f78473
LP
2196int dir_is_empty(const char *path) {
2197 DIR *d;
2198 int r;
2199 struct dirent buf, *de;
2200
2201 if (!(d = opendir(path)))
2202 return -errno;
2203
2204 for (;;) {
2205 if ((r = readdir_r(d, &buf, &de)) > 0) {
2206 r = -r;
2207 break;
2208 }
2209
2210 if (!de) {
2211 r = 1;
2212 break;
2213 }
2214
2215 if (!ignore_file(de->d_name)) {
2216 r = 0;
2217 break;
2218 }
2219 }
2220
2221 closedir(d);
2222 return r;
2223}
2224
d3782d60
LP
2225unsigned long long random_ull(void) {
2226 int fd;
2227 uint64_t ull;
2228 ssize_t r;
2229
2230 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2231 goto fallback;
2232
eb22ac37 2233 r = loop_read(fd, &ull, sizeof(ull), true);
d3782d60
LP
2234 close_nointr_nofail(fd);
2235
2236 if (r != sizeof(ull))
2237 goto fallback;
2238
2239 return ull;
2240
2241fallback:
2242 return random() * RAND_MAX + random();
2243}
2244
5b6319dc
LP
2245void rename_process(const char name[8]) {
2246 assert(name);
2247
2248 prctl(PR_SET_NAME, name);
2249
2250 /* This is a like a poor man's setproctitle(). The string
2251 * passed should fit in 7 chars (i.e. the length of
2252 * "systemd") */
2253
2254 if (program_invocation_name)
2255 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2256}
2257
7d793605
LP
2258void sigset_add_many(sigset_t *ss, ...) {
2259 va_list ap;
2260 int sig;
2261
2262 assert(ss);
2263
2264 va_start(ap, ss);
2265 while ((sig = va_arg(ap, int)) > 0)
2266 assert_se(sigaddset(ss, sig) == 0);
2267 va_end(ap);
2268}
2269
ef2f1067
LP
2270char* gethostname_malloc(void) {
2271 struct utsname u;
2272
2273 assert_se(uname(&u) >= 0);
2274
2275 if (u.nodename[0])
2276 return strdup(u.nodename);
2277
2278 return strdup(u.sysname);
2279}
2280
2281char* getlogname_malloc(void) {
2282 uid_t uid;
2283 long bufsize;
2284 char *buf, *name;
2285 struct passwd pwbuf, *pw = NULL;
2286 struct stat st;
2287
2288 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2289 uid = st.st_uid;
2290 else
2291 uid = getuid();
2292
2293 /* Shortcut things to avoid NSS lookups */
2294 if (uid == 0)
2295 return strdup("root");
2296
2297 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2298 bufsize = 4096;
2299
2300 if (!(buf = malloc(bufsize)))
2301 return NULL;
2302
2303 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2304 name = strdup(pw->pw_name);
2305 free(buf);
2306 return name;
2307 }
2308
2309 free(buf);
2310
2311 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2312 return NULL;
2313
2314 return name;
2315}
2316
2317char *getttyname_malloc(void) {
2318 char path[PATH_MAX], *p;
2319
2320 if (ttyname_r(STDIN_FILENO, path, sizeof(path)) < 0)
2321 return strdup("unknown");
2322
2323 char_array_0(path);
2324
2325 p = path;
2326 if (startswith(path, "/dev/"))
2327 p += 5;
2328
2329 return strdup(p);
2330}
2331
1dccbe19
LP
2332static const char *const ioprio_class_table[] = {
2333 [IOPRIO_CLASS_NONE] = "none",
2334 [IOPRIO_CLASS_RT] = "realtime",
2335 [IOPRIO_CLASS_BE] = "best-effort",
2336 [IOPRIO_CLASS_IDLE] = "idle"
2337};
2338
2339DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2340
2341static const char *const sigchld_code_table[] = {
2342 [CLD_EXITED] = "exited",
2343 [CLD_KILLED] = "killed",
2344 [CLD_DUMPED] = "dumped",
2345 [CLD_TRAPPED] = "trapped",
2346 [CLD_STOPPED] = "stopped",
2347 [CLD_CONTINUED] = "continued",
2348};
2349
2350DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2351
2352static const char *const log_facility_table[LOG_NFACILITIES] = {
2353 [LOG_FAC(LOG_KERN)] = "kern",
2354 [LOG_FAC(LOG_USER)] = "user",
2355 [LOG_FAC(LOG_MAIL)] = "mail",
2356 [LOG_FAC(LOG_DAEMON)] = "daemon",
2357 [LOG_FAC(LOG_AUTH)] = "auth",
2358 [LOG_FAC(LOG_SYSLOG)] = "syslog",
2359 [LOG_FAC(LOG_LPR)] = "lpr",
2360 [LOG_FAC(LOG_NEWS)] = "news",
2361 [LOG_FAC(LOG_UUCP)] = "uucp",
2362 [LOG_FAC(LOG_CRON)] = "cron",
2363 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2364 [LOG_FAC(LOG_FTP)] = "ftp",
2365 [LOG_FAC(LOG_LOCAL0)] = "local0",
2366 [LOG_FAC(LOG_LOCAL1)] = "local1",
2367 [LOG_FAC(LOG_LOCAL2)] = "local2",
2368 [LOG_FAC(LOG_LOCAL3)] = "local3",
2369 [LOG_FAC(LOG_LOCAL4)] = "local4",
2370 [LOG_FAC(LOG_LOCAL5)] = "local5",
2371 [LOG_FAC(LOG_LOCAL6)] = "local6",
2372 [LOG_FAC(LOG_LOCAL7)] = "local7"
2373};
2374
2375DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2376
2377static const char *const log_level_table[] = {
2378 [LOG_EMERG] = "emerg",
2379 [LOG_ALERT] = "alert",
2380 [LOG_CRIT] = "crit",
2381 [LOG_ERR] = "err",
2382 [LOG_WARNING] = "warning",
2383 [LOG_NOTICE] = "notice",
2384 [LOG_INFO] = "info",
2385 [LOG_DEBUG] = "debug"
2386};
2387
2388DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2389
2390static const char* const sched_policy_table[] = {
2391 [SCHED_OTHER] = "other",
2392 [SCHED_BATCH] = "batch",
2393 [SCHED_IDLE] = "idle",
2394 [SCHED_FIFO] = "fifo",
2395 [SCHED_RR] = "rr"
2396};
2397
2398DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2399
2400static const char* const rlimit_table[] = {
2401 [RLIMIT_CPU] = "LimitCPU",
2402 [RLIMIT_FSIZE] = "LimitFSIZE",
2403 [RLIMIT_DATA] = "LimitDATA",
2404 [RLIMIT_STACK] = "LimitSTACK",
2405 [RLIMIT_CORE] = "LimitCORE",
2406 [RLIMIT_RSS] = "LimitRSS",
2407 [RLIMIT_NOFILE] = "LimitNOFILE",
2408 [RLIMIT_AS] = "LimitAS",
2409 [RLIMIT_NPROC] = "LimitNPROC",
2410 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2411 [RLIMIT_LOCKS] = "LimitLOCKS",
2412 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2413 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2414 [RLIMIT_NICE] = "LimitNICE",
2415 [RLIMIT_RTPRIO] = "LimitRTPRIO",
2416 [RLIMIT_RTTIME] = "LimitRTTIME"
2417};
2418
2419DEFINE_STRING_TABLE_LOOKUP(rlimit, int);