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