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