]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/util.c
tmpfiles: ensure we do no follow symlinks when cleaning up dirs
[thirdparty/systemd.git] / src / util.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
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 #include <libgen.h>
45 #include <ctype.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
48 #include <pwd.h>
49 #include <netinet/ip.h>
50 #include <linux/kd.h>
51 #include <dlfcn.h>
52 #include <sys/wait.h>
53
54 #include "macro.h"
55 #include "util.h"
56 #include "ioprio.h"
57 #include "missing.h"
58 #include "log.h"
59 #include "strv.h"
60 #include "label.h"
61 #include "exit-status.h"
62
63 bool streq_ptr(const char *a, const char *b) {
64
65 /* Like streq(), but tries to make sense of NULL pointers */
66
67 if (a && b)
68 return streq(a, b);
69
70 if (!a && !b)
71 return true;
72
73 return false;
74 }
75
76 usec_t now(clockid_t clock_id) {
77 struct timespec ts;
78
79 assert_se(clock_gettime(clock_id, &ts) == 0);
80
81 return timespec_load(&ts);
82 }
83
84 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
85 assert(ts);
86
87 ts->realtime = now(CLOCK_REALTIME);
88 ts->monotonic = now(CLOCK_MONOTONIC);
89
90 return ts;
91 }
92
93 usec_t timespec_load(const struct timespec *ts) {
94 assert(ts);
95
96 return
97 (usec_t) ts->tv_sec * USEC_PER_SEC +
98 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
99 }
100
101 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
102 assert(ts);
103
104 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
105 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
106
107 return ts;
108 }
109
110 usec_t timeval_load(const struct timeval *tv) {
111 assert(tv);
112
113 return
114 (usec_t) tv->tv_sec * USEC_PER_SEC +
115 (usec_t) tv->tv_usec;
116 }
117
118 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
119 assert(tv);
120
121 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
122 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
123
124 return tv;
125 }
126
127 bool endswith(const char *s, const char *postfix) {
128 size_t sl, pl;
129
130 assert(s);
131 assert(postfix);
132
133 sl = strlen(s);
134 pl = strlen(postfix);
135
136 if (pl == 0)
137 return true;
138
139 if (sl < pl)
140 return false;
141
142 return memcmp(s + sl - pl, postfix, pl) == 0;
143 }
144
145 bool startswith(const char *s, const char *prefix) {
146 size_t sl, pl;
147
148 assert(s);
149 assert(prefix);
150
151 sl = strlen(s);
152 pl = strlen(prefix);
153
154 if (pl == 0)
155 return true;
156
157 if (sl < pl)
158 return false;
159
160 return memcmp(s, prefix, pl) == 0;
161 }
162
163 bool startswith_no_case(const char *s, const char *prefix) {
164 size_t sl, pl;
165 unsigned i;
166
167 assert(s);
168 assert(prefix);
169
170 sl = strlen(s);
171 pl = strlen(prefix);
172
173 if (pl == 0)
174 return true;
175
176 if (sl < pl)
177 return false;
178
179 for(i = 0; i < pl; ++i) {
180 if (tolower(s[i]) != tolower(prefix[i]))
181 return false;
182 }
183
184 return true;
185 }
186
187 bool first_word(const char *s, const char *word) {
188 size_t sl, wl;
189
190 assert(s);
191 assert(word);
192
193 sl = strlen(s);
194 wl = strlen(word);
195
196 if (sl < wl)
197 return false;
198
199 if (wl == 0)
200 return true;
201
202 if (memcmp(s, word, wl) != 0)
203 return false;
204
205 return s[wl] == 0 ||
206 strchr(WHITESPACE, s[wl]);
207 }
208
209 int close_nointr(int fd) {
210 assert(fd >= 0);
211
212 for (;;) {
213 int r;
214
215 if ((r = close(fd)) >= 0)
216 return r;
217
218 if (errno != EINTR)
219 return r;
220 }
221 }
222
223 void close_nointr_nofail(int fd) {
224 int saved_errno = errno;
225
226 /* like close_nointr() but cannot fail, and guarantees errno
227 * is unchanged */
228
229 assert_se(close_nointr(fd) == 0);
230
231 errno = saved_errno;
232 }
233
234 void close_many(const int fds[], unsigned n_fd) {
235 unsigned i;
236
237 for (i = 0; i < n_fd; i++)
238 close_nointr_nofail(fds[i]);
239 }
240
241 int parse_boolean(const char *v) {
242 assert(v);
243
244 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
245 return 1;
246 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
247 return 0;
248
249 return -EINVAL;
250 }
251
252 int parse_pid(const char *s, pid_t* ret_pid) {
253 unsigned long ul;
254 pid_t pid;
255 int r;
256
257 assert(s);
258 assert(ret_pid);
259
260 if ((r = safe_atolu(s, &ul)) < 0)
261 return r;
262
263 pid = (pid_t) ul;
264
265 if ((unsigned long) pid != ul)
266 return -ERANGE;
267
268 if (pid <= 0)
269 return -ERANGE;
270
271 *ret_pid = pid;
272 return 0;
273 }
274
275 int safe_atou(const char *s, unsigned *ret_u) {
276 char *x = NULL;
277 unsigned long l;
278
279 assert(s);
280 assert(ret_u);
281
282 errno = 0;
283 l = strtoul(s, &x, 0);
284
285 if (!x || *x || errno)
286 return errno ? -errno : -EINVAL;
287
288 if ((unsigned long) (unsigned) l != l)
289 return -ERANGE;
290
291 *ret_u = (unsigned) l;
292 return 0;
293 }
294
295 int safe_atoi(const char *s, int *ret_i) {
296 char *x = NULL;
297 long l;
298
299 assert(s);
300 assert(ret_i);
301
302 errno = 0;
303 l = strtol(s, &x, 0);
304
305 if (!x || *x || errno)
306 return errno ? -errno : -EINVAL;
307
308 if ((long) (int) l != l)
309 return -ERANGE;
310
311 *ret_i = (int) l;
312 return 0;
313 }
314
315 int safe_atollu(const char *s, long long unsigned *ret_llu) {
316 char *x = NULL;
317 unsigned long long l;
318
319 assert(s);
320 assert(ret_llu);
321
322 errno = 0;
323 l = strtoull(s, &x, 0);
324
325 if (!x || *x || errno)
326 return errno ? -errno : -EINVAL;
327
328 *ret_llu = l;
329 return 0;
330 }
331
332 int safe_atolli(const char *s, long long int *ret_lli) {
333 char *x = NULL;
334 long long l;
335
336 assert(s);
337 assert(ret_lli);
338
339 errno = 0;
340 l = strtoll(s, &x, 0);
341
342 if (!x || *x || errno)
343 return errno ? -errno : -EINVAL;
344
345 *ret_lli = l;
346 return 0;
347 }
348
349 /* Split a string into words. */
350 char *split(const char *c, size_t *l, const char *separator, char **state) {
351 char *current;
352
353 current = *state ? *state : (char*) c;
354
355 if (!*current || *c == 0)
356 return NULL;
357
358 current += strspn(current, separator);
359 *l = strcspn(current, separator);
360 *state = current+*l;
361
362 return (char*) current;
363 }
364
365 /* Split a string into words, but consider strings enclosed in '' and
366 * "" as words even if they include spaces. */
367 char *split_quoted(const char *c, size_t *l, char **state) {
368 char *current, *e;
369 bool escaped = false;
370
371 current = *state ? *state : (char*) c;
372
373 if (!*current || *c == 0)
374 return NULL;
375
376 current += strspn(current, WHITESPACE);
377
378 if (*current == '\'') {
379 current ++;
380
381 for (e = current; *e; e++) {
382 if (escaped)
383 escaped = false;
384 else if (*e == '\\')
385 escaped = true;
386 else if (*e == '\'')
387 break;
388 }
389
390 *l = e-current;
391 *state = *e == 0 ? e : e+1;
392 } else if (*current == '\"') {
393 current ++;
394
395 for (e = current; *e; e++) {
396 if (escaped)
397 escaped = false;
398 else if (*e == '\\')
399 escaped = true;
400 else if (*e == '\"')
401 break;
402 }
403
404 *l = e-current;
405 *state = *e == 0 ? e : e+1;
406 } else {
407 for (e = current; *e; e++) {
408 if (escaped)
409 escaped = false;
410 else if (*e == '\\')
411 escaped = true;
412 else if (strchr(WHITESPACE, *e))
413 break;
414 }
415 *l = e-current;
416 *state = e;
417 }
418
419 return (char*) current;
420 }
421
422 char **split_path_and_make_absolute(const char *p) {
423 char **l;
424 assert(p);
425
426 if (!(l = strv_split(p, ":")))
427 return NULL;
428
429 if (!strv_path_make_absolute_cwd(l)) {
430 strv_free(l);
431 return NULL;
432 }
433
434 return l;
435 }
436
437 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
438 int r;
439 FILE *f;
440 char fn[132], line[256], *p;
441 long unsigned ppid;
442
443 assert(pid >= 0);
444 assert(_ppid);
445
446 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
447 fn[sizeof(fn)-1] = 0;
448
449 if (!(f = fopen(fn, "r")))
450 return -errno;
451
452 if (!(fgets(line, sizeof(line), f))) {
453 r = -errno;
454 fclose(f);
455 return r;
456 }
457
458 fclose(f);
459
460 /* Let's skip the pid and comm fields. The latter is enclosed
461 * in () but does not escape any () in its value, so let's
462 * skip over it manually */
463
464 if (!(p = strrchr(line, ')')))
465 return -EIO;
466
467 p++;
468
469 if (sscanf(p, " "
470 "%*c " /* state */
471 "%lu ", /* ppid */
472 &ppid) != 1)
473 return -EIO;
474
475 if ((long unsigned) (pid_t) ppid != ppid)
476 return -ERANGE;
477
478 *_ppid = (pid_t) ppid;
479
480 return 0;
481 }
482
483 int write_one_line_file(const char *fn, const char *line) {
484 FILE *f;
485 int r;
486
487 assert(fn);
488 assert(line);
489
490 if (!(f = fopen(fn, "we")))
491 return -errno;
492
493 if (fputs(line, f) < 0) {
494 r = -errno;
495 goto finish;
496 }
497
498 if (!endswith(line, "\n"))
499 fputc('\n', f);
500
501 r = 0;
502 finish:
503 fclose(f);
504 return r;
505 }
506
507 int read_one_line_file(const char *fn, char **line) {
508 FILE *f;
509 int r;
510 char t[LINE_MAX], *c;
511
512 assert(fn);
513 assert(line);
514
515 if (!(f = fopen(fn, "re")))
516 return -errno;
517
518 if (!(fgets(t, sizeof(t), f))) {
519 r = -errno;
520 goto finish;
521 }
522
523 if (!(c = strdup(t))) {
524 r = -ENOMEM;
525 goto finish;
526 }
527
528 *line = c;
529 r = 0;
530
531 finish:
532 fclose(f);
533 return r;
534 }
535
536 int read_full_file(const char *fn, char **contents) {
537 FILE *f;
538 int r;
539 size_t n, l;
540 char *buf = NULL;
541 struct stat st;
542
543 if (!(f = fopen(fn, "re")))
544 return -errno;
545
546 if (fstat(fileno(f), &st) < 0) {
547 r = -errno;
548 goto finish;
549 }
550
551 n = st.st_size > 0 ? st.st_size : LINE_MAX;
552 l = 0;
553
554 for (;;) {
555 char *t;
556 size_t k;
557
558 if (!(t = realloc(buf, n+1))) {
559 r = -ENOMEM;
560 goto finish;
561 }
562
563 buf = t;
564 k = fread(buf + l, 1, n - l, f);
565
566 if (k <= 0) {
567 if (ferror(f)) {
568 r = -errno;
569 goto finish;
570 }
571
572 break;
573 }
574
575 l += k;
576 n *= 2;
577
578 /* Safety check */
579 if (n > 4*1024*1024) {
580 r = -E2BIG;
581 goto finish;
582 }
583 }
584
585 if (buf)
586 buf[l] = 0;
587 else if (!(buf = calloc(1, 1))) {
588 r = -errno;
589 goto finish;
590 }
591
592 *contents = buf;
593 buf = NULL;
594
595 r = 0;
596
597 finish:
598 fclose(f);
599 free(buf);
600
601 return r;
602 }
603
604 int parse_env_file(
605 const char *fname,
606 const char *separator, ...) {
607
608 int r = 0;
609 char *contents, *p;
610
611 assert(fname);
612 assert(separator);
613
614 if ((r = read_full_file(fname, &contents)) < 0)
615 return r;
616
617 p = contents;
618 for (;;) {
619 const char *key = NULL;
620
621 p += strspn(p, separator);
622 p += strspn(p, WHITESPACE);
623
624 if (!*p)
625 break;
626
627 if (!strchr(COMMENTS, *p)) {
628 va_list ap;
629 char **value;
630
631 va_start(ap, separator);
632 while ((key = va_arg(ap, char *))) {
633 size_t n;
634 char *v;
635
636 value = va_arg(ap, char **);
637
638 n = strlen(key);
639 if (strncmp(p, key, n) != 0 ||
640 p[n] != '=')
641 continue;
642
643 p += n + 1;
644 n = strcspn(p, separator);
645
646 if (n >= 2 &&
647 strchr(QUOTES, p[0]) &&
648 p[n-1] == p[0])
649 v = strndup(p+1, n-2);
650 else
651 v = strndup(p, n);
652
653 if (!v) {
654 r = -ENOMEM;
655 va_end(ap);
656 goto fail;
657 }
658
659 if (v[0] == '\0') {
660 /* return empty value strings as NULL */
661 free(v);
662 v = NULL;
663 }
664
665 free(*value);
666 *value = v;
667
668 p += n;
669
670 r ++;
671 break;
672 }
673 va_end(ap);
674 }
675
676 if (!key)
677 p += strcspn(p, separator);
678 }
679
680 fail:
681 free(contents);
682 return r;
683 }
684
685 char *truncate_nl(char *s) {
686 assert(s);
687
688 s[strcspn(s, NEWLINE)] = 0;
689 return s;
690 }
691
692 int get_process_name(pid_t pid, char **name) {
693 char *p;
694 int r;
695
696 assert(pid >= 1);
697 assert(name);
698
699 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
700 return -ENOMEM;
701
702 r = read_one_line_file(p, name);
703 free(p);
704
705 if (r < 0)
706 return r;
707
708 truncate_nl(*name);
709 return 0;
710 }
711
712 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
713 char *p, *r, *k;
714 int c;
715 bool space = false;
716 size_t left;
717 FILE *f;
718
719 assert(pid >= 1);
720 assert(max_length > 0);
721 assert(line);
722
723 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
724 return -ENOMEM;
725
726 f = fopen(p, "r");
727 free(p);
728
729 if (!f)
730 return -errno;
731
732 if (!(r = new(char, max_length))) {
733 fclose(f);
734 return -ENOMEM;
735 }
736
737 k = r;
738 left = max_length;
739 while ((c = getc(f)) != EOF) {
740
741 if (isprint(c)) {
742 if (space) {
743 if (left <= 4)
744 break;
745
746 *(k++) = ' ';
747 left--;
748 space = false;
749 }
750
751 if (left <= 4)
752 break;
753
754 *(k++) = (char) c;
755 left--;
756 } else
757 space = true;
758 }
759
760 if (left <= 4) {
761 size_t n = MIN(left-1, 3U);
762 memcpy(k, "...", n);
763 k[n] = 0;
764 } else
765 *k = 0;
766
767 fclose(f);
768
769 /* Kernel threads have no argv[] */
770 if (r[0] == 0) {
771 char *t;
772 int h;
773
774 free(r);
775
776 if ((h = get_process_name(pid, &t)) < 0)
777 return h;
778
779 h = asprintf(&r, "[%s]", t);
780 free(t);
781
782 if (h < 0)
783 return -ENOMEM;
784 }
785
786 *line = r;
787 return 0;
788 }
789
790 char *strnappend(const char *s, const char *suffix, size_t b) {
791 size_t a;
792 char *r;
793
794 if (!s && !suffix)
795 return strdup("");
796
797 if (!s)
798 return strndup(suffix, b);
799
800 if (!suffix)
801 return strdup(s);
802
803 assert(s);
804 assert(suffix);
805
806 a = strlen(s);
807
808 if (!(r = new(char, a+b+1)))
809 return NULL;
810
811 memcpy(r, s, a);
812 memcpy(r+a, suffix, b);
813 r[a+b] = 0;
814
815 return r;
816 }
817
818 char *strappend(const char *s, const char *suffix) {
819 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
820 }
821
822 int readlink_malloc(const char *p, char **r) {
823 size_t l = 100;
824
825 assert(p);
826 assert(r);
827
828 for (;;) {
829 char *c;
830 ssize_t n;
831
832 if (!(c = new(char, l)))
833 return -ENOMEM;
834
835 if ((n = readlink(p, c, l-1)) < 0) {
836 int ret = -errno;
837 free(c);
838 return ret;
839 }
840
841 if ((size_t) n < l-1) {
842 c[n] = 0;
843 *r = c;
844 return 0;
845 }
846
847 free(c);
848 l *= 2;
849 }
850 }
851
852 int readlink_and_make_absolute(const char *p, char **r) {
853 char *target, *k;
854 int j;
855
856 assert(p);
857 assert(r);
858
859 if ((j = readlink_malloc(p, &target)) < 0)
860 return j;
861
862 k = file_in_same_dir(p, target);
863 free(target);
864
865 if (!k)
866 return -ENOMEM;
867
868 *r = k;
869 return 0;
870 }
871
872 int parent_of_path(const char *path, char **_r) {
873 const char *e, *a = NULL, *b = NULL, *p;
874 char *r;
875 bool slash = false;
876
877 assert(path);
878 assert(_r);
879
880 if (!*path)
881 return -EINVAL;
882
883 for (e = path; *e; e++) {
884
885 if (!slash && *e == '/') {
886 a = b;
887 b = e;
888 slash = true;
889 } else if (slash && *e != '/')
890 slash = false;
891 }
892
893 if (*(e-1) == '/')
894 p = a;
895 else
896 p = b;
897
898 if (!p)
899 return -EINVAL;
900
901 if (p == path)
902 r = strdup("/");
903 else
904 r = strndup(path, p-path);
905
906 if (!r)
907 return -ENOMEM;
908
909 *_r = r;
910 return 0;
911 }
912
913
914 char *file_name_from_path(const char *p) {
915 char *r;
916
917 assert(p);
918
919 if ((r = strrchr(p, '/')))
920 return r + 1;
921
922 return (char*) p;
923 }
924
925 bool path_is_absolute(const char *p) {
926 assert(p);
927
928 return p[0] == '/';
929 }
930
931 bool is_path(const char *p) {
932
933 return !!strchr(p, '/');
934 }
935
936 char *path_make_absolute(const char *p, const char *prefix) {
937 char *r;
938
939 assert(p);
940
941 /* Makes every item in the list an absolute path by prepending
942 * the prefix, if specified and necessary */
943
944 if (path_is_absolute(p) || !prefix)
945 return strdup(p);
946
947 if (asprintf(&r, "%s/%s", prefix, p) < 0)
948 return NULL;
949
950 return r;
951 }
952
953 char *path_make_absolute_cwd(const char *p) {
954 char *cwd, *r;
955
956 assert(p);
957
958 /* Similar to path_make_absolute(), but prefixes with the
959 * current working directory. */
960
961 if (path_is_absolute(p))
962 return strdup(p);
963
964 if (!(cwd = get_current_dir_name()))
965 return NULL;
966
967 r = path_make_absolute(p, cwd);
968 free(cwd);
969
970 return r;
971 }
972
973 char **strv_path_make_absolute_cwd(char **l) {
974 char **s;
975
976 /* Goes through every item in the string list and makes it
977 * absolute. This works in place and won't rollback any
978 * changes on failure. */
979
980 STRV_FOREACH(s, l) {
981 char *t;
982
983 if (!(t = path_make_absolute_cwd(*s)))
984 return NULL;
985
986 free(*s);
987 *s = t;
988 }
989
990 return l;
991 }
992
993 char **strv_path_canonicalize(char **l) {
994 char **s;
995 unsigned k = 0;
996 bool enomem = false;
997
998 if (strv_isempty(l))
999 return l;
1000
1001 /* Goes through every item in the string list and canonicalize
1002 * the path. This works in place and won't rollback any
1003 * changes on failure. */
1004
1005 STRV_FOREACH(s, l) {
1006 char *t, *u;
1007
1008 t = path_make_absolute_cwd(*s);
1009 free(*s);
1010
1011 if (!t) {
1012 enomem = true;
1013 continue;
1014 }
1015
1016 errno = 0;
1017 u = canonicalize_file_name(t);
1018 free(t);
1019
1020 if (!u) {
1021 if (errno == ENOMEM || !errno)
1022 enomem = true;
1023
1024 continue;
1025 }
1026
1027 l[k++] = u;
1028 }
1029
1030 l[k] = NULL;
1031
1032 if (enomem)
1033 return NULL;
1034
1035 return l;
1036 }
1037
1038 int reset_all_signal_handlers(void) {
1039 int sig;
1040
1041 for (sig = 1; sig < _NSIG; sig++) {
1042 struct sigaction sa;
1043
1044 if (sig == SIGKILL || sig == SIGSTOP)
1045 continue;
1046
1047 zero(sa);
1048 sa.sa_handler = SIG_DFL;
1049 sa.sa_flags = SA_RESTART;
1050
1051 /* On Linux the first two RT signals are reserved by
1052 * glibc, and sigaction() will return EINVAL for them. */
1053 if ((sigaction(sig, &sa, NULL) < 0))
1054 if (errno != EINVAL)
1055 return -errno;
1056 }
1057
1058 return 0;
1059 }
1060
1061 char *strstrip(char *s) {
1062 char *e, *l = NULL;
1063
1064 /* Drops trailing whitespace. Modifies the string in
1065 * place. Returns pointer to first non-space character */
1066
1067 s += strspn(s, WHITESPACE);
1068
1069 for (e = s; *e; e++)
1070 if (!strchr(WHITESPACE, *e))
1071 l = e;
1072
1073 if (l)
1074 *(l+1) = 0;
1075 else
1076 *s = 0;
1077
1078 return s;
1079 }
1080
1081 char *delete_chars(char *s, const char *bad) {
1082 char *f, *t;
1083
1084 /* Drops all whitespace, regardless where in the string */
1085
1086 for (f = s, t = s; *f; f++) {
1087 if (strchr(bad, *f))
1088 continue;
1089
1090 *(t++) = *f;
1091 }
1092
1093 *t = 0;
1094
1095 return s;
1096 }
1097
1098 char *file_in_same_dir(const char *path, const char *filename) {
1099 char *e, *r;
1100 size_t k;
1101
1102 assert(path);
1103 assert(filename);
1104
1105 /* This removes the last component of path and appends
1106 * filename, unless the latter is absolute anyway or the
1107 * former isn't */
1108
1109 if (path_is_absolute(filename))
1110 return strdup(filename);
1111
1112 if (!(e = strrchr(path, '/')))
1113 return strdup(filename);
1114
1115 k = strlen(filename);
1116 if (!(r = new(char, e-path+1+k+1)))
1117 return NULL;
1118
1119 memcpy(r, path, e-path+1);
1120 memcpy(r+(e-path)+1, filename, k+1);
1121
1122 return r;
1123 }
1124
1125 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1126 struct stat st;
1127
1128 if (label_mkdir(path, mode) >= 0)
1129 if (chmod_and_chown(path, mode, uid, gid) < 0)
1130 return -errno;
1131
1132 if (lstat(path, &st) < 0)
1133 return -errno;
1134
1135 if ((st.st_mode & 0777) != mode ||
1136 st.st_uid != uid ||
1137 st.st_gid != gid ||
1138 !S_ISDIR(st.st_mode)) {
1139 errno = EEXIST;
1140 return -errno;
1141 }
1142
1143 return 0;
1144 }
1145
1146
1147 int mkdir_parents(const char *path, mode_t mode) {
1148 const char *p, *e;
1149
1150 assert(path);
1151
1152 /* Creates every parent directory in the path except the last
1153 * component. */
1154
1155 p = path + strspn(path, "/");
1156 for (;;) {
1157 int r;
1158 char *t;
1159
1160 e = p + strcspn(p, "/");
1161 p = e + strspn(e, "/");
1162
1163 /* Is this the last component? If so, then we're
1164 * done */
1165 if (*p == 0)
1166 return 0;
1167
1168 if (!(t = strndup(path, e - path)))
1169 return -ENOMEM;
1170
1171 r = label_mkdir(t, mode);
1172 free(t);
1173
1174 if (r < 0 && errno != EEXIST)
1175 return -errno;
1176 }
1177 }
1178
1179 int mkdir_p(const char *path, mode_t mode) {
1180 int r;
1181
1182 /* Like mkdir -p */
1183
1184 if ((r = mkdir_parents(path, mode)) < 0)
1185 return r;
1186
1187 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1188 return -errno;
1189
1190 return 0;
1191 }
1192
1193 int rmdir_parents(const char *path, const char *stop) {
1194 size_t l;
1195 int r = 0;
1196
1197 assert(path);
1198 assert(stop);
1199
1200 l = strlen(path);
1201
1202 /* Skip trailing slashes */
1203 while (l > 0 && path[l-1] == '/')
1204 l--;
1205
1206 while (l > 0) {
1207 char *t;
1208
1209 /* Skip last component */
1210 while (l > 0 && path[l-1] != '/')
1211 l--;
1212
1213 /* Skip trailing slashes */
1214 while (l > 0 && path[l-1] == '/')
1215 l--;
1216
1217 if (l <= 0)
1218 break;
1219
1220 if (!(t = strndup(path, l)))
1221 return -ENOMEM;
1222
1223 if (path_startswith(stop, t)) {
1224 free(t);
1225 return 0;
1226 }
1227
1228 r = rmdir(t);
1229 free(t);
1230
1231 if (r < 0)
1232 if (errno != ENOENT)
1233 return -errno;
1234 }
1235
1236 return 0;
1237 }
1238
1239
1240 char hexchar(int x) {
1241 static const char table[16] = "0123456789abcdef";
1242
1243 return table[x & 15];
1244 }
1245
1246 int unhexchar(char c) {
1247
1248 if (c >= '0' && c <= '9')
1249 return c - '0';
1250
1251 if (c >= 'a' && c <= 'f')
1252 return c - 'a' + 10;
1253
1254 if (c >= 'A' && c <= 'F')
1255 return c - 'A' + 10;
1256
1257 return -1;
1258 }
1259
1260 char octchar(int x) {
1261 return '0' + (x & 7);
1262 }
1263
1264 int unoctchar(char c) {
1265
1266 if (c >= '0' && c <= '7')
1267 return c - '0';
1268
1269 return -1;
1270 }
1271
1272 char decchar(int x) {
1273 return '0' + (x % 10);
1274 }
1275
1276 int undecchar(char c) {
1277
1278 if (c >= '0' && c <= '9')
1279 return c - '0';
1280
1281 return -1;
1282 }
1283
1284 char *cescape(const char *s) {
1285 char *r, *t;
1286 const char *f;
1287
1288 assert(s);
1289
1290 /* Does C style string escaping. */
1291
1292 if (!(r = new(char, strlen(s)*4 + 1)))
1293 return NULL;
1294
1295 for (f = s, t = r; *f; f++)
1296
1297 switch (*f) {
1298
1299 case '\a':
1300 *(t++) = '\\';
1301 *(t++) = 'a';
1302 break;
1303 case '\b':
1304 *(t++) = '\\';
1305 *(t++) = 'b';
1306 break;
1307 case '\f':
1308 *(t++) = '\\';
1309 *(t++) = 'f';
1310 break;
1311 case '\n':
1312 *(t++) = '\\';
1313 *(t++) = 'n';
1314 break;
1315 case '\r':
1316 *(t++) = '\\';
1317 *(t++) = 'r';
1318 break;
1319 case '\t':
1320 *(t++) = '\\';
1321 *(t++) = 't';
1322 break;
1323 case '\v':
1324 *(t++) = '\\';
1325 *(t++) = 'v';
1326 break;
1327 case '\\':
1328 *(t++) = '\\';
1329 *(t++) = '\\';
1330 break;
1331 case '"':
1332 *(t++) = '\\';
1333 *(t++) = '"';
1334 break;
1335 case '\'':
1336 *(t++) = '\\';
1337 *(t++) = '\'';
1338 break;
1339
1340 default:
1341 /* For special chars we prefer octal over
1342 * hexadecimal encoding, simply because glib's
1343 * g_strescape() does the same */
1344 if ((*f < ' ') || (*f >= 127)) {
1345 *(t++) = '\\';
1346 *(t++) = octchar((unsigned char) *f >> 6);
1347 *(t++) = octchar((unsigned char) *f >> 3);
1348 *(t++) = octchar((unsigned char) *f);
1349 } else
1350 *(t++) = *f;
1351 break;
1352 }
1353
1354 *t = 0;
1355
1356 return r;
1357 }
1358
1359 char *cunescape_length(const char *s, size_t length) {
1360 char *r, *t;
1361 const char *f;
1362
1363 assert(s);
1364
1365 /* Undoes C style string escaping */
1366
1367 if (!(r = new(char, length+1)))
1368 return r;
1369
1370 for (f = s, t = r; f < s + length; f++) {
1371
1372 if (*f != '\\') {
1373 *(t++) = *f;
1374 continue;
1375 }
1376
1377 f++;
1378
1379 switch (*f) {
1380
1381 case 'a':
1382 *(t++) = '\a';
1383 break;
1384 case 'b':
1385 *(t++) = '\b';
1386 break;
1387 case 'f':
1388 *(t++) = '\f';
1389 break;
1390 case 'n':
1391 *(t++) = '\n';
1392 break;
1393 case 'r':
1394 *(t++) = '\r';
1395 break;
1396 case 't':
1397 *(t++) = '\t';
1398 break;
1399 case 'v':
1400 *(t++) = '\v';
1401 break;
1402 case '\\':
1403 *(t++) = '\\';
1404 break;
1405 case '"':
1406 *(t++) = '"';
1407 break;
1408 case '\'':
1409 *(t++) = '\'';
1410 break;
1411
1412 case 's':
1413 /* This is an extension of the XDG syntax files */
1414 *(t++) = ' ';
1415 break;
1416
1417 case 'x': {
1418 /* hexadecimal encoding */
1419 int a, b;
1420
1421 if ((a = unhexchar(f[1])) < 0 ||
1422 (b = unhexchar(f[2])) < 0) {
1423 /* Invalid escape code, let's take it literal then */
1424 *(t++) = '\\';
1425 *(t++) = 'x';
1426 } else {
1427 *(t++) = (char) ((a << 4) | b);
1428 f += 2;
1429 }
1430
1431 break;
1432 }
1433
1434 case '0':
1435 case '1':
1436 case '2':
1437 case '3':
1438 case '4':
1439 case '5':
1440 case '6':
1441 case '7': {
1442 /* octal encoding */
1443 int a, b, c;
1444
1445 if ((a = unoctchar(f[0])) < 0 ||
1446 (b = unoctchar(f[1])) < 0 ||
1447 (c = unoctchar(f[2])) < 0) {
1448 /* Invalid escape code, let's take it literal then */
1449 *(t++) = '\\';
1450 *(t++) = f[0];
1451 } else {
1452 *(t++) = (char) ((a << 6) | (b << 3) | c);
1453 f += 2;
1454 }
1455
1456 break;
1457 }
1458
1459 case 0:
1460 /* premature end of string.*/
1461 *(t++) = '\\';
1462 goto finish;
1463
1464 default:
1465 /* Invalid escape code, let's take it literal then */
1466 *(t++) = '\\';
1467 *(t++) = *f;
1468 break;
1469 }
1470 }
1471
1472 finish:
1473 *t = 0;
1474 return r;
1475 }
1476
1477 char *cunescape(const char *s) {
1478 return cunescape_length(s, strlen(s));
1479 }
1480
1481 char *xescape(const char *s, const char *bad) {
1482 char *r, *t;
1483 const char *f;
1484
1485 /* Escapes all chars in bad, in addition to \ and all special
1486 * chars, in \xFF style escaping. May be reversed with
1487 * cunescape. */
1488
1489 if (!(r = new(char, strlen(s)*4+1)))
1490 return NULL;
1491
1492 for (f = s, t = r; *f; f++) {
1493
1494 if ((*f < ' ') || (*f >= 127) ||
1495 (*f == '\\') || strchr(bad, *f)) {
1496 *(t++) = '\\';
1497 *(t++) = 'x';
1498 *(t++) = hexchar(*f >> 4);
1499 *(t++) = hexchar(*f);
1500 } else
1501 *(t++) = *f;
1502 }
1503
1504 *t = 0;
1505
1506 return r;
1507 }
1508
1509 char *bus_path_escape(const char *s) {
1510 char *r, *t;
1511 const char *f;
1512
1513 assert(s);
1514
1515 /* Escapes all chars that D-Bus' object path cannot deal
1516 * with. Can be reverse with bus_path_unescape() */
1517
1518 if (!(r = new(char, strlen(s)*3+1)))
1519 return NULL;
1520
1521 for (f = s, t = r; *f; f++) {
1522
1523 if (!(*f >= 'A' && *f <= 'Z') &&
1524 !(*f >= 'a' && *f <= 'z') &&
1525 !(*f >= '0' && *f <= '9')) {
1526 *(t++) = '_';
1527 *(t++) = hexchar(*f >> 4);
1528 *(t++) = hexchar(*f);
1529 } else
1530 *(t++) = *f;
1531 }
1532
1533 *t = 0;
1534
1535 return r;
1536 }
1537
1538 char *bus_path_unescape(const char *f) {
1539 char *r, *t;
1540
1541 assert(f);
1542
1543 if (!(r = strdup(f)))
1544 return NULL;
1545
1546 for (t = r; *f; f++) {
1547
1548 if (*f == '_') {
1549 int a, b;
1550
1551 if ((a = unhexchar(f[1])) < 0 ||
1552 (b = unhexchar(f[2])) < 0) {
1553 /* Invalid escape code, let's take it literal then */
1554 *(t++) = '_';
1555 } else {
1556 *(t++) = (char) ((a << 4) | b);
1557 f += 2;
1558 }
1559 } else
1560 *(t++) = *f;
1561 }
1562
1563 *t = 0;
1564
1565 return r;
1566 }
1567
1568 char *path_kill_slashes(char *path) {
1569 char *f, *t;
1570 bool slash = false;
1571
1572 /* Removes redundant inner and trailing slashes. Modifies the
1573 * passed string in-place.
1574 *
1575 * ///foo///bar/ becomes /foo/bar
1576 */
1577
1578 for (f = path, t = path; *f; f++) {
1579
1580 if (*f == '/') {
1581 slash = true;
1582 continue;
1583 }
1584
1585 if (slash) {
1586 slash = false;
1587 *(t++) = '/';
1588 }
1589
1590 *(t++) = *f;
1591 }
1592
1593 /* Special rule, if we are talking of the root directory, a
1594 trailing slash is good */
1595
1596 if (t == path && slash)
1597 *(t++) = '/';
1598
1599 *t = 0;
1600 return path;
1601 }
1602
1603 bool path_startswith(const char *path, const char *prefix) {
1604 assert(path);
1605 assert(prefix);
1606
1607 if ((path[0] == '/') != (prefix[0] == '/'))
1608 return false;
1609
1610 for (;;) {
1611 size_t a, b;
1612
1613 path += strspn(path, "/");
1614 prefix += strspn(prefix, "/");
1615
1616 if (*prefix == 0)
1617 return true;
1618
1619 if (*path == 0)
1620 return false;
1621
1622 a = strcspn(path, "/");
1623 b = strcspn(prefix, "/");
1624
1625 if (a != b)
1626 return false;
1627
1628 if (memcmp(path, prefix, a) != 0)
1629 return false;
1630
1631 path += a;
1632 prefix += b;
1633 }
1634 }
1635
1636 bool path_equal(const char *a, const char *b) {
1637 assert(a);
1638 assert(b);
1639
1640 if ((a[0] == '/') != (b[0] == '/'))
1641 return false;
1642
1643 for (;;) {
1644 size_t j, k;
1645
1646 a += strspn(a, "/");
1647 b += strspn(b, "/");
1648
1649 if (*a == 0 && *b == 0)
1650 return true;
1651
1652 if (*a == 0 || *b == 0)
1653 return false;
1654
1655 j = strcspn(a, "/");
1656 k = strcspn(b, "/");
1657
1658 if (j != k)
1659 return false;
1660
1661 if (memcmp(a, b, j) != 0)
1662 return false;
1663
1664 a += j;
1665 b += k;
1666 }
1667 }
1668
1669 char *ascii_strlower(char *t) {
1670 char *p;
1671
1672 assert(t);
1673
1674 for (p = t; *p; p++)
1675 if (*p >= 'A' && *p <= 'Z')
1676 *p = *p - 'A' + 'a';
1677
1678 return t;
1679 }
1680
1681 bool ignore_file(const char *filename) {
1682 assert(filename);
1683
1684 return
1685 filename[0] == '.' ||
1686 streq(filename, "lost+found") ||
1687 streq(filename, "aquota.user") ||
1688 streq(filename, "aquota.group") ||
1689 endswith(filename, "~") ||
1690 endswith(filename, ".rpmnew") ||
1691 endswith(filename, ".rpmsave") ||
1692 endswith(filename, ".rpmorig") ||
1693 endswith(filename, ".dpkg-old") ||
1694 endswith(filename, ".dpkg-new") ||
1695 endswith(filename, ".swp");
1696 }
1697
1698 int fd_nonblock(int fd, bool nonblock) {
1699 int flags;
1700
1701 assert(fd >= 0);
1702
1703 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1704 return -errno;
1705
1706 if (nonblock)
1707 flags |= O_NONBLOCK;
1708 else
1709 flags &= ~O_NONBLOCK;
1710
1711 if (fcntl(fd, F_SETFL, flags) < 0)
1712 return -errno;
1713
1714 return 0;
1715 }
1716
1717 int fd_cloexec(int fd, bool cloexec) {
1718 int flags;
1719
1720 assert(fd >= 0);
1721
1722 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1723 return -errno;
1724
1725 if (cloexec)
1726 flags |= FD_CLOEXEC;
1727 else
1728 flags &= ~FD_CLOEXEC;
1729
1730 if (fcntl(fd, F_SETFD, flags) < 0)
1731 return -errno;
1732
1733 return 0;
1734 }
1735
1736 int close_all_fds(const int except[], unsigned n_except) {
1737 DIR *d;
1738 struct dirent *de;
1739 int r = 0;
1740
1741 if (!(d = opendir("/proc/self/fd")))
1742 return -errno;
1743
1744 while ((de = readdir(d))) {
1745 int fd = -1;
1746
1747 if (ignore_file(de->d_name))
1748 continue;
1749
1750 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1751 goto finish;
1752
1753 if (fd < 3)
1754 continue;
1755
1756 if (fd == dirfd(d))
1757 continue;
1758
1759 if (except) {
1760 bool found;
1761 unsigned i;
1762
1763 found = false;
1764 for (i = 0; i < n_except; i++)
1765 if (except[i] == fd) {
1766 found = true;
1767 break;
1768 }
1769
1770 if (found)
1771 continue;
1772 }
1773
1774 if ((r = close_nointr(fd)) < 0) {
1775 /* Valgrind has its own FD and doesn't want to have it closed */
1776 if (errno != EBADF)
1777 goto finish;
1778 }
1779 }
1780
1781 r = 0;
1782
1783 finish:
1784 closedir(d);
1785 return r;
1786 }
1787
1788 bool chars_intersect(const char *a, const char *b) {
1789 const char *p;
1790
1791 /* Returns true if any of the chars in a are in b. */
1792 for (p = a; *p; p++)
1793 if (strchr(b, *p))
1794 return true;
1795
1796 return false;
1797 }
1798
1799 char *format_timestamp(char *buf, size_t l, usec_t t) {
1800 struct tm tm;
1801 time_t sec;
1802
1803 assert(buf);
1804 assert(l > 0);
1805
1806 if (t <= 0)
1807 return NULL;
1808
1809 sec = (time_t) (t / USEC_PER_SEC);
1810
1811 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1812 return NULL;
1813
1814 return buf;
1815 }
1816
1817 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1818 usec_t n, d;
1819
1820 n = now(CLOCK_REALTIME);
1821
1822 if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1823 return NULL;
1824
1825 d = n - t;
1826
1827 if (d >= USEC_PER_YEAR)
1828 snprintf(buf, l, "%llu years and %llu months ago",
1829 (unsigned long long) (d / USEC_PER_YEAR),
1830 (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1831 else if (d >= USEC_PER_MONTH)
1832 snprintf(buf, l, "%llu months and %llu days ago",
1833 (unsigned long long) (d / USEC_PER_MONTH),
1834 (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1835 else if (d >= USEC_PER_WEEK)
1836 snprintf(buf, l, "%llu weeks and %llu days ago",
1837 (unsigned long long) (d / USEC_PER_WEEK),
1838 (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1839 else if (d >= 2*USEC_PER_DAY)
1840 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1841 else if (d >= 25*USEC_PER_HOUR)
1842 snprintf(buf, l, "1 day and %lluh ago",
1843 (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1844 else if (d >= 6*USEC_PER_HOUR)
1845 snprintf(buf, l, "%lluh ago",
1846 (unsigned long long) (d / USEC_PER_HOUR));
1847 else if (d >= USEC_PER_HOUR)
1848 snprintf(buf, l, "%lluh %llumin ago",
1849 (unsigned long long) (d / USEC_PER_HOUR),
1850 (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1851 else if (d >= 5*USEC_PER_MINUTE)
1852 snprintf(buf, l, "%llumin ago",
1853 (unsigned long long) (d / USEC_PER_MINUTE));
1854 else if (d >= USEC_PER_MINUTE)
1855 snprintf(buf, l, "%llumin %llus ago",
1856 (unsigned long long) (d / USEC_PER_MINUTE),
1857 (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
1858 else if (d >= USEC_PER_SEC)
1859 snprintf(buf, l, "%llus ago",
1860 (unsigned long long) (d / USEC_PER_SEC));
1861 else if (d >= USEC_PER_MSEC)
1862 snprintf(buf, l, "%llums ago",
1863 (unsigned long long) (d / USEC_PER_MSEC));
1864 else if (d > 0)
1865 snprintf(buf, l, "%lluus ago",
1866 (unsigned long long) d);
1867 else
1868 snprintf(buf, l, "now");
1869
1870 buf[l-1] = 0;
1871 return buf;
1872 }
1873
1874 char *format_timespan(char *buf, size_t l, usec_t t) {
1875 static const struct {
1876 const char *suffix;
1877 usec_t usec;
1878 } table[] = {
1879 { "w", USEC_PER_WEEK },
1880 { "d", USEC_PER_DAY },
1881 { "h", USEC_PER_HOUR },
1882 { "min", USEC_PER_MINUTE },
1883 { "s", USEC_PER_SEC },
1884 { "ms", USEC_PER_MSEC },
1885 { "us", 1 },
1886 };
1887
1888 unsigned i;
1889 char *p = buf;
1890
1891 assert(buf);
1892 assert(l > 0);
1893
1894 if (t == (usec_t) -1)
1895 return NULL;
1896
1897 if (t == 0) {
1898 snprintf(p, l, "0");
1899 p[l-1] = 0;
1900 return p;
1901 }
1902
1903 /* The result of this function can be parsed with parse_usec */
1904
1905 for (i = 0; i < ELEMENTSOF(table); i++) {
1906 int k;
1907 size_t n;
1908
1909 if (t < table[i].usec)
1910 continue;
1911
1912 if (l <= 1)
1913 break;
1914
1915 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1916 n = MIN((size_t) k, l);
1917
1918 l -= n;
1919 p += n;
1920
1921 t %= table[i].usec;
1922 }
1923
1924 *p = 0;
1925
1926 return buf;
1927 }
1928
1929 bool fstype_is_network(const char *fstype) {
1930 static const char * const table[] = {
1931 "cifs",
1932 "smbfs",
1933 "ncpfs",
1934 "nfs",
1935 "nfs4",
1936 "gfs",
1937 "gfs2"
1938 };
1939
1940 unsigned i;
1941
1942 for (i = 0; i < ELEMENTSOF(table); i++)
1943 if (streq(table[i], fstype))
1944 return true;
1945
1946 return false;
1947 }
1948
1949 int chvt(int vt) {
1950 int fd, r = 0;
1951
1952 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1953 return -errno;
1954
1955 if (vt < 0) {
1956 int tiocl[2] = {
1957 TIOCL_GETKMSGREDIRECT,
1958 0
1959 };
1960
1961 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1962 return -errno;
1963
1964 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1965 }
1966
1967 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1968 r = -errno;
1969
1970 close_nointr_nofail(r);
1971 return r;
1972 }
1973
1974 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1975 struct termios old_termios, new_termios;
1976 char c;
1977 char line[1024];
1978
1979 assert(f);
1980 assert(ret);
1981
1982 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1983 new_termios = old_termios;
1984
1985 new_termios.c_lflag &= ~ICANON;
1986 new_termios.c_cc[VMIN] = 1;
1987 new_termios.c_cc[VTIME] = 0;
1988
1989 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1990 size_t k;
1991
1992 k = fread(&c, 1, 1, f);
1993
1994 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1995
1996 if (k <= 0)
1997 return -EIO;
1998
1999 if (need_nl)
2000 *need_nl = c != '\n';
2001
2002 *ret = c;
2003 return 0;
2004 }
2005 }
2006
2007 if (!(fgets(line, sizeof(line), f)))
2008 return -EIO;
2009
2010 truncate_nl(line);
2011
2012 if (strlen(line) != 1)
2013 return -EBADMSG;
2014
2015 if (need_nl)
2016 *need_nl = false;
2017
2018 *ret = line[0];
2019 return 0;
2020 }
2021
2022 int ask(char *ret, const char *replies, const char *text, ...) {
2023 bool on_tty;
2024
2025 assert(ret);
2026 assert(replies);
2027 assert(text);
2028
2029 on_tty = isatty(STDOUT_FILENO);
2030
2031 for (;;) {
2032 va_list ap;
2033 char c;
2034 int r;
2035 bool need_nl = true;
2036
2037 if (on_tty)
2038 fputs("\x1B[1m", stdout);
2039
2040 va_start(ap, text);
2041 vprintf(text, ap);
2042 va_end(ap);
2043
2044 if (on_tty)
2045 fputs("\x1B[0m", stdout);
2046
2047 fflush(stdout);
2048
2049 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2050
2051 if (r == -EBADMSG) {
2052 puts("Bad input, please try again.");
2053 continue;
2054 }
2055
2056 putchar('\n');
2057 return r;
2058 }
2059
2060 if (need_nl)
2061 putchar('\n');
2062
2063 if (strchr(replies, c)) {
2064 *ret = c;
2065 return 0;
2066 }
2067
2068 puts("Read unexpected character, please try again.");
2069 }
2070 }
2071
2072 int reset_terminal(int fd) {
2073 struct termios termios;
2074 int r = 0;
2075 long arg;
2076
2077 /* Set terminal to some sane defaults */
2078
2079 assert(fd >= 0);
2080
2081 /* We leave locked terminal attributes untouched, so that
2082 * Plymouth may set whatever it wants to set, and we don't
2083 * interfere with that. */
2084
2085 /* Disable exclusive mode, just in case */
2086 ioctl(fd, TIOCNXCL);
2087
2088 /* Enable console unicode mode */
2089 arg = K_UNICODE;
2090 ioctl(fd, KDSKBMODE, &arg);
2091
2092 if (tcgetattr(fd, &termios) < 0) {
2093 r = -errno;
2094 goto finish;
2095 }
2096
2097 /* We only reset the stuff that matters to the software. How
2098 * hardware is set up we don't touch assuming that somebody
2099 * else will do that for us */
2100
2101 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2102 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2103 termios.c_oflag |= ONLCR;
2104 termios.c_cflag |= CREAD;
2105 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2106
2107 termios.c_cc[VINTR] = 03; /* ^C */
2108 termios.c_cc[VQUIT] = 034; /* ^\ */
2109 termios.c_cc[VERASE] = 0177;
2110 termios.c_cc[VKILL] = 025; /* ^X */
2111 termios.c_cc[VEOF] = 04; /* ^D */
2112 termios.c_cc[VSTART] = 021; /* ^Q */
2113 termios.c_cc[VSTOP] = 023; /* ^S */
2114 termios.c_cc[VSUSP] = 032; /* ^Z */
2115 termios.c_cc[VLNEXT] = 026; /* ^V */
2116 termios.c_cc[VWERASE] = 027; /* ^W */
2117 termios.c_cc[VREPRINT] = 022; /* ^R */
2118 termios.c_cc[VEOL] = 0;
2119 termios.c_cc[VEOL2] = 0;
2120
2121 termios.c_cc[VTIME] = 0;
2122 termios.c_cc[VMIN] = 1;
2123
2124 if (tcsetattr(fd, TCSANOW, &termios) < 0)
2125 r = -errno;
2126
2127 finish:
2128 /* Just in case, flush all crap out */
2129 tcflush(fd, TCIOFLUSH);
2130
2131 return r;
2132 }
2133
2134 int open_terminal(const char *name, int mode) {
2135 int fd, r;
2136
2137 if ((fd = open(name, mode)) < 0)
2138 return -errno;
2139
2140 if ((r = isatty(fd)) < 0) {
2141 close_nointr_nofail(fd);
2142 return -errno;
2143 }
2144
2145 if (!r) {
2146 close_nointr_nofail(fd);
2147 return -ENOTTY;
2148 }
2149
2150 return fd;
2151 }
2152
2153 int flush_fd(int fd) {
2154 struct pollfd pollfd;
2155
2156 zero(pollfd);
2157 pollfd.fd = fd;
2158 pollfd.events = POLLIN;
2159
2160 for (;;) {
2161 char buf[1024];
2162 ssize_t l;
2163 int r;
2164
2165 if ((r = poll(&pollfd, 1, 0)) < 0) {
2166
2167 if (errno == EINTR)
2168 continue;
2169
2170 return -errno;
2171 }
2172
2173 if (r == 0)
2174 return 0;
2175
2176 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2177
2178 if (errno == EINTR)
2179 continue;
2180
2181 if (errno == EAGAIN)
2182 return 0;
2183
2184 return -errno;
2185 }
2186
2187 if (l <= 0)
2188 return 0;
2189 }
2190 }
2191
2192 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2193 int fd = -1, notify = -1, r, wd = -1;
2194
2195 assert(name);
2196
2197 /* We use inotify to be notified when the tty is closed. We
2198 * create the watch before checking if we can actually acquire
2199 * it, so that we don't lose any event.
2200 *
2201 * Note: strictly speaking this actually watches for the
2202 * device being closed, it does *not* really watch whether a
2203 * tty loses its controlling process. However, unless some
2204 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2205 * its tty otherwise this will not become a problem. As long
2206 * as the administrator makes sure not configure any service
2207 * on the same tty as an untrusted user this should not be a
2208 * problem. (Which he probably should not do anyway.) */
2209
2210 if (!fail && !force) {
2211 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2212 r = -errno;
2213 goto fail;
2214 }
2215
2216 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2217 r = -errno;
2218 goto fail;
2219 }
2220 }
2221
2222 for (;;) {
2223 if (notify >= 0)
2224 if ((r = flush_fd(notify)) < 0)
2225 goto fail;
2226
2227 /* We pass here O_NOCTTY only so that we can check the return
2228 * value TIOCSCTTY and have a reliable way to figure out if we
2229 * successfully became the controlling process of the tty */
2230 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2231 return -errno;
2232
2233 /* First, try to get the tty */
2234 r = ioctl(fd, TIOCSCTTY, force);
2235
2236 /* Sometimes it makes sense to ignore TIOCSCTTY
2237 * returning EPERM, i.e. when very likely we already
2238 * are have this controlling terminal. */
2239 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2240 r = 0;
2241
2242 if (r < 0 && (force || fail || errno != EPERM)) {
2243 r = -errno;
2244 goto fail;
2245 }
2246
2247 if (r >= 0)
2248 break;
2249
2250 assert(!fail);
2251 assert(!force);
2252 assert(notify >= 0);
2253
2254 for (;;) {
2255 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2256 ssize_t l;
2257 struct inotify_event *e;
2258
2259 if ((l = read(notify, &inotify_buffer, sizeof(inotify_buffer))) < 0) {
2260
2261 if (errno == EINTR)
2262 continue;
2263
2264 r = -errno;
2265 goto fail;
2266 }
2267
2268 e = (struct inotify_event*) inotify_buffer;
2269
2270 while (l > 0) {
2271 size_t step;
2272
2273 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2274 r = -EIO;
2275 goto fail;
2276 }
2277
2278 step = sizeof(struct inotify_event) + e->len;
2279 assert(step <= (size_t) l);
2280
2281 e = (struct inotify_event*) ((uint8_t*) e + step);
2282 l -= step;
2283 }
2284
2285 break;
2286 }
2287
2288 /* We close the tty fd here since if the old session
2289 * ended our handle will be dead. It's important that
2290 * we do this after sleeping, so that we don't enter
2291 * an endless loop. */
2292 close_nointr_nofail(fd);
2293 }
2294
2295 if (notify >= 0)
2296 close_nointr_nofail(notify);
2297
2298 if ((r = reset_terminal(fd)) < 0)
2299 log_warning("Failed to reset terminal: %s", strerror(-r));
2300
2301 return fd;
2302
2303 fail:
2304 if (fd >= 0)
2305 close_nointr_nofail(fd);
2306
2307 if (notify >= 0)
2308 close_nointr_nofail(notify);
2309
2310 return r;
2311 }
2312
2313 int release_terminal(void) {
2314 int r = 0, fd;
2315 struct sigaction sa_old, sa_new;
2316
2317 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2318 return -errno;
2319
2320 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2321 * by our own TIOCNOTTY */
2322
2323 zero(sa_new);
2324 sa_new.sa_handler = SIG_IGN;
2325 sa_new.sa_flags = SA_RESTART;
2326 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2327
2328 if (ioctl(fd, TIOCNOTTY) < 0)
2329 r = -errno;
2330
2331 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2332
2333 close_nointr_nofail(fd);
2334 return r;
2335 }
2336
2337 int sigaction_many(const struct sigaction *sa, ...) {
2338 va_list ap;
2339 int r = 0, sig;
2340
2341 va_start(ap, sa);
2342 while ((sig = va_arg(ap, int)) > 0)
2343 if (sigaction(sig, sa, NULL) < 0)
2344 r = -errno;
2345 va_end(ap);
2346
2347 return r;
2348 }
2349
2350 int ignore_signals(int sig, ...) {
2351 struct sigaction sa;
2352 va_list ap;
2353 int r = 0;
2354
2355 zero(sa);
2356 sa.sa_handler = SIG_IGN;
2357 sa.sa_flags = SA_RESTART;
2358
2359 if (sigaction(sig, &sa, NULL) < 0)
2360 r = -errno;
2361
2362 va_start(ap, sig);
2363 while ((sig = va_arg(ap, int)) > 0)
2364 if (sigaction(sig, &sa, NULL) < 0)
2365 r = -errno;
2366 va_end(ap);
2367
2368 return r;
2369 }
2370
2371 int default_signals(int sig, ...) {
2372 struct sigaction sa;
2373 va_list ap;
2374 int r = 0;
2375
2376 zero(sa);
2377 sa.sa_handler = SIG_DFL;
2378 sa.sa_flags = SA_RESTART;
2379
2380 if (sigaction(sig, &sa, NULL) < 0)
2381 r = -errno;
2382
2383 va_start(ap, sig);
2384 while ((sig = va_arg(ap, int)) > 0)
2385 if (sigaction(sig, &sa, NULL) < 0)
2386 r = -errno;
2387 va_end(ap);
2388
2389 return r;
2390 }
2391
2392 int close_pipe(int p[]) {
2393 int a = 0, b = 0;
2394
2395 assert(p);
2396
2397 if (p[0] >= 0) {
2398 a = close_nointr(p[0]);
2399 p[0] = -1;
2400 }
2401
2402 if (p[1] >= 0) {
2403 b = close_nointr(p[1]);
2404 p[1] = -1;
2405 }
2406
2407 return a < 0 ? a : b;
2408 }
2409
2410 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2411 uint8_t *p;
2412 ssize_t n = 0;
2413
2414 assert(fd >= 0);
2415 assert(buf);
2416
2417 p = buf;
2418
2419 while (nbytes > 0) {
2420 ssize_t k;
2421
2422 if ((k = read(fd, p, nbytes)) <= 0) {
2423
2424 if (k < 0 && errno == EINTR)
2425 continue;
2426
2427 if (k < 0 && errno == EAGAIN && do_poll) {
2428 struct pollfd pollfd;
2429
2430 zero(pollfd);
2431 pollfd.fd = fd;
2432 pollfd.events = POLLIN;
2433
2434 if (poll(&pollfd, 1, -1) < 0) {
2435 if (errno == EINTR)
2436 continue;
2437
2438 return n > 0 ? n : -errno;
2439 }
2440
2441 if (pollfd.revents != POLLIN)
2442 return n > 0 ? n : -EIO;
2443
2444 continue;
2445 }
2446
2447 return n > 0 ? n : (k < 0 ? -errno : 0);
2448 }
2449
2450 p += k;
2451 nbytes -= k;
2452 n += k;
2453 }
2454
2455 return n;
2456 }
2457
2458 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2459 const uint8_t *p;
2460 ssize_t n = 0;
2461
2462 assert(fd >= 0);
2463 assert(buf);
2464
2465 p = buf;
2466
2467 while (nbytes > 0) {
2468 ssize_t k;
2469
2470 if ((k = write(fd, p, nbytes)) <= 0) {
2471
2472 if (k < 0 && errno == EINTR)
2473 continue;
2474
2475 if (k < 0 && errno == EAGAIN && do_poll) {
2476 struct pollfd pollfd;
2477
2478 zero(pollfd);
2479 pollfd.fd = fd;
2480 pollfd.events = POLLOUT;
2481
2482 if (poll(&pollfd, 1, -1) < 0) {
2483 if (errno == EINTR)
2484 continue;
2485
2486 return n > 0 ? n : -errno;
2487 }
2488
2489 if (pollfd.revents != POLLOUT)
2490 return n > 0 ? n : -EIO;
2491
2492 continue;
2493 }
2494
2495 return n > 0 ? n : (k < 0 ? -errno : 0);
2496 }
2497
2498 p += k;
2499 nbytes -= k;
2500 n += k;
2501 }
2502
2503 return n;
2504 }
2505
2506 int path_is_mount_point(const char *t) {
2507 struct stat a, b;
2508 char *parent;
2509 int r;
2510
2511 if (lstat(t, &a) < 0) {
2512 if (errno == ENOENT)
2513 return 0;
2514
2515 return -errno;
2516 }
2517
2518 if ((r = parent_of_path(t, &parent)) < 0)
2519 return r;
2520
2521 r = lstat(parent, &b);
2522 free(parent);
2523
2524 if (r < 0)
2525 return -errno;
2526
2527 return a.st_dev != b.st_dev;
2528 }
2529
2530 int parse_usec(const char *t, usec_t *usec) {
2531 static const struct {
2532 const char *suffix;
2533 usec_t usec;
2534 } table[] = {
2535 { "sec", USEC_PER_SEC },
2536 { "s", USEC_PER_SEC },
2537 { "min", USEC_PER_MINUTE },
2538 { "hr", USEC_PER_HOUR },
2539 { "h", USEC_PER_HOUR },
2540 { "d", USEC_PER_DAY },
2541 { "w", USEC_PER_WEEK },
2542 { "msec", USEC_PER_MSEC },
2543 { "ms", USEC_PER_MSEC },
2544 { "m", USEC_PER_MINUTE },
2545 { "usec", 1ULL },
2546 { "us", 1ULL },
2547 { "", USEC_PER_SEC },
2548 };
2549
2550 const char *p;
2551 usec_t r = 0;
2552
2553 assert(t);
2554 assert(usec);
2555
2556 p = t;
2557 do {
2558 long long l;
2559 char *e;
2560 unsigned i;
2561
2562 errno = 0;
2563 l = strtoll(p, &e, 10);
2564
2565 if (errno != 0)
2566 return -errno;
2567
2568 if (l < 0)
2569 return -ERANGE;
2570
2571 if (e == p)
2572 return -EINVAL;
2573
2574 e += strspn(e, WHITESPACE);
2575
2576 for (i = 0; i < ELEMENTSOF(table); i++)
2577 if (startswith(e, table[i].suffix)) {
2578 r += (usec_t) l * table[i].usec;
2579 p = e + strlen(table[i].suffix);
2580 break;
2581 }
2582
2583 if (i >= ELEMENTSOF(table))
2584 return -EINVAL;
2585
2586 } while (*p != 0);
2587
2588 *usec = r;
2589
2590 return 0;
2591 }
2592
2593 int make_stdio(int fd) {
2594 int r, s, t;
2595
2596 assert(fd >= 0);
2597
2598 r = dup2(fd, STDIN_FILENO);
2599 s = dup2(fd, STDOUT_FILENO);
2600 t = dup2(fd, STDERR_FILENO);
2601
2602 if (fd >= 3)
2603 close_nointr_nofail(fd);
2604
2605 if (r < 0 || s < 0 || t < 0)
2606 return -errno;
2607
2608 return 0;
2609 }
2610
2611 int make_null_stdio(void) {
2612 int null_fd;
2613
2614 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
2615 return -errno;
2616
2617 return make_stdio(null_fd);
2618 }
2619
2620 bool is_clean_exit(int code, int status) {
2621
2622 if (code == CLD_EXITED)
2623 return status == 0;
2624
2625 /* If a daemon does not implement handlers for some of the
2626 * signals that's not considered an unclean shutdown */
2627 if (code == CLD_KILLED)
2628 return
2629 status == SIGHUP ||
2630 status == SIGINT ||
2631 status == SIGTERM ||
2632 status == SIGPIPE;
2633
2634 return false;
2635 }
2636
2637 bool is_clean_exit_lsb(int code, int status) {
2638
2639 if (is_clean_exit(code, status))
2640 return true;
2641
2642 return
2643 code == CLD_EXITED &&
2644 (status == EXIT_NOTINSTALLED || status == EXIT_NOTCONFIGURED);
2645 }
2646
2647 bool is_device_path(const char *path) {
2648
2649 /* Returns true on paths that refer to a device, either in
2650 * sysfs or in /dev */
2651
2652 return
2653 path_startswith(path, "/dev/") ||
2654 path_startswith(path, "/sys/");
2655 }
2656
2657 int dir_is_empty(const char *path) {
2658 DIR *d;
2659 int r;
2660 struct dirent buf, *de;
2661
2662 if (!(d = opendir(path)))
2663 return -errno;
2664
2665 for (;;) {
2666 if ((r = readdir_r(d, &buf, &de)) > 0) {
2667 r = -r;
2668 break;
2669 }
2670
2671 if (!de) {
2672 r = 1;
2673 break;
2674 }
2675
2676 if (!ignore_file(de->d_name)) {
2677 r = 0;
2678 break;
2679 }
2680 }
2681
2682 closedir(d);
2683 return r;
2684 }
2685
2686 unsigned long long random_ull(void) {
2687 int fd;
2688 uint64_t ull;
2689 ssize_t r;
2690
2691 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2692 goto fallback;
2693
2694 r = loop_read(fd, &ull, sizeof(ull), true);
2695 close_nointr_nofail(fd);
2696
2697 if (r != sizeof(ull))
2698 goto fallback;
2699
2700 return ull;
2701
2702 fallback:
2703 return random() * RAND_MAX + random();
2704 }
2705
2706 void rename_process(const char name[8]) {
2707 assert(name);
2708
2709 prctl(PR_SET_NAME, name);
2710
2711 /* This is a like a poor man's setproctitle(). The string
2712 * passed should fit in 7 chars (i.e. the length of
2713 * "systemd") */
2714
2715 if (program_invocation_name)
2716 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2717 }
2718
2719 void sigset_add_many(sigset_t *ss, ...) {
2720 va_list ap;
2721 int sig;
2722
2723 assert(ss);
2724
2725 va_start(ap, ss);
2726 while ((sig = va_arg(ap, int)) > 0)
2727 assert_se(sigaddset(ss, sig) == 0);
2728 va_end(ap);
2729 }
2730
2731 char* gethostname_malloc(void) {
2732 struct utsname u;
2733
2734 assert_se(uname(&u) >= 0);
2735
2736 if (u.nodename[0])
2737 return strdup(u.nodename);
2738
2739 return strdup(u.sysname);
2740 }
2741
2742 char* getlogname_malloc(void) {
2743 uid_t uid;
2744 long bufsize;
2745 char *buf, *name;
2746 struct passwd pwbuf, *pw = NULL;
2747 struct stat st;
2748
2749 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2750 uid = st.st_uid;
2751 else
2752 uid = getuid();
2753
2754 /* Shortcut things to avoid NSS lookups */
2755 if (uid == 0)
2756 return strdup("root");
2757
2758 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2759 bufsize = 4096;
2760
2761 if (!(buf = malloc(bufsize)))
2762 return NULL;
2763
2764 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2765 name = strdup(pw->pw_name);
2766 free(buf);
2767 return name;
2768 }
2769
2770 free(buf);
2771
2772 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2773 return NULL;
2774
2775 return name;
2776 }
2777
2778 int getttyname_malloc(char **r) {
2779 char path[PATH_MAX], *p, *c;
2780 int k;
2781
2782 assert(r);
2783
2784 if ((k = ttyname_r(STDIN_FILENO, path, sizeof(path))) != 0)
2785 return -k;
2786
2787 char_array_0(path);
2788
2789 p = path;
2790 if (startswith(path, "/dev/"))
2791 p += 5;
2792
2793 if (!(c = strdup(p)))
2794 return -ENOMEM;
2795
2796 *r = c;
2797 return 0;
2798 }
2799
2800 static int rm_rf_children(int fd, bool only_dirs) {
2801 DIR *d;
2802 int ret = 0;
2803
2804 assert(fd >= 0);
2805
2806 /* This returns the first error we run into, but nevertheless
2807 * tries to go on */
2808
2809 if (!(d = fdopendir(fd))) {
2810 close_nointr_nofail(fd);
2811
2812 return errno == ENOENT ? 0 : -errno;
2813 }
2814
2815 for (;;) {
2816 struct dirent buf, *de;
2817 bool is_dir;
2818 int r;
2819
2820 if ((r = readdir_r(d, &buf, &de)) != 0) {
2821 if (ret == 0)
2822 ret = -r;
2823 break;
2824 }
2825
2826 if (!de)
2827 break;
2828
2829 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2830 continue;
2831
2832 if (de->d_type == DT_UNKNOWN) {
2833 struct stat st;
2834
2835 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2836 if (ret == 0 && errno != ENOENT)
2837 ret = -errno;
2838 continue;
2839 }
2840
2841 is_dir = S_ISDIR(st.st_mode);
2842 } else
2843 is_dir = de->d_type == DT_DIR;
2844
2845 if (is_dir) {
2846 int subdir_fd;
2847
2848 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2849 if (ret == 0 && errno != ENOENT)
2850 ret = -errno;
2851 continue;
2852 }
2853
2854 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2855 if (ret == 0)
2856 ret = r;
2857 }
2858
2859 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2860 if (ret == 0 && errno != ENOENT)
2861 ret = -errno;
2862 }
2863 } else if (!only_dirs) {
2864
2865 if (unlinkat(fd, de->d_name, 0) < 0) {
2866 if (ret == 0 && errno != ENOENT)
2867 ret = -errno;
2868 }
2869 }
2870 }
2871
2872 closedir(d);
2873
2874 return ret;
2875 }
2876
2877 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2878 int fd;
2879 int r;
2880
2881 assert(path);
2882
2883 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2884
2885 if (errno != ENOTDIR)
2886 return -errno;
2887
2888 if (delete_root && !only_dirs)
2889 if (unlink(path) < 0)
2890 return -errno;
2891
2892 return 0;
2893 }
2894
2895 r = rm_rf_children(fd, only_dirs);
2896
2897 if (delete_root)
2898 if (rmdir(path) < 0) {
2899 if (r == 0)
2900 r = -errno;
2901 }
2902
2903 return r;
2904 }
2905
2906 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2907 assert(path);
2908
2909 /* Under the assumption that we are running privileged we
2910 * first change the access mode and only then hand out
2911 * ownership to avoid a window where access is too open. */
2912
2913 if (chmod(path, mode) < 0)
2914 return -errno;
2915
2916 if (chown(path, uid, gid) < 0)
2917 return -errno;
2918
2919 return 0;
2920 }
2921
2922 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2923 cpu_set_t *r;
2924 unsigned n = 1024;
2925
2926 /* Allocates the cpuset in the right size */
2927
2928 for (;;) {
2929 if (!(r = CPU_ALLOC(n)))
2930 return NULL;
2931
2932 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2933 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2934
2935 if (ncpus)
2936 *ncpus = n;
2937
2938 return r;
2939 }
2940
2941 CPU_FREE(r);
2942
2943 if (errno != EINVAL)
2944 return NULL;
2945
2946 n *= 2;
2947 }
2948 }
2949
2950 void status_vprintf(const char *format, va_list ap) {
2951 char *s = NULL;
2952 int fd = -1;
2953
2954 assert(format);
2955
2956 /* This independent of logging, as status messages are
2957 * optional and go exclusively to the console. */
2958
2959 if (vasprintf(&s, format, ap) < 0)
2960 goto finish;
2961
2962 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2963 goto finish;
2964
2965 write(fd, s, strlen(s));
2966
2967 finish:
2968 free(s);
2969
2970 if (fd >= 0)
2971 close_nointr_nofail(fd);
2972 }
2973
2974 void status_printf(const char *format, ...) {
2975 va_list ap;
2976
2977 assert(format);
2978
2979 va_start(ap, format);
2980 status_vprintf(format, ap);
2981 va_end(ap);
2982 }
2983
2984 void status_welcome(void) {
2985 char *pretty_name = NULL, *ansi_color = NULL;
2986 const char *const_pretty = NULL, *const_color = NULL;
2987 int r;
2988
2989 if ((r = parse_env_file("/etc/os-release", NEWLINE,
2990 "PRETTY_NAME", &pretty_name,
2991 "ANSI_COLOR", &ansi_color,
2992 NULL)) < 0) {
2993
2994 if (r != -ENOENT)
2995 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
2996 }
2997
2998 #if defined(TARGET_FEDORA)
2999 if (!pretty_name) {
3000 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3001
3002 if (r != -ENOENT)
3003 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3004 } else
3005 truncate_nl(pretty_name);
3006 }
3007
3008 if (!ansi_color && pretty_name) {
3009
3010 /* This tries to mimic the color magic the old Red Hat sysinit
3011 * script did. */
3012
3013 if (startswith(pretty_name, "Red Hat"))
3014 const_color = "0;31"; /* Red for RHEL */
3015 else if (startswith(pretty_name, "Fedora"))
3016 const_color = "0;34"; /* Blue for Fedora */
3017 }
3018
3019 #elif defined(TARGET_SUSE)
3020
3021 if (!pretty_name) {
3022 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3023
3024 if (r != -ENOENT)
3025 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3026 } else
3027 truncate_nl(pretty_name);
3028 }
3029
3030 if (!ansi_color)
3031 const_color = "0;32"; /* Green for openSUSE */
3032
3033 #elif defined(TARGET_GENTOO)
3034
3035 if (!pretty_name) {
3036 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3037
3038 if (r != -ENOENT)
3039 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3040 } else
3041 truncate_nl(pretty_name);
3042 }
3043
3044 if (!ansi_color)
3045 const_color = "1;34"; /* Light Blue for Gentoo */
3046
3047 #elif defined(TARGET_DEBIAN)
3048
3049 if (!pretty_name) {
3050 char *version;
3051
3052 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3053
3054 if (r != -ENOENT)
3055 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3056 } else {
3057 truncate_nl(version);
3058 pretty_name = strappend("Debian ", version);
3059 free(version);
3060
3061 if (!pretty_name)
3062 log_warning("Failed to allocate Debian version string.");
3063 }
3064 }
3065
3066 if (!ansi_color)
3067 const_color = "1;31"; /* Light Red for Debian */
3068
3069 #elif defined(TARGET_UBUNTU)
3070
3071 if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3072 "DISTRIB_DESCRIPTION", &pretty_name,
3073 NULL)) < 0) {
3074
3075 if (r != -ENOENT)
3076 log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3077 }
3078
3079 if (!ansi_color)
3080 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3081
3082 #elif defined(TARGET_ARCH)
3083
3084 if (!pretty_name)
3085 const_pretty = "Arch Linux";
3086
3087 if (!ansi_color)
3088 const_color = "1;36"; /* Cyan for Arch */
3089 #endif
3090
3091 if (!pretty_name && !const_pretty)
3092 const_pretty = "Linux";
3093
3094 if (!ansi_color && !const_color)
3095 const_color = "1";
3096
3097 status_printf("Welcome to \x1B[%sm%s\x1B[0m!\n",
3098 const_color ? const_color : ansi_color,
3099 const_pretty ? const_pretty : pretty_name);
3100 }
3101
3102 char *replace_env(const char *format, char **env) {
3103 enum {
3104 WORD,
3105 CURLY,
3106 VARIABLE
3107 } state = WORD;
3108
3109 const char *e, *word = format;
3110 char *r = NULL, *k;
3111
3112 assert(format);
3113
3114 for (e = format; *e; e ++) {
3115
3116 switch (state) {
3117
3118 case WORD:
3119 if (*e == '$')
3120 state = CURLY;
3121 break;
3122
3123 case CURLY:
3124 if (*e == '{') {
3125 if (!(k = strnappend(r, word, e-word-1)))
3126 goto fail;
3127
3128 free(r);
3129 r = k;
3130
3131 word = e-1;
3132 state = VARIABLE;
3133
3134 } else if (*e == '$') {
3135 if (!(k = strnappend(r, word, e-word)))
3136 goto fail;
3137
3138 free(r);
3139 r = k;
3140
3141 word = e+1;
3142 state = WORD;
3143 } else
3144 state = WORD;
3145 break;
3146
3147 case VARIABLE:
3148 if (*e == '}') {
3149 const char *t;
3150
3151 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3152 t = "";
3153
3154 if (!(k = strappend(r, t)))
3155 goto fail;
3156
3157 free(r);
3158 r = k;
3159
3160 word = e+1;
3161 state = WORD;
3162 }
3163 break;
3164 }
3165 }
3166
3167 if (!(k = strnappend(r, word, e-word)))
3168 goto fail;
3169
3170 free(r);
3171 return k;
3172
3173 fail:
3174 free(r);
3175 return NULL;
3176 }
3177
3178 char **replace_env_argv(char **argv, char **env) {
3179 char **r, **i;
3180 unsigned k = 0, l = 0;
3181
3182 l = strv_length(argv);
3183
3184 if (!(r = new(char*, l+1)))
3185 return NULL;
3186
3187 STRV_FOREACH(i, argv) {
3188
3189 /* If $FOO appears as single word, replace it by the split up variable */
3190 if ((*i)[0] == '$' && (*i)[1] != '{') {
3191 char *e;
3192 char **w, **m;
3193 unsigned q;
3194
3195 if ((e = strv_env_get(env, *i+1))) {
3196
3197 if (!(m = strv_split_quoted(e))) {
3198 r[k] = NULL;
3199 strv_free(r);
3200 return NULL;
3201 }
3202 } else
3203 m = NULL;
3204
3205 q = strv_length(m);
3206 l = l + q - 1;
3207
3208 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3209 r[k] = NULL;
3210 strv_free(r);
3211 strv_free(m);
3212 return NULL;
3213 }
3214
3215 r = w;
3216 if (m) {
3217 memcpy(r + k, m, q * sizeof(char*));
3218 free(m);
3219 }
3220
3221 k += q;
3222 continue;
3223 }
3224
3225 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3226 if (!(r[k++] = replace_env(*i, env))) {
3227 strv_free(r);
3228 return NULL;
3229 }
3230 }
3231
3232 r[k] = NULL;
3233 return r;
3234 }
3235
3236 int columns(void) {
3237 static __thread int parsed_columns = 0;
3238 const char *e;
3239
3240 if (parsed_columns > 0)
3241 return parsed_columns;
3242
3243 if ((e = getenv("COLUMNS")))
3244 parsed_columns = atoi(e);
3245
3246 if (parsed_columns <= 0) {
3247 struct winsize ws;
3248 zero(ws);
3249
3250 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) >= 0)
3251 parsed_columns = ws.ws_col;
3252 }
3253
3254 if (parsed_columns <= 0)
3255 parsed_columns = 80;
3256
3257 return parsed_columns;
3258 }
3259
3260 int running_in_chroot(void) {
3261 struct stat a, b;
3262
3263 zero(a);
3264 zero(b);
3265
3266 /* Only works as root */
3267
3268 if (stat("/proc/1/root", &a) < 0)
3269 return -errno;
3270
3271 if (stat("/", &b) < 0)
3272 return -errno;
3273
3274 return
3275 a.st_dev != b.st_dev ||
3276 a.st_ino != b.st_ino;
3277 }
3278
3279 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3280 size_t l, x;
3281 char *r;
3282
3283 assert(s);
3284 assert(percent <= 100);
3285 assert(length >= 3);
3286
3287 l = strlen(s);
3288
3289 if (l <= 3 || l <= length)
3290 return strdup(s);
3291
3292 if (!(r = new0(char, length+1)))
3293 return r;
3294
3295 x = (length * percent) / 100;
3296
3297 if (x > length - 3)
3298 x = length - 3;
3299
3300 memcpy(r, s, x);
3301 r[x] = '.';
3302 r[x+1] = '.';
3303 r[x+2] = '.';
3304 memcpy(r + x + 3,
3305 s + l - (length - x - 3),
3306 length - x - 3);
3307
3308 return r;
3309 }
3310
3311 int touch(const char *path) {
3312 int fd;
3313
3314 assert(path);
3315
3316 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0666)) < 0)
3317 return -errno;
3318
3319 close_nointr_nofail(fd);
3320 return 0;
3321 }
3322
3323 char *unquote(const char *s, const char* quotes) {
3324 size_t l;
3325 assert(s);
3326
3327 if ((l = strlen(s)) < 2)
3328 return strdup(s);
3329
3330 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3331 return strndup(s+1, l-2);
3332
3333 return strdup(s);
3334 }
3335
3336 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3337 assert(pid >= 1);
3338 assert(status);
3339
3340 for (;;) {
3341 zero(*status);
3342
3343 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3344
3345 if (errno == EINTR)
3346 continue;
3347
3348 return -errno;
3349 }
3350
3351 return 0;
3352 }
3353 }
3354
3355 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3356 int r;
3357 siginfo_t status;
3358
3359 assert(name);
3360 assert(pid > 1);
3361
3362 if ((r = wait_for_terminate(pid, &status)) < 0) {
3363 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3364 return r;
3365 }
3366
3367 if (status.si_code == CLD_EXITED) {
3368 if (status.si_status != 0) {
3369 log_warning("%s failed with error code %i.", name, status.si_status);
3370 return -EPROTO;
3371 }
3372
3373 log_debug("%s succeeded.", name);
3374 return 0;
3375
3376 } else if (status.si_code == CLD_KILLED ||
3377 status.si_code == CLD_DUMPED) {
3378
3379 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3380 return -EPROTO;
3381 }
3382
3383 log_warning("%s failed due to unknown reason.", name);
3384 return -EPROTO;
3385
3386 }
3387
3388 void freeze(void) {
3389 for (;;)
3390 pause();
3391 }
3392
3393 bool null_or_empty(struct stat *st) {
3394 assert(st);
3395
3396 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3397 return true;
3398
3399 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3400 return true;
3401
3402 return false;
3403 }
3404
3405 DIR *xopendirat(int fd, const char *name, int flags) {
3406 return fdopendir(openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags));
3407 }
3408
3409 int signal_from_string_try_harder(const char *s) {
3410 int signo;
3411 assert(s);
3412
3413 if ((signo = signal_from_string(s)) <= 0)
3414 if (startswith(s, "SIG"))
3415 return signal_from_string(s+3);
3416
3417 return signo;
3418 }
3419
3420 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
3421
3422 assert(f);
3423 assert(name);
3424 assert(t);
3425
3426 if (!dual_timestamp_is_set(t))
3427 return;
3428
3429 fprintf(f, "%s=%llu %llu\n",
3430 name,
3431 (unsigned long long) t->realtime,
3432 (unsigned long long) t->monotonic);
3433 }
3434
3435 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
3436 unsigned long long a, b;
3437
3438 assert(value);
3439 assert(t);
3440
3441 if (sscanf(value, "%lli %llu", &a, &b) != 2)
3442 log_debug("Failed to parse finish timestamp value %s", value);
3443 else {
3444 t->realtime = a;
3445 t->monotonic = b;
3446 }
3447 }
3448
3449 char *fstab_node_to_udev_node(const char *p) {
3450 char *dn, *t, *u;
3451 int r;
3452
3453 /* FIXME: to follow udev's logic 100% we need to leave valid
3454 * UTF8 chars unescaped */
3455
3456 if (startswith(p, "LABEL=")) {
3457
3458 if (!(u = unquote(p+6, "\"\'")))
3459 return NULL;
3460
3461 t = xescape(u, "/ ");
3462 free(u);
3463
3464 if (!t)
3465 return NULL;
3466
3467 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
3468 free(t);
3469
3470 if (r < 0)
3471 return NULL;
3472
3473 return dn;
3474 }
3475
3476 if (startswith(p, "UUID=")) {
3477
3478 if (!(u = unquote(p+5, "\"\'")))
3479 return NULL;
3480
3481 t = xescape(u, "/ ");
3482 free(u);
3483
3484 if (!t)
3485 return NULL;
3486
3487 r = asprintf(&dn, "/dev/disk/by-uuid/%s", ascii_strlower(t));
3488 free(t);
3489
3490 if (r < 0)
3491 return NULL;
3492
3493 return dn;
3494 }
3495
3496 return strdup(p);
3497 }
3498
3499 void filter_environ(const char *prefix) {
3500 int i, j;
3501 assert(prefix);
3502
3503 if (!environ)
3504 return;
3505
3506 for (i = 0, j = 0; environ[i]; i++) {
3507
3508 if (startswith(environ[i], prefix))
3509 continue;
3510
3511 environ[j++] = environ[i];
3512 }
3513
3514 environ[j] = NULL;
3515 }
3516
3517 const char *default_term_for_tty(const char *tty) {
3518 assert(tty);
3519
3520 if (startswith(tty, "/dev/"))
3521 tty += 5;
3522
3523 if (startswith(tty, "tty") &&
3524 tty[3] >= '0' && tty[3] <= '9')
3525 return "TERM=linux";
3526
3527 /* FIXME: Proper handling of /dev/console would be cool */
3528
3529 return "TERM=vt100-nav";
3530 }
3531
3532 static const char *const ioprio_class_table[] = {
3533 [IOPRIO_CLASS_NONE] = "none",
3534 [IOPRIO_CLASS_RT] = "realtime",
3535 [IOPRIO_CLASS_BE] = "best-effort",
3536 [IOPRIO_CLASS_IDLE] = "idle"
3537 };
3538
3539 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
3540
3541 static const char *const sigchld_code_table[] = {
3542 [CLD_EXITED] = "exited",
3543 [CLD_KILLED] = "killed",
3544 [CLD_DUMPED] = "dumped",
3545 [CLD_TRAPPED] = "trapped",
3546 [CLD_STOPPED] = "stopped",
3547 [CLD_CONTINUED] = "continued",
3548 };
3549
3550 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3551
3552 static const char *const log_facility_table[LOG_NFACILITIES] = {
3553 [LOG_FAC(LOG_KERN)] = "kern",
3554 [LOG_FAC(LOG_USER)] = "user",
3555 [LOG_FAC(LOG_MAIL)] = "mail",
3556 [LOG_FAC(LOG_DAEMON)] = "daemon",
3557 [LOG_FAC(LOG_AUTH)] = "auth",
3558 [LOG_FAC(LOG_SYSLOG)] = "syslog",
3559 [LOG_FAC(LOG_LPR)] = "lpr",
3560 [LOG_FAC(LOG_NEWS)] = "news",
3561 [LOG_FAC(LOG_UUCP)] = "uucp",
3562 [LOG_FAC(LOG_CRON)] = "cron",
3563 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3564 [LOG_FAC(LOG_FTP)] = "ftp",
3565 [LOG_FAC(LOG_LOCAL0)] = "local0",
3566 [LOG_FAC(LOG_LOCAL1)] = "local1",
3567 [LOG_FAC(LOG_LOCAL2)] = "local2",
3568 [LOG_FAC(LOG_LOCAL3)] = "local3",
3569 [LOG_FAC(LOG_LOCAL4)] = "local4",
3570 [LOG_FAC(LOG_LOCAL5)] = "local5",
3571 [LOG_FAC(LOG_LOCAL6)] = "local6",
3572 [LOG_FAC(LOG_LOCAL7)] = "local7"
3573 };
3574
3575 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
3576
3577 static const char *const log_level_table[] = {
3578 [LOG_EMERG] = "emerg",
3579 [LOG_ALERT] = "alert",
3580 [LOG_CRIT] = "crit",
3581 [LOG_ERR] = "err",
3582 [LOG_WARNING] = "warning",
3583 [LOG_NOTICE] = "notice",
3584 [LOG_INFO] = "info",
3585 [LOG_DEBUG] = "debug"
3586 };
3587
3588 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
3589
3590 static const char* const sched_policy_table[] = {
3591 [SCHED_OTHER] = "other",
3592 [SCHED_BATCH] = "batch",
3593 [SCHED_IDLE] = "idle",
3594 [SCHED_FIFO] = "fifo",
3595 [SCHED_RR] = "rr"
3596 };
3597
3598 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
3599
3600 static const char* const rlimit_table[] = {
3601 [RLIMIT_CPU] = "LimitCPU",
3602 [RLIMIT_FSIZE] = "LimitFSIZE",
3603 [RLIMIT_DATA] = "LimitDATA",
3604 [RLIMIT_STACK] = "LimitSTACK",
3605 [RLIMIT_CORE] = "LimitCORE",
3606 [RLIMIT_RSS] = "LimitRSS",
3607 [RLIMIT_NOFILE] = "LimitNOFILE",
3608 [RLIMIT_AS] = "LimitAS",
3609 [RLIMIT_NPROC] = "LimitNPROC",
3610 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3611 [RLIMIT_LOCKS] = "LimitLOCKS",
3612 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3613 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3614 [RLIMIT_NICE] = "LimitNICE",
3615 [RLIMIT_RTPRIO] = "LimitRTPRIO",
3616 [RLIMIT_RTTIME] = "LimitRTTIME"
3617 };
3618
3619 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3620
3621 static const char* const ip_tos_table[] = {
3622 [IPTOS_LOWDELAY] = "low-delay",
3623 [IPTOS_THROUGHPUT] = "throughput",
3624 [IPTOS_RELIABILITY] = "reliability",
3625 [IPTOS_LOWCOST] = "low-cost",
3626 };
3627
3628 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
3629
3630 static const char *const signal_table[] = {
3631 [SIGHUP] = "HUP",
3632 [SIGINT] = "INT",
3633 [SIGQUIT] = "QUIT",
3634 [SIGILL] = "ILL",
3635 [SIGTRAP] = "TRAP",
3636 [SIGABRT] = "ABRT",
3637 [SIGBUS] = "BUS",
3638 [SIGFPE] = "FPE",
3639 [SIGKILL] = "KILL",
3640 [SIGUSR1] = "USR1",
3641 [SIGSEGV] = "SEGV",
3642 [SIGUSR2] = "USR2",
3643 [SIGPIPE] = "PIPE",
3644 [SIGALRM] = "ALRM",
3645 [SIGTERM] = "TERM",
3646 #ifdef SIGSTKFLT
3647 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
3648 #endif
3649 [SIGCHLD] = "CHLD",
3650 [SIGCONT] = "CONT",
3651 [SIGSTOP] = "STOP",
3652 [SIGTSTP] = "TSTP",
3653 [SIGTTIN] = "TTIN",
3654 [SIGTTOU] = "TTOU",
3655 [SIGURG] = "URG",
3656 [SIGXCPU] = "XCPU",
3657 [SIGXFSZ] = "XFSZ",
3658 [SIGVTALRM] = "VTALRM",
3659 [SIGPROF] = "PROF",
3660 [SIGWINCH] = "WINCH",
3661 [SIGIO] = "IO",
3662 [SIGPWR] = "PWR",
3663 [SIGSYS] = "SYS"
3664 };
3665
3666 DEFINE_STRING_TABLE_LOOKUP(signal, int);