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