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