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