]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/util.c
Merge pull request #1227 from intelfx/systemctl-legacy-tools-polkit
[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, uint64_t base, uint64_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", 1ULL },
2246 { "", 1ULL },
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", 1ULL },
2257 { "", 1ULL },
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 unsigned long long l, tmp;
2280 double frac = 0;
2281 char *e;
2282 unsigned i;
2283
2284 p += strspn(p, WHITESPACE);
2285 if (*p == '-')
2286 return -ERANGE;
2287
2288 errno = 0;
2289 l = strtoull(p, &e, 10);
2290 if (errno > 0)
2291 return -errno;
2292 if (e == p)
2293 return -EINVAL;
2294
2295 if (*e == '.') {
2296 e++;
2297
2298 /* strtoull() itself would accept space/+/- */
2299 if (*e >= '0' && *e <= '9') {
2300 unsigned long long l2;
2301 char *e2;
2302
2303 l2 = strtoull(e, &e2, 10);
2304 if (errno > 0)
2305 return -errno;
2306
2307 /* Ignore failure. E.g. 10.M is valid */
2308 frac = l2;
2309 for (; e < e2; e++)
2310 frac /= 10;
2311 }
2312 }
2313
2314 e += strspn(e, WHITESPACE);
2315
2316 for (i = start_pos; i < n_entries; i++)
2317 if (startswith(e, table[i].suffix))
2318 break;
2319
2320 if (i >= n_entries)
2321 return -EINVAL;
2322
2323 if (l + (frac > 0) > ULLONG_MAX / table[i].factor)
2324 return -ERANGE;
2325
2326 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
2327 if (tmp > ULLONG_MAX - r)
2328 return -ERANGE;
2329
2330 r += tmp;
2331 if ((unsigned long long) (uint64_t) r != r)
2332 return -ERANGE;
2333
2334 p = e + strlen(table[i].suffix);
2335
2336 start_pos = i + 1;
2337
2338 } while (*p);
2339
2340 *size = r;
2341
2342 return 0;
2343 }
2344
2345 bool is_device_path(const char *path) {
2346
2347 /* Returns true on paths that refer to a device, either in
2348 * sysfs or in /dev */
2349
2350 return
2351 path_startswith(path, "/dev/") ||
2352 path_startswith(path, "/sys/");
2353 }
2354
2355 int dir_is_empty(const char *path) {
2356 _cleanup_closedir_ DIR *d;
2357
2358 d = opendir(path);
2359 if (!d)
2360 return -errno;
2361
2362 for (;;) {
2363 struct dirent *de;
2364
2365 errno = 0;
2366 de = readdir(d);
2367 if (!de && errno != 0)
2368 return -errno;
2369
2370 if (!de)
2371 return 1;
2372
2373 if (!hidden_file(de->d_name))
2374 return 0;
2375 }
2376 }
2377
2378 char* dirname_malloc(const char *path) {
2379 char *d, *dir, *dir2;
2380
2381 d = strdup(path);
2382 if (!d)
2383 return NULL;
2384 dir = dirname(d);
2385 assert(dir);
2386
2387 if (dir != d) {
2388 dir2 = strdup(dir);
2389 free(d);
2390 return dir2;
2391 }
2392
2393 return dir;
2394 }
2395
2396 void rename_process(const char name[8]) {
2397 assert(name);
2398
2399 /* This is a like a poor man's setproctitle(). It changes the
2400 * comm field, argv[0], and also the glibc's internally used
2401 * name of the process. For the first one a limit of 16 chars
2402 * applies, to the second one usually one of 10 (i.e. length
2403 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2404 * "systemd"). If you pass a longer string it will be
2405 * truncated */
2406
2407 prctl(PR_SET_NAME, name);
2408
2409 if (program_invocation_name)
2410 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2411
2412 if (saved_argc > 0) {
2413 int i;
2414
2415 if (saved_argv[0])
2416 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2417
2418 for (i = 1; i < saved_argc; i++) {
2419 if (!saved_argv[i])
2420 break;
2421
2422 memzero(saved_argv[i], strlen(saved_argv[i]));
2423 }
2424 }
2425 }
2426
2427 char *lookup_uid(uid_t uid) {
2428 long bufsize;
2429 char *name;
2430 _cleanup_free_ char *buf = NULL;
2431 struct passwd pwbuf, *pw = NULL;
2432
2433 /* Shortcut things to avoid NSS lookups */
2434 if (uid == 0)
2435 return strdup("root");
2436
2437 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2438 if (bufsize <= 0)
2439 bufsize = 4096;
2440
2441 buf = malloc(bufsize);
2442 if (!buf)
2443 return NULL;
2444
2445 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2446 return strdup(pw->pw_name);
2447
2448 if (asprintf(&name, UID_FMT, uid) < 0)
2449 return NULL;
2450
2451 return name;
2452 }
2453
2454 char* getlogname_malloc(void) {
2455 uid_t uid;
2456 struct stat st;
2457
2458 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2459 uid = st.st_uid;
2460 else
2461 uid = getuid();
2462
2463 return lookup_uid(uid);
2464 }
2465
2466 char *getusername_malloc(void) {
2467 const char *e;
2468
2469 e = getenv("USER");
2470 if (e)
2471 return strdup(e);
2472
2473 return lookup_uid(getuid());
2474 }
2475
2476 bool is_temporary_fs(const struct statfs *s) {
2477 assert(s);
2478
2479 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
2480 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
2481 }
2482
2483 int fd_is_temporary_fs(int fd) {
2484 struct statfs s;
2485
2486 if (fstatfs(fd, &s) < 0)
2487 return -errno;
2488
2489 return is_temporary_fs(&s);
2490 }
2491
2492 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2493 assert(path);
2494
2495 /* Under the assumption that we are running privileged we
2496 * first change the access mode and only then hand out
2497 * ownership to avoid a window where access is too open. */
2498
2499 if (mode != MODE_INVALID)
2500 if (chmod(path, mode) < 0)
2501 return -errno;
2502
2503 if (uid != UID_INVALID || gid != GID_INVALID)
2504 if (chown(path, uid, gid) < 0)
2505 return -errno;
2506
2507 return 0;
2508 }
2509
2510 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2511 assert(fd >= 0);
2512
2513 /* Under the assumption that we are running privileged we
2514 * first change the access mode and only then hand out
2515 * ownership to avoid a window where access is too open. */
2516
2517 if (mode != MODE_INVALID)
2518 if (fchmod(fd, mode) < 0)
2519 return -errno;
2520
2521 if (uid != UID_INVALID || gid != GID_INVALID)
2522 if (fchown(fd, uid, gid) < 0)
2523 return -errno;
2524
2525 return 0;
2526 }
2527
2528 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2529 cpu_set_t *r;
2530 unsigned n = 1024;
2531
2532 /* Allocates the cpuset in the right size */
2533
2534 for (;;) {
2535 if (!(r = CPU_ALLOC(n)))
2536 return NULL;
2537
2538 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2539 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2540
2541 if (ncpus)
2542 *ncpus = n;
2543
2544 return r;
2545 }
2546
2547 CPU_FREE(r);
2548
2549 if (errno != EINVAL)
2550 return NULL;
2551
2552 n *= 2;
2553 }
2554 }
2555
2556 int files_same(const char *filea, const char *fileb) {
2557 struct stat a, b;
2558
2559 if (stat(filea, &a) < 0)
2560 return -errno;
2561
2562 if (stat(fileb, &b) < 0)
2563 return -errno;
2564
2565 return a.st_dev == b.st_dev &&
2566 a.st_ino == b.st_ino;
2567 }
2568
2569 int running_in_chroot(void) {
2570 int ret;
2571
2572 ret = files_same("/proc/1/root", "/");
2573 if (ret < 0)
2574 return ret;
2575
2576 return ret == 0;
2577 }
2578
2579 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2580 size_t x;
2581 char *r;
2582
2583 assert(s);
2584 assert(percent <= 100);
2585 assert(new_length >= 3);
2586
2587 if (old_length <= 3 || old_length <= new_length)
2588 return strndup(s, old_length);
2589
2590 r = new0(char, new_length+1);
2591 if (!r)
2592 return NULL;
2593
2594 x = (new_length * percent) / 100;
2595
2596 if (x > new_length - 3)
2597 x = new_length - 3;
2598
2599 memcpy(r, s, x);
2600 r[x] = '.';
2601 r[x+1] = '.';
2602 r[x+2] = '.';
2603 memcpy(r + x + 3,
2604 s + old_length - (new_length - x - 3),
2605 new_length - x - 3);
2606
2607 return r;
2608 }
2609
2610 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
2611 size_t x;
2612 char *e;
2613 const char *i, *j;
2614 unsigned k, len, len2;
2615
2616 assert(s);
2617 assert(percent <= 100);
2618 assert(new_length >= 3);
2619
2620 /* if no multibyte characters use ascii_ellipsize_mem for speed */
2621 if (ascii_is_valid(s))
2622 return ascii_ellipsize_mem(s, old_length, new_length, percent);
2623
2624 if (old_length <= 3 || old_length <= new_length)
2625 return strndup(s, old_length);
2626
2627 x = (new_length * percent) / 100;
2628
2629 if (x > new_length - 3)
2630 x = new_length - 3;
2631
2632 k = 0;
2633 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
2634 int c;
2635
2636 c = utf8_encoded_to_unichar(i);
2637 if (c < 0)
2638 return NULL;
2639 k += unichar_iswide(c) ? 2 : 1;
2640 }
2641
2642 if (k > x) /* last character was wide and went over quota */
2643 x ++;
2644
2645 for (j = s + old_length; k < new_length && j > i; ) {
2646 int c;
2647
2648 j = utf8_prev_char(j);
2649 c = utf8_encoded_to_unichar(j);
2650 if (c < 0)
2651 return NULL;
2652 k += unichar_iswide(c) ? 2 : 1;
2653 }
2654 assert(i <= j);
2655
2656 /* we don't actually need to ellipsize */
2657 if (i == j)
2658 return memdup(s, old_length + 1);
2659
2660 /* make space for ellipsis */
2661 j = utf8_next_char(j);
2662
2663 len = i - s;
2664 len2 = s + old_length - j;
2665 e = new(char, len + 3 + len2 + 1);
2666 if (!e)
2667 return NULL;
2668
2669 /*
2670 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
2671 old_length, new_length, x, len, len2, k);
2672 */
2673
2674 memcpy(e, s, len);
2675 e[len] = 0xe2; /* tri-dot ellipsis: … */
2676 e[len + 1] = 0x80;
2677 e[len + 2] = 0xa6;
2678
2679 memcpy(e + len + 3, j, len2 + 1);
2680
2681 return e;
2682 }
2683
2684 char *ellipsize(const char *s, size_t length, unsigned percent) {
2685 return ellipsize_mem(s, strlen(s), length, percent);
2686 }
2687
2688 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
2689 _cleanup_close_ int fd;
2690 int r;
2691
2692 assert(path);
2693
2694 if (parents)
2695 mkdir_parents(path, 0755);
2696
2697 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
2698 if (fd < 0)
2699 return -errno;
2700
2701 if (mode > 0) {
2702 r = fchmod(fd, mode);
2703 if (r < 0)
2704 return -errno;
2705 }
2706
2707 if (uid != UID_INVALID || gid != GID_INVALID) {
2708 r = fchown(fd, uid, gid);
2709 if (r < 0)
2710 return -errno;
2711 }
2712
2713 if (stamp != USEC_INFINITY) {
2714 struct timespec ts[2];
2715
2716 timespec_store(&ts[0], stamp);
2717 ts[1] = ts[0];
2718 r = futimens(fd, ts);
2719 } else
2720 r = futimens(fd, NULL);
2721 if (r < 0)
2722 return -errno;
2723
2724 return 0;
2725 }
2726
2727 int touch(const char *path) {
2728 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
2729 }
2730
2731 static char *unquote(const char *s, const char* quotes) {
2732 size_t l;
2733 assert(s);
2734
2735 /* This is rather stupid, simply removes the heading and
2736 * trailing quotes if there is one. Doesn't care about
2737 * escaping or anything.
2738 *
2739 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
2740
2741 l = strlen(s);
2742 if (l < 2)
2743 return strdup(s);
2744
2745 if (strchr(quotes, s[0]) && s[l-1] == s[0])
2746 return strndup(s+1, l-2);
2747
2748 return strdup(s);
2749 }
2750
2751 noreturn void freeze(void) {
2752
2753 /* Make sure nobody waits for us on a socket anymore */
2754 close_all_fds(NULL, 0);
2755
2756 sync();
2757
2758 for (;;)
2759 pause();
2760 }
2761
2762 bool null_or_empty(struct stat *st) {
2763 assert(st);
2764
2765 if (S_ISREG(st->st_mode) && st->st_size <= 0)
2766 return true;
2767
2768 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
2769 return true;
2770
2771 return false;
2772 }
2773
2774 int null_or_empty_path(const char *fn) {
2775 struct stat st;
2776
2777 assert(fn);
2778
2779 if (stat(fn, &st) < 0)
2780 return -errno;
2781
2782 return null_or_empty(&st);
2783 }
2784
2785 int null_or_empty_fd(int fd) {
2786 struct stat st;
2787
2788 assert(fd >= 0);
2789
2790 if (fstat(fd, &st) < 0)
2791 return -errno;
2792
2793 return null_or_empty(&st);
2794 }
2795
2796 DIR *xopendirat(int fd, const char *name, int flags) {
2797 int nfd;
2798 DIR *d;
2799
2800 assert(!(flags & O_CREAT));
2801
2802 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
2803 if (nfd < 0)
2804 return NULL;
2805
2806 d = fdopendir(nfd);
2807 if (!d) {
2808 safe_close(nfd);
2809 return NULL;
2810 }
2811
2812 return d;
2813 }
2814
2815 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
2816 _cleanup_free_ char *t = NULL, *u = NULL;
2817 size_t enc_len;
2818
2819 u = unquote(tagvalue, QUOTES);
2820 if (!u)
2821 return NULL;
2822
2823 enc_len = strlen(u) * 4 + 1;
2824 t = new(char, enc_len);
2825 if (!t)
2826 return NULL;
2827
2828 if (encode_devnode_name(u, t, enc_len) < 0)
2829 return NULL;
2830
2831 return strjoin("/dev/disk/by-", by, "/", t, NULL);
2832 }
2833
2834 char *fstab_node_to_udev_node(const char *p) {
2835 assert(p);
2836
2837 if (startswith(p, "LABEL="))
2838 return tag_to_udev_node(p+6, "label");
2839
2840 if (startswith(p, "UUID="))
2841 return tag_to_udev_node(p+5, "uuid");
2842
2843 if (startswith(p, "PARTUUID="))
2844 return tag_to_udev_node(p+9, "partuuid");
2845
2846 if (startswith(p, "PARTLABEL="))
2847 return tag_to_udev_node(p+10, "partlabel");
2848
2849 return strdup(p);
2850 }
2851
2852 bool dirent_is_file(const struct dirent *de) {
2853 assert(de);
2854
2855 if (hidden_file(de->d_name))
2856 return false;
2857
2858 if (de->d_type != DT_REG &&
2859 de->d_type != DT_LNK &&
2860 de->d_type != DT_UNKNOWN)
2861 return false;
2862
2863 return true;
2864 }
2865
2866 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
2867 assert(de);
2868
2869 if (de->d_type != DT_REG &&
2870 de->d_type != DT_LNK &&
2871 de->d_type != DT_UNKNOWN)
2872 return false;
2873
2874 if (hidden_file_allow_backup(de->d_name))
2875 return false;
2876
2877 return endswith(de->d_name, suffix);
2878 }
2879
2880 static int do_execute(char **directories, usec_t timeout, char *argv[]) {
2881 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
2882 _cleanup_set_free_free_ Set *seen = NULL;
2883 char **directory;
2884
2885 /* We fork this all off from a child process so that we can
2886 * somewhat cleanly make use of SIGALRM to set a time limit */
2887
2888 (void) reset_all_signal_handlers();
2889 (void) reset_signal_mask();
2890
2891 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2892
2893 pids = hashmap_new(NULL);
2894 if (!pids)
2895 return log_oom();
2896
2897 seen = set_new(&string_hash_ops);
2898 if (!seen)
2899 return log_oom();
2900
2901 STRV_FOREACH(directory, directories) {
2902 _cleanup_closedir_ DIR *d;
2903 struct dirent *de;
2904
2905 d = opendir(*directory);
2906 if (!d) {
2907 if (errno == ENOENT)
2908 continue;
2909
2910 return log_error_errno(errno, "Failed to open directory %s: %m", *directory);
2911 }
2912
2913 FOREACH_DIRENT(de, d, break) {
2914 _cleanup_free_ char *path = NULL;
2915 pid_t pid;
2916 int r;
2917
2918 if (!dirent_is_file(de))
2919 continue;
2920
2921 if (set_contains(seen, de->d_name)) {
2922 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory, de->d_name);
2923 continue;
2924 }
2925
2926 r = set_put_strdup(seen, de->d_name);
2927 if (r < 0)
2928 return log_oom();
2929
2930 path = strjoin(*directory, "/", de->d_name, NULL);
2931 if (!path)
2932 return log_oom();
2933
2934 if (null_or_empty_path(path)) {
2935 log_debug("%s is empty (a mask).", path);
2936 continue;
2937 }
2938
2939 pid = fork();
2940 if (pid < 0) {
2941 log_error_errno(errno, "Failed to fork: %m");
2942 continue;
2943 } else if (pid == 0) {
2944 char *_argv[2];
2945
2946 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
2947
2948 if (!argv) {
2949 _argv[0] = path;
2950 _argv[1] = NULL;
2951 argv = _argv;
2952 } else
2953 argv[0] = path;
2954
2955 execv(path, argv);
2956 return log_error_errno(errno, "Failed to execute %s: %m", path);
2957 }
2958
2959 log_debug("Spawned %s as " PID_FMT ".", path, pid);
2960
2961 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
2962 if (r < 0)
2963 return log_oom();
2964 path = NULL;
2965 }
2966 }
2967
2968 /* Abort execution of this process after the timout. We simply
2969 * rely on SIGALRM as default action terminating the process,
2970 * and turn on alarm(). */
2971
2972 if (timeout != USEC_INFINITY)
2973 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
2974
2975 while (!hashmap_isempty(pids)) {
2976 _cleanup_free_ char *path = NULL;
2977 pid_t pid;
2978
2979 pid = PTR_TO_UINT(hashmap_first_key(pids));
2980 assert(pid > 0);
2981
2982 path = hashmap_remove(pids, UINT_TO_PTR(pid));
2983 assert(path);
2984
2985 wait_for_terminate_and_warn(path, pid, true);
2986 }
2987
2988 return 0;
2989 }
2990
2991 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
2992 pid_t executor_pid;
2993 int r;
2994 char *name;
2995 char **dirs = (char**) directories;
2996
2997 assert(!strv_isempty(dirs));
2998
2999 name = basename(dirs[0]);
3000 assert(!isempty(name));
3001
3002 /* Executes all binaries in the directories in parallel and waits
3003 * for them to finish. Optionally a timeout is applied. If a file
3004 * with the same name exists in more than one directory, the
3005 * earliest one wins. */
3006
3007 executor_pid = fork();
3008 if (executor_pid < 0) {
3009 log_error_errno(errno, "Failed to fork: %m");
3010 return;
3011
3012 } else if (executor_pid == 0) {
3013 r = do_execute(dirs, timeout, argv);
3014 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
3015 }
3016
3017 wait_for_terminate_and_warn(name, executor_pid, true);
3018 }
3019
3020 bool nulstr_contains(const char*nulstr, const char *needle) {
3021 const char *i;
3022
3023 if (!nulstr)
3024 return false;
3025
3026 NULSTR_FOREACH(i, nulstr)
3027 if (streq(i, needle))
3028 return true;
3029
3030 return false;
3031 }
3032
3033 bool plymouth_running(void) {
3034 return access("/run/plymouth/pid", F_OK) >= 0;
3035 }
3036
3037 char* strshorten(char *s, size_t l) {
3038 assert(s);
3039
3040 if (l < strlen(s))
3041 s[l] = 0;
3042
3043 return s;
3044 }
3045
3046 int pipe_eof(int fd) {
3047 struct pollfd pollfd = {
3048 .fd = fd,
3049 .events = POLLIN|POLLHUP,
3050 };
3051
3052 int r;
3053
3054 r = poll(&pollfd, 1, 0);
3055 if (r < 0)
3056 return -errno;
3057
3058 if (r == 0)
3059 return 0;
3060
3061 return pollfd.revents & POLLHUP;
3062 }
3063
3064 int fd_wait_for_event(int fd, int event, usec_t t) {
3065
3066 struct pollfd pollfd = {
3067 .fd = fd,
3068 .events = event,
3069 };
3070
3071 struct timespec ts;
3072 int r;
3073
3074 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
3075 if (r < 0)
3076 return -errno;
3077
3078 if (r == 0)
3079 return 0;
3080
3081 return pollfd.revents;
3082 }
3083
3084 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3085 FILE *f;
3086 char *t;
3087 int r, fd;
3088
3089 assert(path);
3090 assert(_f);
3091 assert(_temp_path);
3092
3093 r = tempfn_xxxxxx(path, NULL, &t);
3094 if (r < 0)
3095 return r;
3096
3097 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
3098 if (fd < 0) {
3099 free(t);
3100 return -errno;
3101 }
3102
3103 f = fdopen(fd, "we");
3104 if (!f) {
3105 unlink_noerrno(t);
3106 free(t);
3107 safe_close(fd);
3108 return -errno;
3109 }
3110
3111 *_f = f;
3112 *_temp_path = t;
3113
3114 return 0;
3115 }
3116
3117 int symlink_atomic(const char *from, const char *to) {
3118 _cleanup_free_ char *t = NULL;
3119 int r;
3120
3121 assert(from);
3122 assert(to);
3123
3124 r = tempfn_random(to, NULL, &t);
3125 if (r < 0)
3126 return r;
3127
3128 if (symlink(from, t) < 0)
3129 return -errno;
3130
3131 if (rename(t, to) < 0) {
3132 unlink_noerrno(t);
3133 return -errno;
3134 }
3135
3136 return 0;
3137 }
3138
3139 int symlink_idempotent(const char *from, const char *to) {
3140 _cleanup_free_ char *p = NULL;
3141 int r;
3142
3143 assert(from);
3144 assert(to);
3145
3146 if (symlink(from, to) < 0) {
3147 if (errno != EEXIST)
3148 return -errno;
3149
3150 r = readlink_malloc(to, &p);
3151 if (r < 0)
3152 return r;
3153
3154 if (!streq(p, from))
3155 return -EINVAL;
3156 }
3157
3158 return 0;
3159 }
3160
3161 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
3162 _cleanup_free_ char *t = NULL;
3163 int r;
3164
3165 assert(path);
3166
3167 r = tempfn_random(path, NULL, &t);
3168 if (r < 0)
3169 return r;
3170
3171 if (mknod(t, mode, dev) < 0)
3172 return -errno;
3173
3174 if (rename(t, path) < 0) {
3175 unlink_noerrno(t);
3176 return -errno;
3177 }
3178
3179 return 0;
3180 }
3181
3182 int mkfifo_atomic(const char *path, mode_t mode) {
3183 _cleanup_free_ char *t = NULL;
3184 int r;
3185
3186 assert(path);
3187
3188 r = tempfn_random(path, NULL, &t);
3189 if (r < 0)
3190 return r;
3191
3192 if (mkfifo(t, mode) < 0)
3193 return -errno;
3194
3195 if (rename(t, path) < 0) {
3196 unlink_noerrno(t);
3197 return -errno;
3198 }
3199
3200 return 0;
3201 }
3202
3203 bool display_is_local(const char *display) {
3204 assert(display);
3205
3206 return
3207 display[0] == ':' &&
3208 display[1] >= '0' &&
3209 display[1] <= '9';
3210 }
3211
3212 int socket_from_display(const char *display, char **path) {
3213 size_t k;
3214 char *f, *c;
3215
3216 assert(display);
3217 assert(path);
3218
3219 if (!display_is_local(display))
3220 return -EINVAL;
3221
3222 k = strspn(display+1, "0123456789");
3223
3224 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
3225 if (!f)
3226 return -ENOMEM;
3227
3228 c = stpcpy(f, "/tmp/.X11-unix/X");
3229 memcpy(c, display+1, k);
3230 c[k] = 0;
3231
3232 *path = f;
3233
3234 return 0;
3235 }
3236
3237 int get_user_creds(
3238 const char **username,
3239 uid_t *uid, gid_t *gid,
3240 const char **home,
3241 const char **shell) {
3242
3243 struct passwd *p;
3244 uid_t u;
3245
3246 assert(username);
3247 assert(*username);
3248
3249 /* We enforce some special rules for uid=0: in order to avoid
3250 * NSS lookups for root we hardcode its data. */
3251
3252 if (streq(*username, "root") || streq(*username, "0")) {
3253 *username = "root";
3254
3255 if (uid)
3256 *uid = 0;
3257
3258 if (gid)
3259 *gid = 0;
3260
3261 if (home)
3262 *home = "/root";
3263
3264 if (shell)
3265 *shell = "/bin/sh";
3266
3267 return 0;
3268 }
3269
3270 if (parse_uid(*username, &u) >= 0) {
3271 errno = 0;
3272 p = getpwuid(u);
3273
3274 /* If there are multiple users with the same id, make
3275 * sure to leave $USER to the configured value instead
3276 * of the first occurrence in the database. However if
3277 * the uid was configured by a numeric uid, then let's
3278 * pick the real username from /etc/passwd. */
3279 if (p)
3280 *username = p->pw_name;
3281 } else {
3282 errno = 0;
3283 p = getpwnam(*username);
3284 }
3285
3286 if (!p)
3287 return errno > 0 ? -errno : -ESRCH;
3288
3289 if (uid)
3290 *uid = p->pw_uid;
3291
3292 if (gid)
3293 *gid = p->pw_gid;
3294
3295 if (home)
3296 *home = p->pw_dir;
3297
3298 if (shell)
3299 *shell = p->pw_shell;
3300
3301 return 0;
3302 }
3303
3304 char* uid_to_name(uid_t uid) {
3305 struct passwd *p;
3306 char *r;
3307
3308 if (uid == 0)
3309 return strdup("root");
3310
3311 p = getpwuid(uid);
3312 if (p)
3313 return strdup(p->pw_name);
3314
3315 if (asprintf(&r, UID_FMT, uid) < 0)
3316 return NULL;
3317
3318 return r;
3319 }
3320
3321 char* gid_to_name(gid_t gid) {
3322 struct group *p;
3323 char *r;
3324
3325 if (gid == 0)
3326 return strdup("root");
3327
3328 p = getgrgid(gid);
3329 if (p)
3330 return strdup(p->gr_name);
3331
3332 if (asprintf(&r, GID_FMT, gid) < 0)
3333 return NULL;
3334
3335 return r;
3336 }
3337
3338 int get_group_creds(const char **groupname, gid_t *gid) {
3339 struct group *g;
3340 gid_t id;
3341
3342 assert(groupname);
3343
3344 /* We enforce some special rules for gid=0: in order to avoid
3345 * NSS lookups for root we hardcode its data. */
3346
3347 if (streq(*groupname, "root") || streq(*groupname, "0")) {
3348 *groupname = "root";
3349
3350 if (gid)
3351 *gid = 0;
3352
3353 return 0;
3354 }
3355
3356 if (parse_gid(*groupname, &id) >= 0) {
3357 errno = 0;
3358 g = getgrgid(id);
3359
3360 if (g)
3361 *groupname = g->gr_name;
3362 } else {
3363 errno = 0;
3364 g = getgrnam(*groupname);
3365 }
3366
3367 if (!g)
3368 return errno > 0 ? -errno : -ESRCH;
3369
3370 if (gid)
3371 *gid = g->gr_gid;
3372
3373 return 0;
3374 }
3375
3376 int in_gid(gid_t gid) {
3377 gid_t *gids;
3378 int ngroups_max, r, i;
3379
3380 if (getgid() == gid)
3381 return 1;
3382
3383 if (getegid() == gid)
3384 return 1;
3385
3386 ngroups_max = sysconf(_SC_NGROUPS_MAX);
3387 assert(ngroups_max > 0);
3388
3389 gids = alloca(sizeof(gid_t) * ngroups_max);
3390
3391 r = getgroups(ngroups_max, gids);
3392 if (r < 0)
3393 return -errno;
3394
3395 for (i = 0; i < r; i++)
3396 if (gids[i] == gid)
3397 return 1;
3398
3399 return 0;
3400 }
3401
3402 int in_group(const char *name) {
3403 int r;
3404 gid_t gid;
3405
3406 r = get_group_creds(&name, &gid);
3407 if (r < 0)
3408 return r;
3409
3410 return in_gid(gid);
3411 }
3412
3413 int glob_exists(const char *path) {
3414 _cleanup_globfree_ glob_t g = {};
3415 int k;
3416
3417 assert(path);
3418
3419 errno = 0;
3420 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
3421
3422 if (k == GLOB_NOMATCH)
3423 return 0;
3424 else if (k == GLOB_NOSPACE)
3425 return -ENOMEM;
3426 else if (k == 0)
3427 return !strv_isempty(g.gl_pathv);
3428 else
3429 return errno ? -errno : -EIO;
3430 }
3431
3432 int glob_extend(char ***strv, const char *path) {
3433 _cleanup_globfree_ glob_t g = {};
3434 int k;
3435 char **p;
3436
3437 errno = 0;
3438 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
3439
3440 if (k == GLOB_NOMATCH)
3441 return -ENOENT;
3442 else if (k == GLOB_NOSPACE)
3443 return -ENOMEM;
3444 else if (k != 0 || strv_isempty(g.gl_pathv))
3445 return errno ? -errno : -EIO;
3446
3447 STRV_FOREACH(p, g.gl_pathv) {
3448 k = strv_extend(strv, *p);
3449 if (k < 0)
3450 break;
3451 }
3452
3453 return k;
3454 }
3455
3456 int dirent_ensure_type(DIR *d, struct dirent *de) {
3457 struct stat st;
3458
3459 assert(d);
3460 assert(de);
3461
3462 if (de->d_type != DT_UNKNOWN)
3463 return 0;
3464
3465 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
3466 return -errno;
3467
3468 de->d_type =
3469 S_ISREG(st.st_mode) ? DT_REG :
3470 S_ISDIR(st.st_mode) ? DT_DIR :
3471 S_ISLNK(st.st_mode) ? DT_LNK :
3472 S_ISFIFO(st.st_mode) ? DT_FIFO :
3473 S_ISSOCK(st.st_mode) ? DT_SOCK :
3474 S_ISCHR(st.st_mode) ? DT_CHR :
3475 S_ISBLK(st.st_mode) ? DT_BLK :
3476 DT_UNKNOWN;
3477
3478 return 0;
3479 }
3480
3481 int get_files_in_directory(const char *path, char ***list) {
3482 _cleanup_closedir_ DIR *d = NULL;
3483 size_t bufsize = 0, n = 0;
3484 _cleanup_strv_free_ char **l = NULL;
3485
3486 assert(path);
3487
3488 /* Returns all files in a directory in *list, and the number
3489 * of files as return value. If list is NULL returns only the
3490 * number. */
3491
3492 d = opendir(path);
3493 if (!d)
3494 return -errno;
3495
3496 for (;;) {
3497 struct dirent *de;
3498
3499 errno = 0;
3500 de = readdir(d);
3501 if (!de && errno != 0)
3502 return -errno;
3503 if (!de)
3504 break;
3505
3506 dirent_ensure_type(d, de);
3507
3508 if (!dirent_is_file(de))
3509 continue;
3510
3511 if (list) {
3512 /* one extra slot is needed for the terminating NULL */
3513 if (!GREEDY_REALLOC(l, bufsize, n + 2))
3514 return -ENOMEM;
3515
3516 l[n] = strdup(de->d_name);
3517 if (!l[n])
3518 return -ENOMEM;
3519
3520 l[++n] = NULL;
3521 } else
3522 n++;
3523 }
3524
3525 if (list) {
3526 *list = l;
3527 l = NULL; /* avoid freeing */
3528 }
3529
3530 return n;
3531 }
3532
3533 char *strjoin(const char *x, ...) {
3534 va_list ap;
3535 size_t l;
3536 char *r, *p;
3537
3538 va_start(ap, x);
3539
3540 if (x) {
3541 l = strlen(x);
3542
3543 for (;;) {
3544 const char *t;
3545 size_t n;
3546
3547 t = va_arg(ap, const char *);
3548 if (!t)
3549 break;
3550
3551 n = strlen(t);
3552 if (n > ((size_t) -1) - l) {
3553 va_end(ap);
3554 return NULL;
3555 }
3556
3557 l += n;
3558 }
3559 } else
3560 l = 0;
3561
3562 va_end(ap);
3563
3564 r = new(char, l+1);
3565 if (!r)
3566 return NULL;
3567
3568 if (x) {
3569 p = stpcpy(r, x);
3570
3571 va_start(ap, x);
3572
3573 for (;;) {
3574 const char *t;
3575
3576 t = va_arg(ap, const char *);
3577 if (!t)
3578 break;
3579
3580 p = stpcpy(p, t);
3581 }
3582
3583 va_end(ap);
3584 } else
3585 r[0] = 0;
3586
3587 return r;
3588 }
3589
3590 bool is_main_thread(void) {
3591 static thread_local int cached = 0;
3592
3593 if (_unlikely_(cached == 0))
3594 cached = getpid() == gettid() ? 1 : -1;
3595
3596 return cached > 0;
3597 }
3598
3599 int block_get_whole_disk(dev_t d, dev_t *ret) {
3600 char *p, *s;
3601 int r;
3602 unsigned n, m;
3603
3604 assert(ret);
3605
3606 /* If it has a queue this is good enough for us */
3607 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
3608 return -ENOMEM;
3609
3610 r = access(p, F_OK);
3611 free(p);
3612
3613 if (r >= 0) {
3614 *ret = d;
3615 return 0;
3616 }
3617
3618 /* If it is a partition find the originating device */
3619 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
3620 return -ENOMEM;
3621
3622 r = access(p, F_OK);
3623 free(p);
3624
3625 if (r < 0)
3626 return -ENOENT;
3627
3628 /* Get parent dev_t */
3629 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
3630 return -ENOMEM;
3631
3632 r = read_one_line_file(p, &s);
3633 free(p);
3634
3635 if (r < 0)
3636 return r;
3637
3638 r = sscanf(s, "%u:%u", &m, &n);
3639 free(s);
3640
3641 if (r != 2)
3642 return -EINVAL;
3643
3644 /* Only return this if it is really good enough for us. */
3645 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
3646 return -ENOMEM;
3647
3648 r = access(p, F_OK);
3649 free(p);
3650
3651 if (r >= 0) {
3652 *ret = makedev(m, n);
3653 return 0;
3654 }
3655
3656 return -ENOENT;
3657 }
3658
3659 static const char *const ioprio_class_table[] = {
3660 [IOPRIO_CLASS_NONE] = "none",
3661 [IOPRIO_CLASS_RT] = "realtime",
3662 [IOPRIO_CLASS_BE] = "best-effort",
3663 [IOPRIO_CLASS_IDLE] = "idle"
3664 };
3665
3666 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
3667
3668 static const char *const sigchld_code_table[] = {
3669 [CLD_EXITED] = "exited",
3670 [CLD_KILLED] = "killed",
3671 [CLD_DUMPED] = "dumped",
3672 [CLD_TRAPPED] = "trapped",
3673 [CLD_STOPPED] = "stopped",
3674 [CLD_CONTINUED] = "continued",
3675 };
3676
3677 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3678
3679 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
3680 [LOG_FAC(LOG_KERN)] = "kern",
3681 [LOG_FAC(LOG_USER)] = "user",
3682 [LOG_FAC(LOG_MAIL)] = "mail",
3683 [LOG_FAC(LOG_DAEMON)] = "daemon",
3684 [LOG_FAC(LOG_AUTH)] = "auth",
3685 [LOG_FAC(LOG_SYSLOG)] = "syslog",
3686 [LOG_FAC(LOG_LPR)] = "lpr",
3687 [LOG_FAC(LOG_NEWS)] = "news",
3688 [LOG_FAC(LOG_UUCP)] = "uucp",
3689 [LOG_FAC(LOG_CRON)] = "cron",
3690 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3691 [LOG_FAC(LOG_FTP)] = "ftp",
3692 [LOG_FAC(LOG_LOCAL0)] = "local0",
3693 [LOG_FAC(LOG_LOCAL1)] = "local1",
3694 [LOG_FAC(LOG_LOCAL2)] = "local2",
3695 [LOG_FAC(LOG_LOCAL3)] = "local3",
3696 [LOG_FAC(LOG_LOCAL4)] = "local4",
3697 [LOG_FAC(LOG_LOCAL5)] = "local5",
3698 [LOG_FAC(LOG_LOCAL6)] = "local6",
3699 [LOG_FAC(LOG_LOCAL7)] = "local7"
3700 };
3701
3702 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
3703
3704 static const char *const log_level_table[] = {
3705 [LOG_EMERG] = "emerg",
3706 [LOG_ALERT] = "alert",
3707 [LOG_CRIT] = "crit",
3708 [LOG_ERR] = "err",
3709 [LOG_WARNING] = "warning",
3710 [LOG_NOTICE] = "notice",
3711 [LOG_INFO] = "info",
3712 [LOG_DEBUG] = "debug"
3713 };
3714
3715 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
3716
3717 static const char* const sched_policy_table[] = {
3718 [SCHED_OTHER] = "other",
3719 [SCHED_BATCH] = "batch",
3720 [SCHED_IDLE] = "idle",
3721 [SCHED_FIFO] = "fifo",
3722 [SCHED_RR] = "rr"
3723 };
3724
3725 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
3726
3727 static const char* const rlimit_table[_RLIMIT_MAX] = {
3728 [RLIMIT_CPU] = "LimitCPU",
3729 [RLIMIT_FSIZE] = "LimitFSIZE",
3730 [RLIMIT_DATA] = "LimitDATA",
3731 [RLIMIT_STACK] = "LimitSTACK",
3732 [RLIMIT_CORE] = "LimitCORE",
3733 [RLIMIT_RSS] = "LimitRSS",
3734 [RLIMIT_NOFILE] = "LimitNOFILE",
3735 [RLIMIT_AS] = "LimitAS",
3736 [RLIMIT_NPROC] = "LimitNPROC",
3737 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3738 [RLIMIT_LOCKS] = "LimitLOCKS",
3739 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3740 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3741 [RLIMIT_NICE] = "LimitNICE",
3742 [RLIMIT_RTPRIO] = "LimitRTPRIO",
3743 [RLIMIT_RTTIME] = "LimitRTTIME"
3744 };
3745
3746 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3747
3748 static const char* const ip_tos_table[] = {
3749 [IPTOS_LOWDELAY] = "low-delay",
3750 [IPTOS_THROUGHPUT] = "throughput",
3751 [IPTOS_RELIABILITY] = "reliability",
3752 [IPTOS_LOWCOST] = "low-cost",
3753 };
3754
3755 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
3756
3757 bool kexec_loaded(void) {
3758 bool loaded = false;
3759 char *s;
3760
3761 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
3762 if (s[0] == '1')
3763 loaded = true;
3764 free(s);
3765 }
3766 return loaded;
3767 }
3768
3769 int prot_from_flags(int flags) {
3770
3771 switch (flags & O_ACCMODE) {
3772
3773 case O_RDONLY:
3774 return PROT_READ;
3775
3776 case O_WRONLY:
3777 return PROT_WRITE;
3778
3779 case O_RDWR:
3780 return PROT_READ|PROT_WRITE;
3781
3782 default:
3783 return -EINVAL;
3784 }
3785 }
3786
3787 char *format_bytes(char *buf, size_t l, uint64_t t) {
3788 unsigned i;
3789
3790 static const struct {
3791 const char *suffix;
3792 uint64_t factor;
3793 } table[] = {
3794 { "E", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3795 { "P", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3796 { "T", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3797 { "G", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
3798 { "M", UINT64_C(1024)*UINT64_C(1024) },
3799 { "K", UINT64_C(1024) },
3800 };
3801
3802 if (t == (uint64_t) -1)
3803 return NULL;
3804
3805 for (i = 0; i < ELEMENTSOF(table); i++) {
3806
3807 if (t >= table[i].factor) {
3808 snprintf(buf, l,
3809 "%" PRIu64 ".%" PRIu64 "%s",
3810 t / table[i].factor,
3811 ((t*UINT64_C(10)) / table[i].factor) % UINT64_C(10),
3812 table[i].suffix);
3813
3814 goto finish;
3815 }
3816 }
3817
3818 snprintf(buf, l, "%" PRIu64 "B", t);
3819
3820 finish:
3821 buf[l-1] = 0;
3822 return buf;
3823
3824 }
3825
3826 void* memdup(const void *p, size_t l) {
3827 void *r;
3828
3829 assert(p);
3830
3831 r = malloc(l);
3832 if (!r)
3833 return NULL;
3834
3835 memcpy(r, p, l);
3836 return r;
3837 }
3838
3839 int fd_inc_sndbuf(int fd, size_t n) {
3840 int r, value;
3841 socklen_t l = sizeof(value);
3842
3843 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
3844 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3845 return 0;
3846
3847 /* If we have the privileges we will ignore the kernel limit. */
3848
3849 value = (int) n;
3850 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
3851 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
3852 return -errno;
3853
3854 return 1;
3855 }
3856
3857 int fd_inc_rcvbuf(int fd, size_t n) {
3858 int r, value;
3859 socklen_t l = sizeof(value);
3860
3861 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
3862 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
3863 return 0;
3864
3865 /* If we have the privileges we will ignore the kernel limit. */
3866
3867 value = (int) n;
3868 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
3869 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
3870 return -errno;
3871 return 1;
3872 }
3873
3874 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
3875 bool stdout_is_tty, stderr_is_tty;
3876 pid_t parent_pid, agent_pid;
3877 sigset_t ss, saved_ss;
3878 unsigned n, i;
3879 va_list ap;
3880 char **l;
3881
3882 assert(pid);
3883 assert(path);
3884
3885 /* Spawns a temporary TTY agent, making sure it goes away when
3886 * we go away */
3887
3888 parent_pid = getpid();
3889
3890 /* First we temporarily block all signals, so that the new
3891 * child has them blocked initially. This way, we can be sure
3892 * that SIGTERMs are not lost we might send to the agent. */
3893 assert_se(sigfillset(&ss) >= 0);
3894 assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
3895
3896 agent_pid = fork();
3897 if (agent_pid < 0) {
3898 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3899 return -errno;
3900 }
3901
3902 if (agent_pid != 0) {
3903 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
3904 *pid = agent_pid;
3905 return 0;
3906 }
3907
3908 /* In the child:
3909 *
3910 * Make sure the agent goes away when the parent dies */
3911 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
3912 _exit(EXIT_FAILURE);
3913
3914 /* Make sure we actually can kill the agent, if we need to, in
3915 * case somebody invoked us from a shell script that trapped
3916 * SIGTERM or so... */
3917 (void) reset_all_signal_handlers();
3918 (void) reset_signal_mask();
3919
3920 /* Check whether our parent died before we were able
3921 * to set the death signal and unblock the signals */
3922 if (getppid() != parent_pid)
3923 _exit(EXIT_SUCCESS);
3924
3925 /* Don't leak fds to the agent */
3926 close_all_fds(except, n_except);
3927
3928 stdout_is_tty = isatty(STDOUT_FILENO);
3929 stderr_is_tty = isatty(STDERR_FILENO);
3930
3931 if (!stdout_is_tty || !stderr_is_tty) {
3932 int fd;
3933
3934 /* Detach from stdout/stderr. and reopen
3935 * /dev/tty for them. This is important to
3936 * ensure that when systemctl is started via
3937 * popen() or a similar call that expects to
3938 * read EOF we actually do generate EOF and
3939 * not delay this indefinitely by because we
3940 * keep an unused copy of stdin around. */
3941 fd = open("/dev/tty", O_WRONLY);
3942 if (fd < 0) {
3943 log_error_errno(errno, "Failed to open /dev/tty: %m");
3944 _exit(EXIT_FAILURE);
3945 }
3946
3947 if (!stdout_is_tty)
3948 dup2(fd, STDOUT_FILENO);
3949
3950 if (!stderr_is_tty)
3951 dup2(fd, STDERR_FILENO);
3952
3953 if (fd > 2)
3954 close(fd);
3955 }
3956
3957 /* Count arguments */
3958 va_start(ap, path);
3959 for (n = 0; va_arg(ap, char*); n++)
3960 ;
3961 va_end(ap);
3962
3963 /* Allocate strv */
3964 l = alloca(sizeof(char *) * (n + 1));
3965
3966 /* Fill in arguments */
3967 va_start(ap, path);
3968 for (i = 0; i <= n; i++)
3969 l[i] = va_arg(ap, char*);
3970 va_end(ap);
3971
3972 execv(path, l);
3973 _exit(EXIT_FAILURE);
3974 }
3975
3976 int setrlimit_closest(int resource, const struct rlimit *rlim) {
3977 struct rlimit highest, fixed;
3978
3979 assert(rlim);
3980
3981 if (setrlimit(resource, rlim) >= 0)
3982 return 0;
3983
3984 if (errno != EPERM)
3985 return -errno;
3986
3987 /* So we failed to set the desired setrlimit, then let's try
3988 * to get as close as we can */
3989 assert_se(getrlimit(resource, &highest) == 0);
3990
3991 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
3992 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
3993
3994 if (setrlimit(resource, &fixed) < 0)
3995 return -errno;
3996
3997 return 0;
3998 }
3999
4000 bool http_etag_is_valid(const char *etag) {
4001 if (isempty(etag))
4002 return false;
4003
4004 if (!endswith(etag, "\""))
4005 return false;
4006
4007 if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
4008 return false;
4009
4010 return true;
4011 }
4012
4013 bool http_url_is_valid(const char *url) {
4014 const char *p;
4015
4016 if (isempty(url))
4017 return false;
4018
4019 p = startswith(url, "http://");
4020 if (!p)
4021 p = startswith(url, "https://");
4022 if (!p)
4023 return false;
4024
4025 if (isempty(p))
4026 return false;
4027
4028 return ascii_is_valid(p);
4029 }
4030
4031 bool documentation_url_is_valid(const char *url) {
4032 const char *p;
4033
4034 if (isempty(url))
4035 return false;
4036
4037 if (http_url_is_valid(url))
4038 return true;
4039
4040 p = startswith(url, "file:/");
4041 if (!p)
4042 p = startswith(url, "info:");
4043 if (!p)
4044 p = startswith(url, "man:");
4045
4046 if (isempty(p))
4047 return false;
4048
4049 return ascii_is_valid(p);
4050 }
4051
4052 bool in_initrd(void) {
4053 static int saved = -1;
4054 struct statfs s;
4055
4056 if (saved >= 0)
4057 return saved;
4058
4059 /* We make two checks here:
4060 *
4061 * 1. the flag file /etc/initrd-release must exist
4062 * 2. the root file system must be a memory file system
4063 *
4064 * The second check is extra paranoia, since misdetecting an
4065 * initrd can have bad bad consequences due the initrd
4066 * emptying when transititioning to the main systemd.
4067 */
4068
4069 saved = access("/etc/initrd-release", F_OK) >= 0 &&
4070 statfs("/", &s) >= 0 &&
4071 is_temporary_fs(&s);
4072
4073 return saved;
4074 }
4075
4076 int get_home_dir(char **_h) {
4077 struct passwd *p;
4078 const char *e;
4079 char *h;
4080 uid_t u;
4081
4082 assert(_h);
4083
4084 /* Take the user specified one */
4085 e = secure_getenv("HOME");
4086 if (e && path_is_absolute(e)) {
4087 h = strdup(e);
4088 if (!h)
4089 return -ENOMEM;
4090
4091 *_h = h;
4092 return 0;
4093 }
4094
4095 /* Hardcode home directory for root to avoid NSS */
4096 u = getuid();
4097 if (u == 0) {
4098 h = strdup("/root");
4099 if (!h)
4100 return -ENOMEM;
4101
4102 *_h = h;
4103 return 0;
4104 }
4105
4106 /* Check the database... */
4107 errno = 0;
4108 p = getpwuid(u);
4109 if (!p)
4110 return errno > 0 ? -errno : -ESRCH;
4111
4112 if (!path_is_absolute(p->pw_dir))
4113 return -EINVAL;
4114
4115 h = strdup(p->pw_dir);
4116 if (!h)
4117 return -ENOMEM;
4118
4119 *_h = h;
4120 return 0;
4121 }
4122
4123 int get_shell(char **_s) {
4124 struct passwd *p;
4125 const char *e;
4126 char *s;
4127 uid_t u;
4128
4129 assert(_s);
4130
4131 /* Take the user specified one */
4132 e = getenv("SHELL");
4133 if (e) {
4134 s = strdup(e);
4135 if (!s)
4136 return -ENOMEM;
4137
4138 *_s = s;
4139 return 0;
4140 }
4141
4142 /* Hardcode home directory for root to avoid NSS */
4143 u = getuid();
4144 if (u == 0) {
4145 s = strdup("/bin/sh");
4146 if (!s)
4147 return -ENOMEM;
4148
4149 *_s = s;
4150 return 0;
4151 }
4152
4153 /* Check the database... */
4154 errno = 0;
4155 p = getpwuid(u);
4156 if (!p)
4157 return errno > 0 ? -errno : -ESRCH;
4158
4159 if (!path_is_absolute(p->pw_shell))
4160 return -EINVAL;
4161
4162 s = strdup(p->pw_shell);
4163 if (!s)
4164 return -ENOMEM;
4165
4166 *_s = s;
4167 return 0;
4168 }
4169
4170 bool filename_is_valid(const char *p) {
4171
4172 if (isempty(p))
4173 return false;
4174
4175 if (strchr(p, '/'))
4176 return false;
4177
4178 if (streq(p, "."))
4179 return false;
4180
4181 if (streq(p, ".."))
4182 return false;
4183
4184 if (strlen(p) > FILENAME_MAX)
4185 return false;
4186
4187 return true;
4188 }
4189
4190 bool string_is_safe(const char *p) {
4191 const char *t;
4192
4193 if (!p)
4194 return false;
4195
4196 for (t = p; *t; t++) {
4197 if (*t > 0 && *t < ' ')
4198 return false;
4199
4200 if (strchr("\\\"\'\x7f", *t))
4201 return false;
4202 }
4203
4204 return true;
4205 }
4206
4207 /**
4208 * Check if a string contains control characters. If 'ok' is non-NULL
4209 * it may be a string containing additional CCs to be considered OK.
4210 */
4211 bool string_has_cc(const char *p, const char *ok) {
4212 const char *t;
4213
4214 assert(p);
4215
4216 for (t = p; *t; t++) {
4217 if (ok && strchr(ok, *t))
4218 continue;
4219
4220 if (*t > 0 && *t < ' ')
4221 return true;
4222
4223 if (*t == 127)
4224 return true;
4225 }
4226
4227 return false;
4228 }
4229
4230 bool path_is_safe(const char *p) {
4231
4232 if (isempty(p))
4233 return false;
4234
4235 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
4236 return false;
4237
4238 if (strlen(p)+1 > PATH_MAX)
4239 return false;
4240
4241 /* The following two checks are not really dangerous, but hey, they still are confusing */
4242 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
4243 return false;
4244
4245 if (strstr(p, "//"))
4246 return false;
4247
4248 return true;
4249 }
4250
4251 /* hey glibc, APIs with callbacks without a user pointer are so useless */
4252 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
4253 int (*compar) (const void *, const void *, void *), void *arg) {
4254 size_t l, u, idx;
4255 const void *p;
4256 int comparison;
4257
4258 l = 0;
4259 u = nmemb;
4260 while (l < u) {
4261 idx = (l + u) / 2;
4262 p = (void *)(((const char *) base) + (idx * size));
4263 comparison = compar(key, p, arg);
4264 if (comparison < 0)
4265 u = idx;
4266 else if (comparison > 0)
4267 l = idx + 1;
4268 else
4269 return (void *)p;
4270 }
4271 return NULL;
4272 }
4273
4274 void init_gettext(void) {
4275 setlocale(LC_ALL, "");
4276 textdomain(GETTEXT_PACKAGE);
4277 }
4278
4279 bool is_locale_utf8(void) {
4280 const char *set;
4281 static int cached_answer = -1;
4282
4283 if (cached_answer >= 0)
4284 goto out;
4285
4286 if (!setlocale(LC_ALL, "")) {
4287 cached_answer = true;
4288 goto out;
4289 }
4290
4291 set = nl_langinfo(CODESET);
4292 if (!set) {
4293 cached_answer = true;
4294 goto out;
4295 }
4296
4297 if (streq(set, "UTF-8")) {
4298 cached_answer = true;
4299 goto out;
4300 }
4301
4302 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
4303 * unset and everything can do to UTF-8 nowadays. */
4304 set = setlocale(LC_CTYPE, NULL);
4305 if (!set) {
4306 cached_answer = true;
4307 goto out;
4308 }
4309
4310 /* Check result, but ignore the result if C was set
4311 * explicitly. */
4312 cached_answer =
4313 STR_IN_SET(set, "C", "POSIX") &&
4314 !getenv("LC_ALL") &&
4315 !getenv("LC_CTYPE") &&
4316 !getenv("LANG");
4317
4318 out:
4319 return (bool) cached_answer;
4320 }
4321
4322 const char *draw_special_char(DrawSpecialChar ch) {
4323 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
4324
4325 /* UTF-8 */ {
4326 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
4327 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
4328 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
4329 [DRAW_TREE_SPACE] = " ", /* */
4330 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
4331 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
4332 [DRAW_ARROW] = "\342\206\222", /* → */
4333 [DRAW_DASH] = "\342\200\223", /* – */
4334 },
4335
4336 /* ASCII fallback */ {
4337 [DRAW_TREE_VERTICAL] = "| ",
4338 [DRAW_TREE_BRANCH] = "|-",
4339 [DRAW_TREE_RIGHT] = "`-",
4340 [DRAW_TREE_SPACE] = " ",
4341 [DRAW_TRIANGULAR_BULLET] = ">",
4342 [DRAW_BLACK_CIRCLE] = "*",
4343 [DRAW_ARROW] = "->",
4344 [DRAW_DASH] = "-",
4345 }
4346 };
4347
4348 return draw_table[!is_locale_utf8()][ch];
4349 }
4350
4351 char *strreplace(const char *text, const char *old_string, const char *new_string) {
4352 const char *f;
4353 char *t, *r;
4354 size_t l, old_len, new_len;
4355
4356 assert(text);
4357 assert(old_string);
4358 assert(new_string);
4359
4360 old_len = strlen(old_string);
4361 new_len = strlen(new_string);
4362
4363 l = strlen(text);
4364 r = new(char, l+1);
4365 if (!r)
4366 return NULL;
4367
4368 f = text;
4369 t = r;
4370 while (*f) {
4371 char *a;
4372 size_t d, nl;
4373
4374 if (!startswith(f, old_string)) {
4375 *(t++) = *(f++);
4376 continue;
4377 }
4378
4379 d = t - r;
4380 nl = l - old_len + new_len;
4381 a = realloc(r, nl + 1);
4382 if (!a)
4383 goto oom;
4384
4385 l = nl;
4386 r = a;
4387 t = r + d;
4388
4389 t = stpcpy(t, new_string);
4390 f += old_len;
4391 }
4392
4393 *t = 0;
4394 return r;
4395
4396 oom:
4397 free(r);
4398 return NULL;
4399 }
4400
4401 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
4402 const char *i, *begin = NULL;
4403 enum {
4404 STATE_OTHER,
4405 STATE_ESCAPE,
4406 STATE_BRACKET
4407 } state = STATE_OTHER;
4408 char *obuf = NULL;
4409 size_t osz = 0, isz;
4410 FILE *f;
4411
4412 assert(ibuf);
4413 assert(*ibuf);
4414
4415 /* Strips ANSI color and replaces TABs by 8 spaces */
4416
4417 isz = _isz ? *_isz : strlen(*ibuf);
4418
4419 f = open_memstream(&obuf, &osz);
4420 if (!f)
4421 return NULL;
4422
4423 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
4424
4425 switch (state) {
4426
4427 case STATE_OTHER:
4428 if (i >= *ibuf + isz) /* EOT */
4429 break;
4430 else if (*i == '\x1B')
4431 state = STATE_ESCAPE;
4432 else if (*i == '\t')
4433 fputs(" ", f);
4434 else
4435 fputc(*i, f);
4436 break;
4437
4438 case STATE_ESCAPE:
4439 if (i >= *ibuf + isz) { /* EOT */
4440 fputc('\x1B', f);
4441 break;
4442 } else if (*i == '[') {
4443 state = STATE_BRACKET;
4444 begin = i + 1;
4445 } else {
4446 fputc('\x1B', f);
4447 fputc(*i, f);
4448 state = STATE_OTHER;
4449 }
4450
4451 break;
4452
4453 case STATE_BRACKET:
4454
4455 if (i >= *ibuf + isz || /* EOT */
4456 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
4457 fputc('\x1B', f);
4458 fputc('[', f);
4459 state = STATE_OTHER;
4460 i = begin-1;
4461 } else if (*i == 'm')
4462 state = STATE_OTHER;
4463 break;
4464 }
4465 }
4466
4467 if (ferror(f)) {
4468 fclose(f);
4469 free(obuf);
4470 return NULL;
4471 }
4472
4473 fclose(f);
4474
4475 free(*ibuf);
4476 *ibuf = obuf;
4477
4478 if (_isz)
4479 *_isz = osz;
4480
4481 return obuf;
4482 }
4483
4484 int on_ac_power(void) {
4485 bool found_offline = false, found_online = false;
4486 _cleanup_closedir_ DIR *d = NULL;
4487
4488 d = opendir("/sys/class/power_supply");
4489 if (!d)
4490 return errno == ENOENT ? true : -errno;
4491
4492 for (;;) {
4493 struct dirent *de;
4494 _cleanup_close_ int fd = -1, device = -1;
4495 char contents[6];
4496 ssize_t n;
4497
4498 errno = 0;
4499 de = readdir(d);
4500 if (!de && errno != 0)
4501 return -errno;
4502
4503 if (!de)
4504 break;
4505
4506 if (hidden_file(de->d_name))
4507 continue;
4508
4509 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
4510 if (device < 0) {
4511 if (errno == ENOENT || errno == ENOTDIR)
4512 continue;
4513
4514 return -errno;
4515 }
4516
4517 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
4518 if (fd < 0) {
4519 if (errno == ENOENT)
4520 continue;
4521
4522 return -errno;
4523 }
4524
4525 n = read(fd, contents, sizeof(contents));
4526 if (n < 0)
4527 return -errno;
4528
4529 if (n != 6 || memcmp(contents, "Mains\n", 6))
4530 continue;
4531
4532 safe_close(fd);
4533 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
4534 if (fd < 0) {
4535 if (errno == ENOENT)
4536 continue;
4537
4538 return -errno;
4539 }
4540
4541 n = read(fd, contents, sizeof(contents));
4542 if (n < 0)
4543 return -errno;
4544
4545 if (n != 2 || contents[1] != '\n')
4546 return -EIO;
4547
4548 if (contents[0] == '1') {
4549 found_online = true;
4550 break;
4551 } else if (contents[0] == '0')
4552 found_offline = true;
4553 else
4554 return -EIO;
4555 }
4556
4557 return found_online || !found_offline;
4558 }
4559
4560 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
4561 char **i;
4562
4563 assert(path);
4564 assert(mode);
4565 assert(_f);
4566
4567 if (!path_strv_resolve_uniq(search, root))
4568 return -ENOMEM;
4569
4570 STRV_FOREACH(i, search) {
4571 _cleanup_free_ char *p = NULL;
4572 FILE *f;
4573
4574 if (root)
4575 p = strjoin(root, *i, "/", path, NULL);
4576 else
4577 p = strjoin(*i, "/", path, NULL);
4578 if (!p)
4579 return -ENOMEM;
4580
4581 f = fopen(p, mode);
4582 if (f) {
4583 *_f = f;
4584 return 0;
4585 }
4586
4587 if (errno != ENOENT)
4588 return -errno;
4589 }
4590
4591 return -ENOENT;
4592 }
4593
4594 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
4595 _cleanup_strv_free_ char **copy = NULL;
4596
4597 assert(path);
4598 assert(mode);
4599 assert(_f);
4600
4601 if (path_is_absolute(path)) {
4602 FILE *f;
4603
4604 f = fopen(path, mode);
4605 if (f) {
4606 *_f = f;
4607 return 0;
4608 }
4609
4610 return -errno;
4611 }
4612
4613 copy = strv_copy((char**) search);
4614 if (!copy)
4615 return -ENOMEM;
4616
4617 return search_and_fopen_internal(path, mode, root, copy, _f);
4618 }
4619
4620 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
4621 _cleanup_strv_free_ char **s = NULL;
4622
4623 if (path_is_absolute(path)) {
4624 FILE *f;
4625
4626 f = fopen(path, mode);
4627 if (f) {
4628 *_f = f;
4629 return 0;
4630 }
4631
4632 return -errno;
4633 }
4634
4635 s = strv_split_nulstr(search);
4636 if (!s)
4637 return -ENOMEM;
4638
4639 return search_and_fopen_internal(path, mode, root, s, _f);
4640 }
4641
4642 char *strextend(char **x, ...) {
4643 va_list ap;
4644 size_t f, l;
4645 char *r, *p;
4646
4647 assert(x);
4648
4649 l = f = *x ? strlen(*x) : 0;
4650
4651 va_start(ap, x);
4652 for (;;) {
4653 const char *t;
4654 size_t n;
4655
4656 t = va_arg(ap, const char *);
4657 if (!t)
4658 break;
4659
4660 n = strlen(t);
4661 if (n > ((size_t) -1) - l) {
4662 va_end(ap);
4663 return NULL;
4664 }
4665
4666 l += n;
4667 }
4668 va_end(ap);
4669
4670 r = realloc(*x, l+1);
4671 if (!r)
4672 return NULL;
4673
4674 p = r + f;
4675
4676 va_start(ap, x);
4677 for (;;) {
4678 const char *t;
4679
4680 t = va_arg(ap, const char *);
4681 if (!t)
4682 break;
4683
4684 p = stpcpy(p, t);
4685 }
4686 va_end(ap);
4687
4688 *p = 0;
4689 *x = r;
4690
4691 return r + l;
4692 }
4693
4694 char *strrep(const char *s, unsigned n) {
4695 size_t l;
4696 char *r, *p;
4697 unsigned i;
4698
4699 assert(s);
4700
4701 l = strlen(s);
4702 p = r = malloc(l * n + 1);
4703 if (!r)
4704 return NULL;
4705
4706 for (i = 0; i < n; i++)
4707 p = stpcpy(p, s);
4708
4709 *p = 0;
4710 return r;
4711 }
4712
4713 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
4714 size_t a, newalloc;
4715 void *q;
4716
4717 assert(p);
4718 assert(allocated);
4719
4720 if (*allocated >= need)
4721 return *p;
4722
4723 newalloc = MAX(need * 2, 64u / size);
4724 a = newalloc * size;
4725
4726 /* check for overflows */
4727 if (a < size * need)
4728 return NULL;
4729
4730 q = realloc(*p, a);
4731 if (!q)
4732 return NULL;
4733
4734 *p = q;
4735 *allocated = newalloc;
4736 return q;
4737 }
4738
4739 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
4740 size_t prev;
4741 uint8_t *q;
4742
4743 assert(p);
4744 assert(allocated);
4745
4746 prev = *allocated;
4747
4748 q = greedy_realloc(p, allocated, need, size);
4749 if (!q)
4750 return NULL;
4751
4752 if (*allocated > prev)
4753 memzero(q + prev * size, (*allocated - prev) * size);
4754
4755 return q;
4756 }
4757
4758 bool id128_is_valid(const char *s) {
4759 size_t i, l;
4760
4761 l = strlen(s);
4762 if (l == 32) {
4763
4764 /* Simple formatted 128bit hex string */
4765
4766 for (i = 0; i < l; i++) {
4767 char c = s[i];
4768
4769 if (!(c >= '0' && c <= '9') &&
4770 !(c >= 'a' && c <= 'z') &&
4771 !(c >= 'A' && c <= 'Z'))
4772 return false;
4773 }
4774
4775 } else if (l == 36) {
4776
4777 /* Formatted UUID */
4778
4779 for (i = 0; i < l; i++) {
4780 char c = s[i];
4781
4782 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
4783 if (c != '-')
4784 return false;
4785 } else {
4786 if (!(c >= '0' && c <= '9') &&
4787 !(c >= 'a' && c <= 'z') &&
4788 !(c >= 'A' && c <= 'Z'))
4789 return false;
4790 }
4791 }
4792
4793 } else
4794 return false;
4795
4796 return true;
4797 }
4798
4799 int split_pair(const char *s, const char *sep, char **l, char **r) {
4800 char *x, *a, *b;
4801
4802 assert(s);
4803 assert(sep);
4804 assert(l);
4805 assert(r);
4806
4807 if (isempty(sep))
4808 return -EINVAL;
4809
4810 x = strstr(s, sep);
4811 if (!x)
4812 return -EINVAL;
4813
4814 a = strndup(s, x - s);
4815 if (!a)
4816 return -ENOMEM;
4817
4818 b = strdup(x + strlen(sep));
4819 if (!b) {
4820 free(a);
4821 return -ENOMEM;
4822 }
4823
4824 *l = a;
4825 *r = b;
4826
4827 return 0;
4828 }
4829
4830 int shall_restore_state(void) {
4831 _cleanup_free_ char *value = NULL;
4832 int r;
4833
4834 r = get_proc_cmdline_key("systemd.restore_state=", &value);
4835 if (r < 0)
4836 return r;
4837 if (r == 0)
4838 return true;
4839
4840 return parse_boolean(value) != 0;
4841 }
4842
4843 int proc_cmdline(char **ret) {
4844 assert(ret);
4845
4846 if (detect_container() > 0)
4847 return get_process_cmdline(1, 0, false, ret);
4848 else
4849 return read_one_line_file("/proc/cmdline", ret);
4850 }
4851
4852 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
4853 _cleanup_free_ char *line = NULL;
4854 const char *p;
4855 int r;
4856
4857 assert(parse_item);
4858
4859 r = proc_cmdline(&line);
4860 if (r < 0)
4861 return r;
4862
4863 p = line;
4864 for (;;) {
4865 _cleanup_free_ char *word = NULL;
4866 char *value = NULL;
4867
4868 r = extract_first_word(&p, &word, NULL, EXTRACT_QUOTES|EXTRACT_RELAX);
4869 if (r < 0)
4870 return r;
4871 if (r == 0)
4872 break;
4873
4874 /* Filter out arguments that are intended only for the
4875 * initrd */
4876 if (!in_initrd() && startswith(word, "rd."))
4877 continue;
4878
4879 value = strchr(word, '=');
4880 if (value)
4881 *(value++) = 0;
4882
4883 r = parse_item(word, value);
4884 if (r < 0)
4885 return r;
4886 }
4887
4888 return 0;
4889 }
4890
4891 int get_proc_cmdline_key(const char *key, char **value) {
4892 _cleanup_free_ char *line = NULL, *ret = NULL;
4893 bool found = false;
4894 const char *p;
4895 int r;
4896
4897 assert(key);
4898
4899 r = proc_cmdline(&line);
4900 if (r < 0)
4901 return r;
4902
4903 p = line;
4904 for (;;) {
4905 _cleanup_free_ char *word = NULL;
4906 const char *e;
4907
4908 r = extract_first_word(&p, &word, NULL, EXTRACT_QUOTES|EXTRACT_RELAX);
4909 if (r < 0)
4910 return r;
4911 if (r == 0)
4912 break;
4913
4914 /* Filter out arguments that are intended only for the
4915 * initrd */
4916 if (!in_initrd() && startswith(word, "rd."))
4917 continue;
4918
4919 if (value) {
4920 e = startswith(word, key);
4921 if (!e)
4922 continue;
4923
4924 r = free_and_strdup(&ret, e);
4925 if (r < 0)
4926 return r;
4927
4928 found = true;
4929 } else {
4930 if (streq(word, key))
4931 found = true;
4932 }
4933 }
4934
4935 if (value) {
4936 *value = ret;
4937 ret = NULL;
4938 }
4939
4940 return found;
4941
4942 }
4943
4944 int container_get_leader(const char *machine, pid_t *pid) {
4945 _cleanup_free_ char *s = NULL, *class = NULL;
4946 const char *p;
4947 pid_t leader;
4948 int r;
4949
4950 assert(machine);
4951 assert(pid);
4952
4953 if (!machine_name_is_valid(machine))
4954 return -EINVAL;
4955
4956 p = strjoina("/run/systemd/machines/", machine);
4957 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
4958 if (r == -ENOENT)
4959 return -EHOSTDOWN;
4960 if (r < 0)
4961 return r;
4962 if (!s)
4963 return -EIO;
4964
4965 if (!streq_ptr(class, "container"))
4966 return -EIO;
4967
4968 r = parse_pid(s, &leader);
4969 if (r < 0)
4970 return r;
4971 if (leader <= 1)
4972 return -EIO;
4973
4974 *pid = leader;
4975 return 0;
4976 }
4977
4978 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *userns_fd, int *root_fd) {
4979 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1, usernsfd = -1;
4980 int rfd = -1;
4981
4982 assert(pid >= 0);
4983
4984 if (mntns_fd) {
4985 const char *mntns;
4986
4987 mntns = procfs_file_alloca(pid, "ns/mnt");
4988 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4989 if (mntnsfd < 0)
4990 return -errno;
4991 }
4992
4993 if (pidns_fd) {
4994 const char *pidns;
4995
4996 pidns = procfs_file_alloca(pid, "ns/pid");
4997 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
4998 if (pidnsfd < 0)
4999 return -errno;
5000 }
5001
5002 if (netns_fd) {
5003 const char *netns;
5004
5005 netns = procfs_file_alloca(pid, "ns/net");
5006 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
5007 if (netnsfd < 0)
5008 return -errno;
5009 }
5010
5011 if (userns_fd) {
5012 const char *userns;
5013
5014 userns = procfs_file_alloca(pid, "ns/user");
5015 usernsfd = open(userns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
5016 if (usernsfd < 0 && errno != ENOENT)
5017 return -errno;
5018 }
5019
5020 if (root_fd) {
5021 const char *root;
5022
5023 root = procfs_file_alloca(pid, "root");
5024 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
5025 if (rfd < 0)
5026 return -errno;
5027 }
5028
5029 if (pidns_fd)
5030 *pidns_fd = pidnsfd;
5031
5032 if (mntns_fd)
5033 *mntns_fd = mntnsfd;
5034
5035 if (netns_fd)
5036 *netns_fd = netnsfd;
5037
5038 if (userns_fd)
5039 *userns_fd = usernsfd;
5040
5041 if (root_fd)
5042 *root_fd = rfd;
5043
5044 pidnsfd = mntnsfd = netnsfd = usernsfd = -1;
5045
5046 return 0;
5047 }
5048
5049 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int userns_fd, int root_fd) {
5050 if (userns_fd >= 0) {
5051 /* Can't setns to your own userns, since then you could
5052 * escalate from non-root to root in your own namespace, so
5053 * check if namespaces equal before attempting to enter. */
5054 _cleanup_free_ char *userns_fd_path = NULL;
5055 int r;
5056 if (asprintf(&userns_fd_path, "/proc/self/fd/%d", userns_fd) < 0)
5057 return -ENOMEM;
5058
5059 r = files_same(userns_fd_path, "/proc/self/ns/user");
5060 if (r < 0)
5061 return r;
5062 if (r)
5063 userns_fd = -1;
5064 }
5065
5066 if (pidns_fd >= 0)
5067 if (setns(pidns_fd, CLONE_NEWPID) < 0)
5068 return -errno;
5069
5070 if (mntns_fd >= 0)
5071 if (setns(mntns_fd, CLONE_NEWNS) < 0)
5072 return -errno;
5073
5074 if (netns_fd >= 0)
5075 if (setns(netns_fd, CLONE_NEWNET) < 0)
5076 return -errno;
5077
5078 if (userns_fd >= 0)
5079 if (setns(userns_fd, CLONE_NEWUSER) < 0)
5080 return -errno;
5081
5082 if (root_fd >= 0) {
5083 if (fchdir(root_fd) < 0)
5084 return -errno;
5085
5086 if (chroot(".") < 0)
5087 return -errno;
5088 }
5089
5090 return reset_uid_gid();
5091 }
5092
5093 int getpeercred(int fd, struct ucred *ucred) {
5094 socklen_t n = sizeof(struct ucred);
5095 struct ucred u;
5096 int r;
5097
5098 assert(fd >= 0);
5099 assert(ucred);
5100
5101 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
5102 if (r < 0)
5103 return -errno;
5104
5105 if (n != sizeof(struct ucred))
5106 return -EIO;
5107
5108 /* Check if the data is actually useful and not suppressed due
5109 * to namespacing issues */
5110 if (u.pid <= 0)
5111 return -ENODATA;
5112 if (u.uid == UID_INVALID)
5113 return -ENODATA;
5114 if (u.gid == GID_INVALID)
5115 return -ENODATA;
5116
5117 *ucred = u;
5118 return 0;
5119 }
5120
5121 int getpeersec(int fd, char **ret) {
5122 socklen_t n = 64;
5123 char *s;
5124 int r;
5125
5126 assert(fd >= 0);
5127 assert(ret);
5128
5129 s = new0(char, n);
5130 if (!s)
5131 return -ENOMEM;
5132
5133 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
5134 if (r < 0) {
5135 free(s);
5136
5137 if (errno != ERANGE)
5138 return -errno;
5139
5140 s = new0(char, n);
5141 if (!s)
5142 return -ENOMEM;
5143
5144 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
5145 if (r < 0) {
5146 free(s);
5147 return -errno;
5148 }
5149 }
5150
5151 if (isempty(s)) {
5152 free(s);
5153 return -EOPNOTSUPP;
5154 }
5155
5156 *ret = s;
5157 return 0;
5158 }
5159
5160 /* This is much like like mkostemp() but is subject to umask(). */
5161 int mkostemp_safe(char *pattern, int flags) {
5162 _cleanup_umask_ mode_t u;
5163 int fd;
5164
5165 assert(pattern);
5166
5167 u = umask(077);
5168
5169 fd = mkostemp(pattern, flags);
5170 if (fd < 0)
5171 return -errno;
5172
5173 return fd;
5174 }
5175
5176 int open_tmpfile(const char *path, int flags) {
5177 char *p;
5178 int fd;
5179
5180 assert(path);
5181
5182 #ifdef O_TMPFILE
5183 /* Try O_TMPFILE first, if it is supported */
5184 fd = open(path, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
5185 if (fd >= 0)
5186 return fd;
5187 #endif
5188
5189 /* Fall back to unguessable name + unlinking */
5190 p = strjoina(path, "/systemd-tmp-XXXXXX");
5191
5192 fd = mkostemp_safe(p, flags);
5193 if (fd < 0)
5194 return fd;
5195
5196 unlink(p);
5197 return fd;
5198 }
5199
5200 int fd_warn_permissions(const char *path, int fd) {
5201 struct stat st;
5202
5203 if (fstat(fd, &st) < 0)
5204 return -errno;
5205
5206 if (st.st_mode & 0111)
5207 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
5208
5209 if (st.st_mode & 0002)
5210 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
5211
5212 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
5213 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);
5214
5215 return 0;
5216 }
5217
5218 unsigned long personality_from_string(const char *p) {
5219
5220 /* Parse a personality specifier. We introduce our own
5221 * identifiers that indicate specific ABIs, rather than just
5222 * hints regarding the register size, since we want to keep
5223 * things open for multiple locally supported ABIs for the
5224 * same register size. We try to reuse the ABI identifiers
5225 * used by libseccomp. */
5226
5227 #if defined(__x86_64__)
5228
5229 if (streq(p, "x86"))
5230 return PER_LINUX32;
5231
5232 if (streq(p, "x86-64"))
5233 return PER_LINUX;
5234
5235 #elif defined(__i386__)
5236
5237 if (streq(p, "x86"))
5238 return PER_LINUX;
5239 #endif
5240
5241 return PERSONALITY_INVALID;
5242 }
5243
5244 const char* personality_to_string(unsigned long p) {
5245
5246 #if defined(__x86_64__)
5247
5248 if (p == PER_LINUX32)
5249 return "x86";
5250
5251 if (p == PER_LINUX)
5252 return "x86-64";
5253
5254 #elif defined(__i386__)
5255
5256 if (p == PER_LINUX)
5257 return "x86";
5258 #endif
5259
5260 return NULL;
5261 }
5262
5263 uint64_t physical_memory(void) {
5264 long mem;
5265
5266 /* We return this as uint64_t in case we are running as 32bit
5267 * process on a 64bit kernel with huge amounts of memory */
5268
5269 mem = sysconf(_SC_PHYS_PAGES);
5270 assert(mem > 0);
5271
5272 return (uint64_t) mem * (uint64_t) page_size();
5273 }
5274
5275 void hexdump(FILE *f, const void *p, size_t s) {
5276 const uint8_t *b = p;
5277 unsigned n = 0;
5278
5279 assert(s == 0 || b);
5280
5281 while (s > 0) {
5282 size_t i;
5283
5284 fprintf(f, "%04x ", n);
5285
5286 for (i = 0; i < 16; i++) {
5287
5288 if (i >= s)
5289 fputs(" ", f);
5290 else
5291 fprintf(f, "%02x ", b[i]);
5292
5293 if (i == 7)
5294 fputc(' ', f);
5295 }
5296
5297 fputc(' ', f);
5298
5299 for (i = 0; i < 16; i++) {
5300
5301 if (i >= s)
5302 fputc(' ', f);
5303 else
5304 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
5305 }
5306
5307 fputc('\n', f);
5308
5309 if (s < 16)
5310 break;
5311
5312 n += 16;
5313 b += 16;
5314 s -= 16;
5315 }
5316 }
5317
5318 int update_reboot_param_file(const char *param) {
5319 int r = 0;
5320
5321 if (param) {
5322
5323 r = write_string_file(REBOOT_PARAM_FILE, param, WRITE_STRING_FILE_CREATE);
5324 if (r < 0)
5325 log_error("Failed to write reboot param to "
5326 REBOOT_PARAM_FILE": %s", strerror(-r));
5327 } else
5328 unlink(REBOOT_PARAM_FILE);
5329
5330 return r;
5331 }
5332
5333 int umount_recursive(const char *prefix, int flags) {
5334 bool again;
5335 int n = 0, r;
5336
5337 /* Try to umount everything recursively below a
5338 * directory. Also, take care of stacked mounts, and keep
5339 * unmounting them until they are gone. */
5340
5341 do {
5342 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
5343
5344 again = false;
5345 r = 0;
5346
5347 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
5348 if (!proc_self_mountinfo)
5349 return -errno;
5350
5351 for (;;) {
5352 _cleanup_free_ char *path = NULL, *p = NULL;
5353 int k;
5354
5355 k = fscanf(proc_self_mountinfo,
5356 "%*s " /* (1) mount id */
5357 "%*s " /* (2) parent id */
5358 "%*s " /* (3) major:minor */
5359 "%*s " /* (4) root */
5360 "%ms " /* (5) mount point */
5361 "%*s" /* (6) mount options */
5362 "%*[^-]" /* (7) optional fields */
5363 "- " /* (8) separator */
5364 "%*s " /* (9) file system type */
5365 "%*s" /* (10) mount source */
5366 "%*s" /* (11) mount options 2 */
5367 "%*[^\n]", /* some rubbish at the end */
5368 &path);
5369 if (k != 1) {
5370 if (k == EOF)
5371 break;
5372
5373 continue;
5374 }
5375
5376 r = cunescape(path, UNESCAPE_RELAX, &p);
5377 if (r < 0)
5378 return r;
5379
5380 if (!path_startswith(p, prefix))
5381 continue;
5382
5383 if (umount2(p, flags) < 0) {
5384 r = -errno;
5385 continue;
5386 }
5387
5388 again = true;
5389 n++;
5390
5391 break;
5392 }
5393
5394 } while (again);
5395
5396 return r ? r : n;
5397 }
5398
5399 static int get_mount_flags(const char *path, unsigned long *flags) {
5400 struct statvfs buf;
5401
5402 if (statvfs(path, &buf) < 0)
5403 return -errno;
5404 *flags = buf.f_flag;
5405 return 0;
5406 }
5407
5408 int bind_remount_recursive(const char *prefix, bool ro) {
5409 _cleanup_set_free_free_ Set *done = NULL;
5410 _cleanup_free_ char *cleaned = NULL;
5411 int r;
5412
5413 /* Recursively remount a directory (and all its submounts)
5414 * read-only or read-write. If the directory is already
5415 * mounted, we reuse the mount and simply mark it
5416 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
5417 * operation). If it isn't we first make it one. Afterwards we
5418 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
5419 * submounts we can access, too. When mounts are stacked on
5420 * the same mount point we only care for each individual
5421 * "top-level" mount on each point, as we cannot
5422 * influence/access the underlying mounts anyway. We do not
5423 * have any effect on future submounts that might get
5424 * propagated, they migt be writable. This includes future
5425 * submounts that have been triggered via autofs. */
5426
5427 cleaned = strdup(prefix);
5428 if (!cleaned)
5429 return -ENOMEM;
5430
5431 path_kill_slashes(cleaned);
5432
5433 done = set_new(&string_hash_ops);
5434 if (!done)
5435 return -ENOMEM;
5436
5437 for (;;) {
5438 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
5439 _cleanup_set_free_free_ Set *todo = NULL;
5440 bool top_autofs = false;
5441 char *x;
5442 unsigned long orig_flags;
5443
5444 todo = set_new(&string_hash_ops);
5445 if (!todo)
5446 return -ENOMEM;
5447
5448 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
5449 if (!proc_self_mountinfo)
5450 return -errno;
5451
5452 for (;;) {
5453 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
5454 int k;
5455
5456 k = fscanf(proc_self_mountinfo,
5457 "%*s " /* (1) mount id */
5458 "%*s " /* (2) parent id */
5459 "%*s " /* (3) major:minor */
5460 "%*s " /* (4) root */
5461 "%ms " /* (5) mount point */
5462 "%*s" /* (6) mount options (superblock) */
5463 "%*[^-]" /* (7) optional fields */
5464 "- " /* (8) separator */
5465 "%ms " /* (9) file system type */
5466 "%*s" /* (10) mount source */
5467 "%*s" /* (11) mount options (bind mount) */
5468 "%*[^\n]", /* some rubbish at the end */
5469 &path,
5470 &type);
5471 if (k != 2) {
5472 if (k == EOF)
5473 break;
5474
5475 continue;
5476 }
5477
5478 r = cunescape(path, UNESCAPE_RELAX, &p);
5479 if (r < 0)
5480 return r;
5481
5482 /* Let's ignore autofs mounts. If they aren't
5483 * triggered yet, we want to avoid triggering
5484 * them, as we don't make any guarantees for
5485 * future submounts anyway. If they are
5486 * already triggered, then we will find
5487 * another entry for this. */
5488 if (streq(type, "autofs")) {
5489 top_autofs = top_autofs || path_equal(cleaned, p);
5490 continue;
5491 }
5492
5493 if (path_startswith(p, cleaned) &&
5494 !set_contains(done, p)) {
5495
5496 r = set_consume(todo, p);
5497 p = NULL;
5498
5499 if (r == -EEXIST)
5500 continue;
5501 if (r < 0)
5502 return r;
5503 }
5504 }
5505
5506 /* If we have no submounts to process anymore and if
5507 * the root is either already done, or an autofs, we
5508 * are done */
5509 if (set_isempty(todo) &&
5510 (top_autofs || set_contains(done, cleaned)))
5511 return 0;
5512
5513 if (!set_contains(done, cleaned) &&
5514 !set_contains(todo, cleaned)) {
5515 /* The prefix directory itself is not yet a
5516 * mount, make it one. */
5517 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
5518 return -errno;
5519
5520 orig_flags = 0;
5521 (void) get_mount_flags(cleaned, &orig_flags);
5522 orig_flags &= ~MS_RDONLY;
5523
5524 if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
5525 return -errno;
5526
5527 x = strdup(cleaned);
5528 if (!x)
5529 return -ENOMEM;
5530
5531 r = set_consume(done, x);
5532 if (r < 0)
5533 return r;
5534 }
5535
5536 while ((x = set_steal_first(todo))) {
5537
5538 r = set_consume(done, x);
5539 if (r == -EEXIST || r == 0)
5540 continue;
5541 if (r < 0)
5542 return r;
5543
5544 /* Try to reuse the original flag set, but
5545 * don't care for errors, in case of
5546 * obstructed mounts */
5547 orig_flags = 0;
5548 (void) get_mount_flags(x, &orig_flags);
5549 orig_flags &= ~MS_RDONLY;
5550
5551 if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
5552
5553 /* Deal with mount points that are
5554 * obstructed by a later mount */
5555
5556 if (errno != ENOENT)
5557 return -errno;
5558 }
5559
5560 }
5561 }
5562 }
5563
5564 int fflush_and_check(FILE *f) {
5565 assert(f);
5566
5567 errno = 0;
5568 fflush(f);
5569
5570 if (ferror(f))
5571 return errno ? -errno : -EIO;
5572
5573 return 0;
5574 }
5575
5576 int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
5577 const char *fn;
5578 char *t;
5579
5580 assert(p);
5581 assert(ret);
5582
5583 /*
5584 * Turns this:
5585 * /foo/bar/waldo
5586 *
5587 * Into this:
5588 * /foo/bar/.#<extra>waldoXXXXXX
5589 */
5590
5591 fn = basename(p);
5592 if (!filename_is_valid(fn))
5593 return -EINVAL;
5594
5595 if (extra == NULL)
5596 extra = "";
5597
5598 t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
5599 if (!t)
5600 return -ENOMEM;
5601
5602 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
5603
5604 *ret = path_kill_slashes(t);
5605 return 0;
5606 }
5607
5608 int tempfn_random(const char *p, const char *extra, char **ret) {
5609 const char *fn;
5610 char *t, *x;
5611 uint64_t u;
5612 unsigned i;
5613
5614 assert(p);
5615 assert(ret);
5616
5617 /*
5618 * Turns this:
5619 * /foo/bar/waldo
5620 *
5621 * Into this:
5622 * /foo/bar/.#<extra>waldobaa2a261115984a9
5623 */
5624
5625 fn = basename(p);
5626 if (!filename_is_valid(fn))
5627 return -EINVAL;
5628
5629 if (!extra)
5630 extra = "";
5631
5632 t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
5633 if (!t)
5634 return -ENOMEM;
5635
5636 x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
5637
5638 u = random_u64();
5639 for (i = 0; i < 16; i++) {
5640 *(x++) = hexchar(u & 0xF);
5641 u >>= 4;
5642 }
5643
5644 *x = 0;
5645
5646 *ret = path_kill_slashes(t);
5647 return 0;
5648 }
5649
5650 int tempfn_random_child(const char *p, const char *extra, char **ret) {
5651 char *t, *x;
5652 uint64_t u;
5653 unsigned i;
5654
5655 assert(p);
5656 assert(ret);
5657
5658 /* Turns this:
5659 * /foo/bar/waldo
5660 * Into this:
5661 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
5662 */
5663
5664 if (!extra)
5665 extra = "";
5666
5667 t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
5668 if (!t)
5669 return -ENOMEM;
5670
5671 x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
5672
5673 u = random_u64();
5674 for (i = 0; i < 16; i++) {
5675 *(x++) = hexchar(u & 0xF);
5676 u >>= 4;
5677 }
5678
5679 *x = 0;
5680
5681 *ret = path_kill_slashes(t);
5682 return 0;
5683 }
5684
5685 int take_password_lock(const char *root) {
5686
5687 struct flock flock = {
5688 .l_type = F_WRLCK,
5689 .l_whence = SEEK_SET,
5690 .l_start = 0,
5691 .l_len = 0,
5692 };
5693
5694 const char *path;
5695 int fd, r;
5696
5697 /* This is roughly the same as lckpwdf(), but not as awful. We
5698 * don't want to use alarm() and signals, hence we implement
5699 * our own trivial version of this.
5700 *
5701 * Note that shadow-utils also takes per-database locks in
5702 * addition to lckpwdf(). However, we don't given that they
5703 * are redundant as they they invoke lckpwdf() first and keep
5704 * it during everything they do. The per-database locks are
5705 * awfully racy, and thus we just won't do them. */
5706
5707 if (root)
5708 path = strjoina(root, "/etc/.pwd.lock");
5709 else
5710 path = "/etc/.pwd.lock";
5711
5712 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
5713 if (fd < 0)
5714 return -errno;
5715
5716 r = fcntl(fd, F_SETLKW, &flock);
5717 if (r < 0) {
5718 safe_close(fd);
5719 return -errno;
5720 }
5721
5722 return fd;
5723 }
5724
5725 int is_symlink(const char *path) {
5726 struct stat info;
5727
5728 if (lstat(path, &info) < 0)
5729 return -errno;
5730
5731 return !!S_ISLNK(info.st_mode);
5732 }
5733
5734 int is_dir(const char* path, bool follow) {
5735 struct stat st;
5736 int r;
5737
5738 if (follow)
5739 r = stat(path, &st);
5740 else
5741 r = lstat(path, &st);
5742 if (r < 0)
5743 return -errno;
5744
5745 return !!S_ISDIR(st.st_mode);
5746 }
5747
5748 int is_device_node(const char *path) {
5749 struct stat info;
5750
5751 if (lstat(path, &info) < 0)
5752 return -errno;
5753
5754 return !!(S_ISBLK(info.st_mode) || S_ISCHR(info.st_mode));
5755 }
5756
5757 int extract_first_word(const char **p, char **ret, const char *separators, ExtractFlags flags) {
5758 _cleanup_free_ char *s = NULL;
5759 size_t allocated = 0, sz = 0;
5760 int r;
5761
5762 enum {
5763 START,
5764 VALUE,
5765 VALUE_ESCAPE,
5766 SINGLE_QUOTE,
5767 SINGLE_QUOTE_ESCAPE,
5768 DOUBLE_QUOTE,
5769 DOUBLE_QUOTE_ESCAPE,
5770 SEPARATOR,
5771 } state = START;
5772
5773 assert(p);
5774 assert(ret);
5775
5776 if (!separators)
5777 separators = WHITESPACE;
5778
5779 /* Bail early if called after last value or with no input */
5780 if (!*p)
5781 goto finish_force_terminate;
5782
5783 /* Parses the first word of a string, and returns it in
5784 * *ret. Removes all quotes in the process. When parsing fails
5785 * (because of an uneven number of quotes or similar), leaves
5786 * the pointer *p at the first invalid character. */
5787
5788 for (;;) {
5789 char c = **p;
5790
5791 switch (state) {
5792
5793 case START:
5794 if (flags & EXTRACT_DONT_COALESCE_SEPARATORS)
5795 if (!GREEDY_REALLOC(s, allocated, sz+1))
5796 return -ENOMEM;
5797
5798 if (c == 0)
5799 goto finish_force_terminate;
5800 else if (strchr(separators, c)) {
5801 if (flags & EXTRACT_DONT_COALESCE_SEPARATORS) {
5802 (*p) ++;
5803 goto finish_force_next;
5804 }
5805 break;
5806 }
5807
5808 /* We found a non-blank character, so we will always
5809 * want to return a string (even if it is empty),
5810 * allocate it here. */
5811 if (!GREEDY_REALLOC(s, allocated, sz+1))
5812 return -ENOMEM;
5813
5814 state = VALUE;
5815 /* fallthrough */
5816
5817 case VALUE:
5818 if (c == 0)
5819 goto finish_force_terminate;
5820 else if (c == '\'' && (flags & EXTRACT_QUOTES))
5821 state = SINGLE_QUOTE;
5822 else if (c == '\\')
5823 state = VALUE_ESCAPE;
5824 else if (c == '\"' && (flags & EXTRACT_QUOTES))
5825 state = DOUBLE_QUOTE;
5826 else if (strchr(separators, c)) {
5827 if (flags & EXTRACT_DONT_COALESCE_SEPARATORS) {
5828 (*p) ++;
5829 goto finish_force_next;
5830 }
5831 state = SEPARATOR;
5832 } else {
5833 if (!GREEDY_REALLOC(s, allocated, sz+2))
5834 return -ENOMEM;
5835
5836 s[sz++] = c;
5837 }
5838
5839 break;
5840
5841 case SINGLE_QUOTE:
5842 if (c == 0) {
5843 if (flags & EXTRACT_RELAX)
5844 goto finish_force_terminate;
5845 return -EINVAL;
5846 } else if (c == '\'')
5847 state = VALUE;
5848 else if (c == '\\')
5849 state = SINGLE_QUOTE_ESCAPE;
5850 else {
5851 if (!GREEDY_REALLOC(s, allocated, sz+2))
5852 return -ENOMEM;
5853
5854 s[sz++] = c;
5855 }
5856
5857 break;
5858
5859 case DOUBLE_QUOTE:
5860 if (c == 0)
5861 return -EINVAL;
5862 else if (c == '\"')
5863 state = VALUE;
5864 else if (c == '\\')
5865 state = DOUBLE_QUOTE_ESCAPE;
5866 else {
5867 if (!GREEDY_REALLOC(s, allocated, sz+2))
5868 return -ENOMEM;
5869
5870 s[sz++] = c;
5871 }
5872
5873 break;
5874
5875 case SINGLE_QUOTE_ESCAPE:
5876 case DOUBLE_QUOTE_ESCAPE:
5877 case VALUE_ESCAPE:
5878 if (!GREEDY_REALLOC(s, allocated, sz+7))
5879 return -ENOMEM;
5880
5881 if (c == 0) {
5882 if ((flags & EXTRACT_CUNESCAPE_RELAX) &&
5883 (state == VALUE_ESCAPE || flags & EXTRACT_RELAX)) {
5884 /* If we find an unquoted trailing backslash and we're in
5885 * EXTRACT_CUNESCAPE_RELAX mode, keep it verbatim in the
5886 * output.
5887 *
5888 * Unbalanced quotes will only be allowed in EXTRACT_RELAX
5889 * mode, EXTRACT_CUNESCAPE_RELAX mode does not allow them.
5890 */
5891 s[sz++] = '\\';
5892 goto finish_force_terminate;
5893 }
5894 if (flags & EXTRACT_RELAX)
5895 goto finish_force_terminate;
5896 return -EINVAL;
5897 }
5898
5899 if (flags & EXTRACT_CUNESCAPE) {
5900 uint32_t u;
5901
5902 r = cunescape_one(*p, (size_t) -1, &c, &u);
5903 if (r < 0) {
5904 if (flags & EXTRACT_CUNESCAPE_RELAX) {
5905 s[sz++] = '\\';
5906 s[sz++] = c;
5907 goto end_escape;
5908 }
5909 return -EINVAL;
5910 }
5911
5912 (*p) += r - 1;
5913
5914 if (c != 0)
5915 s[sz++] = c; /* normal explicit char */
5916 else
5917 sz += utf8_encode_unichar(s + sz, u); /* unicode chars we'll encode as utf8 */
5918 } else
5919 s[sz++] = c;
5920
5921 end_escape:
5922 state = (state == SINGLE_QUOTE_ESCAPE) ? SINGLE_QUOTE :
5923 (state == DOUBLE_QUOTE_ESCAPE) ? DOUBLE_QUOTE :
5924 VALUE;
5925 break;
5926
5927 case SEPARATOR:
5928 if (c == 0)
5929 goto finish_force_terminate;
5930 if (!strchr(separators, c))
5931 goto finish;
5932 break;
5933 }
5934
5935 (*p) ++;
5936 }
5937
5938 finish_force_terminate:
5939 *p = NULL;
5940 finish:
5941 if (!s) {
5942 *p = NULL;
5943 *ret = NULL;
5944 return 0;
5945 }
5946
5947 finish_force_next:
5948 s[sz] = 0;
5949 *ret = s;
5950 s = NULL;
5951
5952 return 1;
5953 }
5954
5955 int extract_first_word_and_warn(
5956 const char **p,
5957 char **ret,
5958 const char *separators,
5959 ExtractFlags flags,
5960 const char *unit,
5961 const char *filename,
5962 unsigned line,
5963 const char *rvalue) {
5964 /* Try to unquote it, if it fails, warn about it and try again but this
5965 * time using EXTRACT_CUNESCAPE_RELAX to keep the backslashes verbatim
5966 * in invalid escape sequences. */
5967 const char *save;
5968 int r;
5969
5970 save = *p;
5971 r = extract_first_word(p, ret, separators, flags);
5972 if (r < 0 && !(flags&EXTRACT_CUNESCAPE_RELAX)) {
5973 /* Retry it with EXTRACT_CUNESCAPE_RELAX. */
5974 *p = save;
5975 r = extract_first_word(p, ret, separators, flags|EXTRACT_CUNESCAPE_RELAX);
5976 if (r < 0)
5977 log_syntax(unit, LOG_ERR, filename, line, EINVAL,
5978 "Unbalanced quoting in command line, ignoring: \"%s\"", rvalue);
5979 else
5980 log_syntax(unit, LOG_WARNING, filename, line, EINVAL,
5981 "Invalid escape sequences in command line: \"%s\"", rvalue);
5982 }
5983 return r;
5984 }
5985
5986 int extract_many_words(const char **p, const char *separators, ExtractFlags flags, ...) {
5987 va_list ap;
5988 char **l;
5989 int n = 0, i, c, r;
5990
5991 /* Parses a number of words from a string, stripping any
5992 * quotes if necessary. */
5993
5994 assert(p);
5995
5996 /* Count how many words are expected */
5997 va_start(ap, flags);
5998 for (;;) {
5999 if (!va_arg(ap, char **))
6000 break;
6001 n++;
6002 }
6003 va_end(ap);
6004
6005 if (n <= 0)
6006 return 0;
6007
6008 /* Read all words into a temporary array */
6009 l = newa0(char*, n);
6010 for (c = 0; c < n; c++) {
6011
6012 r = extract_first_word(p, &l[c], separators, flags);
6013 if (r < 0) {
6014 int j;
6015
6016 for (j = 0; j < c; j++)
6017 free(l[j]);
6018
6019 return r;
6020 }
6021
6022 if (r == 0)
6023 break;
6024 }
6025
6026 /* If we managed to parse all words, return them in the passed
6027 * in parameters */
6028 va_start(ap, flags);
6029 for (i = 0; i < n; i++) {
6030 char **v;
6031
6032 v = va_arg(ap, char **);
6033 assert(v);
6034
6035 *v = l[i];
6036 }
6037 va_end(ap);
6038
6039 return c;
6040 }
6041
6042 int free_and_strdup(char **p, const char *s) {
6043 char *t;
6044
6045 assert(p);
6046
6047 /* Replaces a string pointer with an strdup()ed new string,
6048 * possibly freeing the old one. */
6049
6050 if (streq_ptr(*p, s))
6051 return 0;
6052
6053 if (s) {
6054 t = strdup(s);
6055 if (!t)
6056 return -ENOMEM;
6057 } else
6058 t = NULL;
6059
6060 free(*p);
6061 *p = t;
6062
6063 return 1;
6064 }
6065
6066 int ptsname_malloc(int fd, char **ret) {
6067 size_t l = 100;
6068
6069 assert(fd >= 0);
6070 assert(ret);
6071
6072 for (;;) {
6073 char *c;
6074
6075 c = new(char, l);
6076 if (!c)
6077 return -ENOMEM;
6078
6079 if (ptsname_r(fd, c, l) == 0) {
6080 *ret = c;
6081 return 0;
6082 }
6083 if (errno != ERANGE) {
6084 free(c);
6085 return -errno;
6086 }
6087
6088 free(c);
6089 l *= 2;
6090 }
6091 }
6092
6093 int openpt_in_namespace(pid_t pid, int flags) {
6094 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
6095 _cleanup_close_pair_ int pair[2] = { -1, -1 };
6096 union {
6097 struct cmsghdr cmsghdr;
6098 uint8_t buf[CMSG_SPACE(sizeof(int))];
6099 } control = {};
6100 struct msghdr mh = {
6101 .msg_control = &control,
6102 .msg_controllen = sizeof(control),
6103 };
6104 struct cmsghdr *cmsg;
6105 siginfo_t si;
6106 pid_t child;
6107 int r;
6108
6109 assert(pid > 0);
6110
6111 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
6112 if (r < 0)
6113 return r;
6114
6115 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
6116 return -errno;
6117
6118 child = fork();
6119 if (child < 0)
6120 return -errno;
6121
6122 if (child == 0) {
6123 int master;
6124
6125 pair[0] = safe_close(pair[0]);
6126
6127 r = namespace_enter(pidnsfd, mntnsfd, -1, usernsfd, rootfd);
6128 if (r < 0)
6129 _exit(EXIT_FAILURE);
6130
6131 master = posix_openpt(flags);
6132 if (master < 0)
6133 _exit(EXIT_FAILURE);
6134
6135 if (unlockpt(master) < 0)
6136 _exit(EXIT_FAILURE);
6137
6138 cmsg = CMSG_FIRSTHDR(&mh);
6139 cmsg->cmsg_level = SOL_SOCKET;
6140 cmsg->cmsg_type = SCM_RIGHTS;
6141 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
6142 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
6143
6144 mh.msg_controllen = cmsg->cmsg_len;
6145
6146 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
6147 _exit(EXIT_FAILURE);
6148
6149 _exit(EXIT_SUCCESS);
6150 }
6151
6152 pair[1] = safe_close(pair[1]);
6153
6154 r = wait_for_terminate(child, &si);
6155 if (r < 0)
6156 return r;
6157 if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
6158 return -EIO;
6159
6160 if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
6161 return -errno;
6162
6163 CMSG_FOREACH(cmsg, &mh)
6164 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
6165 int *fds;
6166 unsigned n_fds;
6167
6168 fds = (int*) CMSG_DATA(cmsg);
6169 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
6170
6171 if (n_fds != 1) {
6172 close_many(fds, n_fds);
6173 return -EIO;
6174 }
6175
6176 return fds[0];
6177 }
6178
6179 return -EIO;
6180 }
6181
6182 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
6183 _cleanup_close_ int fd = -1;
6184 ssize_t l;
6185
6186 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
6187
6188 fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
6189 if (fd < 0)
6190 return -errno;
6191
6192 l = fgetxattr(fd, attribute, value, size);
6193 if (l < 0)
6194 return -errno;
6195
6196 return l;
6197 }
6198
6199 static int parse_crtime(le64_t le, usec_t *usec) {
6200 uint64_t u;
6201
6202 assert(usec);
6203
6204 u = le64toh(le);
6205 if (u == 0 || u == (uint64_t) -1)
6206 return -EIO;
6207
6208 *usec = (usec_t) u;
6209 return 0;
6210 }
6211
6212 int fd_getcrtime(int fd, usec_t *usec) {
6213 le64_t le;
6214 ssize_t n;
6215
6216 assert(fd >= 0);
6217 assert(usec);
6218
6219 /* Until Linux gets a real concept of birthtime/creation time,
6220 * let's fake one with xattrs */
6221
6222 n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
6223 if (n < 0)
6224 return -errno;
6225 if (n != sizeof(le))
6226 return -EIO;
6227
6228 return parse_crtime(le, usec);
6229 }
6230
6231 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
6232 le64_t le;
6233 ssize_t n;
6234
6235 n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
6236 if (n < 0)
6237 return -errno;
6238 if (n != sizeof(le))
6239 return -EIO;
6240
6241 return parse_crtime(le, usec);
6242 }
6243
6244 int path_getcrtime(const char *p, usec_t *usec) {
6245 le64_t le;
6246 ssize_t n;
6247
6248 assert(p);
6249 assert(usec);
6250
6251 n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
6252 if (n < 0)
6253 return -errno;
6254 if (n != sizeof(le))
6255 return -EIO;
6256
6257 return parse_crtime(le, usec);
6258 }
6259
6260 int fd_setcrtime(int fd, usec_t usec) {
6261 le64_t le;
6262
6263 assert(fd >= 0);
6264
6265 if (usec <= 0)
6266 usec = now(CLOCK_REALTIME);
6267
6268 le = htole64((uint64_t) usec);
6269 if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
6270 return -errno;
6271
6272 return 0;
6273 }
6274
6275 int same_fd(int a, int b) {
6276 struct stat sta, stb;
6277 pid_t pid;
6278 int r, fa, fb;
6279
6280 assert(a >= 0);
6281 assert(b >= 0);
6282
6283 /* Compares two file descriptors. Note that semantics are
6284 * quite different depending on whether we have kcmp() or we
6285 * don't. If we have kcmp() this will only return true for
6286 * dup()ed file descriptors, but not otherwise. If we don't
6287 * have kcmp() this will also return true for two fds of the same
6288 * file, created by separate open() calls. Since we use this
6289 * call mostly for filtering out duplicates in the fd store
6290 * this difference hopefully doesn't matter too much. */
6291
6292 if (a == b)
6293 return true;
6294
6295 /* Try to use kcmp() if we have it. */
6296 pid = getpid();
6297 r = kcmp(pid, pid, KCMP_FILE, a, b);
6298 if (r == 0)
6299 return true;
6300 if (r > 0)
6301 return false;
6302 if (errno != ENOSYS)
6303 return -errno;
6304
6305 /* We don't have kcmp(), use fstat() instead. */
6306 if (fstat(a, &sta) < 0)
6307 return -errno;
6308
6309 if (fstat(b, &stb) < 0)
6310 return -errno;
6311
6312 if ((sta.st_mode & S_IFMT) != (stb.st_mode & S_IFMT))
6313 return false;
6314
6315 /* We consider all device fds different, since two device fds
6316 * might refer to quite different device contexts even though
6317 * they share the same inode and backing dev_t. */
6318
6319 if (S_ISCHR(sta.st_mode) || S_ISBLK(sta.st_mode))
6320 return false;
6321
6322 if (sta.st_dev != stb.st_dev || sta.st_ino != stb.st_ino)
6323 return false;
6324
6325 /* The fds refer to the same inode on disk, let's also check
6326 * if they have the same fd flags. This is useful to
6327 * distinguish the read and write side of a pipe created with
6328 * pipe(). */
6329 fa = fcntl(a, F_GETFL);
6330 if (fa < 0)
6331 return -errno;
6332
6333 fb = fcntl(b, F_GETFL);
6334 if (fb < 0)
6335 return -errno;
6336
6337 return fa == fb;
6338 }
6339
6340 int chattr_fd(int fd, unsigned value, unsigned mask) {
6341 unsigned old_attr, new_attr;
6342 struct stat st;
6343
6344 assert(fd >= 0);
6345
6346 if (fstat(fd, &st) < 0)
6347 return -errno;
6348
6349 /* Explicitly check whether this is a regular file or
6350 * directory. If it is anything else (such as a device node or
6351 * fifo), then the ioctl will not hit the file systems but
6352 * possibly drivers, where the ioctl might have different
6353 * effects. Notably, DRM is using the same ioctl() number. */
6354
6355 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
6356 return -ENOTTY;
6357
6358 if (mask == 0)
6359 return 0;
6360
6361 if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
6362 return -errno;
6363
6364 new_attr = (old_attr & ~mask) | (value & mask);
6365 if (new_attr == old_attr)
6366 return 0;
6367
6368 if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
6369 return -errno;
6370
6371 return 1;
6372 }
6373
6374 int chattr_path(const char *p, unsigned value, unsigned mask) {
6375 _cleanup_close_ int fd = -1;
6376
6377 assert(p);
6378
6379 if (mask == 0)
6380 return 0;
6381
6382 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
6383 if (fd < 0)
6384 return -errno;
6385
6386 return chattr_fd(fd, value, mask);
6387 }
6388
6389 int read_attr_fd(int fd, unsigned *ret) {
6390 struct stat st;
6391
6392 assert(fd >= 0);
6393
6394 if (fstat(fd, &st) < 0)
6395 return -errno;
6396
6397 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
6398 return -ENOTTY;
6399
6400 if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
6401 return -errno;
6402
6403 return 0;
6404 }
6405
6406 int read_attr_path(const char *p, unsigned *ret) {
6407 _cleanup_close_ int fd = -1;
6408
6409 assert(p);
6410 assert(ret);
6411
6412 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
6413 if (fd < 0)
6414 return -errno;
6415
6416 return read_attr_fd(fd, ret);
6417 }
6418
6419 static size_t nul_length(const uint8_t *p, size_t sz) {
6420 size_t n = 0;
6421
6422 while (sz > 0) {
6423 if (*p != 0)
6424 break;
6425
6426 n++;
6427 p++;
6428 sz--;
6429 }
6430
6431 return n;
6432 }
6433
6434 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
6435 const uint8_t *q, *w, *e;
6436 ssize_t l;
6437
6438 q = w = p;
6439 e = q + sz;
6440 while (q < e) {
6441 size_t n;
6442
6443 n = nul_length(q, e - q);
6444
6445 /* If there are more than the specified run length of
6446 * NUL bytes, or if this is the beginning or the end
6447 * of the buffer, then seek instead of write */
6448 if ((n > run_length) ||
6449 (n > 0 && q == p) ||
6450 (n > 0 && q + n >= e)) {
6451 if (q > w) {
6452 l = write(fd, w, q - w);
6453 if (l < 0)
6454 return -errno;
6455 if (l != q -w)
6456 return -EIO;
6457 }
6458
6459 if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
6460 return -errno;
6461
6462 q += n;
6463 w = q;
6464 } else if (n > 0)
6465 q += n;
6466 else
6467 q ++;
6468 }
6469
6470 if (q > w) {
6471 l = write(fd, w, q - w);
6472 if (l < 0)
6473 return -errno;
6474 if (l != q - w)
6475 return -EIO;
6476 }
6477
6478 return q - (const uint8_t*) p;
6479 }
6480
6481 void sigkill_wait(pid_t *pid) {
6482 if (!pid)
6483 return;
6484 if (*pid <= 1)
6485 return;
6486
6487 if (kill(*pid, SIGKILL) > 0)
6488 (void) wait_for_terminate(*pid, NULL);
6489 }
6490
6491 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
6492 int a = 0, b = 0, c = 0;
6493 int k;
6494
6495 assert(p);
6496 assert(*p);
6497 assert(priority);
6498
6499 if ((*p)[0] != '<')
6500 return 0;
6501
6502 if (!strchr(*p, '>'))
6503 return 0;
6504
6505 if ((*p)[2] == '>') {
6506 c = undecchar((*p)[1]);
6507 k = 3;
6508 } else if ((*p)[3] == '>') {
6509 b = undecchar((*p)[1]);
6510 c = undecchar((*p)[2]);
6511 k = 4;
6512 } else if ((*p)[4] == '>') {
6513 a = undecchar((*p)[1]);
6514 b = undecchar((*p)[2]);
6515 c = undecchar((*p)[3]);
6516 k = 5;
6517 } else
6518 return 0;
6519
6520 if (a < 0 || b < 0 || c < 0 ||
6521 (!with_facility && (a || b || c > 7)))
6522 return 0;
6523
6524 if (with_facility)
6525 *priority = a*100 + b*10 + c;
6526 else
6527 *priority = (*priority & LOG_FACMASK) | c;
6528
6529 *p += k;
6530 return 1;
6531 }
6532
6533 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
6534 size_t i;
6535
6536 if (!key)
6537 return -1;
6538
6539 for (i = 0; i < len; ++i)
6540 if (streq_ptr(table[i], key))
6541 return (ssize_t)i;
6542
6543 return -1;
6544 }
6545
6546 void cmsg_close_all(struct msghdr *mh) {
6547 struct cmsghdr *cmsg;
6548
6549 assert(mh);
6550
6551 CMSG_FOREACH(cmsg, mh)
6552 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
6553 close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
6554 }
6555
6556 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
6557 struct stat buf;
6558 int ret;
6559
6560 ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
6561 if (ret >= 0)
6562 return 0;
6563
6564 /* renameat2() exists since Linux 3.15, btrfs added support for it later.
6565 * If it is not implemented, fallback to another method. */
6566 if (!IN_SET(errno, EINVAL, ENOSYS))
6567 return -errno;
6568
6569 /* The link()/unlink() fallback does not work on directories. But
6570 * renameat() without RENAME_NOREPLACE gives the same semantics on
6571 * directories, except when newpath is an *empty* directory. This is
6572 * good enough. */
6573 ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
6574 if (ret >= 0 && S_ISDIR(buf.st_mode)) {
6575 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
6576 return ret >= 0 ? 0 : -errno;
6577 }
6578
6579 /* If it is not a directory, use the link()/unlink() fallback. */
6580 ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
6581 if (ret < 0)
6582 return -errno;
6583
6584 ret = unlinkat(olddirfd, oldpath, 0);
6585 if (ret < 0) {
6586 /* backup errno before the following unlinkat() alters it */
6587 ret = errno;
6588 (void) unlinkat(newdirfd, newpath, 0);
6589 errno = ret;
6590 return -errno;
6591 }
6592
6593 return 0;
6594 }
6595
6596 static char *strcpy_backslash_escaped(char *t, const char *s, const char *bad) {
6597 assert(bad);
6598
6599 for (; *s; s++) {
6600 if (*s == '\\' || strchr(bad, *s))
6601 *(t++) = '\\';
6602
6603 *(t++) = *s;
6604 }
6605
6606 return t;
6607 }
6608
6609 char *shell_escape(const char *s, const char *bad) {
6610 char *r, *t;
6611
6612 r = new(char, strlen(s)*2+1);
6613 if (!r)
6614 return NULL;
6615
6616 t = strcpy_backslash_escaped(r, s, bad);
6617 *t = 0;
6618
6619 return r;
6620 }
6621
6622 char *shell_maybe_quote(const char *s) {
6623 const char *p;
6624 char *r, *t;
6625
6626 assert(s);
6627
6628 /* Encloses a string in double quotes if necessary to make it
6629 * OK as shell string. */
6630
6631 for (p = s; *p; p++)
6632 if (*p <= ' ' ||
6633 *p >= 127 ||
6634 strchr(SHELL_NEED_QUOTES, *p))
6635 break;
6636
6637 if (!*p)
6638 return strdup(s);
6639
6640 r = new(char, 1+strlen(s)*2+1+1);
6641 if (!r)
6642 return NULL;
6643
6644 t = r;
6645 *(t++) = '"';
6646 t = mempcpy(t, s, p - s);
6647
6648 t = strcpy_backslash_escaped(t, p, SHELL_NEED_ESCAPE);
6649
6650 *(t++)= '"';
6651 *t = 0;
6652
6653 return r;
6654 }
6655
6656 int parse_mode(const char *s, mode_t *ret) {
6657 char *x;
6658 long l;
6659
6660 assert(s);
6661 assert(ret);
6662
6663 errno = 0;
6664 l = strtol(s, &x, 8);
6665 if (errno != 0)
6666 return -errno;
6667
6668 if (!x || x == s || *x)
6669 return -EINVAL;
6670 if (l < 0 || l > 07777)
6671 return -ERANGE;
6672
6673 *ret = (mode_t) l;
6674 return 0;
6675 }
6676
6677 int mount_move_root(const char *path) {
6678 assert(path);
6679
6680 if (chdir(path) < 0)
6681 return -errno;
6682
6683 if (mount(path, "/", NULL, MS_MOVE, NULL) < 0)
6684 return -errno;
6685
6686 if (chroot(".") < 0)
6687 return -errno;
6688
6689 if (chdir("/") < 0)
6690 return -errno;
6691
6692 return 0;
6693 }
6694
6695 int reset_uid_gid(void) {
6696
6697 if (setgroups(0, NULL) < 0)
6698 return -errno;
6699
6700 if (setresgid(0, 0, 0) < 0)
6701 return -errno;
6702
6703 if (setresuid(0, 0, 0) < 0)
6704 return -errno;
6705
6706 return 0;
6707 }
6708
6709 int getxattr_malloc(const char *path, const char *name, char **value, bool allow_symlink) {
6710 char *v;
6711 size_t l;
6712 ssize_t n;
6713
6714 assert(path);
6715 assert(name);
6716 assert(value);
6717
6718 for (l = 100; ; l = (size_t) n + 1) {
6719 v = new0(char, l);
6720 if (!v)
6721 return -ENOMEM;
6722
6723 if (allow_symlink)
6724 n = lgetxattr(path, name, v, l);
6725 else
6726 n = getxattr(path, name, v, l);
6727
6728 if (n >= 0 && (size_t) n < l) {
6729 *value = v;
6730 return n;
6731 }
6732
6733 free(v);
6734
6735 if (n < 0 && errno != ERANGE)
6736 return -errno;
6737
6738 if (allow_symlink)
6739 n = lgetxattr(path, name, NULL, 0);
6740 else
6741 n = getxattr(path, name, NULL, 0);
6742 if (n < 0)
6743 return -errno;
6744 }
6745 }
6746
6747 int fgetxattr_malloc(int fd, const char *name, char **value) {
6748 char *v;
6749 size_t l;
6750 ssize_t n;
6751
6752 assert(fd >= 0);
6753 assert(name);
6754 assert(value);
6755
6756 for (l = 100; ; l = (size_t) n + 1) {
6757 v = new0(char, l);
6758 if (!v)
6759 return -ENOMEM;
6760
6761 n = fgetxattr(fd, name, v, l);
6762
6763 if (n >= 0 && (size_t) n < l) {
6764 *value = v;
6765 return n;
6766 }
6767
6768 free(v);
6769
6770 if (n < 0 && errno != ERANGE)
6771 return -errno;
6772
6773 n = fgetxattr(fd, name, NULL, 0);
6774 if (n < 0)
6775 return -errno;
6776 }
6777 }