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