]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/util.c
util: make creation time xattr logic more generic
[thirdparty/systemd.git] / src / shared / 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 Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser 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/poll.h>
43 #include <ctype.h>
44 #include <sys/prctl.h>
45 #include <sys/utsname.h>
46 #include <pwd.h>
47 #include <netinet/ip.h>
48 #include <linux/kd.h>
49 #include <dlfcn.h>
50 #include <sys/wait.h>
51 #include <sys/time.h>
52 #include <glob.h>
53 #include <grp.h>
54 #include <sys/mman.h>
55 #include <sys/vfs.h>
56 #include <sys/mount.h>
57 #include <linux/magic.h>
58 #include <limits.h>
59 #include <langinfo.h>
60 #include <locale.h>
61 #include <sys/personality.h>
62 #include <sys/xattr.h>
63 #include <libgen.h>
64 #undef basename
65
66 #ifdef HAVE_SYS_AUXV_H
67 #include <sys/auxv.h>
68 #endif
69
70 #include "macro.h"
71 #include "util.h"
72 #include "ioprio.h"
73 #include "missing.h"
74 #include "log.h"
75 #include "strv.h"
76 #include "label.h"
77 #include "mkdir.h"
78 #include "path-util.h"
79 #include "exit-status.h"
80 #include "hashmap.h"
81 #include "env-util.h"
82 #include "fileio.h"
83 #include "device-nodes.h"
84 #include "utf8.h"
85 #include "gunicode.h"
86 #include "virt.h"
87 #include "def.h"
88 #include "sparse-endian.h"
89
90 int saved_argc = 0;
91 char **saved_argv = NULL;
92
93 static volatile unsigned cached_columns = 0;
94 static volatile unsigned cached_lines = 0;
95
96 size_t page_size(void) {
97 static thread_local size_t pgsz = 0;
98 long r;
99
100 if (_likely_(pgsz > 0))
101 return pgsz;
102
103 r = sysconf(_SC_PAGESIZE);
104 assert(r > 0);
105
106 pgsz = (size_t) r;
107 return pgsz;
108 }
109
110 bool streq_ptr(const char *a, const char *b) {
111
112 /* Like streq(), but tries to make sense of NULL pointers */
113
114 if (a && b)
115 return streq(a, b);
116
117 if (!a && !b)
118 return true;
119
120 return false;
121 }
122
123 char* endswith(const char *s, const char *postfix) {
124 size_t sl, pl;
125
126 assert(s);
127 assert(postfix);
128
129 sl = strlen(s);
130 pl = strlen(postfix);
131
132 if (pl == 0)
133 return (char*) s + sl;
134
135 if (sl < pl)
136 return NULL;
137
138 if (memcmp(s + sl - pl, postfix, pl) != 0)
139 return NULL;
140
141 return (char*) s + sl - pl;
142 }
143
144 char* first_word(const char *s, const char *word) {
145 size_t sl, wl;
146 const char *p;
147
148 assert(s);
149 assert(word);
150
151 /* Checks if the string starts with the specified word, either
152 * followed by NUL or by whitespace. Returns a pointer to the
153 * NUL or the first character after the whitespace. */
154
155 sl = strlen(s);
156 wl = strlen(word);
157
158 if (sl < wl)
159 return NULL;
160
161 if (wl == 0)
162 return (char*) s;
163
164 if (memcmp(s, word, wl) != 0)
165 return NULL;
166
167 p = s + wl;
168 if (*p == 0)
169 return (char*) p;
170
171 if (!strchr(WHITESPACE, *p))
172 return NULL;
173
174 p += strspn(p, WHITESPACE);
175 return (char*) p;
176 }
177
178 static size_t cescape_char(char c, char *buf) {
179 char * buf_old = buf;
180
181 switch (c) {
182
183 case '\a':
184 *(buf++) = '\\';
185 *(buf++) = 'a';
186 break;
187 case '\b':
188 *(buf++) = '\\';
189 *(buf++) = 'b';
190 break;
191 case '\f':
192 *(buf++) = '\\';
193 *(buf++) = 'f';
194 break;
195 case '\n':
196 *(buf++) = '\\';
197 *(buf++) = 'n';
198 break;
199 case '\r':
200 *(buf++) = '\\';
201 *(buf++) = 'r';
202 break;
203 case '\t':
204 *(buf++) = '\\';
205 *(buf++) = 't';
206 break;
207 case '\v':
208 *(buf++) = '\\';
209 *(buf++) = 'v';
210 break;
211 case '\\':
212 *(buf++) = '\\';
213 *(buf++) = '\\';
214 break;
215 case '"':
216 *(buf++) = '\\';
217 *(buf++) = '"';
218 break;
219 case '\'':
220 *(buf++) = '\\';
221 *(buf++) = '\'';
222 break;
223
224 default:
225 /* For special chars we prefer octal over
226 * hexadecimal encoding, simply because glib's
227 * g_strescape() does the same */
228 if ((c < ' ') || (c >= 127)) {
229 *(buf++) = '\\';
230 *(buf++) = octchar((unsigned char) c >> 6);
231 *(buf++) = octchar((unsigned char) c >> 3);
232 *(buf++) = octchar((unsigned char) c);
233 } else
234 *(buf++) = c;
235 break;
236 }
237
238 return buf - buf_old;
239 }
240
241 int close_nointr(int fd) {
242 assert(fd >= 0);
243
244 if (close(fd) >= 0)
245 return 0;
246
247 /*
248 * Just ignore EINTR; a retry loop is the wrong thing to do on
249 * Linux.
250 *
251 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
252 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
253 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
254 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
255 */
256 if (errno == EINTR)
257 return 0;
258
259 return -errno;
260 }
261
262 int safe_close(int fd) {
263
264 /*
265 * Like close_nointr() but cannot fail. Guarantees errno is
266 * unchanged. Is a NOP with negative fds passed, and returns
267 * -1, so that it can be used in this syntax:
268 *
269 * fd = safe_close(fd);
270 */
271
272 if (fd >= 0) {
273 PROTECT_ERRNO;
274
275 /* The kernel might return pretty much any error code
276 * via close(), but the fd will be closed anyway. The
277 * only condition we want to check for here is whether
278 * the fd was invalid at all... */
279
280 assert_se(close_nointr(fd) != -EBADF);
281 }
282
283 return -1;
284 }
285
286 void close_many(const int fds[], unsigned n_fd) {
287 unsigned i;
288
289 assert(fds || n_fd <= 0);
290
291 for (i = 0; i < n_fd; i++)
292 safe_close(fds[i]);
293 }
294
295 int unlink_noerrno(const char *path) {
296 PROTECT_ERRNO;
297 int r;
298
299 r = unlink(path);
300 if (r < 0)
301 return -errno;
302
303 return 0;
304 }
305
306 int parse_boolean(const char *v) {
307 assert(v);
308
309 if (streq(v, "1") || strcaseeq(v, "yes") || strcaseeq(v, "y") || strcaseeq(v, "true") || strcaseeq(v, "t") || strcaseeq(v, "on"))
310 return 1;
311 else if (streq(v, "0") || strcaseeq(v, "no") || strcaseeq(v, "n") || strcaseeq(v, "false") || strcaseeq(v, "f") || strcaseeq(v, "off"))
312 return 0;
313
314 return -EINVAL;
315 }
316
317 int parse_pid(const char *s, pid_t* ret_pid) {
318 unsigned long ul = 0;
319 pid_t pid;
320 int r;
321
322 assert(s);
323 assert(ret_pid);
324
325 r = safe_atolu(s, &ul);
326 if (r < 0)
327 return r;
328
329 pid = (pid_t) ul;
330
331 if ((unsigned long) pid != ul)
332 return -ERANGE;
333
334 if (pid <= 0)
335 return -ERANGE;
336
337 *ret_pid = pid;
338 return 0;
339 }
340
341 int parse_uid(const char *s, uid_t* ret_uid) {
342 unsigned long ul = 0;
343 uid_t uid;
344 int r;
345
346 assert(s);
347 assert(ret_uid);
348
349 r = safe_atolu(s, &ul);
350 if (r < 0)
351 return r;
352
353 uid = (uid_t) ul;
354
355 if ((unsigned long) uid != ul)
356 return -ERANGE;
357
358 /* Some libc APIs use UID_INVALID as special placeholder */
359 if (uid == (uid_t) 0xFFFFFFFF)
360 return -ENXIO;
361
362 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
363 if (uid == (uid_t) 0xFFFF)
364 return -ENXIO;
365
366 *ret_uid = uid;
367 return 0;
368 }
369
370 int safe_atou(const char *s, unsigned *ret_u) {
371 char *x = NULL;
372 unsigned long l;
373
374 assert(s);
375 assert(ret_u);
376
377 errno = 0;
378 l = strtoul(s, &x, 0);
379
380 if (!x || x == s || *x || errno)
381 return errno > 0 ? -errno : -EINVAL;
382
383 if ((unsigned long) (unsigned) l != l)
384 return -ERANGE;
385
386 *ret_u = (unsigned) l;
387 return 0;
388 }
389
390 int safe_atoi(const char *s, int *ret_i) {
391 char *x = NULL;
392 long l;
393
394 assert(s);
395 assert(ret_i);
396
397 errno = 0;
398 l = strtol(s, &x, 0);
399
400 if (!x || x == s || *x || errno)
401 return errno > 0 ? -errno : -EINVAL;
402
403 if ((long) (int) l != l)
404 return -ERANGE;
405
406 *ret_i = (int) l;
407 return 0;
408 }
409
410 int safe_atou8(const char *s, uint8_t *ret) {
411 char *x = NULL;
412 unsigned long l;
413
414 assert(s);
415 assert(ret);
416
417 errno = 0;
418 l = strtoul(s, &x, 0);
419
420 if (!x || x == s || *x || errno)
421 return errno > 0 ? -errno : -EINVAL;
422
423 if ((unsigned long) (uint8_t) l != l)
424 return -ERANGE;
425
426 *ret = (uint8_t) l;
427 return 0;
428 }
429
430 int safe_atou16(const char *s, uint16_t *ret) {
431 char *x = NULL;
432 unsigned long l;
433
434 assert(s);
435 assert(ret);
436
437 errno = 0;
438 l = strtoul(s, &x, 0);
439
440 if (!x || x == s || *x || errno)
441 return errno > 0 ? -errno : -EINVAL;
442
443 if ((unsigned long) (uint16_t) l != l)
444 return -ERANGE;
445
446 *ret = (uint16_t) l;
447 return 0;
448 }
449
450 int safe_atoi16(const char *s, int16_t *ret) {
451 char *x = NULL;
452 long l;
453
454 assert(s);
455 assert(ret);
456
457 errno = 0;
458 l = strtol(s, &x, 0);
459
460 if (!x || x == s || *x || errno)
461 return errno > 0 ? -errno : -EINVAL;
462
463 if ((long) (int16_t) l != l)
464 return -ERANGE;
465
466 *ret = (int16_t) l;
467 return 0;
468 }
469
470 int safe_atollu(const char *s, long long unsigned *ret_llu) {
471 char *x = NULL;
472 unsigned long long l;
473
474 assert(s);
475 assert(ret_llu);
476
477 errno = 0;
478 l = strtoull(s, &x, 0);
479
480 if (!x || x == s || *x || errno)
481 return errno ? -errno : -EINVAL;
482
483 *ret_llu = l;
484 return 0;
485 }
486
487 int safe_atolli(const char *s, long long int *ret_lli) {
488 char *x = NULL;
489 long long l;
490
491 assert(s);
492 assert(ret_lli);
493
494 errno = 0;
495 l = strtoll(s, &x, 0);
496
497 if (!x || x == s || *x || errno)
498 return errno ? -errno : -EINVAL;
499
500 *ret_lli = l;
501 return 0;
502 }
503
504 int safe_atod(const char *s, double *ret_d) {
505 char *x = NULL;
506 double d = 0;
507
508 assert(s);
509 assert(ret_d);
510
511 RUN_WITH_LOCALE(LC_NUMERIC_MASK, "C") {
512 errno = 0;
513 d = strtod(s, &x);
514 }
515
516 if (!x || x == s || *x || errno)
517 return errno ? -errno : -EINVAL;
518
519 *ret_d = (double) d;
520 return 0;
521 }
522
523 static size_t strcspn_escaped(const char *s, const char *reject) {
524 bool escaped = false;
525 int n;
526
527 for (n=0; s[n]; n++) {
528 if (escaped)
529 escaped = false;
530 else if (s[n] == '\\')
531 escaped = true;
532 else if (strchr(reject, s[n]))
533 break;
534 }
535
536 /* if s ends in \, return index of previous char */
537 return n - escaped;
538 }
539
540 /* Split a string into words. */
541 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
542 const char *current;
543
544 current = *state;
545
546 if (!*current) {
547 assert(**state == '\0');
548 return NULL;
549 }
550
551 current += strspn(current, separator);
552 if (!*current) {
553 *state = current;
554 return NULL;
555 }
556
557 if (quoted && strchr("\'\"", *current)) {
558 char quotechars[2] = {*current, '\0'};
559
560 *l = strcspn_escaped(current + 1, quotechars);
561 if (current[*l + 1] == '\0' ||
562 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
563 /* right quote missing or garbage at the end */
564 *state = current;
565 return NULL;
566 }
567 assert(current[*l + 1] == quotechars[0]);
568 *state = current++ + *l + 2;
569 } else if (quoted) {
570 *l = strcspn_escaped(current, separator);
571 if (current[*l] && !strchr(separator, current[*l])) {
572 /* unfinished escape */
573 *state = current;
574 return NULL;
575 }
576 *state = current + *l;
577 } else {
578 *l = strcspn(current, separator);
579 *state = current + *l;
580 }
581
582 return current;
583 }
584
585 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
586 int r;
587 _cleanup_free_ char *line = NULL;
588 long unsigned ppid;
589 const char *p;
590
591 assert(pid >= 0);
592 assert(_ppid);
593
594 if (pid == 0) {
595 *_ppid = getppid();
596 return 0;
597 }
598
599 p = procfs_file_alloca(pid, "stat");
600 r = read_one_line_file(p, &line);
601 if (r < 0)
602 return r;
603
604 /* Let's skip the pid and comm fields. The latter is enclosed
605 * in () but does not escape any () in its value, so let's
606 * skip over it manually */
607
608 p = strrchr(line, ')');
609 if (!p)
610 return -EIO;
611
612 p++;
613
614 if (sscanf(p, " "
615 "%*c " /* state */
616 "%lu ", /* ppid */
617 &ppid) != 1)
618 return -EIO;
619
620 if ((long unsigned) (pid_t) ppid != ppid)
621 return -ERANGE;
622
623 *_ppid = (pid_t) ppid;
624
625 return 0;
626 }
627
628 int fchmod_umask(int fd, mode_t m) {
629 mode_t u;
630 int r;
631
632 u = umask(0777);
633 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
634 umask(u);
635
636 return r;
637 }
638
639 char *truncate_nl(char *s) {
640 assert(s);
641
642 s[strcspn(s, NEWLINE)] = 0;
643 return s;
644 }
645
646 int get_process_state(pid_t pid) {
647 const char *p;
648 char state;
649 int r;
650 _cleanup_free_ char *line = NULL;
651
652 assert(pid >= 0);
653
654 p = procfs_file_alloca(pid, "stat");
655 r = read_one_line_file(p, &line);
656 if (r < 0)
657 return r;
658
659 p = strrchr(line, ')');
660 if (!p)
661 return -EIO;
662
663 p++;
664
665 if (sscanf(p, " %c", &state) != 1)
666 return -EIO;
667
668 return (unsigned char) state;
669 }
670
671 int get_process_comm(pid_t pid, char **name) {
672 const char *p;
673 int r;
674
675 assert(name);
676 assert(pid >= 0);
677
678 p = procfs_file_alloca(pid, "comm");
679
680 r = read_one_line_file(p, name);
681 if (r == -ENOENT)
682 return -ESRCH;
683
684 return r;
685 }
686
687 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
688 _cleanup_fclose_ FILE *f = NULL;
689 char *r = NULL, *k;
690 const char *p;
691 int c;
692
693 assert(line);
694 assert(pid >= 0);
695
696 p = procfs_file_alloca(pid, "cmdline");
697
698 f = fopen(p, "re");
699 if (!f)
700 return -errno;
701
702 if (max_length == 0) {
703 size_t len = 0, allocated = 0;
704
705 while ((c = getc(f)) != EOF) {
706
707 if (!GREEDY_REALLOC(r, allocated, len+2)) {
708 free(r);
709 return -ENOMEM;
710 }
711
712 r[len++] = isprint(c) ? c : ' ';
713 }
714
715 if (len > 0)
716 r[len-1] = 0;
717
718 } else {
719 bool space = false;
720 size_t left;
721
722 r = new(char, max_length);
723 if (!r)
724 return -ENOMEM;
725
726 k = r;
727 left = max_length;
728 while ((c = getc(f)) != EOF) {
729
730 if (isprint(c)) {
731 if (space) {
732 if (left <= 4)
733 break;
734
735 *(k++) = ' ';
736 left--;
737 space = false;
738 }
739
740 if (left <= 4)
741 break;
742
743 *(k++) = (char) c;
744 left--;
745 } else
746 space = true;
747 }
748
749 if (left <= 4) {
750 size_t n = MIN(left-1, 3U);
751 memcpy(k, "...", n);
752 k[n] = 0;
753 } else
754 *k = 0;
755 }
756
757 /* Kernel threads have no argv[] */
758 if (isempty(r)) {
759 _cleanup_free_ char *t = NULL;
760 int h;
761
762 free(r);
763
764 if (!comm_fallback)
765 return -ENOENT;
766
767 h = get_process_comm(pid, &t);
768 if (h < 0)
769 return h;
770
771 r = strjoin("[", t, "]", NULL);
772 if (!r)
773 return -ENOMEM;
774 }
775
776 *line = r;
777 return 0;
778 }
779
780 int is_kernel_thread(pid_t pid) {
781 const char *p;
782 size_t count;
783 char c;
784 bool eof;
785 FILE *f;
786
787 if (pid == 0)
788 return 0;
789
790 assert(pid > 0);
791
792 p = procfs_file_alloca(pid, "cmdline");
793 f = fopen(p, "re");
794 if (!f)
795 return -errno;
796
797 count = fread(&c, 1, 1, f);
798 eof = feof(f);
799 fclose(f);
800
801 /* Kernel threads have an empty cmdline */
802
803 if (count <= 0)
804 return eof ? 1 : -errno;
805
806 return 0;
807 }
808
809 int get_process_capeff(pid_t pid, char **capeff) {
810 const char *p;
811
812 assert(capeff);
813 assert(pid >= 0);
814
815 p = procfs_file_alloca(pid, "status");
816
817 return get_status_field(p, "\nCapEff:", capeff);
818 }
819
820 static int get_process_link_contents(const char *proc_file, char **name) {
821 int r;
822
823 assert(proc_file);
824 assert(name);
825
826 r = readlink_malloc(proc_file, name);
827 if (r < 0)
828 return r == -ENOENT ? -ESRCH : r;
829
830 return 0;
831 }
832
833 int get_process_exe(pid_t pid, char **name) {
834 const char *p;
835 char *d;
836 int r;
837
838 assert(pid >= 0);
839
840 p = procfs_file_alloca(pid, "exe");
841 r = get_process_link_contents(p, name);
842 if (r < 0)
843 return r;
844
845 d = endswith(*name, " (deleted)");
846 if (d)
847 *d = '\0';
848
849 return 0;
850 }
851
852 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
853 _cleanup_fclose_ FILE *f = NULL;
854 char line[LINE_MAX];
855 const char *p;
856
857 assert(field);
858 assert(uid);
859
860 if (pid == 0)
861 return getuid();
862
863 p = procfs_file_alloca(pid, "status");
864 f = fopen(p, "re");
865 if (!f)
866 return -errno;
867
868 FOREACH_LINE(line, f, return -errno) {
869 char *l;
870
871 l = strstrip(line);
872
873 if (startswith(l, field)) {
874 l += strlen(field);
875 l += strspn(l, WHITESPACE);
876
877 l[strcspn(l, WHITESPACE)] = 0;
878
879 return parse_uid(l, uid);
880 }
881 }
882
883 return -EIO;
884 }
885
886 int get_process_uid(pid_t pid, uid_t *uid) {
887 return get_process_id(pid, "Uid:", uid);
888 }
889
890 int get_process_gid(pid_t pid, gid_t *gid) {
891 assert_cc(sizeof(uid_t) == sizeof(gid_t));
892 return get_process_id(pid, "Gid:", gid);
893 }
894
895 int get_process_cwd(pid_t pid, char **cwd) {
896 const char *p;
897
898 assert(pid >= 0);
899
900 p = procfs_file_alloca(pid, "cwd");
901
902 return get_process_link_contents(p, cwd);
903 }
904
905 int get_process_root(pid_t pid, char **root) {
906 const char *p;
907
908 assert(pid >= 0);
909
910 p = procfs_file_alloca(pid, "root");
911
912 return get_process_link_contents(p, root);
913 }
914
915 int get_process_environ(pid_t pid, char **env) {
916 _cleanup_fclose_ FILE *f = NULL;
917 _cleanup_free_ char *outcome = NULL;
918 int c;
919 const char *p;
920 size_t allocated = 0, sz = 0;
921
922 assert(pid >= 0);
923 assert(env);
924
925 p = procfs_file_alloca(pid, "environ");
926
927 f = fopen(p, "re");
928 if (!f)
929 return -errno;
930
931 while ((c = fgetc(f)) != EOF) {
932 if (!GREEDY_REALLOC(outcome, allocated, sz + 5))
933 return -ENOMEM;
934
935 if (c == '\0')
936 outcome[sz++] = '\n';
937 else
938 sz += cescape_char(c, outcome + sz);
939 }
940
941 outcome[sz] = '\0';
942 *env = outcome;
943 outcome = NULL;
944
945 return 0;
946 }
947
948 char *strnappend(const char *s, const char *suffix, size_t b) {
949 size_t a;
950 char *r;
951
952 if (!s && !suffix)
953 return strdup("");
954
955 if (!s)
956 return strndup(suffix, b);
957
958 if (!suffix)
959 return strdup(s);
960
961 assert(s);
962 assert(suffix);
963
964 a = strlen(s);
965 if (b > ((size_t) -1) - a)
966 return NULL;
967
968 r = new(char, a+b+1);
969 if (!r)
970 return NULL;
971
972 memcpy(r, s, a);
973 memcpy(r+a, suffix, b);
974 r[a+b] = 0;
975
976 return r;
977 }
978
979 char *strappend(const char *s, const char *suffix) {
980 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
981 }
982
983 int readlinkat_malloc(int fd, const char *p, char **ret) {
984 size_t l = 100;
985 int r;
986
987 assert(p);
988 assert(ret);
989
990 for (;;) {
991 char *c;
992 ssize_t n;
993
994 c = new(char, l);
995 if (!c)
996 return -ENOMEM;
997
998 n = readlinkat(fd, p, c, l-1);
999 if (n < 0) {
1000 r = -errno;
1001 free(c);
1002 return r;
1003 }
1004
1005 if ((size_t) n < l-1) {
1006 c[n] = 0;
1007 *ret = c;
1008 return 0;
1009 }
1010
1011 free(c);
1012 l *= 2;
1013 }
1014 }
1015
1016 int readlink_malloc(const char *p, char **ret) {
1017 return readlinkat_malloc(AT_FDCWD, p, ret);
1018 }
1019
1020 int readlink_value(const char *p, char **ret) {
1021 _cleanup_free_ char *link = NULL;
1022 char *value;
1023 int r;
1024
1025 r = readlink_malloc(p, &link);
1026 if (r < 0)
1027 return r;
1028
1029 value = basename(link);
1030 if (!value)
1031 return -ENOENT;
1032
1033 value = strdup(value);
1034 if (!value)
1035 return -ENOMEM;
1036
1037 *ret = value;
1038
1039 return 0;
1040 }
1041
1042 int readlink_and_make_absolute(const char *p, char **r) {
1043 _cleanup_free_ char *target = NULL;
1044 char *k;
1045 int j;
1046
1047 assert(p);
1048 assert(r);
1049
1050 j = readlink_malloc(p, &target);
1051 if (j < 0)
1052 return j;
1053
1054 k = file_in_same_dir(p, target);
1055 if (!k)
1056 return -ENOMEM;
1057
1058 *r = k;
1059 return 0;
1060 }
1061
1062 int readlink_and_canonicalize(const char *p, char **r) {
1063 char *t, *s;
1064 int j;
1065
1066 assert(p);
1067 assert(r);
1068
1069 j = readlink_and_make_absolute(p, &t);
1070 if (j < 0)
1071 return j;
1072
1073 s = canonicalize_file_name(t);
1074 if (s) {
1075 free(t);
1076 *r = s;
1077 } else
1078 *r = t;
1079
1080 path_kill_slashes(*r);
1081
1082 return 0;
1083 }
1084
1085 int reset_all_signal_handlers(void) {
1086 int sig, r = 0;
1087
1088 for (sig = 1; sig < _NSIG; sig++) {
1089 struct sigaction sa = {
1090 .sa_handler = SIG_DFL,
1091 .sa_flags = SA_RESTART,
1092 };
1093
1094 /* These two cannot be caught... */
1095 if (sig == SIGKILL || sig == SIGSTOP)
1096 continue;
1097
1098 /* On Linux the first two RT signals are reserved by
1099 * glibc, and sigaction() will return EINVAL for them. */
1100 if ((sigaction(sig, &sa, NULL) < 0))
1101 if (errno != EINVAL && r == 0)
1102 r = -errno;
1103 }
1104
1105 return r;
1106 }
1107
1108 int reset_signal_mask(void) {
1109 sigset_t ss;
1110
1111 if (sigemptyset(&ss) < 0)
1112 return -errno;
1113
1114 if (sigprocmask(SIG_SETMASK, &ss, NULL) < 0)
1115 return -errno;
1116
1117 return 0;
1118 }
1119
1120 char *strstrip(char *s) {
1121 char *e;
1122
1123 /* Drops trailing whitespace. Modifies the string in
1124 * place. Returns pointer to first non-space character */
1125
1126 s += strspn(s, WHITESPACE);
1127
1128 for (e = strchr(s, 0); e > s; e --)
1129 if (!strchr(WHITESPACE, e[-1]))
1130 break;
1131
1132 *e = 0;
1133
1134 return s;
1135 }
1136
1137 char *delete_chars(char *s, const char *bad) {
1138 char *f, *t;
1139
1140 /* Drops all whitespace, regardless where in the string */
1141
1142 for (f = s, t = s; *f; f++) {
1143 if (strchr(bad, *f))
1144 continue;
1145
1146 *(t++) = *f;
1147 }
1148
1149 *t = 0;
1150
1151 return s;
1152 }
1153
1154 char *file_in_same_dir(const char *path, const char *filename) {
1155 char *e, *r;
1156 size_t k;
1157
1158 assert(path);
1159 assert(filename);
1160
1161 /* This removes the last component of path and appends
1162 * filename, unless the latter is absolute anyway or the
1163 * former isn't */
1164
1165 if (path_is_absolute(filename))
1166 return strdup(filename);
1167
1168 if (!(e = strrchr(path, '/')))
1169 return strdup(filename);
1170
1171 k = strlen(filename);
1172 if (!(r = new(char, e-path+1+k+1)))
1173 return NULL;
1174
1175 memcpy(r, path, e-path+1);
1176 memcpy(r+(e-path)+1, filename, k+1);
1177
1178 return r;
1179 }
1180
1181 int rmdir_parents(const char *path, const char *stop) {
1182 size_t l;
1183 int r = 0;
1184
1185 assert(path);
1186 assert(stop);
1187
1188 l = strlen(path);
1189
1190 /* Skip trailing slashes */
1191 while (l > 0 && path[l-1] == '/')
1192 l--;
1193
1194 while (l > 0) {
1195 char *t;
1196
1197 /* Skip last component */
1198 while (l > 0 && path[l-1] != '/')
1199 l--;
1200
1201 /* Skip trailing slashes */
1202 while (l > 0 && path[l-1] == '/')
1203 l--;
1204
1205 if (l <= 0)
1206 break;
1207
1208 if (!(t = strndup(path, l)))
1209 return -ENOMEM;
1210
1211 if (path_startswith(stop, t)) {
1212 free(t);
1213 return 0;
1214 }
1215
1216 r = rmdir(t);
1217 free(t);
1218
1219 if (r < 0)
1220 if (errno != ENOENT)
1221 return -errno;
1222 }
1223
1224 return 0;
1225 }
1226
1227 char hexchar(int x) {
1228 static const char table[16] = "0123456789abcdef";
1229
1230 return table[x & 15];
1231 }
1232
1233 int unhexchar(char c) {
1234
1235 if (c >= '0' && c <= '9')
1236 return c - '0';
1237
1238 if (c >= 'a' && c <= 'f')
1239 return c - 'a' + 10;
1240
1241 if (c >= 'A' && c <= 'F')
1242 return c - 'A' + 10;
1243
1244 return -EINVAL;
1245 }
1246
1247 char *hexmem(const void *p, size_t l) {
1248 char *r, *z;
1249 const uint8_t *x;
1250
1251 z = r = malloc(l * 2 + 1);
1252 if (!r)
1253 return NULL;
1254
1255 for (x = p; x < (const uint8_t*) p + l; x++) {
1256 *(z++) = hexchar(*x >> 4);
1257 *(z++) = hexchar(*x & 15);
1258 }
1259
1260 *z = 0;
1261 return r;
1262 }
1263
1264 void *unhexmem(const char *p, size_t l) {
1265 uint8_t *r, *z;
1266 const char *x;
1267
1268 assert(p);
1269
1270 z = r = malloc((l + 1) / 2 + 1);
1271 if (!r)
1272 return NULL;
1273
1274 for (x = p; x < p + l; x += 2) {
1275 int a, b;
1276
1277 a = unhexchar(x[0]);
1278 if (x+1 < p + l)
1279 b = unhexchar(x[1]);
1280 else
1281 b = 0;
1282
1283 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1284 }
1285
1286 *z = 0;
1287 return r;
1288 }
1289
1290 char octchar(int x) {
1291 return '0' + (x & 7);
1292 }
1293
1294 int unoctchar(char c) {
1295
1296 if (c >= '0' && c <= '7')
1297 return c - '0';
1298
1299 return -EINVAL;
1300 }
1301
1302 char decchar(int x) {
1303 return '0' + (x % 10);
1304 }
1305
1306 int undecchar(char c) {
1307
1308 if (c >= '0' && c <= '9')
1309 return c - '0';
1310
1311 return -EINVAL;
1312 }
1313
1314 char *cescape(const char *s) {
1315 char *r, *t;
1316 const char *f;
1317
1318 assert(s);
1319
1320 /* Does C style string escaping. */
1321
1322 r = new(char, strlen(s)*4 + 1);
1323 if (!r)
1324 return NULL;
1325
1326 for (f = s, t = r; *f; f++)
1327 t += cescape_char(*f, t);
1328
1329 *t = 0;
1330
1331 return r;
1332 }
1333
1334 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1335 char *r, *t;
1336 const char *f;
1337 size_t pl;
1338
1339 assert(s);
1340
1341 /* Undoes C style string escaping, and optionally prefixes it. */
1342
1343 pl = prefix ? strlen(prefix) : 0;
1344
1345 r = new(char, pl+length+1);
1346 if (!r)
1347 return NULL;
1348
1349 if (prefix)
1350 memcpy(r, prefix, pl);
1351
1352 for (f = s, t = r + pl; f < s + length; f++) {
1353
1354 if (*f != '\\') {
1355 *(t++) = *f;
1356 continue;
1357 }
1358
1359 f++;
1360
1361 switch (*f) {
1362
1363 case 'a':
1364 *(t++) = '\a';
1365 break;
1366 case 'b':
1367 *(t++) = '\b';
1368 break;
1369 case 'f':
1370 *(t++) = '\f';
1371 break;
1372 case 'n':
1373 *(t++) = '\n';
1374 break;
1375 case 'r':
1376 *(t++) = '\r';
1377 break;
1378 case 't':
1379 *(t++) = '\t';
1380 break;
1381 case 'v':
1382 *(t++) = '\v';
1383 break;
1384 case '\\':
1385 *(t++) = '\\';
1386 break;
1387 case '"':
1388 *(t++) = '"';
1389 break;
1390 case '\'':
1391 *(t++) = '\'';
1392 break;
1393
1394 case 's':
1395 /* This is an extension of the XDG syntax files */
1396 *(t++) = ' ';
1397 break;
1398
1399 case 'x': {
1400 /* hexadecimal encoding */
1401 int a, b;
1402
1403 a = unhexchar(f[1]);
1404 b = unhexchar(f[2]);
1405
1406 if (a < 0 || b < 0 || (a == 0 && b == 0)) {
1407 /* Invalid escape code, let's take it literal then */
1408 *(t++) = '\\';
1409 *(t++) = 'x';
1410 } else {
1411 *(t++) = (char) ((a << 4) | b);
1412 f += 2;
1413 }
1414
1415 break;
1416 }
1417
1418 case '0':
1419 case '1':
1420 case '2':
1421 case '3':
1422 case '4':
1423 case '5':
1424 case '6':
1425 case '7': {
1426 /* octal encoding */
1427 int a, b, c;
1428
1429 a = unoctchar(f[0]);
1430 b = unoctchar(f[1]);
1431 c = unoctchar(f[2]);
1432
1433 if (a < 0 || b < 0 || c < 0 || (a == 0 && b == 0 && c == 0)) {
1434 /* Invalid escape code, let's take it literal then */
1435 *(t++) = '\\';
1436 *(t++) = f[0];
1437 } else {
1438 *(t++) = (char) ((a << 6) | (b << 3) | c);
1439 f += 2;
1440 }
1441
1442 break;
1443 }
1444
1445 case 0:
1446 /* premature end of string. */
1447 *(t++) = '\\';
1448 goto finish;
1449
1450 default:
1451 /* Invalid escape code, let's take it literal then */
1452 *(t++) = '\\';
1453 *(t++) = *f;
1454 break;
1455 }
1456 }
1457
1458 finish:
1459 *t = 0;
1460 return r;
1461 }
1462
1463 char *cunescape_length(const char *s, size_t length) {
1464 return cunescape_length_with_prefix(s, length, NULL);
1465 }
1466
1467 char *cunescape(const char *s) {
1468 assert(s);
1469
1470 return cunescape_length(s, strlen(s));
1471 }
1472
1473 char *xescape(const char *s, const char *bad) {
1474 char *r, *t;
1475 const char *f;
1476
1477 /* Escapes all chars in bad, in addition to \ and all special
1478 * chars, in \xFF style escaping. May be reversed with
1479 * cunescape. */
1480
1481 r = new(char, strlen(s) * 4 + 1);
1482 if (!r)
1483 return NULL;
1484
1485 for (f = s, t = r; *f; f++) {
1486
1487 if ((*f < ' ') || (*f >= 127) ||
1488 (*f == '\\') || strchr(bad, *f)) {
1489 *(t++) = '\\';
1490 *(t++) = 'x';
1491 *(t++) = hexchar(*f >> 4);
1492 *(t++) = hexchar(*f);
1493 } else
1494 *(t++) = *f;
1495 }
1496
1497 *t = 0;
1498
1499 return r;
1500 }
1501
1502 char *ascii_strlower(char *t) {
1503 char *p;
1504
1505 assert(t);
1506
1507 for (p = t; *p; p++)
1508 if (*p >= 'A' && *p <= 'Z')
1509 *p = *p - 'A' + 'a';
1510
1511 return t;
1512 }
1513
1514 _pure_ static bool hidden_file_allow_backup(const char *filename) {
1515 assert(filename);
1516
1517 return
1518 filename[0] == '.' ||
1519 streq(filename, "lost+found") ||
1520 streq(filename, "aquota.user") ||
1521 streq(filename, "aquota.group") ||
1522 endswith(filename, ".rpmnew") ||
1523 endswith(filename, ".rpmsave") ||
1524 endswith(filename, ".rpmorig") ||
1525 endswith(filename, ".dpkg-old") ||
1526 endswith(filename, ".dpkg-new") ||
1527 endswith(filename, ".dpkg-tmp") ||
1528 endswith(filename, ".swp");
1529 }
1530
1531 bool hidden_file(const char *filename) {
1532 assert(filename);
1533
1534 if (endswith(filename, "~"))
1535 return true;
1536
1537 return hidden_file_allow_backup(filename);
1538 }
1539
1540 int fd_nonblock(int fd, bool nonblock) {
1541 int flags, nflags;
1542
1543 assert(fd >= 0);
1544
1545 flags = fcntl(fd, F_GETFL, 0);
1546 if (flags < 0)
1547 return -errno;
1548
1549 if (nonblock)
1550 nflags = flags | O_NONBLOCK;
1551 else
1552 nflags = flags & ~O_NONBLOCK;
1553
1554 if (nflags == flags)
1555 return 0;
1556
1557 if (fcntl(fd, F_SETFL, nflags) < 0)
1558 return -errno;
1559
1560 return 0;
1561 }
1562
1563 int fd_cloexec(int fd, bool cloexec) {
1564 int flags, nflags;
1565
1566 assert(fd >= 0);
1567
1568 flags = fcntl(fd, F_GETFD, 0);
1569 if (flags < 0)
1570 return -errno;
1571
1572 if (cloexec)
1573 nflags = flags | FD_CLOEXEC;
1574 else
1575 nflags = flags & ~FD_CLOEXEC;
1576
1577 if (nflags == flags)
1578 return 0;
1579
1580 if (fcntl(fd, F_SETFD, nflags) < 0)
1581 return -errno;
1582
1583 return 0;
1584 }
1585
1586 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1587 unsigned i;
1588
1589 assert(n_fdset == 0 || fdset);
1590
1591 for (i = 0; i < n_fdset; i++)
1592 if (fdset[i] == fd)
1593 return true;
1594
1595 return false;
1596 }
1597
1598 int close_all_fds(const int except[], unsigned n_except) {
1599 _cleanup_closedir_ DIR *d = NULL;
1600 struct dirent *de;
1601 int r = 0;
1602
1603 assert(n_except == 0 || except);
1604
1605 d = opendir("/proc/self/fd");
1606 if (!d) {
1607 int fd;
1608 struct rlimit rl;
1609
1610 /* When /proc isn't available (for example in chroots)
1611 * the fallback is brute forcing through the fd
1612 * table */
1613
1614 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1615 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1616
1617 if (fd_in_set(fd, except, n_except))
1618 continue;
1619
1620 if (close_nointr(fd) < 0)
1621 if (errno != EBADF && r == 0)
1622 r = -errno;
1623 }
1624
1625 return r;
1626 }
1627
1628 while ((de = readdir(d))) {
1629 int fd = -1;
1630
1631 if (hidden_file(de->d_name))
1632 continue;
1633
1634 if (safe_atoi(de->d_name, &fd) < 0)
1635 /* Let's better ignore this, just in case */
1636 continue;
1637
1638 if (fd < 3)
1639 continue;
1640
1641 if (fd == dirfd(d))
1642 continue;
1643
1644 if (fd_in_set(fd, except, n_except))
1645 continue;
1646
1647 if (close_nointr(fd) < 0) {
1648 /* Valgrind has its own FD and doesn't want to have it closed */
1649 if (errno != EBADF && r == 0)
1650 r = -errno;
1651 }
1652 }
1653
1654 return r;
1655 }
1656
1657 bool chars_intersect(const char *a, const char *b) {
1658 const char *p;
1659
1660 /* Returns true if any of the chars in a are in b. */
1661 for (p = a; *p; p++)
1662 if (strchr(b, *p))
1663 return true;
1664
1665 return false;
1666 }
1667
1668 bool fstype_is_network(const char *fstype) {
1669 static const char table[] =
1670 "cifs\0"
1671 "smbfs\0"
1672 "sshfs\0"
1673 "ncpfs\0"
1674 "ncp\0"
1675 "nfs\0"
1676 "nfs4\0"
1677 "gfs\0"
1678 "gfs2\0"
1679 "glusterfs\0";
1680
1681 const char *x;
1682
1683 x = startswith(fstype, "fuse.");
1684 if (x)
1685 fstype = x;
1686
1687 return nulstr_contains(table, fstype);
1688 }
1689
1690 int chvt(int vt) {
1691 _cleanup_close_ int fd;
1692
1693 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1694 if (fd < 0)
1695 return -errno;
1696
1697 if (vt < 0) {
1698 int tiocl[2] = {
1699 TIOCL_GETKMSGREDIRECT,
1700 0
1701 };
1702
1703 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1704 return -errno;
1705
1706 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1707 }
1708
1709 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1710 return -errno;
1711
1712 return 0;
1713 }
1714
1715 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1716 struct termios old_termios, new_termios;
1717 char c, line[LINE_MAX];
1718
1719 assert(f);
1720 assert(ret);
1721
1722 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1723 new_termios = old_termios;
1724
1725 new_termios.c_lflag &= ~ICANON;
1726 new_termios.c_cc[VMIN] = 1;
1727 new_termios.c_cc[VTIME] = 0;
1728
1729 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1730 size_t k;
1731
1732 if (t != USEC_INFINITY) {
1733 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1734 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1735 return -ETIMEDOUT;
1736 }
1737 }
1738
1739 k = fread(&c, 1, 1, f);
1740
1741 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1742
1743 if (k <= 0)
1744 return -EIO;
1745
1746 if (need_nl)
1747 *need_nl = c != '\n';
1748
1749 *ret = c;
1750 return 0;
1751 }
1752 }
1753
1754 if (t != USEC_INFINITY) {
1755 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1756 return -ETIMEDOUT;
1757 }
1758
1759 errno = 0;
1760 if (!fgets(line, sizeof(line), f))
1761 return errno ? -errno : -EIO;
1762
1763 truncate_nl(line);
1764
1765 if (strlen(line) != 1)
1766 return -EBADMSG;
1767
1768 if (need_nl)
1769 *need_nl = false;
1770
1771 *ret = line[0];
1772 return 0;
1773 }
1774
1775 int ask_char(char *ret, const char *replies, const char *text, ...) {
1776 int r;
1777
1778 assert(ret);
1779 assert(replies);
1780 assert(text);
1781
1782 for (;;) {
1783 va_list ap;
1784 char c;
1785 bool need_nl = true;
1786
1787 if (on_tty())
1788 fputs(ANSI_HIGHLIGHT_ON, stdout);
1789
1790 va_start(ap, text);
1791 vprintf(text, ap);
1792 va_end(ap);
1793
1794 if (on_tty())
1795 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1796
1797 fflush(stdout);
1798
1799 r = read_one_char(stdin, &c, USEC_INFINITY, &need_nl);
1800 if (r < 0) {
1801
1802 if (r == -EBADMSG) {
1803 puts("Bad input, please try again.");
1804 continue;
1805 }
1806
1807 putchar('\n');
1808 return r;
1809 }
1810
1811 if (need_nl)
1812 putchar('\n');
1813
1814 if (strchr(replies, c)) {
1815 *ret = c;
1816 return 0;
1817 }
1818
1819 puts("Read unexpected character, please try again.");
1820 }
1821 }
1822
1823 int ask_string(char **ret, const char *text, ...) {
1824 assert(ret);
1825 assert(text);
1826
1827 for (;;) {
1828 char line[LINE_MAX];
1829 va_list ap;
1830
1831 if (on_tty())
1832 fputs(ANSI_HIGHLIGHT_ON, stdout);
1833
1834 va_start(ap, text);
1835 vprintf(text, ap);
1836 va_end(ap);
1837
1838 if (on_tty())
1839 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1840
1841 fflush(stdout);
1842
1843 errno = 0;
1844 if (!fgets(line, sizeof(line), stdin))
1845 return errno ? -errno : -EIO;
1846
1847 if (!endswith(line, "\n"))
1848 putchar('\n');
1849 else {
1850 char *s;
1851
1852 if (isempty(line))
1853 continue;
1854
1855 truncate_nl(line);
1856 s = strdup(line);
1857 if (!s)
1858 return -ENOMEM;
1859
1860 *ret = s;
1861 return 0;
1862 }
1863 }
1864 }
1865
1866 int reset_terminal_fd(int fd, bool switch_to_text) {
1867 struct termios termios;
1868 int r = 0;
1869
1870 /* Set terminal to some sane defaults */
1871
1872 assert(fd >= 0);
1873
1874 /* We leave locked terminal attributes untouched, so that
1875 * Plymouth may set whatever it wants to set, and we don't
1876 * interfere with that. */
1877
1878 /* Disable exclusive mode, just in case */
1879 ioctl(fd, TIOCNXCL);
1880
1881 /* Switch to text mode */
1882 if (switch_to_text)
1883 ioctl(fd, KDSETMODE, KD_TEXT);
1884
1885 /* Enable console unicode mode */
1886 ioctl(fd, KDSKBMODE, K_UNICODE);
1887
1888 if (tcgetattr(fd, &termios) < 0) {
1889 r = -errno;
1890 goto finish;
1891 }
1892
1893 /* We only reset the stuff that matters to the software. How
1894 * hardware is set up we don't touch assuming that somebody
1895 * else will do that for us */
1896
1897 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1898 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1899 termios.c_oflag |= ONLCR;
1900 termios.c_cflag |= CREAD;
1901 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1902
1903 termios.c_cc[VINTR] = 03; /* ^C */
1904 termios.c_cc[VQUIT] = 034; /* ^\ */
1905 termios.c_cc[VERASE] = 0177;
1906 termios.c_cc[VKILL] = 025; /* ^X */
1907 termios.c_cc[VEOF] = 04; /* ^D */
1908 termios.c_cc[VSTART] = 021; /* ^Q */
1909 termios.c_cc[VSTOP] = 023; /* ^S */
1910 termios.c_cc[VSUSP] = 032; /* ^Z */
1911 termios.c_cc[VLNEXT] = 026; /* ^V */
1912 termios.c_cc[VWERASE] = 027; /* ^W */
1913 termios.c_cc[VREPRINT] = 022; /* ^R */
1914 termios.c_cc[VEOL] = 0;
1915 termios.c_cc[VEOL2] = 0;
1916
1917 termios.c_cc[VTIME] = 0;
1918 termios.c_cc[VMIN] = 1;
1919
1920 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1921 r = -errno;
1922
1923 finish:
1924 /* Just in case, flush all crap out */
1925 tcflush(fd, TCIOFLUSH);
1926
1927 return r;
1928 }
1929
1930 int reset_terminal(const char *name) {
1931 _cleanup_close_ int fd = -1;
1932
1933 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1934 if (fd < 0)
1935 return fd;
1936
1937 return reset_terminal_fd(fd, true);
1938 }
1939
1940 int open_terminal(const char *name, int mode) {
1941 int fd, r;
1942 unsigned c = 0;
1943
1944 /*
1945 * If a TTY is in the process of being closed opening it might
1946 * cause EIO. This is horribly awful, but unlikely to be
1947 * changed in the kernel. Hence we work around this problem by
1948 * retrying a couple of times.
1949 *
1950 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1951 */
1952
1953 assert(!(mode & O_CREAT));
1954
1955 for (;;) {
1956 fd = open(name, mode, 0);
1957 if (fd >= 0)
1958 break;
1959
1960 if (errno != EIO)
1961 return -errno;
1962
1963 /* Max 1s in total */
1964 if (c >= 20)
1965 return -errno;
1966
1967 usleep(50 * USEC_PER_MSEC);
1968 c++;
1969 }
1970
1971 r = isatty(fd);
1972 if (r < 0) {
1973 safe_close(fd);
1974 return -errno;
1975 }
1976
1977 if (!r) {
1978 safe_close(fd);
1979 return -ENOTTY;
1980 }
1981
1982 return fd;
1983 }
1984
1985 int flush_fd(int fd) {
1986 struct pollfd pollfd = {
1987 .fd = fd,
1988 .events = POLLIN,
1989 };
1990
1991 for (;;) {
1992 char buf[LINE_MAX];
1993 ssize_t l;
1994 int r;
1995
1996 r = poll(&pollfd, 1, 0);
1997 if (r < 0) {
1998 if (errno == EINTR)
1999 continue;
2000
2001 return -errno;
2002
2003 } else if (r == 0)
2004 return 0;
2005
2006 l = read(fd, buf, sizeof(buf));
2007 if (l < 0) {
2008
2009 if (errno == EINTR)
2010 continue;
2011
2012 if (errno == EAGAIN)
2013 return 0;
2014
2015 return -errno;
2016 } else if (l == 0)
2017 return 0;
2018 }
2019 }
2020
2021 int acquire_terminal(
2022 const char *name,
2023 bool fail,
2024 bool force,
2025 bool ignore_tiocstty_eperm,
2026 usec_t timeout) {
2027
2028 int fd = -1, notify = -1, r = 0, wd = -1;
2029 usec_t ts = 0;
2030
2031 assert(name);
2032
2033 /* We use inotify to be notified when the tty is closed. We
2034 * create the watch before checking if we can actually acquire
2035 * it, so that we don't lose any event.
2036 *
2037 * Note: strictly speaking this actually watches for the
2038 * device being closed, it does *not* really watch whether a
2039 * tty loses its controlling process. However, unless some
2040 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2041 * its tty otherwise this will not become a problem. As long
2042 * as the administrator makes sure not configure any service
2043 * on the same tty as an untrusted user this should not be a
2044 * problem. (Which he probably should not do anyway.) */
2045
2046 if (timeout != USEC_INFINITY)
2047 ts = now(CLOCK_MONOTONIC);
2048
2049 if (!fail && !force) {
2050 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
2051 if (notify < 0) {
2052 r = -errno;
2053 goto fail;
2054 }
2055
2056 wd = inotify_add_watch(notify, name, IN_CLOSE);
2057 if (wd < 0) {
2058 r = -errno;
2059 goto fail;
2060 }
2061 }
2062
2063 for (;;) {
2064 struct sigaction sa_old, sa_new = {
2065 .sa_handler = SIG_IGN,
2066 .sa_flags = SA_RESTART,
2067 };
2068
2069 if (notify >= 0) {
2070 r = flush_fd(notify);
2071 if (r < 0)
2072 goto fail;
2073 }
2074
2075 /* We pass here O_NOCTTY only so that we can check the return
2076 * value TIOCSCTTY and have a reliable way to figure out if we
2077 * successfully became the controlling process of the tty */
2078 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2079 if (fd < 0)
2080 return fd;
2081
2082 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2083 * if we already own the tty. */
2084 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2085
2086 /* First, try to get the tty */
2087 if (ioctl(fd, TIOCSCTTY, force) < 0)
2088 r = -errno;
2089
2090 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2091
2092 /* Sometimes it makes sense to ignore TIOCSCTTY
2093 * returning EPERM, i.e. when very likely we already
2094 * are have this controlling terminal. */
2095 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2096 r = 0;
2097
2098 if (r < 0 && (force || fail || r != -EPERM)) {
2099 goto fail;
2100 }
2101
2102 if (r >= 0)
2103 break;
2104
2105 assert(!fail);
2106 assert(!force);
2107 assert(notify >= 0);
2108
2109 for (;;) {
2110 union inotify_event_buffer buffer;
2111 struct inotify_event *e;
2112 ssize_t l;
2113
2114 if (timeout != USEC_INFINITY) {
2115 usec_t n;
2116
2117 n = now(CLOCK_MONOTONIC);
2118 if (ts + timeout < n) {
2119 r = -ETIMEDOUT;
2120 goto fail;
2121 }
2122
2123 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2124 if (r < 0)
2125 goto fail;
2126
2127 if (r == 0) {
2128 r = -ETIMEDOUT;
2129 goto fail;
2130 }
2131 }
2132
2133 l = read(notify, &buffer, sizeof(buffer));
2134 if (l < 0) {
2135 if (errno == EINTR || errno == EAGAIN)
2136 continue;
2137
2138 r = -errno;
2139 goto fail;
2140 }
2141
2142 FOREACH_INOTIFY_EVENT(e, buffer, l) {
2143 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2144 r = -EIO;
2145 goto fail;
2146 }
2147 }
2148
2149 break;
2150 }
2151
2152 /* We close the tty fd here since if the old session
2153 * ended our handle will be dead. It's important that
2154 * we do this after sleeping, so that we don't enter
2155 * an endless loop. */
2156 fd = safe_close(fd);
2157 }
2158
2159 safe_close(notify);
2160
2161 r = reset_terminal_fd(fd, true);
2162 if (r < 0)
2163 log_warning_errno(r, "Failed to reset terminal: %m");
2164
2165 return fd;
2166
2167 fail:
2168 safe_close(fd);
2169 safe_close(notify);
2170
2171 return r;
2172 }
2173
2174 int release_terminal(void) {
2175 static const struct sigaction sa_new = {
2176 .sa_handler = SIG_IGN,
2177 .sa_flags = SA_RESTART,
2178 };
2179
2180 _cleanup_close_ int fd = -1;
2181 struct sigaction sa_old;
2182 int r = 0;
2183
2184 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2185 if (fd < 0)
2186 return -errno;
2187
2188 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2189 * by our own TIOCNOTTY */
2190 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2191
2192 if (ioctl(fd, TIOCNOTTY) < 0)
2193 r = -errno;
2194
2195 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2196
2197 return r;
2198 }
2199
2200 int sigaction_many(const struct sigaction *sa, ...) {
2201 va_list ap;
2202 int r = 0, sig;
2203
2204 va_start(ap, sa);
2205 while ((sig = va_arg(ap, int)) > 0)
2206 if (sigaction(sig, sa, NULL) < 0)
2207 r = -errno;
2208 va_end(ap);
2209
2210 return r;
2211 }
2212
2213 int ignore_signals(int sig, ...) {
2214 struct sigaction sa = {
2215 .sa_handler = SIG_IGN,
2216 .sa_flags = SA_RESTART,
2217 };
2218 va_list ap;
2219 int r = 0;
2220
2221 if (sigaction(sig, &sa, NULL) < 0)
2222 r = -errno;
2223
2224 va_start(ap, sig);
2225 while ((sig = va_arg(ap, int)) > 0)
2226 if (sigaction(sig, &sa, NULL) < 0)
2227 r = -errno;
2228 va_end(ap);
2229
2230 return r;
2231 }
2232
2233 int default_signals(int sig, ...) {
2234 struct sigaction sa = {
2235 .sa_handler = SIG_DFL,
2236 .sa_flags = SA_RESTART,
2237 };
2238 va_list ap;
2239 int r = 0;
2240
2241 if (sigaction(sig, &sa, NULL) < 0)
2242 r = -errno;
2243
2244 va_start(ap, sig);
2245 while ((sig = va_arg(ap, int)) > 0)
2246 if (sigaction(sig, &sa, NULL) < 0)
2247 r = -errno;
2248 va_end(ap);
2249
2250 return r;
2251 }
2252
2253 void safe_close_pair(int p[]) {
2254 assert(p);
2255
2256 if (p[0] == p[1]) {
2257 /* Special case pairs which use the same fd in both
2258 * directions... */
2259 p[0] = p[1] = safe_close(p[0]);
2260 return;
2261 }
2262
2263 p[0] = safe_close(p[0]);
2264 p[1] = safe_close(p[1]);
2265 }
2266
2267 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2268 uint8_t *p = buf;
2269 ssize_t n = 0;
2270
2271 assert(fd >= 0);
2272 assert(buf);
2273
2274 while (nbytes > 0) {
2275 ssize_t k;
2276
2277 k = read(fd, p, nbytes);
2278 if (k < 0) {
2279 if (errno == EINTR)
2280 continue;
2281
2282 if (errno == EAGAIN && do_poll) {
2283
2284 /* We knowingly ignore any return value here,
2285 * and expect that any error/EOF is reported
2286 * via read() */
2287
2288 fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
2289 continue;
2290 }
2291
2292 return n > 0 ? n : -errno;
2293 }
2294
2295 if (k == 0)
2296 return n;
2297
2298 p += k;
2299 nbytes -= k;
2300 n += k;
2301 }
2302
2303 return n;
2304 }
2305
2306 int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2307 const uint8_t *p = buf;
2308
2309 assert(fd >= 0);
2310 assert(buf);
2311
2312 errno = 0;
2313
2314 while (nbytes > 0) {
2315 ssize_t k;
2316
2317 k = write(fd, p, nbytes);
2318 if (k < 0) {
2319 if (errno == EINTR)
2320 continue;
2321
2322 if (errno == EAGAIN && do_poll) {
2323 /* We knowingly ignore any return value here,
2324 * and expect that any error/EOF is reported
2325 * via write() */
2326
2327 fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
2328 continue;
2329 }
2330
2331 return -errno;
2332 }
2333
2334 if (k == 0) /* Can't really happen */
2335 return -EIO;
2336
2337 p += k;
2338 nbytes -= k;
2339 }
2340
2341 return 0;
2342 }
2343
2344 int parse_size(const char *t, off_t base, off_t *size) {
2345
2346 /* Soo, sometimes we want to parse IEC binary suffxies, and
2347 * sometimes SI decimal suffixes. This function can parse
2348 * both. Which one is the right way depends on the
2349 * context. Wikipedia suggests that SI is customary for
2350 * hardrware metrics and network speeds, while IEC is
2351 * customary for most data sizes used by software and volatile
2352 * (RAM) memory. Hence be careful which one you pick!
2353 *
2354 * In either case we use just K, M, G as suffix, and not Ki,
2355 * Mi, Gi or so (as IEC would suggest). That's because that's
2356 * frickin' ugly. But this means you really need to make sure
2357 * to document which base you are parsing when you use this
2358 * call. */
2359
2360 struct table {
2361 const char *suffix;
2362 unsigned long long factor;
2363 };
2364
2365 static const struct table iec[] = {
2366 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2367 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2368 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2369 { "G", 1024ULL*1024ULL*1024ULL },
2370 { "M", 1024ULL*1024ULL },
2371 { "K", 1024ULL },
2372 { "B", 1 },
2373 { "", 1 },
2374 };
2375
2376 static const struct table si[] = {
2377 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2378 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2379 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2380 { "G", 1000ULL*1000ULL*1000ULL },
2381 { "M", 1000ULL*1000ULL },
2382 { "K", 1000ULL },
2383 { "B", 1 },
2384 { "", 1 },
2385 };
2386
2387 const struct table *table;
2388 const char *p;
2389 unsigned long long r = 0;
2390 unsigned n_entries, start_pos = 0;
2391
2392 assert(t);
2393 assert(base == 1000 || base == 1024);
2394 assert(size);
2395
2396 if (base == 1000) {
2397 table = si;
2398 n_entries = ELEMENTSOF(si);
2399 } else {
2400 table = iec;
2401 n_entries = ELEMENTSOF(iec);
2402 }
2403
2404 p = t;
2405 do {
2406 long long l;
2407 unsigned long long l2;
2408 double frac = 0;
2409 char *e;
2410 unsigned i;
2411
2412 errno = 0;
2413 l = strtoll(p, &e, 10);
2414
2415 if (errno > 0)
2416 return -errno;
2417
2418 if (l < 0)
2419 return -ERANGE;
2420
2421 if (e == p)
2422 return -EINVAL;
2423
2424 if (*e == '.') {
2425 e++;
2426 if (*e >= '0' && *e <= '9') {
2427 char *e2;
2428
2429 /* strotoull itself would accept space/+/- */
2430 l2 = strtoull(e, &e2, 10);
2431
2432 if (errno == ERANGE)
2433 return -errno;
2434
2435 /* Ignore failure. E.g. 10.M is valid */
2436 frac = l2;
2437 for (; e < e2; e++)
2438 frac /= 10;
2439 }
2440 }
2441
2442 e += strspn(e, WHITESPACE);
2443
2444 for (i = start_pos; i < n_entries; i++)
2445 if (startswith(e, table[i].suffix)) {
2446 unsigned long long tmp;
2447 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
2448 return -ERANGE;
2449 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
2450 if (tmp > ULLONG_MAX - r)
2451 return -ERANGE;
2452
2453 r += tmp;
2454 if ((unsigned long long) (off_t) r != r)
2455 return -ERANGE;
2456
2457 p = e + strlen(table[i].suffix);
2458
2459 start_pos = i + 1;
2460 break;
2461 }
2462
2463 if (i >= n_entries)
2464 return -EINVAL;
2465
2466 } while (*p);
2467
2468 *size = r;
2469
2470 return 0;
2471 }
2472
2473 int make_stdio(int fd) {
2474 int r, s, t;
2475
2476 assert(fd >= 0);
2477
2478 r = dup2(fd, STDIN_FILENO);
2479 s = dup2(fd, STDOUT_FILENO);
2480 t = dup2(fd, STDERR_FILENO);
2481
2482 if (fd >= 3)
2483 safe_close(fd);
2484
2485 if (r < 0 || s < 0 || t < 0)
2486 return -errno;
2487
2488 /* Explicitly unset O_CLOEXEC, since if fd was < 3, then
2489 * dup2() was a NOP and the bit hence possibly set. */
2490 fd_cloexec(STDIN_FILENO, false);
2491 fd_cloexec(STDOUT_FILENO, false);
2492 fd_cloexec(STDERR_FILENO, false);
2493
2494 return 0;
2495 }
2496
2497 int make_null_stdio(void) {
2498 int null_fd;
2499
2500 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2501 if (null_fd < 0)
2502 return -errno;
2503
2504 return make_stdio(null_fd);
2505 }
2506
2507 bool is_device_path(const char *path) {
2508
2509 /* Returns true on paths that refer to a device, either in
2510 * sysfs or in /dev */
2511
2512 return
2513 path_startswith(path, "/dev/") ||
2514 path_startswith(path, "/sys/");
2515 }
2516
2517 int dir_is_empty(const char *path) {
2518 _cleanup_closedir_ DIR *d;
2519
2520 d = opendir(path);
2521 if (!d)
2522 return -errno;
2523
2524 for (;;) {
2525 struct dirent *de;
2526
2527 errno = 0;
2528 de = readdir(d);
2529 if (!de && errno != 0)
2530 return -errno;
2531
2532 if (!de)
2533 return 1;
2534
2535 if (!hidden_file(de->d_name))
2536 return 0;
2537 }
2538 }
2539
2540 char* dirname_malloc(const char *path) {
2541 char *d, *dir, *dir2;
2542
2543 d = strdup(path);
2544 if (!d)
2545 return NULL;
2546 dir = dirname(d);
2547 assert(dir);
2548
2549 if (dir != d) {
2550 dir2 = strdup(dir);
2551 free(d);
2552 return dir2;
2553 }
2554
2555 return dir;
2556 }
2557
2558 int dev_urandom(void *p, size_t n) {
2559 static int have_syscall = -1;
2560 int r, fd;
2561 ssize_t k;
2562
2563 /* Gathers some randomness from the kernel. This call will
2564 * never block, and will always return some data from the
2565 * kernel, regardless if the random pool is fully initialized
2566 * or not. It thus makes no guarantee for the quality of the
2567 * returned entropy, but is good enough for or usual usecases
2568 * of seeding the hash functions for hashtable */
2569
2570 /* Use the getrandom() syscall unless we know we don't have
2571 * it, or when the requested size is too large for it. */
2572 if (have_syscall != 0 || (size_t) (int) n != n) {
2573 r = getrandom(p, n, GRND_NONBLOCK);
2574 if (r == (int) n) {
2575 have_syscall = true;
2576 return 0;
2577 }
2578
2579 if (r < 0) {
2580 if (errno == ENOSYS)
2581 /* we lack the syscall, continue with
2582 * reading from /dev/urandom */
2583 have_syscall = false;
2584 else if (errno == EAGAIN)
2585 /* not enough entropy for now. Let's
2586 * remember to use the syscall the
2587 * next time, again, but also read
2588 * from /dev/urandom for now, which
2589 * doesn't care about the current
2590 * amount of entropy. */
2591 have_syscall = true;
2592 else
2593 return -errno;
2594 } else
2595 /* too short read? */
2596 return -EIO;
2597 }
2598
2599 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2600 if (fd < 0)
2601 return errno == ENOENT ? -ENOSYS : -errno;
2602
2603 k = loop_read(fd, p, n, true);
2604 safe_close(fd);
2605
2606 if (k < 0)
2607 return (int) k;
2608 if ((size_t) k != n)
2609 return -EIO;
2610
2611 return 0;
2612 }
2613
2614 void initialize_srand(void) {
2615 static bool srand_called = false;
2616 unsigned x;
2617 #ifdef HAVE_SYS_AUXV_H
2618 void *auxv;
2619 #endif
2620
2621 if (srand_called)
2622 return;
2623
2624 x = 0;
2625
2626 #ifdef HAVE_SYS_AUXV_H
2627 /* The kernel provides us with a bit of entropy in auxv, so
2628 * let's try to make use of that to seed the pseudo-random
2629 * generator. It's better than nothing... */
2630
2631 auxv = (void*) getauxval(AT_RANDOM);
2632 if (auxv)
2633 x ^= *(unsigned*) auxv;
2634 #endif
2635
2636 x ^= (unsigned) now(CLOCK_REALTIME);
2637 x ^= (unsigned) gettid();
2638
2639 srand(x);
2640 srand_called = true;
2641 }
2642
2643 void random_bytes(void *p, size_t n) {
2644 uint8_t *q;
2645 int r;
2646
2647 r = dev_urandom(p, n);
2648 if (r >= 0)
2649 return;
2650
2651 /* If some idiot made /dev/urandom unavailable to us, he'll
2652 * get a PRNG instead. */
2653
2654 initialize_srand();
2655
2656 for (q = p; q < (uint8_t*) p + n; q ++)
2657 *q = rand();
2658 }
2659
2660 void rename_process(const char name[8]) {
2661 assert(name);
2662
2663 /* This is a like a poor man's setproctitle(). It changes the
2664 * comm field, argv[0], and also the glibc's internally used
2665 * name of the process. For the first one a limit of 16 chars
2666 * applies, to the second one usually one of 10 (i.e. length
2667 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2668 * "systemd"). If you pass a longer string it will be
2669 * truncated */
2670
2671 prctl(PR_SET_NAME, name);
2672
2673 if (program_invocation_name)
2674 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2675
2676 if (saved_argc > 0) {
2677 int i;
2678
2679 if (saved_argv[0])
2680 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2681
2682 for (i = 1; i < saved_argc; i++) {
2683 if (!saved_argv[i])
2684 break;
2685
2686 memzero(saved_argv[i], strlen(saved_argv[i]));
2687 }
2688 }
2689 }
2690
2691 void sigset_add_many(sigset_t *ss, ...) {
2692 va_list ap;
2693 int sig;
2694
2695 assert(ss);
2696
2697 va_start(ap, ss);
2698 while ((sig = va_arg(ap, int)) > 0)
2699 assert_se(sigaddset(ss, sig) == 0);
2700 va_end(ap);
2701 }
2702
2703 int sigprocmask_many(int how, ...) {
2704 va_list ap;
2705 sigset_t ss;
2706 int sig;
2707
2708 assert_se(sigemptyset(&ss) == 0);
2709
2710 va_start(ap, how);
2711 while ((sig = va_arg(ap, int)) > 0)
2712 assert_se(sigaddset(&ss, sig) == 0);
2713 va_end(ap);
2714
2715 if (sigprocmask(how, &ss, NULL) < 0)
2716 return -errno;
2717
2718 return 0;
2719 }
2720
2721 char* gethostname_malloc(void) {
2722 struct utsname u;
2723
2724 assert_se(uname(&u) >= 0);
2725
2726 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2727 return strdup(u.nodename);
2728
2729 return strdup(u.sysname);
2730 }
2731
2732 bool hostname_is_set(void) {
2733 struct utsname u;
2734
2735 assert_se(uname(&u) >= 0);
2736
2737 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2738 }
2739
2740 char *lookup_uid(uid_t uid) {
2741 long bufsize;
2742 char *name;
2743 _cleanup_free_ char *buf = NULL;
2744 struct passwd pwbuf, *pw = NULL;
2745
2746 /* Shortcut things to avoid NSS lookups */
2747 if (uid == 0)
2748 return strdup("root");
2749
2750 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2751 if (bufsize <= 0)
2752 bufsize = 4096;
2753
2754 buf = malloc(bufsize);
2755 if (!buf)
2756 return NULL;
2757
2758 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2759 return strdup(pw->pw_name);
2760
2761 if (asprintf(&name, UID_FMT, uid) < 0)
2762 return NULL;
2763
2764 return name;
2765 }
2766
2767 char* getlogname_malloc(void) {
2768 uid_t uid;
2769 struct stat st;
2770
2771 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2772 uid = st.st_uid;
2773 else
2774 uid = getuid();
2775
2776 return lookup_uid(uid);
2777 }
2778
2779 char *getusername_malloc(void) {
2780 const char *e;
2781
2782 e = getenv("USER");
2783 if (e)
2784 return strdup(e);
2785
2786 return lookup_uid(getuid());
2787 }
2788
2789 int getttyname_malloc(int fd, char **ret) {
2790 size_t l = 100;
2791 int r;
2792
2793 assert(fd >= 0);
2794 assert(ret);
2795
2796 for (;;) {
2797 char path[l];
2798
2799 r = ttyname_r(fd, path, sizeof(path));
2800 if (r == 0) {
2801 const char *p;
2802 char *c;
2803
2804 p = startswith(path, "/dev/");
2805 c = strdup(p ?: path);
2806 if (!c)
2807 return -ENOMEM;
2808
2809 *ret = c;
2810 return 0;
2811 }
2812
2813 if (r != ERANGE)
2814 return -r;
2815
2816 l *= 2;
2817 }
2818
2819 return 0;
2820 }
2821
2822 int getttyname_harder(int fd, char **r) {
2823 int k;
2824 char *s;
2825
2826 k = getttyname_malloc(fd, &s);
2827 if (k < 0)
2828 return k;
2829
2830 if (streq(s, "tty")) {
2831 free(s);
2832 return get_ctty(0, NULL, r);
2833 }
2834
2835 *r = s;
2836 return 0;
2837 }
2838
2839 int get_ctty_devnr(pid_t pid, dev_t *d) {
2840 int r;
2841 _cleanup_free_ char *line = NULL;
2842 const char *p;
2843 unsigned long ttynr;
2844
2845 assert(pid >= 0);
2846
2847 p = procfs_file_alloca(pid, "stat");
2848 r = read_one_line_file(p, &line);
2849 if (r < 0)
2850 return r;
2851
2852 p = strrchr(line, ')');
2853 if (!p)
2854 return -EIO;
2855
2856 p++;
2857
2858 if (sscanf(p, " "
2859 "%*c " /* state */
2860 "%*d " /* ppid */
2861 "%*d " /* pgrp */
2862 "%*d " /* session */
2863 "%lu ", /* ttynr */
2864 &ttynr) != 1)
2865 return -EIO;
2866
2867 if (major(ttynr) == 0 && minor(ttynr) == 0)
2868 return -ENOENT;
2869
2870 if (d)
2871 *d = (dev_t) ttynr;
2872
2873 return 0;
2874 }
2875
2876 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2877 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b = NULL;
2878 _cleanup_free_ char *s = NULL;
2879 const char *p;
2880 dev_t devnr;
2881 int k;
2882
2883 assert(r);
2884
2885 k = get_ctty_devnr(pid, &devnr);
2886 if (k < 0)
2887 return k;
2888
2889 sprintf(fn, "/dev/char/%u:%u", major(devnr), minor(devnr));
2890
2891 k = readlink_malloc(fn, &s);
2892 if (k < 0) {
2893
2894 if (k != -ENOENT)
2895 return k;
2896
2897 /* This is an ugly hack */
2898 if (major(devnr) == 136) {
2899 asprintf(&b, "pts/%u", minor(devnr));
2900 goto finish;
2901 }
2902
2903 /* Probably something like the ptys which have no
2904 * symlink in /dev/char. Let's return something
2905 * vaguely useful. */
2906
2907 b = strdup(fn + 5);
2908 goto finish;
2909 }
2910
2911 if (startswith(s, "/dev/"))
2912 p = s + 5;
2913 else if (startswith(s, "../"))
2914 p = s + 3;
2915 else
2916 p = s;
2917
2918 b = strdup(p);
2919
2920 finish:
2921 if (!b)
2922 return -ENOMEM;
2923
2924 *r = b;
2925 if (_devnr)
2926 *_devnr = devnr;
2927
2928 return 0;
2929 }
2930
2931 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2932 _cleanup_closedir_ DIR *d = NULL;
2933 int ret = 0;
2934
2935 assert(fd >= 0);
2936
2937 /* This returns the first error we run into, but nevertheless
2938 * tries to go on. This closes the passed fd. */
2939
2940 d = fdopendir(fd);
2941 if (!d) {
2942 safe_close(fd);
2943
2944 return errno == ENOENT ? 0 : -errno;
2945 }
2946
2947 for (;;) {
2948 struct dirent *de;
2949 bool is_dir, keep_around;
2950 struct stat st;
2951 int r;
2952
2953 errno = 0;
2954 de = readdir(d);
2955 if (!de) {
2956 if (errno != 0 && ret == 0)
2957 ret = -errno;
2958 return ret;
2959 }
2960
2961 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2962 continue;
2963
2964 if (de->d_type == DT_UNKNOWN ||
2965 honour_sticky ||
2966 (de->d_type == DT_DIR && root_dev)) {
2967 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2968 if (ret == 0 && errno != ENOENT)
2969 ret = -errno;
2970 continue;
2971 }
2972
2973 is_dir = S_ISDIR(st.st_mode);
2974 keep_around =
2975 honour_sticky &&
2976 (st.st_uid == 0 || st.st_uid == getuid()) &&
2977 (st.st_mode & S_ISVTX);
2978 } else {
2979 is_dir = de->d_type == DT_DIR;
2980 keep_around = false;
2981 }
2982
2983 if (is_dir) {
2984 int subdir_fd;
2985
2986 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2987 if (root_dev && st.st_dev != root_dev->st_dev)
2988 continue;
2989
2990 subdir_fd = openat(fd, de->d_name,
2991 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2992 if (subdir_fd < 0) {
2993 if (ret == 0 && errno != ENOENT)
2994 ret = -errno;
2995 continue;
2996 }
2997
2998 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2999 if (r < 0 && ret == 0)
3000 ret = r;
3001
3002 if (!keep_around)
3003 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3004 if (ret == 0 && errno != ENOENT)
3005 ret = -errno;
3006 }
3007
3008 } else if (!only_dirs && !keep_around) {
3009
3010 if (unlinkat(fd, de->d_name, 0) < 0) {
3011 if (ret == 0 && errno != ENOENT)
3012 ret = -errno;
3013 }
3014 }
3015 }
3016 }
3017
3018 _pure_ static int is_temporary_fs(struct statfs *s) {
3019 assert(s);
3020
3021 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
3022 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
3023 }
3024
3025 int is_fd_on_temporary_fs(int fd) {
3026 struct statfs s;
3027
3028 if (fstatfs(fd, &s) < 0)
3029 return -errno;
3030
3031 return is_temporary_fs(&s);
3032 }
3033
3034 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3035 struct statfs s;
3036
3037 assert(fd >= 0);
3038
3039 if (fstatfs(fd, &s) < 0) {
3040 safe_close(fd);
3041 return -errno;
3042 }
3043
3044 /* We refuse to clean disk file systems with this call. This
3045 * is extra paranoia just to be sure we never ever remove
3046 * non-state data */
3047 if (!is_temporary_fs(&s)) {
3048 log_error("Attempted to remove disk file system, and we can't allow that.");
3049 safe_close(fd);
3050 return -EPERM;
3051 }
3052
3053 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3054 }
3055
3056 static int file_is_priv_sticky(const char *p) {
3057 struct stat st;
3058
3059 assert(p);
3060
3061 if (lstat(p, &st) < 0)
3062 return -errno;
3063
3064 return
3065 (st.st_uid == 0 || st.st_uid == getuid()) &&
3066 (st.st_mode & S_ISVTX);
3067 }
3068
3069 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3070 int fd, r;
3071 struct statfs s;
3072
3073 assert(path);
3074
3075 /* We refuse to clean the root file system with this
3076 * call. This is extra paranoia to never cause a really
3077 * seriously broken system. */
3078 if (path_equal(path, "/")) {
3079 log_error("Attempted to remove entire root file system, and we can't allow that.");
3080 return -EPERM;
3081 }
3082
3083 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3084 if (fd < 0) {
3085
3086 if (errno != ENOTDIR && errno != ELOOP)
3087 return -errno;
3088
3089 if (!dangerous) {
3090 if (statfs(path, &s) < 0)
3091 return -errno;
3092
3093 if (!is_temporary_fs(&s)) {
3094 log_error("Attempted to remove disk file system, and we can't allow that.");
3095 return -EPERM;
3096 }
3097 }
3098
3099 if (delete_root && !only_dirs)
3100 if (unlink(path) < 0 && errno != ENOENT)
3101 return -errno;
3102
3103 return 0;
3104 }
3105
3106 if (!dangerous) {
3107 if (fstatfs(fd, &s) < 0) {
3108 safe_close(fd);
3109 return -errno;
3110 }
3111
3112 if (!is_temporary_fs(&s)) {
3113 log_error("Attempted to remove disk file system, and we can't allow that.");
3114 safe_close(fd);
3115 return -EPERM;
3116 }
3117 }
3118
3119 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3120 if (delete_root) {
3121
3122 if (honour_sticky && file_is_priv_sticky(path) > 0)
3123 return r;
3124
3125 if (rmdir(path) < 0 && errno != ENOENT) {
3126 if (r == 0)
3127 r = -errno;
3128 }
3129 }
3130
3131 return r;
3132 }
3133
3134 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3135 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3136 }
3137
3138 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3139 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3140 }
3141
3142 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3143 assert(path);
3144
3145 /* Under the assumption that we are running privileged we
3146 * first change the access mode and only then hand out
3147 * ownership to avoid a window where access is too open. */
3148
3149 if (mode != MODE_INVALID)
3150 if (chmod(path, mode) < 0)
3151 return -errno;
3152
3153 if (uid != UID_INVALID || gid != GID_INVALID)
3154 if (chown(path, uid, gid) < 0)
3155 return -errno;
3156
3157 return 0;
3158 }
3159
3160 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3161 assert(fd >= 0);
3162
3163 /* Under the assumption that we are running privileged we
3164 * first change the access mode and only then hand out
3165 * ownership to avoid a window where access is too open. */
3166
3167 if (mode != MODE_INVALID)
3168 if (fchmod(fd, mode) < 0)
3169 return -errno;
3170
3171 if (uid != UID_INVALID || gid != GID_INVALID)
3172 if (fchown(fd, uid, gid) < 0)
3173 return -errno;
3174
3175 return 0;
3176 }
3177
3178 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3179 cpu_set_t *r;
3180 unsigned n = 1024;
3181
3182 /* Allocates the cpuset in the right size */
3183
3184 for (;;) {
3185 if (!(r = CPU_ALLOC(n)))
3186 return NULL;
3187
3188 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3189 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3190
3191 if (ncpus)
3192 *ncpus = n;
3193
3194 return r;
3195 }
3196
3197 CPU_FREE(r);
3198
3199 if (errno != EINVAL)
3200 return NULL;
3201
3202 n *= 2;
3203 }
3204 }
3205
3206 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
3207 static const char status_indent[] = " "; /* "[" STATUS "] " */
3208 _cleanup_free_ char *s = NULL;
3209 _cleanup_close_ int fd = -1;
3210 struct iovec iovec[6] = {};
3211 int n = 0;
3212 static bool prev_ephemeral;
3213
3214 assert(format);
3215
3216 /* This is independent of logging, as status messages are
3217 * optional and go exclusively to the console. */
3218
3219 if (vasprintf(&s, format, ap) < 0)
3220 return log_oom();
3221
3222 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3223 if (fd < 0)
3224 return fd;
3225
3226 if (ellipse) {
3227 char *e;
3228 size_t emax, sl;
3229 int c;
3230
3231 c = fd_columns(fd);
3232 if (c <= 0)
3233 c = 80;
3234
3235 sl = status ? sizeof(status_indent)-1 : 0;
3236
3237 emax = c - sl - 1;
3238 if (emax < 3)
3239 emax = 3;
3240
3241 e = ellipsize(s, emax, 50);
3242 if (e) {
3243 free(s);
3244 s = e;
3245 }
3246 }
3247
3248 if (prev_ephemeral)
3249 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
3250 prev_ephemeral = ephemeral;
3251
3252 if (status) {
3253 if (!isempty(status)) {
3254 IOVEC_SET_STRING(iovec[n++], "[");
3255 IOVEC_SET_STRING(iovec[n++], status);
3256 IOVEC_SET_STRING(iovec[n++], "] ");
3257 } else
3258 IOVEC_SET_STRING(iovec[n++], status_indent);
3259 }
3260
3261 IOVEC_SET_STRING(iovec[n++], s);
3262 if (!ephemeral)
3263 IOVEC_SET_STRING(iovec[n++], "\n");
3264
3265 if (writev(fd, iovec, n) < 0)
3266 return -errno;
3267
3268 return 0;
3269 }
3270
3271 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
3272 va_list ap;
3273 int r;
3274
3275 assert(format);
3276
3277 va_start(ap, format);
3278 r = status_vprintf(status, ellipse, ephemeral, format, ap);
3279 va_end(ap);
3280
3281 return r;
3282 }
3283
3284 char *replace_env(const char *format, char **env) {
3285 enum {
3286 WORD,
3287 CURLY,
3288 VARIABLE
3289 } state = WORD;
3290
3291 const char *e, *word = format;
3292 char *r = NULL, *k;
3293
3294 assert(format);
3295
3296 for (e = format; *e; e ++) {
3297
3298 switch (state) {
3299
3300 case WORD:
3301 if (*e == '$')
3302 state = CURLY;
3303 break;
3304
3305 case CURLY:
3306 if (*e == '{') {
3307 k = strnappend(r, word, e-word-1);
3308 if (!k)
3309 goto fail;
3310
3311 free(r);
3312 r = k;
3313
3314 word = e-1;
3315 state = VARIABLE;
3316
3317 } else if (*e == '$') {
3318 k = strnappend(r, word, e-word);
3319 if (!k)
3320 goto fail;
3321
3322 free(r);
3323 r = k;
3324
3325 word = e+1;
3326 state = WORD;
3327 } else
3328 state = WORD;
3329 break;
3330
3331 case VARIABLE:
3332 if (*e == '}') {
3333 const char *t;
3334
3335 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3336
3337 k = strappend(r, t);
3338 if (!k)
3339 goto fail;
3340
3341 free(r);
3342 r = k;
3343
3344 word = e+1;
3345 state = WORD;
3346 }
3347 break;
3348 }
3349 }
3350
3351 k = strnappend(r, word, e-word);
3352 if (!k)
3353 goto fail;
3354
3355 free(r);
3356 return k;
3357
3358 fail:
3359 free(r);
3360 return NULL;
3361 }
3362
3363 char **replace_env_argv(char **argv, char **env) {
3364 char **ret, **i;
3365 unsigned k = 0, l = 0;
3366
3367 l = strv_length(argv);
3368
3369 ret = new(char*, l+1);
3370 if (!ret)
3371 return NULL;
3372
3373 STRV_FOREACH(i, argv) {
3374
3375 /* If $FOO appears as single word, replace it by the split up variable */
3376 if ((*i)[0] == '$' && (*i)[1] != '{') {
3377 char *e;
3378 char **w, **m;
3379 unsigned q;
3380
3381 e = strv_env_get(env, *i+1);
3382 if (e) {
3383 int r;
3384
3385 r = strv_split_quoted(&m, e, true);
3386 if (r < 0) {
3387 ret[k] = NULL;
3388 strv_free(ret);
3389 return NULL;
3390 }
3391 } else
3392 m = NULL;
3393
3394 q = strv_length(m);
3395 l = l + q - 1;
3396
3397 w = realloc(ret, sizeof(char*) * (l+1));
3398 if (!w) {
3399 ret[k] = NULL;
3400 strv_free(ret);
3401 strv_free(m);
3402 return NULL;
3403 }
3404
3405 ret = w;
3406 if (m) {
3407 memcpy(ret + k, m, q * sizeof(char*));
3408 free(m);
3409 }
3410
3411 k += q;
3412 continue;
3413 }
3414
3415 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3416 ret[k] = replace_env(*i, env);
3417 if (!ret[k]) {
3418 strv_free(ret);
3419 return NULL;
3420 }
3421 k++;
3422 }
3423
3424 ret[k] = NULL;
3425 return ret;
3426 }
3427
3428 int fd_columns(int fd) {
3429 struct winsize ws = {};
3430
3431 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3432 return -errno;
3433
3434 if (ws.ws_col <= 0)
3435 return -EIO;
3436
3437 return ws.ws_col;
3438 }
3439
3440 unsigned columns(void) {
3441 const char *e;
3442 int c;
3443
3444 if (_likely_(cached_columns > 0))
3445 return cached_columns;
3446
3447 c = 0;
3448 e = getenv("COLUMNS");
3449 if (e)
3450 (void) safe_atoi(e, &c);
3451
3452 if (c <= 0)
3453 c = fd_columns(STDOUT_FILENO);
3454
3455 if (c <= 0)
3456 c = 80;
3457
3458 cached_columns = c;
3459 return c;
3460 }
3461
3462 int fd_lines(int fd) {
3463 struct winsize ws = {};
3464
3465 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3466 return -errno;
3467
3468 if (ws.ws_row <= 0)
3469 return -EIO;
3470
3471 return ws.ws_row;
3472 }
3473
3474 unsigned lines(void) {
3475 const char *e;
3476 unsigned l;
3477
3478 if (_likely_(cached_lines > 0))
3479 return cached_lines;
3480
3481 l = 0;
3482 e = getenv("LINES");
3483 if (e)
3484 (void) safe_atou(e, &l);
3485
3486 if (l <= 0)
3487 l = fd_lines(STDOUT_FILENO);
3488
3489 if (l <= 0)
3490 l = 24;
3491
3492 cached_lines = l;
3493 return cached_lines;
3494 }
3495
3496 /* intended to be used as a SIGWINCH sighandler */
3497 void columns_lines_cache_reset(int signum) {
3498 cached_columns = 0;
3499 cached_lines = 0;
3500 }
3501
3502 bool on_tty(void) {
3503 static int cached_on_tty = -1;
3504
3505 if (_unlikely_(cached_on_tty < 0))
3506 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3507
3508 return cached_on_tty;
3509 }
3510
3511 int files_same(const char *filea, const char *fileb) {
3512 struct stat a, b;
3513
3514 if (stat(filea, &a) < 0)
3515 return -errno;
3516
3517 if (stat(fileb, &b) < 0)
3518 return -errno;
3519
3520 return a.st_dev == b.st_dev &&
3521 a.st_ino == b.st_ino;
3522 }
3523
3524 int running_in_chroot(void) {
3525 int ret;
3526
3527 ret = files_same("/proc/1/root", "/");
3528 if (ret < 0)
3529 return ret;
3530
3531 return ret == 0;
3532 }
3533
3534 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3535 size_t x;
3536 char *r;
3537
3538 assert(s);
3539 assert(percent <= 100);
3540 assert(new_length >= 3);
3541
3542 if (old_length <= 3 || old_length <= new_length)
3543 return strndup(s, old_length);
3544
3545 r = new0(char, new_length+1);
3546 if (!r)
3547 return NULL;
3548
3549 x = (new_length * percent) / 100;
3550
3551 if (x > new_length - 3)
3552 x = new_length - 3;
3553
3554 memcpy(r, s, x);
3555 r[x] = '.';
3556 r[x+1] = '.';
3557 r[x+2] = '.';
3558 memcpy(r + x + 3,
3559 s + old_length - (new_length - x - 3),
3560 new_length - x - 3);
3561
3562 return r;
3563 }
3564
3565 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3566 size_t x;
3567 char *e;
3568 const char *i, *j;
3569 unsigned k, len, len2;
3570
3571 assert(s);
3572 assert(percent <= 100);
3573 assert(new_length >= 3);
3574
3575 /* if no multibyte characters use ascii_ellipsize_mem for speed */
3576 if (ascii_is_valid(s))
3577 return ascii_ellipsize_mem(s, old_length, new_length, percent);
3578
3579 if (old_length <= 3 || old_length <= new_length)
3580 return strndup(s, old_length);
3581
3582 x = (new_length * percent) / 100;
3583
3584 if (x > new_length - 3)
3585 x = new_length - 3;
3586
3587 k = 0;
3588 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
3589 int c;
3590
3591 c = utf8_encoded_to_unichar(i);
3592 if (c < 0)
3593 return NULL;
3594 k += unichar_iswide(c) ? 2 : 1;
3595 }
3596
3597 if (k > x) /* last character was wide and went over quota */
3598 x ++;
3599
3600 for (j = s + old_length; k < new_length && j > i; ) {
3601 int c;
3602
3603 j = utf8_prev_char(j);
3604 c = utf8_encoded_to_unichar(j);
3605 if (c < 0)
3606 return NULL;
3607 k += unichar_iswide(c) ? 2 : 1;
3608 }
3609 assert(i <= j);
3610
3611 /* we don't actually need to ellipsize */
3612 if (i == j)
3613 return memdup(s, old_length + 1);
3614
3615 /* make space for ellipsis */
3616 j = utf8_next_char(j);
3617
3618 len = i - s;
3619 len2 = s + old_length - j;
3620 e = new(char, len + 3 + len2 + 1);
3621 if (!e)
3622 return NULL;
3623
3624 /*
3625 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
3626 old_length, new_length, x, len, len2, k);
3627 */
3628
3629 memcpy(e, s, len);
3630 e[len] = 0xe2; /* tri-dot ellipsis: … */
3631 e[len + 1] = 0x80;
3632 e[len + 2] = 0xa6;
3633
3634 memcpy(e + len + 3, j, len2 + 1);
3635
3636 return e;
3637 }
3638
3639 char *ellipsize(const char *s, size_t length, unsigned percent) {
3640 return ellipsize_mem(s, strlen(s), length, percent);
3641 }
3642
3643 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
3644 _cleanup_close_ int fd;
3645 int r;
3646
3647 assert(path);
3648
3649 if (parents)
3650 mkdir_parents(path, 0755);
3651
3652 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
3653 if (fd < 0)
3654 return -errno;
3655
3656 if (mode > 0) {
3657 r = fchmod(fd, mode);
3658 if (r < 0)
3659 return -errno;
3660 }
3661
3662 if (uid != UID_INVALID || gid != GID_INVALID) {
3663 r = fchown(fd, uid, gid);
3664 if (r < 0)
3665 return -errno;
3666 }
3667
3668 if (stamp != USEC_INFINITY) {
3669 struct timespec ts[2];
3670
3671 timespec_store(&ts[0], stamp);
3672 ts[1] = ts[0];
3673 r = futimens(fd, ts);
3674 } else
3675 r = futimens(fd, NULL);
3676 if (r < 0)
3677 return -errno;
3678
3679 return 0;
3680 }
3681
3682 int touch(const char *path) {
3683 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
3684 }
3685
3686 char *unquote(const char *s, const char* quotes) {
3687 size_t l;
3688 assert(s);
3689
3690 /* This is rather stupid, simply removes the heading and
3691 * trailing quotes if there is one. Doesn't care about
3692 * escaping or anything. We should make this smarter one
3693 * day... */
3694
3695 l = strlen(s);
3696 if (l < 2)
3697 return strdup(s);
3698
3699 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3700 return strndup(s+1, l-2);
3701
3702 return strdup(s);
3703 }
3704
3705 char *normalize_env_assignment(const char *s) {
3706 _cleanup_free_ char *value = NULL;
3707 const char *eq;
3708 char *p, *name;
3709
3710 eq = strchr(s, '=');
3711 if (!eq) {
3712 char *r, *t;
3713
3714 r = strdup(s);
3715 if (!r)
3716 return NULL;
3717
3718 t = strstrip(r);
3719 if (t != r)
3720 memmove(r, t, strlen(t) + 1);
3721
3722 return r;
3723 }
3724
3725 name = strndupa(s, eq - s);
3726 p = strdupa(eq + 1);
3727
3728 value = unquote(strstrip(p), QUOTES);
3729 if (!value)
3730 return NULL;
3731
3732 return strjoin(strstrip(name), "=", value, NULL);
3733 }
3734
3735 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3736 siginfo_t dummy;
3737
3738 assert(pid >= 1);
3739
3740 if (!status)
3741 status = &dummy;
3742
3743 for (;;) {
3744 zero(*status);
3745
3746 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3747
3748 if (errno == EINTR)
3749 continue;
3750
3751 return -errno;
3752 }
3753
3754 return 0;
3755 }
3756 }
3757
3758 /*
3759 * Return values:
3760 * < 0 : wait_for_terminate() failed to get the state of the
3761 * process, the process was terminated by a signal, or
3762 * failed for an unknown reason.
3763 * >=0 : The process terminated normally, and its exit code is
3764 * returned.
3765 *
3766 * That is, success is indicated by a return value of zero, and an
3767 * error is indicated by a non-zero value.
3768 *
3769 * A warning is emitted if the process terminates abnormally,
3770 * and also if it returns non-zero unless check_exit_code is true.
3771 */
3772 int wait_for_terminate_and_warn(const char *name, pid_t pid, bool check_exit_code) {
3773 int r;
3774 siginfo_t status;
3775
3776 assert(name);
3777 assert(pid > 1);
3778
3779 r = wait_for_terminate(pid, &status);
3780 if (r < 0)
3781 return log_warning_errno(r, "Failed to wait for %s: %m", name);
3782
3783 if (status.si_code == CLD_EXITED) {
3784 if (status.si_status != 0)
3785 log_full(check_exit_code ? LOG_WARNING : LOG_DEBUG,
3786 "%s failed with error code %i.", name, status.si_status);
3787 else
3788 log_debug("%s succeeded.", name);
3789
3790 return status.si_status;
3791 } else if (status.si_code == CLD_KILLED ||
3792 status.si_code == CLD_DUMPED) {
3793
3794 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3795 return -EPROTO;
3796 }
3797
3798 log_warning("%s failed due to unknown reason.", name);
3799 return -EPROTO;
3800 }
3801
3802 noreturn void freeze(void) {
3803
3804 /* Make sure nobody waits for us on a socket anymore */
3805 close_all_fds(NULL, 0);
3806
3807 sync();
3808
3809 for (;;)
3810 pause();
3811 }
3812
3813 bool null_or_empty(struct stat *st) {
3814 assert(st);
3815
3816 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3817 return true;
3818
3819 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3820 return true;
3821
3822 return false;
3823 }
3824
3825 int null_or_empty_path(const char *fn) {
3826 struct stat st;
3827
3828 assert(fn);
3829
3830 if (stat(fn, &st) < 0)
3831 return -errno;
3832
3833 return null_or_empty(&st);
3834 }
3835
3836 int null_or_empty_fd(int fd) {
3837 struct stat st;
3838
3839 assert(fd >= 0);
3840
3841 if (fstat(fd, &st) < 0)
3842 return -errno;
3843
3844 return null_or_empty(&st);
3845 }
3846
3847 DIR *xopendirat(int fd, const char *name, int flags) {
3848 int nfd;
3849 DIR *d;
3850
3851 assert(!(flags & O_CREAT));
3852
3853 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
3854 if (nfd < 0)
3855 return NULL;
3856
3857 d = fdopendir(nfd);
3858 if (!d) {
3859 safe_close(nfd);
3860 return NULL;
3861 }
3862
3863 return d;
3864 }
3865
3866 int signal_from_string_try_harder(const char *s) {
3867 int signo;
3868 assert(s);
3869
3870 signo = signal_from_string(s);
3871 if (signo <= 0)
3872 if (startswith(s, "SIG"))
3873 return signal_from_string(s+3);
3874
3875 return signo;
3876 }
3877
3878 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3879 _cleanup_free_ char *t = NULL, *u = NULL;
3880 size_t enc_len;
3881
3882 u = unquote(tagvalue, "\"\'");
3883 if (!u)
3884 return NULL;
3885
3886 enc_len = strlen(u) * 4 + 1;
3887 t = new(char, enc_len);
3888 if (!t)
3889 return NULL;
3890
3891 if (encode_devnode_name(u, t, enc_len) < 0)
3892 return NULL;
3893
3894 return strjoin("/dev/disk/by-", by, "/", t, NULL);
3895 }
3896
3897 char *fstab_node_to_udev_node(const char *p) {
3898 assert(p);
3899
3900 if (startswith(p, "LABEL="))
3901 return tag_to_udev_node(p+6, "label");
3902
3903 if (startswith(p, "UUID="))
3904 return tag_to_udev_node(p+5, "uuid");
3905
3906 if (startswith(p, "PARTUUID="))
3907 return tag_to_udev_node(p+9, "partuuid");
3908
3909 if (startswith(p, "PARTLABEL="))
3910 return tag_to_udev_node(p+10, "partlabel");
3911
3912 return strdup(p);
3913 }
3914
3915 bool tty_is_vc(const char *tty) {
3916 assert(tty);
3917
3918 return vtnr_from_tty(tty) >= 0;
3919 }
3920
3921 bool tty_is_console(const char *tty) {
3922 assert(tty);
3923
3924 if (startswith(tty, "/dev/"))
3925 tty += 5;
3926
3927 return streq(tty, "console");
3928 }
3929
3930 int vtnr_from_tty(const char *tty) {
3931 int i, r;
3932
3933 assert(tty);
3934
3935 if (startswith(tty, "/dev/"))
3936 tty += 5;
3937
3938 if (!startswith(tty, "tty") )
3939 return -EINVAL;
3940
3941 if (tty[3] < '0' || tty[3] > '9')
3942 return -EINVAL;
3943
3944 r = safe_atoi(tty+3, &i);
3945 if (r < 0)
3946 return r;
3947
3948 if (i < 0 || i > 63)
3949 return -EINVAL;
3950
3951 return i;
3952 }
3953
3954 char *resolve_dev_console(char **active) {
3955 char *tty;
3956
3957 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3958 * (i.e. not read-only-mounted which is a sign for container setups) */
3959
3960 if (path_is_read_only_fs("/sys") > 0)
3961 return NULL;
3962
3963 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3964 return NULL;
3965
3966 /* If multiple log outputs are configured the last one is what
3967 * /dev/console points to */
3968 tty = strrchr(*active, ' ');
3969 if (tty)
3970 tty++;
3971 else
3972 tty = *active;
3973
3974 if (streq(tty, "tty0")) {
3975 char *tmp;
3976
3977 /* Get the active VC (e.g. tty1) */
3978 if (read_one_line_file("/sys/class/tty/tty0/active", &tmp) >= 0) {
3979 free(*active);
3980 tty = *active = tmp;
3981 }
3982 }
3983
3984 return tty;
3985 }
3986
3987 bool tty_is_vc_resolve(const char *tty) {
3988 _cleanup_free_ char *active = NULL;
3989
3990 assert(tty);
3991
3992 if (startswith(tty, "/dev/"))
3993 tty += 5;
3994
3995 if (streq(tty, "console")) {
3996 tty = resolve_dev_console(&active);
3997 if (!tty)
3998 return false;
3999 }
4000
4001 return tty_is_vc(tty);
4002 }
4003
4004 const char *default_term_for_tty(const char *tty) {
4005 assert(tty);
4006
4007 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4008 }
4009
4010 bool dirent_is_file(const struct dirent *de) {
4011 assert(de);
4012
4013 if (hidden_file(de->d_name))
4014 return false;
4015
4016 if (de->d_type != DT_REG &&
4017 de->d_type != DT_LNK &&
4018 de->d_type != DT_UNKNOWN)
4019 return false;
4020
4021 return true;
4022 }
4023
4024 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4025 assert(de);
4026
4027 if (de->d_type != DT_REG &&
4028 de->d_type != DT_LNK &&
4029 de->d_type != DT_UNKNOWN)
4030 return false;
4031
4032 if (hidden_file_allow_backup(de->d_name))
4033 return false;
4034
4035 return endswith(de->d_name, suffix);
4036 }
4037
4038 void execute_directory(const char *directory, DIR *d, usec_t timeout, char *argv[]) {
4039 pid_t executor_pid;
4040 int r;
4041
4042 assert(directory);
4043
4044 /* Executes all binaries in a directory in parallel and waits
4045 * for them to finish. Optionally a timeout is applied. */
4046
4047 executor_pid = fork();
4048 if (executor_pid < 0) {
4049 log_error_errno(errno, "Failed to fork: %m");
4050 return;
4051
4052 } else if (executor_pid == 0) {
4053 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
4054 _cleanup_closedir_ DIR *_d = NULL;
4055 struct dirent *de;
4056
4057 /* We fork this all off from a child process so that
4058 * we can somewhat cleanly make use of SIGALRM to set
4059 * a time limit */
4060
4061 reset_all_signal_handlers();
4062 reset_signal_mask();
4063
4064 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
4065
4066 if (!d) {
4067 d = _d = opendir(directory);
4068 if (!d) {
4069 if (errno == ENOENT)
4070 _exit(EXIT_SUCCESS);
4071
4072 log_error_errno(errno, "Failed to enumerate directory %s: %m", directory);
4073 _exit(EXIT_FAILURE);
4074 }
4075 }
4076
4077 pids = hashmap_new(NULL);
4078 if (!pids) {
4079 log_oom();
4080 _exit(EXIT_FAILURE);
4081 }
4082
4083 FOREACH_DIRENT(de, d, break) {
4084 _cleanup_free_ char *path = NULL;
4085 pid_t pid;
4086
4087 if (!dirent_is_file(de))
4088 continue;
4089
4090 path = strjoin(directory, "/", de->d_name, NULL);
4091 if (!path) {
4092 log_oom();
4093 _exit(EXIT_FAILURE);
4094 }
4095
4096 pid = fork();
4097 if (pid < 0) {
4098 log_error_errno(errno, "Failed to fork: %m");
4099 continue;
4100 } else if (pid == 0) {
4101 char *_argv[2];
4102
4103 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
4104
4105 if (!argv) {
4106 _argv[0] = path;
4107 _argv[1] = NULL;
4108 argv = _argv;
4109 } else
4110 argv[0] = path;
4111
4112 execv(path, argv);
4113 log_error_errno(errno, "Failed to execute %s: %m", path);
4114 _exit(EXIT_FAILURE);
4115 }
4116
4117 log_debug("Spawned %s as " PID_FMT ".", path, pid);
4118
4119 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
4120 if (r < 0) {
4121 log_oom();
4122 _exit(EXIT_FAILURE);
4123 }
4124
4125 path = NULL;
4126 }
4127
4128 /* Abort execution of this process after the
4129 * timout. We simply rely on SIGALRM as default action
4130 * terminating the process, and turn on alarm(). */
4131
4132 if (timeout != USEC_INFINITY)
4133 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
4134
4135 while (!hashmap_isempty(pids)) {
4136 _cleanup_free_ char *path = NULL;
4137 pid_t pid;
4138
4139 pid = PTR_TO_UINT(hashmap_first_key(pids));
4140 assert(pid > 0);
4141
4142 path = hashmap_remove(pids, UINT_TO_PTR(pid));
4143 assert(path);
4144
4145 wait_for_terminate_and_warn(path, pid, true);
4146 }
4147
4148 _exit(EXIT_SUCCESS);
4149 }
4150
4151 wait_for_terminate_and_warn(directory, executor_pid, true);
4152 }
4153
4154 int kill_and_sigcont(pid_t pid, int sig) {
4155 int r;
4156
4157 r = kill(pid, sig) < 0 ? -errno : 0;
4158
4159 if (r >= 0)
4160 kill(pid, SIGCONT);
4161
4162 return r;
4163 }
4164
4165 bool nulstr_contains(const char*nulstr, const char *needle) {
4166 const char *i;
4167
4168 if (!nulstr)
4169 return false;
4170
4171 NULSTR_FOREACH(i, nulstr)
4172 if (streq(i, needle))
4173 return true;
4174
4175 return false;
4176 }
4177
4178 bool plymouth_running(void) {
4179 return access("/run/plymouth/pid", F_OK) >= 0;
4180 }
4181
4182 char* strshorten(char *s, size_t l) {
4183 assert(s);
4184
4185 if (l < strlen(s))
4186 s[l] = 0;
4187
4188 return s;
4189 }
4190
4191 static bool hostname_valid_char(char c) {
4192 return
4193 (c >= 'a' && c <= 'z') ||
4194 (c >= 'A' && c <= 'Z') ||
4195 (c >= '0' && c <= '9') ||
4196 c == '-' ||
4197 c == '_' ||
4198 c == '.';
4199 }
4200
4201 bool hostname_is_valid(const char *s) {
4202 const char *p;
4203 bool dot;
4204
4205 if (isempty(s))
4206 return false;
4207
4208 for (p = s, dot = true; *p; p++) {
4209 if (*p == '.') {
4210 if (dot)
4211 return false;
4212
4213 dot = true;
4214 } else {
4215 if (!hostname_valid_char(*p))
4216 return false;
4217
4218 dot = false;
4219 }
4220 }
4221
4222 if (dot)
4223 return false;
4224
4225 if (p-s > HOST_NAME_MAX)
4226 return false;
4227
4228 return true;
4229 }
4230
4231 char* hostname_cleanup(char *s, bool lowercase) {
4232 char *p, *d;
4233 bool dot;
4234
4235 for (p = s, d = s, dot = true; *p; p++) {
4236 if (*p == '.') {
4237 if (dot)
4238 continue;
4239
4240 *(d++) = '.';
4241 dot = true;
4242 } else if (hostname_valid_char(*p)) {
4243 *(d++) = lowercase ? tolower(*p) : *p;
4244 dot = false;
4245 }
4246
4247 }
4248
4249 if (dot && d > s)
4250 d[-1] = 0;
4251 else
4252 *d = 0;
4253
4254 strshorten(s, HOST_NAME_MAX);
4255
4256 return s;
4257 }
4258
4259 bool machine_name_is_valid(const char *s) {
4260
4261 if (!hostname_is_valid(s))
4262 return false;
4263
4264 /* Machine names should be useful hostnames, but also be
4265 * useful in unit names, hence we enforce a stricter length
4266 * limitation. */
4267
4268 if (strlen(s) > 64)
4269 return false;
4270
4271 return true;
4272 }
4273
4274 bool image_name_is_valid(const char *s) {
4275 if (!filename_is_valid(s))
4276 return false;
4277
4278 if (string_has_cc(s, NULL))
4279 return false;
4280
4281 if (!utf8_is_valid(s))
4282 return false;
4283
4284 /* Temporary files for atomically creating new files */
4285 if (startswith(s, ".#"))
4286 return false;
4287
4288 return true;
4289 }
4290
4291 int pipe_eof(int fd) {
4292 struct pollfd pollfd = {
4293 .fd = fd,
4294 .events = POLLIN|POLLHUP,
4295 };
4296
4297 int r;
4298
4299 r = poll(&pollfd, 1, 0);
4300 if (r < 0)
4301 return -errno;
4302
4303 if (r == 0)
4304 return 0;
4305
4306 return pollfd.revents & POLLHUP;
4307 }
4308
4309 int fd_wait_for_event(int fd, int event, usec_t t) {
4310
4311 struct pollfd pollfd = {
4312 .fd = fd,
4313 .events = event,
4314 };
4315
4316 struct timespec ts;
4317 int r;
4318
4319 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
4320 if (r < 0)
4321 return -errno;
4322
4323 if (r == 0)
4324 return 0;
4325
4326 return pollfd.revents;
4327 }
4328
4329 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4330 FILE *f;
4331 char *t;
4332 int r, fd;
4333
4334 assert(path);
4335 assert(_f);
4336 assert(_temp_path);
4337
4338 r = tempfn_xxxxxx(path, &t);
4339 if (r < 0)
4340 return r;
4341
4342 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
4343 if (fd < 0) {
4344 free(t);
4345 return -errno;
4346 }
4347
4348 f = fdopen(fd, "we");
4349 if (!f) {
4350 unlink(t);
4351 free(t);
4352 return -errno;
4353 }
4354
4355 *_f = f;
4356 *_temp_path = t;
4357
4358 return 0;
4359 }
4360
4361 int terminal_vhangup_fd(int fd) {
4362 assert(fd >= 0);
4363
4364 if (ioctl(fd, TIOCVHANGUP) < 0)
4365 return -errno;
4366
4367 return 0;
4368 }
4369
4370 int terminal_vhangup(const char *name) {
4371 _cleanup_close_ int fd;
4372
4373 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4374 if (fd < 0)
4375 return fd;
4376
4377 return terminal_vhangup_fd(fd);
4378 }
4379
4380 int vt_disallocate(const char *name) {
4381 int fd, r;
4382 unsigned u;
4383
4384 /* Deallocate the VT if possible. If not possible
4385 * (i.e. because it is the active one), at least clear it
4386 * entirely (including the scrollback buffer) */
4387
4388 if (!startswith(name, "/dev/"))
4389 return -EINVAL;
4390
4391 if (!tty_is_vc(name)) {
4392 /* So this is not a VT. I guess we cannot deallocate
4393 * it then. But let's at least clear the screen */
4394
4395 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4396 if (fd < 0)
4397 return fd;
4398
4399 loop_write(fd,
4400 "\033[r" /* clear scrolling region */
4401 "\033[H" /* move home */
4402 "\033[2J", /* clear screen */
4403 10, false);
4404 safe_close(fd);
4405
4406 return 0;
4407 }
4408
4409 if (!startswith(name, "/dev/tty"))
4410 return -EINVAL;
4411
4412 r = safe_atou(name+8, &u);
4413 if (r < 0)
4414 return r;
4415
4416 if (u <= 0)
4417 return -EINVAL;
4418
4419 /* Try to deallocate */
4420 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4421 if (fd < 0)
4422 return fd;
4423
4424 r = ioctl(fd, VT_DISALLOCATE, u);
4425 safe_close(fd);
4426
4427 if (r >= 0)
4428 return 0;
4429
4430 if (errno != EBUSY)
4431 return -errno;
4432
4433 /* Couldn't deallocate, so let's clear it fully with
4434 * scrollback */
4435 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4436 if (fd < 0)
4437 return fd;
4438
4439 loop_write(fd,
4440 "\033[r" /* clear scrolling region */
4441 "\033[H" /* move home */
4442 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4443 10, false);
4444 safe_close(fd);
4445
4446 return 0;
4447 }
4448
4449 int symlink_atomic(const char *from, const char *to) {
4450 _cleanup_free_ char *t = NULL;
4451 int r;
4452
4453 assert(from);
4454 assert(to);
4455
4456 r = tempfn_random(to, &t);
4457 if (r < 0)
4458 return r;
4459
4460 if (symlink(from, t) < 0)
4461 return -errno;
4462
4463 if (rename(t, to) < 0) {
4464 unlink_noerrno(t);
4465 return -errno;
4466 }
4467
4468 return 0;
4469 }
4470
4471 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
4472 _cleanup_free_ char *t = NULL;
4473 int r;
4474
4475 assert(path);
4476
4477 r = tempfn_random(path, &t);
4478 if (r < 0)
4479 return r;
4480
4481 if (mknod(t, mode, dev) < 0)
4482 return -errno;
4483
4484 if (rename(t, path) < 0) {
4485 unlink_noerrno(t);
4486 return -errno;
4487 }
4488
4489 return 0;
4490 }
4491
4492 int mkfifo_atomic(const char *path, mode_t mode) {
4493 _cleanup_free_ char *t = NULL;
4494 int r;
4495
4496 assert(path);
4497
4498 r = tempfn_random(path, &t);
4499 if (r < 0)
4500 return r;
4501
4502 if (mkfifo(t, mode) < 0)
4503 return -errno;
4504
4505 if (rename(t, path) < 0) {
4506 unlink_noerrno(t);
4507 return -errno;
4508 }
4509
4510 return 0;
4511 }
4512
4513 bool display_is_local(const char *display) {
4514 assert(display);
4515
4516 return
4517 display[0] == ':' &&
4518 display[1] >= '0' &&
4519 display[1] <= '9';
4520 }
4521
4522 int socket_from_display(const char *display, char **path) {
4523 size_t k;
4524 char *f, *c;
4525
4526 assert(display);
4527 assert(path);
4528
4529 if (!display_is_local(display))
4530 return -EINVAL;
4531
4532 k = strspn(display+1, "0123456789");
4533
4534 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
4535 if (!f)
4536 return -ENOMEM;
4537
4538 c = stpcpy(f, "/tmp/.X11-unix/X");
4539 memcpy(c, display+1, k);
4540 c[k] = 0;
4541
4542 *path = f;
4543
4544 return 0;
4545 }
4546
4547 int get_user_creds(
4548 const char **username,
4549 uid_t *uid, gid_t *gid,
4550 const char **home,
4551 const char **shell) {
4552
4553 struct passwd *p;
4554 uid_t u;
4555
4556 assert(username);
4557 assert(*username);
4558
4559 /* We enforce some special rules for uid=0: in order to avoid
4560 * NSS lookups for root we hardcode its data. */
4561
4562 if (streq(*username, "root") || streq(*username, "0")) {
4563 *username = "root";
4564
4565 if (uid)
4566 *uid = 0;
4567
4568 if (gid)
4569 *gid = 0;
4570
4571 if (home)
4572 *home = "/root";
4573
4574 if (shell)
4575 *shell = "/bin/sh";
4576
4577 return 0;
4578 }
4579
4580 if (parse_uid(*username, &u) >= 0) {
4581 errno = 0;
4582 p = getpwuid(u);
4583
4584 /* If there are multiple users with the same id, make
4585 * sure to leave $USER to the configured value instead
4586 * of the first occurrence in the database. However if
4587 * the uid was configured by a numeric uid, then let's
4588 * pick the real username from /etc/passwd. */
4589 if (p)
4590 *username = p->pw_name;
4591 } else {
4592 errno = 0;
4593 p = getpwnam(*username);
4594 }
4595
4596 if (!p)
4597 return errno > 0 ? -errno : -ESRCH;
4598
4599 if (uid)
4600 *uid = p->pw_uid;
4601
4602 if (gid)
4603 *gid = p->pw_gid;
4604
4605 if (home)
4606 *home = p->pw_dir;
4607
4608 if (shell)
4609 *shell = p->pw_shell;
4610
4611 return 0;
4612 }
4613
4614 char* uid_to_name(uid_t uid) {
4615 struct passwd *p;
4616 char *r;
4617
4618 if (uid == 0)
4619 return strdup("root");
4620
4621 p = getpwuid(uid);
4622 if (p)
4623 return strdup(p->pw_name);
4624
4625 if (asprintf(&r, UID_FMT, uid) < 0)
4626 return NULL;
4627
4628 return r;
4629 }
4630
4631 char* gid_to_name(gid_t gid) {
4632 struct group *p;
4633 char *r;
4634
4635 if (gid == 0)
4636 return strdup("root");
4637
4638 p = getgrgid(gid);
4639 if (p)
4640 return strdup(p->gr_name);
4641
4642 if (asprintf(&r, GID_FMT, gid) < 0)
4643 return NULL;
4644
4645 return r;
4646 }
4647
4648 int get_group_creds(const char **groupname, gid_t *gid) {
4649 struct group *g;
4650 gid_t id;
4651
4652 assert(groupname);
4653
4654 /* We enforce some special rules for gid=0: in order to avoid
4655 * NSS lookups for root we hardcode its data. */
4656
4657 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4658 *groupname = "root";
4659
4660 if (gid)
4661 *gid = 0;
4662
4663 return 0;
4664 }
4665
4666 if (parse_gid(*groupname, &id) >= 0) {
4667 errno = 0;
4668 g = getgrgid(id);
4669
4670 if (g)
4671 *groupname = g->gr_name;
4672 } else {
4673 errno = 0;
4674 g = getgrnam(*groupname);
4675 }
4676
4677 if (!g)
4678 return errno > 0 ? -errno : -ESRCH;
4679
4680 if (gid)
4681 *gid = g->gr_gid;
4682
4683 return 0;
4684 }
4685
4686 int in_gid(gid_t gid) {
4687 gid_t *gids;
4688 int ngroups_max, r, i;
4689
4690 if (getgid() == gid)
4691 return 1;
4692
4693 if (getegid() == gid)
4694 return 1;
4695
4696 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4697 assert(ngroups_max > 0);
4698
4699 gids = alloca(sizeof(gid_t) * ngroups_max);
4700
4701 r = getgroups(ngroups_max, gids);
4702 if (r < 0)
4703 return -errno;
4704
4705 for (i = 0; i < r; i++)
4706 if (gids[i] == gid)
4707 return 1;
4708
4709 return 0;
4710 }
4711
4712 int in_group(const char *name) {
4713 int r;
4714 gid_t gid;
4715
4716 r = get_group_creds(&name, &gid);
4717 if (r < 0)
4718 return r;
4719
4720 return in_gid(gid);
4721 }
4722
4723 int glob_exists(const char *path) {
4724 _cleanup_globfree_ glob_t g = {};
4725 int k;
4726
4727 assert(path);
4728
4729 errno = 0;
4730 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4731
4732 if (k == GLOB_NOMATCH)
4733 return 0;
4734 else if (k == GLOB_NOSPACE)
4735 return -ENOMEM;
4736 else if (k == 0)
4737 return !strv_isempty(g.gl_pathv);
4738 else
4739 return errno ? -errno : -EIO;
4740 }
4741
4742 int glob_extend(char ***strv, const char *path) {
4743 _cleanup_globfree_ glob_t g = {};
4744 int k;
4745 char **p;
4746
4747 errno = 0;
4748 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4749
4750 if (k == GLOB_NOMATCH)
4751 return -ENOENT;
4752 else if (k == GLOB_NOSPACE)
4753 return -ENOMEM;
4754 else if (k != 0 || strv_isempty(g.gl_pathv))
4755 return errno ? -errno : -EIO;
4756
4757 STRV_FOREACH(p, g.gl_pathv) {
4758 k = strv_extend(strv, *p);
4759 if (k < 0)
4760 break;
4761 }
4762
4763 return k;
4764 }
4765
4766 int dirent_ensure_type(DIR *d, struct dirent *de) {
4767 struct stat st;
4768
4769 assert(d);
4770 assert(de);
4771
4772 if (de->d_type != DT_UNKNOWN)
4773 return 0;
4774
4775 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4776 return -errno;
4777
4778 de->d_type =
4779 S_ISREG(st.st_mode) ? DT_REG :
4780 S_ISDIR(st.st_mode) ? DT_DIR :
4781 S_ISLNK(st.st_mode) ? DT_LNK :
4782 S_ISFIFO(st.st_mode) ? DT_FIFO :
4783 S_ISSOCK(st.st_mode) ? DT_SOCK :
4784 S_ISCHR(st.st_mode) ? DT_CHR :
4785 S_ISBLK(st.st_mode) ? DT_BLK :
4786 DT_UNKNOWN;
4787
4788 return 0;
4789 }
4790
4791 int get_files_in_directory(const char *path, char ***list) {
4792 _cleanup_closedir_ DIR *d = NULL;
4793 size_t bufsize = 0, n = 0;
4794 _cleanup_strv_free_ char **l = NULL;
4795
4796 assert(path);
4797
4798 /* Returns all files in a directory in *list, and the number
4799 * of files as return value. If list is NULL returns only the
4800 * number. */
4801
4802 d = opendir(path);
4803 if (!d)
4804 return -errno;
4805
4806 for (;;) {
4807 struct dirent *de;
4808
4809 errno = 0;
4810 de = readdir(d);
4811 if (!de && errno != 0)
4812 return -errno;
4813 if (!de)
4814 break;
4815
4816 dirent_ensure_type(d, de);
4817
4818 if (!dirent_is_file(de))
4819 continue;
4820
4821 if (list) {
4822 /* one extra slot is needed for the terminating NULL */
4823 if (!GREEDY_REALLOC(l, bufsize, n + 2))
4824 return -ENOMEM;
4825
4826 l[n] = strdup(de->d_name);
4827 if (!l[n])
4828 return -ENOMEM;
4829
4830 l[++n] = NULL;
4831 } else
4832 n++;
4833 }
4834
4835 if (list) {
4836 *list = l;
4837 l = NULL; /* avoid freeing */
4838 }
4839
4840 return n;
4841 }
4842
4843 char *strjoin(const char *x, ...) {
4844 va_list ap;
4845 size_t l;
4846 char *r, *p;
4847
4848 va_start(ap, x);
4849
4850 if (x) {
4851 l = strlen(x);
4852
4853 for (;;) {
4854 const char *t;
4855 size_t n;
4856
4857 t = va_arg(ap, const char *);
4858 if (!t)
4859 break;
4860
4861 n = strlen(t);
4862 if (n > ((size_t) -1) - l) {
4863 va_end(ap);
4864 return NULL;
4865 }
4866
4867 l += n;
4868 }
4869 } else
4870 l = 0;
4871
4872 va_end(ap);
4873
4874 r = new(char, l+1);
4875 if (!r)
4876 return NULL;
4877
4878 if (x) {
4879 p = stpcpy(r, x);
4880
4881 va_start(ap, x);
4882
4883 for (;;) {
4884 const char *t;
4885
4886 t = va_arg(ap, const char *);
4887 if (!t)
4888 break;
4889
4890 p = stpcpy(p, t);
4891 }
4892
4893 va_end(ap);
4894 } else
4895 r[0] = 0;
4896
4897 return r;
4898 }
4899
4900 bool is_main_thread(void) {
4901 static thread_local int cached = 0;
4902
4903 if (_unlikely_(cached == 0))
4904 cached = getpid() == gettid() ? 1 : -1;
4905
4906 return cached > 0;
4907 }
4908
4909 int block_get_whole_disk(dev_t d, dev_t *ret) {
4910 char *p, *s;
4911 int r;
4912 unsigned n, m;
4913
4914 assert(ret);
4915
4916 /* If it has a queue this is good enough for us */
4917 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4918 return -ENOMEM;
4919
4920 r = access(p, F_OK);
4921 free(p);
4922
4923 if (r >= 0) {
4924 *ret = d;
4925 return 0;
4926 }
4927
4928 /* If it is a partition find the originating device */
4929 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4930 return -ENOMEM;
4931
4932 r = access(p, F_OK);
4933 free(p);
4934
4935 if (r < 0)
4936 return -ENOENT;
4937
4938 /* Get parent dev_t */
4939 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4940 return -ENOMEM;
4941
4942 r = read_one_line_file(p, &s);
4943 free(p);
4944
4945 if (r < 0)
4946 return r;
4947
4948 r = sscanf(s, "%u:%u", &m, &n);
4949 free(s);
4950
4951 if (r != 2)
4952 return -EINVAL;
4953
4954 /* Only return this if it is really good enough for us. */
4955 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4956 return -ENOMEM;
4957
4958 r = access(p, F_OK);
4959 free(p);
4960
4961 if (r >= 0) {
4962 *ret = makedev(m, n);
4963 return 0;
4964 }
4965
4966 return -ENOENT;
4967 }
4968
4969 static const char *const ioprio_class_table[] = {
4970 [IOPRIO_CLASS_NONE] = "none",
4971 [IOPRIO_CLASS_RT] = "realtime",
4972 [IOPRIO_CLASS_BE] = "best-effort",
4973 [IOPRIO_CLASS_IDLE] = "idle"
4974 };
4975
4976 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4977
4978 static const char *const sigchld_code_table[] = {
4979 [CLD_EXITED] = "exited",
4980 [CLD_KILLED] = "killed",
4981 [CLD_DUMPED] = "dumped",
4982 [CLD_TRAPPED] = "trapped",
4983 [CLD_STOPPED] = "stopped",
4984 [CLD_CONTINUED] = "continued",
4985 };
4986
4987 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4988
4989 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4990 [LOG_FAC(LOG_KERN)] = "kern",
4991 [LOG_FAC(LOG_USER)] = "user",
4992 [LOG_FAC(LOG_MAIL)] = "mail",
4993 [LOG_FAC(LOG_DAEMON)] = "daemon",
4994 [LOG_FAC(LOG_AUTH)] = "auth",
4995 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4996 [LOG_FAC(LOG_LPR)] = "lpr",
4997 [LOG_FAC(LOG_NEWS)] = "news",
4998 [LOG_FAC(LOG_UUCP)] = "uucp",
4999 [LOG_FAC(LOG_CRON)] = "cron",
5000 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5001 [LOG_FAC(LOG_FTP)] = "ftp",
5002 [LOG_FAC(LOG_LOCAL0)] = "local0",
5003 [LOG_FAC(LOG_LOCAL1)] = "local1",
5004 [LOG_FAC(LOG_LOCAL2)] = "local2",
5005 [LOG_FAC(LOG_LOCAL3)] = "local3",
5006 [LOG_FAC(LOG_LOCAL4)] = "local4",
5007 [LOG_FAC(LOG_LOCAL5)] = "local5",
5008 [LOG_FAC(LOG_LOCAL6)] = "local6",
5009 [LOG_FAC(LOG_LOCAL7)] = "local7"
5010 };
5011
5012 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
5013
5014 static const char *const log_level_table[] = {
5015 [LOG_EMERG] = "emerg",
5016 [LOG_ALERT] = "alert",
5017 [LOG_CRIT] = "crit",
5018 [LOG_ERR] = "err",
5019 [LOG_WARNING] = "warning",
5020 [LOG_NOTICE] = "notice",
5021 [LOG_INFO] = "info",
5022 [LOG_DEBUG] = "debug"
5023 };
5024
5025 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
5026
5027 static const char* const sched_policy_table[] = {
5028 [SCHED_OTHER] = "other",
5029 [SCHED_BATCH] = "batch",
5030 [SCHED_IDLE] = "idle",
5031 [SCHED_FIFO] = "fifo",
5032 [SCHED_RR] = "rr"
5033 };
5034
5035 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
5036
5037 static const char* const rlimit_table[_RLIMIT_MAX] = {
5038 [RLIMIT_CPU] = "LimitCPU",
5039 [RLIMIT_FSIZE] = "LimitFSIZE",
5040 [RLIMIT_DATA] = "LimitDATA",
5041 [RLIMIT_STACK] = "LimitSTACK",
5042 [RLIMIT_CORE] = "LimitCORE",
5043 [RLIMIT_RSS] = "LimitRSS",
5044 [RLIMIT_NOFILE] = "LimitNOFILE",
5045 [RLIMIT_AS] = "LimitAS",
5046 [RLIMIT_NPROC] = "LimitNPROC",
5047 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5048 [RLIMIT_LOCKS] = "LimitLOCKS",
5049 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5050 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5051 [RLIMIT_NICE] = "LimitNICE",
5052 [RLIMIT_RTPRIO] = "LimitRTPRIO",
5053 [RLIMIT_RTTIME] = "LimitRTTIME"
5054 };
5055
5056 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5057
5058 static const char* const ip_tos_table[] = {
5059 [IPTOS_LOWDELAY] = "low-delay",
5060 [IPTOS_THROUGHPUT] = "throughput",
5061 [IPTOS_RELIABILITY] = "reliability",
5062 [IPTOS_LOWCOST] = "low-cost",
5063 };
5064
5065 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
5066
5067 static const char *const __signal_table[] = {
5068 [SIGHUP] = "HUP",
5069 [SIGINT] = "INT",
5070 [SIGQUIT] = "QUIT",
5071 [SIGILL] = "ILL",
5072 [SIGTRAP] = "TRAP",
5073 [SIGABRT] = "ABRT",
5074 [SIGBUS] = "BUS",
5075 [SIGFPE] = "FPE",
5076 [SIGKILL] = "KILL",
5077 [SIGUSR1] = "USR1",
5078 [SIGSEGV] = "SEGV",
5079 [SIGUSR2] = "USR2",
5080 [SIGPIPE] = "PIPE",
5081 [SIGALRM] = "ALRM",
5082 [SIGTERM] = "TERM",
5083 #ifdef SIGSTKFLT
5084 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5085 #endif
5086 [SIGCHLD] = "CHLD",
5087 [SIGCONT] = "CONT",
5088 [SIGSTOP] = "STOP",
5089 [SIGTSTP] = "TSTP",
5090 [SIGTTIN] = "TTIN",
5091 [SIGTTOU] = "TTOU",
5092 [SIGURG] = "URG",
5093 [SIGXCPU] = "XCPU",
5094 [SIGXFSZ] = "XFSZ",
5095 [SIGVTALRM] = "VTALRM",
5096 [SIGPROF] = "PROF",
5097 [SIGWINCH] = "WINCH",
5098 [SIGIO] = "IO",
5099 [SIGPWR] = "PWR",
5100 [SIGSYS] = "SYS"
5101 };
5102
5103 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5104
5105 const char *signal_to_string(int signo) {
5106 static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
5107 const char *name;
5108
5109 name = __signal_to_string(signo);
5110 if (name)
5111 return name;
5112
5113 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5114 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
5115 else
5116 snprintf(buf, sizeof(buf), "%d", signo);
5117
5118 return buf;
5119 }
5120
5121 int signal_from_string(const char *s) {
5122 int signo;
5123 int offset = 0;
5124 unsigned u;
5125
5126 signo = __signal_from_string(s);
5127 if (signo > 0)
5128 return signo;
5129
5130 if (startswith(s, "RTMIN+")) {
5131 s += 6;
5132 offset = SIGRTMIN;
5133 }
5134 if (safe_atou(s, &u) >= 0) {
5135 signo = (int) u + offset;
5136 if (signo > 0 && signo < _NSIG)
5137 return signo;
5138 }
5139 return -EINVAL;
5140 }
5141
5142 bool kexec_loaded(void) {
5143 bool loaded = false;
5144 char *s;
5145
5146 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5147 if (s[0] == '1')
5148 loaded = true;
5149 free(s);
5150 }
5151 return loaded;
5152 }
5153
5154 int prot_from_flags(int flags) {
5155
5156 switch (flags & O_ACCMODE) {
5157
5158 case O_RDONLY:
5159 return PROT_READ;
5160
5161 case O_WRONLY:
5162 return PROT_WRITE;
5163
5164 case O_RDWR:
5165 return PROT_READ|PROT_WRITE;
5166
5167 default:
5168 return -EINVAL;
5169 }
5170 }
5171
5172 char *format_bytes(char *buf, size_t l, off_t t) {
5173 unsigned i;
5174
5175 static const struct {
5176 const char *suffix;
5177 off_t factor;
5178 } table[] = {
5179 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5180 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5181 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5182 { "G", 1024ULL*1024ULL*1024ULL },
5183 { "M", 1024ULL*1024ULL },
5184 { "K", 1024ULL },
5185 };
5186
5187 for (i = 0; i < ELEMENTSOF(table); i++) {
5188
5189 if (t >= table[i].factor) {
5190 snprintf(buf, l,
5191 "%llu.%llu%s",
5192 (unsigned long long) (t / table[i].factor),
5193 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5194 table[i].suffix);
5195
5196 goto finish;
5197 }
5198 }
5199
5200 snprintf(buf, l, "%lluB", (unsigned long long) t);
5201
5202 finish:
5203 buf[l-1] = 0;
5204 return buf;
5205
5206 }
5207
5208 void* memdup(const void *p, size_t l) {
5209 void *r;
5210
5211 assert(p);
5212
5213 r = malloc(l);
5214 if (!r)
5215 return NULL;
5216
5217 memcpy(r, p, l);
5218 return r;
5219 }
5220
5221 int fd_inc_sndbuf(int fd, size_t n) {
5222 int r, value;
5223 socklen_t l = sizeof(value);
5224
5225 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5226 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
5227 return 0;
5228
5229 /* If we have the privileges we will ignore the kernel limit. */
5230
5231 value = (int) n;
5232 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
5233 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
5234 return -errno;
5235
5236 return 1;
5237 }
5238
5239 int fd_inc_rcvbuf(int fd, size_t n) {
5240 int r, value;
5241 socklen_t l = sizeof(value);
5242
5243 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5244 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
5245 return 0;
5246
5247 /* If we have the privileges we will ignore the kernel limit. */
5248
5249 value = (int) n;
5250 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
5251 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
5252 return -errno;
5253 return 1;
5254 }
5255
5256 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5257 bool stdout_is_tty, stderr_is_tty;
5258 pid_t parent_pid, agent_pid;
5259 sigset_t ss, saved_ss;
5260 unsigned n, i;
5261 va_list ap;
5262 char **l;
5263
5264 assert(pid);
5265 assert(path);
5266
5267 /* Spawns a temporary TTY agent, making sure it goes away when
5268 * we go away */
5269
5270 parent_pid = getpid();
5271
5272 /* First we temporarily block all signals, so that the new
5273 * child has them blocked initially. This way, we can be sure
5274 * that SIGTERMs are not lost we might send to the agent. */
5275 assert_se(sigfillset(&ss) >= 0);
5276 assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
5277
5278 agent_pid = fork();
5279 if (agent_pid < 0) {
5280 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
5281 return -errno;
5282 }
5283
5284 if (agent_pid != 0) {
5285 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
5286 *pid = agent_pid;
5287 return 0;
5288 }
5289
5290 /* In the child:
5291 *
5292 * Make sure the agent goes away when the parent dies */
5293 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5294 _exit(EXIT_FAILURE);
5295
5296 /* Make sure we actually can kill the agent, if we need to, in
5297 * case somebody invoked us from a shell script that trapped
5298 * SIGTERM or so... */
5299 reset_all_signal_handlers();
5300 reset_signal_mask();
5301
5302 /* Check whether our parent died before we were able
5303 * to set the death signal and unblock the signals */
5304 if (getppid() != parent_pid)
5305 _exit(EXIT_SUCCESS);
5306
5307 /* Don't leak fds to the agent */
5308 close_all_fds(except, n_except);
5309
5310 stdout_is_tty = isatty(STDOUT_FILENO);
5311 stderr_is_tty = isatty(STDERR_FILENO);
5312
5313 if (!stdout_is_tty || !stderr_is_tty) {
5314 int fd;
5315
5316 /* Detach from stdout/stderr. and reopen
5317 * /dev/tty for them. This is important to
5318 * ensure that when systemctl is started via
5319 * popen() or a similar call that expects to
5320 * read EOF we actually do generate EOF and
5321 * not delay this indefinitely by because we
5322 * keep an unused copy of stdin around. */
5323 fd = open("/dev/tty", O_WRONLY);
5324 if (fd < 0) {
5325 log_error_errno(errno, "Failed to open /dev/tty: %m");
5326 _exit(EXIT_FAILURE);
5327 }
5328
5329 if (!stdout_is_tty)
5330 dup2(fd, STDOUT_FILENO);
5331
5332 if (!stderr_is_tty)
5333 dup2(fd, STDERR_FILENO);
5334
5335 if (fd > 2)
5336 close(fd);
5337 }
5338
5339 /* Count arguments */
5340 va_start(ap, path);
5341 for (n = 0; va_arg(ap, char*); n++)
5342 ;
5343 va_end(ap);
5344
5345 /* Allocate strv */
5346 l = alloca(sizeof(char *) * (n + 1));
5347
5348 /* Fill in arguments */
5349 va_start(ap, path);
5350 for (i = 0; i <= n; i++)
5351 l[i] = va_arg(ap, char*);
5352 va_end(ap);
5353
5354 execv(path, l);
5355 _exit(EXIT_FAILURE);
5356 }
5357
5358 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5359 struct rlimit highest, fixed;
5360
5361 assert(rlim);
5362
5363 if (setrlimit(resource, rlim) >= 0)
5364 return 0;
5365
5366 if (errno != EPERM)
5367 return -errno;
5368
5369 /* So we failed to set the desired setrlimit, then let's try
5370 * to get as close as we can */
5371 assert_se(getrlimit(resource, &highest) == 0);
5372
5373 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5374 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5375
5376 if (setrlimit(resource, &fixed) < 0)
5377 return -errno;
5378
5379 return 0;
5380 }
5381
5382 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5383 _cleanup_fclose_ FILE *f = NULL;
5384 char *value = NULL;
5385 int r;
5386 bool done = false;
5387 size_t l;
5388 const char *path;
5389
5390 assert(pid >= 0);
5391 assert(field);
5392 assert(_value);
5393
5394 path = procfs_file_alloca(pid, "environ");
5395
5396 f = fopen(path, "re");
5397 if (!f)
5398 return -errno;
5399
5400 l = strlen(field);
5401 r = 0;
5402
5403 do {
5404 char line[LINE_MAX];
5405 unsigned i;
5406
5407 for (i = 0; i < sizeof(line)-1; i++) {
5408 int c;
5409
5410 c = getc(f);
5411 if (_unlikely_(c == EOF)) {
5412 done = true;
5413 break;
5414 } else if (c == 0)
5415 break;
5416
5417 line[i] = c;
5418 }
5419 line[i] = 0;
5420
5421 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5422 value = strdup(line + l + 1);
5423 if (!value)
5424 return -ENOMEM;
5425
5426 r = 1;
5427 break;
5428 }
5429
5430 } while (!done);
5431
5432 *_value = value;
5433 return r;
5434 }
5435
5436 bool is_valid_documentation_url(const char *url) {
5437 assert(url);
5438
5439 if (startswith(url, "http://") && url[7])
5440 return true;
5441
5442 if (startswith(url, "https://") && url[8])
5443 return true;
5444
5445 if (startswith(url, "file:") && url[5])
5446 return true;
5447
5448 if (startswith(url, "info:") && url[5])
5449 return true;
5450
5451 if (startswith(url, "man:") && url[4])
5452 return true;
5453
5454 return false;
5455 }
5456
5457 bool in_initrd(void) {
5458 static int saved = -1;
5459 struct statfs s;
5460
5461 if (saved >= 0)
5462 return saved;
5463
5464 /* We make two checks here:
5465 *
5466 * 1. the flag file /etc/initrd-release must exist
5467 * 2. the root file system must be a memory file system
5468 *
5469 * The second check is extra paranoia, since misdetecting an
5470 * initrd can have bad bad consequences due the initrd
5471 * emptying when transititioning to the main systemd.
5472 */
5473
5474 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5475 statfs("/", &s) >= 0 &&
5476 is_temporary_fs(&s);
5477
5478 return saved;
5479 }
5480
5481 void warn_melody(void) {
5482 _cleanup_close_ int fd = -1;
5483
5484 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5485 if (fd < 0)
5486 return;
5487
5488 /* Yeah, this is synchronous. Kinda sucks. But well... */
5489
5490 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5491 usleep(125*USEC_PER_MSEC);
5492
5493 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5494 usleep(125*USEC_PER_MSEC);
5495
5496 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5497 usleep(125*USEC_PER_MSEC);
5498
5499 ioctl(fd, KIOCSOUND, 0);
5500 }
5501
5502 int make_console_stdio(void) {
5503 int fd, r;
5504
5505 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5506
5507 fd = acquire_terminal("/dev/console", false, true, true, USEC_INFINITY);
5508 if (fd < 0)
5509 return log_error_errno(fd, "Failed to acquire terminal: %m");
5510
5511 r = make_stdio(fd);
5512 if (r < 0)
5513 return log_error_errno(r, "Failed to duplicate terminal fd: %m");
5514
5515 return 0;
5516 }
5517
5518 int get_home_dir(char **_h) {
5519 struct passwd *p;
5520 const char *e;
5521 char *h;
5522 uid_t u;
5523
5524 assert(_h);
5525
5526 /* Take the user specified one */
5527 e = secure_getenv("HOME");
5528 if (e && path_is_absolute(e)) {
5529 h = strdup(e);
5530 if (!h)
5531 return -ENOMEM;
5532
5533 *_h = h;
5534 return 0;
5535 }
5536
5537 /* Hardcode home directory for root to avoid NSS */
5538 u = getuid();
5539 if (u == 0) {
5540 h = strdup("/root");
5541 if (!h)
5542 return -ENOMEM;
5543
5544 *_h = h;
5545 return 0;
5546 }
5547
5548 /* Check the database... */
5549 errno = 0;
5550 p = getpwuid(u);
5551 if (!p)
5552 return errno > 0 ? -errno : -ESRCH;
5553
5554 if (!path_is_absolute(p->pw_dir))
5555 return -EINVAL;
5556
5557 h = strdup(p->pw_dir);
5558 if (!h)
5559 return -ENOMEM;
5560
5561 *_h = h;
5562 return 0;
5563 }
5564
5565 int get_shell(char **_s) {
5566 struct passwd *p;
5567 const char *e;
5568 char *s;
5569 uid_t u;
5570
5571 assert(_s);
5572
5573 /* Take the user specified one */
5574 e = getenv("SHELL");
5575 if (e) {
5576 s = strdup(e);
5577 if (!s)
5578 return -ENOMEM;
5579
5580 *_s = s;
5581 return 0;
5582 }
5583
5584 /* Hardcode home directory for root to avoid NSS */
5585 u = getuid();
5586 if (u == 0) {
5587 s = strdup("/bin/sh");
5588 if (!s)
5589 return -ENOMEM;
5590
5591 *_s = s;
5592 return 0;
5593 }
5594
5595 /* Check the database... */
5596 errno = 0;
5597 p = getpwuid(u);
5598 if (!p)
5599 return errno > 0 ? -errno : -ESRCH;
5600
5601 if (!path_is_absolute(p->pw_shell))
5602 return -EINVAL;
5603
5604 s = strdup(p->pw_shell);
5605 if (!s)
5606 return -ENOMEM;
5607
5608 *_s = s;
5609 return 0;
5610 }
5611
5612 bool filename_is_valid(const char *p) {
5613
5614 if (isempty(p))
5615 return false;
5616
5617 if (strchr(p, '/'))
5618 return false;
5619
5620 if (streq(p, "."))
5621 return false;
5622
5623 if (streq(p, ".."))
5624 return false;
5625
5626 if (strlen(p) > FILENAME_MAX)
5627 return false;
5628
5629 return true;
5630 }
5631
5632 bool string_is_safe(const char *p) {
5633 const char *t;
5634
5635 if (!p)
5636 return false;
5637
5638 for (t = p; *t; t++) {
5639 if (*t > 0 && *t < ' ')
5640 return false;
5641
5642 if (strchr("\\\"\'\0x7f", *t))
5643 return false;
5644 }
5645
5646 return true;
5647 }
5648
5649 /**
5650 * Check if a string contains control characters. If 'ok' is non-NULL
5651 * it may be a string containing additional CCs to be considered OK.
5652 */
5653 bool string_has_cc(const char *p, const char *ok) {
5654 const char *t;
5655
5656 assert(p);
5657
5658 for (t = p; *t; t++) {
5659 if (ok && strchr(ok, *t))
5660 continue;
5661
5662 if (*t > 0 && *t < ' ')
5663 return true;
5664
5665 if (*t == 127)
5666 return true;
5667 }
5668
5669 return false;
5670 }
5671
5672 bool path_is_safe(const char *p) {
5673
5674 if (isempty(p))
5675 return false;
5676
5677 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5678 return false;
5679
5680 if (strlen(p) > PATH_MAX)
5681 return false;
5682
5683 /* The following two checks are not really dangerous, but hey, they still are confusing */
5684 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5685 return false;
5686
5687 if (strstr(p, "//"))
5688 return false;
5689
5690 return true;
5691 }
5692
5693 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5694 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5695 int (*compar) (const void *, const void *, void *), void *arg) {
5696 size_t l, u, idx;
5697 const void *p;
5698 int comparison;
5699
5700 l = 0;
5701 u = nmemb;
5702 while (l < u) {
5703 idx = (l + u) / 2;
5704 p = (void *)(((const char *) base) + (idx * size));
5705 comparison = compar(key, p, arg);
5706 if (comparison < 0)
5707 u = idx;
5708 else if (comparison > 0)
5709 l = idx + 1;
5710 else
5711 return (void *)p;
5712 }
5713 return NULL;
5714 }
5715
5716 bool is_locale_utf8(void) {
5717 const char *set;
5718 static int cached_answer = -1;
5719
5720 if (cached_answer >= 0)
5721 goto out;
5722
5723 if (!setlocale(LC_ALL, "")) {
5724 cached_answer = true;
5725 goto out;
5726 }
5727
5728 set = nl_langinfo(CODESET);
5729 if (!set) {
5730 cached_answer = true;
5731 goto out;
5732 }
5733
5734 if (streq(set, "UTF-8")) {
5735 cached_answer = true;
5736 goto out;
5737 }
5738
5739 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5740 * unset and everything can do to UTF-8 nowadays. */
5741 set = setlocale(LC_CTYPE, NULL);
5742 if (!set) {
5743 cached_answer = true;
5744 goto out;
5745 }
5746
5747 /* Check result, but ignore the result if C was set
5748 * explicitly. */
5749 cached_answer =
5750 streq(set, "C") &&
5751 !getenv("LC_ALL") &&
5752 !getenv("LC_CTYPE") &&
5753 !getenv("LANG");
5754
5755 out:
5756 return (bool) cached_answer;
5757 }
5758
5759 const char *draw_special_char(DrawSpecialChar ch) {
5760 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5761
5762 /* UTF-8 */ {
5763 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
5764 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5765 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5766 [DRAW_TREE_SPACE] = " ", /* */
5767 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
5768 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
5769 [DRAW_ARROW] = "\342\206\222", /* → */
5770 [DRAW_DASH] = "\342\200\223", /* – */
5771 },
5772
5773 /* ASCII fallback */ {
5774 [DRAW_TREE_VERTICAL] = "| ",
5775 [DRAW_TREE_BRANCH] = "|-",
5776 [DRAW_TREE_RIGHT] = "`-",
5777 [DRAW_TREE_SPACE] = " ",
5778 [DRAW_TRIANGULAR_BULLET] = ">",
5779 [DRAW_BLACK_CIRCLE] = "*",
5780 [DRAW_ARROW] = "->",
5781 [DRAW_DASH] = "-",
5782 }
5783 };
5784
5785 return draw_table[!is_locale_utf8()][ch];
5786 }
5787
5788 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5789 const char *f;
5790 char *t, *r;
5791 size_t l, old_len, new_len;
5792
5793 assert(text);
5794 assert(old_string);
5795 assert(new_string);
5796
5797 old_len = strlen(old_string);
5798 new_len = strlen(new_string);
5799
5800 l = strlen(text);
5801 r = new(char, l+1);
5802 if (!r)
5803 return NULL;
5804
5805 f = text;
5806 t = r;
5807 while (*f) {
5808 char *a;
5809 size_t d, nl;
5810
5811 if (!startswith(f, old_string)) {
5812 *(t++) = *(f++);
5813 continue;
5814 }
5815
5816 d = t - r;
5817 nl = l - old_len + new_len;
5818 a = realloc(r, nl + 1);
5819 if (!a)
5820 goto oom;
5821
5822 l = nl;
5823 r = a;
5824 t = r + d;
5825
5826 t = stpcpy(t, new_string);
5827 f += old_len;
5828 }
5829
5830 *t = 0;
5831 return r;
5832
5833 oom:
5834 free(r);
5835 return NULL;
5836 }
5837
5838 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5839 const char *i, *begin = NULL;
5840 enum {
5841 STATE_OTHER,
5842 STATE_ESCAPE,
5843 STATE_BRACKET
5844 } state = STATE_OTHER;
5845 char *obuf = NULL;
5846 size_t osz = 0, isz;
5847 FILE *f;
5848
5849 assert(ibuf);
5850 assert(*ibuf);
5851
5852 /* Strips ANSI color and replaces TABs by 8 spaces */
5853
5854 isz = _isz ? *_isz : strlen(*ibuf);
5855
5856 f = open_memstream(&obuf, &osz);
5857 if (!f)
5858 return NULL;
5859
5860 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5861
5862 switch (state) {
5863
5864 case STATE_OTHER:
5865 if (i >= *ibuf + isz) /* EOT */
5866 break;
5867 else if (*i == '\x1B')
5868 state = STATE_ESCAPE;
5869 else if (*i == '\t')
5870 fputs(" ", f);
5871 else
5872 fputc(*i, f);
5873 break;
5874
5875 case STATE_ESCAPE:
5876 if (i >= *ibuf + isz) { /* EOT */
5877 fputc('\x1B', f);
5878 break;
5879 } else if (*i == '[') {
5880 state = STATE_BRACKET;
5881 begin = i + 1;
5882 } else {
5883 fputc('\x1B', f);
5884 fputc(*i, f);
5885 state = STATE_OTHER;
5886 }
5887
5888 break;
5889
5890 case STATE_BRACKET:
5891
5892 if (i >= *ibuf + isz || /* EOT */
5893 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5894 fputc('\x1B', f);
5895 fputc('[', f);
5896 state = STATE_OTHER;
5897 i = begin-1;
5898 } else if (*i == 'm')
5899 state = STATE_OTHER;
5900 break;
5901 }
5902 }
5903
5904 if (ferror(f)) {
5905 fclose(f);
5906 free(obuf);
5907 return NULL;
5908 }
5909
5910 fclose(f);
5911
5912 free(*ibuf);
5913 *ibuf = obuf;
5914
5915 if (_isz)
5916 *_isz = osz;
5917
5918 return obuf;
5919 }
5920
5921 int on_ac_power(void) {
5922 bool found_offline = false, found_online = false;
5923 _cleanup_closedir_ DIR *d = NULL;
5924
5925 d = opendir("/sys/class/power_supply");
5926 if (!d)
5927 return -errno;
5928
5929 for (;;) {
5930 struct dirent *de;
5931 _cleanup_close_ int fd = -1, device = -1;
5932 char contents[6];
5933 ssize_t n;
5934
5935 errno = 0;
5936 de = readdir(d);
5937 if (!de && errno != 0)
5938 return -errno;
5939
5940 if (!de)
5941 break;
5942
5943 if (hidden_file(de->d_name))
5944 continue;
5945
5946 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5947 if (device < 0) {
5948 if (errno == ENOENT || errno == ENOTDIR)
5949 continue;
5950
5951 return -errno;
5952 }
5953
5954 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5955 if (fd < 0) {
5956 if (errno == ENOENT)
5957 continue;
5958
5959 return -errno;
5960 }
5961
5962 n = read(fd, contents, sizeof(contents));
5963 if (n < 0)
5964 return -errno;
5965
5966 if (n != 6 || memcmp(contents, "Mains\n", 6))
5967 continue;
5968
5969 safe_close(fd);
5970 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5971 if (fd < 0) {
5972 if (errno == ENOENT)
5973 continue;
5974
5975 return -errno;
5976 }
5977
5978 n = read(fd, contents, sizeof(contents));
5979 if (n < 0)
5980 return -errno;
5981
5982 if (n != 2 || contents[1] != '\n')
5983 return -EIO;
5984
5985 if (contents[0] == '1') {
5986 found_online = true;
5987 break;
5988 } else if (contents[0] == '0')
5989 found_offline = true;
5990 else
5991 return -EIO;
5992 }
5993
5994 return found_online || !found_offline;
5995 }
5996
5997 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
5998 char **i;
5999
6000 assert(path);
6001 assert(mode);
6002 assert(_f);
6003
6004 if (!path_strv_resolve_uniq(search, root))
6005 return -ENOMEM;
6006
6007 STRV_FOREACH(i, search) {
6008 _cleanup_free_ char *p = NULL;
6009 FILE *f;
6010
6011 if (root)
6012 p = strjoin(root, *i, "/", path, NULL);
6013 else
6014 p = strjoin(*i, "/", path, NULL);
6015 if (!p)
6016 return -ENOMEM;
6017
6018 f = fopen(p, mode);
6019 if (f) {
6020 *_f = f;
6021 return 0;
6022 }
6023
6024 if (errno != ENOENT)
6025 return -errno;
6026 }
6027
6028 return -ENOENT;
6029 }
6030
6031 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
6032 _cleanup_strv_free_ char **copy = NULL;
6033
6034 assert(path);
6035 assert(mode);
6036 assert(_f);
6037
6038 if (path_is_absolute(path)) {
6039 FILE *f;
6040
6041 f = fopen(path, mode);
6042 if (f) {
6043 *_f = f;
6044 return 0;
6045 }
6046
6047 return -errno;
6048 }
6049
6050 copy = strv_copy((char**) search);
6051 if (!copy)
6052 return -ENOMEM;
6053
6054 return search_and_fopen_internal(path, mode, root, copy, _f);
6055 }
6056
6057 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
6058 _cleanup_strv_free_ char **s = NULL;
6059
6060 if (path_is_absolute(path)) {
6061 FILE *f;
6062
6063 f = fopen(path, mode);
6064 if (f) {
6065 *_f = f;
6066 return 0;
6067 }
6068
6069 return -errno;
6070 }
6071
6072 s = strv_split_nulstr(search);
6073 if (!s)
6074 return -ENOMEM;
6075
6076 return search_and_fopen_internal(path, mode, root, s, _f);
6077 }
6078
6079 char *strextend(char **x, ...) {
6080 va_list ap;
6081 size_t f, l;
6082 char *r, *p;
6083
6084 assert(x);
6085
6086 l = f = *x ? strlen(*x) : 0;
6087
6088 va_start(ap, x);
6089 for (;;) {
6090 const char *t;
6091 size_t n;
6092
6093 t = va_arg(ap, const char *);
6094 if (!t)
6095 break;
6096
6097 n = strlen(t);
6098 if (n > ((size_t) -1) - l) {
6099 va_end(ap);
6100 return NULL;
6101 }
6102
6103 l += n;
6104 }
6105 va_end(ap);
6106
6107 r = realloc(*x, l+1);
6108 if (!r)
6109 return NULL;
6110
6111 p = r + f;
6112
6113 va_start(ap, x);
6114 for (;;) {
6115 const char *t;
6116
6117 t = va_arg(ap, const char *);
6118 if (!t)
6119 break;
6120
6121 p = stpcpy(p, t);
6122 }
6123 va_end(ap);
6124
6125 *p = 0;
6126 *x = r;
6127
6128 return r + l;
6129 }
6130
6131 char *strrep(const char *s, unsigned n) {
6132 size_t l;
6133 char *r, *p;
6134 unsigned i;
6135
6136 assert(s);
6137
6138 l = strlen(s);
6139 p = r = malloc(l * n + 1);
6140 if (!r)
6141 return NULL;
6142
6143 for (i = 0; i < n; i++)
6144 p = stpcpy(p, s);
6145
6146 *p = 0;
6147 return r;
6148 }
6149
6150 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
6151 size_t a, newalloc;
6152 void *q;
6153
6154 assert(p);
6155 assert(allocated);
6156
6157 if (*allocated >= need)
6158 return *p;
6159
6160 newalloc = MAX(need * 2, 64u / size);
6161 a = newalloc * size;
6162
6163 /* check for overflows */
6164 if (a < size * need)
6165 return NULL;
6166
6167 q = realloc(*p, a);
6168 if (!q)
6169 return NULL;
6170
6171 *p = q;
6172 *allocated = newalloc;
6173 return q;
6174 }
6175
6176 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
6177 size_t prev;
6178 uint8_t *q;
6179
6180 assert(p);
6181 assert(allocated);
6182
6183 prev = *allocated;
6184
6185 q = greedy_realloc(p, allocated, need, size);
6186 if (!q)
6187 return NULL;
6188
6189 if (*allocated > prev)
6190 memzero(q + prev * size, (*allocated - prev) * size);
6191
6192 return q;
6193 }
6194
6195 bool id128_is_valid(const char *s) {
6196 size_t i, l;
6197
6198 l = strlen(s);
6199 if (l == 32) {
6200
6201 /* Simple formatted 128bit hex string */
6202
6203 for (i = 0; i < l; i++) {
6204 char c = s[i];
6205
6206 if (!(c >= '0' && c <= '9') &&
6207 !(c >= 'a' && c <= 'z') &&
6208 !(c >= 'A' && c <= 'Z'))
6209 return false;
6210 }
6211
6212 } else if (l == 36) {
6213
6214 /* Formatted UUID */
6215
6216 for (i = 0; i < l; i++) {
6217 char c = s[i];
6218
6219 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
6220 if (c != '-')
6221 return false;
6222 } else {
6223 if (!(c >= '0' && c <= '9') &&
6224 !(c >= 'a' && c <= 'z') &&
6225 !(c >= 'A' && c <= 'Z'))
6226 return false;
6227 }
6228 }
6229
6230 } else
6231 return false;
6232
6233 return true;
6234 }
6235
6236 int split_pair(const char *s, const char *sep, char **l, char **r) {
6237 char *x, *a, *b;
6238
6239 assert(s);
6240 assert(sep);
6241 assert(l);
6242 assert(r);
6243
6244 if (isempty(sep))
6245 return -EINVAL;
6246
6247 x = strstr(s, sep);
6248 if (!x)
6249 return -EINVAL;
6250
6251 a = strndup(s, x - s);
6252 if (!a)
6253 return -ENOMEM;
6254
6255 b = strdup(x + strlen(sep));
6256 if (!b) {
6257 free(a);
6258 return -ENOMEM;
6259 }
6260
6261 *l = a;
6262 *r = b;
6263
6264 return 0;
6265 }
6266
6267 int shall_restore_state(void) {
6268 _cleanup_free_ char *value = NULL;
6269 int r;
6270
6271 r = get_proc_cmdline_key("systemd.restore_state=", &value);
6272 if (r < 0)
6273 return r;
6274 if (r == 0)
6275 return true;
6276
6277 return parse_boolean(value) != 0;
6278 }
6279
6280 int proc_cmdline(char **ret) {
6281 assert(ret);
6282
6283 if (detect_container(NULL) > 0)
6284 return get_process_cmdline(1, 0, false, ret);
6285 else
6286 return read_one_line_file("/proc/cmdline", ret);
6287 }
6288
6289 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
6290 _cleanup_free_ char *line = NULL;
6291 const char *p;
6292 int r;
6293
6294 assert(parse_item);
6295
6296 r = proc_cmdline(&line);
6297 if (r < 0)
6298 return r;
6299
6300 p = line;
6301 for (;;) {
6302 _cleanup_free_ char *word = NULL;
6303 char *value = NULL;
6304
6305 r = unquote_first_word(&p, &word, true);
6306 if (r < 0)
6307 return r;
6308 if (r == 0)
6309 break;
6310
6311 /* Filter out arguments that are intended only for the
6312 * initrd */
6313 if (!in_initrd() && startswith(word, "rd."))
6314 continue;
6315
6316 value = strchr(word, '=');
6317 if (value)
6318 *(value++) = 0;
6319
6320 r = parse_item(word, value);
6321 if (r < 0)
6322 return r;
6323 }
6324
6325 return 0;
6326 }
6327
6328 int get_proc_cmdline_key(const char *key, char **value) {
6329 _cleanup_free_ char *line = NULL, *ret = NULL;
6330 bool found = false;
6331 const char *p;
6332 int r;
6333
6334 assert(key);
6335
6336 r = proc_cmdline(&line);
6337 if (r < 0)
6338 return r;
6339
6340 p = line;
6341 for (;;) {
6342 _cleanup_free_ char *word = NULL;
6343 const char *e;
6344
6345 r = unquote_first_word(&p, &word, true);
6346 if (r < 0)
6347 return r;
6348 if (r == 0)
6349 break;
6350
6351 /* Filter out arguments that are intended only for the
6352 * initrd */
6353 if (!in_initrd() && startswith(word, "rd."))
6354 continue;
6355
6356 if (value) {
6357 e = startswith(word, key);
6358 if (!e)
6359 continue;
6360
6361 r = free_and_strdup(&ret, e);
6362 if (r < 0)
6363 return r;
6364
6365 found = true;
6366 } else {
6367 if (streq(word, key))
6368 found = true;
6369 }
6370 }
6371
6372 if (value) {
6373 *value = ret;
6374 ret = NULL;
6375 }
6376
6377 return found;
6378
6379 }
6380
6381 int container_get_leader(const char *machine, pid_t *pid) {
6382 _cleanup_free_ char *s = NULL, *class = NULL;
6383 const char *p;
6384 pid_t leader;
6385 int r;
6386
6387 assert(machine);
6388 assert(pid);
6389
6390 p = strappenda("/run/systemd/machines/", machine);
6391 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
6392 if (r == -ENOENT)
6393 return -EHOSTDOWN;
6394 if (r < 0)
6395 return r;
6396 if (!s)
6397 return -EIO;
6398
6399 if (!streq_ptr(class, "container"))
6400 return -EIO;
6401
6402 r = parse_pid(s, &leader);
6403 if (r < 0)
6404 return r;
6405 if (leader <= 1)
6406 return -EIO;
6407
6408 *pid = leader;
6409 return 0;
6410 }
6411
6412 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
6413 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
6414 int rfd = -1;
6415
6416 assert(pid >= 0);
6417
6418 if (mntns_fd) {
6419 const char *mntns;
6420
6421 mntns = procfs_file_alloca(pid, "ns/mnt");
6422 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6423 if (mntnsfd < 0)
6424 return -errno;
6425 }
6426
6427 if (pidns_fd) {
6428 const char *pidns;
6429
6430 pidns = procfs_file_alloca(pid, "ns/pid");
6431 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6432 if (pidnsfd < 0)
6433 return -errno;
6434 }
6435
6436 if (netns_fd) {
6437 const char *netns;
6438
6439 netns = procfs_file_alloca(pid, "ns/net");
6440 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
6441 if (netnsfd < 0)
6442 return -errno;
6443 }
6444
6445 if (root_fd) {
6446 const char *root;
6447
6448 root = procfs_file_alloca(pid, "root");
6449 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
6450 if (rfd < 0)
6451 return -errno;
6452 }
6453
6454 if (pidns_fd)
6455 *pidns_fd = pidnsfd;
6456
6457 if (mntns_fd)
6458 *mntns_fd = mntnsfd;
6459
6460 if (netns_fd)
6461 *netns_fd = netnsfd;
6462
6463 if (root_fd)
6464 *root_fd = rfd;
6465
6466 pidnsfd = mntnsfd = netnsfd = -1;
6467
6468 return 0;
6469 }
6470
6471 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
6472
6473 if (pidns_fd >= 0)
6474 if (setns(pidns_fd, CLONE_NEWPID) < 0)
6475 return -errno;
6476
6477 if (mntns_fd >= 0)
6478 if (setns(mntns_fd, CLONE_NEWNS) < 0)
6479 return -errno;
6480
6481 if (netns_fd >= 0)
6482 if (setns(netns_fd, CLONE_NEWNET) < 0)
6483 return -errno;
6484
6485 if (root_fd >= 0) {
6486 if (fchdir(root_fd) < 0)
6487 return -errno;
6488
6489 if (chroot(".") < 0)
6490 return -errno;
6491 }
6492
6493 if (setresgid(0, 0, 0) < 0)
6494 return -errno;
6495
6496 if (setgroups(0, NULL) < 0)
6497 return -errno;
6498
6499 if (setresuid(0, 0, 0) < 0)
6500 return -errno;
6501
6502 return 0;
6503 }
6504
6505 bool pid_is_unwaited(pid_t pid) {
6506 /* Checks whether a PID is still valid at all, including a zombie */
6507
6508 if (pid <= 0)
6509 return false;
6510
6511 if (kill(pid, 0) >= 0)
6512 return true;
6513
6514 return errno != ESRCH;
6515 }
6516
6517 bool pid_is_alive(pid_t pid) {
6518 int r;
6519
6520 /* Checks whether a PID is still valid and not a zombie */
6521
6522 if (pid <= 0)
6523 return false;
6524
6525 r = get_process_state(pid);
6526 if (r == -ENOENT || r == 'Z')
6527 return false;
6528
6529 return true;
6530 }
6531
6532 int getpeercred(int fd, struct ucred *ucred) {
6533 socklen_t n = sizeof(struct ucred);
6534 struct ucred u;
6535 int r;
6536
6537 assert(fd >= 0);
6538 assert(ucred);
6539
6540 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
6541 if (r < 0)
6542 return -errno;
6543
6544 if (n != sizeof(struct ucred))
6545 return -EIO;
6546
6547 /* Check if the data is actually useful and not suppressed due
6548 * to namespacing issues */
6549 if (u.pid <= 0)
6550 return -ENODATA;
6551 if (u.uid == UID_INVALID)
6552 return -ENODATA;
6553 if (u.gid == GID_INVALID)
6554 return -ENODATA;
6555
6556 *ucred = u;
6557 return 0;
6558 }
6559
6560 int getpeersec(int fd, char **ret) {
6561 socklen_t n = 64;
6562 char *s;
6563 int r;
6564
6565 assert(fd >= 0);
6566 assert(ret);
6567
6568 s = new0(char, n);
6569 if (!s)
6570 return -ENOMEM;
6571
6572 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6573 if (r < 0) {
6574 free(s);
6575
6576 if (errno != ERANGE)
6577 return -errno;
6578
6579 s = new0(char, n);
6580 if (!s)
6581 return -ENOMEM;
6582
6583 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6584 if (r < 0) {
6585 free(s);
6586 return -errno;
6587 }
6588 }
6589
6590 if (isempty(s)) {
6591 free(s);
6592 return -ENOTSUP;
6593 }
6594
6595 *ret = s;
6596 return 0;
6597 }
6598
6599 /* This is much like like mkostemp() but is subject to umask(). */
6600 int mkostemp_safe(char *pattern, int flags) {
6601 _cleanup_umask_ mode_t u;
6602 int fd;
6603
6604 assert(pattern);
6605
6606 u = umask(077);
6607
6608 fd = mkostemp(pattern, flags);
6609 if (fd < 0)
6610 return -errno;
6611
6612 return fd;
6613 }
6614
6615 int open_tmpfile(const char *path, int flags) {
6616 char *p;
6617 int fd;
6618
6619 assert(path);
6620
6621 #ifdef O_TMPFILE
6622 /* Try O_TMPFILE first, if it is supported */
6623 fd = open(path, flags|O_TMPFILE, S_IRUSR|S_IWUSR);
6624 if (fd >= 0)
6625 return fd;
6626 #endif
6627
6628 /* Fall back to unguessable name + unlinking */
6629 p = strappenda(path, "/systemd-tmp-XXXXXX");
6630
6631 fd = mkostemp_safe(p, flags);
6632 if (fd < 0)
6633 return fd;
6634
6635 unlink(p);
6636 return fd;
6637 }
6638
6639 int fd_warn_permissions(const char *path, int fd) {
6640 struct stat st;
6641
6642 if (fstat(fd, &st) < 0)
6643 return -errno;
6644
6645 if (st.st_mode & 0111)
6646 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
6647
6648 if (st.st_mode & 0002)
6649 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
6650
6651 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
6652 log_warning("Configuration file %s is marked world-inaccessible. This has no effect as configuration data is accessible via APIs without restrictions. Proceeding anyway.", path);
6653
6654 return 0;
6655 }
6656
6657 unsigned long personality_from_string(const char *p) {
6658
6659 /* Parse a personality specifier. We introduce our own
6660 * identifiers that indicate specific ABIs, rather than just
6661 * hints regarding the register size, since we want to keep
6662 * things open for multiple locally supported ABIs for the
6663 * same register size. We try to reuse the ABI identifiers
6664 * used by libseccomp. */
6665
6666 #if defined(__x86_64__)
6667
6668 if (streq(p, "x86"))
6669 return PER_LINUX32;
6670
6671 if (streq(p, "x86-64"))
6672 return PER_LINUX;
6673
6674 #elif defined(__i386__)
6675
6676 if (streq(p, "x86"))
6677 return PER_LINUX;
6678 #endif
6679
6680 /* personality(7) documents that 0xffffffffUL is used for
6681 * querying the current personality, hence let's use that here
6682 * as error indicator. */
6683 return 0xffffffffUL;
6684 }
6685
6686 const char* personality_to_string(unsigned long p) {
6687
6688 #if defined(__x86_64__)
6689
6690 if (p == PER_LINUX32)
6691 return "x86";
6692
6693 if (p == PER_LINUX)
6694 return "x86-64";
6695
6696 #elif defined(__i386__)
6697
6698 if (p == PER_LINUX)
6699 return "x86";
6700 #endif
6701
6702 return NULL;
6703 }
6704
6705 uint64_t physical_memory(void) {
6706 long mem;
6707
6708 /* We return this as uint64_t in case we are running as 32bit
6709 * process on a 64bit kernel with huge amounts of memory */
6710
6711 mem = sysconf(_SC_PHYS_PAGES);
6712 assert(mem > 0);
6713
6714 return (uint64_t) mem * (uint64_t) page_size();
6715 }
6716
6717 char* mount_test_option(const char *haystack, const char *needle) {
6718
6719 struct mntent me = {
6720 .mnt_opts = (char*) haystack
6721 };
6722
6723 assert(needle);
6724
6725 /* Like glibc's hasmntopt(), but works on a string, not a
6726 * struct mntent */
6727
6728 if (!haystack)
6729 return NULL;
6730
6731 return hasmntopt(&me, needle);
6732 }
6733
6734 void hexdump(FILE *f, const void *p, size_t s) {
6735 const uint8_t *b = p;
6736 unsigned n = 0;
6737
6738 assert(s == 0 || b);
6739
6740 while (s > 0) {
6741 size_t i;
6742
6743 fprintf(f, "%04x ", n);
6744
6745 for (i = 0; i < 16; i++) {
6746
6747 if (i >= s)
6748 fputs(" ", f);
6749 else
6750 fprintf(f, "%02x ", b[i]);
6751
6752 if (i == 7)
6753 fputc(' ', f);
6754 }
6755
6756 fputc(' ', f);
6757
6758 for (i = 0; i < 16; i++) {
6759
6760 if (i >= s)
6761 fputc(' ', f);
6762 else
6763 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
6764 }
6765
6766 fputc('\n', f);
6767
6768 if (s < 16)
6769 break;
6770
6771 n += 16;
6772 b += 16;
6773 s -= 16;
6774 }
6775 }
6776
6777 int update_reboot_param_file(const char *param) {
6778 int r = 0;
6779
6780 if (param) {
6781
6782 r = write_string_file(REBOOT_PARAM_FILE, param);
6783 if (r < 0)
6784 log_error("Failed to write reboot param to "
6785 REBOOT_PARAM_FILE": %s", strerror(-r));
6786 } else
6787 unlink(REBOOT_PARAM_FILE);
6788
6789 return r;
6790 }
6791
6792 int umount_recursive(const char *prefix, int flags) {
6793 bool again;
6794 int n = 0, r;
6795
6796 /* Try to umount everything recursively below a
6797 * directory. Also, take care of stacked mounts, and keep
6798 * unmounting them until they are gone. */
6799
6800 do {
6801 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6802
6803 again = false;
6804 r = 0;
6805
6806 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6807 if (!proc_self_mountinfo)
6808 return -errno;
6809
6810 for (;;) {
6811 _cleanup_free_ char *path = NULL, *p = NULL;
6812 int k;
6813
6814 k = fscanf(proc_self_mountinfo,
6815 "%*s " /* (1) mount id */
6816 "%*s " /* (2) parent id */
6817 "%*s " /* (3) major:minor */
6818 "%*s " /* (4) root */
6819 "%ms " /* (5) mount point */
6820 "%*s" /* (6) mount options */
6821 "%*[^-]" /* (7) optional fields */
6822 "- " /* (8) separator */
6823 "%*s " /* (9) file system type */
6824 "%*s" /* (10) mount source */
6825 "%*s" /* (11) mount options 2 */
6826 "%*[^\n]", /* some rubbish at the end */
6827 &path);
6828 if (k != 1) {
6829 if (k == EOF)
6830 break;
6831
6832 continue;
6833 }
6834
6835 p = cunescape(path);
6836 if (!p)
6837 return -ENOMEM;
6838
6839 if (!path_startswith(p, prefix))
6840 continue;
6841
6842 if (umount2(p, flags) < 0) {
6843 r = -errno;
6844 continue;
6845 }
6846
6847 again = true;
6848 n++;
6849
6850 break;
6851 }
6852
6853 } while (again);
6854
6855 return r ? r : n;
6856 }
6857
6858 int bind_remount_recursive(const char *prefix, bool ro) {
6859 _cleanup_set_free_free_ Set *done = NULL;
6860 _cleanup_free_ char *cleaned = NULL;
6861 int r;
6862
6863 /* Recursively remount a directory (and all its submounts)
6864 * read-only or read-write. If the directory is already
6865 * mounted, we reuse the mount and simply mark it
6866 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
6867 * operation). If it isn't we first make it one. Afterwards we
6868 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
6869 * submounts we can access, too. When mounts are stacked on
6870 * the same mount point we only care for each individual
6871 * "top-level" mount on each point, as we cannot
6872 * influence/access the underlying mounts anyway. We do not
6873 * have any effect on future submounts that might get
6874 * propagated, they migt be writable. This includes future
6875 * submounts that have been triggered via autofs. */
6876
6877 cleaned = strdup(prefix);
6878 if (!cleaned)
6879 return -ENOMEM;
6880
6881 path_kill_slashes(cleaned);
6882
6883 done = set_new(&string_hash_ops);
6884 if (!done)
6885 return -ENOMEM;
6886
6887 for (;;) {
6888 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6889 _cleanup_set_free_free_ Set *todo = NULL;
6890 bool top_autofs = false;
6891 char *x;
6892
6893 todo = set_new(&string_hash_ops);
6894 if (!todo)
6895 return -ENOMEM;
6896
6897 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6898 if (!proc_self_mountinfo)
6899 return -errno;
6900
6901 for (;;) {
6902 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
6903 int k;
6904
6905 k = fscanf(proc_self_mountinfo,
6906 "%*s " /* (1) mount id */
6907 "%*s " /* (2) parent id */
6908 "%*s " /* (3) major:minor */
6909 "%*s " /* (4) root */
6910 "%ms " /* (5) mount point */
6911 "%*s" /* (6) mount options (superblock) */
6912 "%*[^-]" /* (7) optional fields */
6913 "- " /* (8) separator */
6914 "%ms " /* (9) file system type */
6915 "%*s" /* (10) mount source */
6916 "%*s" /* (11) mount options (bind mount) */
6917 "%*[^\n]", /* some rubbish at the end */
6918 &path,
6919 &type);
6920 if (k != 2) {
6921 if (k == EOF)
6922 break;
6923
6924 continue;
6925 }
6926
6927 p = cunescape(path);
6928 if (!p)
6929 return -ENOMEM;
6930
6931 /* Let's ignore autofs mounts. If they aren't
6932 * triggered yet, we want to avoid triggering
6933 * them, as we don't make any guarantees for
6934 * future submounts anyway. If they are
6935 * already triggered, then we will find
6936 * another entry for this. */
6937 if (streq(type, "autofs")) {
6938 top_autofs = top_autofs || path_equal(cleaned, p);
6939 continue;
6940 }
6941
6942 if (path_startswith(p, cleaned) &&
6943 !set_contains(done, p)) {
6944
6945 r = set_consume(todo, p);
6946 p = NULL;
6947
6948 if (r == -EEXIST)
6949 continue;
6950 if (r < 0)
6951 return r;
6952 }
6953 }
6954
6955 /* If we have no submounts to process anymore and if
6956 * the root is either already done, or an autofs, we
6957 * are done */
6958 if (set_isempty(todo) &&
6959 (top_autofs || set_contains(done, cleaned)))
6960 return 0;
6961
6962 if (!set_contains(done, cleaned) &&
6963 !set_contains(todo, cleaned)) {
6964 /* The prefix directory itself is not yet a
6965 * mount, make it one. */
6966 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
6967 return -errno;
6968
6969 if (mount(NULL, prefix, NULL, MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
6970 return -errno;
6971
6972 x = strdup(cleaned);
6973 if (!x)
6974 return -ENOMEM;
6975
6976 r = set_consume(done, x);
6977 if (r < 0)
6978 return r;
6979 }
6980
6981 while ((x = set_steal_first(todo))) {
6982
6983 r = set_consume(done, x);
6984 if (r == -EEXIST)
6985 continue;
6986 if (r < 0)
6987 return r;
6988
6989 if (mount(NULL, x, NULL, MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
6990
6991 /* Deal with mount points that are
6992 * obstructed by a later mount */
6993
6994 if (errno != ENOENT)
6995 return -errno;
6996 }
6997
6998 }
6999 }
7000 }
7001
7002 int fflush_and_check(FILE *f) {
7003 assert(f);
7004
7005 errno = 0;
7006 fflush(f);
7007
7008 if (ferror(f))
7009 return errno ? -errno : -EIO;
7010
7011 return 0;
7012 }
7013
7014 int tempfn_xxxxxx(const char *p, char **ret) {
7015 const char *fn;
7016 char *t;
7017
7018 assert(p);
7019 assert(ret);
7020
7021 /*
7022 * Turns this:
7023 * /foo/bar/waldo
7024 *
7025 * Into this:
7026 * /foo/bar/.#waldoXXXXXX
7027 */
7028
7029 fn = basename(p);
7030 if (!filename_is_valid(fn))
7031 return -EINVAL;
7032
7033 t = new(char, strlen(p) + 2 + 6 + 1);
7034 if (!t)
7035 return -ENOMEM;
7036
7037 strcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), "XXXXXX");
7038
7039 *ret = path_kill_slashes(t);
7040 return 0;
7041 }
7042
7043 int tempfn_random(const char *p, char **ret) {
7044 const char *fn;
7045 char *t, *x;
7046 uint64_t u;
7047 unsigned i;
7048
7049 assert(p);
7050 assert(ret);
7051
7052 /*
7053 * Turns this:
7054 * /foo/bar/waldo
7055 *
7056 * Into this:
7057 * /foo/bar/.#waldobaa2a261115984a9
7058 */
7059
7060 fn = basename(p);
7061 if (!filename_is_valid(fn))
7062 return -EINVAL;
7063
7064 t = new(char, strlen(p) + 2 + 16 + 1);
7065 if (!t)
7066 return -ENOMEM;
7067
7068 x = stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn);
7069
7070 u = random_u64();
7071 for (i = 0; i < 16; i++) {
7072 *(x++) = hexchar(u & 0xF);
7073 u >>= 4;
7074 }
7075
7076 *x = 0;
7077
7078 *ret = path_kill_slashes(t);
7079 return 0;
7080 }
7081
7082 int tempfn_random_child(const char *p, char **ret) {
7083 char *t, *x;
7084 uint64_t u;
7085 unsigned i;
7086
7087 assert(p);
7088 assert(ret);
7089
7090 /* Turns this:
7091 * /foo/bar/waldo
7092 * Into this:
7093 * /foo/bar/waldo/.#3c2b6219aa75d7d0
7094 */
7095
7096 t = new(char, strlen(p) + 3 + 16 + 1);
7097 if (!t)
7098 return -ENOMEM;
7099
7100 x = stpcpy(stpcpy(t, p), "/.#");
7101
7102 u = random_u64();
7103 for (i = 0; i < 16; i++) {
7104 *(x++) = hexchar(u & 0xF);
7105 u >>= 4;
7106 }
7107
7108 *x = 0;
7109
7110 *ret = path_kill_slashes(t);
7111 return 0;
7112 }
7113
7114 /* make sure the hostname is not "localhost" */
7115 bool is_localhost(const char *hostname) {
7116 assert(hostname);
7117
7118 /* This tries to identify local host and domain names
7119 * described in RFC6761 plus the redhatism of .localdomain */
7120
7121 return streq(hostname, "localhost") ||
7122 streq(hostname, "localhost.") ||
7123 streq(hostname, "localdomain.") ||
7124 streq(hostname, "localdomain") ||
7125 endswith(hostname, ".localhost") ||
7126 endswith(hostname, ".localhost.") ||
7127 endswith(hostname, ".localdomain") ||
7128 endswith(hostname, ".localdomain.");
7129 }
7130
7131 int take_password_lock(const char *root) {
7132
7133 struct flock flock = {
7134 .l_type = F_WRLCK,
7135 .l_whence = SEEK_SET,
7136 .l_start = 0,
7137 .l_len = 0,
7138 };
7139
7140 const char *path;
7141 int fd, r;
7142
7143 /* This is roughly the same as lckpwdf(), but not as awful. We
7144 * don't want to use alarm() and signals, hence we implement
7145 * our own trivial version of this.
7146 *
7147 * Note that shadow-utils also takes per-database locks in
7148 * addition to lckpwdf(). However, we don't given that they
7149 * are redundant as they they invoke lckpwdf() first and keep
7150 * it during everything they do. The per-database locks are
7151 * awfully racy, and thus we just won't do them. */
7152
7153 if (root)
7154 path = strappenda(root, "/etc/.pwd.lock");
7155 else
7156 path = "/etc/.pwd.lock";
7157
7158 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
7159 if (fd < 0)
7160 return -errno;
7161
7162 r = fcntl(fd, F_SETLKW, &flock);
7163 if (r < 0) {
7164 safe_close(fd);
7165 return -errno;
7166 }
7167
7168 return fd;
7169 }
7170
7171 int is_symlink(const char *path) {
7172 struct stat info;
7173
7174 if (lstat(path, &info) < 0)
7175 return -errno;
7176
7177 return !!S_ISLNK(info.st_mode);
7178 }
7179
7180 int is_dir(const char* path, bool follow) {
7181 struct stat st;
7182 int r;
7183
7184 if (follow)
7185 r = stat(path, &st);
7186 else
7187 r = lstat(path, &st);
7188 if (r < 0)
7189 return -errno;
7190
7191 return !!S_ISDIR(st.st_mode);
7192 }
7193
7194 int unquote_first_word(const char **p, char **ret, bool relax) {
7195 _cleanup_free_ char *s = NULL;
7196 size_t allocated = 0, sz = 0;
7197
7198 enum {
7199 START,
7200 VALUE,
7201 VALUE_ESCAPE,
7202 SINGLE_QUOTE,
7203 SINGLE_QUOTE_ESCAPE,
7204 DOUBLE_QUOTE,
7205 DOUBLE_QUOTE_ESCAPE,
7206 SPACE,
7207 } state = START;
7208
7209 assert(p);
7210 assert(*p);
7211 assert(ret);
7212
7213 /* Parses the first word of a string, and returns it in
7214 * *ret. Removes all quotes in the process. When parsing fails
7215 * (because of an uneven number of quotes or similar), leaves
7216 * the pointer *p at the first invalid character. */
7217
7218 for (;;) {
7219 char c = **p;
7220
7221 switch (state) {
7222
7223 case START:
7224 if (c == 0)
7225 goto finish;
7226 else if (strchr(WHITESPACE, c))
7227 break;
7228
7229 state = VALUE;
7230 /* fallthrough */
7231
7232 case VALUE:
7233 if (c == 0)
7234 goto finish;
7235 else if (c == '\'')
7236 state = SINGLE_QUOTE;
7237 else if (c == '\\')
7238 state = VALUE_ESCAPE;
7239 else if (c == '\"')
7240 state = DOUBLE_QUOTE;
7241 else if (strchr(WHITESPACE, c))
7242 state = SPACE;
7243 else {
7244 if (!GREEDY_REALLOC(s, allocated, sz+2))
7245 return -ENOMEM;
7246
7247 s[sz++] = c;
7248 }
7249
7250 break;
7251
7252 case VALUE_ESCAPE:
7253 if (c == 0) {
7254 if (relax)
7255 goto finish;
7256 return -EINVAL;
7257 }
7258
7259 if (!GREEDY_REALLOC(s, allocated, sz+2))
7260 return -ENOMEM;
7261
7262 s[sz++] = c;
7263 state = VALUE;
7264
7265 break;
7266
7267 case SINGLE_QUOTE:
7268 if (c == 0) {
7269 if (relax)
7270 goto finish;
7271 return -EINVAL;
7272 } else if (c == '\'')
7273 state = VALUE;
7274 else if (c == '\\')
7275 state = SINGLE_QUOTE_ESCAPE;
7276 else {
7277 if (!GREEDY_REALLOC(s, allocated, sz+2))
7278 return -ENOMEM;
7279
7280 s[sz++] = c;
7281 }
7282
7283 break;
7284
7285 case SINGLE_QUOTE_ESCAPE:
7286 if (c == 0) {
7287 if (relax)
7288 goto finish;
7289 return -EINVAL;
7290 }
7291
7292 if (!GREEDY_REALLOC(s, allocated, sz+2))
7293 return -ENOMEM;
7294
7295 s[sz++] = c;
7296 state = SINGLE_QUOTE;
7297 break;
7298
7299 case DOUBLE_QUOTE:
7300 if (c == 0)
7301 return -EINVAL;
7302 else if (c == '\"')
7303 state = VALUE;
7304 else if (c == '\\')
7305 state = DOUBLE_QUOTE_ESCAPE;
7306 else {
7307 if (!GREEDY_REALLOC(s, allocated, sz+2))
7308 return -ENOMEM;
7309
7310 s[sz++] = c;
7311 }
7312
7313 break;
7314
7315 case DOUBLE_QUOTE_ESCAPE:
7316 if (c == 0) {
7317 if (relax)
7318 goto finish;
7319 return -EINVAL;
7320 }
7321
7322 if (!GREEDY_REALLOC(s, allocated, sz+2))
7323 return -ENOMEM;
7324
7325 s[sz++] = c;
7326 state = DOUBLE_QUOTE;
7327 break;
7328
7329 case SPACE:
7330 if (c == 0)
7331 goto finish;
7332 if (!strchr(WHITESPACE, c))
7333 goto finish;
7334
7335 break;
7336 }
7337
7338 (*p) ++;
7339 }
7340
7341 finish:
7342 if (!s) {
7343 *ret = NULL;
7344 return 0;
7345 }
7346
7347 s[sz] = 0;
7348 *ret = s;
7349 s = NULL;
7350
7351 return 1;
7352 }
7353
7354 int unquote_many_words(const char **p, ...) {
7355 va_list ap;
7356 char **l;
7357 int n = 0, i, c, r;
7358
7359 /* Parses a number of words from a string, stripping any
7360 * quotes if necessary. */
7361
7362 assert(p);
7363
7364 /* Count how many words are expected */
7365 va_start(ap, p);
7366 for (;;) {
7367 if (!va_arg(ap, char **))
7368 break;
7369 n++;
7370 }
7371 va_end(ap);
7372
7373 if (n <= 0)
7374 return 0;
7375
7376 /* Read all words into a temporary array */
7377 l = newa0(char*, n);
7378 for (c = 0; c < n; c++) {
7379
7380 r = unquote_first_word(p, &l[c], false);
7381 if (r < 0) {
7382 int j;
7383
7384 for (j = 0; j < c; j++)
7385 free(l[j]);
7386
7387 return r;
7388 }
7389
7390 if (r == 0)
7391 break;
7392 }
7393
7394 /* If we managed to parse all words, return them in the passed
7395 * in parameters */
7396 va_start(ap, p);
7397 for (i = 0; i < n; i++) {
7398 char **v;
7399
7400 v = va_arg(ap, char **);
7401 assert(v);
7402
7403 *v = l[i];
7404 }
7405 va_end(ap);
7406
7407 return c;
7408 }
7409
7410 int free_and_strdup(char **p, const char *s) {
7411 char *t;
7412
7413 assert(p);
7414
7415 /* Replaces a string pointer with an strdup()ed new string,
7416 * possibly freeing the old one. */
7417
7418 if (s) {
7419 t = strdup(s);
7420 if (!t)
7421 return -ENOMEM;
7422 } else
7423 t = NULL;
7424
7425 free(*p);
7426 *p = t;
7427
7428 return 0;
7429 }
7430
7431 int sethostname_idempotent(const char *s) {
7432 int r;
7433 char buf[HOST_NAME_MAX + 1] = {};
7434
7435 assert(s);
7436
7437 r = gethostname(buf, sizeof(buf));
7438 if (r < 0)
7439 return -errno;
7440
7441 if (streq(buf, s))
7442 return 0;
7443
7444 r = sethostname(s, strlen(s));
7445 if (r < 0)
7446 return -errno;
7447
7448 return 1;
7449 }
7450
7451 int ptsname_malloc(int fd, char **ret) {
7452 size_t l = 100;
7453
7454 assert(fd >= 0);
7455 assert(ret);
7456
7457 for (;;) {
7458 char *c;
7459
7460 c = new(char, l);
7461 if (!c)
7462 return -ENOMEM;
7463
7464 if (ptsname_r(fd, c, l) == 0) {
7465 *ret = c;
7466 return 0;
7467 }
7468 if (errno != ERANGE) {
7469 free(c);
7470 return -errno;
7471 }
7472
7473 free(c);
7474 l *= 2;
7475 }
7476 }
7477
7478 int openpt_in_namespace(pid_t pid, int flags) {
7479 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
7480 _cleanup_close_pair_ int pair[2] = { -1, -1 };
7481 union {
7482 struct cmsghdr cmsghdr;
7483 uint8_t buf[CMSG_SPACE(sizeof(int))];
7484 } control = {};
7485 struct msghdr mh = {
7486 .msg_control = &control,
7487 .msg_controllen = sizeof(control),
7488 };
7489 struct cmsghdr *cmsg;
7490 siginfo_t si;
7491 pid_t child;
7492 int r;
7493
7494 assert(pid > 0);
7495
7496 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
7497 if (r < 0)
7498 return r;
7499
7500 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
7501 return -errno;
7502
7503 child = fork();
7504 if (child < 0)
7505 return -errno;
7506
7507 if (child == 0) {
7508 int master;
7509
7510 pair[0] = safe_close(pair[0]);
7511
7512 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
7513 if (r < 0)
7514 _exit(EXIT_FAILURE);
7515
7516 master = posix_openpt(flags);
7517 if (master < 0)
7518 _exit(EXIT_FAILURE);
7519
7520 cmsg = CMSG_FIRSTHDR(&mh);
7521 cmsg->cmsg_level = SOL_SOCKET;
7522 cmsg->cmsg_type = SCM_RIGHTS;
7523 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
7524 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
7525
7526 mh.msg_controllen = cmsg->cmsg_len;
7527
7528 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
7529 _exit(EXIT_FAILURE);
7530
7531 _exit(EXIT_SUCCESS);
7532 }
7533
7534 pair[1] = safe_close(pair[1]);
7535
7536 r = wait_for_terminate(child, &si);
7537 if (r < 0)
7538 return r;
7539 if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
7540 return -EIO;
7541
7542 if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
7543 return -errno;
7544
7545 for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
7546 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
7547 int *fds;
7548 unsigned n_fds;
7549
7550 fds = (int*) CMSG_DATA(cmsg);
7551 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
7552
7553 if (n_fds != 1) {
7554 close_many(fds, n_fds);
7555 return -EIO;
7556 }
7557
7558 return fds[0];
7559 }
7560
7561 return -EIO;
7562 }
7563
7564 int fd_getcrtime(int fd, usec_t *usec) {
7565 uint64_t u;
7566 le64_t le;
7567 ssize_t n;
7568
7569 assert(fd >= 0);
7570 assert(usec);
7571
7572 /* Until Linux gets a real concept of birthtime/creation time,
7573 * let's fake one with xattrs */
7574
7575 n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
7576 if (n < 0)
7577 return -errno;
7578 if (n != sizeof(le))
7579 return -EIO;
7580
7581 u = le64toh(le);
7582 if (u == 0 || u == (uint64_t) -1)
7583 return -EIO;
7584
7585 *usec = (usec_t) u;
7586 return 0;
7587 }
7588
7589 int path_getcrtime(const char *p, usec_t *usec) {
7590 uint64_t u;
7591 le64_t le;
7592 ssize_t n;
7593
7594 assert(p);
7595 assert(usec);
7596
7597 n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
7598 if (n < 0)
7599 return -errno;
7600 if (n != sizeof(le))
7601 return -EIO;
7602
7603 u = le64toh(le);
7604 if (u == 0 || u == (uint64_t) -1)
7605 return -EIO;
7606
7607 *usec = (usec_t) u;
7608 return 0;
7609 }
7610
7611 int fd_setcrtime(int fd, usec_t usec) {
7612 le64_t le;
7613
7614 assert(fd >= 0);
7615
7616 le = htole64((uint64_t) usec);
7617 if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), XATTR_CREATE) < 0)
7618 return -errno;
7619
7620 return 0;
7621 }