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