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