]> git.ipfire.org Git - people/ms/systemd.git/blob - util.c
core: add minimal templating system
[people/ms/systemd.git] / util.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
2
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
22 #include <assert.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <errno.h>
26 #include <stdlib.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <syslog.h>
30 #include <sched.h>
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <fcntl.h>
36 #include <dirent.h>
37 #include <sys/ioctl.h>
38 #include <linux/vt.h>
39 #include <linux/tiocl.h>
40 #include <termios.h>
41 #include <stdarg.h>
42 #include <sys/inotify.h>
43 #include <sys/poll.h>
44
45 #include "macro.h"
46 #include "util.h"
47 #include "ioprio.h"
48 #include "missing.h"
49 #include "log.h"
50 #include "strv.h"
51
52 bool streq_ptr(const char *a, const char *b) {
53
54 /* Like streq(), but tries to make sense of NULL pointers */
55
56 if (a && b)
57 return streq(a, b);
58
59 if (!a && !b)
60 return true;
61
62 return false;
63 }
64
65 usec_t now(clockid_t clock_id) {
66 struct timespec ts;
67
68 assert_se(clock_gettime(clock_id, &ts) == 0);
69
70 return timespec_load(&ts);
71 }
72
73 usec_t timespec_load(const struct timespec *ts) {
74 assert(ts);
75
76 return
77 (usec_t) ts->tv_sec * USEC_PER_SEC +
78 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
79 }
80
81 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
82 assert(ts);
83
84 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
85 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
86
87 return ts;
88 }
89
90 usec_t timeval_load(const struct timeval *tv) {
91 assert(tv);
92
93 return
94 (usec_t) tv->tv_sec * USEC_PER_SEC +
95 (usec_t) tv->tv_usec;
96 }
97
98 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
99 assert(tv);
100
101 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
102 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
103
104 return tv;
105 }
106
107 bool endswith(const char *s, const char *postfix) {
108 size_t sl, pl;
109
110 assert(s);
111 assert(postfix);
112
113 sl = strlen(s);
114 pl = strlen(postfix);
115
116 if (sl < pl)
117 return false;
118
119 return memcmp(s + sl - pl, postfix, pl) == 0;
120 }
121
122 bool startswith(const char *s, const char *prefix) {
123 size_t sl, pl;
124
125 assert(s);
126 assert(prefix);
127
128 sl = strlen(s);
129 pl = strlen(prefix);
130
131 if (sl < pl)
132 return false;
133
134 return memcmp(s, prefix, pl) == 0;
135 }
136
137 bool first_word(const char *s, const char *word) {
138 size_t sl, wl;
139
140 assert(s);
141 assert(word);
142
143 sl = strlen(s);
144 wl = strlen(word);
145
146 if (sl < wl)
147 return false;
148
149 if (memcmp(s, word, wl) != 0)
150 return false;
151
152 return (s[wl] == 0 ||
153 strchr(WHITESPACE, s[wl]));
154 }
155
156 int close_nointr(int fd) {
157 assert(fd >= 0);
158
159 for (;;) {
160 int r;
161
162 if ((r = close(fd)) >= 0)
163 return r;
164
165 if (errno != EINTR)
166 return r;
167 }
168 }
169
170 void close_nointr_nofail(int fd) {
171 int saved_errno = errno;
172
173 /* like close_nointr() but cannot fail, and guarantees errno
174 * is unchanged */
175
176 assert_se(close_nointr(fd) == 0);
177
178 errno = saved_errno;
179 }
180
181 int parse_boolean(const char *v) {
182 assert(v);
183
184 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
185 return 1;
186 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
187 return 0;
188
189 return -EINVAL;
190 }
191
192 int safe_atou(const char *s, unsigned *ret_u) {
193 char *x = NULL;
194 unsigned long l;
195
196 assert(s);
197 assert(ret_u);
198
199 errno = 0;
200 l = strtoul(s, &x, 0);
201
202 if (!x || *x || errno)
203 return errno ? -errno : -EINVAL;
204
205 if ((unsigned long) (unsigned) l != l)
206 return -ERANGE;
207
208 *ret_u = (unsigned) l;
209 return 0;
210 }
211
212 int safe_atoi(const char *s, int *ret_i) {
213 char *x = NULL;
214 long l;
215
216 assert(s);
217 assert(ret_i);
218
219 errno = 0;
220 l = strtol(s, &x, 0);
221
222 if (!x || *x || errno)
223 return errno ? -errno : -EINVAL;
224
225 if ((long) (int) l != l)
226 return -ERANGE;
227
228 *ret_i = (int) l;
229 return 0;
230 }
231
232 int safe_atolu(const char *s, long unsigned *ret_lu) {
233 char *x = NULL;
234 unsigned long l;
235
236 assert(s);
237 assert(ret_lu);
238
239 errno = 0;
240 l = strtoul(s, &x, 0);
241
242 if (!x || *x || errno)
243 return errno ? -errno : -EINVAL;
244
245 *ret_lu = l;
246 return 0;
247 }
248
249 int safe_atoli(const char *s, long int *ret_li) {
250 char *x = NULL;
251 long l;
252
253 assert(s);
254 assert(ret_li);
255
256 errno = 0;
257 l = strtol(s, &x, 0);
258
259 if (!x || *x || errno)
260 return errno ? -errno : -EINVAL;
261
262 *ret_li = l;
263 return 0;
264 }
265
266 int safe_atollu(const char *s, long long unsigned *ret_llu) {
267 char *x = NULL;
268 unsigned long long l;
269
270 assert(s);
271 assert(ret_llu);
272
273 errno = 0;
274 l = strtoull(s, &x, 0);
275
276 if (!x || *x || errno)
277 return errno ? -errno : -EINVAL;
278
279 *ret_llu = l;
280 return 0;
281 }
282
283 int safe_atolli(const char *s, long long int *ret_lli) {
284 char *x = NULL;
285 long long l;
286
287 assert(s);
288 assert(ret_lli);
289
290 errno = 0;
291 l = strtoll(s, &x, 0);
292
293 if (!x || *x || errno)
294 return errno ? -errno : -EINVAL;
295
296 *ret_lli = l;
297 return 0;
298 }
299
300 /* Split a string into words. */
301 char *split(const char *c, size_t *l, const char *separator, char **state) {
302 char *current;
303
304 current = *state ? *state : (char*) c;
305
306 if (!*current || *c == 0)
307 return NULL;
308
309 current += strspn(current, separator);
310 *l = strcspn(current, separator);
311 *state = current+*l;
312
313 return (char*) current;
314 }
315
316 /* Split a string into words, but consider strings enclosed in '' and
317 * "" as words even if they include spaces. */
318 char *split_quoted(const char *c, size_t *l, char **state) {
319 char *current;
320
321 current = *state ? *state : (char*) c;
322
323 if (!*current || *c == 0)
324 return NULL;
325
326 current += strspn(current, WHITESPACE);
327
328 if (*current == '\'') {
329 current ++;
330 *l = strcspn(current, "'");
331 *state = current+*l;
332
333 if (**state == '\'')
334 (*state)++;
335 } else if (*current == '\"') {
336 current ++;
337 *l = strcspn(current, "\"");
338 *state = current+*l;
339
340 if (**state == '\"')
341 (*state)++;
342 } else {
343 *l = strcspn(current, WHITESPACE);
344 *state = current+*l;
345 }
346
347 /* FIXME: Cannot deal with strings that have spaces AND ticks
348 * in them */
349
350 return (char*) current;
351 }
352
353 char **split_path_and_make_absolute(const char *p) {
354 char **l;
355 assert(p);
356
357 if (!(l = strv_split(p, ":")))
358 return NULL;
359
360 if (!strv_path_make_absolute_cwd(l)) {
361 strv_free(l);
362 return NULL;
363 }
364
365 return l;
366 }
367
368 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
369 int r;
370 FILE *f;
371 char fn[132], line[256], *p;
372 long long unsigned ppid;
373
374 assert(pid >= 0);
375 assert(_ppid);
376
377 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%llu/stat", (unsigned long long) pid) < (int) (sizeof(fn)-1));
378 fn[sizeof(fn)-1] = 0;
379
380 if (!(f = fopen(fn, "r")))
381 return -errno;
382
383 if (!(fgets(line, sizeof(line), f))) {
384 r = -errno;
385 fclose(f);
386 return r;
387 }
388
389 fclose(f);
390
391 /* Let's skip the pid and comm fields. The latter is enclosed
392 * in () but does not escape any () in its value, so let's
393 * skip over it manually */
394
395 if (!(p = strrchr(line, ')')))
396 return -EIO;
397
398 p++;
399
400 if (sscanf(p, " "
401 "%*c " /* state */
402 "%llu ", /* ppid */
403 &ppid) != 1)
404 return -EIO;
405
406 if ((long long unsigned) (pid_t) ppid != ppid)
407 return -ERANGE;
408
409 *_ppid = (pid_t) ppid;
410
411 return 0;
412 }
413
414 int write_one_line_file(const char *fn, const char *line) {
415 FILE *f;
416 int r;
417
418 assert(fn);
419 assert(line);
420
421 if (!(f = fopen(fn, "we")))
422 return -errno;
423
424 if (fputs(line, f) < 0) {
425 r = -errno;
426 goto finish;
427 }
428
429 r = 0;
430 finish:
431 fclose(f);
432 return r;
433 }
434
435 int read_one_line_file(const char *fn, char **line) {
436 FILE *f;
437 int r;
438 char t[2048], *c;
439
440 assert(fn);
441 assert(line);
442
443 if (!(f = fopen(fn, "re")))
444 return -errno;
445
446 if (!(fgets(t, sizeof(t), f))) {
447 r = -errno;
448 goto finish;
449 }
450
451 if (!(c = strdup(t))) {
452 r = -ENOMEM;
453 goto finish;
454 }
455
456 *line = c;
457 r = 0;
458
459 finish:
460 fclose(f);
461 return r;
462 }
463
464 char *truncate_nl(char *s) {
465 assert(s);
466
467 s[strcspn(s, NEWLINE)] = 0;
468 return s;
469 }
470
471 int get_process_name(pid_t pid, char **name) {
472 char *p;
473 int r;
474
475 assert(pid >= 1);
476 assert(name);
477
478 if (asprintf(&p, "/proc/%llu/comm", (unsigned long long) pid) < 0)
479 return -ENOMEM;
480
481 r = read_one_line_file(p, name);
482 free(p);
483
484 if (r < 0)
485 return r;
486
487 truncate_nl(*name);
488 return 0;
489 }
490
491 char *strappend(const char *s, const char *suffix) {
492 size_t a, b;
493 char *r;
494
495 assert(s);
496 assert(suffix);
497
498 a = strlen(s);
499 b = strlen(suffix);
500
501 if (!(r = new(char, a+b+1)))
502 return NULL;
503
504 memcpy(r, s, a);
505 memcpy(r+a, suffix, b);
506 r[a+b] = 0;
507
508 return r;
509 }
510
511 int readlink_malloc(const char *p, char **r) {
512 size_t l = 100;
513
514 assert(p);
515 assert(r);
516
517 for (;;) {
518 char *c;
519 ssize_t n;
520
521 if (!(c = new(char, l)))
522 return -ENOMEM;
523
524 if ((n = readlink(p, c, l-1)) < 0) {
525 int ret = -errno;
526 free(c);
527 return ret;
528 }
529
530 if ((size_t) n < l-1) {
531 c[n] = 0;
532 *r = c;
533 return 0;
534 }
535
536 free(c);
537 l *= 2;
538 }
539 }
540
541 char *file_name_from_path(const char *p) {
542 char *r;
543
544 assert(p);
545
546 if ((r = strrchr(p, '/')))
547 return r + 1;
548
549 return (char*) p;
550 }
551
552 bool path_is_absolute(const char *p) {
553 assert(p);
554
555 return p[0] == '/';
556 }
557
558 bool is_path(const char *p) {
559
560 return !!strchr(p, '/');
561 }
562
563 char *path_make_absolute(const char *p, const char *prefix) {
564 char *r;
565
566 assert(p);
567
568 /* Makes every item in the list an absolute path by prepending
569 * the prefix, if specified and necessary */
570
571 if (path_is_absolute(p) || !prefix)
572 return strdup(p);
573
574 if (asprintf(&r, "%s/%s", prefix, p) < 0)
575 return NULL;
576
577 return r;
578 }
579
580 char *path_make_absolute_cwd(const char *p) {
581 char *cwd, *r;
582
583 assert(p);
584
585 /* Similar to path_make_absolute(), but prefixes with the
586 * current working directory. */
587
588 if (path_is_absolute(p))
589 return strdup(p);
590
591 if (!(cwd = get_current_dir_name()))
592 return NULL;
593
594 r = path_make_absolute(p, cwd);
595 free(cwd);
596
597 return r;
598 }
599
600 char **strv_path_make_absolute_cwd(char **l) {
601 char **s;
602
603 /* Goes through every item in the string list and makes it
604 * absolute. This works in place and won't rollback any
605 * changes on failure. */
606
607 STRV_FOREACH(s, l) {
608 char *t;
609
610 if (!(t = path_make_absolute_cwd(*s)))
611 return NULL;
612
613 free(*s);
614 *s = t;
615 }
616
617 return l;
618 }
619
620 int reset_all_signal_handlers(void) {
621 int sig;
622
623 for (sig = 1; sig < _NSIG; sig++) {
624 struct sigaction sa;
625
626 if (sig == SIGKILL || sig == SIGSTOP)
627 continue;
628
629 zero(sa);
630 sa.sa_handler = SIG_DFL;
631 sa.sa_flags = SA_RESTART;
632
633 /* On Linux the first two RT signals are reserved by
634 * glibc, and sigaction() will return EINVAL for them. */
635 if ((sigaction(sig, &sa, NULL) < 0))
636 if (errno != EINVAL)
637 return -errno;
638 }
639
640 return 0;
641 }
642
643 char *strstrip(char *s) {
644 char *e, *l = NULL;
645
646 /* Drops trailing whitespace. Modifies the string in
647 * place. Returns pointer to first non-space character */
648
649 s += strspn(s, WHITESPACE);
650
651 for (e = s; *e; e++)
652 if (!strchr(WHITESPACE, *e))
653 l = e;
654
655 if (l)
656 *(l+1) = 0;
657 else
658 *s = 0;
659
660 return s;
661 }
662
663 char *delete_chars(char *s, const char *bad) {
664 char *f, *t;
665
666 /* Drops all whitespace, regardless where in the string */
667
668 for (f = s, t = s; *f; f++) {
669 if (strchr(bad, *f))
670 continue;
671
672 *(t++) = *f;
673 }
674
675 *t = 0;
676
677 return s;
678 }
679
680 char *file_in_same_dir(const char *path, const char *filename) {
681 char *e, *r;
682 size_t k;
683
684 assert(path);
685 assert(filename);
686
687 /* This removes the last component of path and appends
688 * filename, unless the latter is absolute anyway or the
689 * former isn't */
690
691 if (path_is_absolute(filename))
692 return strdup(filename);
693
694 if (!(e = strrchr(path, '/')))
695 return strdup(filename);
696
697 k = strlen(filename);
698 if (!(r = new(char, e-path+1+k+1)))
699 return NULL;
700
701 memcpy(r, path, e-path+1);
702 memcpy(r+(e-path)+1, filename, k+1);
703
704 return r;
705 }
706
707 int mkdir_parents(const char *path, mode_t mode) {
708 const char *p, *e;
709
710 assert(path);
711
712 /* Creates every parent directory in the path except the last
713 * component. */
714
715 p = path + strspn(path, "/");
716 for (;;) {
717 int r;
718 char *t;
719
720 e = p + strcspn(p, "/");
721 p = e + strspn(e, "/");
722
723 /* Is this the last component? If so, then we're
724 * done */
725 if (*p == 0)
726 return 0;
727
728 if (!(t = strndup(path, e - path)))
729 return -ENOMEM;
730
731 r = mkdir(t, mode);
732
733 free(t);
734
735 if (r < 0 && errno != EEXIST)
736 return -errno;
737 }
738 }
739
740 int mkdir_p(const char *path, mode_t mode) {
741 int r;
742
743 /* Like mkdir -p */
744
745 if ((r = mkdir_parents(path, mode)) < 0)
746 return r;
747
748 if (mkdir(path, mode) < 0)
749 return -errno;
750
751 return 0;
752 }
753
754 char hexchar(int x) {
755 static const char table[16] = "0123456789abcdef";
756
757 return table[x & 15];
758 }
759
760 int unhexchar(char c) {
761
762 if (c >= '0' && c <= '9')
763 return c - '0';
764
765 if (c >= 'a' && c <= 'f')
766 return c - 'a' + 10;
767
768 if (c >= 'A' && c <= 'F')
769 return c - 'A' + 10;
770
771 return -1;
772 }
773
774 char octchar(int x) {
775 return '0' + (x & 7);
776 }
777
778 int unoctchar(char c) {
779
780 if (c >= '0' && c <= '7')
781 return c - '0';
782
783 return -1;
784 }
785
786 char decchar(int x) {
787 return '0' + (x % 10);
788 }
789
790 int undecchar(char c) {
791
792 if (c >= '0' && c <= '9')
793 return c - '0';
794
795 return -1;
796 }
797
798 char *cescape(const char *s) {
799 char *r, *t;
800 const char *f;
801
802 assert(s);
803
804 /* Does C style string escaping. */
805
806 if (!(r = new(char, strlen(s)*4 + 1)))
807 return NULL;
808
809 for (f = s, t = r; *f; f++)
810
811 switch (*f) {
812
813 case '\a':
814 *(t++) = '\\';
815 *(t++) = 'a';
816 break;
817 case '\b':
818 *(t++) = '\\';
819 *(t++) = 'b';
820 break;
821 case '\f':
822 *(t++) = '\\';
823 *(t++) = 'f';
824 break;
825 case '\n':
826 *(t++) = '\\';
827 *(t++) = 'n';
828 break;
829 case '\r':
830 *(t++) = '\\';
831 *(t++) = 'r';
832 break;
833 case '\t':
834 *(t++) = '\\';
835 *(t++) = 't';
836 break;
837 case '\v':
838 *(t++) = '\\';
839 *(t++) = 'v';
840 break;
841 case '\\':
842 *(t++) = '\\';
843 *(t++) = '\\';
844 break;
845 case '"':
846 *(t++) = '\\';
847 *(t++) = '"';
848 break;
849 case '\'':
850 *(t++) = '\\';
851 *(t++) = '\'';
852 break;
853
854 default:
855 /* For special chars we prefer octal over
856 * hexadecimal encoding, simply because glib's
857 * g_strescape() does the same */
858 if ((*f < ' ') || (*f >= 127)) {
859 *(t++) = '\\';
860 *(t++) = octchar((unsigned char) *f >> 6);
861 *(t++) = octchar((unsigned char) *f >> 3);
862 *(t++) = octchar((unsigned char) *f);
863 } else
864 *(t++) = *f;
865 break;
866 }
867
868 *t = 0;
869
870 return r;
871 }
872
873 char *cunescape(const char *s) {
874 char *r, *t;
875 const char *f;
876
877 assert(s);
878
879 /* Undoes C style string escaping */
880
881 if (!(r = new(char, strlen(s)+1)))
882 return r;
883
884 for (f = s, t = r; *f; f++) {
885
886 if (*f != '\\') {
887 *(t++) = *f;
888 continue;
889 }
890
891 f++;
892
893 switch (*f) {
894
895 case 'a':
896 *(t++) = '\a';
897 break;
898 case 'b':
899 *(t++) = '\b';
900 break;
901 case 'f':
902 *(t++) = '\f';
903 break;
904 case 'n':
905 *(t++) = '\n';
906 break;
907 case 'r':
908 *(t++) = '\r';
909 break;
910 case 't':
911 *(t++) = '\t';
912 break;
913 case 'v':
914 *(t++) = '\v';
915 break;
916 case '\\':
917 *(t++) = '\\';
918 break;
919 case '"':
920 *(t++) = '"';
921 break;
922 case '\'':
923 *(t++) = '\'';
924 break;
925
926 case 'x': {
927 /* hexadecimal encoding */
928 int a, b;
929
930 if ((a = unhexchar(f[1])) < 0 ||
931 (b = unhexchar(f[2])) < 0) {
932 /* Invalid escape code, let's take it literal then */
933 *(t++) = '\\';
934 *(t++) = 'x';
935 } else {
936 *(t++) = (char) ((a << 4) | b);
937 f += 2;
938 }
939
940 break;
941 }
942
943 case '0':
944 case '1':
945 case '2':
946 case '3':
947 case '4':
948 case '5':
949 case '6':
950 case '7': {
951 /* octal encoding */
952 int a, b, c;
953
954 if ((a = unoctchar(f[0])) < 0 ||
955 (b = unoctchar(f[1])) < 0 ||
956 (c = unoctchar(f[2])) < 0) {
957 /* Invalid escape code, let's take it literal then */
958 *(t++) = '\\';
959 *(t++) = f[0];
960 } else {
961 *(t++) = (char) ((a << 6) | (b << 3) | c);
962 f += 2;
963 }
964
965 break;
966 }
967
968 case 0:
969 /* premature end of string.*/
970 *(t++) = '\\';
971 goto finish;
972
973 default:
974 /* Invalid escape code, let's take it literal then */
975 *(t++) = '\\';
976 *(t++) = 'f';
977 break;
978 }
979 }
980
981 finish:
982 *t = 0;
983 return r;
984 }
985
986
987 char *xescape(const char *s, const char *bad) {
988 char *r, *t;
989 const char *f;
990
991 /* Escapes all chars in bad, in addition to \ and all special
992 * chars, in \xFF style escaping. May be reversed with
993 * cunescape. */
994
995 if (!(r = new(char, strlen(s)*4+1)))
996 return NULL;
997
998 for (f = s, t = r; *f; f++) {
999
1000 if ((*f < ' ') || (*f >= 127) ||
1001 (*f == '\\') || strchr(bad, *f)) {
1002 *(t++) = '\\';
1003 *(t++) = 'x';
1004 *(t++) = hexchar(*f >> 4);
1005 *(t++) = hexchar(*f);
1006 } else
1007 *(t++) = *f;
1008 }
1009
1010 *t = 0;
1011
1012 return r;
1013 }
1014
1015 char *bus_path_escape(const char *s) {
1016 char *r, *t;
1017 const char *f;
1018
1019 assert(s);
1020
1021 /* Escapes all chars that D-Bus' object path cannot deal
1022 * with. Can be reverse with bus_path_unescape() */
1023
1024 if (!(r = new(char, strlen(s)*3+1)))
1025 return NULL;
1026
1027 for (f = s, t = r; *f; f++) {
1028
1029 if (!(*f >= 'A' && *f <= 'Z') &&
1030 !(*f >= 'a' && *f <= 'z') &&
1031 !(*f >= '0' && *f <= '9')) {
1032 *(t++) = '_';
1033 *(t++) = hexchar(*f >> 4);
1034 *(t++) = hexchar(*f);
1035 } else
1036 *(t++) = *f;
1037 }
1038
1039 *t = 0;
1040
1041 return r;
1042 }
1043
1044 char *bus_path_unescape(const char *f) {
1045 char *r, *t;
1046
1047 assert(f);
1048
1049 if (!(r = strdup(f)))
1050 return NULL;
1051
1052 for (t = r; *f; f++) {
1053
1054 if (*f == '_') {
1055 int a, b;
1056
1057 if ((a = unhexchar(f[1])) < 0 ||
1058 (b = unhexchar(f[2])) < 0) {
1059 /* Invalid escape code, let's take it literal then */
1060 *(t++) = '_';
1061 } else {
1062 *(t++) = (char) ((a << 4) | b);
1063 f += 2;
1064 }
1065 } else
1066 *(t++) = *f;
1067 }
1068
1069 *t = 0;
1070
1071 return r;
1072 }
1073
1074 char *path_kill_slashes(char *path) {
1075 char *f, *t;
1076 bool slash = false;
1077
1078 /* Removes redundant inner and trailing slashes. Modifies the
1079 * passed string in-place.
1080 *
1081 * ///foo///bar/ becomes /foo/bar
1082 */
1083
1084 for (f = path, t = path; *f; f++) {
1085
1086 if (*f == '/') {
1087 slash = true;
1088 continue;
1089 }
1090
1091 if (slash) {
1092 slash = false;
1093 *(t++) = '/';
1094 }
1095
1096 *(t++) = *f;
1097 }
1098
1099 /* Special rule, if we are talking of the root directory, a
1100 trailing slash is good */
1101
1102 if (t == path && slash)
1103 *(t++) = '/';
1104
1105 *t = 0;
1106 return path;
1107 }
1108
1109 bool path_startswith(const char *path, const char *prefix) {
1110 assert(path);
1111 assert(prefix);
1112
1113 if ((path[0] == '/') != (prefix[0] == '/'))
1114 return false;
1115
1116 for (;;) {
1117 size_t a, b;
1118
1119 path += strspn(path, "/");
1120 prefix += strspn(prefix, "/");
1121
1122 if (*prefix == 0)
1123 return true;
1124
1125 if (*path == 0)
1126 return false;
1127
1128 a = strcspn(path, "/");
1129 b = strcspn(prefix, "/");
1130
1131 if (a != b)
1132 return false;
1133
1134 if (memcmp(path, prefix, a) != 0)
1135 return false;
1136
1137 path += a;
1138 prefix += b;
1139 }
1140 }
1141
1142 char *ascii_strlower(char *t) {
1143 char *p;
1144
1145 assert(t);
1146
1147 for (p = t; *p; p++)
1148 if (*p >= 'A' && *p <= 'Z')
1149 *p = *p - 'A' + 'a';
1150
1151 return t;
1152 }
1153
1154 bool ignore_file(const char *filename) {
1155 assert(filename);
1156
1157 return
1158 filename[0] == '.' ||
1159 endswith(filename, "~") ||
1160 endswith(filename, ".rpmnew") ||
1161 endswith(filename, ".rpmsave") ||
1162 endswith(filename, ".rpmorig") ||
1163 endswith(filename, ".dpkg-old") ||
1164 endswith(filename, ".dpkg-new") ||
1165 endswith(filename, ".swp");
1166 }
1167
1168 int fd_nonblock(int fd, bool nonblock) {
1169 int flags;
1170
1171 assert(fd >= 0);
1172
1173 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1174 return -errno;
1175
1176 if (nonblock)
1177 flags |= O_NONBLOCK;
1178 else
1179 flags &= ~O_NONBLOCK;
1180
1181 if (fcntl(fd, F_SETFL, flags) < 0)
1182 return -errno;
1183
1184 return 0;
1185 }
1186
1187 int fd_cloexec(int fd, bool cloexec) {
1188 int flags;
1189
1190 assert(fd >= 0);
1191
1192 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1193 return -errno;
1194
1195 if (cloexec)
1196 flags |= FD_CLOEXEC;
1197 else
1198 flags &= ~FD_CLOEXEC;
1199
1200 if (fcntl(fd, F_SETFD, flags) < 0)
1201 return -errno;
1202
1203 return 0;
1204 }
1205
1206 int close_all_fds(const int except[], unsigned n_except) {
1207 DIR *d;
1208 struct dirent *de;
1209 int r = 0;
1210
1211 if (!(d = opendir("/proc/self/fd")))
1212 return -errno;
1213
1214 while ((de = readdir(d))) {
1215 int fd = -1;
1216
1217 if (de->d_name[0] == '.')
1218 continue;
1219
1220 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1221 goto finish;
1222
1223 if (fd < 3)
1224 continue;
1225
1226 if (fd == dirfd(d))
1227 continue;
1228
1229 if (except) {
1230 bool found;
1231 unsigned i;
1232
1233 found = false;
1234 for (i = 0; i < n_except; i++)
1235 if (except[i] == fd) {
1236 found = true;
1237 break;
1238 }
1239
1240 if (found)
1241 continue;
1242 }
1243
1244 if ((r = close_nointr(fd)) < 0) {
1245 /* Valgrind has its own FD and doesn't want to have it closed */
1246 if (errno != EBADF)
1247 goto finish;
1248 }
1249 }
1250
1251 r = 0;
1252
1253 finish:
1254 closedir(d);
1255 return r;
1256 }
1257
1258 bool chars_intersect(const char *a, const char *b) {
1259 const char *p;
1260
1261 /* Returns true if any of the chars in a are in b. */
1262 for (p = a; *p; p++)
1263 if (strchr(b, *p))
1264 return true;
1265
1266 return false;
1267 }
1268
1269 char *format_timestamp(char *buf, size_t l, usec_t t) {
1270 struct tm tm;
1271 time_t sec;
1272
1273 assert(buf);
1274 assert(l > 0);
1275
1276 if (t <= 0)
1277 return NULL;
1278
1279 sec = (time_t) t / USEC_PER_SEC;
1280
1281 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1282 return NULL;
1283
1284 return buf;
1285 }
1286
1287 bool fstype_is_network(const char *fstype) {
1288 static const char * const table[] = {
1289 "cifs",
1290 "smbfs",
1291 "ncpfs",
1292 "nfs",
1293 "nfs4"
1294 };
1295
1296 unsigned i;
1297
1298 for (i = 0; i < ELEMENTSOF(table); i++)
1299 if (streq(table[i], fstype))
1300 return true;
1301
1302 return false;
1303 }
1304
1305 int chvt(int vt) {
1306 int fd, r = 0;
1307
1308 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1309 return -errno;
1310
1311 if (vt < 0) {
1312 int tiocl[2] = {
1313 TIOCL_GETKMSGREDIRECT,
1314 0
1315 };
1316
1317 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1318 return -errno;
1319
1320 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1321 }
1322
1323 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1324 r = -errno;
1325
1326 close_nointr(r);
1327 return r;
1328 }
1329
1330 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1331 struct termios old_termios, new_termios;
1332 char c;
1333 char line[1024];
1334
1335 assert(f);
1336 assert(ret);
1337
1338 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1339 new_termios = old_termios;
1340
1341 new_termios.c_lflag &= ~ICANON;
1342 new_termios.c_cc[VMIN] = 1;
1343 new_termios.c_cc[VTIME] = 0;
1344
1345 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1346 size_t k;
1347
1348 k = fread(&c, 1, 1, f);
1349
1350 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1351
1352 if (k <= 0)
1353 return -EIO;
1354
1355 if (need_nl)
1356 *need_nl = c != '\n';
1357
1358 *ret = c;
1359 return 0;
1360 }
1361 }
1362
1363 if (!(fgets(line, sizeof(line), f)))
1364 return -EIO;
1365
1366 truncate_nl(line);
1367
1368 if (strlen(line) != 1)
1369 return -EBADMSG;
1370
1371 if (need_nl)
1372 *need_nl = false;
1373
1374 *ret = line[0];
1375 return 0;
1376 }
1377
1378 int ask(char *ret, const char *replies, const char *text, ...) {
1379 assert(ret);
1380 assert(replies);
1381 assert(text);
1382
1383 for (;;) {
1384 va_list ap;
1385 char c;
1386 int r;
1387 bool need_nl = true;
1388
1389 va_start(ap, text);
1390 vprintf(text, ap);
1391 va_end(ap);
1392
1393 fflush(stdout);
1394
1395 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1396
1397 if (r == -EBADMSG) {
1398 puts("Bad input, please try again.");
1399 continue;
1400 }
1401
1402 putchar('\n');
1403 return r;
1404 }
1405
1406 if (need_nl)
1407 putchar('\n');
1408
1409 if (strchr(replies, c)) {
1410 *ret = c;
1411 return 0;
1412 }
1413
1414 puts("Read unexpected character, please try again.");
1415 }
1416 }
1417
1418 int reset_terminal(int fd) {
1419 struct termios termios;
1420 int r = 0;
1421
1422 assert(fd >= 0);
1423
1424 /* Set terminal to some sane defaults */
1425
1426 if (tcgetattr(fd, &termios) < 0) {
1427 r = -errno;
1428 goto finish;
1429 }
1430
1431 /* We only reset the stuff that matters to the software. How
1432 * hardware is set up we don't touch assuming that somebody
1433 * else will do that for us */
1434
1435 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1436 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1437 termios.c_oflag |= ONLCR;
1438 termios.c_cflag |= CREAD;
1439 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1440
1441 termios.c_cc[VINTR] = 03; /* ^C */
1442 termios.c_cc[VQUIT] = 034; /* ^\ */
1443 termios.c_cc[VERASE] = 0177;
1444 termios.c_cc[VKILL] = 025; /* ^X */
1445 termios.c_cc[VEOF] = 04; /* ^D */
1446 termios.c_cc[VSTART] = 021; /* ^Q */
1447 termios.c_cc[VSTOP] = 023; /* ^S */
1448 termios.c_cc[VSUSP] = 032; /* ^Z */
1449 termios.c_cc[VLNEXT] = 026; /* ^V */
1450 termios.c_cc[VWERASE] = 027; /* ^W */
1451 termios.c_cc[VREPRINT] = 022; /* ^R */
1452 termios.c_cc[VEOL] = 0;
1453 termios.c_cc[VEOL2] = 0;
1454
1455 termios.c_cc[VTIME] = 0;
1456 termios.c_cc[VMIN] = 1;
1457
1458 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1459 r = -errno;
1460
1461 finish:
1462 /* Just in case, flush all crap out */
1463 tcflush(fd, TCIOFLUSH);
1464
1465 return r;
1466 }
1467
1468 int open_terminal(const char *name, int mode) {
1469 int fd, r;
1470
1471 if ((fd = open(name, mode)) < 0)
1472 return -errno;
1473
1474 if ((r = isatty(fd)) < 0) {
1475 close_nointr_nofail(fd);
1476 return -errno;
1477 }
1478
1479 if (!r) {
1480 close_nointr_nofail(fd);
1481 return -ENOTTY;
1482 }
1483
1484 return fd;
1485 }
1486
1487 int flush_fd(int fd) {
1488 struct pollfd pollfd;
1489
1490 zero(pollfd);
1491 pollfd.fd = fd;
1492 pollfd.events = POLLIN;
1493
1494 for (;;) {
1495 char buf[1024];
1496 ssize_t l;
1497 int r;
1498
1499 if ((r = poll(&pollfd, 1, 0)) < 0) {
1500
1501 if (errno == EINTR)
1502 continue;
1503
1504 return -errno;
1505 }
1506
1507 if (r == 0)
1508 return 0;
1509
1510 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1511
1512 if (errno == EINTR)
1513 continue;
1514
1515 if (errno == EAGAIN)
1516 return 0;
1517
1518 return -errno;
1519 }
1520
1521 if (l <= 0)
1522 return 0;
1523 }
1524 }
1525
1526 int acquire_terminal(const char *name, bool fail, bool force) {
1527 int fd = -1, notify = -1, r, wd;
1528
1529 assert(name);
1530
1531 /* We use inotify to be notified when the tty is closed. We
1532 * create the watch before checking if we can actually acquire
1533 * it, so that we don't lose any event.
1534 *
1535 * Note: strictly speaking this actually watches for the
1536 * device being closed, it does *not* really watch whether a
1537 * tty loses its controlling process. However, unless some
1538 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1539 * its tty otherwise this will not become a problem. As long
1540 * as the administrator makes sure not configure any service
1541 * on the same tty as an untrusted user this should not be a
1542 * problem. (Which he probably should not do anyway.) */
1543
1544 if (!fail && !force) {
1545 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1546 r = -errno;
1547 goto fail;
1548 }
1549
1550 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1551 r = -errno;
1552 goto fail;
1553 }
1554 }
1555
1556 for (;;) {
1557 if ((r = flush_fd(notify)) < 0)
1558 goto fail;
1559
1560 /* We pass here O_NOCTTY only so that we can check the return
1561 * value TIOCSCTTY and have a reliable way to figure out if we
1562 * successfully became the controlling process of the tty */
1563 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1564 return -errno;
1565
1566 /* First, try to get the tty */
1567 if ((r = ioctl(fd, TIOCSCTTY, force)) < 0 &&
1568 (force || fail || errno != EPERM)) {
1569 r = -errno;
1570 goto fail;
1571 }
1572
1573 if (r >= 0)
1574 break;
1575
1576 assert(!fail);
1577 assert(!force);
1578 assert(notify >= 0);
1579
1580 for (;;) {
1581 struct inotify_event e;
1582 ssize_t l;
1583
1584 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1585
1586 if (l < 0) {
1587
1588 if (errno == EINTR)
1589 continue;
1590
1591 r = -errno;
1592 } else
1593 r = -EIO;
1594
1595 goto fail;
1596 }
1597
1598 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1599 r = -errno;
1600 goto fail;
1601 }
1602
1603 break;
1604 }
1605
1606 /* We close the tty fd here since if the old session
1607 * ended our handle will be dead. It's important that
1608 * we do this after sleeping, so that we don't enter
1609 * an endless loop. */
1610 close_nointr_nofail(fd);
1611 }
1612
1613 if (notify >= 0)
1614 close_nointr(notify);
1615
1616 if ((r = reset_terminal(fd)) < 0)
1617 log_warning("Failed to reset terminal: %s", strerror(-r));
1618
1619 return fd;
1620
1621 fail:
1622 if (fd >= 0)
1623 close_nointr(fd);
1624
1625 if (notify >= 0)
1626 close_nointr(notify);
1627
1628 return r;
1629 }
1630
1631 int release_terminal(void) {
1632 int r = 0, fd;
1633
1634 if ((fd = open("/dev/tty", O_RDWR)) < 0)
1635 return -errno;
1636
1637 if (ioctl(fd, TIOCNOTTY) < 0)
1638 r = -errno;
1639
1640 close_nointr_nofail(fd);
1641 return r;
1642 }
1643
1644 int ignore_signal(int sig) {
1645 struct sigaction sa;
1646
1647 zero(sa);
1648 sa.sa_handler = SIG_IGN;
1649 sa.sa_flags = SA_RESTART;
1650
1651 return sigaction(sig, &sa, NULL);
1652 }
1653
1654 static const char *const ioprio_class_table[] = {
1655 [IOPRIO_CLASS_NONE] = "none",
1656 [IOPRIO_CLASS_RT] = "realtime",
1657 [IOPRIO_CLASS_BE] = "best-effort",
1658 [IOPRIO_CLASS_IDLE] = "idle"
1659 };
1660
1661 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
1662
1663 static const char *const sigchld_code_table[] = {
1664 [CLD_EXITED] = "exited",
1665 [CLD_KILLED] = "killed",
1666 [CLD_DUMPED] = "dumped",
1667 [CLD_TRAPPED] = "trapped",
1668 [CLD_STOPPED] = "stopped",
1669 [CLD_CONTINUED] = "continued",
1670 };
1671
1672 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
1673
1674 static const char *const log_facility_table[LOG_NFACILITIES] = {
1675 [LOG_FAC(LOG_KERN)] = "kern",
1676 [LOG_FAC(LOG_USER)] = "user",
1677 [LOG_FAC(LOG_MAIL)] = "mail",
1678 [LOG_FAC(LOG_DAEMON)] = "daemon",
1679 [LOG_FAC(LOG_AUTH)] = "auth",
1680 [LOG_FAC(LOG_SYSLOG)] = "syslog",
1681 [LOG_FAC(LOG_LPR)] = "lpr",
1682 [LOG_FAC(LOG_NEWS)] = "news",
1683 [LOG_FAC(LOG_UUCP)] = "uucp",
1684 [LOG_FAC(LOG_CRON)] = "cron",
1685 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
1686 [LOG_FAC(LOG_FTP)] = "ftp",
1687 [LOG_FAC(LOG_LOCAL0)] = "local0",
1688 [LOG_FAC(LOG_LOCAL1)] = "local1",
1689 [LOG_FAC(LOG_LOCAL2)] = "local2",
1690 [LOG_FAC(LOG_LOCAL3)] = "local3",
1691 [LOG_FAC(LOG_LOCAL4)] = "local4",
1692 [LOG_FAC(LOG_LOCAL5)] = "local5",
1693 [LOG_FAC(LOG_LOCAL6)] = "local6",
1694 [LOG_FAC(LOG_LOCAL7)] = "local7"
1695 };
1696
1697 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
1698
1699 static const char *const log_level_table[] = {
1700 [LOG_EMERG] = "emerg",
1701 [LOG_ALERT] = "alert",
1702 [LOG_CRIT] = "crit",
1703 [LOG_ERR] = "err",
1704 [LOG_WARNING] = "warning",
1705 [LOG_NOTICE] = "notice",
1706 [LOG_INFO] = "info",
1707 [LOG_DEBUG] = "debug"
1708 };
1709
1710 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
1711
1712 static const char* const sched_policy_table[] = {
1713 [SCHED_OTHER] = "other",
1714 [SCHED_BATCH] = "batch",
1715 [SCHED_IDLE] = "idle",
1716 [SCHED_FIFO] = "fifo",
1717 [SCHED_RR] = "rr"
1718 };
1719
1720 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
1721
1722 static const char* const rlimit_table[] = {
1723 [RLIMIT_CPU] = "LimitCPU",
1724 [RLIMIT_FSIZE] = "LimitFSIZE",
1725 [RLIMIT_DATA] = "LimitDATA",
1726 [RLIMIT_STACK] = "LimitSTACK",
1727 [RLIMIT_CORE] = "LimitCORE",
1728 [RLIMIT_RSS] = "LimitRSS",
1729 [RLIMIT_NOFILE] = "LimitNOFILE",
1730 [RLIMIT_AS] = "LimitAS",
1731 [RLIMIT_NPROC] = "LimitNPROC",
1732 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
1733 [RLIMIT_LOCKS] = "LimitLOCKS",
1734 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
1735 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
1736 [RLIMIT_NICE] = "LimitNICE",
1737 [RLIMIT_RTPRIO] = "LimitRTPRIO",
1738 [RLIMIT_RTTIME] = "LimitRTTIME"
1739 };
1740
1741 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);