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